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
1371
1372
1373
1374
1375 if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF.Load() {
1376 w.closeAfterReply = true
1377 }
1378
1379
1380
1381
1382
1383
1384
1385
1386 if w.req.ContentLength != 0 && !w.closeAfterReply && !w.fullDuplex {
1387 var discard, tooBig bool
1388
1389 switch bdy := w.req.Body.(type) {
1390 case *expectContinueReader:
1391 if bdy.resp.wroteContinue {
1392 discard = true
1393 }
1394 case *body:
1395 bdy.mu.Lock()
1396 switch {
1397 case bdy.closed:
1398 if !bdy.sawEOF {
1399
1400 w.closeAfterReply = true
1401 }
1402 case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes:
1403 tooBig = true
1404 default:
1405 discard = true
1406 }
1407 bdy.mu.Unlock()
1408 default:
1409 discard = true
1410 }
1411
1412 if discard {
1413 _, err := io.CopyN(io.Discard, w.reqBody, maxPostHandlerReadBytes+1)
1414 switch err {
1415 case nil:
1416
1417 tooBig = true
1418 case ErrBodyReadAfterClose:
1419
1420 case io.EOF:
1421
1422 err = w.reqBody.Close()
1423 if err != nil {
1424 w.closeAfterReply = true
1425 }
1426 default:
1427
1428
1429
1430 w.closeAfterReply = true
1431 }
1432 }
1433
1434 if tooBig {
1435 w.requestTooLarge()
1436 delHeader("Connection")
1437 setHeader.connection = "close"
1438 }
1439 }
1440
1441 code := w.status
1442 if bodyAllowedForStatus(code) {
1443
1444 _, haveType := header["Content-Type"]
1445
1446
1447
1448 ce := header.Get("Content-Encoding")
1449 hasCE := len(ce) > 0
1450 if !hasCE && !haveType && !hasTE && len(p) > 0 {
1451 setHeader.contentType = DetectContentType(p)
1452 }
1453 } else {
1454 for _, k := range suppressedHeaders(code) {
1455 delHeader(k)
1456 }
1457 }
1458
1459 if !header.has("Date") {
1460 setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now())
1461 }
1462
1463 if hasCL && hasTE && te != "identity" {
1464
1465
1466 w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
1467 te, w.contentLength)
1468 delHeader("Content-Length")
1469 hasCL = false
1470 }
1471
1472 if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) || code == StatusNoContent {
1473
1474 delHeader("Transfer-Encoding")
1475 } else if hasCL {
1476
1477 delHeader("Transfer-Encoding")
1478 } else if w.req.ProtoAtLeast(1, 1) {
1479
1480
1481
1482
1483
1484 if hasTE && te == "identity" {
1485 cw.chunking = false
1486 w.closeAfterReply = true
1487 delHeader("Transfer-Encoding")
1488 } else {
1489
1490
1491 cw.chunking = true
1492 setHeader.transferEncoding = "chunked"
1493 if hasTE && te == "chunked" {
1494
1495 delHeader("Transfer-Encoding")
1496 }
1497 }
1498 } else {
1499
1500
1501
1502 w.closeAfterReply = true
1503 delHeader("Transfer-Encoding")
1504 }
1505
1506
1507 if cw.chunking {
1508 delHeader("Content-Length")
1509 }
1510 if !w.req.ProtoAtLeast(1, 0) {
1511 return
1512 }
1513
1514
1515
1516
1517 delConnectionHeader := w.closeAfterReply &&
1518 (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) &&
1519 !isProtocolSwitchResponse(w.status, header)
1520 if delConnectionHeader {
1521 delHeader("Connection")
1522 if w.req.ProtoAtLeast(1, 1) {
1523 setHeader.connection = "close"
1524 }
1525 }
1526
1527 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
1528 cw.header.WriteSubset(w.conn.bufw, excludeHeader)
1529 setHeader.Write(w.conn.bufw)
1530 w.conn.bufw.Write(crlf)
1531 }
1532
1533
1534
1535 func foreachHeaderElement(v string, fn func(string)) {
1536 v = textproto.TrimString(v)
1537 if v == "" {
1538 return
1539 }
1540 if !strings.Contains(v, ",") {
1541 fn(v)
1542 return
1543 }
1544 for _, f := range strings.Split(v, ",") {
1545 if f = textproto.TrimString(f); f != "" {
1546 fn(f)
1547 }
1548 }
1549 }
1550
1551
1552
1553
1554
1555 func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte) {
1556 if is11 {
1557 bw.WriteString("HTTP/1.1 ")
1558 } else {
1559 bw.WriteString("HTTP/1.0 ")
1560 }
1561 if text := StatusText(code); text != "" {
1562 bw.Write(strconv.AppendInt(scratch[:0], int64(code), 10))
1563 bw.WriteByte(' ')
1564 bw.WriteString(text)
1565 bw.WriteString("\r\n")
1566 } else {
1567
1568 fmt.Fprintf(bw, "%03d status code %d\r\n", code, code)
1569 }
1570 }
1571
1572
1573
1574 func (w *response) bodyAllowed() bool {
1575 if !w.wroteHeader {
1576 panic("")
1577 }
1578 return bodyAllowedForStatus(w.status)
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
1611
1612
1613
1614
1615 func (w *response) Write(data []byte) (n int, err error) {
1616 return w.write(len(data), data, "")
1617 }
1618
1619 func (w *response) WriteString(data string) (n int, err error) {
1620 return w.write(len(data), nil, data)
1621 }
1622
1623
1624 func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
1625 if w.conn.hijacked() {
1626 if lenData > 0 {
1627 caller := relevantCaller()
1628 w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1629 }
1630 return 0, ErrHijacked
1631 }
1632
1633 if w.canWriteContinue.Load() {
1634
1635
1636
1637
1638 w.writeContinueMu.Lock()
1639 w.canWriteContinue.Store(false)
1640 w.writeContinueMu.Unlock()
1641 }
1642
1643 if !w.wroteHeader {
1644 w.WriteHeader(StatusOK)
1645 }
1646 if lenData == 0 {
1647 return 0, nil
1648 }
1649 if !w.bodyAllowed() {
1650 return 0, ErrBodyNotAllowed
1651 }
1652
1653 w.written += int64(lenData)
1654 if w.contentLength != -1 && w.written > w.contentLength {
1655 return 0, ErrContentLength
1656 }
1657 if dataB != nil {
1658 return w.w.Write(dataB)
1659 } else {
1660 return w.w.WriteString(dataS)
1661 }
1662 }
1663
1664 func (w *response) finishRequest() {
1665 w.handlerDone.Store(true)
1666
1667 if !w.wroteHeader {
1668 w.WriteHeader(StatusOK)
1669 }
1670
1671 w.w.Flush()
1672 putBufioWriter(w.w)
1673 w.cw.close()
1674 w.conn.bufw.Flush()
1675
1676 w.conn.r.abortPendingRead()
1677
1678
1679
1680 w.reqBody.Close()
1681
1682 if w.req.MultipartForm != nil {
1683 w.req.MultipartForm.RemoveAll()
1684 }
1685 }
1686
1687
1688
1689 func (w *response) shouldReuseConnection() bool {
1690 if w.closeAfterReply {
1691
1692
1693
1694 return false
1695 }
1696
1697 if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
1698
1699 return false
1700 }
1701
1702
1703
1704 if w.conn.werr != nil {
1705 return false
1706 }
1707
1708 if w.closedRequestBodyEarly() {
1709 return false
1710 }
1711
1712 return true
1713 }
1714
1715 func (w *response) closedRequestBodyEarly() bool {
1716 body, ok := w.req.Body.(*body)
1717 return ok && body.didEarlyClose()
1718 }
1719
1720 func (w *response) Flush() {
1721 w.FlushError()
1722 }
1723
1724 func (w *response) FlushError() error {
1725 if !w.wroteHeader {
1726 w.WriteHeader(StatusOK)
1727 }
1728 err := w.w.Flush()
1729 e2 := w.cw.flush()
1730 if err == nil {
1731 err = e2
1732 }
1733 return err
1734 }
1735
1736 func (c *conn) finalFlush() {
1737 if c.bufr != nil {
1738
1739
1740 putBufioReader(c.bufr)
1741 c.bufr = nil
1742 }
1743
1744 if c.bufw != nil {
1745 c.bufw.Flush()
1746
1747
1748 putBufioWriter(c.bufw)
1749 c.bufw = nil
1750 }
1751 }
1752
1753
1754 func (c *conn) close() {
1755 c.finalFlush()
1756 c.rwc.Close()
1757 }
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770 var rstAvoidanceDelay = 500 * time.Millisecond
1771
1772 type closeWriter interface {
1773 CloseWrite() error
1774 }
1775
1776 var _ closeWriter = (*net.TCPConn)(nil)
1777
1778
1779
1780
1781
1782
1783
1784 func (c *conn) closeWriteAndWait() {
1785 c.finalFlush()
1786 if tcp, ok := c.rwc.(closeWriter); ok {
1787 tcp.CloseWrite()
1788 }
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810 time.Sleep(rstAvoidanceDelay)
1811 }
1812
1813
1814
1815
1816 func validNextProto(proto string) bool {
1817 switch proto {
1818 case "", "http/1.1", "http/1.0":
1819 return false
1820 }
1821 return true
1822 }
1823
1824 const (
1825 runHooks = true
1826 skipHooks = false
1827 )
1828
1829 func (c *conn) setState(nc net.Conn, state ConnState, runHook bool) {
1830 srv := c.server
1831 switch state {
1832 case StateNew:
1833 srv.trackConn(c, true)
1834 case StateHijacked, StateClosed:
1835 srv.trackConn(c, false)
1836 }
1837 if state > 0xff || state < 0 {
1838 panic("internal error")
1839 }
1840 packedState := uint64(time.Now().Unix()<<8) | uint64(state)
1841 c.curState.Store(packedState)
1842 if !runHook {
1843 return
1844 }
1845 if hook := srv.ConnState; hook != nil {
1846 hook(nc, state)
1847 }
1848 }
1849
1850 func (c *conn) getState() (state ConnState, unixSec int64) {
1851 packedState := c.curState.Load()
1852 return ConnState(packedState & 0xff), int64(packedState >> 8)
1853 }
1854
1855
1856
1857
1858 func badRequestError(e string) error { return statusError{StatusBadRequest, e} }
1859
1860
1861
1862 type statusError struct {
1863 code int
1864 text string
1865 }
1866
1867 func (e statusError) Error() string { return StatusText(e.code) + ": " + e.text }
1868
1869
1870
1871
1872
1873 var ErrAbortHandler = errors.New("net/http: abort Handler")
1874
1875
1876
1877
1878
1879 func isCommonNetReadError(err error) bool {
1880 if err == io.EOF {
1881 return true
1882 }
1883 if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
1884 return true
1885 }
1886 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
1887 return true
1888 }
1889 return false
1890 }
1891
1892
1893 func (c *conn) serve(ctx context.Context) {
1894 if ra := c.rwc.RemoteAddr(); ra != nil {
1895 c.remoteAddr = ra.String()
1896 }
1897 ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr())
1898 var inFlightResponse *response
1899 defer func() {
1900 if err := recover(); err != nil && err != ErrAbortHandler {
1901 const size = 64 << 10
1902 buf := make([]byte, size)
1903 buf = buf[:runtime.Stack(buf, false)]
1904 c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
1905 }
1906 if inFlightResponse != nil {
1907 inFlightResponse.cancelCtx()
1908 }
1909 if !c.hijacked() {
1910 if inFlightResponse != nil {
1911 inFlightResponse.conn.r.abortPendingRead()
1912 inFlightResponse.reqBody.Close()
1913 }
1914 c.close()
1915 c.setState(c.rwc, StateClosed, runHooks)
1916 }
1917 }()
1918
1919 if tlsConn, ok := c.rwc.(*tls.Conn); ok {
1920 tlsTO := c.server.tlsHandshakeTimeout()
1921 if tlsTO > 0 {
1922 dl := time.Now().Add(tlsTO)
1923 c.rwc.SetReadDeadline(dl)
1924 c.rwc.SetWriteDeadline(dl)
1925 }
1926 if err := tlsConn.HandshakeContext(ctx); err != nil {
1927
1928
1929
1930 if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) {
1931 io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
1932 re.Conn.Close()
1933 return
1934 }
1935 c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err)
1936 return
1937 }
1938
1939 if tlsTO > 0 {
1940 c.rwc.SetReadDeadline(time.Time{})
1941 c.rwc.SetWriteDeadline(time.Time{})
1942 }
1943 c.tlsState = new(tls.ConnectionState)
1944 *c.tlsState = tlsConn.ConnectionState()
1945 if proto := c.tlsState.NegotiatedProtocol; validNextProto(proto) {
1946 if fn := c.server.TLSNextProto[proto]; fn != nil {
1947 h := initALPNRequest{ctx, tlsConn, serverHandler{c.server}}
1948
1949
1950
1951 c.setState(c.rwc, StateActive, skipHooks)
1952 fn(c.server, tlsConn, h)
1953 }
1954 return
1955 }
1956 }
1957
1958
1959
1960 ctx, cancelCtx := context.WithCancel(ctx)
1961 c.cancelCtx = cancelCtx
1962 defer cancelCtx()
1963
1964 c.r = &connReader{conn: c}
1965 c.bufr = newBufioReader(c.r)
1966 c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
1967
1968 for {
1969 w, err := c.readRequest(ctx)
1970 if c.r.remain != c.server.initialReadLimitSize() {
1971
1972 c.setState(c.rwc, StateActive, runHooks)
1973 }
1974 if err != nil {
1975 const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
1976
1977 switch {
1978 case err == errTooLarge:
1979
1980
1981
1982
1983
1984 const publicErr = "431 Request Header Fields Too Large"
1985 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
1986 c.closeWriteAndWait()
1987 return
1988
1989 case isUnsupportedTEError(err):
1990
1991
1992
1993
1994 code := StatusNotImplemented
1995
1996
1997
1998 fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders)
1999 return
2000
2001 case isCommonNetReadError(err):
2002 return
2003
2004 default:
2005 if v, ok := err.(statusError); ok {
2006 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)
2007 return
2008 }
2009 const publicErr = "400 Bad Request"
2010 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
2011 return
2012 }
2013 }
2014
2015
2016 req := w.req
2017 if req.expectsContinue() {
2018 if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
2019
2020 req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
2021 w.canWriteContinue.Store(true)
2022 }
2023 } else if req.Header.get("Expect") != "" {
2024 w.sendExpectationFailed()
2025 return
2026 }
2027
2028 c.curReq.Store(w)
2029
2030 if requestBodyRemains(req.Body) {
2031 registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
2032 } else {
2033 w.conn.r.startBackgroundRead()
2034 }
2035
2036
2037
2038
2039
2040
2041
2042
2043 inFlightResponse = w
2044 serverHandler{c.server}.ServeHTTP(w, w.req)
2045 inFlightResponse = nil
2046 w.cancelCtx()
2047 if c.hijacked() {
2048 return
2049 }
2050 w.finishRequest()
2051 c.rwc.SetWriteDeadline(time.Time{})
2052 if !w.shouldReuseConnection() {
2053 if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
2054 c.closeWriteAndWait()
2055 }
2056 return
2057 }
2058 c.setState(c.rwc, StateIdle, runHooks)
2059 c.curReq.Store(nil)
2060
2061 if !w.conn.server.doKeepAlives() {
2062
2063
2064
2065
2066 return
2067 }
2068
2069 if d := c.server.idleTimeout(); d != 0 {
2070 c.rwc.SetReadDeadline(time.Now().Add(d))
2071 } else {
2072 c.rwc.SetReadDeadline(time.Time{})
2073 }
2074
2075
2076
2077
2078
2079 if _, err := c.bufr.Peek(4); err != nil {
2080 return
2081 }
2082
2083 c.rwc.SetReadDeadline(time.Time{})
2084 }
2085 }
2086
2087 func (w *response) sendExpectationFailed() {
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100 w.Header().Set("Connection", "close")
2101 w.WriteHeader(StatusExpectationFailed)
2102 w.finishRequest()
2103 }
2104
2105
2106
2107 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
2108 if w.handlerDone.Load() {
2109 panic("net/http: Hijack called after ServeHTTP finished")
2110 }
2111 if w.wroteHeader {
2112 w.cw.flush()
2113 }
2114
2115 c := w.conn
2116 c.mu.Lock()
2117 defer c.mu.Unlock()
2118
2119
2120
2121 rwc, buf, err = c.hijackLocked()
2122 if err == nil {
2123 putBufioWriter(w.w)
2124 w.w = nil
2125 }
2126 return rwc, buf, err
2127 }
2128
2129 func (w *response) CloseNotify() <-chan bool {
2130 if w.handlerDone.Load() {
2131 panic("net/http: CloseNotify called after ServeHTTP finished")
2132 }
2133 return w.closeNotifyCh
2134 }
2135
2136 func registerOnHitEOF(rc io.ReadCloser, fn func()) {
2137 switch v := rc.(type) {
2138 case *expectContinueReader:
2139 registerOnHitEOF(v.readCloser, fn)
2140 case *body:
2141 v.registerOnHitEOF(fn)
2142 default:
2143 panic("unexpected type " + fmt.Sprintf("%T", rc))
2144 }
2145 }
2146
2147
2148
2149 func requestBodyRemains(rc io.ReadCloser) bool {
2150 if rc == NoBody {
2151 return false
2152 }
2153 switch v := rc.(type) {
2154 case *expectContinueReader:
2155 return requestBodyRemains(v.readCloser)
2156 case *body:
2157 return v.bodyRemains()
2158 default:
2159 panic("unexpected type " + fmt.Sprintf("%T", rc))
2160 }
2161 }
2162
2163
2164
2165
2166
2167 type HandlerFunc func(ResponseWriter, *Request)
2168
2169
2170 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
2171 f(w, r)
2172 }
2173
2174
2175
2176
2177
2178
2179
2180 func Error(w ResponseWriter, error string, code int) {
2181 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
2182 w.Header().Set("X-Content-Type-Options", "nosniff")
2183 w.WriteHeader(code)
2184 fmt.Fprintln(w, error)
2185 }
2186
2187
2188 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
2189
2190
2191
2192 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
2193
2194
2195
2196
2197
2198
2199
2200 func StripPrefix(prefix string, h Handler) Handler {
2201 if prefix == "" {
2202 return h
2203 }
2204 return HandlerFunc(func(w ResponseWriter, r *Request) {
2205 p := strings.TrimPrefix(r.URL.Path, prefix)
2206 rp := strings.TrimPrefix(r.URL.RawPath, prefix)
2207 if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
2208 r2 := new(Request)
2209 *r2 = *r
2210 r2.URL = new(url.URL)
2211 *r2.URL = *r.URL
2212 r2.URL.Path = p
2213 r2.URL.RawPath = rp
2214 h.ServeHTTP(w, r2)
2215 } else {
2216 NotFound(w, r)
2217 }
2218 })
2219 }
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231 func Redirect(w ResponseWriter, r *Request, url string, code int) {
2232 if u, err := urlpkg.Parse(url); err == nil {
2233
2234
2235
2236
2237
2238 if u.Scheme == "" && u.Host == "" {
2239 oldpath := r.URL.Path
2240 if oldpath == "" {
2241 oldpath = "/"
2242 }
2243
2244
2245 if url == "" || url[0] != '/' {
2246
2247 olddir, _ := path.Split(oldpath)
2248 url = olddir + url
2249 }
2250
2251 var query string
2252 if i := strings.Index(url, "?"); i != -1 {
2253 url, query = url[:i], url[i:]
2254 }
2255
2256
2257 trailing := strings.HasSuffix(url, "/")
2258 url = path.Clean(url)
2259 if trailing && !strings.HasSuffix(url, "/") {
2260 url += "/"
2261 }
2262 url += query
2263 }
2264 }
2265
2266 h := w.Header()
2267
2268
2269
2270
2271 _, hadCT := h["Content-Type"]
2272
2273 h.Set("Location", hexEscapeNonASCII(url))
2274 if !hadCT && (r.Method == "GET" || r.Method == "HEAD") {
2275 h.Set("Content-Type", "text/html; charset=utf-8")
2276 }
2277 w.WriteHeader(code)
2278
2279
2280 if !hadCT && r.Method == "GET" {
2281 body := "<a href=\"" + htmlEscape(url) + "\">" + StatusText(code) + "</a>.\n"
2282 fmt.Fprintln(w, body)
2283 }
2284 }
2285
2286 var htmlReplacer = strings.NewReplacer(
2287 "&", "&",
2288 "<", "<",
2289 ">", ">",
2290
2291 `"`, """,
2292
2293 "'", "'",
2294 )
2295
2296 func htmlEscape(s string) string {
2297 return htmlReplacer.Replace(s)
2298 }
2299
2300
2301 type redirectHandler struct {
2302 url string
2303 code int
2304 }
2305
2306 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
2307 Redirect(w, r, rh.url, rh.code)
2308 }
2309
2310
2311
2312
2313
2314
2315
2316 func RedirectHandler(url string, code int) Handler {
2317 return &redirectHandler{url, code}
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
2433
2434
2435
2436
2437 type ServeMux struct {
2438 mu sync.RWMutex
2439 tree routingNode
2440 index routingIndex
2441 patterns []*pattern
2442 mux121 serveMux121
2443 }
2444
2445
2446 func NewServeMux() *ServeMux {
2447 return &ServeMux{}
2448 }
2449
2450
2451 var DefaultServeMux = &defaultServeMux
2452
2453 var defaultServeMux ServeMux
2454
2455
2456 func cleanPath(p string) string {
2457 if p == "" {
2458 return "/"
2459 }
2460 if p[0] != '/' {
2461 p = "/" + p
2462 }
2463 np := path.Clean(p)
2464
2465
2466 if p[len(p)-1] == '/' && np != "/" {
2467
2468 if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
2469 np = p
2470 } else {
2471 np += "/"
2472 }
2473 }
2474 return np
2475 }
2476
2477
2478 func stripHostPort(h string) string {
2479
2480 if !strings.Contains(h, ":") {
2481 return h
2482 }
2483 host, _, err := net.SplitHostPort(h)
2484 if err != nil {
2485 return h
2486 }
2487 return host
2488 }
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
2506 if use121 {
2507 return mux.mux121.findHandler(r)
2508 }
2509 h, p, _, _ := mux.findHandler(r)
2510 return h, p
2511 }
2512
2513
2514
2515
2516
2517 func (mux *ServeMux) findHandler(r *Request) (h Handler, patStr string, _ *pattern, matches []string) {
2518 var n *routingNode
2519 host := r.URL.Host
2520 escapedPath := r.URL.EscapedPath()
2521 path := escapedPath
2522
2523 if r.Method == "CONNECT" {
2524
2525
2526
2527 _, _, u := mux.matchOrRedirect(host, r.Method, path, r.URL)
2528 if u != nil {
2529 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path, nil, nil
2530 }
2531
2532
2533 n, matches, _ = mux.matchOrRedirect(r.Host, r.Method, path, nil)
2534 } else {
2535
2536
2537 host = stripHostPort(r.Host)
2538 path = cleanPath(path)
2539
2540
2541
2542 var u *url.URL
2543 n, matches, u = mux.matchOrRedirect(host, r.Method, path, r.URL)
2544 if u != nil {
2545 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path, nil, nil
2546 }
2547 if path != escapedPath {
2548
2549 patStr := ""
2550 if n != nil {
2551 patStr = n.pattern.String()
2552 }
2553 u := &url.URL{Path: path, RawQuery: r.URL.RawQuery}
2554 return RedirectHandler(u.String(), StatusMovedPermanently), patStr, nil, nil
2555 }
2556 }
2557 if n == nil {
2558
2559
2560
2561 allowedMethods := mux.matchingMethods(host, path)
2562 if len(allowedMethods) > 0 {
2563 return HandlerFunc(func(w ResponseWriter, r *Request) {
2564 w.Header().Set("Allow", strings.Join(allowedMethods, ", "))
2565 Error(w, StatusText(StatusMethodNotAllowed), StatusMethodNotAllowed)
2566 }), "", nil, nil
2567 }
2568 return NotFoundHandler(), "", nil, nil
2569 }
2570 return n.handler, n.pattern.String(), n.pattern, matches
2571 }
2572
2573
2574
2575
2576
2577
2578
2579 func (mux *ServeMux) matchOrRedirect(host, method, path string, u *url.URL) (_ *routingNode, matches []string, redirectTo *url.URL) {
2580 mux.mu.RLock()
2581 defer mux.mu.RUnlock()
2582
2583 n, matches := mux.tree.match(host, method, path)
2584
2585
2586 if !exactMatch(n, path) && u != nil {
2587
2588 path += "/"
2589 n2, _ := mux.tree.match(host, method, path)
2590 if exactMatch(n2, path) {
2591 return nil, nil, &url.URL{Path: cleanPath(u.Path) + "/", RawQuery: u.RawQuery}
2592 }
2593 }
2594 return n, matches, nil
2595 }
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623 func exactMatch(n *routingNode, path string) bool {
2624 if n == nil {
2625 return false
2626 }
2627
2628
2629
2630
2631 if !n.pattern.lastSegment().multi {
2632 return true
2633 }
2634
2635
2636
2637 if len(path) > 0 && path[len(path)-1] != '/' {
2638 return false
2639 }
2640
2641
2642
2643
2644
2645 return len(n.pattern.segments) == strings.Count(path, "/")
2646 }
2647
2648
2649 func (mux *ServeMux) matchingMethods(host, path string) []string {
2650
2651
2652 mux.mu.RLock()
2653 defer mux.mu.RUnlock()
2654 ms := map[string]bool{}
2655 mux.tree.matchingMethods(host, path, ms)
2656
2657 mux.tree.matchingMethods(host, path+"/", ms)
2658 methods := mapKeys(ms)
2659 sort.Strings(methods)
2660 return methods
2661 }
2662
2663
2664 func mapKeys[K comparable, V any](m map[K]V) []K {
2665 var ks []K
2666 for k := range m {
2667 ks = append(ks, k)
2668 }
2669 return ks
2670 }
2671
2672
2673
2674 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
2675 if r.RequestURI == "*" {
2676 if r.ProtoAtLeast(1, 1) {
2677 w.Header().Set("Connection", "close")
2678 }
2679 w.WriteHeader(StatusBadRequest)
2680 return
2681 }
2682 var h Handler
2683 if use121 {
2684 h, _ = mux.mux121.findHandler(r)
2685 } else {
2686 h, _, r.pat, r.matches = mux.findHandler(r)
2687 }
2688 h.ServeHTTP(w, r)
2689 }
2690
2691
2692
2693
2694
2695
2696
2697 func (mux *ServeMux) Handle(pattern string, handler Handler) {
2698 if use121 {
2699 mux.mux121.handle(pattern, handler)
2700 } else {
2701 mux.register(pattern, handler)
2702 }
2703 }
2704
2705
2706
2707
2708 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2709 if use121 {
2710 mux.mux121.handleFunc(pattern, handler)
2711 } else {
2712 mux.register(pattern, HandlerFunc(handler))
2713 }
2714 }
2715
2716
2717
2718 func Handle(pattern string, handler Handler) {
2719 if use121 {
2720 DefaultServeMux.mux121.handle(pattern, handler)
2721 } else {
2722 DefaultServeMux.register(pattern, handler)
2723 }
2724 }
2725
2726
2727
2728 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2729 if use121 {
2730 DefaultServeMux.mux121.handleFunc(pattern, handler)
2731 } else {
2732 DefaultServeMux.register(pattern, HandlerFunc(handler))
2733 }
2734 }
2735
2736 func (mux *ServeMux) register(pattern string, handler Handler) {
2737 if err := mux.registerErr(pattern, handler); err != nil {
2738 panic(err)
2739 }
2740 }
2741
2742 func (mux *ServeMux) registerErr(patstr string, handler Handler) error {
2743 if patstr == "" {
2744 return errors.New("http: invalid pattern")
2745 }
2746 if handler == nil {
2747 return errors.New("http: nil handler")
2748 }
2749 if f, ok := handler.(HandlerFunc); ok && f == nil {
2750 return errors.New("http: nil handler")
2751 }
2752
2753 pat, err := parsePattern(patstr)
2754 if err != nil {
2755 return fmt.Errorf("parsing %q: %w", patstr, err)
2756 }
2757
2758
2759
2760 _, file, line, ok := runtime.Caller(3)
2761 if !ok {
2762 pat.loc = "unknown location"
2763 } else {
2764 pat.loc = fmt.Sprintf("%s:%d", file, line)
2765 }
2766
2767 mux.mu.Lock()
2768 defer mux.mu.Unlock()
2769
2770 if err := mux.index.possiblyConflictingPatterns(pat, func(pat2 *pattern) error {
2771 if pat.conflictsWith(pat2) {
2772 d := describeConflict(pat, pat2)
2773 return fmt.Errorf("pattern %q (registered at %s) conflicts with pattern %q (registered at %s):\n%s",
2774 pat, pat.loc, pat2, pat2.loc, d)
2775 }
2776 return nil
2777 }); err != nil {
2778 return err
2779 }
2780 mux.tree.addPattern(pat, handler)
2781 mux.index.addPattern(pat)
2782 mux.patterns = append(mux.patterns, pat)
2783 return nil
2784 }
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797 func Serve(l net.Listener, handler Handler) error {
2798 srv := &Server{Handler: handler}
2799 return srv.Serve(l)
2800 }
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814 func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {
2815 srv := &Server{Handler: handler}
2816 return srv.ServeTLS(l, certFile, keyFile)
2817 }
2818
2819
2820
2821 type Server struct {
2822
2823
2824
2825
2826 Addr string
2827
2828 Handler Handler
2829
2830
2831
2832 DisableGeneralOptionsHandler bool
2833
2834
2835
2836
2837
2838
2839
2840
2841 TLSConfig *tls.Config
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851 ReadTimeout time.Duration
2852
2853
2854
2855
2856
2857
2858
2859 ReadHeaderTimeout time.Duration
2860
2861
2862
2863
2864
2865
2866 WriteTimeout time.Duration
2867
2868
2869
2870
2871
2872 IdleTimeout time.Duration
2873
2874
2875
2876
2877
2878
2879 MaxHeaderBytes int
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890 TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
2891
2892
2893
2894
2895 ConnState func(net.Conn, ConnState)
2896
2897
2898
2899
2900
2901 ErrorLog *log.Logger
2902
2903
2904
2905
2906
2907
2908
2909 BaseContext func(net.Listener) context.Context
2910
2911
2912
2913
2914
2915 ConnContext func(ctx context.Context, c net.Conn) context.Context
2916
2917 inShutdown atomic.Bool
2918
2919 disableKeepAlives atomic.Bool
2920 nextProtoOnce sync.Once
2921 nextProtoErr error
2922
2923 mu sync.Mutex
2924 listeners map[*net.Listener]struct{}
2925 activeConn map[*conn]struct{}
2926 onShutdown []func()
2927
2928 listenerGroup sync.WaitGroup
2929 }
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940 func (srv *Server) Close() error {
2941 srv.inShutdown.Store(true)
2942 srv.mu.Lock()
2943 defer srv.mu.Unlock()
2944 err := srv.closeListenersLocked()
2945
2946
2947
2948
2949
2950 srv.mu.Unlock()
2951 srv.listenerGroup.Wait()
2952 srv.mu.Lock()
2953
2954 for c := range srv.activeConn {
2955 c.rwc.Close()
2956 delete(srv.activeConn, c)
2957 }
2958 return err
2959 }
2960
2961
2962
2963
2964
2965
2966
2967
2968 const shutdownPollIntervalMax = 500 * time.Millisecond
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990 func (srv *Server) Shutdown(ctx context.Context) error {
2991 srv.inShutdown.Store(true)
2992
2993 srv.mu.Lock()
2994 lnerr := srv.closeListenersLocked()
2995 for _, f := range srv.onShutdown {
2996 go f()
2997 }
2998 srv.mu.Unlock()
2999 srv.listenerGroup.Wait()
3000
3001 pollIntervalBase := time.Millisecond
3002 nextPollInterval := func() time.Duration {
3003
3004 interval := pollIntervalBase + time.Duration(rand.Intn(int(pollIntervalBase/10)))
3005
3006 pollIntervalBase *= 2
3007 if pollIntervalBase > shutdownPollIntervalMax {
3008 pollIntervalBase = shutdownPollIntervalMax
3009 }
3010 return interval
3011 }
3012
3013 timer := time.NewTimer(nextPollInterval())
3014 defer timer.Stop()
3015 for {
3016 if srv.closeIdleConns() {
3017 return lnerr
3018 }
3019 select {
3020 case <-ctx.Done():
3021 return ctx.Err()
3022 case <-timer.C:
3023 timer.Reset(nextPollInterval())
3024 }
3025 }
3026 }
3027
3028
3029
3030
3031
3032
3033 func (srv *Server) RegisterOnShutdown(f func()) {
3034 srv.mu.Lock()
3035 srv.onShutdown = append(srv.onShutdown, f)
3036 srv.mu.Unlock()
3037 }
3038
3039
3040
3041 func (s *Server) closeIdleConns() bool {
3042 s.mu.Lock()
3043 defer s.mu.Unlock()
3044 quiescent := true
3045 for c := range s.activeConn {
3046 st, unixSec := c.getState()
3047
3048
3049
3050 if st == StateNew && unixSec < time.Now().Unix()-5 {
3051 st = StateIdle
3052 }
3053 if st != StateIdle || unixSec == 0 {
3054
3055
3056 quiescent = false
3057 continue
3058 }
3059 c.rwc.Close()
3060 delete(s.activeConn, c)
3061 }
3062 return quiescent
3063 }
3064
3065 func (s *Server) closeListenersLocked() error {
3066 var err error
3067 for ln := range s.listeners {
3068 if cerr := (*ln).Close(); cerr != nil && err == nil {
3069 err = cerr
3070 }
3071 }
3072 return err
3073 }
3074
3075
3076
3077 type ConnState int
3078
3079 const (
3080
3081
3082
3083
3084 StateNew ConnState = iota
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097 StateActive
3098
3099
3100
3101
3102
3103 StateIdle
3104
3105
3106
3107 StateHijacked
3108
3109
3110
3111
3112 StateClosed
3113 )
3114
3115 var stateName = map[ConnState]string{
3116 StateNew: "new",
3117 StateActive: "active",
3118 StateIdle: "idle",
3119 StateHijacked: "hijacked",
3120 StateClosed: "closed",
3121 }
3122
3123 func (c ConnState) String() string {
3124 return stateName[c]
3125 }
3126
3127
3128
3129 type serverHandler struct {
3130 srv *Server
3131 }
3132
3133 func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
3134 handler := sh.srv.Handler
3135 if handler == nil {
3136 handler = DefaultServeMux
3137 }
3138 if !sh.srv.DisableGeneralOptionsHandler && req.RequestURI == "*" && req.Method == "OPTIONS" {
3139 handler = globalOptionsHandler{}
3140 }
3141
3142 handler.ServeHTTP(rw, req)
3143 }
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154 func AllowQuerySemicolons(h Handler) Handler {
3155 return HandlerFunc(func(w ResponseWriter, r *Request) {
3156 if strings.Contains(r.URL.RawQuery, ";") {
3157 r2 := new(Request)
3158 *r2 = *r
3159 r2.URL = new(url.URL)
3160 *r2.URL = *r.URL
3161 r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&")
3162 h.ServeHTTP(w, r2)
3163 } else {
3164 h.ServeHTTP(w, r)
3165 }
3166 })
3167 }
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177 func (srv *Server) ListenAndServe() error {
3178 if srv.shuttingDown() {
3179 return ErrServerClosed
3180 }
3181 addr := srv.Addr
3182 if addr == "" {
3183 addr = ":http"
3184 }
3185 ln, err := net.Listen("tcp", addr)
3186 if err != nil {
3187 return err
3188 }
3189 return srv.Serve(ln)
3190 }
3191
3192 var testHookServerServe func(*Server, net.Listener)
3193
3194
3195
3196 func (srv *Server) shouldConfigureHTTP2ForServe() bool {
3197 if srv.TLSConfig == nil {
3198
3199
3200
3201
3202
3203
3204 return true
3205 }
3206
3207
3208
3209
3210
3211
3212
3213 return strSliceContains(srv.TLSConfig.NextProtos, http2NextProtoTLS)
3214 }
3215
3216
3217
3218 var ErrServerClosed = errors.New("http: Server closed")
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230 func (srv *Server) Serve(l net.Listener) error {
3231 if fn := testHookServerServe; fn != nil {
3232 fn(srv, l)
3233 }
3234
3235 origListener := l
3236 l = &onceCloseListener{Listener: l}
3237 defer l.Close()
3238
3239 if err := srv.setupHTTP2_Serve(); err != nil {
3240 return err
3241 }
3242
3243 if !srv.trackListener(&l, true) {
3244 return ErrServerClosed
3245 }
3246 defer srv.trackListener(&l, false)
3247
3248 baseCtx := context.Background()
3249 if srv.BaseContext != nil {
3250 baseCtx = srv.BaseContext(origListener)
3251 if baseCtx == nil {
3252 panic("BaseContext returned a nil context")
3253 }
3254 }
3255
3256 var tempDelay time.Duration
3257
3258 ctx := context.WithValue(baseCtx, ServerContextKey, srv)
3259 for {
3260 rw, err := l.Accept()
3261 if err != nil {
3262 if srv.shuttingDown() {
3263 return ErrServerClosed
3264 }
3265 if ne, ok := err.(net.Error); ok && ne.Temporary() {
3266 if tempDelay == 0 {
3267 tempDelay = 5 * time.Millisecond
3268 } else {
3269 tempDelay *= 2
3270 }
3271 if max := 1 * time.Second; tempDelay > max {
3272 tempDelay = max
3273 }
3274 srv.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
3275 time.Sleep(tempDelay)
3276 continue
3277 }
3278 return err
3279 }
3280 connCtx := ctx
3281 if cc := srv.ConnContext; cc != nil {
3282 connCtx = cc(connCtx, rw)
3283 if connCtx == nil {
3284 panic("ConnContext returned nil")
3285 }
3286 }
3287 tempDelay = 0
3288 c := srv.newConn(rw)
3289 c.setState(c.rwc, StateNew, runHooks)
3290 go c.serve(connCtx)
3291 }
3292 }
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307 func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {
3308
3309
3310 if err := srv.setupHTTP2_ServeTLS(); err != nil {
3311 return err
3312 }
3313
3314 config := cloneTLSConfig(srv.TLSConfig)
3315 if !strSliceContains(config.NextProtos, "http/1.1") {
3316 config.NextProtos = append(config.NextProtos, "http/1.1")
3317 }
3318
3319 configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil
3320 if !configHasCert || certFile != "" || keyFile != "" {
3321 var err error
3322 config.Certificates = make([]tls.Certificate, 1)
3323 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
3324 if err != nil {
3325 return err
3326 }
3327 }
3328
3329 tlsListener := tls.NewListener(l, config)
3330 return srv.Serve(tlsListener)
3331 }
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343 func (s *Server) trackListener(ln *net.Listener, add bool) bool {
3344 s.mu.Lock()
3345 defer s.mu.Unlock()
3346 if s.listeners == nil {
3347 s.listeners = make(map[*net.Listener]struct{})
3348 }
3349 if add {
3350 if s.shuttingDown() {
3351 return false
3352 }
3353 s.listeners[ln] = struct{}{}
3354 s.listenerGroup.Add(1)
3355 } else {
3356 delete(s.listeners, ln)
3357 s.listenerGroup.Done()
3358 }
3359 return true
3360 }
3361
3362 func (s *Server) trackConn(c *conn, add bool) {
3363 s.mu.Lock()
3364 defer s.mu.Unlock()
3365 if s.activeConn == nil {
3366 s.activeConn = make(map[*conn]struct{})
3367 }
3368 if add {
3369 s.activeConn[c] = struct{}{}
3370 } else {
3371 delete(s.activeConn, c)
3372 }
3373 }
3374
3375 func (s *Server) idleTimeout() time.Duration {
3376 if s.IdleTimeout != 0 {
3377 return s.IdleTimeout
3378 }
3379 return s.ReadTimeout
3380 }
3381
3382 func (s *Server) readHeaderTimeout() time.Duration {
3383 if s.ReadHeaderTimeout != 0 {
3384 return s.ReadHeaderTimeout
3385 }
3386 return s.ReadTimeout
3387 }
3388
3389 func (s *Server) doKeepAlives() bool {
3390 return !s.disableKeepAlives.Load() && !s.shuttingDown()
3391 }
3392
3393 func (s *Server) shuttingDown() bool {
3394 return s.inShutdown.Load()
3395 }
3396
3397
3398
3399
3400
3401 func (srv *Server) SetKeepAlivesEnabled(v bool) {
3402 if v {
3403 srv.disableKeepAlives.Store(false)
3404 return
3405 }
3406 srv.disableKeepAlives.Store(true)
3407
3408
3409 srv.closeIdleConns()
3410
3411
3412 }
3413
3414 func (s *Server) logf(format string, args ...any) {
3415 if s.ErrorLog != nil {
3416 s.ErrorLog.Printf(format, args...)
3417 } else {
3418 log.Printf(format, args...)
3419 }
3420 }
3421
3422
3423
3424
3425 func logf(r *Request, format string, args ...any) {
3426 s, _ := r.Context().Value(ServerContextKey).(*Server)
3427 if s != nil && s.ErrorLog != nil {
3428 s.ErrorLog.Printf(format, args...)
3429 } else {
3430 log.Printf(format, args...)
3431 }
3432 }
3433
3434
3435
3436
3437
3438
3439
3440
3441 func ListenAndServe(addr string, handler Handler) error {
3442 server := &Server{Addr: addr, Handler: handler}
3443 return server.ListenAndServe()
3444 }
3445
3446
3447
3448
3449
3450
3451 func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
3452 server := &Server{Addr: addr, Handler: handler}
3453 return server.ListenAndServeTLS(certFile, keyFile)
3454 }
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
3472 if srv.shuttingDown() {
3473 return ErrServerClosed
3474 }
3475 addr := srv.Addr
3476 if addr == "" {
3477 addr = ":https"
3478 }
3479
3480 ln, err := net.Listen("tcp", addr)
3481 if err != nil {
3482 return err
3483 }
3484
3485 defer ln.Close()
3486
3487 return srv.ServeTLS(ln, certFile, keyFile)
3488 }
3489
3490
3491
3492
3493 func (srv *Server) setupHTTP2_ServeTLS() error {
3494 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults)
3495 return srv.nextProtoErr
3496 }
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506 func (srv *Server) setupHTTP2_Serve() error {
3507 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve)
3508 return srv.nextProtoErr
3509 }
3510
3511 func (srv *Server) onceSetNextProtoDefaults_Serve() {
3512 if srv.shouldConfigureHTTP2ForServe() {
3513 srv.onceSetNextProtoDefaults()
3514 }
3515 }
3516
3517 var http2server = godebug.New("http2server")
3518
3519
3520
3521
3522 func (srv *Server) onceSetNextProtoDefaults() {
3523 if omitBundledHTTP2 {
3524 return
3525 }
3526 if http2server.Value() == "0" {
3527 http2server.IncNonDefault()
3528 return
3529 }
3530
3531
3532 if srv.TLSNextProto == nil {
3533 conf := &http2Server{
3534 NewWriteScheduler: func() http2WriteScheduler { return http2NewPriorityWriteScheduler(nil) },
3535 }
3536 srv.nextProtoErr = http2ConfigureServer(srv, conf)
3537 }
3538 }
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
3552 return &timeoutHandler{
3553 handler: h,
3554 body: msg,
3555 dt: dt,
3556 }
3557 }
3558
3559
3560
3561 var ErrHandlerTimeout = errors.New("http: Handler timeout")
3562
3563 type timeoutHandler struct {
3564 handler Handler
3565 body string
3566 dt time.Duration
3567
3568
3569
3570 testContext context.Context
3571 }
3572
3573 func (h *timeoutHandler) errorBody() string {
3574 if h.body != "" {
3575 return h.body
3576 }
3577 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
3578 }
3579
3580 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
3581 ctx := h.testContext
3582 if ctx == nil {
3583 var cancelCtx context.CancelFunc
3584 ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
3585 defer cancelCtx()
3586 }
3587 r = r.WithContext(ctx)
3588 done := make(chan struct{})
3589 tw := &timeoutWriter{
3590 w: w,
3591 h: make(Header),
3592 req: r,
3593 }
3594 panicChan := make(chan any, 1)
3595 go func() {
3596 defer func() {
3597 if p := recover(); p != nil {
3598 panicChan <- p
3599 }
3600 }()
3601 h.handler.ServeHTTP(tw, r)
3602 close(done)
3603 }()
3604 select {
3605 case p := <-panicChan:
3606 panic(p)
3607 case <-done:
3608 tw.mu.Lock()
3609 defer tw.mu.Unlock()
3610 dst := w.Header()
3611 for k, vv := range tw.h {
3612 dst[k] = vv
3613 }
3614 if !tw.wroteHeader {
3615 tw.code = StatusOK
3616 }
3617 w.WriteHeader(tw.code)
3618 w.Write(tw.wbuf.Bytes())
3619 case <-ctx.Done():
3620 tw.mu.Lock()
3621 defer tw.mu.Unlock()
3622 switch err := ctx.Err(); err {
3623 case context.DeadlineExceeded:
3624 w.WriteHeader(StatusServiceUnavailable)
3625 io.WriteString(w, h.errorBody())
3626 tw.err = ErrHandlerTimeout
3627 default:
3628 w.WriteHeader(StatusServiceUnavailable)
3629 tw.err = err
3630 }
3631 }
3632 }
3633
3634 type timeoutWriter struct {
3635 w ResponseWriter
3636 h Header
3637 wbuf bytes.Buffer
3638 req *Request
3639
3640 mu sync.Mutex
3641 err error
3642 wroteHeader bool
3643 code int
3644 }
3645
3646 var _ Pusher = (*timeoutWriter)(nil)
3647
3648
3649 func (tw *timeoutWriter) Push(target string, opts *PushOptions) error {
3650 if pusher, ok := tw.w.(Pusher); ok {
3651 return pusher.Push(target, opts)
3652 }
3653 return ErrNotSupported
3654 }
3655
3656 func (tw *timeoutWriter) Header() Header { return tw.h }
3657
3658 func (tw *timeoutWriter) Write(p []byte) (int, error) {
3659 tw.mu.Lock()
3660 defer tw.mu.Unlock()
3661 if tw.err != nil {
3662 return 0, tw.err
3663 }
3664 if !tw.wroteHeader {
3665 tw.writeHeaderLocked(StatusOK)
3666 }
3667 return tw.wbuf.Write(p)
3668 }
3669
3670 func (tw *timeoutWriter) writeHeaderLocked(code int) {
3671 checkWriteHeaderCode(code)
3672
3673 switch {
3674 case tw.err != nil:
3675 return
3676 case tw.wroteHeader:
3677 if tw.req != nil {
3678 caller := relevantCaller()
3679 logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
3680 }
3681 default:
3682 tw.wroteHeader = true
3683 tw.code = code
3684 }
3685 }
3686
3687 func (tw *timeoutWriter) WriteHeader(code int) {
3688 tw.mu.Lock()
3689 defer tw.mu.Unlock()
3690 tw.writeHeaderLocked(code)
3691 }
3692
3693
3694
3695 type onceCloseListener struct {
3696 net.Listener
3697 once sync.Once
3698 closeErr error
3699 }
3700
3701 func (oc *onceCloseListener) Close() error {
3702 oc.once.Do(oc.close)
3703 return oc.closeErr
3704 }
3705
3706 func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() }
3707
3708
3709 type globalOptionsHandler struct{}
3710
3711 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
3712 w.Header().Set("Content-Length", "0")
3713 if r.ContentLength != 0 {
3714
3715
3716
3717
3718
3719 mb := MaxBytesReader(w, r.Body, 4<<10)
3720 io.Copy(io.Discard, mb)
3721 }
3722 }
3723
3724
3725
3726
3727 type initALPNRequest struct {
3728 ctx context.Context
3729 c *tls.Conn
3730 h serverHandler
3731 }
3732
3733
3734
3735
3736
3737 func (h initALPNRequest) BaseContext() context.Context { return h.ctx }
3738
3739 func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
3740 if req.TLS == nil {
3741 req.TLS = &tls.ConnectionState{}
3742 *req.TLS = h.c.ConnectionState()
3743 }
3744 if req.Body == nil {
3745 req.Body = NoBody
3746 }
3747 if req.RemoteAddr == "" {
3748 req.RemoteAddr = h.c.RemoteAddr().String()
3749 }
3750 h.h.ServeHTTP(rw, req)
3751 }
3752
3753
3754 type loggingConn struct {
3755 name string
3756 net.Conn
3757 }
3758
3759 var (
3760 uniqNameMu sync.Mutex
3761 uniqNameNext = make(map[string]int)
3762 )
3763
3764 func newLoggingConn(baseName string, c net.Conn) net.Conn {
3765 uniqNameMu.Lock()
3766 defer uniqNameMu.Unlock()
3767 uniqNameNext[baseName]++
3768 return &loggingConn{
3769 name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
3770 Conn: c,
3771 }
3772 }
3773
3774 func (c *loggingConn) Write(p []byte) (n int, err error) {
3775 log.Printf("%s.Write(%d) = ....", c.name, len(p))
3776 n, err = c.Conn.Write(p)
3777 log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
3778 return
3779 }
3780
3781 func (c *loggingConn) Read(p []byte) (n int, err error) {
3782 log.Printf("%s.Read(%d) = ....", c.name, len(p))
3783 n, err = c.Conn.Read(p)
3784 log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
3785 return
3786 }
3787
3788 func (c *loggingConn) Close() (err error) {
3789 log.Printf("%s.Close() = ...", c.name)
3790 err = c.Conn.Close()
3791 log.Printf("%s.Close() = %v", c.name, err)
3792 return
3793 }
3794
3795
3796
3797
3798 type checkConnErrorWriter struct {
3799 c *conn
3800 }
3801
3802 func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
3803 n, err = w.c.rwc.Write(p)
3804 if err != nil && w.c.werr == nil {
3805 w.c.werr = err
3806 w.c.cancelCtx()
3807 }
3808 return
3809 }
3810
3811 func numLeadingCRorLF(v []byte) (n int) {
3812 for _, b := range v {
3813 if b == '\r' || b == '\n' {
3814 n++
3815 continue
3816 }
3817 break
3818 }
3819 return
3820 }
3821
3822 func strSliceContains(ss []string, s string) bool {
3823 for _, v := range ss {
3824 if v == s {
3825 return true
3826 }
3827 }
3828 return false
3829 }
3830
3831
3832
3833 func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool {
3834 switch string(hdr[:]) {
3835 case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
3836 return true
3837 }
3838 return false
3839 }
3840
3841
3842 func MaxBytesHandler(h Handler, n int64) Handler {
3843 return HandlerFunc(func(w ResponseWriter, r *Request) {
3844 r2 := *r
3845 r2.Body = MaxBytesReader(w, r.Body, n)
3846 h.ServeHTTP(w, &r2)
3847 })
3848 }
3849
View as plain text