-
Notifications
You must be signed in to change notification settings - Fork 23
/
http.go
76 lines (68 loc) · 1.74 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package proxy
import (
"context"
"encoding/base64"
"fmt"
"net"
"net/url"
"strings"
"time"
"github.com/projectdiscovery/fastdialer/fastdialer"
"github.com/projectdiscovery/rawhttp/client"
)
func httpDialer(proxyAddr string, timeout time.Duration, fd *fastdialer.Dialer) DialFunc {
return func(addr string) (net.Conn, error) {
var netConn net.Conn
var err error
var auth string
// close the connection when an error occurs
defer func() {
if err != nil && netConn != nil {
netConn.Close()
}
}()
u, err := url.Parse(proxyAddr)
if err != nil {
return nil, err
}
if strings.Contains(proxyAddr, "@") {
split := strings.Split(proxyAddr, "@")
auth = base64.StdEncoding.EncodeToString([]byte(split[0]))
proxyAddr = split[1]
}
if fd != nil {
netConn, err = fd.Dial(context.TODO(), "tcp", u.Host)
} else {
netConn, err = net.DialTimeout("tcp", u.Host, timeout)
}
if err != nil {
return nil, err
}
conn := client.NewClient(netConn)
req := "CONNECT " + addr + " HTTP/1.1\r\n"
if auth != "" {
req += "Proxy-Authorization: Basic " + auth + "\r\n"
}
req += "\r\n"
clientReq := &client.Request{
RawBytes: []byte(req),
}
if err = conn.WriteRequest(clientReq); err != nil {
return nil, err
}
resp, err := conn.ReadResponse(false)
if err != nil {
return nil, err
}
if resp.Status.Code != 200 {
return nil, fmt.Errorf("could not connect to proxy: %s status code: %d", proxyAddr, resp.Status.Code)
}
return netConn, nil
}
}
func HTTPDialer(proxyAddr string, timeout time.Duration) DialFunc {
return httpDialer(proxyAddr, timeout, nil)
}
func HTTPFastDialer(proxyAddr string, timeout time.Duration, fd *fastdialer.Dialer) DialFunc {
return httpDialer(proxyAddr, timeout, fd)
}