-
-
Notifications
You must be signed in to change notification settings - Fork 629
/
torrent.go
2899 lines (2646 loc) · 74.8 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 (
"bytes"
"container/heap"
"context"
"crypto/sha1"
"errors"
"fmt"
"io"
"math/rand"
"net/netip"
"net/url"
"sort"
"strings"
"text/tabwriter"
"time"
"unsafe"
"github.com/RoaringBitmap/roaring"
"github.com/anacrolix/chansync"
"github.com/anacrolix/chansync/events"
"github.com/anacrolix/dht/v2"
. "github.com/anacrolix/generics"
g "github.com/anacrolix/generics"
"github.com/anacrolix/log"
"github.com/anacrolix/missinggo/perf"
"github.com/anacrolix/missinggo/slices"
"github.com/anacrolix/missinggo/v2"
"github.com/anacrolix/missinggo/v2/bitmap"
"github.com/anacrolix/missinggo/v2/pubsub"
"github.com/anacrolix/multiless"
"github.com/anacrolix/sync"
"github.com/pion/datachannel"
"golang.org/x/exp/maps"
"github.com/anacrolix/torrent/bencode"
"github.com/anacrolix/torrent/common"
"github.com/anacrolix/torrent/internal/check"
"github.com/anacrolix/torrent/internal/nestedmaps"
"github.com/anacrolix/torrent/metainfo"
pp "github.com/anacrolix/torrent/peer_protocol"
utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
request_strategy "github.com/anacrolix/torrent/request-strategy"
"github.com/anacrolix/torrent/segments"
"github.com/anacrolix/torrent/storage"
"github.com/anacrolix/torrent/tracker"
typedRoaring "github.com/anacrolix/torrent/typed-roaring"
"github.com/anacrolix/torrent/webseed"
"github.com/anacrolix/torrent/webtorrent"
)
// Maintains state of torrent within a Client. Many methods should not be called before the info is
// available, see .Info and .GotInfo.
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 chansync.Flag
dataDownloadDisallowed chansync.Flag
dataUploadDisallowed bool
userOnWriteChunkErr func(error)
closed chansync.SetOnce
onClose []func()
infoHash metainfo.Hash
pieces []Piece
// The order pieces are requested if there's no stronger reason like availability or priority.
pieceRequestOrder []int
// Values are the piece indices that changed.
pieceStateChanges pubsub.PubSub[PieceStateChange]
// 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 Option[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
fileIndex segments.Index
files *[]*File
_chunksPerRegularPiece chunkIndexType
webSeeds map[string]*Peer
// Active peer connections, running message stream loops. TODO: Make this
// open (not-closed) connections only.
conns map[*PeerConn]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]map[outgoingConnAttemptKey]*PeerInfo
// 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
// Whether we want to know more peers.
wantPeersEvent missinggo.Event
// An announcer for each tracker URL.
trackerAnnouncers map[string]torrentTrackerAnnouncer
// 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
// Closed when .Info is obtained.
gotMetainfoC chan struct{}
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 roaring.Bitmap
// A cache of completed piece indices.
_completedPieces roaring.Bitmap
// Pieces that need to be hashed.
piecesQueuedForHash bitmap.Bitmap
activePieceHashes int
initialPieceCheckDisabled bool
connsWithAllPieces map[*Peer]struct{}
requestState map[RequestIndex]requestState
// Chunks we've written to since the corresponding piece was last checked.
dirtyChunks typedRoaring.Bitmap[RequestIndex]
pex pexState
// Is On when all pieces are complete.
Complete chansync.Flag
// Torrent sources in use keyed by the source string.
activeSources sync.Map
sourcesLogger log.Logger
smartBanCache smartBanCache
// Large allocations reused between request state updates.
requestPieceStates []request_strategy.PieceRequestOrderState
requestIndexes []RequestIndex
}
type outgoingConnAttemptKey = *PeerInfo
func (t *Torrent) length() int64 {
return t._length.Value
}
func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
// This could be done with roaring.BitSliceIndexing.
t.iterPeers(func(peer *Peer) {
if _, ok := t.connsWithAllPieces[peer]; ok {
return
}
if peer.peerHasPiece(i) {
count++
}
})
return
}
func (t *Torrent) decPieceAvailability(i pieceIndex) {
if !t.haveInfo() {
return
}
p := t.piece(i)
if p.relativeAvailability <= 0 {
panic(p.relativeAvailability)
}
p.relativeAvailability--
t.updatePieceRequestOrder(i)
}
func (t *Torrent) incPieceAvailability(i pieceIndex) {
// If we don't the info, this should be reconciled when we do.
if t.haveInfo() {
p := t.piece(i)
p.relativeAvailability++
t.updatePieceRequestOrder(i)
}
}
func (t *Torrent) readerNowPieces() bitmap.Bitmap {
return t._readerNowPieces
}
func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
return t._readerReadaheadPieces
}
func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
return !t.wantPieceIndex(i)
}
// Returns a channel that is closed when the Torrent is closed.
func (t *Torrent) Closed() events.Done {
return t.closed.Done()
}
// 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 []PeerInfo) {
// Add pending peers to the list
t.peers.Each(func(peer PeerInfo) {
ks = append(ks, peer)
})
// Add half-open peers to the list
for _, attempts := range t.halfOpen {
for _, peer := range attempts {
ks = append(ks, *peer)
}
}
// Add active peers to the list
for conn := range t.conns {
ks = append(ks, PeerInfo{
Id: conn.PeerID,
Addr: conn.RemoteAddr,
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.Contains(bitmap.BitIndex(piece))
}
func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
if t.storage == nil {
return storage.Completion{Complete: false, Ok: true}
}
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) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
return t.appendConns(ret, func(conn *PeerConn) bool {
return !conn.closed.IsSet()
})
}
func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
for c := range t.conns {
if f(c) {
ret = append(ret, c)
}
}
return ret
}
func (t *Torrent) addPeer(p PeerInfo) (added bool) {
cl := t.cl
torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
if t.closed.IsSet() {
return false
}
if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
torrent.Add("peers not added because of bad addr", 1)
// cl.logger.Printf("peers not added because of bad addr: %v", p)
return false
}
}
if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
torrent.Add("peers replaced", 1)
if !replaced.equal(p) {
t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
added = true
}
} else {
added = true
}
t.openNewConns()
for t.peers.Len() > cl.config.TorrentPeersHighWater {
_, ok := t.peers.DeleteMin()
if ok {
torrent.Add("excess reserve peers discarded", 1)
}
}
return
}
func (t *Torrent) invalidateMetadata() {
for i := 0; i < len(t.metadataCompletedChunks); i++ {
t.metadataCompletedChunks[i] = false
}
t.nameMu.Lock()
t.gotMetainfoC = make(chan struct{})
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))
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 = Some(l)
}
// TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
// separately.
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._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
t.updateComplete()
t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
t.displayName = "" // Save a few bytes lol.
t.initFiles()
t.cacheLength()
t.makePieces()
return nil
}
func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
return request_strategy.PieceRequestOrderKey{
InfoHash: t.infoHash,
Index: i,
}
}
// This seems to be all the follow-up tasks after info is set, that can't fail.
func (t *Torrent) onSetInfo() {
t.pieceRequestOrder = rand.Perm(t.numPieces())
t.initPieceRequestOrder()
MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
for i := range t.pieces {
p := &t.pieces[i]
// Need to add relativeAvailability before updating piece completion, as that may result in conns
// being dropped.
if p.relativeAvailability != 0 {
panic(p.relativeAvailability)
}
p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
t.addRequestOrderPiece(i)
t.updatePieceCompletion(i)
if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
// t.logger.Printf("piece %s completion unknown, queueing check", p)
t.queuePieceCheck(i)
}
}
t.cl.event.Broadcast()
close(t.gotMetainfoC)
t.updateWantPeersEvent()
t.requestState = make(map[RequestIndex]requestState)
t.tryCreateMorePieceHashers()
t.iterPeers(func(p *Peer) {
p.onGotInfo(t.info)
p.updateRequests("onSetInfo")
})
}
// Called when metadata for a torrent becomes available.
func (t *Torrent) setInfoBytesLocked(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)
}
t.metadataBytes = b
t.metadataCompletedChunks = nil
if t.info != nil {
return nil
}
if err := t.setInfo(&info); err != nil {
return err
}
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(size int) (err error) {
if t.haveInfo() {
// We already know the correct metadata size.
return
}
if uint32(size) > maxMetadataSize {
return log.WithLevel(log.Warning, errors.New("bad size"))
}
if len(t.metadataBytes) == size {
return
}
t.metadataBytes = make([]byte, size)
t.metadataCompletedChunks = make([]bool, (size+(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.BestName()
}
if t.displayName != "" {
return t.displayName
}
return "infohash:" + t.infoHash.HexString()
}
func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
p := &t.pieces[index]
ret.Priority = t.piecePriority(index)
ret.Completion = p.completion()
ret.QueuedForHash = p.queuedForHash()
ret.Hashing = p.hashing
ret.Checking = ret.QueuedForHash || ret.Hashing
ret.Marking = p.marking
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 *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
return pp.Message{
Type: pp.Extended,
ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
Piece: piece,
TotalSize: len(t.metadataBytes),
Type: msgType,
}), data...),
}
}
type pieceAvailabilityRun struct {
Count pieceIndex
Availability int
}
func (me pieceAvailabilityRun) String() string {
return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
}
func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
})
for i := range t.pieces {
rle.Append(t.pieces[i].availability(), 1)
}
rle.Flush()
return
}
func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
freqs = make([]int, t.numActivePeers()+1)
for i := range t.pieces {
freqs[t.piece(i).availability()]++
}
return
}
func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
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 (psr PieceStateRun) String() (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.Hashing {
ret += "H"
}
if psr.QueuedForHash {
ret += "Q"
}
if psr.Marking {
ret += "M"
}
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.Sprintf("%v (%v chunks)",
t.usualPieceSize(),
float64(t.usualPieceSize())/float64(t.chunkSize))
} else {
return "no info"
}
}(),
)
if t.info != nil {
fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
// Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
// availability frequencies instead.
if false {
fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
for _, run := range t.pieceAvailabilityRuns() {
ret = append(ret, run.String())
}
return
}(), " "))
}
fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
func() (ret []string) {
for avail, freq := range t.pieceAvailabilityFrequencies() {
if freq == 0 {
continue
}
ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
}
return
}(),
", "))
}
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\tExtra\n")
for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
lu := l.URL()
ru := r.URL()
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()
}).([]torrentTrackerAnnouncer) {
fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
}
tw.Flush()
}()
fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
dumpStats(w, t.statsLocked())
fmt.Fprintf(w, "webseeds:\n")
t.writePeerStatuses(w, maps.Values(t.webSeeds))
peerConns := maps.Keys(t.conns)
// Peers without priorities first, then those with. I'm undecided about how to order peers
// without priorities.
sort.Slice(peerConns, func(li, ri int) bool {
l := peerConns[li]
r := peerConns[ri]
ml := multiless.New()
lpp := g.ResultFromTuple(l.peerPriority()).ToOption()
rpp := g.ResultFromTuple(r.peerPriority()).ToOption()
ml = ml.Bool(lpp.Ok, rpp.Ok)
ml = ml.Uint32(rpp.Value, lpp.Value)
return ml.Less()
})
fmt.Fprintf(w, "%v peer conns:\n", len(peerConns))
t.writePeerStatuses(w, g.SliceMap(peerConns, func(pc *PeerConn) *Peer {
return &pc.Peer
}))
}
func (t *Torrent) writePeerStatuses(w io.Writer, peers []*Peer) {
var buf bytes.Buffer
for _, c := range peers {
fmt.Fprintf(w, "- ")
buf.Reset()
c.writeStatus(&buf)
w.Write(bytes.TrimRight(
bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
" "))
}
}
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().Clone(),
InfoBytes: func() []byte {
if t.haveInfo() {
return t.metadataBytes
} else {
return nil
}
}(),
UrlList: func() []string {
ret := make([]string, 0, len(t.webSeeds))
for url := range t.webSeeds {
ret = append(ret, url)
}
return ret
}(),
}
}
// Returns a count of bytes that are not complete in storage, and not pending being written to
// storage. This value is from the perspective of the download manager, and may not agree with the
// actual state in storage. If you want read data synchronously you should use a Reader. See
// https://github.com/anacrolix/torrent/issues/828.
func (t *Torrent) BytesMissing() (n int64) {
t.cl.rLock()
n = t.bytesMissingLocked()
t.cl.rUnlock()
return
}
func (t *Torrent) bytesMissingLocked() int64 {
return t.bytesLeft()
}
func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
roaring.Flip(b, 0, end).Iterate(cb)
}
func (t *Torrent) bytesLeft() (left int64) {
iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
p := t.piece(pieceIndex(x))
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 t.info.NumPieces()
}
func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
return pieceIndex(t._completedPieces.GetCardinality())
}
func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
if !t.closed.Set() {
err = errors.New("already closed")
return
}
for _, f := range t.onClose {
f()
}
if t.storage != nil {
wg.Add(1)
go func() {
defer wg.Done()
t.storageLock.Lock()
defer t.storageLock.Unlock()
if f := t.storage.Close; f != nil {
err1 := f()
if err1 != nil {
t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
}
}
}()
}
t.iterPeers(func(p *Peer) {
p.close()
})
if t.storage != nil {
t.deletePieceRequestOrder()
}
t.assertAllPiecesRelativeAvailabilityZero()
t.pex.Reset()
t.cl.event.Broadcast()
t.pieceStateChanges.Close()
t.updateWantPeersEvent()
return
}
func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
for i := range t.pieces {
p := t.piece(i)
if p.relativeAvailability != 0 {
panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
}
}
}
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 err
}
func (t *Torrent) bitfield() (bf []bool) {
bf = make([]bool, t.numPieces())
t._completedPieces.Iterate(func(piece uint32) (again bool) {
bf[piece] = true
return true
})
return
}
func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
}
func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
return t._chunksPerRegularPiece
}
func (t *Torrent) numChunks() RequestIndex {
if t.numPieces() == 0 {
return 0
}
return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
}
func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
t.dirtyChunks.RemoveRange(
uint64(t.pieceRequestIndexOffset(pieceIndex)),
uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
}
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) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {