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 {
213 ks = append(ks, PeerInfo{
215 Addr: conn.RemoteAddr,
216 Source: conn.Discovery,
217 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
218 // > But if we're not connected to them with an encrypted connection, I couldn't say
219 // > what's appropriate. We can carry forward the SupportsEncryption value as we
220 // > received it from trackers/DHT/PEX, or just use the encryption state for the
221 // > connection. It's probably easiest to do the latter for now.
222 // https://github.com/anacrolix/torrent/pull/188
223 SupportsEncryption: conn.headerEncrypted,
230 func (t *Torrent) setChunkSize(size pp.Integer) {
232 t.chunkPool = sync.Pool{
233 New: func() interface{} {
234 b := make([]byte, size)
240 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
241 return t._completedPieces.Contains(bitmap.BitIndex(piece))
244 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
245 return t.pieces[piece].Storage().Completion()
248 // There's a connection to that address already.
249 func (t *Torrent) addrActive(addr string) bool {
250 if _, ok := t.halfOpen[addr]; ok {
253 for c := range t.conns {
255 if ra.String() == addr {
262 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
263 for c := range t.conns {
264 if !c.closed.IsSet() {
271 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
273 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
274 if t.closed.IsSet() {
277 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
278 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
279 torrent.Add("peers not added because of bad addr", 1)
280 // cl.logger.Printf("peers not added because of bad addr: %v", p)
284 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
285 torrent.Add("peers replaced", 1)
286 if !replaced.equal(p) {
287 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
294 for t.peers.Len() > cl.config.TorrentPeersHighWater {
295 _, ok := t.peers.DeleteMin()
297 torrent.Add("excess reserve peers discarded", 1)
303 func (t *Torrent) invalidateMetadata() {
304 for i := 0; i < len(t.metadataCompletedChunks); i++ {
305 t.metadataCompletedChunks[i] = false
308 t.gotMetainfoC = make(chan struct{})
313 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
317 if index >= len(t.metadataCompletedChunks) {
318 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
321 copy(t.metadataBytes[(1<<14)*index:], data)
322 t.metadataCompletedChunks[index] = true
325 func (t *Torrent) metadataPieceCount() int {
326 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
329 func (t *Torrent) haveMetadataPiece(piece int) bool {
331 return (1<<14)*piece < len(t.metadataBytes)
333 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
337 func (t *Torrent) metadataSize() int {
338 return len(t.metadataBytes)
341 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
342 for i := 0; i < len(info.Pieces); i += sha1.Size {
343 ret = append(ret, info.Pieces[i:i+sha1.Size])
348 func (t *Torrent) makePieces() {
349 hashes := infoPieceHashes(t.info)
350 t.pieces = make([]Piece, len(hashes))
351 for i, hash := range hashes {
352 piece := &t.pieces[i]
354 piece.index = pieceIndex(i)
355 piece.noPendingWrites.L = &piece.pendingWritesMutex
356 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
358 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
359 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
360 piece.files = files[beginFile:endFile]
361 piece.undirtiedChunksIter = undirtiedChunksIter{
362 TorrentDirtyChunks: &t.dirtyChunks,
363 StartRequestIndex: piece.requestIndexOffset(),
364 EndRequestIndex: piece.requestIndexOffset() + piece.numChunks(),
369 // Returns the index of the first file containing the piece. files must be
370 // ordered by offset.
371 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
372 for i, f := range files {
373 if f.offset+f.length > pieceOffset {
380 // Returns the index after the last file containing the piece. files must be
381 // ordered by offset.
382 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
383 for i, f := range files {
384 if f.offset+f.length >= pieceEndOffset {
391 func (t *Torrent) cacheLength() {
393 for _, f := range t.info.UpvertedFiles() {
399 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
401 func (t *Torrent) setInfo(info *metainfo.Info) error {
402 if err := validateInfo(info); err != nil {
403 return fmt.Errorf("bad info: %s", err)
405 if t.storageOpener != nil {
407 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
409 return fmt.Errorf("error opening torrent storage: %s", err)
416 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
417 t.displayName = "" // Save a few bytes lol.
424 // This seems to be all the follow-up tasks after info is set, that can't fail.
425 func (t *Torrent) onSetInfo() {
426 for i := range t.pieces {
428 // Need to add availability before updating piece completion, as that may result in conns
430 if p.availability != 0 {
431 panic(p.availability)
433 p.availability = int64(t.pieceAvailabilityFromPeers(i))
434 t.updatePieceCompletion(pieceIndex(i))
435 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
436 // t.logger.Printf("piece %s completion unknown, queueing check", p)
437 t.queuePieceCheck(pieceIndex(i))
440 t.cl.event.Broadcast()
441 close(t.gotMetainfoC)
442 t.updateWantPeersEvent()
443 t.pendingRequests.Init(t.numRequests())
444 t.tryCreateMorePieceHashers()
445 t.iterPeers(func(p *Peer) {
447 p.updateRequests("onSetInfo")
451 // Called when metadata for a torrent becomes available.
452 func (t *Torrent) setInfoBytesLocked(b []byte) error {
453 if metainfo.HashBytes(b) != t.infoHash {
454 return errors.New("info bytes have wrong hash")
456 var info metainfo.Info
457 if err := bencode.Unmarshal(b, &info); err != nil {
458 return fmt.Errorf("error unmarshalling info bytes: %s", err)
461 t.metadataCompletedChunks = nil
465 if err := t.setInfo(&info); err != nil {
472 func (t *Torrent) haveAllMetadataPieces() bool {
476 if t.metadataCompletedChunks == nil {
479 for _, have := range t.metadataCompletedChunks {
487 // TODO: Propagate errors to disconnect peer.
488 func (t *Torrent) setMetadataSize(size int) (err error) {
490 // We already know the correct metadata size.
493 if uint32(size) > maxMetadataSize {
494 return errors.New("bad size")
496 if len(t.metadataBytes) == size {
499 t.metadataBytes = make([]byte, size)
500 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
501 t.metadataChanged.Broadcast()
502 for c := range t.conns {
503 c.requestPendingMetadata()
508 // The current working name for the torrent. Either the name in the info dict,
509 // or a display name given such as by the dn value in a magnet link, or "".
510 func (t *Torrent) name() string {
512 defer t.nameMu.RUnlock()
516 if t.displayName != "" {
519 return "infohash:" + t.infoHash.HexString()
522 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
523 p := &t.pieces[index]
524 ret.Priority = t.piecePriority(index)
525 ret.Completion = p.completion()
526 ret.QueuedForHash = p.queuedForHash()
527 ret.Hashing = p.hashing
528 ret.Checking = ret.QueuedForHash || ret.Hashing
529 ret.Marking = p.marking
530 if !ret.Complete && t.piecePartiallyDownloaded(index) {
536 func (t *Torrent) metadataPieceSize(piece int) int {
537 return metadataPieceSize(len(t.metadataBytes), piece)
540 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
543 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
544 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
546 TotalSize: len(t.metadataBytes),
552 type pieceAvailabilityRun struct {
557 func (me pieceAvailabilityRun) String() string {
558 return fmt.Sprintf("%v(%v)", me.count, me.availability)
561 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
562 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
563 ret = append(ret, pieceAvailabilityRun{availability: el.(int64), count: int(count)})
565 for i := range t.pieces {
566 rle.Append(t.pieces[i].availability, 1)
572 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
573 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
574 ret = append(ret, PieceStateRun{
575 PieceState: el.(PieceState),
579 for index := range t.pieces {
580 rle.Append(t.pieceState(pieceIndex(index)), 1)
586 // Produces a small string representing a PieceStateRun.
587 func (psr PieceStateRun) String() (ret string) {
588 ret = fmt.Sprintf("%d", psr.Length)
589 ret += func() string {
590 switch psr.Priority {
591 case PiecePriorityNext:
593 case PiecePriorityNormal:
595 case PiecePriorityReadahead:
597 case PiecePriorityNow:
599 case PiecePriorityHigh:
608 if psr.QueuedForHash {
626 func (t *Torrent) writeStatus(w io.Writer) {
627 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
628 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
630 fmt.Fprintf(w, "Metadata have: ")
631 for _, h := range t.metadataCompletedChunks {
632 fmt.Fprintf(w, "%c", func() rune {
642 fmt.Fprintf(w, "Piece length: %s\n",
645 return fmt.Sprintf("%v (%v chunks)",
647 float64(t.usualPieceSize())/float64(t.chunkSize))
654 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
655 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
656 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
657 for _, run := range t.pieceAvailabilityRuns() {
658 ret = append(ret, run.String())
663 fmt.Fprintf(w, "Reader Pieces:")
664 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
665 fmt.Fprintf(w, " %d:%d", begin, end)
670 fmt.Fprintf(w, "Enabled trackers:\n")
672 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
673 fmt.Fprintf(tw, " URL\tExtra\n")
674 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
677 var luns, runs url.URL = *lu, *ru
680 var ml missinggo.MultiLess
681 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
682 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
684 }).([]torrentTrackerAnnouncer) {
685 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
690 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
692 spew.NewDefaultConfig()
693 spew.Fdump(w, t.statsLocked())
695 peers := t.peersAsSlice()
696 sort.Slice(peers, func(_i, _j int) bool {
699 if less, ok := multiless.New().EagerSameLess(
700 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
704 return worseConn(i, j)
706 for i, c := range peers {
707 fmt.Fprintf(w, "%2d. ", i+1)
712 func (t *Torrent) haveInfo() bool {
716 // Returns a run-time generated MetaInfo that includes the info bytes and
717 // announce-list as currently known to the client.
718 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
719 return metainfo.MetaInfo{
720 CreationDate: time.Now().Unix(),
721 Comment: "dynamic metainfo from client",
722 CreatedBy: "go.torrent",
723 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
724 InfoBytes: func() []byte {
726 return t.metadataBytes
731 UrlList: func() []string {
732 ret := make([]string, 0, len(t.webSeeds))
733 for url := range t.webSeeds {
734 ret = append(ret, url)
742 func (t *Torrent) BytesMissing() (n int64) {
744 n = t.bytesMissingLocked()
749 func (t *Torrent) bytesMissingLocked() int64 {
753 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
754 roaring.Flip(b, 0, end).Iterate(cb)
757 func (t *Torrent) bytesLeft() (left int64) {
758 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
759 p := t.piece(pieceIndex(x))
760 left += int64(p.length() - p.numDirtyBytes())
766 // Bytes left to give in tracker announces.
767 func (t *Torrent) bytesLeftAnnounce() int64 {
775 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
776 if t.pieceComplete(piece) {
779 if t.pieceAllDirty(piece) {
782 return t.pieces[piece].hasDirtyChunks()
785 func (t *Torrent) usualPieceSize() int {
786 return int(t.info.PieceLength)
789 func (t *Torrent) numPieces() pieceIndex {
790 return pieceIndex(t.info.NumPieces())
793 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
794 return pieceIndex(t._completedPieces.GetCardinality())
797 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
799 if t.storage != nil {
804 defer t.storageLock.Unlock()
805 if f := t.storage.Close; f != nil {
808 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
813 t.iterPeers(func(p *Peer) {
817 t.cl.event.Broadcast()
818 t.pieceStateChanges.Close()
819 t.updateWantPeersEvent()
823 func (t *Torrent) requestOffset(r Request) int64 {
824 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
827 // Return the request that would include the given offset into the torrent data. Returns !ok if
828 // there is no such request.
829 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
830 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
833 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
834 defer perf.ScopeTimerErr(&err)()
835 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
836 if err == nil && n != len(data) {
837 err = io.ErrShortWrite
842 func (t *Torrent) bitfield() (bf []bool) {
843 bf = make([]bool, t.numPieces())
844 t._completedPieces.Iterate(func(piece uint32) (again bool) {
851 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
852 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
855 func (t *Torrent) chunksPerRegularPiece() uint32 {
856 return uint32((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
859 func (t *Torrent) numRequests() RequestIndex {
860 if t.numPieces() == 0 {
863 return uint32(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
866 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
867 t.dirtyChunks.RemoveRange(
868 uint64(t.pieceRequestIndexOffset(pieceIndex)),
869 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
872 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
873 if t.info.PieceLength == 0 {
874 // There will be no variance amongst pieces. Only pain.
877 if piece == t.numPieces()-1 {
878 ret := pp.Integer(*t.length % t.info.PieceLength)
883 return pp.Integer(t.info.PieceLength)
886 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
888 p.waitNoPendingWrites()
889 storagePiece := t.pieces[piece].Storage()
891 //Does the backend want to do its own hashing?
892 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
893 var sum metainfo.Hash
894 //log.Printf("A piece decided to self-hash: %d", piece)
895 sum, err = i.SelfHash()
896 missinggo.CopyExact(&ret, sum)
900 hash := pieceHash.New()
901 const logPieceContents = false
902 if logPieceContents {
903 var examineBuf bytes.Buffer
904 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
905 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
907 _, err = storagePiece.WriteTo(hash)
909 missinggo.CopyExact(&ret, hash.Sum(nil))
913 func (t *Torrent) haveAnyPieces() bool {
914 return t._completedPieces.GetCardinality() != 0
917 func (t *Torrent) haveAllPieces() bool {
921 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
924 func (t *Torrent) havePiece(index pieceIndex) bool {
925 return t.haveInfo() && t.pieceComplete(index)
928 func (t *Torrent) maybeDropMutuallyCompletePeer(
929 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
933 if !t.cl.config.DropMutuallyCompletePeers {
936 if !t.haveAllPieces() {
939 if all, known := p.peerHasAllPieces(); !(known && all) {
945 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
949 func (t *Torrent) haveChunk(r Request) (ret bool) {
951 // log.Println("have chunk", r, ret)
956 if t.pieceComplete(pieceIndex(r.Index)) {
959 p := &t.pieces[r.Index]
960 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
963 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
964 return chunkIndexType(cs.Begin / chunkSize)
967 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
968 return t._pendingPieces.Contains(uint32(index))
971 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
972 // conns (which is a map).
973 var peerConnSlices sync.Pool
975 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
976 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
977 // established connections for more than a minute. This is O(n log n). If there was a way to not
978 // consider the position of a conn relative to the total number, it could be reduced to O(n).
979 func (t *Torrent) worstBadConn() (ret *PeerConn) {
981 getInterface := peerConnSlices.Get()
982 if getInterface == nil {
983 sl = make([]*PeerConn, 0, len(t.conns))
985 sl = getInterface.([]*PeerConn)[:0]
987 sl = t.appendUnclosedConns(sl)
988 defer peerConnSlices.Put(sl)
989 wcs := worseConnSlice{sl}
992 c := heap.Pop(&wcs).(*PeerConn)
993 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
996 // If the connection is in the worst half of the established
997 // connection quota and is older than a minute.
998 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
999 // Give connections 1 minute to prove themselves.
1000 if time.Since(c.completedHandshake) > time.Minute {
1008 type PieceStateChange struct {
1013 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1014 t.cl._mu.Defer(func() {
1015 cur := t.pieceState(piece)
1016 p := &t.pieces[piece]
1017 if cur != p.publicPieceState {
1018 p.publicPieceState = cur
1019 t.pieceStateChanges.Publish(PieceStateChange{
1027 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1028 if t.pieceComplete(piece) {
1031 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1034 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1035 return t.pieces[piece].allChunksDirty()
1038 func (t *Torrent) readersChanged() {
1039 t.updateReaderPieces()
1040 t.updateAllPiecePriorities("Torrent.readersChanged")
1043 func (t *Torrent) updateReaderPieces() {
1044 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1047 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1051 t.updateReaderPieces()
1052 // Order the ranges, high and low.
1054 if l.begin > h.begin {
1057 if l.end < h.begin {
1058 // Two distinct ranges.
1059 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1060 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1067 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1071 func (t *Torrent) maybeNewConns() {
1072 // Tickle the accept routine.
1073 t.cl.event.Broadcast()
1077 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1078 if t._pendingPieces.Contains(uint32(piece)) {
1079 t.iterPeers(func(c *Peer) {
1080 if c.actualRequestState.Interested {
1083 if !c.isLowOnRequests() {
1086 if !c.peerHasPiece(piece) {
1089 c.updateRequests(reason)
1093 t.publishPieceChange(piece)
1096 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1097 p := &t.pieces[piece]
1098 newPrio := p.uncachedPriority()
1099 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1100 if newPrio == PiecePriorityNone {
1101 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1105 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1109 t.piecePriorityChanged(piece, reason)
1112 func (t *Torrent) updateAllPiecePriorities(reason string) {
1113 t.updatePiecePriorities(0, t.numPieces(), reason)
1116 // Update all piece priorities in one hit. This function should have the same
1117 // output as updatePiecePriority, but across all pieces.
1118 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1119 for i := begin; i < end; i++ {
1120 t.updatePiecePriority(i, reason)
1124 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1125 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1126 if off >= *t.length {
1136 begin = pieceIndex(off / t.info.PieceLength)
1137 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1138 if end > pieceIndex(t.info.NumPieces()) {
1139 end = pieceIndex(t.info.NumPieces())
1144 // Returns true if all iterations complete without breaking. Returns the read regions for all
1145 // readers. The reader regions should not be merged as some callers depend on this method to
1146 // enumerate readers.
1147 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1148 for r := range t.readers {
1150 if p.begin >= p.end {
1153 if !f(p.begin, p.end) {
1160 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1161 return t.piece(piece).uncachedPriority()
1164 func (t *Torrent) pendRequest(req RequestIndex) {
1165 t.piece(int(req / t.chunksPerRegularPiece())).pendChunkIndex(req % t.chunksPerRegularPiece())
1168 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1169 t.cl.event.Broadcast()
1170 if t.pieceComplete(piece) {
1171 t.onPieceCompleted(piece)
1173 t.onIncompletePiece(piece)
1175 t.updatePiecePriority(piece, reason)
1178 func (t *Torrent) numReceivedConns() (ret int) {
1179 for c := range t.conns {
1180 if c.Discovery == PeerSourceIncoming {
1187 func (t *Torrent) maxHalfOpen() int {
1188 // Note that if we somehow exceed the maximum established conns, we want
1189 // the negative value to have an effect.
1190 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1191 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1192 // We want to allow some experimentation with new peers, and to try to
1193 // upset an oversupply of received connections.
1194 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1197 func (t *Torrent) openNewConns() (initiated int) {
1198 defer t.updateWantPeersEvent()
1199 for t.peers.Len() != 0 {
1203 if len(t.halfOpen) >= t.maxHalfOpen() {
1206 if len(t.cl.dialers) == 0 {
1209 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1212 p := t.peers.PopMax()
1219 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1221 uncached := t.pieceCompleteUncached(piece)
1222 cached := p.completion()
1223 changed := cached != uncached
1224 complete := uncached.Complete
1225 p.storageCompletionOk = uncached.Ok
1228 t._completedPieces.Add(x)
1230 t._completedPieces.Remove(x)
1233 if complete && len(p.dirtiers) != 0 {
1234 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1237 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1238 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1243 // Non-blocking read. Client lock is not required.
1244 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1246 p := &t.pieces[off/t.info.PieceLength]
1247 p.waitNoPendingWrites()
1249 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1260 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1261 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1262 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1263 func (t *Torrent) maybeCompleteMetadata() error {
1268 if !t.haveAllMetadataPieces() {
1269 // Don't have enough metadata pieces.
1272 err := t.setInfoBytesLocked(t.metadataBytes)
1274 t.invalidateMetadata()
1275 return fmt.Errorf("error setting info bytes: %s", err)
1277 if t.cl.config.Debug {
1278 t.logger.Printf("%s: got metadata from peers", t)
1283 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1284 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1286 now.Add(bitmap.BitIndex(begin))
1287 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1294 func (t *Torrent) needData() bool {
1295 if t.closed.IsSet() {
1301 return !t._pendingPieces.IsEmpty()
1304 func appendMissingStrings(old, new []string) (ret []string) {
1307 for _, n := range new {
1308 for _, o := range old {
1313 ret = append(ret, n)
1318 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1320 for minNumTiers > len(ret) {
1321 ret = append(ret, nil)
1326 func (t *Torrent) addTrackers(announceList [][]string) {
1327 fullAnnounceList := &t.metainfo.AnnounceList
1328 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1329 for tierIndex, trackerURLs := range announceList {
1330 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1332 t.startMissingTrackerScrapers()
1333 t.updateWantPeersEvent()
1336 // Don't call this before the info is available.
1337 func (t *Torrent) bytesCompleted() int64 {
1341 return *t.length - t.bytesLeft()
1344 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1347 return t.setInfoBytesLocked(b)
1350 // Returns true if connection is removed from torrent.Conns.
1351 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1352 if !c.closed.IsSet() {
1353 panic("connection is not closed")
1354 // There are behaviours prevented by the closed state that will fail
1355 // if the connection has been deleted.
1359 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1360 // the drop event against the PexConnState instead.
1362 if !t.cl.config.DisablePEX {
1366 torrent.Add("deleted connections", 1)
1367 c.deleteAllRequests()
1368 t.assertPendingRequests()
1372 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1376 p.newPeerPieces().Iterate(func(i uint32) bool {
1377 p.t.decPieceAvailability(pieceIndex(i))
1382 func (t *Torrent) assertPendingRequests() {
1386 var actual pendingRequests
1388 actual.m = make([]int, t.numRequests())
1390 t.iterPeers(func(p *Peer) {
1391 p.actualRequestState.Requests.Iterate(func(x uint32) bool {
1396 diff := cmp.Diff(actual.m, t.pendingRequests.m)
1402 func (t *Torrent) dropConnection(c *PeerConn) {
1403 t.cl.event.Broadcast()
1405 if t.deletePeerConn(c) {
1410 func (t *Torrent) wantPeers() bool {
1411 if t.closed.IsSet() {
1414 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1417 return t.needData() || t.seeding()
1420 func (t *Torrent) updateWantPeersEvent() {
1422 t.wantPeersEvent.Set()
1424 t.wantPeersEvent.Clear()
1428 // Returns whether the client should make effort to seed the torrent.
1429 func (t *Torrent) seeding() bool {
1431 if t.closed.IsSet() {
1434 if t.dataUploadDisallowed {
1437 if cl.config.NoUpload {
1440 if !cl.config.Seed {
1443 if cl.config.DisableAggressiveUpload && t.needData() {
1449 func (t *Torrent) onWebRtcConn(
1450 c datachannel.ReadWriteCloser,
1451 dcc webtorrent.DataChannelContext,
1454 pc, err := t.cl.initiateProtocolHandshakes(
1455 context.Background(),
1456 webrtcNetConn{c, dcc},
1460 webrtcNetAddr{dcc.Remote},
1462 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1465 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1468 if dcc.LocalOffered {
1469 pc.Discovery = PeerSourceTracker
1471 pc.Discovery = PeerSourceIncoming
1475 err = t.cl.runHandshookConn(pc, t)
1477 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1481 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1482 err := t.cl.runHandshookConn(pc, t)
1483 if err != nil || logAll {
1484 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1488 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1489 t.logRunHandshookConn(pc, false, log.Debug)
1492 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1493 wtc, release := t.cl.websocketTrackers.Get(u.String())
1498 wst := websocketTrackerStatus{u, wtc}
1500 err := wtc.Announce(tracker.Started, t.infoHash)
1502 t.logger.WithDefaultLevel(log.Warning).Printf(
1503 "error in initial announce to %q: %v",
1512 func (t *Torrent) startScrapingTracker(_url string) {
1516 u, err := url.Parse(_url)
1518 // URLs with a leading '*' appear to be a uTorrent convention to
1519 // disable trackers.
1521 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1525 if u.Scheme == "udp" {
1527 t.startScrapingTracker(u.String())
1529 t.startScrapingTracker(u.String())
1532 if _, ok := t.trackerAnnouncers[_url]; ok {
1535 sl := func() torrentTrackerAnnouncer {
1538 if t.cl.config.DisableWebtorrent {
1541 return t.startWebsocketAnnouncer(*u)
1543 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1547 if t.cl.config.DisableIPv6 {
1551 newAnnouncer := &trackerScraper{
1554 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1556 go newAnnouncer.Run()
1562 if t.trackerAnnouncers == nil {
1563 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1565 t.trackerAnnouncers[_url] = sl
1568 // Adds and starts tracker scrapers for tracker URLs that aren't already
1570 func (t *Torrent) startMissingTrackerScrapers() {
1571 if t.cl.config.DisableTrackers {
1574 t.startScrapingTracker(t.metainfo.Announce)
1575 for _, tier := range t.metainfo.AnnounceList {
1576 for _, url := range tier {
1577 t.startScrapingTracker(url)
1582 // Returns an AnnounceRequest with fields filled out to defaults and current
1584 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1585 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1586 // dependent on the network in use.
1587 return tracker.AnnounceRequest{
1589 NumWant: func() int32 {
1590 if t.wantPeers() && len(t.cl.dialers) > 0 {
1596 Port: uint16(t.cl.incomingPeerPort()),
1597 PeerId: t.cl.peerID,
1598 InfoHash: t.infoHash,
1599 Key: t.cl.announceKey(),
1601 // The following are vaguely described in BEP 3.
1603 Left: t.bytesLeftAnnounce(),
1604 Uploaded: t.stats.BytesWrittenData.Int64(),
1605 // There's no mention of wasted or unwanted download in the BEP.
1606 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1610 // Adds peers revealed in an announce until the announce ends, or we have
1612 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1614 for v := range pvs {
1617 for _, cp := range v.Peers {
1619 // Can't do anything with this.
1622 if t.addPeer(PeerInfo{
1623 Addr: ipPortAddr{cp.IP, cp.Port},
1624 Source: PeerSourceDhtGetPeers,
1631 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1636 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1637 // announce ends. stop will force the announce to end.
1638 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1639 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1643 _done := make(chan struct{})
1647 t.consumeDhtAnnouncePeers(ps.Peers())
1653 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1654 _, stop, err := t.AnnounceToDht(s)
1659 case <-t.closed.Done():
1660 case <-time.After(5 * time.Minute):
1666 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1672 if t.closed.IsSet() {
1678 // TODO: Determine if there's a listener on the port we're announcing.
1679 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1690 err := t.timeboxedAnnounceToDht(s)
1692 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1698 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1699 for _, p := range peers {
1707 // The returned TorrentStats may require alignment in memory. See
1708 // https://github.com/anacrolix/torrent/issues/383.
1709 func (t *Torrent) Stats() TorrentStats {
1711 defer t.cl.rUnlock()
1712 return t.statsLocked()
1715 func (t *Torrent) statsLocked() (ret TorrentStats) {
1716 ret.ActivePeers = len(t.conns)
1717 ret.HalfOpenPeers = len(t.halfOpen)
1718 ret.PendingPeers = t.peers.Len()
1719 ret.TotalPeers = t.numTotalPeers()
1720 ret.ConnectedSeeders = 0
1721 for c := range t.conns {
1722 if all, ok := c.peerHasAllPieces(); all && ok {
1723 ret.ConnectedSeeders++
1726 ret.ConnStats = t.stats.Copy()
1727 ret.PiecesComplete = t.numPiecesCompleted()
1731 // The total number of peers in the torrent.
1732 func (t *Torrent) numTotalPeers() int {
1733 peers := make(map[string]struct{})
1734 for conn := range t.conns {
1735 ra := conn.conn.RemoteAddr()
1737 // It's been closed and doesn't support RemoteAddr.
1740 peers[ra.String()] = struct{}{}
1742 for addr := range t.halfOpen {
1743 peers[addr] = struct{}{}
1745 t.peers.Each(func(peer PeerInfo) {
1746 peers[peer.Addr.String()] = struct{}{}
1751 // Reconcile bytes transferred before connection was associated with a
1753 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1754 if c._stats != (ConnStats{
1755 // Handshakes should only increment these fields:
1756 BytesWritten: c._stats.BytesWritten,
1757 BytesRead: c._stats.BytesRead,
1761 c.postHandshakeStats(func(cs *ConnStats) {
1762 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1763 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1765 c.reconciledHandshakeStats = true
1768 // Returns true if the connection is added.
1769 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1772 torrent.Add("added connections", 1)
1775 if t.closed.IsSet() {
1776 return errors.New("torrent closed")
1778 for c0 := range t.conns {
1779 if c.PeerID != c0.PeerID {
1782 if !t.cl.config.DropDuplicatePeerIds {
1785 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1787 t.deletePeerConn(c0)
1789 return errors.New("existing connection preferred")
1792 if len(t.conns) >= t.maxEstablishedConns {
1793 c := t.worstBadConn()
1795 return errors.New("don't want conns")
1800 if len(t.conns) >= t.maxEstablishedConns {
1803 t.conns[c] = struct{}{}
1804 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1805 t.pex.Add(c) // as no further extended handshake expected
1810 func (t *Torrent) wantConns() bool {
1811 if !t.networkingEnabled.Bool() {
1814 if t.closed.IsSet() {
1817 if !t.seeding() && !t.needData() {
1820 if len(t.conns) < t.maxEstablishedConns {
1823 return t.worstBadConn() != nil
1826 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1829 oldMax = t.maxEstablishedConns
1830 t.maxEstablishedConns = max
1831 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1832 return worseConn(&l.Peer, &r.Peer)
1834 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1835 t.dropConnection(wcs.Pop().(*PeerConn))
1841 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1842 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1845 t.cl.event.Broadcast()
1846 if t.closed.IsSet() {
1850 // Don't score the first time a piece is hashed, it could be an initial check.
1851 if p.storageCompletionOk {
1853 pieceHashedCorrect.Add(1)
1856 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1857 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1858 pieceHashedNotCorrect.Add(1)
1863 t.publishPieceChange(piece)
1866 t.publishPieceChange(piece)
1870 if len(p.dirtiers) != 0 {
1871 // Don't increment stats above connection-level for every involved connection.
1872 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1874 for c := range p.dirtiers {
1875 c._stats.incrementPiecesDirtiedGood()
1877 t.clearPieceTouchers(piece)
1879 err := p.Storage().MarkComplete()
1881 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1885 if t.closed.IsSet() {
1888 t.pendAllChunkSpecs(piece)
1890 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1891 // Peers contributed to all the data for this piece hash failure, and the failure was
1892 // not due to errors in the storage (such as data being dropped in a cache).
1894 // Increment Torrent and above stats, and then specific connections.
1895 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1896 for c := range p.dirtiers {
1897 // Y u do dis peer?!
1898 c.stats().incrementPiecesDirtiedBad()
1901 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1902 for c := range p.dirtiers {
1904 bannableTouchers = append(bannableTouchers, c)
1907 t.clearPieceTouchers(piece)
1908 slices.Sort(bannableTouchers, connLessTrusted)
1910 if t.cl.config.Debug {
1912 "bannable conns by trust for piece %d: %v",
1914 func() (ret []connectionTrust) {
1915 for _, c := range bannableTouchers {
1916 ret = append(ret, c.trust())
1923 if len(bannableTouchers) >= 1 {
1924 c := bannableTouchers[0]
1925 t.cl.banPeerIP(c.remoteIp())
1929 t.onIncompletePiece(piece)
1930 p.Storage().MarkNotComplete()
1932 t.updatePieceCompletion(piece)
1935 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1936 // TODO: Make faster
1937 for cn := range t.conns {
1942 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1943 t.pendAllChunkSpecs(piece)
1944 t.cancelRequestsForPiece(piece)
1945 t.piece(piece).readerCond.Broadcast()
1946 for conn := range t.conns {
1948 t.maybeDropMutuallyCompletePeer(&conn.Peer)
1952 // Called when a piece is found to be not complete.
1953 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1954 if t.pieceAllDirty(piece) {
1955 t.pendAllChunkSpecs(piece)
1957 if !t.wantPieceIndex(piece) {
1958 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1961 // We could drop any connections that we told we have a piece that we
1962 // don't here. But there's a test failure, and it seems clients don't care
1963 // if you request pieces that you already claim to have. Pruning bad
1964 // connections might just remove any connections that aren't treating us
1965 // favourably anyway.
1967 // for c := range t.conns {
1968 // if c.sentHave(piece) {
1972 t.iterPeers(func(conn *Peer) {
1973 if conn.peerHasPiece(piece) {
1974 conn.updateRequests("piece incomplete")
1979 func (t *Torrent) tryCreateMorePieceHashers() {
1980 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1984 func (t *Torrent) tryCreatePieceHasher() bool {
1985 if t.storage == nil {
1988 pi, ok := t.getPieceToHash()
1993 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
1995 t.publishPieceChange(pi)
1996 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
1997 t.storageLock.RLock()
1998 t.activePieceHashes++
1999 go t.pieceHasher(pi)
2003 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2004 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2005 if t.piece(i).hashing {
2015 func (t *Torrent) pieceHasher(index pieceIndex) {
2017 sum, copyErr := t.hashPiece(index)
2018 correct := sum == *p.hash
2022 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2024 t.storageLock.RUnlock()
2028 t.pieceHashed(index, correct, copyErr)
2029 t.updatePiecePriority(index, "Torrent.pieceHasher")
2030 t.activePieceHashes--
2031 t.tryCreateMorePieceHashers()
2034 // Return the connections that touched a piece, and clear the entries while doing it.
2035 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2037 for c := range p.dirtiers {
2038 delete(c.peerTouchedPieces, pi)
2039 delete(p.dirtiers, c)
2043 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2044 t.iterPeers(func(p *Peer) {
2045 ret = append(ret, p)
2050 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2051 piece := t.piece(pieceIndex)
2052 if piece.queuedForHash() {
2055 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2056 t.publishPieceChange(pieceIndex)
2057 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2058 t.tryCreateMorePieceHashers()
2061 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2062 // before the Info is available.
2063 func (t *Torrent) VerifyData() {
2064 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2065 t.Piece(i).VerifyData()
2069 // Start the process of connecting to the given peer for the given torrent if appropriate.
2070 func (t *Torrent) initiateConn(peer PeerInfo) {
2071 if peer.Id == t.cl.peerID {
2074 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2078 if t.addrActive(addr.String()) {
2082 t.halfOpen[addr.String()] = peer
2083 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2086 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2087 // quickly make one Client visible to the Torrent of another Client.
2088 func (t *Torrent) AddClientPeer(cl *Client) int {
2089 return t.AddPeers(func() (ps []PeerInfo) {
2090 for _, la := range cl.ListenAddrs() {
2091 ps = append(ps, PeerInfo{
2100 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2102 func (t *Torrent) allStats(f func(*ConnStats)) {
2107 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2108 return t.pieces[i].hashing
2111 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2112 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2115 func (t *Torrent) dialTimeout() time.Duration {
2116 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2119 func (t *Torrent) piece(i int) *Piece {
2123 func (t *Torrent) onWriteChunkErr(err error) {
2124 if t.userOnWriteChunkErr != nil {
2125 go t.userOnWriteChunkErr(err)
2128 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2129 t.disallowDataDownloadLocked()
2132 func (t *Torrent) DisallowDataDownload() {
2133 t.disallowDataDownloadLocked()
2136 func (t *Torrent) disallowDataDownloadLocked() {
2137 t.dataDownloadDisallowed.Set()
2140 func (t *Torrent) AllowDataDownload() {
2141 t.dataDownloadDisallowed.Clear()
2144 // Enables uploading data, if it was disabled.
2145 func (t *Torrent) AllowDataUpload() {
2148 t.dataUploadDisallowed = false
2149 for c := range t.conns {
2150 c.updateRequests("allow data upload")
2154 // Disables uploading data, if it was enabled.
2155 func (t *Torrent) DisallowDataUpload() {
2158 t.dataUploadDisallowed = true
2159 for c := range t.conns {
2160 c.updateRequests("disallow data upload")
2164 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2165 // or if nil, a critical message is logged, and data download is disabled.
2166 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2169 t.userOnWriteChunkErr = f
2172 func (t *Torrent) iterPeers(f func(p *Peer)) {
2173 for pc := range t.conns {
2176 for _, ws := range t.webSeeds {
2181 func (t *Torrent) callbacks() *Callbacks {
2182 return &t.cl.config.Callbacks
2185 var WebseedHttpClient = &http.Client{
2186 Transport: &http.Transport{
2187 MaxConnsPerHost: 10,
2191 func (t *Torrent) addWebSeed(url string) {
2192 if t.cl.config.DisableWebseeds {
2195 if _, ok := t.webSeeds[url]; ok {
2198 const maxRequests = 10
2204 reconciledHandshakeStats: true,
2205 // TODO: Raise this limit, and instead limit concurrent fetches.
2206 PeerMaxRequests: 32,
2207 RemoteAddr: remoteAddrFromUrl(url),
2208 callbacks: t.callbacks(),
2210 client: webseed.Client{
2211 // Consider a MaxConnsPerHost in the transport for this, possibly in a global Client.
2212 HttpClient: WebseedHttpClient,
2215 activeRequests: make(map[Request]webseed.Request, maxRequests),
2216 maxRequests: maxRequests,
2218 ws.peer.initUpdateRequestsTimer()
2219 ws.requesterCond.L = t.cl.locker()
2220 for i := 0; i < maxRequests; i += 1 {
2223 for _, f := range t.callbacks().NewPeer {
2226 ws.peer.logger = t.logger.WithContextValue(&ws)
2227 ws.peer.peerImpl = &ws
2229 ws.onGotInfo(t.info)
2231 t.webSeeds[url] = &ws.peer
2232 ws.peer.onPeerHasAllPieces()
2235 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2236 t.iterPeers(func(p1 *Peer) {
2244 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2245 index := ri / t.chunksPerRegularPiece()
2248 t.piece(int(index)).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2252 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2253 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + uint32(r.Begin/t.chunkSize)
2256 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2257 return RequestIndex(piece) * t.chunksPerRegularPiece()
2260 func (t *Torrent) updateComplete() {
2261 t.Complete.SetBool(t.haveAllPieces())