1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 package http2
27
28 import (
29 "bufio"
30 "bytes"
31 "context"
32 "crypto/rand"
33 "crypto/tls"
34 "errors"
35 "fmt"
36 "io"
37 "log"
38 "math"
39 "net"
40 "net/http/internal"
41 "net/http/internal/httpcommon"
42 "net/textproto"
43 "net/url"
44 "os"
45 "reflect"
46 "runtime"
47 "slices"
48 "strconv"
49 "strings"
50 "sync"
51 "time"
52
53 "golang.org/x/net/http/httpguts"
54 "golang.org/x/net/http2/hpack"
55 )
56
57 const (
58 prefaceTimeout = 10 * time.Second
59 firstSettingsTimeout = 2 * time.Second
60 handlerChunkWriteSize = 4 << 10
61 defaultMaxStreams = 250
62
63
64
65
66 maxQueuedControlFrames = 10000
67 )
68
69 var (
70 errClientDisconnected = errors.New("client disconnected")
71 errClosedBody = errors.New("body closed by handler")
72 errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
73 errStreamClosed = errors.New("http2: stream closed")
74 )
75
76 var responseWriterStatePool = sync.Pool{
77 New: func() any {
78 rws := &responseWriterState{}
79 rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
80 return rws
81 },
82 }
83
84
85 var (
86 testHookOnConn func()
87 testHookOnPanicMu *sync.Mutex
88 testHookOnPanic func(sc *serverConn, panicVal any) (rePanic bool)
89 )
90
91
92 type Server struct {
93 mu sync.Mutex
94 activeConns map[*serverConn]struct{}
95
96
97
98 errChanPool sync.Pool
99 }
100
101 func (s *Server) registerConn(sc *serverConn) {
102 if s == nil {
103 return
104 }
105 s.mu.Lock()
106 s.activeConns[sc] = struct{}{}
107 s.mu.Unlock()
108 }
109
110 func (s *Server) unregisterConn(sc *serverConn) {
111 if s == nil {
112 return
113 }
114 s.mu.Lock()
115 delete(s.activeConns, sc)
116 s.mu.Unlock()
117 }
118
119 func (s *Server) startGracefulShutdown() {
120 if s == nil {
121 return
122 }
123 s.mu.Lock()
124 for sc := range s.activeConns {
125 sc.startGracefulShutdown()
126 }
127 s.mu.Unlock()
128 }
129
130
131
132 var errChanPool = sync.Pool{
133 New: func() any { return make(chan error, 1) },
134 }
135
136 func (s *Server) getErrChan() chan error {
137 if s == nil {
138 return errChanPool.Get().(chan error)
139 }
140 return s.errChanPool.Get().(chan error)
141 }
142
143 func (s *Server) putErrChan(ch chan error) {
144 if s == nil {
145 errChanPool.Put(ch)
146 return
147 }
148 s.errChanPool.Put(ch)
149 }
150
151 func (s *Server) Configure(conf ServerConfig, tcfg *tls.Config) error {
152 s.activeConns = make(map[*serverConn]struct{})
153 s.errChanPool = sync.Pool{New: func() any { return make(chan error, 1) }}
154
155 if tcfg.CipherSuites != nil && tcfg.MinVersion < tls.VersionTLS13 {
156
157
158
159 haveRequired := false
160 for _, cs := range tcfg.CipherSuites {
161 switch cs {
162 case tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
163
164
165 tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
166 haveRequired = true
167 }
168 }
169 if !haveRequired {
170 return fmt.Errorf("http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher (need at least one of TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 or TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)")
171 }
172 }
173
174
175
176
177
178
179
180
181 return nil
182 }
183
184 func (s *Server) GracefulShutdown() {
185 s.startGracefulShutdown()
186 }
187
188
189 type ServeConnOpts struct {
190
191
192 Context context.Context
193
194
195
196 BaseConfig ServerConfig
197
198
199
200
201 Handler Handler
202
203
204
205 Settings []byte
206
207 UpgradeRequest *ServerRequest
208
209
210
211 SawClientPreface bool
212 }
213
214 func (o *ServeConnOpts) context() context.Context {
215 if o != nil && o.Context != nil {
216 return o.Context
217 }
218 return context.Background()
219 }
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235 func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
236 if opts == nil {
237 opts = &ServeConnOpts{}
238 }
239
240 var newf func(*serverConn)
241 if inTests {
242
243 newf, _ = opts.Context.Value(NewConnContextKey).(func(*serverConn))
244 }
245
246 s.serveConn(c, opts, newf)
247 }
248
249 type contextKey string
250
251 var (
252 NewConnContextKey = new("NewConnContextKey")
253 ConnectionStateContextKey = new("ConnectionStateContextKey")
254 )
255
256 func (s *Server) serveConn(c net.Conn, opts *ServeConnOpts, newf func(*serverConn)) {
257 baseCtx, cancel := serverConnBaseContext(c, opts)
258 defer cancel()
259
260 conf := configFromServer(opts.BaseConfig)
261 sc := &serverConn{
262 srv: s,
263 hs: opts.BaseConfig,
264 conn: c,
265 baseCtx: baseCtx,
266 remoteAddrStr: c.RemoteAddr().String(),
267 bw: newBufferedWriter(c, conf.WriteByteTimeout),
268 handler: opts.Handler,
269 streams: make(map[uint32]*stream),
270 readFrameCh: make(chan readFrameResult),
271 wantWriteFrameCh: make(chan FrameWriteRequest, 8),
272 serveMsgCh: make(chan any, 8),
273 wroteFrameCh: make(chan frameWriteResult, 1),
274 bodyReadCh: make(chan bodyReadMsg),
275 doneServing: make(chan struct{}),
276 clientMaxStreams: math.MaxUint32,
277 advMaxStreams: uint32(conf.MaxConcurrentStreams),
278 initialStreamSendWindowSize: initialWindowSize,
279 initialStreamRecvWindowSize: int32(conf.MaxReceiveBufferPerStream),
280 maxFrameSize: initialMaxFrameSize,
281 pingTimeout: conf.PingTimeout,
282 countErrorFunc: conf.CountError,
283 serveG: newGoroutineLock(),
284 pushEnabled: true,
285 sawClientPreface: opts.SawClientPreface,
286 }
287 if newf != nil {
288 newf(sc)
289 }
290
291 s.registerConn(sc)
292 defer s.unregisterConn(sc)
293
294 switch {
295 case sc.hs.DisableClientPriority():
296 sc.writeSched = newRoundRobinWriteScheduler()
297 default:
298 sc.writeSched = newPriorityWriteSchedulerRFC9218()
299 }
300
301
302
303
304 sc.flow.add(initialWindowSize)
305 sc.inflow.init(initialWindowSize)
306 sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
307 sc.hpackEncoder.SetMaxDynamicTableSizeLimit(uint32(conf.MaxEncoderHeaderTableSize))
308
309 fr := NewFramer(sc.bw, c)
310 if conf.CountError != nil {
311 fr.countError = conf.CountError
312 }
313 fr.ReadMetaHeaders = hpack.NewDecoder(uint32(conf.MaxDecoderHeaderTableSize), nil)
314 fr.MaxHeaderListSize = sc.maxHeaderListSize()
315 fr.MaxHeaderValueCount = sc.hs.MaxHeaderValueCount()
316 fr.SetMaxReadFrameSize(uint32(conf.MaxReadFrameSize))
317 sc.framer = fr
318
319 if tc, ok := c.(connectionStater); ok {
320 sc.tlsState = new(tls.ConnectionState)
321 *sc.tlsState = tc.ConnectionState()
322
323
324 if inTests {
325 f, ok := opts.Context.Value(ConnectionStateContextKey).(func() tls.ConnectionState)
326 if ok {
327 *sc.tlsState = f()
328 }
329 }
330
331
332
333
334
335
336
337
338
339
340
341 if sc.tlsState.Version < tls.VersionTLS12 {
342 sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
343 return
344 }
345
346 if sc.tlsState.ServerName == "" {
347
348
349
350
351
352
353
354
355
356 }
357
358 if !conf.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
359
360
361
362
363
364
365
366
367
368
369 sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
370 return
371 }
372 }
373
374 if opts.Settings != nil {
375 fr := &SettingsFrame{
376 FrameHeader: FrameHeader{valid: true},
377 p: opts.Settings,
378 }
379 if err := fr.ForeachSetting(sc.processSetting); err != nil {
380 sc.rejectConn(ErrCodeProtocol, "invalid settings")
381 return
382 }
383 opts.Settings = nil
384 }
385
386 if opts.UpgradeRequest != nil {
387 sc.upgradeRequest(opts.UpgradeRequest)
388 opts.UpgradeRequest = nil
389 }
390
391 sc.serve(conf)
392 }
393
394 func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx context.Context, cancel func()) {
395 return context.WithCancel(opts.context())
396 }
397
398 func (sc *serverConn) rejectConn(err ErrCode, debug string) {
399 sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
400
401 sc.framer.WriteGoAway(0, err, []byte(debug))
402 sc.bw.Flush()
403 sc.conn.Close()
404 }
405
406 type serverConn struct {
407
408 srv *Server
409 hs ServerConfig
410 conn net.Conn
411 bw *bufferedWriter
412 handler Handler
413 baseCtx context.Context
414 framer *Framer
415 doneServing chan struct{}
416 readFrameCh chan readFrameResult
417 wantWriteFrameCh chan FrameWriteRequest
418 wroteFrameCh chan frameWriteResult
419 bodyReadCh chan bodyReadMsg
420 serveMsgCh chan any
421 flow outflow
422 inflow inflow
423 tlsState *tls.ConnectionState
424 remoteAddrStr string
425 writeSched WriteScheduler
426 countErrorFunc func(errType string)
427
428
429 serveG goroutineLock
430 pushEnabled bool
431 sawClientPreface bool
432 sawFirstSettings bool
433 needToSendSettingsAck bool
434 unackedSettings int
435 queuedControlFrames int
436 clientMaxStreams uint32
437 advMaxStreams uint32
438 curClientStreams uint32
439 curPushedStreams uint32
440 curHandlers uint32
441 maxClientStreamID uint32
442 maxPushPromiseID uint32
443 streams map[uint32]*stream
444 unstartedHandlers []unstartedHandler
445 initialStreamSendWindowSize int32
446 initialStreamRecvWindowSize int32
447 maxFrameSize int32
448 peerMaxHeaderListSize uint32
449 canonHeader map[string]string
450 canonHeaderKeysSize int
451 writingFrame bool
452 writingFrameAsync bool
453 needsFrameFlush bool
454 inGoAway bool
455 inFrameScheduleLoop bool
456 needToSendGoAway bool
457 pingSent bool
458 sentPingData [8]byte
459 goAwayCode ErrCode
460 shutdownTimer *time.Timer
461 idleTimer *time.Timer
462 readIdleTimeout time.Duration
463 pingTimeout time.Duration
464 readIdleTimer *time.Timer
465
466
467 headerWriteBuf bytes.Buffer
468 hpackEncoder *hpack.Encoder
469
470
471 shutdownOnce sync.Once
472
473
474 hasIntermediary bool
475 priorityAware bool
476 }
477
478 func (sc *serverConn) writeSchedIgnoresRFC7540() bool {
479 switch sc.writeSched.(type) {
480 case *priorityWriteSchedulerRFC9218:
481 return true
482 case *roundRobinWriteScheduler:
483 return true
484 default:
485 return false
486 }
487 }
488
489 const DefaultMaxHeaderBytes = 1 << 20
490
491 func (sc *serverConn) maxHeaderListSize() uint32 {
492 n := sc.hs.MaxHeaderBytes()
493 if n <= 0 {
494 n = DefaultMaxHeaderBytes
495 }
496 return uint32(adjustHTTP1MaxHeaderSize(int64(n)))
497 }
498
499 func (sc *serverConn) curOpenStreams() uint32 {
500 sc.serveG.check()
501 return sc.curClientStreams + sc.curPushedStreams
502 }
503
504
505
506
507
508
509
510
511 type stream struct {
512
513 sc *serverConn
514 id uint32
515 body *pipe
516 cw closeWaiter
517 ctx context.Context
518 cancelCtx func()
519
520
521 bodyBytes int64
522 declBodyBytes int64
523 flow outflow
524 inflow inflow
525 state streamState
526 resetQueued bool
527 gotTrailerHeader bool
528 wroteHeaders bool
529 readDeadline *time.Timer
530 writeDeadline *time.Timer
531 closeErr error
532
533 trailer Header
534 reqTrailer Header
535 }
536
537 func (sc *serverConn) Framer() *Framer { return sc.framer }
538 func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
539 func (sc *serverConn) Flush() error { return sc.bw.Flush() }
540 func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
541 return sc.hpackEncoder, &sc.headerWriteBuf
542 }
543
544 func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
545 sc.serveG.check()
546
547 if st, ok := sc.streams[streamID]; ok {
548 return st.state, st
549 }
550
551
552
553
554
555
556 if streamID%2 == 1 {
557 if streamID <= sc.maxClientStreamID {
558 return stateClosed, nil
559 }
560 } else {
561 if streamID <= sc.maxPushPromiseID {
562 return stateClosed, nil
563 }
564 }
565 return stateIdle, nil
566 }
567
568
569
570
571 func (sc *serverConn) setConnState(state ConnState) {
572 sc.hs.ConnState(sc.conn, state)
573 }
574
575 func (sc *serverConn) vlogf(format string, args ...any) {
576 if VerboseLogs {
577 sc.logf(format, args...)
578 }
579 }
580
581 func (sc *serverConn) logf(format string, args ...any) {
582 if lg := sc.hs.ErrorLog(); lg != nil {
583 lg.Printf(format, args...)
584 } else {
585 log.Printf(format, args...)
586 }
587 }
588
589
590
591
592
593 func errno(v error) uintptr {
594 if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
595 return uintptr(rv.Uint())
596 }
597 return 0
598 }
599
600
601
602 func isClosedConnError(err error) bool {
603 if err == nil {
604 return false
605 }
606
607 if errors.Is(err, net.ErrClosed) {
608 return true
609 }
610
611
612
613
614
615 if runtime.GOOS == "windows" {
616 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
617 if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
618 const WSAECONNABORTED = 10053
619 const WSAECONNRESET = 10054
620 if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
621 return true
622 }
623 }
624 }
625 }
626 return false
627 }
628
629 func (sc *serverConn) condlogf(err error, format string, args ...any) {
630 if err == nil {
631 return
632 }
633 if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) || err == errPrefaceTimeout {
634
635 sc.vlogf(format, args...)
636 } else {
637 sc.logf(format, args...)
638 }
639 }
640
641
642
643
644
645
646 const maxCachedCanonicalHeadersKeysSize = 2048
647
648 func (sc *serverConn) canonicalHeader(v string) string {
649 sc.serveG.check()
650 cv, ok := httpcommon.CachedCanonicalHeader(v)
651 if ok {
652 return cv
653 }
654 cv, ok = sc.canonHeader[v]
655 if ok {
656 return cv
657 }
658 if sc.canonHeader == nil {
659 sc.canonHeader = make(map[string]string)
660 }
661 cv = textproto.CanonicalMIMEHeaderKey(v)
662 size := 100 + len(v)*2
663 if sc.canonHeaderKeysSize+size <= maxCachedCanonicalHeadersKeysSize {
664 sc.canonHeader[v] = cv
665 sc.canonHeaderKeysSize += size
666 }
667 return cv
668 }
669
670 type readFrameResult struct {
671 f Frame
672 err error
673
674
675
676
677 readMore func()
678 }
679
680
681
682
683
684 func (sc *serverConn) readFrames() {
685 gate := make(chan struct{})
686 gateDone := func() { gate <- struct{}{} }
687 for {
688 f, err := sc.framer.ReadFrame()
689 select {
690 case sc.readFrameCh <- readFrameResult{f, err, gateDone}:
691 case <-sc.doneServing:
692 return
693 }
694 select {
695 case <-gate:
696 case <-sc.doneServing:
697 return
698 }
699 if terminalReadFrameError(err) {
700 return
701 }
702 }
703 }
704
705
706 type frameWriteResult struct {
707 _ incomparable
708 wr FrameWriteRequest
709 err error
710 }
711
712
713
714
715
716 func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest, wd *writeData) {
717 var err error
718 if wd == nil {
719 err = wr.write.writeFrame(sc)
720 } else {
721 err = sc.framer.endWrite()
722 }
723 sc.wroteFrameCh <- frameWriteResult{wr: wr, err: err}
724 }
725
726 func (sc *serverConn) closeAllStreamsOnConnClose() {
727 sc.serveG.check()
728 for _, st := range sc.streams {
729 sc.closeStream(st, errClientDisconnected)
730 }
731 }
732
733 func (sc *serverConn) stopShutdownTimer() {
734 sc.serveG.check()
735 if t := sc.shutdownTimer; t != nil {
736 t.Stop()
737 }
738 }
739
740 func (sc *serverConn) notePanic() {
741
742 if testHookOnPanicMu != nil {
743 testHookOnPanicMu.Lock()
744 defer testHookOnPanicMu.Unlock()
745 }
746 if testHookOnPanic != nil {
747 if e := recover(); e != nil {
748 if testHookOnPanic(sc, e) {
749 panic(e)
750 }
751 }
752 }
753 }
754
755 func (sc *serverConn) serve(conf Config) {
756 sc.serveG.check()
757 defer sc.notePanic()
758 defer sc.conn.Close()
759 defer sc.closeAllStreamsOnConnClose()
760 defer sc.stopShutdownTimer()
761 defer close(sc.doneServing)
762
763 if VerboseLogs {
764 sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
765 }
766
767 settings := writeSettings{
768 {SettingMaxFrameSize, uint32(conf.MaxReadFrameSize)},
769 {SettingMaxConcurrentStreams, sc.advMaxStreams},
770 {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
771 {SettingHeaderTableSize, uint32(conf.MaxDecoderHeaderTableSize)},
772 {SettingInitialWindowSize, uint32(sc.initialStreamRecvWindowSize)},
773 }
774 if !disableExtendedConnectProtocol {
775 settings = append(settings, Setting{SettingEnableConnectProtocol, 1})
776 }
777 if sc.writeSchedIgnoresRFC7540() {
778 settings = append(settings, Setting{SettingNoRFC7540Priorities, 1})
779 }
780 sc.writeFrame(FrameWriteRequest{
781 write: settings,
782 })
783 sc.unackedSettings++
784
785
786
787 if diff := conf.MaxReceiveBufferPerConnection - initialWindowSize; diff > 0 {
788 sc.sendWindowUpdate(nil, int(diff))
789 }
790
791 if err := sc.readPreface(); err != nil {
792 sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
793 return
794 }
795
796
797
798
799 sc.setConnState(ConnStateActive)
800 sc.setConnState(ConnStateIdle)
801
802 if idle := sc.hs.IdleTimeout(); idle > 0 {
803 sc.idleTimer = time.AfterFunc(idle, sc.onIdleTimer)
804 defer sc.idleTimer.Stop()
805 }
806
807 if conf.SendPingTimeout > 0 {
808 sc.readIdleTimeout = conf.SendPingTimeout
809 sc.readIdleTimer = time.AfterFunc(conf.SendPingTimeout, sc.onReadIdleTimer)
810 defer sc.readIdleTimer.Stop()
811 }
812
813 go sc.readFrames()
814
815 settingsTimer := time.AfterFunc(firstSettingsTimeout, sc.onSettingsTimer)
816 defer settingsTimer.Stop()
817
818 lastFrameTime := time.Now()
819 loopNum := 0
820 for {
821 loopNum++
822 select {
823 case wr := <-sc.wantWriteFrameCh:
824 if se, ok := wr.write.(StreamError); ok {
825 sc.resetStream(se)
826 break
827 }
828 sc.writeFrame(wr)
829 case res := <-sc.wroteFrameCh:
830 sc.wroteFrame(res)
831 case res := <-sc.readFrameCh:
832 lastFrameTime = time.Now()
833
834
835 if sc.writingFrameAsync {
836 select {
837 case wroteRes := <-sc.wroteFrameCh:
838 sc.wroteFrame(wroteRes)
839 default:
840 }
841 }
842 if !sc.processFrameFromReader(res) {
843 return
844 }
845 res.readMore()
846 if settingsTimer != nil {
847 settingsTimer.Stop()
848 settingsTimer = nil
849 }
850 case m := <-sc.bodyReadCh:
851 sc.noteBodyRead(m.st, m.n)
852 case msg := <-sc.serveMsgCh:
853 switch v := msg.(type) {
854 case func(int):
855 v(loopNum)
856 case *serverMessage:
857 switch v {
858 case settingsTimerMsg:
859 sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
860 return
861 case idleTimerMsg:
862 sc.vlogf("connection is idle")
863 sc.goAway(ErrCodeNo)
864 case readIdleTimerMsg:
865 sc.handlePingTimer(lastFrameTime)
866 case shutdownTimerMsg:
867 sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
868 return
869 case gracefulShutdownMsg:
870 sc.startGracefulShutdownInternal()
871 case handlerDoneMsg:
872 sc.handlerDone()
873 default:
874 panic("unknown timer")
875 }
876 case *startPushRequest:
877 sc.startPush(v)
878 case func(*serverConn):
879 v(sc)
880 default:
881 panic(fmt.Sprintf("unexpected type %T", v))
882 }
883 }
884
885
886
887
888 if sc.queuedControlFrames > maxQueuedControlFrames {
889 sc.vlogf("http2: too many control frames in send queue, closing connection")
890 return
891 }
892
893
894
895
896 sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame
897 gracefulShutdownComplete := sc.goAwayCode == ErrCodeNo && sc.curOpenStreams() == 0
898 if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != ErrCodeNo || gracefulShutdownComplete) {
899 sc.shutDownIn(goAwayTimeout)
900 }
901 }
902 }
903
904 func (sc *serverConn) handlePingTimer(lastFrameReadTime time.Time) {
905 if sc.pingSent {
906 sc.logf("timeout waiting for PING response")
907 if f := sc.countErrorFunc; f != nil {
908 f("conn_close_lost_ping")
909 }
910 sc.conn.Close()
911 return
912 }
913
914 pingAt := lastFrameReadTime.Add(sc.readIdleTimeout)
915 now := time.Now()
916 if pingAt.After(now) {
917
918
919 sc.readIdleTimer.Reset(pingAt.Sub(now))
920 return
921 }
922
923 sc.pingSent = true
924
925
926 _, _ = rand.Read(sc.sentPingData[:])
927 sc.writeFrame(FrameWriteRequest{
928 write: &writePing{data: sc.sentPingData},
929 })
930 sc.readIdleTimer.Reset(sc.pingTimeout)
931 }
932
933 type serverMessage int
934
935
936 var (
937 settingsTimerMsg = new(serverMessage)
938 idleTimerMsg = new(serverMessage)
939 readIdleTimerMsg = new(serverMessage)
940 shutdownTimerMsg = new(serverMessage)
941 gracefulShutdownMsg = new(serverMessage)
942 handlerDoneMsg = new(serverMessage)
943 )
944
945 func (sc *serverConn) onSettingsTimer() { sc.sendServeMsg(settingsTimerMsg) }
946 func (sc *serverConn) onIdleTimer() { sc.sendServeMsg(idleTimerMsg) }
947 func (sc *serverConn) onReadIdleTimer() { sc.sendServeMsg(readIdleTimerMsg) }
948 func (sc *serverConn) onShutdownTimer() { sc.sendServeMsg(shutdownTimerMsg) }
949
950 func (sc *serverConn) sendServeMsg(msg any) {
951 sc.serveG.checkNotOn()
952 select {
953 case sc.serveMsgCh <- msg:
954 case <-sc.doneServing:
955 }
956 }
957
958 var errPrefaceTimeout = errors.New("timeout waiting for client preface")
959
960
961
962
963 func (sc *serverConn) readPreface() error {
964 if sc.sawClientPreface {
965 return nil
966 }
967 errc := make(chan error, 1)
968 go func() {
969
970 buf := make([]byte, len(ClientPreface))
971 if _, err := io.ReadFull(sc.conn, buf); err != nil {
972 errc <- err
973 } else if !bytes.Equal(buf, clientPreface) {
974 errc <- fmt.Errorf("bogus greeting %q", buf)
975 } else {
976 errc <- nil
977 }
978 }()
979 timer := time.NewTimer(prefaceTimeout)
980 defer timer.Stop()
981 select {
982 case <-timer.C:
983 return errPrefaceTimeout
984 case err := <-errc:
985 if err == nil {
986 if VerboseLogs {
987 sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
988 }
989 }
990 return err
991 }
992 }
993
994 var writeDataPool = sync.Pool{
995 New: func() any { return new(writeData) },
996 }
997
998
999
1000 func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
1001 ch := sc.srv.getErrChan()
1002 writeArg := writeDataPool.Get().(*writeData)
1003 *writeArg = writeData{stream.id, data, endStream}
1004 err := sc.writeFrameFromHandler(FrameWriteRequest{
1005 write: writeArg,
1006 stream: stream,
1007 done: ch,
1008 })
1009 if err != nil {
1010 return err
1011 }
1012 var frameWriteDone bool
1013 select {
1014 case err = <-ch:
1015 frameWriteDone = true
1016 case <-sc.doneServing:
1017 return errClientDisconnected
1018 case <-stream.cw:
1019
1020
1021
1022
1023
1024
1025
1026 select {
1027 case err = <-ch:
1028 frameWriteDone = true
1029 default:
1030 return errStreamClosed
1031 }
1032 }
1033 sc.srv.putErrChan(ch)
1034 if frameWriteDone {
1035 writeDataPool.Put(writeArg)
1036 }
1037 return err
1038 }
1039
1040
1041
1042
1043
1044
1045
1046
1047 func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error {
1048 sc.serveG.checkNotOn()
1049 select {
1050 case sc.wantWriteFrameCh <- wr:
1051 return nil
1052 case <-sc.doneServing:
1053
1054
1055 return errClientDisconnected
1056 }
1057 }
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067 func (sc *serverConn) writeFrame(wr FrameWriteRequest) {
1068 sc.serveG.check()
1069
1070
1071 var ignoreWrite bool
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091 if wr.StreamID() != 0 {
1092 _, isReset := wr.write.(StreamError)
1093 if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset {
1094 ignoreWrite = true
1095 }
1096 }
1097
1098
1099
1100 switch wr.write.(type) {
1101 case *writeResHeaders:
1102 wr.stream.wroteHeaders = true
1103 case write100ContinueHeadersFrame:
1104 if wr.stream.wroteHeaders {
1105
1106
1107 if wr.done != nil {
1108 panic("wr.done != nil for write100ContinueHeadersFrame")
1109 }
1110 ignoreWrite = true
1111 }
1112 }
1113
1114 if !ignoreWrite {
1115 if wr.isControl() {
1116 sc.queuedControlFrames++
1117
1118
1119 if sc.queuedControlFrames < 0 {
1120 sc.conn.Close()
1121 }
1122 }
1123 sc.writeSched.Push(wr)
1124 }
1125 sc.scheduleFrameWrite()
1126 }
1127
1128
1129
1130
1131 func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) {
1132 sc.serveG.check()
1133 if sc.writingFrame {
1134 panic("internal error: can only be writing one frame at a time")
1135 }
1136
1137 st := wr.stream
1138 if st != nil {
1139 switch st.state {
1140 case stateHalfClosedLocal:
1141 switch wr.write.(type) {
1142 case StreamError, handlerPanicRST, writeWindowUpdate:
1143
1144
1145 default:
1146 panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
1147 }
1148 case stateClosed:
1149 panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
1150 }
1151 }
1152 if wpp, ok := wr.write.(*writePushPromise); ok {
1153 var err error
1154 wpp.promisedID, err = wpp.allocatePromisedID()
1155 if err != nil {
1156 sc.writingFrameAsync = false
1157 wr.replyToWriter(err)
1158 return
1159 }
1160 }
1161
1162 sc.writingFrame = true
1163 sc.needsFrameFlush = true
1164 if wr.write.staysWithinBuffer(sc.bw.Available()) {
1165 sc.writingFrameAsync = false
1166 err := wr.write.writeFrame(sc)
1167 sc.wroteFrame(frameWriteResult{wr: wr, err: err})
1168 } else if wd, ok := wr.write.(*writeData); ok {
1169
1170
1171
1172 sc.framer.startWriteDataPadded(wd.streamID, wd.endStream, wd.p, nil)
1173 sc.writingFrameAsync = true
1174 go sc.writeFrameAsync(wr, wd)
1175 } else {
1176 sc.writingFrameAsync = true
1177 go sc.writeFrameAsync(wr, nil)
1178 }
1179 }
1180
1181
1182
1183
1184 var errHandlerPanicked = errors.New("http2: handler panicked")
1185
1186
1187
1188 func (sc *serverConn) wroteFrame(res frameWriteResult) {
1189 sc.serveG.check()
1190 if !sc.writingFrame {
1191 panic("internal error: expected to be already writing a frame")
1192 }
1193 sc.writingFrame = false
1194 sc.writingFrameAsync = false
1195
1196 if res.err != nil {
1197 sc.conn.Close()
1198 }
1199
1200 wr := res.wr
1201
1202 if writeEndsStream(wr.write) {
1203 st := wr.stream
1204 if st == nil {
1205 panic("internal error: expecting non-nil stream")
1206 }
1207 switch st.state {
1208 case stateOpen:
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219 st.state = stateHalfClosedLocal
1220
1221
1222
1223
1224 sc.resetStream(streamError(st.id, ErrCodeNo))
1225 case stateHalfClosedRemote:
1226 sc.closeStream(st, errHandlerComplete)
1227 }
1228 } else {
1229 switch v := wr.write.(type) {
1230 case StreamError:
1231
1232 if st, ok := sc.streams[v.StreamID]; ok {
1233 sc.closeStream(st, v)
1234 }
1235 case handlerPanicRST:
1236 sc.closeStream(wr.stream, errHandlerPanicked)
1237 }
1238 }
1239
1240
1241 wr.replyToWriter(res.err)
1242
1243 sc.scheduleFrameWrite()
1244 }
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256 func (sc *serverConn) scheduleFrameWrite() {
1257 sc.serveG.check()
1258 if sc.writingFrame || sc.inFrameScheduleLoop {
1259 return
1260 }
1261 sc.inFrameScheduleLoop = true
1262 for !sc.writingFrameAsync {
1263 if sc.needToSendGoAway {
1264 sc.needToSendGoAway = false
1265 sc.startFrameWrite(FrameWriteRequest{
1266 write: &writeGoAway{
1267 maxStreamID: sc.maxClientStreamID,
1268 code: sc.goAwayCode,
1269 },
1270 })
1271 continue
1272 }
1273 if sc.needToSendSettingsAck {
1274 sc.needToSendSettingsAck = false
1275 sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}})
1276 continue
1277 }
1278 if !sc.inGoAway || sc.goAwayCode == ErrCodeNo {
1279 if wr, ok := sc.writeSched.Pop(); ok {
1280 if wr.isControl() {
1281 sc.queuedControlFrames--
1282 }
1283 sc.startFrameWrite(wr)
1284 continue
1285 }
1286 }
1287 if sc.needsFrameFlush {
1288 sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
1289 sc.needsFrameFlush = false
1290 continue
1291 }
1292 break
1293 }
1294 sc.inFrameScheduleLoop = false
1295 }
1296
1297
1298
1299
1300
1301
1302
1303
1304 func (sc *serverConn) startGracefulShutdown() {
1305 sc.serveG.checkNotOn()
1306 sc.shutdownOnce.Do(func() { sc.sendServeMsg(gracefulShutdownMsg) })
1307 }
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325 var goAwayTimeout = 1 * time.Second
1326
1327 func (sc *serverConn) startGracefulShutdownInternal() {
1328 sc.goAway(ErrCodeNo)
1329 }
1330
1331 func (sc *serverConn) goAway(code ErrCode) {
1332 sc.serveG.check()
1333 if sc.inGoAway {
1334 if sc.goAwayCode == ErrCodeNo {
1335 sc.goAwayCode = code
1336 }
1337 return
1338 }
1339 sc.inGoAway = true
1340 sc.needToSendGoAway = true
1341 sc.goAwayCode = code
1342 sc.scheduleFrameWrite()
1343 }
1344
1345 func (sc *serverConn) shutDownIn(d time.Duration) {
1346 sc.serveG.check()
1347 sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer)
1348 }
1349
1350 func (sc *serverConn) resetStream(se StreamError) {
1351 sc.serveG.check()
1352 sc.writeFrame(FrameWriteRequest{write: se})
1353 if st, ok := sc.streams[se.StreamID]; ok {
1354 st.resetQueued = true
1355 }
1356 }
1357
1358
1359
1360
1361 func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
1362 sc.serveG.check()
1363 err := res.err
1364 if err != nil {
1365 if err == ErrFrameTooLarge {
1366 sc.goAway(ErrCodeFrameSize)
1367 return true
1368 }
1369 clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
1370 if clientGone {
1371
1372
1373
1374
1375
1376
1377
1378
1379 return false
1380 }
1381 } else {
1382 f := res.f
1383 if VerboseLogs {
1384 sc.vlogf("http2: server read frame %v", summarizeFrame(f))
1385 }
1386 err = sc.processFrame(f)
1387 if err == nil {
1388 return true
1389 }
1390 }
1391
1392 switch ev := err.(type) {
1393 case StreamError:
1394 sc.resetStream(ev)
1395 return true
1396 case goAwayFlowError:
1397 sc.goAway(ErrCodeFlowControl)
1398 return true
1399 case ConnectionError:
1400 if res.f != nil {
1401 if id := res.f.Header().StreamID; id > sc.maxClientStreamID {
1402 sc.maxClientStreamID = id
1403 }
1404 }
1405 sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
1406 sc.goAway(ErrCode(ev))
1407 return true
1408 default:
1409 if res.err != nil {
1410 sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
1411 } else {
1412 sc.logf("http2: server closing client connection: %v", err)
1413 }
1414 return false
1415 }
1416 }
1417
1418 func (sc *serverConn) processFrame(f Frame) error {
1419 sc.serveG.check()
1420
1421
1422 if !sc.sawFirstSettings {
1423 if _, ok := f.(*SettingsFrame); !ok {
1424 return sc.countError("first_settings", ConnectionError(ErrCodeProtocol))
1425 }
1426 sc.sawFirstSettings = true
1427 }
1428
1429
1430
1431
1432
1433 if sc.inGoAway && (sc.goAwayCode != ErrCodeNo || f.Header().StreamID > sc.maxClientStreamID) {
1434
1435 if f, ok := f.(*DataFrame); ok {
1436 if !sc.inflow.take(f.Length) {
1437 return sc.countError("data_flow", streamError(f.Header().StreamID, ErrCodeFlowControl))
1438 }
1439 sc.sendWindowUpdate(nil, int(f.Length))
1440 }
1441 return nil
1442 }
1443
1444 switch f := f.(type) {
1445 case *SettingsFrame:
1446 return sc.processSettings(f)
1447 case *MetaHeadersFrame:
1448 return sc.processHeaders(f)
1449 case *WindowUpdateFrame:
1450 return sc.processWindowUpdate(f)
1451 case *PingFrame:
1452 return sc.processPing(f)
1453 case *DataFrame:
1454 return sc.processData(f)
1455 case *RSTStreamFrame:
1456 return sc.processResetStream(f)
1457 case *PriorityFrame:
1458 return sc.processPriority(f)
1459 case *GoAwayFrame:
1460 return sc.processGoAway(f)
1461 case *PushPromiseFrame:
1462
1463
1464 return sc.countError("push_promise", ConnectionError(ErrCodeProtocol))
1465 case *PriorityUpdateFrame:
1466 return sc.processPriorityUpdate(f)
1467 default:
1468 sc.vlogf("http2: server ignoring frame: %v", f.Header())
1469 return nil
1470 }
1471 }
1472
1473 func (sc *serverConn) processPing(f *PingFrame) error {
1474 sc.serveG.check()
1475 if f.IsAck() {
1476 if sc.pingSent && sc.sentPingData == f.Data {
1477
1478 sc.pingSent = false
1479 sc.readIdleTimer.Reset(sc.readIdleTimeout)
1480 }
1481
1482
1483 return nil
1484 }
1485 if f.StreamID != 0 {
1486
1487
1488
1489
1490
1491 return sc.countError("ping_on_stream", ConnectionError(ErrCodeProtocol))
1492 }
1493 sc.writeFrame(FrameWriteRequest{write: writePingAck{f}})
1494 return nil
1495 }
1496
1497 func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
1498 sc.serveG.check()
1499 switch {
1500 case f.StreamID != 0:
1501 state, st := sc.state(f.StreamID)
1502 if state == stateIdle {
1503
1504
1505
1506
1507 return sc.countError("stream_idle", ConnectionError(ErrCodeProtocol))
1508 }
1509 if st == nil {
1510
1511
1512
1513
1514
1515 return nil
1516 }
1517 if !st.flow.add(int32(f.Increment)) {
1518 return sc.countError("bad_flow", streamError(f.StreamID, ErrCodeFlowControl))
1519 }
1520 default:
1521 if !sc.flow.add(int32(f.Increment)) {
1522 return goAwayFlowError{}
1523 }
1524 }
1525 sc.scheduleFrameWrite()
1526 return nil
1527 }
1528
1529 func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
1530 sc.serveG.check()
1531
1532 state, st := sc.state(f.StreamID)
1533 if state == stateIdle {
1534
1535
1536
1537
1538
1539 return sc.countError("reset_idle_stream", ConnectionError(ErrCodeProtocol))
1540 }
1541 if st != nil {
1542 st.cancelCtx()
1543 sc.closeStream(st, streamError(f.StreamID, f.ErrCode))
1544 }
1545 return nil
1546 }
1547
1548 func (sc *serverConn) closeStream(st *stream, err error) {
1549 sc.serveG.check()
1550 if st.state == stateIdle || st.state == stateClosed {
1551 panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
1552 }
1553 st.state = stateClosed
1554 if st.readDeadline != nil {
1555 st.readDeadline.Stop()
1556 }
1557 if st.writeDeadline != nil {
1558 st.writeDeadline.Stop()
1559 }
1560 if st.isPushed() {
1561 sc.curPushedStreams--
1562 } else {
1563 sc.curClientStreams--
1564 }
1565 delete(sc.streams, st.id)
1566 if len(sc.streams) == 0 {
1567 sc.setConnState(ConnStateIdle)
1568 idleTimeout := sc.hs.IdleTimeout()
1569 if idleTimeout > 0 && sc.idleTimer != nil {
1570 sc.idleTimer.Reset(idleTimeout)
1571 }
1572 if h1ServerKeepAlivesDisabled(sc.hs) {
1573 sc.startGracefulShutdownInternal()
1574 }
1575 }
1576 if p := st.body; p != nil {
1577
1578
1579 sc.sendWindowUpdate(nil, p.Len())
1580
1581 p.CloseWithError(err)
1582 }
1583 if e, ok := err.(StreamError); ok {
1584 if e.Cause != nil {
1585 err = e.Cause
1586 } else {
1587 err = errStreamClosed
1588 }
1589 }
1590 st.closeErr = err
1591 st.cancelCtx()
1592 st.cw.Close()
1593 sc.writeSched.CloseStream(st.id)
1594 }
1595
1596 func (sc *serverConn) processSettings(f *SettingsFrame) error {
1597 sc.serveG.check()
1598 if f.IsAck() {
1599 sc.unackedSettings--
1600 if sc.unackedSettings < 0 {
1601
1602
1603
1604 return sc.countError("ack_mystery", ConnectionError(ErrCodeProtocol))
1605 }
1606 return nil
1607 }
1608 if f.NumSettings() > 100 || f.HasDuplicates() {
1609
1610
1611
1612 return sc.countError("settings_big_or_dups", ConnectionError(ErrCodeProtocol))
1613 }
1614 if err := f.ForeachSetting(sc.processSetting); err != nil {
1615 return err
1616 }
1617
1618
1619 sc.needToSendSettingsAck = true
1620 sc.scheduleFrameWrite()
1621 return nil
1622 }
1623
1624 func (sc *serverConn) processSetting(s Setting) error {
1625 sc.serveG.check()
1626 if err := s.Valid(); err != nil {
1627 return err
1628 }
1629 if VerboseLogs {
1630 sc.vlogf("http2: server processing setting %v", s)
1631 }
1632 switch s.ID {
1633 case SettingHeaderTableSize:
1634 sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
1635 case SettingEnablePush:
1636 sc.pushEnabled = s.Val != 0
1637 case SettingMaxConcurrentStreams:
1638 sc.clientMaxStreams = s.Val
1639 case SettingInitialWindowSize:
1640 return sc.processSettingInitialWindowSize(s.Val)
1641 case SettingMaxFrameSize:
1642 sc.maxFrameSize = int32(s.Val)
1643 case SettingMaxHeaderListSize:
1644 sc.peerMaxHeaderListSize = s.Val
1645 case SettingEnableConnectProtocol:
1646
1647
1648 case SettingNoRFC7540Priorities:
1649 if s.Val > 1 {
1650 return ConnectionError(ErrCodeProtocol)
1651 }
1652 default:
1653
1654
1655
1656 if VerboseLogs {
1657 sc.vlogf("http2: server ignoring unknown setting %v", s)
1658 }
1659 }
1660 return nil
1661 }
1662
1663 func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
1664 sc.serveG.check()
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674 old := sc.initialStreamSendWindowSize
1675 sc.initialStreamSendWindowSize = int32(val)
1676 growth := int32(val) - old
1677 for _, st := range sc.streams {
1678 if !st.flow.add(growth) {
1679
1680
1681
1682
1683
1684
1685 return sc.countError("setting_win_size", ConnectionError(ErrCodeFlowControl))
1686 }
1687 }
1688 return nil
1689 }
1690
1691 func (sc *serverConn) processData(f *DataFrame) error {
1692 sc.serveG.check()
1693 id := f.Header().StreamID
1694
1695 data := f.Data()
1696 state, st := sc.state(id)
1697 if id == 0 || state == stateIdle {
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708 return sc.countError("data_on_idle", ConnectionError(ErrCodeProtocol))
1709 }
1710
1711
1712
1713
1714 if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued {
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724 if !sc.inflow.take(f.Length) {
1725 return sc.countError("data_flow", streamError(id, ErrCodeFlowControl))
1726 }
1727 sc.sendWindowUpdate(nil, int(f.Length))
1728
1729 if st != nil && st.resetQueued {
1730
1731 return nil
1732 }
1733 return sc.countError("closed", streamError(id, ErrCodeStreamClosed))
1734 }
1735 if st.body == nil {
1736 panic("internal error: should have a body in this state")
1737 }
1738
1739
1740 if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
1741 if !sc.inflow.take(f.Length) {
1742 return sc.countError("data_flow", streamError(id, ErrCodeFlowControl))
1743 }
1744 sc.sendWindowUpdate(nil, int(f.Length))
1745
1746 st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
1747
1748
1749
1750 return sc.countError("send_too_much", streamError(id, ErrCodeProtocol))
1751 }
1752 if f.Length > 0 {
1753
1754 if !takeInflows(&sc.inflow, &st.inflow, f.Length) {
1755 return sc.countError("flow_on_data_length", streamError(id, ErrCodeFlowControl))
1756 }
1757
1758 if len(data) > 0 {
1759 st.bodyBytes += int64(len(data))
1760 wrote, err := st.body.Write(data)
1761 if err != nil {
1762
1763
1764
1765 sc.sendWindowUpdate(nil, int(f.Length)-wrote)
1766 return nil
1767 }
1768 if wrote != len(data) {
1769 panic("internal error: bad Writer")
1770 }
1771 }
1772
1773
1774
1775
1776
1777
1778 pad := int32(f.Length) - int32(len(data))
1779 sc.sendWindowUpdate32(nil, pad)
1780 sc.sendWindowUpdate32(st, pad)
1781 }
1782 if f.StreamEnded() {
1783 st.endStream()
1784 }
1785 return nil
1786 }
1787
1788 func (sc *serverConn) processGoAway(f *GoAwayFrame) error {
1789 sc.serveG.check()
1790 if f.ErrCode != ErrCodeNo {
1791 sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
1792 } else {
1793 sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
1794 }
1795 sc.startGracefulShutdownInternal()
1796
1797
1798 sc.pushEnabled = false
1799 return nil
1800 }
1801
1802
1803 func (st *stream) isPushed() bool {
1804 return st.id%2 == 0
1805 }
1806
1807
1808
1809 func (st *stream) endStream() {
1810 sc := st.sc
1811 sc.serveG.check()
1812
1813 if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
1814 st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
1815 st.declBodyBytes, st.bodyBytes))
1816 } else {
1817 st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
1818 st.body.CloseWithError(io.EOF)
1819 }
1820 st.state = stateHalfClosedRemote
1821 }
1822
1823
1824
1825 func (st *stream) copyTrailersToHandlerRequest() {
1826 for k, vv := range st.trailer {
1827 if _, ok := st.reqTrailer[k]; ok {
1828
1829 st.reqTrailer[k] = vv
1830 }
1831 }
1832 }
1833
1834
1835
1836 func (st *stream) onReadTimeout() {
1837 if st.body != nil {
1838
1839
1840 st.body.CloseWithError(fmt.Errorf("%w", os.ErrDeadlineExceeded))
1841 }
1842 }
1843
1844
1845
1846 func (st *stream) onWriteTimeout() {
1847 st.sc.writeFrameFromHandler(FrameWriteRequest{write: StreamError{
1848 StreamID: st.id,
1849 Code: ErrCodeInternal,
1850 Cause: os.ErrDeadlineExceeded,
1851 }})
1852 }
1853
1854 func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
1855 sc.serveG.check()
1856 id := f.StreamID
1857
1858
1859
1860
1861
1862 if id%2 != 1 {
1863 return sc.countError("headers_even", ConnectionError(ErrCodeProtocol))
1864 }
1865
1866
1867
1868
1869 if st := sc.streams[f.StreamID]; st != nil {
1870 if st.resetQueued {
1871
1872
1873 return nil
1874 }
1875
1876
1877
1878
1879 if st.state == stateHalfClosedRemote {
1880 return sc.countError("headers_half_closed", streamError(id, ErrCodeStreamClosed))
1881 }
1882 return st.processTrailerHeaders(f)
1883 }
1884
1885
1886
1887
1888
1889
1890 if id <= sc.maxClientStreamID {
1891 return sc.countError("stream_went_down", ConnectionError(ErrCodeProtocol))
1892 }
1893 sc.maxClientStreamID = id
1894
1895 if sc.idleTimer != nil {
1896 sc.idleTimer.Stop()
1897 }
1898
1899
1900
1901
1902
1903
1904
1905 if sc.curClientStreams+1 > sc.advMaxStreams {
1906 if sc.unackedSettings == 0 {
1907
1908 return sc.countError("over_max_streams", streamError(id, ErrCodeProtocol))
1909 }
1910
1911
1912
1913
1914
1915 return sc.countError("over_max_streams_race", streamError(id, ErrCodeRefusedStream))
1916 }
1917
1918 initialState := stateOpen
1919 if f.StreamEnded() {
1920 initialState = stateHalfClosedRemote
1921 }
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931 initialPriority := defaultRFC9218Priority(sc.priorityAware && !sc.hasIntermediary)
1932 if _, ok := sc.writeSched.(*priorityWriteSchedulerRFC9218); ok && !sc.hasIntermediary {
1933 headerPriority, priorityAware, hasIntermediary := f.rfc9218Priority(sc.priorityAware)
1934 initialPriority = headerPriority
1935 sc.hasIntermediary = hasIntermediary
1936 if priorityAware {
1937 sc.priorityAware = true
1938 }
1939 }
1940 st := sc.newStream(id, 0, initialState, initialPriority)
1941
1942 if f.HasPriority() {
1943 if err := sc.checkPriority(f.StreamID, f.Priority); err != nil {
1944 return err
1945 }
1946 if !sc.writeSchedIgnoresRFC7540() {
1947 sc.writeSched.AdjustStream(st.id, f.Priority)
1948 }
1949 }
1950
1951 rw, req, err := sc.newWriterAndRequest(st, f)
1952 if err != nil {
1953 return err
1954 }
1955 st.reqTrailer = req.Trailer
1956 if st.reqTrailer != nil {
1957 st.trailer = make(Header)
1958 }
1959 st.body = req.Body.(*requestBody).pipe
1960 st.declBodyBytes = req.ContentLength
1961
1962 handler := sc.handler.ServeHTTP
1963 if f.Truncated {
1964
1965 handler = handleHeaderListTooLong
1966 } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil {
1967 handler = serve400Handler{err}.ServeHTTP
1968 }
1969
1970 if sc.hs.ReadTimeout() > 0 {
1971 st.readDeadline = time.AfterFunc(sc.hs.ReadTimeout(), st.onReadTimeout)
1972 }
1973
1974 return sc.scheduleHandler(id, rw, req, handler)
1975 }
1976
1977 func (sc *serverConn) upgradeRequest(req *ServerRequest) {
1978 sc.serveG.check()
1979 id := uint32(1)
1980 sc.maxClientStreamID = id
1981 st := sc.newStream(id, 0, stateHalfClosedRemote, defaultRFC9218Priority(sc.priorityAware && !sc.hasIntermediary))
1982 st.reqTrailer = req.Trailer
1983 if st.reqTrailer != nil {
1984 st.trailer = make(Header)
1985 }
1986 rw := sc.newResponseWriter(st)
1987 rw.rws.req = *req
1988 req = &rw.rws.req
1989
1990
1991
1992
1993 sc.curHandlers++
1994 go sc.runHandler(rw, req, sc.handler.ServeHTTP)
1995 }
1996
1997 func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
1998 sc := st.sc
1999 sc.serveG.check()
2000 if st.gotTrailerHeader {
2001 return sc.countError("dup_trailers", ConnectionError(ErrCodeProtocol))
2002 }
2003 st.gotTrailerHeader = true
2004 if !f.StreamEnded() {
2005 return sc.countError("trailers_not_ended", streamError(st.id, ErrCodeProtocol))
2006 }
2007
2008 if len(f.PseudoFields()) > 0 {
2009 return sc.countError("trailers_pseudo", streamError(st.id, ErrCodeProtocol))
2010 }
2011 if f.Truncated {
2012 return sc.countError("trailers_too_large", streamError(st.id, ErrCodeProtocol))
2013 }
2014 if st.trailer != nil {
2015 for _, hf := range f.RegularFields() {
2016 key := sc.canonicalHeader(hf.Name)
2017 if !httpguts.ValidTrailerHeader(key) {
2018
2019
2020
2021 return sc.countError("trailers_bogus", streamError(st.id, ErrCodeProtocol))
2022 }
2023 st.trailer[key] = append(st.trailer[key], hf.Value)
2024 }
2025 }
2026 st.endStream()
2027 return nil
2028 }
2029
2030 func (sc *serverConn) checkPriority(streamID uint32, p PriorityParam) error {
2031 if streamID == p.StreamDep {
2032
2033
2034
2035
2036 return sc.countError("priority", streamError(streamID, ErrCodeProtocol))
2037 }
2038 return nil
2039 }
2040
2041 func (sc *serverConn) processPriority(f *PriorityFrame) error {
2042 if err := sc.checkPriority(f.StreamID, f.PriorityParam); err != nil {
2043 return err
2044 }
2045
2046
2047
2048
2049
2050 if sc.writeSchedIgnoresRFC7540() {
2051 return nil
2052 }
2053 sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam)
2054 return nil
2055 }
2056
2057 func (sc *serverConn) processPriorityUpdate(f *PriorityUpdateFrame) error {
2058 sc.priorityAware = true
2059 if _, ok := sc.writeSched.(*priorityWriteSchedulerRFC9218); !ok {
2060 return nil
2061 }
2062 p, ok := parseRFC9218Priority(f.Priority, sc.priorityAware)
2063 if !ok {
2064 return sc.countError("unparsable_priority_update", streamError(f.PrioritizedStreamID, ErrCodeProtocol))
2065 }
2066 sc.writeSched.AdjustStream(f.PrioritizedStreamID, p)
2067 return nil
2068 }
2069
2070 func (sc *serverConn) newStream(id, pusherID uint32, state streamState, priority PriorityParam) *stream {
2071 sc.serveG.check()
2072 if id == 0 {
2073 panic("internal error: cannot create stream with id 0")
2074 }
2075
2076 ctx, cancelCtx := context.WithCancel(sc.baseCtx)
2077 st := &stream{
2078 sc: sc,
2079 id: id,
2080 state: state,
2081 ctx: ctx,
2082 cancelCtx: cancelCtx,
2083 }
2084 st.cw.Init()
2085 st.flow.conn = &sc.flow
2086 st.flow.add(sc.initialStreamSendWindowSize)
2087 st.inflow.init(sc.initialStreamRecvWindowSize)
2088 if writeTimeout := sc.hs.WriteTimeout(); writeTimeout > 0 {
2089 st.writeDeadline = time.AfterFunc(writeTimeout, st.onWriteTimeout)
2090 }
2091
2092 sc.streams[id] = st
2093 sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID, priority: priority})
2094 if st.isPushed() {
2095 sc.curPushedStreams++
2096 } else {
2097 sc.curClientStreams++
2098 }
2099 if sc.curOpenStreams() == 1 {
2100 sc.setConnState(ConnStateActive)
2101 }
2102
2103 return st
2104 }
2105
2106 func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *ServerRequest, error) {
2107 sc.serveG.check()
2108
2109 rp := httpcommon.ServerRequestParam{
2110 Method: f.PseudoValue("method"),
2111 Scheme: f.PseudoValue("scheme"),
2112 Authority: f.PseudoValue("authority"),
2113 Path: f.PseudoValue("path"),
2114 Protocol: f.PseudoValue("protocol"),
2115 }
2116
2117
2118 if disableExtendedConnectProtocol && rp.Protocol != "" {
2119 return nil, nil, sc.countError("bad_connect", streamError(f.StreamID, ErrCodeProtocol))
2120 }
2121
2122 isConnect := rp.Method == "CONNECT"
2123 if isConnect {
2124 if rp.Protocol == "" && (rp.Path != "" || rp.Scheme != "" || rp.Authority == "") {
2125 return nil, nil, sc.countError("bad_connect", streamError(f.StreamID, ErrCodeProtocol))
2126 }
2127 } else if rp.Method == "" || rp.Path == "" || (rp.Scheme != "https" && rp.Scheme != "http") {
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138 return nil, nil, sc.countError("bad_path_method", streamError(f.StreamID, ErrCodeProtocol))
2139 }
2140
2141 header := make(Header)
2142 rp.Header = header
2143 for _, hf := range f.RegularFields() {
2144 header.Add(sc.canonicalHeader(hf.Name), hf.Value)
2145 }
2146 if rp.Authority == "" {
2147 rp.Authority = header.Get("Host")
2148 }
2149 if rp.Protocol != "" {
2150 header.Set(":protocol", rp.Protocol)
2151 }
2152
2153 rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
2154 if err != nil {
2155 return nil, nil, err
2156 }
2157 bodyOpen := !f.StreamEnded()
2158 if clens, ok := rp.Header["Content-Length"]; ok {
2159 if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
2160 req.ContentLength = int64(cl)
2161 } else {
2162 req.ContentLength = 0
2163 }
2164 if !bodyOpen && req.ContentLength != 0 {
2165 return nil, nil, sc.countError("bodyless_content_length", streamError(f.StreamID, ErrCodeProtocol))
2166 }
2167 if len(clens) > 1 {
2168 for _, dup := range clens[1:] {
2169 if clens[0] != dup {
2170 return nil, nil, sc.countError("duplicate_content_length", streamError(f.StreamID, ErrCodeProtocol))
2171 }
2172 }
2173 rp.Header["Content-Length"] = clens[:1]
2174 }
2175 }
2176 if bodyOpen {
2177 if _, ok := rp.Header["Content-Length"]; !ok {
2178 req.ContentLength = -1
2179 }
2180 req.Body.(*requestBody).pipe = &pipe{
2181 b: &dataBuffer{expected: req.ContentLength},
2182 }
2183 }
2184 return rw, req, nil
2185 }
2186
2187 func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp httpcommon.ServerRequestParam) (*responseWriter, *ServerRequest, error) {
2188 sc.serveG.check()
2189
2190 res := httpcommon.NewServerRequest(rp)
2191 if res.InvalidReason != "" {
2192 return nil, nil, sc.countError(res.InvalidReason, streamError(st.id, ErrCodeProtocol))
2193 }
2194
2195 body := &requestBody{
2196 conn: sc,
2197 stream: st,
2198 needsContinue: res.NeedsContinue,
2199 }
2200 rw := sc.newResponseWriter(st)
2201 rw.rws.req = ServerRequest{
2202 Context: st.ctx,
2203 Method: rp.Method,
2204 URL: res.URL,
2205 RemoteAddr: sc.remoteAddrStr,
2206 Header: rp.Header,
2207 RequestURI: res.RequestURI,
2208 Proto: "HTTP/2.0",
2209 ProtoMajor: 2,
2210 ProtoMinor: 0,
2211 TLS: sc.tlsState,
2212 Host: rp.Authority,
2213 Body: body,
2214 Trailer: res.Trailer,
2215 }
2216 return rw, &rw.rws.req, nil
2217 }
2218
2219 func (sc *serverConn) newResponseWriter(st *stream) *responseWriter {
2220 rws := responseWriterStatePool.Get().(*responseWriterState)
2221 bwSave := rws.bw
2222 *rws = responseWriterState{}
2223 rws.conn = sc
2224 rws.bw = bwSave
2225 rws.bw.Reset(chunkWriter{rws})
2226 rws.stream = st
2227 return &responseWriter{rws: rws}
2228 }
2229
2230 type unstartedHandler struct {
2231 streamID uint32
2232 rw *responseWriter
2233 req *ServerRequest
2234 handler func(*ResponseWriter, *ServerRequest)
2235 }
2236
2237
2238
2239 func (sc *serverConn) scheduleHandler(streamID uint32, rw *responseWriter, req *ServerRequest, handler func(*ResponseWriter, *ServerRequest)) error {
2240 sc.serveG.check()
2241 maxHandlers := sc.advMaxStreams
2242 if sc.curHandlers < maxHandlers {
2243 sc.curHandlers++
2244 go sc.runHandler(rw, req, handler)
2245 return nil
2246 }
2247 if len(sc.unstartedHandlers) > int(4*sc.advMaxStreams) {
2248 return sc.countError("too_many_early_resets", ConnectionError(ErrCodeEnhanceYourCalm))
2249 }
2250 sc.unstartedHandlers = append(sc.unstartedHandlers, unstartedHandler{
2251 streamID: streamID,
2252 rw: rw,
2253 req: req,
2254 handler: handler,
2255 })
2256 return nil
2257 }
2258
2259 func (sc *serverConn) handlerDone() {
2260 sc.serveG.check()
2261 sc.curHandlers--
2262 i := 0
2263 maxHandlers := sc.advMaxStreams
2264 for ; i < len(sc.unstartedHandlers); i++ {
2265 u := sc.unstartedHandlers[i]
2266 if sc.streams[u.streamID] == nil {
2267
2268 continue
2269 }
2270 if sc.curHandlers >= maxHandlers {
2271 break
2272 }
2273 sc.curHandlers++
2274 go sc.runHandler(u.rw, u.req, u.handler)
2275 sc.unstartedHandlers[i] = unstartedHandler{}
2276 }
2277 sc.unstartedHandlers = sc.unstartedHandlers[i:]
2278 if len(sc.unstartedHandlers) == 0 {
2279 sc.unstartedHandlers = nil
2280 }
2281 }
2282
2283
2284 func (sc *serverConn) runHandler(rw *responseWriter, req *ServerRequest, handler func(*ResponseWriter, *ServerRequest)) {
2285 defer sc.sendServeMsg(handlerDoneMsg)
2286 didPanic := true
2287 defer func() {
2288 rw.rws.stream.cancelCtx()
2289 if req.MultipartForm != nil {
2290 req.MultipartForm.RemoveAll()
2291 }
2292 if didPanic {
2293 e := recover()
2294 sc.writeFrameFromHandler(FrameWriteRequest{
2295 write: handlerPanicRST{rw.rws.stream.id},
2296 stream: rw.rws.stream,
2297 })
2298
2299 if e != nil && e != ErrAbortHandler {
2300 const size = 64 << 10
2301 buf := make([]byte, size)
2302 buf = buf[:runtime.Stack(buf, false)]
2303 sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
2304 }
2305 return
2306 }
2307 rw.handlerDone()
2308 }()
2309 handler(rw, req)
2310 didPanic = false
2311 }
2312
2313 func handleHeaderListTooLong(w *ResponseWriter, r *ServerRequest) {
2314
2315
2316
2317
2318 const statusRequestHeaderFieldsTooLarge = 431
2319 w.WriteHeader(statusRequestHeaderFieldsTooLarge)
2320 io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
2321 }
2322
2323
2324
2325 func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
2326 sc.serveG.checkNotOn()
2327 var errc chan error
2328 if headerData.h != nil {
2329
2330
2331
2332
2333 errc = sc.srv.getErrChan()
2334 }
2335 if err := sc.writeFrameFromHandler(FrameWriteRequest{
2336 write: headerData,
2337 stream: st,
2338 done: errc,
2339 }); err != nil {
2340 return err
2341 }
2342 if errc != nil {
2343 select {
2344 case err := <-errc:
2345 sc.srv.putErrChan(errc)
2346 return err
2347 case <-sc.doneServing:
2348 return errClientDisconnected
2349 case <-st.cw:
2350 return errStreamClosed
2351 }
2352 }
2353 return nil
2354 }
2355
2356
2357 func (sc *serverConn) write100ContinueHeaders(st *stream) {
2358 sc.writeFrameFromHandler(FrameWriteRequest{
2359 write: write100ContinueHeadersFrame{st.id},
2360 stream: st,
2361 })
2362 }
2363
2364
2365
2366 type bodyReadMsg struct {
2367 st *stream
2368 n int
2369 }
2370
2371
2372
2373
2374 func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
2375 sc.serveG.checkNotOn()
2376 if n > 0 {
2377 select {
2378 case sc.bodyReadCh <- bodyReadMsg{st, n}:
2379 case <-sc.doneServing:
2380 }
2381 }
2382 }
2383
2384 func (sc *serverConn) noteBodyRead(st *stream, n int) {
2385 sc.serveG.check()
2386 sc.sendWindowUpdate(nil, n)
2387 if st.state != stateHalfClosedRemote && st.state != stateClosed {
2388
2389
2390 sc.sendWindowUpdate(st, n)
2391 }
2392 }
2393
2394
2395 func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
2396 sc.sendWindowUpdate(st, int(n))
2397 }
2398
2399
2400 func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
2401 sc.serveG.check()
2402 var streamID uint32
2403 var send int32
2404 if st == nil {
2405 send = sc.inflow.add(n)
2406 } else {
2407 streamID = st.id
2408 send = st.inflow.add(n)
2409 }
2410 if send == 0 {
2411 return
2412 }
2413 sc.writeFrame(FrameWriteRequest{
2414 write: writeWindowUpdate{streamID: streamID, n: uint32(send)},
2415 stream: st,
2416 })
2417 }
2418
2419
2420
2421 type requestBody struct {
2422 _ incomparable
2423 stream *stream
2424 conn *serverConn
2425 closeOnce sync.Once
2426 sawEOF bool
2427 pipe *pipe
2428 needsContinue bool
2429 }
2430
2431 func (b *requestBody) Close() error {
2432 b.closeOnce.Do(func() {
2433 if b.pipe != nil {
2434 b.pipe.BreakWithError(errClosedBody)
2435 }
2436 })
2437 return nil
2438 }
2439
2440 func (b *requestBody) Read(p []byte) (n int, err error) {
2441 if b.needsContinue {
2442 b.needsContinue = false
2443 b.conn.write100ContinueHeaders(b.stream)
2444 }
2445 if b.pipe == nil || b.sawEOF {
2446 return 0, io.EOF
2447 }
2448 n, err = b.pipe.Read(p)
2449 if err == io.EOF {
2450 b.sawEOF = true
2451 }
2452 if b.conn == nil {
2453 return
2454 }
2455 b.conn.noteBodyReadFromHandler(b.stream, n, err)
2456 return
2457 }
2458
2459
2460
2461
2462
2463
2464
2465 type responseWriter struct {
2466 rws *responseWriterState
2467 }
2468
2469 type responseWriterState struct {
2470
2471 stream *stream
2472 req ServerRequest
2473 conn *serverConn
2474
2475
2476 bw *bufio.Writer
2477
2478
2479 handlerHeader Header
2480 snapHeader Header
2481 trailers []string
2482 status int
2483 wroteHeader bool
2484 sentHeader bool
2485 handlerDone bool
2486
2487 sentContentLen int64
2488 wroteBytes int64
2489
2490 closeNotifierMu sync.Mutex
2491 closeNotifierCh chan bool
2492 }
2493
2494 type chunkWriter struct{ rws *responseWriterState }
2495
2496 func (cw chunkWriter) Write(p []byte) (n int, err error) {
2497 n, err = cw.rws.writeChunk(p)
2498 if err == errStreamClosed {
2499
2500
2501 err = cw.rws.stream.closeErr
2502 }
2503 return n, err
2504 }
2505
2506 func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) > 0 }
2507
2508 func (rws *responseWriterState) hasNonemptyTrailers() bool {
2509 for _, trailer := range rws.trailers {
2510 if _, ok := rws.handlerHeader[trailer]; ok {
2511 return true
2512 }
2513 }
2514 return false
2515 }
2516
2517
2518
2519
2520 func (rws *responseWriterState) declareTrailer(k string) {
2521 k = textproto.CanonicalMIMEHeaderKey(k)
2522 if !httpguts.ValidTrailerHeader(k) {
2523
2524 rws.conn.logf("ignoring invalid trailer %q", k)
2525 return
2526 }
2527 if !slices.Contains(rws.trailers, k) {
2528 rws.trailers = append(rws.trailers, k)
2529 }
2530 }
2531
2532 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
2533
2534
2535
2536
2537
2538
2539
2540 func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
2541 if !rws.wroteHeader {
2542 rws.writeHeader(200)
2543 }
2544
2545 if rws.handlerDone {
2546 rws.promoteUndeclaredTrailers()
2547 }
2548
2549 isHeadResp := rws.req.Method == "HEAD"
2550 if !rws.sentHeader {
2551 rws.sentHeader = true
2552 var ctype, clen string
2553 if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
2554 rws.snapHeader.Del("Content-Length")
2555 if cl, err := strconv.ParseUint(clen, 10, 63); err == nil {
2556 rws.sentContentLen = int64(cl)
2557 } else {
2558 clen = ""
2559 }
2560 }
2561 _, hasContentLength := rws.snapHeader["Content-Length"]
2562 if !hasContentLength && clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
2563 clen = strconv.Itoa(len(p))
2564 }
2565 _, hasContentType := rws.snapHeader["Content-Type"]
2566
2567
2568 ce := rws.snapHeader.Get("Content-Encoding")
2569 hasCE := len(ce) > 0
2570 if !hasCE && !hasContentType && bodyAllowedForStatus(rws.status) && len(p) > 0 {
2571 ctype = internal.DetectContentType(p)
2572 }
2573 var date string
2574 if _, ok := rws.snapHeader["Date"]; !ok {
2575
2576 date = time.Now().UTC().Format(TimeFormat)
2577 }
2578
2579 for _, v := range rws.snapHeader["Trailer"] {
2580 foreachHeaderElement(v, rws.declareTrailer)
2581 }
2582
2583
2584
2585
2586
2587
2588 if _, ok := rws.snapHeader["Connection"]; ok {
2589 v := rws.snapHeader.Get("Connection")
2590 delete(rws.snapHeader, "Connection")
2591 if v == "close" {
2592 rws.conn.startGracefulShutdown()
2593 }
2594 }
2595
2596 endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
2597 err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2598 streamID: rws.stream.id,
2599 httpResCode: rws.status,
2600 h: rws.snapHeader,
2601 endStream: endStream,
2602 contentType: ctype,
2603 contentLength: clen,
2604 date: date,
2605 })
2606 if err != nil {
2607 return 0, err
2608 }
2609 if endStream {
2610 return 0, nil
2611 }
2612 }
2613 if isHeadResp {
2614 return len(p), nil
2615 }
2616 if len(p) == 0 && !rws.handlerDone {
2617 return 0, nil
2618 }
2619
2620
2621
2622 hasNonemptyTrailers := rws.hasNonemptyTrailers()
2623 endStream := rws.handlerDone && !hasNonemptyTrailers
2624 if len(p) > 0 || endStream {
2625
2626 if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
2627 return 0, err
2628 }
2629 }
2630
2631 if rws.handlerDone && hasNonemptyTrailers {
2632 err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2633 streamID: rws.stream.id,
2634 h: rws.handlerHeader,
2635 trailers: rws.trailers,
2636 endStream: true,
2637 })
2638 return len(p), err
2639 }
2640 return len(p), nil
2641 }
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656 const TrailerPrefix = "Trailer:"
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679 func (rws *responseWriterState) promoteUndeclaredTrailers() {
2680 for k, vv := range rws.handlerHeader {
2681 if !strings.HasPrefix(k, TrailerPrefix) {
2682 continue
2683 }
2684 trailerKey := strings.TrimPrefix(k, TrailerPrefix)
2685 rws.declareTrailer(trailerKey)
2686 rws.handlerHeader[textproto.CanonicalMIMEHeaderKey(trailerKey)] = vv
2687 }
2688
2689 if len(rws.trailers) > 1 {
2690 slices.Sort(rws.trailers)
2691 }
2692 }
2693
2694 func (w *responseWriter) SetReadDeadline(deadline time.Time) error {
2695 st := w.rws.stream
2696 if !deadline.IsZero() && deadline.Before(time.Now()) {
2697
2698
2699 st.onReadTimeout()
2700 return nil
2701 }
2702 w.rws.conn.sendServeMsg(func(sc *serverConn) {
2703 if st.readDeadline != nil {
2704 if !st.readDeadline.Stop() {
2705
2706 return
2707 }
2708 }
2709 if deadline.IsZero() {
2710 st.readDeadline = nil
2711 } else if st.readDeadline == nil {
2712 st.readDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onReadTimeout)
2713 } else {
2714 st.readDeadline.Reset(deadline.Sub(time.Now()))
2715 }
2716 })
2717 return nil
2718 }
2719
2720 func (w *responseWriter) SetWriteDeadline(deadline time.Time) error {
2721 st := w.rws.stream
2722 if !deadline.IsZero() && deadline.Before(time.Now()) {
2723
2724
2725 st.onWriteTimeout()
2726 return nil
2727 }
2728 w.rws.conn.sendServeMsg(func(sc *serverConn) {
2729 if st.writeDeadline != nil {
2730 if !st.writeDeadline.Stop() {
2731
2732 return
2733 }
2734 }
2735 if deadline.IsZero() {
2736 st.writeDeadline = nil
2737 } else if st.writeDeadline == nil {
2738 st.writeDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onWriteTimeout)
2739 } else {
2740 st.writeDeadline.Reset(deadline.Sub(time.Now()))
2741 }
2742 })
2743 return nil
2744 }
2745
2746 func (w *responseWriter) EnableFullDuplex() error {
2747
2748 return nil
2749 }
2750
2751 func (w *responseWriter) Flush() {
2752 w.FlushError()
2753 }
2754
2755 func (w *responseWriter) FlushError() error {
2756 rws := w.rws
2757 if rws == nil {
2758 panic("Header called after Handler finished")
2759 }
2760 var err error
2761 if rws.bw.Buffered() > 0 {
2762 err = rws.bw.Flush()
2763 } else {
2764
2765
2766
2767
2768 _, err = chunkWriter{rws}.Write(nil)
2769 if err == nil {
2770 select {
2771 case <-rws.stream.cw:
2772 err = rws.stream.closeErr
2773 default:
2774 }
2775 }
2776 }
2777 return err
2778 }
2779
2780 func (w *responseWriter) CloseNotify() <-chan bool {
2781 rws := w.rws
2782 if rws == nil {
2783 panic("CloseNotify called after Handler finished")
2784 }
2785 rws.closeNotifierMu.Lock()
2786 ch := rws.closeNotifierCh
2787 if ch == nil {
2788 ch = make(chan bool, 1)
2789 rws.closeNotifierCh = ch
2790 cw := rws.stream.cw
2791 go func() {
2792 cw.Wait()
2793 ch <- true
2794 }()
2795 }
2796 rws.closeNotifierMu.Unlock()
2797 return ch
2798 }
2799
2800 func (w *responseWriter) Header() Header {
2801 rws := w.rws
2802 if rws == nil {
2803 panic("Header called after Handler finished")
2804 }
2805 if rws.handlerHeader == nil {
2806 rws.handlerHeader = make(Header)
2807 }
2808 return rws.handlerHeader
2809 }
2810
2811
2812 func checkWriteHeaderCode(code int) {
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823 if code < 100 || code > 999 {
2824 panic(fmt.Sprintf("invalid WriteHeader code %v", code))
2825 }
2826 }
2827
2828 func (w *responseWriter) WriteHeader(code int) {
2829 rws := w.rws
2830 if rws == nil {
2831 panic("WriteHeader called after Handler finished")
2832 }
2833 rws.writeHeader(code)
2834 }
2835
2836 func (rws *responseWriterState) writeHeader(code int) {
2837 if rws.wroteHeader {
2838 return
2839 }
2840
2841 checkWriteHeaderCode(code)
2842
2843
2844 if code >= 100 && code <= 199 {
2845
2846 h := rws.handlerHeader
2847
2848 _, cl := h["Content-Length"]
2849 _, te := h["Transfer-Encoding"]
2850 if cl || te {
2851 h = cloneHeader(h)
2852 h.Del("Content-Length")
2853 h.Del("Transfer-Encoding")
2854 }
2855
2856 rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2857 streamID: rws.stream.id,
2858 httpResCode: code,
2859 h: h,
2860 endStream: rws.handlerDone && !rws.hasTrailers(),
2861 })
2862
2863 return
2864 }
2865
2866 rws.wroteHeader = true
2867 rws.status = code
2868 if len(rws.handlerHeader) > 0 {
2869 rws.snapHeader = cloneHeader(rws.handlerHeader)
2870 }
2871 }
2872
2873 func cloneHeader(h Header) Header {
2874 h2 := make(Header, len(h))
2875 for k, vv := range h {
2876 vv2 := make([]string, len(vv))
2877 copy(vv2, vv)
2878 h2[k] = vv2
2879 }
2880 return h2
2881 }
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891 func (w *responseWriter) Write(p []byte) (n int, err error) {
2892 return w.write(len(p), p, "")
2893 }
2894
2895 func (w *responseWriter) WriteString(s string) (n int, err error) {
2896 return w.write(len(s), nil, s)
2897 }
2898
2899
2900 func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
2901 rws := w.rws
2902 if rws == nil {
2903 panic("Write called after Handler finished")
2904 }
2905 if !rws.wroteHeader {
2906 w.WriteHeader(200)
2907 }
2908 if !bodyAllowedForStatus(rws.status) {
2909 return 0, ErrBodyNotAllowed
2910 }
2911 rws.wroteBytes += int64(len(dataB)) + int64(len(dataS))
2912 if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
2913
2914 return 0, errors.New("http2: handler wrote more than declared Content-Length")
2915 }
2916
2917 if dataB != nil {
2918 return rws.bw.Write(dataB)
2919 } else {
2920 return rws.bw.WriteString(dataS)
2921 }
2922 }
2923
2924 func (w *responseWriter) handlerDone() {
2925 rws := w.rws
2926 rws.handlerDone = true
2927 w.Flush()
2928 w.rws = nil
2929 responseWriterStatePool.Put(rws)
2930 }
2931
2932
2933 var (
2934 ErrRecursivePush = errors.New("http2: recursive push not allowed")
2935 ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
2936 )
2937
2938 func (w *responseWriter) Push(target, method string, header Header) error {
2939 st := w.rws.stream
2940 sc := st.sc
2941 sc.serveG.checkNotOn()
2942
2943
2944
2945 if st.isPushed() {
2946 return ErrRecursivePush
2947 }
2948
2949
2950 if method == "" {
2951 method = "GET"
2952 }
2953 if header == nil {
2954 header = Header{}
2955 }
2956 wantScheme := "http"
2957 if w.rws.req.TLS != nil {
2958 wantScheme = "https"
2959 }
2960
2961
2962 u, err := url.Parse(target)
2963 if err != nil {
2964 return err
2965 }
2966 if u.Scheme == "" {
2967 if !strings.HasPrefix(target, "/") {
2968 return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
2969 }
2970 u.Scheme = wantScheme
2971 u.Host = w.rws.req.Host
2972 } else {
2973 if u.Scheme != wantScheme {
2974 return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
2975 }
2976 if u.Host == "" {
2977 return errors.New("URL must have a host")
2978 }
2979 }
2980 for k := range header {
2981 if strings.HasPrefix(k, ":") {
2982 return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
2983 }
2984
2985
2986
2987
2988 if asciiEqualFold(k, "content-length") ||
2989 asciiEqualFold(k, "content-encoding") ||
2990 asciiEqualFold(k, "trailer") ||
2991 asciiEqualFold(k, "te") ||
2992 asciiEqualFold(k, "expect") ||
2993 asciiEqualFold(k, "host") {
2994 return fmt.Errorf("promised request headers cannot include %q", k)
2995 }
2996 }
2997 if err := checkValidHTTP2RequestHeaders(header); err != nil {
2998 return err
2999 }
3000
3001
3002
3003
3004 if method != "GET" && method != "HEAD" {
3005 return fmt.Errorf("method %q must be GET or HEAD", method)
3006 }
3007
3008 msg := &startPushRequest{
3009 parent: st,
3010 method: method,
3011 url: u,
3012 header: cloneHeader(header),
3013 done: sc.srv.getErrChan(),
3014 }
3015
3016 select {
3017 case <-sc.doneServing:
3018 return errClientDisconnected
3019 case <-st.cw:
3020 return errStreamClosed
3021 case sc.serveMsgCh <- msg:
3022 }
3023
3024 select {
3025 case <-sc.doneServing:
3026 return errClientDisconnected
3027 case <-st.cw:
3028 return errStreamClosed
3029 case err := <-msg.done:
3030 sc.srv.putErrChan(msg.done)
3031 return err
3032 }
3033 }
3034
3035 type startPushRequest struct {
3036 parent *stream
3037 method string
3038 url *url.URL
3039 header Header
3040 done chan error
3041 }
3042
3043 func (sc *serverConn) startPush(msg *startPushRequest) {
3044 sc.serveG.check()
3045
3046
3047
3048
3049 if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
3050
3051 msg.done <- errStreamClosed
3052 return
3053 }
3054
3055
3056 if !sc.pushEnabled {
3057 msg.done <- ErrNotSupported
3058 return
3059 }
3060
3061
3062
3063
3064 allocatePromisedID := func() (uint32, error) {
3065 sc.serveG.check()
3066
3067
3068
3069 if !sc.pushEnabled {
3070 return 0, ErrNotSupported
3071 }
3072
3073 if sc.curPushedStreams+1 > sc.clientMaxStreams {
3074 return 0, ErrPushLimitReached
3075 }
3076
3077
3078
3079
3080
3081 if sc.maxPushPromiseID+2 >= 1<<31 {
3082 sc.startGracefulShutdownInternal()
3083 return 0, ErrPushLimitReached
3084 }
3085 sc.maxPushPromiseID += 2
3086 promisedID := sc.maxPushPromiseID
3087
3088
3089
3090
3091
3092
3093 promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote, defaultRFC9218Priority(sc.priorityAware && !sc.hasIntermediary))
3094 rw, req, err := sc.newWriterAndRequestNoBody(promised, httpcommon.ServerRequestParam{
3095 Method: msg.method,
3096 Scheme: msg.url.Scheme,
3097 Authority: msg.url.Host,
3098 Path: msg.url.RequestURI(),
3099 Header: cloneHeader(msg.header),
3100 })
3101 if err != nil {
3102
3103 panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
3104 }
3105
3106 sc.curHandlers++
3107 go sc.runHandler(rw, req, sc.handler.ServeHTTP)
3108 return promisedID, nil
3109 }
3110
3111 sc.writeFrame(FrameWriteRequest{
3112 write: &writePushPromise{
3113 streamID: msg.parent.id,
3114 method: msg.method,
3115 url: msg.url,
3116 h: msg.header,
3117 allocatePromisedID: allocatePromisedID,
3118 },
3119 stream: msg.parent,
3120 done: msg.done,
3121 })
3122 }
3123
3124
3125
3126 func foreachHeaderElement(v string, fn func(string)) {
3127 v = textproto.TrimString(v)
3128 if v == "" {
3129 return
3130 }
3131 if !strings.Contains(v, ",") {
3132 fn(v)
3133 return
3134 }
3135 for f := range strings.SplitSeq(v, ",") {
3136 if f = textproto.TrimString(f); f != "" {
3137 fn(f)
3138 }
3139 }
3140 }
3141
3142
3143 var connHeaders = []string{
3144 "Connection",
3145 "Keep-Alive",
3146 "Proxy-Connection",
3147 "Transfer-Encoding",
3148 "Upgrade",
3149 }
3150
3151
3152
3153
3154 func checkValidHTTP2RequestHeaders(h Header) error {
3155 for _, k := range connHeaders {
3156 if _, ok := h[k]; ok {
3157 return fmt.Errorf("request header %q is not valid in HTTP/2", k)
3158 }
3159 }
3160 te := h["Te"]
3161 if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
3162 return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
3163 }
3164 return nil
3165 }
3166
3167 type serve400Handler struct {
3168 err error
3169 }
3170
3171 func (handler serve400Handler) ServeHTTP(w *ResponseWriter, r *ServerRequest) {
3172 const statusBadRequest = 400
3173
3174
3175 h := w.Header()
3176 h.Del("Content-Length")
3177 h.Set("Content-Type", "text/plain; charset=utf-8")
3178 h.Set("X-Content-Type-Options", "nosniff")
3179 w.WriteHeader(statusBadRequest)
3180 fmt.Fprintln(w, handler.err.Error())
3181 }
3182
3183
3184
3185
3186 func h1ServerKeepAlivesDisabled(hs ServerConfig) bool {
3187 return !hs.DoKeepAlives()
3188 }
3189
3190 func (sc *serverConn) countError(name string, err error) error {
3191 if sc == nil || sc.srv == nil {
3192 return err
3193 }
3194 f := sc.countErrorFunc
3195 if f == nil {
3196 return err
3197 }
3198 var typ string
3199 var code ErrCode
3200 switch e := err.(type) {
3201 case ConnectionError:
3202 typ = "conn"
3203 code = ErrCode(e)
3204 case StreamError:
3205 typ = "stream"
3206 code = ErrCode(e.Code)
3207 default:
3208 return err
3209 }
3210 codeStr := errCodeName[code]
3211 if codeStr == "" {
3212 codeStr = strconv.Itoa(int(code))
3213 }
3214 f(fmt.Sprintf("%s_%s_%s", typ, codeStr, name))
3215 return err
3216 }
3217
View as plain text