-
Notifications
You must be signed in to change notification settings - Fork 16
/
connection.go
1957 lines (1677 loc) · 53.6 KB
/
connection.go
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 minq is a minimal implementation of QUIC, as documented at
https://quicwg.github.io/. Minq partly implements draft-04.
*/
package minq
import (
"bytes"
"crypto"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"time"
"github.com/bifurcation/mint"
// "github.com/bifurcation/mint/syntax"
)
// Role determines whether an endpoint is client or server.
type Role uint8
// These are roles.
const (
RoleClient = Role(1)
RoleServer = Role(2)
)
var HsEpochs = []mint.Epoch{mint.EpochClear, mint.EpochHandshakeData}
// State is the state of a QUIC connection.
type State uint8
// These are connection states.
const (
StateInit = State(1)
StateWaitClientInitial = State(2)
StateWaitServerInitial = State(3)
StateWaitServerFirstFlight = State(4)
StateWaitClientSecondFlight = State(5)
StateEstablished = State(6)
StateClosing = State(7)
StateClosed = State(8)
StateError = State(9)
)
const (
kMinimumClientInitialLength = 1200 // draft-ietf-quic-transport S 9.0
kLongHeaderLength = 12 // omits connection ID lengths
kInitialIntegrityCheckLength = 16 // Overhead.
kInitialMTU = 1252 // 1280 - UDP headers.
)
// The protocol version number.
type VersionNumber uint32
const (
kQuicDraftVersion = 15
kQuicVersion = VersionNumber(0xff000000 | kQuicDraftVersion)
kQuicGreaseVersion1 = VersionNumber(0x1a1a1a1a)
kQuicGreaseVersion2 = VersionNumber(0x2a2a2a2a)
)
const (
kQuicALPNToken = "hq-13"
)
// Interface for the handler object which the Connection will call
// to notify of events on the connection.
type ConnectionHandler interface {
// The connection has changed state to state |s|
StateChanged(s State)
// NewRecvStream indicates that a new unidirectional stream has been
// created by the remote peer. |s| contains the stream.
NewRecvStream(s RecvStream)
// NewStream indicates that a new bidirectional stream has been
// created by the remote peer. |s| contains the stream.
NewStream(s Stream)
// StreamReadable indicates that |s| is now readable.
StreamReadable(s RecvStream)
}
// Internal structures indicating ranges to ACK
type ackRange struct {
lastPacket uint64 // Packet with highest pn in range
count uint64 // Total number of packets in range
}
type ackRanges []ackRange
/*
Connection represents a QUIC connection. Clients can make
connections directly but servers should create a minq.Server
object which creates Connections as a side effect.
The control discipline is entirely operated by the consuming
application. It has two major responsibilities:
1. Deliver any incoming datagrams using Input()
2. Periodically call CheckTimer(). In future there will be some
way to know how often to call it, but right now it treats
every call to CheckTimer() as timer expiry.
The application provides a handler object which the Connection
calls to notify it of various events.
*/
type encryptionLevel struct {
epoch mint.Epoch
nextSendPacket uint64
sendCipher *cryptoState
recvCipher *cryptoState
sendCryptoStream SendStream
recvCryptoStream RecvStream
outputQ []*frame
recvd *recvdPackets
}
func (el *encryptionLevel) packetType() packetType {
return []packetType{
packetTypeInitial,
packetType0RTTProtected,
packetTypeHandshake,
packetTypeProtectedShort,
}[el.epoch]
}
type Connection struct {
handler ConnectionHandler
role Role
state State
version VersionNumber
clientConnectionId ConnectionId
serverConnectionId ConnectionId
transport Transport
tls *tlsConn
encryptionLevels []*encryptionLevel
recvCryptoEpoch mint.Epoch
mtu int
localBidiStreams *streamSet
remoteBidiStreams *streamSet
localUniStreams *streamSet
remoteUniStreams *streamSet
clientInitial []byte
sendFlowControl flowControl
recvFlowControl flowControl
amountRead uint64
sentAcks map[uint64]ackRanges
lastInput time.Time
idleTimeout time.Duration
tpHandler *transportParametersHandler
log loggingFunction
retransmitTime time.Duration
congestion CongestionController
lastSendQueuedTime time.Time
closingEnd time.Time
closePacket []byte
}
// Create a new QUIC connection. Should only be used with role=RoleClient,
// though we use it with RoleServer internally.
func NewConnection(trans Transport, role Role, tls *TlsConfig, handler ConnectionHandler) *Connection {
mint.HkdfLabelPrefix = "quic "
c := &Connection{
handler: handler,
role: role,
state: StateInit,
version: kQuicVersion,
clientConnectionId: nil,
serverConnectionId: nil,
transport: trans,
tls: nil,
encryptionLevels: make([]*encryptionLevel, 4),
recvCryptoEpoch: mint.EpochClear,
mtu: kInitialMTU,
localBidiStreams: newStreamSet(streamTypeBidirectionalLocal, role, 1),
remoteBidiStreams: newStreamSet(streamTypeBidirectionalRemote, role, kConcurrentStreamsBidi),
localUniStreams: newStreamSet(streamTypeUnidirectionalLocal, role, 0),
remoteUniStreams: newStreamSet(streamTypeUnidirectionalRemote, role, kConcurrentStreamsUni),
clientInitial: nil,
sendFlowControl: flowControl{false, 0, 0},
recvFlowControl: flowControl{false, kInitialMaxData, 0},
amountRead: 0,
sentAcks: make(map[uint64]ackRanges, 0),
lastInput: time.Now(),
idleTimeout: time.Second * 5, // a pretty short time
tpHandler: nil,
log: nil,
retransmitTime: kDefaultInitialRtt,
congestion: nil,
lastSendQueuedTime: time.Now(),
closingEnd: time.Time{}, // Zero time
closePacket: nil,
}
c.log = newConnectionLogger(c)
c.tls = newTlsConn(c, tls, role)
//c.congestion = newCongestionControllerIetf(c)
c.congestion = &CongestionControllerDummy{}
c.congestion.setLostPacketHandler(c.handleLostPacket)
// TODO(ekr@rtfm.com): This isn't generic, but rather tied to
// Mint.
c.tpHandler = newTransportParametersHandler(c.log, role, kQuicVersion)
c.tls.setTransportParametersHandler(c.tpHandler)
for i := int(0); i < 4; i++ {
el := encryptionLevel{
nextSendPacket: 1,
epoch: mint.Epoch(i),
sendCipher: nil,
recvCipher: nil,
// We are using the streams data structures, but without flow control
sendCryptoStream: newSendStream(c, ^uint64(uint64(i)), ^uint64(0)),
recvCryptoStream: newRecvStream(c, ^uint64(uint64(i)), ^uint64(0)),
}
// TODO(ekr@rtfm.com): 0-RTT and 1-RTT should share these somehow.
el.outputQ = make([]*frame, 0)
el.recvd = newRecvdPackets(c.log)
c.encryptionLevels[i] = &el
}
var err error
if role == RoleClient {
c.serverConnectionId, err = c.randomConnectionId(8)
if err != nil {
return nil
}
c.clientConnectionId, err = c.randomConnectionId(kCidDefaultLength)
if err != nil {
return nil
}
err = c.setupAeadMasking(c.serverConnectionId)
if err != nil {
return nil
}
} else {
c.serverConnectionId, err = c.randomConnectionId(kCidDefaultLength)
if err != nil {
return nil
}
c.setState(StateWaitClientInitial)
}
return c
}
func (c *Connection) String() string {
return fmt.Sprintf("Conn: %v_%v: %s", c.clientConnectionId, c.serverConnectionId, c.role)
}
func (c *Connection) zeroRttAllowed() bool {
// Placeholder
return false
}
func (c *Connection) start() error {
return nil
}
func (c *Connection) Role() Role {
return c.role
}
func (r Role) String() string {
switch r {
case RoleClient:
return "client"
case RoleServer:
return "server"
default:
panic("invalid role")
}
}
func (c *Connection) setState(state State) {
if c.state == state {
return
}
c.log(logTypeConnection, "Connection state %v -> %v", c.state, state)
if c.handler != nil {
c.handler.StateChanged(state)
}
c.state = state
}
func (state State) String() string {
// TODO(ekr@rtfm.com): is there a way to get the name from the
// const value.
switch state {
case StateInit:
return "StateInit"
case StateWaitClientInitial:
return "StateWaitClientInitial"
case StateWaitServerInitial:
return "StateWaitServerInitial"
case StateWaitServerFirstFlight:
return "StateWaitServerFirstFlight"
case StateWaitClientSecondFlight:
return "StateWaitClientSecondFlight"
case StateEstablished:
return "StateEstablished"
case StateClosing:
return "StateClosing"
case StateClosed:
return "StateClosed"
case StateError:
return "StateError"
default:
return "Unknown state"
}
}
// ClientId returns the current identity, as dictated by the client.
func (c *Connection) ClientId() ConnectionId {
return c.clientConnectionId
}
// ServerId returns the current identity, as dictated by the server.
func (c *Connection) ServerId() ConnectionId {
return c.serverConnectionId
}
func (c *Connection) ensureRemoteBidi(id uint64) hasIdentity {
return c.remoteBidiStreams.ensure(id, func(x uint64) hasIdentity {
msd := uint64(c.tpHandler.peerParams.maxStreamDataBidiRemote)
return newStream(c, x, kInitialMaxStreamData, msd)
}, func(s hasIdentity) {
if c.handler != nil {
c.log(logTypeStream, "Created Stream %v", s.Id())
c.handler.NewStream(s.(Stream))
}
})
}
// This manages the creation of local and remote bidirectional streams as well
// as remote unidirectional streams.
func (c *Connection) ensureSendStream(id uint64) sendStreamPrivate {
var s hasIdentity
switch streamTypeFromId(id, c.role) {
case streamTypeBidirectionalLocal:
s = c.localBidiStreams.get(id)
case streamTypeBidirectionalRemote:
s = c.ensureRemoteBidi(id)
case streamTypeUnidirectionalLocal:
s = c.localUniStreams.get(id)
default:
// Local unidirectional streams can't receive.
return nil
}
if s == nil {
return nil
}
return s.(sendStreamPrivate)
}
// This manages the creation of local and remote bidirectional streams as well
// as remote unidirectional streams.
func (c *Connection) ensureRecvStream(id uint64) recvStreamPrivate {
var s hasIdentity
switch streamTypeFromId(id, c.role) {
case streamTypeBidirectionalLocal:
s = c.localBidiStreams.get(id)
case streamTypeBidirectionalRemote:
s = c.ensureRemoteBidi(id)
case streamTypeUnidirectionalRemote:
s = c.remoteUniStreams.ensure(id, func(x uint64) hasIdentity {
return newRecvStream(c, x, kInitialMaxStreamData)
}, func(s hasIdentity) {
if c.handler != nil {
c.log(logTypeStream, "Created RecvStream %v", s.Id())
c.handler.NewRecvStream(s.(RecvStream))
}
})
default:
// Local unidirectional streams can't receive.
return nil
}
if s == nil {
return nil
}
return s.(recvStreamPrivate)
}
func (c *Connection) forEachSend(f func(sendStreamPrivate)) {
c.localBidiStreams.forEach(func(s hasIdentity) {
f(s.(sendStreamPrivate))
})
c.remoteBidiStreams.forEach(func(s hasIdentity) {
f(s.(sendStreamPrivate))
})
c.localUniStreams.forEach(func(s hasIdentity) {
f(s.(sendStreamPrivate))
})
}
func (c *Connection) forEachRecv(f func(recvStreamPrivate)) {
c.localBidiStreams.forEach(func(s hasIdentity) {
f(s.(recvStreamPrivate))
})
c.remoteBidiStreams.forEach(func(s hasIdentity) {
f(s.(recvStreamPrivate))
})
c.remoteUniStreams.forEach(func(s hasIdentity) {
f(s.(recvStreamPrivate))
})
}
func (c *Connection) sendClientInitial() error {
panic("sendClientInitial API no longer exists")
}
func (c *Connection) determineEpoch(pt packetType) mint.Epoch {
switch pt {
case packetTypeInitial:
return mint.EpochClear
case packetType0RTTProtected:
return mint.EpochEarlyData
case packetTypeHandshake:
return mint.EpochHandshakeData
case packetTypeProtectedShort:
return mint.EpochApplicationData
default:
// TODO(ekr@rtfm.com)": Check that packet decoding checks the types
panic("Internal error")
}
}
func (c *Connection) getEncryptionLevel(epoch mint.Epoch) *encryptionLevel {
if int(epoch) >= len(c.encryptionLevels) {
return nil
}
return c.encryptionLevels[epoch]
}
func (c *Connection) sendPacketRaw(el *encryptionLevel, pt packetType, version VersionNumber, pn uint64, payload []byte, containsOnlyAcks bool) ([]byte, error) {
c.log(logTypeConnection, "Sending packet PT=%v PN=%x: %s", pt, pn, dumpPacket(payload))
left := c.mtu // track how much space is left for payload
aead := el.sendCipher.aead
left -= aead.Overhead()
var destCid ConnectionId
var srcCid ConnectionId
if c.role == RoleClient {
destCid = c.serverConnectionId
srcCid = c.clientConnectionId
} else {
srcCid = c.serverConnectionId
destCid = c.clientConnectionId
}
p := newPacket(pt, destCid, srcCid, version, pn, payload, aead.Overhead())
c.logPacket("Sending", &p.packetHeader, pn, payload)
// Encode the header so we know how long it is.
// TODO(ekr@rtfm.com): this is gross.
hdr, err := encode(&p.packetHeader)
if err != nil {
return nil, err
}
hdrx := append(hdr, encodePacketNumber(pn, 4)...) // Always use the 4-byte PN
left -= len(hdrx)
assert(left >= len(payload))
p.payload = payload
protected := aead.Seal(nil, c.packetNonce(p.PacketNumber), p.payload, hdrx)
packet := append(hdrx, protected...)
// Encrypt the packet number in place.
err = xorPacketNumber(&p.packetHeader, len(hdr), packet[len(hdr):len(hdr)+4], packet, el.sendCipher.pne)
assert(err == nil)
c.log(logTypeTrace, "Sending packet len=%d, len=%v", len(packet), hex.EncodeToString(packet))
c.congestion.onPacketSent(pn, containsOnlyAcks, len(packet)) //TODO(piet@devae.re) check isackonly
c.transport.Send(packet)
return packet, nil
}
// Send a packet with whatever PT seems appropriate now.
func (c *Connection) sendPacketNow(tosend []*frame, containsOnlyAcks bool) ([]byte, error) {
return c.sendPacket(c.encryptionLevels[mint.EpochApplicationData], packetTypeProtectedShort, tosend, containsOnlyAcks)
}
// Send a packet with a specific PT.
func (c *Connection) sendPacket(el *encryptionLevel, pt packetType, tosend []*frame, containsOnlyAcks bool) ([]byte, error) {
sent := 0
payload := make([]byte, 0)
for _, f := range tosend {
_, err := f.length()
if err != nil {
return nil, err
}
c.log(logTypeTrace, "Frame=%v", hex.EncodeToString(f.encoded))
{
msd, ok := f.f.(*maxStreamDataFrame)
if ok {
c.log(logTypeFlowControl, "EKR: PT=%x Sending maxStreamDate %v %v", el.nextSendPacket, msd.StreamId, msd.MaximumStreamData)
}
}
payload = append(payload, f.encoded...)
sent++
}
// Pad out client Initial
if pt == packetTypeInitial && c.role == RoleClient && !containsOnlyAcks {
topad := kMinimumClientInitialLength - (len(payload) +
c.packetOverhead(el))
payload = append(payload, make([]byte, topad)...)
}
pn := el.nextSendPacket
el.nextSendPacket++
return c.sendPacketRaw(el, pt, c.version, pn, payload, containsOnlyAcks)
}
func (c *Connection) makeAckFrame(el *encryptionLevel, acks ackRanges, left int) (*frame, int, error) {
c.log(logTypeConnection, "Making ack frame, room=%d", left)
af, rangesSent, err := newAckFrame(el.recvd, acks, left)
if err != nil {
c.log(logTypeConnection, "Couldn't prepare ACK frame %v", err)
return nil, 0, err
}
return af, rangesSent, nil
}
func (c *Connection) sendQueued(bareAcks bool) (int, error) {
c.log(logTypeConnection, "Calling sendQueued state=%s", c.GetState())
c.lastSendQueuedTime = time.Now()
if c.state == StateInit {
return 0, nil
}
sent := 0
// Send CRYPTO_HS and associated
for _, el := range c.encryptionLevels {
if el.sendCipher != nil {
s, err := c.sendCryptoFrames(el, bareAcks)
if err != nil {
return sent, err
}
sent += s
}
}
// Send application data
el := c.streamEncryptionLevel()
if el != nil {
err := c.queueStreamFrames(el)
if err != nil {
return sent, err
}
// Send enqueued data from protected streams
s, err := c.sendQueuedFrames(el, bareAcks)
if err != nil {
return sent, err
}
sent += s
}
return sent, nil
}
// Send a packet of stream frames, plus whatever acks fit.
func (c *Connection) sendCombinedPacket(pt packetType, el *encryptionLevel, frames []*frame, acks ackRanges, left int) (int, error) {
asent := int(0)
var err error
containsOnlyAcks := len(frames) == 0
if len(acks) > 0 && (left-kMaxAckHeaderLength) >= 0 {
var af *frame
af, asent, err = c.makeAckFrame(el, acks, left)
if err != nil {
return 0, err
}
if af != nil {
frames = append(frames, af)
}
}
// Record which packets we sent ACKs in.
c.sentAcks[el.nextSendPacket] = acks[0:asent]
_, err = c.sendPacket(el, pt, frames, containsOnlyAcks)
if err != nil {
return 0, err
}
return asent, nil
}
func (c *Connection) queueFrame(q *[]*frame, f *frame) {
*q = append(*q, f)
}
// TODO(ekr@rtfm.com): Coalesce the frames, either here or in Mint.
func (c *Connection) sendCryptoFrames(el *encryptionLevel, bareAcks bool) (int, error) {
s := el.sendCryptoStream
q := &el.outputQ
for _, ch := range s.(sendStreamPrivate).outputWritable() {
f := newCryptoHsFrame(ch.offset, ch.data)
c.queueFrame(q, f)
}
n, err := c.sendQueuedFrames(el, bareAcks)
if err != nil {
return 0, err
}
return n, err
}
func (c *Connection) enqueueStreamFrames(s sendStreamPrivate, q *[]*frame) {
logf(logTypeStream, "Stream %v: enqueueing", s.Id())
if s == nil {
return
}
for _, ch := range s.outputWritable() {
logf(logTypeStream, "Stream %v is writable", s.Id())
f := newStreamFrame(s.Id(), ch.offset, ch.data, ch.last)
c.queueFrame(q, f)
}
}
// Send all the queued data on a set of streams with the current app data encryption
// level.
func (c *Connection) queueStreamFrames(el *encryptionLevel) error {
c.log(logTypeConnection, "%v: queueStreamFrames", c.role)
// Output all the stream frames that are now permitted by stream flow control
c.forEachSend(func(s sendStreamPrivate) {
c.enqueueStreamFrames(s, &el.outputQ)
})
return nil
}
func (c *Connection) sendFrame(f *frame) error {
if c.state != StateEstablished {
return ErrorWouldBlock
}
c.queueFrame(&c.encryptionLevels[mint.EpochApplicationData].outputQ, f)
_, err := c.sendQueued(false)
return err
}
func (c *Connection) packetOverhead(el *encryptionLevel) int {
overhead := el.sendCipher.aead.Overhead()
if el.epoch < mint.EpochApplicationData {
overhead += kLongHeaderLength
if c.role == RoleClient {
overhead += len(c.clientConnectionId)
} else {
overhead += len(c.serverConnectionId)
}
} else {
overhead += 5
}
if c.role == RoleClient {
overhead += len(c.serverConnectionId)
} else {
overhead += len(c.clientConnectionId)
}
return overhead
}
func (c *Connection) suppressRetransmission(f *frame) bool {
switch inner := f.f.(type) {
case *paddingFrame, *pathChallengeFrame, *pathResponseFrame:
return true
case *streamIdBlockedFrame:
switch streamTypeFromId(inner.StreamId, c.role) {
case streamTypeBidirectionalLocal:
return c.localBidiStreams.nstreams > len(c.localBidiStreams.streams)
case streamTypeUnidirectionalLocal:
return c.localUniStreams.nstreams > len(c.localUniStreams.streams)
default:
panic("shouldn't be complaining about this")
}
case *blockedFrame:
return c.sendFlowControl.max > inner.Offset
case *streamBlockedFrame:
fc := c.ensureSendStream(inner.StreamId).flowControl()
return fc.max > inner.Offset
default:
return false
}
}
// maybeRemoveFromQueue is run after a packet is sent.
// Here we assume that toRemove is in the same order as the queue.
func (c *Connection) maybeRemoveFromQueue(queue *[]*frame, toRemove []*frame) {
q := make([]*frame, 0, len(*queue)-len(toRemove))
next := 0
for _, f := range *queue {
maybeRemove := (next < len(toRemove)) && (f == toRemove[next])
if maybeRemove && c.suppressRetransmission(f) {
c.log(logTypeTrace, "frame sent, suppressing retransmission: %v", f)
} else {
q = append(q, f)
}
if maybeRemove {
next++
}
}
*queue = q
}
/* Transmit all the frames permitted by connection level flow control and
* the congestion controller. We're going to need to be more sophisticated
* when we actually do connection level flow control. */
func (c *Connection) sendQueuedFrames(el *encryptionLevel, bareAcks bool) (int, error) {
pt := el.packetType()
c.log(logTypeConnection, "sendQueuedFrames, pt=%v, epoch=%v", pt, el.epoch)
acks := el.recvd.prepareAckRange(el.epoch, false)
now := time.Now()
txAge := c.retransmitTime
sent := int(0)
spaceInCongestionWindow := c.congestion.bytesAllowedToSend()
// Select the queue we will send from
queue := &el.outputQ
/* Iterate through the queue, and append frames to packet, sending
* packets when the maximum packet size is reached, or we are not
* allowed to send more from the congestion controller */
// Calculate available space in the next packet.
overhead := c.packetOverhead(el)
spaceInPacket := c.mtu - overhead
spaceInCongestionWindow -= overhead
// Save a copy of the queue because this removes frames if they don't
// need be sent again.
originalQueue := *queue
congested := false
for index := 0; index < len(originalQueue); {
// Store frames that will be sent in the next packet
toSend := make([]*frame, 0)
toRemove := make([]*frame, 0)
spaceInPacket = c.mtu - overhead
spaceInCongestionWindow -= overhead
c.log(logTypeStream, "Building packet with %d and %d octets left",
spaceInPacket, spaceInCongestionWindow)
for ; index < len(originalQueue); index++ {
f := originalQueue[index]
frameLength, err := f.length()
if err != nil {
return sent, err
}
cAge := now.Sub(f.time)
if f.needsTransmit {
c.log(logTypeStream, "Frame %v requires transmission", f)
} else if cAge < txAge {
c.log(logTypeStream, "Skipping frame %v because sent too recently (%v < %v)", f, cAge, txAge)
continue
}
// if there is no more space in the congestion window, this frame
// can't be sent.
if spaceInCongestionWindow < frameLength {
congested = true
break
}
// if there is no more space for the next frame in the packet,
// send what we have and start forming a new packet
if spaceInPacket < frameLength {
break
}
c.log(logTypeFrame, "Sending frame %v, age = %v", f, cAge)
// add the frame to the packet
toSend = append(toSend, f)
toRemove = append(toRemove, f)
spaceInPacket -= frameLength
spaceInCongestionWindow -= frameLength
}
// Now send the packet if there is anything worth sending.
if len(toSend) == 0 {
break
}
acksSent, err := c.sendCombinedPacket(pt, el, toSend, acks, spaceInPacket)
if err != nil {
return sent, err
}
// Record what was sent.
sent++
acks = acks[acksSent:]
for _, f := range toSend {
f.time = now
f.needsTransmit = false
f.pns = append(f.pns, el.nextSendPacket-1)
}
c.maybeRemoveFromQueue(queue, toRemove)
if congested {
break
}
}
// Now send any bare acks that didn't fit in earlier packets.
if len(acks) > 0 {
if bareAcks {
_, err := c.sendCombinedPacket(pt, el, nil, acks, c.mtu-overhead)
if err != nil {
return sent, err
}
sent++
} else {
c.log(logTypeAck, "Acks to send, but suppressing bare acks")
return sent, nil
}
}
return sent, nil
}
func (c *Connection) handleLostPacket(lostPn uint64) {
panic("Unimplemented")
/*
queues := [][]*frame{c.outputClearQ, c.outputProtectedQ}
for _, queue := range queues {
for _, frame := range queue {
for _, pn := range frame.pns {
if pn == lostPn {
// If the packet is considered lost, remember that.
// Do *not* remove the PN from the list, because
// the packet might pop up later anyway, and then
// we want to mark this frame as received.
frame.lostPns = append(frame.lostPns, lostPn)
}
if len(frame.pns) == len(frame.lostPns) {
// if we consider all packets that this frame was send in as lost,
// we have to retransmit it.
frame.needsTransmit = true
break
}
}
}
}*/
}
// Walk through all the streams and see how many bytes are outstanding.
// Right now this is very expensive.
func (c *Connection) outstandingQueuedBytes() (n int) {
c.forEachSend(func(s sendStreamPrivate) {
n += s.outstandingQueuedBytes()
})
cd := func(frames []*frame) int {
ret := 0
for _, f := range frames {
sf, ok := f.f.(*streamFrame)
if ok {
ret += len(sf.Data)
}
}
return ret
}
for _, el := range c.encryptionLevels {
n += cd(el.outputQ)
}
return
}
// Input provides a packet to the connection.
//
// TODO(ekr@rtfm.com): when is error returned?
func (c *Connection) Input(p []byte) error {
return c.handleError(c.input(p))
}
func (c *Connection) fireReadable() {
if c.handler == nil {
return
}
c.forEachRecv(func(s recvStreamPrivate) {
if s.clearReadable() {
c.handler.StreamReadable(s)
}
})
}
func (c *Connection) input(payload []byte) error {
c.log(logTypeTrace, "Input packet length=%d", len(payload))
fullLength := len(payload)
if c.isClosed() {
return ErrorConnIsClosed
}
if c.state == StateClosing {
c.log(logTypeConnection, "Discarding packet while closing (closePacket=%v)", c.closePacket != nil)
if c.closePacket != nil {
c.transport.Send(c.closePacket)
}
return ErrorConnIsClosing
}
c.lastInput = time.Now()
hdr := packetHeader{shortCidLength: kCidDefaultLength}
c.log(logTypeTrace, "Receiving packet len=%v %v", len(payload), hex.EncodeToString(payload))
hdrlen, err := decode(&hdr, payload)
if err != nil {
c.log(logTypeConnection, "Could not decode packet: %v", hex.EncodeToString(payload))
return wrapE(ErrorInvalidPacket, err)
}
assert(int(hdrlen) <= len(payload))
hdrbytes := payload[:hdrlen]
if hdr.Type.isLongHeader() && hdr.Version != c.version {
if c.role == RoleServer {
c.log(logTypeConnection, "Received unsupported version %v, expected %v", hdr.Version, c.version)
err = c.sendVersionNegotiation(hdr)
if err != nil {
return err
}
if c.state == StateWaitClientInitial {
return ErrorDestroyConnection
}
return nil
} else {
// If we're a client, choke on unknown versions, unless
// they come in version negotiation packets.
if hdr.Version != 0 {
return fmt.Errorf("Received packet with unexpected version %v", hdr.Version)
}
}
}
typ := hdr.getHeaderType()
c.log(logTypeConnection, "Packet header %v, %d", hdr, typ)
if hdr.Type.isLongHeader() && hdr.Version == 0 {
return c.processVersionNegotiation(&hdr, hdrbytes)
}
if c.state == StateWaitClientInitial {
if typ != packetTypeInitial {
c.log(logTypeConnection, "Received unexpected packet before client initial")
return ErrorDestroyConnection
}
// Now check the size.
if fullLength < kMinimumClientInitialLength {
c.log(logTypeConnection, "Discarding too short client Initial")
return nil
}
err := c.setupAeadMasking(hdr.DestinationConnectionID)
if err != nil {
return err
}
c.serverConnectionId, err = c.randomConnectionId(kCidDefaultLength)
if err != nil {
return err
}
c.clientConnectionId = hdr.SourceConnectionID
}
// Figure out the epoch
epoch := c.determineEpoch(typ)
el := c.getEncryptionLevel(epoch)
if el == nil || el.recvCipher == nil {
c.log(logTypeConnection, "Received protected data before crypto state is ready")
return nil