/
utp.go
1463 lines (1334 loc) · 31.7 KB
/
utp.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 utp implements uTP, the micro transport protocol as used with
// Bittorrent. It opts for simplicity and reliability over strict adherence to
// the (poor) spec. It allows using the underlying OS-level transport despite
// dispatching uTP on top to allow for example, shared socket use with DHT.
// Additionally, multiple uTP connections can share the same OS socket, to
// truly realize uTP's claim to be light on system and network switching
// resources.
//
// Socket is a wrapper of net.UDPConn, and performs dispatching of uTP packets
// to attached uTP Conns. Dial and Accept is done via Socket. Conn implements
// net.Conn over uTP, via aforementioned Socket.
package utp
import (
"encoding/binary"
"errors"
"expvar"
"fmt"
"io"
"log"
"math/rand"
"net"
"os"
"strconv"
"sync"
"time"
"github.com/anacrolix/missinggo"
"github.com/anacrolix/missinggo/pproffd"
)
const (
// Maximum received SYNs that haven't been accepted. If more SYNs are
// received, a pseudo randomly selected SYN is replied to with a reset to
// make room.
backlog = 50
// IPv6 min MTU is 1280, -40 for IPv6 header, and ~8 for fragment header?
minMTU = 1232
recvWindow = 1 << 18 // 256KiB
// uTP header of 20, +2 for the next extension, and 8 bytes of selective
// ACK.
maxHeaderSize = 30
maxPayloadSize = minMTU - maxHeaderSize
maxRecvSize = 0x2000
// Maximum out-of-order packets to buffer.
maxUnackedInbound = 256
maxUnackedSends = 256
)
var (
ackSkippedResends = expvar.NewInt("utpAckSkippedResends")
// Inbound packets processed by a Conn.
deliveriesProcessed = expvar.NewInt("utpDeliveriesProcessed")
sentStatePackets = expvar.NewInt("utpSentStatePackets")
unusedReads = expvar.NewInt("utpUnusedReads")
sendBufferPool = sync.Pool{
New: func() interface{} { return make([]byte, minMTU) },
}
// This is the latency we assume on new connections. It should be higher
// than the latency we expect on most connections to prevent excessive
// resending to peers that take a long time to respond, before we've got a
// better idea of their actual latency.
initialLatency = 400 * time.Millisecond
// If a write isn't acked within this period, destroy the connection.
writeTimeout = 15 * time.Second
packetReadTimeout = 2 * time.Minute
)
type deadlineCallback struct {
deadline time.Time
timer *time.Timer
callback func()
}
func (me *deadlineCallback) deadlineExceeded() bool {
return !me.deadline.IsZero() && !time.Now().Before(me.deadline)
}
func (me *deadlineCallback) updateTimer() {
if me.timer != nil {
me.timer.Stop()
}
if me.deadline.IsZero() {
return
}
if me.callback == nil {
panic("deadline callback is nil")
}
me.timer = time.AfterFunc(me.deadline.Sub(time.Now()), me.callback)
}
func (me *deadlineCallback) setDeadline(t time.Time) {
me.deadline = t
me.updateTimer()
}
func (me *deadlineCallback) setCallback(f func()) {
me.callback = f
me.updateTimer()
}
type connDeadlines struct {
// mu sync.Mutex
read, write deadlineCallback
}
func (c *connDeadlines) SetDeadline(t time.Time) error {
c.read.setDeadline(t)
c.write.setDeadline(t)
return nil
}
func (c *connDeadlines) SetReadDeadline(t time.Time) error {
c.read.setDeadline(t)
return nil
}
func (c *connDeadlines) SetWriteDeadline(t time.Time) error {
c.write.setDeadline(t)
return nil
}
// Strongly-type guarantee of resolved network address.
type resolvedAddrStr string
// Uniquely identifies any uTP connection on top of the underlying packet
// stream.
type connKey struct {
remoteAddr resolvedAddrStr
connID uint16
}
// A Socket wraps a net.PacketConn, diverting uTP packets to its child uTP
// Conns.
type Socket struct {
mu sync.RWMutex
pc net.PacketConn
conns map[connKey]*Conn
backlogNotEmpty missinggo.Event
backlog map[syn]struct{}
reads chan read
closed missinggo.Event
unusedReads chan read
connDeadlines
// If a read error occurs on the underlying net.PacketConn, it is put
// here. This is because reading is done in its own goroutine to dispatch
// to uTP Conns.
ReadErr error
}
type read struct {
data []byte
from net.Addr
}
type syn struct {
seq_nr, conn_id uint16
addr string
}
const (
extensionTypeSelectiveAck = 1
)
type extensionField struct {
Type byte
Bytes []byte
}
type header struct {
Type st
Version int
ConnID uint16
Timestamp uint32
TimestampDiff uint32
WndSize uint32
SeqNr uint16
AckNr uint16
Extensions []extensionField
}
var (
mu sync.RWMutex
sockets = map[*Socket]struct{}{}
logLevel = 0
artificialPacketDropChance = 0.0
)
func init() {
logLevel, _ = strconv.Atoi(os.Getenv("GO_UTP_LOGGING"))
fmt.Sscanf(os.Getenv("GO_UTP_PACKET_DROP"), "%f", &artificialPacketDropChance)
}
var (
errClosed = errors.New("closed")
errNotImplemented = errors.New("not implemented")
errTimeout net.Error = timeoutError{"i/o timeout"}
errAckTimeout = timeoutError{"timed out waiting for ack"}
)
type timeoutError struct {
msg string
}
func (me timeoutError) Timeout() bool { return true }
func (me timeoutError) Error() string { return me.msg }
func (me timeoutError) Temporary() bool { return false }
func unmarshalExtensions(_type byte, b []byte) (n int, ef []extensionField, err error) {
for _type != 0 {
if _type != extensionTypeSelectiveAck {
// An extension type that is not known to us. Generally we're
// unmarshalling an packet that isn't actually uTP but we don't
// yet know for sure until we try to deliver it.
// logonce.Stderr.Printf("utp extension %d", _type)
}
if len(b) < 2 || len(b) < int(b[1])+2 {
err = fmt.Errorf("buffer ends prematurely: %x", b)
return
}
ef = append(ef, extensionField{
Type: _type,
Bytes: append([]byte{}, b[2:int(b[1])+2]...),
})
_type = b[0]
n += 2 + int(b[1])
b = b[2+int(b[1]):]
}
return
}
var errInvalidHeader = errors.New("invalid header")
func (h *header) Unmarshal(b []byte) (n int, err error) {
h.Type = st(b[0] >> 4)
h.Version = int(b[0] & 0xf)
if h.Type > stMax || h.Version != 1 {
err = errInvalidHeader
return
}
n, h.Extensions, err = unmarshalExtensions(b[1], b[20:])
if err != nil {
return
}
h.ConnID = binary.BigEndian.Uint16(b[2:4])
h.Timestamp = binary.BigEndian.Uint32(b[4:8])
h.TimestampDiff = binary.BigEndian.Uint32(b[8:12])
h.WndSize = binary.BigEndian.Uint32(b[12:16])
h.SeqNr = binary.BigEndian.Uint16(b[16:18])
h.AckNr = binary.BigEndian.Uint16(b[18:20])
n += 20
return
}
func (h *header) Marshal() (ret []byte) {
hLen := 20 + func() (ret int) {
for _, ext := range h.Extensions {
ret += 2 + len(ext.Bytes)
}
return
}()
ret = sendBufferPool.Get().([]byte)[:hLen:minMTU]
// ret = make([]byte, hLen, minMTU)
p := ret // Used for manipulating ret.
p[0] = byte(h.Type<<4 | 1)
binary.BigEndian.PutUint16(p[2:4], h.ConnID)
binary.BigEndian.PutUint32(p[4:8], h.Timestamp)
binary.BigEndian.PutUint32(p[8:12], h.TimestampDiff)
binary.BigEndian.PutUint32(p[12:16], h.WndSize)
binary.BigEndian.PutUint16(p[16:18], h.SeqNr)
binary.BigEndian.PutUint16(p[18:20], h.AckNr)
// Pointer to the last type field so the next extension can set it.
_type := &p[1]
// We're done with the basic header.
p = p[20:]
for _, ext := range h.Extensions {
*_type = ext.Type
// The next extension's type will go here.
_type = &p[0]
p[1] = uint8(len(ext.Bytes))
if int(p[1]) != copy(p[2:], ext.Bytes) {
panic("unexpected extension length")
}
p = p[2+len(ext.Bytes):]
}
if len(p) != 0 {
panic("header length changed")
}
return
}
var (
_ net.Listener = &Socket{}
_ net.PacketConn = &Socket{}
)
type st int
func (me st) String() string {
switch me {
case stData:
return "stData"
case stFin:
return "stFin"
case stState:
return "stState"
case stReset:
return "stReset"
case stSyn:
return "stSyn"
default:
panic(fmt.Sprintf("%d", me))
}
}
const (
stData st = 0
stFin = 1
stState = 2
stReset = 3
stSyn = 4
// Used for validating packet headers.
stMax = stSyn
)
// Conn is a uTP stream and implements net.Conn. It owned by a Socket, which
// handles dispatching packets to and from Conns.
type Conn struct {
mu sync.Mutex
event sync.Cond
recv_id, send_id uint16
seq_nr, ack_nr uint16
lastAck uint16
lastTimeDiff uint32
peerWndSize uint32
cur_window uint32
// Data waiting to be Read.
readBuf []byte
socket *Socket
remoteAddr net.Addr
// The uTP timestamp.
startTimestamp uint32
// When the conn was allocated.
created time.Time
sentSyn bool
synAcked bool
gotFin bool
wroteFin bool
finAcked bool
err error
closing bool
closed bool
unackedSends []*send
// Inbound payloads, the first is ack_nr+1.
inbound []recv
inboundWnd uint32
packetsIn chan packet
connDeadlines
latencies []time.Duration
pendingSendState bool
}
type send struct {
acked bool // Closed with Conn lock.
payloadSize uint32
started missinggo.MonotonicTime
// This send was skipped in a selective ack.
resend func()
timedOut func()
conn *Conn
acksSkipped int
resendTimer *time.Timer
numResends int
}
// first is true if this is the first time the send is acked. latency is
// calculated for the first ack.
func (s *send) Ack() (latency time.Duration, first bool) {
s.resendTimer.Stop()
if s.acked {
return
}
s.acked = true
s.conn.event.Broadcast()
first = true
latency = missinggo.MonotonicSince(s.started)
return
}
type recv struct {
seen bool
data []byte
Type st
}
var (
_ net.Conn = &Conn{}
)
func (c *Conn) age() time.Duration {
return time.Since(c.created)
}
func (c *Conn) timestamp() uint32 {
return nowTimestamp() - c.startTimestamp
}
// Create a Socket, using the provided net.PacketConn. If you want to retain
// use of the net.PacketConn after the Socket closes it, override your
// net.PacketConn's Close method.
func NewSocketFromPacketConn(pc net.PacketConn) (s *Socket, err error) {
s = &Socket{
backlog: make(map[syn]struct{}, backlog),
reads: make(chan read, 100),
pc: pc,
unusedReads: make(chan read, 100),
}
mu.Lock()
sockets[s] = struct{}{}
mu.Unlock()
go s.reader()
go s.dispatcher()
return
}
// addr is used to create a listening UDP conn which becomes the underlying
// net.PacketConn for the Socket.
func NewSocket(network, addr string) (s *Socket, err error) {
pc, err := net.ListenPacket(network, addr)
if err != nil {
return
}
return NewSocketFromPacketConn(pc)
}
func packetDebugString(h *header, payload []byte) string {
return fmt.Sprintf("%s->%d: %q", h.Type, h.ConnID, payload)
}
func (s *Socket) reader() {
defer close(s.reads)
var b [maxRecvSize]byte
for {
if s.pc == nil {
break
}
n, addr, err := s.pc.ReadFrom(b[:])
if err != nil {
s.mu.Lock()
if !s.closed.IsSet() {
s.ReadErr = err
}
s.mu.Unlock()
return
}
var nilB []byte
s.reads <- read{append(nilB, b[:n:n]...), addr}
}
}
func (s *Socket) unusedRead(read read) {
unusedReads.Add(1)
select {
case s.unusedReads <- read:
default:
// Drop the packet.
}
}
func stringAddr(s string) net.Addr {
addr, err := net.ResolveUDPAddr("udp", s)
if err != nil {
panic(err)
}
return addr
}
func (s *Socket) pushBacklog(syn syn) {
if _, ok := s.backlog[syn]; ok {
return
}
for k := range s.backlog {
if len(s.backlog) < backlog {
break
}
delete(s.backlog, k)
// A syn is sent on the remote's recv_id, so this is where we can send
// the reset.
s.reset(stringAddr(k.addr), k.seq_nr, k.conn_id)
}
s.backlog[syn] = struct{}{}
s.backlogChanged()
}
func (s *Socket) dispatcher() {
for {
select {
case read, ok := <-s.reads:
if !ok {
return
}
if len(read.data) < 20 {
s.unusedRead(read)
continue
}
s.dispatch(read)
}
}
}
func (s *Socket) dispatch(read read) {
b := read.data
addr := read.from
var h header
hEnd, err := h.Unmarshal(b)
if logLevel >= 1 {
log.Printf("recvd utp msg: %s", packetDebugString(&h, b[hEnd:]))
}
if err != nil || h.Type > stMax || h.Version != 1 {
s.unusedRead(read)
return
}
s.mu.Lock()
defer s.mu.Unlock()
c, ok := s.conns[connKey{resolvedAddrStr(addr.String()), func() (recvID uint16) {
recvID = h.ConnID
// If a SYN is resent, its connection ID field will be one lower
// than we expect.
if h.Type == stSyn {
recvID++
}
return
}()}]
if ok {
if h.Type == stSyn {
if h.ConnID == c.send_id-2 {
// This is a SYN for connection that cannot exist locally. The
// connection the remote wants to establish here with the proposed
// recv_id, already has an existing connection that was dialled
// *out* from this socket, which is why the send_id is 1 higher,
// rather than 1 lower than the recv_id.
log.Print("resetting conflicting syn")
s.reset(addr, h.SeqNr, h.ConnID)
return
} else if h.ConnID != c.send_id {
panic("bad assumption")
}
}
c.deliver(h, b[hEnd:])
return
}
if h.Type == stSyn {
if logLevel >= 1 {
log.Printf("adding SYN to backlog")
}
syn := syn{
seq_nr: h.SeqNr,
conn_id: h.ConnID,
addr: addr.String(),
}
s.pushBacklog(syn)
return
} else if h.Type != stReset {
// This is an unexpected packet. We'll send a reset, but also pass
// it on.
// log.Print("resetting unexpected packet")
// I don't think you can reset on the received packets ConnID if it isn't a SYN, as the send_id will differ in this case.
s.reset(addr, h.SeqNr, h.ConnID)
s.reset(addr, h.SeqNr, h.ConnID-1)
s.reset(addr, h.SeqNr, h.ConnID+1)
}
s.unusedRead(read)
}
// Send a reset in response to a packet with the given header.
func (s *Socket) reset(addr net.Addr, ackNr, connId uint16) {
go s.writeTo((&header{
Type: stReset,
Version: 1,
ConnID: connId,
AckNr: ackNr,
}).Marshal(), addr)
}
// Attempt to connect to a remote uTP listener, creating a Socket just for
// this connection.
func Dial(addr string) (net.Conn, error) {
return DialTimeout(addr, 0)
}
// Same as Dial with a timeout parameter.
func DialTimeout(addr string, timeout time.Duration) (nc net.Conn, err error) {
s, err := NewSocket("udp", ":0")
if err != nil {
return
}
defer s.Close()
return s.DialTimeout(addr, timeout)
}
// Return a recv_id that should be free. Handling the case where it isn't is
// deferred to a more appropriate function.
func (s *Socket) newConnID(remoteAddr resolvedAddrStr) (id uint16) {
// Rather than use math.Rand, which requires generating all the IDs up
// front and allocating a slice, we do it on the stack, generating the IDs
// only as required. To do this, we use the fact that the array is
// default-initialized. IDs that are 0, are actually their index in the
// array. IDs that are non-zero, are +1 from their intended ID.
var idsBack [0x10000]int
ids := idsBack[:]
for len(ids) != 0 {
// Pick the next ID from the untried ids.
i := rand.Intn(len(ids))
id = uint16(ids[i])
// If it's zero, then treat it as though the index i was the ID.
// Otherwise the value we get is the ID+1.
if id == 0 {
id = uint16(i)
} else {
id--
}
// Check there's no connection using this ID for its recv_id...
_, ok1 := s.conns[connKey{remoteAddr, id}]
// and if we're connecting to our own Socket, that there isn't a Conn
// already receiving on what will correspond to our send_id. Note that
// we just assume that we could be connecting to our own Socket. This
// will halve the available connection IDs to each distinct remote
// address. Presumably that's ~0x8000, down from ~0x10000.
_, ok2 := s.conns[connKey{remoteAddr, id + 1}]
_, ok4 := s.conns[connKey{remoteAddr, id - 1}]
if !ok1 && !ok2 && !ok4 {
return
}
// The set of possible IDs is shrinking. The highest one will be lost, so
// it's moved to the location of the one we just tried.
ids[i] = len(ids) // Conveniently already +1.
// And shrink.
ids = ids[:len(ids)-1]
}
return
}
func (c *Conn) sendPendingState() {
if !c.pendingSendState {
return
}
if c.closed {
c.sendReset()
} else {
c.sendState()
}
}
func (s *Socket) newConn(addr net.Addr) (c *Conn) {
c = &Conn{
socket: s,
remoteAddr: addr,
created: time.Now(),
packetsIn: make(chan packet, 100),
}
c.event.L = &c.mu
c.mu.Lock()
c.connDeadlines.read.setCallback(func() {
c.mu.Lock()
c.event.Broadcast()
c.mu.Unlock()
})
c.connDeadlines.write.setCallback(func() {
c.mu.Lock()
c.event.Broadcast()
c.mu.Unlock()
})
c.mu.Unlock()
go c.deliveryProcessor()
return
}
func (s *Socket) Dial(addr string) (net.Conn, error) {
return s.DialTimeout(addr, 0)
}
func (s *Socket) DialTimeout(addr string, timeout time.Duration) (nc net.Conn, err error) {
netAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return
}
s.mu.Lock()
c := s.newConn(netAddr)
c.recv_id = s.newConnID(resolvedAddrStr(netAddr.String()))
c.send_id = c.recv_id + 1
if logLevel >= 1 {
log.Printf("dial registering addr: %s", netAddr.String())
}
if !s.registerConn(c.recv_id, resolvedAddrStr(netAddr.String()), c) {
err = errors.New("couldn't register new connection")
log.Println(c.recv_id, netAddr.String())
for k, c := range s.conns {
log.Println(k, c, c.age())
}
log.Printf("that's %d connections", len(s.conns))
}
s.mu.Unlock()
if err != nil {
return
}
connErr := make(chan error, 1)
go func() {
connErr <- c.connect()
}()
var timeoutCh <-chan time.Time
if timeout != 0 {
timeoutCh = time.After(timeout)
}
select {
case err = <-connErr:
case <-timeoutCh:
err = errTimeout
}
if err != nil {
c.Close()
return
}
nc = pproffd.WrapNetConn(c)
return
}
func (c *Conn) wndSize() uint32 {
if len(c.inbound) > maxUnackedInbound/2 {
return 0
}
buffered := uint32(len(c.readBuf)) + c.inboundWnd
if buffered > recvWindow {
return 0
}
return recvWindow - buffered
}
func nowTimestamp() uint32 {
return uint32(time.Now().UnixNano() / int64(time.Microsecond))
}
// Send the given payload with an up to date header.
func (c *Conn) send(_type st, connID uint16, payload []byte, seqNr uint16) (err error) {
// Always selectively ack the first 64 packets. Don't bother with rest for
// now.
selAck := selectiveAckBitmask(make([]byte, 8))
for i := 1; i < 65; i++ {
if len(c.inbound) <= i {
break
}
if c.inbound[i].seen {
selAck.SetBit(i - 1)
}
}
h := header{
Type: _type,
Version: 1,
ConnID: connID,
SeqNr: seqNr,
AckNr: c.ack_nr,
WndSize: c.wndSize(),
Timestamp: c.timestamp(),
TimestampDiff: c.lastTimeDiff,
// Currently always send an 8 byte selective ack.
Extensions: []extensionField{{
Type: extensionTypeSelectiveAck,
Bytes: selAck,
}},
}
p := h.Marshal()
// Extension headers are currently fixed in size.
if len(p) != maxHeaderSize {
panic("header has unexpected size")
}
p = append(p, payload...)
if logLevel >= 1 {
log.Printf("writing utp msg to %s: %s", c.remoteAddr, packetDebugString(&h, payload))
}
n1, err := c.socket.writeTo(p, c.remoteAddr)
if err != nil {
return
}
if n1 != len(p) {
panic(n1)
}
c.unpendSendState()
return
}
func (me *Conn) unpendSendState() {
me.pendingSendState = false
}
func (c *Conn) pendSendState() {
c.pendingSendState = true
}
func (me *Socket) writeTo(b []byte, addr net.Addr) (n int, err error) {
mu.RLock()
apdc := artificialPacketDropChance
mu.RUnlock()
if apdc != 0 {
if rand.Float64() < apdc {
n = len(b)
return
}
}
n, err = me.pc.WriteTo(b, addr)
return
}
func (s *send) timeoutResend() {
if missinggo.MonotonicSince(s.started) >= writeTimeout {
s.timedOut()
return
}
s.conn.mu.Lock()
defer s.conn.mu.Unlock()
if s.acked || s.conn.closed {
return
}
rt := s.conn.resendTimeout()
go s.resend()
s.numResends++
s.resendTimer.Reset(rt * time.Duration(s.numResends))
}
func (me *Conn) writeSyn() {
if me.sentSyn {
panic("already sent syn")
}
me.write(stSyn, me.recv_id, nil, me.seq_nr)
return
}
func (c *Conn) write(_type st, connID uint16, payload []byte, seqNr uint16) (n int) {
switch _type {
case stSyn, stFin, stData:
default:
panic(_type)
}
if c.wroteFin {
panic("can't write after fin")
}
if len(payload) > maxPayloadSize {
payload = payload[:maxPayloadSize]
}
err := c.send(_type, connID, payload, seqNr)
if err != nil {
c.destroy(fmt.Errorf("error sending packet: %s", err))
return
}
n = len(payload)
// Copy payload so caller to write can continue to use the buffer.
if payload != nil {
payload = append(sendBufferPool.Get().([]byte)[:0:minMTU], payload...)
}
send := &send{
payloadSize: uint32(len(payload)),
started: missinggo.MonotonicNow(),
resend: func() {
c.mu.Lock()
err := c.send(_type, connID, payload, seqNr)
if err != nil {
log.Printf("error resending packet: %s", err)
}
c.mu.Unlock()
},
timedOut: func() {
c.mu.Lock()
c.destroy(errAckTimeout)
c.mu.Unlock()
},
conn: c,
}
send.resendTimer = time.AfterFunc(c.resendTimeout(), send.timeoutResend)
c.unackedSends = append(c.unackedSends, send)
c.cur_window += send.payloadSize
c.seq_nr++
return
}
func (c *Conn) latency() (ret time.Duration) {
if len(c.latencies) == 0 {
return initialLatency
}
for _, l := range c.latencies {
ret += l
}
ret = (ret + time.Duration(len(c.latencies)) - 1) / time.Duration(len(c.latencies))
return
}
func (c *Conn) numUnackedSends() (num int) {
for _, s := range c.unackedSends {
if !s.acked {
num++
}
}
return
}
func (c *Conn) sendState() {
c.send(stState, c.send_id, nil, c.seq_nr)
sentStatePackets.Add(1)
}
func (c *Conn) sendReset() {
c.send(stReset, c.send_id, nil, c.seq_nr)
}
func seqLess(a, b uint16) bool {
if b < 0x8000 {
return a < b || a >= b-0x8000
} else {
return a < b && a >= b-0x8000
}
}
// Ack our send with the given sequence number.
func (c *Conn) ack(nr uint16) {
if !seqLess(c.lastAck, nr) {
// Already acked.
return
}
i := nr - c.lastAck - 1
if int(i) >= len(c.unackedSends) {
log.Printf("got ack ahead of syn (%x > %x)", nr, c.seq_nr-1)
return
}
s := c.unackedSends[i]
latency, first := s.Ack()
if first {
c.cur_window -= s.payloadSize
c.latencies = append(c.latencies, latency)
if len(c.latencies) > 10 {
c.latencies = c.latencies[len(c.latencies)-10:]
}
}
for {
if len(c.unackedSends) == 0 {
break
}
if !c.unackedSends[0].acked {
// Can't trim unacked sends any further.
return
}
// Trim the front of the unacked sends.
c.unackedSends = c.unackedSends[1:]
c.lastAck++
}
c.event.Broadcast()
}
func (c *Conn) ackTo(nr uint16) {
if !seqLess(nr, c.seq_nr) {
return
}
for seqLess(c.lastAck, nr) {
c.ack(c.lastAck + 1)
}
}
type selectiveAckBitmask []byte
func (me selectiveAckBitmask) NumBits() int {
return len(me) * 8
}
func (me selectiveAckBitmask) SetBit(index int) {
me[index/8] |= 1 << uint(index%8)
}
func (me selectiveAckBitmask) BitIsSet(index int) bool {
return me[index/8]>>uint(index%8)&1 == 1
}
// Return the send state for the sequence number. Returns nil if there's no
// outstanding send for that sequence number.
func (c *Conn) seqSend(seqNr uint16) *send {
if !seqLess(c.lastAck, seqNr) {
// Presumably already acked.
return nil