20 "github.com/RoaringBitmap/roaring"
21 "github.com/anacrolix/chansync"
22 "github.com/anacrolix/chansync/events"
23 "github.com/anacrolix/dht/v2"
24 . "github.com/anacrolix/generics"
25 "github.com/anacrolix/log"
26 "github.com/anacrolix/missinggo/perf"
27 "github.com/anacrolix/missinggo/slices"
28 "github.com/anacrolix/missinggo/v2"
29 "github.com/anacrolix/missinggo/v2/bitmap"
30 "github.com/anacrolix/missinggo/v2/pubsub"
31 "github.com/anacrolix/multiless"
32 "github.com/anacrolix/sync"
33 request_strategy "github.com/anacrolix/torrent/request-strategy"
34 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
35 "github.com/davecgh/go-spew/spew"
36 "github.com/pion/datachannel"
38 "github.com/anacrolix/torrent/bencode"
39 "github.com/anacrolix/torrent/common"
40 "github.com/anacrolix/torrent/metainfo"
41 pp "github.com/anacrolix/torrent/peer_protocol"
42 "github.com/anacrolix/torrent/segments"
43 "github.com/anacrolix/torrent/storage"
44 "github.com/anacrolix/torrent/tracker"
45 "github.com/anacrolix/torrent/webseed"
46 "github.com/anacrolix/torrent/webtorrent"
49 // Maintains state of torrent within a Client. Many methods should not be called before the info is
50 // available, see .Info and .GotInfo.
52 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
53 // alignment. See #262.
58 networkingEnabled chansync.Flag
59 dataDownloadDisallowed chansync.Flag
60 dataUploadDisallowed bool
61 userOnWriteChunkErr func(error)
63 closed chansync.SetOnce
64 infoHash metainfo.Hash
67 // The order pieces are requested if there's no stronger reason like availability or priority.
68 pieceRequestOrder []int
69 // Values are the piece indices that changed.
70 pieceStateChanges pubsub.PubSub[PieceStateChange]
71 // The size of chunks to request from peers over the wire. This is
72 // normally 16KiB by convention these days.
75 // Total length of the torrent in bytes. Stored because it's not O(1) to
76 // get this from the info dict.
79 // The storage to open when the info dict becomes available.
80 storageOpener *storage.Client
81 // Storage for torrent data.
82 storage *storage.Torrent
83 // Read-locked for using storage, and write-locked for Closing.
84 storageLock sync.RWMutex
86 // TODO: Only announce stuff is used?
87 metainfo metainfo.MetaInfo
89 // The info dict. nil if we don't have it (yet).
91 fileIndex segments.Index
94 _chunksPerRegularPiece chunkIndexType
96 webSeeds map[string]*Peer
97 // Active peer connections, running message stream loops. TODO: Make this
98 // open (not-closed) connections only.
99 conns map[*PeerConn]struct{}
100 maxEstablishedConns int
101 // Set of addrs to which we're attempting to connect. Connections are
102 // half-open until all handshakes are completed.
103 halfOpen map[string]PeerInfo
105 // Reserve of peers to connect to. A peer can be both here and in the
106 // active connections if were told about the peer after connecting with
107 // them. That encourages us to reconnect to peers that are well known in
109 peers prioritizedPeers
110 // Whether we want to know to know more peers.
111 wantPeersEvent missinggo.Event
112 // An announcer for each tracker URL.
113 trackerAnnouncers map[string]torrentTrackerAnnouncer
114 // How many times we've initiated a DHT announce. TODO: Move into stats.
117 // Name used if the info name isn't available. Should be cleared when the
118 // Info does become available.
122 // The bencoded bytes of the info dict. This is actively manipulated if
123 // the info bytes aren't initially available, and we try to fetch them
126 // Each element corresponds to the 16KiB metadata pieces. If true, we have
127 // received that piece.
128 metadataCompletedChunks []bool
129 metadataChanged sync.Cond
131 // Closed when .Info is obtained.
132 gotMetainfoC chan struct{}
134 readers map[*reader]struct{}
135 _readerNowPieces bitmap.Bitmap
136 _readerReadaheadPieces bitmap.Bitmap
138 // A cache of pieces we need to get. Calculated from various piece and
139 // file priorities and completion states elsewhere.
140 _pendingPieces roaring.Bitmap
141 // A cache of completed piece indices.
142 _completedPieces roaring.Bitmap
143 // Pieces that need to be hashed.
144 piecesQueuedForHash bitmap.Bitmap
145 activePieceHashes int
146 initialPieceCheckDisabled bool
148 connsWithAllPieces map[*Peer]struct{}
150 requestState map[RequestIndex]requestState
151 // Chunks we've written to since the corresponding piece was last checked.
152 dirtyChunks typedRoaring.Bitmap[RequestIndex]
156 // Is On when all pieces are complete.
157 Complete chansync.Flag
159 // Torrent sources in use keyed by the source string.
160 activeSources sync.Map
161 sourcesLogger log.Logger
163 smartBanCache smartBanCache
165 // Large allocations reused between request state updates.
166 requestPieceStates []request_strategy.PieceRequestOrderState
167 requestIndexes []RequestIndex
170 func (t *Torrent) length() int64 {
171 return t._length.Value
174 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
175 // This could be done with roaring.BitSliceIndexing.
176 t.iterPeers(func(peer *Peer) {
177 if _, ok := t.connsWithAllPieces[peer]; ok {
180 if peer.peerHasPiece(i) {
187 func (t *Torrent) decPieceAvailability(i pieceIndex) {
192 if p.relativeAvailability <= 0 {
193 panic(p.relativeAvailability)
195 p.relativeAvailability--
196 t.updatePieceRequestOrder(i)
199 func (t *Torrent) incPieceAvailability(i pieceIndex) {
200 // If we don't the info, this should be reconciled when we do.
203 p.relativeAvailability++
204 t.updatePieceRequestOrder(i)
208 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
209 return t._readerNowPieces
212 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
213 return t._readerReadaheadPieces
216 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
217 return !t.wantPieceIndex(i)
220 // Returns a channel that is closed when the Torrent is closed.
221 func (t *Torrent) Closed() events.Done {
222 return t.closed.Done()
225 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
226 // pending, and half-open peers.
227 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
228 // Add pending peers to the list
229 t.peers.Each(func(peer PeerInfo) {
230 ks = append(ks, peer)
233 // Add half-open peers to the list
234 for _, peer := range t.halfOpen {
235 ks = append(ks, peer)
238 // Add active peers to the list
239 for conn := range t.conns {
240 ks = append(ks, PeerInfo{
242 Addr: conn.RemoteAddr,
243 Source: conn.Discovery,
244 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
245 // > But if we're not connected to them with an encrypted connection, I couldn't say
246 // > what's appropriate. We can carry forward the SupportsEncryption value as we
247 // > received it from trackers/DHT/PEX, or just use the encryption state for the
248 // > connection. It's probably easiest to do the latter for now.
249 // https://github.com/anacrolix/torrent/pull/188
250 SupportsEncryption: conn.headerEncrypted,
257 func (t *Torrent) setChunkSize(size pp.Integer) {
259 t.chunkPool = sync.Pool{
260 New: func() interface{} {
261 b := make([]byte, size)
267 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
268 return t._completedPieces.Contains(bitmap.BitIndex(piece))
271 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
272 if t.storage == nil {
273 return storage.Completion{Complete: false, Ok: true}
275 return t.pieces[piece].Storage().Completion()
278 // There's a connection to that address already.
279 func (t *Torrent) addrActive(addr string) bool {
280 if _, ok := t.halfOpen[addr]; ok {
283 for c := range t.conns {
285 if ra.String() == addr {
292 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
293 return t.appendConns(ret, func(conn *PeerConn) bool {
294 return !conn.closed.IsSet()
298 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
299 for c := range t.conns {
307 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
309 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
310 if t.closed.IsSet() {
313 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
314 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
315 torrent.Add("peers not added because of bad addr", 1)
316 // cl.logger.Printf("peers not added because of bad addr: %v", p)
320 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
321 torrent.Add("peers replaced", 1)
322 if !replaced.equal(p) {
323 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
330 for t.peers.Len() > cl.config.TorrentPeersHighWater {
331 _, ok := t.peers.DeleteMin()
333 torrent.Add("excess reserve peers discarded", 1)
339 func (t *Torrent) invalidateMetadata() {
340 for i := 0; i < len(t.metadataCompletedChunks); i++ {
341 t.metadataCompletedChunks[i] = false
344 t.gotMetainfoC = make(chan struct{})
349 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
353 if index >= len(t.metadataCompletedChunks) {
354 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
357 copy(t.metadataBytes[(1<<14)*index:], data)
358 t.metadataCompletedChunks[index] = true
361 func (t *Torrent) metadataPieceCount() int {
362 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
365 func (t *Torrent) haveMetadataPiece(piece int) bool {
367 return (1<<14)*piece < len(t.metadataBytes)
369 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
373 func (t *Torrent) metadataSize() int {
374 return len(t.metadataBytes)
377 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
378 for i := 0; i < len(info.Pieces); i += sha1.Size {
379 ret = append(ret, info.Pieces[i:i+sha1.Size])
384 func (t *Torrent) makePieces() {
385 hashes := infoPieceHashes(t.info)
386 t.pieces = make([]Piece, len(hashes))
387 for i, hash := range hashes {
388 piece := &t.pieces[i]
390 piece.index = pieceIndex(i)
391 piece.noPendingWrites.L = &piece.pendingWritesMutex
392 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
394 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
395 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
396 piece.files = files[beginFile:endFile]
400 // Returns the index of the first file containing the piece. files must be
401 // ordered by offset.
402 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
403 for i, f := range files {
404 if f.offset+f.length > pieceOffset {
411 // Returns the index after the last file containing the piece. files must be
412 // ordered by offset.
413 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
414 for i, f := range files {
415 if f.offset+f.length >= pieceEndOffset {
422 func (t *Torrent) cacheLength() {
424 for _, f := range t.info.UpvertedFiles() {
430 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
432 func (t *Torrent) setInfo(info *metainfo.Info) error {
433 if err := validateInfo(info); err != nil {
434 return fmt.Errorf("bad info: %s", err)
436 if t.storageOpener != nil {
438 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
440 return fmt.Errorf("error opening torrent storage: %s", err)
446 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
448 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
449 t.displayName = "" // Save a few bytes lol.
456 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
457 return request_strategy.PieceRequestOrderKey{
458 InfoHash: t.infoHash,
463 // This seems to be all the follow-up tasks after info is set, that can't fail.
464 func (t *Torrent) onSetInfo() {
465 t.pieceRequestOrder = rand.Perm(t.numPieces())
466 t.initPieceRequestOrder()
467 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
468 for i := range t.pieces {
470 // Need to add relativeAvailability before updating piece completion, as that may result in conns
472 if p.relativeAvailability != 0 {
473 panic(p.relativeAvailability)
475 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
476 t.addRequestOrderPiece(i)
477 t.updatePieceCompletion(i)
478 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
479 // t.logger.Printf("piece %s completion unknown, queueing check", p)
483 t.cl.event.Broadcast()
484 close(t.gotMetainfoC)
485 t.updateWantPeersEvent()
486 t.requestState = make(map[RequestIndex]requestState)
487 t.tryCreateMorePieceHashers()
488 t.iterPeers(func(p *Peer) {
490 p.updateRequests("onSetInfo")
494 // Called when metadata for a torrent becomes available.
495 func (t *Torrent) setInfoBytesLocked(b []byte) error {
496 if metainfo.HashBytes(b) != t.infoHash {
497 return errors.New("info bytes have wrong hash")
499 var info metainfo.Info
500 if err := bencode.Unmarshal(b, &info); err != nil {
501 return fmt.Errorf("error unmarshalling info bytes: %s", err)
504 t.metadataCompletedChunks = nil
508 if err := t.setInfo(&info); err != nil {
515 func (t *Torrent) haveAllMetadataPieces() bool {
519 if t.metadataCompletedChunks == nil {
522 for _, have := range t.metadataCompletedChunks {
530 // TODO: Propagate errors to disconnect peer.
531 func (t *Torrent) setMetadataSize(size int) (err error) {
533 // We already know the correct metadata size.
536 if uint32(size) > maxMetadataSize {
537 return errors.New("bad size")
539 if len(t.metadataBytes) == size {
542 t.metadataBytes = make([]byte, size)
543 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
544 t.metadataChanged.Broadcast()
545 for c := range t.conns {
546 c.requestPendingMetadata()
551 // The current working name for the torrent. Either the name in the info dict,
552 // or a display name given such as by the dn value in a magnet link, or "".
553 func (t *Torrent) name() string {
555 defer t.nameMu.RUnlock()
557 return t.info.BestName()
559 if t.displayName != "" {
562 return "infohash:" + t.infoHash.HexString()
565 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
566 p := &t.pieces[index]
567 ret.Priority = t.piecePriority(index)
568 ret.Completion = p.completion()
569 ret.QueuedForHash = p.queuedForHash()
570 ret.Hashing = p.hashing
571 ret.Checking = ret.QueuedForHash || ret.Hashing
572 ret.Marking = p.marking
573 if !ret.Complete && t.piecePartiallyDownloaded(index) {
579 func (t *Torrent) metadataPieceSize(piece int) int {
580 return metadataPieceSize(len(t.metadataBytes), piece)
583 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
586 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
587 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
589 TotalSize: len(t.metadataBytes),
595 type pieceAvailabilityRun struct {
600 func (me pieceAvailabilityRun) String() string {
601 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
604 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
605 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
606 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
608 for i := range t.pieces {
609 rle.Append(t.pieces[i].availability(), 1)
615 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
616 freqs = make([]int, t.numActivePeers()+1)
617 for i := range t.pieces {
618 freqs[t.piece(i).availability()]++
623 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
624 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
625 ret = append(ret, PieceStateRun{
626 PieceState: el.(PieceState),
630 for index := range t.pieces {
631 rle.Append(t.pieceState(pieceIndex(index)), 1)
637 // Produces a small string representing a PieceStateRun.
638 func (psr PieceStateRun) String() (ret string) {
639 ret = fmt.Sprintf("%d", psr.Length)
640 ret += func() string {
641 switch psr.Priority {
642 case PiecePriorityNext:
644 case PiecePriorityNormal:
646 case PiecePriorityReadahead:
648 case PiecePriorityNow:
650 case PiecePriorityHigh:
659 if psr.QueuedForHash {
677 func (t *Torrent) writeStatus(w io.Writer) {
678 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
679 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
681 fmt.Fprintf(w, "Metadata have: ")
682 for _, h := range t.metadataCompletedChunks {
683 fmt.Fprintf(w, "%c", func() rune {
693 fmt.Fprintf(w, "Piece length: %s\n",
696 return fmt.Sprintf("%v (%v chunks)",
698 float64(t.usualPieceSize())/float64(t.chunkSize))
705 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
706 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
707 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
708 // availability frequencies instead.
710 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
711 for _, run := range t.pieceAvailabilityRuns() {
712 ret = append(ret, run.String())
717 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
718 func() (ret []string) {
719 for avail, freq := range t.pieceAvailabilityFrequencies() {
723 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
729 fmt.Fprintf(w, "Reader Pieces:")
730 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
731 fmt.Fprintf(w, " %d:%d", begin, end)
736 fmt.Fprintf(w, "Enabled trackers:\n")
738 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
739 fmt.Fprintf(tw, " URL\tExtra\n")
740 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
743 var luns, runs url.URL = *lu, *ru
746 var ml missinggo.MultiLess
747 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
748 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
750 }).([]torrentTrackerAnnouncer) {
751 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
756 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
758 spew.NewDefaultConfig()
759 spew.Fdump(w, t.statsLocked())
761 peers := t.peersAsSlice()
762 sort.Slice(peers, func(_i, _j int) bool {
765 if less, ok := multiless.New().EagerSameLess(
766 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
770 return worseConn(i, j)
772 for i, c := range peers {
773 fmt.Fprintf(w, "%2d. ", i+1)
778 func (t *Torrent) haveInfo() bool {
782 // Returns a run-time generated MetaInfo that includes the info bytes and
783 // announce-list as currently known to the client.
784 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
785 return metainfo.MetaInfo{
786 CreationDate: time.Now().Unix(),
787 Comment: "dynamic metainfo from client",
788 CreatedBy: "go.torrent",
789 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
790 InfoBytes: func() []byte {
792 return t.metadataBytes
797 UrlList: func() []string {
798 ret := make([]string, 0, len(t.webSeeds))
799 for url := range t.webSeeds {
800 ret = append(ret, url)
808 func (t *Torrent) BytesMissing() (n int64) {
810 n = t.bytesMissingLocked()
815 func (t *Torrent) bytesMissingLocked() int64 {
819 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
820 roaring.Flip(b, 0, end).Iterate(cb)
823 func (t *Torrent) bytesLeft() (left int64) {
824 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
825 p := t.piece(pieceIndex(x))
826 left += int64(p.length() - p.numDirtyBytes())
832 // Bytes left to give in tracker announces.
833 func (t *Torrent) bytesLeftAnnounce() int64 {
841 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
842 if t.pieceComplete(piece) {
845 if t.pieceAllDirty(piece) {
848 return t.pieces[piece].hasDirtyChunks()
851 func (t *Torrent) usualPieceSize() int {
852 return int(t.info.PieceLength)
855 func (t *Torrent) numPieces() pieceIndex {
856 return t.info.NumPieces()
859 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
860 return pieceIndex(t._completedPieces.GetCardinality())
863 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
865 err = errors.New("already closed")
868 if t.storage != nil {
873 defer t.storageLock.Unlock()
874 if f := t.storage.Close; f != nil {
877 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
882 t.iterPeers(func(p *Peer) {
885 if t.storage != nil {
886 t.deletePieceRequestOrder()
888 for i := range t.pieces {
890 if p.relativeAvailability != 0 {
891 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
895 t.cl.event.Broadcast()
896 t.pieceStateChanges.Close()
897 t.updateWantPeersEvent()
901 func (t *Torrent) requestOffset(r Request) int64 {
902 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
905 // Return the request that would include the given offset into the torrent data. Returns !ok if
906 // there is no such request.
907 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
908 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
911 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
912 defer perf.ScopeTimerErr(&err)()
913 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
914 if err == nil && n != len(data) {
915 err = io.ErrShortWrite
920 func (t *Torrent) bitfield() (bf []bool) {
921 bf = make([]bool, t.numPieces())
922 t._completedPieces.Iterate(func(piece uint32) (again bool) {
929 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
930 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
933 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
934 return t._chunksPerRegularPiece
937 func (t *Torrent) numChunks() RequestIndex {
938 if t.numPieces() == 0 {
941 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
944 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
945 t.dirtyChunks.RemoveRange(
946 uint64(t.pieceRequestIndexOffset(pieceIndex)),
947 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
950 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
951 if t.info.PieceLength == 0 {
952 // There will be no variance amongst pieces. Only pain.
955 if piece == t.numPieces()-1 {
956 ret := pp.Integer(t.length() % t.info.PieceLength)
961 return pp.Integer(t.info.PieceLength)
964 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
965 return &blockCheckingWriter{
966 cache: &t.smartBanCache,
967 requestIndex: t.pieceRequestIndexOffset(piece),
968 chunkSize: t.chunkSize.Int(),
972 func (t *Torrent) hashPiece(piece pieceIndex) (
974 // These are peers that sent us blocks that differ from what we hash here.
975 differingPeers map[bannableAddr]struct{},
979 p.waitNoPendingWrites()
980 storagePiece := t.pieces[piece].Storage()
982 // Does the backend want to do its own hashing?
983 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
984 var sum metainfo.Hash
985 // log.Printf("A piece decided to self-hash: %d", piece)
986 sum, err = i.SelfHash()
987 missinggo.CopyExact(&ret, sum)
991 hash := pieceHash.New()
992 const logPieceContents = false
993 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
994 writers := []io.Writer{hash, smartBanWriter}
995 var examineBuf bytes.Buffer
996 if logPieceContents {
997 writers = append(writers, &examineBuf)
999 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1000 if logPieceContents {
1001 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1003 smartBanWriter.Flush()
1004 differingPeers = smartBanWriter.badPeers
1005 missinggo.CopyExact(&ret, hash.Sum(nil))
1009 func (t *Torrent) haveAnyPieces() bool {
1010 return !t._completedPieces.IsEmpty()
1013 func (t *Torrent) haveAllPieces() bool {
1017 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1020 func (t *Torrent) havePiece(index pieceIndex) bool {
1021 return t.haveInfo() && t.pieceComplete(index)
1024 func (t *Torrent) maybeDropMutuallyCompletePeer(
1025 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1029 if !t.cl.config.DropMutuallyCompletePeers {
1032 if !t.haveAllPieces() {
1035 if all, known := p.peerHasAllPieces(); !(known && all) {
1041 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1045 func (t *Torrent) haveChunk(r Request) (ret bool) {
1047 // log.Println("have chunk", r, ret)
1052 if t.pieceComplete(pieceIndex(r.Index)) {
1055 p := &t.pieces[r.Index]
1056 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1059 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1060 return chunkIndexType(cs.Begin / chunkSize)
1063 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1064 return t._pendingPieces.Contains(uint32(index))
1067 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1068 // conns (which is a map).
1069 var peerConnSlices sync.Pool
1071 func getPeerConnSlice(cap int) []*PeerConn {
1072 getInterface := peerConnSlices.Get()
1073 if getInterface == nil {
1074 return make([]*PeerConn, 0, cap)
1076 return getInterface.([]*PeerConn)[:0]
1080 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1081 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1082 // established connections for more than a minute. This is O(n log n). If there was a way to not
1083 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1084 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1085 wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
1086 defer peerConnSlices.Put(wcs.conns)
1089 for wcs.Len() != 0 {
1090 c := heap.Pop(&wcs).(*PeerConn)
1091 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1094 // If the connection is in the worst half of the established
1095 // connection quota and is older than a minute.
1096 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1097 // Give connections 1 minute to prove themselves.
1098 if time.Since(c.completedHandshake) > time.Minute {
1106 type PieceStateChange struct {
1111 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1112 t.cl._mu.Defer(func() {
1113 cur := t.pieceState(piece)
1114 p := &t.pieces[piece]
1115 if cur != p.publicPieceState {
1116 p.publicPieceState = cur
1117 t.pieceStateChanges.Publish(PieceStateChange{
1125 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1126 if t.pieceComplete(piece) {
1129 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1132 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1133 return t.pieces[piece].allChunksDirty()
1136 func (t *Torrent) readersChanged() {
1137 t.updateReaderPieces()
1138 t.updateAllPiecePriorities("Torrent.readersChanged")
1141 func (t *Torrent) updateReaderPieces() {
1142 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1145 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1149 t.updateReaderPieces()
1150 // Order the ranges, high and low.
1152 if l.begin > h.begin {
1155 if l.end < h.begin {
1156 // Two distinct ranges.
1157 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1158 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1165 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1169 func (t *Torrent) maybeNewConns() {
1170 // Tickle the accept routine.
1171 t.cl.event.Broadcast()
1175 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1176 if t._pendingPieces.Contains(uint32(piece)) {
1177 t.iterPeers(func(c *Peer) {
1178 // if c.requestState.Interested {
1181 if !c.isLowOnRequests() {
1184 if !c.peerHasPiece(piece) {
1187 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1190 c.updateRequests(reason)
1194 t.publishPieceChange(piece)
1197 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1198 if !t.closed.IsSet() {
1199 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1201 t.updatePieceRequestOrder(piece)
1203 p := &t.pieces[piece]
1204 newPrio := p.uncachedPriority()
1205 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1206 if newPrio == PiecePriorityNone {
1207 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1211 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1215 t.piecePriorityChanged(piece, reason)
1218 func (t *Torrent) updateAllPiecePriorities(reason string) {
1219 t.updatePiecePriorities(0, t.numPieces(), reason)
1222 // Update all piece priorities in one hit. This function should have the same
1223 // output as updatePiecePriority, but across all pieces.
1224 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1225 for i := begin; i < end; i++ {
1226 t.updatePiecePriority(i, reason)
1230 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1231 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1232 if off >= t.length() {
1242 begin = pieceIndex(off / t.info.PieceLength)
1243 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1244 if end > pieceIndex(t.info.NumPieces()) {
1245 end = pieceIndex(t.info.NumPieces())
1250 // Returns true if all iterations complete without breaking. Returns the read regions for all
1251 // readers. The reader regions should not be merged as some callers depend on this method to
1252 // enumerate readers.
1253 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1254 for r := range t.readers {
1256 if p.begin >= p.end {
1259 if !f(p.begin, p.end) {
1266 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1267 return t.piece(piece).uncachedPriority()
1270 func (t *Torrent) pendRequest(req RequestIndex) {
1271 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1274 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1275 t.cl.event.Broadcast()
1276 if t.pieceComplete(piece) {
1277 t.onPieceCompleted(piece)
1279 t.onIncompletePiece(piece)
1281 t.updatePiecePriority(piece, reason)
1284 func (t *Torrent) numReceivedConns() (ret int) {
1285 for c := range t.conns {
1286 if c.Discovery == PeerSourceIncoming {
1293 func (t *Torrent) maxHalfOpen() int {
1294 // Note that if we somehow exceed the maximum established conns, we want
1295 // the negative value to have an effect.
1296 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1297 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1298 // We want to allow some experimentation with new peers, and to try to
1299 // upset an oversupply of received connections.
1300 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1303 func (t *Torrent) openNewConns() (initiated int) {
1304 defer t.updateWantPeersEvent()
1305 for t.peers.Len() != 0 {
1309 if len(t.halfOpen) >= t.maxHalfOpen() {
1312 if len(t.cl.dialers) == 0 {
1315 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1318 p := t.peers.PopMax()
1325 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1327 uncached := t.pieceCompleteUncached(piece)
1328 cached := p.completion()
1329 changed := cached != uncached
1330 complete := uncached.Complete
1331 p.storageCompletionOk = uncached.Ok
1334 t._completedPieces.Add(x)
1337 t._completedPieces.Remove(x)
1339 p.t.updatePieceRequestOrder(piece)
1341 if complete && len(p.dirtiers) != 0 {
1342 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1345 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1346 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1351 // Non-blocking read. Client lock is not required.
1352 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1354 p := &t.pieces[off/t.info.PieceLength]
1355 p.waitNoPendingWrites()
1357 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1368 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1369 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1370 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1371 func (t *Torrent) maybeCompleteMetadata() error {
1376 if !t.haveAllMetadataPieces() {
1377 // Don't have enough metadata pieces.
1380 err := t.setInfoBytesLocked(t.metadataBytes)
1382 t.invalidateMetadata()
1383 return fmt.Errorf("error setting info bytes: %s", err)
1385 if t.cl.config.Debug {
1386 t.logger.Printf("%s: got metadata from peers", t)
1391 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1392 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1394 now.Add(bitmap.BitIndex(begin))
1395 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1402 func (t *Torrent) needData() bool {
1403 if t.closed.IsSet() {
1409 return !t._pendingPieces.IsEmpty()
1412 func appendMissingStrings(old, new []string) (ret []string) {
1415 for _, n := range new {
1416 for _, o := range old {
1421 ret = append(ret, n)
1426 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1428 for minNumTiers > len(ret) {
1429 ret = append(ret, nil)
1434 func (t *Torrent) addTrackers(announceList [][]string) {
1435 fullAnnounceList := &t.metainfo.AnnounceList
1436 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1437 for tierIndex, trackerURLs := range announceList {
1438 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1440 t.startMissingTrackerScrapers()
1441 t.updateWantPeersEvent()
1444 // Don't call this before the info is available.
1445 func (t *Torrent) bytesCompleted() int64 {
1449 return t.length() - t.bytesLeft()
1452 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1455 return t.setInfoBytesLocked(b)
1458 // Returns true if connection is removed from torrent.Conns.
1459 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1460 if !c.closed.IsSet() {
1461 panic("connection is not closed")
1462 // There are behaviours prevented by the closed state that will fail
1463 // if the connection has been deleted.
1467 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1468 // the drop event against the PexConnState instead.
1470 if !t.cl.config.DisablePEX {
1474 torrent.Add("deleted connections", 1)
1475 c.deleteAllRequests("Torrent.deletePeerConn")
1476 t.assertPendingRequests()
1477 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1478 panic(t.connsWithAllPieces)
1483 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1484 if t.deleteConnWithAllPieces(p) {
1490 p.peerPieces().Iterate(func(i uint32) bool {
1491 p.t.decPieceAvailability(pieceIndex(i))
1496 func (t *Torrent) assertPendingRequests() {
1500 // var actual pendingRequests
1501 // if t.haveInfo() {
1502 // actual.m = make([]int, t.numChunks())
1504 // t.iterPeers(func(p *Peer) {
1505 // p.requestState.Requests.Iterate(func(x uint32) bool {
1510 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1516 func (t *Torrent) dropConnection(c *PeerConn) {
1517 t.cl.event.Broadcast()
1519 if t.deletePeerConn(c) {
1524 // Peers as in contact information for dialing out.
1525 func (t *Torrent) wantPeers() bool {
1526 if t.closed.IsSet() {
1529 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1532 return t.wantConns()
1535 func (t *Torrent) updateWantPeersEvent() {
1537 t.wantPeersEvent.Set()
1539 t.wantPeersEvent.Clear()
1543 // Returns whether the client should make effort to seed the torrent.
1544 func (t *Torrent) seeding() bool {
1546 if t.closed.IsSet() {
1549 if t.dataUploadDisallowed {
1552 if cl.config.NoUpload {
1555 if !cl.config.Seed {
1558 if cl.config.DisableAggressiveUpload && t.needData() {
1564 func (t *Torrent) onWebRtcConn(
1565 c datachannel.ReadWriteCloser,
1566 dcc webtorrent.DataChannelContext,
1569 netConn := webrtcNetConn{
1571 DataChannelContext: dcc,
1573 peerRemoteAddr := netConn.RemoteAddr()
1574 if t.cl.badPeerAddr(peerRemoteAddr) {
1577 pc, err := t.cl.initiateProtocolHandshakes(
1578 context.Background(),
1583 netConn.RemoteAddr(),
1585 fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1588 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1591 if dcc.LocalOffered {
1592 pc.Discovery = PeerSourceTracker
1594 pc.Discovery = PeerSourceIncoming
1596 pc.conn.SetWriteDeadline(time.Time{})
1599 err = t.cl.runHandshookConn(pc, t)
1601 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1605 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1606 err := t.cl.runHandshookConn(pc, t)
1607 if err != nil || logAll {
1608 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1612 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1613 t.logRunHandshookConn(pc, false, log.Debug)
1616 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1617 wtc, release := t.cl.websocketTrackers.Get(u.String())
1622 wst := websocketTrackerStatus{u, wtc}
1624 err := wtc.Announce(tracker.Started, t.infoHash)
1626 t.logger.WithDefaultLevel(log.Warning).Printf(
1627 "error in initial announce to %q: %v",
1635 func (t *Torrent) startScrapingTracker(_url string) {
1639 u, err := url.Parse(_url)
1641 // URLs with a leading '*' appear to be a uTorrent convention to
1642 // disable trackers.
1644 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1648 if u.Scheme == "udp" {
1650 t.startScrapingTracker(u.String())
1652 t.startScrapingTracker(u.String())
1655 if _, ok := t.trackerAnnouncers[_url]; ok {
1658 sl := func() torrentTrackerAnnouncer {
1661 if t.cl.config.DisableWebtorrent {
1664 return t.startWebsocketAnnouncer(*u)
1666 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1670 if t.cl.config.DisableIPv6 {
1674 newAnnouncer := &trackerScraper{
1677 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1679 go newAnnouncer.Run()
1685 if t.trackerAnnouncers == nil {
1686 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1688 t.trackerAnnouncers[_url] = sl
1691 // Adds and starts tracker scrapers for tracker URLs that aren't already
1693 func (t *Torrent) startMissingTrackerScrapers() {
1694 if t.cl.config.DisableTrackers {
1697 t.startScrapingTracker(t.metainfo.Announce)
1698 for _, tier := range t.metainfo.AnnounceList {
1699 for _, url := range tier {
1700 t.startScrapingTracker(url)
1705 // Returns an AnnounceRequest with fields filled out to defaults and current
1707 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1708 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1709 // dependent on the network in use.
1710 return tracker.AnnounceRequest{
1712 NumWant: func() int32 {
1713 if t.wantPeers() && len(t.cl.dialers) > 0 {
1719 Port: uint16(t.cl.incomingPeerPort()),
1720 PeerId: t.cl.peerID,
1721 InfoHash: t.infoHash,
1722 Key: t.cl.announceKey(),
1724 // The following are vaguely described in BEP 3.
1726 Left: t.bytesLeftAnnounce(),
1727 Uploaded: t.stats.BytesWrittenData.Int64(),
1728 // There's no mention of wasted or unwanted download in the BEP.
1729 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1733 // Adds peers revealed in an announce until the announce ends, or we have
1735 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1737 for v := range pvs {
1740 for _, cp := range v.Peers {
1742 // Can't do anything with this.
1745 if t.addPeer(PeerInfo{
1746 Addr: ipPortAddr{cp.IP, cp.Port},
1747 Source: PeerSourceDhtGetPeers,
1754 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1759 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1760 // announce ends. stop will force the announce to end.
1761 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1762 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1766 _done := make(chan struct{})
1770 t.consumeDhtAnnouncePeers(ps.Peers())
1776 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1777 _, stop, err := t.AnnounceToDht(s)
1782 case <-t.closed.Done():
1783 case <-time.After(5 * time.Minute):
1789 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1795 if t.closed.IsSet() {
1798 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1799 // TODO: We can include the announce_peer step depending on whether we can receive
1800 // inbound connections. We should probably only announce once every 15 mins too.
1804 // TODO: Determine if there's a listener on the port we're announcing.
1805 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1816 err := t.timeboxedAnnounceToDht(s)
1818 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1824 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1825 for _, p := range peers {
1833 // The returned TorrentStats may require alignment in memory. See
1834 // https://github.com/anacrolix/torrent/issues/383.
1835 func (t *Torrent) Stats() TorrentStats {
1837 defer t.cl.rUnlock()
1838 return t.statsLocked()
1841 func (t *Torrent) statsLocked() (ret TorrentStats) {
1842 ret.ActivePeers = len(t.conns)
1843 ret.HalfOpenPeers = len(t.halfOpen)
1844 ret.PendingPeers = t.peers.Len()
1845 ret.TotalPeers = t.numTotalPeers()
1846 ret.ConnectedSeeders = 0
1847 for c := range t.conns {
1848 if all, ok := c.peerHasAllPieces(); all && ok {
1849 ret.ConnectedSeeders++
1852 ret.ConnStats = t.stats.Copy()
1853 ret.PiecesComplete = t.numPiecesCompleted()
1857 // The total number of peers in the torrent.
1858 func (t *Torrent) numTotalPeers() int {
1859 peers := make(map[string]struct{})
1860 for conn := range t.conns {
1861 ra := conn.conn.RemoteAddr()
1863 // It's been closed and doesn't support RemoteAddr.
1866 peers[ra.String()] = struct{}{}
1868 for addr := range t.halfOpen {
1869 peers[addr] = struct{}{}
1871 t.peers.Each(func(peer PeerInfo) {
1872 peers[peer.Addr.String()] = struct{}{}
1877 // Reconcile bytes transferred before connection was associated with a
1879 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1880 if c._stats != (ConnStats{
1881 // Handshakes should only increment these fields:
1882 BytesWritten: c._stats.BytesWritten,
1883 BytesRead: c._stats.BytesRead,
1887 c.postHandshakeStats(func(cs *ConnStats) {
1888 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1889 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1891 c.reconciledHandshakeStats = true
1894 // Returns true if the connection is added.
1895 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1898 torrent.Add("added connections", 1)
1901 if t.closed.IsSet() {
1902 return errors.New("torrent closed")
1904 for c0 := range t.conns {
1905 if c.PeerID != c0.PeerID {
1908 if !t.cl.config.DropDuplicatePeerIds {
1911 if c.hasPreferredNetworkOver(c0) {
1913 t.deletePeerConn(c0)
1915 return errors.New("existing connection preferred")
1918 if len(t.conns) >= t.maxEstablishedConns {
1919 c := t.worstBadConn()
1921 return errors.New("don't want conns")
1926 if len(t.conns) >= t.maxEstablishedConns {
1929 t.conns[c] = struct{}{}
1930 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1931 t.pex.Add(c) // as no further extended handshake expected
1936 func (t *Torrent) wantConns() bool {
1937 if !t.networkingEnabled.Bool() {
1940 if t.closed.IsSet() {
1943 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
1946 return len(t.conns) < t.maxEstablishedConns || t.worstBadConn() != nil
1949 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1952 oldMax = t.maxEstablishedConns
1953 t.maxEstablishedConns = max
1954 wcs := worseConnSlice{
1955 conns: t.appendConns(nil, func(*PeerConn) bool {
1961 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1962 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
1968 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1969 t.logger.LazyLog(log.Debug, func() log.Msg {
1970 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
1974 t.cl.event.Broadcast()
1975 if t.closed.IsSet() {
1979 // Don't score the first time a piece is hashed, it could be an initial check.
1980 if p.storageCompletionOk {
1982 pieceHashedCorrect.Add(1)
1985 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1986 ).AddValues(t, p).LogLevel(
1988 log.Debug, t.logger)
1990 pieceHashedNotCorrect.Add(1)
1995 t.publishPieceChange(piece)
1998 t.publishPieceChange(piece)
2002 if len(p.dirtiers) != 0 {
2003 // Don't increment stats above connection-level for every involved connection.
2004 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2006 for c := range p.dirtiers {
2007 c._stats.incrementPiecesDirtiedGood()
2009 t.clearPieceTouchers(piece)
2011 err := p.Storage().MarkComplete()
2013 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2017 if t.closed.IsSet() {
2020 t.pendAllChunkSpecs(piece)
2022 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2023 // Peers contributed to all the data for this piece hash failure, and the failure was
2024 // not due to errors in the storage (such as data being dropped in a cache).
2026 // Increment Torrent and above stats, and then specific connections.
2027 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2028 for c := range p.dirtiers {
2029 // Y u do dis peer?!
2030 c.stats().incrementPiecesDirtiedBad()
2033 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2034 for c := range p.dirtiers {
2036 bannableTouchers = append(bannableTouchers, c)
2039 t.clearPieceTouchers(piece)
2040 slices.Sort(bannableTouchers, connLessTrusted)
2042 if t.cl.config.Debug {
2044 "bannable conns by trust for piece %d: %v",
2046 func() (ret []connectionTrust) {
2047 for _, c := range bannableTouchers {
2048 ret = append(ret, c.trust())
2055 if len(bannableTouchers) >= 1 {
2056 c := bannableTouchers[0]
2057 if len(bannableTouchers) != 1 {
2058 t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2060 // Turns out it's still useful to ban peers like this because if there's only a
2061 // single peer for a piece, and we never progress that piece to completion, we
2062 // will never smart-ban them. Discovered in
2063 // https://github.com/anacrolix/torrent/issues/715.
2064 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2069 t.onIncompletePiece(piece)
2070 p.Storage().MarkNotComplete()
2072 t.updatePieceCompletion(piece)
2075 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2076 start := t.pieceRequestIndexOffset(piece)
2077 end := start + t.pieceNumChunks(piece)
2078 for ri := start; ri < end; ri++ {
2083 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2084 t.pendAllChunkSpecs(piece)
2085 t.cancelRequestsForPiece(piece)
2086 t.piece(piece).readerCond.Broadcast()
2087 for conn := range t.conns {
2089 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2093 // Called when a piece is found to be not complete.
2094 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2095 if t.pieceAllDirty(piece) {
2096 t.pendAllChunkSpecs(piece)
2098 if !t.wantPieceIndex(piece) {
2099 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2102 // We could drop any connections that we told we have a piece that we
2103 // don't here. But there's a test failure, and it seems clients don't care
2104 // if you request pieces that you already claim to have. Pruning bad
2105 // connections might just remove any connections that aren't treating us
2106 // favourably anyway.
2108 // for c := range t.conns {
2109 // if c.sentHave(piece) {
2113 t.iterPeers(func(conn *Peer) {
2114 if conn.peerHasPiece(piece) {
2115 conn.updateRequests("piece incomplete")
2120 func (t *Torrent) tryCreateMorePieceHashers() {
2121 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2125 func (t *Torrent) tryCreatePieceHasher() bool {
2126 if t.storage == nil {
2129 pi, ok := t.getPieceToHash()
2134 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2136 t.publishPieceChange(pi)
2137 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2138 t.storageLock.RLock()
2139 t.activePieceHashes++
2140 go t.pieceHasher(pi)
2144 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2145 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2146 if t.piece(i).hashing {
2156 func (t *Torrent) dropBannedPeers() {
2157 t.iterPeers(func(p *Peer) {
2158 remoteIp := p.remoteIp()
2159 if remoteIp == nil {
2160 if p.bannableAddr.Ok {
2161 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2165 netipAddr := netip.MustParseAddr(remoteIp.String())
2166 if Some(netipAddr) != p.bannableAddr {
2167 t.logger.WithDefaultLevel(log.Debug).Printf(
2168 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2169 p, remoteIp, p.bannableAddr)
2171 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2172 // Should this be a close?
2174 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2179 func (t *Torrent) pieceHasher(index pieceIndex) {
2181 sum, failedPeers, copyErr := t.hashPiece(index)
2182 correct := sum == *p.hash
2186 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2188 t.storageLock.RUnlock()
2192 for peer := range failedPeers {
2193 t.cl.banPeerIP(peer.AsSlice())
2194 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2197 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2198 t.smartBanCache.ForgetBlock(ri)
2202 t.pieceHashed(index, correct, copyErr)
2203 t.updatePiecePriority(index, "Torrent.pieceHasher")
2204 t.activePieceHashes--
2205 t.tryCreateMorePieceHashers()
2208 // Return the connections that touched a piece, and clear the entries while doing it.
2209 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2211 for c := range p.dirtiers {
2212 delete(c.peerTouchedPieces, pi)
2213 delete(p.dirtiers, c)
2217 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2218 t.iterPeers(func(p *Peer) {
2219 ret = append(ret, p)
2224 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2225 piece := t.piece(pieceIndex)
2226 if piece.queuedForHash() {
2229 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2230 t.publishPieceChange(pieceIndex)
2231 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2232 t.tryCreateMorePieceHashers()
2235 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2236 // before the Info is available.
2237 func (t *Torrent) VerifyData() {
2238 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2239 t.Piece(i).VerifyData()
2243 // Start the process of connecting to the given peer for the given torrent if appropriate.
2244 func (t *Torrent) initiateConn(peer PeerInfo) {
2245 if peer.Id == t.cl.peerID {
2248 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2252 if t.addrActive(addr.String()) {
2256 t.halfOpen[addr.String()] = peer
2257 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2260 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2261 // quickly make one Client visible to the Torrent of another Client.
2262 func (t *Torrent) AddClientPeer(cl *Client) int {
2263 return t.AddPeers(func() (ps []PeerInfo) {
2264 for _, la := range cl.ListenAddrs() {
2265 ps = append(ps, PeerInfo{
2274 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2276 func (t *Torrent) allStats(f func(*ConnStats)) {
2281 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2282 return t.pieces[i].hashing
2285 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2286 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2289 func (t *Torrent) dialTimeout() time.Duration {
2290 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2293 func (t *Torrent) piece(i int) *Piece {
2297 func (t *Torrent) onWriteChunkErr(err error) {
2298 if t.userOnWriteChunkErr != nil {
2299 go t.userOnWriteChunkErr(err)
2302 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2303 t.disallowDataDownloadLocked()
2306 func (t *Torrent) DisallowDataDownload() {
2307 t.disallowDataDownloadLocked()
2310 func (t *Torrent) disallowDataDownloadLocked() {
2311 t.dataDownloadDisallowed.Set()
2314 func (t *Torrent) AllowDataDownload() {
2315 t.dataDownloadDisallowed.Clear()
2318 // Enables uploading data, if it was disabled.
2319 func (t *Torrent) AllowDataUpload() {
2322 t.dataUploadDisallowed = false
2323 for c := range t.conns {
2324 c.updateRequests("allow data upload")
2328 // Disables uploading data, if it was enabled.
2329 func (t *Torrent) DisallowDataUpload() {
2332 t.dataUploadDisallowed = true
2333 for c := range t.conns {
2334 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2335 c.updateRequests("disallow data upload")
2339 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2340 // or if nil, a critical message is logged, and data download is disabled.
2341 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2344 t.userOnWriteChunkErr = f
2347 func (t *Torrent) iterPeers(f func(p *Peer)) {
2348 for pc := range t.conns {
2351 for _, ws := range t.webSeeds {
2356 func (t *Torrent) callbacks() *Callbacks {
2357 return &t.cl.config.Callbacks
2360 type AddWebSeedsOpt func(*webseed.Client)
2362 // Sets the WebSeed trailing path escaper for a webseed.Client.
2363 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2364 return func(c *webseed.Client) {
2365 c.PathEscaper = custom
2369 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2372 for _, u := range urls {
2373 t.addWebSeed(u, opts...)
2377 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2378 if t.cl.config.DisableWebseeds {
2381 if _, ok := t.webSeeds[url]; ok {
2384 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2385 // right away. This value should be some multiple of the number of connections to a host. I
2386 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2387 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2388 // "https://webtorrent.io/torrents/".
2389 const maxRequests = 16
2395 reconciledHandshakeStats: true,
2396 // This should affect how often we have to recompute requests for this peer. Note that
2397 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2398 // requests mark more often, so recomputation is probably sooner than with regular peer
2399 // conns. ~4x maxRequests would be about right.
2400 PeerMaxRequests: 128,
2401 // TODO: Set ban prefix?
2402 RemoteAddr: remoteAddrFromUrl(url),
2403 callbacks: t.callbacks(),
2405 client: webseed.Client{
2406 HttpClient: t.cl.httpClient,
2408 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2409 return &rateLimitedReader{
2410 l: t.cl.config.DownloadRateLimiter,
2415 activeRequests: make(map[Request]webseed.Request, maxRequests),
2416 maxRequests: maxRequests,
2418 ws.peer.initRequestState()
2419 for _, opt := range opts {
2422 ws.peer.initUpdateRequestsTimer()
2423 ws.requesterCond.L = t.cl.locker()
2424 for i := 0; i < maxRequests; i += 1 {
2427 for _, f := range t.callbacks().NewPeer {
2430 ws.peer.logger = t.logger.WithContextValue(&ws)
2431 ws.peer.peerImpl = &ws
2433 ws.onGotInfo(t.info)
2435 t.webSeeds[url] = &ws.peer
2438 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2439 t.iterPeers(func(p1 *Peer) {
2447 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2448 index := t.pieceIndexOfRequestIndex(ri)
2451 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2455 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2456 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2459 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2460 return RequestIndex(piece) * t.chunksPerRegularPiece()
2463 func (t *Torrent) updateComplete() {
2464 t.Complete.SetBool(t.haveAllPieces())
2467 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2468 p := t.requestingPeer(r)
2472 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2473 //delete(t.pendingRequests, r)
2474 if _, ok := t.requestState[r]; ok {
2475 panic("expected request state to be gone")
2480 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2481 return t.requestState[r].peer
2484 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2485 if t.connsWithAllPieces == nil {
2486 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2488 t.connsWithAllPieces[p] = struct{}{}
2491 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2492 _, ok := t.connsWithAllPieces[p]
2493 delete(t.connsWithAllPieces, p)
2497 func (t *Torrent) numActivePeers() int {
2498 return len(t.conns) + len(t.webSeeds)
2501 func (t *Torrent) hasStorageCap() bool {
2502 f := t.storage.Capacity
2510 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2511 return pieceIndex(ri / t.chunksPerRegularPiece())
2514 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2515 reuseIter *typedRoaring.Iterator[RequestIndex],
2517 f func(RequestIndex),
2519 reuseIter.Initialize(&t.dirtyChunks)
2520 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2521 iterBitmapUnsetInRange(
2523 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2528 type requestState struct {