|
| 1 | +package dialer |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/tls" |
| 6 | + "fmt" |
| 7 | + "net" |
| 8 | + "net/url" |
| 9 | + |
| 10 | + "github.com/SenseUnit/dumbproxy/tlsutil" |
| 11 | + xproxy "golang.org/x/net/proxy" |
| 12 | +) |
| 13 | + |
| 14 | +func SOCKS5SDialerFromURL(u *url.URL, next xproxy.Dialer) (xproxy.Dialer, error) { |
| 15 | + var ( |
| 16 | + tlsConfig *tls.Config |
| 17 | + tlsFactory func(net.Conn, *tls.Config) net.Conn |
| 18 | + err error |
| 19 | + ) |
| 20 | + tlsConfig, err = tlsutil.TLSConfigFromURL(u) |
| 21 | + if err != nil { |
| 22 | + return nil, fmt.Errorf("TLS configuration failed: %w", err) |
| 23 | + } |
| 24 | + tlsFactory, err = tlsutil.TLSFactoryFromURL(u) |
| 25 | + if err != nil { |
| 26 | + return nil, fmt.Errorf("TLS configuration failed: %w", err) |
| 27 | + } |
| 28 | + u.Scheme = "socks5" |
| 29 | + u.RawQuery = "" |
| 30 | + return xproxy.FromURL(u, NewTLSWrappingDialer(tlsConfig, tlsFactory, MaybeWrapWithContextDialer(next))) |
| 31 | +} |
| 32 | + |
| 33 | +type TLSWrappingDialer struct { |
| 34 | + next Dialer |
| 35 | + tlsConfig *tls.Config |
| 36 | + tlsFactory func(net.Conn, *tls.Config) net.Conn |
| 37 | +} |
| 38 | + |
| 39 | +func NewTLSWrappingDialer(tlsConfig *tls.Config, tlsFactory func(net.Conn, *tls.Config) net.Conn, next Dialer) *TLSWrappingDialer { |
| 40 | + return &TLSWrappingDialer{ |
| 41 | + next: next, |
| 42 | + tlsConfig: tlsConfig, |
| 43 | + tlsFactory: tlsFactory, |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +func (d *TLSWrappingDialer) Dial(network, address string) (net.Conn, error) { |
| 48 | + return d.DialContext(context.Background(), network, address) |
| 49 | +} |
| 50 | + |
| 51 | +func (d *TLSWrappingDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { |
| 52 | + conn, err := d.next.DialContext(ctx, network, address) |
| 53 | + if err != nil { |
| 54 | + return nil, err |
| 55 | + } |
| 56 | + return d.tlsFactory(conn, d.tlsConfig), nil |
| 57 | +} |
0 commit comments