forked from cyfdecyf/cow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparent_proxy.go
382 lines (332 loc) · 9.29 KB
/
parent_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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package main
import (
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
ss "github.com/shadowsocks/shadowsocks-go/shadowsocks"
"io"
"math/rand"
"net"
"strconv"
)
func connectByParentProxy(url *URL) (srvconn net.Conn, err error) {
const baseFailCnt = 9
var skipped []int
nproxy := len(parentProxy)
firstId := 0
if config.LoadBalance == loadBalanceHash {
firstId = int(stringHash(url.Host) % uint64(nproxy))
debug.Println("use proxy", firstId)
}
for i := 0; i < nproxy; i++ {
proxyId := (firstId + i) % nproxy
pp := &parentProxy[proxyId]
// skip failed server, but try it with some probability
if pp.failCnt > 0 && rand.Intn(pp.failCnt+baseFailCnt) != 0 {
skipped = append(skipped, proxyId)
continue
}
if srvconn, err = pp.connect(url); err == nil {
return
}
}
// last resort, try skipped one, not likely to succeed
for _, skippedId := range skipped {
if srvconn, err = parentProxy[skippedId].connect(url); err == nil {
return
}
}
if len(parentProxy) != 0 {
return
}
return nil, errors.New("no parent proxy")
}
// proxyConnector is the interface that all parent proxies should support.
type proxyConnector interface {
connect(*URL) (net.Conn, error)
genConfig() string // for upgrading config
}
type ParentProxy struct {
proxyConnector
failCnt int
}
var parentProxy []ParentProxy
func hasParentProxy() bool {
return len(parentProxy) != 0
}
func addParentProxy(pc proxyConnector) {
parentProxy = append(parentProxy, ParentProxy{pc, 0})
}
func (pp *ParentProxy) connect(url *URL) (srvconn net.Conn, err error) {
const maxFailCnt = 30
srvconn, err = pp.proxyConnector.connect(url)
if err != nil {
if pp.failCnt < maxFailCnt && !networkBad() {
pp.failCnt++
}
return
}
pp.failCnt = 0
return
}
func printParentProxy() {
debug.Println("avaiable parent proxies:")
for _, pp := range parentProxy {
switch pc := pp.proxyConnector.(type) {
case *shadowsocksParent:
debug.Println("\tshadowsocks: ", pc.server)
case *httpParent:
debug.Println("\thttp parent: ", pc.server)
case *socksParent:
debug.Println("\tsocks parent: ", pc.server)
case *cowParent:
debug.Println("\tcow parent: ", pc.server)
}
}
}
// http parent proxy
type httpParent struct {
server string
userPasswd string // for upgrade config
authHeader []byte
}
type httpConn struct {
net.Conn
parent *httpParent
}
func (s httpConn) String() string {
return "http parent proxy " + s.parent.server
}
func newHttpParent(server string) *httpParent {
return &httpParent{server: server}
}
func (hp *httpParent) genConfig() string {
if hp.userPasswd != "" {
return fmt.Sprintf("proxy = http://%s@%s", hp.userPasswd, hp.server)
} else {
return fmt.Sprintf("proxy = http://%s", hp.server)
}
}
func (hp *httpParent) initAuth(userPasswd string) {
if userPasswd == "" {
return
}
hp.userPasswd = userPasswd
b64 := base64.StdEncoding.EncodeToString([]byte(userPasswd))
hp.authHeader = []byte(headerProxyAuthorization + ": Basic " + b64 + CRLF)
}
func (hp *httpParent) connect(url *URL) (net.Conn, error) {
c, err := net.Dial("tcp", hp.server)
if err != nil {
errl.Printf("can't connect to http parent %s for %s: %v\n",
hp.server, url.HostPort, err)
return nil, err
}
debug.Printf("connected to: %s via http parent: %s\n",
url.HostPort, hp.server)
return httpConn{c, hp}, nil
}
// shadowsocks parent proxy
type shadowsocksParent struct {
server string
method string // method and passwd are for upgrade config
passwd string
cipher *ss.Cipher
}
type shadowsocksConn struct {
net.Conn
parent *shadowsocksParent
}
func (s shadowsocksConn) String() string {
return "shadowsocks proxy " + s.parent.server
}
// In order to use parent proxy in the order specified in the config file, we
// insert an uninitialized proxy into parent proxy list, and initialize it
// when all its config have been parsed.
func newShadowsocksParent(server string) *shadowsocksParent {
return &shadowsocksParent{server: server}
}
func (sp *shadowsocksParent) genConfig() string {
if sp.method == "" {
return fmt.Sprintf("proxy = ss://table:%s@%s", sp.passwd, sp.server)
} else {
return fmt.Sprintf("proxy = ss://%s:%s@%s", sp.method, sp.passwd, sp.server)
}
}
func (sp *shadowsocksParent) initCipher(method, passwd string) {
sp.method = method
sp.passwd = passwd
cipher, err := ss.NewCipher(method, passwd)
if err != nil {
Fatal("create shadowsocks cipher:", err)
}
sp.cipher = cipher
}
func (sp *shadowsocksParent) connect(url *URL) (net.Conn, error) {
c, err := ss.Dial(url.HostPort, sp.server, sp.cipher.Copy())
if err != nil {
errl.Printf("can't connect to shadowsocks parent %s for %s: %v\n",
sp.server, url.HostPort, err)
return nil, err
}
debug.Println("connected to:", url.HostPort, "via shadowsocks:", sp.server)
return shadowsocksConn{c, sp}, nil
}
// cow parent proxy
type cowParent struct {
server string
cipher *ss.Cipher
}
type cowConn struct {
net.Conn
parent *cowParent
}
func (s cowConn) String() string {
return "cow proxy " + s.parent.server
}
func newCowParent(srv, method, passwd string) *cowParent {
cipher, err := ss.NewCipher(method, passwd)
if err != nil {
Fatal("create cow cipher:", err)
}
return &cowParent{srv, cipher}
}
func (cp *cowParent) genConfig() string {
return "" // no upgrading need
}
func (cp *cowParent) connect(url *URL) (net.Conn, error) {
c, err := net.Dial("tcp", cp.server)
if err != nil {
errl.Printf("can't connect to cow parent %s for %s: %v\n",
cp.server, url.HostPort, err)
return nil, err
}
debug.Printf("connected to: %s via cow parent: %s\n",
url.HostPort, cp.server)
ssconn := ss.NewConn(c, cp.cipher.Copy())
return cowConn{ssconn, cp}, nil
}
// For socks documentation, refer to rfc 1928 http://www.ietf.org/rfc/rfc1928.txt
var socksError = [...]string{
1: "General SOCKS server failure",
2: "Connection not allowed by ruleset",
3: "Network unreachable",
4: "Host unreachable",
5: "Connection refused",
6: "TTL expired",
7: "Command not supported",
8: "Address type not supported",
9: "to X'FF' unassigned",
}
var socksProtocolErr = errors.New("socks protocol error")
var socksMsgVerMethodSelection = []byte{
0x5, // version 5
1, // n method
0, // no authorization required
}
// socks5 parent proxy
type socksParent struct {
server string
}
type socksConn struct {
net.Conn
parent *socksParent
}
func (s socksConn) String() string {
return "socks proxy " + s.parent.server
}
func newSocksParent(server string) *socksParent {
return &socksParent{server}
}
func (sp *socksParent) genConfig() string {
return fmt.Sprintf("proxy = socks5://%s", sp.server)
}
func (sp *socksParent) connect(url *URL) (net.Conn, error) {
c, err := net.Dial("tcp", sp.server)
if err != nil {
errl.Printf("can't connect to socks parent %s for %s: %v\n",
sp.server, url.HostPort, err)
return nil, err
}
hasErr := false
defer func() {
if hasErr {
c.Close()
}
}()
var n int
if n, err = c.Write(socksMsgVerMethodSelection); n != 3 || err != nil {
errl.Printf("sending ver/method selection msg %v n = %v\n", err, n)
hasErr = true
return nil, err
}
// version/method selection
repBuf := make([]byte, 2)
_, err = io.ReadFull(c, repBuf)
if err != nil {
errl.Printf("read ver/method selection error %v\n", err)
hasErr = true
return nil, err
}
if repBuf[0] != 5 || repBuf[1] != 0 {
errl.Printf("socks ver/method selection reply error ver %d method %d",
repBuf[0], repBuf[1])
hasErr = true
return nil, err
}
// debug.Println("Socks version selection done")
// send connect request
host := url.Host
port, err := strconv.Atoi(url.Port)
if err != nil {
errl.Printf("should not happen, port error %v\n", port)
hasErr = true
return nil, err
}
hostLen := len(host)
bufLen := 5 + hostLen + 2 // last 2 is port
reqBuf := make([]byte, bufLen)
reqBuf[0] = 5 // version 5
reqBuf[1] = 1 // cmd: connect
// reqBuf[2] = 0 // rsv: set to 0 when initializing
reqBuf[3] = 3 // atyp: domain name
reqBuf[4] = byte(hostLen)
copy(reqBuf[5:], host)
binary.BigEndian.PutUint16(reqBuf[5+hostLen:5+hostLen+2], uint16(port))
if n, err = c.Write(reqBuf); err != nil || n != bufLen {
errl.Printf("send socks request err %v n %d\n", err, n)
hasErr = true
return nil, err
}
// I'm not clear why the buffer is fixed at 10. The rfc document does not say this.
// Polipo set this to 10 and I also observed the reply is always 10.
replyBuf := make([]byte, 10)
if n, err = c.Read(replyBuf); err != nil {
// Seems that socks server will close connection if it can't find host
if err != io.EOF {
errl.Printf("read socks reply err %v n %d\n", err, n)
}
hasErr = true
return nil, errors.New("connection failed (by socks server " + sp.server + "). No such host?")
}
// debug.Printf("Socks reply length %d\n", n)
if replyBuf[0] != 5 {
errl.Printf("socks reply connect %s VER %d not supported\n", url.HostPort, replyBuf[0])
hasErr = true
return nil, socksProtocolErr
}
if replyBuf[1] != 0 {
errl.Printf("socks reply connect %s error %s\n", url.HostPort, socksError[replyBuf[1]])
hasErr = true
return nil, socksProtocolErr
}
if replyBuf[3] != 1 {
errl.Printf("socks reply connect %s ATYP %d\n", url.HostPort, replyBuf[3])
hasErr = true
return nil, socksProtocolErr
}
debug.Println("connected to:", url.HostPort, "via socks server:", sp.server)
// Now the socket can be used to pass data.
return socksConn{c, sp}, nil
}