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 g "github.com/anacrolix/generics"
26 "github.com/anacrolix/log"
27 "github.com/anacrolix/missinggo/perf"
28 "github.com/anacrolix/missinggo/slices"
29 "github.com/anacrolix/missinggo/v2"
30 "github.com/anacrolix/missinggo/v2/bitmap"
31 "github.com/anacrolix/missinggo/v2/pubsub"
32 "github.com/anacrolix/multiless"
33 "github.com/anacrolix/sync"
34 "github.com/pion/datachannel"
35 "golang.org/x/exp/maps"
37 "github.com/anacrolix/torrent/bencode"
38 "github.com/anacrolix/torrent/common"
39 "github.com/anacrolix/torrent/internal/check"
40 "github.com/anacrolix/torrent/internal/nestedmaps"
41 "github.com/anacrolix/torrent/metainfo"
42 pp "github.com/anacrolix/torrent/peer_protocol"
43 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
44 request_strategy "github.com/anacrolix/torrent/request-strategy"
45 "github.com/anacrolix/torrent/segments"
46 "github.com/anacrolix/torrent/storage"
47 "github.com/anacrolix/torrent/tracker"
48 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
49 "github.com/anacrolix/torrent/webseed"
50 "github.com/anacrolix/torrent/webtorrent"
53 // Maintains state of torrent within a Client. Many methods should not be called before the info is
54 // available, see .Info and .GotInfo.
56 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
57 // alignment. See #262.
62 networkingEnabled chansync.Flag
63 dataDownloadDisallowed chansync.Flag
64 dataUploadDisallowed bool
65 userOnWriteChunkErr func(error)
67 closed chansync.SetOnce
69 infoHash metainfo.Hash
72 // The order pieces are requested if there's no stronger reason like availability or priority.
73 pieceRequestOrder []int
74 // Values are the piece indices that changed.
75 pieceStateChanges pubsub.PubSub[PieceStateChange]
76 // The size of chunks to request from peers over the wire. This is
77 // normally 16KiB by convention these days.
80 // Total length of the torrent in bytes. Stored because it's not O(1) to
81 // get this from the info dict.
84 // The storage to open when the info dict becomes available.
85 storageOpener *storage.Client
86 // Storage for torrent data.
87 storage *storage.Torrent
88 // Read-locked for using storage, and write-locked for Closing.
89 storageLock sync.RWMutex
91 // TODO: Only announce stuff is used?
92 metainfo metainfo.MetaInfo
94 // The info dict. nil if we don't have it (yet).
96 fileIndex segments.Index
99 _chunksPerRegularPiece chunkIndexType
101 webSeeds map[string]*Peer
102 // Active peer connections, running message stream loops. TODO: Make this
103 // open (not-closed) connections only.
104 conns map[*PeerConn]struct{}
105 maxEstablishedConns int
106 // Set of addrs to which we're attempting to connect. Connections are
107 // half-open until all handshakes are completed.
108 halfOpen map[string]map[outgoingConnAttemptKey]*PeerInfo
110 // Reserve of peers to connect to. A peer can be both here and in the
111 // active connections if were told about the peer after connecting with
112 // them. That encourages us to reconnect to peers that are well known in
114 peers prioritizedPeers
115 // Whether we want to know more peers.
116 wantPeersEvent missinggo.Event
117 // An announcer for each tracker URL.
118 trackerAnnouncers map[string]torrentTrackerAnnouncer
119 // How many times we've initiated a DHT announce. TODO: Move into stats.
122 // Name used if the info name isn't available. Should be cleared when the
123 // Info does become available.
127 // The bencoded bytes of the info dict. This is actively manipulated if
128 // the info bytes aren't initially available, and we try to fetch them
131 // Each element corresponds to the 16KiB metadata pieces. If true, we have
132 // received that piece.
133 metadataCompletedChunks []bool
134 metadataChanged sync.Cond
136 // Closed when .Info is obtained.
137 gotMetainfoC chan struct{}
139 readers map[*reader]struct{}
140 _readerNowPieces bitmap.Bitmap
141 _readerReadaheadPieces bitmap.Bitmap
143 // A cache of pieces we need to get. Calculated from various piece and
144 // file priorities and completion states elsewhere.
145 _pendingPieces roaring.Bitmap
146 // A cache of completed piece indices.
147 _completedPieces roaring.Bitmap
148 // Pieces that need to be hashed.
149 piecesQueuedForHash bitmap.Bitmap
150 activePieceHashes int
151 initialPieceCheckDisabled bool
153 connsWithAllPieces map[*Peer]struct{}
155 requestState map[RequestIndex]requestState
156 // Chunks we've written to since the corresponding piece was last checked.
157 dirtyChunks typedRoaring.Bitmap[RequestIndex]
161 // Is On when all pieces are complete.
162 Complete chansync.Flag
164 // Torrent sources in use keyed by the source string.
165 activeSources sync.Map
166 sourcesLogger log.Logger
168 smartBanCache smartBanCache
170 // Large allocations reused between request state updates.
171 requestPieceStates []request_strategy.PieceRequestOrderState
172 requestIndexes []RequestIndex
175 type outgoingConnAttemptKey = *PeerInfo
177 func (t *Torrent) length() int64 {
178 return t._length.Value
181 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
182 // This could be done with roaring.BitSliceIndexing.
183 t.iterPeers(func(peer *Peer) {
184 if _, ok := t.connsWithAllPieces[peer]; ok {
187 if peer.peerHasPiece(i) {
194 func (t *Torrent) decPieceAvailability(i pieceIndex) {
199 if p.relativeAvailability <= 0 {
200 panic(p.relativeAvailability)
202 p.relativeAvailability--
203 t.updatePieceRequestOrder(i)
206 func (t *Torrent) incPieceAvailability(i pieceIndex) {
207 // If we don't the info, this should be reconciled when we do.
210 p.relativeAvailability++
211 t.updatePieceRequestOrder(i)
215 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
216 return t._readerNowPieces
219 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
220 return t._readerReadaheadPieces
223 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
224 return !t.wantPieceIndex(i)
227 // Returns a channel that is closed when the Torrent is closed.
228 func (t *Torrent) Closed() events.Done {
229 return t.closed.Done()
232 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
233 // pending, and half-open peers.
234 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
235 // Add pending peers to the list
236 t.peers.Each(func(peer PeerInfo) {
237 ks = append(ks, peer)
240 // Add half-open peers to the list
241 for _, attempts := range t.halfOpen {
242 for _, peer := range attempts {
243 ks = append(ks, *peer)
247 // Add active peers to the list
248 for conn := range t.conns {
249 ks = append(ks, PeerInfo{
251 Addr: conn.RemoteAddr,
252 Source: conn.Discovery,
253 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
254 // > But if we're not connected to them with an encrypted connection, I couldn't say
255 // > what's appropriate. We can carry forward the SupportsEncryption value as we
256 // > received it from trackers/DHT/PEX, or just use the encryption state for the
257 // > connection. It's probably easiest to do the latter for now.
258 // https://github.com/anacrolix/torrent/pull/188
259 SupportsEncryption: conn.headerEncrypted,
266 func (t *Torrent) setChunkSize(size pp.Integer) {
268 t.chunkPool = sync.Pool{
269 New: func() interface{} {
270 b := make([]byte, size)
276 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
277 return t._completedPieces.Contains(bitmap.BitIndex(piece))
280 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
281 if t.storage == nil {
282 return storage.Completion{Complete: false, Ok: true}
284 return t.pieces[piece].Storage().Completion()
287 // There's a connection to that address already.
288 func (t *Torrent) addrActive(addr string) bool {
289 if _, ok := t.halfOpen[addr]; ok {
292 for c := range t.conns {
294 if ra.String() == addr {
301 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
302 return t.appendConns(ret, func(conn *PeerConn) bool {
303 return !conn.closed.IsSet()
307 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
308 for c := range t.conns {
316 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
318 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
319 if t.closed.IsSet() {
322 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
323 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
324 torrent.Add("peers not added because of bad addr", 1)
325 // cl.logger.Printf("peers not added because of bad addr: %v", p)
329 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
330 torrent.Add("peers replaced", 1)
331 if !replaced.equal(p) {
332 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
339 for t.peers.Len() > cl.config.TorrentPeersHighWater {
340 _, ok := t.peers.DeleteMin()
342 torrent.Add("excess reserve peers discarded", 1)
348 func (t *Torrent) invalidateMetadata() {
349 for i := 0; i < len(t.metadataCompletedChunks); i++ {
350 t.metadataCompletedChunks[i] = false
353 t.gotMetainfoC = make(chan struct{})
358 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
362 if index >= len(t.metadataCompletedChunks) {
363 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
366 copy(t.metadataBytes[(1<<14)*index:], data)
367 t.metadataCompletedChunks[index] = true
370 func (t *Torrent) metadataPieceCount() int {
371 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
374 func (t *Torrent) haveMetadataPiece(piece int) bool {
376 return (1<<14)*piece < len(t.metadataBytes)
378 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
382 func (t *Torrent) metadataSize() int {
383 return len(t.metadataBytes)
386 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
387 for i := 0; i < len(info.Pieces); i += sha1.Size {
388 ret = append(ret, info.Pieces[i:i+sha1.Size])
393 func (t *Torrent) makePieces() {
394 hashes := infoPieceHashes(t.info)
395 t.pieces = make([]Piece, len(hashes))
396 for i, hash := range hashes {
397 piece := &t.pieces[i]
399 piece.index = pieceIndex(i)
400 piece.noPendingWrites.L = &piece.pendingWritesMutex
401 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
403 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
404 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
405 piece.files = files[beginFile:endFile]
409 // Returns the index of the first file containing the piece. files must be
410 // ordered by offset.
411 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
412 for i, f := range files {
413 if f.offset+f.length > pieceOffset {
420 // Returns the index after the last file containing the piece. files must be
421 // ordered by offset.
422 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
423 for i, f := range files {
424 if f.offset+f.length >= pieceEndOffset {
431 func (t *Torrent) cacheLength() {
433 for _, f := range t.info.UpvertedFiles() {
439 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
441 func (t *Torrent) setInfo(info *metainfo.Info) error {
442 if err := validateInfo(info); err != nil {
443 return fmt.Errorf("bad info: %s", err)
445 if t.storageOpener != nil {
447 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
449 return fmt.Errorf("error opening torrent storage: %s", err)
455 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
457 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
458 t.displayName = "" // Save a few bytes lol.
465 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
466 return request_strategy.PieceRequestOrderKey{
467 InfoHash: t.infoHash,
472 // This seems to be all the follow-up tasks after info is set, that can't fail.
473 func (t *Torrent) onSetInfo() {
474 t.pieceRequestOrder = rand.Perm(t.numPieces())
475 t.initPieceRequestOrder()
476 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
477 for i := range t.pieces {
479 // Need to add relativeAvailability before updating piece completion, as that may result in conns
481 if p.relativeAvailability != 0 {
482 panic(p.relativeAvailability)
484 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
485 t.addRequestOrderPiece(i)
486 t.updatePieceCompletion(i)
487 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
488 // t.logger.Printf("piece %s completion unknown, queueing check", p)
492 t.cl.event.Broadcast()
493 close(t.gotMetainfoC)
494 t.updateWantPeersEvent()
495 t.requestState = make(map[RequestIndex]requestState)
496 t.tryCreateMorePieceHashers()
497 t.iterPeers(func(p *Peer) {
499 p.updateRequests("onSetInfo")
503 // Called when metadata for a torrent becomes available.
504 func (t *Torrent) setInfoBytesLocked(b []byte) error {
505 if metainfo.HashBytes(b) != t.infoHash {
506 return errors.New("info bytes have wrong hash")
508 var info metainfo.Info
509 if err := bencode.Unmarshal(b, &info); err != nil {
510 return fmt.Errorf("error unmarshalling info bytes: %s", err)
513 t.metadataCompletedChunks = nil
517 if err := t.setInfo(&info); err != nil {
524 func (t *Torrent) haveAllMetadataPieces() bool {
528 if t.metadataCompletedChunks == nil {
531 for _, have := range t.metadataCompletedChunks {
539 // TODO: Propagate errors to disconnect peer.
540 func (t *Torrent) setMetadataSize(size int) (err error) {
542 // We already know the correct metadata size.
545 if uint32(size) > maxMetadataSize {
546 return log.WithLevel(log.Warning, errors.New("bad size"))
548 if len(t.metadataBytes) == size {
551 t.metadataBytes = make([]byte, size)
552 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
553 t.metadataChanged.Broadcast()
554 for c := range t.conns {
555 c.requestPendingMetadata()
560 // The current working name for the torrent. Either the name in the info dict,
561 // or a display name given such as by the dn value in a magnet link, or "".
562 func (t *Torrent) name() string {
564 defer t.nameMu.RUnlock()
566 return t.info.BestName()
568 if t.displayName != "" {
571 return "infohash:" + t.infoHash.HexString()
574 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
575 p := &t.pieces[index]
576 ret.Priority = t.piecePriority(index)
577 ret.Completion = p.completion()
578 ret.QueuedForHash = p.queuedForHash()
579 ret.Hashing = p.hashing
580 ret.Checking = ret.QueuedForHash || ret.Hashing
581 ret.Marking = p.marking
582 if !ret.Complete && t.piecePartiallyDownloaded(index) {
588 func (t *Torrent) metadataPieceSize(piece int) int {
589 return metadataPieceSize(len(t.metadataBytes), piece)
592 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
595 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
596 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
598 TotalSize: len(t.metadataBytes),
604 type pieceAvailabilityRun struct {
609 func (me pieceAvailabilityRun) String() string {
610 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
613 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
614 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
615 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
617 for i := range t.pieces {
618 rle.Append(t.pieces[i].availability(), 1)
624 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
625 freqs = make([]int, t.numActivePeers()+1)
626 for i := range t.pieces {
627 freqs[t.piece(i).availability()]++
632 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
633 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
634 ret = append(ret, PieceStateRun{
635 PieceState: el.(PieceState),
639 for index := range t.pieces {
640 rle.Append(t.pieceState(pieceIndex(index)), 1)
646 // Produces a small string representing a PieceStateRun.
647 func (psr PieceStateRun) String() (ret string) {
648 ret = fmt.Sprintf("%d", psr.Length)
649 ret += func() string {
650 switch psr.Priority {
651 case PiecePriorityNext:
653 case PiecePriorityNormal:
655 case PiecePriorityReadahead:
657 case PiecePriorityNow:
659 case PiecePriorityHigh:
668 if psr.QueuedForHash {
686 func (t *Torrent) writeStatus(w io.Writer) {
687 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
688 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
690 fmt.Fprintf(w, "Metadata have: ")
691 for _, h := range t.metadataCompletedChunks {
692 fmt.Fprintf(w, "%c", func() rune {
702 fmt.Fprintf(w, "Piece length: %s\n",
705 return fmt.Sprintf("%v (%v chunks)",
707 float64(t.usualPieceSize())/float64(t.chunkSize))
714 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
715 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
716 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
717 // availability frequencies instead.
719 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
720 for _, run := range t.pieceAvailabilityRuns() {
721 ret = append(ret, run.String())
726 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
727 func() (ret []string) {
728 for avail, freq := range t.pieceAvailabilityFrequencies() {
732 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
738 fmt.Fprintf(w, "Reader Pieces:")
739 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
740 fmt.Fprintf(w, " %d:%d", begin, end)
745 fmt.Fprintf(w, "Enabled trackers:\n")
747 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
748 fmt.Fprintf(tw, " URL\tExtra\n")
749 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
752 var luns, runs url.URL = *lu, *ru
755 var ml missinggo.MultiLess
756 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
757 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
759 }).([]torrentTrackerAnnouncer) {
760 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
765 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
767 dumpStats(w, t.statsLocked())
769 fmt.Fprintf(w, "webseeds:\n")
770 t.writePeerStatuses(w, maps.Values(t.webSeeds))
772 peerConns := maps.Keys(t.conns)
773 // Peers without priorities first, then those with. I'm undecided about how to order peers
774 // without priorities.
775 sort.Slice(peerConns, func(li, ri int) bool {
778 ml := multiless.New()
779 lpp := g.ResultFromTuple(l.peerPriority()).ToOption()
780 rpp := g.ResultFromTuple(r.peerPriority()).ToOption()
781 ml = ml.Bool(lpp.Ok, rpp.Ok)
782 ml = ml.Uint32(rpp.Value, lpp.Value)
786 fmt.Fprintf(w, "%v peer conns:\n", len(peerConns))
787 t.writePeerStatuses(w, g.SliceMap(peerConns, func(pc *PeerConn) *Peer {
792 func (t *Torrent) writePeerStatuses(w io.Writer, peers []*Peer) {
794 for _, c := range peers {
798 w.Write(bytes.TrimRight(
799 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
804 func (t *Torrent) haveInfo() bool {
808 // Returns a run-time generated MetaInfo that includes the info bytes and
809 // announce-list as currently known to the client.
810 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
811 return metainfo.MetaInfo{
812 CreationDate: time.Now().Unix(),
813 Comment: "dynamic metainfo from client",
814 CreatedBy: "go.torrent",
815 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
816 InfoBytes: func() []byte {
818 return t.metadataBytes
823 UrlList: func() []string {
824 ret := make([]string, 0, len(t.webSeeds))
825 for url := range t.webSeeds {
826 ret = append(ret, url)
834 func (t *Torrent) BytesMissing() (n int64) {
836 n = t.bytesMissingLocked()
841 func (t *Torrent) bytesMissingLocked() int64 {
845 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
846 roaring.Flip(b, 0, end).Iterate(cb)
849 func (t *Torrent) bytesLeft() (left int64) {
850 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
851 p := t.piece(pieceIndex(x))
852 left += int64(p.length() - p.numDirtyBytes())
858 // Bytes left to give in tracker announces.
859 func (t *Torrent) bytesLeftAnnounce() int64 {
867 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
868 if t.pieceComplete(piece) {
871 if t.pieceAllDirty(piece) {
874 return t.pieces[piece].hasDirtyChunks()
877 func (t *Torrent) usualPieceSize() int {
878 return int(t.info.PieceLength)
881 func (t *Torrent) numPieces() pieceIndex {
882 return t.info.NumPieces()
885 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
886 return pieceIndex(t._completedPieces.GetCardinality())
889 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
891 err = errors.New("already closed")
894 for _, f := range t.onClose {
897 if t.storage != nil {
902 defer t.storageLock.Unlock()
903 if f := t.storage.Close; f != nil {
906 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
911 t.iterPeers(func(p *Peer) {
914 if t.storage != nil {
915 t.deletePieceRequestOrder()
917 t.assertAllPiecesRelativeAvailabilityZero()
919 t.cl.event.Broadcast()
920 t.pieceStateChanges.Close()
921 t.updateWantPeersEvent()
925 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
926 for i := range t.pieces {
928 if p.relativeAvailability != 0 {
929 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
934 func (t *Torrent) requestOffset(r Request) int64 {
935 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
938 // Return the request that would include the given offset into the torrent data. Returns !ok if
939 // there is no such request.
940 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
941 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
944 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
945 defer perf.ScopeTimerErr(&err)()
946 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
947 if err == nil && n != len(data) {
948 err = io.ErrShortWrite
953 func (t *Torrent) bitfield() (bf []bool) {
954 bf = make([]bool, t.numPieces())
955 t._completedPieces.Iterate(func(piece uint32) (again bool) {
962 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
963 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
966 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
967 return t._chunksPerRegularPiece
970 func (t *Torrent) numChunks() RequestIndex {
971 if t.numPieces() == 0 {
974 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
977 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
978 t.dirtyChunks.RemoveRange(
979 uint64(t.pieceRequestIndexOffset(pieceIndex)),
980 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
983 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
984 if t.info.PieceLength == 0 {
985 // There will be no variance amongst pieces. Only pain.
988 if piece == t.numPieces()-1 {
989 ret := pp.Integer(t.length() % t.info.PieceLength)
994 return pp.Integer(t.info.PieceLength)
997 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
998 return &blockCheckingWriter{
999 cache: &t.smartBanCache,
1000 requestIndex: t.pieceRequestIndexOffset(piece),
1001 chunkSize: t.chunkSize.Int(),
1005 func (t *Torrent) hashPiece(piece pieceIndex) (
1007 // These are peers that sent us blocks that differ from what we hash here.
1008 differingPeers map[bannableAddr]struct{},
1012 p.waitNoPendingWrites()
1013 storagePiece := t.pieces[piece].Storage()
1015 // Does the backend want to do its own hashing?
1016 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
1017 var sum metainfo.Hash
1018 // log.Printf("A piece decided to self-hash: %d", piece)
1019 sum, err = i.SelfHash()
1020 missinggo.CopyExact(&ret, sum)
1024 hash := pieceHash.New()
1025 const logPieceContents = false
1026 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1027 writers := []io.Writer{hash, smartBanWriter}
1028 var examineBuf bytes.Buffer
1029 if logPieceContents {
1030 writers = append(writers, &examineBuf)
1032 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1033 if logPieceContents {
1034 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1036 smartBanWriter.Flush()
1037 differingPeers = smartBanWriter.badPeers
1038 missinggo.CopyExact(&ret, hash.Sum(nil))
1042 func (t *Torrent) haveAnyPieces() bool {
1043 return !t._completedPieces.IsEmpty()
1046 func (t *Torrent) haveAllPieces() bool {
1050 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1053 func (t *Torrent) havePiece(index pieceIndex) bool {
1054 return t.haveInfo() && t.pieceComplete(index)
1057 func (t *Torrent) maybeDropMutuallyCompletePeer(
1058 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1062 if !t.cl.config.DropMutuallyCompletePeers {
1065 if !t.haveAllPieces() {
1068 if all, known := p.peerHasAllPieces(); !(known && all) {
1074 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1078 func (t *Torrent) haveChunk(r Request) (ret bool) {
1080 // log.Println("have chunk", r, ret)
1085 if t.pieceComplete(pieceIndex(r.Index)) {
1088 p := &t.pieces[r.Index]
1089 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1092 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1093 return chunkIndexType(cs.Begin / chunkSize)
1096 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1097 return t._pendingPieces.Contains(uint32(index))
1100 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1101 // conns (which is a map).
1102 var peerConnSlices sync.Pool
1104 func getPeerConnSlice(cap int) []*PeerConn {
1105 getInterface := peerConnSlices.Get()
1106 if getInterface == nil {
1107 return make([]*PeerConn, 0, cap)
1109 return getInterface.([]*PeerConn)[:0]
1113 // Calls the given function with a slice of unclosed conns. It uses a pool to reduce allocations as
1114 // this is a frequent occurrence.
1115 func (t *Torrent) withUnclosedConns(f func([]*PeerConn)) {
1116 sl := t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))
1118 peerConnSlices.Put(sl)
1121 func (t *Torrent) worstBadConnFromSlice(opts worseConnLensOpts, sl []*PeerConn) *PeerConn {
1122 wcs := worseConnSlice{conns: sl}
1125 for wcs.Len() != 0 {
1126 c := heap.Pop(&wcs).(*PeerConn)
1127 if opts.incomingIsBad && !c.outgoing {
1130 if opts.outgoingIsBad && c.outgoing {
1133 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1136 // If the connection is in the worst half of the established
1137 // connection quota and is older than a minute.
1138 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1139 // Give connections 1 minute to prove themselves.
1140 if time.Since(c.completedHandshake) > time.Minute {
1148 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1149 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1150 // established connections for more than a minute. This is O(n log n). If there was a way to not
1151 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1152 func (t *Torrent) worstBadConn(opts worseConnLensOpts) (ret *PeerConn) {
1153 t.withUnclosedConns(func(ucs []*PeerConn) {
1154 ret = t.worstBadConnFromSlice(opts, ucs)
1159 type PieceStateChange struct {
1164 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1165 t.cl._mu.Defer(func() {
1166 cur := t.pieceState(piece)
1167 p := &t.pieces[piece]
1168 if cur != p.publicPieceState {
1169 p.publicPieceState = cur
1170 t.pieceStateChanges.Publish(PieceStateChange{
1178 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1179 if t.pieceComplete(piece) {
1182 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1185 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1186 return t.pieces[piece].allChunksDirty()
1189 func (t *Torrent) readersChanged() {
1190 t.updateReaderPieces()
1191 t.updateAllPiecePriorities("Torrent.readersChanged")
1194 func (t *Torrent) updateReaderPieces() {
1195 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1198 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1202 t.updateReaderPieces()
1203 // Order the ranges, high and low.
1205 if l.begin > h.begin {
1208 if l.end < h.begin {
1209 // Two distinct ranges.
1210 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1211 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1218 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1222 func (t *Torrent) maybeNewConns() {
1223 // Tickle the accept routine.
1224 t.cl.event.Broadcast()
1228 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1229 if t._pendingPieces.Contains(uint32(piece)) {
1230 t.iterPeers(func(c *Peer) {
1231 // if c.requestState.Interested {
1234 if !c.isLowOnRequests() {
1237 if !c.peerHasPiece(piece) {
1240 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1243 c.updateRequests(reason)
1247 t.publishPieceChange(piece)
1250 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1251 if !t.closed.IsSet() {
1252 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1254 t.updatePieceRequestOrder(piece)
1256 p := &t.pieces[piece]
1257 newPrio := p.uncachedPriority()
1258 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1259 if newPrio == PiecePriorityNone {
1260 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1264 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1268 t.piecePriorityChanged(piece, reason)
1271 func (t *Torrent) updateAllPiecePriorities(reason string) {
1272 t.updatePiecePriorities(0, t.numPieces(), reason)
1275 // Update all piece priorities in one hit. This function should have the same
1276 // output as updatePiecePriority, but across all pieces.
1277 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1278 for i := begin; i < end; i++ {
1279 t.updatePiecePriority(i, reason)
1283 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1284 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1285 if off >= t.length() {
1295 begin = pieceIndex(off / t.info.PieceLength)
1296 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1297 if end > pieceIndex(t.info.NumPieces()) {
1298 end = pieceIndex(t.info.NumPieces())
1303 // Returns true if all iterations complete without breaking. Returns the read regions for all
1304 // readers. The reader regions should not be merged as some callers depend on this method to
1305 // enumerate readers.
1306 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1307 for r := range t.readers {
1309 if p.begin >= p.end {
1312 if !f(p.begin, p.end) {
1319 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1320 return t.piece(piece).uncachedPriority()
1323 func (t *Torrent) pendRequest(req RequestIndex) {
1324 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1327 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1328 t.cl.event.Broadcast()
1329 if t.pieceComplete(piece) {
1330 t.onPieceCompleted(piece)
1332 t.onIncompletePiece(piece)
1334 t.updatePiecePriority(piece, reason)
1337 func (t *Torrent) numReceivedConns() (ret int) {
1338 for c := range t.conns {
1339 if c.Discovery == PeerSourceIncoming {
1346 func (t *Torrent) numOutgoingConns() (ret int) {
1347 for c := range t.conns {
1355 func (t *Torrent) maxHalfOpen() int {
1356 // Note that if we somehow exceed the maximum established conns, we want
1357 // the negative value to have an effect.
1358 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1359 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1360 // We want to allow some experimentation with new peers, and to try to
1361 // upset an oversupply of received connections.
1363 max(5, extraIncoming)+establishedHeadroom,
1364 int64(t.cl.config.HalfOpenConnsPerTorrent),
1368 func (t *Torrent) openNewConns() (initiated int) {
1369 defer t.updateWantPeersEvent()
1370 for t.peers.Len() != 0 {
1371 if !t.wantOutgoingConns() {
1374 if len(t.halfOpen) >= t.maxHalfOpen() {
1377 if len(t.cl.dialers) == 0 {
1380 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1383 p := t.peers.PopMax()
1384 opts := outgoingConnOpts{
1387 requireRendezvous: false,
1388 skipHolepunchRendezvous: false,
1389 receivedHolepunchConnect: false,
1390 HeaderObfuscationPolicy: t.cl.config.HeaderObfuscationPolicy,
1392 initiateConn(opts, false)
1398 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1400 uncached := t.pieceCompleteUncached(piece)
1401 cached := p.completion()
1402 changed := cached != uncached
1403 complete := uncached.Complete
1404 p.storageCompletionOk = uncached.Ok
1407 t._completedPieces.Add(x)
1410 t._completedPieces.Remove(x)
1412 p.t.updatePieceRequestOrder(piece)
1414 if complete && len(p.dirtiers) != 0 {
1415 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1418 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1419 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1424 // Non-blocking read. Client lock is not required.
1425 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1427 p := &t.pieces[off/t.info.PieceLength]
1428 p.waitNoPendingWrites()
1430 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1441 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1442 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1443 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1444 func (t *Torrent) maybeCompleteMetadata() error {
1449 if !t.haveAllMetadataPieces() {
1450 // Don't have enough metadata pieces.
1453 err := t.setInfoBytesLocked(t.metadataBytes)
1455 t.invalidateMetadata()
1456 return fmt.Errorf("error setting info bytes: %s", err)
1458 if t.cl.config.Debug {
1459 t.logger.Printf("%s: got metadata from peers", t)
1464 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1465 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1467 now.Add(bitmap.BitIndex(begin))
1468 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1475 func (t *Torrent) needData() bool {
1476 if t.closed.IsSet() {
1482 return !t._pendingPieces.IsEmpty()
1485 func appendMissingStrings(old, new []string) (ret []string) {
1488 for _, n := range new {
1489 for _, o := range old {
1494 ret = append(ret, n)
1499 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1501 for minNumTiers > len(ret) {
1502 ret = append(ret, nil)
1507 func (t *Torrent) addTrackers(announceList [][]string) {
1508 fullAnnounceList := &t.metainfo.AnnounceList
1509 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1510 for tierIndex, trackerURLs := range announceList {
1511 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1513 t.startMissingTrackerScrapers()
1514 t.updateWantPeersEvent()
1517 // Don't call this before the info is available.
1518 func (t *Torrent) bytesCompleted() int64 {
1522 return t.length() - t.bytesLeft()
1525 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1528 return t.setInfoBytesLocked(b)
1531 // Returns true if connection is removed from torrent.Conns.
1532 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1533 if !c.closed.IsSet() {
1534 panic("connection is not closed")
1535 // There are behaviours prevented by the closed state that will fail
1536 // if the connection has been deleted.
1540 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1541 // the drop event against the PexConnState instead.
1543 if !t.cl.config.DisablePEX {
1547 torrent.Add("deleted connections", 1)
1548 c.deleteAllRequests("Torrent.deletePeerConn")
1549 t.assertPendingRequests()
1550 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1551 panic(t.connsWithAllPieces)
1556 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1557 if t.deleteConnWithAllPieces(p) {
1563 p.peerPieces().Iterate(func(i uint32) bool {
1564 p.t.decPieceAvailability(pieceIndex(i))
1569 func (t *Torrent) assertPendingRequests() {
1573 // var actual pendingRequests
1574 // if t.haveInfo() {
1575 // actual.m = make([]int, t.numChunks())
1577 // t.iterPeers(func(p *Peer) {
1578 // p.requestState.Requests.Iterate(func(x uint32) bool {
1583 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1589 func (t *Torrent) dropConnection(c *PeerConn) {
1590 t.cl.event.Broadcast()
1592 if t.deletePeerConn(c) {
1597 // Peers as in contact information for dialing out.
1598 func (t *Torrent) wantPeers() bool {
1599 if t.closed.IsSet() {
1602 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1605 return t.wantOutgoingConns()
1608 func (t *Torrent) updateWantPeersEvent() {
1610 t.wantPeersEvent.Set()
1612 t.wantPeersEvent.Clear()
1616 // Returns whether the client should make effort to seed the torrent.
1617 func (t *Torrent) seeding() bool {
1619 if t.closed.IsSet() {
1622 if t.dataUploadDisallowed {
1625 if cl.config.NoUpload {
1628 if !cl.config.Seed {
1631 if cl.config.DisableAggressiveUpload && t.needData() {
1637 func (t *Torrent) onWebRtcConn(
1638 c datachannel.ReadWriteCloser,
1639 dcc webtorrent.DataChannelContext,
1642 netConn := webrtcNetConn{
1644 DataChannelContext: dcc,
1646 peerRemoteAddr := netConn.RemoteAddr()
1647 //t.logger.Levelf(log.Critical, "onWebRtcConn remote addr: %v", peerRemoteAddr)
1648 if t.cl.badPeerAddr(peerRemoteAddr) {
1651 localAddrIpPort := missinggo.IpPortFromNetAddr(netConn.LocalAddr())
1652 pc, err := t.cl.initiateProtocolHandshakes(
1653 context.Background(),
1658 outgoing: dcc.LocalOffered,
1659 remoteAddr: peerRemoteAddr,
1660 localPublicAddr: localAddrIpPort,
1661 network: webrtcNetwork,
1662 connString: fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1666 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1669 if dcc.LocalOffered {
1670 pc.Discovery = PeerSourceTracker
1672 pc.Discovery = PeerSourceIncoming
1674 pc.conn.SetWriteDeadline(time.Time{})
1677 err = t.cl.runHandshookConn(pc, t)
1679 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1683 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1684 err := t.cl.runHandshookConn(pc, t)
1685 if err != nil || logAll {
1686 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1690 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1691 t.logRunHandshookConn(pc, false, log.Debug)
1694 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1695 wtc, release := t.cl.websocketTrackers.Get(u.String(), t.infoHash)
1696 // This needs to run before the Torrent is dropped from the Client, to prevent a new webtorrent.TrackerClient for
1697 // the same info hash before the old one is cleaned up.
1698 t.onClose = append(t.onClose, release)
1699 wst := websocketTrackerStatus{u, wtc}
1701 err := wtc.Announce(tracker.Started, t.infoHash)
1703 t.logger.WithDefaultLevel(log.Warning).Printf(
1704 "error in initial announce to %q: %v",
1712 func (t *Torrent) startScrapingTracker(_url string) {
1716 u, err := url.Parse(_url)
1718 // URLs with a leading '*' appear to be a uTorrent convention to
1719 // disable trackers.
1721 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1725 if u.Scheme == "udp" {
1727 t.startScrapingTracker(u.String())
1729 t.startScrapingTracker(u.String())
1732 if _, ok := t.trackerAnnouncers[_url]; ok {
1735 sl := func() torrentTrackerAnnouncer {
1738 if t.cl.config.DisableWebtorrent {
1741 return t.startWebsocketAnnouncer(*u)
1743 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1747 if t.cl.config.DisableIPv6 {
1751 newAnnouncer := &trackerScraper{
1754 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1756 go newAnnouncer.Run()
1762 if t.trackerAnnouncers == nil {
1763 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1765 t.trackerAnnouncers[_url] = sl
1768 // Adds and starts tracker scrapers for tracker URLs that aren't already
1770 func (t *Torrent) startMissingTrackerScrapers() {
1771 if t.cl.config.DisableTrackers {
1774 t.startScrapingTracker(t.metainfo.Announce)
1775 for _, tier := range t.metainfo.AnnounceList {
1776 for _, url := range tier {
1777 t.startScrapingTracker(url)
1782 // Returns an AnnounceRequest with fields filled out to defaults and current
1784 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1785 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1786 // dependent on the network in use.
1787 return tracker.AnnounceRequest{
1789 NumWant: func() int32 {
1790 if t.wantPeers() && len(t.cl.dialers) > 0 {
1791 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1796 Port: uint16(t.cl.incomingPeerPort()),
1797 PeerId: t.cl.peerID,
1798 InfoHash: t.infoHash,
1799 Key: t.cl.announceKey(),
1801 // The following are vaguely described in BEP 3.
1803 Left: t.bytesLeftAnnounce(),
1804 Uploaded: t.stats.BytesWrittenData.Int64(),
1805 // There's no mention of wasted or unwanted download in the BEP.
1806 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1810 // Adds peers revealed in an announce until the announce ends, or we have
1812 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1814 for v := range pvs {
1817 for _, cp := range v.Peers {
1819 // Can't do anything with this.
1822 if t.addPeer(PeerInfo{
1823 Addr: ipPortAddr{cp.IP, cp.Port},
1824 Source: PeerSourceDhtGetPeers,
1831 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1836 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1837 // announce ends. stop will force the announce to end.
1838 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1839 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1843 _done := make(chan struct{})
1847 t.consumeDhtAnnouncePeers(ps.Peers())
1853 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1854 _, stop, err := t.AnnounceToDht(s)
1859 case <-t.closed.Done():
1860 case <-time.After(5 * time.Minute):
1866 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1872 if t.closed.IsSet() {
1875 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1876 // TODO: We can include the announce_peer step depending on whether we can receive
1877 // inbound connections. We should probably only announce once every 15 mins too.
1878 if !t.wantAnyConns() {
1881 // TODO: Determine if there's a listener on the port we're announcing.
1882 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1893 err := t.timeboxedAnnounceToDht(s)
1895 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1901 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1902 for _, p := range peers {
1910 // The returned TorrentStats may require alignment in memory. See
1911 // https://github.com/anacrolix/torrent/issues/383.
1912 func (t *Torrent) Stats() TorrentStats {
1914 defer t.cl.rUnlock()
1915 return t.statsLocked()
1918 func (t *Torrent) statsLocked() (ret TorrentStats) {
1919 ret.ActivePeers = len(t.conns)
1920 ret.HalfOpenPeers = len(t.halfOpen)
1921 ret.PendingPeers = t.peers.Len()
1922 ret.TotalPeers = t.numTotalPeers()
1923 ret.ConnectedSeeders = 0
1924 for c := range t.conns {
1925 if all, ok := c.peerHasAllPieces(); all && ok {
1926 ret.ConnectedSeeders++
1929 ret.ConnStats = t.stats.Copy()
1930 ret.PiecesComplete = t.numPiecesCompleted()
1934 // The total number of peers in the torrent.
1935 func (t *Torrent) numTotalPeers() int {
1936 peers := make(map[string]struct{})
1937 for conn := range t.conns {
1938 ra := conn.conn.RemoteAddr()
1940 // It's been closed and doesn't support RemoteAddr.
1943 peers[ra.String()] = struct{}{}
1945 for addr := range t.halfOpen {
1946 peers[addr] = struct{}{}
1948 t.peers.Each(func(peer PeerInfo) {
1949 peers[peer.Addr.String()] = struct{}{}
1954 // Reconcile bytes transferred before connection was associated with a
1956 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1957 if c._stats != (ConnStats{
1958 // Handshakes should only increment these fields:
1959 BytesWritten: c._stats.BytesWritten,
1960 BytesRead: c._stats.BytesRead,
1964 c.postHandshakeStats(func(cs *ConnStats) {
1965 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1966 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1968 c.reconciledHandshakeStats = true
1971 // Returns true if the connection is added.
1972 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1975 torrent.Add("added connections", 1)
1978 if t.closed.IsSet() {
1979 return errors.New("torrent closed")
1981 for c0 := range t.conns {
1982 if c.PeerID != c0.PeerID {
1985 if !t.cl.config.DropDuplicatePeerIds {
1988 if c.hasPreferredNetworkOver(c0) {
1990 t.deletePeerConn(c0)
1992 return errors.New("existing connection preferred")
1995 if len(t.conns) >= t.maxEstablishedConns {
1996 numOutgoing := t.numOutgoingConns()
1997 numIncoming := len(t.conns) - numOutgoing
1998 c := t.worstBadConn(worseConnLensOpts{
1999 // We've already established that we have too many connections at this point, so we just
2000 // need to match what kind we have too many of vs. what we're trying to add now.
2001 incomingIsBad: (numIncoming-numOutgoing > 1) && c.outgoing,
2002 outgoingIsBad: (numOutgoing-numIncoming > 1) && !c.outgoing,
2005 return errors.New("don't want conn")
2010 if len(t.conns) >= t.maxEstablishedConns {
2013 t.conns[c] = struct{}{}
2014 t.cl.event.Broadcast()
2015 // We'll never receive the "p" extended handshake parameter.
2016 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
2022 func (t *Torrent) newConnsAllowed() bool {
2023 if !t.networkingEnabled.Bool() {
2026 if t.closed.IsSet() {
2029 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2035 func (t *Torrent) wantAnyConns() bool {
2036 if !t.networkingEnabled.Bool() {
2039 if t.closed.IsSet() {
2042 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2045 return len(t.conns) < t.maxEstablishedConns
2048 func (t *Torrent) wantOutgoingConns() bool {
2049 if !t.newConnsAllowed() {
2052 if len(t.conns) < t.maxEstablishedConns {
2055 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2056 return t.worstBadConn(worseConnLensOpts{
2057 incomingIsBad: numIncomingConns-t.numOutgoingConns() > 1,
2058 outgoingIsBad: false,
2062 func (t *Torrent) wantIncomingConns() bool {
2063 if !t.newConnsAllowed() {
2066 if len(t.conns) < t.maxEstablishedConns {
2069 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2070 return t.worstBadConn(worseConnLensOpts{
2071 incomingIsBad: false,
2072 outgoingIsBad: t.numOutgoingConns()-numIncomingConns > 1,
2076 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
2079 oldMax = t.maxEstablishedConns
2080 t.maxEstablishedConns = max
2081 wcs := worseConnSlice{
2082 conns: t.appendConns(nil, func(*PeerConn) bool {
2086 wcs.initKeys(worseConnLensOpts{})
2088 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
2089 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
2095 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
2096 t.logger.LazyLog(log.Debug, func() log.Msg {
2097 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
2101 t.cl.event.Broadcast()
2102 if t.closed.IsSet() {
2106 // Don't score the first time a piece is hashed, it could be an initial check.
2107 if p.storageCompletionOk {
2109 pieceHashedCorrect.Add(1)
2112 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
2113 ).AddValues(t, p).LogLevel(
2115 log.Debug, t.logger)
2117 pieceHashedNotCorrect.Add(1)
2122 t.publishPieceChange(piece)
2125 t.publishPieceChange(piece)
2129 if len(p.dirtiers) != 0 {
2130 // Don't increment stats above connection-level for every involved connection.
2131 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2133 for c := range p.dirtiers {
2134 c._stats.incrementPiecesDirtiedGood()
2136 t.clearPieceTouchers(piece)
2137 hasDirty := p.hasDirtyChunks()
2140 p.Flush() // You can be synchronous here!
2142 err := p.Storage().MarkComplete()
2144 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2148 if t.closed.IsSet() {
2151 t.pendAllChunkSpecs(piece)
2153 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2154 // Peers contributed to all the data for this piece hash failure, and the failure was
2155 // not due to errors in the storage (such as data being dropped in a cache).
2157 // Increment Torrent and above stats, and then specific connections.
2158 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2159 for c := range p.dirtiers {
2160 // Y u do dis peer?!
2161 c.stats().incrementPiecesDirtiedBad()
2164 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2165 for c := range p.dirtiers {
2167 bannableTouchers = append(bannableTouchers, c)
2170 t.clearPieceTouchers(piece)
2171 slices.Sort(bannableTouchers, connLessTrusted)
2173 if t.cl.config.Debug {
2175 "bannable conns by trust for piece %d: %v",
2177 func() (ret []connectionTrust) {
2178 for _, c := range bannableTouchers {
2179 ret = append(ret, c.trust())
2186 if len(bannableTouchers) >= 1 {
2187 c := bannableTouchers[0]
2188 if len(bannableTouchers) != 1 {
2189 t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2191 // Turns out it's still useful to ban peers like this because if there's only a
2192 // single peer for a piece, and we never progress that piece to completion, we
2193 // will never smart-ban them. Discovered in
2194 // https://github.com/anacrolix/torrent/issues/715.
2195 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2200 t.onIncompletePiece(piece)
2201 p.Storage().MarkNotComplete()
2203 t.updatePieceCompletion(piece)
2206 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2207 start := t.pieceRequestIndexOffset(piece)
2208 end := start + t.pieceNumChunks(piece)
2209 for ri := start; ri < end; ri++ {
2214 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2215 t.pendAllChunkSpecs(piece)
2216 t.cancelRequestsForPiece(piece)
2217 t.piece(piece).readerCond.Broadcast()
2218 for conn := range t.conns {
2220 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2224 // Called when a piece is found to be not complete.
2225 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2226 if t.pieceAllDirty(piece) {
2227 t.pendAllChunkSpecs(piece)
2229 if !t.wantPieceIndex(piece) {
2230 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2233 // We could drop any connections that we told we have a piece that we
2234 // don't here. But there's a test failure, and it seems clients don't care
2235 // if you request pieces that you already claim to have. Pruning bad
2236 // connections might just remove any connections that aren't treating us
2237 // favourably anyway.
2239 // for c := range t.conns {
2240 // if c.sentHave(piece) {
2244 t.iterPeers(func(conn *Peer) {
2245 if conn.peerHasPiece(piece) {
2246 conn.updateRequests("piece incomplete")
2251 func (t *Torrent) tryCreateMorePieceHashers() {
2252 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2256 func (t *Torrent) tryCreatePieceHasher() bool {
2257 if t.storage == nil {
2260 pi, ok := t.getPieceToHash()
2265 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2267 t.publishPieceChange(pi)
2268 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2269 t.storageLock.RLock()
2270 t.activePieceHashes++
2271 go t.pieceHasher(pi)
2275 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2276 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2277 if t.piece(i).hashing {
2287 func (t *Torrent) dropBannedPeers() {
2288 t.iterPeers(func(p *Peer) {
2289 remoteIp := p.remoteIp()
2290 if remoteIp == nil {
2291 if p.bannableAddr.Ok {
2292 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2296 netipAddr := netip.MustParseAddr(remoteIp.String())
2297 if Some(netipAddr) != p.bannableAddr {
2298 t.logger.WithDefaultLevel(log.Debug).Printf(
2299 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2300 p, remoteIp, p.bannableAddr)
2302 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2303 // Should this be a close?
2305 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2310 func (t *Torrent) pieceHasher(index pieceIndex) {
2312 sum, failedPeers, copyErr := t.hashPiece(index)
2313 correct := sum == *p.hash
2317 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2319 t.storageLock.RUnlock()
2323 for peer := range failedPeers {
2324 t.cl.banPeerIP(peer.AsSlice())
2325 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2328 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2329 t.smartBanCache.ForgetBlock(ri)
2333 t.pieceHashed(index, correct, copyErr)
2334 t.updatePiecePriority(index, "Torrent.pieceHasher")
2335 t.activePieceHashes--
2336 t.tryCreateMorePieceHashers()
2339 // Return the connections that touched a piece, and clear the entries while doing it.
2340 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2342 for c := range p.dirtiers {
2343 delete(c.peerTouchedPieces, pi)
2344 delete(p.dirtiers, c)
2348 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2349 t.iterPeers(func(p *Peer) {
2350 ret = append(ret, p)
2355 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2356 piece := t.piece(pieceIndex)
2357 if piece.queuedForHash() {
2360 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2361 t.publishPieceChange(pieceIndex)
2362 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2363 t.tryCreateMorePieceHashers()
2366 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2367 // before the Info is available.
2368 func (t *Torrent) VerifyData() {
2369 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2370 t.Piece(i).VerifyData()
2374 func (t *Torrent) connectingToPeerAddr(addrStr string) bool {
2375 return len(t.halfOpen[addrStr]) != 0
2378 func (t *Torrent) hasPeerConnForAddr(x PeerRemoteAddr) bool {
2379 addrStr := x.String()
2380 for c := range t.conns {
2382 if ra.String() == addrStr {
2389 func (t *Torrent) getHalfOpenPath(
2391 attemptKey outgoingConnAttemptKey,
2392 ) nestedmaps.Path[*PeerInfo] {
2393 return nestedmaps.Next(nestedmaps.Next(nestedmaps.Begin(&t.halfOpen), addrStr), attemptKey)
2396 func (t *Torrent) addHalfOpen(addrStr string, attemptKey *PeerInfo) {
2397 path := t.getHalfOpenPath(addrStr, attemptKey)
2399 panic("should be unique")
2401 path.Set(attemptKey)
2405 // Start the process of connecting to the given peer for the given torrent if appropriate. I'm not
2406 // sure all the PeerInfo fields are being used.
2408 opts outgoingConnOpts,
2412 peer := opts.peerInfo
2413 if peer.Id == t.cl.peerID {
2416 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2420 addrStr := addr.String()
2422 if t.connectingToPeerAddr(addrStr) {
2426 if t.hasPeerConnForAddr(addr) {
2430 t.addHalfOpen(addrStr, attemptKey)
2431 go t.cl.outgoingConnection(
2437 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2438 // quickly make one Client visible to the Torrent of another Client.
2439 func (t *Torrent) AddClientPeer(cl *Client) int {
2440 return t.AddPeers(func() (ps []PeerInfo) {
2441 for _, la := range cl.ListenAddrs() {
2442 ps = append(ps, PeerInfo{
2451 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2453 func (t *Torrent) allStats(f func(*ConnStats)) {
2458 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2459 return t.pieces[i].hashing
2462 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2463 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2466 func (t *Torrent) dialTimeout() time.Duration {
2467 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2470 func (t *Torrent) piece(i int) *Piece {
2474 func (t *Torrent) onWriteChunkErr(err error) {
2475 if t.userOnWriteChunkErr != nil {
2476 go t.userOnWriteChunkErr(err)
2479 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2480 t.disallowDataDownloadLocked()
2483 func (t *Torrent) DisallowDataDownload() {
2484 t.disallowDataDownloadLocked()
2487 func (t *Torrent) disallowDataDownloadLocked() {
2488 t.dataDownloadDisallowed.Set()
2491 func (t *Torrent) AllowDataDownload() {
2492 t.dataDownloadDisallowed.Clear()
2495 // Enables uploading data, if it was disabled.
2496 func (t *Torrent) AllowDataUpload() {
2499 t.dataUploadDisallowed = false
2500 for c := range t.conns {
2501 c.updateRequests("allow data upload")
2505 // Disables uploading data, if it was enabled.
2506 func (t *Torrent) DisallowDataUpload() {
2509 t.dataUploadDisallowed = true
2510 for c := range t.conns {
2511 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2512 c.updateRequests("disallow data upload")
2516 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2517 // or if nil, a critical message is logged, and data download is disabled.
2518 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2521 t.userOnWriteChunkErr = f
2524 func (t *Torrent) iterPeers(f func(p *Peer)) {
2525 for pc := range t.conns {
2528 for _, ws := range t.webSeeds {
2533 func (t *Torrent) callbacks() *Callbacks {
2534 return &t.cl.config.Callbacks
2537 type AddWebSeedsOpt func(*webseed.Client)
2539 // Sets the WebSeed trailing path escaper for a webseed.Client.
2540 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2541 return func(c *webseed.Client) {
2542 c.PathEscaper = custom
2546 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2549 for _, u := range urls {
2550 t.addWebSeed(u, opts...)
2554 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2555 if t.cl.config.DisableWebseeds {
2558 if _, ok := t.webSeeds[url]; ok {
2561 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2562 // right away. This value should be some multiple of the number of connections to a host. I
2563 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2564 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2565 // "https://webtorrent.io/torrents/".
2566 const maxRequests = 16
2572 reconciledHandshakeStats: true,
2573 // This should affect how often we have to recompute requests for this peer. Note that
2574 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2575 // requests mark more often, so recomputation is probably sooner than with regular peer
2576 // conns. ~4x maxRequests would be about right.
2577 PeerMaxRequests: 128,
2578 // TODO: Set ban prefix?
2579 RemoteAddr: remoteAddrFromUrl(url),
2580 callbacks: t.callbacks(),
2582 client: webseed.Client{
2583 HttpClient: t.cl.httpClient,
2585 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2586 return &rateLimitedReader{
2587 l: t.cl.config.DownloadRateLimiter,
2592 activeRequests: make(map[Request]webseed.Request, maxRequests),
2594 ws.peer.initRequestState()
2595 for _, opt := range opts {
2598 ws.peer.initUpdateRequestsTimer()
2599 ws.requesterCond.L = t.cl.locker()
2600 for i := 0; i < maxRequests; i += 1 {
2603 for _, f := range t.callbacks().NewPeer {
2606 ws.peer.logger = t.logger.WithContextValue(&ws)
2607 ws.peer.peerImpl = &ws
2609 ws.onGotInfo(t.info)
2611 t.webSeeds[url] = &ws.peer
2614 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2615 t.iterPeers(func(p1 *Peer) {
2623 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2624 index := t.pieceIndexOfRequestIndex(ri)
2627 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2631 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2632 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2635 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2636 return RequestIndex(piece) * t.chunksPerRegularPiece()
2639 func (t *Torrent) updateComplete() {
2640 t.Complete.SetBool(t.haveAllPieces())
2643 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2644 p := t.requestingPeer(r)
2648 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2649 //delete(t.pendingRequests, r)
2650 if _, ok := t.requestState[r]; ok {
2651 panic("expected request state to be gone")
2656 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2657 return t.requestState[r].peer
2660 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2661 if t.connsWithAllPieces == nil {
2662 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2664 t.connsWithAllPieces[p] = struct{}{}
2667 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2668 _, ok := t.connsWithAllPieces[p]
2669 delete(t.connsWithAllPieces, p)
2673 func (t *Torrent) numActivePeers() int {
2674 return len(t.conns) + len(t.webSeeds)
2677 func (t *Torrent) hasStorageCap() bool {
2678 f := t.storage.Capacity
2686 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2687 return pieceIndex(ri / t.chunksPerRegularPiece())
2690 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2691 reuseIter *typedRoaring.Iterator[RequestIndex],
2693 f func(RequestIndex),
2695 reuseIter.Initialize(&t.dirtyChunks)
2696 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2697 iterBitmapUnsetInRange(
2699 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2704 type requestState struct {
2709 // Returns an error if a received chunk is out of bounds in someway.
2710 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2712 return errors.New("torrent missing info")
2714 if int(r.Index) >= t.numPieces() {
2715 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2717 pieceLength := t.pieceLength(pieceIndex(r.Index))
2718 if r.Begin >= pieceLength {
2719 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2721 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2722 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2723 // should be considerable checks elsewhere for this case due to the network overhead. We should
2724 // catch most of the overflow manipulation stuff by checking index and begin above.
2728 func (t *Torrent) peerConnsWithDialAddrPort(target netip.AddrPort) (ret []*PeerConn) {
2729 for pc := range t.conns {
2730 dialAddr, err := pc.remoteDialAddrPort()
2734 if dialAddr != target {
2737 ret = append(ret, pc)
2742 func makeUtHolepunchMsgForPeerConn(
2743 recipient *PeerConn,
2744 msgType utHolepunch.MsgType,
2745 addrPort netip.AddrPort,
2746 errCode utHolepunch.ErrCode,
2748 utHolepunchMsg := utHolepunch.Msg{
2753 extendedPayload, err := utHolepunchMsg.MarshalBinary()
2759 ExtendedID: MapMustGet(recipient.PeerExtensionIDs, utHolepunch.ExtensionName),
2760 ExtendedPayload: extendedPayload,
2764 func sendUtHolepunchMsg(
2766 msgType utHolepunch.MsgType,
2767 addrPort netip.AddrPort,
2768 errCode utHolepunch.ErrCode,
2770 pc.write(makeUtHolepunchMsgForPeerConn(pc, msgType, addrPort, errCode))
2773 func (t *Torrent) handleReceivedUtHolepunchMsg(msg utHolepunch.Msg, sender *PeerConn) error {
2774 switch msg.MsgType {
2775 case utHolepunch.Rendezvous:
2776 t.logger.Printf("got holepunch rendezvous request for %v from %p", msg.AddrPort, sender)
2777 sendMsg := sendUtHolepunchMsg
2778 senderAddrPort, err := sender.remoteDialAddrPort()
2780 sender.logger.Levelf(
2782 "error getting ut_holepunch rendezvous sender's dial address: %v",
2785 // There's no better error code. The sender's address itself is invalid. I don't see
2786 // this error message being appropriate anywhere else anyway.
2787 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSuchPeer)
2789 targets := t.peerConnsWithDialAddrPort(msg.AddrPort)
2790 if len(targets) == 0 {
2791 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NotConnected)
2794 for _, pc := range targets {
2795 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2796 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSupport)
2799 sendMsg(sender, utHolepunch.Connect, msg.AddrPort, 0)
2800 sendMsg(pc, utHolepunch.Connect, senderAddrPort, 0)
2803 case utHolepunch.Connect:
2804 opts := outgoingConnOpts{
2807 Source: PeerSourceUtHolepunch,
2808 PexPeerFlags: sender.pex.remoteLiveConns[msg.AddrPort].UnwrapOrZeroValue(),
2811 // Don't attempt to start our own rendezvous if we fail to connect.
2812 skipHolepunchRendezvous: true,
2813 receivedHolepunchConnect: true,
2814 // Assume that the other end initiated the rendezvous, and will use our preferred
2815 // encryption. So we will act normally.
2816 HeaderObfuscationPolicy: t.cl.config.HeaderObfuscationPolicy,
2818 initiateConn(opts, true)
2820 case utHolepunch.Error:
2821 t.logger.Levelf(log.Debug, "received ut_holepunch error message from %v: %v", sender, msg.ErrCode)
2824 return fmt.Errorf("unhandled msg type %v", msg.MsgType)
2828 func (t *Torrent) startHolepunchRendezvous(addrPort netip.AddrPort) error {
2830 for pc := range t.conns {
2831 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2834 if pc.supportsExtension(pp.ExtensionNamePex) {
2835 if !g.MapContains(pc.pex.remoteLiveConns, addrPort) {
2839 t.logger.Levelf(log.Debug, "sent ut_holepunch rendezvous message to %v for %v", pc, addrPort)
2840 sendUtHolepunchMsg(pc, utHolepunch.Rendezvous, addrPort, 0)
2844 return errors.New("no eligible relays")
2849 func (t *Torrent) numHalfOpenAttempts() (num int) {
2850 for _, attempts := range t.halfOpen {
2851 num += len(attempts)
2856 func (t *Torrent) getDialTimeoutUnlocked() time.Duration {
2860 return t.dialTimeout()