Files
fasthttp/fasthttpproxy/http.go
T
Amzza0x00 f6aac906c8 Fixed an error caused of character when @ > 1 during proxy authentication (#1452)
* Fixed a error caused by more @ character during proxy authentication

* Fixed a error caused by more @ character during proxy authentication
2022-12-08 15:03:55 +08:00

80 lines
1.9 KiB
Go

package fasthttpproxy
import (
"bufio"
"encoding/base64"
"fmt"
"net"
"strings"
"time"
"github.com/valyala/fasthttp"
)
// FasthttpHTTPDialer returns a fasthttp.DialFunc that dials using
// the provided HTTP proxy.
//
// Example usage:
//
// c := &fasthttp.Client{
// Dial: fasthttpproxy.FasthttpHTTPDialer("username:password@localhost:9050"),
// }
func FasthttpHTTPDialer(proxy string) fasthttp.DialFunc {
return FasthttpHTTPDialerTimeout(proxy, 0)
}
// FasthttpHTTPDialerTimeout returns a fasthttp.DialFunc that dials using
// the provided HTTP proxy using the given timeout.
//
// Example usage:
//
// c := &fasthttp.Client{
// 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
if timeout == 0 {
conn, err = fasthttp.Dial(proxy)
} else {
conn, err = fasthttp.DialTimeout(proxy, timeout)
}
if err != nil {
return nil, err
}
req := fmt.Sprintf("CONNECT %s HTTP/1.1\r\nHost: %s\r\n", addr, addr)
if auth != "" {
req += "Proxy-Authorization: Basic " + auth + "\r\n"
}
req += "\r\n"
if _, err := conn.Write([]byte(req)); err != nil {
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())
}
return conn, nil
}
}