Repository navigation
Expand file tree
/
Copy pathconn.go
More file actions
1616 lines (1274 loc) · 38.1 KB
/
Copy pathconn.go
File metadata and controls
1616 lines (1274 loc) · 38.1 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"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/valyala/fasthttp"
)
// ConnOpts defines the connection options.
type ConnOpts struct {
// PingInterval defines the interval in which the client will ping the server.
//
// An interval of <=0 will make the library to use DefaultPingInterval. Because ping intervals can't be disabled
PingInterval time.Duration
// DisablePingChecking ...
DisablePingChecking bool
// OnDisconnect is a callback that fires when the Conn disconnects.
OnDisconnect func(c *Conn)
}
// Handshake performs an HTTP/2 handshake. That means, it will send
// the preface if `preface` is true, send a settings frame and a
// window update frame (for the connection's window).
// TODO: explain more
func Handshake(preface bool, bw *bufio.Writer, st *Settings, maxWin int32) error {
if preface {
err := WritePreface(bw)
if err != nil {
return err
}
}
fr := AcquireFrameHeader()
defer ReleaseFrameHeader(fr)
// write the settings
st2 := &Settings{}
st.CopyTo(st2)
fr.SetBody(st2)
_, err := fr.WriteTo(bw)
if err == nil {
// then send a window update
fr := AcquireFrameHeader()
wu := AcquireFrame(FrameWindowUpdate).(*WindowUpdate)
wu.SetIncrement(int(maxWin))
fr.SetBody(wu)
_, err = fr.WriteTo(bw)
if err == nil {
err = bw.Flush()
}
ReleaseFrameHeader(fr)
}
return err
}
// pendingBody is the tail of a request body that flow control has not let out
// yet. The write loop owns it; the read loop only grows its window.
type pendingBody struct {
ctx *Ctx
body []byte
window int32
// stream is a streamed request body, pulled a chunk at a time as the
// windows allow rather than held in memory in one go. size is the declared
// content length, negative when the reader runs until EOF, and buf is where
// each chunk lands, with body pointing into it.
stream io.Reader
size int64
read int64
buf []byte
// drained is set once the reader has nothing left to give, so the last
// chunk can carry END_STREAM.
drained bool
}
// hasMore reports whether the body still owes the peer bytes.
func (pb *pendingBody) hasMore() bool {
return len(pb.body) > 0 || (pb.stream != nil && !pb.drained)
}
// Conn represents a raw HTTP/2 connection over TLS + TCP.
type Conn struct {
c net.Conn
br *bufio.Reader
bw *bufio.Writer
enc *HPACK
dec *HPACK
nextID uint32
maxWindow int32
currentWindow int32
openStreams int32
// Flow control for the data we send. The read loop grows the windows as
// WINDOW_UPDATE arrives, the write loop spends them.
// https://httpwg.org/specs/rfc7540.html#rfc.section.6.9
sendLck sync.Mutex
connWindow int32
streamWindow int32
pending map[uint32]*pendingBody
// winCh wakes the write loop when a send window has opened.
winCh chan struct{}
// The server's settings are read on the write loop and on whatever
// goroutine calls CanOpenStream, but a SETTINGS frame can arrive at any
// point, so the values the other goroutines need are kept as atomics
// rather than read straight out of serverS.
maxStreams uint32
maxFrameSize uint32
// encTableSize is the header table size the server last asked for. The
// read loop records it and the write loop, which owns the encoder, applies
// it. encTableSizeSeen belongs to the write loop alone.
encTableSize uint32
encTableSizeSeen uint32
current Settings
// serverS belongs to the read loop once the handshake is over.
serverS Settings
state connState
closeRef uint32
// goAway is set once the server has told us not to open more streams.
goAway uint32
// reqQueued maps a stream id to the request waiting on it. A plain map
// under a mutex beats sync.Map here: every entry is written once and
// deleted once, which is the pattern sync.Map is worst at.
reqLck sync.Mutex
reqQueued map[uint32]*Ctx
in chan *Ctx
out chan *FrameHeader
// bwLck guards bw. Every other write to it happens on the write loop
// goroutine, but Close can be called from any goroutine: the read loop on
// its way out, or a caller of Client.Close.
bwLck sync.Mutex
pingInterval time.Duration
// unacks counts pings sent without a matching ack. The write loop bumps it
// and the read loop clears it, so it has to be touched atomically.
unacks int32
disableAcks bool
// lastErrLck guards lastErr. Both loops write it and LastErr reads it from
// whatever goroutine the caller happens to be on.
lastErrLck sync.Mutex
lastErr error
onDisconnect func(*Conn)
// done is closed by Close. Every send into in and out selects on it: once
// the write loop is gone a bare send blocks forever, and closing in instead
// would panic any Write that is running concurrently.
done chan struct{}
closed uint64
}
// setLastErr records the error that ended the connection, keeping the first one
// seen: it is the one that explains the rest.
func (c *Conn) setLastErr(err error) {
if err == nil {
return
}
c.lastErrLck.Lock()
if c.lastErr == nil {
c.lastErr = err
}
c.lastErrLck.Unlock()
}
// ErrConnectionClosed is returned for requests handed to a connection that has
// already been closed.
var ErrConnectionClosed = errors.New("connection is closed")
// closeErr returns the reason the connection ended, for resolving requests that
// never made it onto the wire.
func (c *Conn) closeErr() error {
if err := c.LastErr(); err != nil {
return err
}
return ErrConnectionClosed
}
// NewConn returns a new HTTP/2 connection.
// To start using the connection you need to call Handshake.
func NewConn(c net.Conn, opts ConnOpts) *Conn {
nc := &Conn{
c: c,
br: bufio.NewReaderSize(c, 4096),
bw: bufio.NewWriterSize(c, maxFrameSize),
enc: AcquireHPACK(),
dec: AcquireHPACK(),
nextID: 1,
maxWindow: 1 << 20,
currentWindow: 1 << 20,
connWindow: int32(defaultWindowSize),
streamWindow: int32(defaultWindowSize),
maxStreams: defaultConcurrentStreams,
maxFrameSize: defaultDataFrameSize,
pending: make(map[uint32]*pendingBody),
reqQueued: make(map[uint32]*Ctx),
winCh: make(chan struct{}, 1),
in: make(chan *Ctx, 128),
out: make(chan *FrameHeader, 128),
done: make(chan struct{}),
pingInterval: opts.PingInterval,
disableAcks: opts.DisablePingChecking,
onDisconnect: opts.OnDisconnect,
}
nc.current.SetMaxWindowSize(1 << 20)
nc.current.SetPush(false)
return nc
}
// queueReq records the request waiting on a stream.
func (c *Conn) queueReq(id uint32, ctx *Ctx) {
c.reqLck.Lock()
c.reqQueued[id] = ctx
c.reqLck.Unlock()
}
// dequeueReq drops a stream from the table.
func (c *Conn) dequeueReq(id uint32) {
c.reqLck.Lock()
delete(c.reqQueued, id)
c.reqLck.Unlock()
}
// takeReq drops a stream from the table and reports whether it was still
// there. Exactly one caller gets a true, which is what decides who accounts for
// the stream closing: a cancel and a late response can both reach the same
// stream, and counting it twice would leave the connection thinking it has
// fewer streams open than it does.
func (c *Conn) takeReq(id uint32) bool {
c.reqLck.Lock()
_, ok := c.reqQueued[id]
if ok {
delete(c.reqQueued, id)
}
c.reqLck.Unlock()
return ok
}
// loadReq returns the request waiting on a stream, if there is one.
func (c *Conn) loadReq(id uint32) (*Ctx, bool) {
c.reqLck.Lock()
ctx, ok := c.reqQueued[id]
c.reqLck.Unlock()
return ctx, ok
}
// takeAllReqs empties the table and returns what was in it, for resolving
// everything at once when the connection ends.
func (c *Conn) takeAllReqs() []*Ctx {
c.reqLck.Lock()
defer c.reqLck.Unlock()
if len(c.reqQueued) == 0 {
return nil
}
out := make([]*Ctx, 0, len(c.reqQueued))
for id, ctx := range c.reqQueued {
out = append(out, ctx)
delete(c.reqQueued, id)
}
return out
}
// Dialer allows creating HTTP/2 connections by specifying an address and tls configuration.
type Dialer struct {
// Addr is the server's address in the form: `host:port`.
Addr string
// TLSConfig is the tls configuration.
//
// If TLSConfig is nil, a default one will be defined on the Dial call.
TLSConfig *tls.Config
// PingInterval defines the interval in which the client will ping the server.
//
// An interval of 0 will make the library to use DefaultPingInterval. Because ping intervals can't be disabled.
PingInterval time.Duration
// NetDial defines the callback for establishing new connection to the host.
// Default Dial is used if not set.
NetDial fasthttp.DialFunc
}
func (d *Dialer) tryDial() (net.Conn, error) {
if d.TLSConfig == nil || !func() bool {
for _, proto := range d.TLSConfig.NextProtos {
if proto == "h2" {
return true
}
}
return false
}() {
configureDialer(d)
}
var c net.Conn
var err error
if d.NetDial != nil {
c, err = d.NetDial(d.Addr)
if err != nil {
return nil, err
}
} else {
tcpAddr, err := net.ResolveTCPAddr("tcp", d.Addr)
if err != nil {
return nil, err
}
c, err = net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
return nil, err
}
}
tlsConn := tls.Client(c, d.TLSConfig)
if err := tlsConn.Handshake(); err != nil {
_ = c.Close()
return nil, err
}
if tlsConn.ConnectionState().NegotiatedProtocol != "h2" {
_ = c.Close()
return nil, ErrServerSupport
}
return tlsConn, nil
}
// Dial creates an HTTP/2 connection or returns an error.
//
// An expected error is ErrServerSupport.
func (d *Dialer) Dial(opts ConnOpts) (*Conn, error) {
c, err := d.tryDial()
if err != nil {
return nil, err
}
nc := NewConn(c, opts)
err = nc.Handshake()
return nc, err
}
// SetOnDisconnect sets the callback that will fire when the HTTP/2 connection is closed.
func (c *Conn) SetOnDisconnect(cb func(*Conn)) {
c.onDisconnect = cb
}
// LastErr returns the last registered error in case the connection was closed by the server.
func (c *Conn) LastErr() error {
c.lastErrLck.Lock()
defer c.lastErrLck.Unlock()
return c.lastErr
}
// Handshake will perform the necessary handshake to establish the connection
// with the server. If an error is returned you can assume the TCP connection has been closed.
func (c *Conn) Handshake() error {
err := c.doHandshake()
if err == nil {
go c.writeLoop()
go c.readLoop()
}
return err
}
func (c *Conn) doHandshake() error {
var err error
if err = Handshake(true, c.bw, &c.current, c.maxWindow-65535); err != nil {
_ = c.c.Close()
return err
}
var fr *FrameHeader
if fr, err = ReadFrameFrom(c.br); err == nil && fr.Type() != FrameSettings {
_ = c.c.Close()
return fmt.Errorf("unexpected frame, expected settings, got %s", fr.Type())
} else if err == nil {
st := fr.Body().(*Settings)
if !st.IsAck() {
st.CopyTo(&c.serverS)
// Nothing else is running yet, so these can be set directly.
c.streamWindow = int32(c.serverS.MaxWindowSize())
c.maxStreams = c.serverS.MaxConcurrentStreams()
c.maxFrameSize = c.serverS.MaxFrameSize()
if st.HeaderTableSize() <= defaultHeaderTableSize {
c.enc.SetMaxTableSize(st.HeaderTableSize())
c.encTableSize = st.HeaderTableSize()
c.encTableSizeSeen = st.HeaderTableSize()
}
// reply back
fr := AcquireFrameHeader()
stRes := AcquireFrame(FrameSettings).(*Settings)
stRes.SetAck(true)
fr.SetBody(stRes)
if _, err = fr.WriteTo(c.bw); err == nil {
err = c.bw.Flush()
}
ReleaseFrameHeader(fr)
}
}
if err != nil {
_ = c.c.Close()
} else {
ReleaseFrameHeader(fr)
}
return err
}
// maxStreamID is the largest stream identifier the protocol allows. A client
// that runs out has to open a new connection.
// https://httpwg.org/specs/rfc7540.html#rfc.section.5.1.1
const maxStreamID = uint32(1)<<31 - 1
// CanOpenStream returns whether the client will be able to open a new stream or not.
//
// It reports false once the server has told us to stop (GOAWAY) and once the
// stream identifiers on this connection have run out, so the caller moves on to
// a fresh connection instead of writing frames the server will reject.
func (c *Conn) CanOpenStream() bool {
if atomic.LoadUint32(&c.goAway) != 0 {
return false
}
if atomic.LoadUint32(&c.nextID) > maxStreamID {
return false
}
return atomic.LoadInt32(&c.openStreams) < int32(atomic.LoadUint32(&c.maxStreams))
}
// Closed indicates whether the connection is closed or not.
func (c *Conn) Closed() bool {
return atomic.LoadUint64(&c.closed) == 1
}
// Close closes the connection gracefully, sending a GoAway message
// and then closing the underlying TCP connection.
func (c *Conn) Close() error {
if !atomic.CompareAndSwapUint64(&c.closed, 0, 1) {
return io.EOF
}
// in is deliberately not closed: Write can be running on any goroutine, and
// a send on a closed channel panics. Closing done tells it to stop instead.
close(c.done)
fr := AcquireFrameHeader()
defer ReleaseFrameHeader(fr)
ga := AcquireFrame(FrameGoAway).(*GoAway)
ga.SetStream(0)
ga.SetCode(NoError)
fr.SetBody(ga)
c.bwLck.Lock()
_, err := fr.WriteTo(c.bw)
if err == nil {
err = c.bw.Flush()
}
c.bwLck.Unlock()
_ = c.c.Close()
if c.onDisconnect != nil {
c.onDisconnect(c)
}
return err
}
// Write queues the request to be sent to the server.
//
// If the connection is closed before the request reaches the write loop, the
// Ctx is resolved with the reason instead of being left to time out.
func (c *Conn) Write(r *Ctx) {
select {
case c.in <- r:
case <-c.done:
r.resolve(c.closeErr())
return
}
// The write loop may have gone away between the send and now, in which case
// it has already drained the queue and nobody will ever pick this Ctx up.
// Resolving twice is harmless: Err is buffered and read once.
select {
case <-c.done:
r.resolve(c.closeErr())
default:
}
}
// writeOut queues a connection-level frame. It drops the frame rather than
// blocking forever when the write loop has already exited.
func (c *Conn) writeOut(fr *FrameHeader) {
select {
case c.out <- fr:
case <-c.done:
ReleaseFrameHeader(fr)
}
}
var ErrStreamNotReady = errors.New("stream hasn't been created")
// ErrNoMoreStreamIDs is returned once a connection has used up the stream
// identifier space. The connection stays usable for the streams already on it,
// but no new request can be started: the caller needs a new connection.
var ErrNoMoreStreamIDs = errors.New("no more stream ids available on this connection")
// Cancel will try to cancel the request.
//
// Cancel can only return ErrStreamNotReady when the cancel is performed before the stream is created.
func (c *Conn) Cancel(ctx *Ctx) error {
if atomic.LoadUint32(&ctx.streamID) == 0 {
return ErrStreamNotReady
}
c.cancel(ctx)
return nil
}
func (c *Conn) cancel(ctx *Ctx) {
id := atomic.LoadUint32(&ctx.streamID)
if id == 0 {
// The request never reached the wire, so there is no stream to reset.
// RST_STREAM on stream 0 is a connection error, not a no-op.
return
}
// Whatever is left of the body is not going out on a stream we are
// resetting, and the buffer stops being ours as soon as RoundTrip returns.
c.deletePending(id)
// Drop the stream here rather than waiting for a response that may never
// come. Leaving it queued kept the Ctx alive for the life of the connection
// and, worse, left openStreams counting a stream that was over, so enough
// timed-out requests made the connection refuse to open any more.
if c.takeReq(id) {
atomic.AddInt32(&c.openStreams, -1)
}
c.cancelStream(id, StreamCanceled)
}
// cancelStream resets a stream that cannot be finished. The caller has already
// taken it off the queue.
func (c *Conn) cancelStream(id uint32, code ErrorCode) {
h := AcquireFrameHeader()
h.SetStream(id)
fr := AcquireFrame(FrameResetStream).(*RstStream)
fr.SetCode(code)
h.SetBody(fr)
c.writeOut(h)
}
type WriteError struct {
err error
}
func (we WriteError) Error() string {
return fmt.Sprintf("writing error: %s", we.err)
}
func (we WriteError) Unwrap() error {
return we.err
}
func (we WriteError) Is(target error) bool {
return errors.Is(we.err, target)
}
func (we WriteError) As(target interface{}) bool {
return errors.As(we.err, target)
}
func (c *Conn) writeLoop() {
lastErr := c.runWriteLoop()
if lastErr == nil {
lastErr = io.ErrUnexpectedEOF
}
c.setLastErr(lastErr)
// Close before draining, not after. Closing is what stops Write from
// handing us requests, so anything that lands in the queue from here on
// sees a closed connection and resolves itself.
_ = c.Close()
for _, ctx := range c.takeAllReqs() {
ctx.resolve(lastErr)
}
for {
select {
case ctx := <-c.in:
ctx.resolve(lastErr)
case fr := <-c.out:
ReleaseFrameHeader(fr)
default:
return
}
}
}
func (c *Conn) runWriteLoop() (lastErr error) {
defer func() {
if err := recover(); err != nil {
if lastErr == nil {
switch errn := err.(type) {
case error:
lastErr = errn
case string:
lastErr = errors.New(errn)
default:
lastErr = fmt.Errorf("%v", errn)
}
}
}
}()
if c.pingInterval <= 0 {
c.pingInterval = DefaultPingInterval
}
ticker := time.NewTicker(c.pingInterval)
defer ticker.Stop()
for {
select {
case <-c.done:
return lastErr
case ctx := <-c.in: // sending requests
err := c.writeRequest(ctx)
if err != nil {
ctx.resolve(err)
if errors.Is(err, ErrNotAvailableStreams) {
continue
}
return WriteError{err}
}
case fr := <-c.out: // generic output
err := c.writeFrame(fr)
ReleaseFrameHeader(fr)
if err != nil {
return WriteError{err}
}
case <-c.winCh: // a send window opened
if err := c.flushPending(); err != nil {
return WriteError{err}
}
case <-ticker.C: // ping
if err := c.writePing(); err != nil {
return WriteError{err}
}
}
if !c.disableAcks && atomic.LoadInt32(&c.unacks) >= 3 {
return ErrTimeout
}
}
}
func (c *Conn) writeFrame(fr *FrameHeader) error {
c.bwLck.Lock()
defer c.bwLck.Unlock()
_, err := fr.WriteTo(c.bw)
if err == nil {
if err = c.bw.Flush(); err != nil {
return err
}
}
return err
}
func (c *Conn) finish(r *Ctx, stream uint32, err error) {
// Drop the stream before resolving: once RoundTrip returns it may hand the
// Ctx back to a pool, and it can only do that when nothing here still
// refers to it.
if c.takeReq(stream) {
atomic.AddInt32(&c.openStreams, -1)
}
c.deletePending(stream)
r.markFinished()
r.resolve(err)
}
func (c *Conn) readLoop() {
defer func() { _ = c.Close() }()
// A panic here would otherwise take the whole process down: this goroutine
// parses whatever the server sends. Resolve the in-flight requests with the
// failure instead, the way the write loop does.
defer func() {
err := recover()
if err == nil {
return
}
perr, ok := err.(error)
if !ok {
perr = fmt.Errorf("%v", err)
}
c.setLastErr(perr)
for _, ctx := range c.takeAllReqs() {
ctx.resolve(perr)
}
}()
for {
fr, err := c.readNext()
if err != nil {
c.setLastErr(err)
break
}
// We advertise SETTINGS_ENABLE_PUSH of 0, so the server has no business
// promising anything. Ignoring the frame would leave it holding a
// stream we are never going to read.
// https://httpwg.org/specs/rfc7540.html#rfc.section.6.5.2
if fr.Type() == FramePushPromise {
c.setLastErr(NewGoAwayError(ProtocolError, "server pushed with push disabled"))
ReleaseFrameHeader(fr)
break
}
// A stream-level WINDOW_UPDATE has to be applied whether or not a
// request is still waiting on the stream, so it is handled before the
// lookup in dispatch.
if fr.Type() == FrameWindowUpdate {
c.addWindow(fr.Stream(), int32(fr.Body().(*WindowUpdate).Increment()))
}
stop := c.dispatch(fr)
ReleaseFrameHeader(fr)
if stop {
break
}
}
}
// dispatch hands a stream frame to the request waiting on it. It reports
// whether the read loop should stop.
func (c *Conn) dispatch(fr *FrameHeader) bool {
r, ok := c.loadReq(fr.Stream())
if !ok {
return false
}
// A canceled or finished request has taken its Response back, so there is
// nowhere to put this frame. Drop the stream and carry on.
if !r.acquireFor(c, fr.Stream()) {
c.dequeueReq(fr.Stream())
return false
}
// Released on the way out even if readStream panics: leaving the Ctx locked
// would wedge the RoundTrip that is waiting to take it back.
defer r.release()
endStream, err := c.readStream(fr, r)
if err == nil {
if endStream {
c.finish(r, fr.Stream(), nil)
}
} else {
c.finish(r, fr.Stream(), err)
}
if err != nil && errors.Is(err, FlowControlError) {
return true
}
return c.state == connStateClosed && fr.Stream() == c.closeRef
}
func (c *Conn) writeRequest(ctx *Ctx) error {
if !c.CanOpenStream() {
return ErrNotAvailableStreams
}
// The request may have been canceled while it sat in the queue, in which
// case its Request no longer belongs to us. Ownership is handed back
// explicitly rather than deferred: sending the body takes it again, and the
// lock is not reentrant.
if !ctx.acquire() {
return nil
}
released := false
release := func() {
if !released {
released = true
ctx.release()
}
}
defer release()
req := ctx.Request
// Request.Body() reads a streamed body into memory, which is the one thing
// a caller who reached for SetBodyStream asked us not to do, so the check
// for a stream has to come first.
bodyStream := req.IsBodyStream()
hasBody := bodyStream || len(req.Body()) != 0
// The server may have changed the header table size since the last request.
// The encoder is the write loop's, so this is the only safe place to apply
// it, and the encoder signals the change to the peer's decoder itself.
if size := atomic.LoadUint32(&c.encTableSize); size != c.encTableSizeSeen {
c.encTableSizeSeen = size
c.enc.SetMaxTableSize(size)
}
enc := c.enc
id := atomic.LoadUint32(&c.nextID)
if id > maxStreamID {
return ErrNoMoreStreamIDs
}
atomic.StoreUint32(&c.nextID, id+2)
fr := AcquireFrameHeader()
defer ReleaseFrameHeader(fr)
fr.SetStream(id)
h := AcquireFrame(FrameHeaders).(*Headers)
fr.SetBody(h)
hf := AcquireHeaderField()
hf.SetBytes(StringAuthority, req.URI().Host())
enc.AppendHeaderField(h, hf, true)
hf.SetBytes(StringMethod, req.Header.Method())
enc.AppendHeaderField(h, hf, true)
hf.SetBytes(StringPath, req.URI().RequestURI())
enc.AppendHeaderField(h, hf, true)
hf.SetBytes(StringScheme, req.URI().Scheme())
enc.AppendHeaderField(h, hf, true)
hf.SetBytes(StringUserAgent, req.Header.UserAgent())
enc.AppendHeaderField(h, hf, true)
for k, v := range req.Header.All() {
if bytes.EqualFold(k, StringUserAgent) {
continue
}
// Lowercase hf's own copy of the name: k may point at fasthttp's
// shared header name constants.
hf.SetBytes(k, v)
ToLower(hf.key)
// Connection-specific fields are forbidden in HTTP/2 and a peer that
// enforces the rule answers them with a stream error (RFC 7540 8.1.2.2).
// fasthttp sets Transfer-Encoding: chunked on a body stream of unknown
// length, for the benefit of its HTTP/1 writer; here END_STREAM ends
// the body and there is nothing to say.
if isConnectionSpecific(hf.key) {
continue
}
enc.AppendHeaderField(h, hf, false)
}
h.SetPadding(false)
h.SetEndStream(!hasBody)
h.SetEndHeaders(true)
// store the ctx before sending the request
ctx.conn.Store(c)
atomic.StoreUint32(&ctx.streamID, id)
c.queueReq(id, ctx)
if hasBody {
pb := &pendingBody{
ctx: ctx,
window: c.streamWindow,
size: -1,
}
if bodyStream {
pb.stream = req.BodyStream()
pb.size = int64(req.Header.ContentLength())
// A body declared as empty has nothing to read, and calling Read
// on it would block on a reader that will never produce anything.
pb.drained = pb.size == 0
} else {
pb.body = req.Body()
}
c.sendLck.Lock()
c.pending[id] = pb
c.sendLck.Unlock()
}
c.bwLck.Lock()
_, err := fr.WriteTo(c.bw)
if err == nil {
err = c.bw.Flush()
}
c.bwLck.Unlock()
ReleaseHeaderField(hf)
if err != nil {