From 6ed7f6bbf789cdff7b1019e8fce299ee558818c6 Mon Sep 17 00:00:00 2001 From: newacorn Date: Sat, 24 Aug 2024 18:46:01 +0800 Subject: [PATCH] Add a multifunctional Dialer struct. (#1829) Add a multifunctional `Dialer` struct and reimplement the function API Reimplement the existing function interfaces of the fasthttpproxy package through Dialer. Refactor Dialer.GetDialFunc to ensure that its performance is comparable to the original function interfaces when the proxy does not change with the request address. --- fasthttpproxy/dialer.go | 263 ++++++++++++++++++++++++++++++ fasthttpproxy/dialer_test.go | 306 +++++++++++++++++++++++++++++++++++ fasthttpproxy/http.go | 81 +--------- fasthttpproxy/proxy_env.go | 114 +------------ fasthttpproxy/socks5.go | 27 +--- 5 files changed, 582 insertions(+), 209 deletions(-) create mode 100644 fasthttpproxy/dialer.go create mode 100644 fasthttpproxy/dialer_test.go diff --git a/fasthttpproxy/dialer.go b/fasthttpproxy/dialer.go new file mode 100644 index 0000000000..9846491c69 --- /dev/null +++ b/fasthttpproxy/dialer.go @@ -0,0 +1,263 @@ +package fasthttpproxy + +import ( + "bufio" + "encoding/base64" + "errors" + "fmt" + "net" + "net/url" + "strings" + "sync" + "time" + + "github.com/valyala/fasthttp" + "golang.org/x/net/http/httpproxy" + "golang.org/x/net/proxy" +) + +var ( + // Used for caching authentication information when using an HTTP proxy, + // it helps avoid re-encoding the authentication details when the ProxyURL + // changes along with the request URL. + authCache = sync.Map{} + colonTLSPort = ":443" + tmpURL = &url.URL{Scheme: httpsScheme, Host: "example.com"} +) + +// Dialer embeds both fasthttp.TCPDialer and httpproxy.Config, allowing it +// to take advantage of the optimizations provided by fasthttp for dialing while also +// utilizing the finer-grained configuration options offered by httpproxy. +type Dialer struct { + fasthttp.TCPDialer + // Support HTTPProxy, HTTPSProxy and NoProxy configuration. + // + // HTTPProxy represents the value of the HTTP_PROXY or + // http_proxy environment variable. It will be used as the proxy + // URL for HTTP requests unless overridden by NoProxy. + // + // HTTPSProxy represents the HTTPS_PROXY or https_proxy + // environment variable. It will be used as the proxy URL for + // HTTPS requests unless overridden by NoProxy. + // + // NoProxy represents the NO_PROXY or no_proxy environment + // variable. It specifies a string that contains comma-separated values + // specifying hosts that should be excluded from proxying. Each value is + // represented by an IP address prefix (1.2.3.4), an IP address prefix in + // CIDR notation (1.2.3.4/8), a domain name, or a special DNS label (*). + // An IP address prefix and domain name can also include a literal port + // number (1.2.3.4:80). + // A domain name matches that name and all subdomains. A domain name with + // a leading "." matches subdomains only. For example "foo.com" matches + // "foo.com" and "bar.foo.com"; ".y.com" matches "x.y.com" but not "y.com". + // A single asterisk (*) indicates that no proxying should be done. + // A best effort is made to parse the string and errors are + // ignored. + httpproxy.Config + // Attempt to connect to both ipv4 and ipv6 addresses if set to true. + // By default, dial only to ipv4 addresses, + // since unfortunately ipv6 remains broken in many networks worldwide :) + // + // This field from the fasthttp client is provided redundantly here because + // when we customize the Dial function for the client, its DialDualStack field + // configuration becomes ineffective. + DialDualStack bool + // Dial timeout. + // + // This field from the fasthttp client is provided redundantly here because + // when we customize the Dial function for the client, its DialTimeout field + // configuration becomes ineffective. + Timeout time.Duration + // The timeout for sending a CONNECT request when using an HTTP proxy. + ConnectTimeout time.Duration +} + +// GetDialFunc method returns a fasthttp-style dial function. The useEnv parameter +// determines whether the proxy address comes from Dialer.Config or from environment variables. +func (d *Dialer) GetDialFunc(useEnv bool) (dialFunc fasthttp.DialFunc, err error) { + config := &d.Config + if useEnv { + config = httpproxy.FromEnvironment() + } + proxyURLIsSame := false + if config.HTTPSProxy == config.HTTPProxy && config.NoProxy == "" { + proxyURLIsSame = true + } + network := "tcp4" + if d.DialDualStack { + network = "tcp" + } + proxyFunc := config.ProxyFunc() + if proxyURLIsSame { + var proxyURL *url.URL + var proxyDialer proxy.Dialer + proxyURL, err = proxyFunc(tmpURL) + if err != nil { + return nil, err + } + if proxyURL == nil { + // dial directly + return func(addr string) (net.Conn, error) { + return d.Dial(network, addr) + }, nil + } + switch proxyURL.Scheme { + case "socks5", "socks5h": + proxyDialer, err = proxy.FromURL(proxyURL, d) + if err != nil { + return + } + case "http": + proxyAddr, auth := addrAndAuth(proxyURL) + proxyDialer = DialerFunc(func(network, addr string) (conn net.Conn, err error) { + return httpProxyDial(d, network, addr, proxyAddr, auth) + }) + default: + return nil, errors.New("proxy: unknown scheme: " + proxyURL.Scheme) + } + return func(addr string) (net.Conn, error) { + return proxyDialer.Dial(network, addr) + }, nil + } + // slow path when the proxyURL changes along with the request URL. + return func(addr string) (conn net.Conn, err error) { + var proxyDialer proxy.Dialer + var proxyURL *url.URL + scheme := httpsScheme + if !strings.HasSuffix(addr, colonTLSPort) { + scheme = httpScheme + } + reqURL := &url.URL{Host: addr, Scheme: scheme} + proxyURL, err = proxyFunc(reqURL) + if err != nil { + return + } + if proxyURL == nil { + // dial directly + return d.Dial(network, addr) + } + switch proxyURL.Scheme { + case "socks5", "socks5h": + proxyDialer, err = proxy.FromURL(proxyURL, d) + if err != nil { + return + } + case "http": + proxyAddr, auth := addrAndAuth(proxyURL) + proxyDialer = DialerFunc(func(network, addr string) (conn net.Conn, err error) { + return httpProxyDial(d, network, addr, proxyAddr, auth) + }) + default: + return nil, errors.New("proxy: unknown scheme: " + proxyURL.Scheme) + } + return proxyDialer.Dial(network, addr) + }, nil +} + +// Dial is solely for implementing the proxy.Dialer interface. +func (d *Dialer) Dial(network, addr string) (conn net.Conn, err error) { + if network == "tcp4" { + if d.Timeout > 0 { + return d.TCPDialer.DialTimeout(addr, d.Timeout) + } + return d.TCPDialer.Dial(addr) + } + if network == "tcp" { + if d.Timeout > 0 { + return d.TCPDialer.DialDualStackTimeout(addr, d.Timeout) + } + return d.TCPDialer.DialDualStack(addr) + } + err = errors.New("dont support the network: " + network) + return +} + +func (d *Dialer) connectTimeout() time.Duration { + return d.ConnectTimeout +} + +// In the httpProxyDial function, the proxy.Dialer that implements +// this interface can retrieve timeout information when sending the CONNECT +// method to the HTTP proxy. +type httpProxyDialer interface { + connectTimeout() time.Duration +} + +// DialerFunc Make a function of type func(network, addr string) (net.Conn, error) +// implement the proxy.Dialer interface. +type DialerFunc func(network, addr string) (net.Conn, error) + +func (d DialerFunc) Dial(network, addr string) (net.Conn, error) { + return d(network, addr) +} + +// Establish a connection through an HTTP proxy. +func httpProxyDial(dialer proxy.Dialer, network, addr, proxyAddr, auth string) (conn net.Conn, err error) { + conn, err = dialer.Dial(network, proxyAddr) + if err != nil { + return + } + var connectTimeout time.Duration + hp, ok := dialer.(httpProxyDialer) + if ok { + connectTimeout = hp.connectTimeout() + } + + if connectTimeout > 0 { + if err = conn.SetDeadline(time.Now().Add(connectTimeout)); err != nil { + _ = conn.Close() + return nil, err + } + defer func() { + _ = conn.SetDeadline(time.Time{}) + }() + } + req := "CONNECT " + addr + " HTTP/1.1\r\nHost: " + addr + "\r\n" + if auth != "" { + req += "Proxy-Authorization: Basic " + auth + "\r\n" + } + req += "\r\n" + _, err = conn.Write([]byte(req)) + if err != nil { + _ = conn.Close() + return + } + res := fasthttp.AcquireResponse() + defer fasthttp.ReleaseResponse(res) + res.SkipBody = true + if err = res.Read(bufio.NewReaderSize(conn, 1024)); err != nil { + _ = conn.Close() + return + } + if res.Header.StatusCode() != 200 { + _ = conn.Close() + err = fmt.Errorf("could not connect to proxyAddr: %s status code: %d", proxyAddr, res.Header.StatusCode()) + return + } + return +} + +// Cache authentication information for HTTP proxies. +type proxyInfo struct { + auth string + addr string +} + +func addrAndAuth(pu *url.URL) (proxyAddr, auth string) { + if pu.User == nil { + proxyAddr = pu.Host + pu.Path + return + } + var info *proxyInfo + v, ok := authCache.Load(pu) + if ok { + info = v.(*proxyInfo) + return info.addr, info.auth + } + info = &proxyInfo{ + auth: base64.StdEncoding.EncodeToString([]byte(pu.User.String())), + addr: pu.Host + pu.Path, + } + authCache.Store(pu, info) + return info.addr, info.auth +} diff --git a/fasthttpproxy/dialer_test.go b/fasthttpproxy/dialer_test.go new file mode 100644 index 0000000000..e2802c10aa --- /dev/null +++ b/fasthttpproxy/dialer_test.go @@ -0,0 +1,306 @@ +package fasthttpproxy + +import ( + "bufio" + "io" + "net" + "strings" + "sync/atomic" + "testing" + + "github.com/valyala/fasthttp" + "golang.org/x/net/http/httpproxy" +) + +func TestDialer_GetDialFunc(t *testing.T) { + counts := make([]atomic.Int64, 4) + proxyListenPorts := []string{"8001", "8002", "8003", "8004"} + lns := startProxyServer(t, proxyListenPorts, counts) + defer func() { + for _, l := range lns { + l.Close() + } + }() + t.Setenv("HTTP_PROXY", "http://127.0.0.1:"+proxyListenPorts[2]) + t.Setenv("HTTPS_PROXY", "http://127.0.0.1:"+proxyListenPorts[3]) + t.Setenv("NO_PROXY", "example.com") + type fields struct { + httpProxy string + httpsProxy string + noProxy string + } + type args struct { + useEnv bool + } + tests := []struct { + name string + fields fields + args args + wantCounts []int64 + dialAddr string + wantErrMessage string + }{ + { + name: "proxy information comes from the configuration. dial https host", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[1], + noProxy: "example.com", + }, + args: args{ + useEnv: false, + }, + wantCounts: []int64{0, 1, 0, 0}, + dialAddr: "www.google.com:443", + }, + { + name: "proxy information comes from the configuration. dial http host", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[1], + noProxy: "example.com", + }, + args: args{ + useEnv: false, + }, + wantCounts: []int64{1, 0, 0, 0}, + dialAddr: "www.google.com:80", + }, + { + name: "proxy information comes from the configuration. dial http host matched with noProxy", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[1], + noProxy: "example.com", + }, + args: args{ + useEnv: false, + }, + wantCounts: []int64{0, 0, 0, 0}, + dialAddr: "example.com:80", + }, + { + name: "proxy information comes from the configuration. dial https host matched with noProxy", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[1], + noProxy: "example.com", + }, + args: args{ + useEnv: false, + }, + wantCounts: []int64{0, 0, 0, 0}, + dialAddr: "example.com:443", + }, + { + name: "proxy information comes from the env. dial http host", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[1], + noProxy: "example.com", + }, + args: args{ + useEnv: true, + }, + wantCounts: []int64{0, 0, 1, 0}, + dialAddr: "www.google.com:80", + }, + { + name: "proxy information comes from the env. dial https host", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[1], + noProxy: "example.com", + }, + args: args{ + useEnv: true, + }, + wantCounts: []int64{0, 0, 0, 1}, + dialAddr: "www.google.com:443", + }, + + { + name: "proxy information comes from the env. dial http host matched with noProxy", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[1], + noProxy: "example.com", + }, + args: args{ + useEnv: true, + }, + wantCounts: []int64{0, 0, 0, 0}, + dialAddr: "example.com:80", + }, + { + name: "proxy information comes from the env. dial https host matched with noProxy", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[1], + noProxy: "example.com", + }, + args: args{ + useEnv: true, + }, + wantCounts: []int64{0, 0, 0, 0}, + dialAddr: "example.com:443", + }, + { + name: "proxy information comes from the configuration and httpProxy same with httpsProxy. dial http host", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[0], + noProxy: "example.com", + }, + args: args{ + useEnv: false, + }, + wantCounts: []int64{1, 0, 0, 0}, + dialAddr: "www.google.com:80", + }, + { + name: "proxy information comes from the configuration and httpProxy same with httpsProxy. dial https host", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[0], + noProxy: "example.com", + }, + args: args{ + useEnv: false, + }, + wantCounts: []int64{1, 0, 0, 0}, + dialAddr: "www.google.com:443", + }, + { + name: "proxy information comes from the configuration and httpProxy same with httpsProxy. dial http host matched with noProxy", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[0], + noProxy: "example.com", + }, + args: args{ + useEnv: false, + }, + wantCounts: []int64{0, 0, 0, 0}, + dialAddr: "example.com:80", + }, + { + name: "proxy information comes from the configuration and httpProxy same with httpsProxy. dial https host matched with noProxy", + fields: fields{ + httpProxy: "http://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "http://127.0.0.1:" + proxyListenPorts[0], + noProxy: "example.com", + }, + args: args{ + useEnv: false, + }, + wantCounts: []int64{0, 0, 0, 0}, + dialAddr: "example.com:443", + }, + { + name: "return an error for unsupported proxy protocols.", + fields: fields{ + httpProxy: "socket6://127.0.0.1:" + proxyListenPorts[0], + httpsProxy: "socket6://127.0.0.1:" + proxyListenPorts[0], + }, + args: args{ + useEnv: false, + }, + wantCounts: []int64{0, 0, 0, 0}, + dialAddr: "www.google.com:80", + wantErrMessage: "proxy: unknown scheme: socket6", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + d := getDialer(tt.fields.httpProxy, tt.fields.httpsProxy, tt.fields.noProxy) + dialFunc, err := d.GetDialFunc(tt.args.useEnv) + if (err != nil) != (tt.wantErrMessage != "") { + t.Fatalf("GetDialFunc() error = %v, wantErr %v", err, tt.wantErrMessage) + return + } + if tt.wantErrMessage != "" { + if err.Error() != tt.wantErrMessage { + t.Fatalf("want error message: %s, got: %s", err.Error(), tt.wantErrMessage) + } + return + } + _, err = dialFunc(tt.dialAddr) + if err != nil { + t.Fatal(err) + } + if !countsEqual(getCounts(counts), tt.wantCounts) { + t.Errorf("GetDialFunc() counts = %v, want %v", getCounts(counts), tt.wantCounts) + } + }) + for i := 0; i < len(counts); i++ { + counts[i].Store(0) + } + } +} + +func startProxyServer(t *testing.T, ports []string, counts []atomic.Int64) (lns []net.Listener) { + for i, port := range ports { + ln, err := net.Listen("tcp", ":"+port) + if err != nil { + t.Fatal(err) + } + lns = append(lns, ln) + i := i + go func() { + req := fasthttp.AcquireRequest() + for { + conn, err := ln.Accept() + if err != nil { + if err != io.EOF && !strings.Contains(err.Error(), "use of closed network connection") { + t.Error(err) + } + break + } + err = req.Read(bufio.NewReader(conn)) + if err != nil { + t.Error(err) + } + if string(req.Header.Method()) == "CONNECT" { + counts[i].Add(1) + } + _, err = conn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) + if err != nil { + t.Error(err) + } + req.Reset() + } + fasthttp.ReleaseRequest(req) + }() + } + return +} + +func getDialer(httpProxy, httpsProxy, noProxy string) *Dialer { + return &Dialer{ + Config: httpproxy.Config{ + HTTPProxy: httpProxy, + HTTPSProxy: httpsProxy, + NoProxy: noProxy, + }, + } +} + +func getCounts(counts []atomic.Int64) (r []int64) { + for i := 0; i < len(counts); i++ { + r = append(r, counts[i].Load()) + } + return +} + +func countsEqual(a, b []int64) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if b[i] != a[i] { + return false + } + } + return true +} diff --git a/fasthttpproxy/http.go b/fasthttpproxy/http.go index a1a9e4c741..80885d01e1 100644 --- a/fasthttpproxy/http.go +++ b/fasthttpproxy/http.go @@ -1,14 +1,10 @@ package fasthttpproxy import ( - "bufio" - "encoding/base64" - "fmt" - "net" - "strings" "time" "github.com/valyala/fasthttp" + "golang.org/x/net/http/httpproxy" ) // FasthttpHTTPDialer returns a fasthttp.DialFunc that dials using @@ -25,6 +21,7 @@ func FasthttpHTTPDialer(proxy string) fasthttp.DialFunc { // FasthttpHTTPDialerTimeout returns a fasthttp.DialFunc that dials using // the provided HTTP proxy using the given timeout. +// The timeout parameter determines both the dial timeout and the CONNECT request timeout. // // Example usage: // @@ -32,75 +29,7 @@ func FasthttpHTTPDialer(proxy string) fasthttp.DialFunc { // Dial: fasthttpproxy.FasthttpHTTPDialerTimeout("username:password@localhost:9050", time.Second * 2), // } func FasthttpHTTPDialerTimeout(proxy string, timeout time.Duration) fasthttp.DialFunc { - var auth string - if strings.Contains(proxy, "@") { - index := strings.LastIndex(proxy, "@") - auth = base64.StdEncoding.EncodeToString([]byte(proxy[:index])) - proxy = proxy[index+1:] - } - - return func(addr string) (net.Conn, error) { - var conn net.Conn - var err error - start := time.Now() - - if strings.HasPrefix(proxy, "[") { - // ipv6 - if timeout == 0 { - conn, err = fasthttp.DialDualStack(proxy) - } else { - conn, err = fasthttp.DialDualStackTimeout(proxy, timeout) - } - } else { - // ipv4 - if timeout == 0 { - conn, err = fasthttp.Dial(proxy) - } else { - conn, err = fasthttp.DialTimeout(proxy, timeout) - } - } - - if err != nil { - return nil, err - } - - if timeout > 0 { - if err = conn.SetDeadline(start.Add(timeout)); err != nil { - conn.Close() - return nil, err - } - } - - req := "CONNECT " + addr + " HTTP/1.1\r\nHost: " + addr + "\r\n" - if auth != "" { - req += "Proxy-Authorization: Basic " + auth + "\r\n" - } - req += "\r\n" - - if _, err := conn.Write([]byte(req)); err != nil { - conn.Close() - return nil, err - } - - res := fasthttp.AcquireResponse() - defer fasthttp.ReleaseResponse(res) - - res.SkipBody = true - - if err := res.Read(bufio.NewReader(conn)); err != nil { - conn.Close() - return nil, err - } - if res.Header.StatusCode() != 200 { - conn.Close() - return nil, fmt.Errorf("could not connect to proxy: %s status code: %d", proxy, res.Header.StatusCode()) - } - if timeout > 0 { - if err := conn.SetDeadline(time.Time{}); err != nil { - conn.Close() - return nil, err - } - } - return conn, nil - } + d := Dialer{Config: httpproxy.Config{HTTPProxy: proxy, HTTPSProxy: proxy}, Timeout: timeout, ConnectTimeout: timeout} + dialFunc, _ := d.GetDialFunc(false) + return dialFunc } diff --git a/fasthttpproxy/proxy_env.go b/fasthttpproxy/proxy_env.go index 144859398c..342b09346f 100644 --- a/fasthttpproxy/proxy_env.go +++ b/fasthttpproxy/proxy_env.go @@ -1,22 +1,14 @@ package fasthttpproxy import ( - "bufio" - "encoding/base64" - "fmt" - "net" - "net/url" - "sync/atomic" "time" "github.com/valyala/fasthttp" - "golang.org/x/net/http/httpproxy" ) const ( httpsScheme = "https" httpScheme = "http" - tlsPort = "443" ) // FasthttpProxyHTTPDialer returns a fasthttp.DialFunc that dials using @@ -33,6 +25,7 @@ func FasthttpProxyHTTPDialer() fasthttp.DialFunc { // FasthttpProxyHTTPDialerTimeout returns a fasthttp.DialFunc that dials using // the env(HTTP_PROXY, HTTPS_PROXY and NO_PROXY) configured HTTP proxy using the given timeout. +// The timeout parameter determines both the dial timeout and the CONNECT request timeout. // // Example usage: // @@ -40,106 +33,7 @@ func FasthttpProxyHTTPDialer() fasthttp.DialFunc { // Dial: fasthttpproxy.FasthttpProxyHTTPDialerTimeout(time.Second * 2), // } func FasthttpProxyHTTPDialerTimeout(timeout time.Duration) fasthttp.DialFunc { - proxier := httpproxy.FromEnvironment().ProxyFunc() - - // encoded auth barrier for http and https proxy. - authHTTPStorage := &atomic.Value{} - authHTTPSStorage := &atomic.Value{} - - return func(addr string) (net.Conn, error) { - start := time.Now() - port, _, err := net.SplitHostPort(addr) - if err != nil { - return nil, fmt.Errorf("unexpected addr format: %w", err) - } - - reqURL := &url.URL{Host: addr, Scheme: httpScheme} - if port == tlsPort { - reqURL.Scheme = httpsScheme - } - proxyURL, err := proxier(reqURL) - if err != nil { - return nil, err - } - - if proxyURL == nil { - if timeout == 0 { - return fasthttp.Dial(addr) - } - return fasthttp.DialTimeout(addr, timeout) - } - - var conn net.Conn - if timeout == 0 { - conn, err = fasthttp.Dial(proxyURL.Host) - } else { - conn, err = fasthttp.DialTimeout(proxyURL.Host, timeout) - } - if err != nil { - return nil, err - } - - if timeout > 0 { - if err := conn.SetDeadline(start.Add(timeout)); err != nil { - if connErr := conn.Close(); connErr != nil { - return nil, fmt.Errorf("conn close err %v precede by set conn deadline %w", connErr, err) - } - } - } - - req := "CONNECT " + addr + " HTTP/1.1\r\n" - - if proxyURL.User != nil { - authBarrierStorage := authHTTPStorage - if port == tlsPort { - authBarrierStorage = authHTTPSStorage - } - - auth := authBarrierStorage.Load() - if auth == nil { - authBarrier := base64.StdEncoding.EncodeToString([]byte(proxyURL.User.String())) - auth = &authBarrier - authBarrierStorage.Store(auth) - } - - req += "Proxy-Authorization: Basic " + *auth.(*string) + "\r\n" - } - req += "\r\n" - - if _, err := conn.Write([]byte(req)); err != nil { - if connErr := conn.Close(); connErr != nil { - return nil, fmt.Errorf("conn close err %v precede by write conn err %w", connErr, err) - } - return nil, err - } - - res := fasthttp.AcquireResponse() - defer fasthttp.ReleaseResponse(res) - - res.SkipBody = true - - if err := res.Read(bufio.NewReader(conn)); err != nil { - if connErr := conn.Close(); connErr != nil { - return nil, fmt.Errorf("conn close err %v precede by read conn err %w", connErr, err) - } - return nil, err - } - if res.Header.StatusCode() != 200 { - if connErr := conn.Close(); connErr != nil { - return nil, fmt.Errorf( - "conn close err %w precede by connect to proxy: code: %d body %q", - connErr, res.StatusCode(), string(res.Body())) - } - return nil, fmt.Errorf("could not connect to proxy: code: %d body %q", res.StatusCode(), string(res.Body())) - } - if timeout > 0 { - if err := conn.SetDeadline(time.Time{}); err != nil { - if connErr := conn.Close(); connErr != nil { - return nil, fmt.Errorf("conn close err %v precede by clear conn deadline err %w", connErr, err) - } - return nil, err - } - } - return conn, nil - } + d := Dialer{Timeout: timeout, ConnectTimeout: timeout} + dialFunc, _ := d.GetDialFunc(true) + return dialFunc } diff --git a/fasthttpproxy/socks5.go b/fasthttpproxy/socks5.go index a01c2047f1..0328cd25cd 100644 --- a/fasthttpproxy/socks5.go +++ b/fasthttpproxy/socks5.go @@ -1,11 +1,8 @@ package fasthttpproxy import ( - "net" - "net/url" - "github.com/valyala/fasthttp" - "golang.org/x/net/proxy" + "golang.org/x/net/http/httpproxy" ) // FasthttpSocksDialer returns a fasthttp.DialFunc that dials using @@ -17,23 +14,7 @@ import ( // Dial: fasthttpproxy.FasthttpSocksDialer("socks5://localhost:9050"), // } func FasthttpSocksDialer(proxyAddr string) fasthttp.DialFunc { - var ( - u *url.URL - err error - dialer proxy.Dialer - ) - if u, err = url.Parse(proxyAddr); err == nil { - dialer, err = proxy.FromURL(u, proxy.Direct) - } - // It would be nice if we could return the error here. But we can't - // change our API so just keep returning it in the returned Dial function. - // Besides the implementation of proxy.SOCKS5() at the time of writing this - // will always return nil as error. - - return func(addr string) (net.Conn, error) { - if err != nil { - return nil, err - } - return dialer.Dial("tcp", addr) - } + d := Dialer{Config: httpproxy.Config{HTTPProxy: proxyAddr, HTTPSProxy: proxyAddr}} + dialFunc, _ := d.GetDialFunc(false) + return dialFunc }