-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathserverConn.go
More file actions
1754 lines (1438 loc) · 50.3 KB
/
Copy pathserverConn.go
File metadata and controls
1754 lines (1438 loc) · 50.3 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package http2
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
"math"
"net"
"os"
"runtime/debug"
"sync"
"sync/atomic"
"time"
"github.com/valyala/fasthttp"
)
// timerDisarmed is far enough in the future that a timer created with it will
// not fire before it gets Reset to a real interval.
const timerDisarmed = time.Duration(math.MaxInt64)
// maxDataFrameSize is the largest DATA frame the server emits. It is the
// smallest SETTINGS_MAX_FRAME_SIZE the protocol allows, so every peer accepts
// it without having to be asked.
const maxDataFrameSize = 1 << 14
// errConnClosed signals that the read loop terminated the connection on
// purpose, typically after sending a connection-level GOAWAY. It is handled
// as a graceful shutdown rather than a transport error.
// closedStrmsCap is how many recently closed stream ids a connection keeps.
const closedStrmsCap = 256
// writeDrainTimeout is how long teardown waits for queued frames, a GOAWAY in
// particular, to reach a peer that may have stopped reading.
const writeDrainTimeout = time.Second
var errConnClosed = errors.New("connection closed after GOAWAY")
type connState int32
const (
connStateOpen connState = iota
connStateClosed
)
type serverConn struct {
c net.Conn
h fasthttp.RequestHandler
br *bufio.Reader
bw *bufio.Writer
enc HPACK
dec HPACK
// last valid ID used as a reference for new IDs
lastID uint32
// refusedID is the stream whose header block is being decoded and thrown
// away, and refusedBytes holds the field its last frame cut in half.
// See discardHeaderBlock.
refusedID uint32
refusedBytes []byte
// client's window
// should be int64 because the user can try to overflow it
clientWindow int64
// our values
maxWindow int32
currentWindow int32
writer chan *FrameHeader
reader chan *FrameHeader
// writeStop is closed when the connection is on its way out. Every send
// into writer selects on it: the ping timer and the idle timer both queue
// frames from their own goroutines, so closing writer to stop the write
// loop meant one of them could panic the process with a send on a closed
// channel.
writeStop chan struct{}
// handlerDone carries a stream back to the stream loop once its handler has
// returned. Handlers run on their own goroutines so that a slow request
// does not hold up the other streams on the connection, but everything the
// handler produces is turned into frames back on the loop, which owns the
// HPACK encoder, the flow-control windows and the stream table.
handlerDone chan *Stream
// handlerStop is closed once the stream loop stops reading handlerDone, so
// a handler that outlives the connection has somewhere to give up.
handlerStop chan struct{}
state connState
// closeRef stores the last stream that was valid before sending a GOAWAY.
// Thus, the number stored in closeRef is used to complete all the requests that were sent before
// to gracefully close the connection with a GOAWAY.
closeRef uint32
// maxRequestTime is the max time of a request over one single stream
maxHeaderList int
// maxRequestBodySize mirrors fasthttp.Server.MaxRequestBodySize. The
// request body is buffered in memory, so without a cap one stream can grow
// until the process runs out.
maxRequestBodySize int
maxRequestTime time.Duration
pingInterval time.Duration
// maxIdleTime is the max time a client can be connected without sending any REQUEST.
// As highlighted, PING/PONG frames are completely excluded.
//
// Therefore, a client that didn't send a request for more than `maxIdleTime` will see it's connection closed.
maxIdleTime time.Duration
st Settings
clientS Settings
// pingTimer
pingTimer *time.Timer
maxRequestTimer *time.Timer
maxIdleTimer *time.Timer
closer chan struct{}
debug bool
logger fasthttp.Logger
}
func (sc *serverConn) closeIdleConn() {
sc.writeGoAway(0, NoError, "connection has been idle for a long time")
if sc.debug {
sc.logger.Printf("Connection is idle. Closing\n")
}
close(sc.closer)
}
func (sc *serverConn) Handshake() error {
return Handshake(false, sc.bw, &sc.st, sc.maxWindow)
}
func (sc *serverConn) Serve() error {
sc.closer = make(chan struct{}, 1)
sc.writeStop = make(chan struct{})
sc.handlerDone = make(chan *Stream, 128)
sc.handlerStop = make(chan struct{})
// Created disarmed. time.NewTimer(0) fires at once, and with no read
// timeout configured every stream open at that moment looked overdue, so a
// request that arrived in the same instant was answered with
// RST_STREAM(CANCEL) for no reason anyone could see.
sc.maxRequestTimer = time.NewTimer(timerDisarmed)
// The connection-level flow-control window always starts at 65535 octets,
// independent of SETTINGS_INITIAL_WINDOW_SIZE (RFC 7540 6.9.2).
sc.clientWindow = int64(defaultWindowSize)
if sc.maxIdleTime > 0 {
sc.maxIdleTimer = time.AfterFunc(sc.maxIdleTime, sc.closeIdleConn)
}
// Create the ping timer here, before spawning the read/write goroutines, so
// the field is written once and read (Stop) from other goroutines without a
// data race. The writer channel is buffered, so an early tick does not block.
//
// sendPingAndSchedule rearms sc.pingTimer, so the callback must not be able
// to run before the assignment lands: create the timer disarmed and arm it
// afterwards.
if sc.pingInterval > 0 {
sc.pingTimer = time.AfterFunc(timerDisarmed, sc.sendPingAndSchedule)
sc.pingTimer.Reset(sc.pingInterval)
}
defer func() {
if err := recover(); err != nil {
sc.logger.Printf("Serve panicked: %s:\n%s\n", err, debug.Stack())
}
}()
// writeDone lets the teardown wait for queued frames to reach the socket.
writeDone := make(chan struct{})
go func() {
defer close(writeDone)
// defer closing the connection in the writeLoop in case the writeLoop panics
defer func() {
_ = sc.c.Close()
}()
sc.writeLoop()
}()
go func() {
sc.handleStreams()
// Fix #55: The pingTimer fired while we were closing the connection.
// It is nil when pings are disabled with a negative PingInterval.
if sc.pingTimer != nil {
sc.pingTimer.Stop()
}
// Tell the write loop to drain what is queued and stop. The channel
// itself is never closed: anything still holding a frame would panic
// trying to hand it over.
close(sc.writeStop)
}()
defer func() {
// close the reader here so we can stop handling stream updates
close(sc.reader)
// ServeConn closes the socket the moment this returns, so a GOAWAY that
// is still queued would never reach the peer and it would see a bare
// disconnect instead of an error code (RFC 7540 5.4.1). Closing the
// reader unwinds handleStreams, which closes the writer, which lets the
// write loop drain.
//
// Bounded, because a peer that has stopped reading would otherwise hold
// this goroutine open for as long as it likes.
select {
case <-writeDone:
case <-time.After(writeDrainTimeout):
}
}()
var err error
// unset any deadline
if err = sc.c.SetWriteDeadline(time.Time{}); err == nil {
err = sc.c.SetReadDeadline(time.Time{})
}
if err != nil {
return err
}
err = sc.readLoop()
if errors.Is(err, io.EOF) || errors.Is(err, errConnClosed) {
// errConnClosed means we deliberately terminated the connection
// after emitting a GOAWAY. It is not a transport failure.
err = nil
}
sc.close()
return err
}
func (sc *serverConn) close() {
if sc.pingTimer != nil {
sc.pingTimer.Stop()
}
if sc.maxIdleTimer != nil {
sc.maxIdleTimer.Stop()
}
sc.maxRequestTimer.Stop()
}
func (sc *serverConn) handlePing(ping *Ping) {
// ping belongs to the frame header the read loop releases as soon as this
// returns, so echo the payload on a frame of our own. Forwarding the
// borrowed one puts the same Ping in the pool twice, and two connections
// then get handed the same object.
ack := AcquireFrame(FramePing).(*Ping)
ack.SetAck(true)
ack.SetData(ping.Data())
fr := AcquireFrameHeader()
fr.SetBody(ack)
sc.write(fr)
}
func (sc *serverConn) writePing() {
fr := AcquireFrameHeader()
ping := AcquireFrame(FramePing).(*Ping)
ping.SetCurrentTime()
fr.SetBody(ping)
sc.write(fr)
}
func (sc *serverConn) checkFrameWithStream(fr *FrameHeader) error {
if fr.Stream()&1 == 0 {
return NewGoAwayError(ProtocolError, "invalid stream id")
}
switch fr.Type() {
case FramePing:
return NewGoAwayError(ProtocolError, "ping is carrying a stream id")
case FramePushPromise:
return NewGoAwayError(ProtocolError, "clients can't send push_promise frames")
}
return nil
}
func (sc *serverConn) readLoop() (err error) {
defer func() {
if err := recover(); err != nil {
sc.logger.Printf("readLoop panicked: %s\n%s\n", err, debug.Stack())
}
}()
var fr *FrameHeader
// expectContinuation holds the stream id of a header block that has been
// opened by a HEADERS frame without END_HEADERS. While it is non-zero the
// only frame the peer may send is a CONTINUATION on that same stream.
// https://httpwg.org/specs/rfc7540.html#rfc.section.6.10
var expectContinuation uint32
for err == nil {
// Our own SETTINGS_MAX_FRAME_SIZE, not the peer's: what the peer
// advertises is what it is willing to receive, and says nothing about
// what it may send us (RFC 7540 4.2).
fr, err = ReadFrameFromWithSize(sc.br, sc.st.frameSize)
if err != nil {
if errors.Is(err, ErrUnknownFrameType) {
// Unknown frame types are discarded, not rejected (RFC 7540
// 4.1). The exception is one appearing inside a header block,
// which 6.10 makes a connection error.
if expectContinuation != 0 {
sc.writeGoAway(0, ProtocolError, "extension frame inside a header block")
return errConnClosed
}
err = nil
continue
}
// a malformed frame (wrong size, bad padding, ...) is a
// connection error: emit the GOAWAY and close the connection.
var h2err Error
if errors.As(err, &h2err) && h2err.frameType == FrameGoAway {
sc.writeGoAway(0, h2err.Code(), h2err.Error())
return errConnClosed
}
break
}
// Enforce the CONTINUATION rules before any other handling. A header
// block must be a single HEADERS/PUSH_PROMISE followed by zero or more
// CONTINUATION frames on the same stream, with nothing interleaved.
if expectContinuation != 0 {
if fr.Type() != FrameContinuation || fr.Stream() != expectContinuation {
sc.writeGoAway(0, ProtocolError, "expected a CONTINUATION frame")
ReleaseFrameHeader(fr)
return errConnClosed
}
if fr.Flags().Has(FlagEndHeaders) {
expectContinuation = 0
}
} else if fr.Type() == FrameContinuation {
sc.writeGoAway(0, ProtocolError, "unexpected CONTINUATION frame")
ReleaseFrameHeader(fr)
return errConnClosed
} else if fr.Type() == FrameHeaders && !fr.Flags().Has(FlagEndHeaders) {
expectContinuation = fr.Stream()
}
if fr.Stream() != 0 {
if cerr := sc.checkFrameWithStream(fr); cerr != nil {
// a frame that violates connection-level rules is a
// connection error: emit the GOAWAY and terminate.
sc.writeError(nil, cerr)
ReleaseFrameHeader(fr)
return errConnClosed
}
sc.reader <- fr
continue
}
// handle 'anonymous' frames (frames without stream_id)
switch fr.Type() {
case FrameSettings:
st := fr.Body().(*Settings)
if !st.IsAck() { // if it has ack, just ignore
sc.handleSettings(st)
// forward to handleStreams so the INITIAL_WINDOW_SIZE delta is
// applied to open streams in frame order.
sc.reader <- fr
continue
}
case FrameWindowUpdate:
win := int64(fr.Body().(*WindowUpdate).Increment())
if win == 0 {
sc.writeGoAway(0, ProtocolError, "window increment of 0")
ReleaseFrameHeader(fr)
return errConnClosed
}
// the actual window bookkeeping happens in handleStreams.
sc.reader <- fr
continue
case FramePing:
ping := fr.Body().(*Ping)
if !ping.IsAck() {
sc.handlePing(ping)
}
case FrameGoAway:
ga := fr.Body().(*GoAway)
if ga.Code() == NoError {
err = io.EOF
} else {
err = fmt.Errorf("goaway: %s: %s", ga.Code(), ga.Data())
}
default:
sc.writeGoAway(0, ProtocolError, "invalid frame")
ReleaseFrameHeader(fr)
return errConnClosed
}
ReleaseFrameHeader(fr)
}
return err
}
// handleStreams handles everything related to the streams
// and the HPACK table is accessed synchronously.
func (sc *serverConn) handleStreams() {
defer func() {
if err := recover(); err != nil {
sc.logger.Printf("handleStreams panicked: %s\n%s\n", err, debug.Stack())
}
}()
var strms Streams
var reqTimerArmed bool
var openStreams int
// curInitialWindow tracks the client's SETTINGS_INITIAL_WINDOW_SIZE, which
// is the send window every new stream starts with. It starts at the spec
// default of 65535; the client's SETTINGS frames are forwarded to this
// goroutine, which applies any change as a delta to all open streams
// (RFC 7540 6.9.2). Reading it here rather than sc.clientS keeps all
// window state owned by this single goroutine.
curInitialWindow := int32(defaultWindowSize)
// closedStrms remembers recently closed stream ids so that a late frame on
// one can be told apart from a frame on a stream that was never opened,
// which is a protocol error rather than something to ignore. Only the most
// recent ids are kept: a peer that has not caught up is at most a round
// trip behind, and an unbounded set would grow for the whole life of the
// connection.
closedStrms := make(map[uint32]struct{}, closedStrmsCap)
closedRing := make([]uint32, 0, closedStrmsCap)
closedOldest := 0
markClosed := func(id uint32) {
if _, ok := closedStrms[id]; ok {
return
}
if len(closedRing) < closedStrmsCap {
closedRing = append(closedRing, id)
} else {
delete(closedStrms, closedRing[closedOldest])
closedRing[closedOldest] = id
closedOldest = (closedOldest + 1) % closedStrmsCap
}
closedStrms[id] = struct{}{}
}
// releaseStream returns a finished stream and its context to the pools and
// gives its concurrency slot back.
releaseStream := func(strm *Stream) {
if strm.origType == FrameHeaders {
openStreams--
}
if strm.ctx != nil {
// The handler may have left a body stream behind on a response
// nobody will send. Whatever is behind it stays open otherwise.
_ = strm.ctx.Response.CloseBodyStream()
ctxPool.Put(strm.ctx)
strm.ctx = nil
}
streamPool.Put(strm)
}
closeStream := func(strm *Stream) {
strmID := strm.ID()
markClosed(strmID)
strms.Del(strmID)
sc.closeBodyStream(strm)
// A handler still owns ctx, so neither the memory nor the concurrency
// slot can be handed out yet. Holding the slot is also what keeps a
// rapid-reset flood bounded: if canceling a stream freed it here, every
// RST_STREAM would buy the peer another handler goroutine while never
// appearing to exceed SETTINGS_MAX_CONCURRENT_STREAMS.
if strm.handlerRunning {
strm.abandoned = true
if sc.debug {
sc.logger.Printf("Stream %d closed with its handler still running\n", strmID)
}
return
}
releaseStream(strm)
if sc.debug {
sc.logger.Printf("Stream destroyed %d. Open streams: %d\n", strmID, openStreams)
}
}
// Frames come off sc.reader owned by this goroutine and have to go back to
// the pool once the iteration that handled them is done. Releasing at the
// top of the next iteration covers every path out of the body, of which
// there are many, without a release on each one.
var handled *FrameHeader
releaseHandled := func() {
if handled != nil {
ReleaseFrameHeader(handled)
handled = nil
}
}
defer releaseHandled()
// Handlers that are still running when the loop stops have nowhere to
// report back to, and would otherwise park on handlerDone for good.
defer close(sc.handlerStop)
// canCloseAfterGoAway reports whether every stream the GOAWAY promised to
// finish has finished, so the connection can go.
//
// A GOAWAY that carries no reference has nothing to wait for and nothing to
// close on either: those paths break the loop where they send it.
canCloseAfterGoAway := func() bool {
ref := atomic.LoadUint32(&sc.closeRef)
if ref == 0 {
return false
}
for _, strm := range strms {
if strm.origType == FrameHeaders && strm.ID() <= ref {
return false
}
}
return true
}
isClosing := func() bool {
return atomic.LoadInt32((*int32)(&sc.state)) == int32(connStateClosed)
}
loop:
for {
releaseHandled()
select {
case <-sc.closer:
break loop
case strm := <-sc.handlerDone:
strm.handlerRunning = false
if strm.abandoned {
// The peer reset the stream, or it timed out, while the
// handler was running. It is already out of the stream table.
releaseStream(strm)
continue
}
if sc.finishRequest(strm) {
strm.SetState(StreamStateClosed)
closeStream(strm)
}
// The response that just went out may have been the last one a
// GOAWAY was waiting for. Nothing else will arrive to notice: the
// check below only runs when a frame comes in, and after a GOAWAY
// there may be no more frames.
if isClosing() && canCloseAfterGoAway() {
break loop
}
case <-sc.maxRequestTimer.C:
reqTimerArmed = false
// No read timeout configured means requests do not time out.
if sc.maxRequestTime <= 0 {
continue
}
deleteUntil := 0
for _, strm := range strms {
// the request is due if the startedAt time + maxRequestTime is in the past
isDue := time.Now().After(
strm.startedAt.Add(sc.maxRequestTime))
if !isDue {
break
}
deleteUntil++
}
for deleteUntil > 0 {
strm := strms[0]
if sc.debug {
sc.logger.Printf("Stream timed out: %d\n", strm.ID())
}
sc.writeReset(strm.ID(), StreamCanceled)
// set the state to closed in case it comes back to life later
strm.SetState(StreamStateClosed)
closeStream(strm)
deleteUntil--
}
if len(strms) != 0 && sc.maxRequestTime > 0 {
// the first in the stream list might have started with a PushPromise
strm := strms.GetFirstOf(FrameHeaders)
if strm != nil {
reqTimerArmed = true
// try to arm the timer
when := time.Until(strm.startedAt.Add(sc.maxRequestTime))
// if the time is negative or zero it triggers imm
sc.maxRequestTimer.Reset(when)
if sc.debug {
sc.logger.Printf("Next request will timeout in %f seconds\n", when.Seconds())
}
}
}
case fr, ok := <-sc.reader:
if !ok {
return
}
handled = fr
// Connection-level flow-control frames are forwarded here so the
// window bookkeeping and the resumption of buffered response data
// happen in this single goroutine, in frame order.
if fr.Stream() == 0 {
switch fr.Type() {
case FrameSettings:
st := fr.Body().(*Settings)
if st.has(MaxWindowSize) {
delta := int64(int32(st.windowSize)) - int64(curInitialWindow)
curInitialWindow = int32(st.windowSize)
for _, s := range strms {
s.window += delta
if s.window > 1<<31-1 {
sc.writeGoAway(0, FlowControlError, "stream flow-control window exceeded maximum")
break loop
}
}
sc.flushStreams(strms, closeStream)
}
case FrameWindowUpdate:
sc.clientWindow += int64(fr.Body().(*WindowUpdate).Increment())
if sc.clientWindow > 1<<31-1 {
sc.writeGoAway(0, FlowControlError, "connection flow-control window exceeded maximum")
break loop
}
sc.flushStreams(strms, closeStream)
}
continue
}
// Snapshot taken before the frame is handled: handling it may send a
// GOAWAY of its own, and those paths end the loop where they are.
wasClosing := isClosing()
var strm *Stream
if fr.Stream() <= sc.lastID {
strm = strms.Search(fr.Stream())
}
if strm == nil {
// if the stream doesn't exist, create it
if fr.Type() == FrameResetStream {
// only send go away on idle stream not on an already-closed stream
if fr.Stream() > sc.lastID {
sc.writeGoAway(fr.Stream(), ProtocolError, "RST_STREAM on idle stream")
}
continue
}
if _, ok := closedStrms[fr.Stream()]; ok {
// A WINDOW_UPDATE, RST_STREAM or PRIORITY frame may
// legitimately arrive shortly after a stream is closed,
// because the peer had not yet processed the END_STREAM or
// RST_STREAM when it sent them. These MUST be ignored, not
// treated as connection errors (RFC 7540 5.1). Anything else
// (HEADERS, DATA, CONTINUATION) on a closed stream is an
// error.
switch fr.Type() {
case FramePriority, FrameWindowUpdate, FrameResetStream:
default:
sc.writeGoAway(fr.Stream(), StreamClosedError, "frame on closed stream")
}
continue
}
// if the client has more open streams than the maximum allowed OR
// the connection is closing, then refuse the stream
if openStreams >= int(sc.st.maxStreams) || wasClosing {
if sc.debug {
if wasClosing {
sc.logger.Printf("Closing the connection. Rejecting stream %d\n", fr.Stream())
} else {
sc.logger.Printf("Max open streams reached: %d >= %d\n",
openStreams, sc.st.maxStreams)
}
}
sc.writeReset(fr.Stream(), RefusedStreamError)
if err := sc.discardHeaderBlock(fr); err != nil {
sc.writeError(nil, err)
break loop
}
continue
}
if fr.Stream() < sc.lastID {
sc.writeGoAway(fr.Stream(), ProtocolError, "stream ID is lower than the latest")
continue
}
strm = NewStream(fr.Stream(), curInitialWindow)
strms = append(strms, strm)
// RFC(5.1.1):
//
// The identifier of a newly established stream MUST be numerically
// greater than all streams that the initiating endpoint has opened
// or reserved. This governs streams that are opened using a
// HEADERS frame and streams that are reserved using PUSH_PROMISE.
if fr.Type() == FrameHeaders {
openStreams++
sc.lastID = fr.Stream()
}
sc.createStream(sc.c, fr.Type(), strm)
if sc.debug {
sc.logger.Printf("Stream %d created. Open streams: %d\n", strm.ID(), openStreams)
}
if !reqTimerArmed && sc.maxRequestTime > 0 {
reqTimerArmed = true
sc.maxRequestTimer.Reset(sc.maxRequestTime)
if sc.debug {
sc.logger.Printf("Next request will timeout in %f seconds\n", sc.maxRequestTime.Seconds())
}
}
}
// if we have more than one stream (this one newly created) check if the previous finished sending the headers
if fr.Type() == FrameHeaders {
nstrm := strms.getPrevious(FrameHeaders)
if nstrm != nil && !nstrm.headersFinished {
sc.writeError(nstrm, NewGoAwayError(ProtocolError, "previous stream headers not ended"))
continue
}
for len(strms) != 0 {
nstrm := strms[0]
// RFC(5.1.1):
//
// The first use of a new stream identifier implicitly
// closes all streams in the "idle" state that might
// have been initiated by that peer with a lower-valued stream identifier
if nstrm.ID() < strm.ID() &&
nstrm.State() == StreamStateIdle &&
nstrm.origType == FrameHeaders {
nstrm.SetState(StreamStateClosed)
// nstrm, not strm: closing the stream that was just
// created leaves nstrm at the head of the list, still
// idle, so the loop never makes progress.
closeStream(nstrm)
if sc.debug {
sc.logger.Printf("Canceling stream in idle state: %d\n", nstrm.ID())
}
sc.writeReset(nstrm.ID(), StreamCanceled)
continue
}
break
}
if sc.maxIdleTimer != nil {
sc.maxIdleTimer.Reset(sc.maxIdleTime)
}
}
if err := sc.handleFrame(strm, fr); err != nil {
sc.writeError(strm, err)
strm.SetState(StreamStateClosed)
// A GOAWAY carries a connection error, so stop serving this
// connection rather than letting the peer carry on sending.
// writeError has already queued the frame and the writer is
// drained before it closes (RFC 7540 6.8).
var connErr Error
if errors.As(err, &connErr) &&
connErr.frameType == FrameGoAway && connErr.Code() != NoError {
break loop
}
}
handleState(fr, strm)
// Hand the request to the handler once the client is done sending
// it, then (re)send buffered response data. The response may not
// fit the flow-control window in one go, in which case the stream
// stays open until a WINDOW_UPDATE lets us finish.
// headersFinished matters as much as the state does. END_STREAM on
// a HEADERS frame half-closes the stream while the header block is
// still arriving in CONTINUATION frames, and dispatching there
// hands the handler a request whose headers are half decoded.
if strm.State() == StreamStateHalfClosed && strm.headersFinished && !strm.responded {
strm.responded = true
// The declared content-length must match the number of DATA
// bytes actually received.
// https://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.6
if strm.hasContentLength && strm.recvBody != strm.contentLength {
sc.writeReset(strm.ID(), ProtocolError)
strm.SetState(StreamStateClosed)
} else {
// The response comes back on handlerDone, not here.
sc.dispatchHandler(strm)
}
} else if strm.responded && !strm.handlerRunning && strm.hasMoreToSend() {
// a stream-level WINDOW_UPDATE may have opened up space
if sc.sendData(strm) {
strm.SetState(StreamStateClosed)
}
}
if strm.State() == StreamStateClosed {
closeStream(strm)
}
if wasClosing && canCloseAfterGoAway() {
break loop
}
}
}
}
// consumeRecvWindow accounts for DATA that has been received and hands the
// space straight back with WINDOW_UPDATE. Without it the peer's send window
// runs down and never recovers, so a client that respects flow control stops
// uploading for good once it has sent the initial window.
//
// The space is returned as soon as the bytes are buffered rather than when the
// handler reads them, so the receive window never becomes the thing that limits
// throughput. What bounds the memory instead is MaxRequestBodySize per stream
// and SETTINGS_MAX_CONCURRENT_STREAMS across the connection, plus the backlog
// on sc.reader, which stops being read once it is full and lets TCP push back.
// https://httpwg.org/specs/rfc7540.html#rfc.section.6.9
func (sc *serverConn) consumeRecvWindow(strm *Stream, fr *FrameHeader, n int) {
if n <= 0 {
return
}
// The body has already been copied into the request, so the stream window
// goes back in full. There is nothing to give back on a stream the peer has
// just finished with.
if !fr.Flags().Has(FlagEndStream) {
sc.writeWindowUpdate(strm.ID(), n)
}
sc.currentWindow -= int32(n)
if sc.currentWindow < sc.maxWindow/2 {
inc := sc.maxWindow - sc.currentWindow
sc.currentWindow = sc.maxWindow
sc.writeWindowUpdate(0, int(inc))
}
}
func (sc *serverConn) writeWindowUpdate(id uint32, inc int) {
fr := AcquireFrameHeader()
fr.SetStream(id)
wu := AcquireFrame(FrameWindowUpdate).(*WindowUpdate)
wu.SetIncrement(inc)
fr.SetBody(wu)
sc.write(fr)
}
func (sc *serverConn) writeReset(strm uint32, code ErrorCode) {
r := AcquireFrame(FrameResetStream).(*RstStream)
fr := AcquireFrameHeader()
fr.SetStream(strm)
fr.SetBody(r)
r.SetCode(code)
sc.write(fr)
if sc.debug {
sc.logger.Printf(
"%s: Reset(stream=%d, code=%s)\n",
sc.c.RemoteAddr(), strm, code,
)
}
}
func (sc *serverConn) writeGoAway(strm uint32, code ErrorCode, message string) {
ga := AcquireFrame(FrameGoAway).(*GoAway)
fr := AcquireFrameHeader()
ga.SetStream(strm)
ga.SetCode(code)
ga.SetData([]byte(message))
fr.SetBody(ga)
sc.write(fr)
if strm != 0 {
atomic.StoreUint32(&sc.closeRef, sc.lastID)
}
atomic.StoreInt32((*int32)(&sc.state), int32(connStateClosed))
if sc.debug {
sc.logger.Printf(
"%s: GoAway(stream=%d, code=%s): %s\n",
sc.c.RemoteAddr(), strm, code, message,
)
}
}
func (sc *serverConn) writeError(strm *Stream, err error) {
streamErr := Error{}
if !errors.As(err, &streamErr) {
// Not one of ours, so there is no code to report. Without a stream
// there is nothing to reset either, and the connection error path is
// the only thing left.
if strm == nil {
sc.writeGoAway(0, InternalError, err.Error())
return
}
sc.writeReset(strm.ID(), InternalError)
strm.SetState(StreamStateClosed)
return
}
switch streamErr.frameType {
case FrameGoAway:
if strm == nil {
sc.writeGoAway(0, streamErr.Code(), streamErr.Error())
} else {
sc.writeGoAway(strm.ID(), streamErr.Code(), streamErr.Error())
}
case FrameResetStream:
if strm == nil {
sc.writeGoAway(0, streamErr.Code(), streamErr.Error())
return
}
sc.writeReset(strm.ID(), streamErr.Code())
}