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 "io"
17 "log"
18 "math/rand"
19 "net"
20 "net/textproto"
21 "net/url"
22 urlpkg "net/url"
23 "os"
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() interface{} {
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 type expectContinueReader struct {
871 resp *response
872 readCloser io.ReadCloser
873 closed atomicBool
874 sawEOF atomicBool
875 }
876
877 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
878 if ecr.closed.isSet() {
879 return 0, ErrBodyReadAfterClose
880 }
881 w := ecr.resp
882 if !w.wroteContinue && w.canWriteContinue.isSet() && !w.conn.hijacked() {
883 w.wroteContinue = true
884 w.writeContinueMu.Lock()
885 if w.canWriteContinue.isSet() {
886 w.conn.bufw.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
887 w.conn.bufw.Flush()
888 w.canWriteContinue.setFalse()
889 }
890 w.writeContinueMu.Unlock()
891 }
892 n, err = ecr.readCloser.Read(p)
893 if err == io.EOF {
894 ecr.sawEOF.setTrue()
895 }
896 return
897 }
898
899 func (ecr *expectContinueReader) Close() error {
900 ecr.closed.setTrue()
901 return ecr.readCloser.Close()
902 }
903
904
905
906
907
908
909
910 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
911
912
913 func appendTime(b []byte, t time.Time) []byte {
914 const days = "SunMonTueWedThuFriSat"
915 const months = "JanFebMarAprMayJunJulAugSepOctNovDec"
916
917 t = t.UTC()
918 yy, mm, dd := t.Date()
919 hh, mn, ss := t.Clock()
920 day := days[3*t.Weekday():]
921 mon := months[3*(mm-1):]
922
923 return append(b,
924 day[0], day[1], day[2], ',', ' ',
925 byte('0'+dd/10), byte('0'+dd%10), ' ',
926 mon[0], mon[1], mon[2], ' ',
927 byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ',
928 byte('0'+hh/10), byte('0'+hh%10), ':',
929 byte('0'+mn/10), byte('0'+mn%10), ':',
930 byte('0'+ss/10), byte('0'+ss%10), ' ',
931 'G', 'M', 'T')
932 }
933
934 var errTooLarge = errors.New("http: request too large")
935
936
937 func (c *conn) readRequest(ctx context.Context) (w *response, err error) {
938 if c.hijacked() {
939 return nil, ErrHijacked
940 }
941
942 var (
943 wholeReqDeadline time.Time
944 hdrDeadline time.Time
945 )
946 t0 := time.Now()
947 if d := c.server.readHeaderTimeout(); d > 0 {
948 hdrDeadline = t0.Add(d)
949 }
950 if d := c.server.ReadTimeout; d > 0 {
951 wholeReqDeadline = t0.Add(d)
952 }
953 c.rwc.SetReadDeadline(hdrDeadline)
954 if d := c.server.WriteTimeout; d > 0 {
955 defer func() {
956 c.rwc.SetWriteDeadline(time.Now().Add(d))
957 }()
958 }
959
960 c.r.setReadLimit(c.server.initialReadLimitSize())
961 if c.lastMethod == "POST" {
962
963 peek, _ := c.bufr.Peek(4)
964 c.bufr.Discard(numLeadingCRorLF(peek))
965 }
966 req, err := readRequest(c.bufr)
967 if err != nil {
968 if c.r.hitReadLimit() {
969 return nil, errTooLarge
970 }
971 return nil, err
972 }
973
974 if !http1ServerSupportsRequest(req) {
975 return nil, statusError{StatusHTTPVersionNotSupported, "unsupported protocol version"}
976 }
977
978 c.lastMethod = req.Method
979 c.r.setInfiniteReadLimit()
980
981 hosts, haveHost := req.Header["Host"]
982 isH2Upgrade := req.isH2Upgrade()
983 if req.ProtoAtLeast(1, 1) && (!haveHost || len(hosts) == 0) && !isH2Upgrade && req.Method != "CONNECT" {
984 return nil, badRequestError("missing required Host header")
985 }
986 if len(hosts) == 1 && !httpguts.ValidHostHeader(hosts[0]) {
987 return nil, badRequestError("malformed Host header")
988 }
989 for k, vv := range req.Header {
990 if !httpguts.ValidHeaderFieldName(k) {
991 return nil, badRequestError("invalid header name")
992 }
993 for _, v := range vv {
994 if !httpguts.ValidHeaderFieldValue(v) {
995 return nil, badRequestError("invalid header value")
996 }
997 }
998 }
999 delete(req.Header, "Host")
1000
1001 ctx, cancelCtx := context.WithCancel(ctx)
1002 req.ctx = ctx
1003 req.RemoteAddr = c.remoteAddr
1004 req.TLS = c.tlsState
1005 if body, ok := req.Body.(*body); ok {
1006 body.doEarlyClose = true
1007 }
1008
1009
1010 if !hdrDeadline.Equal(wholeReqDeadline) {
1011 c.rwc.SetReadDeadline(wholeReqDeadline)
1012 }
1013
1014 w = &response{
1015 conn: c,
1016 cancelCtx: cancelCtx,
1017 req: req,
1018 reqBody: req.Body,
1019 handlerHeader: make(Header),
1020 contentLength: -1,
1021 closeNotifyCh: make(chan bool, 1),
1022
1023
1024
1025
1026 wants10KeepAlive: req.wantsHttp10KeepAlive(),
1027 wantsClose: req.wantsClose(),
1028 }
1029 if isH2Upgrade {
1030 w.closeAfterReply = true
1031 }
1032 w.cw.res = w
1033 w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize)
1034 return w, nil
1035 }
1036
1037
1038
1039 func http1ServerSupportsRequest(req *Request) bool {
1040 if req.ProtoMajor == 1 {
1041 return true
1042 }
1043
1044
1045 if req.ProtoMajor == 2 && req.ProtoMinor == 0 &&
1046 req.Method == "PRI" && req.RequestURI == "*" {
1047 return true
1048 }
1049
1050
1051 return false
1052 }
1053
1054 func (w *response) Header() Header {
1055 if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader {
1056
1057
1058
1059 w.cw.header = w.handlerHeader.Clone()
1060 }
1061 w.calledHeader = true
1062 return w.handlerHeader
1063 }
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074 const maxPostHandlerReadBytes = 256 << 10
1075
1076 func checkWriteHeaderCode(code int) {
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088 if code < 100 || code > 999 {
1089 panic(fmt.Sprintf("invalid WriteHeader code %v", code))
1090 }
1091 }
1092
1093
1094
1095 func relevantCaller() runtime.Frame {
1096 pc := make([]uintptr, 16)
1097 n := runtime.Callers(1, pc)
1098 frames := runtime.CallersFrames(pc[:n])
1099 var frame runtime.Frame
1100 for {
1101 frame, more := frames.Next()
1102 if !strings.HasPrefix(frame.Function, "net/http.") {
1103 return frame
1104 }
1105 if !more {
1106 break
1107 }
1108 }
1109 return frame
1110 }
1111
1112 func (w *response) WriteHeader(code int) {
1113 if w.conn.hijacked() {
1114 caller := relevantCaller()
1115 w.conn.server.logf("http: response.WriteHeader on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1116 return
1117 }
1118 if w.wroteHeader {
1119 caller := relevantCaller()
1120 w.conn.server.logf("http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1121 return
1122 }
1123 checkWriteHeaderCode(code)
1124 w.wroteHeader = true
1125 w.status = code
1126
1127 if w.calledHeader && w.cw.header == nil {
1128 w.cw.header = w.handlerHeader.Clone()
1129 }
1130
1131 if cl := w.handlerHeader.get("Content-Length"); cl != "" {
1132 v, err := strconv.ParseInt(cl, 10, 64)
1133 if err == nil && v >= 0 {
1134 w.contentLength = v
1135 } else {
1136 w.conn.server.logf("http: invalid Content-Length of %q", cl)
1137 w.handlerHeader.Del("Content-Length")
1138 }
1139 }
1140 }
1141
1142
1143
1144
1145 type extraHeader struct {
1146 contentType string
1147 connection string
1148 transferEncoding string
1149 date []byte
1150 contentLength []byte
1151 }
1152
1153
1154 var extraHeaderKeys = [][]byte{
1155 []byte("Content-Type"),
1156 []byte("Connection"),
1157 []byte("Transfer-Encoding"),
1158 }
1159
1160 var (
1161 headerContentLength = []byte("Content-Length: ")
1162 headerDate = []byte("Date: ")
1163 )
1164
1165
1166
1167
1168
1169
1170 func (h extraHeader) Write(w *bufio.Writer) {
1171 if h.date != nil {
1172 w.Write(headerDate)
1173 w.Write(h.date)
1174 w.Write(crlf)
1175 }
1176 if h.contentLength != nil {
1177 w.Write(headerContentLength)
1178 w.Write(h.contentLength)
1179 w.Write(crlf)
1180 }
1181 for i, v := range []string{h.contentType, h.connection, h.transferEncoding} {
1182 if v != "" {
1183 w.Write(extraHeaderKeys[i])
1184 w.Write(colonSpace)
1185 w.WriteString(v)
1186 w.Write(crlf)
1187 }
1188 }
1189 }
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199 func (cw *chunkWriter) writeHeader(p []byte) {
1200 if cw.wroteHeader {
1201 return
1202 }
1203 cw.wroteHeader = true
1204
1205 w := cw.res
1206 keepAlivesEnabled := w.conn.server.doKeepAlives()
1207 isHEAD := w.req.Method == "HEAD"
1208
1209
1210
1211
1212
1213
1214 header := cw.header
1215 owned := header != nil
1216 if !owned {
1217 header = w.handlerHeader
1218 }
1219 var excludeHeader map[string]bool
1220 delHeader := func(key string) {
1221 if owned {
1222 header.Del(key)
1223 return
1224 }
1225 if _, ok := header[key]; !ok {
1226 return
1227 }
1228 if excludeHeader == nil {
1229 excludeHeader = make(map[string]bool)
1230 }
1231 excludeHeader[key] = true
1232 }
1233 var setHeader extraHeader
1234
1235
1236 trailers := false
1237 for k := range cw.header {
1238 if strings.HasPrefix(k, TrailerPrefix) {
1239 if excludeHeader == nil {
1240 excludeHeader = make(map[string]bool)
1241 }
1242 excludeHeader[k] = true
1243 trailers = true
1244 }
1245 }
1246 for _, v := range cw.header["Trailer"] {
1247 trailers = true
1248 foreachHeaderElement(v, cw.res.declareTrailer)
1249 }
1250
1251 te := header.get("Transfer-Encoding")
1252 hasTE := te != ""
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268 if w.handlerDone.isSet() && !trailers && !hasTE && bodyAllowedForStatus(w.status) && header.get("Content-Length") == "" && (!isHEAD || len(p) > 0) {
1269 w.contentLength = int64(len(p))
1270 setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10)
1271 }
1272
1273
1274
1275 if w.wants10KeepAlive && keepAlivesEnabled {
1276 sentLength := header.get("Content-Length") != ""
1277 if sentLength && header.get("Connection") == "keep-alive" {
1278 w.closeAfterReply = false
1279 }
1280 }
1281
1282
1283 hasCL := w.contentLength != -1
1284
1285 if w.wants10KeepAlive && (isHEAD || hasCL || !bodyAllowedForStatus(w.status)) {
1286 _, connectionHeaderSet := header["Connection"]
1287 if !connectionHeaderSet {
1288 setHeader.connection = "keep-alive"
1289 }
1290 } else if !w.req.ProtoAtLeast(1, 1) || w.wantsClose {
1291 w.closeAfterReply = true
1292 }
1293
1294 if header.get("Connection") == "close" || !keepAlivesEnabled {
1295 w.closeAfterReply = true
1296 }
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310 if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF.isSet() {
1311 w.closeAfterReply = true
1312 }
1313
1314
1315
1316
1317
1318
1319
1320
1321 if w.req.ContentLength != 0 && !w.closeAfterReply {
1322 var discard, tooBig bool
1323
1324 switch bdy := w.req.Body.(type) {
1325 case *expectContinueReader:
1326 if bdy.resp.wroteContinue {
1327 discard = true
1328 }
1329 case *body:
1330 bdy.mu.Lock()
1331 switch {
1332 case bdy.closed:
1333 if !bdy.sawEOF {
1334
1335 w.closeAfterReply = true
1336 }
1337 case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes:
1338 tooBig = true
1339 default:
1340 discard = true
1341 }
1342 bdy.mu.Unlock()
1343 default:
1344 discard = true
1345 }
1346
1347 if discard {
1348 _, err := io.CopyN(io.Discard, w.reqBody, maxPostHandlerReadBytes+1)
1349 switch err {
1350 case nil:
1351
1352 tooBig = true
1353 case ErrBodyReadAfterClose:
1354
1355 case io.EOF:
1356
1357 err = w.reqBody.Close()
1358 if err != nil {
1359 w.closeAfterReply = true
1360 }
1361 default:
1362
1363
1364
1365 w.closeAfterReply = true
1366 }
1367 }
1368
1369 if tooBig {
1370 w.requestTooLarge()
1371 delHeader("Connection")
1372 setHeader.connection = "close"
1373 }
1374 }
1375
1376 code := w.status
1377 if bodyAllowedForStatus(code) {
1378
1379 _, haveType := header["Content-Type"]
1380
1381
1382
1383 ce := header.Get("Content-Encoding")
1384 hasCE := len(ce) > 0
1385 if !hasCE && !haveType && !hasTE && len(p) > 0 {
1386 setHeader.contentType = DetectContentType(p)
1387 }
1388 } else {
1389 for _, k := range suppressedHeaders(code) {
1390 delHeader(k)
1391 }
1392 }
1393
1394 if !header.has("Date") {
1395 setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now())
1396 }
1397
1398 if hasCL && hasTE && te != "identity" {
1399
1400
1401 w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
1402 te, w.contentLength)
1403 delHeader("Content-Length")
1404 hasCL = false
1405 }
1406
1407 if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) || code == StatusNoContent {
1408
1409 delHeader("Transfer-Encoding")
1410 } else if hasCL {
1411
1412 delHeader("Transfer-Encoding")
1413 } else if w.req.ProtoAtLeast(1, 1) {
1414
1415
1416
1417
1418
1419 if hasTE && te == "identity" {
1420 cw.chunking = false
1421 w.closeAfterReply = true
1422 delHeader("Transfer-Encoding")
1423 } else {
1424
1425
1426 cw.chunking = true
1427 setHeader.transferEncoding = "chunked"
1428 if hasTE && te == "chunked" {
1429
1430 delHeader("Transfer-Encoding")
1431 }
1432 }
1433 } else {
1434
1435
1436
1437 w.closeAfterReply = true
1438 delHeader("Transfer-Encoding")
1439 }
1440
1441
1442 if cw.chunking {
1443 delHeader("Content-Length")
1444 }
1445 if !w.req.ProtoAtLeast(1, 0) {
1446 return
1447 }
1448
1449
1450
1451
1452 delConnectionHeader := w.closeAfterReply &&
1453 (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) &&
1454 !isProtocolSwitchResponse(w.status, header)
1455 if delConnectionHeader {
1456 delHeader("Connection")
1457 if w.req.ProtoAtLeast(1, 1) {
1458 setHeader.connection = "close"
1459 }
1460 }
1461
1462 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
1463 cw.header.WriteSubset(w.conn.bufw, excludeHeader)
1464 setHeader.Write(w.conn.bufw)
1465 w.conn.bufw.Write(crlf)
1466 }
1467
1468
1469
1470 func foreachHeaderElement(v string, fn func(string)) {
1471 v = textproto.TrimString(v)
1472 if v == "" {
1473 return
1474 }
1475 if !strings.Contains(v, ",") {
1476 fn(v)
1477 return
1478 }
1479 for _, f := range strings.Split(v, ",") {
1480 if f = textproto.TrimString(f); f != "" {
1481 fn(f)
1482 }
1483 }
1484 }
1485
1486
1487
1488
1489
1490 func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte) {
1491 if is11 {
1492 bw.WriteString("HTTP/1.1 ")
1493 } else {
1494 bw.WriteString("HTTP/1.0 ")
1495 }
1496 if text, ok := statusText[code]; ok {
1497 bw.Write(strconv.AppendInt(scratch[:0], int64(code), 10))
1498 bw.WriteByte(' ')
1499 bw.WriteString(text)
1500 bw.WriteString("\r\n")
1501 } else {
1502
1503 fmt.Fprintf(bw, "%03d status code %d\r\n", code, code)
1504 }
1505 }
1506
1507
1508
1509 func (w *response) bodyAllowed() bool {
1510 if !w.wroteHeader {
1511 panic("")
1512 }
1513 return bodyAllowedForStatus(w.status)
1514 }
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550 func (w *response) Write(data []byte) (n int, err error) {
1551 return w.write(len(data), data, "")
1552 }
1553
1554 func (w *response) WriteString(data string) (n int, err error) {
1555 return w.write(len(data), nil, data)
1556 }
1557
1558
1559 func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
1560 if w.conn.hijacked() {
1561 if lenData > 0 {
1562 caller := relevantCaller()
1563 w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1564 }
1565 return 0, ErrHijacked
1566 }
1567
1568 if w.canWriteContinue.isSet() {
1569
1570
1571
1572
1573 w.writeContinueMu.Lock()
1574 w.canWriteContinue.setFalse()
1575 w.writeContinueMu.Unlock()
1576 }
1577
1578 if !w.wroteHeader {
1579 w.WriteHeader(StatusOK)
1580 }
1581 if lenData == 0 {
1582 return 0, nil
1583 }
1584 if !w.bodyAllowed() {
1585 return 0, ErrBodyNotAllowed
1586 }
1587
1588 w.written += int64(lenData)
1589 if w.contentLength != -1 && w.written > w.contentLength {
1590 return 0, ErrContentLength
1591 }
1592 if dataB != nil {
1593 return w.w.Write(dataB)
1594 } else {
1595 return w.w.WriteString(dataS)
1596 }
1597 }
1598
1599 func (w *response) finishRequest() {
1600 w.handlerDone.setTrue()
1601
1602 if !w.wroteHeader {
1603 w.WriteHeader(StatusOK)
1604 }
1605
1606 w.w.Flush()
1607 putBufioWriter(w.w)
1608 w.cw.close()
1609 w.conn.bufw.Flush()
1610
1611 w.conn.r.abortPendingRead()
1612
1613
1614
1615 w.reqBody.Close()
1616
1617 if w.req.MultipartForm != nil {
1618 w.req.MultipartForm.RemoveAll()
1619 }
1620 }
1621
1622
1623
1624 func (w *response) shouldReuseConnection() bool {
1625 if w.closeAfterReply {
1626
1627
1628
1629 return false
1630 }
1631
1632 if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
1633
1634 return false
1635 }
1636
1637
1638
1639 if w.conn.werr != nil {
1640 return false
1641 }
1642
1643 if w.closedRequestBodyEarly() {
1644 return false
1645 }
1646
1647 return true
1648 }
1649
1650 func (w *response) closedRequestBodyEarly() bool {
1651 body, ok := w.req.Body.(*body)
1652 return ok && body.didEarlyClose()
1653 }
1654
1655 func (w *response) Flush() {
1656 if !w.wroteHeader {
1657 w.WriteHeader(StatusOK)
1658 }
1659 w.w.Flush()
1660 w.cw.flush()
1661 }
1662
1663 func (c *conn) finalFlush() {
1664 if c.bufr != nil {
1665
1666
1667 putBufioReader(c.bufr)
1668 c.bufr = nil
1669 }
1670
1671 if c.bufw != nil {
1672 c.bufw.Flush()
1673
1674
1675 putBufioWriter(c.bufw)
1676 c.bufw = nil
1677 }
1678 }
1679
1680
1681 func (c *conn) close() {
1682 c.finalFlush()
1683 c.rwc.Close()
1684 }
1685
1686
1687
1688
1689
1690
1691
1692
1693 const rstAvoidanceDelay = 500 * time.Millisecond
1694
1695 type closeWriter interface {
1696 CloseWrite() error
1697 }
1698
1699 var _ closeWriter = (*net.TCPConn)(nil)
1700
1701
1702
1703
1704
1705
1706
1707 func (c *conn) closeWriteAndWait() {
1708 c.finalFlush()
1709 if tcp, ok := c.rwc.(closeWriter); ok {
1710 tcp.CloseWrite()
1711 }
1712 time.Sleep(rstAvoidanceDelay)
1713 }
1714
1715
1716
1717
1718 func validNextProto(proto string) bool {
1719 switch proto {
1720 case "", "http/1.1", "http/1.0":
1721 return false
1722 }
1723 return true
1724 }
1725
1726 const (
1727 runHooks = true
1728 skipHooks = false
1729 )
1730
1731 func (c *conn) setState(nc net.Conn, state ConnState, runHook bool) {
1732 srv := c.server
1733 switch state {
1734 case StateNew:
1735 srv.trackConn(c, true)
1736 case StateHijacked, StateClosed:
1737 srv.trackConn(c, false)
1738 }
1739 if state > 0xff || state < 0 {
1740 panic("internal error")
1741 }
1742 packedState := uint64(time.Now().Unix()<<8) | uint64(state)
1743 atomic.StoreUint64(&c.curState.atomic, packedState)
1744 if !runHook {
1745 return
1746 }
1747 if hook := srv.ConnState; hook != nil {
1748 hook(nc, state)
1749 }
1750 }
1751
1752 func (c *conn) getState() (state ConnState, unixSec int64) {
1753 packedState := atomic.LoadUint64(&c.curState.atomic)
1754 return ConnState(packedState & 0xff), int64(packedState >> 8)
1755 }
1756
1757
1758
1759
1760 func badRequestError(e string) error { return statusError{StatusBadRequest, e} }
1761
1762
1763
1764 type statusError struct {
1765 code int
1766 text string
1767 }
1768
1769 func (e statusError) Error() string { return StatusText(e.code) + ": " + e.text }
1770
1771
1772
1773
1774
1775 var ErrAbortHandler = errors.New("net/http: abort Handler")
1776
1777
1778
1779
1780
1781 func isCommonNetReadError(err error) bool {
1782 if err == io.EOF {
1783 return true
1784 }
1785 if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
1786 return true
1787 }
1788 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
1789 return true
1790 }
1791 return false
1792 }
1793
1794
1795 func (c *conn) serve(ctx context.Context) {
1796 c.remoteAddr = c.rwc.RemoteAddr().String()
1797 ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr())
1798 defer func() {
1799 if err := recover(); err != nil && err != ErrAbortHandler {
1800 const size = 64 << 10
1801 buf := make([]byte, size)
1802 buf = buf[:runtime.Stack(buf, false)]
1803 c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
1804 }
1805 if !c.hijacked() {
1806 c.close()
1807 c.setState(c.rwc, StateClosed, runHooks)
1808 }
1809 }()
1810
1811 if tlsConn, ok := c.rwc.(*tls.Conn); ok {
1812 if d := c.server.ReadTimeout; d > 0 {
1813 c.rwc.SetReadDeadline(time.Now().Add(d))
1814 }
1815 if d := c.server.WriteTimeout; d > 0 {
1816 c.rwc.SetWriteDeadline(time.Now().Add(d))
1817 }
1818 if err := tlsConn.HandshakeContext(ctx); err != nil {
1819
1820
1821
1822 if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) {
1823 io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
1824 re.Conn.Close()
1825 return
1826 }
1827 c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err)
1828 return
1829 }
1830 c.tlsState = new(tls.ConnectionState)
1831 *c.tlsState = tlsConn.ConnectionState()
1832 if proto := c.tlsState.NegotiatedProtocol; validNextProto(proto) {
1833 if fn := c.server.TLSNextProto[proto]; fn != nil {
1834 h := initALPNRequest{ctx, tlsConn, serverHandler{c.server}}
1835
1836
1837
1838 c.setState(c.rwc, StateActive, skipHooks)
1839 fn(c.server, tlsConn, h)
1840 }
1841 return
1842 }
1843 }
1844
1845
1846
1847 ctx, cancelCtx := context.WithCancel(ctx)
1848 c.cancelCtx = cancelCtx
1849 defer cancelCtx()
1850
1851 c.r = &connReader{conn: c}
1852 c.bufr = newBufioReader(c.r)
1853 c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
1854
1855 for {
1856 w, err := c.readRequest(ctx)
1857 if c.r.remain != c.server.initialReadLimitSize() {
1858
1859 c.setState(c.rwc, StateActive, runHooks)
1860 }
1861 if err != nil {
1862 const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
1863
1864 switch {
1865 case err == errTooLarge:
1866
1867
1868
1869
1870
1871 const publicErr = "431 Request Header Fields Too Large"
1872 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
1873 c.closeWriteAndWait()
1874 return
1875
1876 case isUnsupportedTEError(err):
1877
1878
1879
1880
1881 code := StatusNotImplemented
1882
1883
1884
1885 fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders)
1886 return
1887
1888 case isCommonNetReadError(err):
1889 return
1890
1891 default:
1892 if v, ok := err.(statusError); ok {
1893 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)
1894 return
1895 }
1896 publicErr := "400 Bad Request"
1897 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
1898 return
1899 }
1900 }
1901
1902
1903 req := w.req
1904 if req.expectsContinue() {
1905 if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
1906
1907 req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
1908 w.canWriteContinue.setTrue()
1909 }
1910 } else if req.Header.get("Expect") != "" {
1911 w.sendExpectationFailed()
1912 return
1913 }
1914
1915 c.curReq.Store(w)
1916
1917 if requestBodyRemains(req.Body) {
1918 registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
1919 } else {
1920 w.conn.r.startBackgroundRead()
1921 }
1922
1923
1924
1925
1926
1927
1928
1929
1930 serverHandler{c.server}.ServeHTTP(w, w.req)
1931 w.cancelCtx()
1932 if c.hijacked() {
1933 return
1934 }
1935 w.finishRequest()
1936 if !w.shouldReuseConnection() {
1937 if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
1938 c.closeWriteAndWait()
1939 }
1940 return
1941 }
1942 c.setState(c.rwc, StateIdle, runHooks)
1943 c.curReq.Store((*response)(nil))
1944
1945 if !w.conn.server.doKeepAlives() {
1946
1947
1948
1949
1950 return
1951 }
1952
1953 if d := c.server.idleTimeout(); d != 0 {
1954 c.rwc.SetReadDeadline(time.Now().Add(d))
1955 if _, err := c.bufr.Peek(4); err != nil {
1956 return
1957 }
1958 }
1959 c.rwc.SetReadDeadline(time.Time{})
1960 }
1961 }
1962
1963 func (w *response) sendExpectationFailed() {
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976 w.Header().Set("Connection", "close")
1977 w.WriteHeader(StatusExpectationFailed)
1978 w.finishRequest()
1979 }
1980
1981
1982
1983 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
1984 if w.handlerDone.isSet() {
1985 panic("net/http: Hijack called after ServeHTTP finished")
1986 }
1987 if w.wroteHeader {
1988 w.cw.flush()
1989 }
1990
1991 c := w.conn
1992 c.mu.Lock()
1993 defer c.mu.Unlock()
1994
1995
1996
1997 rwc, buf, err = c.hijackLocked()
1998 if err == nil {
1999 putBufioWriter(w.w)
2000 w.w = nil
2001 }
2002 return rwc, buf, err
2003 }
2004
2005 func (w *response) CloseNotify() <-chan bool {
2006 if w.handlerDone.isSet() {
2007 panic("net/http: CloseNotify called after ServeHTTP finished")
2008 }
2009 return w.closeNotifyCh
2010 }
2011
2012 func registerOnHitEOF(rc io.ReadCloser, fn func()) {
2013 switch v := rc.(type) {
2014 case *expectContinueReader:
2015 registerOnHitEOF(v.readCloser, fn)
2016 case *body:
2017 v.registerOnHitEOF(fn)
2018 default:
2019 panic("unexpected type " + fmt.Sprintf("%T", rc))
2020 }
2021 }
2022
2023
2024
2025 func requestBodyRemains(rc io.ReadCloser) bool {
2026 if rc == NoBody {
2027 return false
2028 }
2029 switch v := rc.(type) {
2030 case *expectContinueReader:
2031 return requestBodyRemains(v.readCloser)
2032 case *body:
2033 return v.bodyRemains()
2034 default:
2035 panic("unexpected type " + fmt.Sprintf("%T", rc))
2036 }
2037 }
2038
2039
2040
2041
2042
2043 type HandlerFunc func(ResponseWriter, *Request)
2044
2045
2046 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
2047 f(w, r)
2048 }
2049
2050
2051
2052
2053
2054
2055
2056 func Error(w ResponseWriter, error string, code int) {
2057 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
2058 w.Header().Set("X-Content-Type-Options", "nosniff")
2059 w.WriteHeader(code)
2060 fmt.Fprintln(w, error)
2061 }
2062
2063
2064 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
2065
2066
2067
2068 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
2069
2070
2071
2072
2073
2074
2075
2076 func StripPrefix(prefix string, h Handler) Handler {
2077 if prefix == "" {
2078 return h
2079 }
2080 return HandlerFunc(func(w ResponseWriter, r *Request) {
2081 p := strings.TrimPrefix(r.URL.Path, prefix)
2082 rp := strings.TrimPrefix(r.URL.RawPath, prefix)
2083 if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
2084 r2 := new(Request)
2085 *r2 = *r
2086 r2.URL = new(url.URL)
2087 *r2.URL = *r.URL
2088 r2.URL.Path = p
2089 r2.URL.RawPath = rp
2090 h.ServeHTTP(w, r2)
2091 } else {
2092 NotFound(w, r)
2093 }
2094 })
2095 }
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107 func Redirect(w ResponseWriter, r *Request, url string, code int) {
2108 if u, err := urlpkg.Parse(url); err == nil {
2109
2110
2111
2112
2113
2114 if u.Scheme == "" && u.Host == "" {
2115 oldpath := r.URL.Path
2116 if oldpath == "" {
2117 oldpath = "/"
2118 }
2119
2120
2121 if url == "" || url[0] != '/' {
2122
2123 olddir, _ := path.Split(oldpath)
2124 url = olddir + url
2125 }
2126
2127 var query string
2128 if i := strings.Index(url, "?"); i != -1 {
2129 url, query = url[:i], url[i:]
2130 }
2131
2132
2133 trailing := strings.HasSuffix(url, "/")
2134 url = path.Clean(url)
2135 if trailing && !strings.HasSuffix(url, "/") {
2136 url += "/"
2137 }
2138 url += query
2139 }
2140 }
2141
2142 h := w.Header()
2143
2144
2145
2146
2147 _, hadCT := h["Content-Type"]
2148
2149 h.Set("Location", hexEscapeNonASCII(url))
2150 if !hadCT && (r.Method == "GET" || r.Method == "HEAD") {
2151 h.Set("Content-Type", "text/html; charset=utf-8")
2152 }
2153 w.WriteHeader(code)
2154
2155
2156 if !hadCT && r.Method == "GET" {
2157 body := "<a href=\"" + htmlEscape(url) + "\">" + statusText[code] + "</a>.\n"
2158 fmt.Fprintln(w, body)
2159 }
2160 }
2161
2162 var htmlReplacer = strings.NewReplacer(
2163 "&", "&",
2164 "<", "<",
2165 ">", ">",
2166
2167 `"`, """,
2168
2169 "'", "'",
2170 )
2171
2172 func htmlEscape(s string) string {
2173 return htmlReplacer.Replace(s)
2174 }
2175
2176
2177 type redirectHandler struct {
2178 url string
2179 code int
2180 }
2181
2182 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
2183 Redirect(w, r, rh.url, rh.code)
2184 }
2185
2186
2187
2188
2189
2190
2191
2192 func RedirectHandler(url string, code int) Handler {
2193 return &redirectHandler{url, code}
2194 }
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231 type ServeMux struct {
2232 mu sync.RWMutex
2233 m map[string]muxEntry
2234 es []muxEntry
2235 hosts bool
2236 }
2237
2238 type muxEntry struct {
2239 h Handler
2240 pattern string
2241 }
2242
2243
2244 func NewServeMux() *ServeMux { return new(ServeMux) }
2245
2246
2247 var DefaultServeMux = &defaultServeMux
2248
2249 var defaultServeMux ServeMux
2250
2251
2252 func cleanPath(p string) string {
2253 if p == "" {
2254 return "/"
2255 }
2256 if p[0] != '/' {
2257 p = "/" + p
2258 }
2259 np := path.Clean(p)
2260
2261
2262 if p[len(p)-1] == '/' && np != "/" {
2263
2264 if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
2265 np = p
2266 } else {
2267 np += "/"
2268 }
2269 }
2270 return np
2271 }
2272
2273
2274 func stripHostPort(h string) string {
2275
2276 if strings.IndexByte(h, ':') == -1 {
2277 return h
2278 }
2279 host, _, err := net.SplitHostPort(h)
2280 if err != nil {
2281 return h
2282 }
2283 return host
2284 }
2285
2286
2287
2288 func (mux *ServeMux) match(path string) (h Handler, pattern string) {
2289
2290 v, ok := mux.m[path]
2291 if ok {
2292 return v.h, v.pattern
2293 }
2294
2295
2296
2297 for _, e := range mux.es {
2298 if strings.HasPrefix(path, e.pattern) {
2299 return e.h, e.pattern
2300 }
2301 }
2302 return nil, ""
2303 }
2304
2305
2306
2307
2308
2309 func (mux *ServeMux) redirectToPathSlash(host, path string, u *url.URL) (*url.URL, bool) {
2310 mux.mu.RLock()
2311 shouldRedirect := mux.shouldRedirectRLocked(host, path)
2312 mux.mu.RUnlock()
2313 if !shouldRedirect {
2314 return u, false
2315 }
2316 path = path + "/"
2317 u = &url.URL{Path: path, RawQuery: u.RawQuery}
2318 return u, true
2319 }
2320
2321
2322
2323
2324 func (mux *ServeMux) shouldRedirectRLocked(host, path string) bool {
2325 p := []string{path, host + path}
2326
2327 for _, c := range p {
2328 if _, exist := mux.m[c]; exist {
2329 return false
2330 }
2331 }
2332
2333 n := len(path)
2334 if n == 0 {
2335 return false
2336 }
2337 for _, c := range p {
2338 if _, exist := mux.m[c+"/"]; exist {
2339 return path[n-1] != '/'
2340 }
2341 }
2342
2343 return false
2344 }
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
2362
2363
2364 if r.Method == "CONNECT" {
2365
2366
2367
2368 if u, ok := mux.redirectToPathSlash(r.URL.Host, r.URL.Path, r.URL); ok {
2369 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path
2370 }
2371
2372 return mux.handler(r.Host, r.URL.Path)
2373 }
2374
2375
2376
2377 host := stripHostPort(r.Host)
2378 path := cleanPath(r.URL.Path)
2379
2380
2381
2382 if u, ok := mux.redirectToPathSlash(host, path, r.URL); ok {
2383 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path
2384 }
2385
2386 if path != r.URL.Path {
2387 _, pattern = mux.handler(host, path)
2388 u := &url.URL{Path: path, RawQuery: r.URL.RawQuery}
2389 return RedirectHandler(u.String(), StatusMovedPermanently), pattern
2390 }
2391
2392 return mux.handler(host, r.URL.Path)
2393 }
2394
2395
2396
2397 func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) {
2398 mux.mu.RLock()
2399 defer mux.mu.RUnlock()
2400
2401
2402 if mux.hosts {
2403 h, pattern = mux.match(host + path)
2404 }
2405 if h == nil {
2406 h, pattern = mux.match(path)
2407 }
2408 if h == nil {
2409 h, pattern = NotFoundHandler(), ""
2410 }
2411 return
2412 }
2413
2414
2415
2416 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
2417 if r.RequestURI == "*" {
2418 if r.ProtoAtLeast(1, 1) {
2419 w.Header().Set("Connection", "close")
2420 }
2421 w.WriteHeader(StatusBadRequest)
2422 return
2423 }
2424 h, _ := mux.Handler(r)
2425 h.ServeHTTP(w, r)
2426 }
2427
2428
2429
2430 func (mux *ServeMux) Handle(pattern string, handler Handler) {
2431 mux.mu.Lock()
2432 defer mux.mu.Unlock()
2433
2434 if pattern == "" {
2435 panic("http: invalid pattern")
2436 }
2437 if handler == nil {
2438 panic("http: nil handler")
2439 }
2440 if _, exist := mux.m[pattern]; exist {
2441 panic("http: multiple registrations for " + pattern)
2442 }
2443
2444 if mux.m == nil {
2445 mux.m = make(map[string]muxEntry)
2446 }
2447 e := muxEntry{h: handler, pattern: pattern}
2448 mux.m[pattern] = e
2449 if pattern[len(pattern)-1] == '/' {
2450 mux.es = appendSorted(mux.es, e)
2451 }
2452
2453 if pattern[0] != '/' {
2454 mux.hosts = true
2455 }
2456 }
2457
2458 func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
2459 n := len(es)
2460 i := sort.Search(n, func(i int) bool {
2461 return len(es[i].pattern) < len(e.pattern)
2462 })
2463 if i == n {
2464 return append(es, e)
2465 }
2466
2467 es = append(es, muxEntry{})
2468 copy(es[i+1:], es[i:])
2469 es[i] = e
2470 return es
2471 }
2472
2473
2474 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2475 if handler == nil {
2476 panic("http: nil handler")
2477 }
2478 mux.Handle(pattern, HandlerFunc(handler))
2479 }
2480
2481
2482
2483
2484 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
2485
2486
2487
2488
2489 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2490 DefaultServeMux.HandleFunc(pattern, handler)
2491 }
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504 func Serve(l net.Listener, handler Handler) error {
2505 srv := &Server{Handler: handler}
2506 return srv.Serve(l)
2507 }
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521 func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {
2522 srv := &Server{Handler: handler}
2523 return srv.ServeTLS(l, certFile, keyFile)
2524 }
2525
2526
2527
2528 type Server struct {
2529
2530
2531
2532
2533 Addr string
2534
2535 Handler Handler
2536
2537
2538
2539
2540
2541
2542
2543
2544 TLSConfig *tls.Config
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554 ReadTimeout time.Duration
2555
2556
2557
2558
2559
2560
2561
2562 ReadHeaderTimeout time.Duration
2563
2564
2565
2566
2567
2568
2569 WriteTimeout time.Duration
2570
2571
2572
2573
2574
2575 IdleTimeout time.Duration
2576
2577
2578
2579
2580
2581
2582 MaxHeaderBytes int
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593 TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
2594
2595
2596
2597
2598 ConnState func(net.Conn, ConnState)
2599
2600
2601
2602
2603
2604 ErrorLog *log.Logger
2605
2606
2607
2608
2609
2610
2611
2612 BaseContext func(net.Listener) context.Context
2613
2614
2615
2616
2617
2618 ConnContext func(ctx context.Context, c net.Conn) context.Context
2619
2620 inShutdown atomicBool
2621
2622 disableKeepAlives int32
2623 nextProtoOnce sync.Once
2624 nextProtoErr error
2625
2626 mu sync.Mutex
2627 listeners map[*net.Listener]struct{}
2628 activeConn map[*conn]struct{}
2629 doneChan chan struct{}
2630 onShutdown []func()
2631 }
2632
2633 func (s *Server) getDoneChan() <-chan struct{} {
2634 s.mu.Lock()
2635 defer s.mu.Unlock()
2636 return s.getDoneChanLocked()
2637 }
2638
2639 func (s *Server) getDoneChanLocked() chan struct{} {
2640 if s.doneChan == nil {
2641 s.doneChan = make(chan struct{})
2642 }
2643 return s.doneChan
2644 }
2645
2646 func (s *Server) closeDoneChanLocked() {
2647 ch := s.getDoneChanLocked()
2648 select {
2649 case <-ch:
2650
2651 default:
2652
2653
2654 close(ch)
2655 }
2656 }
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667 func (srv *Server) Close() error {
2668 srv.inShutdown.setTrue()
2669 srv.mu.Lock()
2670 defer srv.mu.Unlock()
2671 srv.closeDoneChanLocked()
2672 err := srv.closeListenersLocked()
2673 for c := range srv.activeConn {
2674 c.rwc.Close()
2675 delete(srv.activeConn, c)
2676 }
2677 return err
2678 }
2679
2680
2681
2682
2683
2684
2685
2686
2687 const shutdownPollIntervalMax = 500 * time.Millisecond
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709 func (srv *Server) Shutdown(ctx context.Context) error {
2710 srv.inShutdown.setTrue()
2711
2712 srv.mu.Lock()
2713 lnerr := srv.closeListenersLocked()
2714 srv.closeDoneChanLocked()
2715 for _, f := range srv.onShutdown {
2716 go f()
2717 }
2718 srv.mu.Unlock()
2719
2720 pollIntervalBase := time.Millisecond
2721 nextPollInterval := func() time.Duration {
2722
2723 interval := pollIntervalBase + time.Duration(rand.Intn(int(pollIntervalBase/10)))
2724
2725 pollIntervalBase *= 2
2726 if pollIntervalBase > shutdownPollIntervalMax {
2727 pollIntervalBase = shutdownPollIntervalMax
2728 }
2729 return interval
2730 }
2731
2732 timer := time.NewTimer(nextPollInterval())
2733 defer timer.Stop()
2734 for {
2735 if srv.closeIdleConns() && srv.numListeners() == 0 {
2736 return lnerr
2737 }
2738 select {
2739 case <-ctx.Done():
2740 return ctx.Err()
2741 case <-timer.C:
2742 timer.Reset(nextPollInterval())
2743 }
2744 }
2745 }
2746
2747
2748
2749
2750
2751
2752 func (srv *Server) RegisterOnShutdown(f func()) {
2753 srv.mu.Lock()
2754 srv.onShutdown = append(srv.onShutdown, f)
2755 srv.mu.Unlock()
2756 }
2757
2758 func (s *Server) numListeners() int {
2759 s.mu.Lock()
2760 defer s.mu.Unlock()
2761 return len(s.listeners)
2762 }
2763
2764
2765
2766 func (s *Server) closeIdleConns() bool {
2767 s.mu.Lock()
2768 defer s.mu.Unlock()
2769 quiescent := true
2770 for c := range s.activeConn {
2771 st, unixSec := c.getState()
2772
2773
2774
2775 if st == StateNew && unixSec < time.Now().Unix()-5 {
2776 st = StateIdle
2777 }
2778 if st != StateIdle || unixSec == 0 {
2779
2780
2781 quiescent = false
2782 continue
2783 }
2784 c.rwc.Close()
2785 delete(s.activeConn, c)
2786 }
2787 return quiescent
2788 }
2789
2790 func (s *Server) closeListenersLocked() error {
2791 var err error
2792 for ln := range s.listeners {
2793 if cerr := (*ln).Close(); cerr != nil && err == nil {
2794 err = cerr
2795 }
2796 }
2797 return err
2798 }
2799
2800
2801
2802 type ConnState int
2803
2804 const (
2805
2806
2807
2808
2809 StateNew ConnState = iota
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822 StateActive
2823
2824
2825
2826
2827
2828 StateIdle
2829
2830
2831
2832 StateHijacked
2833
2834
2835
2836
2837 StateClosed
2838 )
2839
2840 var stateName = map[ConnState]string{
2841 StateNew: "new",
2842 StateActive: "active",
2843 StateIdle: "idle",
2844 StateHijacked: "hijacked",
2845 StateClosed: "closed",
2846 }
2847
2848 func (c ConnState) String() string {
2849 return stateName[c]
2850 }
2851
2852
2853
2854 type serverHandler struct {
2855 srv *Server
2856 }
2857
2858 func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
2859 handler := sh.srv.Handler
2860 if handler == nil {
2861 handler = DefaultServeMux
2862 }
2863 if req.RequestURI == "*" && req.Method == "OPTIONS" {
2864 handler = globalOptionsHandler{}
2865 }
2866
2867 if req.URL != nil && strings.Contains(req.URL.RawQuery, ";") {
2868 var allowQuerySemicolonsInUse int32
2869 req = req.WithContext(context.WithValue(req.Context(), silenceSemWarnContextKey, func() {
2870 atomic.StoreInt32(&allowQuerySemicolonsInUse, 1)
2871 }))
2872 defer func() {
2873 if atomic.LoadInt32(&allowQuerySemicolonsInUse) == 0 {
2874 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")
2875 }
2876 }()
2877 }
2878
2879 handler.ServeHTTP(rw, req)
2880 }
2881
2882 var silenceSemWarnContextKey = &contextKey{"silence-semicolons"}
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893 func AllowQuerySemicolons(h Handler) Handler {
2894 return HandlerFunc(func(w ResponseWriter, r *Request) {
2895 if silenceSemicolonsWarning, ok := r.Context().Value(silenceSemWarnContextKey).(func()); ok {
2896 silenceSemicolonsWarning()
2897 }
2898 if strings.Contains(r.URL.RawQuery, ";") {
2899 r2 := new(Request)
2900 *r2 = *r
2901 r2.URL = new(url.URL)
2902 *r2.URL = *r.URL
2903 r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&")
2904 h.ServeHTTP(w, r2)
2905 } else {
2906 h.ServeHTTP(w, r)
2907 }
2908 })
2909 }
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919 func (srv *Server) ListenAndServe() error {
2920 if srv.shuttingDown() {
2921 return ErrServerClosed
2922 }
2923 addr := srv.Addr
2924 if addr == "" {
2925 addr = ":http"
2926 }
2927 ln, err := net.Listen("tcp", addr)
2928 if err != nil {
2929 return err
2930 }
2931 return srv.Serve(ln)
2932 }
2933
2934 var testHookServerServe func(*Server, net.Listener)
2935
2936
2937
2938 func (srv *Server) shouldConfigureHTTP2ForServe() bool {
2939 if srv.TLSConfig == nil {
2940
2941
2942
2943
2944
2945
2946 return true
2947 }
2948
2949
2950
2951
2952
2953
2954
2955 return strSliceContains(srv.TLSConfig.NextProtos, http2NextProtoTLS)
2956 }
2957
2958
2959
2960 var ErrServerClosed = errors.New("http: Server closed")
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972 func (srv *Server) Serve(l net.Listener) error {
2973 if fn := testHookServerServe; fn != nil {
2974 fn(srv, l)
2975 }
2976
2977 origListener := l
2978 l = &onceCloseListener{Listener: l}
2979 defer l.Close()
2980
2981 if err := srv.setupHTTP2_Serve(); err != nil {
2982 return err
2983 }
2984
2985 if !srv.trackListener(&l, true) {
2986 return ErrServerClosed
2987 }
2988 defer srv.trackListener(&l, false)
2989
2990 baseCtx := context.Background()
2991 if srv.BaseContext != nil {
2992 baseCtx = srv.BaseContext(origListener)
2993 if baseCtx == nil {
2994 panic("BaseContext returned a nil context")
2995 }
2996 }
2997
2998 var tempDelay time.Duration
2999
3000 ctx := context.WithValue(baseCtx, ServerContextKey, srv)
3001 for {
3002 rw, err := l.Accept()
3003 if err != nil {
3004 select {
3005 case <-srv.getDoneChan():
3006 return ErrServerClosed
3007 default:
3008 }
3009 if ne, ok := err.(net.Error); ok && ne.Temporary() {
3010 if tempDelay == 0 {
3011 tempDelay = 5 * time.Millisecond
3012 } else {
3013 tempDelay *= 2
3014 }
3015 if max := 1 * time.Second; tempDelay > max {
3016 tempDelay = max
3017 }
3018 srv.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
3019 time.Sleep(tempDelay)
3020 continue
3021 }
3022 return err
3023 }
3024 connCtx := ctx
3025 if cc := srv.ConnContext; cc != nil {
3026 connCtx = cc(connCtx, rw)
3027 if connCtx == nil {
3028 panic("ConnContext returned nil")
3029 }
3030 }
3031 tempDelay = 0
3032 c := srv.newConn(rw)
3033 c.setState(c.rwc, StateNew, runHooks)
3034 go c.serve(connCtx)
3035 }
3036 }
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051 func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {
3052
3053
3054 if err := srv.setupHTTP2_ServeTLS(); err != nil {
3055 return err
3056 }
3057
3058 config := cloneTLSConfig(srv.TLSConfig)
3059 if !strSliceContains(config.NextProtos, "http/1.1") {
3060 config.NextProtos = append(config.NextProtos, "http/1.1")
3061 }
3062
3063 configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil
3064 if !configHasCert || certFile != "" || keyFile != "" {
3065 var err error
3066 config.Certificates = make([]tls.Certificate, 1)
3067 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
3068 if err != nil {
3069 return err
3070 }
3071 }
3072
3073 tlsListener := tls.NewListener(l, config)
3074 return srv.Serve(tlsListener)
3075 }
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087 func (s *Server) trackListener(ln *net.Listener, add bool) bool {
3088 s.mu.Lock()
3089 defer s.mu.Unlock()
3090 if s.listeners == nil {
3091 s.listeners = make(map[*net.Listener]struct{})
3092 }
3093 if add {
3094 if s.shuttingDown() {
3095 return false
3096 }
3097 s.listeners[ln] = struct{}{}
3098 } else {
3099 delete(s.listeners, ln)
3100 }
3101 return true
3102 }
3103
3104 func (s *Server) trackConn(c *conn, add bool) {
3105 s.mu.Lock()
3106 defer s.mu.Unlock()
3107 if s.activeConn == nil {
3108 s.activeConn = make(map[*conn]struct{})
3109 }
3110 if add {
3111 s.activeConn[c] = struct{}{}
3112 } else {
3113 delete(s.activeConn, c)
3114 }
3115 }
3116
3117 func (s *Server) idleTimeout() time.Duration {
3118 if s.IdleTimeout != 0 {
3119 return s.IdleTimeout
3120 }
3121 return s.ReadTimeout
3122 }
3123
3124 func (s *Server) readHeaderTimeout() time.Duration {
3125 if s.ReadHeaderTimeout != 0 {
3126 return s.ReadHeaderTimeout
3127 }
3128 return s.ReadTimeout
3129 }
3130
3131 func (s *Server) doKeepAlives() bool {
3132 return atomic.LoadInt32(&s.disableKeepAlives) == 0 && !s.shuttingDown()
3133 }
3134
3135 func (s *Server) shuttingDown() bool {
3136 return s.inShutdown.isSet()
3137 }
3138
3139
3140
3141
3142
3143 func (srv *Server) SetKeepAlivesEnabled(v bool) {
3144 if v {
3145 atomic.StoreInt32(&srv.disableKeepAlives, 0)
3146 return
3147 }
3148 atomic.StoreInt32(&srv.disableKeepAlives, 1)
3149
3150
3151 srv.closeIdleConns()
3152
3153
3154 }
3155
3156 func (s *Server) logf(format string, args ...interface{}) {
3157 if s.ErrorLog != nil {
3158 s.ErrorLog.Printf(format, args...)
3159 } else {
3160 log.Printf(format, args...)
3161 }
3162 }
3163
3164
3165
3166
3167 func logf(r *Request, format string, args ...interface{}) {
3168 s, _ := r.Context().Value(ServerContextKey).(*Server)
3169 if s != nil && s.ErrorLog != nil {
3170 s.ErrorLog.Printf(format, args...)
3171 } else {
3172 log.Printf(format, args...)
3173 }
3174 }
3175
3176
3177
3178
3179
3180
3181
3182
3183 func ListenAndServe(addr string, handler Handler) error {
3184 server := &Server{Addr: addr, Handler: handler}
3185 return server.ListenAndServe()
3186 }
3187
3188
3189
3190
3191
3192
3193 func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
3194 server := &Server{Addr: addr, Handler: handler}
3195 return server.ListenAndServeTLS(certFile, keyFile)
3196 }
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
3214 if srv.shuttingDown() {
3215 return ErrServerClosed
3216 }
3217 addr := srv.Addr
3218 if addr == "" {
3219 addr = ":https"
3220 }
3221
3222 ln, err := net.Listen("tcp", addr)
3223 if err != nil {
3224 return err
3225 }
3226
3227 defer ln.Close()
3228
3229 return srv.ServeTLS(ln, certFile, keyFile)
3230 }
3231
3232
3233
3234
3235 func (srv *Server) setupHTTP2_ServeTLS() error {
3236 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults)
3237 return srv.nextProtoErr
3238 }
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248 func (srv *Server) setupHTTP2_Serve() error {
3249 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve)
3250 return srv.nextProtoErr
3251 }
3252
3253 func (srv *Server) onceSetNextProtoDefaults_Serve() {
3254 if srv.shouldConfigureHTTP2ForServe() {
3255 srv.onceSetNextProtoDefaults()
3256 }
3257 }
3258
3259
3260
3261
3262 func (srv *Server) onceSetNextProtoDefaults() {
3263 if omitBundledHTTP2 || strings.Contains(os.Getenv("GODEBUG"), "http2server=0") {
3264 return
3265 }
3266
3267
3268 if srv.TLSNextProto == nil {
3269 conf := &http2Server{
3270 NewWriteScheduler: func() http2WriteScheduler { return http2NewPriorityWriteScheduler(nil) },
3271 }
3272 srv.nextProtoErr = http2ConfigureServer(srv, conf)
3273 }
3274 }
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
3288 return &timeoutHandler{
3289 handler: h,
3290 body: msg,
3291 dt: dt,
3292 }
3293 }
3294
3295
3296
3297 var ErrHandlerTimeout = errors.New("http: Handler timeout")
3298
3299 type timeoutHandler struct {
3300 handler Handler
3301 body string
3302 dt time.Duration
3303
3304
3305
3306 testContext context.Context
3307 }
3308
3309 func (h *timeoutHandler) errorBody() string {
3310 if h.body != "" {
3311 return h.body
3312 }
3313 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
3314 }
3315
3316 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
3317 ctx := h.testContext
3318 if ctx == nil {
3319 var cancelCtx context.CancelFunc
3320 ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
3321 defer cancelCtx()
3322 }
3323 r = r.WithContext(ctx)
3324 done := make(chan struct{})
3325 tw := &timeoutWriter{
3326 w: w,
3327 h: make(Header),
3328 req: r,
3329 }
3330 panicChan := make(chan interface{}, 1)
3331 go func() {
3332 defer func() {
3333 if p := recover(); p != nil {
3334 panicChan <- p
3335 }
3336 }()
3337 h.handler.ServeHTTP(tw, r)
3338 close(done)
3339 }()
3340 select {
3341 case p := <-panicChan:
3342 panic(p)
3343 case <-done:
3344 tw.mu.Lock()
3345 defer tw.mu.Unlock()
3346 dst := w.Header()
3347 for k, vv := range tw.h {
3348 dst[k] = vv
3349 }
3350 if !tw.wroteHeader {
3351 tw.code = StatusOK
3352 }
3353 w.WriteHeader(tw.code)
3354 w.Write(tw.wbuf.Bytes())
3355 case <-ctx.Done():
3356 tw.mu.Lock()
3357 defer tw.mu.Unlock()
3358 w.WriteHeader(StatusServiceUnavailable)
3359 io.WriteString(w, h.errorBody())
3360 tw.timedOut = true
3361 }
3362 }
3363
3364 type timeoutWriter struct {
3365 w ResponseWriter
3366 h Header
3367 wbuf bytes.Buffer
3368 req *Request
3369
3370 mu sync.Mutex
3371 timedOut bool
3372 wroteHeader bool
3373 code int
3374 }
3375
3376 var _ Pusher = (*timeoutWriter)(nil)
3377
3378
3379 func (tw *timeoutWriter) Push(target string, opts *PushOptions) error {
3380 if pusher, ok := tw.w.(Pusher); ok {
3381 return pusher.Push(target, opts)
3382 }
3383 return ErrNotSupported
3384 }
3385
3386 func (tw *timeoutWriter) Header() Header { return tw.h }
3387
3388 func (tw *timeoutWriter) Write(p []byte) (int, error) {
3389 tw.mu.Lock()
3390 defer tw.mu.Unlock()
3391 if tw.timedOut {
3392 return 0, ErrHandlerTimeout
3393 }
3394 if !tw.wroteHeader {
3395 tw.writeHeaderLocked(StatusOK)
3396 }
3397 return tw.wbuf.Write(p)
3398 }
3399
3400 func (tw *timeoutWriter) writeHeaderLocked(code int) {
3401 checkWriteHeaderCode(code)
3402
3403 switch {
3404 case tw.timedOut:
3405 return
3406 case tw.wroteHeader:
3407 if tw.req != nil {
3408 caller := relevantCaller()
3409 logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
3410 }
3411 default:
3412 tw.wroteHeader = true
3413 tw.code = code
3414 }
3415 }
3416
3417 func (tw *timeoutWriter) WriteHeader(code int) {
3418 tw.mu.Lock()
3419 defer tw.mu.Unlock()
3420 tw.writeHeaderLocked(code)
3421 }
3422
3423
3424
3425 type onceCloseListener struct {
3426 net.Listener
3427 once sync.Once
3428 closeErr error
3429 }
3430
3431 func (oc *onceCloseListener) Close() error {
3432 oc.once.Do(oc.close)
3433 return oc.closeErr
3434 }
3435
3436 func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() }
3437
3438
3439 type globalOptionsHandler struct{}
3440
3441 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
3442 w.Header().Set("Content-Length", "0")
3443 if r.ContentLength != 0 {
3444
3445
3446
3447
3448
3449 mb := MaxBytesReader(w, r.Body, 4<<10)
3450 io.Copy(io.Discard, mb)
3451 }
3452 }
3453
3454
3455
3456
3457 type initALPNRequest struct {
3458 ctx context.Context
3459 c *tls.Conn
3460 h serverHandler
3461 }
3462
3463
3464
3465
3466
3467 func (h initALPNRequest) BaseContext() context.Context { return h.ctx }
3468
3469 func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
3470 if req.TLS == nil {
3471 req.TLS = &tls.ConnectionState{}
3472 *req.TLS = h.c.ConnectionState()
3473 }
3474 if req.Body == nil {
3475 req.Body = NoBody
3476 }
3477 if req.RemoteAddr == "" {
3478 req.RemoteAddr = h.c.RemoteAddr().String()
3479 }
3480 h.h.ServeHTTP(rw, req)
3481 }
3482
3483
3484 type loggingConn struct {
3485 name string
3486 net.Conn
3487 }
3488
3489 var (
3490 uniqNameMu sync.Mutex
3491 uniqNameNext = make(map[string]int)
3492 )
3493
3494 func newLoggingConn(baseName string, c net.Conn) net.Conn {
3495 uniqNameMu.Lock()
3496 defer uniqNameMu.Unlock()
3497 uniqNameNext[baseName]++
3498 return &loggingConn{
3499 name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
3500 Conn: c,
3501 }
3502 }
3503
3504 func (c *loggingConn) Write(p []byte) (n int, err error) {
3505 log.Printf("%s.Write(%d) = ....", c.name, len(p))
3506 n, err = c.Conn.Write(p)
3507 log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
3508 return
3509 }
3510
3511 func (c *loggingConn) Read(p []byte) (n int, err error) {
3512 log.Printf("%s.Read(%d) = ....", c.name, len(p))
3513 n, err = c.Conn.Read(p)
3514 log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
3515 return
3516 }
3517
3518 func (c *loggingConn) Close() (err error) {
3519 log.Printf("%s.Close() = ...", c.name)
3520 err = c.Conn.Close()
3521 log.Printf("%s.Close() = %v", c.name, err)
3522 return
3523 }
3524
3525
3526
3527
3528 type checkConnErrorWriter struct {
3529 c *conn
3530 }
3531
3532 func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
3533 n, err = w.c.rwc.Write(p)
3534 if err != nil && w.c.werr == nil {
3535 w.c.werr = err
3536 w.c.cancelCtx()
3537 }
3538 return
3539 }
3540
3541 func numLeadingCRorLF(v []byte) (n int) {
3542 for _, b := range v {
3543 if b == '\r' || b == '\n' {
3544 n++
3545 continue
3546 }
3547 break
3548 }
3549 return
3550
3551 }
3552
3553 func strSliceContains(ss []string, s string) bool {
3554 for _, v := range ss {
3555 if v == s {
3556 return true
3557 }
3558 }
3559 return false
3560 }
3561
3562
3563
3564 func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool {
3565 switch string(hdr[:]) {
3566 case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
3567 return true
3568 }
3569 return false
3570 }
3571
View as plain text