forked from cyfdecyf/cow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
1444 lines (1316 loc) · 39.8 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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cow
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"time"
"github.com/cyfdecyf/bufio"
"github.com/cyfdecyf/leakybuf"
ss "github.com/shadowsocks/shadowsocks-go/shadowsocks"
)
// As I'm using ReadSlice to read line, it's possible to get
// bufio.ErrBufferFull while reading line, so set it to a large value to
// prevent such problems.
//
// For limits about URL and HTTP header size, refer to:
// http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url
// "de facto limit of 2000 characters"
// http://www.mnot.net/blog/2011/07/11/what_proxies_must_do
// "URIs should be allowed at least 8000 octets, and HTTP headers should have
// 4000 as an absolute minimum".
// In practice, there are sites using cookies larger than 4096 bytes,
// e.g. www.fitbit.com. So set http buffer size to 8192 to be safe.
const httpBufSize = 8192
// Hold at most 4MB memory as buffer for parsing http request/response and
// holding post data.
var httpBuf = leakybuf.NewLeakyBuf(512, httpBufSize)
// If no keep-alive header in response, use this as the keep-alive value.
const defaultServerConnTimeout = 15 * time.Second
// Close client connection if no new requests received in some time.
// (On OS X, the default soft limit of open file descriptor is 256, which is
// very conservative and easy to cause problem if we are not careful to limit
// open fds.)
const clientConnTimeout = 15 * time.Second
const fullKeepAliveHeader = "Keep-Alive: timeout=15\r\n"
// If client closed connection for HTTP CONNECT method in less then 1 second,
// consider it as an ssl error. This is only effective for Chrome which will
// drop connection immediately upon SSL error.
const sslLeastDuration = time.Second
// Some code are learnt from the http package
// encapulate actual error for an retry error
type RetryError struct {
error
}
func isErrRetry(err error) bool {
if err == nil {
return false
}
_, ok := err.(RetryError)
return ok
}
var zeroTime time.Time
type directConn struct {
net.Conn
}
func (dc directConn) String() string {
return "direct connection"
}
type serverConnState byte
const (
svConnected serverConnState = iota
svSendRecvResponse
svStopped
)
type serverConn struct {
net.Conn
bufRd *bufio.Reader
buf []byte // buffer for the buffered reader
hostPort string
state serverConnState
willCloseOn time.Time
siteInfo *VisitCnt
visited bool
}
type clientConn struct {
net.Conn // connection to the proxy client
bufRd *bufio.Reader
buf []byte // buffer for the buffered reader
proxy Proxy
}
var (
errPageSent = errors.New("error page has sent")
errClientTimeout = errors.New("read client request timeout")
errAuthRequired = errors.New("authentication requried")
)
type Proxy interface {
Serve(*sync.WaitGroup, <-chan struct{})
Addr() string
genConfig() string // for upgrading config
}
var listenProxy []Proxy
func addListenProxy(p Proxy) {
listenProxy = append(listenProxy, p)
}
type httpProxy struct {
addr string // listen address, contains port
port string // for use when generating PAC
addrInPAC string // proxy server address to use in PAC
}
func newHttpProxy(addr, addrInPAC string) *httpProxy {
_, port, err := net.SplitHostPort(addr)
if err != nil {
panic("proxy addr" + err.Error())
}
return &httpProxy{addr, port, addrInPAC}
}
func (proxy *httpProxy) genConfig() string {
if proxy.addrInPAC != "" {
return fmt.Sprintf("listen = http://%s %s", proxy.addr, proxy.addrInPAC)
} else {
return fmt.Sprintf("listen = http://%s", proxy.addr)
}
}
func (proxy *httpProxy) Addr() string {
return proxy.addr
}
func (hp *httpProxy) Serve(wg *sync.WaitGroup, quit <-chan struct{}) {
defer func() {
wg.Done()
}()
ln, err := net.Listen("tcp", hp.addr)
if err != nil {
fmt.Println("listen http failed:", err)
return
}
var exit bool
go func() {
<-quit
exit = true
ln.Close()
}()
host, _, _ := net.SplitHostPort(hp.addr)
var pacURL string
if host == "" || host == "0.0.0.0" {
pacURL = fmt.Sprintf("http://<hostip>:%s/pac", hp.port)
} else if hp.addrInPAC == "" {
pacURL = fmt.Sprintf("http://%s/pac", hp.addr)
} else {
pacURL = fmt.Sprintf("http://%s/pac", hp.addrInPAC)
}
info.Printf("COW %s listen http %s, PAC url %s\n", version, hp.addr, pacURL)
for {
conn, err := ln.Accept()
if err != nil && !exit {
errl.Printf("http proxy(%s) accept %v\n", ln.Addr(), err)
if isErrTooManyOpenFd(err) {
connPool.CloseAll()
}
time.Sleep(time.Millisecond)
continue
}
if exit {
debug.Println("exiting the http listner")
break
}
c := newClientConn(conn, hp)
go c.serve()
}
}
type cowProxy struct {
addr string
method string
passwd string
cipher *ss.Cipher
}
func newCowProxy(method, passwd, addr string) *cowProxy {
cipher, err := ss.NewCipher(method, passwd)
if err != nil {
Fatal("can't initialize cow proxy server", err)
}
return &cowProxy{addr, method, passwd, cipher}
}
func (cp *cowProxy) genConfig() string {
method := cp.method
if method == "" {
method = "table"
}
return fmt.Sprintf("listen = cow://%s:%s@%s", method, cp.passwd, cp.addr)
}
func (cp *cowProxy) Addr() string {
return cp.addr
}
func (cp *cowProxy) Serve(wg *sync.WaitGroup, quit <-chan struct{}) {
defer func() {
wg.Done()
}()
ln, err := net.Listen("tcp", cp.addr)
if err != nil {
fmt.Println("listen cow failed:", err)
return
}
info.Printf("COW %s cow proxy address %s\n", version, cp.addr)
var exit bool
go func() {
<-quit
exit = true
ln.Close()
}()
for {
conn, err := ln.Accept()
if err != nil && !exit {
errl.Printf("cow proxy(%s) accept %v\n", ln.Addr(), err)
if isErrTooManyOpenFd(err) {
connPool.CloseAll()
}
time.Sleep(time.Millisecond)
continue
}
if exit {
debug.Println("exiting cow listner")
break
}
ssConn := ss.NewConn(conn, cp.cipher.Copy())
c := newClientConn(ssConn, cp)
go c.serve()
}
}
func newClientConn(cli net.Conn, proxy Proxy) *clientConn {
buf := httpBuf.Get()
c := &clientConn{
Conn: cli,
buf: buf,
bufRd: bufio.NewReaderFromBuf(cli, buf),
proxy: proxy,
}
if debug {
debug.Printf("cli(%s) connected, total %d clients\n",
cli.RemoteAddr(), incCliCnt())
}
return c
}
func (c *clientConn) releaseBuf() {
if c.bufRd != nil {
// debug.Println("release client buffer")
httpBuf.Put(c.buf)
c.buf = nil
c.bufRd = nil
}
}
func (c *clientConn) Close() {
c.releaseBuf()
if debug {
debug.Printf("cli(%s) closed, total %d clients\n",
c.RemoteAddr(), decCliCnt())
}
c.Conn.Close()
}
func (c *clientConn) setReadTimeout(msg string) {
// Always keep connections alive for cow conn from client for more reuse.
// For other client connections, set read timeout so we can close the
// connection after a period of idle to reduce number of open connections.
if _, ok := c.Conn.(*ss.Conn); !ok {
// make actual timeout a little longer than keep-alive value sent to client
setConnReadTimeout(c.Conn, clientConnTimeout+2*time.Second, msg)
}
}
func (c *clientConn) unsetReadTimeout(msg string) {
if _, ok := c.Conn.(*ss.Conn); !ok {
unsetConnReadTimeout(c.Conn, msg)
}
}
// Listen address as key, not including port part.
var selfListenAddr map[string]bool
// Called in main, so no need to protect concurrent initialization.
func initSelfListenAddr() {
selfListenAddr = make(map[string]bool)
// Add empty host to self listen addr, in case there's no Host header.
selfListenAddr[""] = true
for _, proxy := range listenProxy {
addr := proxy.Addr()
// Handle wildcard address.
if addr[0] == ':' || strings.HasPrefix(addr, "0.0.0.0") {
for _, ad := range hostAddr() {
selfListenAddr[ad] = true
}
selfListenAddr["localhost"] = true
continue
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
panic("listen addr invalid: " + addr)
}
selfListenAddr[host] = true
if host == "127.0.0.1" {
selfListenAddr["localhost"] = true
} else if host == "localhost" {
selfListenAddr["127.0.0.1"] = true
}
}
}
func isSelfRequest(r *Request) bool {
if r.URL.HostPort != "" {
return false
}
// Maxthon sometimes sends requests without host in request line,
// in that case, get host information from Host header.
// But if client PAC setting is using cow server's DNS name, we can't
// decide if the request is for cow itself (need reverse lookup).
// So if request path seems like getting PAC, simply return true.
if r.URL.Path == "/pac" || strings.HasPrefix(r.URL.Path, "/pac?") {
return true
}
r.URL.ParseHostPort(r.Header.Host)
if selfListenAddr[r.URL.Host] {
return true
}
debug.Printf("fixed request with no host in request line %s\n", r)
return false
}
func (c *clientConn) serveSelfURL(r *Request) (err error) {
if _, ok := c.proxy.(*httpProxy); !ok {
goto end
}
if r.Method != "GET" {
goto end
}
if r.URL.Path == "/pac" || strings.HasPrefix(r.URL.Path, "/pac?") {
sendPAC(c)
// PAC header contains connection close, send non nil error to close
// client connection.
return errPageSent
}
end:
sendErrorPage(c, "404 not found", "Page not found",
genErrMsg(r, nil, "Serving request to COW proxy."))
errl.Printf("cli(%s) page not found, serving request to cow %s\n%s",
c.RemoteAddr(), r, r.Verbose())
return errPageSent
}
func (c *clientConn) shouldRetry(r *Request, sv *serverConn, re error) bool {
if !isErrRetry(re) {
return false
}
err, _ := re.(RetryError)
if !r.responseNotSent() {
if debug {
debug.Printf("cli(%s) has sent some response, can't retry %v\n", c.RemoteAddr(), r)
}
return false
}
if r.partial {
if debug {
debug.Printf("cli(%s) partial request, can't retry %v\n", c.RemoteAddr(), r)
}
sendErrorPage(c, "502 partial request", err.Error(),
genErrMsg(r, sv, "Request is too large to hold in buffer, can't retry. "+
"Refresh to retry may work."))
return false
} else if r.raw == nil {
msg := "Please report issue to the developer: Non partial request with buffer released"
errl.Println(msg, r)
panic(msg)
}
if r.tooManyRetry() {
if sv.maybeFake() {
// Sometimes GFW reset will got EOF error leading to retry too many times.
// In that case, consider the url as temp blocked and try parent proxy.
siteStat.TempBlocked(r.URL)
r.tryCnt = 0
return true
}
debug.Printf("cli(%s) can't retry %v tryCnt=%d\n", c.RemoteAddr(), r, r.tryCnt)
sendErrorPage(c, "502 retry failed", "Can't finish HTTP request",
genErrMsg(r, sv, "Has tried several times."))
return false
}
return true
}
func dbgPrintRq(c *clientConn, r *Request) {
if r.Trailer {
errl.Printf("cli(%s) request %s has Trailer header\n%s",
c.RemoteAddr(), r, r.Verbose())
}
if dbgRq {
if verbose {
dbgRq.Printf("cli(%s) request %s\n%s", c.RemoteAddr(), r, r.Verbose())
} else {
dbgRq.Printf("cli(%s) request %s\n", c.RemoteAddr(), r)
}
}
}
type SinkWriter struct{}
func (s SinkWriter) Write(p []byte) (int, error) {
return len(p), nil
}
func (c *clientConn) serve() {
var r Request
var rp Response
var sv *serverConn
var err error
var authed bool
// For cow proxy server, authentication is done by matching password.
if _, ok := c.proxy.(*cowProxy); ok {
authed = true
}
defer func() {
r.releaseBuf()
c.Close()
}()
// Refer to implementation.md for the design choices on parsing the request
// and response.
for {
if c.bufRd == nil || c.buf == nil {
panic("client read buffer nil")
}
if err = parseRequest(c, &r); err != nil {
debug.Printf("cli(%s) parse request %v\n", c.RemoteAddr(), err)
if err == io.EOF || isErrConnReset(err) {
return
}
if err != errClientTimeout {
sendErrorPage(c, "404 Bad request", "Bad request", err.Error())
return
}
sendErrorPage(c, statusRequestTimeout, statusRequestTimeout,
"Your browser didn't send a complete request in time.")
return
}
dbgPrintRq(c, &r)
// PAC may leak frequently visited sites information. But if cow
// requires authentication for PAC, some clients may not be able
// handle it. (e.g. Proxy SwitchySharp extension on Chrome.)
if isSelfRequest(&r) {
if err = c.serveSelfURL(&r); err != nil {
return
}
continue
}
if auth.required && !authed {
if err = Authenticate(c, &r); err != nil {
errl.Printf("cli(%s) %v\n", c.RemoteAddr(), err)
// Request may have body. To make things simple, close
// connection so we don't need to skip request body before
// reading the next request.
return
}
authed = true
}
if r.isConnect && !config.TunnelAllowedPort[r.URL.Port] {
sendErrorPage(c, statusForbidden, "Forbidden tunnel port",
genErrMsg(&r, nil, "Please contact proxy admin."))
return
}
if r.ExpectContinue {
sendErrorPage(c, statusExpectFailed, "Expect header not supported",
"Please contact COW's developer if you see this.")
// Client may have sent request body at this point. Simply close
// connection so we don't need to handle this case.
// NOTE: sendErrorPage tells client the connection will keep alive, but
// actually it will close here.
return
}
retry:
r.tryOnce()
if bool(debug) && r.isRetry() {
debug.Printf("cli(%s) retry request tryCnt=%d %v\n", c.RemoteAddr(), r.tryCnt, &r)
}
if sv, err = c.getServerConn(&r); err != nil {
if debug {
debug.Printf("cli(%s) failed to get server conn %v\n", c.RemoteAddr(), &r)
}
// Failed connection will send error page back to the client.
// For CONNECT, the client read buffer is released in copyClient2Server,
// so can't go back to getRequest.
if err == errPageSent && !r.isConnect {
if r.hasBody() {
// skip request body
debug.Printf("cli(%s) skip request body %v\n", c.RemoteAddr(), &r)
sendBody(SinkWriter{}, c.bufRd, int(r.ContLen), r.Chunking)
}
continue
}
return
}
if r.isConnect {
// server connection will be closed in doConnect
err = sv.doConnect(&r, c)
if c.shouldRetry(&r, sv, err) {
goto retry
}
// debug.Printf("doConnect %s to %s done\n", c.RemoteAddr(), r.URL.HostPort)
return
}
if err = sv.doRequest(c, &r, &rp); err != nil {
// For client I/O error, we can actually put server connection to
// pool. But let's make thing simple for now.
sv.Close()
if c.shouldRetry(&r, sv, err) {
goto retry
} else if err == errPageSent && (!r.hasBody() || r.hasSent()) {
// Can only continue if request has no body, or request body
// has been read.
continue
}
return
}
// Put server connection to pool, so other clients can use it.
_, isCowConn := sv.Conn.(cowConn)
if rp.ConnectionKeepAlive || isCowConn {
if debug {
debug.Printf("cli(%s) connPool put %s", c.RemoteAddr(), sv.hostPort)
}
// If the server connection is not going to be used soon,
// release buffer before putting back to pool can save memory.
sv.releaseBuf()
connPool.Put(sv)
} else {
if debug {
debug.Printf("cli(%s) server %s close conn\n", c.RemoteAddr(), sv.hostPort)
}
sv.Close()
}
if !r.ConnectionKeepAlive {
if debug {
debug.Printf("cli(%s) close connection\n", c.RemoteAddr())
}
return
}
}
}
func genErrMsg(r *Request, sv *serverConn, what string) string {
if sv == nil {
return fmt.Sprintf("<p>HTTP Request <strong>%v</strong></p> <p>%s</p>", r, what)
}
return fmt.Sprintf("<p>HTTP Request <strong>%v</strong></p> <p>%s</p> <p>Using %s.</p>",
r, what, sv.Conn)
}
func (c *clientConn) handleBlockedRequest(r *Request, err error) error {
siteStat.TempBlocked(r.URL)
return RetryError{err}
}
func (c *clientConn) handleServerReadError(r *Request, sv *serverConn, err error, msg string) error {
if debug {
debug.Printf("cli(%s) server read error %s %T %v %v\n",
c.RemoteAddr(), msg, err, err, r)
}
if err == io.EOF {
return RetryError{err}
}
if sv.maybeFake() && maybeBlocked(err) {
return c.handleBlockedRequest(r, err)
}
if r.responseNotSent() {
sendErrorPage(c, "502 read error", err.Error(), genErrMsg(r, sv, msg))
return errPageSent
}
errl.Printf("cli(%s) unhandled server read error %s %v %s\n", c.RemoteAddr(), msg, err, r)
return err
}
func (c *clientConn) handleServerWriteError(r *Request, sv *serverConn, err error, msg string) error {
// This function is only called in doRequest, no response is sent to client.
// So if visiting blocked site, can always retry request.
if sv.maybeFake() && isErrConnReset(err) {
siteStat.TempBlocked(r.URL)
}
return RetryError{err}
}
func dbgPrintRep(c *clientConn, r *Request, rp *Response) {
if rp.Trailer {
errl.Printf("cli(%s) response %s has Trailer header\n%s",
c.RemoteAddr(), rp, rp.Verbose())
}
if dbgRep {
if verbose {
dbgRep.Printf("cli(%s) response %s %s\n%s",
c.RemoteAddr(), r, rp, rp.Verbose())
} else {
dbgRep.Printf("cli(%s) response %s %s\n",
c.RemoteAddr(), r, rp)
}
}
}
func (c *clientConn) readResponse(sv *serverConn, r *Request, rp *Response) (err error) {
sv.initBuf()
defer func() {
rp.releaseBuf()
}()
/*
if r.partial {
return RetryError{errors.New("debug retry for partial request")}
}
*/
/*
// force retry for debugging
if r.tryCnt == 1 {
return RetryError{errors.New("debug retry in readResponse")}
}
*/
if err = parseResponse(sv, r, rp); err != nil {
return c.handleServerReadError(r, sv, err, "parse response")
}
dbgPrintRep(c, r, rp)
// After have received the first reponses from the server, we consider
// ther server as real instead of fake one caused by wrong DNS reply. So
// don't time out later.
sv.state = svSendRecvResponse
r.state = rsRecvBody
r.releaseBuf()
if _, err = c.Write(rp.rawResponse()); err != nil {
return err
}
rp.releaseBuf()
if rp.hasBody(r.Method) {
if err = sendBody(c, sv.bufRd, int(rp.ContLen), rp.Chunking); err != nil {
if debug {
debug.Printf("cli(%s) send body %v\n", c.RemoteAddr(), err)
}
// Non persistent connection will return nil upon successful response reading
if err == io.EOF {
// For persistent connection, EOF from server is error.
// Response header has been read, server using persistent
// connection indicates the end of response and proxy should
// not got EOF while reading response.
// The client connection will be closed to indicate this error.
// Proxy can't send error page here because response header has
// been sent.
return fmt.Errorf("read response body unexpected EOF %v", rp)
} else if isErrOpRead(err) {
return c.handleServerReadError(r, sv, err, "read response body")
}
// errl.Printf("cli(%s) sendBody error %T %v %v", err, err, r)
return err
}
}
r.state = rsDone
/*
if debug {
debug.Printf("[Finished] %v request %s %s\n", c.RemoteAddr(), r.Method, r.URL)
}
*/
if rp.ConnectionKeepAlive {
if rp.KeepAlive == time.Duration(0) {
sv.willCloseOn = time.Now().Add(defaultServerConnTimeout)
} else {
// debug.Printf("cli(%s) server %s keep-alive %v\n", c.RemoteAddr(), sv.hostPort, rp.KeepAlive)
sv.willCloseOn = time.Now().Add(rp.KeepAlive)
}
}
return
}
func (c *clientConn) getServerConn(r *Request) (*serverConn, error) {
siteInfo := siteStat.GetVisitCnt(r.URL)
// For CONNECT method, always create new connection.
if r.isConnect {
return c.createServerConn(r, siteInfo)
}
sv := connPool.Get(r.URL.HostPort, siteInfo.AsDirect())
if sv != nil {
// For websites like feedly, the site itself is not blocked, but the
// content it loads may result reset. So we should reset server
// connection state to just connected.
sv.state = svConnected
if debug {
debug.Printf("cli(%s) connPool get %s\n", c.RemoteAddr(), r.URL.HostPort)
}
return sv, nil
}
if debug {
debug.Printf("cli(%s) connPool no conn %s", c.RemoteAddr(), r.URL.HostPort)
}
return c.createServerConn(r, siteInfo)
}
func connectDirect2(url *URL, siteInfo *VisitCnt, recursive bool) (net.Conn, error) {
var c net.Conn
var err error
if siteInfo.AlwaysDirect() {
c, err = net.Dial("tcp", url.HostPort)
} else {
to := dialTimeout
if siteInfo.OnceBlocked() && to >= defaultDialTimeout {
// If once blocked, decrease timeout to switch to parent proxy faster.
to = minDialTimeout
} else if siteInfo.AsDirect() {
// If usually can be accessed directly, increase timeout to avoid
// problems when network condition is bad.
to = maxTimeout
}
c, err = net.DialTimeout("tcp", url.HostPort, to)
}
if err != nil {
debug.Printf("error direct connect to: %s %v\n", url.HostPort, err)
if isErrTooManyOpenFd(err) && !recursive {
return connectDirect2(url, siteInfo, true)
}
return nil, err
}
// debug.Println("directly connected to", url.HostPort)
return directConn{c}, nil
}
func connectDirect(url *URL, siteInfo *VisitCnt) (net.Conn, error) {
return connectDirect2(url, siteInfo, false)
}
func isErrTimeout(err error) bool {
if ne, ok := err.(net.Error); ok {
return ne.Timeout()
}
return false
}
func isHttpErrCode(err error) bool {
if config.HttpErrorCode <= 0 {
return false
}
if err == CustomHttpErr {
return true
}
return false
}
func maybeBlocked(err error) bool {
if parentProxy.empty() {
return false
}
return isErrTimeout(err) || isErrConnReset(err) || isHttpErrCode(err)
}
// Connect to requested server according to whether it's visit count.
// If direct connection fails, try parent proxies.
func (c *clientConn) connect(r *Request, siteInfo *VisitCnt) (srvconn net.Conn, err error) {
var errMsg string
if config.AlwaysProxy {
if srvconn, err = parentProxy.connect(r.URL); err == nil {
return
}
errMsg = genErrMsg(r, nil, "Parent proxy connection failed, always use parent proxy.")
goto fail
}
if siteInfo.AsBlocked() && !parentProxy.empty() {
// In case of connection error to socks server, fallback to direct connection
if srvconn, err = parentProxy.connect(r.URL); err == nil {
return
}
if siteInfo.AlwaysBlocked() {
errMsg = genErrMsg(r, nil, "Parent proxy connection failed, always blocked site.")
goto fail
}
if siteInfo.AsTempBlocked() {
errMsg = genErrMsg(r, nil, "Parent proxy connection failed, temporarily blocked site.")
goto fail
}
if srvconn, err = connectDirect(r.URL, siteInfo); err == nil {
return
}
errMsg = genErrMsg(r, nil, "Parent proxy and direct connection failed, maybe blocked site.")
} else {
// In case of error on direction connection, try parent server
if srvconn, err = connectDirect(r.URL, siteInfo); err == nil {
return
}
if parentProxy.empty() {
errMsg = genErrMsg(r, nil, "Direct connection failed, no parent proxy.")
goto fail
}
if siteInfo.AlwaysDirect() {
errMsg = genErrMsg(r, nil, "Direct connection failed, always direct site.")
goto fail
}
// net.Dial does two things: DNS lookup and TCP connection.
// GFW may cause failure here: make it time out or reset connection.
// debug.Printf("type of err %T %v\n", err, err)
// RST during TCP handshake is valid and would return as connection
// refused error. My observation is that GFW does not use RST to stop
// TCP handshake.
// To simplify things and avoid error in my observation, always try
// parent proxy in case of Dial error.
var socksErr error
if srvconn, socksErr = parentProxy.connect(r.URL); socksErr == nil {
c.handleBlockedRequest(r, err)
if debug {
debug.Printf("cli(%s) direct connection failed, use parent proxy for %v\n",
c.RemoteAddr(), r)
}
return srvconn, nil
}
errMsg = genErrMsg(r, nil,
"Direct and parent proxy connection failed, maybe blocked site.")
}
fail:
sendErrorPage(c, "504 Connection failed", err.Error(), errMsg)
return nil, errPageSent
}
func (c *clientConn) createServerConn(r *Request, siteInfo *VisitCnt) (*serverConn, error) {
srvconn, err := c.connect(r, siteInfo)
if err != nil {
return nil, err
}
sv := newServerConn(srvconn, r.URL.HostPort, siteInfo)
if debug {
debug.Printf("cli(%s) connected to %s %d concurrent connections\n",
c.RemoteAddr(), sv.hostPort, incSrvConnCnt(sv.hostPort))
}
return sv, nil
}
// Should call initBuf before reading http response from server. This allows
// us not init buf for connect method which does not need to parse http
// respnose.
func newServerConn(c net.Conn, hostPort string, siteInfo *VisitCnt) *serverConn {
sv := &serverConn{
Conn: c,
hostPort: hostPort,
siteInfo: siteInfo,
}
return sv
}
func (sv *serverConn) isDirect() bool {
_, ok := sv.Conn.(directConn)
return ok
}
func (sv *serverConn) updateVisit() {
if sv.visited {
return
}
sv.visited = true
if sv.isDirect() {
sv.siteInfo.DirectVisit()
} else {
sv.siteInfo.BlockedVisit()
}
}
func (sv *serverConn) initBuf() {
if sv.bufRd == nil {
sv.buf = httpBuf.Get()
sv.bufRd = bufio.NewReaderFromBuf(sv, sv.buf)
}
}
func (sv *serverConn) releaseBuf() {
if sv.bufRd != nil {
// debug.Println("release server buffer")
httpBuf.Put(sv.buf)
sv.buf = nil
sv.bufRd = nil
}
}
func (sv *serverConn) Close() error {
sv.releaseBuf()
if debug {
debug.Printf("close connection to %s remains %d concurrent connections\n",
sv.hostPort, decSrvConnCnt(sv.hostPort))
}
return sv.Conn.Close()
}
func (sv *serverConn) maybeFake() bool {
return sv.state == svConnected && sv.isDirect() && !sv.siteInfo.AlwaysDirect()
}
func setConnReadTimeout(cn net.Conn, d time.Duration, msg string) {
if err := cn.SetReadDeadline(time.Now().Add(d)); err != nil {
errl.Println("set readtimeout:", msg, err)
}
}
func unsetConnReadTimeout(cn net.Conn, msg string) {
if err := cn.SetReadDeadline(zeroTime); err != nil {
// It's possible that conn has been closed, so use debug log.
debug.Println("unset readtimeout:", msg, err)
}
}
func (sv *serverConn) setReadTimeout(msg string) {
to := readTimeout
if sv.siteInfo.OnceBlocked() && to > defaultReadTimeout {
to = minReadTimeout
} else if sv.siteInfo.AsDirect() {
to = maxTimeout
}
setConnReadTimeout(sv.Conn, to, msg)
}
func (sv *serverConn) unsetReadTimeout(msg string) {
unsetConnReadTimeout(sv.Conn, msg)
}
func (sv *serverConn) maybeSSLErr(cliStart time.Time) bool {
// If client closes connection very soon, maybe there's SSL error, maybe
// not (e.g. user stopped request).
// COW can't tell which is the case, so this detection is not reliable.
return sv.state > svConnected && time.Now().Sub(cliStart) < sslLeastDuration
}
func (sv *serverConn) mayBeClosed() bool {
if _, ok := sv.Conn.(cowConn); ok {
debug.Println("cow parent would keep alive")
return false
}
return time.Now().After(sv.willCloseOn)
}
// Use smaller buffer for connection method as the buffer will be hold for a
// very long time.
const connectBufSize = 4096
// Hold at most 2M memory for connection buffer. This can support 256
// concurrent connect method.
var connectBuf = leakybuf.NewLeakyBuf(512, connectBufSize)
func copyServer2Client(sv *serverConn, c *clientConn, r *Request) (err error) {
buf := connectBuf.Get()
defer func() {
connectBuf.Put(buf)
}()
/*
// force retry for debugging
if r.tryCnt == 1 && sv.maybeFake() {
time.Sleep(1)
return RetryError{errors.New("debug retry in copyServer2Client")}
}
*/
total := 0