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 request_strategy "github.com/anacrolix/torrent/request-strategy"
33 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
34 "github.com/davecgh/go-spew/spew"
35 "github.com/pion/datachannel"
37 "github.com/anacrolix/torrent/bencode"
38 "github.com/anacrolix/torrent/common"
39 "github.com/anacrolix/torrent/metainfo"
40 pp "github.com/anacrolix/torrent/peer_protocol"
41 "github.com/anacrolix/torrent/segments"
42 "github.com/anacrolix/torrent/storage"
43 "github.com/anacrolix/torrent/tracker"
44 "github.com/anacrolix/torrent/webseed"
45 "github.com/anacrolix/torrent/webtorrent"
48 // Maintains state of torrent within a Client. Many methods should not be called before the info is
49 // available, see .Info and .GotInfo.
51 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
52 // alignment. See #262.
57 networkingEnabled chansync.Flag
58 dataDownloadDisallowed chansync.Flag
59 dataUploadDisallowed bool
60 userOnWriteChunkErr func(error)
62 closed chansync.SetOnce
63 infoHash metainfo.Hash
65 // Values are the piece indices that changed.
66 pieceStateChanges pubsub.PubSub[PieceStateChange]
67 // The size of chunks to request from peers over the wire. This is
68 // normally 16KiB by convention these days.
71 // Total length of the torrent in bytes. Stored because it's not O(1) to
72 // get this from the info dict.
75 // The storage to open when the info dict becomes available.
76 storageOpener *storage.Client
77 // Storage for torrent data.
78 storage *storage.Torrent
79 // Read-locked for using storage, and write-locked for Closing.
80 storageLock sync.RWMutex
82 // TODO: Only announce stuff is used?
83 metainfo metainfo.MetaInfo
85 // The info dict. nil if we don't have it (yet).
87 fileIndex segments.Index
90 _chunksPerRegularPiece chunkIndexType
92 webSeeds map[string]*Peer
93 // Active peer connections, running message stream loops. TODO: Make this
94 // open (not-closed) connections only.
95 conns map[*PeerConn]struct{}
96 maxEstablishedConns int
97 // Set of addrs to which we're attempting to connect. Connections are
98 // half-open until all handshakes are completed.
99 halfOpen map[string]PeerInfo
101 // Reserve of peers to connect to. A peer can be both here and in the
102 // active connections if were told about the peer after connecting with
103 // them. That encourages us to reconnect to peers that are well known in
105 peers prioritizedPeers
106 // Whether we want to know to know more peers.
107 wantPeersEvent missinggo.Event
108 // An announcer for each tracker URL.
109 trackerAnnouncers map[string]torrentTrackerAnnouncer
110 // How many times we've initiated a DHT announce. TODO: Move into stats.
113 // Name used if the info name isn't available. Should be cleared when the
114 // Info does become available.
118 // The bencoded bytes of the info dict. This is actively manipulated if
119 // the info bytes aren't initially available, and we try to fetch them
122 // Each element corresponds to the 16KiB metadata pieces. If true, we have
123 // received that piece.
124 metadataCompletedChunks []bool
125 metadataChanged sync.Cond
127 // Closed when .Info is obtained.
128 gotMetainfoC chan struct{}
130 readers map[*reader]struct{}
131 _readerNowPieces bitmap.Bitmap
132 _readerReadaheadPieces bitmap.Bitmap
134 // A cache of pieces we need to get. Calculated from various piece and
135 // file priorities and completion states elsewhere.
136 _pendingPieces roaring.Bitmap
137 // A cache of completed piece indices.
138 _completedPieces roaring.Bitmap
139 // Pieces that need to be hashed.
140 piecesQueuedForHash bitmap.Bitmap
141 activePieceHashes int
142 initialPieceCheckDisabled bool
144 connsWithAllPieces map[*Peer]struct{}
146 requestState map[RequestIndex]requestState
147 // Chunks we've written to since the corresponding piece was last checked.
148 dirtyChunks typedRoaring.Bitmap[RequestIndex]
152 // Is On when all pieces are complete.
153 Complete chansync.Flag
155 // Torrent sources in use keyed by the source string.
156 activeSources sync.Map
157 sourcesLogger log.Logger
159 smartBanCache smartBanCache
162 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
163 // This could be done with roaring.BitSliceIndexing.
164 t.iterPeers(func(peer *Peer) {
165 if _, ok := t.connsWithAllPieces[peer]; ok {
168 if peer.peerHasPiece(i) {
175 func (t *Torrent) decPieceAvailability(i pieceIndex) {
180 if p.relativeAvailability <= 0 {
181 panic(p.relativeAvailability)
183 p.relativeAvailability--
184 t.updatePieceRequestOrder(i)
187 func (t *Torrent) incPieceAvailability(i pieceIndex) {
188 // If we don't the info, this should be reconciled when we do.
191 p.relativeAvailability++
192 t.updatePieceRequestOrder(i)
196 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
197 return t._readerNowPieces
200 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
201 return t._readerReadaheadPieces
204 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
205 return !t.wantPieceIndex(i)
208 // Returns a channel that is closed when the Torrent is closed.
209 func (t *Torrent) Closed() events.Done {
210 return t.closed.Done()
213 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
214 // pending, and half-open peers.
215 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
216 // Add pending peers to the list
217 t.peers.Each(func(peer PeerInfo) {
218 ks = append(ks, peer)
221 // Add half-open peers to the list
222 for _, peer := range t.halfOpen {
223 ks = append(ks, peer)
226 // Add active peers to the list
227 for conn := range t.conns {
228 ks = append(ks, PeerInfo{
230 Addr: conn.RemoteAddr,
231 Source: conn.Discovery,
232 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
233 // > But if we're not connected to them with an encrypted connection, I couldn't say
234 // > what's appropriate. We can carry forward the SupportsEncryption value as we
235 // > received it from trackers/DHT/PEX, or just use the encryption state for the
236 // > connection. It's probably easiest to do the latter for now.
237 // https://github.com/anacrolix/torrent/pull/188
238 SupportsEncryption: conn.headerEncrypted,
245 func (t *Torrent) setChunkSize(size pp.Integer) {
247 t.chunkPool = sync.Pool{
248 New: func() interface{} {
249 b := make([]byte, size)
255 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
256 return t._completedPieces.Contains(bitmap.BitIndex(piece))
259 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
260 if t.storage == nil {
261 return storage.Completion{Complete: false, Ok: true}
263 return t.pieces[piece].Storage().Completion()
266 // There's a connection to that address already.
267 func (t *Torrent) addrActive(addr string) bool {
268 if _, ok := t.halfOpen[addr]; ok {
271 for c := range t.conns {
273 if ra.String() == addr {
280 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
281 return t.appendConns(ret, func(conn *PeerConn) bool {
282 return !conn.closed.IsSet()
286 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
287 for c := range t.conns {
295 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
297 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
298 if t.closed.IsSet() {
301 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
302 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
303 torrent.Add("peers not added because of bad addr", 1)
304 // cl.logger.Printf("peers not added because of bad addr: %v", p)
308 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
309 torrent.Add("peers replaced", 1)
310 if !replaced.equal(p) {
311 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
318 for t.peers.Len() > cl.config.TorrentPeersHighWater {
319 _, ok := t.peers.DeleteMin()
321 torrent.Add("excess reserve peers discarded", 1)
327 func (t *Torrent) invalidateMetadata() {
328 for i := 0; i < len(t.metadataCompletedChunks); i++ {
329 t.metadataCompletedChunks[i] = false
332 t.gotMetainfoC = make(chan struct{})
337 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
341 if index >= len(t.metadataCompletedChunks) {
342 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
345 copy(t.metadataBytes[(1<<14)*index:], data)
346 t.metadataCompletedChunks[index] = true
349 func (t *Torrent) metadataPieceCount() int {
350 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
353 func (t *Torrent) haveMetadataPiece(piece int) bool {
355 return (1<<14)*piece < len(t.metadataBytes)
357 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
361 func (t *Torrent) metadataSize() int {
362 return len(t.metadataBytes)
365 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
366 for i := 0; i < len(info.Pieces); i += sha1.Size {
367 ret = append(ret, info.Pieces[i:i+sha1.Size])
372 func (t *Torrent) makePieces() {
373 hashes := infoPieceHashes(t.info)
374 t.pieces = make([]Piece, len(hashes))
375 for i, hash := range hashes {
376 piece := &t.pieces[i]
378 piece.index = pieceIndex(i)
379 piece.noPendingWrites.L = &piece.pendingWritesMutex
380 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
382 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
383 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
384 piece.files = files[beginFile:endFile]
385 piece.undirtiedChunksIter = undirtiedChunksIter{
386 TorrentDirtyChunks: &t.dirtyChunks,
387 StartRequestIndex: piece.requestIndexOffset(),
388 EndRequestIndex: piece.requestIndexOffset() + piece.numChunks(),
393 // Returns the index of the first file containing the piece. files must be
394 // ordered by offset.
395 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
396 for i, f := range files {
397 if f.offset+f.length > pieceOffset {
404 // Returns the index after the last file containing the piece. files must be
405 // ordered by offset.
406 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
407 for i, f := range files {
408 if f.offset+f.length >= pieceEndOffset {
415 func (t *Torrent) cacheLength() {
417 for _, f := range t.info.UpvertedFiles() {
423 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
425 func (t *Torrent) setInfo(info *metainfo.Info) error {
426 if err := validateInfo(info); err != nil {
427 return fmt.Errorf("bad info: %s", err)
429 if t.storageOpener != nil {
431 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
433 return fmt.Errorf("error opening torrent storage: %s", err)
439 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
441 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
442 t.displayName = "" // Save a few bytes lol.
449 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
450 return request_strategy.PieceRequestOrderKey{
451 InfoHash: t.infoHash,
456 // This seems to be all the follow-up tasks after info is set, that can't fail.
457 func (t *Torrent) onSetInfo() {
458 t.initPieceRequestOrder()
459 for i := range t.pieces {
461 // Need to add relativeAvailability before updating piece completion, as that may result in conns
463 if p.relativeAvailability != 0 {
464 panic(p.relativeAvailability)
466 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
467 t.addRequestOrderPiece(i)
468 t.updatePieceCompletion(i)
469 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
470 // t.logger.Printf("piece %s completion unknown, queueing check", p)
474 t.cl.event.Broadcast()
475 close(t.gotMetainfoC)
476 t.updateWantPeersEvent()
477 t.requestState = make(map[RequestIndex]requestState)
478 t.tryCreateMorePieceHashers()
479 t.iterPeers(func(p *Peer) {
481 p.updateRequests("onSetInfo")
485 // Called when metadata for a torrent becomes available.
486 func (t *Torrent) setInfoBytesLocked(b []byte) error {
487 if metainfo.HashBytes(b) != t.infoHash {
488 return errors.New("info bytes have wrong hash")
490 var info metainfo.Info
491 if err := bencode.Unmarshal(b, &info); err != nil {
492 return fmt.Errorf("error unmarshalling info bytes: %s", err)
495 t.metadataCompletedChunks = nil
499 if err := t.setInfo(&info); err != nil {
506 func (t *Torrent) haveAllMetadataPieces() bool {
510 if t.metadataCompletedChunks == nil {
513 for _, have := range t.metadataCompletedChunks {
521 // TODO: Propagate errors to disconnect peer.
522 func (t *Torrent) setMetadataSize(size int) (err error) {
524 // We already know the correct metadata size.
527 if uint32(size) > maxMetadataSize {
528 return errors.New("bad size")
530 if len(t.metadataBytes) == size {
533 t.metadataBytes = make([]byte, size)
534 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
535 t.metadataChanged.Broadcast()
536 for c := range t.conns {
537 c.requestPendingMetadata()
542 // The current working name for the torrent. Either the name in the info dict,
543 // or a display name given such as by the dn value in a magnet link, or "".
544 func (t *Torrent) name() string {
546 defer t.nameMu.RUnlock()
548 return t.info.BestName()
550 if t.displayName != "" {
553 return "infohash:" + t.infoHash.HexString()
556 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
557 p := &t.pieces[index]
558 ret.Priority = t.piecePriority(index)
559 ret.Completion = p.completion()
560 ret.QueuedForHash = p.queuedForHash()
561 ret.Hashing = p.hashing
562 ret.Checking = ret.QueuedForHash || ret.Hashing
563 ret.Marking = p.marking
564 if !ret.Complete && t.piecePartiallyDownloaded(index) {
570 func (t *Torrent) metadataPieceSize(piece int) int {
571 return metadataPieceSize(len(t.metadataBytes), piece)
574 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
577 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
578 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
580 TotalSize: len(t.metadataBytes),
586 type pieceAvailabilityRun struct {
591 func (me pieceAvailabilityRun) String() string {
592 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
595 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
596 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
597 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
599 for i := range t.pieces {
600 rle.Append(t.pieces[i].availability(), 1)
606 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
607 freqs = make([]int, t.numActivePeers()+1)
608 for i := range t.pieces {
609 freqs[t.piece(i).availability()]++
614 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
615 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
616 ret = append(ret, PieceStateRun{
617 PieceState: el.(PieceState),
621 for index := range t.pieces {
622 rle.Append(t.pieceState(pieceIndex(index)), 1)
628 // Produces a small string representing a PieceStateRun.
629 func (psr PieceStateRun) String() (ret string) {
630 ret = fmt.Sprintf("%d", psr.Length)
631 ret += func() string {
632 switch psr.Priority {
633 case PiecePriorityNext:
635 case PiecePriorityNormal:
637 case PiecePriorityReadahead:
639 case PiecePriorityNow:
641 case PiecePriorityHigh:
650 if psr.QueuedForHash {
668 func (t *Torrent) writeStatus(w io.Writer) {
669 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
670 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
672 fmt.Fprintf(w, "Metadata have: ")
673 for _, h := range t.metadataCompletedChunks {
674 fmt.Fprintf(w, "%c", func() rune {
684 fmt.Fprintf(w, "Piece length: %s\n",
687 return fmt.Sprintf("%v (%v chunks)",
689 float64(t.usualPieceSize())/float64(t.chunkSize))
696 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
697 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
698 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
699 // availability frequencies instead.
701 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
702 for _, run := range t.pieceAvailabilityRuns() {
703 ret = append(ret, run.String())
708 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
709 func() (ret []string) {
710 for avail, freq := range t.pieceAvailabilityFrequencies() {
714 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
720 fmt.Fprintf(w, "Reader Pieces:")
721 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
722 fmt.Fprintf(w, " %d:%d", begin, end)
727 fmt.Fprintf(w, "Enabled trackers:\n")
729 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
730 fmt.Fprintf(tw, " URL\tExtra\n")
731 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
734 var luns, runs url.URL = *lu, *ru
737 var ml missinggo.MultiLess
738 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
739 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
741 }).([]torrentTrackerAnnouncer) {
742 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
747 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
749 spew.NewDefaultConfig()
750 spew.Fdump(w, t.statsLocked())
752 peers := t.peersAsSlice()
753 sort.Slice(peers, func(_i, _j int) bool {
756 if less, ok := multiless.New().EagerSameLess(
757 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
761 return worseConn(i, j)
763 for i, c := range peers {
764 fmt.Fprintf(w, "%2d. ", i+1)
769 func (t *Torrent) haveInfo() bool {
773 // Returns a run-time generated MetaInfo that includes the info bytes and
774 // announce-list as currently known to the client.
775 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
776 return metainfo.MetaInfo{
777 CreationDate: time.Now().Unix(),
778 Comment: "dynamic metainfo from client",
779 CreatedBy: "go.torrent",
780 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
781 InfoBytes: func() []byte {
783 return t.metadataBytes
788 UrlList: func() []string {
789 ret := make([]string, 0, len(t.webSeeds))
790 for url := range t.webSeeds {
791 ret = append(ret, url)
799 func (t *Torrent) BytesMissing() (n int64) {
801 n = t.bytesMissingLocked()
806 func (t *Torrent) bytesMissingLocked() int64 {
810 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
811 roaring.Flip(b, 0, end).Iterate(cb)
814 func (t *Torrent) bytesLeft() (left int64) {
815 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
816 p := t.piece(pieceIndex(x))
817 left += int64(p.length() - p.numDirtyBytes())
823 // Bytes left to give in tracker announces.
824 func (t *Torrent) bytesLeftAnnounce() int64 {
832 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
833 if t.pieceComplete(piece) {
836 if t.pieceAllDirty(piece) {
839 return t.pieces[piece].hasDirtyChunks()
842 func (t *Torrent) usualPieceSize() int {
843 return int(t.info.PieceLength)
846 func (t *Torrent) numPieces() pieceIndex {
847 return pieceIndex(t.info.NumPieces())
850 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
851 return pieceIndex(t._completedPieces.GetCardinality())
854 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
856 err = errors.New("already closed")
859 if t.storage != nil {
864 defer t.storageLock.Unlock()
865 if f := t.storage.Close; f != nil {
868 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
873 t.iterPeers(func(p *Peer) {
876 if t.storage != nil {
877 t.deletePieceRequestOrder()
879 for i := range t.pieces {
881 if p.relativeAvailability != 0 {
882 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
886 t.cl.event.Broadcast()
887 t.pieceStateChanges.Close()
888 t.updateWantPeersEvent()
892 func (t *Torrent) requestOffset(r Request) int64 {
893 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
896 // Return the request that would include the given offset into the torrent data. Returns !ok if
897 // there is no such request.
898 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
899 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
902 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
903 defer perf.ScopeTimerErr(&err)()
904 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
905 if err == nil && n != len(data) {
906 err = io.ErrShortWrite
911 func (t *Torrent) bitfield() (bf []bool) {
912 bf = make([]bool, t.numPieces())
913 t._completedPieces.Iterate(func(piece uint32) (again bool) {
920 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
921 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
924 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
925 return t._chunksPerRegularPiece
928 func (t *Torrent) numRequests() RequestIndex {
929 if t.numPieces() == 0 {
932 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
935 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
936 t.dirtyChunks.RemoveRange(
937 uint64(t.pieceRequestIndexOffset(pieceIndex)),
938 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
941 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
942 if t.info.PieceLength == 0 {
943 // There will be no variance amongst pieces. Only pain.
946 if piece == t.numPieces()-1 {
947 ret := pp.Integer(*t.length % t.info.PieceLength)
952 return pp.Integer(t.info.PieceLength)
955 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
956 return &blockCheckingWriter{
957 cache: &t.smartBanCache,
958 requestIndex: t.pieceRequestIndexOffset(piece),
959 chunkSize: t.chunkSize.Int(),
963 func (t *Torrent) hashPiece(piece pieceIndex) (
965 // These are peers that sent us blocks that differ from what we hash here.
966 differingPeers map[bannableAddr]struct{},
970 p.waitNoPendingWrites()
971 storagePiece := t.pieces[piece].Storage()
973 // Does the backend want to do its own hashing?
974 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
975 var sum metainfo.Hash
976 // log.Printf("A piece decided to self-hash: %d", piece)
977 sum, err = i.SelfHash()
978 missinggo.CopyExact(&ret, sum)
982 hash := pieceHash.New()
983 const logPieceContents = false
984 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
985 writers := []io.Writer{hash, smartBanWriter}
986 var examineBuf bytes.Buffer
987 if logPieceContents {
988 writers = append(writers, &examineBuf)
990 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
991 if logPieceContents {
992 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
994 smartBanWriter.Flush()
995 differingPeers = smartBanWriter.badPeers
996 missinggo.CopyExact(&ret, hash.Sum(nil))
1000 func (t *Torrent) haveAnyPieces() bool {
1001 return !t._completedPieces.IsEmpty()
1004 func (t *Torrent) haveAllPieces() bool {
1008 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1011 func (t *Torrent) havePiece(index pieceIndex) bool {
1012 return t.haveInfo() && t.pieceComplete(index)
1015 func (t *Torrent) maybeDropMutuallyCompletePeer(
1016 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1020 if !t.cl.config.DropMutuallyCompletePeers {
1023 if !t.haveAllPieces() {
1026 if all, known := p.peerHasAllPieces(); !(known && all) {
1032 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1036 func (t *Torrent) haveChunk(r Request) (ret bool) {
1038 // log.Println("have chunk", r, ret)
1043 if t.pieceComplete(pieceIndex(r.Index)) {
1046 p := &t.pieces[r.Index]
1047 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1050 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1051 return chunkIndexType(cs.Begin / chunkSize)
1054 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1055 return t._pendingPieces.Contains(uint32(index))
1058 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1059 // conns (which is a map).
1060 var peerConnSlices sync.Pool
1062 func getPeerConnSlice(cap int) []*PeerConn {
1063 getInterface := peerConnSlices.Get()
1064 if getInterface == nil {
1065 return make([]*PeerConn, 0, cap)
1067 return getInterface.([]*PeerConn)[:0]
1071 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1072 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1073 // established connections for more than a minute. This is O(n log n). If there was a way to not
1074 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1075 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1076 wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
1077 defer peerConnSlices.Put(wcs.conns)
1080 for wcs.Len() != 0 {
1081 c := heap.Pop(&wcs).(*PeerConn)
1082 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1085 // If the connection is in the worst half of the established
1086 // connection quota and is older than a minute.
1087 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1088 // Give connections 1 minute to prove themselves.
1089 if time.Since(c.completedHandshake) > time.Minute {
1097 type PieceStateChange struct {
1102 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1103 t.cl._mu.Defer(func() {
1104 cur := t.pieceState(piece)
1105 p := &t.pieces[piece]
1106 if cur != p.publicPieceState {
1107 p.publicPieceState = cur
1108 t.pieceStateChanges.Publish(PieceStateChange{
1116 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1117 if t.pieceComplete(piece) {
1120 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1123 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1124 return t.pieces[piece].allChunksDirty()
1127 func (t *Torrent) readersChanged() {
1128 t.updateReaderPieces()
1129 t.updateAllPiecePriorities("Torrent.readersChanged")
1132 func (t *Torrent) updateReaderPieces() {
1133 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1136 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1140 t.updateReaderPieces()
1141 // Order the ranges, high and low.
1143 if l.begin > h.begin {
1146 if l.end < h.begin {
1147 // Two distinct ranges.
1148 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1149 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1156 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1160 func (t *Torrent) maybeNewConns() {
1161 // Tickle the accept routine.
1162 t.cl.event.Broadcast()
1166 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1167 if t._pendingPieces.Contains(uint32(piece)) {
1168 t.iterPeers(func(c *Peer) {
1169 // if c.requestState.Interested {
1172 if !c.isLowOnRequests() {
1175 if !c.peerHasPiece(piece) {
1178 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1181 c.updateRequests(reason)
1185 t.publishPieceChange(piece)
1188 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1189 if !t.closed.IsSet() {
1190 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1192 t.updatePieceRequestOrder(piece)
1194 p := &t.pieces[piece]
1195 newPrio := p.uncachedPriority()
1196 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1197 if newPrio == PiecePriorityNone {
1198 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1202 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1206 t.piecePriorityChanged(piece, reason)
1209 func (t *Torrent) updateAllPiecePriorities(reason string) {
1210 t.updatePiecePriorities(0, t.numPieces(), reason)
1213 // Update all piece priorities in one hit. This function should have the same
1214 // output as updatePiecePriority, but across all pieces.
1215 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1216 for i := begin; i < end; i++ {
1217 t.updatePiecePriority(i, reason)
1221 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1222 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1223 if off >= *t.length {
1233 begin = pieceIndex(off / t.info.PieceLength)
1234 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1235 if end > pieceIndex(t.info.NumPieces()) {
1236 end = pieceIndex(t.info.NumPieces())
1241 // Returns true if all iterations complete without breaking. Returns the read regions for all
1242 // readers. The reader regions should not be merged as some callers depend on this method to
1243 // enumerate readers.
1244 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1245 for r := range t.readers {
1247 if p.begin >= p.end {
1250 if !f(p.begin, p.end) {
1257 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1258 return t.piece(piece).uncachedPriority()
1261 func (t *Torrent) pendRequest(req RequestIndex) {
1262 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1265 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1266 t.cl.event.Broadcast()
1267 if t.pieceComplete(piece) {
1268 t.onPieceCompleted(piece)
1270 t.onIncompletePiece(piece)
1272 t.updatePiecePriority(piece, reason)
1275 func (t *Torrent) numReceivedConns() (ret int) {
1276 for c := range t.conns {
1277 if c.Discovery == PeerSourceIncoming {
1284 func (t *Torrent) maxHalfOpen() int {
1285 // Note that if we somehow exceed the maximum established conns, we want
1286 // the negative value to have an effect.
1287 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1288 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1289 // We want to allow some experimentation with new peers, and to try to
1290 // upset an oversupply of received connections.
1291 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1294 func (t *Torrent) openNewConns() (initiated int) {
1295 defer t.updateWantPeersEvent()
1296 for t.peers.Len() != 0 {
1300 if len(t.halfOpen) >= t.maxHalfOpen() {
1303 if len(t.cl.dialers) == 0 {
1306 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1309 p := t.peers.PopMax()
1316 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1318 uncached := t.pieceCompleteUncached(piece)
1319 cached := p.completion()
1320 changed := cached != uncached
1321 complete := uncached.Complete
1322 p.storageCompletionOk = uncached.Ok
1325 t._completedPieces.Add(x)
1328 t._completedPieces.Remove(x)
1330 p.t.updatePieceRequestOrder(piece)
1332 if complete && len(p.dirtiers) != 0 {
1333 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1336 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1337 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1342 // Non-blocking read. Client lock is not required.
1343 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1345 p := &t.pieces[off/t.info.PieceLength]
1346 p.waitNoPendingWrites()
1348 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1359 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1360 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1361 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1362 func (t *Torrent) maybeCompleteMetadata() error {
1367 if !t.haveAllMetadataPieces() {
1368 // Don't have enough metadata pieces.
1371 err := t.setInfoBytesLocked(t.metadataBytes)
1373 t.invalidateMetadata()
1374 return fmt.Errorf("error setting info bytes: %s", err)
1376 if t.cl.config.Debug {
1377 t.logger.Printf("%s: got metadata from peers", t)
1382 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1383 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1385 now.Add(bitmap.BitIndex(begin))
1386 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1393 func (t *Torrent) needData() bool {
1394 if t.closed.IsSet() {
1400 return !t._pendingPieces.IsEmpty()
1403 func appendMissingStrings(old, new []string) (ret []string) {
1406 for _, n := range new {
1407 for _, o := range old {
1412 ret = append(ret, n)
1417 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1419 for minNumTiers > len(ret) {
1420 ret = append(ret, nil)
1425 func (t *Torrent) addTrackers(announceList [][]string) {
1426 fullAnnounceList := &t.metainfo.AnnounceList
1427 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1428 for tierIndex, trackerURLs := range announceList {
1429 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1431 t.startMissingTrackerScrapers()
1432 t.updateWantPeersEvent()
1435 // Don't call this before the info is available.
1436 func (t *Torrent) bytesCompleted() int64 {
1440 return *t.length - t.bytesLeft()
1443 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1446 return t.setInfoBytesLocked(b)
1449 // Returns true if connection is removed from torrent.Conns.
1450 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1451 if !c.closed.IsSet() {
1452 panic("connection is not closed")
1453 // There are behaviours prevented by the closed state that will fail
1454 // if the connection has been deleted.
1458 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1459 // the drop event against the PexConnState instead.
1461 if !t.cl.config.DisablePEX {
1465 torrent.Add("deleted connections", 1)
1466 c.deleteAllRequests("Torrent.deletePeerConn")
1467 t.assertPendingRequests()
1468 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1469 panic(t.connsWithAllPieces)
1474 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1475 if t.deleteConnWithAllPieces(p) {
1481 p.peerPieces().Iterate(func(i uint32) bool {
1482 p.t.decPieceAvailability(pieceIndex(i))
1487 func (t *Torrent) assertPendingRequests() {
1491 // var actual pendingRequests
1492 // if t.haveInfo() {
1493 // actual.m = make([]int, t.numRequests())
1495 // t.iterPeers(func(p *Peer) {
1496 // p.requestState.Requests.Iterate(func(x uint32) bool {
1501 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1507 func (t *Torrent) dropConnection(c *PeerConn) {
1508 t.cl.event.Broadcast()
1510 if t.deletePeerConn(c) {
1515 // Peers as in contact information for dialing out.
1516 func (t *Torrent) wantPeers() bool {
1517 if t.closed.IsSet() {
1520 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1523 return t.wantConns()
1526 func (t *Torrent) updateWantPeersEvent() {
1528 t.wantPeersEvent.Set()
1530 t.wantPeersEvent.Clear()
1534 // Returns whether the client should make effort to seed the torrent.
1535 func (t *Torrent) seeding() bool {
1537 if t.closed.IsSet() {
1540 if t.dataUploadDisallowed {
1543 if cl.config.NoUpload {
1546 if !cl.config.Seed {
1549 if cl.config.DisableAggressiveUpload && t.needData() {
1555 func (t *Torrent) onWebRtcConn(
1556 c datachannel.ReadWriteCloser,
1557 dcc webtorrent.DataChannelContext,
1560 netConn := webrtcNetConn{
1562 DataChannelContext: dcc,
1564 peerRemoteAddr := netConn.RemoteAddr()
1565 if t.cl.badPeerAddr(peerRemoteAddr) {
1568 pc, err := t.cl.initiateProtocolHandshakes(
1569 context.Background(),
1574 netConn.RemoteAddr(),
1576 fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1579 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1582 if dcc.LocalOffered {
1583 pc.Discovery = PeerSourceTracker
1585 pc.Discovery = PeerSourceIncoming
1587 pc.conn.SetWriteDeadline(time.Time{})
1590 err = t.cl.runHandshookConn(pc, t)
1592 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1596 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1597 err := t.cl.runHandshookConn(pc, t)
1598 if err != nil || logAll {
1599 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1603 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1604 t.logRunHandshookConn(pc, false, log.Debug)
1607 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1608 wtc, release := t.cl.websocketTrackers.Get(u.String())
1613 wst := websocketTrackerStatus{u, wtc}
1615 err := wtc.Announce(tracker.Started, t.infoHash)
1617 t.logger.WithDefaultLevel(log.Warning).Printf(
1618 "error in initial announce to %q: %v",
1626 func (t *Torrent) startScrapingTracker(_url string) {
1630 u, err := url.Parse(_url)
1632 // URLs with a leading '*' appear to be a uTorrent convention to
1633 // disable trackers.
1635 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1639 if u.Scheme == "udp" {
1641 t.startScrapingTracker(u.String())
1643 t.startScrapingTracker(u.String())
1646 if _, ok := t.trackerAnnouncers[_url]; ok {
1649 sl := func() torrentTrackerAnnouncer {
1652 if t.cl.config.DisableWebtorrent {
1655 return t.startWebsocketAnnouncer(*u)
1657 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1661 if t.cl.config.DisableIPv6 {
1665 newAnnouncer := &trackerScraper{
1668 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1670 go newAnnouncer.Run()
1676 if t.trackerAnnouncers == nil {
1677 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1679 t.trackerAnnouncers[_url] = sl
1682 // Adds and starts tracker scrapers for tracker URLs that aren't already
1684 func (t *Torrent) startMissingTrackerScrapers() {
1685 if t.cl.config.DisableTrackers {
1688 t.startScrapingTracker(t.metainfo.Announce)
1689 for _, tier := range t.metainfo.AnnounceList {
1690 for _, url := range tier {
1691 t.startScrapingTracker(url)
1696 // Returns an AnnounceRequest with fields filled out to defaults and current
1698 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1699 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1700 // dependent on the network in use.
1701 return tracker.AnnounceRequest{
1703 NumWant: func() int32 {
1704 if t.wantPeers() && len(t.cl.dialers) > 0 {
1710 Port: uint16(t.cl.incomingPeerPort()),
1711 PeerId: t.cl.peerID,
1712 InfoHash: t.infoHash,
1713 Key: t.cl.announceKey(),
1715 // The following are vaguely described in BEP 3.
1717 Left: t.bytesLeftAnnounce(),
1718 Uploaded: t.stats.BytesWrittenData.Int64(),
1719 // There's no mention of wasted or unwanted download in the BEP.
1720 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1724 // Adds peers revealed in an announce until the announce ends, or we have
1726 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1728 for v := range pvs {
1731 for _, cp := range v.Peers {
1733 // Can't do anything with this.
1736 if t.addPeer(PeerInfo{
1737 Addr: ipPortAddr{cp.IP, cp.Port},
1738 Source: PeerSourceDhtGetPeers,
1745 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1750 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1751 // announce ends. stop will force the announce to end.
1752 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1753 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1757 _done := make(chan struct{})
1761 t.consumeDhtAnnouncePeers(ps.Peers())
1767 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1768 _, stop, err := t.AnnounceToDht(s)
1773 case <-t.closed.Done():
1774 case <-time.After(5 * time.Minute):
1780 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1786 if t.closed.IsSet() {
1789 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1790 // TODO: We can include the announce_peer step depending on whether we can receive
1791 // inbound connections. We should probably only announce once every 15 mins too.
1795 // TODO: Determine if there's a listener on the port we're announcing.
1796 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1807 err := t.timeboxedAnnounceToDht(s)
1809 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1815 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1816 for _, p := range peers {
1824 // The returned TorrentStats may require alignment in memory. See
1825 // https://github.com/anacrolix/torrent/issues/383.
1826 func (t *Torrent) Stats() TorrentStats {
1828 defer t.cl.rUnlock()
1829 return t.statsLocked()
1832 func (t *Torrent) statsLocked() (ret TorrentStats) {
1833 ret.ActivePeers = len(t.conns)
1834 ret.HalfOpenPeers = len(t.halfOpen)
1835 ret.PendingPeers = t.peers.Len()
1836 ret.TotalPeers = t.numTotalPeers()
1837 ret.ConnectedSeeders = 0
1838 for c := range t.conns {
1839 if all, ok := c.peerHasAllPieces(); all && ok {
1840 ret.ConnectedSeeders++
1843 ret.ConnStats = t.stats.Copy()
1844 ret.PiecesComplete = t.numPiecesCompleted()
1848 // The total number of peers in the torrent.
1849 func (t *Torrent) numTotalPeers() int {
1850 peers := make(map[string]struct{})
1851 for conn := range t.conns {
1852 ra := conn.conn.RemoteAddr()
1854 // It's been closed and doesn't support RemoteAddr.
1857 peers[ra.String()] = struct{}{}
1859 for addr := range t.halfOpen {
1860 peers[addr] = struct{}{}
1862 t.peers.Each(func(peer PeerInfo) {
1863 peers[peer.Addr.String()] = struct{}{}
1868 // Reconcile bytes transferred before connection was associated with a
1870 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1871 if c._stats != (ConnStats{
1872 // Handshakes should only increment these fields:
1873 BytesWritten: c._stats.BytesWritten,
1874 BytesRead: c._stats.BytesRead,
1878 c.postHandshakeStats(func(cs *ConnStats) {
1879 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1880 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1882 c.reconciledHandshakeStats = true
1885 // Returns true if the connection is added.
1886 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1889 torrent.Add("added connections", 1)
1892 if t.closed.IsSet() {
1893 return errors.New("torrent closed")
1895 for c0 := range t.conns {
1896 if c.PeerID != c0.PeerID {
1899 if !t.cl.config.DropDuplicatePeerIds {
1902 if c.hasPreferredNetworkOver(c0) {
1904 t.deletePeerConn(c0)
1906 return errors.New("existing connection preferred")
1909 if len(t.conns) >= t.maxEstablishedConns {
1910 c := t.worstBadConn()
1912 return errors.New("don't want conns")
1917 if len(t.conns) >= t.maxEstablishedConns {
1920 t.conns[c] = struct{}{}
1921 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1922 t.pex.Add(c) // as no further extended handshake expected
1927 func (t *Torrent) wantConns() bool {
1928 if !t.networkingEnabled.Bool() {
1931 if t.closed.IsSet() {
1934 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
1937 return len(t.conns) < t.maxEstablishedConns || t.worstBadConn() != nil
1940 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1943 oldMax = t.maxEstablishedConns
1944 t.maxEstablishedConns = max
1945 wcs := worseConnSlice{
1946 conns: t.appendConns(nil, func(*PeerConn) bool {
1952 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1953 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
1959 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1960 t.logger.LazyLog(log.Debug, func() log.Msg {
1961 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
1965 t.cl.event.Broadcast()
1966 if t.closed.IsSet() {
1970 // Don't score the first time a piece is hashed, it could be an initial check.
1971 if p.storageCompletionOk {
1973 pieceHashedCorrect.Add(1)
1976 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1977 ).AddValues(t, p).LogLevel(
1979 log.Debug, t.logger)
1981 pieceHashedNotCorrect.Add(1)
1986 t.publishPieceChange(piece)
1989 t.publishPieceChange(piece)
1993 if len(p.dirtiers) != 0 {
1994 // Don't increment stats above connection-level for every involved connection.
1995 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1997 for c := range p.dirtiers {
1998 c._stats.incrementPiecesDirtiedGood()
2000 t.clearPieceTouchers(piece)
2002 err := p.Storage().MarkComplete()
2004 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2008 if t.closed.IsSet() {
2011 t.pendAllChunkSpecs(piece)
2013 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2014 // Peers contributed to all the data for this piece hash failure, and the failure was
2015 // not due to errors in the storage (such as data being dropped in a cache).
2017 // Increment Torrent and above stats, and then specific connections.
2018 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2019 for c := range p.dirtiers {
2020 // Y u do dis peer?!
2021 c.stats().incrementPiecesDirtiedBad()
2024 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2025 for c := range p.dirtiers {
2027 bannableTouchers = append(bannableTouchers, c)
2030 t.clearPieceTouchers(piece)
2031 slices.Sort(bannableTouchers, connLessTrusted)
2033 if t.cl.config.Debug {
2035 "bannable conns by trust for piece %d: %v",
2037 func() (ret []connectionTrust) {
2038 for _, c := range bannableTouchers {
2039 ret = append(ret, c.trust())
2046 if len(bannableTouchers) >= 1 {
2047 c := bannableTouchers[0]
2048 if len(bannableTouchers) != 1 {
2049 t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2051 // Turns out it's still useful to ban peers like this because if there's only a
2052 // single peer for a piece, and we never progress that piece to completion, we
2053 // will never smart-ban them. Discovered in
2054 // https://github.com/anacrolix/torrent/issues/715.
2055 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2060 t.onIncompletePiece(piece)
2061 p.Storage().MarkNotComplete()
2063 t.updatePieceCompletion(piece)
2066 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2067 for ri := t.pieceRequestIndexOffset(piece); ri < t.pieceRequestIndexOffset(piece+1); ri++ {
2072 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2073 t.pendAllChunkSpecs(piece)
2074 t.cancelRequestsForPiece(piece)
2075 t.piece(piece).readerCond.Broadcast()
2076 for conn := range t.conns {
2078 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2082 // Called when a piece is found to be not complete.
2083 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2084 if t.pieceAllDirty(piece) {
2085 t.pendAllChunkSpecs(piece)
2087 if !t.wantPieceIndex(piece) {
2088 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2091 // We could drop any connections that we told we have a piece that we
2092 // don't here. But there's a test failure, and it seems clients don't care
2093 // if you request pieces that you already claim to have. Pruning bad
2094 // connections might just remove any connections that aren't treating us
2095 // favourably anyway.
2097 // for c := range t.conns {
2098 // if c.sentHave(piece) {
2102 t.iterPeers(func(conn *Peer) {
2103 if conn.peerHasPiece(piece) {
2104 conn.updateRequests("piece incomplete")
2109 func (t *Torrent) tryCreateMorePieceHashers() {
2110 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2114 func (t *Torrent) tryCreatePieceHasher() bool {
2115 if t.storage == nil {
2118 pi, ok := t.getPieceToHash()
2123 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2125 t.publishPieceChange(pi)
2126 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2127 t.storageLock.RLock()
2128 t.activePieceHashes++
2129 go t.pieceHasher(pi)
2133 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2134 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2135 if t.piece(i).hashing {
2145 func (t *Torrent) dropBannedPeers() {
2146 t.iterPeers(func(p *Peer) {
2147 remoteIp := p.remoteIp()
2148 if remoteIp == nil {
2149 if p.bannableAddr.Ok() {
2150 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2154 netipAddr := netip.MustParseAddr(remoteIp.String())
2155 if Some(netipAddr) != p.bannableAddr {
2156 t.logger.WithDefaultLevel(log.Debug).Printf(
2157 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2158 p, remoteIp, p.bannableAddr)
2160 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2161 // Should this be a close?
2163 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2168 func (t *Torrent) pieceHasher(index pieceIndex) {
2170 sum, failedPeers, copyErr := t.hashPiece(index)
2171 correct := sum == *p.hash
2175 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2177 t.storageLock.RUnlock()
2181 for peer := range failedPeers {
2182 t.cl.banPeerIP(peer.AsSlice())
2183 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2186 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2187 t.smartBanCache.ForgetBlock(ri)
2191 t.pieceHashed(index, correct, copyErr)
2192 t.updatePiecePriority(index, "Torrent.pieceHasher")
2193 t.activePieceHashes--
2194 t.tryCreateMorePieceHashers()
2197 // Return the connections that touched a piece, and clear the entries while doing it.
2198 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2200 for c := range p.dirtiers {
2201 delete(c.peerTouchedPieces, pi)
2202 delete(p.dirtiers, c)
2206 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2207 t.iterPeers(func(p *Peer) {
2208 ret = append(ret, p)
2213 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2214 piece := t.piece(pieceIndex)
2215 if piece.queuedForHash() {
2218 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2219 t.publishPieceChange(pieceIndex)
2220 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2221 t.tryCreateMorePieceHashers()
2224 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2225 // before the Info is available.
2226 func (t *Torrent) VerifyData() {
2227 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2228 t.Piece(i).VerifyData()
2232 // Start the process of connecting to the given peer for the given torrent if appropriate.
2233 func (t *Torrent) initiateConn(peer PeerInfo) {
2234 if peer.Id == t.cl.peerID {
2237 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2241 if t.addrActive(addr.String()) {
2245 t.halfOpen[addr.String()] = peer
2246 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2249 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2250 // quickly make one Client visible to the Torrent of another Client.
2251 func (t *Torrent) AddClientPeer(cl *Client) int {
2252 return t.AddPeers(func() (ps []PeerInfo) {
2253 for _, la := range cl.ListenAddrs() {
2254 ps = append(ps, PeerInfo{
2263 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2265 func (t *Torrent) allStats(f func(*ConnStats)) {
2270 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2271 return t.pieces[i].hashing
2274 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2275 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2278 func (t *Torrent) dialTimeout() time.Duration {
2279 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2282 func (t *Torrent) piece(i int) *Piece {
2286 func (t *Torrent) onWriteChunkErr(err error) {
2287 if t.userOnWriteChunkErr != nil {
2288 go t.userOnWriteChunkErr(err)
2291 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2292 t.disallowDataDownloadLocked()
2295 func (t *Torrent) DisallowDataDownload() {
2296 t.disallowDataDownloadLocked()
2299 func (t *Torrent) disallowDataDownloadLocked() {
2300 t.dataDownloadDisallowed.Set()
2303 func (t *Torrent) AllowDataDownload() {
2304 t.dataDownloadDisallowed.Clear()
2307 // Enables uploading data, if it was disabled.
2308 func (t *Torrent) AllowDataUpload() {
2311 t.dataUploadDisallowed = false
2312 for c := range t.conns {
2313 c.updateRequests("allow data upload")
2317 // Disables uploading data, if it was enabled.
2318 func (t *Torrent) DisallowDataUpload() {
2321 t.dataUploadDisallowed = true
2322 for c := range t.conns {
2323 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2324 c.updateRequests("disallow data upload")
2328 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2329 // or if nil, a critical message is logged, and data download is disabled.
2330 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2333 t.userOnWriteChunkErr = f
2336 func (t *Torrent) iterPeers(f func(p *Peer)) {
2337 for pc := range t.conns {
2340 for _, ws := range t.webSeeds {
2345 func (t *Torrent) callbacks() *Callbacks {
2346 return &t.cl.config.Callbacks
2349 type AddWebSeedsOpt func(*webseed.Client)
2351 // Sets the WebSeed trailing path escaper for a webseed.Client.
2352 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2353 return func(c *webseed.Client) {
2354 c.PathEscaper = custom
2358 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2361 for _, u := range urls {
2362 t.addWebSeed(u, opts...)
2366 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2367 if t.cl.config.DisableWebseeds {
2370 if _, ok := t.webSeeds[url]; ok {
2373 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2374 // right away. This value should be some multiple of the number of connections to a host. I
2375 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2376 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2377 // "https://webtorrent.io/torrents/".
2378 const maxRequests = 16
2384 reconciledHandshakeStats: true,
2385 // This should affect how often we have to recompute requests for this peer. Note that
2386 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2387 // requests mark more often, so recomputation is probably sooner than with regular peer
2388 // conns. ~4x maxRequests would be about right.
2389 PeerMaxRequests: 128,
2390 // TODO: Set ban prefix?
2391 RemoteAddr: remoteAddrFromUrl(url),
2392 callbacks: t.callbacks(),
2394 client: webseed.Client{
2395 HttpClient: t.cl.httpClient,
2397 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2398 return &rateLimitedReader{
2399 l: t.cl.config.DownloadRateLimiter,
2404 activeRequests: make(map[Request]webseed.Request, maxRequests),
2405 maxRequests: maxRequests,
2407 ws.peer.initRequestState()
2408 for _, opt := range opts {
2411 ws.peer.initUpdateRequestsTimer()
2412 ws.requesterCond.L = t.cl.locker()
2413 for i := 0; i < maxRequests; i += 1 {
2416 for _, f := range t.callbacks().NewPeer {
2419 ws.peer.logger = t.logger.WithContextValue(&ws)
2420 ws.peer.peerImpl = &ws
2422 ws.onGotInfo(t.info)
2424 t.webSeeds[url] = &ws.peer
2427 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2428 t.iterPeers(func(p1 *Peer) {
2436 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2437 index := t.pieceIndexOfRequestIndex(ri)
2440 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2444 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2445 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2448 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2449 return RequestIndex(piece) * t.chunksPerRegularPiece()
2452 func (t *Torrent) updateComplete() {
2453 t.Complete.SetBool(t.haveAllPieces())
2456 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2457 p := t.requestingPeer(r)
2461 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2462 //delete(t.pendingRequests, r)
2463 if _, ok := t.requestState[r]; ok {
2464 panic("expected request state to be gone")
2469 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2470 return t.requestState[r].peer
2473 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2474 if t.connsWithAllPieces == nil {
2475 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2477 t.connsWithAllPieces[p] = struct{}{}
2480 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2481 _, ok := t.connsWithAllPieces[p]
2482 delete(t.connsWithAllPieces, p)
2486 func (t *Torrent) numActivePeers() int {
2487 return len(t.conns) + len(t.webSeeds)
2490 func (t *Torrent) hasStorageCap() bool {
2491 f := t.storage.Capacity
2499 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2500 return pieceIndex(ri / t.chunksPerRegularPiece())
2503 type requestState struct {