19 "github.com/RoaringBitmap/roaring"
20 "github.com/anacrolix/chansync"
21 "github.com/anacrolix/chansync/events"
22 "github.com/anacrolix/dht/v2"
23 "github.com/anacrolix/log"
24 "github.com/anacrolix/missinggo/perf"
25 "github.com/anacrolix/missinggo/pubsub"
26 "github.com/anacrolix/missinggo/slices"
27 "github.com/anacrolix/missinggo/v2"
28 "github.com/anacrolix/missinggo/v2/bitmap"
29 "github.com/anacrolix/multiless"
30 "github.com/anacrolix/sync"
31 "github.com/davecgh/go-spew/spew"
32 "github.com/google/go-cmp/cmp"
33 "github.com/pion/datachannel"
35 "github.com/anacrolix/torrent/bencode"
36 "github.com/anacrolix/torrent/common"
37 "github.com/anacrolix/torrent/metainfo"
38 pp "github.com/anacrolix/torrent/peer_protocol"
39 "github.com/anacrolix/torrent/segments"
40 "github.com/anacrolix/torrent/storage"
41 "github.com/anacrolix/torrent/tracker"
42 "github.com/anacrolix/torrent/webseed"
43 "github.com/anacrolix/torrent/webtorrent"
46 // Maintains state of torrent within a Client. Many methods should not be called before the info is
47 // available, see .Info and .GotInfo.
49 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
50 // alignment. See #262.
55 networkingEnabled chansync.Flag
56 dataDownloadDisallowed chansync.Flag
57 dataUploadDisallowed bool
58 userOnWriteChunkErr func(error)
60 closed chansync.SetOnce
61 infoHash metainfo.Hash
63 // Values are the piece indices that changed.
64 pieceStateChanges *pubsub.PubSub
65 // The size of chunks to request from peers over the wire. This is
66 // normally 16KiB by convention these days.
69 // Total length of the torrent in bytes. Stored because it's not O(1) to
70 // get this from the info dict.
73 // The storage to open when the info dict becomes available.
74 storageOpener *storage.Client
75 // Storage for torrent data.
76 storage *storage.Torrent
77 // Read-locked for using storage, and write-locked for Closing.
78 storageLock sync.RWMutex
80 // TODO: Only announce stuff is used?
81 metainfo metainfo.MetaInfo
83 // The info dict. nil if we don't have it (yet).
85 fileIndex segments.Index
88 webSeeds map[string]*Peer
90 // Active peer connections, running message stream loops. TODO: Make this
91 // open (not-closed) connections only.
92 conns map[*PeerConn]struct{}
93 maxEstablishedConns int
94 // Set of addrs to which we're attempting to connect. Connections are
95 // half-open until all handshakes are completed.
96 halfOpen map[string]PeerInfo
98 // Reserve of peers to connect to. A peer can be both here and in the
99 // active connections if were told about the peer after connecting with
100 // them. That encourages us to reconnect to peers that are well known in
102 peers prioritizedPeers
103 // Whether we want to know to know more peers.
104 wantPeersEvent missinggo.Event
105 // An announcer for each tracker URL.
106 trackerAnnouncers map[string]torrentTrackerAnnouncer
107 // How many times we've initiated a DHT announce. TODO: Move into stats.
110 // Name used if the info name isn't available. Should be cleared when the
111 // Info does become available.
115 // The bencoded bytes of the info dict. This is actively manipulated if
116 // the info bytes aren't initially available, and we try to fetch them
119 // Each element corresponds to the 16KiB metadata pieces. If true, we have
120 // received that piece.
121 metadataCompletedChunks []bool
122 metadataChanged sync.Cond
124 // Closed when .Info is obtained.
125 gotMetainfoC chan struct{}
127 readers map[*reader]struct{}
128 _readerNowPieces bitmap.Bitmap
129 _readerReadaheadPieces bitmap.Bitmap
131 // A cache of pieces we need to get. Calculated from various piece and
132 // file priorities and completion states elsewhere.
133 _pendingPieces roaring.Bitmap
134 // A cache of completed piece indices.
135 _completedPieces roaring.Bitmap
136 // Pieces that need to be hashed.
137 piecesQueuedForHash bitmap.Bitmap
138 activePieceHashes int
139 initialPieceCheckDisabled bool
141 // Count of each request across active connections.
142 pendingRequests pendingRequests
143 // Chunks we've written to since the corresponding piece was last checked.
144 dirtyChunks roaring.Bitmap
148 // Is On when all pieces are complete.
149 Complete chansync.Flag
152 func (t *Torrent) pieceAvailabilityFromPeers(i pieceIndex) (count int) {
153 t.iterPeers(func(peer *Peer) {
154 if peer.peerHasPiece(i) {
161 func (t *Torrent) decPieceAvailability(i pieceIndex) {
166 if p.availability <= 0 {
167 panic(p.availability)
172 func (t *Torrent) incPieceAvailability(i pieceIndex) {
173 // If we don't the info, this should be reconciled when we do.
180 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
181 return t._readerNowPieces
184 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
185 return t._readerReadaheadPieces
188 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
189 return !t.wantPieceIndex(i)
192 // Returns a channel that is closed when the Torrent is closed.
193 func (t *Torrent) Closed() events.Done {
194 return t.closed.Done()
197 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
198 // pending, and half-open peers.
199 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
200 // Add pending peers to the list
201 t.peers.Each(func(peer PeerInfo) {
202 ks = append(ks, peer)
205 // Add half-open peers to the list
206 for _, peer := range t.halfOpen {
207 ks = append(ks, peer)
210 // Add active peers to the list
211 for conn := range t.conns {
212 ks = append(ks, PeerInfo{
214 Addr: conn.RemoteAddr,
215 Source: conn.Discovery,
216 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
217 // > But if we're not connected to them with an encrypted connection, I couldn't say
218 // > what's appropriate. We can carry forward the SupportsEncryption value as we
219 // > received it from trackers/DHT/PEX, or just use the encryption state for the
220 // > connection. It's probably easiest to do the latter for now.
221 // https://github.com/anacrolix/torrent/pull/188
222 SupportsEncryption: conn.headerEncrypted,
229 func (t *Torrent) setChunkSize(size pp.Integer) {
231 t.chunkPool = sync.Pool{
232 New: func() interface{} {
233 b := make([]byte, size)
239 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
240 return t._completedPieces.Contains(bitmap.BitIndex(piece))
243 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
244 return t.pieces[piece].Storage().Completion()
247 // There's a connection to that address already.
248 func (t *Torrent) addrActive(addr string) bool {
249 if _, ok := t.halfOpen[addr]; ok {
252 for c := range t.conns {
254 if ra.String() == addr {
261 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
262 for c := range t.conns {
263 if !c.closed.IsSet() {
270 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
272 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
273 if t.closed.IsSet() {
276 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
277 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
278 torrent.Add("peers not added because of bad addr", 1)
279 // cl.logger.Printf("peers not added because of bad addr: %v", p)
283 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
284 torrent.Add("peers replaced", 1)
285 if !replaced.equal(p) {
286 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
293 for t.peers.Len() > cl.config.TorrentPeersHighWater {
294 _, ok := t.peers.DeleteMin()
296 torrent.Add("excess reserve peers discarded", 1)
302 func (t *Torrent) invalidateMetadata() {
303 for i := 0; i < len(t.metadataCompletedChunks); i++ {
304 t.metadataCompletedChunks[i] = false
307 t.gotMetainfoC = make(chan struct{})
312 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
316 if index >= len(t.metadataCompletedChunks) {
317 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
320 copy(t.metadataBytes[(1<<14)*index:], data)
321 t.metadataCompletedChunks[index] = true
324 func (t *Torrent) metadataPieceCount() int {
325 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
328 func (t *Torrent) haveMetadataPiece(piece int) bool {
330 return (1<<14)*piece < len(t.metadataBytes)
332 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
336 func (t *Torrent) metadataSize() int {
337 return len(t.metadataBytes)
340 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
341 for i := 0; i < len(info.Pieces); i += sha1.Size {
342 ret = append(ret, info.Pieces[i:i+sha1.Size])
347 func (t *Torrent) makePieces() {
348 hashes := infoPieceHashes(t.info)
349 t.pieces = make([]Piece, len(hashes))
350 for i, hash := range hashes {
351 piece := &t.pieces[i]
353 piece.index = pieceIndex(i)
354 piece.noPendingWrites.L = &piece.pendingWritesMutex
355 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
357 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
358 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
359 piece.files = files[beginFile:endFile]
360 piece.undirtiedChunksIter = undirtiedChunksIter{
361 TorrentDirtyChunks: &t.dirtyChunks,
362 StartRequestIndex: piece.requestIndexOffset(),
363 EndRequestIndex: piece.requestIndexOffset() + piece.numChunks(),
368 // Returns the index of the first file containing the piece. files must be
369 // ordered by offset.
370 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
371 for i, f := range files {
372 if f.offset+f.length > pieceOffset {
379 // Returns the index after the last file containing the piece. files must be
380 // ordered by offset.
381 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
382 for i, f := range files {
383 if f.offset+f.length >= pieceEndOffset {
390 func (t *Torrent) cacheLength() {
392 for _, f := range t.info.UpvertedFiles() {
398 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
400 func (t *Torrent) setInfo(info *metainfo.Info) error {
401 if err := validateInfo(info); err != nil {
402 return fmt.Errorf("bad info: %s", err)
404 if t.storageOpener != nil {
406 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
408 return fmt.Errorf("error opening torrent storage: %s", err)
415 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
416 t.displayName = "" // Save a few bytes lol.
423 // This seems to be all the follow-up tasks after info is set, that can't fail.
424 func (t *Torrent) onSetInfo() {
425 for i := range t.pieces {
427 // Need to add availability before updating piece completion, as that may result in conns
429 if p.availability != 0 {
430 panic(p.availability)
432 p.availability = int64(t.pieceAvailabilityFromPeers(i))
433 t.updatePieceCompletion(pieceIndex(i))
434 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
435 // t.logger.Printf("piece %s completion unknown, queueing check", p)
436 t.queuePieceCheck(pieceIndex(i))
439 t.cl.event.Broadcast()
440 close(t.gotMetainfoC)
441 t.updateWantPeersEvent()
442 t.pendingRequests.Init(t.numRequests())
443 t.tryCreateMorePieceHashers()
444 t.iterPeers(func(p *Peer) {
446 p.updateRequests("onSetInfo")
450 // Called when metadata for a torrent becomes available.
451 func (t *Torrent) setInfoBytesLocked(b []byte) error {
452 if metainfo.HashBytes(b) != t.infoHash {
453 return errors.New("info bytes have wrong hash")
455 var info metainfo.Info
456 if err := bencode.Unmarshal(b, &info); err != nil {
457 return fmt.Errorf("error unmarshalling info bytes: %s", err)
460 t.metadataCompletedChunks = nil
464 if err := t.setInfo(&info); err != nil {
471 func (t *Torrent) haveAllMetadataPieces() bool {
475 if t.metadataCompletedChunks == nil {
478 for _, have := range t.metadataCompletedChunks {
486 // TODO: Propagate errors to disconnect peer.
487 func (t *Torrent) setMetadataSize(size int) (err error) {
489 // We already know the correct metadata size.
492 if uint32(size) > maxMetadataSize {
493 return errors.New("bad size")
495 if len(t.metadataBytes) == size {
498 t.metadataBytes = make([]byte, size)
499 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
500 t.metadataChanged.Broadcast()
501 for c := range t.conns {
502 c.requestPendingMetadata()
507 // The current working name for the torrent. Either the name in the info dict,
508 // or a display name given such as by the dn value in a magnet link, or "".
509 func (t *Torrent) name() string {
511 defer t.nameMu.RUnlock()
515 if t.displayName != "" {
518 return "infohash:" + t.infoHash.HexString()
521 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
522 p := &t.pieces[index]
523 ret.Priority = t.piecePriority(index)
524 ret.Completion = p.completion()
525 ret.QueuedForHash = p.queuedForHash()
526 ret.Hashing = p.hashing
527 ret.Checking = ret.QueuedForHash || ret.Hashing
528 ret.Marking = p.marking
529 if !ret.Complete && t.piecePartiallyDownloaded(index) {
535 func (t *Torrent) metadataPieceSize(piece int) int {
536 return metadataPieceSize(len(t.metadataBytes), piece)
539 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
542 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
543 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
545 TotalSize: len(t.metadataBytes),
551 type pieceAvailabilityRun struct {
556 func (me pieceAvailabilityRun) String() string {
557 return fmt.Sprintf("%v(%v)", me.count, me.availability)
560 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
561 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
562 ret = append(ret, pieceAvailabilityRun{availability: el.(int64), count: int(count)})
564 for i := range t.pieces {
565 rle.Append(t.pieces[i].availability, 1)
571 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
572 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
573 ret = append(ret, PieceStateRun{
574 PieceState: el.(PieceState),
578 for index := range t.pieces {
579 rle.Append(t.pieceState(pieceIndex(index)), 1)
585 // Produces a small string representing a PieceStateRun.
586 func (psr PieceStateRun) String() (ret string) {
587 ret = fmt.Sprintf("%d", psr.Length)
588 ret += func() string {
589 switch psr.Priority {
590 case PiecePriorityNext:
592 case PiecePriorityNormal:
594 case PiecePriorityReadahead:
596 case PiecePriorityNow:
598 case PiecePriorityHigh:
607 if psr.QueuedForHash {
625 func (t *Torrent) writeStatus(w io.Writer) {
626 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
627 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
629 fmt.Fprintf(w, "Metadata have: ")
630 for _, h := range t.metadataCompletedChunks {
631 fmt.Fprintf(w, "%c", func() rune {
641 fmt.Fprintf(w, "Piece length: %s\n",
644 return fmt.Sprintf("%v (%v chunks)",
646 float64(t.usualPieceSize())/float64(t.chunkSize))
653 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
654 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
655 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
656 for _, run := range t.pieceAvailabilityRuns() {
657 ret = append(ret, run.String())
662 fmt.Fprintf(w, "Reader Pieces:")
663 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
664 fmt.Fprintf(w, " %d:%d", begin, end)
669 fmt.Fprintf(w, "Enabled trackers:\n")
671 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
672 fmt.Fprintf(tw, " URL\tExtra\n")
673 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
676 var luns, runs url.URL = *lu, *ru
679 var ml missinggo.MultiLess
680 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
681 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
683 }).([]torrentTrackerAnnouncer) {
684 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
689 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
691 spew.NewDefaultConfig()
692 spew.Fdump(w, t.statsLocked())
694 peers := t.peersAsSlice()
695 sort.Slice(peers, func(_i, _j int) bool {
698 if less, ok := multiless.New().EagerSameLess(
699 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
703 return worseConn(i, j)
705 for i, c := range peers {
706 fmt.Fprintf(w, "%2d. ", i+1)
711 func (t *Torrent) haveInfo() bool {
715 // Returns a run-time generated MetaInfo that includes the info bytes and
716 // announce-list as currently known to the client.
717 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
718 return metainfo.MetaInfo{
719 CreationDate: time.Now().Unix(),
720 Comment: "dynamic metainfo from client",
721 CreatedBy: "go.torrent",
722 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
723 InfoBytes: func() []byte {
725 return t.metadataBytes
730 UrlList: func() []string {
731 ret := make([]string, 0, len(t.webSeeds))
732 for url := range t.webSeeds {
733 ret = append(ret, url)
741 func (t *Torrent) BytesMissing() (n int64) {
743 n = t.bytesMissingLocked()
748 func (t *Torrent) bytesMissingLocked() int64 {
752 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
753 roaring.Flip(b, 0, end).Iterate(cb)
756 func (t *Torrent) bytesLeft() (left int64) {
757 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
758 p := t.piece(pieceIndex(x))
759 left += int64(p.length() - p.numDirtyBytes())
765 // Bytes left to give in tracker announces.
766 func (t *Torrent) bytesLeftAnnounce() int64 {
774 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
775 if t.pieceComplete(piece) {
778 if t.pieceAllDirty(piece) {
781 return t.pieces[piece].hasDirtyChunks()
784 func (t *Torrent) usualPieceSize() int {
785 return int(t.info.PieceLength)
788 func (t *Torrent) numPieces() pieceIndex {
789 return pieceIndex(t.info.NumPieces())
792 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
793 return pieceIndex(t._completedPieces.GetCardinality())
796 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
798 if t.storage != nil {
803 defer t.storageLock.Unlock()
804 if f := t.storage.Close; f != nil {
807 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
812 t.iterPeers(func(p *Peer) {
816 t.cl.event.Broadcast()
817 t.pieceStateChanges.Close()
818 t.updateWantPeersEvent()
822 func (t *Torrent) requestOffset(r Request) int64 {
823 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
826 // Return the request that would include the given offset into the torrent data. Returns !ok if
827 // there is no such request.
828 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
829 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
832 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
833 defer perf.ScopeTimerErr(&err)()
834 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
835 if err == nil && n != len(data) {
836 err = io.ErrShortWrite
841 func (t *Torrent) bitfield() (bf []bool) {
842 bf = make([]bool, t.numPieces())
843 t._completedPieces.Iterate(func(piece uint32) (again bool) {
850 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
851 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
854 func (t *Torrent) chunksPerRegularPiece() uint32 {
855 return uint32((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
858 func (t *Torrent) numRequests() RequestIndex {
859 if t.numPieces() == 0 {
862 return uint32(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
865 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
866 t.dirtyChunks.RemoveRange(
867 uint64(t.pieceRequestIndexOffset(pieceIndex)),
868 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
871 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
872 if t.info.PieceLength == 0 {
873 // There will be no variance amongst pieces. Only pain.
876 if piece == t.numPieces()-1 {
877 ret := pp.Integer(*t.length % t.info.PieceLength)
882 return pp.Integer(t.info.PieceLength)
885 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
887 p.waitNoPendingWrites()
888 storagePiece := t.pieces[piece].Storage()
890 // Does the backend want to do its own hashing?
891 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
892 var sum metainfo.Hash
893 // log.Printf("A piece decided to self-hash: %d", piece)
894 sum, err = i.SelfHash()
895 missinggo.CopyExact(&ret, sum)
899 hash := pieceHash.New()
900 const logPieceContents = false
901 if logPieceContents {
902 var examineBuf bytes.Buffer
903 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
904 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
906 _, err = storagePiece.WriteTo(hash)
908 missinggo.CopyExact(&ret, hash.Sum(nil))
912 func (t *Torrent) haveAnyPieces() bool {
913 return t._completedPieces.GetCardinality() != 0
916 func (t *Torrent) haveAllPieces() bool {
920 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
923 func (t *Torrent) havePiece(index pieceIndex) bool {
924 return t.haveInfo() && t.pieceComplete(index)
927 func (t *Torrent) maybeDropMutuallyCompletePeer(
928 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
932 if !t.cl.config.DropMutuallyCompletePeers {
935 if !t.haveAllPieces() {
938 if all, known := p.peerHasAllPieces(); !(known && all) {
944 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
948 func (t *Torrent) haveChunk(r Request) (ret bool) {
950 // log.Println("have chunk", r, ret)
955 if t.pieceComplete(pieceIndex(r.Index)) {
958 p := &t.pieces[r.Index]
959 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
962 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
963 return chunkIndexType(cs.Begin / chunkSize)
966 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
967 return t._pendingPieces.Contains(uint32(index))
970 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
971 // conns (which is a map).
972 var peerConnSlices sync.Pool
974 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
975 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
976 // established connections for more than a minute. This is O(n log n). If there was a way to not
977 // consider the position of a conn relative to the total number, it could be reduced to O(n).
978 func (t *Torrent) worstBadConn() (ret *PeerConn) {
980 getInterface := peerConnSlices.Get()
981 if getInterface == nil {
982 sl = make([]*PeerConn, 0, len(t.conns))
984 sl = getInterface.([]*PeerConn)[:0]
986 sl = t.appendUnclosedConns(sl)
987 defer peerConnSlices.Put(sl)
988 wcs := worseConnSlice{sl}
991 c := heap.Pop(&wcs).(*PeerConn)
992 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
995 // If the connection is in the worst half of the established
996 // connection quota and is older than a minute.
997 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
998 // Give connections 1 minute to prove themselves.
999 if time.Since(c.completedHandshake) > time.Minute {
1007 type PieceStateChange struct {
1012 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1013 t.cl._mu.Defer(func() {
1014 cur := t.pieceState(piece)
1015 p := &t.pieces[piece]
1016 if cur != p.publicPieceState {
1017 p.publicPieceState = cur
1018 t.pieceStateChanges.Publish(PieceStateChange{
1026 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1027 if t.pieceComplete(piece) {
1030 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1033 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1034 return t.pieces[piece].allChunksDirty()
1037 func (t *Torrent) readersChanged() {
1038 t.updateReaderPieces()
1039 t.updateAllPiecePriorities("Torrent.readersChanged")
1042 func (t *Torrent) updateReaderPieces() {
1043 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1046 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1050 t.updateReaderPieces()
1051 // Order the ranges, high and low.
1053 if l.begin > h.begin {
1056 if l.end < h.begin {
1057 // Two distinct ranges.
1058 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1059 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1066 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1070 func (t *Torrent) maybeNewConns() {
1071 // Tickle the accept routine.
1072 t.cl.event.Broadcast()
1076 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1077 if t._pendingPieces.Contains(uint32(piece)) {
1078 t.iterPeers(func(c *Peer) {
1079 if c.actualRequestState.Interested {
1082 if !c.isLowOnRequests() {
1085 if !c.peerHasPiece(piece) {
1088 c.updateRequests(reason)
1092 t.publishPieceChange(piece)
1095 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1096 p := &t.pieces[piece]
1097 newPrio := p.uncachedPriority()
1098 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1099 if newPrio == PiecePriorityNone {
1100 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1104 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1108 t.piecePriorityChanged(piece, reason)
1111 func (t *Torrent) updateAllPiecePriorities(reason string) {
1112 t.updatePiecePriorities(0, t.numPieces(), reason)
1115 // Update all piece priorities in one hit. This function should have the same
1116 // output as updatePiecePriority, but across all pieces.
1117 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1118 for i := begin; i < end; i++ {
1119 t.updatePiecePriority(i, reason)
1123 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1124 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1125 if off >= *t.length {
1135 begin = pieceIndex(off / t.info.PieceLength)
1136 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1137 if end > pieceIndex(t.info.NumPieces()) {
1138 end = pieceIndex(t.info.NumPieces())
1143 // Returns true if all iterations complete without breaking. Returns the read regions for all
1144 // readers. The reader regions should not be merged as some callers depend on this method to
1145 // enumerate readers.
1146 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1147 for r := range t.readers {
1149 if p.begin >= p.end {
1152 if !f(p.begin, p.end) {
1159 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1160 return t.piece(piece).uncachedPriority()
1163 func (t *Torrent) pendRequest(req RequestIndex) {
1164 t.piece(int(req / t.chunksPerRegularPiece())).pendChunkIndex(req % t.chunksPerRegularPiece())
1167 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1168 t.cl.event.Broadcast()
1169 if t.pieceComplete(piece) {
1170 t.onPieceCompleted(piece)
1172 t.onIncompletePiece(piece)
1174 t.updatePiecePriority(piece, reason)
1177 func (t *Torrent) numReceivedConns() (ret int) {
1178 for c := range t.conns {
1179 if c.Discovery == PeerSourceIncoming {
1186 func (t *Torrent) maxHalfOpen() int {
1187 // Note that if we somehow exceed the maximum established conns, we want
1188 // the negative value to have an effect.
1189 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1190 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1191 // We want to allow some experimentation with new peers, and to try to
1192 // upset an oversupply of received connections.
1193 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1196 func (t *Torrent) openNewConns() (initiated int) {
1197 defer t.updateWantPeersEvent()
1198 for t.peers.Len() != 0 {
1202 if len(t.halfOpen) >= t.maxHalfOpen() {
1205 if len(t.cl.dialers) == 0 {
1208 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1211 p := t.peers.PopMax()
1218 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1220 uncached := t.pieceCompleteUncached(piece)
1221 cached := p.completion()
1222 changed := cached != uncached
1223 complete := uncached.Complete
1224 p.storageCompletionOk = uncached.Ok
1227 t._completedPieces.Add(x)
1229 t._completedPieces.Remove(x)
1232 if complete && len(p.dirtiers) != 0 {
1233 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1236 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1237 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1242 // Non-blocking read. Client lock is not required.
1243 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1245 p := &t.pieces[off/t.info.PieceLength]
1246 p.waitNoPendingWrites()
1248 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1259 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1260 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1261 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1262 func (t *Torrent) maybeCompleteMetadata() error {
1267 if !t.haveAllMetadataPieces() {
1268 // Don't have enough metadata pieces.
1271 err := t.setInfoBytesLocked(t.metadataBytes)
1273 t.invalidateMetadata()
1274 return fmt.Errorf("error setting info bytes: %s", err)
1276 if t.cl.config.Debug {
1277 t.logger.Printf("%s: got metadata from peers", t)
1282 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1283 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1285 now.Add(bitmap.BitIndex(begin))
1286 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1293 func (t *Torrent) needData() bool {
1294 if t.closed.IsSet() {
1300 return !t._pendingPieces.IsEmpty()
1303 func appendMissingStrings(old, new []string) (ret []string) {
1306 for _, n := range new {
1307 for _, o := range old {
1312 ret = append(ret, n)
1317 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1319 for minNumTiers > len(ret) {
1320 ret = append(ret, nil)
1325 func (t *Torrent) addTrackers(announceList [][]string) {
1326 fullAnnounceList := &t.metainfo.AnnounceList
1327 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1328 for tierIndex, trackerURLs := range announceList {
1329 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1331 t.startMissingTrackerScrapers()
1332 t.updateWantPeersEvent()
1335 // Don't call this before the info is available.
1336 func (t *Torrent) bytesCompleted() int64 {
1340 return *t.length - t.bytesLeft()
1343 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1346 return t.setInfoBytesLocked(b)
1349 // Returns true if connection is removed from torrent.Conns.
1350 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1351 if !c.closed.IsSet() {
1352 panic("connection is not closed")
1353 // There are behaviours prevented by the closed state that will fail
1354 // if the connection has been deleted.
1358 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1359 // the drop event against the PexConnState instead.
1361 if !t.cl.config.DisablePEX {
1365 torrent.Add("deleted connections", 1)
1366 c.deleteAllRequests()
1367 t.assertPendingRequests()
1371 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1375 p.newPeerPieces().Iterate(func(i uint32) bool {
1376 p.t.decPieceAvailability(pieceIndex(i))
1381 func (t *Torrent) assertPendingRequests() {
1385 var actual pendingRequests
1387 actual.m = make([]int, t.numRequests())
1389 t.iterPeers(func(p *Peer) {
1390 p.actualRequestState.Requests.Iterate(func(x uint32) bool {
1395 diff := cmp.Diff(actual.m, t.pendingRequests.m)
1401 func (t *Torrent) dropConnection(c *PeerConn) {
1402 t.cl.event.Broadcast()
1404 if t.deletePeerConn(c) {
1409 func (t *Torrent) wantPeers() bool {
1410 if t.closed.IsSet() {
1413 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1416 return t.needData() || t.seeding()
1419 func (t *Torrent) updateWantPeersEvent() {
1421 t.wantPeersEvent.Set()
1423 t.wantPeersEvent.Clear()
1427 // Returns whether the client should make effort to seed the torrent.
1428 func (t *Torrent) seeding() bool {
1430 if t.closed.IsSet() {
1433 if t.dataUploadDisallowed {
1436 if cl.config.NoUpload {
1439 if !cl.config.Seed {
1442 if cl.config.DisableAggressiveUpload && t.needData() {
1448 func (t *Torrent) onWebRtcConn(
1449 c datachannel.ReadWriteCloser,
1450 dcc webtorrent.DataChannelContext,
1453 pc, err := t.cl.initiateProtocolHandshakes(
1454 context.Background(),
1455 webrtcNetConn{c, dcc},
1459 webrtcNetAddr{dcc.Remote},
1461 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1464 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1467 if dcc.LocalOffered {
1468 pc.Discovery = PeerSourceTracker
1470 pc.Discovery = PeerSourceIncoming
1474 err = t.cl.runHandshookConn(pc, t)
1476 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1480 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1481 err := t.cl.runHandshookConn(pc, t)
1482 if err != nil || logAll {
1483 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1487 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1488 t.logRunHandshookConn(pc, false, log.Debug)
1491 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1492 wtc, release := t.cl.websocketTrackers.Get(u.String())
1497 wst := websocketTrackerStatus{u, wtc}
1499 err := wtc.Announce(tracker.Started, t.infoHash)
1501 t.logger.WithDefaultLevel(log.Warning).Printf(
1502 "error in initial announce to %q: %v",
1510 func (t *Torrent) startScrapingTracker(_url string) {
1514 u, err := url.Parse(_url)
1516 // URLs with a leading '*' appear to be a uTorrent convention to
1517 // disable trackers.
1519 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1523 if u.Scheme == "udp" {
1525 t.startScrapingTracker(u.String())
1527 t.startScrapingTracker(u.String())
1530 if _, ok := t.trackerAnnouncers[_url]; ok {
1533 sl := func() torrentTrackerAnnouncer {
1536 if t.cl.config.DisableWebtorrent {
1539 return t.startWebsocketAnnouncer(*u)
1541 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1545 if t.cl.config.DisableIPv6 {
1549 newAnnouncer := &trackerScraper{
1552 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1554 go newAnnouncer.Run()
1560 if t.trackerAnnouncers == nil {
1561 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1563 t.trackerAnnouncers[_url] = sl
1566 // Adds and starts tracker scrapers for tracker URLs that aren't already
1568 func (t *Torrent) startMissingTrackerScrapers() {
1569 if t.cl.config.DisableTrackers {
1572 t.startScrapingTracker(t.metainfo.Announce)
1573 for _, tier := range t.metainfo.AnnounceList {
1574 for _, url := range tier {
1575 t.startScrapingTracker(url)
1580 // Returns an AnnounceRequest with fields filled out to defaults and current
1582 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1583 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1584 // dependent on the network in use.
1585 return tracker.AnnounceRequest{
1587 NumWant: func() int32 {
1588 if t.wantPeers() && len(t.cl.dialers) > 0 {
1594 Port: uint16(t.cl.incomingPeerPort()),
1595 PeerId: t.cl.peerID,
1596 InfoHash: t.infoHash,
1597 Key: t.cl.announceKey(),
1599 // The following are vaguely described in BEP 3.
1601 Left: t.bytesLeftAnnounce(),
1602 Uploaded: t.stats.BytesWrittenData.Int64(),
1603 // There's no mention of wasted or unwanted download in the BEP.
1604 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1608 // Adds peers revealed in an announce until the announce ends, or we have
1610 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1612 for v := range pvs {
1615 for _, cp := range v.Peers {
1617 // Can't do anything with this.
1620 if t.addPeer(PeerInfo{
1621 Addr: ipPortAddr{cp.IP, cp.Port},
1622 Source: PeerSourceDhtGetPeers,
1629 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1634 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1635 // announce ends. stop will force the announce to end.
1636 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1637 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1641 _done := make(chan struct{})
1645 t.consumeDhtAnnouncePeers(ps.Peers())
1651 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1652 _, stop, err := t.AnnounceToDht(s)
1657 case <-t.closed.Done():
1658 case <-time.After(5 * time.Minute):
1664 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1670 if t.closed.IsSet() {
1676 // TODO: Determine if there's a listener on the port we're announcing.
1677 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1688 err := t.timeboxedAnnounceToDht(s)
1690 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1696 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1697 for _, p := range peers {
1705 // The returned TorrentStats may require alignment in memory. See
1706 // https://github.com/anacrolix/torrent/issues/383.
1707 func (t *Torrent) Stats() TorrentStats {
1709 defer t.cl.rUnlock()
1710 return t.statsLocked()
1713 func (t *Torrent) statsLocked() (ret TorrentStats) {
1714 ret.ActivePeers = len(t.conns)
1715 ret.HalfOpenPeers = len(t.halfOpen)
1716 ret.PendingPeers = t.peers.Len()
1717 ret.TotalPeers = t.numTotalPeers()
1718 ret.ConnectedSeeders = 0
1719 for c := range t.conns {
1720 if all, ok := c.peerHasAllPieces(); all && ok {
1721 ret.ConnectedSeeders++
1724 ret.ConnStats = t.stats.Copy()
1725 ret.PiecesComplete = t.numPiecesCompleted()
1729 // The total number of peers in the torrent.
1730 func (t *Torrent) numTotalPeers() int {
1731 peers := make(map[string]struct{})
1732 for conn := range t.conns {
1733 ra := conn.conn.RemoteAddr()
1735 // It's been closed and doesn't support RemoteAddr.
1738 peers[ra.String()] = struct{}{}
1740 for addr := range t.halfOpen {
1741 peers[addr] = struct{}{}
1743 t.peers.Each(func(peer PeerInfo) {
1744 peers[peer.Addr.String()] = struct{}{}
1749 // Reconcile bytes transferred before connection was associated with a
1751 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1752 if c._stats != (ConnStats{
1753 // Handshakes should only increment these fields:
1754 BytesWritten: c._stats.BytesWritten,
1755 BytesRead: c._stats.BytesRead,
1759 c.postHandshakeStats(func(cs *ConnStats) {
1760 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1761 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1763 c.reconciledHandshakeStats = true
1766 // Returns true if the connection is added.
1767 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1770 torrent.Add("added connections", 1)
1773 if t.closed.IsSet() {
1774 return errors.New("torrent closed")
1776 for c0 := range t.conns {
1777 if c.PeerID != c0.PeerID {
1780 if !t.cl.config.DropDuplicatePeerIds {
1783 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1785 t.deletePeerConn(c0)
1787 return errors.New("existing connection preferred")
1790 if len(t.conns) >= t.maxEstablishedConns {
1791 c := t.worstBadConn()
1793 return errors.New("don't want conns")
1798 if len(t.conns) >= t.maxEstablishedConns {
1801 t.conns[c] = struct{}{}
1802 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1803 t.pex.Add(c) // as no further extended handshake expected
1808 func (t *Torrent) wantConns() bool {
1809 if !t.networkingEnabled.Bool() {
1812 if t.closed.IsSet() {
1815 if !t.seeding() && !t.needData() {
1818 if len(t.conns) < t.maxEstablishedConns {
1821 return t.worstBadConn() != nil
1824 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1827 oldMax = t.maxEstablishedConns
1828 t.maxEstablishedConns = max
1829 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1830 return worseConn(&l.Peer, &r.Peer)
1832 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1833 t.dropConnection(wcs.Pop().(*PeerConn))
1839 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1840 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1843 t.cl.event.Broadcast()
1844 if t.closed.IsSet() {
1848 // Don't score the first time a piece is hashed, it could be an initial check.
1849 if p.storageCompletionOk {
1851 pieceHashedCorrect.Add(1)
1854 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1855 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1856 pieceHashedNotCorrect.Add(1)
1861 t.publishPieceChange(piece)
1864 t.publishPieceChange(piece)
1868 if len(p.dirtiers) != 0 {
1869 // Don't increment stats above connection-level for every involved connection.
1870 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1872 for c := range p.dirtiers {
1873 c._stats.incrementPiecesDirtiedGood()
1875 t.clearPieceTouchers(piece)
1877 err := p.Storage().MarkComplete()
1879 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1883 if t.closed.IsSet() {
1886 t.pendAllChunkSpecs(piece)
1888 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1889 // Peers contributed to all the data for this piece hash failure, and the failure was
1890 // not due to errors in the storage (such as data being dropped in a cache).
1892 // Increment Torrent and above stats, and then specific connections.
1893 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1894 for c := range p.dirtiers {
1895 // Y u do dis peer?!
1896 c.stats().incrementPiecesDirtiedBad()
1899 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1900 for c := range p.dirtiers {
1902 bannableTouchers = append(bannableTouchers, c)
1905 t.clearPieceTouchers(piece)
1906 slices.Sort(bannableTouchers, connLessTrusted)
1908 if t.cl.config.Debug {
1910 "bannable conns by trust for piece %d: %v",
1912 func() (ret []connectionTrust) {
1913 for _, c := range bannableTouchers {
1914 ret = append(ret, c.trust())
1921 if len(bannableTouchers) >= 1 {
1922 c := bannableTouchers[0]
1923 t.cl.banPeerIP(c.remoteIp())
1927 t.onIncompletePiece(piece)
1928 p.Storage().MarkNotComplete()
1930 t.updatePieceCompletion(piece)
1933 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1934 // TODO: Make faster
1935 for cn := range t.conns {
1940 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1941 t.pendAllChunkSpecs(piece)
1942 t.cancelRequestsForPiece(piece)
1943 t.piece(piece).readerCond.Broadcast()
1944 for conn := range t.conns {
1946 t.maybeDropMutuallyCompletePeer(&conn.Peer)
1950 // Called when a piece is found to be not complete.
1951 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1952 if t.pieceAllDirty(piece) {
1953 t.pendAllChunkSpecs(piece)
1955 if !t.wantPieceIndex(piece) {
1956 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1959 // We could drop any connections that we told we have a piece that we
1960 // don't here. But there's a test failure, and it seems clients don't care
1961 // if you request pieces that you already claim to have. Pruning bad
1962 // connections might just remove any connections that aren't treating us
1963 // favourably anyway.
1965 // for c := range t.conns {
1966 // if c.sentHave(piece) {
1970 t.iterPeers(func(conn *Peer) {
1971 if conn.peerHasPiece(piece) {
1972 conn.updateRequests("piece incomplete")
1977 func (t *Torrent) tryCreateMorePieceHashers() {
1978 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1982 func (t *Torrent) tryCreatePieceHasher() bool {
1983 if t.storage == nil {
1986 pi, ok := t.getPieceToHash()
1991 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
1993 t.publishPieceChange(pi)
1994 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
1995 t.storageLock.RLock()
1996 t.activePieceHashes++
1997 go t.pieceHasher(pi)
2001 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2002 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2003 if t.piece(i).hashing {
2013 func (t *Torrent) pieceHasher(index pieceIndex) {
2015 sum, copyErr := t.hashPiece(index)
2016 correct := sum == *p.hash
2020 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2022 t.storageLock.RUnlock()
2026 t.pieceHashed(index, correct, copyErr)
2027 t.updatePiecePriority(index, "Torrent.pieceHasher")
2028 t.activePieceHashes--
2029 t.tryCreateMorePieceHashers()
2032 // Return the connections that touched a piece, and clear the entries while doing it.
2033 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2035 for c := range p.dirtiers {
2036 delete(c.peerTouchedPieces, pi)
2037 delete(p.dirtiers, c)
2041 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2042 t.iterPeers(func(p *Peer) {
2043 ret = append(ret, p)
2048 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2049 piece := t.piece(pieceIndex)
2050 if piece.queuedForHash() {
2053 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2054 t.publishPieceChange(pieceIndex)
2055 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2056 t.tryCreateMorePieceHashers()
2059 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2060 // before the Info is available.
2061 func (t *Torrent) VerifyData() {
2062 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2063 t.Piece(i).VerifyData()
2067 // Start the process of connecting to the given peer for the given torrent if appropriate.
2068 func (t *Torrent) initiateConn(peer PeerInfo) {
2069 if peer.Id == t.cl.peerID {
2072 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2076 if t.addrActive(addr.String()) {
2080 t.halfOpen[addr.String()] = peer
2081 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2084 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2085 // quickly make one Client visible to the Torrent of another Client.
2086 func (t *Torrent) AddClientPeer(cl *Client) int {
2087 return t.AddPeers(func() (ps []PeerInfo) {
2088 for _, la := range cl.ListenAddrs() {
2089 ps = append(ps, PeerInfo{
2098 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2100 func (t *Torrent) allStats(f func(*ConnStats)) {
2105 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2106 return t.pieces[i].hashing
2109 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2110 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2113 func (t *Torrent) dialTimeout() time.Duration {
2114 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2117 func (t *Torrent) piece(i int) *Piece {
2121 func (t *Torrent) onWriteChunkErr(err error) {
2122 if t.userOnWriteChunkErr != nil {
2123 go t.userOnWriteChunkErr(err)
2126 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2127 t.disallowDataDownloadLocked()
2130 func (t *Torrent) DisallowDataDownload() {
2131 t.disallowDataDownloadLocked()
2134 func (t *Torrent) disallowDataDownloadLocked() {
2135 t.dataDownloadDisallowed.Set()
2138 func (t *Torrent) AllowDataDownload() {
2139 t.dataDownloadDisallowed.Clear()
2142 // Enables uploading data, if it was disabled.
2143 func (t *Torrent) AllowDataUpload() {
2146 t.dataUploadDisallowed = false
2147 for c := range t.conns {
2148 c.updateRequests("allow data upload")
2152 // Disables uploading data, if it was enabled.
2153 func (t *Torrent) DisallowDataUpload() {
2156 t.dataUploadDisallowed = true
2157 for c := range t.conns {
2158 c.updateRequests("disallow data upload")
2162 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2163 // or if nil, a critical message is logged, and data download is disabled.
2164 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2167 t.userOnWriteChunkErr = f
2170 func (t *Torrent) iterPeers(f func(p *Peer)) {
2171 for pc := range t.conns {
2174 for _, ws := range t.webSeeds {
2179 func (t *Torrent) callbacks() *Callbacks {
2180 return &t.cl.config.Callbacks
2183 var WebseedHttpClient = &http.Client{
2184 Transport: &http.Transport{
2185 MaxConnsPerHost: 10,
2189 func (t *Torrent) addWebSeed(url string) {
2190 if t.cl.config.DisableWebseeds {
2193 if _, ok := t.webSeeds[url]; ok {
2196 const maxRequests = 10
2202 reconciledHandshakeStats: true,
2203 // TODO: Raise this limit, and instead limit concurrent fetches.
2204 PeerMaxRequests: 32,
2205 RemoteAddr: remoteAddrFromUrl(url),
2206 callbacks: t.callbacks(),
2208 client: webseed.Client{
2209 // Consider a MaxConnsPerHost in the transport for this, possibly in a global Client.
2210 HttpClient: WebseedHttpClient,
2213 activeRequests: make(map[Request]webseed.Request, maxRequests),
2214 maxRequests: maxRequests,
2216 ws.peer.initUpdateRequestsTimer()
2217 ws.requesterCond.L = t.cl.locker()
2218 for i := 0; i < maxRequests; i += 1 {
2221 for _, f := range t.callbacks().NewPeer {
2224 ws.peer.logger = t.logger.WithContextValue(&ws)
2225 ws.peer.peerImpl = &ws
2227 ws.onGotInfo(t.info)
2229 t.webSeeds[url] = &ws.peer
2230 ws.peer.onPeerHasAllPieces()
2233 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2234 t.iterPeers(func(p1 *Peer) {
2242 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2243 index := ri / t.chunksPerRegularPiece()
2246 t.piece(int(index)).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2250 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2251 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + uint32(r.Begin/t.chunkSize)
2254 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2255 return RequestIndex(piece) * t.chunksPerRegularPiece()
2258 func (t *Torrent) updateComplete() {
2259 t.Complete.SetBool(t.haveAllPieces())