-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathproxy.go
309 lines (255 loc) · 6.61 KB
/
proxy.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package azuretls
import (
"bufio"
"context"
"encoding/base64"
"errors"
"fmt"
http "github.com/Noooste/fhttp"
"github.com/Noooste/fhttp/http2"
tls "github.com/Noooste/utls"
"golang.org/x/net/proxy"
"io"
"net"
"net/url"
"strings"
"sync"
)
type proxyDialer struct {
ProxyURL *url.URL
DefaultHeader http.Header
Dialer net.Dialer
DialTLS func(network string, address string) (net.Conn, string, error)
h2Mu sync.Mutex
H2Conn *http2.ClientConn
conn net.Conn
sess *Session
}
const (
invalidProxy = "invalid proxy `%s`, %s"
)
func (s *Session) assignProxy(proxy string) error {
parsed, err := url.Parse(proxy)
if err != nil {
return err
}
switch parsed.Scheme {
case SchemeHttp:
if parsed.Port() == "" {
parsed.Host = net.JoinHostPort(parsed.Host, "80")
}
case SchemeHttps:
if parsed.Port() == "" {
parsed.Host = net.JoinHostPort(parsed.Host, "443")
}
case Socks5, Socks5H:
if parsed.Port() == "" {
parsed.Host = net.JoinHostPort(parsed.Host, "1080")
}
default:
return fmt.Errorf(invalidProxy, proxy, "scheme "+parsed.Scheme+" is not supported")
}
s.ProxyDialer = &proxyDialer{
ProxyURL: parsed,
DefaultHeader: make(http.Header),
sess: s,
}
if parsed.User != nil {
if parsed.User.Username() != "" {
if password, ok := parsed.User.Password(); !ok {
return fmt.Errorf(invalidProxy, proxy, "password is empty")
} else {
auth := parsed.User.Username() + ":" + password
basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
s.ProxyDialer.DefaultHeader.Add("Proxy-Authorization", basicAuth)
}
}
}
return nil
}
func (c *proxyDialer) Dial(userAgent, network, address string) (net.Conn, error) {
return c.DialContext(context.Background(), userAgent, network, address)
}
func (c *proxyDialer) DialContext(ctx context.Context, userAgent, network, address string) (net.Conn, error) {
if c.ProxyURL == nil {
return nil, errors.New("proxy is not set")
}
if strings.HasPrefix(c.ProxyURL.Scheme, "socks") {
dial, err := proxy.FromURL(c.ProxyURL, proxy.Direct)
if err != nil {
return nil, err
}
return dial.(proxy.ContextDialer).DialContext(ctx, network, address)
}
req := (&http.Request{
Method: http.MethodConnect,
URL: &url.URL{Host: address},
Header: make(http.Header),
Host: address,
}).WithContext(ctx)
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Connection", "keep-alive")
for k, v := range c.DefaultHeader {
req.Header[k] = v
}
for k, v := range c.sess.ProxyHeader {
if k == http.HeaderOrderKey {
for _, vv := range v {
req.Header[http.HeaderOrderKey] = append(req.Header[http.HeaderOrderKey], strings.ToLower(vv))
}
} else {
req.Header[k] = v
}
}
if ctxHeader, ctxHasHeader := ctx.Value(ContextKeyHeader{}).(http.Header); ctxHasHeader {
for k, v := range ctxHeader {
req.Header[k] = v
}
}
c.h2Mu.Lock()
unlocked := false
if c.H2Conn != nil && c.conn != nil {
if c.H2Conn.CanTakeNewRequest() {
rc := c.conn
cc := c.H2Conn
c.h2Mu.Unlock()
unlocked = true
if proxyConn, err := c.connectHTTP2(req, rc, cc); err == nil {
return proxyConn, nil
}
}
}
if !unlocked {
c.h2Mu.Unlock()
}
rawConn, negotiatedProtocol, err := c.InitProxyConn(ctx, network)
if err != nil {
return nil, err
}
return c.connect(req, rawConn, negotiatedProtocol)
}
type ContextKeyHeader struct{}
func (c *proxyDialer) connectHTTP1(req *http.Request, conn net.Conn) error {
req.Proto = "HTTP/1.1"
req.ProtoMajor = 1
req.ProtoMinor = 1
err := req.Write(conn)
if err != nil {
_ = conn.Close()
return err
}
resp, err := http.ReadResponse(bufio.NewReader(conn), req)
if err != nil {
_ = conn.Close()
return err
}
if resp.StatusCode != http.StatusOK {
_ = conn.Close()
return fmt.Errorf("proxy error : %s", resp.Status)
}
return nil
}
func (c *proxyDialer) connectHTTP2(req *http.Request, conn net.Conn, h2clientConn *http2.ClientConn) (net.Conn, error) {
req.Proto = "HTTP/2.0"
req.ProtoMajor = 2
req.ProtoMinor = 0
pr, pw := io.Pipe()
req.Body = pr
resp, err := h2clientConn.RoundTrip(req)
if err != nil {
_ = conn.Close()
return nil, err
}
if resp.StatusCode != http.StatusOK {
_ = conn.Close()
return nil, fmt.Errorf("proxy error : %s", resp.Status)
}
return newHTTP2Conn(conn, pw, resp.Body), nil
}
func (c *proxyDialer) InitProxyConn(ctx context.Context, network string) (rawConn net.Conn, negotiatedProtocol string, err error) {
switch c.ProxyURL.Scheme {
case SchemeHttp:
rawConn, err = c.Dialer.DialContext(ctx, network, c.ProxyURL.Host)
if err != nil {
return nil, "", err
}
case SchemeHttps:
if c.DialTLS != nil {
rawConn, negotiatedProtocol, err = c.DialTLS(network, c.ProxyURL.Host)
if err != nil {
return nil, "", err
}
} else {
tlsConf := tls.Config{
NextProtos: []string{"h2", "http/1.1"},
ServerName: c.ProxyURL.Hostname(),
InsecureSkipVerify: true,
}
var tlsConn *tls.Conn
tlsConn, err = tls.Dial(network, c.ProxyURL.Host, &tlsConf)
if err != nil {
return nil, "", err
}
err = tlsConn.Handshake()
if err != nil {
return nil, "", err
}
negotiatedProtocol = tlsConn.ConnectionState().NegotiatedProtocol
rawConn = tlsConn
}
default:
return nil, "", errors.New("scheme " + c.ProxyURL.Scheme + " is not supported")
}
return
}
func (c *proxyDialer) connect(req *http.Request, conn net.Conn, negotiatedProtocol string) (net.Conn, error) {
if negotiatedProtocol == http2.NextProtoTLS {
if h2clientConn, err := c.sess.HTTP2Transport.NewClientConn(conn); err == nil {
if proxyConn, err := c.connectHTTP2(req, conn, h2clientConn); err == nil {
c.h2Mu.Lock()
c.H2Conn = h2clientConn
c.conn = conn
c.h2Mu.Unlock()
return proxyConn, nil
}
}
}
if err := c.connectHTTP1(req, conn); err != nil {
_ = conn.Close()
return nil, err
}
return conn, nil
}
func newHTTP2Conn(c net.Conn, pipedReqBody *io.PipeWriter, respBody io.ReadCloser) net.Conn {
return &http2Conn{Conn: c, in: pipedReqBody, out: respBody}
}
type http2Conn struct {
net.Conn
in *io.PipeWriter
out io.ReadCloser
}
func (h *http2Conn) Read(p []byte) (n int, err error) {
return h.out.Read(p)
}
func (h *http2Conn) Write(p []byte) (n int, err error) {
return h.in.Write(p)
}
func (h *http2Conn) Close() error {
var retErr error = nil
if err := h.in.Close(); err != nil {
retErr = err
}
if err := h.out.Close(); err != nil {
retErr = err
}
return retErr
}
func (h *http2Conn) CloseConn() error {
return h.Conn.Close()
}
func (h *http2Conn) CloseWrite() error {
return h.in.Close()
}
func (h *http2Conn) CloseRead() error {
return h.out.Close()
}