10 "github.com/anacrolix/torrent/merkle"
11 infohash_v2 "github.com/anacrolix/torrent/types/infohash-v2"
22 "github.com/RoaringBitmap/roaring"
23 "github.com/anacrolix/chansync"
24 "github.com/anacrolix/chansync/events"
25 "github.com/anacrolix/dht/v2"
26 . "github.com/anacrolix/generics"
27 g "github.com/anacrolix/generics"
28 "github.com/anacrolix/log"
29 "github.com/anacrolix/missinggo/slices"
30 "github.com/anacrolix/missinggo/v2"
31 "github.com/anacrolix/missinggo/v2/bitmap"
32 "github.com/anacrolix/missinggo/v2/pubsub"
33 "github.com/anacrolix/multiless"
34 "github.com/anacrolix/sync"
35 "github.com/pion/datachannel"
36 "golang.org/x/exp/maps"
38 "github.com/anacrolix/torrent/bencode"
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/storage"
46 "github.com/anacrolix/torrent/tracker"
47 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
48 "github.com/anacrolix/torrent/webseed"
49 "github.com/anacrolix/torrent/webtorrent"
52 // Maintains state of torrent within a Client. Many methods should not be called before the info is
53 // available, see .Info and .GotInfo.
55 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
56 // alignment. See #262.
61 networkingEnabled chansync.Flag
62 dataDownloadDisallowed chansync.Flag
63 dataUploadDisallowed bool
64 userOnWriteChunkErr func(error)
66 closed chansync.SetOnce
69 infoHash metainfo.Hash
70 infoHashV2 g.Option[infohash_v2.T]
74 // The order pieces are requested if there's no stronger reason like availability or priority.
75 pieceRequestOrder []int
76 // Values are the piece indices that changed.
77 pieceStateChanges pubsub.PubSub[PieceStateChange]
78 // The size of chunks to request from peers over the wire. This is
79 // normally 16KiB by convention these days.
82 // Total length of the torrent in bytes. Stored because it's not O(1) to
83 // get this from the info dict.
86 // The storage to open when the info dict becomes available.
87 storageOpener *storage.Client
88 // Storage for torrent data.
89 storage *storage.Torrent
90 // Read-locked for using storage, and write-locked for Closing.
91 storageLock sync.RWMutex
93 // TODO: Only announce stuff is used?
94 metainfo metainfo.MetaInfo
96 // The info dict. nil if we don't have it (yet).
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
111 // Reserve of peers to connect to. A peer can be both here and in the
112 // active connections if were told about the peer after connecting with
113 // them. That encourages us to reconnect to peers that are well known in
115 peers prioritizedPeers
116 // Whether we want to know more peers.
117 wantPeersEvent missinggo.Event
118 // An announcer for each tracker URL.
119 trackerAnnouncers map[string]torrentTrackerAnnouncer
120 // How many times we've initiated a DHT announce. TODO: Move into stats.
123 // Name used if the info name isn't available. Should be cleared when the
124 // Info does become available.
128 // The bencoded bytes of the info dict. This is actively manipulated if
129 // the info bytes aren't initially available, and we try to fetch them
132 // Each element corresponds to the 16KiB metadata pieces. If true, we have
133 // received that piece.
134 metadataCompletedChunks []bool
135 metadataChanged sync.Cond
137 // Closed when .Info is obtained.
138 gotMetainfoC chan struct{}
140 readers map[*reader]struct{}
141 _readerNowPieces bitmap.Bitmap
142 _readerReadaheadPieces bitmap.Bitmap
144 // A cache of pieces we need to get. Calculated from various piece and
145 // file priorities and completion states elsewhere.
146 _pendingPieces roaring.Bitmap
147 // A cache of completed piece indices.
148 _completedPieces roaring.Bitmap
149 // Pieces that need to be hashed.
150 piecesQueuedForHash bitmap.Bitmap
151 activePieceHashes int
152 initialPieceCheckDisabled bool
154 connsWithAllPieces map[*Peer]struct{}
156 requestState map[RequestIndex]requestState
157 // Chunks we've written to since the corresponding piece was last checked.
158 dirtyChunks typedRoaring.Bitmap[RequestIndex]
162 // Is On when all pieces are complete.
163 Complete chansync.Flag
165 // Torrent sources in use keyed by the source string.
166 activeSources sync.Map
167 sourcesLogger log.Logger
169 smartBanCache smartBanCache
171 // Large allocations reused between request state updates.
172 requestPieceStates []request_strategy.PieceRequestOrderState
173 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.updatePieceRequestOrderPiece(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.updatePieceRequestOrderPiece(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
253 for conn := range t.conns {
254 ks = append(ks, PeerInfo{
256 Addr: conn.RemoteAddr,
257 Source: conn.Discovery,
258 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
259 // > But if we're not connected to them with an encrypted connection, I couldn't say
260 // > what's appropriate. We can carry forward the SupportsEncryption value as we
261 // > received it from trackers/DHT/PEX, or just use the encryption state for the
262 // > connection. It's probably easiest to do the latter for now.
263 // https://github.com/anacrolix/torrent/pull/188
264 SupportsEncryption: conn.headerEncrypted,
271 func (t *Torrent) setChunkSize(size pp.Integer) {
273 t.chunkPool = sync.Pool{
274 New: func() interface{} {
275 b := make([]byte, size)
281 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
282 return t._completedPieces.Contains(bitmap.BitIndex(piece))
285 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
286 if t.storage == nil {
287 return storage.Completion{Complete: false, Ok: true}
289 return t.pieces[piece].Storage().Completion()
292 // There's a connection to that address already.
293 func (t *Torrent) addrActive(addr string) bool {
294 if _, ok := t.halfOpen[addr]; ok {
297 for c := range t.conns {
299 if ra.String() == addr {
306 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
307 return t.appendConns(ret, func(conn *PeerConn) bool {
308 return !conn.closed.IsSet()
312 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
313 for c := range t.conns {
321 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
323 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
324 if t.closed.IsSet() {
327 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
328 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
329 torrent.Add("peers not added because of bad addr", 1)
330 // cl.logger.Printf("peers not added because of bad addr: %v", p)
334 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
335 torrent.Add("peers replaced", 1)
336 if !replaced.equal(p) {
337 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
344 for t.peers.Len() > cl.config.TorrentPeersHighWater {
345 _, ok := t.peers.DeleteMin()
347 torrent.Add("excess reserve peers discarded", 1)
353 func (t *Torrent) invalidateMetadata() {
354 for i := 0; i < len(t.metadataCompletedChunks); i++ {
355 t.metadataCompletedChunks[i] = false
358 t.gotMetainfoC = make(chan struct{})
363 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
367 if index >= len(t.metadataCompletedChunks) {
368 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
371 copy(t.metadataBytes[(1<<14)*index:], data)
372 t.metadataCompletedChunks[index] = true
375 func (t *Torrent) metadataPieceCount() int {
376 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
379 func (t *Torrent) haveMetadataPiece(piece int) bool {
381 return (1<<14)*piece < len(t.metadataBytes)
383 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
387 func (t *Torrent) metadataSize() int {
388 return len(t.metadataBytes)
391 func (t *Torrent) makePieces() {
392 t.pieces = make([]Piece, t.info.NumPieces())
393 for i := range t.pieces {
394 piece := &t.pieces[i]
397 piece.noPendingWrites.L = &piece.pendingWritesMutex
399 piece.hash = (*metainfo.Hash)(unsafe.Pointer(
400 unsafe.SliceData(t.info.Pieces[i*sha1.Size : (i+1)*sha1.Size])))
403 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
404 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
405 piece.files = files[beginFile:endFile]
406 if t.info.FilesArePieceAligned() {
407 numFiles := len(piece.files)
409 panic(fmt.Sprintf("%v:%v", beginFile, endFile))
415 func (t *Torrent) AddPieceLayers(layers map[string]string) (err error) {
419 for _, f := range *t.files {
420 if !f.piecesRoot.Ok {
421 err = fmt.Errorf("no piece root set for file %v", f)
424 compactLayer, ok := layers[string(f.piecesRoot.Value[:])]
428 var hashes [][32]byte
429 hashes, err = merkle.CompactLayerToSliceHashes(compactLayer)
431 err = fmt.Errorf("bad piece layers for file %q: %w", f, err)
434 if len(hashes) != f.numPieces() {
435 err = fmt.Errorf("file %q: got %v hashes expected %v", f, len(hashes), f.numPieces())
438 for i := range f.numPieces() {
439 p := t.piece(f.BeginPieceIndex() + i)
440 p.hashV2.Set(hashes[i])
446 // Returns the index of the first file containing the piece. files must be
447 // ordered by offset.
448 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
449 for i, f := range files {
450 if f.offset+f.length > pieceOffset {
457 // Returns the index after the last file containing the piece. files must be
458 // ordered by offset.
459 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
460 for i, f := range files {
461 if f.offset >= pieceEndOffset {
468 func (t *Torrent) cacheLength() {
470 for _, f := range t.info.UpvertedFiles() {
476 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
478 func (t *Torrent) setInfo(info *metainfo.Info) error {
479 if err := validateInfo(info); err != nil {
480 return fmt.Errorf("bad info: %s", err)
482 if t.storageOpener != nil {
484 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
486 return fmt.Errorf("error opening torrent storage: %s", err)
492 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
494 t.displayName = "" // Save a few bytes lol.
501 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
502 return request_strategy.PieceRequestOrderKey{
503 InfoHash: t.infoHash,
508 // This seems to be all the follow-up tasks after info is set, that can't fail.
509 func (t *Torrent) onSetInfo() {
510 t.pieceRequestOrder = rand.Perm(t.numPieces())
511 t.initPieceRequestOrder()
512 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
513 for i := range t.pieces {
515 // Need to add relativeAvailability before updating piece completion, as that may result in conns
517 if p.relativeAvailability != 0 {
518 panic(p.relativeAvailability)
520 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
521 t.addRequestOrderPiece(i)
522 t.updatePieceCompletion(i)
523 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
524 // t.logger.Printf("piece %s completion unknown, queueing check", p)
528 t.cl.event.Broadcast()
529 close(t.gotMetainfoC)
530 t.updateWantPeersEvent()
531 t.requestState = make(map[RequestIndex]requestState)
532 t.tryCreateMorePieceHashers()
533 t.iterPeers(func(p *Peer) {
535 p.updateRequests("onSetInfo")
539 // Called when metadata for a torrent becomes available.
540 func (t *Torrent) setInfoBytesLocked(b []byte) error {
541 if metainfo.HashBytes(b) != t.infoHash {
542 return errors.New("info bytes have wrong hash")
544 var info metainfo.Info
545 if err := bencode.Unmarshal(b, &info); err != nil {
546 return fmt.Errorf("error unmarshalling info bytes: %s", err)
549 t.metadataCompletedChunks = nil
553 if err := t.setInfo(&info); err != nil {
560 func (t *Torrent) haveAllMetadataPieces() bool {
564 if t.metadataCompletedChunks == nil {
567 for _, have := range t.metadataCompletedChunks {
575 // TODO: Propagate errors to disconnect peer.
576 func (t *Torrent) setMetadataSize(size int) (err error) {
578 // We already know the correct metadata size.
581 if uint32(size) > maxMetadataSize {
582 return log.WithLevel(log.Warning, errors.New("bad size"))
584 if len(t.metadataBytes) == size {
587 t.metadataBytes = make([]byte, size)
588 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
589 t.metadataChanged.Broadcast()
590 for c := range t.conns {
591 c.requestPendingMetadata()
596 // The current working name for the torrent. Either the name in the info dict,
597 // or a display name given such as by the dn value in a magnet link, or "".
598 func (t *Torrent) name() string {
600 defer t.nameMu.RUnlock()
602 return t.info.BestName()
604 if t.displayName != "" {
607 return "infohash:" + t.infoHash.HexString()
610 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
611 p := &t.pieces[index]
612 ret.Priority = t.piecePriority(index)
613 ret.Completion = p.completion()
614 ret.QueuedForHash = p.queuedForHash()
615 ret.Hashing = p.hashing
616 ret.Checking = ret.QueuedForHash || ret.Hashing
617 ret.Marking = p.marking
618 if !ret.Complete && t.piecePartiallyDownloaded(index) {
624 func (t *Torrent) metadataPieceSize(piece int) int {
625 return metadataPieceSize(len(t.metadataBytes), piece)
628 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
631 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
632 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
634 TotalSize: len(t.metadataBytes),
640 type pieceAvailabilityRun struct {
645 func (me pieceAvailabilityRun) String() string {
646 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
649 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
650 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
651 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
653 for i := range t.pieces {
654 rle.Append(t.pieces[i].availability(), 1)
660 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
661 freqs = make([]int, t.numActivePeers()+1)
662 for i := range t.pieces {
663 freqs[t.piece(i).availability()]++
668 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
669 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
670 ret = append(ret, PieceStateRun{
671 PieceState: el.(PieceState),
675 for index := range t.pieces {
676 rle.Append(t.pieceState(pieceIndex(index)), 1)
682 // Produces a small string representing a PieceStateRun.
683 func (psr PieceStateRun) String() (ret string) {
684 ret = fmt.Sprintf("%d", psr.Length)
685 ret += func() string {
686 switch psr.Priority {
687 case PiecePriorityNext:
689 case PiecePriorityNormal:
691 case PiecePriorityReadahead:
693 case PiecePriorityNow:
695 case PiecePriorityHigh:
704 if psr.QueuedForHash {
722 func (t *Torrent) writeStatus(w io.Writer) {
723 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
724 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
726 fmt.Fprintf(w, "Metadata have: ")
727 for _, h := range t.metadataCompletedChunks {
728 fmt.Fprintf(w, "%c", func() rune {
738 fmt.Fprintf(w, "Piece length: %s\n",
741 return fmt.Sprintf("%v (%v chunks)",
743 float64(t.usualPieceSize())/float64(t.chunkSize))
750 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
751 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
752 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
753 // availability frequencies instead.
755 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
756 for _, run := range t.pieceAvailabilityRuns() {
757 ret = append(ret, run.String())
762 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
763 func() (ret []string) {
764 for avail, freq := range t.pieceAvailabilityFrequencies() {
768 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
774 fmt.Fprintf(w, "Reader Pieces:")
775 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
776 fmt.Fprintf(w, " %d:%d", begin, end)
781 fmt.Fprintf(w, "Enabled trackers:\n")
783 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
784 fmt.Fprintf(tw, " URL\tExtra\n")
785 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
788 var luns, runs url.URL = *lu, *ru
791 var ml missinggo.MultiLess
792 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
793 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
795 }).([]torrentTrackerAnnouncer) {
796 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
801 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
803 dumpStats(w, t.statsLocked())
805 fmt.Fprintf(w, "webseeds:\n")
806 t.writePeerStatuses(w, maps.Values(t.webSeeds))
808 peerConns := maps.Keys(t.conns)
809 // Peers without priorities first, then those with. I'm undecided about how to order peers
810 // without priorities.
811 sort.Slice(peerConns, func(li, ri int) bool {
814 ml := multiless.New()
815 lpp := g.ResultFromTuple(l.peerPriority()).ToOption()
816 rpp := g.ResultFromTuple(r.peerPriority()).ToOption()
817 ml = ml.Bool(lpp.Ok, rpp.Ok)
818 ml = ml.Uint32(rpp.Value, lpp.Value)
822 fmt.Fprintf(w, "%v peer conns:\n", len(peerConns))
823 t.writePeerStatuses(w, g.SliceMap(peerConns, func(pc *PeerConn) *Peer {
828 func (t *Torrent) writePeerStatuses(w io.Writer, peers []*Peer) {
830 for _, c := range peers {
834 w.Write(bytes.TrimRight(
835 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
840 func (t *Torrent) haveInfo() bool {
844 // Returns a run-time generated MetaInfo that includes the info bytes and
845 // announce-list as currently known to the client.
846 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
847 return metainfo.MetaInfo{
848 CreationDate: time.Now().Unix(),
849 Comment: "dynamic metainfo from client",
850 CreatedBy: "go.torrent",
851 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
852 InfoBytes: func() []byte {
854 return t.metadataBytes
859 UrlList: func() []string {
860 ret := make([]string, 0, len(t.webSeeds))
861 for url := range t.webSeeds {
862 ret = append(ret, url)
869 // Returns a count of bytes that are not complete in storage, and not pending being written to
870 // storage. This value is from the perspective of the download manager, and may not agree with the
871 // actual state in storage. If you want read data synchronously you should use a Reader. See
872 // https://github.com/anacrolix/torrent/issues/828.
873 func (t *Torrent) BytesMissing() (n int64) {
875 n = t.bytesMissingLocked()
880 func (t *Torrent) bytesMissingLocked() int64 {
884 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
885 roaring.Flip(b, 0, end).Iterate(cb)
888 func (t *Torrent) bytesLeft() (left int64) {
889 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
890 p := t.piece(pieceIndex(x))
891 left += int64(p.length() - p.numDirtyBytes())
897 // Bytes left to give in tracker announces.
898 func (t *Torrent) bytesLeftAnnounce() int64 {
906 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
907 if t.pieceComplete(piece) {
910 if t.pieceAllDirty(piece) {
913 return t.pieces[piece].hasDirtyChunks()
916 func (t *Torrent) usualPieceSize() int {
917 return int(t.info.PieceLength)
920 func (t *Torrent) numPieces() pieceIndex {
921 return t.info.NumPieces()
924 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
925 return pieceIndex(t._completedPieces.GetCardinality())
928 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
930 err = errors.New("already closed")
933 for _, f := range t.onClose {
936 if t.storage != nil {
941 defer t.storageLock.Unlock()
942 if f := t.storage.Close; f != nil {
945 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
950 t.iterPeers(func(p *Peer) {
953 if t.storage != nil {
954 t.deletePieceRequestOrder()
956 t.assertAllPiecesRelativeAvailabilityZero()
958 t.cl.event.Broadcast()
959 t.pieceStateChanges.Close()
960 t.updateWantPeersEvent()
964 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
965 for i := range t.pieces {
967 if p.relativeAvailability != 0 {
968 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
973 func (t *Torrent) requestOffset(r Request) int64 {
974 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
977 // Return the request that would include the given offset into the torrent data. Returns !ok if
978 // there is no such request.
979 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
980 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
983 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
984 //defer perf.ScopeTimerErr(&err)()
985 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
986 if err == nil && n != len(data) {
987 err = io.ErrShortWrite
992 func (t *Torrent) bitfield() (bf []bool) {
993 bf = make([]bool, t.numPieces())
994 t._completedPieces.Iterate(func(piece uint32) (again bool) {
1001 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
1002 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
1005 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
1006 return t._chunksPerRegularPiece
1009 func (t *Torrent) numChunks() RequestIndex {
1010 if t.numPieces() == 0 {
1013 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
1016 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
1017 t.dirtyChunks.RemoveRange(
1018 uint64(t.pieceRequestIndexOffset(pieceIndex)),
1019 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
1022 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
1023 if t.info.PieceLength == 0 {
1024 // There will be no variance amongst pieces. Only pain.
1027 if t.info.FilesArePieceAligned() {
1029 file := p.mustGetOnlyFile()
1030 if piece == file.EndPieceIndex()-1 {
1031 return pp.Integer(file.length - (p.torrentBeginOffset() - file.offset))
1033 return pp.Integer(t.usualPieceSize())
1035 if piece == t.numPieces()-1 {
1036 ret := pp.Integer(t.length() % t.info.PieceLength)
1041 return pp.Integer(t.info.PieceLength)
1044 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
1045 return &blockCheckingWriter{
1046 cache: &t.smartBanCache,
1047 requestIndex: t.pieceRequestIndexOffset(piece),
1048 chunkSize: t.chunkSize.Int(),
1052 func (t *Torrent) hashPiece(piece pieceIndex) (
1054 // These are peers that sent us blocks that differ from what we hash here.
1055 differingPeers map[bannableAddr]struct{},
1059 p.waitNoPendingWrites()
1060 storagePiece := t.pieces[piece].Storage()
1062 // Does the backend want to do its own hashing?
1063 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
1064 var sum metainfo.Hash
1065 // log.Printf("A piece decided to self-hash: %d", piece)
1066 sum, err = i.SelfHash()
1067 missinggo.CopyExact(&ret, sum)
1071 hash := pieceHash.New()
1072 const logPieceContents = false
1073 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1074 writers := []io.Writer{hash, smartBanWriter}
1075 var examineBuf bytes.Buffer
1076 if logPieceContents {
1077 writers = append(writers, &examineBuf)
1079 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1080 if logPieceContents {
1081 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1083 smartBanWriter.Flush()
1084 differingPeers = smartBanWriter.badPeers
1085 missinggo.CopyExact(&ret, hash.Sum(nil))
1089 func (t *Torrent) haveAnyPieces() bool {
1090 return !t._completedPieces.IsEmpty()
1093 func (t *Torrent) haveAllPieces() bool {
1097 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1100 func (t *Torrent) havePiece(index pieceIndex) bool {
1101 return t.haveInfo() && t.pieceComplete(index)
1104 func (t *Torrent) maybeDropMutuallyCompletePeer(
1105 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1109 if !t.cl.config.DropMutuallyCompletePeers {
1112 if !t.haveAllPieces() {
1115 if all, known := p.peerHasAllPieces(); !(known && all) {
1121 p.logger.Levelf(log.Debug, "is mutually complete; dropping")
1125 func (t *Torrent) haveChunk(r Request) (ret bool) {
1127 // log.Println("have chunk", r, ret)
1132 if t.pieceComplete(pieceIndex(r.Index)) {
1135 p := &t.pieces[r.Index]
1136 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1139 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1140 return chunkIndexType(cs.Begin / chunkSize)
1143 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1144 return !t._pendingPieces.IsEmpty() && t._pendingPieces.Contains(uint32(index))
1147 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1148 // conns (which is a map).
1149 var peerConnSlices sync.Pool
1151 func getPeerConnSlice(cap int) []*PeerConn {
1152 getInterface := peerConnSlices.Get()
1153 if getInterface == nil {
1154 return make([]*PeerConn, 0, cap)
1156 return getInterface.([]*PeerConn)[:0]
1160 // Calls the given function with a slice of unclosed conns. It uses a pool to reduce allocations as
1161 // this is a frequent occurrence.
1162 func (t *Torrent) withUnclosedConns(f func([]*PeerConn)) {
1163 sl := t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))
1165 peerConnSlices.Put(sl)
1168 func (t *Torrent) worstBadConnFromSlice(opts worseConnLensOpts, sl []*PeerConn) *PeerConn {
1169 wcs := worseConnSlice{conns: sl}
1172 for wcs.Len() != 0 {
1173 c := heap.Pop(&wcs).(*PeerConn)
1174 if opts.incomingIsBad && !c.outgoing {
1177 if opts.outgoingIsBad && c.outgoing {
1180 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1183 // If the connection is in the worst half of the established
1184 // connection quota and is older than a minute.
1185 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1186 // Give connections 1 minute to prove themselves.
1187 if time.Since(c.completedHandshake) > time.Minute {
1195 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1196 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1197 // established connections for more than a minute. This is O(n log n). If there was a way to not
1198 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1199 func (t *Torrent) worstBadConn(opts worseConnLensOpts) (ret *PeerConn) {
1200 t.withUnclosedConns(func(ucs []*PeerConn) {
1201 ret = t.worstBadConnFromSlice(opts, ucs)
1206 type PieceStateChange struct {
1211 func (t *Torrent) publishPieceStateChange(piece pieceIndex) {
1212 t.cl._mu.Defer(func() {
1213 cur := t.pieceState(piece)
1214 p := &t.pieces[piece]
1215 if cur != p.publicPieceState {
1216 p.publicPieceState = cur
1217 t.pieceStateChanges.Publish(PieceStateChange{
1225 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1226 if t.pieceComplete(piece) {
1229 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1232 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1233 return t.pieces[piece].allChunksDirty()
1236 func (t *Torrent) readersChanged() {
1237 t.updateReaderPieces()
1238 t.updateAllPiecePriorities("Torrent.readersChanged")
1241 func (t *Torrent) updateReaderPieces() {
1242 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1245 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1249 t.updateReaderPieces()
1250 // Order the ranges, high and low.
1252 if l.begin > h.begin {
1255 if l.end < h.begin {
1256 // Two distinct ranges.
1257 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1258 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1265 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1269 func (t *Torrent) maybeNewConns() {
1270 // Tickle the accept routine.
1271 t.cl.event.Broadcast()
1275 func (t *Torrent) onPiecePendingTriggers(piece pieceIndex, reason string) {
1276 if t._pendingPieces.Contains(uint32(piece)) {
1277 t.iterPeers(func(c *Peer) {
1278 // if c.requestState.Interested {
1281 if !c.isLowOnRequests() {
1284 if !c.peerHasPiece(piece) {
1287 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1290 c.updateRequests(reason)
1294 t.publishPieceStateChange(piece)
1297 func (t *Torrent) updatePiecePriorityNoTriggers(piece pieceIndex) (pendingChanged bool) {
1298 if !t.closed.IsSet() {
1299 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1301 t.updatePieceRequestOrderPiece(piece)
1303 p := &t.pieces[piece]
1304 newPrio := p.uncachedPriority()
1305 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1306 if newPrio == PiecePriorityNone {
1307 return t._pendingPieces.CheckedRemove(uint32(piece))
1309 return t._pendingPieces.CheckedAdd(uint32(piece))
1313 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1314 if t.updatePiecePriorityNoTriggers(piece) && !t.disableTriggers {
1315 t.onPiecePendingTriggers(piece, reason)
1317 t.updatePieceRequestOrderPiece(piece)
1320 func (t *Torrent) updateAllPiecePriorities(reason string) {
1321 t.updatePiecePriorities(0, t.numPieces(), reason)
1324 // Update all piece priorities in one hit. This function should have the same
1325 // output as updatePiecePriority, but across all pieces.
1326 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1327 for i := begin; i < end; i++ {
1328 t.updatePiecePriority(i, reason)
1332 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1333 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1334 if off >= t.length() {
1344 begin = pieceIndex(off / t.info.PieceLength)
1345 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1346 if end > pieceIndex(t.info.NumPieces()) {
1347 end = pieceIndex(t.info.NumPieces())
1352 // Returns true if all iterations complete without breaking. Returns the read regions for all
1353 // readers. The reader regions should not be merged as some callers depend on this method to
1354 // enumerate readers.
1355 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1356 for r := range t.readers {
1358 if p.begin >= p.end {
1361 if !f(p.begin, p.end) {
1368 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1369 return t.piece(piece).uncachedPriority()
1372 func (t *Torrent) pendRequest(req RequestIndex) {
1373 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1376 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1377 t.cl.event.Broadcast()
1378 if t.pieceComplete(piece) {
1379 t.onPieceCompleted(piece)
1381 t.onIncompletePiece(piece)
1383 t.updatePiecePriority(piece, reason)
1386 func (t *Torrent) numReceivedConns() (ret int) {
1387 for c := range t.conns {
1388 if c.Discovery == PeerSourceIncoming {
1395 func (t *Torrent) numOutgoingConns() (ret int) {
1396 for c := range t.conns {
1404 func (t *Torrent) maxHalfOpen() int {
1405 // Note that if we somehow exceed the maximum established conns, we want
1406 // the negative value to have an effect.
1407 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1408 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1409 // We want to allow some experimentation with new peers, and to try to
1410 // upset an oversupply of received connections.
1412 max(5, extraIncoming)+establishedHeadroom,
1413 int64(t.cl.config.HalfOpenConnsPerTorrent),
1417 func (t *Torrent) openNewConns() (initiated int) {
1418 defer t.updateWantPeersEvent()
1419 for t.peers.Len() != 0 {
1420 if !t.wantOutgoingConns() {
1423 if len(t.halfOpen) >= t.maxHalfOpen() {
1426 if len(t.cl.dialers) == 0 {
1429 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1432 p := t.peers.PopMax()
1433 opts := outgoingConnOpts{
1436 requireRendezvous: false,
1437 skipHolepunchRendezvous: false,
1438 receivedHolepunchConnect: false,
1439 HeaderObfuscationPolicy: t.cl.config.HeaderObfuscationPolicy,
1441 initiateConn(opts, false)
1447 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1449 uncached := t.pieceCompleteUncached(piece)
1450 cached := p.completion()
1451 changed := cached != uncached
1452 complete := uncached.Complete
1453 p.storageCompletionOk = uncached.Ok
1456 t._completedPieces.Add(x)
1459 t._completedPieces.Remove(x)
1461 p.t.updatePieceRequestOrderPiece(piece)
1463 if complete && len(p.dirtiers) != 0 {
1464 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1468 // "piece completion changed",
1469 // slog.Int("piece", piece),
1470 // slog.Any("from", cached),
1471 // slog.Any("to", uncached))
1472 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1477 // Non-blocking read. Client lock is not required.
1478 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1480 p := &t.pieces[off/t.info.PieceLength]
1481 p.waitNoPendingWrites()
1483 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1494 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1495 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1496 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1497 func (t *Torrent) maybeCompleteMetadata() error {
1502 if !t.haveAllMetadataPieces() {
1503 // Don't have enough metadata pieces.
1506 err := t.setInfoBytesLocked(t.metadataBytes)
1508 t.invalidateMetadata()
1509 return fmt.Errorf("error setting info bytes: %s", err)
1511 if t.cl.config.Debug {
1512 t.logger.Printf("%s: got metadata from peers", t)
1517 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1518 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1520 now.Add(bitmap.BitIndex(begin))
1521 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1528 func (t *Torrent) needData() bool {
1529 if t.closed.IsSet() {
1535 return !t._pendingPieces.IsEmpty()
1538 func appendMissingStrings(old, new []string) (ret []string) {
1541 for _, n := range new {
1542 for _, o := range old {
1547 ret = append(ret, n)
1552 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1554 for minNumTiers > len(ret) {
1555 ret = append(ret, nil)
1560 func (t *Torrent) addTrackers(announceList [][]string) {
1561 fullAnnounceList := &t.metainfo.AnnounceList
1562 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1563 for tierIndex, trackerURLs := range announceList {
1564 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1566 t.startMissingTrackerScrapers()
1567 t.updateWantPeersEvent()
1570 // Don't call this before the info is available.
1571 func (t *Torrent) bytesCompleted() int64 {
1575 return t.length() - t.bytesLeft()
1578 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1581 return t.setInfoBytesLocked(b)
1584 // Returns true if connection is removed from torrent.Conns.
1585 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1586 if !c.closed.IsSet() {
1587 panic("connection is not closed")
1588 // There are behaviours prevented by the closed state that will fail
1589 // if the connection has been deleted.
1593 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1594 // the drop event against the PexConnState instead.
1596 if !t.cl.config.DisablePEX {
1600 torrent.Add("deleted connections", 1)
1601 c.deleteAllRequests("Torrent.deletePeerConn")
1602 t.assertPendingRequests()
1603 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1604 panic(t.connsWithAllPieces)
1609 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1610 if t.deleteConnWithAllPieces(p) {
1616 p.peerPieces().Iterate(func(i uint32) bool {
1617 p.t.decPieceAvailability(pieceIndex(i))
1622 func (t *Torrent) assertPendingRequests() {
1626 // var actual pendingRequests
1627 // if t.haveInfo() {
1628 // actual.m = make([]int, t.numChunks())
1630 // t.iterPeers(func(p *Peer) {
1631 // p.requestState.Requests.Iterate(func(x uint32) bool {
1636 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1642 func (t *Torrent) dropConnection(c *PeerConn) {
1643 t.cl.event.Broadcast()
1645 if t.deletePeerConn(c) {
1650 // Peers as in contact information for dialing out.
1651 func (t *Torrent) wantPeers() bool {
1652 if t.closed.IsSet() {
1655 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1658 return t.wantOutgoingConns()
1661 func (t *Torrent) updateWantPeersEvent() {
1663 t.wantPeersEvent.Set()
1665 t.wantPeersEvent.Clear()
1669 // Returns whether the client should make effort to seed the torrent.
1670 func (t *Torrent) seeding() bool {
1672 if t.closed.IsSet() {
1675 if t.dataUploadDisallowed {
1678 if cl.config.NoUpload {
1681 if !cl.config.Seed {
1684 if cl.config.DisableAggressiveUpload && t.needData() {
1690 func (t *Torrent) onWebRtcConn(
1691 c datachannel.ReadWriteCloser,
1692 dcc webtorrent.DataChannelContext,
1695 netConn := webrtcNetConn{
1697 DataChannelContext: dcc,
1699 peerRemoteAddr := netConn.RemoteAddr()
1700 //t.logger.Levelf(log.Critical, "onWebRtcConn remote addr: %v", peerRemoteAddr)
1701 if t.cl.badPeerAddr(peerRemoteAddr) {
1704 localAddrIpPort := missinggo.IpPortFromNetAddr(netConn.LocalAddr())
1705 pc, err := t.cl.initiateProtocolHandshakes(
1706 context.Background(),
1711 outgoing: dcc.LocalOffered,
1712 remoteAddr: peerRemoteAddr,
1713 localPublicAddr: localAddrIpPort,
1714 network: webrtcNetwork,
1715 connString: fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1719 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1722 if dcc.LocalOffered {
1723 pc.Discovery = PeerSourceTracker
1725 pc.Discovery = PeerSourceIncoming
1727 pc.conn.SetWriteDeadline(time.Time{})
1730 err = t.runHandshookConn(pc)
1732 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1736 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1737 err := t.runHandshookConn(pc)
1738 if err != nil || logAll {
1739 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1743 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1744 t.logRunHandshookConn(pc, false, log.Debug)
1747 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1748 wtc, release := t.cl.websocketTrackers.Get(u.String(), t.infoHash)
1749 // This needs to run before the Torrent is dropped from the Client, to prevent a new webtorrent.TrackerClient for
1750 // the same info hash before the old one is cleaned up.
1751 t.onClose = append(t.onClose, release)
1752 wst := websocketTrackerStatus{u, wtc}
1754 err := wtc.Announce(tracker.Started, t.infoHash)
1756 t.logger.WithDefaultLevel(log.Warning).Printf(
1757 "error in initial announce to %q: %v",
1765 func (t *Torrent) startScrapingTracker(_url string) {
1769 u, err := url.Parse(_url)
1771 // URLs with a leading '*' appear to be a uTorrent convention to disable trackers.
1773 t.logger.Levelf(log.Warning, "error parsing tracker url: %v", err)
1777 if u.Scheme == "udp" {
1779 t.startScrapingTracker(u.String())
1781 t.startScrapingTracker(u.String())
1784 if _, ok := t.trackerAnnouncers[_url]; ok {
1787 sl := func() torrentTrackerAnnouncer {
1790 if t.cl.config.DisableWebtorrent {
1793 return t.startWebsocketAnnouncer(*u)
1795 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1799 if t.cl.config.DisableIPv6 {
1803 newAnnouncer := &trackerScraper{
1806 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1808 go newAnnouncer.Run()
1814 if t.trackerAnnouncers == nil {
1815 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1817 t.trackerAnnouncers[_url] = sl
1820 // Adds and starts tracker scrapers for tracker URLs that aren't already
1822 func (t *Torrent) startMissingTrackerScrapers() {
1823 if t.cl.config.DisableTrackers {
1826 t.startScrapingTracker(t.metainfo.Announce)
1827 for _, tier := range t.metainfo.AnnounceList {
1828 for _, url := range tier {
1829 t.startScrapingTracker(url)
1834 // Returns an AnnounceRequest with fields filled out to defaults and current
1836 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1837 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1838 // dependent on the network in use.
1839 return tracker.AnnounceRequest{
1841 NumWant: func() int32 {
1842 if t.wantPeers() && len(t.cl.dialers) > 0 {
1843 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1848 Port: uint16(t.cl.incomingPeerPort()),
1849 PeerId: t.cl.peerID,
1850 InfoHash: t.infoHash,
1851 Key: t.cl.announceKey(),
1853 // The following are vaguely described in BEP 3.
1855 Left: t.bytesLeftAnnounce(),
1856 Uploaded: t.stats.BytesWrittenData.Int64(),
1857 // There's no mention of wasted or unwanted download in the BEP.
1858 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1862 // Adds peers revealed in an announce until the announce ends, or we have
1864 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1866 for v := range pvs {
1869 for _, cp := range v.Peers {
1871 // Can't do anything with this.
1874 if t.addPeer(PeerInfo{
1875 Addr: ipPortAddr{cp.IP, cp.Port},
1876 Source: PeerSourceDhtGetPeers,
1883 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1888 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1889 // announce ends. stop will force the announce to end.
1890 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1891 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1895 _done := make(chan struct{})
1899 t.consumeDhtAnnouncePeers(ps.Peers())
1905 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1906 _, stop, err := t.AnnounceToDht(s)
1911 case <-t.closed.Done():
1912 case <-time.After(5 * time.Minute):
1918 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1924 if t.closed.IsSet() {
1927 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1928 // TODO: We can include the announce_peer step depending on whether we can receive
1929 // inbound connections. We should probably only announce once every 15 mins too.
1930 if !t.wantAnyConns() {
1933 // TODO: Determine if there's a listener on the port we're announcing.
1934 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1945 err := t.timeboxedAnnounceToDht(s)
1947 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1953 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1954 for _, p := range peers {
1962 // The returned TorrentStats may require alignment in memory. See
1963 // https://github.com/anacrolix/torrent/issues/383.
1964 func (t *Torrent) Stats() TorrentStats {
1966 defer t.cl.rUnlock()
1967 return t.statsLocked()
1970 func (t *Torrent) statsLocked() (ret TorrentStats) {
1971 ret.ActivePeers = len(t.conns)
1972 ret.HalfOpenPeers = len(t.halfOpen)
1973 ret.PendingPeers = t.peers.Len()
1974 ret.TotalPeers = t.numTotalPeers()
1975 ret.ConnectedSeeders = 0
1976 for c := range t.conns {
1977 if all, ok := c.peerHasAllPieces(); all && ok {
1978 ret.ConnectedSeeders++
1981 ret.ConnStats = t.stats.Copy()
1982 ret.PiecesComplete = t.numPiecesCompleted()
1986 // The total number of peers in the torrent.
1987 func (t *Torrent) numTotalPeers() int {
1988 peers := make(map[string]struct{})
1989 for conn := range t.conns {
1990 ra := conn.conn.RemoteAddr()
1992 // It's been closed and doesn't support RemoteAddr.
1995 peers[ra.String()] = struct{}{}
1997 for addr := range t.halfOpen {
1998 peers[addr] = struct{}{}
2000 t.peers.Each(func(peer PeerInfo) {
2001 peers[peer.Addr.String()] = struct{}{}
2006 // Reconcile bytes transferred before connection was associated with a
2008 func (t *Torrent) reconcileHandshakeStats(c *Peer) {
2009 if c._stats != (ConnStats{
2010 // Handshakes should only increment these fields:
2011 BytesWritten: c._stats.BytesWritten,
2012 BytesRead: c._stats.BytesRead,
2016 c.postHandshakeStats(func(cs *ConnStats) {
2017 cs.BytesRead.Add(c._stats.BytesRead.Int64())
2018 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
2020 c.reconciledHandshakeStats = true
2023 // Returns true if the connection is added.
2024 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
2027 torrent.Add("added connections", 1)
2030 if t.closed.IsSet() {
2031 return errors.New("torrent closed")
2033 for c0 := range t.conns {
2034 if c.PeerID != c0.PeerID {
2037 if !t.cl.config.DropDuplicatePeerIds {
2040 if c.hasPreferredNetworkOver(c0) {
2042 t.deletePeerConn(c0)
2044 return errors.New("existing connection preferred")
2047 if len(t.conns) >= t.maxEstablishedConns {
2048 numOutgoing := t.numOutgoingConns()
2049 numIncoming := len(t.conns) - numOutgoing
2050 c := t.worstBadConn(worseConnLensOpts{
2051 // We've already established that we have too many connections at this point, so we just
2052 // need to match what kind we have too many of vs. what we're trying to add now.
2053 incomingIsBad: (numIncoming-numOutgoing > 1) && c.outgoing,
2054 outgoingIsBad: (numOutgoing-numIncoming > 1) && !c.outgoing,
2057 return errors.New("don't want conn")
2062 if len(t.conns) >= t.maxEstablishedConns {
2065 t.conns[c] = struct{}{}
2066 t.cl.event.Broadcast()
2067 // We'll never receive the "p" extended handshake parameter.
2068 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
2074 func (t *Torrent) newConnsAllowed() bool {
2075 if !t.networkingEnabled.Bool() {
2078 if t.closed.IsSet() {
2081 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2087 func (t *Torrent) wantAnyConns() bool {
2088 if !t.networkingEnabled.Bool() {
2091 if t.closed.IsSet() {
2094 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2097 return len(t.conns) < t.maxEstablishedConns
2100 func (t *Torrent) wantOutgoingConns() bool {
2101 if !t.newConnsAllowed() {
2104 if len(t.conns) < t.maxEstablishedConns {
2107 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2108 return t.worstBadConn(worseConnLensOpts{
2109 incomingIsBad: numIncomingConns-t.numOutgoingConns() > 1,
2110 outgoingIsBad: false,
2114 func (t *Torrent) wantIncomingConns() bool {
2115 if !t.newConnsAllowed() {
2118 if len(t.conns) < t.maxEstablishedConns {
2121 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2122 return t.worstBadConn(worseConnLensOpts{
2123 incomingIsBad: false,
2124 outgoingIsBad: t.numOutgoingConns()-numIncomingConns > 1,
2128 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
2131 oldMax = t.maxEstablishedConns
2132 t.maxEstablishedConns = max
2133 wcs := worseConnSlice{
2134 conns: t.appendConns(nil, func(*PeerConn) bool {
2138 wcs.initKeys(worseConnLensOpts{})
2140 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
2141 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
2147 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
2148 t.logger.LazyLog(log.Debug, func() log.Msg {
2149 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
2153 t.cl.event.Broadcast()
2154 if t.closed.IsSet() {
2158 // Don't score the first time a piece is hashed, it could be an initial check.
2159 if p.storageCompletionOk {
2161 pieceHashedCorrect.Add(1)
2164 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
2165 ).AddValues(t, p).LogLevel(
2167 log.Debug, t.logger)
2169 pieceHashedNotCorrect.Add(1)
2174 t.publishPieceStateChange(piece)
2177 t.publishPieceStateChange(piece)
2181 if len(p.dirtiers) != 0 {
2182 // Don't increment stats above connection-level for every involved connection.
2183 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2185 for c := range p.dirtiers {
2186 c._stats.incrementPiecesDirtiedGood()
2188 t.clearPieceTouchers(piece)
2189 hasDirty := p.hasDirtyChunks()
2192 p.Flush() // You can be synchronous here!
2194 err := p.Storage().MarkComplete()
2196 t.logger.Levelf(log.Warning, "%T: error marking piece complete %d: %s", t.storage, piece, err)
2200 if t.closed.IsSet() {
2203 t.pendAllChunkSpecs(piece)
2205 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2206 // Peers contributed to all the data for this piece hash failure, and the failure was
2207 // not due to errors in the storage (such as data being dropped in a cache).
2209 // Increment Torrent and above stats, and then specific connections.
2210 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2211 for c := range p.dirtiers {
2212 // Y u do dis peer?!
2213 c.stats().incrementPiecesDirtiedBad()
2216 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2217 for c := range p.dirtiers {
2219 bannableTouchers = append(bannableTouchers, c)
2222 t.clearPieceTouchers(piece)
2223 slices.Sort(bannableTouchers, connLessTrusted)
2225 if t.cl.config.Debug {
2227 "bannable conns by trust for piece %d: %v",
2229 func() (ret []connectionTrust) {
2230 for _, c := range bannableTouchers {
2231 ret = append(ret, c.trust())
2238 if len(bannableTouchers) >= 1 {
2239 c := bannableTouchers[0]
2240 if len(bannableTouchers) != 1 {
2241 t.logger.Levelf(log.Debug, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2243 // Turns out it's still useful to ban peers like this because if there's only a
2244 // single peer for a piece, and we never progress that piece to completion, we
2245 // will never smart-ban them. Discovered in
2246 // https://github.com/anacrolix/torrent/issues/715.
2247 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2252 t.onIncompletePiece(piece)
2253 p.Storage().MarkNotComplete()
2255 t.updatePieceCompletion(piece)
2258 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2259 start := t.pieceRequestIndexOffset(piece)
2260 end := start + t.pieceNumChunks(piece)
2261 for ri := start; ri < end; ri++ {
2266 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2267 t.pendAllChunkSpecs(piece)
2268 t.cancelRequestsForPiece(piece)
2269 t.piece(piece).readerCond.Broadcast()
2270 for conn := range t.conns {
2272 t.maybeDropMutuallyCompletePeer(conn)
2276 // Called when a piece is found to be not complete.
2277 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2278 if t.pieceAllDirty(piece) {
2279 t.pendAllChunkSpecs(piece)
2281 if !t.wantPieceIndex(piece) {
2282 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2285 // We could drop any connections that we told we have a piece that we
2286 // don't here. But there's a test failure, and it seems clients don't care
2287 // if you request pieces that you already claim to have. Pruning bad
2288 // connections might just remove any connections that aren't treating us
2289 // favourably anyway.
2291 // for c := range t.conns {
2292 // if c.sentHave(piece) {
2296 t.iterPeers(func(conn *Peer) {
2297 if conn.peerHasPiece(piece) {
2298 conn.updateRequests("piece incomplete")
2303 func (t *Torrent) tryCreateMorePieceHashers() {
2304 for !t.closed.IsSet() && t.activePieceHashes < t.cl.config.PieceHashersPerTorrent && t.tryCreatePieceHasher() {
2308 func (t *Torrent) tryCreatePieceHasher() bool {
2309 if t.storage == nil {
2312 pi, ok := t.getPieceToHash()
2317 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2319 t.publishPieceStateChange(pi)
2320 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2321 t.storageLock.RLock()
2322 t.activePieceHashes++
2323 go t.pieceHasher(pi)
2327 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2328 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2329 if t.piece(i).hashing {
2339 func (t *Torrent) dropBannedPeers() {
2340 t.iterPeers(func(p *Peer) {
2341 remoteIp := p.remoteIp()
2342 if remoteIp == nil {
2343 if p.bannableAddr.Ok {
2344 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2348 netipAddr := netip.MustParseAddr(remoteIp.String())
2349 if Some(netipAddr) != p.bannableAddr {
2350 t.logger.WithDefaultLevel(log.Debug).Printf(
2351 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2352 p, remoteIp, p.bannableAddr)
2354 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2355 // Should this be a close?
2357 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2362 func (t *Torrent) pieceHasher(index pieceIndex) {
2364 sum, failedPeers, copyErr := t.hashPiece(index)
2365 correct := sum == *p.hash
2369 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2371 t.storageLock.RUnlock()
2375 for peer := range failedPeers {
2376 t.cl.banPeerIP(peer.AsSlice())
2377 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2380 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2381 t.smartBanCache.ForgetBlock(ri)
2385 t.pieceHashed(index, correct, copyErr)
2386 t.updatePiecePriority(index, "Torrent.pieceHasher")
2387 t.activePieceHashes--
2388 t.tryCreateMorePieceHashers()
2391 // Return the connections that touched a piece, and clear the entries while doing it.
2392 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2394 for c := range p.dirtiers {
2395 delete(c.peerTouchedPieces, pi)
2396 delete(p.dirtiers, c)
2400 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2401 t.iterPeers(func(p *Peer) {
2402 ret = append(ret, p)
2407 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2408 piece := t.piece(pieceIndex)
2409 if piece.hash == nil && !piece.hashV2.Ok {
2412 if piece.queuedForHash() {
2415 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2416 t.publishPieceStateChange(pieceIndex)
2417 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2418 t.tryCreateMorePieceHashers()
2421 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2422 // before the Info is available.
2423 func (t *Torrent) VerifyData() {
2424 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2425 t.Piece(i).VerifyData()
2429 func (t *Torrent) connectingToPeerAddr(addrStr string) bool {
2430 return len(t.halfOpen[addrStr]) != 0
2433 func (t *Torrent) hasPeerConnForAddr(x PeerRemoteAddr) bool {
2434 addrStr := x.String()
2435 for c := range t.conns {
2437 if ra.String() == addrStr {
2444 func (t *Torrent) getHalfOpenPath(
2446 attemptKey outgoingConnAttemptKey,
2447 ) nestedmaps.Path[*PeerInfo] {
2448 return nestedmaps.Next(nestedmaps.Next(nestedmaps.Begin(&t.halfOpen), addrStr), attemptKey)
2451 func (t *Torrent) addHalfOpen(addrStr string, attemptKey *PeerInfo) {
2452 path := t.getHalfOpenPath(addrStr, attemptKey)
2454 panic("should be unique")
2456 path.Set(attemptKey)
2460 // Start the process of connecting to the given peer for the given torrent if appropriate. I'm not
2461 // sure all the PeerInfo fields are being used.
2463 opts outgoingConnOpts,
2467 peer := opts.peerInfo
2468 if peer.Id == t.cl.peerID {
2471 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2475 addrStr := addr.String()
2477 if t.connectingToPeerAddr(addrStr) {
2481 if t.hasPeerConnForAddr(addr) {
2485 t.addHalfOpen(addrStr, attemptKey)
2486 go t.cl.outgoingConnection(
2492 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2493 // quickly make one Client visible to the Torrent of another Client.
2494 func (t *Torrent) AddClientPeer(cl *Client) int {
2495 return t.AddPeers(func() (ps []PeerInfo) {
2496 for _, la := range cl.ListenAddrs() {
2497 ps = append(ps, PeerInfo{
2506 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2508 func (t *Torrent) allStats(f func(*ConnStats)) {
2513 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2514 return t.pieces[i].hashing
2517 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2518 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2521 func (t *Torrent) dialTimeout() time.Duration {
2522 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2525 func (t *Torrent) piece(i int) *Piece {
2529 func (t *Torrent) onWriteChunkErr(err error) {
2530 if t.userOnWriteChunkErr != nil {
2531 go t.userOnWriteChunkErr(err)
2534 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2535 t.disallowDataDownloadLocked()
2538 func (t *Torrent) DisallowDataDownload() {
2541 t.disallowDataDownloadLocked()
2544 func (t *Torrent) disallowDataDownloadLocked() {
2545 t.dataDownloadDisallowed.Set()
2546 t.iterPeers(func(p *Peer) {
2547 // Could check if peer request state is empty/not interested?
2548 p.updateRequests("disallow data download")
2549 p.cancelAllRequests()
2553 func (t *Torrent) AllowDataDownload() {
2556 t.dataDownloadDisallowed.Clear()
2557 t.iterPeers(func(p *Peer) {
2558 p.updateRequests("allow data download")
2562 // Enables uploading data, if it was disabled.
2563 func (t *Torrent) AllowDataUpload() {
2566 t.dataUploadDisallowed = false
2567 t.iterPeers(func(p *Peer) {
2568 p.updateRequests("allow data upload")
2572 // Disables uploading data, if it was enabled.
2573 func (t *Torrent) DisallowDataUpload() {
2576 t.dataUploadDisallowed = true
2577 for c := range t.conns {
2578 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2579 c.updateRequests("disallow data upload")
2583 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2584 // or if nil, a critical message is logged, and data download is disabled.
2585 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2588 t.userOnWriteChunkErr = f
2591 func (t *Torrent) iterPeers(f func(p *Peer)) {
2592 for pc := range t.conns {
2595 for _, ws := range t.webSeeds {
2600 func (t *Torrent) callbacks() *Callbacks {
2601 return &t.cl.config.Callbacks
2604 type AddWebSeedsOpt func(*webseed.Client)
2606 // Sets the WebSeed trailing path escaper for a webseed.Client.
2607 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2608 return func(c *webseed.Client) {
2609 c.PathEscaper = custom
2613 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2616 for _, u := range urls {
2617 t.addWebSeed(u, opts...)
2621 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2622 if t.cl.config.DisableWebseeds {
2625 if _, ok := t.webSeeds[url]; ok {
2628 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2629 // right away. This value should be some multiple of the number of connections to a host. I
2630 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2631 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2632 // "https://webtorrent.io/torrents/".
2633 const maxRequests = 16
2639 reconciledHandshakeStats: true,
2640 // This should affect how often we have to recompute requests for this peer. Note that
2641 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2642 // requests mark more often, so recomputation is probably sooner than with regular peer
2643 // conns. ~4x maxRequests would be about right.
2644 PeerMaxRequests: 128,
2645 // TODO: Set ban prefix?
2646 RemoteAddr: remoteAddrFromUrl(url),
2647 callbacks: t.callbacks(),
2649 client: webseed.Client{
2650 HttpClient: t.cl.httpClient,
2652 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2653 return &rateLimitedReader{
2654 l: t.cl.config.DownloadRateLimiter,
2659 activeRequests: make(map[Request]webseed.Request, maxRequests),
2661 ws.peer.initRequestState()
2662 for _, opt := range opts {
2665 ws.peer.initUpdateRequestsTimer()
2666 ws.requesterCond.L = t.cl.locker()
2667 for i := 0; i < maxRequests; i += 1 {
2670 for _, f := range t.callbacks().NewPeer {
2673 ws.peer.logger = t.logger.WithContextValue(&ws)
2674 ws.peer.peerImpl = &ws
2676 ws.onGotInfo(t.info)
2678 t.webSeeds[url] = &ws.peer
2681 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2682 t.iterPeers(func(p1 *Peer) {
2690 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2691 index := t.pieceIndexOfRequestIndex(ri)
2694 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2698 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2699 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2702 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2703 return RequestIndex(piece) * t.chunksPerRegularPiece()
2706 func (t *Torrent) updateComplete() {
2707 t.Complete.SetBool(t.haveAllPieces())
2710 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2711 p := t.requestingPeer(r)
2715 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2716 //delete(t.pendingRequests, r)
2717 if _, ok := t.requestState[r]; ok {
2718 panic("expected request state to be gone")
2723 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2724 return t.requestState[r].peer
2727 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2728 if t.connsWithAllPieces == nil {
2729 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2731 t.connsWithAllPieces[p] = struct{}{}
2734 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2735 _, ok := t.connsWithAllPieces[p]
2736 delete(t.connsWithAllPieces, p)
2740 func (t *Torrent) numActivePeers() int {
2741 return len(t.conns) + len(t.webSeeds)
2744 func (t *Torrent) hasStorageCap() bool {
2745 f := t.storage.Capacity
2753 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2754 return pieceIndex(ri / t.chunksPerRegularPiece())
2757 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2758 reuseIter *typedRoaring.Iterator[RequestIndex],
2760 f func(RequestIndex),
2762 reuseIter.Initialize(&t.dirtyChunks)
2763 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2764 iterBitmapUnsetInRange(
2766 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2771 type requestState struct {
2776 // Returns an error if a received chunk is out of bounds in someway.
2777 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2779 return errors.New("torrent missing info")
2781 if int(r.Index) >= t.numPieces() {
2782 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2784 pieceLength := t.pieceLength(pieceIndex(r.Index))
2785 if r.Begin >= pieceLength {
2786 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2788 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2789 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2790 // should be considerable checks elsewhere for this case due to the network overhead. We should
2791 // catch most of the overflow manipulation stuff by checking index and begin above.
2795 func (t *Torrent) peerConnsWithDialAddrPort(target netip.AddrPort) (ret []*PeerConn) {
2796 for pc := range t.conns {
2797 dialAddr, err := pc.remoteDialAddrPort()
2801 if dialAddr != target {
2804 ret = append(ret, pc)
2809 func wrapUtHolepunchMsgForPeerConn(
2810 recipient *PeerConn,
2811 msg utHolepunch.Msg,
2813 extendedPayload, err := msg.MarshalBinary()
2819 ExtendedID: MapMustGet(recipient.PeerExtensionIDs, utHolepunch.ExtensionName),
2820 ExtendedPayload: extendedPayload,
2824 func sendUtHolepunchMsg(
2826 msgType utHolepunch.MsgType,
2827 addrPort netip.AddrPort,
2828 errCode utHolepunch.ErrCode,
2830 holepunchMsg := utHolepunch.Msg{
2835 incHolepunchMessagesSent(holepunchMsg)
2836 ppMsg := wrapUtHolepunchMsgForPeerConn(pc, holepunchMsg)
2840 func incHolepunchMessages(msg utHolepunch.Msg, verb string) {
2843 "holepunch %v %v messages %v",
2845 addrPortProtocolStr(msg.AddrPort),
2852 func incHolepunchMessagesReceived(msg utHolepunch.Msg) {
2853 incHolepunchMessages(msg, "received")
2856 func incHolepunchMessagesSent(msg utHolepunch.Msg) {
2857 incHolepunchMessages(msg, "sent")
2860 func (t *Torrent) handleReceivedUtHolepunchMsg(msg utHolepunch.Msg, sender *PeerConn) error {
2861 incHolepunchMessagesReceived(msg)
2862 switch msg.MsgType {
2863 case utHolepunch.Rendezvous:
2864 t.logger.Printf("got holepunch rendezvous request for %v from %p", msg.AddrPort, sender)
2865 sendMsg := sendUtHolepunchMsg
2866 senderAddrPort, err := sender.remoteDialAddrPort()
2868 sender.logger.Levelf(
2870 "error getting ut_holepunch rendezvous sender's dial address: %v",
2873 // There's no better error code. The sender's address itself is invalid. I don't see
2874 // this error message being appropriate anywhere else anyway.
2875 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSuchPeer)
2877 targets := t.peerConnsWithDialAddrPort(msg.AddrPort)
2878 if len(targets) == 0 {
2879 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NotConnected)
2882 for _, pc := range targets {
2883 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2884 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSupport)
2887 sendMsg(sender, utHolepunch.Connect, msg.AddrPort, 0)
2888 sendMsg(pc, utHolepunch.Connect, senderAddrPort, 0)
2891 case utHolepunch.Connect:
2892 holepunchAddr := msg.AddrPort
2893 t.logger.Printf("got holepunch connect request for %v from %p", holepunchAddr, sender)
2894 if g.MapContains(t.cl.undialableWithoutHolepunch, holepunchAddr) {
2895 setAdd(&t.cl.undialableWithoutHolepunchDialedAfterHolepunchConnect, holepunchAddr)
2896 if g.MapContains(t.cl.accepted, holepunchAddr) {
2897 setAdd(&t.cl.probablyOnlyConnectedDueToHolepunch, holepunchAddr)
2900 opts := outgoingConnOpts{
2903 Source: PeerSourceUtHolepunch,
2904 PexPeerFlags: sender.pex.remoteLiveConns[msg.AddrPort].UnwrapOrZeroValue(),
2907 // Don't attempt to start our own rendezvous if we fail to connect.
2908 skipHolepunchRendezvous: true,
2909 receivedHolepunchConnect: true,
2910 // Assume that the other end initiated the rendezvous, and will use our preferred
2911 // encryption. So we will act normally.
2912 HeaderObfuscationPolicy: t.cl.config.HeaderObfuscationPolicy,
2914 initiateConn(opts, true)
2916 case utHolepunch.Error:
2917 torrent.Add("holepunch error messages received", 1)
2918 t.logger.Levelf(log.Debug, "received ut_holepunch error message from %v: %v", sender, msg.ErrCode)
2921 return fmt.Errorf("unhandled msg type %v", msg.MsgType)
2925 func addrPortProtocolStr(addrPort netip.AddrPort) string {
2926 addr := addrPort.Addr()
2937 func (t *Torrent) trySendHolepunchRendezvous(addrPort netip.AddrPort) error {
2939 for pc := range t.conns {
2940 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2943 if pc.supportsExtension(pp.ExtensionNamePex) {
2944 if !g.MapContains(pc.pex.remoteLiveConns, addrPort) {
2948 t.logger.Levelf(log.Debug, "sent ut_holepunch rendezvous message to %v for %v", pc, addrPort)
2949 sendUtHolepunchMsg(pc, utHolepunch.Rendezvous, addrPort, 0)
2953 return errors.New("no eligible relays")
2958 func (t *Torrent) numHalfOpenAttempts() (num int) {
2959 for _, attempts := range t.halfOpen {
2960 num += len(attempts)
2965 func (t *Torrent) getDialTimeoutUnlocked() time.Duration {
2969 return t.dialTimeout()