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