-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdial.go
124 lines (100 loc) · 2.36 KB
/
dial.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package proxy
import (
"bufio"
"context"
"crypto/tls"
"fmt"
"golang.org/x/net/proxy"
"net"
"net/http"
"net/url"
)
type Dialer interface {
proxy.Dialer
SetTLS(isTLS bool)
}
type HttpDialer struct {
proxyURL *url.URL
isTLS bool
}
func (h *HttpDialer) Dial(network, addr string) (c net.Conn, err error) {
c, err = net.Dial(network, h.proxyURL.Host)
if err != nil {
return nil, err
}
if h.isTLS {
_, _ = httpsHandshake(c, addr)
return DailTLS(c)
}
return c, nil
}
func (h *HttpDialer) SetTLS(isTLS bool) {
h.isTLS = isTLS
}
type DefaultDialer struct {
dialer proxy.Dialer
isTLS bool
}
func (d *DefaultDialer) Dial(network, addr string) (c net.Conn, err error) {
c, err = d.dialer.Dial(network, addr)
if err != nil {
return nil, err
}
if d.isTLS {
return DailTLS(c)
}
return c, nil
}
func (d *DefaultDialer) SetTLS(isTLS bool) {
d.isTLS = isTLS
}
func FromURL(httpClient *http.Client, rawURL any) (dialer proxy.Dialer, err error) {
// input URL support type are string , *url.URL
var proxyURL *url.URL
switch rawURL.(type) {
case string:
proxyURL, err = url.Parse(rawURL.(string))
if err != nil {
return nil, err
}
case *url.URL:
proxyURL = rawURL.(*url.URL)
default:
return nil, fmt.Errorf("unsupported type: %T", rawURL)
}
transport := httpClient.Transport.(*http.Transport)
switch proxyURL.Scheme {
case "http":
transport.Proxy = http.ProxyURL(proxyURL)
return &HttpDialer{proxyURL: proxyURL}, nil
default:
dialer, err = proxy.FromURL(proxyURL, proxy.Direct)
if err != nil {
return nil, err
}
transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.Dial(network, addr)
}
return &DefaultDialer{dialer: dialer}, nil
}
}
func httpsHandshake(c net.Conn, addr string) (code int, err error) {
connReq := fmt.Sprintf("CONNECT %s HTTP/1.1\r\n", addr)
connReq += fmt.Sprintf("Host: %s\r\n", addr)
connReq += "Connection: close\r\n\r\n"
if _, err = c.Write([]byte(connReq)); err != nil {
return 0, err
}
connResp, err := http.ReadResponse(bufio.NewReader(c), nil)
if err != nil {
return 0, err
}
return connResp.StatusCode, nil
}
func DailTLS(c net.Conn) (tlsClient *tls.Conn, err error) {
tlsClient = tls.Client(c, &tls.Config{InsecureSkipVerify: true})
if err = tlsClient.Handshake(); err != nil {
return nil, err
}
return tlsClient, nil
}