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 var tlsState *tls.ConnectionState
2191 if rp.Scheme == "https" {
2192 tlsState = sc.tlsState
2193 }
2194
2195 res := httpcommon.NewServerRequest(rp)
2196 if res.InvalidReason != "" {
2197 return nil, nil, sc.countError(res.InvalidReason, streamError(st.id, ErrCodeProtocol))
2198 }
2199
2200 body := &requestBody{
2201 conn: sc,
2202 stream: st,
2203 needsContinue: res.NeedsContinue,
2204 }
2205 rw := sc.newResponseWriter(st)
2206 rw.rws.req = ServerRequest{
2207 Context: st.ctx,
2208 Method: rp.Method,
2209 URL: res.URL,
2210 RemoteAddr: sc.remoteAddrStr,
2211 Header: rp.Header,
2212 RequestURI: res.RequestURI,
2213 Proto: "HTTP/2.0",
2214 ProtoMajor: 2,
2215 ProtoMinor: 0,
2216 TLS: tlsState,
2217 Host: rp.Authority,
2218 Body: body,
2219 Trailer: res.Trailer,
2220 }
2221 return rw, &rw.rws.req, nil
2222 }
2223
2224 func (sc *serverConn) newResponseWriter(st *stream) *responseWriter {
2225 rws := responseWriterStatePool.Get().(*responseWriterState)
2226 bwSave := rws.bw
2227 *rws = responseWriterState{}
2228 rws.conn = sc
2229 rws.bw = bwSave
2230 rws.bw.Reset(chunkWriter{rws})
2231 rws.stream = st
2232 return &responseWriter{rws: rws}
2233 }
2234
2235 type unstartedHandler struct {
2236 streamID uint32
2237 rw *responseWriter
2238 req *ServerRequest
2239 handler func(*ResponseWriter, *ServerRequest)
2240 }
2241
2242
2243
2244 func (sc *serverConn) scheduleHandler(streamID uint32, rw *responseWriter, req *ServerRequest, handler func(*ResponseWriter, *ServerRequest)) error {
2245 sc.serveG.check()
2246 maxHandlers := sc.advMaxStreams
2247 if sc.curHandlers < maxHandlers {
2248 sc.curHandlers++
2249 go sc.runHandler(rw, req, handler)
2250 return nil
2251 }
2252 if len(sc.unstartedHandlers) > int(4*sc.advMaxStreams) {
2253 return sc.countError("too_many_early_resets", ConnectionError(ErrCodeEnhanceYourCalm))
2254 }
2255 sc.unstartedHandlers = append(sc.unstartedHandlers, unstartedHandler{
2256 streamID: streamID,
2257 rw: rw,
2258 req: req,
2259 handler: handler,
2260 })
2261 return nil
2262 }
2263
2264 func (sc *serverConn) handlerDone() {
2265 sc.serveG.check()
2266 sc.curHandlers--
2267 i := 0
2268 maxHandlers := sc.advMaxStreams
2269 for ; i < len(sc.unstartedHandlers); i++ {
2270 u := sc.unstartedHandlers[i]
2271 if sc.streams[u.streamID] == nil {
2272
2273 continue
2274 }
2275 if sc.curHandlers >= maxHandlers {
2276 break
2277 }
2278 sc.curHandlers++
2279 go sc.runHandler(u.rw, u.req, u.handler)
2280 sc.unstartedHandlers[i] = unstartedHandler{}
2281 }
2282 sc.unstartedHandlers = sc.unstartedHandlers[i:]
2283 if len(sc.unstartedHandlers) == 0 {
2284 sc.unstartedHandlers = nil
2285 }
2286 }
2287
2288
2289 func (sc *serverConn) runHandler(rw *responseWriter, req *ServerRequest, handler func(*ResponseWriter, *ServerRequest)) {
2290 defer sc.sendServeMsg(handlerDoneMsg)
2291 didPanic := true
2292 defer func() {
2293 rw.rws.stream.cancelCtx()
2294 if req.MultipartForm != nil {
2295 req.MultipartForm.RemoveAll()
2296 }
2297 if didPanic {
2298 e := recover()
2299 sc.writeFrameFromHandler(FrameWriteRequest{
2300 write: handlerPanicRST{rw.rws.stream.id},
2301 stream: rw.rws.stream,
2302 })
2303
2304 if e != nil && e != ErrAbortHandler {
2305 const size = 64 << 10
2306 buf := make([]byte, size)
2307 buf = buf[:runtime.Stack(buf, false)]
2308 sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
2309 }
2310 return
2311 }
2312 rw.handlerDone()
2313 }()
2314 handler(rw, req)
2315 didPanic = false
2316 }
2317
2318 func handleHeaderListTooLong(w *ResponseWriter, r *ServerRequest) {
2319
2320
2321
2322
2323 const statusRequestHeaderFieldsTooLarge = 431
2324 w.WriteHeader(statusRequestHeaderFieldsTooLarge)
2325 io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
2326 }
2327
2328
2329
2330 func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
2331 sc.serveG.checkNotOn()
2332 var errc chan error
2333 if headerData.h != nil {
2334
2335
2336
2337
2338 errc = sc.srv.getErrChan()
2339 }
2340 if err := sc.writeFrameFromHandler(FrameWriteRequest{
2341 write: headerData,
2342 stream: st,
2343 done: errc,
2344 }); err != nil {
2345 return err
2346 }
2347 if errc != nil {
2348 select {
2349 case err := <-errc:
2350 sc.srv.putErrChan(errc)
2351 return err
2352 case <-sc.doneServing:
2353 return errClientDisconnected
2354 case <-st.cw:
2355 return errStreamClosed
2356 }
2357 }
2358 return nil
2359 }
2360
2361
2362 func (sc *serverConn) write100ContinueHeaders(st *stream) {
2363 sc.writeFrameFromHandler(FrameWriteRequest{
2364 write: write100ContinueHeadersFrame{st.id},
2365 stream: st,
2366 })
2367 }
2368
2369
2370
2371 type bodyReadMsg struct {
2372 st *stream
2373 n int
2374 }
2375
2376
2377
2378
2379 func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
2380 sc.serveG.checkNotOn()
2381 if n > 0 {
2382 select {
2383 case sc.bodyReadCh <- bodyReadMsg{st, n}:
2384 case <-sc.doneServing:
2385 }
2386 }
2387 }
2388
2389 func (sc *serverConn) noteBodyRead(st *stream, n int) {
2390 sc.serveG.check()
2391 sc.sendWindowUpdate(nil, n)
2392 if st.state != stateHalfClosedRemote && st.state != stateClosed {
2393
2394
2395 sc.sendWindowUpdate(st, n)
2396 }
2397 }
2398
2399
2400 func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
2401 sc.sendWindowUpdate(st, int(n))
2402 }
2403
2404
2405 func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
2406 sc.serveG.check()
2407 var streamID uint32
2408 var send int32
2409 if st == nil {
2410 send = sc.inflow.add(n)
2411 } else {
2412 streamID = st.id
2413 send = st.inflow.add(n)
2414 }
2415 if send == 0 {
2416 return
2417 }
2418 sc.writeFrame(FrameWriteRequest{
2419 write: writeWindowUpdate{streamID: streamID, n: uint32(send)},
2420 stream: st,
2421 })
2422 }
2423
2424
2425
2426 type requestBody struct {
2427 _ incomparable
2428 stream *stream
2429 conn *serverConn
2430 closeOnce sync.Once
2431 sawEOF bool
2432 pipe *pipe
2433 needsContinue bool
2434 }
2435
2436 func (b *requestBody) Close() error {
2437 b.closeOnce.Do(func() {
2438 if b.pipe != nil {
2439 b.pipe.BreakWithError(errClosedBody)
2440 }
2441 })
2442 return nil
2443 }
2444
2445 func (b *requestBody) Read(p []byte) (n int, err error) {
2446 if b.needsContinue {
2447 b.needsContinue = false
2448 b.conn.write100ContinueHeaders(b.stream)
2449 }
2450 if b.pipe == nil || b.sawEOF {
2451 return 0, io.EOF
2452 }
2453 n, err = b.pipe.Read(p)
2454 if err == io.EOF {
2455 b.sawEOF = true
2456 }
2457 if b.conn == nil {
2458 return
2459 }
2460 b.conn.noteBodyReadFromHandler(b.stream, n, err)
2461 return
2462 }
2463
2464
2465
2466
2467
2468
2469
2470 type responseWriter struct {
2471 rws *responseWriterState
2472 }
2473
2474 type responseWriterState struct {
2475
2476 stream *stream
2477 req ServerRequest
2478 conn *serverConn
2479
2480
2481 bw *bufio.Writer
2482
2483
2484 handlerHeader Header
2485 snapHeader Header
2486 trailers []string
2487 status int
2488 wroteHeader bool
2489 sentHeader bool
2490 handlerDone bool
2491
2492 sentContentLen int64
2493 wroteBytes int64
2494
2495 closeNotifierMu sync.Mutex
2496 closeNotifierCh chan bool
2497 }
2498
2499 type chunkWriter struct{ rws *responseWriterState }
2500
2501 func (cw chunkWriter) Write(p []byte) (n int, err error) {
2502 n, err = cw.rws.writeChunk(p)
2503 if err == errStreamClosed {
2504
2505
2506 err = cw.rws.stream.closeErr
2507 }
2508 return n, err
2509 }
2510
2511 func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) > 0 }
2512
2513 func (rws *responseWriterState) hasNonemptyTrailers() bool {
2514 for _, trailer := range rws.trailers {
2515 if _, ok := rws.handlerHeader[trailer]; ok {
2516 return true
2517 }
2518 }
2519 return false
2520 }
2521
2522
2523
2524
2525 func (rws *responseWriterState) declareTrailer(k string) {
2526 k = textproto.CanonicalMIMEHeaderKey(k)
2527 if !httpguts.ValidTrailerHeader(k) {
2528
2529 rws.conn.logf("ignoring invalid trailer %q", k)
2530 return
2531 }
2532 if !slices.Contains(rws.trailers, k) {
2533 rws.trailers = append(rws.trailers, k)
2534 }
2535 }
2536
2537 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
2538
2539
2540
2541
2542
2543
2544
2545 func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
2546 if !rws.wroteHeader {
2547 rws.writeHeader(200)
2548 }
2549
2550 if rws.handlerDone {
2551 rws.promoteUndeclaredTrailers()
2552 }
2553
2554 isHeadResp := rws.req.Method == "HEAD"
2555 if !rws.sentHeader {
2556 rws.sentHeader = true
2557 var ctype, clen string
2558 if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
2559 rws.snapHeader.Del("Content-Length")
2560 if cl, err := strconv.ParseUint(clen, 10, 63); err == nil {
2561 rws.sentContentLen = int64(cl)
2562 } else {
2563 clen = ""
2564 }
2565 }
2566 _, hasContentLength := rws.snapHeader["Content-Length"]
2567 if !hasContentLength && clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
2568 clen = strconv.Itoa(len(p))
2569 }
2570 _, hasContentType := rws.snapHeader["Content-Type"]
2571
2572
2573 ce := rws.snapHeader.Get("Content-Encoding")
2574 hasCE := len(ce) > 0
2575 if !hasCE && !hasContentType && bodyAllowedForStatus(rws.status) && len(p) > 0 {
2576 ctype = internal.DetectContentType(p)
2577 }
2578 var date string
2579 if _, ok := rws.snapHeader["Date"]; !ok {
2580
2581 date = time.Now().UTC().Format(TimeFormat)
2582 }
2583
2584 for _, v := range rws.snapHeader["Trailer"] {
2585 foreachHeaderElement(v, rws.declareTrailer)
2586 }
2587
2588
2589
2590
2591
2592
2593 if _, ok := rws.snapHeader["Connection"]; ok {
2594 v := rws.snapHeader.Get("Connection")
2595 delete(rws.snapHeader, "Connection")
2596 if v == "close" {
2597 rws.conn.startGracefulShutdown()
2598 }
2599 }
2600
2601 endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
2602 err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2603 streamID: rws.stream.id,
2604 httpResCode: rws.status,
2605 h: rws.snapHeader,
2606 endStream: endStream,
2607 contentType: ctype,
2608 contentLength: clen,
2609 date: date,
2610 })
2611 if err != nil {
2612 return 0, err
2613 }
2614 if endStream {
2615 return 0, nil
2616 }
2617 }
2618 if isHeadResp {
2619 return len(p), nil
2620 }
2621 if len(p) == 0 && !rws.handlerDone {
2622 return 0, nil
2623 }
2624
2625
2626
2627 hasNonemptyTrailers := rws.hasNonemptyTrailers()
2628 endStream := rws.handlerDone && !hasNonemptyTrailers
2629 if len(p) > 0 || endStream {
2630
2631 if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
2632 return 0, err
2633 }
2634 }
2635
2636 if rws.handlerDone && hasNonemptyTrailers {
2637 err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2638 streamID: rws.stream.id,
2639 h: rws.handlerHeader,
2640 trailers: rws.trailers,
2641 endStream: true,
2642 })
2643 return len(p), err
2644 }
2645 return len(p), nil
2646 }
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661 const TrailerPrefix = "Trailer:"
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684 func (rws *responseWriterState) promoteUndeclaredTrailers() {
2685 for k, vv := range rws.handlerHeader {
2686 if !strings.HasPrefix(k, TrailerPrefix) {
2687 continue
2688 }
2689 trailerKey := strings.TrimPrefix(k, TrailerPrefix)
2690 rws.declareTrailer(trailerKey)
2691 rws.handlerHeader[textproto.CanonicalMIMEHeaderKey(trailerKey)] = vv
2692 }
2693
2694 if len(rws.trailers) > 1 {
2695 slices.Sort(rws.trailers)
2696 }
2697 }
2698
2699 func (w *responseWriter) SetReadDeadline(deadline time.Time) error {
2700 st := w.rws.stream
2701 if !deadline.IsZero() && deadline.Before(time.Now()) {
2702
2703
2704 st.onReadTimeout()
2705 return nil
2706 }
2707 w.rws.conn.sendServeMsg(func(sc *serverConn) {
2708 if st.readDeadline != nil {
2709 if !st.readDeadline.Stop() {
2710
2711 return
2712 }
2713 }
2714 if deadline.IsZero() {
2715 st.readDeadline = nil
2716 } else if st.readDeadline == nil {
2717 st.readDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onReadTimeout)
2718 } else {
2719 st.readDeadline.Reset(deadline.Sub(time.Now()))
2720 }
2721 })
2722 return nil
2723 }
2724
2725 func (w *responseWriter) SetWriteDeadline(deadline time.Time) error {
2726 st := w.rws.stream
2727 if !deadline.IsZero() && deadline.Before(time.Now()) {
2728
2729
2730 st.onWriteTimeout()
2731 return nil
2732 }
2733 w.rws.conn.sendServeMsg(func(sc *serverConn) {
2734 if st.writeDeadline != nil {
2735 if !st.writeDeadline.Stop() {
2736
2737 return
2738 }
2739 }
2740 if deadline.IsZero() {
2741 st.writeDeadline = nil
2742 } else if st.writeDeadline == nil {
2743 st.writeDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onWriteTimeout)
2744 } else {
2745 st.writeDeadline.Reset(deadline.Sub(time.Now()))
2746 }
2747 })
2748 return nil
2749 }
2750
2751 func (w *responseWriter) EnableFullDuplex() error {
2752
2753 return nil
2754 }
2755
2756 func (w *responseWriter) Flush() {
2757 w.FlushError()
2758 }
2759
2760 func (w *responseWriter) FlushError() error {
2761 rws := w.rws
2762 if rws == nil {
2763 panic("Header called after Handler finished")
2764 }
2765 var err error
2766 if rws.bw.Buffered() > 0 {
2767 err = rws.bw.Flush()
2768 } else {
2769
2770
2771
2772
2773 _, err = chunkWriter{rws}.Write(nil)
2774 if err == nil {
2775 select {
2776 case <-rws.stream.cw:
2777 err = rws.stream.closeErr
2778 default:
2779 }
2780 }
2781 }
2782 return err
2783 }
2784
2785 func (w *responseWriter) CloseNotify() <-chan bool {
2786 rws := w.rws
2787 if rws == nil {
2788 panic("CloseNotify called after Handler finished")
2789 }
2790 rws.closeNotifierMu.Lock()
2791 ch := rws.closeNotifierCh
2792 if ch == nil {
2793 ch = make(chan bool, 1)
2794 rws.closeNotifierCh = ch
2795 cw := rws.stream.cw
2796 go func() {
2797 cw.Wait()
2798 ch <- true
2799 }()
2800 }
2801 rws.closeNotifierMu.Unlock()
2802 return ch
2803 }
2804
2805 func (w *responseWriter) Header() Header {
2806 rws := w.rws
2807 if rws == nil {
2808 panic("Header called after Handler finished")
2809 }
2810 if rws.handlerHeader == nil {
2811 rws.handlerHeader = make(Header)
2812 }
2813 return rws.handlerHeader
2814 }
2815
2816
2817 func checkWriteHeaderCode(code int) {
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828 if code < 100 || code > 999 {
2829 panic(fmt.Sprintf("invalid WriteHeader code %v", code))
2830 }
2831 }
2832
2833 func (w *responseWriter) WriteHeader(code int) {
2834 rws := w.rws
2835 if rws == nil {
2836 panic("WriteHeader called after Handler finished")
2837 }
2838 rws.writeHeader(code)
2839 }
2840
2841 func (rws *responseWriterState) writeHeader(code int) {
2842 if rws.wroteHeader {
2843 return
2844 }
2845
2846 checkWriteHeaderCode(code)
2847
2848
2849 if code >= 100 && code <= 199 {
2850
2851 h := rws.handlerHeader
2852
2853 _, cl := h["Content-Length"]
2854 _, te := h["Transfer-Encoding"]
2855 if cl || te {
2856 h = cloneHeader(h)
2857 h.Del("Content-Length")
2858 h.Del("Transfer-Encoding")
2859 }
2860
2861 rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2862 streamID: rws.stream.id,
2863 httpResCode: code,
2864 h: h,
2865 endStream: rws.handlerDone && !rws.hasTrailers(),
2866 })
2867
2868 return
2869 }
2870
2871 rws.wroteHeader = true
2872 rws.status = code
2873 if len(rws.handlerHeader) > 0 {
2874 rws.snapHeader = cloneHeader(rws.handlerHeader)
2875 }
2876 }
2877
2878 func cloneHeader(h Header) Header {
2879 h2 := make(Header, len(h))
2880 for k, vv := range h {
2881 vv2 := make([]string, len(vv))
2882 copy(vv2, vv)
2883 h2[k] = vv2
2884 }
2885 return h2
2886 }
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896 func (w *responseWriter) Write(p []byte) (n int, err error) {
2897 return w.write(len(p), p, "")
2898 }
2899
2900 func (w *responseWriter) WriteString(s string) (n int, err error) {
2901 return w.write(len(s), nil, s)
2902 }
2903
2904
2905 func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
2906 rws := w.rws
2907 if rws == nil {
2908 panic("Write called after Handler finished")
2909 }
2910 if !rws.wroteHeader {
2911 w.WriteHeader(200)
2912 }
2913 if !bodyAllowedForStatus(rws.status) {
2914 return 0, ErrBodyNotAllowed
2915 }
2916 rws.wroteBytes += int64(len(dataB)) + int64(len(dataS))
2917 if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
2918
2919 return 0, errors.New("http2: handler wrote more than declared Content-Length")
2920 }
2921
2922 if dataB != nil {
2923 return rws.bw.Write(dataB)
2924 } else {
2925 return rws.bw.WriteString(dataS)
2926 }
2927 }
2928
2929 func (w *responseWriter) handlerDone() {
2930 rws := w.rws
2931 rws.handlerDone = true
2932 w.Flush()
2933 w.rws = nil
2934 responseWriterStatePool.Put(rws)
2935 }
2936
2937
2938 var (
2939 ErrRecursivePush = errors.New("http2: recursive push not allowed")
2940 ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
2941 )
2942
2943 func (w *responseWriter) Push(target, method string, header Header) error {
2944 st := w.rws.stream
2945 sc := st.sc
2946 sc.serveG.checkNotOn()
2947
2948
2949
2950 if st.isPushed() {
2951 return ErrRecursivePush
2952 }
2953
2954
2955 if method == "" {
2956 method = "GET"
2957 }
2958 if header == nil {
2959 header = Header{}
2960 }
2961 wantScheme := "http"
2962 if w.rws.req.TLS != nil {
2963 wantScheme = "https"
2964 }
2965
2966
2967 u, err := url.Parse(target)
2968 if err != nil {
2969 return err
2970 }
2971 if u.Scheme == "" {
2972 if !strings.HasPrefix(target, "/") {
2973 return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
2974 }
2975 u.Scheme = wantScheme
2976 u.Host = w.rws.req.Host
2977 } else {
2978 if u.Scheme != wantScheme {
2979 return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
2980 }
2981 if u.Host == "" {
2982 return errors.New("URL must have a host")
2983 }
2984 }
2985 for k := range header {
2986 if strings.HasPrefix(k, ":") {
2987 return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
2988 }
2989
2990
2991
2992
2993 if asciiEqualFold(k, "content-length") ||
2994 asciiEqualFold(k, "content-encoding") ||
2995 asciiEqualFold(k, "trailer") ||
2996 asciiEqualFold(k, "te") ||
2997 asciiEqualFold(k, "expect") ||
2998 asciiEqualFold(k, "host") {
2999 return fmt.Errorf("promised request headers cannot include %q", k)
3000 }
3001 }
3002 if err := checkValidHTTP2RequestHeaders(header); err != nil {
3003 return err
3004 }
3005
3006
3007
3008
3009 if method != "GET" && method != "HEAD" {
3010 return fmt.Errorf("method %q must be GET or HEAD", method)
3011 }
3012
3013 msg := &startPushRequest{
3014 parent: st,
3015 method: method,
3016 url: u,
3017 header: cloneHeader(header),
3018 done: sc.srv.getErrChan(),
3019 }
3020
3021 select {
3022 case <-sc.doneServing:
3023 return errClientDisconnected
3024 case <-st.cw:
3025 return errStreamClosed
3026 case sc.serveMsgCh <- msg:
3027 }
3028
3029 select {
3030 case <-sc.doneServing:
3031 return errClientDisconnected
3032 case <-st.cw:
3033 return errStreamClosed
3034 case err := <-msg.done:
3035 sc.srv.putErrChan(msg.done)
3036 return err
3037 }
3038 }
3039
3040 type startPushRequest struct {
3041 parent *stream
3042 method string
3043 url *url.URL
3044 header Header
3045 done chan error
3046 }
3047
3048 func (sc *serverConn) startPush(msg *startPushRequest) {
3049 sc.serveG.check()
3050
3051
3052
3053
3054 if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
3055
3056 msg.done <- errStreamClosed
3057 return
3058 }
3059
3060
3061 if !sc.pushEnabled {
3062 msg.done <- ErrNotSupported
3063 return
3064 }
3065
3066
3067
3068
3069 allocatePromisedID := func() (uint32, error) {
3070 sc.serveG.check()
3071
3072
3073
3074 if !sc.pushEnabled {
3075 return 0, ErrNotSupported
3076 }
3077
3078 if sc.curPushedStreams+1 > sc.clientMaxStreams {
3079 return 0, ErrPushLimitReached
3080 }
3081
3082
3083
3084
3085
3086 if sc.maxPushPromiseID+2 >= 1<<31 {
3087 sc.startGracefulShutdownInternal()
3088 return 0, ErrPushLimitReached
3089 }
3090 sc.maxPushPromiseID += 2
3091 promisedID := sc.maxPushPromiseID
3092
3093
3094
3095
3096
3097
3098 promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote, defaultRFC9218Priority(sc.priorityAware && !sc.hasIntermediary))
3099 rw, req, err := sc.newWriterAndRequestNoBody(promised, httpcommon.ServerRequestParam{
3100 Method: msg.method,
3101 Scheme: msg.url.Scheme,
3102 Authority: msg.url.Host,
3103 Path: msg.url.RequestURI(),
3104 Header: cloneHeader(msg.header),
3105 })
3106 if err != nil {
3107
3108 panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
3109 }
3110
3111 sc.curHandlers++
3112 go sc.runHandler(rw, req, sc.handler.ServeHTTP)
3113 return promisedID, nil
3114 }
3115
3116 sc.writeFrame(FrameWriteRequest{
3117 write: &writePushPromise{
3118 streamID: msg.parent.id,
3119 method: msg.method,
3120 url: msg.url,
3121 h: msg.header,
3122 allocatePromisedID: allocatePromisedID,
3123 },
3124 stream: msg.parent,
3125 done: msg.done,
3126 })
3127 }
3128
3129
3130
3131 func foreachHeaderElement(v string, fn func(string)) {
3132 v = textproto.TrimString(v)
3133 if v == "" {
3134 return
3135 }
3136 if !strings.Contains(v, ",") {
3137 fn(v)
3138 return
3139 }
3140 for f := range strings.SplitSeq(v, ",") {
3141 if f = textproto.TrimString(f); f != "" {
3142 fn(f)
3143 }
3144 }
3145 }
3146
3147
3148 var connHeaders = []string{
3149 "Connection",
3150 "Keep-Alive",
3151 "Proxy-Connection",
3152 "Transfer-Encoding",
3153 "Upgrade",
3154 }
3155
3156
3157
3158
3159 func checkValidHTTP2RequestHeaders(h Header) error {
3160 for _, k := range connHeaders {
3161 if _, ok := h[k]; ok {
3162 return fmt.Errorf("request header %q is not valid in HTTP/2", k)
3163 }
3164 }
3165 te := h["Te"]
3166 if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
3167 return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
3168 }
3169 return nil
3170 }
3171
3172 type serve400Handler struct {
3173 err error
3174 }
3175
3176 func (handler serve400Handler) ServeHTTP(w *ResponseWriter, r *ServerRequest) {
3177 const statusBadRequest = 400
3178
3179
3180 h := w.Header()
3181 h.Del("Content-Length")
3182 h.Set("Content-Type", "text/plain; charset=utf-8")
3183 h.Set("X-Content-Type-Options", "nosniff")
3184 w.WriteHeader(statusBadRequest)
3185 fmt.Fprintln(w, handler.err.Error())
3186 }
3187
3188
3189
3190
3191 func h1ServerKeepAlivesDisabled(hs ServerConfig) bool {
3192 return !hs.DoKeepAlives()
3193 }
3194
3195 func (sc *serverConn) countError(name string, err error) error {
3196 if sc == nil || sc.srv == nil {
3197 return err
3198 }
3199 f := sc.countErrorFunc
3200 if f == nil {
3201 return err
3202 }
3203 var typ string
3204 var code ErrCode
3205 switch e := err.(type) {
3206 case ConnectionError:
3207 typ = "conn"
3208 code = ErrCode(e)
3209 case StreamError:
3210 typ = "stream"
3211 code = ErrCode(e.Code)
3212 default:
3213 return err
3214 }
3215 codeStr := errCodeName[code]
3216 if codeStr == "" {
3217 codeStr = strconv.Itoa(int(code))
3218 }
3219 f(fmt.Sprintf("%s_%s_%s", typ, codeStr, name))
3220 return err
3221 }
3222
View as plain text