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/davecgh/go-spew/spew"
35 "github.com/pion/datachannel"
36 "golang.org/x/exp/maps"
38 "github.com/anacrolix/torrent/bencode"
39 "github.com/anacrolix/torrent/common"
40 "github.com/anacrolix/torrent/internal/check"
41 "github.com/anacrolix/torrent/internal/nestedmaps"
42 "github.com/anacrolix/torrent/metainfo"
43 pp "github.com/anacrolix/torrent/peer_protocol"
44 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
45 request_strategy "github.com/anacrolix/torrent/request-strategy"
46 "github.com/anacrolix/torrent/segments"
47 "github.com/anacrolix/torrent/storage"
48 "github.com/anacrolix/torrent/tracker"
49 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
50 "github.com/anacrolix/torrent/webseed"
51 "github.com/anacrolix/torrent/webtorrent"
54 // Maintains state of torrent within a Client. Many methods should not be called before the info is
55 // available, see .Info and .GotInfo.
57 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
58 // alignment. See #262.
63 networkingEnabled chansync.Flag
64 dataDownloadDisallowed chansync.Flag
65 dataUploadDisallowed bool
66 userOnWriteChunkErr func(error)
68 closed chansync.SetOnce
70 infoHash metainfo.Hash
73 // The order pieces are requested if there's no stronger reason like availability or priority.
74 pieceRequestOrder []int
75 // Values are the piece indices that changed.
76 pieceStateChanges pubsub.PubSub[PieceStateChange]
77 // The size of chunks to request from peers over the wire. This is
78 // normally 16KiB by convention these days.
81 // Total length of the torrent in bytes. Stored because it's not O(1) to
82 // get this from the info dict.
85 // The storage to open when the info dict becomes available.
86 storageOpener *storage.Client
87 // Storage for torrent data.
88 storage *storage.Torrent
89 // Read-locked for using storage, and write-locked for Closing.
90 storageLock sync.RWMutex
92 // TODO: Only announce stuff is used?
93 metainfo metainfo.MetaInfo
95 // The info dict. nil if we don't have it (yet).
97 fileIndex segments.Index
100 _chunksPerRegularPiece chunkIndexType
102 webSeeds map[string]*Peer
103 // Active peer connections, running message stream loops. TODO: Make this
104 // open (not-closed) connections only.
105 conns map[*PeerConn]struct{}
106 maxEstablishedConns int
107 // Set of addrs to which we're attempting to connect. Connections are
108 // half-open until all handshakes are completed.
109 halfOpen map[string]map[outgoingConnAttemptKey]*PeerInfo
110 // The final ess is not silent here as it's in the plural.
111 utHolepunchRendezvous map[netip.AddrPort]*utHolepunchRendezvous
113 // Reserve of peers to connect to. A peer can be both here and in the
114 // active connections if were told about the peer after connecting with
115 // them. That encourages us to reconnect to peers that are well known in
117 peers prioritizedPeers
118 // Whether we want to know more peers.
119 wantPeersEvent missinggo.Event
120 // An announcer for each tracker URL.
121 trackerAnnouncers map[string]torrentTrackerAnnouncer
122 // How many times we've initiated a DHT announce. TODO: Move into stats.
125 // Name used if the info name isn't available. Should be cleared when the
126 // Info does become available.
130 // The bencoded bytes of the info dict. This is actively manipulated if
131 // the info bytes aren't initially available, and we try to fetch them
134 // Each element corresponds to the 16KiB metadata pieces. If true, we have
135 // received that piece.
136 metadataCompletedChunks []bool
137 metadataChanged sync.Cond
139 // Closed when .Info is obtained.
140 gotMetainfoC chan struct{}
142 readers map[*reader]struct{}
143 _readerNowPieces bitmap.Bitmap
144 _readerReadaheadPieces bitmap.Bitmap
146 // A cache of pieces we need to get. Calculated from various piece and
147 // file priorities and completion states elsewhere.
148 _pendingPieces roaring.Bitmap
149 // A cache of completed piece indices.
150 _completedPieces roaring.Bitmap
151 // Pieces that need to be hashed.
152 piecesQueuedForHash bitmap.Bitmap
153 activePieceHashes int
154 initialPieceCheckDisabled bool
156 connsWithAllPieces map[*Peer]struct{}
158 requestState map[RequestIndex]requestState
159 // Chunks we've written to since the corresponding piece was last checked.
160 dirtyChunks typedRoaring.Bitmap[RequestIndex]
164 // Is On when all pieces are complete.
165 Complete chansync.Flag
167 // Torrent sources in use keyed by the source string.
168 activeSources sync.Map
169 sourcesLogger log.Logger
171 smartBanCache smartBanCache
173 // Large allocations reused between request state updates.
174 requestPieceStates []request_strategy.PieceRequestOrderState
175 requestIndexes []RequestIndex
178 type outgoingConnAttemptKey = *PeerInfo
180 func (t *Torrent) length() int64 {
181 return t._length.Value
184 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
185 // This could be done with roaring.BitSliceIndexing.
186 t.iterPeers(func(peer *Peer) {
187 if _, ok := t.connsWithAllPieces[peer]; ok {
190 if peer.peerHasPiece(i) {
197 func (t *Torrent) decPieceAvailability(i pieceIndex) {
202 if p.relativeAvailability <= 0 {
203 panic(p.relativeAvailability)
205 p.relativeAvailability--
206 t.updatePieceRequestOrder(i)
209 func (t *Torrent) incPieceAvailability(i pieceIndex) {
210 // If we don't the info, this should be reconciled when we do.
213 p.relativeAvailability++
214 t.updatePieceRequestOrder(i)
218 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
219 return t._readerNowPieces
222 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
223 return t._readerReadaheadPieces
226 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
227 return !t.wantPieceIndex(i)
230 // Returns a channel that is closed when the Torrent is closed.
231 func (t *Torrent) Closed() events.Done {
232 return t.closed.Done()
235 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
236 // pending, and half-open peers.
237 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
238 // Add pending peers to the list
239 t.peers.Each(func(peer PeerInfo) {
240 ks = append(ks, peer)
243 // Add half-open peers to the list
244 for _, attempts := range t.halfOpen {
245 for _, peer := range attempts {
246 ks = append(ks, *peer)
250 // Add active peers to the list
251 for conn := range t.conns {
252 ks = append(ks, PeerInfo{
254 Addr: conn.RemoteAddr,
255 Source: conn.Discovery,
256 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
257 // > But if we're not connected to them with an encrypted connection, I couldn't say
258 // > what's appropriate. We can carry forward the SupportsEncryption value as we
259 // > received it from trackers/DHT/PEX, or just use the encryption state for the
260 // > connection. It's probably easiest to do the latter for now.
261 // https://github.com/anacrolix/torrent/pull/188
262 SupportsEncryption: conn.headerEncrypted,
269 func (t *Torrent) setChunkSize(size pp.Integer) {
271 t.chunkPool = sync.Pool{
272 New: func() interface{} {
273 b := make([]byte, size)
279 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
280 return t._completedPieces.Contains(bitmap.BitIndex(piece))
283 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
284 if t.storage == nil {
285 return storage.Completion{Complete: false, Ok: true}
287 return t.pieces[piece].Storage().Completion()
290 // There's a connection to that address already.
291 func (t *Torrent) addrActive(addr string) bool {
292 if _, ok := t.halfOpen[addr]; ok {
295 for c := range t.conns {
297 if ra.String() == addr {
304 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
305 return t.appendConns(ret, func(conn *PeerConn) bool {
306 return !conn.closed.IsSet()
310 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
311 for c := range t.conns {
319 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
321 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
322 if t.closed.IsSet() {
325 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
326 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
327 torrent.Add("peers not added because of bad addr", 1)
328 // cl.logger.Printf("peers not added because of bad addr: %v", p)
332 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
333 torrent.Add("peers replaced", 1)
334 if !replaced.equal(p) {
335 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
342 for t.peers.Len() > cl.config.TorrentPeersHighWater {
343 _, ok := t.peers.DeleteMin()
345 torrent.Add("excess reserve peers discarded", 1)
351 func (t *Torrent) invalidateMetadata() {
352 for i := 0; i < len(t.metadataCompletedChunks); i++ {
353 t.metadataCompletedChunks[i] = false
356 t.gotMetainfoC = make(chan struct{})
361 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
365 if index >= len(t.metadataCompletedChunks) {
366 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
369 copy(t.metadataBytes[(1<<14)*index:], data)
370 t.metadataCompletedChunks[index] = true
373 func (t *Torrent) metadataPieceCount() int {
374 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
377 func (t *Torrent) haveMetadataPiece(piece int) bool {
379 return (1<<14)*piece < len(t.metadataBytes)
381 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
385 func (t *Torrent) metadataSize() int {
386 return len(t.metadataBytes)
389 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
390 for i := 0; i < len(info.Pieces); i += sha1.Size {
391 ret = append(ret, info.Pieces[i:i+sha1.Size])
396 func (t *Torrent) makePieces() {
397 hashes := infoPieceHashes(t.info)
398 t.pieces = make([]Piece, len(hashes))
399 for i, hash := range hashes {
400 piece := &t.pieces[i]
402 piece.index = pieceIndex(i)
403 piece.noPendingWrites.L = &piece.pendingWritesMutex
404 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
406 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
407 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
408 piece.files = files[beginFile:endFile]
412 // Returns the index of the first file containing the piece. files must be
413 // ordered by offset.
414 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
415 for i, f := range files {
416 if f.offset+f.length > pieceOffset {
423 // Returns the index after the last file containing the piece. files must be
424 // ordered by offset.
425 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
426 for i, f := range files {
427 if f.offset+f.length >= pieceEndOffset {
434 func (t *Torrent) cacheLength() {
436 for _, f := range t.info.UpvertedFiles() {
442 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
444 func (t *Torrent) setInfo(info *metainfo.Info) error {
445 if err := validateInfo(info); err != nil {
446 return fmt.Errorf("bad info: %s", err)
448 if t.storageOpener != nil {
450 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
452 return fmt.Errorf("error opening torrent storage: %s", err)
458 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
460 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
461 t.displayName = "" // Save a few bytes lol.
468 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
469 return request_strategy.PieceRequestOrderKey{
470 InfoHash: t.infoHash,
475 // This seems to be all the follow-up tasks after info is set, that can't fail.
476 func (t *Torrent) onSetInfo() {
477 t.pieceRequestOrder = rand.Perm(t.numPieces())
478 t.initPieceRequestOrder()
479 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
480 for i := range t.pieces {
482 // Need to add relativeAvailability before updating piece completion, as that may result in conns
484 if p.relativeAvailability != 0 {
485 panic(p.relativeAvailability)
487 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
488 t.addRequestOrderPiece(i)
489 t.updatePieceCompletion(i)
490 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
491 // t.logger.Printf("piece %s completion unknown, queueing check", p)
495 t.cl.event.Broadcast()
496 close(t.gotMetainfoC)
497 t.updateWantPeersEvent()
498 t.requestState = make(map[RequestIndex]requestState)
499 t.tryCreateMorePieceHashers()
500 t.iterPeers(func(p *Peer) {
502 p.updateRequests("onSetInfo")
506 // Called when metadata for a torrent becomes available.
507 func (t *Torrent) setInfoBytesLocked(b []byte) error {
508 if metainfo.HashBytes(b) != t.infoHash {
509 return errors.New("info bytes have wrong hash")
511 var info metainfo.Info
512 if err := bencode.Unmarshal(b, &info); err != nil {
513 return fmt.Errorf("error unmarshalling info bytes: %s", err)
516 t.metadataCompletedChunks = nil
520 if err := t.setInfo(&info); err != nil {
527 func (t *Torrent) haveAllMetadataPieces() bool {
531 if t.metadataCompletedChunks == nil {
534 for _, have := range t.metadataCompletedChunks {
542 // TODO: Propagate errors to disconnect peer.
543 func (t *Torrent) setMetadataSize(size int) (err error) {
545 // We already know the correct metadata size.
548 if uint32(size) > maxMetadataSize {
549 return log.WithLevel(log.Warning, errors.New("bad size"))
551 if len(t.metadataBytes) == size {
554 t.metadataBytes = make([]byte, size)
555 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
556 t.metadataChanged.Broadcast()
557 for c := range t.conns {
558 c.requestPendingMetadata()
563 // The current working name for the torrent. Either the name in the info dict,
564 // or a display name given such as by the dn value in a magnet link, or "".
565 func (t *Torrent) name() string {
567 defer t.nameMu.RUnlock()
569 return t.info.BestName()
571 if t.displayName != "" {
574 return "infohash:" + t.infoHash.HexString()
577 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
578 p := &t.pieces[index]
579 ret.Priority = t.piecePriority(index)
580 ret.Completion = p.completion()
581 ret.QueuedForHash = p.queuedForHash()
582 ret.Hashing = p.hashing
583 ret.Checking = ret.QueuedForHash || ret.Hashing
584 ret.Marking = p.marking
585 if !ret.Complete && t.piecePartiallyDownloaded(index) {
591 func (t *Torrent) metadataPieceSize(piece int) int {
592 return metadataPieceSize(len(t.metadataBytes), piece)
595 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
598 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
599 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
601 TotalSize: len(t.metadataBytes),
607 type pieceAvailabilityRun struct {
612 func (me pieceAvailabilityRun) String() string {
613 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
616 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
617 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
618 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
620 for i := range t.pieces {
621 rle.Append(t.pieces[i].availability(), 1)
627 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
628 freqs = make([]int, t.numActivePeers()+1)
629 for i := range t.pieces {
630 freqs[t.piece(i).availability()]++
635 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
636 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
637 ret = append(ret, PieceStateRun{
638 PieceState: el.(PieceState),
642 for index := range t.pieces {
643 rle.Append(t.pieceState(pieceIndex(index)), 1)
649 // Produces a small string representing a PieceStateRun.
650 func (psr PieceStateRun) String() (ret string) {
651 ret = fmt.Sprintf("%d", psr.Length)
652 ret += func() string {
653 switch psr.Priority {
654 case PiecePriorityNext:
656 case PiecePriorityNormal:
658 case PiecePriorityReadahead:
660 case PiecePriorityNow:
662 case PiecePriorityHigh:
671 if psr.QueuedForHash {
689 func (t *Torrent) writeStatus(w io.Writer) {
690 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
691 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
693 fmt.Fprintf(w, "Metadata have: ")
694 for _, h := range t.metadataCompletedChunks {
695 fmt.Fprintf(w, "%c", func() rune {
705 fmt.Fprintf(w, "Piece length: %s\n",
708 return fmt.Sprintf("%v (%v chunks)",
710 float64(t.usualPieceSize())/float64(t.chunkSize))
717 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
718 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
719 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
720 // availability frequencies instead.
722 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
723 for _, run := range t.pieceAvailabilityRuns() {
724 ret = append(ret, run.String())
729 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
730 func() (ret []string) {
731 for avail, freq := range t.pieceAvailabilityFrequencies() {
735 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
741 fmt.Fprintf(w, "Reader Pieces:")
742 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
743 fmt.Fprintf(w, " %d:%d", begin, end)
748 fmt.Fprintf(w, "Enabled trackers:\n")
750 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
751 fmt.Fprintf(tw, " URL\tExtra\n")
752 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
755 var luns, runs url.URL = *lu, *ru
758 var ml missinggo.MultiLess
759 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
760 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
762 }).([]torrentTrackerAnnouncer) {
763 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
768 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
770 spew.NewDefaultConfig()
771 spew.Fdump(w, t.statsLocked())
773 fmt.Fprintf(w, "webseeds:\n")
774 t.writePeerStatuses(w, maps.Values(t.webSeeds))
776 peerConns := maps.Keys(t.conns)
777 // Peers without priorities first, then those with. I'm undecided about how to order peers
778 // without priorities.
779 sort.Slice(peerConns, func(li, ri int) bool {
782 ml := multiless.New()
783 lpp := g.ResultFromTuple(l.peerPriority()).ToOption()
784 rpp := g.ResultFromTuple(r.peerPriority()).ToOption()
785 ml = ml.Bool(lpp.Ok, rpp.Ok)
786 ml = ml.Uint32(rpp.Value, lpp.Value)
790 fmt.Fprintf(w, "peer conns:\n")
791 t.writePeerStatuses(w, g.SliceMap(peerConns, func(pc *PeerConn) *Peer {
796 func (t *Torrent) writePeerStatuses(w io.Writer, peers []*Peer) {
798 for _, c := range peers {
802 w.Write(bytes.TrimRight(
803 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
808 func (t *Torrent) haveInfo() bool {
812 // Returns a run-time generated MetaInfo that includes the info bytes and
813 // announce-list as currently known to the client.
814 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
815 return metainfo.MetaInfo{
816 CreationDate: time.Now().Unix(),
817 Comment: "dynamic metainfo from client",
818 CreatedBy: "go.torrent",
819 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
820 InfoBytes: func() []byte {
822 return t.metadataBytes
827 UrlList: func() []string {
828 ret := make([]string, 0, len(t.webSeeds))
829 for url := range t.webSeeds {
830 ret = append(ret, url)
838 func (t *Torrent) BytesMissing() (n int64) {
840 n = t.bytesMissingLocked()
845 func (t *Torrent) bytesMissingLocked() int64 {
849 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
850 roaring.Flip(b, 0, end).Iterate(cb)
853 func (t *Torrent) bytesLeft() (left int64) {
854 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
855 p := t.piece(pieceIndex(x))
856 left += int64(p.length() - p.numDirtyBytes())
862 // Bytes left to give in tracker announces.
863 func (t *Torrent) bytesLeftAnnounce() int64 {
871 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
872 if t.pieceComplete(piece) {
875 if t.pieceAllDirty(piece) {
878 return t.pieces[piece].hasDirtyChunks()
881 func (t *Torrent) usualPieceSize() int {
882 return int(t.info.PieceLength)
885 func (t *Torrent) numPieces() pieceIndex {
886 return t.info.NumPieces()
889 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
890 return pieceIndex(t._completedPieces.GetCardinality())
893 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
895 err = errors.New("already closed")
898 for _, f := range t.onClose {
901 if t.storage != nil {
906 defer t.storageLock.Unlock()
907 if f := t.storage.Close; f != nil {
910 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
915 t.iterPeers(func(p *Peer) {
918 if t.storage != nil {
919 t.deletePieceRequestOrder()
921 t.assertAllPiecesRelativeAvailabilityZero()
923 t.cl.event.Broadcast()
924 t.pieceStateChanges.Close()
925 t.updateWantPeersEvent()
929 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
930 for i := range t.pieces {
932 if p.relativeAvailability != 0 {
933 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
938 func (t *Torrent) requestOffset(r Request) int64 {
939 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
942 // Return the request that would include the given offset into the torrent data. Returns !ok if
943 // there is no such request.
944 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
945 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
948 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
949 defer perf.ScopeTimerErr(&err)()
950 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
951 if err == nil && n != len(data) {
952 err = io.ErrShortWrite
957 func (t *Torrent) bitfield() (bf []bool) {
958 bf = make([]bool, t.numPieces())
959 t._completedPieces.Iterate(func(piece uint32) (again bool) {
966 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
967 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
970 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
971 return t._chunksPerRegularPiece
974 func (t *Torrent) numChunks() RequestIndex {
975 if t.numPieces() == 0 {
978 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
981 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
982 t.dirtyChunks.RemoveRange(
983 uint64(t.pieceRequestIndexOffset(pieceIndex)),
984 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
987 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
988 if t.info.PieceLength == 0 {
989 // There will be no variance amongst pieces. Only pain.
992 if piece == t.numPieces()-1 {
993 ret := pp.Integer(t.length() % t.info.PieceLength)
998 return pp.Integer(t.info.PieceLength)
1001 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
1002 return &blockCheckingWriter{
1003 cache: &t.smartBanCache,
1004 requestIndex: t.pieceRequestIndexOffset(piece),
1005 chunkSize: t.chunkSize.Int(),
1009 func (t *Torrent) hashPiece(piece pieceIndex) (
1011 // These are peers that sent us blocks that differ from what we hash here.
1012 differingPeers map[bannableAddr]struct{},
1016 p.waitNoPendingWrites()
1017 storagePiece := t.pieces[piece].Storage()
1019 // Does the backend want to do its own hashing?
1020 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
1021 var sum metainfo.Hash
1022 // log.Printf("A piece decided to self-hash: %d", piece)
1023 sum, err = i.SelfHash()
1024 missinggo.CopyExact(&ret, sum)
1028 hash := pieceHash.New()
1029 const logPieceContents = false
1030 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1031 writers := []io.Writer{hash, smartBanWriter}
1032 var examineBuf bytes.Buffer
1033 if logPieceContents {
1034 writers = append(writers, &examineBuf)
1036 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1037 if logPieceContents {
1038 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1040 smartBanWriter.Flush()
1041 differingPeers = smartBanWriter.badPeers
1042 missinggo.CopyExact(&ret, hash.Sum(nil))
1046 func (t *Torrent) haveAnyPieces() bool {
1047 return !t._completedPieces.IsEmpty()
1050 func (t *Torrent) haveAllPieces() bool {
1054 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1057 func (t *Torrent) havePiece(index pieceIndex) bool {
1058 return t.haveInfo() && t.pieceComplete(index)
1061 func (t *Torrent) maybeDropMutuallyCompletePeer(
1062 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1066 if !t.cl.config.DropMutuallyCompletePeers {
1069 if !t.haveAllPieces() {
1072 if all, known := p.peerHasAllPieces(); !(known && all) {
1078 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1082 func (t *Torrent) haveChunk(r Request) (ret bool) {
1084 // log.Println("have chunk", r, ret)
1089 if t.pieceComplete(pieceIndex(r.Index)) {
1092 p := &t.pieces[r.Index]
1093 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1096 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1097 return chunkIndexType(cs.Begin / chunkSize)
1100 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1101 return t._pendingPieces.Contains(uint32(index))
1104 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1105 // conns (which is a map).
1106 var peerConnSlices sync.Pool
1108 func getPeerConnSlice(cap int) []*PeerConn {
1109 getInterface := peerConnSlices.Get()
1110 if getInterface == nil {
1111 return make([]*PeerConn, 0, cap)
1113 return getInterface.([]*PeerConn)[:0]
1117 // Calls the given function with a slice of unclosed conns. It uses a pool to reduce allocations as
1118 // this is a frequent occurrence.
1119 func (t *Torrent) withUnclosedConns(f func([]*PeerConn)) {
1120 sl := t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))
1122 peerConnSlices.Put(sl)
1125 func (t *Torrent) worstBadConnFromSlice(opts worseConnLensOpts, sl []*PeerConn) *PeerConn {
1126 wcs := worseConnSlice{conns: sl}
1129 for wcs.Len() != 0 {
1130 c := heap.Pop(&wcs).(*PeerConn)
1131 if opts.incomingIsBad && !c.outgoing {
1134 if opts.outgoingIsBad && c.outgoing {
1137 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1140 // If the connection is in the worst half of the established
1141 // connection quota and is older than a minute.
1142 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1143 // Give connections 1 minute to prove themselves.
1144 if time.Since(c.completedHandshake) > time.Minute {
1152 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1153 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1154 // established connections for more than a minute. This is O(n log n). If there was a way to not
1155 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1156 func (t *Torrent) worstBadConn(opts worseConnLensOpts) (ret *PeerConn) {
1157 t.withUnclosedConns(func(ucs []*PeerConn) {
1158 ret = t.worstBadConnFromSlice(opts, ucs)
1163 type PieceStateChange struct {
1168 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1169 t.cl._mu.Defer(func() {
1170 cur := t.pieceState(piece)
1171 p := &t.pieces[piece]
1172 if cur != p.publicPieceState {
1173 p.publicPieceState = cur
1174 t.pieceStateChanges.Publish(PieceStateChange{
1182 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1183 if t.pieceComplete(piece) {
1186 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1189 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1190 return t.pieces[piece].allChunksDirty()
1193 func (t *Torrent) readersChanged() {
1194 t.updateReaderPieces()
1195 t.updateAllPiecePriorities("Torrent.readersChanged")
1198 func (t *Torrent) updateReaderPieces() {
1199 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1202 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1206 t.updateReaderPieces()
1207 // Order the ranges, high and low.
1209 if l.begin > h.begin {
1212 if l.end < h.begin {
1213 // Two distinct ranges.
1214 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1215 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1222 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1226 func (t *Torrent) maybeNewConns() {
1227 // Tickle the accept routine.
1228 t.cl.event.Broadcast()
1232 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1233 if t._pendingPieces.Contains(uint32(piece)) {
1234 t.iterPeers(func(c *Peer) {
1235 // if c.requestState.Interested {
1238 if !c.isLowOnRequests() {
1241 if !c.peerHasPiece(piece) {
1244 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1247 c.updateRequests(reason)
1251 t.publishPieceChange(piece)
1254 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1255 if !t.closed.IsSet() {
1256 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1258 t.updatePieceRequestOrder(piece)
1260 p := &t.pieces[piece]
1261 newPrio := p.uncachedPriority()
1262 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1263 if newPrio == PiecePriorityNone {
1264 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1268 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1272 t.piecePriorityChanged(piece, reason)
1275 func (t *Torrent) updateAllPiecePriorities(reason string) {
1276 t.updatePiecePriorities(0, t.numPieces(), reason)
1279 // Update all piece priorities in one hit. This function should have the same
1280 // output as updatePiecePriority, but across all pieces.
1281 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1282 for i := begin; i < end; i++ {
1283 t.updatePiecePriority(i, reason)
1287 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1288 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1289 if off >= t.length() {
1299 begin = pieceIndex(off / t.info.PieceLength)
1300 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1301 if end > pieceIndex(t.info.NumPieces()) {
1302 end = pieceIndex(t.info.NumPieces())
1307 // Returns true if all iterations complete without breaking. Returns the read regions for all
1308 // readers. The reader regions should not be merged as some callers depend on this method to
1309 // enumerate readers.
1310 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1311 for r := range t.readers {
1313 if p.begin >= p.end {
1316 if !f(p.begin, p.end) {
1323 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1324 return t.piece(piece).uncachedPriority()
1327 func (t *Torrent) pendRequest(req RequestIndex) {
1328 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1331 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1332 t.cl.event.Broadcast()
1333 if t.pieceComplete(piece) {
1334 t.onPieceCompleted(piece)
1336 t.onIncompletePiece(piece)
1338 t.updatePiecePriority(piece, reason)
1341 func (t *Torrent) numReceivedConns() (ret int) {
1342 for c := range t.conns {
1343 if c.Discovery == PeerSourceIncoming {
1350 func (t *Torrent) numOutgoingConns() (ret int) {
1351 for c := range t.conns {
1359 func (t *Torrent) maxHalfOpen() int {
1360 // Note that if we somehow exceed the maximum established conns, we want
1361 // the negative value to have an effect.
1362 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1363 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1364 // We want to allow some experimentation with new peers, and to try to
1365 // upset an oversupply of received connections.
1367 max(5, extraIncoming)+establishedHeadroom,
1368 int64(t.cl.config.HalfOpenConnsPerTorrent),
1372 func (t *Torrent) openNewConns() (initiated int) {
1373 defer t.updateWantPeersEvent()
1374 for t.peers.Len() != 0 {
1375 if !t.wantOutgoingConns() {
1378 if len(t.halfOpen) >= t.maxHalfOpen() {
1381 if len(t.cl.dialers) == 0 {
1384 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1387 p := t.peers.PopMax()
1388 t.initiateConn(p, false, false, false)
1394 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1396 uncached := t.pieceCompleteUncached(piece)
1397 cached := p.completion()
1398 changed := cached != uncached
1399 complete := uncached.Complete
1400 p.storageCompletionOk = uncached.Ok
1403 t._completedPieces.Add(x)
1406 t._completedPieces.Remove(x)
1408 p.t.updatePieceRequestOrder(piece)
1410 if complete && len(p.dirtiers) != 0 {
1411 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1414 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1415 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1420 // Non-blocking read. Client lock is not required.
1421 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1423 p := &t.pieces[off/t.info.PieceLength]
1424 p.waitNoPendingWrites()
1426 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1437 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1438 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1439 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1440 func (t *Torrent) maybeCompleteMetadata() error {
1445 if !t.haveAllMetadataPieces() {
1446 // Don't have enough metadata pieces.
1449 err := t.setInfoBytesLocked(t.metadataBytes)
1451 t.invalidateMetadata()
1452 return fmt.Errorf("error setting info bytes: %s", err)
1454 if t.cl.config.Debug {
1455 t.logger.Printf("%s: got metadata from peers", t)
1460 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1461 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1463 now.Add(bitmap.BitIndex(begin))
1464 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1471 func (t *Torrent) needData() bool {
1472 if t.closed.IsSet() {
1478 return !t._pendingPieces.IsEmpty()
1481 func appendMissingStrings(old, new []string) (ret []string) {
1484 for _, n := range new {
1485 for _, o := range old {
1490 ret = append(ret, n)
1495 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1497 for minNumTiers > len(ret) {
1498 ret = append(ret, nil)
1503 func (t *Torrent) addTrackers(announceList [][]string) {
1504 fullAnnounceList := &t.metainfo.AnnounceList
1505 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1506 for tierIndex, trackerURLs := range announceList {
1507 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1509 t.startMissingTrackerScrapers()
1510 t.updateWantPeersEvent()
1513 // Don't call this before the info is available.
1514 func (t *Torrent) bytesCompleted() int64 {
1518 return t.length() - t.bytesLeft()
1521 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1524 return t.setInfoBytesLocked(b)
1527 // Returns true if connection is removed from torrent.Conns.
1528 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1529 if !c.closed.IsSet() {
1530 panic("connection is not closed")
1531 // There are behaviours prevented by the closed state that will fail
1532 // if the connection has been deleted.
1536 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1537 // the drop event against the PexConnState instead.
1539 if !t.cl.config.DisablePEX {
1543 torrent.Add("deleted connections", 1)
1544 c.deleteAllRequests("Torrent.deletePeerConn")
1545 t.assertPendingRequests()
1546 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1547 panic(t.connsWithAllPieces)
1552 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1553 if t.deleteConnWithAllPieces(p) {
1559 p.peerPieces().Iterate(func(i uint32) bool {
1560 p.t.decPieceAvailability(pieceIndex(i))
1565 func (t *Torrent) assertPendingRequests() {
1569 // var actual pendingRequests
1570 // if t.haveInfo() {
1571 // actual.m = make([]int, t.numChunks())
1573 // t.iterPeers(func(p *Peer) {
1574 // p.requestState.Requests.Iterate(func(x uint32) bool {
1579 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1585 func (t *Torrent) dropConnection(c *PeerConn) {
1586 t.cl.event.Broadcast()
1588 if t.deletePeerConn(c) {
1593 // Peers as in contact information for dialing out.
1594 func (t *Torrent) wantPeers() bool {
1595 if t.closed.IsSet() {
1598 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1601 return t.wantOutgoingConns()
1604 func (t *Torrent) updateWantPeersEvent() {
1606 t.wantPeersEvent.Set()
1608 t.wantPeersEvent.Clear()
1612 // Returns whether the client should make effort to seed the torrent.
1613 func (t *Torrent) seeding() bool {
1615 if t.closed.IsSet() {
1618 if t.dataUploadDisallowed {
1621 if cl.config.NoUpload {
1624 if !cl.config.Seed {
1627 if cl.config.DisableAggressiveUpload && t.needData() {
1633 func (t *Torrent) onWebRtcConn(
1634 c datachannel.ReadWriteCloser,
1635 dcc webtorrent.DataChannelContext,
1638 netConn := webrtcNetConn{
1640 DataChannelContext: dcc,
1642 peerRemoteAddr := netConn.RemoteAddr()
1643 //t.logger.Levelf(log.Critical, "onWebRtcConn remote addr: %v", peerRemoteAddr)
1644 if t.cl.badPeerAddr(peerRemoteAddr) {
1647 localAddrIpPort := missinggo.IpPortFromNetAddr(netConn.LocalAddr())
1648 pc, err := t.cl.initiateProtocolHandshakes(
1649 context.Background(),
1654 outgoing: dcc.LocalOffered,
1655 remoteAddr: peerRemoteAddr,
1656 localPublicAddr: localAddrIpPort,
1657 network: webrtcNetwork,
1658 connString: fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1662 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1665 if dcc.LocalOffered {
1666 pc.Discovery = PeerSourceTracker
1668 pc.Discovery = PeerSourceIncoming
1670 pc.conn.SetWriteDeadline(time.Time{})
1673 err = t.cl.runHandshookConn(pc, t)
1675 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1679 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1680 err := t.cl.runHandshookConn(pc, t)
1681 if err != nil || logAll {
1682 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1686 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1687 t.logRunHandshookConn(pc, false, log.Debug)
1690 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1691 wtc, release := t.cl.websocketTrackers.Get(u.String(), t.infoHash)
1692 // This needs to run before the Torrent is dropped from the Client, to prevent a new webtorrent.TrackerClient for
1693 // the same info hash before the old one is cleaned up.
1694 t.onClose = append(t.onClose, release)
1695 wst := websocketTrackerStatus{u, wtc}
1697 err := wtc.Announce(tracker.Started, t.infoHash)
1699 t.logger.WithDefaultLevel(log.Warning).Printf(
1700 "error in initial announce to %q: %v",
1708 func (t *Torrent) startScrapingTracker(_url string) {
1712 u, err := url.Parse(_url)
1714 // URLs with a leading '*' appear to be a uTorrent convention to
1715 // disable trackers.
1717 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1721 if u.Scheme == "udp" {
1723 t.startScrapingTracker(u.String())
1725 t.startScrapingTracker(u.String())
1728 if _, ok := t.trackerAnnouncers[_url]; ok {
1731 sl := func() torrentTrackerAnnouncer {
1734 if t.cl.config.DisableWebtorrent {
1737 return t.startWebsocketAnnouncer(*u)
1739 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1743 if t.cl.config.DisableIPv6 {
1747 newAnnouncer := &trackerScraper{
1750 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1752 go newAnnouncer.Run()
1758 if t.trackerAnnouncers == nil {
1759 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1761 t.trackerAnnouncers[_url] = sl
1764 // Adds and starts tracker scrapers for tracker URLs that aren't already
1766 func (t *Torrent) startMissingTrackerScrapers() {
1767 if t.cl.config.DisableTrackers {
1770 t.startScrapingTracker(t.metainfo.Announce)
1771 for _, tier := range t.metainfo.AnnounceList {
1772 for _, url := range tier {
1773 t.startScrapingTracker(url)
1778 // Returns an AnnounceRequest with fields filled out to defaults and current
1780 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1781 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1782 // dependent on the network in use.
1783 return tracker.AnnounceRequest{
1785 NumWant: func() int32 {
1786 if t.wantPeers() && len(t.cl.dialers) > 0 {
1787 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1792 Port: uint16(t.cl.incomingPeerPort()),
1793 PeerId: t.cl.peerID,
1794 InfoHash: t.infoHash,
1795 Key: t.cl.announceKey(),
1797 // The following are vaguely described in BEP 3.
1799 Left: t.bytesLeftAnnounce(),
1800 Uploaded: t.stats.BytesWrittenData.Int64(),
1801 // There's no mention of wasted or unwanted download in the BEP.
1802 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1806 // Adds peers revealed in an announce until the announce ends, or we have
1808 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1810 for v := range pvs {
1813 for _, cp := range v.Peers {
1815 // Can't do anything with this.
1818 if t.addPeer(PeerInfo{
1819 Addr: ipPortAddr{cp.IP, cp.Port},
1820 Source: PeerSourceDhtGetPeers,
1827 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1832 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1833 // announce ends. stop will force the announce to end.
1834 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1835 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1839 _done := make(chan struct{})
1843 t.consumeDhtAnnouncePeers(ps.Peers())
1849 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1850 _, stop, err := t.AnnounceToDht(s)
1855 case <-t.closed.Done():
1856 case <-time.After(5 * time.Minute):
1862 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1868 if t.closed.IsSet() {
1871 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1872 // TODO: We can include the announce_peer step depending on whether we can receive
1873 // inbound connections. We should probably only announce once every 15 mins too.
1874 if !t.wantAnyConns() {
1877 // TODO: Determine if there's a listener on the port we're announcing.
1878 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1889 err := t.timeboxedAnnounceToDht(s)
1891 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1897 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1898 for _, p := range peers {
1906 // The returned TorrentStats may require alignment in memory. See
1907 // https://github.com/anacrolix/torrent/issues/383.
1908 func (t *Torrent) Stats() TorrentStats {
1910 defer t.cl.rUnlock()
1911 return t.statsLocked()
1914 func (t *Torrent) statsLocked() (ret TorrentStats) {
1915 ret.ActivePeers = len(t.conns)
1916 ret.HalfOpenPeers = len(t.halfOpen)
1917 ret.PendingPeers = t.peers.Len()
1918 ret.TotalPeers = t.numTotalPeers()
1919 ret.ConnectedSeeders = 0
1920 for c := range t.conns {
1921 if all, ok := c.peerHasAllPieces(); all && ok {
1922 ret.ConnectedSeeders++
1925 ret.ConnStats = t.stats.Copy()
1926 ret.PiecesComplete = t.numPiecesCompleted()
1930 // The total number of peers in the torrent.
1931 func (t *Torrent) numTotalPeers() int {
1932 peers := make(map[string]struct{})
1933 for conn := range t.conns {
1934 ra := conn.conn.RemoteAddr()
1936 // It's been closed and doesn't support RemoteAddr.
1939 peers[ra.String()] = struct{}{}
1941 for addr := range t.halfOpen {
1942 peers[addr] = struct{}{}
1944 t.peers.Each(func(peer PeerInfo) {
1945 peers[peer.Addr.String()] = struct{}{}
1950 // Reconcile bytes transferred before connection was associated with a
1952 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1953 if c._stats != (ConnStats{
1954 // Handshakes should only increment these fields:
1955 BytesWritten: c._stats.BytesWritten,
1956 BytesRead: c._stats.BytesRead,
1960 c.postHandshakeStats(func(cs *ConnStats) {
1961 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1962 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1964 c.reconciledHandshakeStats = true
1967 // Returns true if the connection is added.
1968 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1971 torrent.Add("added connections", 1)
1974 if t.closed.IsSet() {
1975 return errors.New("torrent closed")
1977 for c0 := range t.conns {
1978 if c.PeerID != c0.PeerID {
1981 if !t.cl.config.DropDuplicatePeerIds {
1984 if c.hasPreferredNetworkOver(c0) {
1986 t.deletePeerConn(c0)
1988 return errors.New("existing connection preferred")
1991 if len(t.conns) >= t.maxEstablishedConns {
1992 numOutgoing := t.numOutgoingConns()
1993 numIncoming := len(t.conns) - numOutgoing
1994 c := t.worstBadConn(worseConnLensOpts{
1995 // We've already established that we have too many connections at this point, so we just
1996 // need to match what kind we have too many of vs. what we're trying to add now.
1997 incomingIsBad: (numIncoming-numOutgoing > 1) && c.outgoing,
1998 outgoingIsBad: (numOutgoing-numIncoming > 1) && !c.outgoing,
2001 return errors.New("don't want conn")
2006 if len(t.conns) >= t.maxEstablishedConns {
2009 t.conns[c] = struct{}{}
2010 t.cl.event.Broadcast()
2011 // We'll never receive the "p" extended handshake parameter.
2012 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
2018 func (t *Torrent) newConnsAllowed() bool {
2019 if !t.networkingEnabled.Bool() {
2022 if t.closed.IsSet() {
2025 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2031 func (t *Torrent) wantAnyConns() bool {
2032 if !t.networkingEnabled.Bool() {
2035 if t.closed.IsSet() {
2038 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2041 return len(t.conns) < t.maxEstablishedConns
2044 func (t *Torrent) wantOutgoingConns() bool {
2045 if !t.newConnsAllowed() {
2048 if len(t.conns) < t.maxEstablishedConns {
2051 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2052 return t.worstBadConn(worseConnLensOpts{
2053 incomingIsBad: numIncomingConns-t.numOutgoingConns() > 1,
2054 outgoingIsBad: false,
2058 func (t *Torrent) wantIncomingConns() bool {
2059 if !t.newConnsAllowed() {
2062 if len(t.conns) < t.maxEstablishedConns {
2065 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2066 return t.worstBadConn(worseConnLensOpts{
2067 incomingIsBad: false,
2068 outgoingIsBad: t.numOutgoingConns()-numIncomingConns > 1,
2072 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
2075 oldMax = t.maxEstablishedConns
2076 t.maxEstablishedConns = max
2077 wcs := worseConnSlice{
2078 conns: t.appendConns(nil, func(*PeerConn) bool {
2082 wcs.initKeys(worseConnLensOpts{})
2084 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
2085 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
2091 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
2092 t.logger.LazyLog(log.Debug, func() log.Msg {
2093 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
2097 t.cl.event.Broadcast()
2098 if t.closed.IsSet() {
2102 // Don't score the first time a piece is hashed, it could be an initial check.
2103 if p.storageCompletionOk {
2105 pieceHashedCorrect.Add(1)
2108 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
2109 ).AddValues(t, p).LogLevel(
2111 log.Debug, t.logger)
2113 pieceHashedNotCorrect.Add(1)
2118 t.publishPieceChange(piece)
2121 t.publishPieceChange(piece)
2125 if len(p.dirtiers) != 0 {
2126 // Don't increment stats above connection-level for every involved connection.
2127 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2129 for c := range p.dirtiers {
2130 c._stats.incrementPiecesDirtiedGood()
2132 t.clearPieceTouchers(piece)
2133 hasDirty := p.hasDirtyChunks()
2136 p.Flush() // You can be synchronous here!
2138 err := p.Storage().MarkComplete()
2140 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2144 if t.closed.IsSet() {
2147 t.pendAllChunkSpecs(piece)
2149 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2150 // Peers contributed to all the data for this piece hash failure, and the failure was
2151 // not due to errors in the storage (such as data being dropped in a cache).
2153 // Increment Torrent and above stats, and then specific connections.
2154 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2155 for c := range p.dirtiers {
2156 // Y u do dis peer?!
2157 c.stats().incrementPiecesDirtiedBad()
2160 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2161 for c := range p.dirtiers {
2163 bannableTouchers = append(bannableTouchers, c)
2166 t.clearPieceTouchers(piece)
2167 slices.Sort(bannableTouchers, connLessTrusted)
2169 if t.cl.config.Debug {
2171 "bannable conns by trust for piece %d: %v",
2173 func() (ret []connectionTrust) {
2174 for _, c := range bannableTouchers {
2175 ret = append(ret, c.trust())
2182 if len(bannableTouchers) >= 1 {
2183 c := bannableTouchers[0]
2184 if len(bannableTouchers) != 1 {
2185 t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2187 // Turns out it's still useful to ban peers like this because if there's only a
2188 // single peer for a piece, and we never progress that piece to completion, we
2189 // will never smart-ban them. Discovered in
2190 // https://github.com/anacrolix/torrent/issues/715.
2191 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2196 t.onIncompletePiece(piece)
2197 p.Storage().MarkNotComplete()
2199 t.updatePieceCompletion(piece)
2202 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2203 start := t.pieceRequestIndexOffset(piece)
2204 end := start + t.pieceNumChunks(piece)
2205 for ri := start; ri < end; ri++ {
2210 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2211 t.pendAllChunkSpecs(piece)
2212 t.cancelRequestsForPiece(piece)
2213 t.piece(piece).readerCond.Broadcast()
2214 for conn := range t.conns {
2216 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2220 // Called when a piece is found to be not complete.
2221 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2222 if t.pieceAllDirty(piece) {
2223 t.pendAllChunkSpecs(piece)
2225 if !t.wantPieceIndex(piece) {
2226 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2229 // We could drop any connections that we told we have a piece that we
2230 // don't here. But there's a test failure, and it seems clients don't care
2231 // if you request pieces that you already claim to have. Pruning bad
2232 // connections might just remove any connections that aren't treating us
2233 // favourably anyway.
2235 // for c := range t.conns {
2236 // if c.sentHave(piece) {
2240 t.iterPeers(func(conn *Peer) {
2241 if conn.peerHasPiece(piece) {
2242 conn.updateRequests("piece incomplete")
2247 func (t *Torrent) tryCreateMorePieceHashers() {
2248 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2252 func (t *Torrent) tryCreatePieceHasher() bool {
2253 if t.storage == nil {
2256 pi, ok := t.getPieceToHash()
2261 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2263 t.publishPieceChange(pi)
2264 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2265 t.storageLock.RLock()
2266 t.activePieceHashes++
2267 go t.pieceHasher(pi)
2271 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2272 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2273 if t.piece(i).hashing {
2283 func (t *Torrent) dropBannedPeers() {
2284 t.iterPeers(func(p *Peer) {
2285 remoteIp := p.remoteIp()
2286 if remoteIp == nil {
2287 if p.bannableAddr.Ok {
2288 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2292 netipAddr := netip.MustParseAddr(remoteIp.String())
2293 if Some(netipAddr) != p.bannableAddr {
2294 t.logger.WithDefaultLevel(log.Debug).Printf(
2295 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2296 p, remoteIp, p.bannableAddr)
2298 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2299 // Should this be a close?
2301 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2306 func (t *Torrent) pieceHasher(index pieceIndex) {
2308 sum, failedPeers, copyErr := t.hashPiece(index)
2309 correct := sum == *p.hash
2313 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2315 t.storageLock.RUnlock()
2319 for peer := range failedPeers {
2320 t.cl.banPeerIP(peer.AsSlice())
2321 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2324 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2325 t.smartBanCache.ForgetBlock(ri)
2329 t.pieceHashed(index, correct, copyErr)
2330 t.updatePiecePriority(index, "Torrent.pieceHasher")
2331 t.activePieceHashes--
2332 t.tryCreateMorePieceHashers()
2335 // Return the connections that touched a piece, and clear the entries while doing it.
2336 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2338 for c := range p.dirtiers {
2339 delete(c.peerTouchedPieces, pi)
2340 delete(p.dirtiers, c)
2344 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2345 t.iterPeers(func(p *Peer) {
2346 ret = append(ret, p)
2351 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2352 piece := t.piece(pieceIndex)
2353 if piece.queuedForHash() {
2356 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2357 t.publishPieceChange(pieceIndex)
2358 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2359 t.tryCreateMorePieceHashers()
2362 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2363 // before the Info is available.
2364 func (t *Torrent) VerifyData() {
2365 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2366 t.Piece(i).VerifyData()
2370 func (t *Torrent) connectingToPeerAddr(addrStr string) bool {
2371 return len(t.halfOpen[addrStr]) != 0
2374 func (t *Torrent) hasPeerConnForAddr(x PeerRemoteAddr) bool {
2375 addrStr := x.String()
2376 for c := range t.conns {
2378 if ra.String() == addrStr {
2385 func (t *Torrent) getHalfOpenPath(
2387 attemptKey outgoingConnAttemptKey,
2388 ) nestedmaps.Path[*PeerInfo] {
2389 return nestedmaps.Next(nestedmaps.Next(nestedmaps.Begin(&t.halfOpen), addrStr), attemptKey)
2392 func (t *Torrent) addHalfOpen(addrStr string, attemptKey *PeerInfo) {
2393 path := t.getHalfOpenPath(addrStr, attemptKey)
2395 panic("should be unique")
2397 path.Set(attemptKey)
2401 // Start the process of connecting to the given peer for the given torrent if appropriate. I'm not
2402 // sure all the PeerInfo fields are being used.
2403 func (t *Torrent) initiateConn(
2405 requireRendezvous bool,
2406 skipHolepunchRendezvous bool,
2409 if peer.Id == t.cl.peerID {
2412 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2416 addrStr := addr.String()
2418 if t.connectingToPeerAddr(addrStr) {
2422 if t.hasPeerConnForAddr(addr) {
2426 t.addHalfOpen(addrStr, attemptKey)
2427 go t.cl.outgoingConnection(
2431 requireRendezvous: requireRendezvous,
2432 skipHolepunchRendezvous: skipHolepunchRendezvous,
2440 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2441 // quickly make one Client visible to the Torrent of another Client.
2442 func (t *Torrent) AddClientPeer(cl *Client) int {
2443 return t.AddPeers(func() (ps []PeerInfo) {
2444 for _, la := range cl.ListenAddrs() {
2445 ps = append(ps, PeerInfo{
2454 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2456 func (t *Torrent) allStats(f func(*ConnStats)) {
2461 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2462 return t.pieces[i].hashing
2465 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2466 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2469 func (t *Torrent) dialTimeout() time.Duration {
2470 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2473 func (t *Torrent) piece(i int) *Piece {
2477 func (t *Torrent) onWriteChunkErr(err error) {
2478 if t.userOnWriteChunkErr != nil {
2479 go t.userOnWriteChunkErr(err)
2482 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2483 t.disallowDataDownloadLocked()
2486 func (t *Torrent) DisallowDataDownload() {
2487 t.disallowDataDownloadLocked()
2490 func (t *Torrent) disallowDataDownloadLocked() {
2491 t.dataDownloadDisallowed.Set()
2494 func (t *Torrent) AllowDataDownload() {
2495 t.dataDownloadDisallowed.Clear()
2498 // Enables uploading data, if it was disabled.
2499 func (t *Torrent) AllowDataUpload() {
2502 t.dataUploadDisallowed = false
2503 for c := range t.conns {
2504 c.updateRequests("allow data upload")
2508 // Disables uploading data, if it was enabled.
2509 func (t *Torrent) DisallowDataUpload() {
2512 t.dataUploadDisallowed = true
2513 for c := range t.conns {
2514 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2515 c.updateRequests("disallow data upload")
2519 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2520 // or if nil, a critical message is logged, and data download is disabled.
2521 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2524 t.userOnWriteChunkErr = f
2527 func (t *Torrent) iterPeers(f func(p *Peer)) {
2528 for pc := range t.conns {
2531 for _, ws := range t.webSeeds {
2536 func (t *Torrent) callbacks() *Callbacks {
2537 return &t.cl.config.Callbacks
2540 type AddWebSeedsOpt func(*webseed.Client)
2542 // Sets the WebSeed trailing path escaper for a webseed.Client.
2543 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2544 return func(c *webseed.Client) {
2545 c.PathEscaper = custom
2549 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2552 for _, u := range urls {
2553 t.addWebSeed(u, opts...)
2557 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2558 if t.cl.config.DisableWebseeds {
2561 if _, ok := t.webSeeds[url]; ok {
2564 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2565 // right away. This value should be some multiple of the number of connections to a host. I
2566 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2567 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2568 // "https://webtorrent.io/torrents/".
2569 const maxRequests = 16
2575 reconciledHandshakeStats: true,
2576 // This should affect how often we have to recompute requests for this peer. Note that
2577 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2578 // requests mark more often, so recomputation is probably sooner than with regular peer
2579 // conns. ~4x maxRequests would be about right.
2580 PeerMaxRequests: 128,
2581 // TODO: Set ban prefix?
2582 RemoteAddr: remoteAddrFromUrl(url),
2583 callbacks: t.callbacks(),
2585 client: webseed.Client{
2586 HttpClient: t.cl.httpClient,
2588 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2589 return &rateLimitedReader{
2590 l: t.cl.config.DownloadRateLimiter,
2595 activeRequests: make(map[Request]webseed.Request, maxRequests),
2597 ws.peer.initRequestState()
2598 for _, opt := range opts {
2601 ws.peer.initUpdateRequestsTimer()
2602 ws.requesterCond.L = t.cl.locker()
2603 for i := 0; i < maxRequests; i += 1 {
2606 for _, f := range t.callbacks().NewPeer {
2609 ws.peer.logger = t.logger.WithContextValue(&ws)
2610 ws.peer.peerImpl = &ws
2612 ws.onGotInfo(t.info)
2614 t.webSeeds[url] = &ws.peer
2617 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2618 t.iterPeers(func(p1 *Peer) {
2626 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2627 index := t.pieceIndexOfRequestIndex(ri)
2630 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2634 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2635 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2638 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2639 return RequestIndex(piece) * t.chunksPerRegularPiece()
2642 func (t *Torrent) updateComplete() {
2643 t.Complete.SetBool(t.haveAllPieces())
2646 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2647 p := t.requestingPeer(r)
2651 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2652 //delete(t.pendingRequests, r)
2653 if _, ok := t.requestState[r]; ok {
2654 panic("expected request state to be gone")
2659 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2660 return t.requestState[r].peer
2663 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2664 if t.connsWithAllPieces == nil {
2665 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2667 t.connsWithAllPieces[p] = struct{}{}
2670 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2671 _, ok := t.connsWithAllPieces[p]
2672 delete(t.connsWithAllPieces, p)
2676 func (t *Torrent) numActivePeers() int {
2677 return len(t.conns) + len(t.webSeeds)
2680 func (t *Torrent) hasStorageCap() bool {
2681 f := t.storage.Capacity
2689 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2690 return pieceIndex(ri / t.chunksPerRegularPiece())
2693 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2694 reuseIter *typedRoaring.Iterator[RequestIndex],
2696 f func(RequestIndex),
2698 reuseIter.Initialize(&t.dirtyChunks)
2699 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2700 iterBitmapUnsetInRange(
2702 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2707 type requestState struct {
2712 // Returns an error if a received chunk is out of bounds in someway.
2713 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2715 return errors.New("torrent missing info")
2717 if int(r.Index) >= t.numPieces() {
2718 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2720 pieceLength := t.pieceLength(pieceIndex(r.Index))
2721 if r.Begin >= pieceLength {
2722 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2724 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2725 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2726 // should be considerable checks elsewhere for this case due to the network overhead. We should
2727 // catch most of the overflow manipulation stuff by checking index and begin above.
2731 func (t *Torrent) peerConnsWithDialAddrPort(target netip.AddrPort) (ret []*PeerConn) {
2732 for pc := range t.conns {
2733 dialAddr, err := pc.remoteDialAddrPort()
2737 if dialAddr != target {
2740 ret = append(ret, pc)
2745 func makeUtHolepunchMsgForPeerConn(
2746 recipient *PeerConn,
2747 msgType utHolepunch.MsgType,
2748 addrPort netip.AddrPort,
2749 errCode utHolepunch.ErrCode,
2751 utHolepunchMsg := utHolepunch.Msg{
2756 extendedPayload, err := utHolepunchMsg.MarshalBinary()
2762 ExtendedID: MapMustGet(recipient.PeerExtensionIDs, utHolepunch.ExtensionName),
2763 ExtendedPayload: extendedPayload,
2767 func sendUtHolepunchMsg(
2769 msgType utHolepunch.MsgType,
2770 addrPort netip.AddrPort,
2771 errCode utHolepunch.ErrCode,
2773 pc.write(makeUtHolepunchMsgForPeerConn(pc, msgType, addrPort, errCode))
2776 func (t *Torrent) handleReceivedUtHolepunchMsg(msg utHolepunch.Msg, sender *PeerConn) error {
2777 switch msg.MsgType {
2778 case utHolepunch.Rendezvous:
2779 t.logger.Printf("got holepunch rendezvous request for %v from %p", msg.AddrPort, sender)
2780 sendMsg := sendUtHolepunchMsg
2781 senderAddrPort, err := sender.remoteDialAddrPort()
2783 sender.logger.Levelf(
2785 "error getting ut_holepunch rendezvous sender's dial address: %v",
2788 // There's no better error code. The sender's address itself is invalid. I don't see
2789 // this error message being appropriate anywhere else anyway.
2790 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSuchPeer)
2792 targets := t.peerConnsWithDialAddrPort(msg.AddrPort)
2793 if len(targets) == 0 {
2794 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NotConnected)
2797 for _, pc := range targets {
2798 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2799 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSupport)
2802 sendMsg(sender, utHolepunch.Connect, msg.AddrPort, 0)
2803 sendMsg(pc, utHolepunch.Connect, senderAddrPort, 0)
2806 case utHolepunch.Connect:
2807 t.logger.Printf("got holepunch connect from %v for %v", sender, msg.AddrPort)
2808 rz, ok := t.utHolepunchRendezvous[msg.AddrPort]
2810 delete(rz.relays, sender)
2812 rz.relayCond.Broadcast()
2814 // If the rendezvous was removed because we timed out or already got a connect signal,
2815 // it doesn't hurt to try again.
2816 t.initiateConn(PeerInfo{
2818 Source: PeerSourceUtHolepunch,
2819 }, false, true, true)
2822 case utHolepunch.Error:
2823 rz, ok := t.utHolepunchRendezvous[msg.AddrPort]
2825 delete(rz.relays, sender)
2826 rz.relayCond.Broadcast()
2828 t.logger.Printf("received ut_holepunch error message from %v: %v", sender, msg.ErrCode)
2831 return fmt.Errorf("unhandled msg type %v", msg.MsgType)
2835 func (t *Torrent) startHolepunchRendezvous(addrPort netip.AddrPort) (rz *utHolepunchRendezvous, err error) {
2836 if MapContains(t.utHolepunchRendezvous, addrPort) {
2837 err = errors.New("rendezvous already exists")
2841 for pc := range t.conns {
2842 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2845 if pc.supportsExtension(pp.ExtensionNamePex) {
2846 if !g.MapContains(pc.pex.remoteLiveConns, addrPort) {
2850 sendUtHolepunchMsg(pc, utHolepunch.Rendezvous, addrPort, 0)
2851 MakeMapIfNilAndSet(&rz.relays, pc, struct{}{})
2853 if len(rz.relays) == 0 {
2854 err = fmt.Errorf("no eligible relays")
2857 if !MakeMapIfNilAndSet(&t.utHolepunchRendezvous, addrPort, rz) {
2858 panic("expected to fail earlier if rendezvous already exists")