1
2
3
4
5
6
7 package httputil
8
9 import (
10 "context"
11 "errors"
12 "fmt"
13 "internal/godebug"
14 "io"
15 "log"
16 "maps"
17 "mime"
18 "net"
19 "net/http"
20 "net/http/httptrace"
21 "net/http/internal/ascii"
22 "net/textproto"
23 "net/url"
24 "strings"
25 "sync"
26 "time"
27
28 "golang.org/x/net/http/httpguts"
29 )
30
31
32 type ProxyRequest struct {
33
34
35 In *http.Request
36
37
38
39
40
41 Out *http.Request
42 }
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58 func (r *ProxyRequest) SetURL(target *url.URL) {
59 rewriteRequestURL(r.Out, target)
60 r.Out.Host = ""
61 }
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82 func (r *ProxyRequest) SetXForwarded() {
83 clientIP, _, err := net.SplitHostPort(r.In.RemoteAddr)
84 if err == nil {
85 prior := r.Out.Header["X-Forwarded-For"]
86 if len(prior) > 0 {
87 clientIP = strings.Join(prior, ", ") + ", " + clientIP
88 }
89 r.Out.Header.Set("X-Forwarded-For", clientIP)
90 } else {
91 r.Out.Header.Del("X-Forwarded-For")
92 }
93 r.Out.Header.Set("X-Forwarded-Host", r.In.Host)
94 if r.In.TLS == nil {
95 r.Out.Header.Set("X-Forwarded-Proto", "http")
96 } else {
97 r.Out.Header.Set("X-Forwarded-Proto", "https")
98 }
99 }
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120 type ReverseProxy struct {
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 Rewrite func(*ProxyRequest)
154
155
156
157 Transport http.RoundTripper
158
159
160
161
162
163
164
165
166
167
168
169 FlushInterval time.Duration
170
171
172
173
174 ErrorLog *log.Logger
175
176
177
178
179 BufferPool BufferPool
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194 ModifyResponse func(*http.Response) error
195
196
197
198
199
200
201 ErrorHandler func(http.ResponseWriter, *http.Request, error)
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 Director func(*http.Request)
284 }
285
286
287
288 type BufferPool interface {
289 Get() []byte
290 Put([]byte)
291 }
292
293 func singleJoiningSlash(a, b string) string {
294 aslash := strings.HasSuffix(a, "/")
295 bslash := strings.HasPrefix(b, "/")
296 switch {
297 case aslash && bslash:
298 return a + b[1:]
299 case !aslash && !bslash:
300 return a + "/" + b
301 }
302 return a + b
303 }
304
305 func joinURLPath(a, b *url.URL) (path, rawpath string) {
306 if a.RawPath == "" && b.RawPath == "" {
307 return singleJoiningSlash(a.Path, b.Path), ""
308 }
309
310
311 apath := a.EscapedPath()
312 bpath := b.EscapedPath()
313
314 aslash := strings.HasSuffix(apath, "/")
315 bslash := strings.HasPrefix(bpath, "/")
316
317 switch {
318 case aslash && bslash:
319 return a.Path + b.Path[1:], apath + bpath[1:]
320 case !aslash && !bslash:
321 return a.Path + "/" + b.Path, apath + "/" + bpath
322 }
323 return a.Path + b.Path, apath + bpath
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 func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
351 director := func(req *http.Request) {
352 rewriteRequestURL(req, target)
353 }
354 return &ReverseProxy{Director: director}
355 }
356
357 func rewriteRequestURL(req *http.Request, target *url.URL) {
358 u := url.URL{
359 Scheme: target.Scheme,
360 User: target.User,
361 Host: target.Host,
362 OmitHost: target.OmitHost,
363 ForceQuery: req.URL.ForceQuery,
364 }
365 u.Path, u.RawPath = joinURLPath(target, req.URL)
366 if target.RawQuery == "" || req.URL.RawQuery == "" {
367 u.RawQuery = target.RawQuery + req.URL.RawQuery
368 } else {
369 u.RawQuery = target.RawQuery + "&" + req.URL.RawQuery
370 }
371 *req.URL = u
372 }
373
374 func copyHeader(dst, src http.Header) {
375 for k, vv := range src {
376 for _, v := range vv {
377 dst.Add(k, v)
378 }
379 }
380 }
381
382
383
384
385
386
387 var hopHeaders = []string{
388 "Connection",
389 "Proxy-Connection",
390 "Keep-Alive",
391 "Proxy-Authenticate",
392 "Proxy-Authorization",
393 "Te",
394 "Trailer",
395 "Transfer-Encoding",
396 "Upgrade",
397 "HTTP2-Settings",
398 }
399
400 func (p *ReverseProxy) defaultErrorHandler(rw http.ResponseWriter, req *http.Request, err error) {
401 p.logf("http: proxy error: %v", err)
402 rw.WriteHeader(http.StatusBadGateway)
403 }
404
405 func (p *ReverseProxy) getErrorHandler() func(http.ResponseWriter, *http.Request, error) {
406 if p.ErrorHandler != nil {
407 return p.ErrorHandler
408 }
409 return p.defaultErrorHandler
410 }
411
412
413
414 func (p *ReverseProxy) modifyResponse(rw http.ResponseWriter, res *http.Response, req *http.Request) bool {
415 if p.ModifyResponse == nil {
416 return true
417 }
418 if err := p.ModifyResponse(res); err != nil {
419 res.Body.Close()
420 p.getErrorHandler()(rw, req, err)
421 return false
422 }
423 return true
424 }
425
426 func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
427 transport := p.Transport
428 if transport == nil {
429 transport = http.DefaultTransport
430 }
431
432 ctx := req.Context()
433 if ctx.Done() != nil {
434
435
436
437
438
439
440
441
442
443
444 } else if cn, ok := rw.(http.CloseNotifier); ok {
445 var cancel context.CancelFunc
446 ctx, cancel = context.WithCancel(ctx)
447 defer cancel()
448 notifyChan := cn.CloseNotify()
449 go func() {
450 select {
451 case <-notifyChan:
452 cancel()
453 case <-ctx.Done():
454 }
455 }()
456 }
457
458 outreq := req.Clone(ctx)
459 if req.ContentLength == 0 {
460 outreq.Body = nil
461 }
462 if outreq.Body != nil {
463
464
465
466
467
468
469 defer outreq.Body.Close()
470 }
471 if outreq.Header == nil {
472 outreq.Header = make(http.Header)
473 }
474
475 if (p.Director != nil) == (p.Rewrite != nil) {
476 p.getErrorHandler()(rw, req, errors.New("ReverseProxy must have exactly one of Director or Rewrite set"))
477 return
478 }
479
480 if p.Director != nil {
481 p.Director(outreq)
482 if outreq.Form != nil {
483 outreq.URL.RawQuery = cleanQueryParams(outreq.URL.RawQuery)
484 }
485 }
486 outreq.Close = false
487
488 reqUpType := upgradeType(outreq.Header)
489 if !ascii.IsPrint(reqUpType) {
490 p.getErrorHandler()(rw, req, fmt.Errorf("client tried to switch to invalid protocol %q", reqUpType))
491 return
492 }
493 if reqUpType != "" {
494 if req.ProtoMajor != 1 || req.ProtoMinor != 1 {
495 p.getErrorHandler()(rw, req, fmt.Errorf("client tried to use Upgrade header on non-HTTP/1 connection"))
496 return
497 }
498 if httpguts.HeaderValuesContainsToken([]string{reqUpType}, "h2c") {
499
500
501 reqUpType = ""
502 }
503 }
504 removeHopByHopHeaders(outreq.Header)
505
506
507
508
509
510
511 if httpguts.HeaderValuesContainsToken(req.Header["Te"], "trailers") {
512 outreq.Header.Set("Te", "trailers")
513 }
514
515
516
517 if reqUpType != "" {
518 outreq.Header.Set("Connection", "Upgrade")
519 outreq.Header.Set("Upgrade", reqUpType)
520 }
521
522 if p.Rewrite != nil {
523
524
525
526 outreq.Header.Del("Forwarded")
527 outreq.Header.Del("X-Forwarded-For")
528 outreq.Header.Del("X-Forwarded-Host")
529 outreq.Header.Del("X-Forwarded-Proto")
530
531
532 outreq.URL.RawQuery = cleanQueryParams(outreq.URL.RawQuery)
533
534
535 outreq.URL.Opaque = ""
536 outreq.URL.OmitHost = false
537
538
539
540 outreq.URL.User = nil
541
542 pr := &ProxyRequest{
543 In: req,
544 Out: outreq,
545 }
546 p.Rewrite(pr)
547 outreq = pr.Out
548 } else {
549 if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
550
551
552
553 prior, ok := outreq.Header["X-Forwarded-For"]
554 omit := ok && prior == nil
555 if len(prior) > 0 {
556 clientIP = strings.Join(prior, ", ") + ", " + clientIP
557 }
558 if !omit {
559 outreq.Header.Set("X-Forwarded-For", clientIP)
560 }
561 }
562 }
563
564 if outreq.Method == "CONNECT" {
565
566
567
568
569 err := errors.New("client sent unsupported CONNECT request")
570 if p.ErrorHandler != nil {
571 p.ErrorHandler(rw, outreq, err)
572 } else {
573 p.logf("http: proxy error: %v", err)
574 rw.WriteHeader(http.StatusMethodNotAllowed)
575 }
576 return
577 }
578
579 if _, ok := outreq.Header["User-Agent"]; !ok {
580
581
582 outreq.Header.Set("User-Agent", "")
583 }
584
585 var (
586 roundTripMutex sync.Mutex
587 roundTripDone bool
588 )
589 trace := &httptrace.ClientTrace{
590 Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
591 roundTripMutex.Lock()
592 defer roundTripMutex.Unlock()
593 if roundTripDone {
594
595
596 return nil
597 }
598 h := rw.Header()
599 var orig http.Header
600 if len(h) > 0 {
601 orig = h.Clone()
602 }
603
604 copyHeader(h, http.Header(header))
605 rw.WriteHeader(code)
606
607
608
609 clear(h)
610 maps.Copy(h, orig)
611
612 return nil
613 },
614 }
615 outreq = outreq.WithContext(httptrace.WithClientTrace(outreq.Context(), trace))
616
617 res, err := transport.RoundTrip(outreq)
618 roundTripMutex.Lock()
619 roundTripDone = true
620 roundTripMutex.Unlock()
621 if err != nil {
622 p.getErrorHandler()(rw, outreq, err)
623 return
624 }
625
626
627 if res.StatusCode == http.StatusSwitchingProtocols {
628 if !p.modifyResponse(rw, res, outreq) {
629 return
630 }
631 p.handleUpgradeResponse(rw, outreq, res)
632 return
633 }
634
635 removeHopByHopHeaders(res.Header)
636
637 if !p.modifyResponse(rw, res, outreq) {
638 return
639 }
640
641 copyHeader(rw.Header(), res.Header)
642
643
644
645 announcedTrailers := len(res.Trailer)
646 if announcedTrailers > 0 {
647 trailerKeys := make([]string, 0, len(res.Trailer))
648 for k := range res.Trailer {
649 trailerKeys = append(trailerKeys, k)
650 }
651 rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
652 }
653
654 rw.WriteHeader(res.StatusCode)
655
656 err = p.copyResponse(rw, res.Body, p.flushInterval(res))
657 if err != nil {
658 defer res.Body.Close()
659
660
661
662 if !shouldPanicOnCopyError(req) {
663 p.logf("suppressing panic for copyResponse error in test; copy error: %v", err)
664 return
665 }
666 panic(http.ErrAbortHandler)
667 }
668 res.Body.Close()
669
670 if len(res.Trailer) > 0 {
671
672
673
674 http.NewResponseController(rw).Flush()
675 }
676
677 if len(res.Trailer) == announcedTrailers {
678 copyHeader(rw.Header(), res.Trailer)
679 return
680 }
681
682 for k, vv := range res.Trailer {
683 k = http.TrailerPrefix + k
684 for _, v := range vv {
685 rw.Header().Add(k, v)
686 }
687 }
688 }
689
690 var inOurTests bool
691
692
693
694
695
696
697 func shouldPanicOnCopyError(req *http.Request) bool {
698 if inOurTests {
699
700 return true
701 }
702 if req.Context().Value(http.ServerContextKey) != nil {
703
704
705 return true
706 }
707
708
709 return false
710 }
711
712
713 func removeHopByHopHeaders(h http.Header) {
714
715 for _, f := range h["Connection"] {
716 for sf := range strings.SplitSeq(f, ",") {
717 if sf = textproto.TrimString(sf); sf != "" {
718 h.Del(sf)
719 }
720 }
721 }
722
723
724
725 for _, f := range hopHeaders {
726 h.Del(f)
727 }
728 }
729
730
731
732 func (p *ReverseProxy) flushInterval(res *http.Response) time.Duration {
733 resCT := res.Header.Get("Content-Type")
734
735
736
737 if baseCT, _, _ := mime.ParseMediaType(resCT); baseCT == "text/event-stream" {
738 return -1
739 }
740
741
742 if res.ContentLength == -1 {
743 return -1
744 }
745
746 return p.FlushInterval
747 }
748
749 func (p *ReverseProxy) copyResponse(dst http.ResponseWriter, src io.Reader, flushInterval time.Duration) error {
750 var w io.Writer = dst
751
752 if flushInterval != 0 {
753 mlw := &maxLatencyWriter{
754 dst: dst,
755 flush: http.NewResponseController(dst).Flush,
756 latency: flushInterval,
757 }
758 defer mlw.stop()
759
760
761 mlw.flushPending = true
762 mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush)
763
764 w = mlw
765 }
766
767 var buf []byte
768 if p.BufferPool != nil {
769 buf = p.BufferPool.Get()
770 defer p.BufferPool.Put(buf)
771 }
772 _, err := p.copyBuffer(w, src, buf)
773 return err
774 }
775
776
777
778 func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
779 if len(buf) == 0 {
780 buf = make([]byte, 32*1024)
781 }
782 var written int64
783 for {
784 nr, rerr := src.Read(buf)
785 if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
786 p.logf("httputil: ReverseProxy read error during body copy: %v", rerr)
787 }
788 if nr > 0 {
789 nw, werr := dst.Write(buf[:nr])
790 if nw > 0 {
791 written += int64(nw)
792 }
793 if werr != nil {
794 return written, werr
795 }
796 if nr != nw {
797 return written, io.ErrShortWrite
798 }
799 }
800 if rerr != nil {
801 if rerr == io.EOF {
802 rerr = nil
803 }
804 return written, rerr
805 }
806 }
807 }
808
809 func (p *ReverseProxy) logf(format string, args ...any) {
810 if p.ErrorLog != nil {
811 p.ErrorLog.Printf(format, args...)
812 } else {
813 log.Printf(format, args...)
814 }
815 }
816
817 type maxLatencyWriter struct {
818 dst io.Writer
819 flush func() error
820 latency time.Duration
821
822 mu sync.Mutex
823 t *time.Timer
824 flushPending bool
825 }
826
827 func (m *maxLatencyWriter) Write(p []byte) (n int, err error) {
828 m.mu.Lock()
829 defer m.mu.Unlock()
830 n, err = m.dst.Write(p)
831 if m.latency < 0 {
832 m.flush()
833 return
834 }
835 if m.flushPending {
836 return
837 }
838 if m.t == nil {
839 m.t = time.AfterFunc(m.latency, m.delayedFlush)
840 } else {
841 m.t.Reset(m.latency)
842 }
843 m.flushPending = true
844 return
845 }
846
847 func (m *maxLatencyWriter) delayedFlush() {
848 m.mu.Lock()
849 defer m.mu.Unlock()
850 if !m.flushPending {
851 return
852 }
853 m.flush()
854 m.flushPending = false
855 }
856
857 func (m *maxLatencyWriter) stop() {
858 m.mu.Lock()
859 defer m.mu.Unlock()
860 m.flushPending = false
861 if m.t != nil {
862 m.t.Stop()
863 }
864 }
865
866 func upgradeType(h http.Header) string {
867 if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") {
868 return ""
869 }
870 return h.Get("Upgrade")
871 }
872
873 func (p *ReverseProxy) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) {
874 reqUpType := upgradeType(req.Header)
875 resUpType := upgradeType(res.Header)
876 if !ascii.IsPrint(resUpType) {
877 p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch to invalid protocol %q", resUpType))
878 return
879 }
880 if !ascii.EqualFold(reqUpType, resUpType) {
881 p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch protocol %q when %q was requested", resUpType, reqUpType))
882 return
883 }
884
885 backConn, ok := res.Body.(io.ReadWriteCloser)
886 if !ok {
887 p.getErrorHandler()(rw, req, fmt.Errorf("internal error: 101 switching protocols response with non-writable body"))
888 return
889 }
890
891 rc := http.NewResponseController(rw)
892 conn, brw, hijackErr := rc.Hijack()
893 if errors.Is(hijackErr, http.ErrNotSupported) {
894 p.getErrorHandler()(rw, req, fmt.Errorf("can't switch protocols using non-Hijacker ResponseWriter type %T", rw))
895 return
896 }
897
898 backConnCloseCh := make(chan bool)
899 go func() {
900
901
902 select {
903 case <-req.Context().Done():
904 case <-backConnCloseCh:
905 }
906 backConn.Close()
907 }()
908 defer close(backConnCloseCh)
909
910 if hijackErr != nil {
911 p.getErrorHandler()(rw, req, fmt.Errorf("Hijack failed on protocol switch: %v", hijackErr))
912 return
913 }
914 defer conn.Close()
915
916 copyHeader(rw.Header(), res.Header)
917
918 res.Header = rw.Header()
919 res.Body = nil
920 if err := res.Write(brw); err != nil {
921 p.getErrorHandler()(rw, req, fmt.Errorf("response write: %v", err))
922 return
923 }
924 if err := brw.Flush(); err != nil {
925 p.getErrorHandler()(rw, req, fmt.Errorf("response flush: %v", err))
926 return
927 }
928 errc := make(chan error, 1)
929 spc := switchProtocolCopier{user: conn, backend: backConn}
930 go spc.copyToBackend(errc)
931 go spc.copyFromBackend(errc)
932
933
934
935 err := <-errc
936 if err == nil {
937 err = <-errc
938 }
939 }
940
941 var errCopyDone = errors.New("hijacked connection copy complete")
942
943
944
945 type switchProtocolCopier struct {
946 user, backend io.ReadWriter
947 }
948
949 func (c switchProtocolCopier) copyFromBackend(errc chan<- error) {
950 if _, err := io.Copy(c.user, c.backend); err != nil {
951 errc <- err
952 return
953 }
954
955
956 if wc, ok := c.user.(interface{ CloseWrite() error }); ok {
957 errc <- wc.CloseWrite()
958 return
959 }
960
961 errc <- errCopyDone
962 }
963
964 func (c switchProtocolCopier) copyToBackend(errc chan<- error) {
965 if _, err := io.Copy(c.backend, c.user); err != nil {
966 errc <- err
967 return
968 }
969
970
971 if wc, ok := c.backend.(interface{ CloseWrite() error }); ok {
972 errc <- wc.CloseWrite()
973 return
974 }
975
976 errc <- errCopyDone
977 }
978
979 var urlmaxqueryparams = godebug.New("urlmaxqueryparams")
980
981
982 const defaultMaxParams = 10000
983
984 func cleanQueryParams(s string) string {
985 reencode := func(s string) string {
986 v, _ := url.ParseQuery(s)
987 return v.Encode()
988 }
989 if urlmaxqueryparams.Value() != "" {
990
991 return reencode(s)
992 }
993 if numParams := strings.Count(s, "&") + 1; numParams > defaultMaxParams {
994
995 return reencode(s)
996 }
997 for i := 0; i < len(s); {
998 switch s[i] {
999 case ';':
1000 return reencode(s)
1001 case '%':
1002 if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
1003 return reencode(s)
1004 }
1005 i += 3
1006 default:
1007 i++
1008 }
1009 }
1010 return s
1011 }
1012
1013 func ishex(c byte) bool {
1014 switch {
1015 case '0' <= c && c <= '9':
1016 return true
1017 case 'a' <= c && c <= 'f':
1018 return true
1019 case 'A' <= c && c <= 'F':
1020 return true
1021 }
1022 return false
1023 }
1024
View as plain text