-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
1559 lines (1434 loc) · 40.7 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 torrent
import (
"bufio"
"bytes"
"fmt"
"io"
"math"
"math/rand"
"net"
"strconv"
"strings"
"sync"
"time"
"github.com/anacrolix/dht"
"github.com/anacrolix/log"
"github.com/anacrolix/missinggo"
"github.com/anacrolix/missinggo/bitmap"
"github.com/anacrolix/missinggo/iter"
"github.com/anacrolix/missinggo/prioritybitmap"
"github.com/pkg/errors"
"github.com/anacrolix/torrent/bencode"
"github.com/anacrolix/torrent/mse"
pp "github.com/anacrolix/torrent/peer_protocol"
)
type peerSource string
const (
peerSourceTracker = "Tr"
peerSourceIncoming = "I"
peerSourceDHTGetPeers = "Hg" // Peers we found by searching a DHT.
peerSourceDHTAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
peerSourcePEX = "X"
)
// Maintains the state of a connection with a peer.
type connection struct {
// First to ensure 64-bit alignment for atomics. See #262.
stats ConnStats
t *Torrent
// The actual Conn, used for closing, and setting socket options.
conn net.Conn
outgoing bool
// The Reader and Writer for this Conn, with hooks installed for stats,
// limiting, deadlines etc.
w io.Writer
r io.Reader
// True if the connection is operating over MSE obfuscation.
headerEncrypted bool
cryptoMethod mse.CryptoMethod
Discovery peerSource
closed missinggo.Event
// Set true after we've added our ConnStats generated during handshake to
// other ConnStat instances as determined when the *Torrent became known.
reconciledHandshakeStats bool
lastMessageReceived time.Time
completedHandshake time.Time
lastUsefulChunkReceived time.Time
lastChunkSent time.Time
// Stuff controlled by the local peer.
Interested bool
lastBecameInterested time.Time
priorInterest time.Duration
lastStartedExpectingToReceiveChunks time.Time
cumulativeExpectedToReceiveChunks time.Duration
chunksReceivedWhileExpecting int64
Choked bool
requests map[request]struct{}
requestsLowWater int
// Chunks that we might reasonably expect to receive from the peer. Due to
// latency, buffering, and implementation differences, we may receive
// chunks that are no longer in the set of requests actually want.
validReceiveChunks map[request]struct{}
// Indexed by metadata piece, set to true if posted and pending a
// response.
metadataRequests []bool
sentHaves bitmap.Bitmap
// Stuff controlled by the remote peer.
PeerID PeerID
PeerInterested bool
PeerChoked bool
PeerRequests map[request]struct{}
PeerExtensionBytes pp.PeerExtensionBits
// The pieces the peer has claimed to have.
peerPieces bitmap.Bitmap
// The peer has everything. This can occur due to a special message, when
// we may not even know the number of pieces in the torrent yet.
peerSentHaveAll bool
// The highest possible number of pieces the torrent could have based on
// communication with the peer. Generally only useful until we have the
// torrent info.
peerMinPieces pieceIndex
// Pieces we've accepted chunks for from the peer.
peerTouchedPieces map[pieceIndex]struct{}
peerAllowedFast bitmap.Bitmap
PeerMaxRequests int // Maximum pending requests the peer allows.
PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
PeerClientName string
pieceInclination []int
pieceRequestOrder prioritybitmap.PriorityBitmap
writeBuffer *bytes.Buffer
uploadTimer *time.Timer
writerCond sync.Cond
}
func (cn *connection) updateExpectingChunks() {
if cn.expectingChunks() {
if cn.lastStartedExpectingToReceiveChunks.IsZero() {
cn.lastStartedExpectingToReceiveChunks = time.Now()
}
} else {
if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
cn.lastStartedExpectingToReceiveChunks = time.Time{}
}
}
}
func (cn *connection) expectingChunks() bool {
return cn.Interested && !cn.PeerChoked
}
// Returns true if the connection is over IPv6.
func (cn *connection) ipv6() bool {
ip := missinggo.AddrIP(cn.remoteAddr())
if ip.To4() != nil {
return false
}
return len(ip) == net.IPv6len
}
// Returns true the dialer has the lower client peer ID. TODO: Find the
// specification for this.
func (cn *connection) isPreferredDirection() bool {
return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
}
// Returns whether the left connection should be preferred over the right one,
// considering only their networking properties. If ok is false, we can't
// decide.
func (l *connection) hasPreferredNetworkOver(r *connection) (left, ok bool) {
var ml multiLess
ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
ml.NextBool(!l.utp(), !r.utp())
ml.NextBool(l.ipv6(), r.ipv6())
return ml.FinalOk()
}
func (cn *connection) cumInterest() time.Duration {
ret := cn.priorInterest
if cn.Interested {
ret += time.Since(cn.lastBecameInterested)
}
return ret
}
func (cn *connection) peerHasAllPieces() (all bool, known bool) {
if cn.peerSentHaveAll {
return true, true
}
if !cn.t.haveInfo() {
return false, false
}
return bitmap.Flip(cn.peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
}
func (cn *connection) mu() sync.Locker {
return cn.t.cl.locker()
}
func (cn *connection) remoteAddr() net.Addr {
return cn.conn.RemoteAddr()
}
func (cn *connection) localAddr() net.Addr {
return cn.conn.LocalAddr()
}
func (cn *connection) supportsExtension(ext pp.ExtensionName) bool {
_, ok := cn.PeerExtensionIDs[ext]
return ok
}
// The best guess at number of pieces in the torrent for this peer.
func (cn *connection) bestPeerNumPieces() pieceIndex {
if cn.t.haveInfo() {
return cn.t.numPieces()
}
return cn.peerMinPieces
}
func (cn *connection) completedString() string {
have := pieceIndex(cn.peerPieces.Len())
if cn.peerSentHaveAll {
have = cn.bestPeerNumPieces()
}
return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
}
// Correct the PeerPieces slice length. Return false if the existing slice is
// invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
// messages.
func (cn *connection) setNumPieces(num pieceIndex) error {
cn.peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
cn.peerPiecesChanged()
return nil
}
func eventAgeString(t time.Time) string {
if t.IsZero() {
return "never"
}
return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
}
func (cn *connection) connectionFlags() (ret string) {
c := func(b byte) {
ret += string([]byte{b})
}
if cn.cryptoMethod == mse.CryptoMethodRC4 {
c('E')
} else if cn.headerEncrypted {
c('e')
}
ret += string(cn.Discovery)
if cn.utp() {
c('U')
}
return
}
func (cn *connection) utp() bool {
return isUtpNetwork(cn.remoteAddr().Network())
}
// Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
func (cn *connection) statusFlags() (ret string) {
c := func(b byte) {
ret += string([]byte{b})
}
if cn.Interested {
c('i')
}
if cn.Choked {
c('c')
}
c('-')
ret += cn.connectionFlags()
c('-')
if cn.PeerInterested {
c('i')
}
if cn.PeerChoked {
c('c')
}
return
}
// func (cn *connection) String() string {
// var buf bytes.Buffer
// cn.WriteStatus(&buf, nil)
// return buf.String()
// }
func (cn *connection) downloadRate() float64 {
return float64(cn.stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
}
func (cn *connection) WriteStatus(w io.Writer, t *Torrent) {
// \t isn't preserved in <pre> blocks?
fmt.Fprintf(w, "%+-55q %s %s-%s\n", cn.PeerID, cn.PeerExtensionBytes, cn.localAddr(), cn.remoteAddr())
fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
eventAgeString(cn.lastMessageReceived),
eventAgeString(cn.completedHandshake),
eventAgeString(cn.lastHelpful()),
cn.cumInterest(),
cn.totalExpectingTime(),
)
fmt.Fprintf(w,
" %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
cn.completedString(),
len(cn.peerTouchedPieces),
&cn.stats.ChunksReadUseful,
&cn.stats.ChunksRead,
&cn.stats.ChunksWritten,
cn.requestsLowWater,
cn.numLocalRequests(),
cn.nominalMaxRequests(),
len(cn.PeerRequests),
cn.statusFlags(),
cn.downloadRate()/(1<<10),
)
fmt.Fprintf(w, " next pieces: %v%s\n",
iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
func() string {
if cn.shouldRequestWithoutBias() {
return " (fastest)"
} else {
return ""
}
}())
}
func (cn *connection) Close() {
if !cn.closed.Set() {
return
}
cn.tickleWriter()
cn.discardPieceInclination()
cn.pieceRequestOrder.Clear()
if cn.conn != nil {
go cn.conn.Close()
}
}
func (cn *connection) PeerHasPiece(piece pieceIndex) bool {
return cn.peerSentHaveAll || cn.peerPieces.Contains(bitmap.BitIndex(piece))
}
// Writes a message into the write buffer.
func (cn *connection) Post(msg pp.Message) {
torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
// We don't need to track bytes here because a connection.w Writer wrapper
// takes care of that (although there's some delay between us recording
// the message, and the connection writer flushing it out.).
cn.writeBuffer.Write(msg.MustMarshalBinary())
// Last I checked only Piece messages affect stats, and we don't post
// those.
cn.wroteMsg(&msg)
cn.tickleWriter()
}
func (cn *connection) requestMetadataPiece(index int) {
eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
if eID == 0 {
return
}
if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
return
}
cn.Post(pp.Message{
Type: pp.Extended,
ExtendedID: eID,
ExtendedPayload: func() []byte {
b, err := bencode.Marshal(map[string]int{
"msg_type": pp.RequestMetadataExtensionMsgType,
"piece": index,
})
if err != nil {
panic(err)
}
return b
}(),
})
for index >= len(cn.metadataRequests) {
cn.metadataRequests = append(cn.metadataRequests, false)
}
cn.metadataRequests[index] = true
}
func (cn *connection) requestedMetadataPiece(index int) bool {
return index < len(cn.metadataRequests) && cn.metadataRequests[index]
}
// The actual value to use as the maximum outbound requests.
func (cn *connection) nominalMaxRequests() (ret int) {
if cn.t.requestStrategy == 3 {
expectingTime := int64(cn.totalExpectingTime())
if expectingTime == 0 {
expectingTime = math.MaxInt64
} else {
expectingTime *= 2
}
return int(clamp(
1,
int64(cn.PeerMaxRequests),
max(
// It makes sense to always pipeline at least one connection,
// since latency must be non-zero.
2,
// Request only as many as we expect to receive in the
// dupliateRequestTimeout window. We are trying to avoid having to
// duplicate requests.
cn.chunksReceivedWhileExpecting*int64(cn.t.duplicateRequestTimeout)/expectingTime,
),
))
}
return int(clamp(
1,
int64(cn.PeerMaxRequests),
max(64,
cn.stats.ChunksReadUseful.Int64()-(cn.stats.ChunksRead.Int64()-cn.stats.ChunksReadUseful.Int64()))))
}
func (cn *connection) totalExpectingTime() (ret time.Duration) {
ret = cn.cumulativeExpectedToReceiveChunks
if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
}
return
}
func (cn *connection) onPeerSentCancel(r request) {
if _, ok := cn.PeerRequests[r]; !ok {
torrent.Add("unexpected cancels received", 1)
return
}
if cn.fastEnabled() {
cn.reject(r)
} else {
delete(cn.PeerRequests, r)
}
}
func (cn *connection) Choke(msg messageWriter) (more bool) {
if cn.Choked {
return true
}
cn.Choked = true
more = msg(pp.Message{
Type: pp.Choke,
})
if cn.fastEnabled() {
for r := range cn.PeerRequests {
// TODO: Don't reject pieces in allowed fast set.
cn.reject(r)
}
} else {
cn.PeerRequests = nil
}
return
}
func (cn *connection) Unchoke(msg func(pp.Message) bool) bool {
if !cn.Choked {
return true
}
cn.Choked = false
return msg(pp.Message{
Type: pp.Unchoke,
})
}
func (cn *connection) SetInterested(interested bool, msg func(pp.Message) bool) bool {
if cn.Interested == interested {
return true
}
cn.Interested = interested
if interested {
cn.lastBecameInterested = time.Now()
} else if !cn.lastBecameInterested.IsZero() {
cn.priorInterest += time.Since(cn.lastBecameInterested)
}
cn.updateExpectingChunks()
// log.Printf("%p: setting interest: %v", cn, interested)
return msg(pp.Message{
Type: func() pp.MessageType {
if interested {
return pp.Interested
} else {
return pp.NotInterested
}
}(),
})
}
// The function takes a message to be sent, and returns true if more messages
// are okay.
type messageWriter func(pp.Message) bool
// Proxies the messageWriter's response.
func (cn *connection) request(r request, mw messageWriter) bool {
if _, ok := cn.requests[r]; ok {
panic("chunk already requested")
}
if !cn.PeerHasPiece(pieceIndex(r.Index)) {
panic("requesting piece peer doesn't have")
}
if _, ok := cn.t.conns[cn]; !ok {
panic("requesting but not in active conns")
}
if cn.closed.IsSet() {
panic("requesting when connection is closed")
}
if cn.PeerChoked {
if cn.peerAllowedFast.Get(int(r.Index)) {
torrent.Add("allowed fast requests sent", 1)
} else {
panic("requesting while choked and not allowed fast")
}
}
if cn.t.hashingPiece(pieceIndex(r.Index)) {
panic("piece is being hashed")
}
if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
panic("piece is queued for hash")
}
if cn.requests == nil {
cn.requests = make(map[request]struct{})
}
cn.requests[r] = struct{}{}
if cn.validReceiveChunks == nil {
cn.validReceiveChunks = make(map[request]struct{})
}
cn.validReceiveChunks[r] = struct{}{}
cn.t.pendingRequests[r]++
cn.t.lastRequested[r] = time.AfterFunc(cn.t.duplicateRequestTimeout, func() {
torrent.Add("duplicate request timeouts", 1)
cn.mu().Lock()
defer cn.mu().Unlock()
delete(cn.t.lastRequested, r)
for cn := range cn.t.conns {
if cn.PeerHasPiece(pieceIndex(r.Index)) {
cn.updateRequests()
}
}
})
cn.updateExpectingChunks()
return mw(pp.Message{
Type: pp.Request,
Index: r.Index,
Begin: r.Begin,
Length: r.Length,
})
}
func (cn *connection) fillWriteBuffer(msg func(pp.Message) bool) {
if !cn.t.networkingEnabled {
if !cn.SetInterested(false, msg) {
return
}
if len(cn.requests) != 0 {
for r := range cn.requests {
cn.deleteRequest(r)
// log.Printf("%p: cancelling request: %v", cn, r)
if !msg(makeCancelMessage(r)) {
return
}
}
}
}
if len(cn.requests) <= cn.requestsLowWater {
filledBuffer := false
cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
cn.iterPendingRequests(pieceIndex, func(r request) bool {
if !cn.SetInterested(true, msg) {
filledBuffer = true
return false
}
if len(cn.requests) >= cn.nominalMaxRequests() {
return false
}
// Choking is looked at here because our interest is dependent
// on whether we'd make requests in its absence.
if cn.PeerChoked {
if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
return false
}
}
if _, ok := cn.requests[r]; ok {
return true
}
filledBuffer = !cn.request(r, msg)
return !filledBuffer
})
return !filledBuffer
})
if filledBuffer {
// If we didn't completely top up the requests, we shouldn't mark
// the low water, since we'll want to top up the requests as soon
// as we have more write buffer space.
return
}
cn.requestsLowWater = len(cn.requests) / 2
}
cn.upload(msg)
}
// Routine that writes to the peer. Some of what to write is buffered by
// activity elsewhere in the Client, and some is determined locally when the
// connection is writable.
func (cn *connection) writer(keepAliveTimeout time.Duration) {
var (
lastWrite time.Time = time.Now()
keepAliveTimer *time.Timer
)
keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
cn.mu().Lock()
defer cn.mu().Unlock()
if time.Since(lastWrite) >= keepAliveTimeout {
cn.tickleWriter()
}
keepAliveTimer.Reset(keepAliveTimeout)
})
cn.mu().Lock()
defer cn.mu().Unlock()
defer cn.Close()
defer keepAliveTimer.Stop()
frontBuf := new(bytes.Buffer)
for {
if cn.closed.IsSet() {
return
}
if cn.writeBuffer.Len() == 0 {
cn.fillWriteBuffer(func(msg pp.Message) bool {
cn.wroteMsg(&msg)
cn.writeBuffer.Write(msg.MustMarshalBinary())
torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
return cn.writeBuffer.Len() < 1<<16 // 64KiB
})
}
if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
postedKeepalives.Add(1)
}
if cn.writeBuffer.Len() == 0 {
// TODO: Minimize wakeups....
cn.writerCond.Wait()
continue
}
// Flip the buffers.
frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
cn.mu().Unlock()
n, err := cn.w.Write(frontBuf.Bytes())
cn.mu().Lock()
if n != 0 {
lastWrite = time.Now()
keepAliveTimer.Reset(keepAliveTimeout)
}
if err != nil {
return
}
if n != frontBuf.Len() {
panic("short write")
}
frontBuf.Reset()
}
}
func (cn *connection) Have(piece pieceIndex) {
if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
return
}
cn.Post(pp.Message{
Type: pp.Have,
Index: pp.Integer(piece),
})
cn.sentHaves.Add(bitmap.BitIndex(piece))
}
func (cn *connection) PostBitfield() {
if cn.sentHaves.Len() != 0 {
panic("bitfield must be first have-related message sent")
}
if !cn.t.haveAnyPieces() {
return
}
cn.Post(pp.Message{
Type: pp.Bitfield,
Bitfield: cn.t.bitfield(),
})
cn.sentHaves = cn.t.completedPieces.Copy()
}
func (cn *connection) updateRequests() {
// log.Print("update requests")
cn.tickleWriter()
}
// Emits the indices in the Bitmaps bms in order, never repeating any index.
// skip is mutated during execution, and its initial values will never be
// emitted.
func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
return func(cb iter.Callback) {
for _, bm := range bms {
if !iter.All(func(i interface{}) bool {
skip.Add(i.(int))
return cb(i)
}, bitmap.Sub(bm, *skip).Iter) {
return
}
}
}
}
func (cn *connection) iterUnbiasedPieceRequestOrder(f func(piece pieceIndex) bool) bool {
now, readahead := cn.t.readerPiecePriorities()
var skip bitmap.Bitmap
if !cn.peerSentHaveAll {
// Pieces to skip include pieces the peer doesn't have.
skip = bitmap.Flip(cn.peerPieces, 0, bitmap.BitIndex(cn.t.numPieces()))
}
// And pieces that we already have.
skip.Union(cn.t.completedPieces)
skip.Union(cn.t.piecesQueuedForHash)
// Return an iterator over the different priority classes, minus the skip
// pieces.
return iter.All(
func(_piece interface{}) bool {
i := _piece.(bitmap.BitIndex)
if cn.t.hashingPiece(pieceIndex(i)) {
return true
}
return f(pieceIndex(i))
},
iterBitmapsDistinct(&skip, now, readahead),
func(cb iter.Callback) {
cn.t.pendingPieces.IterTyped(func(piece int) bool {
if skip.Contains(piece) {
return true
}
more := cb(piece)
skip.Add(piece)
return more
})
},
)
}
// The connection should download highest priority pieces first, without any
// inclination toward avoiding wastage. Generally we might do this if there's
// a single connection, or this is the fastest connection, and we have active
// readers that signal an ordering preference. It's conceivable that the best
// connection should do this, since it's least likely to waste our time if
// assigned to the highest priority pieces, and assigning more than one this
// role would cause significant wasted bandwidth.
func (cn *connection) shouldRequestWithoutBias() bool {
if cn.t.requestStrategy != 2 {
return false
}
if len(cn.t.readers) == 0 {
return false
}
if len(cn.t.conns) == 1 {
return true
}
if cn == cn.t.fastestConn {
return true
}
return false
}
func (cn *connection) iterPendingPieces(f func(pieceIndex) bool) bool {
if !cn.t.haveInfo() {
return false
}
if cn.t.requestStrategy == 3 {
return cn.iterUnbiasedPieceRequestOrder(f)
}
if cn.shouldRequestWithoutBias() {
return cn.iterUnbiasedPieceRequestOrder(f)
} else {
return cn.pieceRequestOrder.IterTyped(func(i int) bool {
return f(pieceIndex(i))
})
}
}
func (cn *connection) iterPendingPiecesUntyped(f iter.Callback) {
cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
}
func (cn *connection) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
return iterUndirtiedChunks(piece, cn.t, func(cs chunkSpec) bool {
r := request{pp.Integer(piece), cs}
if cn.t.requestStrategy == 3 {
if _, ok := cn.t.lastRequested[r]; ok {
// This piece has been requested on another connection, and
// the duplicate request timer is still running.
return true
}
}
return f(r)
})
}
func iterUndirtiedChunks(piece pieceIndex, t *Torrent, f func(chunkSpec) bool) bool {
p := &t.pieces[piece]
if t.requestStrategy == 3 {
for i := pp.Integer(0); i < p.numChunks(); i++ {
if !p.dirtyChunks.Get(bitmap.BitIndex(i)) {
if !f(t.chunkIndexSpec(i, piece)) {
return false
}
}
}
return true
}
chunkIndices := t.pieces[piece].undirtiedChunkIndices().ToSortedSlice()
// TODO: Use "math/rand".Shuffle >= Go 1.10
return iter.ForPerm(len(chunkIndices), func(i int) bool {
return f(t.chunkIndexSpec(pp.Integer(chunkIndices[i]), piece))
})
}
// check callers updaterequests
func (cn *connection) stopRequestingPiece(piece pieceIndex) bool {
return cn.pieceRequestOrder.Remove(bitmap.BitIndex(piece))
}
// This is distinct from Torrent piece priority, which is the user's
// preference. Connection piece priority is specific to a connection and is
// used to pseudorandomly avoid connections always requesting the same pieces
// and thus wasting effort.
func (cn *connection) updatePiecePriority(piece pieceIndex) bool {
tpp := cn.t.piecePriority(piece)
if !cn.PeerHasPiece(piece) {
tpp = PiecePriorityNone
}
if tpp == PiecePriorityNone {
return cn.stopRequestingPiece(piece)
}
prio := cn.getPieceInclination()[piece]
switch cn.t.requestStrategy {
case 1:
switch tpp {
case PiecePriorityNormal:
case PiecePriorityReadahead:
prio -= int(cn.t.numPieces())
case PiecePriorityNext, PiecePriorityNow:
prio -= 2 * int(cn.t.numPieces())
default:
panic(tpp)
}
prio += int(piece / 3)
default:
}
return cn.pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
}
func (cn *connection) getPieceInclination() []int {
if cn.pieceInclination == nil {
cn.pieceInclination = cn.t.getConnPieceInclination()
}
return cn.pieceInclination
}
func (cn *connection) discardPieceInclination() {
if cn.pieceInclination == nil {
return
}
cn.t.putPieceInclination(cn.pieceInclination)
cn.pieceInclination = nil
}
func (cn *connection) peerPiecesChanged() {
if cn.t.haveInfo() {
prioritiesChanged := false
for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
if cn.updatePiecePriority(i) {
prioritiesChanged = true
}
}
if prioritiesChanged {
cn.updateRequests()
}
}
}
func (cn *connection) raisePeerMinPieces(newMin pieceIndex) {
if newMin > cn.peerMinPieces {
cn.peerMinPieces = newMin
}
}
func (cn *connection) peerSentHave(piece pieceIndex) error {
if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
return errors.New("invalid piece")
}
if cn.PeerHasPiece(piece) {
return nil
}
cn.raisePeerMinPieces(piece + 1)
cn.peerPieces.Set(bitmap.BitIndex(piece), true)
if cn.updatePiecePriority(piece) {
cn.updateRequests()
}
return nil
}
func (cn *connection) peerSentBitfield(bf []bool) error {
cn.peerSentHaveAll = false
if len(bf)%8 != 0 {
panic("expected bitfield length divisible by 8")
}
// We know that the last byte means that at most the last 7 bits are
// wasted.
cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
// Ignore known excess pieces.
bf = bf[:cn.t.numPieces()]
}
for i, have := range bf {
if have {
cn.raisePeerMinPieces(pieceIndex(i) + 1)
}
cn.peerPieces.Set(i, have)
}
cn.peerPiecesChanged()
return nil
}
func (cn *connection) onPeerSentHaveAll() error {
cn.peerSentHaveAll = true
cn.peerPieces.Clear()
cn.peerPiecesChanged()
return nil
}
func (cn *connection) peerSentHaveNone() error {
cn.peerPieces.Clear()
cn.peerSentHaveAll = false
cn.peerPiecesChanged()
return nil
}
func (c *connection) requestPendingMetadata() {
if c.t.haveInfo() {
return
}
if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
// Peer doesn't support this.
return
}
// Request metadata pieces that we don't have in a random order.
var pending []int
for index := 0; index < c.t.metadataPieceCount(); index++ {
if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
pending = append(pending, index)
}
}
for _, i := range rand.Perm(len(pending)) {
c.requestMetadataPiece(pending[i])
}
}
func (cn *connection) wroteMsg(msg *pp.Message) {
torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
}
func (cn *connection) readMsg(msg *pp.Message) {
cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
}
// After handshake, we know what Torrent and Client stats to include for a
// connection.
func (cn *connection) postHandshakeStats(f func(*ConnStats)) {
t := cn.t
f(&t.stats)
f(&t.cl.stats)
}
// All ConnStats that include this connection. Some objects are not known
// until the handshake is complete, after which it's expected to reconcile the
// differences.
func (cn *connection) allStats(f func(*ConnStats)) {
f(&cn.stats)
if cn.reconciledHandshakeStats {
cn.postHandshakeStats(f)
}
}
func (cn *connection) wroteBytes(n int64) {
cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
}
func (cn *connection) readBytes(n int64) {
cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
}
// Returns whether the connection could be useful to us. We're seeding and
// they want data, we don't have metainfo and they can provide it, etc.
func (c *connection) useful() bool {
t := c.t
if c.closed.IsSet() {
return false
}
if !t.haveInfo() {
return c.supportsExtension("ut_metadata")
}
if t.seeding() && c.PeerInterested {
return true
}
if c.peerHasWantedPieces() {
return true