forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 2
/
torrent.go
1776 lines (1611 loc) · 43.5 KB
/
torrent.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 (
"container/heap"
"crypto/sha1"
"errors"
"fmt"
"io"
"math/rand"
"net"
"net/url"
"os"
"sync"
"text/tabwriter"
"time"
"unsafe"
"github.com/davecgh/go-spew/spew"
"github.com/anacrolix/dht/v2"
"github.com/anacrolix/log"
"github.com/anacrolix/missinggo"
"github.com/anacrolix/missinggo/bitmap"
"github.com/anacrolix/missinggo/perf"
"github.com/anacrolix/missinggo/prioritybitmap"
"github.com/anacrolix/missinggo/pubsub"
"github.com/anacrolix/missinggo/slices"
"github.com/anacrolix/torrent/bencode"
"github.com/anacrolix/torrent/metainfo"
pp "github.com/anacrolix/torrent/peer_protocol"
"github.com/anacrolix/torrent/storage"
"github.com/anacrolix/torrent/tracker"
)
func (t *Torrent) chunkIndexSpec(chunkIndex pp.Integer, piece pieceIndex) chunkSpec {
return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
}
// Maintains state of torrent within a Client.
type Torrent struct {
// Torrent-level aggregate statistics. First in struct to ensure 64-bit
// alignment. See #262.
stats ConnStats
cl *Client
logger log.Logger
networkingEnabled bool
// Determines what chunks to request from peers. 1: Favour higher priority
// pieces with some fuzzing to reduce overlaps and wastage across
// connections. 2: The fastest connection downloads strictly in order of
// priority, while all others adher to their piece inclications. 3:
// Requests are strictly by piece priority, and not duplicated until
// duplicateRequestTimeout is reached.
requestStrategy int
// How long to avoid duplicating a pending request.
duplicateRequestTimeout time.Duration
closed missinggo.Event
infoHash metainfo.Hash
pieces []Piece
// Values are the piece indices that changed.
pieceStateChanges *pubsub.PubSub
// The size of chunks to request from peers over the wire. This is
// normally 16KiB by convention these days.
chunkSize pp.Integer
chunkPool *sync.Pool
// Total length of the torrent in bytes. Stored because it's not O(1) to
// get this from the info dict.
length *int64
// The storage to open when the info dict becomes available.
storageOpener *storage.Client
// Storage for torrent data.
storage *storage.Torrent
// Read-locked for using storage, and write-locked for Closing.
storageLock sync.RWMutex
// TODO: Only announce stuff is used?
metainfo metainfo.MetaInfo
// The info dict. nil if we don't have it (yet).
info *metainfo.Info
files *[]*File
// Active peer connections, running message stream loops. TODO: Make this
// open (not-closed) connections only.
conns map[*connection]struct{}
maxEstablishedConns int
// Set of addrs to which we're attempting to connect. Connections are
// half-open until all handshakes are completed.
halfOpen map[string]Peer
fastestConn *connection
// Reserve of peers to connect to. A peer can be both here and in the
// active connections if were told about the peer after connecting with
// them. That encourages us to reconnect to peers that are well known in
// the swarm.
peers prioritizedPeers
wantPeersEvent missinggo.Event
// An announcer for each tracker URL.
trackerAnnouncers map[string]*trackerScraper
// How many times we've initiated a DHT announce. TODO: Move into stats.
numDHTAnnounces int
// Name used if the info name isn't available. Should be cleared when the
// Info does become available.
nameMu sync.RWMutex
displayName string
// The bencoded bytes of the info dict. This is actively manipulated if
// the info bytes aren't initially available, and we try to fetch them
// from peers.
metadataBytes []byte
// Each element corresponds to the 16KiB metadata pieces. If true, we have
// received that piece.
metadataCompletedChunks []bool
metadataChanged sync.Cond
// Set when .Info is obtained.
gotMetainfo missinggo.Event
readers map[*reader]struct{}
readerNowPieces bitmap.Bitmap
readerReadaheadPieces bitmap.Bitmap
// A cache of pieces we need to get. Calculated from various piece and
// file priorities and completion states elsewhere.
pendingPieces prioritybitmap.PriorityBitmap
// A cache of completed piece indices.
completedPieces bitmap.Bitmap
// Pieces that need to be hashed.
piecesQueuedForHash bitmap.Bitmap
activePieceHashes int
// A pool of piece priorities []int for assignment to new connections.
// These "inclinations" are used to give connections preference for
// different pieces.
connPieceInclinationPool sync.Pool
// Count of each request across active connections.
pendingRequests map[request]int
// The last time we requested a chunk. Deleting the request from any
// connection will clear this value.
lastRequested map[request]*time.Timer
}
func (t *Torrent) tickleReaders() {
t.cl.event.Broadcast()
}
// Returns a channel that is closed when the Torrent is closed.
func (t *Torrent) Closed() <-chan struct{} {
return t.closed.LockedChan(t.cl.locker())
}
// KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
// pending, and half-open peers.
func (t *Torrent) KnownSwarm() (ks []Peer) {
// Add pending peers to the list
t.peers.Each(func(peer Peer) {
ks = append(ks, peer)
})
// Add half-open peers to the list
for _, peer := range t.halfOpen {
ks = append(ks, peer)
}
// Add active peers to the list
for conn := range t.conns {
ks = append(ks, Peer{
Id: conn.PeerID,
IP: conn.remoteAddr.IP,
Port: int(conn.remoteAddr.Port),
Source: conn.Discovery,
// > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
// > But if we're not connected to them with an encrypted connection, I couldn't say
// > what's appropriate. We can carry forward the SupportsEncryption value as we
// > received it from trackers/DHT/PEX, or just use the encryption state for the
// > connection. It's probably easiest to do the latter for now.
// https://github.com/anacrolix/torrent/pull/188
SupportsEncryption: conn.headerEncrypted,
})
}
return
}
func (t *Torrent) setChunkSize(size pp.Integer) {
t.chunkSize = size
t.chunkPool = &sync.Pool{
New: func() interface{} {
b := make([]byte, size)
return &b
},
}
}
func (t *Torrent) pieceComplete(piece pieceIndex) bool {
return t.completedPieces.Get(bitmap.BitIndex(piece))
}
func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
return t.pieces[piece].Storage().Completion()
}
// There's a connection to that address already.
func (t *Torrent) addrActive(addr string) bool {
/*if _, ok := t.halfOpen[addr]; ok {
return true
}
for c := range t.conns {
ra := c.remoteAddr
if ra.String() == addr {
return true
}
}*/
return false
}
func (t *Torrent) unclosedConnsAsSlice() (ret []*connection) {
ret = make([]*connection, 0, len(t.conns))
for c := range t.conns {
if !c.closed.IsSet() {
ret = append(ret, c)
}
}
return
}
func (t *Torrent) addPeer(p Peer) {
cl := t.cl
peersAddedBySource.Add(string(p.Source), 1)
if t.closed.IsSet() {
return
}
if !p.IsScion {
if cl.badPeerIPPort(p.IP, p.Port) {
torrent.Add("peers not added because of bad addr", 1)
return
}
}
if t.peers.Add(p) {
torrent.Add("peers replaced", 1)
}
t.openNewConns()
for t.peers.Len() > cl.config.TorrentPeersHighWater {
_, ok := t.peers.DeleteMin()
if ok {
torrent.Add("excess reserve peers discarded", 1)
}
}
}
func (t *Torrent) invalidateMetadata() {
for i := range t.metadataCompletedChunks {
t.metadataCompletedChunks[i] = false
}
t.nameMu.Lock()
t.info = nil
t.nameMu.Unlock()
}
func (t *Torrent) saveMetadataPiece(index int, data []byte) {
if t.haveInfo() {
return
}
if index >= len(t.metadataCompletedChunks) {
t.logger.Printf("%s: ignoring metadata piece %d", t, index)
return
}
copy(t.metadataBytes[(1<<14)*index:], data)
t.metadataCompletedChunks[index] = true
}
func (t *Torrent) metadataPieceCount() int {
return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
}
func (t *Torrent) haveMetadataPiece(piece int) bool {
if t.haveInfo() {
return (1<<14)*piece < len(t.metadataBytes)
} else {
return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
}
}
func (t *Torrent) metadataSize() int {
return len(t.metadataBytes)
}
func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
for i := 0; i < len(info.Pieces); i += sha1.Size {
ret = append(ret, info.Pieces[i:i+sha1.Size])
}
return
}
func (t *Torrent) makePieces() {
hashes := infoPieceHashes(t.info)
t.pieces = make([]Piece, len(hashes), len(hashes))
for i, hash := range hashes {
piece := &t.pieces[i]
piece.t = t
piece.index = pieceIndex(i)
piece.noPendingWrites.L = &piece.pendingWritesMutex
piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
files := *t.files
beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
piece.files = files[beginFile:endFile]
}
}
// Returns the index of the first file containing the piece. files must be
// ordered by offset.
func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
for i, f := range files {
if f.offset+f.length > pieceOffset {
return i
}
}
return 0
}
// Returns the index after the last file containing the piece. files must be
// ordered by offset.
func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
for i, f := range files {
if f.offset+f.length >= pieceEndOffset {
return i + 1
}
}
return 0
}
func (t *Torrent) cacheLength() {
var l int64
for _, f := range t.info.UpvertedFiles() {
l += f.Length
}
t.length = &l
}
func (t *Torrent) setInfo(info *metainfo.Info) error {
if err := validateInfo(info); err != nil {
return fmt.Errorf("bad info: %s", err)
}
if t.storageOpener != nil {
var err error
t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
if err != nil {
return fmt.Errorf("error opening torrent storage: %s", err)
}
}
t.nameMu.Lock()
t.info = info
t.nameMu.Unlock()
t.displayName = "" // Save a few bytes lol.
t.initFiles()
t.cacheLength()
t.makePieces()
return nil
}
func (t *Torrent) onSetInfo() {
for conn := range t.conns {
if err := conn.setNumPieces(t.numPieces()); err != nil {
t.logger.Printf("closing connection: %s", err)
conn.Close()
}
}
for i := range t.pieces {
t.updatePieceCompletion(pieceIndex(i))
p := &t.pieces[i]
if !p.storageCompletionOk {
// t.logger.Printf("piece %s completion unknown, queueing check", p)
t.queuePieceCheck(pieceIndex(i))
}
}
t.cl.event.Broadcast()
t.gotMetainfo.Set()
t.updateWantPeersEvent()
t.pendingRequests = make(map[request]int)
t.lastRequested = make(map[request]*time.Timer)
t.tryCreateMorePieceHashers()
}
// Called when metadata for a torrent becomes available.
func (t *Torrent) setInfoBytes(b []byte) error {
if metainfo.HashBytes(b) != t.infoHash {
return errors.New("info bytes have wrong hash")
}
var info metainfo.Info
if err := bencode.Unmarshal(b, &info); err != nil {
return fmt.Errorf("error unmarshalling info bytes: %s", err)
}
if err := t.setInfo(&info); err != nil {
return err
}
t.metadataBytes = b
t.metadataCompletedChunks = nil
t.onSetInfo()
return nil
}
func (t *Torrent) haveAllMetadataPieces() bool {
if t.haveInfo() {
return true
}
if t.metadataCompletedChunks == nil {
return false
}
for _, have := range t.metadataCompletedChunks {
if !have {
return false
}
}
return true
}
// TODO: Propagate errors to disconnect peer.
func (t *Torrent) setMetadataSize(bytes int) (err error) {
if t.haveInfo() {
// We already know the correct metadata size.
return
}
if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
return errors.New("bad size")
}
if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
return
}
t.metadataBytes = make([]byte, bytes)
t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
t.metadataChanged.Broadcast()
for c := range t.conns {
c.requestPendingMetadata()
}
return
}
// The current working name for the torrent. Either the name in the info dict,
// or a display name given such as by the dn value in a magnet link, or "".
func (t *Torrent) name() string {
t.nameMu.RLock()
defer t.nameMu.RUnlock()
if t.haveInfo() {
return t.info.Name
}
return t.displayName
}
func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
p := &t.pieces[index]
ret.Priority = t.piecePriority(index)
ret.Completion = p.completion()
if p.queuedForHash() || p.hashing {
ret.Checking = true
}
if !ret.Complete && t.piecePartiallyDownloaded(index) {
ret.Partial = true
}
return
}
func (t *Torrent) metadataPieceSize(piece int) int {
return metadataPieceSize(len(t.metadataBytes), piece)
}
func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
d := map[string]int{
"msg_type": msgType,
"piece": piece,
}
if data != nil {
d["total_size"] = len(t.metadataBytes)
}
p := bencode.MustMarshal(d)
return pp.Message{
Type: pp.Extended,
ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
ExtendedPayload: append(p, data...),
}
}
func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
ret = append(ret, PieceStateRun{
PieceState: el.(PieceState),
Length: int(count),
})
})
for index := range t.pieces {
rle.Append(t.pieceState(pieceIndex(index)), 1)
}
rle.Flush()
return
}
// Produces a small string representing a PieceStateRun.
func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
ret = fmt.Sprintf("%d", psr.Length)
ret += func() string {
switch psr.Priority {
case PiecePriorityNext:
return "N"
case PiecePriorityNormal:
return "."
case PiecePriorityReadahead:
return "R"
case PiecePriorityNow:
return "!"
case PiecePriorityHigh:
return "H"
default:
return ""
}
}()
if psr.Checking {
ret += "H"
}
if psr.Partial {
ret += "P"
}
if psr.Complete {
ret += "C"
}
if !psr.Ok {
ret += "?"
}
return
}
func (t *Torrent) writeStatus(w io.Writer) {
fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
if !t.haveInfo() {
fmt.Fprintf(w, "Metadata have: ")
for _, h := range t.metadataCompletedChunks {
fmt.Fprintf(w, "%c", func() rune {
if h {
return 'H'
} else {
return '.'
}
}())
}
fmt.Fprintln(w)
}
fmt.Fprintf(w, "Piece length: %s\n", func() string {
if t.haveInfo() {
return fmt.Sprint(t.usualPieceSize())
} else {
return "?"
}
}())
if t.info != nil {
fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
fmt.Fprint(w, "Piece States:")
for _, psr := range t.pieceStateRuns() {
w.Write([]byte(" "))
w.Write([]byte(pieceStateRunStatusChars(psr)))
}
fmt.Fprintln(w)
}
fmt.Fprintf(w, "Reader Pieces:")
t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
fmt.Fprintf(w, " %d:%d", begin, end)
return true
})
fmt.Fprintln(w)
fmt.Fprintf(w, "Enabled trackers:\n")
func() {
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
lu := l.u
ru := r.u
var luns, runs url.URL = lu, ru
luns.Scheme = ""
runs.Scheme = ""
var ml missinggo.MultiLess
ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
return ml.Less()
}).([]*trackerScraper) {
fmt.Fprintf(tw, " %s\n", ta.statusLine())
}
tw.Flush()
}()
fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
spew.NewDefaultConfig()
spew.Fdump(w, t.statsLocked())
conns := t.connsAsSlice()
slices.Sort(conns, worseConn)
for i, c := range conns {
fmt.Fprintf(w, "%2d. ", i+1)
c.WriteStatus(w, t)
}
}
func (t *Torrent) haveInfo() bool {
return t.info != nil
}
// Returns a run-time generated MetaInfo that includes the info bytes and
// announce-list as currently known to the client.
func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
return metainfo.MetaInfo{
CreationDate: time.Now().Unix(),
Comment: "dynamic metainfo from client",
CreatedBy: "go.torrent",
AnnounceList: t.metainfo.UpvertedAnnounceList(),
InfoBytes: func() []byte {
if t.haveInfo() {
return t.metadataBytes
} else {
return nil
}
}(),
}
}
func (t *Torrent) BytesMissing() int64 {
t.cl.rLock()
defer t.cl.rUnlock()
return t.bytesMissingLocked()
}
func (t *Torrent) bytesMissingLocked() int64 {
return t.bytesLeft()
}
func (t *Torrent) bytesLeft() (left int64) {
bitmap.Flip(t.completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
p := &t.pieces[piece]
left += int64(p.length() - p.numDirtyBytes())
return true
})
return
}
// Bytes left to give in tracker announces.
func (t *Torrent) bytesLeftAnnounce() int64 {
if t.haveInfo() {
return t.bytesLeft()
} else {
return -1
}
}
func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
if t.pieceComplete(piece) {
return false
}
if t.pieceAllDirty(piece) {
return false
}
return t.pieces[piece].hasDirtyChunks()
}
func (t *Torrent) usualPieceSize() int {
return int(t.info.PieceLength)
}
func (t *Torrent) numPieces() pieceIndex {
return pieceIndex(t.info.NumPieces())
}
func (t *Torrent) numPiecesCompleted() (num int) {
return t.completedPieces.Len()
}
func (t *Torrent) close() (err error) {
t.closed.Set()
t.tickleReaders()
if t.storage != nil {
t.storageLock.Lock()
t.storage.Close()
t.storageLock.Unlock()
}
for conn := range t.conns {
conn.Close()
}
t.cl.event.Broadcast()
t.pieceStateChanges.Close()
t.updateWantPeersEvent()
return
}
func (t *Torrent) requestOffset(r request) int64 {
return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
}
// Return the request that would include the given offset into the torrent
// data. Returns !ok if there is no such request.
func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
}
func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
defer perf.ScopeTimerErr(&err)()
n, err := t.pieces[piece].Storage().WriteAt(data, begin)
if err == nil && n != len(data) {
err = io.ErrShortWrite
}
return
}
func (t *Torrent) bitfield() (bf []bool) {
bf = make([]bool, t.numPieces())
t.completedPieces.IterTyped(func(piece int) (again bool) {
bf[piece] = true
return true
})
return
}
func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
}
func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
t.pieces[pieceIndex].dirtyChunks.Clear()
}
func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
if t.info.PieceLength == 0 {
// There will be no variance amongst pieces. Only pain.
return 0
}
if piece == t.numPieces()-1 {
ret := pp.Integer(*t.length % t.info.PieceLength)
if ret != 0 {
return ret
}
}
return pp.Integer(t.info.PieceLength)
}
func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash) {
hash := pieceHash.New()
p := t.piece(piece)
p.waitNoPendingWrites()
ip := t.info.Piece(int(piece))
pl := ip.Length()
n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
if n == pl {
missinggo.CopyExact(&ret, hash.Sum(nil))
return
}
if err != io.ErrUnexpectedEOF && !os.IsNotExist(err) {
t.logger.Printf("unexpected error hashing piece %d through %T: %s", piece, t.storage.TorrentImpl, err)
}
return
}
func (t *Torrent) haveAnyPieces() bool {
return t.completedPieces.Len() != 0
}
func (t *Torrent) haveAllPieces() bool {
if !t.haveInfo() {
return false
}
return t.completedPieces.Len() == bitmap.BitIndex(t.numPieces())
}
func (t *Torrent) havePiece(index pieceIndex) bool {
return t.haveInfo() && t.pieceComplete(index)
}
func (t *Torrent) haveChunk(r request) (ret bool) {
// defer func() {
// log.Println("have chunk", r, ret)
// }()
if !t.haveInfo() {
return false
}
if t.pieceComplete(pieceIndex(r.Index)) {
return true
}
p := &t.pieces[r.Index]
return !p.pendingChunk(r.chunkSpec, t.chunkSize)
}
func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
return int(cs.Begin / chunkSize)
}
func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
if !t.haveInfo() {
return false
}
if index < 0 || index >= t.numPieces() {
return false
}
p := &t.pieces[index]
if p.queuedForHash() {
return false
}
if p.hashing {
return false
}
if t.pieceComplete(index) {
return false
}
if t.pendingPieces.Contains(bitmap.BitIndex(index)) {
return true
}
// t.logger.Printf("piece %d not pending", index)
return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
return index < begin || index >= end
})
}
// The worst connection is one that hasn't been sent, or sent anything useful
// for the longest. A bad connection is one that usually sends us unwanted
// pieces, or has been in worser half of the established connections for more
// than a minute.
func (t *Torrent) worstBadConn() *connection {
wcs := worseConnSlice{t.unclosedConnsAsSlice()}
heap.Init(&wcs)
for wcs.Len() != 0 {
c := heap.Pop(&wcs).(*connection)
if c.stats.ChunksReadWasted.Int64() >= 6 && c.stats.ChunksReadWasted.Int64() > c.stats.ChunksReadUseful.Int64() {
return c
}
// If the connection is in the worst half of the established
// connection quota and is older than a minute.
if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
// Give connections 1 minute to prove themselves.
if time.Since(*c.completedHandshake) > time.Minute {
return c
}
}
}
return nil
}
type PieceStateChange struct {
Index int
PieceState
}
func (t *Torrent) publishPieceChange(piece pieceIndex) {
cur := t.pieceState(piece)
p := &t.pieces[piece]
if cur != p.publicPieceState {
p.publicPieceState = cur
t.pieceStateChanges.Publish(PieceStateChange{
int(piece),
cur,
})
}
}
func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
if t.pieceComplete(piece) {
return 0
}
return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
}
func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
return t.pieces[piece].dirtyChunks.Len() == int(t.pieceNumChunks(piece))
}
func (t *Torrent) readersChanged() {
t.updateReaderPieces()
t.updateAllPiecePriorities()
}
func (t *Torrent) updateReaderPieces() {
t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
}
func (t *Torrent) readerPosChanged(from, to pieceRange) {
if from == to {
return
}
t.updateReaderPieces()
// Order the ranges, high and low.
l, h := from, to
if l.begin > h.begin {
l, h = h, l
}
if l.end < h.begin {
// Two distinct ranges.
t.updatePiecePriorities(l.begin, l.end)
t.updatePiecePriorities(h.begin, h.end)
} else {
// Ranges overlap.
end := l.end
if h.end > end {
end = h.end
}
t.updatePiecePriorities(l.begin, end)
}
}
func (t *Torrent) maybeNewConns() {
// Tickle the accept routine.
t.cl.event.Broadcast()
t.openNewConns()
}
func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
// t.logger.Printf("piece %d priority changed", piece)
for c := range t.conns {
if c.updatePiecePriority(piece) {
// log.Print("conn piece priority changed")
c.updateRequests()
}
}
t.maybeNewConns()
t.publishPieceChange(piece)
}
func (t *Torrent) updatePiecePriority(piece pieceIndex) {
p := &t.pieces[piece]
newPrio := p.uncachedPriority()
// t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
if newPrio == PiecePriorityNone {
if !t.pendingPieces.Remove(bitmap.BitIndex(piece)) {
return
}
} else {
if !t.pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
return
}
}
t.piecePriorityChanged(piece)
}
func (t *Torrent) updateAllPiecePriorities() {
t.updatePiecePriorities(0, t.numPieces())
}
// Update all piece priorities in one hit. This function should have the same
// output as updatePiecePriority, but across all pieces.
func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
for i := begin; i < end; i++ {
t.updatePiecePriority(i)
}
}
// Returns the range of pieces [begin, end) that contains the extent of bytes.
func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
if off >= *t.length {
return
}
if off < 0 {
size += off
off = 0
}
if size <= 0 {
return
}
begin = pieceIndex(off / t.info.PieceLength)
end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
if end > pieceIndex(t.info.NumPieces()) {
end = pieceIndex(t.info.NumPieces())
}
return
}
// Returns true if all iterations complete without breaking. Returns the read
// regions for all readers. The reader regions should not be merged as some
// callers depend on this method to enumerate readers.
func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
for r := range t.readers {
p := r.pieces
if p.begin >= p.end {
continue
}
if !f(p.begin, p.end) {
return false
}
}
return true
}
func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
prio, ok := t.pendingPieces.GetPriority(bitmap.BitIndex(piece))
if !ok {
return PiecePriorityNone
}
if prio > 0 {
panic(prio)