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 "github.com/davecgh/go-spew/spew"
34 "github.com/pion/datachannel"
36 "github.com/anacrolix/torrent/bencode"
37 "github.com/anacrolix/torrent/common"
38 "github.com/anacrolix/torrent/metainfo"
39 pp "github.com/anacrolix/torrent/peer_protocol"
40 request_strategy "github.com/anacrolix/torrent/request-strategy"
41 "github.com/anacrolix/torrent/segments"
42 "github.com/anacrolix/torrent/storage"
43 "github.com/anacrolix/torrent/tracker"
44 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
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
65 infoHash metainfo.Hash
68 // The order pieces are requested if there's no stronger reason like availability or priority.
69 pieceRequestOrder []int
70 // Values are the piece indices that changed.
71 pieceStateChanges pubsub.PubSub[PieceStateChange]
72 // The size of chunks to request from peers over the wire. This is
73 // normally 16KiB by convention these days.
76 // Total length of the torrent in bytes. Stored because it's not O(1) to
77 // get this from the info dict.
80 // The storage to open when the info dict becomes available.
81 storageOpener *storage.Client
82 // Storage for torrent data.
83 storage *storage.Torrent
84 // Read-locked for using storage, and write-locked for Closing.
85 storageLock sync.RWMutex
87 // TODO: Only announce stuff is used?
88 metainfo metainfo.MetaInfo
90 // The info dict. nil if we don't have it (yet).
92 fileIndex segments.Index
95 _chunksPerRegularPiece chunkIndexType
97 webSeeds map[string]*Peer
98 // Active peer connections, running message stream loops. TODO: Make this
99 // open (not-closed) connections only.
100 conns map[*PeerConn]struct{}
101 maxEstablishedConns int
102 // Set of addrs to which we're attempting to connect. Connections are
103 // half-open until all handshakes are completed.
104 halfOpen map[string]PeerInfo
106 // Reserve of peers to connect to. A peer can be both here and in the
107 // active connections if were told about the peer after connecting with
108 // them. That encourages us to reconnect to peers that are well known in
110 peers prioritizedPeers
111 // Whether we want to know to know more peers.
112 wantPeersEvent missinggo.Event
113 // An announcer for each tracker URL.
114 trackerAnnouncers map[string]torrentTrackerAnnouncer
115 // How many times we've initiated a DHT announce. TODO: Move into stats.
118 // Name used if the info name isn't available. Should be cleared when the
119 // Info does become available.
123 // The bencoded bytes of the info dict. This is actively manipulated if
124 // the info bytes aren't initially available, and we try to fetch them
127 // Each element corresponds to the 16KiB metadata pieces. If true, we have
128 // received that piece.
129 metadataCompletedChunks []bool
130 metadataChanged sync.Cond
132 // Closed when .Info is obtained.
133 gotMetainfoC chan struct{}
135 readers map[*reader]struct{}
136 _readerNowPieces bitmap.Bitmap
137 _readerReadaheadPieces bitmap.Bitmap
139 // A cache of pieces we need to get. Calculated from various piece and
140 // file priorities and completion states elsewhere.
141 _pendingPieces roaring.Bitmap
142 // A cache of completed piece indices.
143 _completedPieces roaring.Bitmap
144 // Pieces that need to be hashed.
145 piecesQueuedForHash bitmap.Bitmap
146 activePieceHashes int
147 initialPieceCheckDisabled bool
149 connsWithAllPieces map[*Peer]struct{}
151 requestState map[RequestIndex]requestState
152 // Chunks we've written to since the corresponding piece was last checked.
153 dirtyChunks typedRoaring.Bitmap[RequestIndex]
157 // Is On when all pieces are complete.
158 Complete chansync.Flag
160 // Torrent sources in use keyed by the source string.
161 activeSources sync.Map
162 sourcesLogger log.Logger
164 smartBanCache smartBanCache
166 // Large allocations reused between request state updates.
167 requestPieceStates []request_strategy.PieceRequestOrderState
168 requestIndexes []RequestIndex
171 func (t *Torrent) length() int64 {
172 return t._length.Value
175 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
176 // This could be done with roaring.BitSliceIndexing.
177 t.iterPeers(func(peer *Peer) {
178 if _, ok := t.connsWithAllPieces[peer]; ok {
181 if peer.peerHasPiece(i) {
188 func (t *Torrent) decPieceAvailability(i pieceIndex) {
193 if p.relativeAvailability <= 0 {
194 panic(p.relativeAvailability)
196 p.relativeAvailability--
197 t.updatePieceRequestOrder(i)
200 func (t *Torrent) incPieceAvailability(i pieceIndex) {
201 // If we don't the info, this should be reconciled when we do.
204 p.relativeAvailability++
205 t.updatePieceRequestOrder(i)
209 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
210 return t._readerNowPieces
213 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
214 return t._readerReadaheadPieces
217 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
218 return !t.wantPieceIndex(i)
221 // Returns a channel that is closed when the Torrent is closed.
222 func (t *Torrent) Closed() events.Done {
223 return t.closed.Done()
226 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
227 // pending, and half-open peers.
228 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
229 // Add pending peers to the list
230 t.peers.Each(func(peer PeerInfo) {
231 ks = append(ks, peer)
234 // Add half-open peers to the list
235 for _, peer := range t.halfOpen {
236 ks = append(ks, peer)
239 // Add active peers to the list
240 for conn := range t.conns {
241 ks = append(ks, PeerInfo{
243 Addr: conn.RemoteAddr,
244 Source: conn.Discovery,
245 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
246 // > But if we're not connected to them with an encrypted connection, I couldn't say
247 // > what's appropriate. We can carry forward the SupportsEncryption value as we
248 // > received it from trackers/DHT/PEX, or just use the encryption state for the
249 // > connection. It's probably easiest to do the latter for now.
250 // https://github.com/anacrolix/torrent/pull/188
251 SupportsEncryption: conn.headerEncrypted,
258 func (t *Torrent) setChunkSize(size pp.Integer) {
260 t.chunkPool = sync.Pool{
261 New: func() interface{} {
262 b := make([]byte, size)
268 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
269 return t._completedPieces.Contains(bitmap.BitIndex(piece))
272 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
273 if t.storage == nil {
274 return storage.Completion{Complete: false, Ok: true}
276 return t.pieces[piece].Storage().Completion()
279 // There's a connection to that address already.
280 func (t *Torrent) addrActive(addr string) bool {
281 if _, ok := t.halfOpen[addr]; ok {
284 for c := range t.conns {
286 if ra.String() == addr {
293 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
294 return t.appendConns(ret, func(conn *PeerConn) bool {
295 return !conn.closed.IsSet()
299 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
300 for c := range t.conns {
308 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
310 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
311 if t.closed.IsSet() {
314 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
315 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
316 torrent.Add("peers not added because of bad addr", 1)
317 // cl.logger.Printf("peers not added because of bad addr: %v", p)
321 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
322 torrent.Add("peers replaced", 1)
323 if !replaced.equal(p) {
324 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
331 for t.peers.Len() > cl.config.TorrentPeersHighWater {
332 _, ok := t.peers.DeleteMin()
334 torrent.Add("excess reserve peers discarded", 1)
340 func (t *Torrent) invalidateMetadata() {
341 for i := 0; i < len(t.metadataCompletedChunks); i++ {
342 t.metadataCompletedChunks[i] = false
345 t.gotMetainfoC = make(chan struct{})
350 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
354 if index >= len(t.metadataCompletedChunks) {
355 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
358 copy(t.metadataBytes[(1<<14)*index:], data)
359 t.metadataCompletedChunks[index] = true
362 func (t *Torrent) metadataPieceCount() int {
363 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
366 func (t *Torrent) haveMetadataPiece(piece int) bool {
368 return (1<<14)*piece < len(t.metadataBytes)
370 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
374 func (t *Torrent) metadataSize() int {
375 return len(t.metadataBytes)
378 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
379 for i := 0; i < len(info.Pieces); i += sha1.Size {
380 ret = append(ret, info.Pieces[i:i+sha1.Size])
385 func (t *Torrent) makePieces() {
386 hashes := infoPieceHashes(t.info)
387 t.pieces = make([]Piece, len(hashes))
388 for i, hash := range hashes {
389 piece := &t.pieces[i]
391 piece.index = pieceIndex(i)
392 piece.noPendingWrites.L = &piece.pendingWritesMutex
393 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
395 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
396 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
397 piece.files = files[beginFile:endFile]
401 // Returns the index of the first file containing the piece. files must be
402 // ordered by offset.
403 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
404 for i, f := range files {
405 if f.offset+f.length > pieceOffset {
412 // Returns the index after the last file containing the piece. files must be
413 // ordered by offset.
414 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
415 for i, f := range files {
416 if f.offset+f.length >= pieceEndOffset {
423 func (t *Torrent) cacheLength() {
425 for _, f := range t.info.UpvertedFiles() {
431 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
433 func (t *Torrent) setInfo(info *metainfo.Info) error {
434 if err := validateInfo(info); err != nil {
435 return fmt.Errorf("bad info: %s", err)
437 if t.storageOpener != nil {
439 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
441 return fmt.Errorf("error opening torrent storage: %s", err)
447 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
449 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
450 t.displayName = "" // Save a few bytes lol.
457 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
458 return request_strategy.PieceRequestOrderKey{
459 InfoHash: t.infoHash,
464 // This seems to be all the follow-up tasks after info is set, that can't fail.
465 func (t *Torrent) onSetInfo() {
466 t.pieceRequestOrder = rand.Perm(t.numPieces())
467 t.initPieceRequestOrder()
468 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
469 for i := range t.pieces {
471 // Need to add relativeAvailability before updating piece completion, as that may result in conns
473 if p.relativeAvailability != 0 {
474 panic(p.relativeAvailability)
476 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
477 t.addRequestOrderPiece(i)
478 t.updatePieceCompletion(i)
479 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
480 // t.logger.Printf("piece %s completion unknown, queueing check", p)
484 t.cl.event.Broadcast()
485 close(t.gotMetainfoC)
486 t.updateWantPeersEvent()
487 t.requestState = make(map[RequestIndex]requestState)
488 t.tryCreateMorePieceHashers()
489 t.iterPeers(func(p *Peer) {
491 p.updateRequests("onSetInfo")
495 // Called when metadata for a torrent becomes available.
496 func (t *Torrent) setInfoBytesLocked(b []byte) error {
497 if metainfo.HashBytes(b) != t.infoHash {
498 return errors.New("info bytes have wrong hash")
500 var info metainfo.Info
501 if err := bencode.Unmarshal(b, &info); err != nil {
502 return fmt.Errorf("error unmarshalling info bytes: %s", err)
505 t.metadataCompletedChunks = nil
509 if err := t.setInfo(&info); err != nil {
516 func (t *Torrent) haveAllMetadataPieces() bool {
520 if t.metadataCompletedChunks == nil {
523 for _, have := range t.metadataCompletedChunks {
531 // TODO: Propagate errors to disconnect peer.
532 func (t *Torrent) setMetadataSize(size int) (err error) {
534 // We already know the correct metadata size.
537 if uint32(size) > maxMetadataSize {
538 return log.WithLevel(log.Warning, errors.New("bad size"))
540 if len(t.metadataBytes) == size {
543 t.metadataBytes = make([]byte, size)
544 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
545 t.metadataChanged.Broadcast()
546 for c := range t.conns {
547 c.requestPendingMetadata()
552 // The current working name for the torrent. Either the name in the info dict,
553 // or a display name given such as by the dn value in a magnet link, or "".
554 func (t *Torrent) name() string {
556 defer t.nameMu.RUnlock()
558 return t.info.BestName()
560 if t.displayName != "" {
563 return "infohash:" + t.infoHash.HexString()
566 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
567 p := &t.pieces[index]
568 ret.Priority = t.piecePriority(index)
569 ret.Completion = p.completion()
570 ret.QueuedForHash = p.queuedForHash()
571 ret.Hashing = p.hashing
572 ret.Checking = ret.QueuedForHash || ret.Hashing
573 ret.Marking = p.marking
574 if !ret.Complete && t.piecePartiallyDownloaded(index) {
580 func (t *Torrent) metadataPieceSize(piece int) int {
581 return metadataPieceSize(len(t.metadataBytes), piece)
584 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
587 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
588 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
590 TotalSize: len(t.metadataBytes),
596 type pieceAvailabilityRun struct {
601 func (me pieceAvailabilityRun) String() string {
602 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
605 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
606 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
607 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
609 for i := range t.pieces {
610 rle.Append(t.pieces[i].availability(), 1)
616 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
617 freqs = make([]int, t.numActivePeers()+1)
618 for i := range t.pieces {
619 freqs[t.piece(i).availability()]++
624 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
625 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
626 ret = append(ret, PieceStateRun{
627 PieceState: el.(PieceState),
631 for index := range t.pieces {
632 rle.Append(t.pieceState(pieceIndex(index)), 1)
638 // Produces a small string representing a PieceStateRun.
639 func (psr PieceStateRun) String() (ret string) {
640 ret = fmt.Sprintf("%d", psr.Length)
641 ret += func() string {
642 switch psr.Priority {
643 case PiecePriorityNext:
645 case PiecePriorityNormal:
647 case PiecePriorityReadahead:
649 case PiecePriorityNow:
651 case PiecePriorityHigh:
660 if psr.QueuedForHash {
678 func (t *Torrent) writeStatus(w io.Writer) {
679 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
680 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
682 fmt.Fprintf(w, "Metadata have: ")
683 for _, h := range t.metadataCompletedChunks {
684 fmt.Fprintf(w, "%c", func() rune {
694 fmt.Fprintf(w, "Piece length: %s\n",
697 return fmt.Sprintf("%v (%v chunks)",
699 float64(t.usualPieceSize())/float64(t.chunkSize))
706 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
707 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
708 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
709 // availability frequencies instead.
711 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
712 for _, run := range t.pieceAvailabilityRuns() {
713 ret = append(ret, run.String())
718 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
719 func() (ret []string) {
720 for avail, freq := range t.pieceAvailabilityFrequencies() {
724 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
730 fmt.Fprintf(w, "Reader Pieces:")
731 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
732 fmt.Fprintf(w, " %d:%d", begin, end)
737 fmt.Fprintf(w, "Enabled trackers:\n")
739 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
740 fmt.Fprintf(tw, " URL\tExtra\n")
741 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
744 var luns, runs url.URL = *lu, *ru
747 var ml missinggo.MultiLess
748 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
749 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
751 }).([]torrentTrackerAnnouncer) {
752 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
757 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
759 spew.NewDefaultConfig()
760 spew.Fdump(w, t.statsLocked())
762 peers := t.peersAsSlice()
763 sort.Slice(peers, func(_i, _j int) bool {
766 if less, ok := multiless.New().EagerSameLess(
767 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
771 return worseConn(i, j)
774 for i, c := range peers {
775 fmt.Fprintf(w, "%2d. ", i+1)
777 c.writeStatus(&buf, t)
778 w.Write(bytes.TrimRight(
779 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
784 func (t *Torrent) haveInfo() bool {
788 // Returns a run-time generated MetaInfo that includes the info bytes and
789 // announce-list as currently known to the client.
790 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
791 return metainfo.MetaInfo{
792 CreationDate: time.Now().Unix(),
793 Comment: "dynamic metainfo from client",
794 CreatedBy: "go.torrent",
795 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
796 InfoBytes: func() []byte {
798 return t.metadataBytes
803 UrlList: func() []string {
804 ret := make([]string, 0, len(t.webSeeds))
805 for url := range t.webSeeds {
806 ret = append(ret, url)
814 func (t *Torrent) BytesMissing() (n int64) {
816 n = t.bytesMissingLocked()
821 func (t *Torrent) bytesMissingLocked() int64 {
825 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
826 roaring.Flip(b, 0, end).Iterate(cb)
829 func (t *Torrent) bytesLeft() (left int64) {
830 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
831 p := t.piece(pieceIndex(x))
832 left += int64(p.length() - p.numDirtyBytes())
838 // Bytes left to give in tracker announces.
839 func (t *Torrent) bytesLeftAnnounce() int64 {
847 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
848 if t.pieceComplete(piece) {
851 if t.pieceAllDirty(piece) {
854 return t.pieces[piece].hasDirtyChunks()
857 func (t *Torrent) usualPieceSize() int {
858 return int(t.info.PieceLength)
861 func (t *Torrent) numPieces() pieceIndex {
862 return t.info.NumPieces()
865 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
866 return pieceIndex(t._completedPieces.GetCardinality())
869 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
871 err = errors.New("already closed")
874 for _, f := range t.onClose {
877 if t.storage != nil {
882 defer t.storageLock.Unlock()
883 if f := t.storage.Close; f != nil {
886 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
891 t.iterPeers(func(p *Peer) {
894 if t.storage != nil {
895 t.deletePieceRequestOrder()
897 t.assertAllPiecesRelativeAvailabilityZero()
899 t.cl.event.Broadcast()
900 t.pieceStateChanges.Close()
901 t.updateWantPeersEvent()
905 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
906 for i := range t.pieces {
908 if p.relativeAvailability != 0 {
909 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
914 func (t *Torrent) requestOffset(r Request) int64 {
915 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
918 // Return the request that would include the given offset into the torrent data. Returns !ok if
919 // there is no such request.
920 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
921 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
924 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
925 defer perf.ScopeTimerErr(&err)()
926 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
927 if err == nil && n != len(data) {
928 err = io.ErrShortWrite
933 func (t *Torrent) bitfield() (bf []bool) {
934 bf = make([]bool, t.numPieces())
935 t._completedPieces.Iterate(func(piece uint32) (again bool) {
942 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
943 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
946 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
947 return t._chunksPerRegularPiece
950 func (t *Torrent) numChunks() RequestIndex {
951 if t.numPieces() == 0 {
954 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
957 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
958 t.dirtyChunks.RemoveRange(
959 uint64(t.pieceRequestIndexOffset(pieceIndex)),
960 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
963 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
964 if t.info.PieceLength == 0 {
965 // There will be no variance amongst pieces. Only pain.
968 if piece == t.numPieces()-1 {
969 ret := pp.Integer(t.length() % t.info.PieceLength)
974 return pp.Integer(t.info.PieceLength)
977 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
978 return &blockCheckingWriter{
979 cache: &t.smartBanCache,
980 requestIndex: t.pieceRequestIndexOffset(piece),
981 chunkSize: t.chunkSize.Int(),
985 func (t *Torrent) hashPiece(piece pieceIndex) (
987 // These are peers that sent us blocks that differ from what we hash here.
988 differingPeers map[bannableAddr]struct{},
992 p.waitNoPendingWrites()
993 storagePiece := t.pieces[piece].Storage()
995 // Does the backend want to do its own hashing?
996 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
997 var sum metainfo.Hash
998 // log.Printf("A piece decided to self-hash: %d", piece)
999 sum, err = i.SelfHash()
1000 missinggo.CopyExact(&ret, sum)
1004 hash := pieceHash.New()
1005 const logPieceContents = false
1006 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1007 writers := []io.Writer{hash, smartBanWriter}
1008 var examineBuf bytes.Buffer
1009 if logPieceContents {
1010 writers = append(writers, &examineBuf)
1012 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1013 if logPieceContents {
1014 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1016 smartBanWriter.Flush()
1017 differingPeers = smartBanWriter.badPeers
1018 missinggo.CopyExact(&ret, hash.Sum(nil))
1022 func (t *Torrent) haveAnyPieces() bool {
1023 return !t._completedPieces.IsEmpty()
1026 func (t *Torrent) haveAllPieces() bool {
1030 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1033 func (t *Torrent) havePiece(index pieceIndex) bool {
1034 return t.haveInfo() && t.pieceComplete(index)
1037 func (t *Torrent) maybeDropMutuallyCompletePeer(
1038 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1042 if !t.cl.config.DropMutuallyCompletePeers {
1045 if !t.haveAllPieces() {
1048 if all, known := p.peerHasAllPieces(); !(known && all) {
1054 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1058 func (t *Torrent) haveChunk(r Request) (ret bool) {
1060 // log.Println("have chunk", r, ret)
1065 if t.pieceComplete(pieceIndex(r.Index)) {
1068 p := &t.pieces[r.Index]
1069 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1072 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1073 return chunkIndexType(cs.Begin / chunkSize)
1076 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1077 return t._pendingPieces.Contains(uint32(index))
1080 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1081 // conns (which is a map).
1082 var peerConnSlices sync.Pool
1084 func getPeerConnSlice(cap int) []*PeerConn {
1085 getInterface := peerConnSlices.Get()
1086 if getInterface == nil {
1087 return make([]*PeerConn, 0, cap)
1089 return getInterface.([]*PeerConn)[:0]
1093 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1094 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1095 // established connections for more than a minute. This is O(n log n). If there was a way to not
1096 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1097 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1098 wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
1099 defer peerConnSlices.Put(wcs.conns)
1102 for wcs.Len() != 0 {
1103 c := heap.Pop(&wcs).(*PeerConn)
1104 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1107 // If the connection is in the worst half of the established
1108 // connection quota and is older than a minute.
1109 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1110 // Give connections 1 minute to prove themselves.
1111 if time.Since(c.completedHandshake) > time.Minute {
1119 type PieceStateChange struct {
1124 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1125 t.cl._mu.Defer(func() {
1126 cur := t.pieceState(piece)
1127 p := &t.pieces[piece]
1128 if cur != p.publicPieceState {
1129 p.publicPieceState = cur
1130 t.pieceStateChanges.Publish(PieceStateChange{
1138 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1139 if t.pieceComplete(piece) {
1142 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1145 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1146 return t.pieces[piece].allChunksDirty()
1149 func (t *Torrent) readersChanged() {
1150 t.updateReaderPieces()
1151 t.updateAllPiecePriorities("Torrent.readersChanged")
1154 func (t *Torrent) updateReaderPieces() {
1155 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1158 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1162 t.updateReaderPieces()
1163 // Order the ranges, high and low.
1165 if l.begin > h.begin {
1168 if l.end < h.begin {
1169 // Two distinct ranges.
1170 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1171 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1178 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1182 func (t *Torrent) maybeNewConns() {
1183 // Tickle the accept routine.
1184 t.cl.event.Broadcast()
1188 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1189 if t._pendingPieces.Contains(uint32(piece)) {
1190 t.iterPeers(func(c *Peer) {
1191 // if c.requestState.Interested {
1194 if !c.isLowOnRequests() {
1197 if !c.peerHasPiece(piece) {
1200 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1203 c.updateRequests(reason)
1207 t.publishPieceChange(piece)
1210 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1211 if !t.closed.IsSet() {
1212 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1214 t.updatePieceRequestOrder(piece)
1216 p := &t.pieces[piece]
1217 newPrio := p.uncachedPriority()
1218 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1219 if newPrio == PiecePriorityNone {
1220 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1224 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1228 t.piecePriorityChanged(piece, reason)
1231 func (t *Torrent) updateAllPiecePriorities(reason string) {
1232 t.updatePiecePriorities(0, t.numPieces(), reason)
1235 // Update all piece priorities in one hit. This function should have the same
1236 // output as updatePiecePriority, but across all pieces.
1237 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1238 for i := begin; i < end; i++ {
1239 t.updatePiecePriority(i, reason)
1243 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1244 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1245 if off >= t.length() {
1255 begin = pieceIndex(off / t.info.PieceLength)
1256 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1257 if end > pieceIndex(t.info.NumPieces()) {
1258 end = pieceIndex(t.info.NumPieces())
1263 // Returns true if all iterations complete without breaking. Returns the read regions for all
1264 // readers. The reader regions should not be merged as some callers depend on this method to
1265 // enumerate readers.
1266 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1267 for r := range t.readers {
1269 if p.begin >= p.end {
1272 if !f(p.begin, p.end) {
1279 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1280 return t.piece(piece).uncachedPriority()
1283 func (t *Torrent) pendRequest(req RequestIndex) {
1284 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1287 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1288 t.cl.event.Broadcast()
1289 if t.pieceComplete(piece) {
1290 t.onPieceCompleted(piece)
1292 t.onIncompletePiece(piece)
1294 t.updatePiecePriority(piece, reason)
1297 func (t *Torrent) numReceivedConns() (ret int) {
1298 for c := range t.conns {
1299 if c.Discovery == PeerSourceIncoming {
1306 func (t *Torrent) maxHalfOpen() int {
1307 // Note that if we somehow exceed the maximum established conns, we want
1308 // the negative value to have an effect.
1309 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1310 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1311 // We want to allow some experimentation with new peers, and to try to
1312 // upset an oversupply of received connections.
1313 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1316 func (t *Torrent) openNewConns() (initiated int) {
1317 defer t.updateWantPeersEvent()
1318 for t.peers.Len() != 0 {
1322 if len(t.halfOpen) >= t.maxHalfOpen() {
1325 if len(t.cl.dialers) == 0 {
1328 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1331 p := t.peers.PopMax()
1338 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1340 uncached := t.pieceCompleteUncached(piece)
1341 cached := p.completion()
1342 changed := cached != uncached
1343 complete := uncached.Complete
1344 p.storageCompletionOk = uncached.Ok
1347 t._completedPieces.Add(x)
1350 t._completedPieces.Remove(x)
1352 p.t.updatePieceRequestOrder(piece)
1354 if complete && len(p.dirtiers) != 0 {
1355 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1358 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1359 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1364 // Non-blocking read. Client lock is not required.
1365 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1367 p := &t.pieces[off/t.info.PieceLength]
1368 p.waitNoPendingWrites()
1370 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1381 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1382 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1383 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1384 func (t *Torrent) maybeCompleteMetadata() error {
1389 if !t.haveAllMetadataPieces() {
1390 // Don't have enough metadata pieces.
1393 err := t.setInfoBytesLocked(t.metadataBytes)
1395 t.invalidateMetadata()
1396 return fmt.Errorf("error setting info bytes: %s", err)
1398 if t.cl.config.Debug {
1399 t.logger.Printf("%s: got metadata from peers", t)
1404 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1405 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1407 now.Add(bitmap.BitIndex(begin))
1408 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1415 func (t *Torrent) needData() bool {
1416 if t.closed.IsSet() {
1422 return !t._pendingPieces.IsEmpty()
1425 func appendMissingStrings(old, new []string) (ret []string) {
1428 for _, n := range new {
1429 for _, o := range old {
1434 ret = append(ret, n)
1439 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1441 for minNumTiers > len(ret) {
1442 ret = append(ret, nil)
1447 func (t *Torrent) addTrackers(announceList [][]string) {
1448 fullAnnounceList := &t.metainfo.AnnounceList
1449 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1450 for tierIndex, trackerURLs := range announceList {
1451 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1453 t.startMissingTrackerScrapers()
1454 t.updateWantPeersEvent()
1457 // Don't call this before the info is available.
1458 func (t *Torrent) bytesCompleted() int64 {
1462 return t.length() - t.bytesLeft()
1465 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1468 return t.setInfoBytesLocked(b)
1471 // Returns true if connection is removed from torrent.Conns.
1472 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1473 if !c.closed.IsSet() {
1474 panic("connection is not closed")
1475 // There are behaviours prevented by the closed state that will fail
1476 // if the connection has been deleted.
1480 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1481 // the drop event against the PexConnState instead.
1483 if !t.cl.config.DisablePEX {
1487 torrent.Add("deleted connections", 1)
1488 c.deleteAllRequests("Torrent.deletePeerConn")
1489 t.assertPendingRequests()
1490 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1491 panic(t.connsWithAllPieces)
1496 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1497 if t.deleteConnWithAllPieces(p) {
1503 p.peerPieces().Iterate(func(i uint32) bool {
1504 p.t.decPieceAvailability(pieceIndex(i))
1509 func (t *Torrent) assertPendingRequests() {
1513 // var actual pendingRequests
1514 // if t.haveInfo() {
1515 // actual.m = make([]int, t.numChunks())
1517 // t.iterPeers(func(p *Peer) {
1518 // p.requestState.Requests.Iterate(func(x uint32) bool {
1523 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1529 func (t *Torrent) dropConnection(c *PeerConn) {
1530 t.cl.event.Broadcast()
1532 if t.deletePeerConn(c) {
1537 // Peers as in contact information for dialing out.
1538 func (t *Torrent) wantPeers() bool {
1539 if t.closed.IsSet() {
1542 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1545 return t.wantConns()
1548 func (t *Torrent) updateWantPeersEvent() {
1550 t.wantPeersEvent.Set()
1552 t.wantPeersEvent.Clear()
1556 // Returns whether the client should make effort to seed the torrent.
1557 func (t *Torrent) seeding() bool {
1559 if t.closed.IsSet() {
1562 if t.dataUploadDisallowed {
1565 if cl.config.NoUpload {
1568 if !cl.config.Seed {
1571 if cl.config.DisableAggressiveUpload && t.needData() {
1577 func (t *Torrent) onWebRtcConn(
1578 c datachannel.ReadWriteCloser,
1579 dcc webtorrent.DataChannelContext,
1582 netConn := webrtcNetConn{
1584 DataChannelContext: dcc,
1586 peerRemoteAddr := netConn.RemoteAddr()
1587 //t.logger.Levelf(log.Critical, "onWebRtcConn remote addr: %v", peerRemoteAddr)
1588 if t.cl.badPeerAddr(peerRemoteAddr) {
1591 localAddrIpPort := missinggo.IpPortFromNetAddr(netConn.LocalAddr())
1592 pc, err := t.cl.initiateProtocolHandshakes(
1593 context.Background(),
1598 outgoing: dcc.LocalOffered,
1599 remoteAddr: peerRemoteAddr,
1600 localPublicAddr: localAddrIpPort,
1601 network: webrtcNetwork,
1602 connString: fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1606 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1609 if dcc.LocalOffered {
1610 pc.Discovery = PeerSourceTracker
1612 pc.Discovery = PeerSourceIncoming
1614 pc.conn.SetWriteDeadline(time.Time{})
1617 err = t.cl.runHandshookConn(pc, t)
1619 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1623 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1624 err := t.cl.runHandshookConn(pc, t)
1625 if err != nil || logAll {
1626 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1630 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1631 t.logRunHandshookConn(pc, false, log.Debug)
1634 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1635 wtc, release := t.cl.websocketTrackers.Get(u.String(), t.infoHash)
1636 // This needs to run before the Torrent is dropped from the Client, to prevent a new webtorrent.TrackerClient for
1637 // the same info hash before the old one is cleaned up.
1638 t.onClose = append(t.onClose, release)
1639 wst := websocketTrackerStatus{u, wtc}
1641 err := wtc.Announce(tracker.Started, t.infoHash)
1643 t.logger.WithDefaultLevel(log.Warning).Printf(
1644 "error in initial announce to %q: %v",
1652 func (t *Torrent) startScrapingTracker(_url string) {
1656 u, err := url.Parse(_url)
1658 // URLs with a leading '*' appear to be a uTorrent convention to
1659 // disable trackers.
1661 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1665 if u.Scheme == "udp" {
1667 t.startScrapingTracker(u.String())
1669 t.startScrapingTracker(u.String())
1672 if _, ok := t.trackerAnnouncers[_url]; ok {
1675 sl := func() torrentTrackerAnnouncer {
1678 if t.cl.config.DisableWebtorrent {
1681 return t.startWebsocketAnnouncer(*u)
1683 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1687 if t.cl.config.DisableIPv6 {
1691 newAnnouncer := &trackerScraper{
1694 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1696 go newAnnouncer.Run()
1702 if t.trackerAnnouncers == nil {
1703 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1705 t.trackerAnnouncers[_url] = sl
1708 // Adds and starts tracker scrapers for tracker URLs that aren't already
1710 func (t *Torrent) startMissingTrackerScrapers() {
1711 if t.cl.config.DisableTrackers {
1714 t.startScrapingTracker(t.metainfo.Announce)
1715 for _, tier := range t.metainfo.AnnounceList {
1716 for _, url := range tier {
1717 t.startScrapingTracker(url)
1722 // Returns an AnnounceRequest with fields filled out to defaults and current
1724 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1725 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1726 // dependent on the network in use.
1727 return tracker.AnnounceRequest{
1729 NumWant: func() int32 {
1730 if t.wantPeers() && len(t.cl.dialers) > 0 {
1731 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1736 Port: uint16(t.cl.incomingPeerPort()),
1737 PeerId: t.cl.peerID,
1738 InfoHash: t.infoHash,
1739 Key: t.cl.announceKey(),
1741 // The following are vaguely described in BEP 3.
1743 Left: t.bytesLeftAnnounce(),
1744 Uploaded: t.stats.BytesWrittenData.Int64(),
1745 // There's no mention of wasted or unwanted download in the BEP.
1746 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1750 // Adds peers revealed in an announce until the announce ends, or we have
1752 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1754 for v := range pvs {
1757 for _, cp := range v.Peers {
1759 // Can't do anything with this.
1762 if t.addPeer(PeerInfo{
1763 Addr: ipPortAddr{cp.IP, cp.Port},
1764 Source: PeerSourceDhtGetPeers,
1771 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1776 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1777 // announce ends. stop will force the announce to end.
1778 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1779 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1783 _done := make(chan struct{})
1787 t.consumeDhtAnnouncePeers(ps.Peers())
1793 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1794 _, stop, err := t.AnnounceToDht(s)
1799 case <-t.closed.Done():
1800 case <-time.After(5 * time.Minute):
1806 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1812 if t.closed.IsSet() {
1815 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1816 // TODO: We can include the announce_peer step depending on whether we can receive
1817 // inbound connections. We should probably only announce once every 15 mins too.
1821 // TODO: Determine if there's a listener on the port we're announcing.
1822 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1833 err := t.timeboxedAnnounceToDht(s)
1835 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1841 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1842 for _, p := range peers {
1850 // The returned TorrentStats may require alignment in memory. See
1851 // https://github.com/anacrolix/torrent/issues/383.
1852 func (t *Torrent) Stats() TorrentStats {
1854 defer t.cl.rUnlock()
1855 return t.statsLocked()
1858 func (t *Torrent) statsLocked() (ret TorrentStats) {
1859 ret.ActivePeers = len(t.conns)
1860 ret.HalfOpenPeers = len(t.halfOpen)
1861 ret.PendingPeers = t.peers.Len()
1862 ret.TotalPeers = t.numTotalPeers()
1863 ret.ConnectedSeeders = 0
1864 for c := range t.conns {
1865 if all, ok := c.peerHasAllPieces(); all && ok {
1866 ret.ConnectedSeeders++
1869 ret.ConnStats = t.stats.Copy()
1870 ret.PiecesComplete = t.numPiecesCompleted()
1874 // The total number of peers in the torrent.
1875 func (t *Torrent) numTotalPeers() int {
1876 peers := make(map[string]struct{})
1877 for conn := range t.conns {
1878 ra := conn.conn.RemoteAddr()
1880 // It's been closed and doesn't support RemoteAddr.
1883 peers[ra.String()] = struct{}{}
1885 for addr := range t.halfOpen {
1886 peers[addr] = struct{}{}
1888 t.peers.Each(func(peer PeerInfo) {
1889 peers[peer.Addr.String()] = struct{}{}
1894 // Reconcile bytes transferred before connection was associated with a
1896 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1897 if c._stats != (ConnStats{
1898 // Handshakes should only increment these fields:
1899 BytesWritten: c._stats.BytesWritten,
1900 BytesRead: c._stats.BytesRead,
1904 c.postHandshakeStats(func(cs *ConnStats) {
1905 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1906 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1908 c.reconciledHandshakeStats = true
1911 // Returns true if the connection is added.
1912 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1915 torrent.Add("added connections", 1)
1918 if t.closed.IsSet() {
1919 return errors.New("torrent closed")
1921 for c0 := range t.conns {
1922 if c.PeerID != c0.PeerID {
1925 if !t.cl.config.DropDuplicatePeerIds {
1928 if c.hasPreferredNetworkOver(c0) {
1930 t.deletePeerConn(c0)
1932 return errors.New("existing connection preferred")
1935 if len(t.conns) >= t.maxEstablishedConns {
1936 c := t.worstBadConn()
1938 return errors.New("don't want conns")
1943 if len(t.conns) >= t.maxEstablishedConns {
1946 t.conns[c] = struct{}{}
1947 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1948 t.pex.Add(c) // as no further extended handshake expected
1953 func (t *Torrent) wantConns() bool {
1954 if !t.networkingEnabled.Bool() {
1957 if t.closed.IsSet() {
1960 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
1963 return len(t.conns) < t.maxEstablishedConns || t.worstBadConn() != nil
1966 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1969 oldMax = t.maxEstablishedConns
1970 t.maxEstablishedConns = max
1971 wcs := worseConnSlice{
1972 conns: t.appendConns(nil, func(*PeerConn) bool {
1978 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1979 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
1985 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1986 t.logger.LazyLog(log.Debug, func() log.Msg {
1987 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
1991 t.cl.event.Broadcast()
1992 if t.closed.IsSet() {
1996 // Don't score the first time a piece is hashed, it could be an initial check.
1997 if p.storageCompletionOk {
1999 pieceHashedCorrect.Add(1)
2002 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
2003 ).AddValues(t, p).LogLevel(
2005 log.Debug, t.logger)
2007 pieceHashedNotCorrect.Add(1)
2012 t.publishPieceChange(piece)
2015 t.publishPieceChange(piece)
2019 if len(p.dirtiers) != 0 {
2020 // Don't increment stats above connection-level for every involved connection.
2021 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2023 for c := range p.dirtiers {
2024 c._stats.incrementPiecesDirtiedGood()
2026 t.clearPieceTouchers(piece)
2027 hasDirty := p.hasDirtyChunks()
2030 p.Flush() // You can be synchronous here!
2032 err := p.Storage().MarkComplete()
2034 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2038 if t.closed.IsSet() {
2041 t.pendAllChunkSpecs(piece)
2043 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2044 // Peers contributed to all the data for this piece hash failure, and the failure was
2045 // not due to errors in the storage (such as data being dropped in a cache).
2047 // Increment Torrent and above stats, and then specific connections.
2048 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2049 for c := range p.dirtiers {
2050 // Y u do dis peer?!
2051 c.stats().incrementPiecesDirtiedBad()
2054 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2055 for c := range p.dirtiers {
2057 bannableTouchers = append(bannableTouchers, c)
2060 t.clearPieceTouchers(piece)
2061 slices.Sort(bannableTouchers, connLessTrusted)
2063 if t.cl.config.Debug {
2065 "bannable conns by trust for piece %d: %v",
2067 func() (ret []connectionTrust) {
2068 for _, c := range bannableTouchers {
2069 ret = append(ret, c.trust())
2076 if len(bannableTouchers) >= 1 {
2077 c := bannableTouchers[0]
2078 if len(bannableTouchers) != 1 {
2079 t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2081 // Turns out it's still useful to ban peers like this because if there's only a
2082 // single peer for a piece, and we never progress that piece to completion, we
2083 // will never smart-ban them. Discovered in
2084 // https://github.com/anacrolix/torrent/issues/715.
2085 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2090 t.onIncompletePiece(piece)
2091 p.Storage().MarkNotComplete()
2093 t.updatePieceCompletion(piece)
2096 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2097 start := t.pieceRequestIndexOffset(piece)
2098 end := start + t.pieceNumChunks(piece)
2099 for ri := start; ri < end; ri++ {
2104 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2105 t.pendAllChunkSpecs(piece)
2106 t.cancelRequestsForPiece(piece)
2107 t.piece(piece).readerCond.Broadcast()
2108 for conn := range t.conns {
2110 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2114 // Called when a piece is found to be not complete.
2115 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2116 if t.pieceAllDirty(piece) {
2117 t.pendAllChunkSpecs(piece)
2119 if !t.wantPieceIndex(piece) {
2120 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2123 // We could drop any connections that we told we have a piece that we
2124 // don't here. But there's a test failure, and it seems clients don't care
2125 // if you request pieces that you already claim to have. Pruning bad
2126 // connections might just remove any connections that aren't treating us
2127 // favourably anyway.
2129 // for c := range t.conns {
2130 // if c.sentHave(piece) {
2134 t.iterPeers(func(conn *Peer) {
2135 if conn.peerHasPiece(piece) {
2136 conn.updateRequests("piece incomplete")
2141 func (t *Torrent) tryCreateMorePieceHashers() {
2142 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2146 func (t *Torrent) tryCreatePieceHasher() bool {
2147 if t.storage == nil {
2150 pi, ok := t.getPieceToHash()
2155 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2157 t.publishPieceChange(pi)
2158 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2159 t.storageLock.RLock()
2160 t.activePieceHashes++
2161 go t.pieceHasher(pi)
2165 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2166 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2167 if t.piece(i).hashing {
2177 func (t *Torrent) dropBannedPeers() {
2178 t.iterPeers(func(p *Peer) {
2179 remoteIp := p.remoteIp()
2180 if remoteIp == nil {
2181 if p.bannableAddr.Ok {
2182 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2186 netipAddr := netip.MustParseAddr(remoteIp.String())
2187 if Some(netipAddr) != p.bannableAddr {
2188 t.logger.WithDefaultLevel(log.Debug).Printf(
2189 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2190 p, remoteIp, p.bannableAddr)
2192 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2193 // Should this be a close?
2195 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2200 func (t *Torrent) pieceHasher(index pieceIndex) {
2202 sum, failedPeers, copyErr := t.hashPiece(index)
2203 correct := sum == *p.hash
2207 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2209 t.storageLock.RUnlock()
2213 for peer := range failedPeers {
2214 t.cl.banPeerIP(peer.AsSlice())
2215 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2218 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2219 t.smartBanCache.ForgetBlock(ri)
2223 t.pieceHashed(index, correct, copyErr)
2224 t.updatePiecePriority(index, "Torrent.pieceHasher")
2225 t.activePieceHashes--
2226 t.tryCreateMorePieceHashers()
2229 // Return the connections that touched a piece, and clear the entries while doing it.
2230 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2232 for c := range p.dirtiers {
2233 delete(c.peerTouchedPieces, pi)
2234 delete(p.dirtiers, c)
2238 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2239 t.iterPeers(func(p *Peer) {
2240 ret = append(ret, p)
2245 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2246 piece := t.piece(pieceIndex)
2247 if piece.queuedForHash() {
2250 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2251 t.publishPieceChange(pieceIndex)
2252 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2253 t.tryCreateMorePieceHashers()
2256 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2257 // before the Info is available.
2258 func (t *Torrent) VerifyData() {
2259 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2260 t.Piece(i).VerifyData()
2264 // Start the process of connecting to the given peer for the given torrent if appropriate.
2265 func (t *Torrent) initiateConn(peer PeerInfo) {
2266 if peer.Id == t.cl.peerID {
2269 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2273 if t.addrActive(addr.String()) {
2277 t.halfOpen[addr.String()] = peer
2278 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2281 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2282 // quickly make one Client visible to the Torrent of another Client.
2283 func (t *Torrent) AddClientPeer(cl *Client) int {
2284 return t.AddPeers(func() (ps []PeerInfo) {
2285 for _, la := range cl.ListenAddrs() {
2286 ps = append(ps, PeerInfo{
2295 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2297 func (t *Torrent) allStats(f func(*ConnStats)) {
2302 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2303 return t.pieces[i].hashing
2306 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2307 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2310 func (t *Torrent) dialTimeout() time.Duration {
2311 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2314 func (t *Torrent) piece(i int) *Piece {
2318 func (t *Torrent) onWriteChunkErr(err error) {
2319 if t.userOnWriteChunkErr != nil {
2320 go t.userOnWriteChunkErr(err)
2323 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2324 t.disallowDataDownloadLocked()
2327 func (t *Torrent) DisallowDataDownload() {
2328 t.disallowDataDownloadLocked()
2331 func (t *Torrent) disallowDataDownloadLocked() {
2332 t.dataDownloadDisallowed.Set()
2335 func (t *Torrent) AllowDataDownload() {
2336 t.dataDownloadDisallowed.Clear()
2339 // Enables uploading data, if it was disabled.
2340 func (t *Torrent) AllowDataUpload() {
2343 t.dataUploadDisallowed = false
2344 for c := range t.conns {
2345 c.updateRequests("allow data upload")
2349 // Disables uploading data, if it was enabled.
2350 func (t *Torrent) DisallowDataUpload() {
2353 t.dataUploadDisallowed = true
2354 for c := range t.conns {
2355 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2356 c.updateRequests("disallow data upload")
2360 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2361 // or if nil, a critical message is logged, and data download is disabled.
2362 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2365 t.userOnWriteChunkErr = f
2368 func (t *Torrent) iterPeers(f func(p *Peer)) {
2369 for pc := range t.conns {
2372 for _, ws := range t.webSeeds {
2377 func (t *Torrent) callbacks() *Callbacks {
2378 return &t.cl.config.Callbacks
2381 type AddWebSeedsOpt func(*webseed.Client)
2383 // Sets the WebSeed trailing path escaper for a webseed.Client.
2384 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2385 return func(c *webseed.Client) {
2386 c.PathEscaper = custom
2390 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2393 for _, u := range urls {
2394 t.addWebSeed(u, opts...)
2398 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2399 if t.cl.config.DisableWebseeds {
2402 if _, ok := t.webSeeds[url]; ok {
2405 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2406 // right away. This value should be some multiple of the number of connections to a host. I
2407 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2408 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2409 // "https://webtorrent.io/torrents/".
2410 const maxRequests = 16
2416 reconciledHandshakeStats: true,
2417 // This should affect how often we have to recompute requests for this peer. Note that
2418 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2419 // requests mark more often, so recomputation is probably sooner than with regular peer
2420 // conns. ~4x maxRequests would be about right.
2421 PeerMaxRequests: 128,
2422 // TODO: Set ban prefix?
2423 RemoteAddr: remoteAddrFromUrl(url),
2424 callbacks: t.callbacks(),
2426 client: webseed.Client{
2427 HttpClient: t.cl.httpClient,
2429 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2430 return &rateLimitedReader{
2431 l: t.cl.config.DownloadRateLimiter,
2436 activeRequests: make(map[Request]webseed.Request, maxRequests),
2438 ws.peer.initRequestState()
2439 for _, opt := range opts {
2442 ws.peer.initUpdateRequestsTimer()
2443 ws.requesterCond.L = t.cl.locker()
2444 for i := 0; i < maxRequests; i += 1 {
2447 for _, f := range t.callbacks().NewPeer {
2450 ws.peer.logger = t.logger.WithContextValue(&ws)
2451 ws.peer.peerImpl = &ws
2453 ws.onGotInfo(t.info)
2455 t.webSeeds[url] = &ws.peer
2458 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2459 t.iterPeers(func(p1 *Peer) {
2467 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2468 index := t.pieceIndexOfRequestIndex(ri)
2471 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2475 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2476 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2479 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2480 return RequestIndex(piece) * t.chunksPerRegularPiece()
2483 func (t *Torrent) updateComplete() {
2484 t.Complete.SetBool(t.haveAllPieces())
2487 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2488 p := t.requestingPeer(r)
2492 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2493 //delete(t.pendingRequests, r)
2494 if _, ok := t.requestState[r]; ok {
2495 panic("expected request state to be gone")
2500 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2501 return t.requestState[r].peer
2504 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2505 if t.connsWithAllPieces == nil {
2506 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2508 t.connsWithAllPieces[p] = struct{}{}
2511 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2512 _, ok := t.connsWithAllPieces[p]
2513 delete(t.connsWithAllPieces, p)
2517 func (t *Torrent) numActivePeers() int {
2518 return len(t.conns) + len(t.webSeeds)
2521 func (t *Torrent) hasStorageCap() bool {
2522 f := t.storage.Capacity
2530 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2531 return pieceIndex(ri / t.chunksPerRegularPiece())
2534 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2535 reuseIter *typedRoaring.Iterator[RequestIndex],
2537 f func(RequestIndex),
2539 reuseIter.Initialize(&t.dirtyChunks)
2540 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2541 iterBitmapUnsetInRange(
2543 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2548 type requestState struct {
2553 // Returns an error if a received chunk is out of bounds in someway.
2554 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2556 return errors.New("torrent missing info")
2558 if int(r.Index) >= t.numPieces() {
2559 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2561 pieceLength := t.pieceLength(pieceIndex(r.Index))
2562 if r.Begin >= pieceLength {
2563 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2565 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2566 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2567 // should be considerable checks elsewhere for this case due to the network overhead. We should
2568 // catch most of the overflow manipulation stuff by checking index and begin above.