forked from ekr/minq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
1894 lines (1601 loc) · 48.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/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"github.com/bifurcation/mint"
"time"
)
var DUMMY_NO_ENCRYPT bool = true
const (
RoleClient = 1
RoleServer = 2
)
// The state of a QUIC connection.
type State uint8
const (
StateInit = State(1)
StateWaitClientInitial = State(2)
StateWaitServerFirstFlight = State(3)
StateWaitClientSecondFlight = State(4)
StateEstablished = State(5)
StateClosed = State(6)
StateError = State(7)
)
const (
kMinimumClientInitialLength = 1200 // draft-ietf-quic-transport S 9.0
kLongHeaderLength = 18
kInitialIntegrityCheckLength = 16 // Overhead.
kInitialMTU = 1252 // 1280 - UDP headers.
)
// The protocol version number.
type VersionNumber uint32
const (
kQuicDraftVersion = 7
kQuicVersion = VersionNumber(0xf0f0f0f0)// VersionNumber(0xff000000 | kQuicDraftVersion)
kQuicGreaseVersion1 = VersionNumber(0x1a1a1a1a)
kQuicGreaseVersion2 = VersionNumber(0x2a2a2a2a)
)
const (
kQuicALPNToken = "hq-07"
)
const (
kDefaultInitialRtt = uint32(100)
)
// 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)
// A new stream has been created (by receiving a frame
// from the other side. |s| contains the stream.
NewStream(s *Stream)
// Stream |s| is now readable.
StreamReadable(s *Stream)
}
// 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 Connection struct {
handler ConnectionHandler
role uint8
state State
version VersionNumber
clientConnId ConnectionId
serverConnId ConnectionId
transport Transport
tls *tlsConn
writeClear *cryptoState
readClear *cryptoState
writeProtected *cryptoState
readProtected *cryptoState
nextSendPacket uint64
mtu int
streams []*Stream
maxStream uint32
outputClearQ []frame // For stream 0
outputProtectedQ []frame // For stream >= 0
clientInitial []byte
recvd *recvdPackets
sentAcks map[uint64]ackRanges
lastInput time.Time
idleTimeout uint16
tpHandler *transportParametersHandler
log loggingFunction
retransmitTime uint32
congestion CongestionController
lastSendQueuedTime time.Time
measurement MeasurementData
}
// Create a new QUIC connection. Should only be used with role=RoleClient,
// though we use it with RoleServer internally.
func NewConnection(trans Transport, role uint8, tls TlsConfig, handler ConnectionHandler) *Connection {
c := Connection{
handler,
role,
StateInit,
kQuicVersion,
0,
0,
trans,
newTlsConn(tls, role),
nil,
nil,
nil,
nil,
uint64(0),
kInitialMTU,
nil,
0,
nil,
nil,
nil,
nil,
make(map[uint64]ackRanges, 0),
time.Now(),
10, // Very short idle timeout.
nil,
nil,
kDefaultInitialRtt,
nil,
time.Now(),
newMeasurementData(role),
}
c.log = newConnectionLogger(&c)
//c.congestion = newCongestionControllerIetf(&c)
//c.congestion = newCongestionControllerFixedWindow(&c, 60*kInitialMTU)
c.congestion = newCongestionControllerFixedRate(&c, 600000, 0)
//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)
c.recvd = newRecvdPackets(c.log)
tmp, err := generateRand64()
if err != nil {
return nil
}
connId := ConnectionId(tmp)
if role == RoleClient {
c.clientConnId = connId
err = c.setupAeadMasking()
if err != nil {
return nil
}
} else {
c.serverConnId = connId
c.setState(StateWaitClientInitial)
}
tmp, err = generateRand64()
if err != nil {
return nil
}
c.nextSendPacket = tmp & 0x7fffffff
s, newframe, _ := c.ensureStream(0, false)
if newframe {
s.setState(kStreamStateOpen)
}
return &c
}
func (c *Connection) zeroRttAllowed() bool {
// Placeholder
return false
}
func (c *Connection) start() error {
return nil
}
func (c *Connection) label() string {
if c.role == RoleClient {
return "client"
}
return "server"
}
func (c *Connection) setState(state State) {
if c.state == state {
return
}
c.log(logTypeConnection, "%s: Connection state %s -> %v", c.label(), StateName(c.state), StateName(state))
if c.handler != nil {
c.handler.StateChanged(state)
}
c.state = state
}
func StateName(state State) 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 StateWaitServerFirstFlight:
return "StateWaitServerFirstFlight"
case StateWaitClientSecondFlight:
return "StateWaitClientSecondFlight"
case StateEstablished:
return "StateEstablished"
case StateClosed:
return "StateClosed"
case StateError:
return "StateError"
default:
return "Unknown state"
}
}
func (c *Connection) myStream(id uint32) bool {
return id == 0 || (((id & 1) == 1) == (c.role == RoleClient))
}
func (c *Connection) ensureStream(id uint32, remote bool) (*Stream, bool, error) {
c.log(logTypeTrace, "Ensuring stream %d exists", id)
// TODO(ekr@rtfm.com): this is not really done, because we never clean up
// Resize to fit.
if uint32(len(c.streams)) >= id+1 {
return c.streams[id], false, nil
}
// Don't create the stream if it's the wrong direction.
if remote == c.myStream(id) {
return nil, false, ErrorProtocolViolation
}
needed := id - uint32(len(c.streams)) + 1
c.log(logTypeTrace, "Needed=%d", needed)
c.streams = append(c.streams, make([]*Stream, needed)...)
// Now make all the streams in the same direction
i := id
var initialMax uint64
if c.tpHandler.peerParams != nil {
initialMax = uint64(c.tpHandler.peerParams.maxStreamsData)
} else {
assert(id == 0)
initialMax = 1280
}
for {
if c.streams[i] != nil {
break
}
if (i & 1) == (id & 1) {
s := newStream(c, i, initialMax, kStreamStateIdle)
c.streams[i] = s
if id != i {
// Any lower-numbered streams start in open, so set the
// state and notify.
s.setState(kStreamStateOpen)
if c.handler != nil {
c.handler.NewStream(s)
}
}
}
if i == 0 {
break
}
i--
}
if id > c.maxStream {
c.maxStream = id
}
return c.streams[id], true, nil
}
func (c *Connection) sendClientInitial() error {
queued := make([]frame, 0)
var err error
c.log(logTypeHandshake, "Sending client initial packet")
if c.clientInitial == nil {
c.clientInitial, err = c.tls.handshake(nil)
if err != nil {
return err
}
}
f := newStreamFrame(0, 0, c.clientInitial, false)
// Encode this so we know how much room it is going to take up.
l, err := f.length()
if err != nil {
return err
}
/*
unless the client has a reasonable assurance that the PMTU is larger.
Sending a packet of this size ensures that the network path supports
an MTU of this size and helps reduce the amplitude of amplification
attacks caused by server responses toward an unverified client
address.
*/
topad := kMinimumClientInitialLength - (kLongHeaderLength + l + kInitialIntegrityCheckLength)
c.log(logTypeHandshake, "Padding with %d padding frames", topad)
// Enqueue the frame for transmission.
queued = append(queued, f)
c.streams[0].send.setOffset(uint64(len(c.clientInitial)))
for i := 0; i < topad; i++ {
queued = append(queued, newPaddingFrame(0))
}
c.setState(StateWaitServerFirstFlight)
return c.sendPacket(packetTypeClientInitial, queued, false)
}
func (c *Connection) sendSpecialClearPacket(pt uint8, connId ConnectionId, pn uint64, version VersionNumber, payload []byte) error {
c.log(logTypeConnection, "Sending special clear packet type=%v", pt)
p := packet{
packetHeader{
pt | packetFlagLongHeader,
connId,
pn,
version,
0,
},
payload,
}
packet, err := encode(&p.packetHeader)
if err != nil {
return err
}
packet = append(packet, payload...)
c.congestion.onPacketSent(pn, false, len(packet)) //TODO(piet@devae.re) check isackonly
c.transport.Send(packet)
return nil
}
func (c *Connection) determineAead(pt uint8) cipher.AEAD {
var aead cipher.AEAD
if c.writeProtected != nil {
aead = c.writeProtected.aead
}
if c.role == RoleClient {
switch {
case pt == packetTypeClientInitial:
aead = c.writeClear.aead
case pt == packetTypeClientCleartext:
aead = c.writeClear.aead
case pt == packetType0RTTProtected:
aead = nil // This will cause a crash b/c 0-RTT doesn't work yet
}
} else {
if pt == packetTypeServerCleartext || pt == packetTypeServerStatelessRetry {
aead = c.writeClear.aead
}
}
return aead
}
func (c *Connection) sendPacketRaw(pt uint8, connId ConnectionId, pn uint64, version VersionNumber, payload []byte, containsOnlyAcks bool) error {
c.log(logTypeConnection, "Sending packet PT=%v PN=%x: %s", pt, c.nextSendPacket, dumpPacket(payload))
left := c.mtu // track how much space is left for payload
aead := c.determineAead(pt)
left -= aead.Overhead()
c.measurement.outgoingMeasurementTasks(c)
measurementField := c.measurement.hdrData.encode()
// Horrible hack. Map phase0 -> short header.
// TODO(ekr@rtfm.com): Fix this way above here.
if pt == packetType1RTTProtectedPhase0 {
pt = 3 | packetFlagC // 4-byte packet number
} else {
pt = pt | packetFlagLongHeader
}
p := packet{
packetHeader{
pt,
connId,
pn,
version,
measurementField,
},
nil,
}
c.logPacket("Sent", &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 err
}
left -= len(hdr)
assert(left >= len(payload))
p.payload = payload
var packet []byte
/* hack to not have encryption pietdv */
if DUMMY_NO_ENCRYPT {
packet = append(hdr, payload...)
} else {
protected := aead.Seal(nil, c.packetNonce(p.PacketNumber), p.payload, hdr)
packet = append(hdr, protected...)
}
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 nil
}
// Send a packet with whatever PT seems appropriate now.
func (c *Connection) sendPacketNow(tosend []frame, containsOnlyAcks bool) error {
// Right now this is just 1-RTT 0-phase
return c.sendPacket(packetType1RTTProtectedPhase0, tosend, containsOnlyAcks)
}
// Send a packet with a specific PT.
func (c *Connection) sendPacket(pt uint8, tosend []frame, containsOnlyAcks bool) error {
sent := 0
payload := make([]byte, 0)
for _, f := range tosend {
_, err := f.length()
if err != nil {
return 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", c.nextSendPacket, msd.StreamId, msd.MaximumStreamData)
}
}
payload = append(payload, f.encoded...)
sent++
}
connId := c.serverConnId
if c.role == RoleClient {
if pt == packetTypeClientInitial {
connId = c.clientConnId
}
} else {
if pt == packetTypeServerStatelessRetry {
connId = c.clientConnId
}
}
pn := c.nextSendPacket
c.nextSendPacket++
return c.sendPacketRaw(pt, connId, pn, c.version, payload, containsOnlyAcks)
}
func (c *Connection) sendFramesInPacket(pt uint8, tosend []frame) error {
c.log(logTypeConnection, "%s: Sending packet of type %v. %v frames", c.label(), pt, len(tosend))
c.log(logTypeTrace, "Sending packet of type %v. %v frames", pt, len(tosend))
left := c.mtu
var connId ConnectionId
var aead cipher.AEAD
if c.writeProtected != nil {
aead = c.writeProtected.aead
}
connId = c.serverConnId
longHeader := true
if c.role == RoleClient {
switch {
case pt == packetTypeClientInitial:
aead = c.writeClear.aead
connId = c.clientConnId
case pt == packetTypeClientCleartext:
aead = c.writeClear.aead
case pt == packetType0RTTProtected:
connId = c.clientConnId
aead = nil // This will cause a crash b/c 0-RTT doesn't work yet
default:
longHeader = false
}
} else {
if pt == packetTypeServerCleartext {
aead = c.writeClear.aead
} else {
longHeader = true
}
}
left -= aead.Overhead()
npt := pt
if longHeader {
npt |= packetFlagLongHeader
}
pn := c.nextSendPacket
p := packet{
packetHeader{
npt,
connId,
pn,
c.version,
0,
},
nil,
}
c.nextSendPacket++
// 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 err
}
left -= len(hdr)
sent := 0
for _, f := range tosend {
l, err := f.length()
if err != nil {
return err
}
assert(l <= left)
c.log(logTypeTrace, "Frame=%v", hex.EncodeToString(f.encoded))
p.payload = append(p.payload, f.encoded...)
sent++
}
protected := aead.Seal(nil, c.packetNonce(p.PacketNumber), p.payload, hdr)
packet := append(hdr, protected...)
c.log(logTypeTrace, "Sending packet len=%d, len=%v", len(packet), hex.EncodeToString(packet))
c.congestion.onPacketSent(pn, false, len(packet)) //TODO(piet@devae.re) check isackonly
c.transport.Send(packet)
return nil
}
func (c *Connection) sendOnStream(streamId uint32, data []byte) error {
c.log(logTypeConnection, "%v: sending %v bytes on stream %v", c.label(), len(data), streamId)
stream, newStream, _ := c.ensureStream(streamId, false)
if newStream {
stream.setState(kStreamStateOpen)
}
_, err := stream.Write(data)
return err
}
func (c *Connection) makeAckFrame(acks ackRanges, left int) (*frame, int, error) {
c.log(logTypeConnection, "Making ack frame, room=%d", left)
af, rangesSent, err := newAckFrame(c.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")
c.lastSendQueuedTime = time.Now()
if c.state == StateInit || c.state == StateWaitClientInitial {
return 0, nil
}
sent := int(0)
/*
* ENQUEUE STUFF
*/
// FIRST enqueue data for stream 0
err := c.queueStreamFrames(false)
if err != nil {
return sent, err
}
// SECOND enqueue data for protected streams
if c.state == StateEstablished {
err := c.queueStreamFrames(true)
if err != nil {
return sent, err
}
/*
* SEND STUFF
*/
// THIRD send enqueued data from protected streams
s, err := c.sendQueuedFrames(packetType1RTTProtectedPhase0, true, bareAcks)
if err != nil {
return sent, err
}
sent += s
// We still want to send out data in unprotected mode but we don't need to just ACK stuff.
bareAcks = false
}
// FOURTH send enqueued data from stream 0
pt := uint8(packetTypeClientCleartext)
if c.role == RoleServer {
pt = packetTypeServerCleartext
}
s, err := c.sendQueuedFrames(pt, false, 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 uint8, frames []frame, acks ackRanges, left int) (int, error) {
asent := int(0)
var err error
containsOnlyAcks := len(frames) == 0
// (left - 16) is positive if there is place enough for a basic ACK frame without
// aditional ACK blocks.
if len(acks) > 0 && (left-kAckHeaderLength) >= 0 {
var af *frame
af, asent, err = c.makeAckFrame(acks, left)
if err != nil {
return 0, err
}
if af != nil {
frames = append(frames, *af)
}
}
// Record which packets we sent ACKs in.
c.sentAcks[c.nextSendPacket] = acks[0:asent]
err = c.sendPacket(pt, frames, containsOnlyAcks)
if err != nil {
return 0, err
}
return asent, nil
}
func (c *Connection) queueFrame(q *[]frame, f frame) {
*q = append(*q, f)
}
// Send all the queued data on a set of streams with packet type |pt|
func (c *Connection) queueStreamFrames(protected bool) error {
c.log(logTypeConnection, "%v: queueStreamFrames, protected=%v",
c.label(), protected)
var streams []*Stream
var q *[]frame
if !protected {
streams = c.streams[0:1]
q = &c.outputClearQ
} else {
streams = c.streams[1:]
q = &c.outputProtectedQ
}
// Output all the stream frames that are now permitted by stream flow control
for _, s := range streams {
if s != nil {
chunks, _ := s.outputWritable()
for _, ch := range chunks {
c.queueFrame(q, newStreamFrame(s.id, ch.offset, ch.data, ch.last))
}
}
}
return nil
}
/* 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(pt uint8, protected bool, bareAcks bool) (int, error) {
c.log(logTypeConnection, "%v: sendQueuedFrames, pt=%v, protected=%v",
c.label(), pt, protected)
acks := c.recvd.prepareAckRange(protected, false)
now := time.Now()
txAge := time.Duration(c.retransmitTime) * time.Millisecond
aeadOverhead := c.determineAead(pt).Overhead()
sent := int(0)
spaceInCongestionWindow := c.congestion.bytesAllowedToSend()
// Select the queue we will send from
var queue *[]frame
if protected {
queue = &c.outputProtectedQ
} else {
queue = &c.outputClearQ
}
// TODO(ekr@rtfm.com): Don't retransmit non-retransmittable.
/* 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 */
// Store frames that will be sent in the next packet
frames := make([]frame, 0)
// The length of the next packet to be send
spaceInPacket := c.mtu - aeadOverhead - kLongHeaderLength // TODO(ekr@rtfm.com): check header type
spaceInCongestionWindow -= (aeadOverhead + kLongHeaderLength)
for i, _ := range *queue {
f := &((*queue)[i])
// c.log(logTypeStream, "Examining frame=%v", f)
frameLength, err := f.length()
if err != nil {
return 0, err
}
cAge := now.Sub(f.time)
if f.needsTransmit {
c.log(logTypeStream, "Frame %f requires transmission", f.String())
} else if cAge < txAge {
c.log(logTypeStream, "Skipping frame %f because sent too recently", f.String())
continue
}
// if there is no more space in the congestion window, stop
// trying to send stuff
if spaceInCongestionWindow < frameLength {
break
}
c.log(logTypeStream, "Sending frame %s, age = %v", f.String(), cAge)
f.time = now
f.needsTransmit = false
// if there is no more space for the next frame in the packet,
// send it and start forming a new packet
if spaceInPacket < frameLength {
asent, err := c.sendCombinedPacket(pt, frames, acks, spaceInPacket)
if err != nil {
return 0, err
}
sent++
acks = acks[asent:]
frames = make([]frame, 0)
spaceInPacket = c.mtu - aeadOverhead - kLongHeaderLength // TODO(ekr@rtfm.com): check header type
spaceInCongestionWindow -= (aeadOverhead + kLongHeaderLength)
}
// add the frame to the packet
frames = append(frames, *f)
spaceInPacket -= frameLength
spaceInCongestionWindow -= frameLength
// Record that we send this chunk in the current packet
f.pns = append(f.pns, c.nextSendPacket)
sf, ok := f.f.(*streamFrame)
if ok && sf.hasFin() {
c.streams[sf.StreamId].closeSend()
}
}
// Send the remainder, plus any ACKs that are left.
// TODO(piet@devae.re) This might push the outstanding data over the congestion window
c.log(logTypeConnection, "%s: Remainder to send? sent=%v frames=%v acks=%v bareAcks=%v",
c.label(), sent, len(frames), len(acks), bareAcks)
if len(frames) > 0 || (len(acks) > 0 && bareAcks) {
// TODO(ekr@rtfm.com): this may skip acks if there isn't
// room, but hopefully we eventually catch up.
_, err := c.sendCombinedPacket(pt, frames, acks, spaceInPacket)
if err != nil {
return 0, err
}
sent++
} else if len(acks) > 0 {
c.log(logTypeAck, "Acks to send, but suppressing bare acks")
}
return sent, nil
}
func (c *Connection) handleLostPacket(lostPn uint64) {
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) {
for _, s := range c.streams {
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
}
n += cd(c.outputClearQ)
n += cd(c.outputProtectedQ)
return
}
// Provide 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) input(p []byte) error {
if c.isClosed() {
return ErrorConnIsClosed
}
c.lastInput = time.Now()
var hdr packetHeader
c.log(logTypeTrace, "Receiving packet len=%v %v", len(p), hex.EncodeToString(p))
hdrlen, err := decode(&hdr, p)
if err != nil {
c.log(logTypeConnection, "Could not decode packetX: %v", hex.EncodeToString(p))
return wrapE(ErrorInvalidPacket, err)
}
assert(int(hdrlen) <= len(p))
if isLongHeader(&hdr) && hdr.Version != c.version {
if c.role == RoleServer {
c.log(logTypeConnection, "%s: Received unsupported version %v, expected %v", c.label(), hdr.Version, c.version)
err = c.sendVersionNegotiation(hdr.ConnectionID, hdr.PacketNumber, hdr.Version)
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.getHeaderType() != packetTypeVersionNegotiation {
return fmt.Errorf("Received packet with unexpected version %v", hdr.Version)
}
}
}
typ := hdr.getHeaderType()
c.log(logTypeFlowControl, "EKR: Received packet %x len=%d", hdr.PacketNumber, len(p))
c.log(logTypeConnection, "Packet header %v, %d", hdr, typ)
if typ == packetTypeVersionNegotiation {
return c.processVersionNegotiation(&hdr, p[hdrlen:])
}
if c.state == StateWaitClientInitial {
if typ != packetTypeClientInitial {
c.log(logTypeConnection, "Received unexpected packet before client initial")
return nil
}
// TODO(ekr@rtfm.com): This will result in connection ID flap if we
// receive a new connection from the same tuple with a different conn ID.
c.clientConnId = hdr.ConnectionID
err := c.setupAeadMasking()
if err != nil {
return err
}
}
aead := c.readClear.aead
if hdr.isProtected() {
if c.readProtected == nil {
c.log(logTypeConnection, "Received protected data before crypto state is ready")
return nil
}
aead = c.readProtected.aead
}
// TODO(ekr@rtfm.com): this dup detection doesn't work right if you
// get a cleartext packet that has the same PN as a ciphertext or vice versa.
// Need to fix.
c.log(logTypeConnection, "%s: Received (unverified) packet with PN=%x PT=%v",
c.label(), hdr.PacketNumber, hdr.getHeaderType())
packetNumber := hdr.PacketNumber
if c.recvd.initialized() {
packetNumber = c.expandPacketNumber(hdr.PacketNumber, int(hdr.PacketNumber__length()))
c.log(logTypeConnection, "Reconstructed packet number %x", packetNumber)
}
if c.recvd.initialized() && !c.recvd.packetNotReceived(packetNumber) {
c.log(logTypeConnection, "Discarding duplicate packet %x", packetNumber)
return nonFatalError(fmt.Sprintf("Duplicate packet id %x", packetNumber))
}
var payload []byte
/* hack to not have encryption pietdv */
if DUMMY_NO_ENCRYPT {
payload = p[hdrlen:]
} else {
var err error