forked from dgrr/http2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverConn.go
More file actions
1509 lines (1233 loc) · 37.2 KB
/
Copy pathserverConn.go
File metadata and controls
1509 lines (1233 loc) · 37.2 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"
"net"
"os"
"runtime/debug"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/valyala/fasthttp"
)
type connState int32
const (
connStateOpen connState = iota
connStateClosed
)
// errRequestBodyTooLarge signals that a stream's accumulated request body
// exceeded maxBodySize. Handled by responding 413 + RST_STREAM(NO_ERROR)
// rather than a bare reset: clients surface the HTTP error instead of
// retrying (x/net retries PROTOCOL_ERROR and REFUSED_STREAM resets).
var errRequestBodyTooLarge = errors.New("request body too large")
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
// Send-side flow control (server -> client). All guarded by fcMu;
// fcCond is broadcast whenever credit arrives, the client's initial
// window changes, a stream is cancelled, or the connection starts
// closing — waking any handler goroutine blocked in acquireSendCredit.
fcMu sync.Mutex
fcCond *sync.Cond
connSendQuota int64 // connection-level send window
initialStreamWin int64 // client's SETTINGS_INITIAL_WINDOW_SIZE
closing bool // connection is shutting down
// our values
maxWindow int32
currentWindow int32
// hpackMu serializes response header encoding: the HPACK encoder is
// stateful, so header blocks must be encoded and enqueued to the writer
// in the same order.
hpackMu sync.Mutex
// writerMu guards writer against send-after-close: senders hold RLock,
// closeWriter takes Lock.
writerMu sync.RWMutex
writerClosed bool
// handlersWG tracks in-flight request handler goroutines.
handlersWG sync.WaitGroup
// done receives streams whose handler goroutine finished, so the
// handleStreams loop can release them. Buffered to maxStreams so
// handlers never block on it.
done chan *Stream
// activeStreams counts open request streams, including those whose
// handler is still running. Read by the idle timer goroutine.
activeStreams int32
writer chan *FrameHeader
reader chan *FrameHeader
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
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
// maxBodySize limits the accumulated request body per stream
// (fasthttp.Server.MaxRequestBodySize). 0 disables the limit.
maxBodySize int
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() {
// "Idle" means no new requests — but long-lived streams (SSE, gRPC
// streaming) are still doing useful work without ever starting a new
// request. Never close a connection with active streams.
if atomic.LoadInt32(&sc.activeStreams) > 0 {
sc.maxIdleTimer.Reset(sc.maxIdleTime)
return
}
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.maxRequestTimer = time.NewTimer(0)
sc.fcCond = sync.NewCond(&sc.fcMu)
sc.connSendQuota = int64(defaultWindowSize)
sc.initialStreamWin = int64(sc.clientS.MaxWindowSize())
sc.done = make(chan *Stream, sc.st.maxStreams)
if sc.maxIdleTime > 0 {
sc.maxIdleTimer = time.AfterFunc(sc.maxIdleTime, sc.closeIdleConn)
}
// Created here, before any goroutine that stops it, to avoid a nil
// deref when handleStreams returns before writeLoop ran (#55 and the
// init race that came with that fix).
if sc.pingInterval > 0 {
sc.pingTimer = time.AfterFunc(sc.pingInterval, sc.sendPingAndSchedule)
}
defer func() {
if err := recover(); err != nil {
sc.logger.Printf("Serve panicked: %s:\n%s\n", err, debug.Stack())
}
}()
go func() {
// defer closing the connection in the writeLoop in case the writeLoop panics
defer func() {
_ = sc.c.Close()
}()
sc.writeLoop()
}()
streamsDone := make(chan struct{})
go func() {
sc.handleStreams()
if sc.pingTimer != nil {
sc.pingTimer.Stop()
}
close(streamsDone)
// Keep draining the reader until readLoop closes it, so readLoop
// never blocks sending to a loop that already exited (e.g. after
// an idle-connection GOAWAY).
for fr := range sc.reader {
ReleaseFrameHeader(fr)
}
}()
go func() {
<-streamsDone
// Wake handler goroutines blocked on flow-control credit and let
// them unwind before the writer closes.
sc.fcMu.Lock()
sc.closing = true
sc.fcMu.Unlock()
sc.fcCond.Broadcast()
sc.handlersWG.Wait()
sc.closeWriter()
}()
defer func() {
// close the reader here so we can stop handling stream updates
close(sc.reader)
}()
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) {
err = nil
}
sc.close()
return err
}
// push enqueues a frame for writing unless the writer is already closed.
// Reports whether the frame was enqueued; on false the frame is released.
func (sc *serverConn) push(fr *FrameHeader) bool {
sc.writerMu.RLock()
defer sc.writerMu.RUnlock()
if sc.writerClosed {
ReleaseFrameHeader(fr)
return false
}
sc.writer <- fr
return true
}
func (sc *serverConn) closeWriter() {
sc.writerMu.Lock()
if !sc.writerClosed {
sc.writerClosed = true
close(sc.writer)
}
sc.writerMu.Unlock()
}
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) {
fr := AcquireFrameHeader()
ping.SetAck(true)
fr.SetBody(ping)
sc.push(fr)
}
func (sc *serverConn) writePing() {
fr := AcquireFrameHeader()
ping := AcquireFrame(FramePing).(*Ping)
ping.SetCurrentTime()
fr.SetBody(ping)
sc.push(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
for err == nil {
fr, err = ReadFrameFromWithSize(sc.br, sc.clientS.frameSize)
if err != nil {
if errors.Is(err, ErrUnknownFrameType) {
sc.writeGoAway(0, ProtocolError, "unknown frame type")
err = nil
continue
}
break
}
if fr.Stream() != 0 {
err := sc.checkFrameWithStream(fr)
if err != nil {
sc.writeError(nil, err)
} else {
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)
}
case FrameWindowUpdate:
win := int64(fr.Body().(*WindowUpdate).Increment())
if win == 0 {
sc.writeGoAway(0, ProtocolError, "window increment of 0")
// return
continue
}
sc.fcMu.Lock()
sc.connSendQuota += win
overflow := sc.connSendQuota >= 1<<31-1
sc.fcMu.Unlock()
if overflow {
sc.writeGoAway(0, FlowControlError, "window is above limits")
} else {
sc.fcCond.Broadcast()
}
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
}
// 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
closeStream := func(strm *Stream) {
if strm.origType == FrameHeaders {
openStreams--
atomic.AddInt32(&sc.activeStreams, -1)
}
strmID := strm.ID()
strms.Del(strm.ID())
ctxPool.Put(strm.ctx)
streamPool.Put(strm)
if sc.debug {
sc.logger.Printf("Stream destroyed %d. Open streams: %d\n", strmID, openStreams)
}
}
// cancelStream tells a stream's handler goroutine to stop writing.
// The stream itself is released later, when the handler signals done.
cancelStream := func(strm *Stream) {
sc.fcMu.Lock()
strm.cancelled = true
sc.fcMu.Unlock()
sc.fcCond.Broadcast()
}
// goAwayComplete reports whether a GOAWAY was sent and every stream the
// GOAWAY promised to finish (ID <= closeRef) has now completed, meaning
// the connection can be torn down. Checked after both frame handling
// and handler completions — with async handlers, the last promised
// stream usually finishes via sc.done, not via a frame.
goAwayComplete := func() bool {
if atomic.LoadInt32((*int32)(&sc.state)) != int32(connStateClosed) {
return false
}
ref := atomic.LoadUint32(&sc.closeRef)
// if there's no reference, then just close the connection
if ref == 0 {
return true
}
// if we have a ref, then check that all streams previous to that ref are closed
for _, strm := range strms {
// if the stream is here, then it's not closed yet
if strm.origType == FrameHeaders && strm.ID() <= ref {
return false
}
}
return true
}
loop:
for {
select {
case <-sc.closer:
break loop
case <-sc.maxRequestTimer.C:
reqTimerArmed = false
// maxRequestTime is a read timeout: it only applies to streams
// still receiving their request. Streams whose handler is
// already running (long responses, SSE, gRPC streaming) are
// never timed out here — the handler owns its own lifetime.
var due []*Stream
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
}
if strm.processing {
continue
}
due = append(due, strm)
}
for _, strm := range due {
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)
}
// Re-arm the timer only for a stream still RECEIVING its request.
// A stream whose handler is already running (processing) is never
// timed out here (see the skip above) — but its startedAt is long
// past, so arming against it yields a negative deadline that fires
// the timer immediately, busy-looping this select at 100% CPU for
// the entire life of the long response (SSE, gRPC, LLM streaming).
// Pick the oldest not-yet-processing stream instead, clamp to a
// positive deadline, and disarm if none remain so the next new
// stream re-arms via the reader branch.
reqTimerArmed = false
if sc.maxRequestTime > 0 {
for _, strm := range strms {
if strm.origType != FrameHeaders || strm.processing {
continue
}
reqTimerArmed = true
when := strm.startedAt.Add(sc.maxRequestTime).Sub(time.Now())
if when < time.Millisecond {
when = time.Millisecond
}
sc.maxRequestTimer.Reset(when)
if sc.debug {
sc.logger.Printf("Next request will timeout in %f seconds\n", when.Seconds())
}
break
}
}
case strm := <-sc.done:
// A handler goroutine finished writing its response.
strm.processing = false
strm.SetState(StreamStateClosed)
closeStream(strm)
if goAwayComplete() {
break loop
}
case fr, ok := <-sc.reader:
if !ok {
return
}
isClosing := atomic.LoadInt32((*int32)(&sc.state)) == int32(connStateClosed)
var strm *Stream
if fr.Stream() <= sc.lastID {
strm = strms.Search(fr.Stream())
}
if strm == nil {
// if the stream doesn't exist, create it
// Stream IDs at or below lastID that are no longer tracked
// are closed — explicitly, or implicitly per RFC 7540
// §5.1.1 (a higher HEADERS closes lower idle IDs). Frames
// legitimately race a RST_STREAM we sent (§5.1): the
// client keeps sending until it processes the reset.
// Ignore them — but DATA still consumed connection
// flow-control window, so return that credit. HEADERS on
// a closed stream remains a protocol error. Tracking via
// the lastID watermark instead of a closed-streams map
// keeps memory flat on long-lived connections.
if fr.Stream() <= sc.lastID {
switch fr.Type() {
case FrameData:
sc.replenishConnWindow(fr)
case FramePriority, FrameResetStream, FrameWindowUpdate:
// ignore
default:
sc.writeGoAway(fr.Stream(), StreamClosedError, "frame on closed stream")
}
continue
}
if fr.Type() == FrameResetStream {
sc.writeGoAway(fr.Stream(), ProtocolError, "RST_STREAM on idle 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) || isClosing {
if sc.debug {
if isClosing {
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)
continue
}
// Flow-control windows are tracked via initialStreamWin +
// sendQuota under fcMu; the legacy window field is unused.
strm = NewStream(fr.Stream(), 0)
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++
atomic.AddInt32(&sc.activeStreams, 1)
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)
closeStream(strm)
if sc.debug {
sc.logger.Printf("Cancelling 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 {
if errors.Is(err, errRequestBodyTooLarge) {
// Respond 413 and stop the upload with a complete
// response + RST_STREAM(NO_ERROR) (RFC 7540 §8.1).
// Later DATA frames hit this branch again and are
// dropped; their connection window credit was already
// returned in handleFrame.
if !strm.processing {
strm.processing = true
sc.handlersWG.Add(1)
go sc.runRejection(strm)
}
continue
}
sc.writeError(strm, err)
strm.SetState(StreamStateClosed)
}
handleState(fr, strm)
switch strm.State() {
case StreamStateHalfClosed:
// Request fully received — run the handler in its own
// goroutine so a slow or streaming response never blocks
// frame processing for the other streams on this
// connection. The stream is released via sc.done.
if !strm.processing {
strm.processing = true
sc.handlersWG.Add(1)
go sc.runHandler(strm)
}
case StreamStateClosed:
if strm.processing {
// Reset mid-handler: stop the writer, release on done.
cancelStream(strm)
} else {
closeStream(strm)
}
}
if isClosing && goAwayComplete() {
break loop
}
}
}
}
func (sc *serverConn) writeReset(strm uint32, code ErrorCode) {
r := AcquireFrame(FrameResetStream).(*RstStream)
fr := AcquireFrameHeader()
fr.SetStream(strm)
fr.SetBody(r)
r.SetCode(code)
sc.push(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.push(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) {
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:
sc.writeReset(strm.ID(), streamErr.Code())
}
if strm != nil {
strm.SetState(StreamStateClosed)
}
}
func handleState(fr *FrameHeader, strm *Stream) {
if fr.Type() == FrameResetStream {
strm.SetState(StreamStateClosed)
}
switch strm.State() {
case StreamStateIdle:
if fr.Type() == FrameHeaders {
strm.SetState(StreamStateOpen)
if fr.Flags().Has(FlagEndStream) {
strm.SetState(StreamStateHalfClosed)
}
} // TODO: else push promise ...
case StreamStateReserved:
// TODO: ...
case StreamStateOpen:
if fr.Flags().Has(FlagEndStream) {
strm.SetState(StreamStateHalfClosed)
} else if fr.Type() == FrameResetStream {
strm.SetState(StreamStateClosed)
}
case StreamStateHalfClosed:
// a stream can only go from HalfClosed to Closed if the client
// sends a ResetStream frame.
if fr.Type() == FrameResetStream {
strm.SetState(StreamStateClosed)
}
case StreamStateClosed:
}
}
var logger = log.New(os.Stdout, "[HTTP/2] ", log.LstdFlags)
var ctxPool = sync.Pool{
New: func() interface{} {
return &fasthttp.RequestCtx{}
},
}
func (sc *serverConn) createStream(c net.Conn, frameType FrameType, strm *Stream) {
ctx := ctxPool.Get().(*fasthttp.RequestCtx)
ctx.Request.Reset()
ctx.Response.Reset()
ctx.Init2(c, sc.logger, false)
strm.origType = frameType
strm.startedAt = time.Now()
strm.SetData(ctx)
}
func (sc *serverConn) handleFrame(strm *Stream, fr *FrameHeader) error {
err := sc.verifyState(strm, fr)
if err != nil {
return err
}
switch fr.Type() {
case FrameHeaders, FrameContinuation:
if strm.State() >= StreamStateHalfClosed {
return NewGoAwayError(ProtocolError, "received headers on a finished stream")
}
err = sc.handleHeaderFrame(strm, fr)
if err != nil {
return err
}
if fr.Flags().Has(FlagEndHeaders) {
// headers are only finished if there's no previousHeaderBytes
strm.headersFinished = len(strm.previousHeaderBytes) == 0
if !strm.headersFinished {
return NewGoAwayError(ProtocolError, "END_HEADERS received on an incomplete stream")
}
// calling req.URI() triggers a URL parsing, so because of that we need to delay the URL parsing.
strm.ctx.Request.URI().SetSchemeBytes(strm.scheme)
}
case FrameData:
// Connection-level credit is returned even on error paths below:
// the bytes were consumed off the wire either way, and without the
// credit the connection window would leak shut.
sc.replenishConnWindow(fr)
if strm.State() == StreamStateClosed {
// We reset this stream (e.g. cancelled mid-handler); the
// client's remaining DATA races the RST (RFC 7540 §5.1).
return nil
}
if !strm.headersFinished {
return NewGoAwayError(ProtocolError, "stream didn't end the headers")
}
if strm.State() >= StreamStateHalfClosed {
return NewGoAwayError(StreamClosedError, "stream closed")
}
if sc.maxBodySize > 0 && len(strm.ctx.Request.Body())+fr.Len() > sc.maxBodySize {
return errRequestBodyTooLarge
}
strm.ctx.Request.AppendBody(
fr.Body().(*Data).Data())
sc.replenishStreamWindow(strm, fr)
case FrameResetStream:
if strm.State() == StreamStateIdle {
return NewGoAwayError(ProtocolError, "RST_STREAM on idle stream")
}
case FramePriority:
if strm.State() != StreamStateIdle && !strm.headersFinished {
return NewGoAwayError(ProtocolError, "frame priority on an open stream")
}
if priorityFrame, ok := fr.Body().(*Priority); ok && priorityFrame.Stream() == strm.ID() {
return NewGoAwayError(ProtocolError, "stream that depends on itself")
}
case FrameWindowUpdate:
if strm.State() == StreamStateIdle {
return NewGoAwayError(ProtocolError, "window update on idle stream")
}
win := int64(fr.Body().(*WindowUpdate).Increment())
if win == 0 {
return NewGoAwayError(ProtocolError, "window increment of 0")
}
sc.fcMu.Lock()
strm.sendQuota += win
overflow := sc.initialStreamWin+strm.sendQuota >= 1<<31-1
sc.fcMu.Unlock()
if overflow {
return NewResetStreamError(FlowControlError, "window is above limits")
}
sc.fcCond.Broadcast()
default:
return NewGoAwayError(ProtocolError, "invalid frame")
}
return err
}
// replenishStreamWindow and replenishConnWindow return flow-control credit
// consumed by a received DATA frame. The request body is buffered
// immediately, so the full frame length can be credited back right away.
// Without this the client exhausts the initial windows and stalls: the
// stream window caps a single request body at maxWindow, and the connection
// window caps the total body bytes ever received over the connection's
// lifetime.
//
// Flow control counts the whole DATA frame payload including padding, hence
// fr.Len() rather than the data length.
//
// Only called from handleStreams, so sc.currentWindow needs no atomics.
// replenishStreamWindow sends stream-level credit, per frame. Skipped once
// the client ends the stream — no more DATA can arrive on it.
func (sc *serverConn) replenishStreamWindow(strm *Stream, fr *FrameHeader) {
n := fr.Len()
if n <= 0 || fr.Flags().Has(FlagEndStream) {
return
}
wu := AcquireFrame(FrameWindowUpdate).(*WindowUpdate)
wu.SetIncrement(n)
wfr := AcquireFrameHeader()
wfr.SetStream(strm.ID())
wfr.SetBody(wu)
sc.push(wfr)
}
// replenishConnWindow sends connection-level credit, batched: refill to
// maxWindow once half is consumed, mirroring the client side in
// Conn.readLoop.
func (sc *serverConn) replenishConnWindow(fr *FrameHeader) {
n := int32(fr.Len())
if n <= 0 {
return
}
sc.currentWindow -= n
if sc.currentWindow < sc.maxWindow/2 {
inc := sc.maxWindow - sc.currentWindow
sc.currentWindow = sc.maxWindow
wu := AcquireFrame(FrameWindowUpdate).(*WindowUpdate)
wu.SetIncrement(int(inc))
wfr := AcquireFrameHeader()
wfr.SetStream(0)
wfr.SetBody(wu)
sc.push(wfr)
}
}
func (sc *serverConn) handleHeaderFrame(strm *Stream, fr *FrameHeader) error {
if strm.headersFinished && !fr.Flags().Has(FlagEndStream|FlagEndHeaders) {
// TODO handle trailers
return NewGoAwayError(ProtocolError, "stream not open")
}
if headerFrame, ok := fr.Body().(*Headers); ok && headerFrame.Stream() == strm.ID() {
return NewGoAwayError(ProtocolError, "stream that depends on itself")
}
b := append(strm.previousHeaderBytes, fr.Body().(FrameWithHeaders).Headers()...)
hf := AcquireHeaderField()
req := &strm.ctx.Request
var err error
strm.previousHeaderBytes = strm.previousHeaderBytes[:0]
fieldsProcessed := 0
for len(b) > 0 {
pb := b
b, err = sc.dec.nextField(hf, strm.headerBlockNum, fieldsProcessed, b)
if err != nil {
if errors.Is(err, ErrUnexpectedSize) && len(pb) > 0 {
err = nil
strm.previousHeaderBytes = append(strm.previousHeaderBytes, pb...)