Source file
src/net/http/server.go
1
2
3
4
5
6
7 package http
8
9 import (
10 "bufio"
11 "bytes"
12 "context"
13 "crypto/tls"
14 "errors"
15 "fmt"
16 "internal/godebug"
17 "io"
18 "log"
19 "math/rand"
20 "net"
21 "net/textproto"
22 "net/url"
23 urlpkg "net/url"
24 "path"
25 "runtime"
26 "sort"
27 "strconv"
28 "strings"
29 "sync"
30 "sync/atomic"
31 "time"
32
33 "golang.org/x/net/http/httpguts"
34 )
35
36
37 var (
38
39
40
41 ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
42
43
44
45
46
47
48 ErrHijacked = errors.New("http: connection has been hijacked")
49
50
51
52
53
54 ErrContentLength = errors.New("http: wrote more than the declared Content-Length")
55
56
57
58
59 ErrWriteAfterFlush = errors.New("unused")
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 type Handler interface {
87 ServeHTTP(ResponseWriter, *Request)
88 }
89
90
91
92
93
94 type ResponseWriter interface {
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115 Header() Header
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138 Write([]byte) (int, error)
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158 WriteHeader(statusCode int)
159 }
160
161
162
163
164
165
166
167
168
169
170
171
172 type Flusher interface {
173
174 Flush()
175 }
176
177
178
179
180
181
182
183
184 type Hijacker interface {
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204 Hijack() (net.Conn, *bufio.ReadWriter, error)
205 }
206
207
208
209
210
211
212
213
214
215 type CloseNotifier interface {
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234 CloseNotify() <-chan bool
235 }
236
237 var (
238
239
240
241
242 ServerContextKey = &contextKey{"http-server"}
243
244
245
246
247
248 LocalAddrContextKey = &contextKey{"local-addr"}
249 )
250
251
252 type conn struct {
253
254
255 server *Server
256
257
258 cancelCtx context.CancelFunc
259
260
261
262
263
264 rwc net.Conn
265
266
267
268
269
270 remoteAddr string
271
272
273
274 tlsState *tls.ConnectionState
275
276
277
278 werr error
279
280
281
282
283 r *connReader
284
285
286 bufr *bufio.Reader
287
288
289 bufw *bufio.Writer
290
291
292
293 lastMethod string
294
295 curReq atomic.Pointer[response]
296
297 curState atomic.Uint64
298
299
300 mu sync.Mutex
301
302
303
304
305 hijackedv bool
306 }
307
308 func (c *conn) hijacked() bool {
309 c.mu.Lock()
310 defer c.mu.Unlock()
311 return c.hijackedv
312 }
313
314
315 func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
316 if c.hijackedv {
317 return nil, nil, ErrHijacked
318 }
319 c.r.abortPendingRead()
320
321 c.hijackedv = true
322 rwc = c.rwc
323 rwc.SetDeadline(time.Time{})
324
325 buf = bufio.NewReadWriter(c.bufr, bufio.NewWriter(rwc))
326 if c.r.hasByte {
327 if _, err := c.bufr.Peek(c.bufr.Buffered() + 1); err != nil {
328 return nil, nil, fmt.Errorf("unexpected Peek failure reading buffered byte: %v", err)
329 }
330 }
331 c.setState(rwc, StateHijacked, runHooks)
332 return
333 }
334
335
336
337 const bufferBeforeChunkingSize = 2048
338
339
340
341
342
343
344
345
346
347
348 type chunkWriter struct {
349 res *response
350
351
352
353
354
355 header Header
356
357
358
359
360
361 wroteHeader bool
362
363
364 chunking bool
365 }
366
367 var (
368 crlf = []byte("\r\n")
369 colonSpace = []byte(": ")
370 )
371
372 func (cw *chunkWriter) Write(p []byte) (n int, err error) {
373 if !cw.wroteHeader {
374 cw.writeHeader(p)
375 }
376 if cw.res.req.Method == "HEAD" {
377
378 return len(p), nil
379 }
380 if cw.chunking {
381 _, err = fmt.Fprintf(cw.res.conn.bufw, "%x\r\n", len(p))
382 if err != nil {
383 cw.res.conn.rwc.Close()
384 return
385 }
386 }
387 n, err = cw.res.conn.bufw.Write(p)
388 if cw.chunking && err == nil {
389 _, err = cw.res.conn.bufw.Write(crlf)
390 }
391 if err != nil {
392 cw.res.conn.rwc.Close()
393 }
394 return
395 }
396
397 func (cw *chunkWriter) flush() error {
398 if !cw.wroteHeader {
399 cw.writeHeader(nil)
400 }
401 return cw.res.conn.bufw.Flush()
402 }
403
404 func (cw *chunkWriter) close() {
405 if !cw.wroteHeader {
406 cw.writeHeader(nil)
407 }
408 if cw.chunking {
409 bw := cw.res.conn.bufw
410
411 bw.WriteString("0\r\n")
412 if trailers := cw.res.finalTrailers(); trailers != nil {
413 trailers.Write(bw)
414 }
415
416
417 bw.WriteString("\r\n")
418 }
419 }
420
421
422 type response struct {
423 conn *conn
424 req *Request
425 reqBody io.ReadCloser
426 cancelCtx context.CancelFunc
427 wroteHeader bool
428 wroteContinue bool
429 wants10KeepAlive bool
430 wantsClose bool
431
432
433
434
435
436
437
438
439 canWriteContinue atomic.Bool
440 writeContinueMu sync.Mutex
441
442 w *bufio.Writer
443 cw chunkWriter
444
445
446
447
448
449 handlerHeader Header
450 calledHeader bool
451
452 written int64
453 contentLength int64
454 status int
455
456
457
458
459
460 closeAfterReply bool
461
462
463
464 fullDuplex bool
465
466
467
468
469
470
471
472
473 requestBodyLimitHit bool
474
475
476
477
478
479 trailers []string
480
481 handlerDone atomic.Bool
482
483
484 dateBuf [len(TimeFormat)]byte
485 clenBuf [10]byte
486 statusBuf [3]byte
487
488
489
490
491 closeNotifyCh chan bool
492 didCloseNotify atomic.Bool
493 }
494
495 func (c *response) SetReadDeadline(deadline time.Time) error {
496 return c.conn.rwc.SetReadDeadline(deadline)
497 }
498
499 func (c *response) SetWriteDeadline(deadline time.Time) error {
500 return c.conn.rwc.SetWriteDeadline(deadline)
501 }
502
503 func (c *response) EnableFullDuplex() error {
504 c.fullDuplex = true
505 return nil
506 }
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521 const TrailerPrefix = "Trailer:"
522
523
524
525 func (w *response) finalTrailers() Header {
526 var t Header
527 for k, vv := range w.handlerHeader {
528 if kk, found := strings.CutPrefix(k, TrailerPrefix); found {
529 if t == nil {
530 t = make(Header)
531 }
532 t[kk] = vv
533 }
534 }
535 for _, k := range w.trailers {
536 if t == nil {
537 t = make(Header)
538 }
539 for _, v := range w.handlerHeader[k] {
540 t.Add(k, v)
541 }
542 }
543 return t
544 }
545
546
547
548
549 func (w *response) declareTrailer(k string) {
550 k = CanonicalHeaderKey(k)
551 if !httpguts.ValidTrailerHeader(k) {
552
553 return
554 }
555 w.trailers = append(w.trailers, k)
556 }
557
558
559
560 func (w *response) requestTooLarge() {
561 w.closeAfterReply = true
562 w.requestBodyLimitHit = true
563 if !w.wroteHeader {
564 w.Header().Set("Connection", "close")
565 }
566 }
567
568
569
570 type writerOnly struct {
571 io.Writer
572 }
573
574
575
576
577 func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
578 buf := getCopyBuf()
579 defer putCopyBuf(buf)
580
581
582
583
584 rf, ok := w.conn.rwc.(io.ReaderFrom)
585 if !ok {
586 return io.CopyBuffer(writerOnly{w}, src, buf)
587 }
588
589
590
591
592
593 if !w.cw.wroteHeader {
594 n0, err := io.CopyBuffer(writerOnly{w}, io.LimitReader(src, sniffLen), buf)
595 n += n0
596 if err != nil || n0 < sniffLen {
597 return n, err
598 }
599 }
600
601 w.w.Flush()
602 w.cw.flush()
603
604
605 if !w.cw.chunking && w.bodyAllowed() {
606 n0, err := rf.ReadFrom(src)
607 n += n0
608 w.written += n0
609 return n, err
610 }
611
612 n0, err := io.CopyBuffer(writerOnly{w}, src, buf)
613 n += n0
614 return n, err
615 }
616
617
618
619 const debugServerConnections = false
620
621
622 func (srv *Server) newConn(rwc net.Conn) *conn {
623 c := &conn{
624 server: srv,
625 rwc: rwc,
626 }
627 if debugServerConnections {
628 c.rwc = newLoggingConn("server", c.rwc)
629 }
630 return c
631 }
632
633 type readResult struct {
634 _ incomparable
635 n int
636 err error
637 b byte
638 }
639
640
641
642
643
644
645 type connReader struct {
646 conn *conn
647
648 mu sync.Mutex
649 hasByte bool
650 byteBuf [1]byte
651 cond *sync.Cond
652 inRead bool
653 aborted bool
654 remain int64
655 }
656
657 func (cr *connReader) lock() {
658 cr.mu.Lock()
659 if cr.cond == nil {
660 cr.cond = sync.NewCond(&cr.mu)
661 }
662 }
663
664 func (cr *connReader) unlock() { cr.mu.Unlock() }
665
666 func (cr *connReader) startBackgroundRead() {
667 cr.lock()
668 defer cr.unlock()
669 if cr.inRead {
670 panic("invalid concurrent Body.Read call")
671 }
672 if cr.hasByte {
673 return
674 }
675 cr.inRead = true
676 cr.conn.rwc.SetReadDeadline(time.Time{})
677 go cr.backgroundRead()
678 }
679
680 func (cr *connReader) backgroundRead() {
681 n, err := cr.conn.rwc.Read(cr.byteBuf[:])
682 cr.lock()
683 if n == 1 {
684 cr.hasByte = true
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707 }
708 if ne, ok := err.(net.Error); ok && cr.aborted && ne.Timeout() {
709
710
711 } else if err != nil {
712 cr.handleReadError(err)
713 }
714 cr.aborted = false
715 cr.inRead = false
716 cr.unlock()
717 cr.cond.Broadcast()
718 }
719
720 func (cr *connReader) abortPendingRead() {
721 cr.lock()
722 defer cr.unlock()
723 if !cr.inRead {
724 return
725 }
726 cr.aborted = true
727 cr.conn.rwc.SetReadDeadline(aLongTimeAgo)
728 for cr.inRead {
729 cr.cond.Wait()
730 }
731 cr.conn.rwc.SetReadDeadline(time.Time{})
732 }
733
734 func (cr *connReader) setReadLimit(remain int64) { cr.remain = remain }
735 func (cr *connReader) setInfiniteReadLimit() { cr.remain = maxInt64 }
736 func (cr *connReader) hitReadLimit() bool { return cr.remain <= 0 }
737
738
739
740
741
742
743
744
745
746
747
748 func (cr *connReader) handleReadError(_ error) {
749 cr.conn.cancelCtx()
750 cr.closeNotify()
751 }
752
753
754 func (cr *connReader) closeNotify() {
755 res := cr.conn.curReq.Load()
756 if res != nil && !res.didCloseNotify.Swap(true) {
757 res.closeNotifyCh <- true
758 }
759 }
760
761 func (cr *connReader) Read(p []byte) (n int, err error) {
762 cr.lock()
763 if cr.inRead {
764 cr.unlock()
765 if cr.conn.hijacked() {
766 panic("invalid Body.Read call. After hijacked, the original Request must not be used")
767 }
768 panic("invalid concurrent Body.Read call")
769 }
770 if cr.hitReadLimit() {
771 cr.unlock()
772 return 0, io.EOF
773 }
774 if len(p) == 0 {
775 cr.unlock()
776 return 0, nil
777 }
778 if int64(len(p)) > cr.remain {
779 p = p[:cr.remain]
780 }
781 if cr.hasByte {
782 p[0] = cr.byteBuf[0]
783 cr.hasByte = false
784 cr.unlock()
785 return 1, nil
786 }
787 cr.inRead = true
788 cr.unlock()
789 n, err = cr.conn.rwc.Read(p)
790
791 cr.lock()
792 cr.inRead = false
793 if err != nil {
794 cr.handleReadError(err)
795 }
796 cr.remain -= int64(n)
797 cr.unlock()
798
799 cr.cond.Broadcast()
800 return n, err
801 }
802
803 var (
804 bufioReaderPool sync.Pool
805 bufioWriter2kPool sync.Pool
806 bufioWriter4kPool sync.Pool
807 )
808
809 const copyBufPoolSize = 32 * 1024
810
811 var copyBufPool = sync.Pool{New: func() any { return new([copyBufPoolSize]byte) }}
812
813 func getCopyBuf() []byte {
814 return copyBufPool.Get().(*[copyBufPoolSize]byte)[:]
815 }
816 func putCopyBuf(b []byte) {
817 if len(b) != copyBufPoolSize {
818 panic("trying to put back buffer of the wrong size in the copyBufPool")
819 }
820 copyBufPool.Put((*[copyBufPoolSize]byte)(b))
821 }
822
823 func bufioWriterPool(size int) *sync.Pool {
824 switch size {
825 case 2 << 10:
826 return &bufioWriter2kPool
827 case 4 << 10:
828 return &bufioWriter4kPool
829 }
830 return nil
831 }
832
833 func newBufioReader(r io.Reader) *bufio.Reader {
834 if v := bufioReaderPool.Get(); v != nil {
835 br := v.(*bufio.Reader)
836 br.Reset(r)
837 return br
838 }
839
840
841 return bufio.NewReader(r)
842 }
843
844 func putBufioReader(br *bufio.Reader) {
845 br.Reset(nil)
846 bufioReaderPool.Put(br)
847 }
848
849 func newBufioWriterSize(w io.Writer, size int) *bufio.Writer {
850 pool := bufioWriterPool(size)
851 if pool != nil {
852 if v := pool.Get(); v != nil {
853 bw := v.(*bufio.Writer)
854 bw.Reset(w)
855 return bw
856 }
857 }
858 return bufio.NewWriterSize(w, size)
859 }
860
861 func putBufioWriter(bw *bufio.Writer) {
862 bw.Reset(nil)
863 if pool := bufioWriterPool(bw.Available()); pool != nil {
864 pool.Put(bw)
865 }
866 }
867
868
869
870
871 const DefaultMaxHeaderBytes = 1 << 20
872
873 func (srv *Server) maxHeaderBytes() int {
874 if srv.MaxHeaderBytes > 0 {
875 return srv.MaxHeaderBytes
876 }
877 return DefaultMaxHeaderBytes
878 }
879
880 func (srv *Server) initialReadLimitSize() int64 {
881 return int64(srv.maxHeaderBytes()) + 4096
882 }
883
884
885
886
887
888
889 func (srv *Server) tlsHandshakeTimeout() time.Duration {
890 var ret time.Duration
891 for _, v := range [...]time.Duration{
892 srv.ReadHeaderTimeout,
893 srv.ReadTimeout,
894 srv.WriteTimeout,
895 } {
896 if v <= 0 {
897 continue
898 }
899 if ret == 0 || v < ret {
900 ret = v
901 }
902 }
903 return ret
904 }
905
906
907
908 type expectContinueReader struct {
909 resp *response
910 readCloser io.ReadCloser
911 closed atomic.Bool
912 sawEOF atomic.Bool
913 }
914
915 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
916 if ecr.closed.Load() {
917 return 0, ErrBodyReadAfterClose
918 }
919 w := ecr.resp
920 if !w.wroteContinue && w.canWriteContinue.Load() && !w.conn.hijacked() {
921 w.wroteContinue = true
922 w.writeContinueMu.Lock()
923 if w.canWriteContinue.Load() {
924 w.conn.bufw.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
925 w.conn.bufw.Flush()
926 w.canWriteContinue.Store(false)
927 }
928 w.writeContinueMu.Unlock()
929 }
930 n, err = ecr.readCloser.Read(p)
931 if err == io.EOF {
932 ecr.sawEOF.Store(true)
933 }
934 return
935 }
936
937 func (ecr *expectContinueReader) Close() error {
938 ecr.closed.Store(true)
939 return ecr.readCloser.Close()
940 }
941
942
943
944
945
946
947
948 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
949
950
951 func appendTime(b []byte, t time.Time) []byte {
952 const days = "SunMonTueWedThuFriSat"
953 const months = "JanFebMarAprMayJunJulAugSepOctNovDec"
954
955 t = t.UTC()
956 yy, mm, dd := t.Date()
957 hh, mn, ss := t.Clock()
958 day := days[3*t.Weekday():]
959 mon := months[3*(mm-1):]
960
961 return append(b,
962 day[0], day[1], day[2], ',', ' ',
963 byte('0'+dd/10), byte('0'+dd%10), ' ',
964 mon[0], mon[1], mon[2], ' ',
965 byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ',
966 byte('0'+hh/10), byte('0'+hh%10), ':',
967 byte('0'+mn/10), byte('0'+mn%10), ':',
968 byte('0'+ss/10), byte('0'+ss%10), ' ',
969 'G', 'M', 'T')
970 }
971
972 var errTooLarge = errors.New("http: request too large")
973
974
975 func (c *conn) readRequest(ctx context.Context) (w *response, err error) {
976 if c.hijacked() {
977 return nil, ErrHijacked
978 }
979
980 var (
981 wholeReqDeadline time.Time
982 hdrDeadline time.Time
983 )
984 t0 := time.Now()
985 if d := c.server.readHeaderTimeout(); d > 0 {
986 hdrDeadline = t0.Add(d)
987 }
988 if d := c.server.ReadTimeout; d > 0 {
989 wholeReqDeadline = t0.Add(d)
990 }
991 c.rwc.SetReadDeadline(hdrDeadline)
992 if d := c.server.WriteTimeout; d > 0 {
993 defer func() {
994 c.rwc.SetWriteDeadline(time.Now().Add(d))
995 }()
996 }
997
998 c.r.setReadLimit(c.server.initialReadLimitSize())
999 if c.lastMethod == "POST" {
1000
1001 peek, _ := c.bufr.Peek(4)
1002 c.bufr.Discard(numLeadingCRorLF(peek))
1003 }
1004 req, err := readRequest(c.bufr)
1005 if err != nil {
1006 if c.r.hitReadLimit() {
1007 return nil, errTooLarge
1008 }
1009 return nil, err
1010 }
1011
1012 if !http1ServerSupportsRequest(req) {
1013 return nil, statusError{StatusHTTPVersionNotSupported, "unsupported protocol version"}
1014 }
1015
1016 c.lastMethod = req.Method
1017 c.r.setInfiniteReadLimit()
1018
1019 hosts, haveHost := req.Header["Host"]
1020 isH2Upgrade := req.isH2Upgrade()
1021 if req.ProtoAtLeast(1, 1) && (!haveHost || len(hosts) == 0) && !isH2Upgrade && req.Method != "CONNECT" {
1022 return nil, badRequestError("missing required Host header")
1023 }
1024 if len(hosts) == 1 && !httpguts.ValidHostHeader(hosts[0]) {
1025 return nil, badRequestError("malformed Host header")
1026 }
1027 for k, vv := range req.Header {
1028 if !httpguts.ValidHeaderFieldName(k) {
1029 return nil, badRequestError("invalid header name")
1030 }
1031 for _, v := range vv {
1032 if !httpguts.ValidHeaderFieldValue(v) {
1033 return nil, badRequestError("invalid header value")
1034 }
1035 }
1036 }
1037 delete(req.Header, "Host")
1038
1039 ctx, cancelCtx := context.WithCancel(ctx)
1040 req.ctx = ctx
1041 req.RemoteAddr = c.remoteAddr
1042 req.TLS = c.tlsState
1043 if body, ok := req.Body.(*body); ok {
1044 body.doEarlyClose = true
1045 }
1046
1047
1048 if !hdrDeadline.Equal(wholeReqDeadline) {
1049 c.rwc.SetReadDeadline(wholeReqDeadline)
1050 }
1051
1052 w = &response{
1053 conn: c,
1054 cancelCtx: cancelCtx,
1055 req: req,
1056 reqBody: req.Body,
1057 handlerHeader: make(Header),
1058 contentLength: -1,
1059 closeNotifyCh: make(chan bool, 1),
1060
1061
1062
1063
1064 wants10KeepAlive: req.wantsHttp10KeepAlive(),
1065 wantsClose: req.wantsClose(),
1066 }
1067 if isH2Upgrade {
1068 w.closeAfterReply = true
1069 }
1070 w.cw.res = w
1071 w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize)
1072 return w, nil
1073 }
1074
1075
1076
1077 func http1ServerSupportsRequest(req *Request) bool {
1078 if req.ProtoMajor == 1 {
1079 return true
1080 }
1081
1082
1083 if req.ProtoMajor == 2 && req.ProtoMinor == 0 &&
1084 req.Method == "PRI" && req.RequestURI == "*" {
1085 return true
1086 }
1087
1088
1089 return false
1090 }
1091
1092 func (w *response) Header() Header {
1093 if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader {
1094
1095
1096
1097 w.cw.header = w.handlerHeader.Clone()
1098 }
1099 w.calledHeader = true
1100 return w.handlerHeader
1101 }
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112 const maxPostHandlerReadBytes = 256 << 10
1113
1114 func checkWriteHeaderCode(code int) {
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125 if code < 100 || code > 999 {
1126 panic(fmt.Sprintf("invalid WriteHeader code %v", code))
1127 }
1128 }
1129
1130
1131
1132 func relevantCaller() runtime.Frame {
1133 pc := make([]uintptr, 16)
1134 n := runtime.Callers(1, pc)
1135 frames := runtime.CallersFrames(pc[:n])
1136 var frame runtime.Frame
1137 for {
1138 frame, more := frames.Next()
1139 if !strings.HasPrefix(frame.Function, "net/http.") {
1140 return frame
1141 }
1142 if !more {
1143 break
1144 }
1145 }
1146 return frame
1147 }
1148
1149 func (w *response) WriteHeader(code int) {
1150 if w.conn.hijacked() {
1151 caller := relevantCaller()
1152 w.conn.server.logf("http: response.WriteHeader on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1153 return
1154 }
1155 if w.wroteHeader {
1156 caller := relevantCaller()
1157 w.conn.server.logf("http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1158 return
1159 }
1160 checkWriteHeaderCode(code)
1161
1162
1163
1164
1165
1166 if code >= 100 && code <= 199 && code != StatusSwitchingProtocols {
1167
1168 if code == 100 && w.canWriteContinue.Load() {
1169 w.writeContinueMu.Lock()
1170 w.canWriteContinue.Store(false)
1171 w.writeContinueMu.Unlock()
1172 }
1173
1174 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
1175
1176
1177 w.handlerHeader.WriteSubset(w.conn.bufw, excludedHeadersNoBody)
1178 w.conn.bufw.Write(crlf)
1179 w.conn.bufw.Flush()
1180
1181 return
1182 }
1183
1184 w.wroteHeader = true
1185 w.status = code
1186
1187 if w.calledHeader && w.cw.header == nil {
1188 w.cw.header = w.handlerHeader.Clone()
1189 }
1190
1191 if cl := w.handlerHeader.get("Content-Length"); cl != "" {
1192 v, err := strconv.ParseInt(cl, 10, 64)
1193 if err == nil && v >= 0 {
1194 w.contentLength = v
1195 } else {
1196 w.conn.server.logf("http: invalid Content-Length of %q", cl)
1197 w.handlerHeader.Del("Content-Length")
1198 }
1199 }
1200 }
1201
1202
1203
1204
1205 type extraHeader struct {
1206 contentType string
1207 connection string
1208 transferEncoding string
1209 date []byte
1210 contentLength []byte
1211 }
1212
1213
1214 var extraHeaderKeys = [][]byte{
1215 []byte("Content-Type"),
1216 []byte("Connection"),
1217 []byte("Transfer-Encoding"),
1218 }
1219
1220 var (
1221 headerContentLength = []byte("Content-Length: ")
1222 headerDate = []byte("Date: ")
1223 )
1224
1225
1226
1227
1228
1229
1230 func (h extraHeader) Write(w *bufio.Writer) {
1231 if h.date != nil {
1232 w.Write(headerDate)
1233 w.Write(h.date)
1234 w.Write(crlf)
1235 }
1236 if h.contentLength != nil {
1237 w.Write(headerContentLength)
1238 w.Write(h.contentLength)
1239 w.Write(crlf)
1240 }
1241 for i, v := range []string{h.contentType, h.connection, h.transferEncoding} {
1242 if v != "" {
1243 w.Write(extraHeaderKeys[i])
1244 w.Write(colonSpace)
1245 w.WriteString(v)
1246 w.Write(crlf)
1247 }
1248 }
1249 }
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259 func (cw *chunkWriter) writeHeader(p []byte) {
1260 if cw.wroteHeader {
1261 return
1262 }
1263 cw.wroteHeader = true
1264
1265 w := cw.res
1266 keepAlivesEnabled := w.conn.server.doKeepAlives()
1267 isHEAD := w.req.Method == "HEAD"
1268
1269
1270
1271
1272
1273
1274 header := cw.header
1275 owned := header != nil
1276 if !owned {
1277 header = w.handlerHeader
1278 }
1279 var excludeHeader map[string]bool
1280 delHeader := func(key string) {
1281 if owned {
1282 header.Del(key)
1283 return
1284 }
1285 if _, ok := header[key]; !ok {
1286 return
1287 }
1288 if excludeHeader == nil {
1289 excludeHeader = make(map[string]bool)
1290 }
1291 excludeHeader[key] = true
1292 }
1293 var setHeader extraHeader
1294
1295
1296 trailers := false
1297 for k := range cw.header {
1298 if strings.HasPrefix(k, TrailerPrefix) {
1299 if excludeHeader == nil {
1300 excludeHeader = make(map[string]bool)
1301 }
1302 excludeHeader[k] = true
1303 trailers = true
1304 }
1305 }
1306 for _, v := range cw.header["Trailer"] {
1307 trailers = true
1308 foreachHeaderElement(v, cw.res.declareTrailer)
1309 }
1310
1311 te := header.get("Transfer-Encoding")
1312 hasTE := te != ""
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328 if w.handlerDone.Load() && !trailers && !hasTE && bodyAllowedForStatus(w.status) && !header.has("Content-Length") && (!isHEAD || len(p) > 0) {
1329 w.contentLength = int64(len(p))
1330 setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10)
1331 }
1332
1333
1334
1335 if w.wants10KeepAlive && keepAlivesEnabled {
1336 sentLength := header.get("Content-Length") != ""
1337 if sentLength && header.get("Connection") == "keep-alive" {
1338 w.closeAfterReply = false
1339 }
1340 }
1341
1342
1343 hasCL := w.contentLength != -1
1344
1345 if w.wants10KeepAlive && (isHEAD || hasCL || !bodyAllowedForStatus(w.status)) {
1346 _, connectionHeaderSet := header["Connection"]
1347 if !connectionHeaderSet {
1348 setHeader.connection = "keep-alive"
1349 }
1350 } else if !w.req.ProtoAtLeast(1, 1) || w.wantsClose {
1351 w.closeAfterReply = true
1352 }
1353
1354 if header.get("Connection") == "close" || !keepAlivesEnabled {
1355 w.closeAfterReply = true
1356 }
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370 if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF.Load() {
1371 w.closeAfterReply = true
1372 }
1373
1374
1375
1376
1377
1378
1379
1380
1381 if w.req.ContentLength != 0 && !w.closeAfterReply && !w.fullDuplex {
1382 var discard, tooBig bool
1383
1384 switch bdy := w.req.Body.(type) {
1385 case *expectContinueReader:
1386 if bdy.resp.wroteContinue {
1387 discard = true
1388 }
1389 case *body:
1390 bdy.mu.Lock()
1391 switch {
1392 case bdy.closed:
1393 if !bdy.sawEOF {
1394
1395 w.closeAfterReply = true
1396 }
1397 case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes:
1398 tooBig = true
1399 default:
1400 discard = true
1401 }
1402 bdy.mu.Unlock()
1403 default:
1404 discard = true
1405 }
1406
1407 if discard {
1408 _, err := io.CopyN(io.Discard, w.reqBody, maxPostHandlerReadBytes+1)
1409 switch err {
1410 case nil:
1411
1412 tooBig = true
1413 case ErrBodyReadAfterClose:
1414
1415 case io.EOF:
1416
1417 err = w.reqBody.Close()
1418 if err != nil {
1419 w.closeAfterReply = true
1420 }
1421 default:
1422
1423
1424
1425 w.closeAfterReply = true
1426 }
1427 }
1428
1429 if tooBig {
1430 w.requestTooLarge()
1431 delHeader("Connection")
1432 setHeader.connection = "close"
1433 }
1434 }
1435
1436 code := w.status
1437 if bodyAllowedForStatus(code) {
1438
1439 _, haveType := header["Content-Type"]
1440
1441
1442
1443 ce := header.Get("Content-Encoding")
1444 hasCE := len(ce) > 0
1445 if !hasCE && !haveType && !hasTE && len(p) > 0 {
1446 setHeader.contentType = DetectContentType(p)
1447 }
1448 } else {
1449 for _, k := range suppressedHeaders(code) {
1450 delHeader(k)
1451 }
1452 }
1453
1454 if !header.has("Date") {
1455 setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now())
1456 }
1457
1458 if hasCL && hasTE && te != "identity" {
1459
1460
1461 w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
1462 te, w.contentLength)
1463 delHeader("Content-Length")
1464 hasCL = false
1465 }
1466
1467 if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) || code == StatusNoContent {
1468
1469 delHeader("Transfer-Encoding")
1470 } else if hasCL {
1471
1472 delHeader("Transfer-Encoding")
1473 } else if w.req.ProtoAtLeast(1, 1) {
1474
1475
1476
1477
1478
1479 if hasTE && te == "identity" {
1480 cw.chunking = false
1481 w.closeAfterReply = true
1482 delHeader("Transfer-Encoding")
1483 } else {
1484
1485
1486 cw.chunking = true
1487 setHeader.transferEncoding = "chunked"
1488 if hasTE && te == "chunked" {
1489
1490 delHeader("Transfer-Encoding")
1491 }
1492 }
1493 } else {
1494
1495
1496
1497 w.closeAfterReply = true
1498 delHeader("Transfer-Encoding")
1499 }
1500
1501
1502 if cw.chunking {
1503 delHeader("Content-Length")
1504 }
1505 if !w.req.ProtoAtLeast(1, 0) {
1506 return
1507 }
1508
1509
1510
1511
1512 delConnectionHeader := w.closeAfterReply &&
1513 (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) &&
1514 !isProtocolSwitchResponse(w.status, header)
1515 if delConnectionHeader {
1516 delHeader("Connection")
1517 if w.req.ProtoAtLeast(1, 1) {
1518 setHeader.connection = "close"
1519 }
1520 }
1521
1522 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
1523 cw.header.WriteSubset(w.conn.bufw, excludeHeader)
1524 setHeader.Write(w.conn.bufw)
1525 w.conn.bufw.Write(crlf)
1526 }
1527
1528
1529
1530 func foreachHeaderElement(v string, fn func(string)) {
1531 v = textproto.TrimString(v)
1532 if v == "" {
1533 return
1534 }
1535 if !strings.Contains(v, ",") {
1536 fn(v)
1537 return
1538 }
1539 for _, f := range strings.Split(v, ",") {
1540 if f = textproto.TrimString(f); f != "" {
1541 fn(f)
1542 }
1543 }
1544 }
1545
1546
1547
1548
1549
1550 func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte) {
1551 if is11 {
1552 bw.WriteString("HTTP/1.1 ")
1553 } else {
1554 bw.WriteString("HTTP/1.0 ")
1555 }
1556 if text := StatusText(code); text != "" {
1557 bw.Write(strconv.AppendInt(scratch[:0], int64(code), 10))
1558 bw.WriteByte(' ')
1559 bw.WriteString(text)
1560 bw.WriteString("\r\n")
1561 } else {
1562
1563 fmt.Fprintf(bw, "%03d status code %d\r\n", code, code)
1564 }
1565 }
1566
1567
1568
1569 func (w *response) bodyAllowed() bool {
1570 if !w.wroteHeader {
1571 panic("")
1572 }
1573 return bodyAllowedForStatus(w.status)
1574 }
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610 func (w *response) Write(data []byte) (n int, err error) {
1611 return w.write(len(data), data, "")
1612 }
1613
1614 func (w *response) WriteString(data string) (n int, err error) {
1615 return w.write(len(data), nil, data)
1616 }
1617
1618
1619 func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
1620 if w.conn.hijacked() {
1621 if lenData > 0 {
1622 caller := relevantCaller()
1623 w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1624 }
1625 return 0, ErrHijacked
1626 }
1627
1628 if w.canWriteContinue.Load() {
1629
1630
1631
1632
1633 w.writeContinueMu.Lock()
1634 w.canWriteContinue.Store(false)
1635 w.writeContinueMu.Unlock()
1636 }
1637
1638 if !w.wroteHeader {
1639 w.WriteHeader(StatusOK)
1640 }
1641 if lenData == 0 {
1642 return 0, nil
1643 }
1644 if !w.bodyAllowed() {
1645 return 0, ErrBodyNotAllowed
1646 }
1647
1648 w.written += int64(lenData)
1649 if w.contentLength != -1 && w.written > w.contentLength {
1650 return 0, ErrContentLength
1651 }
1652 if dataB != nil {
1653 return w.w.Write(dataB)
1654 } else {
1655 return w.w.WriteString(dataS)
1656 }
1657 }
1658
1659 func (w *response) finishRequest() {
1660 w.handlerDone.Store(true)
1661
1662 if !w.wroteHeader {
1663 w.WriteHeader(StatusOK)
1664 }
1665
1666 w.w.Flush()
1667 putBufioWriter(w.w)
1668 w.cw.close()
1669 w.conn.bufw.Flush()
1670
1671 w.conn.r.abortPendingRead()
1672
1673
1674
1675 w.reqBody.Close()
1676
1677 if w.req.MultipartForm != nil {
1678 w.req.MultipartForm.RemoveAll()
1679 }
1680 }
1681
1682
1683
1684 func (w *response) shouldReuseConnection() bool {
1685 if w.closeAfterReply {
1686
1687
1688
1689 return false
1690 }
1691
1692 if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
1693
1694 return false
1695 }
1696
1697
1698
1699 if w.conn.werr != nil {
1700 return false
1701 }
1702
1703 if w.closedRequestBodyEarly() {
1704 return false
1705 }
1706
1707 return true
1708 }
1709
1710 func (w *response) closedRequestBodyEarly() bool {
1711 body, ok := w.req.Body.(*body)
1712 return ok && body.didEarlyClose()
1713 }
1714
1715 func (w *response) Flush() {
1716 w.FlushError()
1717 }
1718
1719 func (w *response) FlushError() error {
1720 if !w.wroteHeader {
1721 w.WriteHeader(StatusOK)
1722 }
1723 err := w.w.Flush()
1724 e2 := w.cw.flush()
1725 if err == nil {
1726 err = e2
1727 }
1728 return err
1729 }
1730
1731 func (c *conn) finalFlush() {
1732 if c.bufr != nil {
1733
1734
1735 putBufioReader(c.bufr)
1736 c.bufr = nil
1737 }
1738
1739 if c.bufw != nil {
1740 c.bufw.Flush()
1741
1742
1743 putBufioWriter(c.bufw)
1744 c.bufw = nil
1745 }
1746 }
1747
1748
1749 func (c *conn) close() {
1750 c.finalFlush()
1751 c.rwc.Close()
1752 }
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765 var rstAvoidanceDelay = 500 * time.Millisecond
1766
1767 type closeWriter interface {
1768 CloseWrite() error
1769 }
1770
1771 var _ closeWriter = (*net.TCPConn)(nil)
1772
1773
1774
1775
1776
1777
1778
1779 func (c *conn) closeWriteAndWait() {
1780 c.finalFlush()
1781 if tcp, ok := c.rwc.(closeWriter); ok {
1782 tcp.CloseWrite()
1783 }
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805 time.Sleep(rstAvoidanceDelay)
1806 }
1807
1808
1809
1810
1811 func validNextProto(proto string) bool {
1812 switch proto {
1813 case "", "http/1.1", "http/1.0":
1814 return false
1815 }
1816 return true
1817 }
1818
1819 const (
1820 runHooks = true
1821 skipHooks = false
1822 )
1823
1824 func (c *conn) setState(nc net.Conn, state ConnState, runHook bool) {
1825 srv := c.server
1826 switch state {
1827 case StateNew:
1828 srv.trackConn(c, true)
1829 case StateHijacked, StateClosed:
1830 srv.trackConn(c, false)
1831 }
1832 if state > 0xff || state < 0 {
1833 panic("internal error")
1834 }
1835 packedState := uint64(time.Now().Unix()<<8) | uint64(state)
1836 c.curState.Store(packedState)
1837 if !runHook {
1838 return
1839 }
1840 if hook := srv.ConnState; hook != nil {
1841 hook(nc, state)
1842 }
1843 }
1844
1845 func (c *conn) getState() (state ConnState, unixSec int64) {
1846 packedState := c.curState.Load()
1847 return ConnState(packedState & 0xff), int64(packedState >> 8)
1848 }
1849
1850
1851
1852
1853 func badRequestError(e string) error { return statusError{StatusBadRequest, e} }
1854
1855
1856
1857 type statusError struct {
1858 code int
1859 text string
1860 }
1861
1862 func (e statusError) Error() string { return StatusText(e.code) + ": " + e.text }
1863
1864
1865
1866
1867
1868 var ErrAbortHandler = errors.New("net/http: abort Handler")
1869
1870
1871
1872
1873
1874 func isCommonNetReadError(err error) bool {
1875 if err == io.EOF {
1876 return true
1877 }
1878 if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
1879 return true
1880 }
1881 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
1882 return true
1883 }
1884 return false
1885 }
1886
1887
1888 func (c *conn) serve(ctx context.Context) {
1889 if ra := c.rwc.RemoteAddr(); ra != nil {
1890 c.remoteAddr = ra.String()
1891 }
1892 ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr())
1893 var inFlightResponse *response
1894 defer func() {
1895 if err := recover(); err != nil && err != ErrAbortHandler {
1896 const size = 64 << 10
1897 buf := make([]byte, size)
1898 buf = buf[:runtime.Stack(buf, false)]
1899 c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
1900 }
1901 if inFlightResponse != nil {
1902 inFlightResponse.cancelCtx()
1903 }
1904 if !c.hijacked() {
1905 if inFlightResponse != nil {
1906 inFlightResponse.conn.r.abortPendingRead()
1907 inFlightResponse.reqBody.Close()
1908 }
1909 c.close()
1910 c.setState(c.rwc, StateClosed, runHooks)
1911 }
1912 }()
1913
1914 if tlsConn, ok := c.rwc.(*tls.Conn); ok {
1915 tlsTO := c.server.tlsHandshakeTimeout()
1916 if tlsTO > 0 {
1917 dl := time.Now().Add(tlsTO)
1918 c.rwc.SetReadDeadline(dl)
1919 c.rwc.SetWriteDeadline(dl)
1920 }
1921 if err := tlsConn.HandshakeContext(ctx); err != nil {
1922
1923
1924
1925 if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) {
1926 io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
1927 re.Conn.Close()
1928 return
1929 }
1930 c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err)
1931 return
1932 }
1933
1934 if tlsTO > 0 {
1935 c.rwc.SetReadDeadline(time.Time{})
1936 c.rwc.SetWriteDeadline(time.Time{})
1937 }
1938 c.tlsState = new(tls.ConnectionState)
1939 *c.tlsState = tlsConn.ConnectionState()
1940 if proto := c.tlsState.NegotiatedProtocol; validNextProto(proto) {
1941 if fn := c.server.TLSNextProto[proto]; fn != nil {
1942 h := initALPNRequest{ctx, tlsConn, serverHandler{c.server}}
1943
1944
1945
1946 c.setState(c.rwc, StateActive, skipHooks)
1947 fn(c.server, tlsConn, h)
1948 }
1949 return
1950 }
1951 }
1952
1953
1954
1955 ctx, cancelCtx := context.WithCancel(ctx)
1956 c.cancelCtx = cancelCtx
1957 defer cancelCtx()
1958
1959 c.r = &connReader{conn: c}
1960 c.bufr = newBufioReader(c.r)
1961 c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
1962
1963 for {
1964 w, err := c.readRequest(ctx)
1965 if c.r.remain != c.server.initialReadLimitSize() {
1966
1967 c.setState(c.rwc, StateActive, runHooks)
1968 }
1969 if err != nil {
1970 const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
1971
1972 switch {
1973 case err == errTooLarge:
1974
1975
1976
1977
1978
1979 const publicErr = "431 Request Header Fields Too Large"
1980 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
1981 c.closeWriteAndWait()
1982 return
1983
1984 case isUnsupportedTEError(err):
1985
1986
1987
1988
1989 code := StatusNotImplemented
1990
1991
1992
1993 fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders)
1994 return
1995
1996 case isCommonNetReadError(err):
1997 return
1998
1999 default:
2000 if v, ok := err.(statusError); ok {
2001 fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s: %s%s%d %s: %s", v.code, StatusText(v.code), v.text, errorHeaders, v.code, StatusText(v.code), v.text)
2002 return
2003 }
2004 const publicErr = "400 Bad Request"
2005 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
2006 return
2007 }
2008 }
2009
2010
2011 req := w.req
2012 if req.expectsContinue() {
2013 if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
2014
2015 req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
2016 w.canWriteContinue.Store(true)
2017 }
2018 } else if req.Header.get("Expect") != "" {
2019 w.sendExpectationFailed()
2020 return
2021 }
2022
2023 c.curReq.Store(w)
2024
2025 if requestBodyRemains(req.Body) {
2026 registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
2027 } else {
2028 w.conn.r.startBackgroundRead()
2029 }
2030
2031
2032
2033
2034
2035
2036
2037
2038 inFlightResponse = w
2039 serverHandler{c.server}.ServeHTTP(w, w.req)
2040 inFlightResponse = nil
2041 w.cancelCtx()
2042 if c.hijacked() {
2043 return
2044 }
2045 w.finishRequest()
2046 c.rwc.SetWriteDeadline(time.Time{})
2047 if !w.shouldReuseConnection() {
2048 if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
2049 c.closeWriteAndWait()
2050 }
2051 return
2052 }
2053 c.setState(c.rwc, StateIdle, runHooks)
2054 c.curReq.Store(nil)
2055
2056 if !w.conn.server.doKeepAlives() {
2057
2058
2059
2060
2061 return
2062 }
2063
2064 if d := c.server.idleTimeout(); d != 0 {
2065 c.rwc.SetReadDeadline(time.Now().Add(d))
2066 } else {
2067 c.rwc.SetReadDeadline(time.Time{})
2068 }
2069
2070
2071
2072
2073
2074 if _, err := c.bufr.Peek(4); err != nil {
2075 return
2076 }
2077
2078 c.rwc.SetReadDeadline(time.Time{})
2079 }
2080 }
2081
2082 func (w *response) sendExpectationFailed() {
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095 w.Header().Set("Connection", "close")
2096 w.WriteHeader(StatusExpectationFailed)
2097 w.finishRequest()
2098 }
2099
2100
2101
2102 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
2103 if w.handlerDone.Load() {
2104 panic("net/http: Hijack called after ServeHTTP finished")
2105 }
2106 if w.wroteHeader {
2107 w.cw.flush()
2108 }
2109
2110 c := w.conn
2111 c.mu.Lock()
2112 defer c.mu.Unlock()
2113
2114
2115
2116 rwc, buf, err = c.hijackLocked()
2117 if err == nil {
2118 putBufioWriter(w.w)
2119 w.w = nil
2120 }
2121 return rwc, buf, err
2122 }
2123
2124 func (w *response) CloseNotify() <-chan bool {
2125 if w.handlerDone.Load() {
2126 panic("net/http: CloseNotify called after ServeHTTP finished")
2127 }
2128 return w.closeNotifyCh
2129 }
2130
2131 func registerOnHitEOF(rc io.ReadCloser, fn func()) {
2132 switch v := rc.(type) {
2133 case *expectContinueReader:
2134 registerOnHitEOF(v.readCloser, fn)
2135 case *body:
2136 v.registerOnHitEOF(fn)
2137 default:
2138 panic("unexpected type " + fmt.Sprintf("%T", rc))
2139 }
2140 }
2141
2142
2143
2144 func requestBodyRemains(rc io.ReadCloser) bool {
2145 if rc == NoBody {
2146 return false
2147 }
2148 switch v := rc.(type) {
2149 case *expectContinueReader:
2150 return requestBodyRemains(v.readCloser)
2151 case *body:
2152 return v.bodyRemains()
2153 default:
2154 panic("unexpected type " + fmt.Sprintf("%T", rc))
2155 }
2156 }
2157
2158
2159
2160
2161
2162 type HandlerFunc func(ResponseWriter, *Request)
2163
2164
2165 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
2166 f(w, r)
2167 }
2168
2169
2170
2171
2172
2173
2174
2175 func Error(w ResponseWriter, error string, code int) {
2176 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
2177 w.Header().Set("X-Content-Type-Options", "nosniff")
2178 w.WriteHeader(code)
2179 fmt.Fprintln(w, error)
2180 }
2181
2182
2183 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
2184
2185
2186
2187 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
2188
2189
2190
2191
2192
2193
2194
2195 func StripPrefix(prefix string, h Handler) Handler {
2196 if prefix == "" {
2197 return h
2198 }
2199 return HandlerFunc(func(w ResponseWriter, r *Request) {
2200 p := strings.TrimPrefix(r.URL.Path, prefix)
2201 rp := strings.TrimPrefix(r.URL.RawPath, prefix)
2202 if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
2203 r2 := new(Request)
2204 *r2 = *r
2205 r2.URL = new(url.URL)
2206 *r2.URL = *r.URL
2207 r2.URL.Path = p
2208 r2.URL.RawPath = rp
2209 h.ServeHTTP(w, r2)
2210 } else {
2211 NotFound(w, r)
2212 }
2213 })
2214 }
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226 func Redirect(w ResponseWriter, r *Request, url string, code int) {
2227 if u, err := urlpkg.Parse(url); err == nil {
2228
2229
2230
2231
2232
2233 if u.Scheme == "" && u.Host == "" {
2234 oldpath := r.URL.Path
2235 if oldpath == "" {
2236 oldpath = "/"
2237 }
2238
2239
2240 if url == "" || url[0] != '/' {
2241
2242 olddir, _ := path.Split(oldpath)
2243 url = olddir + url
2244 }
2245
2246 var query string
2247 if i := strings.Index(url, "?"); i != -1 {
2248 url, query = url[:i], url[i:]
2249 }
2250
2251
2252 trailing := strings.HasSuffix(url, "/")
2253 url = path.Clean(url)
2254 if trailing && !strings.HasSuffix(url, "/") {
2255 url += "/"
2256 }
2257 url += query
2258 }
2259 }
2260
2261 h := w.Header()
2262
2263
2264
2265
2266 _, hadCT := h["Content-Type"]
2267
2268 h.Set("Location", hexEscapeNonASCII(url))
2269 if !hadCT && (r.Method == "GET" || r.Method == "HEAD") {
2270 h.Set("Content-Type", "text/html; charset=utf-8")
2271 }
2272 w.WriteHeader(code)
2273
2274
2275 if !hadCT && r.Method == "GET" {
2276 body := "<a href=\"" + htmlEscape(url) + "\">" + StatusText(code) + "</a>.\n"
2277 fmt.Fprintln(w, body)
2278 }
2279 }
2280
2281 var htmlReplacer = strings.NewReplacer(
2282 "&", "&",
2283 "<", "<",
2284 ">", ">",
2285
2286 `"`, """,
2287
2288 "'", "'",
2289 )
2290
2291 func htmlEscape(s string) string {
2292 return htmlReplacer.Replace(s)
2293 }
2294
2295
2296 type redirectHandler struct {
2297 url string
2298 code int
2299 }
2300
2301 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
2302 Redirect(w, r, rh.url, rh.code)
2303 }
2304
2305
2306
2307
2308
2309
2310
2311 func RedirectHandler(url string, code int) Handler {
2312 return &redirectHandler{url, code}
2313 }
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432 type ServeMux struct {
2433 mu sync.RWMutex
2434 tree routingNode
2435 index routingIndex
2436 patterns []*pattern
2437 mux121 serveMux121
2438 }
2439
2440
2441 func NewServeMux() *ServeMux {
2442 return &ServeMux{}
2443 }
2444
2445
2446 var DefaultServeMux = &defaultServeMux
2447
2448 var defaultServeMux ServeMux
2449
2450
2451 func cleanPath(p string) string {
2452 if p == "" {
2453 return "/"
2454 }
2455 if p[0] != '/' {
2456 p = "/" + p
2457 }
2458 np := path.Clean(p)
2459
2460
2461 if p[len(p)-1] == '/' && np != "/" {
2462
2463 if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
2464 np = p
2465 } else {
2466 np += "/"
2467 }
2468 }
2469 return np
2470 }
2471
2472
2473 func stripHostPort(h string) string {
2474
2475 if !strings.Contains(h, ":") {
2476 return h
2477 }
2478 host, _, err := net.SplitHostPort(h)
2479 if err != nil {
2480 return h
2481 }
2482 return host
2483 }
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
2501 if use121 {
2502 return mux.mux121.findHandler(r)
2503 }
2504 h, p, _, _ := mux.findHandler(r)
2505 return h, p
2506 }
2507
2508
2509
2510
2511
2512 func (mux *ServeMux) findHandler(r *Request) (h Handler, patStr string, _ *pattern, matches []string) {
2513 var n *routingNode
2514 host := r.URL.Host
2515 escapedPath := r.URL.EscapedPath()
2516 path := escapedPath
2517
2518 if r.Method == "CONNECT" {
2519
2520
2521
2522 _, _, u := mux.matchOrRedirect(host, r.Method, path, r.URL)
2523 if u != nil {
2524 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path, nil, nil
2525 }
2526
2527
2528 n, matches, _ = mux.matchOrRedirect(r.Host, r.Method, path, nil)
2529 } else {
2530
2531
2532 host = stripHostPort(r.Host)
2533 path = cleanPath(path)
2534
2535
2536
2537 var u *url.URL
2538 n, matches, u = mux.matchOrRedirect(host, r.Method, path, r.URL)
2539 if u != nil {
2540 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path, nil, nil
2541 }
2542 if path != escapedPath {
2543
2544 patStr := ""
2545 if n != nil {
2546 patStr = n.pattern.String()
2547 }
2548 u := &url.URL{Path: path, RawQuery: r.URL.RawQuery}
2549 return RedirectHandler(u.String(), StatusMovedPermanently), patStr, nil, nil
2550 }
2551 }
2552 if n == nil {
2553
2554
2555
2556 allowedMethods := mux.matchingMethods(host, path)
2557 if len(allowedMethods) > 0 {
2558 return HandlerFunc(func(w ResponseWriter, r *Request) {
2559 w.Header().Set("Allow", strings.Join(allowedMethods, ", "))
2560 Error(w, StatusText(StatusMethodNotAllowed), StatusMethodNotAllowed)
2561 }), "", nil, nil
2562 }
2563 return NotFoundHandler(), "", nil, nil
2564 }
2565 return n.handler, n.pattern.String(), n.pattern, matches
2566 }
2567
2568
2569
2570
2571
2572
2573
2574 func (mux *ServeMux) matchOrRedirect(host, method, path string, u *url.URL) (_ *routingNode, matches []string, redirectTo *url.URL) {
2575 mux.mu.RLock()
2576 defer mux.mu.RUnlock()
2577
2578 n, matches := mux.tree.match(host, method, path)
2579
2580
2581 if !exactMatch(n, path) && u != nil {
2582
2583 path += "/"
2584 n2, _ := mux.tree.match(host, method, path)
2585 if exactMatch(n2, path) {
2586 return nil, nil, &url.URL{Path: cleanPath(u.Path) + "/", RawQuery: u.RawQuery}
2587 }
2588 }
2589 return n, matches, nil
2590 }
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618 func exactMatch(n *routingNode, path string) bool {
2619 if n == nil {
2620 return false
2621 }
2622
2623
2624
2625
2626 if !n.pattern.lastSegment().multi {
2627 return true
2628 }
2629
2630
2631
2632 if len(path) > 0 && path[len(path)-1] != '/' {
2633 return false
2634 }
2635
2636
2637
2638
2639
2640 return len(n.pattern.segments) == strings.Count(path, "/")
2641 }
2642
2643
2644 func (mux *ServeMux) matchingMethods(host, path string) []string {
2645
2646
2647 mux.mu.RLock()
2648 defer mux.mu.RUnlock()
2649 ms := map[string]bool{}
2650 mux.tree.matchingMethods(host, path, ms)
2651
2652 mux.tree.matchingMethods(host, path+"/", ms)
2653 methods := mapKeys(ms)
2654 sort.Strings(methods)
2655 return methods
2656 }
2657
2658
2659 func mapKeys[K comparable, V any](m map[K]V) []K {
2660 var ks []K
2661 for k := range m {
2662 ks = append(ks, k)
2663 }
2664 return ks
2665 }
2666
2667
2668
2669 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
2670 if r.RequestURI == "*" {
2671 if r.ProtoAtLeast(1, 1) {
2672 w.Header().Set("Connection", "close")
2673 }
2674 w.WriteHeader(StatusBadRequest)
2675 return
2676 }
2677 var h Handler
2678 if use121 {
2679 h, _ = mux.mux121.findHandler(r)
2680 } else {
2681 h, _, r.pat, r.matches = mux.findHandler(r)
2682 }
2683 h.ServeHTTP(w, r)
2684 }
2685
2686
2687
2688
2689
2690
2691
2692 func (mux *ServeMux) Handle(pattern string, handler Handler) {
2693 if use121 {
2694 mux.mux121.handle(pattern, handler)
2695 } else {
2696 mux.register(pattern, handler)
2697 }
2698 }
2699
2700
2701
2702
2703 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2704 if use121 {
2705 mux.mux121.handleFunc(pattern, handler)
2706 } else {
2707 mux.register(pattern, HandlerFunc(handler))
2708 }
2709 }
2710
2711
2712
2713 func Handle(pattern string, handler Handler) {
2714 if use121 {
2715 DefaultServeMux.mux121.handle(pattern, handler)
2716 } else {
2717 DefaultServeMux.register(pattern, handler)
2718 }
2719 }
2720
2721
2722
2723 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2724 if use121 {
2725 DefaultServeMux.mux121.handleFunc(pattern, handler)
2726 } else {
2727 DefaultServeMux.register(pattern, HandlerFunc(handler))
2728 }
2729 }
2730
2731 func (mux *ServeMux) register(pattern string, handler Handler) {
2732 if err := mux.registerErr(pattern, handler); err != nil {
2733 panic(err)
2734 }
2735 }
2736
2737 func (mux *ServeMux) registerErr(patstr string, handler Handler) error {
2738 if patstr == "" {
2739 return errors.New("http: invalid pattern")
2740 }
2741 if handler == nil {
2742 return errors.New("http: nil handler")
2743 }
2744 if f, ok := handler.(HandlerFunc); ok && f == nil {
2745 return errors.New("http: nil handler")
2746 }
2747
2748 pat, err := parsePattern(patstr)
2749 if err != nil {
2750 return fmt.Errorf("parsing %q: %w", patstr, err)
2751 }
2752
2753
2754
2755 _, file, line, ok := runtime.Caller(3)
2756 if !ok {
2757 pat.loc = "unknown location"
2758 } else {
2759 pat.loc = fmt.Sprintf("%s:%d", file, line)
2760 }
2761
2762 mux.mu.Lock()
2763 defer mux.mu.Unlock()
2764
2765 if err := mux.index.possiblyConflictingPatterns(pat, func(pat2 *pattern) error {
2766 if pat.conflictsWith(pat2) {
2767 d := describeConflict(pat, pat2)
2768 return fmt.Errorf("pattern %q (registered at %s) conflicts with pattern %q (registered at %s):\n%s",
2769 pat, pat.loc, pat2, pat2.loc, d)
2770 }
2771 return nil
2772 }); err != nil {
2773 return err
2774 }
2775 mux.tree.addPattern(pat, handler)
2776 mux.index.addPattern(pat)
2777 mux.patterns = append(mux.patterns, pat)
2778 return nil
2779 }
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792 func Serve(l net.Listener, handler Handler) error {
2793 srv := &Server{Handler: handler}
2794 return srv.Serve(l)
2795 }
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809 func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {
2810 srv := &Server{Handler: handler}
2811 return srv.ServeTLS(l, certFile, keyFile)
2812 }
2813
2814
2815
2816 type Server struct {
2817
2818
2819
2820
2821 Addr string
2822
2823 Handler Handler
2824
2825
2826
2827 DisableGeneralOptionsHandler bool
2828
2829
2830
2831
2832
2833
2834
2835
2836 TLSConfig *tls.Config
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846 ReadTimeout time.Duration
2847
2848
2849
2850
2851
2852
2853
2854 ReadHeaderTimeout time.Duration
2855
2856
2857
2858
2859
2860
2861 WriteTimeout time.Duration
2862
2863
2864
2865
2866
2867 IdleTimeout time.Duration
2868
2869
2870
2871
2872
2873
2874 MaxHeaderBytes int
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885 TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
2886
2887
2888
2889
2890 ConnState func(net.Conn, ConnState)
2891
2892
2893
2894
2895
2896 ErrorLog *log.Logger
2897
2898
2899
2900
2901
2902
2903
2904 BaseContext func(net.Listener) context.Context
2905
2906
2907
2908
2909
2910 ConnContext func(ctx context.Context, c net.Conn) context.Context
2911
2912 inShutdown atomic.Bool
2913
2914 disableKeepAlives atomic.Bool
2915 nextProtoOnce sync.Once
2916 nextProtoErr error
2917
2918 mu sync.Mutex
2919 listeners map[*net.Listener]struct{}
2920 activeConn map[*conn]struct{}
2921 onShutdown []func()
2922
2923 listenerGroup sync.WaitGroup
2924 }
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935 func (srv *Server) Close() error {
2936 srv.inShutdown.Store(true)
2937 srv.mu.Lock()
2938 defer srv.mu.Unlock()
2939 err := srv.closeListenersLocked()
2940
2941
2942
2943
2944
2945 srv.mu.Unlock()
2946 srv.listenerGroup.Wait()
2947 srv.mu.Lock()
2948
2949 for c := range srv.activeConn {
2950 c.rwc.Close()
2951 delete(srv.activeConn, c)
2952 }
2953 return err
2954 }
2955
2956
2957
2958
2959
2960
2961
2962
2963 const shutdownPollIntervalMax = 500 * time.Millisecond
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985 func (srv *Server) Shutdown(ctx context.Context) error {
2986 srv.inShutdown.Store(true)
2987
2988 srv.mu.Lock()
2989 lnerr := srv.closeListenersLocked()
2990 for _, f := range srv.onShutdown {
2991 go f()
2992 }
2993 srv.mu.Unlock()
2994 srv.listenerGroup.Wait()
2995
2996 pollIntervalBase := time.Millisecond
2997 nextPollInterval := func() time.Duration {
2998
2999 interval := pollIntervalBase + time.Duration(rand.Intn(int(pollIntervalBase/10)))
3000
3001 pollIntervalBase *= 2
3002 if pollIntervalBase > shutdownPollIntervalMax {
3003 pollIntervalBase = shutdownPollIntervalMax
3004 }
3005 return interval
3006 }
3007
3008 timer := time.NewTimer(nextPollInterval())
3009 defer timer.Stop()
3010 for {
3011 if srv.closeIdleConns() {
3012 return lnerr
3013 }
3014 select {
3015 case <-ctx.Done():
3016 return ctx.Err()
3017 case <-timer.C:
3018 timer.Reset(nextPollInterval())
3019 }
3020 }
3021 }
3022
3023
3024
3025
3026
3027
3028 func (srv *Server) RegisterOnShutdown(f func()) {
3029 srv.mu.Lock()
3030 srv.onShutdown = append(srv.onShutdown, f)
3031 srv.mu.Unlock()
3032 }
3033
3034
3035
3036 func (s *Server) closeIdleConns() bool {
3037 s.mu.Lock()
3038 defer s.mu.Unlock()
3039 quiescent := true
3040 for c := range s.activeConn {
3041 st, unixSec := c.getState()
3042
3043
3044
3045 if st == StateNew && unixSec < time.Now().Unix()-5 {
3046 st = StateIdle
3047 }
3048 if st != StateIdle || unixSec == 0 {
3049
3050
3051 quiescent = false
3052 continue
3053 }
3054 c.rwc.Close()
3055 delete(s.activeConn, c)
3056 }
3057 return quiescent
3058 }
3059
3060 func (s *Server) closeListenersLocked() error {
3061 var err error
3062 for ln := range s.listeners {
3063 if cerr := (*ln).Close(); cerr != nil && err == nil {
3064 err = cerr
3065 }
3066 }
3067 return err
3068 }
3069
3070
3071
3072 type ConnState int
3073
3074 const (
3075
3076
3077
3078
3079 StateNew ConnState = iota
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092 StateActive
3093
3094
3095
3096
3097
3098 StateIdle
3099
3100
3101
3102 StateHijacked
3103
3104
3105
3106
3107 StateClosed
3108 )
3109
3110 var stateName = map[ConnState]string{
3111 StateNew: "new",
3112 StateActive: "active",
3113 StateIdle: "idle",
3114 StateHijacked: "hijacked",
3115 StateClosed: "closed",
3116 }
3117
3118 func (c ConnState) String() string {
3119 return stateName[c]
3120 }
3121
3122
3123
3124 type serverHandler struct {
3125 srv *Server
3126 }
3127
3128 func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
3129 handler := sh.srv.Handler
3130 if handler == nil {
3131 handler = DefaultServeMux
3132 }
3133 if !sh.srv.DisableGeneralOptionsHandler && req.RequestURI == "*" && req.Method == "OPTIONS" {
3134 handler = globalOptionsHandler{}
3135 }
3136
3137 handler.ServeHTTP(rw, req)
3138 }
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149 func AllowQuerySemicolons(h Handler) Handler {
3150 return HandlerFunc(func(w ResponseWriter, r *Request) {
3151 if strings.Contains(r.URL.RawQuery, ";") {
3152 r2 := new(Request)
3153 *r2 = *r
3154 r2.URL = new(url.URL)
3155 *r2.URL = *r.URL
3156 r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&")
3157 h.ServeHTTP(w, r2)
3158 } else {
3159 h.ServeHTTP(w, r)
3160 }
3161 })
3162 }
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172 func (srv *Server) ListenAndServe() error {
3173 if srv.shuttingDown() {
3174 return ErrServerClosed
3175 }
3176 addr := srv.Addr
3177 if addr == "" {
3178 addr = ":http"
3179 }
3180 ln, err := net.Listen("tcp", addr)
3181 if err != nil {
3182 return err
3183 }
3184 return srv.Serve(ln)
3185 }
3186
3187 var testHookServerServe func(*Server, net.Listener)
3188
3189
3190
3191 func (srv *Server) shouldConfigureHTTP2ForServe() bool {
3192 if srv.TLSConfig == nil {
3193
3194
3195
3196
3197
3198
3199 return true
3200 }
3201
3202
3203
3204
3205
3206
3207
3208 return strSliceContains(srv.TLSConfig.NextProtos, http2NextProtoTLS)
3209 }
3210
3211
3212
3213 var ErrServerClosed = errors.New("http: Server closed")
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225 func (srv *Server) Serve(l net.Listener) error {
3226 if fn := testHookServerServe; fn != nil {
3227 fn(srv, l)
3228 }
3229
3230 origListener := l
3231 l = &onceCloseListener{Listener: l}
3232 defer l.Close()
3233
3234 if err := srv.setupHTTP2_Serve(); err != nil {
3235 return err
3236 }
3237
3238 if !srv.trackListener(&l, true) {
3239 return ErrServerClosed
3240 }
3241 defer srv.trackListener(&l, false)
3242
3243 baseCtx := context.Background()
3244 if srv.BaseContext != nil {
3245 baseCtx = srv.BaseContext(origListener)
3246 if baseCtx == nil {
3247 panic("BaseContext returned a nil context")
3248 }
3249 }
3250
3251 var tempDelay time.Duration
3252
3253 ctx := context.WithValue(baseCtx, ServerContextKey, srv)
3254 for {
3255 rw, err := l.Accept()
3256 if err != nil {
3257 if srv.shuttingDown() {
3258 return ErrServerClosed
3259 }
3260 if ne, ok := err.(net.Error); ok && ne.Temporary() {
3261 if tempDelay == 0 {
3262 tempDelay = 5 * time.Millisecond
3263 } else {
3264 tempDelay *= 2
3265 }
3266 if max := 1 * time.Second; tempDelay > max {
3267 tempDelay = max
3268 }
3269 srv.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
3270 time.Sleep(tempDelay)
3271 continue
3272 }
3273 return err
3274 }
3275 connCtx := ctx
3276 if cc := srv.ConnContext; cc != nil {
3277 connCtx = cc(connCtx, rw)
3278 if connCtx == nil {
3279 panic("ConnContext returned nil")
3280 }
3281 }
3282 tempDelay = 0
3283 c := srv.newConn(rw)
3284 c.setState(c.rwc, StateNew, runHooks)
3285 go c.serve(connCtx)
3286 }
3287 }
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302 func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {
3303
3304
3305 if err := srv.setupHTTP2_ServeTLS(); err != nil {
3306 return err
3307 }
3308
3309 config := cloneTLSConfig(srv.TLSConfig)
3310 if !strSliceContains(config.NextProtos, "http/1.1") {
3311 config.NextProtos = append(config.NextProtos, "http/1.1")
3312 }
3313
3314 configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil
3315 if !configHasCert || certFile != "" || keyFile != "" {
3316 var err error
3317 config.Certificates = make([]tls.Certificate, 1)
3318 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
3319 if err != nil {
3320 return err
3321 }
3322 }
3323
3324 tlsListener := tls.NewListener(l, config)
3325 return srv.Serve(tlsListener)
3326 }
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338 func (s *Server) trackListener(ln *net.Listener, add bool) bool {
3339 s.mu.Lock()
3340 defer s.mu.Unlock()
3341 if s.listeners == nil {
3342 s.listeners = make(map[*net.Listener]struct{})
3343 }
3344 if add {
3345 if s.shuttingDown() {
3346 return false
3347 }
3348 s.listeners[ln] = struct{}{}
3349 s.listenerGroup.Add(1)
3350 } else {
3351 delete(s.listeners, ln)
3352 s.listenerGroup.Done()
3353 }
3354 return true
3355 }
3356
3357 func (s *Server) trackConn(c *conn, add bool) {
3358 s.mu.Lock()
3359 defer s.mu.Unlock()
3360 if s.activeConn == nil {
3361 s.activeConn = make(map[*conn]struct{})
3362 }
3363 if add {
3364 s.activeConn[c] = struct{}{}
3365 } else {
3366 delete(s.activeConn, c)
3367 }
3368 }
3369
3370 func (s *Server) idleTimeout() time.Duration {
3371 if s.IdleTimeout != 0 {
3372 return s.IdleTimeout
3373 }
3374 return s.ReadTimeout
3375 }
3376
3377 func (s *Server) readHeaderTimeout() time.Duration {
3378 if s.ReadHeaderTimeout != 0 {
3379 return s.ReadHeaderTimeout
3380 }
3381 return s.ReadTimeout
3382 }
3383
3384 func (s *Server) doKeepAlives() bool {
3385 return !s.disableKeepAlives.Load() && !s.shuttingDown()
3386 }
3387
3388 func (s *Server) shuttingDown() bool {
3389 return s.inShutdown.Load()
3390 }
3391
3392
3393
3394
3395
3396 func (srv *Server) SetKeepAlivesEnabled(v bool) {
3397 if v {
3398 srv.disableKeepAlives.Store(false)
3399 return
3400 }
3401 srv.disableKeepAlives.Store(true)
3402
3403
3404 srv.closeIdleConns()
3405
3406
3407 }
3408
3409 func (s *Server) logf(format string, args ...any) {
3410 if s.ErrorLog != nil {
3411 s.ErrorLog.Printf(format, args...)
3412 } else {
3413 log.Printf(format, args...)
3414 }
3415 }
3416
3417
3418
3419
3420 func logf(r *Request, format string, args ...any) {
3421 s, _ := r.Context().Value(ServerContextKey).(*Server)
3422 if s != nil && s.ErrorLog != nil {
3423 s.ErrorLog.Printf(format, args...)
3424 } else {
3425 log.Printf(format, args...)
3426 }
3427 }
3428
3429
3430
3431
3432
3433
3434
3435
3436 func ListenAndServe(addr string, handler Handler) error {
3437 server := &Server{Addr: addr, Handler: handler}
3438 return server.ListenAndServe()
3439 }
3440
3441
3442
3443
3444
3445
3446 func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
3447 server := &Server{Addr: addr, Handler: handler}
3448 return server.ListenAndServeTLS(certFile, keyFile)
3449 }
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
3467 if srv.shuttingDown() {
3468 return ErrServerClosed
3469 }
3470 addr := srv.Addr
3471 if addr == "" {
3472 addr = ":https"
3473 }
3474
3475 ln, err := net.Listen("tcp", addr)
3476 if err != nil {
3477 return err
3478 }
3479
3480 defer ln.Close()
3481
3482 return srv.ServeTLS(ln, certFile, keyFile)
3483 }
3484
3485
3486
3487
3488 func (srv *Server) setupHTTP2_ServeTLS() error {
3489 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults)
3490 return srv.nextProtoErr
3491 }
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501 func (srv *Server) setupHTTP2_Serve() error {
3502 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve)
3503 return srv.nextProtoErr
3504 }
3505
3506 func (srv *Server) onceSetNextProtoDefaults_Serve() {
3507 if srv.shouldConfigureHTTP2ForServe() {
3508 srv.onceSetNextProtoDefaults()
3509 }
3510 }
3511
3512 var http2server = godebug.New("http2server")
3513
3514
3515
3516
3517 func (srv *Server) onceSetNextProtoDefaults() {
3518 if omitBundledHTTP2 {
3519 return
3520 }
3521 if http2server.Value() == "0" {
3522 http2server.IncNonDefault()
3523 return
3524 }
3525
3526
3527 if srv.TLSNextProto == nil {
3528 conf := &http2Server{
3529 NewWriteScheduler: func() http2WriteScheduler { return http2NewPriorityWriteScheduler(nil) },
3530 }
3531 srv.nextProtoErr = http2ConfigureServer(srv, conf)
3532 }
3533 }
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
3547 return &timeoutHandler{
3548 handler: h,
3549 body: msg,
3550 dt: dt,
3551 }
3552 }
3553
3554
3555
3556 var ErrHandlerTimeout = errors.New("http: Handler timeout")
3557
3558 type timeoutHandler struct {
3559 handler Handler
3560 body string
3561 dt time.Duration
3562
3563
3564
3565 testContext context.Context
3566 }
3567
3568 func (h *timeoutHandler) errorBody() string {
3569 if h.body != "" {
3570 return h.body
3571 }
3572 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
3573 }
3574
3575 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
3576 ctx := h.testContext
3577 if ctx == nil {
3578 var cancelCtx context.CancelFunc
3579 ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
3580 defer cancelCtx()
3581 }
3582 r = r.WithContext(ctx)
3583 done := make(chan struct{})
3584 tw := &timeoutWriter{
3585 w: w,
3586 h: make(Header),
3587 req: r,
3588 }
3589 panicChan := make(chan any, 1)
3590 go func() {
3591 defer func() {
3592 if p := recover(); p != nil {
3593 panicChan <- p
3594 }
3595 }()
3596 h.handler.ServeHTTP(tw, r)
3597 close(done)
3598 }()
3599 select {
3600 case p := <-panicChan:
3601 panic(p)
3602 case <-done:
3603 tw.mu.Lock()
3604 defer tw.mu.Unlock()
3605 dst := w.Header()
3606 for k, vv := range tw.h {
3607 dst[k] = vv
3608 }
3609 if !tw.wroteHeader {
3610 tw.code = StatusOK
3611 }
3612 w.WriteHeader(tw.code)
3613 w.Write(tw.wbuf.Bytes())
3614 case <-ctx.Done():
3615 tw.mu.Lock()
3616 defer tw.mu.Unlock()
3617 switch err := ctx.Err(); err {
3618 case context.DeadlineExceeded:
3619 w.WriteHeader(StatusServiceUnavailable)
3620 io.WriteString(w, h.errorBody())
3621 tw.err = ErrHandlerTimeout
3622 default:
3623 w.WriteHeader(StatusServiceUnavailable)
3624 tw.err = err
3625 }
3626 }
3627 }
3628
3629 type timeoutWriter struct {
3630 w ResponseWriter
3631 h Header
3632 wbuf bytes.Buffer
3633 req *Request
3634
3635 mu sync.Mutex
3636 err error
3637 wroteHeader bool
3638 code int
3639 }
3640
3641 var _ Pusher = (*timeoutWriter)(nil)
3642
3643
3644 func (tw *timeoutWriter) Push(target string, opts *PushOptions) error {
3645 if pusher, ok := tw.w.(Pusher); ok {
3646 return pusher.Push(target, opts)
3647 }
3648 return ErrNotSupported
3649 }
3650
3651 func (tw *timeoutWriter) Header() Header { return tw.h }
3652
3653 func (tw *timeoutWriter) Write(p []byte) (int, error) {
3654 tw.mu.Lock()
3655 defer tw.mu.Unlock()
3656 if tw.err != nil {
3657 return 0, tw.err
3658 }
3659 if !tw.wroteHeader {
3660 tw.writeHeaderLocked(StatusOK)
3661 }
3662 return tw.wbuf.Write(p)
3663 }
3664
3665 func (tw *timeoutWriter) writeHeaderLocked(code int) {
3666 checkWriteHeaderCode(code)
3667
3668 switch {
3669 case tw.err != nil:
3670 return
3671 case tw.wroteHeader:
3672 if tw.req != nil {
3673 caller := relevantCaller()
3674 logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
3675 }
3676 default:
3677 tw.wroteHeader = true
3678 tw.code = code
3679 }
3680 }
3681
3682 func (tw *timeoutWriter) WriteHeader(code int) {
3683 tw.mu.Lock()
3684 defer tw.mu.Unlock()
3685 tw.writeHeaderLocked(code)
3686 }
3687
3688
3689
3690 type onceCloseListener struct {
3691 net.Listener
3692 once sync.Once
3693 closeErr error
3694 }
3695
3696 func (oc *onceCloseListener) Close() error {
3697 oc.once.Do(oc.close)
3698 return oc.closeErr
3699 }
3700
3701 func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() }
3702
3703
3704 type globalOptionsHandler struct{}
3705
3706 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
3707 w.Header().Set("Content-Length", "0")
3708 if r.ContentLength != 0 {
3709
3710
3711
3712
3713
3714 mb := MaxBytesReader(w, r.Body, 4<<10)
3715 io.Copy(io.Discard, mb)
3716 }
3717 }
3718
3719
3720
3721
3722 type initALPNRequest struct {
3723 ctx context.Context
3724 c *tls.Conn
3725 h serverHandler
3726 }
3727
3728
3729
3730
3731
3732 func (h initALPNRequest) BaseContext() context.Context { return h.ctx }
3733
3734 func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
3735 if req.TLS == nil {
3736 req.TLS = &tls.ConnectionState{}
3737 *req.TLS = h.c.ConnectionState()
3738 }
3739 if req.Body == nil {
3740 req.Body = NoBody
3741 }
3742 if req.RemoteAddr == "" {
3743 req.RemoteAddr = h.c.RemoteAddr().String()
3744 }
3745 h.h.ServeHTTP(rw, req)
3746 }
3747
3748
3749 type loggingConn struct {
3750 name string
3751 net.Conn
3752 }
3753
3754 var (
3755 uniqNameMu sync.Mutex
3756 uniqNameNext = make(map[string]int)
3757 )
3758
3759 func newLoggingConn(baseName string, c net.Conn) net.Conn {
3760 uniqNameMu.Lock()
3761 defer uniqNameMu.Unlock()
3762 uniqNameNext[baseName]++
3763 return &loggingConn{
3764 name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
3765 Conn: c,
3766 }
3767 }
3768
3769 func (c *loggingConn) Write(p []byte) (n int, err error) {
3770 log.Printf("%s.Write(%d) = ....", c.name, len(p))
3771 n, err = c.Conn.Write(p)
3772 log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
3773 return
3774 }
3775
3776 func (c *loggingConn) Read(p []byte) (n int, err error) {
3777 log.Printf("%s.Read(%d) = ....", c.name, len(p))
3778 n, err = c.Conn.Read(p)
3779 log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
3780 return
3781 }
3782
3783 func (c *loggingConn) Close() (err error) {
3784 log.Printf("%s.Close() = ...", c.name)
3785 err = c.Conn.Close()
3786 log.Printf("%s.Close() = %v", c.name, err)
3787 return
3788 }
3789
3790
3791
3792
3793 type checkConnErrorWriter struct {
3794 c *conn
3795 }
3796
3797 func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
3798 n, err = w.c.rwc.Write(p)
3799 if err != nil && w.c.werr == nil {
3800 w.c.werr = err
3801 w.c.cancelCtx()
3802 }
3803 return
3804 }
3805
3806 func numLeadingCRorLF(v []byte) (n int) {
3807 for _, b := range v {
3808 if b == '\r' || b == '\n' {
3809 n++
3810 continue
3811 }
3812 break
3813 }
3814 return
3815 }
3816
3817 func strSliceContains(ss []string, s string) bool {
3818 for _, v := range ss {
3819 if v == s {
3820 return true
3821 }
3822 }
3823 return false
3824 }
3825
3826
3827
3828 func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool {
3829 switch string(hdr[:]) {
3830 case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
3831 return true
3832 }
3833 return false
3834 }
3835
3836
3837 func MaxBytesHandler(h Handler, n int64) Handler {
3838 return HandlerFunc(func(w ResponseWriter, r *Request) {
3839 r2 := *r
3840 r2.Body = MaxBytesReader(w, r.Body, n)
3841 h.ServeHTTP(w, &r2)
3842 })
3843 }
3844
View as plain text