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/generics"
24 "github.com/anacrolix/log"
25 "github.com/anacrolix/missinggo/perf"
26 "github.com/anacrolix/missinggo/slices"
27 "github.com/anacrolix/missinggo/v2"
28 "github.com/anacrolix/missinggo/v2/bitmap"
29 "github.com/anacrolix/missinggo/v2/pubsub"
30 "github.com/anacrolix/multiless"
31 "github.com/anacrolix/sync"
32 "github.com/davecgh/go-spew/spew"
34 "github.com/anacrolix/torrent/bencode"
35 "github.com/anacrolix/torrent/common"
36 "github.com/anacrolix/torrent/metainfo"
37 pp "github.com/anacrolix/torrent/peer_protocol"
38 request_strategy "github.com/anacrolix/torrent/request-strategy"
39 "github.com/anacrolix/torrent/segments"
40 "github.com/anacrolix/torrent/storage"
41 "github.com/anacrolix/torrent/tracker"
42 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
43 "github.com/anacrolix/torrent/webseed"
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
62 infoHash metainfo.Hash
65 // The order pieces are requested if there's no stronger reason like availability or priority.
66 pieceRequestOrder []int
67 // Values are the piece indices that changed.
68 pieceStateChanges pubsub.PubSub[PieceStateChange]
69 // The size of chunks to request from peers over the wire. This is
70 // normally 16KiB by convention these days.
73 // Total length of the torrent in bytes. Stored because it's not O(1) to
74 // get this from the info dict.
77 // The storage to open when the info dict becomes available.
78 storageOpener *storage.Client
79 // Storage for torrent data.
80 storage *storage.Torrent
81 // Read-locked for using storage, and write-locked for Closing.
82 storageLock sync.RWMutex
84 // TODO: Only announce stuff is used?
85 metainfo metainfo.MetaInfo
87 // The info dict. nil if we don't have it (yet).
89 fileIndex segments.Index
92 _chunksPerRegularPiece chunkIndexType
94 webSeeds map[string]*Peer
95 // Active peer connections, running message stream loops. TODO: Make this
96 // open (not-closed) connections only.
97 conns map[*PeerConn]struct{}
98 maxEstablishedConns int
99 // Set of addrs to which we're attempting to connect. Connections are
100 // half-open until all handshakes are completed.
101 halfOpen map[string]PeerInfo
103 // Reserve of peers to connect to. A peer can be both here and in the
104 // active connections if were told about the peer after connecting with
105 // them. That encourages us to reconnect to peers that are well known in
107 peers prioritizedPeers
108 // Whether we want to know to know more peers.
109 wantPeersEvent missinggo.Event
110 // An announcer for each tracker URL.
111 trackerAnnouncers map[string]torrentTrackerAnnouncer
112 // How many times we've initiated a DHT announce. TODO: Move into stats.
115 // Name used if the info name isn't available. Should be cleared when the
116 // Info does become available.
120 // The bencoded bytes of the info dict. This is actively manipulated if
121 // the info bytes aren't initially available, and we try to fetch them
124 // Each element corresponds to the 16KiB metadata pieces. If true, we have
125 // received that piece.
126 metadataCompletedChunks []bool
127 metadataChanged sync.Cond
129 // Closed when .Info is obtained.
130 gotMetainfoC chan struct{}
132 readers map[*reader]struct{}
133 _readerNowPieces bitmap.Bitmap
134 _readerReadaheadPieces bitmap.Bitmap
136 // A cache of pieces we need to get. Calculated from various piece and
137 // file priorities and completion states elsewhere.
138 _pendingPieces roaring.Bitmap
139 // A cache of completed piece indices.
140 _completedPieces roaring.Bitmap
141 // Pieces that need to be hashed.
142 piecesQueuedForHash bitmap.Bitmap
143 activePieceHashes int
144 initialPieceCheckDisabled bool
146 connsWithAllPieces map[*Peer]struct{}
148 requestState map[RequestIndex]requestState
149 // Chunks we've written to since the corresponding piece was last checked.
150 dirtyChunks typedRoaring.Bitmap[RequestIndex]
154 // Is On when all pieces are complete.
155 Complete chansync.Flag
157 // Torrent sources in use keyed by the source string.
158 activeSources sync.Map
159 sourcesLogger log.Logger
161 smartBanCache smartBanCache
163 // Large allocations reused between request state updates.
164 requestPieceStates []request_strategy.PieceRequestOrderState
165 requestIndexes []RequestIndex
168 func (t *Torrent) length() int64 {
169 return t._length.Value
172 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
173 // This could be done with roaring.BitSliceIndexing.
174 t.iterPeers(func(peer *Peer) {
175 if _, ok := t.connsWithAllPieces[peer]; ok {
178 if peer.peerHasPiece(i) {
185 func (t *Torrent) decPieceAvailability(i pieceIndex) {
190 if p.relativeAvailability <= 0 {
191 panic(p.relativeAvailability)
193 p.relativeAvailability--
194 t.updatePieceRequestOrder(i)
197 func (t *Torrent) incPieceAvailability(i pieceIndex) {
198 // If we don't the info, this should be reconciled when we do.
201 p.relativeAvailability++
202 t.updatePieceRequestOrder(i)
206 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
207 return t._readerNowPieces
210 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
211 return t._readerReadaheadPieces
214 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
215 return !t.wantPieceIndex(i)
218 // Returns a channel that is closed when the Torrent is closed.
219 func (t *Torrent) Closed() events.Done {
220 return t.closed.Done()
223 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
224 // pending, and half-open peers.
225 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
226 // Add pending peers to the list
227 t.peers.Each(func(peer PeerInfo) {
228 ks = append(ks, peer)
231 // Add half-open peers to the list
232 for _, peer := range t.halfOpen {
233 ks = append(ks, peer)
236 // Add active peers to the list
237 for conn := range t.conns {
238 ks = append(ks, PeerInfo{
240 Addr: conn.RemoteAddr,
241 Source: conn.Discovery,
242 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
243 // > But if we're not connected to them with an encrypted connection, I couldn't say
244 // > what's appropriate. We can carry forward the SupportsEncryption value as we
245 // > received it from trackers/DHT/PEX, or just use the encryption state for the
246 // > connection. It's probably easiest to do the latter for now.
247 // https://github.com/anacrolix/torrent/pull/188
248 SupportsEncryption: conn.headerEncrypted,
255 func (t *Torrent) setChunkSize(size pp.Integer) {
257 t.chunkPool = sync.Pool{
258 New: func() interface{} {
259 b := make([]byte, size)
265 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
266 return t._completedPieces.Contains(bitmap.BitIndex(piece))
269 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
270 if t.storage == nil {
271 return storage.Completion{Complete: false, Ok: true}
273 return t.pieces[piece].Storage().Completion()
276 // There's a connection to that address already.
277 func (t *Torrent) addrActive(addr string) bool {
278 if _, ok := t.halfOpen[addr]; ok {
281 for c := range t.conns {
283 if ra.String() == addr {
290 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
291 return t.appendConns(ret, func(conn *PeerConn) bool {
292 return !conn.closed.IsSet()
296 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
297 for c := range t.conns {
305 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
307 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
308 if t.closed.IsSet() {
311 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
312 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
313 torrent.Add("peers not added because of bad addr", 1)
314 // cl.logger.Printf("peers not added because of bad addr: %v", p)
318 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
319 torrent.Add("peers replaced", 1)
320 if !replaced.equal(p) {
321 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
328 for t.peers.Len() > cl.config.TorrentPeersHighWater {
329 _, ok := t.peers.DeleteMin()
331 torrent.Add("excess reserve peers discarded", 1)
337 func (t *Torrent) invalidateMetadata() {
338 for i := 0; i < len(t.metadataCompletedChunks); i++ {
339 t.metadataCompletedChunks[i] = false
342 t.gotMetainfoC = make(chan struct{})
347 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
351 if index >= len(t.metadataCompletedChunks) {
352 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
355 copy(t.metadataBytes[(1<<14)*index:], data)
356 t.metadataCompletedChunks[index] = true
359 func (t *Torrent) metadataPieceCount() int {
360 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
363 func (t *Torrent) haveMetadataPiece(piece int) bool {
365 return (1<<14)*piece < len(t.metadataBytes)
367 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
371 func (t *Torrent) metadataSize() int {
372 return len(t.metadataBytes)
375 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
376 for i := 0; i < len(info.Pieces); i += sha1.Size {
377 ret = append(ret, info.Pieces[i:i+sha1.Size])
382 func (t *Torrent) makePieces() {
383 hashes := infoPieceHashes(t.info)
384 t.pieces = make([]Piece, len(hashes))
385 for i, hash := range hashes {
386 piece := &t.pieces[i]
388 piece.index = pieceIndex(i)
389 piece.noPendingWrites.L = &piece.pendingWritesMutex
390 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
392 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
393 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
394 piece.files = files[beginFile:endFile]
398 // Returns the index of the first file containing the piece. files must be
399 // ordered by offset.
400 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
401 for i, f := range files {
402 if f.offset+f.length > pieceOffset {
409 // Returns the index after the last file containing the piece. files must be
410 // ordered by offset.
411 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
412 for i, f := range files {
413 if f.offset+f.length >= pieceEndOffset {
420 func (t *Torrent) cacheLength() {
422 for _, f := range t.info.UpvertedFiles() {
428 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
430 func (t *Torrent) setInfo(info *metainfo.Info) error {
431 if err := validateInfo(info); err != nil {
432 return fmt.Errorf("bad info: %s", err)
434 if t.storageOpener != nil {
436 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
438 return fmt.Errorf("error opening torrent storage: %s", err)
444 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
446 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
447 t.displayName = "" // Save a few bytes lol.
454 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
455 return request_strategy.PieceRequestOrderKey{
456 InfoHash: t.infoHash,
461 // This seems to be all the follow-up tasks after info is set, that can't fail.
462 func (t *Torrent) onSetInfo() {
463 t.pieceRequestOrder = rand.Perm(t.numPieces())
464 t.initPieceRequestOrder()
465 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
466 for i := range t.pieces {
468 // Need to add relativeAvailability before updating piece completion, as that may result in conns
470 if p.relativeAvailability != 0 {
471 panic(p.relativeAvailability)
473 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
474 t.addRequestOrderPiece(i)
475 t.updatePieceCompletion(i)
476 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
477 // t.logger.Printf("piece %s completion unknown, queueing check", p)
481 t.cl.event.Broadcast()
482 close(t.gotMetainfoC)
483 t.updateWantPeersEvent()
484 t.requestState = make(map[RequestIndex]requestState)
485 t.tryCreateMorePieceHashers()
486 t.iterPeers(func(p *Peer) {
488 p.updateRequests("onSetInfo")
492 // Called when metadata for a torrent becomes available.
493 func (t *Torrent) setInfoBytesLocked(b []byte) error {
494 if metainfo.HashBytes(b) != t.infoHash {
495 return errors.New("info bytes have wrong hash")
497 var info metainfo.Info
498 if err := bencode.Unmarshal(b, &info); err != nil {
499 return fmt.Errorf("error unmarshalling info bytes: %s", err)
502 t.metadataCompletedChunks = nil
506 if err := t.setInfo(&info); err != nil {
513 func (t *Torrent) haveAllMetadataPieces() bool {
517 if t.metadataCompletedChunks == nil {
520 for _, have := range t.metadataCompletedChunks {
528 // TODO: Propagate errors to disconnect peer.
529 func (t *Torrent) setMetadataSize(size int) (err error) {
531 // We already know the correct metadata size.
534 if uint32(size) > maxMetadataSize {
535 return log.WithLevel(log.Warning, errors.New("bad size"))
537 if len(t.metadataBytes) == size {
540 t.metadataBytes = make([]byte, size)
541 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
542 t.metadataChanged.Broadcast()
543 for c := range t.conns {
544 c.requestPendingMetadata()
549 // The current working name for the torrent. Either the name in the info dict,
550 // or a display name given such as by the dn value in a magnet link, or "".
551 func (t *Torrent) name() string {
553 defer t.nameMu.RUnlock()
555 return t.info.BestName()
557 if t.displayName != "" {
560 return "infohash:" + t.infoHash.HexString()
563 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
564 p := &t.pieces[index]
565 ret.Priority = t.piecePriority(index)
566 ret.Completion = p.completion()
567 ret.QueuedForHash = p.queuedForHash()
568 ret.Hashing = p.hashing
569 ret.Checking = ret.QueuedForHash || ret.Hashing
570 ret.Marking = p.marking
571 if !ret.Complete && t.piecePartiallyDownloaded(index) {
577 func (t *Torrent) metadataPieceSize(piece int) int {
578 return metadataPieceSize(len(t.metadataBytes), piece)
581 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
584 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
585 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
587 TotalSize: len(t.metadataBytes),
593 type pieceAvailabilityRun struct {
598 func (me pieceAvailabilityRun) String() string {
599 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
602 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
603 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
604 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
606 for i := range t.pieces {
607 rle.Append(t.pieces[i].availability(), 1)
613 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
614 freqs = make([]int, t.numActivePeers()+1)
615 for i := range t.pieces {
616 freqs[t.piece(i).availability()]++
621 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
622 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
623 ret = append(ret, PieceStateRun{
624 PieceState: el.(PieceState),
628 for index := range t.pieces {
629 rle.Append(t.pieceState(pieceIndex(index)), 1)
635 // Produces a small string representing a PieceStateRun.
636 func (psr PieceStateRun) String() (ret string) {
637 ret = fmt.Sprintf("%d", psr.Length)
638 ret += func() string {
639 switch psr.Priority {
640 case PiecePriorityNext:
642 case PiecePriorityNormal:
644 case PiecePriorityReadahead:
646 case PiecePriorityNow:
648 case PiecePriorityHigh:
657 if psr.QueuedForHash {
675 func (t *Torrent) writeStatus(w io.Writer) {
676 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
677 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
679 fmt.Fprintf(w, "Metadata have: ")
680 for _, h := range t.metadataCompletedChunks {
681 fmt.Fprintf(w, "%c", func() rune {
691 fmt.Fprintf(w, "Piece length: %s\n",
694 return fmt.Sprintf("%v (%v chunks)",
696 float64(t.usualPieceSize())/float64(t.chunkSize))
703 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
704 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
705 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
706 // availability frequencies instead.
708 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
709 for _, run := range t.pieceAvailabilityRuns() {
710 ret = append(ret, run.String())
715 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
716 func() (ret []string) {
717 for avail, freq := range t.pieceAvailabilityFrequencies() {
721 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
727 fmt.Fprintf(w, "Reader Pieces:")
728 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
729 fmt.Fprintf(w, " %d:%d", begin, end)
734 fmt.Fprintf(w, "Enabled trackers:\n")
736 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
737 fmt.Fprintf(tw, " URL\tExtra\n")
738 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
741 var luns, runs url.URL = *lu, *ru
744 var ml missinggo.MultiLess
745 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
746 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
748 }).([]torrentTrackerAnnouncer) {
749 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
754 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
756 spew.NewDefaultConfig()
757 spew.Fdump(w, t.statsLocked())
759 peers := t.peersAsSlice()
760 sort.Slice(peers, func(_i, _j int) bool {
763 if less, ok := multiless.New().EagerSameLess(
764 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
768 return worseConn(i, j)
771 for i, c := range peers {
772 fmt.Fprintf(w, "%2d. ", i+1)
774 c.writeStatus(&buf, t)
775 w.Write(bytes.TrimRight(
776 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
781 func (t *Torrent) haveInfo() bool {
785 // Returns a run-time generated MetaInfo that includes the info bytes and
786 // announce-list as currently known to the client.
787 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
788 return metainfo.MetaInfo{
789 CreationDate: time.Now().Unix(),
790 Comment: "dynamic metainfo from client",
791 CreatedBy: "go.torrent",
792 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
793 InfoBytes: func() []byte {
795 return t.metadataBytes
800 UrlList: func() []string {
801 ret := make([]string, 0, len(t.webSeeds))
802 for url := range t.webSeeds {
803 ret = append(ret, url)
811 func (t *Torrent) BytesMissing() (n int64) {
813 n = t.bytesMissingLocked()
818 func (t *Torrent) bytesMissingLocked() int64 {
822 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
823 roaring.Flip(b, 0, end).Iterate(cb)
826 func (t *Torrent) bytesLeft() (left int64) {
827 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
828 p := t.piece(pieceIndex(x))
829 left += int64(p.length() - p.numDirtyBytes())
835 // Bytes left to give in tracker announces.
836 func (t *Torrent) bytesLeftAnnounce() int64 {
844 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
845 if t.pieceComplete(piece) {
848 if t.pieceAllDirty(piece) {
851 return t.pieces[piece].hasDirtyChunks()
854 func (t *Torrent) usualPieceSize() int {
855 return int(t.info.PieceLength)
858 func (t *Torrent) numPieces() pieceIndex {
859 return t.info.NumPieces()
862 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
863 return pieceIndex(t._completedPieces.GetCardinality())
866 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
868 err = errors.New("already closed")
871 for _, f := range t.onClose {
874 if t.storage != nil {
879 defer t.storageLock.Unlock()
880 if f := t.storage.Close; f != nil {
883 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
888 t.iterPeers(func(p *Peer) {
891 if t.storage != nil {
892 t.deletePieceRequestOrder()
894 for i := range t.pieces {
896 if p.relativeAvailability != 0 {
897 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
901 t.cl.event.Broadcast()
902 t.pieceStateChanges.Close()
903 t.updateWantPeersEvent()
907 func (t *Torrent) requestOffset(r Request) int64 {
908 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
911 // Return the request that would include the given offset into the torrent data. Returns !ok if
912 // there is no such request.
913 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
914 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
917 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
918 defer perf.ScopeTimerErr(&err)()
919 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
920 if err == nil && n != len(data) {
921 err = io.ErrShortWrite
926 func (t *Torrent) bitfield() (bf []bool) {
927 bf = make([]bool, t.numPieces())
928 t._completedPieces.Iterate(func(piece uint32) (again bool) {
935 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
936 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
939 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
940 return t._chunksPerRegularPiece
943 func (t *Torrent) numChunks() RequestIndex {
944 if t.numPieces() == 0 {
947 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
950 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
951 t.dirtyChunks.RemoveRange(
952 uint64(t.pieceRequestIndexOffset(pieceIndex)),
953 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
956 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
957 if t.info.PieceLength == 0 {
958 // There will be no variance amongst pieces. Only pain.
961 if piece == t.numPieces()-1 {
962 ret := pp.Integer(t.length() % t.info.PieceLength)
967 return pp.Integer(t.info.PieceLength)
970 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
971 return &blockCheckingWriter{
972 cache: &t.smartBanCache,
973 requestIndex: t.pieceRequestIndexOffset(piece),
974 chunkSize: t.chunkSize.Int(),
978 func (t *Torrent) hashPiece(piece pieceIndex) (
980 // These are peers that sent us blocks that differ from what we hash here.
981 differingPeers map[bannableAddr]struct{},
985 p.waitNoPendingWrites()
986 storagePiece := t.pieces[piece].Storage()
988 // Does the backend want to do its own hashing?
989 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
990 var sum metainfo.Hash
991 // log.Printf("A piece decided to self-hash: %d", piece)
992 sum, err = i.SelfHash()
993 missinggo.CopyExact(&ret, sum)
997 hash := pieceHash.New()
998 const logPieceContents = false
999 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1000 writers := []io.Writer{hash, smartBanWriter}
1001 var examineBuf bytes.Buffer
1002 if logPieceContents {
1003 writers = append(writers, &examineBuf)
1005 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1006 if logPieceContents {
1007 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1009 smartBanWriter.Flush()
1010 differingPeers = smartBanWriter.badPeers
1011 missinggo.CopyExact(&ret, hash.Sum(nil))
1015 func (t *Torrent) haveAnyPieces() bool {
1016 return !t._completedPieces.IsEmpty()
1019 func (t *Torrent) haveAllPieces() bool {
1023 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1026 func (t *Torrent) havePiece(index pieceIndex) bool {
1027 return t.haveInfo() && t.pieceComplete(index)
1030 func (t *Torrent) maybeDropMutuallyCompletePeer(
1031 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1035 if !t.cl.config.DropMutuallyCompletePeers {
1038 if !t.haveAllPieces() {
1041 if all, known := p.peerHasAllPieces(); !(known && all) {
1047 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1051 func (t *Torrent) haveChunk(r Request) (ret bool) {
1053 // log.Println("have chunk", r, ret)
1058 if t.pieceComplete(pieceIndex(r.Index)) {
1061 p := &t.pieces[r.Index]
1062 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1065 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1066 return chunkIndexType(cs.Begin / chunkSize)
1069 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1070 return t._pendingPieces.Contains(uint32(index))
1073 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1074 // conns (which is a map).
1075 var peerConnSlices sync.Pool
1077 func getPeerConnSlice(cap int) []*PeerConn {
1078 getInterface := peerConnSlices.Get()
1079 if getInterface == nil {
1080 return make([]*PeerConn, 0, cap)
1082 return getInterface.([]*PeerConn)[:0]
1086 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1087 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1088 // established connections for more than a minute. This is O(n log n). If there was a way to not
1089 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1090 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1091 wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
1092 defer peerConnSlices.Put(wcs.conns)
1095 for wcs.Len() != 0 {
1096 c := heap.Pop(&wcs).(*PeerConn)
1097 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1100 // If the connection is in the worst half of the established
1101 // connection quota and is older than a minute.
1102 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1103 // Give connections 1 minute to prove themselves.
1104 if time.Since(c.completedHandshake) > time.Minute {
1112 type PieceStateChange struct {
1117 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1118 t.cl._mu.Defer(func() {
1119 cur := t.pieceState(piece)
1120 p := &t.pieces[piece]
1121 if cur != p.publicPieceState {
1122 p.publicPieceState = cur
1123 t.pieceStateChanges.Publish(PieceStateChange{
1131 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1132 if t.pieceComplete(piece) {
1135 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1138 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1139 return t.pieces[piece].allChunksDirty()
1142 func (t *Torrent) readersChanged() {
1143 t.updateReaderPieces()
1144 t.updateAllPiecePriorities("Torrent.readersChanged")
1147 func (t *Torrent) updateReaderPieces() {
1148 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1151 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1155 t.updateReaderPieces()
1156 // Order the ranges, high and low.
1158 if l.begin > h.begin {
1161 if l.end < h.begin {
1162 // Two distinct ranges.
1163 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1164 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1171 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1175 func (t *Torrent) maybeNewConns() {
1176 // Tickle the accept routine.
1177 t.cl.event.Broadcast()
1181 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1182 if t._pendingPieces.Contains(uint32(piece)) {
1183 t.iterPeers(func(c *Peer) {
1184 // if c.requestState.Interested {
1187 if !c.isLowOnRequests() {
1190 if !c.peerHasPiece(piece) {
1193 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1196 c.updateRequests(reason)
1200 t.publishPieceChange(piece)
1203 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1204 if !t.closed.IsSet() {
1205 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1207 t.updatePieceRequestOrder(piece)
1209 p := &t.pieces[piece]
1210 newPrio := p.uncachedPriority()
1211 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1212 if newPrio == PiecePriorityNone {
1213 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1217 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1221 t.piecePriorityChanged(piece, reason)
1224 func (t *Torrent) updateAllPiecePriorities(reason string) {
1225 t.updatePiecePriorities(0, t.numPieces(), reason)
1228 // Update all piece priorities in one hit. This function should have the same
1229 // output as updatePiecePriority, but across all pieces.
1230 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1231 for i := begin; i < end; i++ {
1232 t.updatePiecePriority(i, reason)
1236 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1237 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1238 if off >= t.length() {
1248 begin = pieceIndex(off / t.info.PieceLength)
1249 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1250 if end > pieceIndex(t.info.NumPieces()) {
1251 end = pieceIndex(t.info.NumPieces())
1256 // Returns true if all iterations complete without breaking. Returns the read regions for all
1257 // readers. The reader regions should not be merged as some callers depend on this method to
1258 // enumerate readers.
1259 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1260 for r := range t.readers {
1262 if p.begin >= p.end {
1265 if !f(p.begin, p.end) {
1272 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1273 return t.piece(piece).uncachedPriority()
1276 func (t *Torrent) pendRequest(req RequestIndex) {
1277 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1280 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1281 t.cl.event.Broadcast()
1282 if t.pieceComplete(piece) {
1283 t.onPieceCompleted(piece)
1285 t.onIncompletePiece(piece)
1287 t.updatePiecePriority(piece, reason)
1290 func (t *Torrent) numReceivedConns() (ret int) {
1291 for c := range t.conns {
1292 if c.Discovery == PeerSourceIncoming {
1299 func (t *Torrent) maxHalfOpen() int {
1300 // Note that if we somehow exceed the maximum established conns, we want
1301 // the negative value to have an effect.
1302 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1303 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1304 // We want to allow some experimentation with new peers, and to try to
1305 // upset an oversupply of received connections.
1306 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1309 func (t *Torrent) openNewConns() (initiated int) {
1310 defer t.updateWantPeersEvent()
1311 for t.peers.Len() != 0 {
1315 if len(t.halfOpen) >= t.maxHalfOpen() {
1318 if len(t.cl.dialers) == 0 {
1321 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1324 p := t.peers.PopMax()
1331 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1333 uncached := t.pieceCompleteUncached(piece)
1334 cached := p.completion()
1335 changed := cached != uncached
1336 complete := uncached.Complete
1337 p.storageCompletionOk = uncached.Ok
1340 t._completedPieces.Add(x)
1343 t._completedPieces.Remove(x)
1345 p.t.updatePieceRequestOrder(piece)
1347 if complete && len(p.dirtiers) != 0 {
1348 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1351 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1352 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1357 // Non-blocking read. Client lock is not required.
1358 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1360 p := &t.pieces[off/t.info.PieceLength]
1361 p.waitNoPendingWrites()
1363 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1374 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1375 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1376 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1377 func (t *Torrent) maybeCompleteMetadata() error {
1382 if !t.haveAllMetadataPieces() {
1383 // Don't have enough metadata pieces.
1386 err := t.setInfoBytesLocked(t.metadataBytes)
1388 t.invalidateMetadata()
1389 return fmt.Errorf("error setting info bytes: %s", err)
1391 if t.cl.config.Debug {
1392 t.logger.Printf("%s: got metadata from peers", t)
1397 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1398 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1400 now.Add(bitmap.BitIndex(begin))
1401 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1408 func (t *Torrent) needData() bool {
1409 if t.closed.IsSet() {
1415 return !t._pendingPieces.IsEmpty()
1418 func appendMissingStrings(old, new []string) (ret []string) {
1421 for _, n := range new {
1422 for _, o := range old {
1427 ret = append(ret, n)
1432 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1434 for minNumTiers > len(ret) {
1435 ret = append(ret, nil)
1440 func (t *Torrent) addTrackers(announceList [][]string) {
1441 fullAnnounceList := &t.metainfo.AnnounceList
1442 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1443 for tierIndex, trackerURLs := range announceList {
1444 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1446 t.startMissingTrackerScrapers()
1447 t.updateWantPeersEvent()
1450 // Don't call this before the info is available.
1451 func (t *Torrent) bytesCompleted() int64 {
1455 return t.length() - t.bytesLeft()
1458 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1461 return t.setInfoBytesLocked(b)
1464 // Returns true if connection is removed from torrent.Conns.
1465 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1466 if !c.closed.IsSet() {
1467 panic("connection is not closed")
1468 // There are behaviours prevented by the closed state that will fail
1469 // if the connection has been deleted.
1473 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1474 // the drop event against the PexConnState instead.
1476 if !t.cl.config.DisablePEX {
1480 torrent.Add("deleted connections", 1)
1481 c.deleteAllRequests("Torrent.deletePeerConn")
1482 t.assertPendingRequests()
1483 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1484 panic(t.connsWithAllPieces)
1489 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1490 if t.deleteConnWithAllPieces(p) {
1496 p.peerPieces().Iterate(func(i uint32) bool {
1497 p.t.decPieceAvailability(pieceIndex(i))
1502 func (t *Torrent) assertPendingRequests() {
1506 // var actual pendingRequests
1507 // if t.haveInfo() {
1508 // actual.m = make([]int, t.numChunks())
1510 // t.iterPeers(func(p *Peer) {
1511 // p.requestState.Requests.Iterate(func(x uint32) bool {
1516 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1522 func (t *Torrent) dropConnection(c *PeerConn) {
1523 t.cl.event.Broadcast()
1525 if t.deletePeerConn(c) {
1530 // Peers as in contact information for dialing out.
1531 func (t *Torrent) wantPeers() bool {
1532 if t.closed.IsSet() {
1535 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1538 return t.wantConns()
1541 func (t *Torrent) updateWantPeersEvent() {
1543 t.wantPeersEvent.Set()
1545 t.wantPeersEvent.Clear()
1549 // Returns whether the client should make effort to seed the torrent.
1550 func (t *Torrent) seeding() bool {
1552 if t.closed.IsSet() {
1555 if t.dataUploadDisallowed {
1558 if cl.config.NoUpload {
1561 if !cl.config.Seed {
1564 if cl.config.DisableAggressiveUpload && t.needData() {
1570 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1571 err := t.cl.runHandshookConn(pc, t)
1572 if err != nil || logAll {
1573 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1577 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1578 t.logRunHandshookConn(pc, false, log.Debug)
1581 func (t *Torrent) startScrapingTracker(_url string) {
1585 u, err := url.Parse(_url)
1587 // URLs with a leading '*' appear to be a uTorrent convention to
1588 // disable trackers.
1590 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1594 if u.Scheme == "udp" {
1596 t.startScrapingTracker(u.String())
1598 t.startScrapingTracker(u.String())
1601 if _, ok := t.trackerAnnouncers[_url]; ok {
1604 sl := func() torrentTrackerAnnouncer {
1607 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1611 if t.cl.config.DisableIPv6 {
1615 newAnnouncer := &trackerScraper{
1618 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1620 go newAnnouncer.Run()
1626 if t.trackerAnnouncers == nil {
1627 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1629 t.trackerAnnouncers[_url] = sl
1632 // Adds and starts tracker scrapers for tracker URLs that aren't already
1634 func (t *Torrent) startMissingTrackerScrapers() {
1635 if t.cl.config.DisableTrackers {
1638 t.startScrapingTracker(t.metainfo.Announce)
1639 for _, tier := range t.metainfo.AnnounceList {
1640 for _, url := range tier {
1641 t.startScrapingTracker(url)
1646 // Returns an AnnounceRequest with fields filled out to defaults and current
1648 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1649 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1650 // dependent on the network in use.
1651 return tracker.AnnounceRequest{
1653 NumWant: func() int32 {
1654 if t.wantPeers() && len(t.cl.dialers) > 0 {
1655 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1660 Port: uint16(t.cl.incomingPeerPort()),
1661 PeerId: t.cl.peerID,
1662 InfoHash: t.infoHash,
1663 Key: t.cl.announceKey(),
1665 // The following are vaguely described in BEP 3.
1667 Left: t.bytesLeftAnnounce(),
1668 Uploaded: t.stats.BytesWrittenData.Int64(),
1669 // There's no mention of wasted or unwanted download in the BEP.
1670 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1674 // Adds peers revealed in an announce until the announce ends, or we have
1676 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1678 for v := range pvs {
1681 for _, cp := range v.Peers {
1683 // Can't do anything with this.
1686 if t.addPeer(PeerInfo{
1687 Addr: ipPortAddr{cp.IP, cp.Port},
1688 Source: PeerSourceDhtGetPeers,
1695 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1700 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1701 // announce ends. stop will force the announce to end.
1702 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1703 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1707 _done := make(chan struct{})
1711 t.consumeDhtAnnouncePeers(ps.Peers())
1717 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1718 _, stop, err := t.AnnounceToDht(s)
1723 case <-t.closed.Done():
1724 case <-time.After(5 * time.Minute):
1730 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1736 if t.closed.IsSet() {
1739 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1740 // TODO: We can include the announce_peer step depending on whether we can receive
1741 // inbound connections. We should probably only announce once every 15 mins too.
1745 // TODO: Determine if there's a listener on the port we're announcing.
1746 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1757 err := t.timeboxedAnnounceToDht(s)
1759 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1765 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1766 for _, p := range peers {
1774 // The returned TorrentStats may require alignment in memory. See
1775 // https://github.com/anacrolix/torrent/issues/383.
1776 func (t *Torrent) Stats() TorrentStats {
1778 defer t.cl.rUnlock()
1779 return t.statsLocked()
1782 func (t *Torrent) statsLocked() (ret TorrentStats) {
1783 ret.ActivePeers = len(t.conns)
1784 ret.HalfOpenPeers = len(t.halfOpen)
1785 ret.PendingPeers = t.peers.Len()
1786 ret.TotalPeers = t.numTotalPeers()
1787 ret.ConnectedSeeders = 0
1788 for c := range t.conns {
1789 if all, ok := c.peerHasAllPieces(); all && ok {
1790 ret.ConnectedSeeders++
1793 ret.ConnStats = t.stats.Copy()
1794 ret.PiecesComplete = t.numPiecesCompleted()
1798 // The total number of peers in the torrent.
1799 func (t *Torrent) numTotalPeers() int {
1800 peers := make(map[string]struct{})
1801 for conn := range t.conns {
1802 ra := conn.conn.RemoteAddr()
1804 // It's been closed and doesn't support RemoteAddr.
1807 peers[ra.String()] = struct{}{}
1809 for addr := range t.halfOpen {
1810 peers[addr] = struct{}{}
1812 t.peers.Each(func(peer PeerInfo) {
1813 peers[peer.Addr.String()] = struct{}{}
1818 // Reconcile bytes transferred before connection was associated with a
1820 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1821 if c._stats != (ConnStats{
1822 // Handshakes should only increment these fields:
1823 BytesWritten: c._stats.BytesWritten,
1824 BytesRead: c._stats.BytesRead,
1828 c.postHandshakeStats(func(cs *ConnStats) {
1829 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1830 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1832 c.reconciledHandshakeStats = true
1835 // Returns true if the connection is added.
1836 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1839 torrent.Add("added connections", 1)
1842 if t.closed.IsSet() {
1843 return errors.New("torrent closed")
1845 for c0 := range t.conns {
1846 if c.PeerID != c0.PeerID {
1849 if !t.cl.config.DropDuplicatePeerIds {
1852 if c.hasPreferredNetworkOver(c0) {
1854 t.deletePeerConn(c0)
1856 return errors.New("existing connection preferred")
1859 if len(t.conns) >= t.maxEstablishedConns {
1860 c := t.worstBadConn()
1862 return errors.New("don't want conns")
1867 if len(t.conns) >= t.maxEstablishedConns {
1870 t.conns[c] = struct{}{}
1871 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1872 t.pex.Add(c) // as no further extended handshake expected
1877 func (t *Torrent) wantConns() bool {
1878 if !t.networkingEnabled.Bool() {
1881 if t.closed.IsSet() {
1884 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
1887 return len(t.conns) < t.maxEstablishedConns || t.worstBadConn() != nil
1890 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1893 oldMax = t.maxEstablishedConns
1894 t.maxEstablishedConns = max
1895 wcs := worseConnSlice{
1896 conns: t.appendConns(nil, func(*PeerConn) bool {
1902 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1903 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
1909 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1910 t.logger.LazyLog(log.Debug, func() log.Msg {
1911 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
1915 t.cl.event.Broadcast()
1916 if t.closed.IsSet() {
1920 // Don't score the first time a piece is hashed, it could be an initial check.
1921 if p.storageCompletionOk {
1923 pieceHashedCorrect.Add(1)
1926 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1927 ).AddValues(t, p).LogLevel(
1929 log.Debug, t.logger)
1931 pieceHashedNotCorrect.Add(1)
1936 t.publishPieceChange(piece)
1939 t.publishPieceChange(piece)
1943 if len(p.dirtiers) != 0 {
1944 // Don't increment stats above connection-level for every involved connection.
1945 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1947 for c := range p.dirtiers {
1948 c._stats.incrementPiecesDirtiedGood()
1950 t.clearPieceTouchers(piece)
1951 hasDirty := p.hasDirtyChunks()
1954 p.Flush() // You can be synchronous here!
1956 err := p.Storage().MarkComplete()
1958 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1962 if t.closed.IsSet() {
1965 t.pendAllChunkSpecs(piece)
1967 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1968 // Peers contributed to all the data for this piece hash failure, and the failure was
1969 // not due to errors in the storage (such as data being dropped in a cache).
1971 // Increment Torrent and above stats, and then specific connections.
1972 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1973 for c := range p.dirtiers {
1974 // Y u do dis peer?!
1975 c.stats().incrementPiecesDirtiedBad()
1978 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1979 for c := range p.dirtiers {
1981 bannableTouchers = append(bannableTouchers, c)
1984 t.clearPieceTouchers(piece)
1985 slices.Sort(bannableTouchers, connLessTrusted)
1987 if t.cl.config.Debug {
1989 "bannable conns by trust for piece %d: %v",
1991 func() (ret []connectionTrust) {
1992 for _, c := range bannableTouchers {
1993 ret = append(ret, c.trust())
2000 if len(bannableTouchers) >= 1 {
2001 c := bannableTouchers[0]
2002 if len(bannableTouchers) != 1 {
2003 t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2005 // Turns out it's still useful to ban peers like this because if there's only a
2006 // single peer for a piece, and we never progress that piece to completion, we
2007 // will never smart-ban them. Discovered in
2008 // https://github.com/anacrolix/torrent/issues/715.
2009 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2014 t.onIncompletePiece(piece)
2015 p.Storage().MarkNotComplete()
2017 t.updatePieceCompletion(piece)
2020 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2021 start := t.pieceRequestIndexOffset(piece)
2022 end := start + t.pieceNumChunks(piece)
2023 for ri := start; ri < end; ri++ {
2028 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2029 t.pendAllChunkSpecs(piece)
2030 t.cancelRequestsForPiece(piece)
2031 t.piece(piece).readerCond.Broadcast()
2032 for conn := range t.conns {
2034 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2038 // Called when a piece is found to be not complete.
2039 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2040 if t.pieceAllDirty(piece) {
2041 t.pendAllChunkSpecs(piece)
2043 if !t.wantPieceIndex(piece) {
2044 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2047 // We could drop any connections that we told we have a piece that we
2048 // don't here. But there's a test failure, and it seems clients don't care
2049 // if you request pieces that you already claim to have. Pruning bad
2050 // connections might just remove any connections that aren't treating us
2051 // favourably anyway.
2053 // for c := range t.conns {
2054 // if c.sentHave(piece) {
2058 t.iterPeers(func(conn *Peer) {
2059 if conn.peerHasPiece(piece) {
2060 conn.updateRequests("piece incomplete")
2065 func (t *Torrent) tryCreateMorePieceHashers() {
2066 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2070 func (t *Torrent) tryCreatePieceHasher() bool {
2071 if t.storage == nil {
2074 pi, ok := t.getPieceToHash()
2079 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2081 t.publishPieceChange(pi)
2082 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2083 t.storageLock.RLock()
2084 t.activePieceHashes++
2085 go t.pieceHasher(pi)
2089 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2090 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2091 if t.piece(i).hashing {
2101 func (t *Torrent) dropBannedPeers() {
2102 t.iterPeers(func(p *Peer) {
2103 remoteIp := p.remoteIp()
2104 if remoteIp == nil {
2105 if p.bannableAddr.Ok {
2106 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2110 netipAddr := netip.MustParseAddr(remoteIp.String())
2111 if Some(netipAddr) != p.bannableAddr {
2112 t.logger.WithDefaultLevel(log.Debug).Printf(
2113 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2114 p, remoteIp, p.bannableAddr)
2116 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2117 // Should this be a close?
2119 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2124 func (t *Torrent) pieceHasher(index pieceIndex) {
2126 sum, failedPeers, copyErr := t.hashPiece(index)
2127 correct := sum == *p.hash
2131 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2133 t.storageLock.RUnlock()
2137 for peer := range failedPeers {
2138 t.cl.banPeerIP(peer.AsSlice())
2139 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2142 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2143 t.smartBanCache.ForgetBlock(ri)
2147 t.pieceHashed(index, correct, copyErr)
2148 t.updatePiecePriority(index, "Torrent.pieceHasher")
2149 t.activePieceHashes--
2150 t.tryCreateMorePieceHashers()
2153 // Return the connections that touched a piece, and clear the entries while doing it.
2154 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2156 for c := range p.dirtiers {
2157 delete(c.peerTouchedPieces, pi)
2158 delete(p.dirtiers, c)
2162 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2163 t.iterPeers(func(p *Peer) {
2164 ret = append(ret, p)
2169 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2170 piece := t.piece(pieceIndex)
2171 if piece.queuedForHash() {
2174 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2175 t.publishPieceChange(pieceIndex)
2176 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2177 t.tryCreateMorePieceHashers()
2180 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2181 // before the Info is available.
2182 func (t *Torrent) VerifyData() {
2183 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2184 t.Piece(i).VerifyData()
2188 // Start the process of connecting to the given peer for the given torrent if appropriate.
2189 func (t *Torrent) initiateConn(peer PeerInfo) {
2190 if peer.Id == t.cl.peerID {
2193 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2197 if t.addrActive(addr.String()) {
2201 t.halfOpen[addr.String()] = peer
2202 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2205 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2206 // quickly make one Client visible to the Torrent of another Client.
2207 func (t *Torrent) AddClientPeer(cl *Client) int {
2208 return t.AddPeers(func() (ps []PeerInfo) {
2209 for _, la := range cl.ListenAddrs() {
2210 ps = append(ps, PeerInfo{
2219 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2221 func (t *Torrent) allStats(f func(*ConnStats)) {
2226 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2227 return t.pieces[i].hashing
2230 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2231 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2234 func (t *Torrent) dialTimeout() time.Duration {
2235 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2238 func (t *Torrent) piece(i int) *Piece {
2242 func (t *Torrent) onWriteChunkErr(err error) {
2243 if t.userOnWriteChunkErr != nil {
2244 go t.userOnWriteChunkErr(err)
2247 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2248 t.disallowDataDownloadLocked()
2251 func (t *Torrent) DisallowDataDownload() {
2252 t.disallowDataDownloadLocked()
2255 func (t *Torrent) disallowDataDownloadLocked() {
2256 t.dataDownloadDisallowed.Set()
2259 func (t *Torrent) AllowDataDownload() {
2260 t.dataDownloadDisallowed.Clear()
2263 // Enables uploading data, if it was disabled.
2264 func (t *Torrent) AllowDataUpload() {
2267 t.dataUploadDisallowed = false
2268 for c := range t.conns {
2269 c.updateRequests("allow data upload")
2273 // Disables uploading data, if it was enabled.
2274 func (t *Torrent) DisallowDataUpload() {
2277 t.dataUploadDisallowed = true
2278 for c := range t.conns {
2279 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2280 c.updateRequests("disallow data upload")
2284 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2285 // or if nil, a critical message is logged, and data download is disabled.
2286 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2289 t.userOnWriteChunkErr = f
2292 func (t *Torrent) iterPeers(f func(p *Peer)) {
2293 for pc := range t.conns {
2296 for _, ws := range t.webSeeds {
2301 func (t *Torrent) callbacks() *Callbacks {
2302 return &t.cl.config.Callbacks
2305 type AddWebSeedsOpt func(*webseed.Client)
2307 // Sets the WebSeed trailing path escaper for a webseed.Client.
2308 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2309 return func(c *webseed.Client) {
2310 c.PathEscaper = custom
2314 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2317 for _, u := range urls {
2318 t.addWebSeed(u, opts...)
2322 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2323 if t.cl.config.DisableWebseeds {
2326 if _, ok := t.webSeeds[url]; ok {
2329 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2330 // right away. This value should be some multiple of the number of connections to a host. I
2331 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2332 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2333 // "https://webtorrent.io/torrents/".
2334 const maxRequests = 16
2340 reconciledHandshakeStats: true,
2341 // This should affect how often we have to recompute requests for this peer. Note that
2342 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2343 // requests mark more often, so recomputation is probably sooner than with regular peer
2344 // conns. ~4x maxRequests would be about right.
2345 PeerMaxRequests: 128,
2346 // TODO: Set ban prefix?
2347 RemoteAddr: remoteAddrFromUrl(url),
2348 callbacks: t.callbacks(),
2350 client: webseed.Client{
2351 HttpClient: t.cl.httpClient,
2353 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2354 return &rateLimitedReader{
2355 l: t.cl.config.DownloadRateLimiter,
2360 activeRequests: make(map[Request]webseed.Request, maxRequests),
2362 ws.peer.initRequestState()
2363 for _, opt := range opts {
2366 ws.peer.initUpdateRequestsTimer()
2367 ws.requesterCond.L = t.cl.locker()
2368 for i := 0; i < maxRequests; i += 1 {
2371 for _, f := range t.callbacks().NewPeer {
2374 ws.peer.logger = t.logger.WithContextValue(&ws)
2375 ws.peer.peerImpl = &ws
2377 ws.onGotInfo(t.info)
2379 t.webSeeds[url] = &ws.peer
2382 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2383 t.iterPeers(func(p1 *Peer) {
2391 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2392 index := t.pieceIndexOfRequestIndex(ri)
2395 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2399 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2400 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2403 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2404 return RequestIndex(piece) * t.chunksPerRegularPiece()
2407 func (t *Torrent) updateComplete() {
2408 t.Complete.SetBool(t.haveAllPieces())
2411 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2412 p := t.requestingPeer(r)
2416 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2417 //delete(t.pendingRequests, r)
2418 if _, ok := t.requestState[r]; ok {
2419 panic("expected request state to be gone")
2424 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2425 return t.requestState[r].peer
2428 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2429 if t.connsWithAllPieces == nil {
2430 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2432 t.connsWithAllPieces[p] = struct{}{}
2435 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2436 _, ok := t.connsWithAllPieces[p]
2437 delete(t.connsWithAllPieces, p)
2441 func (t *Torrent) numActivePeers() int {
2442 return len(t.conns) + len(t.webSeeds)
2445 func (t *Torrent) hasStorageCap() bool {
2446 f := t.storage.Capacity
2454 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2455 return pieceIndex(ri / t.chunksPerRegularPiece())
2458 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2459 reuseIter *typedRoaring.Iterator[RequestIndex],
2461 f func(RequestIndex),
2463 reuseIter.Initialize(&t.dirtyChunks)
2464 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2465 iterBitmapUnsetInRange(
2467 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2472 type requestState struct {
2477 // Returns an error if a received chunk is out of bounds in someway.
2478 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2480 return errors.New("torrent missing info")
2482 if int(r.Index) >= t.numPieces() {
2483 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2485 pieceLength := t.pieceLength(pieceIndex(r.Index))
2486 if r.Begin >= pieceLength {
2487 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2489 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2490 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2491 // should be considerable checks elsewhere for this case due to the network overhead. We should
2492 // catch most of the overflow manipulation stuff by checking index and begin above.