|
| 1 | +package connpool |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net" |
| 7 | + "net/url" |
| 8 | + |
| 9 | + "golang.org/x/net/proxy" |
| 10 | +) |
| 11 | + |
| 12 | +// socks5WrapperDialer adapts a golang.org/x/net/proxy.Dialer to our Dialer interface. |
| 13 | +type socks5WrapperDialer struct { |
| 14 | + dialer proxy.Dialer |
| 15 | +} |
| 16 | + |
| 17 | +func (s *socks5WrapperDialer) Dial(ctx context.Context, network, address string) (net.Conn, error) { |
| 18 | + conn, err := s.dialer.Dial(network, address) |
| 19 | + if err != nil { |
| 20 | + return nil, fmt.Errorf("failed to connect via SOCKS5 proxy: %w", err) |
| 21 | + } |
| 22 | + return conn, nil |
| 23 | +} |
| 24 | + |
| 25 | +// NewCreateSOCKS5Dialer creates a Dialer that routes connections via a SOCKS5 proxy. |
| 26 | +// socks5ProxyURLStr should be of the form: socks5://user:pass@host:port |
| 27 | +func NewCreateSOCKS5Dialer(socks5ProxyURLStr string) (Dialer, error) { |
| 28 | + proxyURL, err := url.Parse(socks5ProxyURLStr) |
| 29 | + if err != nil { |
| 30 | + return nil, fmt.Errorf("failed to parse proxy URL: %v", err) |
| 31 | + } |
| 32 | + if proxyURL.Scheme != "socks5" { |
| 33 | + return nil, fmt.Errorf("unsupported proxy scheme: %s, only socks5 is supported", proxyURL.Scheme) |
| 34 | + } |
| 35 | + |
| 36 | + var auth *proxy.Auth |
| 37 | + if proxyURL.User != nil { |
| 38 | + username := proxyURL.User.Username() |
| 39 | + password, hasPassword := proxyURL.User.Password() |
| 40 | + if hasPassword { |
| 41 | + auth = &proxy.Auth{User: username, Password: password} |
| 42 | + } else { |
| 43 | + auth = &proxy.Auth{User: username} |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // Create the SOCKS5 dialer |
| 48 | + socks5ProxyDialer, err := proxy.SOCKS5("tcp", proxyURL.Host, auth, proxy.Direct) |
| 49 | + if err != nil { |
| 50 | + return nil, fmt.Errorf("failed to create SOCKS5 proxy dialer: %w", err) |
| 51 | + } |
| 52 | + |
| 53 | + return &socks5WrapperDialer{dialer: socks5ProxyDialer}, nil |
| 54 | +} |
0 commit comments