forked from cyfdecyf/cow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
1228 lines (1109 loc) · 33.1 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 main
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"time"
"os"
"syscall"
"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 = 5 * 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 = 5 * time.Second
const fullKeepAliveHeader = "Keep-Alive: timeout=5\r\n"
// Some code are learnt from the http package
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
direct 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)
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
proto string
}
func newHttpProxy(addr, addrInPAC string, proto string) *httpProxy {
_, port, err := net.SplitHostPort(addr)
if err != nil {
panic("proxy addr" + err.Error())
}
return &httpProxy{addr, port, addrInPAC, proto}
}
func (proxy *httpProxy) genConfig() string {
if proxy.addrInPAC != "" {
return fmt.Sprintf("listen = %s://%s %s", proxy.proto, proxy.addr, proxy.addrInPAC)
} else {
return fmt.Sprintf("listen = %s://%s", proxy.proto, proxy.addr)
}
}
func (proxy *httpProxy) Addr() string {
return proxy.addr
}
func (hp *httpProxy) Serve(wg *sync.WaitGroup) {
var err error
var ln net.Listener
defer func() {
wg.Done()
}()
if hp.proto == "https" {
cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
if err != nil {
fmt.Println("cert error:", err.Error())
return
}
config := tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: false,
MinVersion: tls.VersionTLS11,
PreferServerCipherSuites: true,
}
ln, err = tls.Listen("tcp", hp.addr, &config)
} else {
ln, err = net.Listen("tcp", hp.addr)
}
if err != nil {
fmt.Println("listen", hp.proto, "failed:", err)
return
}
host, _, _ := net.SplitHostPort(hp.addr)
var pacURL string
if host == "" || host == "0.0.0.0" {
pacURL = fmt.Sprintf("%s://<hostip>:%s/pac", hp.proto, hp.port)
} else if hp.addrInPAC == "" {
pacURL = fmt.Sprintf("%s://%s/pac", hp.proto, hp.addr)
} else {
pacURL = fmt.Sprintf("%s://%s/pac", hp.proto, hp.addrInPAC)
}
info.Printf("listen %s %s, PAC url %s\n", hp.proto, hp.addr, pacURL)
for {
conn, err := ln.Accept()
if err != nil {
errl.Printf("%s proxy(%s) accept %v\n", hp.proto, ln.Addr(), err)
if isErrTooManyOpenFd(err) {
connPool.CloseAll()
}
time.Sleep(time.Millisecond)
continue
}
c := newClientConn(conn, hp)
go c.serve()
}
}
type meowProxy struct {
addr string
method string
passwd string
cipher *ss.Cipher
}
func newMeowProxy(method, passwd, addr string) *meowProxy {
cipher, err := ss.NewCipher(method, passwd)
if err != nil {
Fatal("can't initialize meow proxy server", err)
}
return &meowProxy{addr, method, passwd, cipher}
}
func (cp *meowProxy) genConfig() string {
method := cp.method
if method == "" {
method = "table"
}
return fmt.Sprintf("listen = meow://%s:%s@%s", method, cp.passwd, cp.addr)
}
func (cp *meowProxy) Addr() string {
return cp.addr
}
func (cp *meowProxy) Serve(wg *sync.WaitGroup) {
defer func() {
wg.Done()
}()
ln, err := net.Listen("tcp", cp.addr)
if err != nil {
fmt.Println("listen meow failed:", err)
return
}
info.Printf("meow proxy address %s\n", cp.addr)
for {
conn, err := ln.Accept()
if err != nil {
errl.Printf("meow proxy(%s) accept %v\n", ln.Addr(), err)
if isErrTooManyOpenFd(err) {
connPool.CloseAll()
}
time.Sleep(time.Millisecond)
continue
}
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 meow 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)
}
}
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)
}
}
// 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
selfListenAddr["127.0.0.1"] = 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 meow server's DNS name, we can't
// decide if the request is for meow 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 meow proxy."))
errl.Printf("cli(%s) page not found, serving request to meow %s\n%s",
c.RemoteAddr(), r, r.Verbose())
return errPageSent
}
func dbgPrintRq(c *clientConn, r *Request, direct bool) {
if r.Trailer {
errl.Printf("cli(%s) request %s has Trailer header\n%s",
c.RemoteAddr(), r, r.Verbose())
}
if dbgRq {
var connType string
if direct {
connType = "DIRECT"
} else {
connType = "PROXY"
}
if verbose {
dbgRq.Printf("%s %s %s\n%s\n", connType, c.RemoteAddr(), r, r.Verbose())
} else {
dbgRq.Printf("%s %s %s\n", connType, 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 meow proxy server, authentication is done by matching password.
if _, ok := c.proxy.(*meowProxy); 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
}
// PAC may leak frequently visited sites information. But if meow
// 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.ExpectContinue {
sendErrorPage(c, statusExpectFailed, "Expect header not supported",
"Please contact meow'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
}
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)
// 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 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.
_, isMeowConn := sv.Conn.(meowConn)
if rp.ConnectionKeepAlive || isMeowConn {
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) 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 err
}
if isErrTimeout(err) || isErrConnReset(err) || isHttpErrCode(err) {
return 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 {
return 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("%s %s\n%s", r, rp, rp.Verbose())
} else {
dbgRep.Printf("%s %s\n", 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) {
domainType := domainList.judge(r.URL)
// For CONNECT method, always create new connection.
direct := (domainType == domainTypeDirect)
if domainType == domainTypeReject {
dbgRq.Printf("%s REJECT\n", r.URL)
return nil, errors.New("Reject")
}
if r.isConnect {
return c.createServerConn(r, direct)
}
sv := connPool.Get(r.URL.HostPort, direct)
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, direct)
}
func connectDirect2(url *URL, recursive bool) (net.Conn, error) {
var c net.Conn
var err error
c, err = net.Dial("tcp", url.HostPort)
if err != nil {
debug.Printf("error direct connect to: %s %v\n", url.HostPort, err)
if isErrTooManyOpenFd(err) && !recursive {
return connectDirect2(url, true)
}
return nil, err
}
// debug.Println("directly connected to", url.HostPort)
return directConn{c}, nil
}
func connectDirect(url *URL) (net.Conn, error) {
return connectDirect2(url, 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 isErrTooManyOpenFd(err error) bool {
if ne, ok := err.(*net.OpError); ok {
if se, seok := ne.Err.(*os.SyscallError); seok && (se.Err == syscall.EMFILE || se.Err == syscall.ENFILE) {
errl.Println("too many open fd")
return true
}
}
return false
}
// MEOW !!!
// Connect to requested server according to whether it's visit count.
// If direct connection fails, try parent proxies.
func (c *clientConn) connect(r *Request, direct bool) (srvconn net.Conn, err error) {
var errMsg string
if direct {
dbgPrintRq(c, r, true)
if srvconn, err = connectDirect(r.URL); err == nil {
return
}
errMsg = genErrMsg(r, nil, "Direct connection failed.")
goto fail
}
if parentProxy.empty() {
errMsg = genErrMsg(r, nil, "No parent proxy.")
goto fail
}
// “我向来是不惮以最坏的恶意来揣测中国人的”
dbgPrintRq(c, r, false)
if srvconn, err = parentProxy.connect(r.URL); err == nil {
return
}
errMsg = genErrMsg(r, nil, "Parent proxy connection failed.")
fail:
sendErrorPage(c, "504 Connection failed", err.Error(), errMsg)
return nil, errPageSent
}
func (c *clientConn) createServerConn(r *Request, direct bool) (*serverConn, error) {
srvconn, err := c.connect(r, direct)
if err != nil {
return nil, err
}
sv := newServerConn(srvconn, r.URL.HostPort, direct)
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, direct bool) *serverConn {
sv := &serverConn{
Conn: c,
hostPort: hostPort,
direct: direct,
}
return sv
}
func (sv *serverConn) isDirect() bool {
_, ok := sv.Conn.(directConn)
return ok
}
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) mayBeClosed() bool {
if _, ok := sv.Conn.(meowConn); ok {
debug.Println("meow 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
for {
// debug.Println("srv->cli")
var n int
if n, err = sv.Read(buf); err != nil {
// Expected error besides EOF: "use of closed network connection",
// this is to make blocking read return.
// debug.Printf("copyServer2Client read data: %v\n", err)
return
}
total += n
if _, err = c.Write(buf[0:n]); err != nil {
// debug.Printf("copyServer2Client write data: %v\n", err)
return
}
// debug.Printf("srv(%s)->cli(%s) sent %d bytes data\n", r.URL.HostPort, c.RemoteAddr(), total)
// set state to rsRecvBody to indicate the request has partial response sent to client
r.state = rsRecvBody
sv.state = svSendRecvResponse
}
}
type serverWriter struct {
rq *Request
sv *serverConn
}
func newServerWriter(r *Request, sv *serverConn) *serverWriter {
return &serverWriter{r, sv}
}
// Write to server, store written data in request buffer if necessary.
// We have to save request body in order to retry request.
// FIXME: too tighly coupled with Request.
func (sw *serverWriter) Write(p []byte) (int, error) {
if sw.rq.raw == nil {
// buffer released
} else if sw.rq.raw.Len() >= 2*httpBufSize {
// Avoid using too much memory to hold request body. If a request is
// not buffered completely, meow can't retry and can release memory
// immediately.
debug.Println(sw.rq, "request body too large, not buffering any more")
sw.rq.releaseBuf()
sw.rq.partial = true
} else if sw.rq.responseNotSent() {
sw.rq.raw.Write(p)
} else { // has sent response, happens when saving data for CONNECT method
sw.rq.releaseBuf()
}
return sw.sv.Write(p)
}
func copyClient2Server(c *clientConn, sv *serverConn, r *Request, srvStopped notification, done chan struct{}) (err error) {
var n int
w := newServerWriter(r, sv)
if c.bufRd != nil {
n = c.bufRd.Buffered()
if n > 0 {
buffered, _ := c.bufRd.Peek(n) // should not return error
if _, err = w.Write(buffered); err != nil {
// debug.Printf("cli->srv write buffered err: %v\n", err)
return
}
}
if debug {
debug.Printf("cli(%s)->srv(%s) released read buffer\n",
c.RemoteAddr(), r.URL.HostPort)
}
c.releaseBuf()
}
buf := connectBuf.Get()
defer func() {
connectBuf.Put(buf)
}()
for {
// debug.Println("908: cli->srv")
if n, err = c.Read(buf); err != nil {
if isErrTimeout(err) && !srvStopped.hasNotified() {
debug.Printf("911: cli(%s)->srv(%s) timeout\n", c.RemoteAddr(), r.URL.HostPort)
continue
}
debug.Printf("914: cli->srv read err: %v\n", err)
return
}
// copyServer2Client will detect write to closed server. Just store client content for retry.
if _, err = w.Write(buf[:n]); err != nil {
// XXX is it enough to only do block detection in copyServer2Client?
debug.Printf("921: cli->srv write err: %v\n", err)
return
}
// debug.Printf("924: cli(%s)->srv(%s) sent %d bytes data\n", c.RemoteAddr(), r.URL.HostPort, n)
}
}
var connEstablished = []byte("HTTP/1.1 200 Tunnel established\r\n\r\n")
// Do HTTP CONNECT
func (sv *serverConn) doConnect(r *Request, c *clientConn) (err error) {
r.state = rsCreated
_, isHttpConn := sv.Conn.(httpConn)
_, isHttpsConn := sv.Conn.(httpsConn)
_, isMeowConn := sv.Conn.(meowConn)
if isHttpConn || isHttpsConn || isMeowConn {
if debug {
debug.Printf("cli(%s) send CONNECT request to parent\n", c.RemoteAddr())
}
if err = sv.sendHTTPProxyRequestHeader(r, c); err != nil {
debug.Printf("cli(%s) error send CONNECT request to parent: %v\n",
c.RemoteAddr(), err)
return err
}
} else {
// debug.Printf("send connection confirmation to %s->%s\n", c.RemoteAddr(), r.URL.HostPort)
if _, err = c.Write(connEstablished); err != nil {
debug.Printf("cli(%s) error send 200 Connecion established: %v\n",
c.RemoteAddr(), err)
return err
}
}
var cli2srvErr error
done := make(chan struct{})
srvStopped := newNotification()
go func() {
debug.Printf("989: doConnect: cli(%s)->srv(%s)\n", c.RemoteAddr(), r.URL.HostPort)
cli2srvErr = copyClient2Server(c, sv, r, srvStopped, done)
// Close sv to force read from server in copyServer2Client return.
// Note: there's no other code closing the server connection for CONNECT.
sv.Close()
}()
// debug.Printf("doConnect: srv(%s)->cli(%s)\n", r.URL.HostPort, c.RemoteAddr())
err = copyServer2Client(sv, c, r)
if isErrTimeout(err) || isErrConnReset(err) || isHttpErrCode(err) {
srvStopped.notify()
<-done
} else {
// close client connection to force read from client in copyClient2Server return
c.Conn.Close()
}
if cli2srvErr != nil {
return cli2srvErr
}
return
}
func (sv *serverConn) sendHTTPProxyRequestHeader(r *Request, c *clientConn) (err error) {
if _, err = sv.Write(r.proxyRequestLine()); err != nil {
return c.handleServerWriteError(r, sv, err,
"send proxy request line to http parent")
}
if hc, ok := sv.Conn.(httpConn); ok && hc.parent.authHeader != nil {
// Add authorization header for parent http proxy