20 "github.com/RoaringBitmap/roaring"
21 "github.com/anacrolix/chansync"
22 "github.com/anacrolix/chansync/events"
23 "github.com/anacrolix/dht/v2"
24 . "github.com/anacrolix/generics"
25 g "github.com/anacrolix/generics"
26 "github.com/anacrolix/log"
27 "github.com/anacrolix/missinggo/perf"
28 "github.com/anacrolix/missinggo/slices"
29 "github.com/anacrolix/missinggo/v2"
30 "github.com/anacrolix/missinggo/v2/bitmap"
31 "github.com/anacrolix/missinggo/v2/pubsub"
32 "github.com/anacrolix/multiless"
33 "github.com/anacrolix/sync"
34 "github.com/pion/datachannel"
35 "golang.org/x/exp/maps"
37 "github.com/anacrolix/torrent/bencode"
38 "github.com/anacrolix/torrent/common"
39 "github.com/anacrolix/torrent/internal/check"
40 "github.com/anacrolix/torrent/internal/nestedmaps"
41 "github.com/anacrolix/torrent/metainfo"
42 pp "github.com/anacrolix/torrent/peer_protocol"
43 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
44 request_strategy "github.com/anacrolix/torrent/request-strategy"
45 "github.com/anacrolix/torrent/segments"
46 "github.com/anacrolix/torrent/storage"
47 "github.com/anacrolix/torrent/tracker"
48 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
49 "github.com/anacrolix/torrent/webseed"
50 "github.com/anacrolix/torrent/webtorrent"
53 // Maintains state of torrent within a Client. Many methods should not be called before the info is
54 // available, see .Info and .GotInfo.
56 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
57 // alignment. See #262.
62 networkingEnabled chansync.Flag
63 dataDownloadDisallowed chansync.Flag
64 dataUploadDisallowed bool
65 userOnWriteChunkErr func(error)
67 closed chansync.SetOnce
69 infoHash metainfo.Hash
72 // The order pieces are requested if there's no stronger reason like availability or priority.
73 pieceRequestOrder []int
74 // Values are the piece indices that changed.
75 pieceStateChanges pubsub.PubSub[PieceStateChange]
76 // The size of chunks to request from peers over the wire. This is
77 // normally 16KiB by convention these days.
80 // Total length of the torrent in bytes. Stored because it's not O(1) to
81 // get this from the info dict.
84 // The storage to open when the info dict becomes available.
85 storageOpener *storage.Client
86 // Storage for torrent data.
87 storage *storage.Torrent
88 // Read-locked for using storage, and write-locked for Closing.
89 storageLock sync.RWMutex
91 // TODO: Only announce stuff is used?
92 metainfo metainfo.MetaInfo
94 // The info dict. nil if we don't have it (yet).
96 fileIndex segments.Index
99 _chunksPerRegularPiece chunkIndexType
101 webSeeds map[string]*Peer
102 // Active peer connections, running message stream loops. TODO: Make this
103 // open (not-closed) connections only.
104 conns map[*PeerConn]struct{}
105 maxEstablishedConns int
106 // Set of addrs to which we're attempting to connect. Connections are
107 // half-open until all handshakes are completed.
108 halfOpen map[string]map[outgoingConnAttemptKey]*PeerInfo
110 // Reserve of peers to connect to. A peer can be both here and in the
111 // active connections if were told about the peer after connecting with
112 // them. That encourages us to reconnect to peers that are well known in
114 peers prioritizedPeers
115 // Whether we want to know more peers.
116 wantPeersEvent missinggo.Event
117 // An announcer for each tracker URL.
118 trackerAnnouncers map[string]torrentTrackerAnnouncer
119 // How many times we've initiated a DHT announce. TODO: Move into stats.
122 // Name used if the info name isn't available. Should be cleared when the
123 // Info does become available.
127 // The bencoded bytes of the info dict. This is actively manipulated if
128 // the info bytes aren't initially available, and we try to fetch them
131 // Each element corresponds to the 16KiB metadata pieces. If true, we have
132 // received that piece.
133 metadataCompletedChunks []bool
134 metadataChanged sync.Cond
136 // Closed when .Info is obtained.
137 gotMetainfoC chan struct{}
139 readers map[*reader]struct{}
140 _readerNowPieces bitmap.Bitmap
141 _readerReadaheadPieces bitmap.Bitmap
143 // A cache of pieces we need to get. Calculated from various piece and
144 // file priorities and completion states elsewhere.
145 _pendingPieces roaring.Bitmap
146 // A cache of completed piece indices.
147 _completedPieces roaring.Bitmap
148 // Pieces that need to be hashed.
149 piecesQueuedForHash bitmap.Bitmap
150 activePieceHashes int
151 initialPieceCheckDisabled bool
153 connsWithAllPieces map[*Peer]struct{}
155 requestState map[RequestIndex]requestState
156 // Chunks we've written to since the corresponding piece was last checked.
157 dirtyChunks typedRoaring.Bitmap[RequestIndex]
161 // Is On when all pieces are complete.
162 Complete chansync.Flag
164 // Torrent sources in use keyed by the source string.
165 activeSources sync.Map
166 sourcesLogger log.Logger
168 smartBanCache smartBanCache
170 // Large allocations reused between request state updates.
171 requestPieceStates []request_strategy.PieceRequestOrderState
172 requestIndexes []RequestIndex
175 type outgoingConnAttemptKey = *PeerInfo
177 func (t *Torrent) length() int64 {
178 return t._length.Value
181 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
182 // This could be done with roaring.BitSliceIndexing.
183 t.iterPeers(func(peer *Peer) {
184 if _, ok := t.connsWithAllPieces[peer]; ok {
187 if peer.peerHasPiece(i) {
194 func (t *Torrent) decPieceAvailability(i pieceIndex) {
199 if p.relativeAvailability <= 0 {
200 panic(p.relativeAvailability)
202 p.relativeAvailability--
203 t.updatePieceRequestOrder(i)
206 func (t *Torrent) incPieceAvailability(i pieceIndex) {
207 // If we don't the info, this should be reconciled when we do.
210 p.relativeAvailability++
211 t.updatePieceRequestOrder(i)
215 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
216 return t._readerNowPieces
219 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
220 return t._readerReadaheadPieces
223 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
224 return !t.wantPieceIndex(i)
227 // Returns a channel that is closed when the Torrent is closed.
228 func (t *Torrent) Closed() events.Done {
229 return t.closed.Done()
232 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
233 // pending, and half-open peers.
234 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
235 // Add pending peers to the list
236 t.peers.Each(func(peer PeerInfo) {
237 ks = append(ks, peer)
240 // Add half-open peers to the list
241 for _, attempts := range t.halfOpen {
242 for _, peer := range attempts {
243 ks = append(ks, *peer)
247 // Add active peers to the list
248 for conn := range t.conns {
249 ks = append(ks, PeerInfo{
251 Addr: conn.RemoteAddr,
252 Source: conn.Discovery,
253 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
254 // > But if we're not connected to them with an encrypted connection, I couldn't say
255 // > what's appropriate. We can carry forward the SupportsEncryption value as we
256 // > received it from trackers/DHT/PEX, or just use the encryption state for the
257 // > connection. It's probably easiest to do the latter for now.
258 // https://github.com/anacrolix/torrent/pull/188
259 SupportsEncryption: conn.headerEncrypted,
266 func (t *Torrent) setChunkSize(size pp.Integer) {
268 t.chunkPool = sync.Pool{
269 New: func() interface{} {
270 b := make([]byte, size)
276 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
277 return t._completedPieces.Contains(bitmap.BitIndex(piece))
280 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
281 if t.storage == nil {
282 return storage.Completion{Complete: false, Ok: true}
284 return t.pieces[piece].Storage().Completion()
287 // There's a connection to that address already.
288 func (t *Torrent) addrActive(addr string) bool {
289 if _, ok := t.halfOpen[addr]; ok {
292 for c := range t.conns {
294 if ra.String() == addr {
301 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
302 return t.appendConns(ret, func(conn *PeerConn) bool {
303 return !conn.closed.IsSet()
307 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
308 for c := range t.conns {
316 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
318 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
319 if t.closed.IsSet() {
322 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
323 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
324 torrent.Add("peers not added because of bad addr", 1)
325 // cl.logger.Printf("peers not added because of bad addr: %v", p)
329 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
330 torrent.Add("peers replaced", 1)
331 if !replaced.equal(p) {
332 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
339 for t.peers.Len() > cl.config.TorrentPeersHighWater {
340 _, ok := t.peers.DeleteMin()
342 torrent.Add("excess reserve peers discarded", 1)
348 func (t *Torrent) invalidateMetadata() {
349 for i := 0; i < len(t.metadataCompletedChunks); i++ {
350 t.metadataCompletedChunks[i] = false
353 t.gotMetainfoC = make(chan struct{})
358 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
362 if index >= len(t.metadataCompletedChunks) {
363 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
366 copy(t.metadataBytes[(1<<14)*index:], data)
367 t.metadataCompletedChunks[index] = true
370 func (t *Torrent) metadataPieceCount() int {
371 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
374 func (t *Torrent) haveMetadataPiece(piece int) bool {
376 return (1<<14)*piece < len(t.metadataBytes)
378 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
382 func (t *Torrent) metadataSize() int {
383 return len(t.metadataBytes)
386 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
387 for i := 0; i < len(info.Pieces); i += sha1.Size {
388 ret = append(ret, info.Pieces[i:i+sha1.Size])
393 func (t *Torrent) makePieces() {
394 hashes := infoPieceHashes(t.info)
395 t.pieces = make([]Piece, len(hashes))
396 for i, hash := range hashes {
397 piece := &t.pieces[i]
399 piece.index = pieceIndex(i)
400 piece.noPendingWrites.L = &piece.pendingWritesMutex
401 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
403 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
404 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
405 piece.files = files[beginFile:endFile]
409 // Returns the index of the first file containing the piece. files must be
410 // ordered by offset.
411 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
412 for i, f := range files {
413 if f.offset+f.length > pieceOffset {
420 // Returns the index after the last file containing the piece. files must be
421 // ordered by offset.
422 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
423 for i, f := range files {
424 if f.offset+f.length >= pieceEndOffset {
431 func (t *Torrent) cacheLength() {
433 for _, f := range t.info.UpvertedFiles() {
439 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
441 func (t *Torrent) setInfo(info *metainfo.Info) error {
442 if err := validateInfo(info); err != nil {
443 return fmt.Errorf("bad info: %s", err)
445 if t.storageOpener != nil {
447 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
449 return fmt.Errorf("error opening torrent storage: %s", err)
455 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
457 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
458 t.displayName = "" // Save a few bytes lol.
465 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
466 return request_strategy.PieceRequestOrderKey{
467 InfoHash: t.infoHash,
472 // This seems to be all the follow-up tasks after info is set, that can't fail.
473 func (t *Torrent) onSetInfo() {
474 t.pieceRequestOrder = rand.Perm(t.numPieces())
475 t.initPieceRequestOrder()
476 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
477 for i := range t.pieces {
479 // Need to add relativeAvailability before updating piece completion, as that may result in conns
481 if p.relativeAvailability != 0 {
482 panic(p.relativeAvailability)
484 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
485 t.addRequestOrderPiece(i)
486 t.updatePieceCompletion(i)
487 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
488 // t.logger.Printf("piece %s completion unknown, queueing check", p)
492 t.cl.event.Broadcast()
493 close(t.gotMetainfoC)
494 t.updateWantPeersEvent()
495 t.requestState = make(map[RequestIndex]requestState)
496 t.tryCreateMorePieceHashers()
497 t.iterPeers(func(p *Peer) {
499 p.updateRequests("onSetInfo")
503 // Called when metadata for a torrent becomes available.
504 func (t *Torrent) setInfoBytesLocked(b []byte) error {
505 if metainfo.HashBytes(b) != t.infoHash {
506 return errors.New("info bytes have wrong hash")
508 var info metainfo.Info
509 if err := bencode.Unmarshal(b, &info); err != nil {
510 return fmt.Errorf("error unmarshalling info bytes: %s", err)
513 t.metadataCompletedChunks = nil
517 if err := t.setInfo(&info); err != nil {
524 func (t *Torrent) haveAllMetadataPieces() bool {
528 if t.metadataCompletedChunks == nil {
531 for _, have := range t.metadataCompletedChunks {
539 // TODO: Propagate errors to disconnect peer.
540 func (t *Torrent) setMetadataSize(size int) (err error) {
542 // We already know the correct metadata size.
545 if uint32(size) > maxMetadataSize {
546 return log.WithLevel(log.Warning, errors.New("bad size"))
548 if len(t.metadataBytes) == size {
551 t.metadataBytes = make([]byte, size)
552 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
553 t.metadataChanged.Broadcast()
554 for c := range t.conns {
555 c.requestPendingMetadata()
560 // The current working name for the torrent. Either the name in the info dict,
561 // or a display name given such as by the dn value in a magnet link, or "".
562 func (t *Torrent) name() string {
564 defer t.nameMu.RUnlock()
566 return t.info.BestName()
568 if t.displayName != "" {
571 return "infohash:" + t.infoHash.HexString()
574 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
575 p := &t.pieces[index]
576 ret.Priority = t.piecePriority(index)
577 ret.Completion = p.completion()
578 ret.QueuedForHash = p.queuedForHash()
579 ret.Hashing = p.hashing
580 ret.Checking = ret.QueuedForHash || ret.Hashing
581 ret.Marking = p.marking
582 if !ret.Complete && t.piecePartiallyDownloaded(index) {
588 func (t *Torrent) metadataPieceSize(piece int) int {
589 return metadataPieceSize(len(t.metadataBytes), piece)
592 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
595 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
596 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
598 TotalSize: len(t.metadataBytes),
604 type pieceAvailabilityRun struct {
609 func (me pieceAvailabilityRun) String() string {
610 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
613 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
614 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
615 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
617 for i := range t.pieces {
618 rle.Append(t.pieces[i].availability(), 1)
624 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
625 freqs = make([]int, t.numActivePeers()+1)
626 for i := range t.pieces {
627 freqs[t.piece(i).availability()]++
632 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
633 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
634 ret = append(ret, PieceStateRun{
635 PieceState: el.(PieceState),
639 for index := range t.pieces {
640 rle.Append(t.pieceState(pieceIndex(index)), 1)
646 // Produces a small string representing a PieceStateRun.
647 func (psr PieceStateRun) String() (ret string) {
648 ret = fmt.Sprintf("%d", psr.Length)
649 ret += func() string {
650 switch psr.Priority {
651 case PiecePriorityNext:
653 case PiecePriorityNormal:
655 case PiecePriorityReadahead:
657 case PiecePriorityNow:
659 case PiecePriorityHigh:
668 if psr.QueuedForHash {
686 func (t *Torrent) writeStatus(w io.Writer) {
687 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
688 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
690 fmt.Fprintf(w, "Metadata have: ")
691 for _, h := range t.metadataCompletedChunks {
692 fmt.Fprintf(w, "%c", func() rune {
702 fmt.Fprintf(w, "Piece length: %s\n",
705 return fmt.Sprintf("%v (%v chunks)",
707 float64(t.usualPieceSize())/float64(t.chunkSize))
714 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
715 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
716 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
717 // availability frequencies instead.
719 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
720 for _, run := range t.pieceAvailabilityRuns() {
721 ret = append(ret, run.String())
726 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
727 func() (ret []string) {
728 for avail, freq := range t.pieceAvailabilityFrequencies() {
732 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
738 fmt.Fprintf(w, "Reader Pieces:")
739 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
740 fmt.Fprintf(w, " %d:%d", begin, end)
745 fmt.Fprintf(w, "Enabled trackers:\n")
747 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
748 fmt.Fprintf(tw, " URL\tExtra\n")
749 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
752 var luns, runs url.URL = *lu, *ru
755 var ml missinggo.MultiLess
756 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
757 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
759 }).([]torrentTrackerAnnouncer) {
760 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
765 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
767 dumpStats(w, t.statsLocked())
769 fmt.Fprintf(w, "webseeds:\n")
770 t.writePeerStatuses(w, maps.Values(t.webSeeds))
772 peerConns := maps.Keys(t.conns)
773 // Peers without priorities first, then those with. I'm undecided about how to order peers
774 // without priorities.
775 sort.Slice(peerConns, func(li, ri int) bool {
778 ml := multiless.New()
779 lpp := g.ResultFromTuple(l.peerPriority()).ToOption()
780 rpp := g.ResultFromTuple(r.peerPriority()).ToOption()
781 ml = ml.Bool(lpp.Ok, rpp.Ok)
782 ml = ml.Uint32(rpp.Value, lpp.Value)
786 fmt.Fprintf(w, "%v peer conns:\n", len(peerConns))
787 t.writePeerStatuses(w, g.SliceMap(peerConns, func(pc *PeerConn) *Peer {
792 func (t *Torrent) writePeerStatuses(w io.Writer, peers []*Peer) {
794 for _, c := range peers {
798 w.Write(bytes.TrimRight(
799 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
804 func (t *Torrent) haveInfo() bool {
808 // Returns a run-time generated MetaInfo that includes the info bytes and
809 // announce-list as currently known to the client.
810 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
811 return metainfo.MetaInfo{
812 CreationDate: time.Now().Unix(),
813 Comment: "dynamic metainfo from client",
814 CreatedBy: "go.torrent",
815 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
816 InfoBytes: func() []byte {
818 return t.metadataBytes
823 UrlList: func() []string {
824 ret := make([]string, 0, len(t.webSeeds))
825 for url := range t.webSeeds {
826 ret = append(ret, url)
833 // Returns a count of bytes that are not complete in storage, and not pending being written to
834 // storage. This value is from the perspective of the download manager, and may not agree with the
835 // actual state in storage. If you want read data synchronously you should use a Reader. See
836 // https://github.com/anacrolix/torrent/issues/828.
837 func (t *Torrent) BytesMissing() (n int64) {
839 n = t.bytesMissingLocked()
844 func (t *Torrent) bytesMissingLocked() int64 {
848 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
849 roaring.Flip(b, 0, end).Iterate(cb)
852 func (t *Torrent) bytesLeft() (left int64) {
853 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
854 p := t.piece(pieceIndex(x))
855 left += int64(p.length() - p.numDirtyBytes())
861 // Bytes left to give in tracker announces.
862 func (t *Torrent) bytesLeftAnnounce() int64 {
870 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
871 if t.pieceComplete(piece) {
874 if t.pieceAllDirty(piece) {
877 return t.pieces[piece].hasDirtyChunks()
880 func (t *Torrent) usualPieceSize() int {
881 return int(t.info.PieceLength)
884 func (t *Torrent) numPieces() pieceIndex {
885 return t.info.NumPieces()
888 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
889 return pieceIndex(t._completedPieces.GetCardinality())
892 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
894 err = errors.New("already closed")
897 for _, f := range t.onClose {
900 if t.storage != nil {
905 defer t.storageLock.Unlock()
906 if f := t.storage.Close; f != nil {
909 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
914 t.iterPeers(func(p *Peer) {
917 if t.storage != nil {
918 t.deletePieceRequestOrder()
920 t.assertAllPiecesRelativeAvailabilityZero()
922 t.cl.event.Broadcast()
923 t.pieceStateChanges.Close()
924 t.updateWantPeersEvent()
928 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
929 for i := range t.pieces {
931 if p.relativeAvailability != 0 {
932 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
937 func (t *Torrent) requestOffset(r Request) int64 {
938 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
941 // Return the request that would include the given offset into the torrent data. Returns !ok if
942 // there is no such request.
943 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
944 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
947 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
948 defer perf.ScopeTimerErr(&err)()
949 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
950 if err == nil && n != len(data) {
951 err = io.ErrShortWrite
956 func (t *Torrent) bitfield() (bf []bool) {
957 bf = make([]bool, t.numPieces())
958 t._completedPieces.Iterate(func(piece uint32) (again bool) {
965 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
966 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
969 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
970 return t._chunksPerRegularPiece
973 func (t *Torrent) numChunks() RequestIndex {
974 if t.numPieces() == 0 {
977 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
980 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
981 t.dirtyChunks.RemoveRange(
982 uint64(t.pieceRequestIndexOffset(pieceIndex)),
983 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
986 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
987 if t.info.PieceLength == 0 {
988 // There will be no variance amongst pieces. Only pain.
991 if piece == t.numPieces()-1 {
992 ret := pp.Integer(t.length() % t.info.PieceLength)
997 return pp.Integer(t.info.PieceLength)
1000 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
1001 return &blockCheckingWriter{
1002 cache: &t.smartBanCache,
1003 requestIndex: t.pieceRequestIndexOffset(piece),
1004 chunkSize: t.chunkSize.Int(),
1008 func (t *Torrent) hashPiece(piece pieceIndex) (
1010 // These are peers that sent us blocks that differ from what we hash here.
1011 differingPeers map[bannableAddr]struct{},
1015 p.waitNoPendingWrites()
1016 storagePiece := t.pieces[piece].Storage()
1018 // Does the backend want to do its own hashing?
1019 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
1020 var sum metainfo.Hash
1021 // log.Printf("A piece decided to self-hash: %d", piece)
1022 sum, err = i.SelfHash()
1023 missinggo.CopyExact(&ret, sum)
1027 hash := pieceHash.New()
1028 const logPieceContents = false
1029 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1030 writers := []io.Writer{hash, smartBanWriter}
1031 var examineBuf bytes.Buffer
1032 if logPieceContents {
1033 writers = append(writers, &examineBuf)
1035 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1036 if logPieceContents {
1037 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1039 smartBanWriter.Flush()
1040 differingPeers = smartBanWriter.badPeers
1041 missinggo.CopyExact(&ret, hash.Sum(nil))
1045 func (t *Torrent) haveAnyPieces() bool {
1046 return !t._completedPieces.IsEmpty()
1049 func (t *Torrent) haveAllPieces() bool {
1053 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1056 func (t *Torrent) havePiece(index pieceIndex) bool {
1057 return t.haveInfo() && t.pieceComplete(index)
1060 func (t *Torrent) maybeDropMutuallyCompletePeer(
1061 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1065 if !t.cl.config.DropMutuallyCompletePeers {
1068 if !t.haveAllPieces() {
1071 if all, known := p.peerHasAllPieces(); !(known && all) {
1077 p.logger.Levelf(log.Debug, "is mutually complete; dropping")
1081 func (t *Torrent) haveChunk(r Request) (ret bool) {
1083 // log.Println("have chunk", r, ret)
1088 if t.pieceComplete(pieceIndex(r.Index)) {
1091 p := &t.pieces[r.Index]
1092 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1095 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1096 return chunkIndexType(cs.Begin / chunkSize)
1099 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1100 return t._pendingPieces.Contains(uint32(index))
1103 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1104 // conns (which is a map).
1105 var peerConnSlices sync.Pool
1107 func getPeerConnSlice(cap int) []*PeerConn {
1108 getInterface := peerConnSlices.Get()
1109 if getInterface == nil {
1110 return make([]*PeerConn, 0, cap)
1112 return getInterface.([]*PeerConn)[:0]
1116 // Calls the given function with a slice of unclosed conns. It uses a pool to reduce allocations as
1117 // this is a frequent occurrence.
1118 func (t *Torrent) withUnclosedConns(f func([]*PeerConn)) {
1119 sl := t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))
1121 peerConnSlices.Put(sl)
1124 func (t *Torrent) worstBadConnFromSlice(opts worseConnLensOpts, sl []*PeerConn) *PeerConn {
1125 wcs := worseConnSlice{conns: sl}
1128 for wcs.Len() != 0 {
1129 c := heap.Pop(&wcs).(*PeerConn)
1130 if opts.incomingIsBad && !c.outgoing {
1133 if opts.outgoingIsBad && c.outgoing {
1136 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1139 // If the connection is in the worst half of the established
1140 // connection quota and is older than a minute.
1141 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1142 // Give connections 1 minute to prove themselves.
1143 if time.Since(c.completedHandshake) > time.Minute {
1151 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1152 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1153 // established connections for more than a minute. This is O(n log n). If there was a way to not
1154 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1155 func (t *Torrent) worstBadConn(opts worseConnLensOpts) (ret *PeerConn) {
1156 t.withUnclosedConns(func(ucs []*PeerConn) {
1157 ret = t.worstBadConnFromSlice(opts, ucs)
1162 type PieceStateChange struct {
1167 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1168 t.cl._mu.Defer(func() {
1169 cur := t.pieceState(piece)
1170 p := &t.pieces[piece]
1171 if cur != p.publicPieceState {
1172 p.publicPieceState = cur
1173 t.pieceStateChanges.Publish(PieceStateChange{
1181 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1182 if t.pieceComplete(piece) {
1185 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1188 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1189 return t.pieces[piece].allChunksDirty()
1192 func (t *Torrent) readersChanged() {
1193 t.updateReaderPieces()
1194 t.updateAllPiecePriorities("Torrent.readersChanged")
1197 func (t *Torrent) updateReaderPieces() {
1198 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1201 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1205 t.updateReaderPieces()
1206 // Order the ranges, high and low.
1208 if l.begin > h.begin {
1211 if l.end < h.begin {
1212 // Two distinct ranges.
1213 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1214 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1221 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1225 func (t *Torrent) maybeNewConns() {
1226 // Tickle the accept routine.
1227 t.cl.event.Broadcast()
1231 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1232 if t._pendingPieces.Contains(uint32(piece)) {
1233 t.iterPeers(func(c *Peer) {
1234 // if c.requestState.Interested {
1237 if !c.isLowOnRequests() {
1240 if !c.peerHasPiece(piece) {
1243 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1246 c.updateRequests(reason)
1250 t.publishPieceChange(piece)
1253 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1254 if !t.closed.IsSet() {
1255 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1257 t.updatePieceRequestOrder(piece)
1259 p := &t.pieces[piece]
1260 newPrio := p.uncachedPriority()
1261 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1262 if newPrio == PiecePriorityNone {
1263 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1267 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1271 t.piecePriorityChanged(piece, reason)
1274 func (t *Torrent) updateAllPiecePriorities(reason string) {
1275 t.updatePiecePriorities(0, t.numPieces(), reason)
1278 // Update all piece priorities in one hit. This function should have the same
1279 // output as updatePiecePriority, but across all pieces.
1280 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1281 for i := begin; i < end; i++ {
1282 t.updatePiecePriority(i, reason)
1286 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1287 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1288 if off >= t.length() {
1298 begin = pieceIndex(off / t.info.PieceLength)
1299 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1300 if end > pieceIndex(t.info.NumPieces()) {
1301 end = pieceIndex(t.info.NumPieces())
1306 // Returns true if all iterations complete without breaking. Returns the read regions for all
1307 // readers. The reader regions should not be merged as some callers depend on this method to
1308 // enumerate readers.
1309 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1310 for r := range t.readers {
1312 if p.begin >= p.end {
1315 if !f(p.begin, p.end) {
1322 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1323 return t.piece(piece).uncachedPriority()
1326 func (t *Torrent) pendRequest(req RequestIndex) {
1327 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1330 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1331 t.cl.event.Broadcast()
1332 if t.pieceComplete(piece) {
1333 t.onPieceCompleted(piece)
1335 t.onIncompletePiece(piece)
1337 t.updatePiecePriority(piece, reason)
1340 func (t *Torrent) numReceivedConns() (ret int) {
1341 for c := range t.conns {
1342 if c.Discovery == PeerSourceIncoming {
1349 func (t *Torrent) numOutgoingConns() (ret int) {
1350 for c := range t.conns {
1358 func (t *Torrent) maxHalfOpen() int {
1359 // Note that if we somehow exceed the maximum established conns, we want
1360 // the negative value to have an effect.
1361 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1362 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1363 // We want to allow some experimentation with new peers, and to try to
1364 // upset an oversupply of received connections.
1366 max(5, extraIncoming)+establishedHeadroom,
1367 int64(t.cl.config.HalfOpenConnsPerTorrent),
1371 func (t *Torrent) openNewConns() (initiated int) {
1372 defer t.updateWantPeersEvent()
1373 for t.peers.Len() != 0 {
1374 if !t.wantOutgoingConns() {
1377 if len(t.halfOpen) >= t.maxHalfOpen() {
1380 if len(t.cl.dialers) == 0 {
1383 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1386 p := t.peers.PopMax()
1387 opts := outgoingConnOpts{
1390 requireRendezvous: false,
1391 skipHolepunchRendezvous: false,
1392 receivedHolepunchConnect: false,
1393 HeaderObfuscationPolicy: t.cl.config.HeaderObfuscationPolicy,
1395 initiateConn(opts, false)
1401 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1403 uncached := t.pieceCompleteUncached(piece)
1404 cached := p.completion()
1405 changed := cached != uncached
1406 complete := uncached.Complete
1407 p.storageCompletionOk = uncached.Ok
1410 t._completedPieces.Add(x)
1413 t._completedPieces.Remove(x)
1415 p.t.updatePieceRequestOrder(piece)
1417 if complete && len(p.dirtiers) != 0 {
1418 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1421 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1422 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1427 // Non-blocking read. Client lock is not required.
1428 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1430 p := &t.pieces[off/t.info.PieceLength]
1431 p.waitNoPendingWrites()
1433 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1444 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1445 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1446 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1447 func (t *Torrent) maybeCompleteMetadata() error {
1452 if !t.haveAllMetadataPieces() {
1453 // Don't have enough metadata pieces.
1456 err := t.setInfoBytesLocked(t.metadataBytes)
1458 t.invalidateMetadata()
1459 return fmt.Errorf("error setting info bytes: %s", err)
1461 if t.cl.config.Debug {
1462 t.logger.Printf("%s: got metadata from peers", t)
1467 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1468 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1470 now.Add(bitmap.BitIndex(begin))
1471 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1478 func (t *Torrent) needData() bool {
1479 if t.closed.IsSet() {
1485 return !t._pendingPieces.IsEmpty()
1488 func appendMissingStrings(old, new []string) (ret []string) {
1491 for _, n := range new {
1492 for _, o := range old {
1497 ret = append(ret, n)
1502 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1504 for minNumTiers > len(ret) {
1505 ret = append(ret, nil)
1510 func (t *Torrent) addTrackers(announceList [][]string) {
1511 fullAnnounceList := &t.metainfo.AnnounceList
1512 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1513 for tierIndex, trackerURLs := range announceList {
1514 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1516 t.startMissingTrackerScrapers()
1517 t.updateWantPeersEvent()
1520 // Don't call this before the info is available.
1521 func (t *Torrent) bytesCompleted() int64 {
1525 return t.length() - t.bytesLeft()
1528 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1531 return t.setInfoBytesLocked(b)
1534 // Returns true if connection is removed from torrent.Conns.
1535 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1536 if !c.closed.IsSet() {
1537 panic("connection is not closed")
1538 // There are behaviours prevented by the closed state that will fail
1539 // if the connection has been deleted.
1543 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1544 // the drop event against the PexConnState instead.
1546 if !t.cl.config.DisablePEX {
1550 torrent.Add("deleted connections", 1)
1551 c.deleteAllRequests("Torrent.deletePeerConn")
1552 t.assertPendingRequests()
1553 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1554 panic(t.connsWithAllPieces)
1559 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1560 if t.deleteConnWithAllPieces(p) {
1566 p.peerPieces().Iterate(func(i uint32) bool {
1567 p.t.decPieceAvailability(pieceIndex(i))
1572 func (t *Torrent) assertPendingRequests() {
1576 // var actual pendingRequests
1577 // if t.haveInfo() {
1578 // actual.m = make([]int, t.numChunks())
1580 // t.iterPeers(func(p *Peer) {
1581 // p.requestState.Requests.Iterate(func(x uint32) bool {
1586 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1592 func (t *Torrent) dropConnection(c *PeerConn) {
1593 t.cl.event.Broadcast()
1595 if t.deletePeerConn(c) {
1600 // Peers as in contact information for dialing out.
1601 func (t *Torrent) wantPeers() bool {
1602 if t.closed.IsSet() {
1605 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1608 return t.wantOutgoingConns()
1611 func (t *Torrent) updateWantPeersEvent() {
1613 t.wantPeersEvent.Set()
1615 t.wantPeersEvent.Clear()
1619 // Returns whether the client should make effort to seed the torrent.
1620 func (t *Torrent) seeding() bool {
1622 if t.closed.IsSet() {
1625 if t.dataUploadDisallowed {
1628 if cl.config.NoUpload {
1631 if !cl.config.Seed {
1634 if cl.config.DisableAggressiveUpload && t.needData() {
1640 func (t *Torrent) onWebRtcConn(
1641 c datachannel.ReadWriteCloser,
1642 dcc webtorrent.DataChannelContext,
1645 netConn := webrtcNetConn{
1647 DataChannelContext: dcc,
1649 peerRemoteAddr := netConn.RemoteAddr()
1650 //t.logger.Levelf(log.Critical, "onWebRtcConn remote addr: %v", peerRemoteAddr)
1651 if t.cl.badPeerAddr(peerRemoteAddr) {
1654 localAddrIpPort := missinggo.IpPortFromNetAddr(netConn.LocalAddr())
1655 pc, err := t.cl.initiateProtocolHandshakes(
1656 context.Background(),
1661 outgoing: dcc.LocalOffered,
1662 remoteAddr: peerRemoteAddr,
1663 localPublicAddr: localAddrIpPort,
1664 network: webrtcNetwork,
1665 connString: fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1669 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1672 if dcc.LocalOffered {
1673 pc.Discovery = PeerSourceTracker
1675 pc.Discovery = PeerSourceIncoming
1677 pc.conn.SetWriteDeadline(time.Time{})
1680 err = t.cl.runHandshookConn(pc, t)
1682 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1686 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1687 err := t.cl.runHandshookConn(pc, t)
1688 if err != nil || logAll {
1689 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1693 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1694 t.logRunHandshookConn(pc, false, log.Debug)
1697 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1698 wtc, release := t.cl.websocketTrackers.Get(u.String(), t.infoHash)
1699 // This needs to run before the Torrent is dropped from the Client, to prevent a new webtorrent.TrackerClient for
1700 // the same info hash before the old one is cleaned up.
1701 t.onClose = append(t.onClose, release)
1702 wst := websocketTrackerStatus{u, wtc}
1704 err := wtc.Announce(tracker.Started, t.infoHash)
1706 t.logger.WithDefaultLevel(log.Warning).Printf(
1707 "error in initial announce to %q: %v",
1715 func (t *Torrent) startScrapingTracker(_url string) {
1719 u, err := url.Parse(_url)
1721 // URLs with a leading '*' appear to be a uTorrent convention to disable trackers.
1723 t.logger.Levelf(log.Warning, "error parsing tracker url: %v", err)
1727 if u.Scheme == "udp" {
1729 t.startScrapingTracker(u.String())
1731 t.startScrapingTracker(u.String())
1734 if _, ok := t.trackerAnnouncers[_url]; ok {
1737 sl := func() torrentTrackerAnnouncer {
1740 if t.cl.config.DisableWebtorrent {
1743 return t.startWebsocketAnnouncer(*u)
1745 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1749 if t.cl.config.DisableIPv6 {
1753 newAnnouncer := &trackerScraper{
1756 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1758 go newAnnouncer.Run()
1764 if t.trackerAnnouncers == nil {
1765 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1767 t.trackerAnnouncers[_url] = sl
1770 // Adds and starts tracker scrapers for tracker URLs that aren't already
1772 func (t *Torrent) startMissingTrackerScrapers() {
1773 if t.cl.config.DisableTrackers {
1776 t.startScrapingTracker(t.metainfo.Announce)
1777 for _, tier := range t.metainfo.AnnounceList {
1778 for _, url := range tier {
1779 t.startScrapingTracker(url)
1784 // Returns an AnnounceRequest with fields filled out to defaults and current
1786 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1787 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1788 // dependent on the network in use.
1789 return tracker.AnnounceRequest{
1791 NumWant: func() int32 {
1792 if t.wantPeers() && len(t.cl.dialers) > 0 {
1793 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1798 Port: uint16(t.cl.incomingPeerPort()),
1799 PeerId: t.cl.peerID,
1800 InfoHash: t.infoHash,
1801 Key: t.cl.announceKey(),
1803 // The following are vaguely described in BEP 3.
1805 Left: t.bytesLeftAnnounce(),
1806 Uploaded: t.stats.BytesWrittenData.Int64(),
1807 // There's no mention of wasted or unwanted download in the BEP.
1808 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1812 // Adds peers revealed in an announce until the announce ends, or we have
1814 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1816 for v := range pvs {
1819 for _, cp := range v.Peers {
1821 // Can't do anything with this.
1824 if t.addPeer(PeerInfo{
1825 Addr: ipPortAddr{cp.IP, cp.Port},
1826 Source: PeerSourceDhtGetPeers,
1833 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1838 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1839 // announce ends. stop will force the announce to end.
1840 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1841 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1845 _done := make(chan struct{})
1849 t.consumeDhtAnnouncePeers(ps.Peers())
1855 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1856 _, stop, err := t.AnnounceToDht(s)
1861 case <-t.closed.Done():
1862 case <-time.After(5 * time.Minute):
1868 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1874 if t.closed.IsSet() {
1877 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1878 // TODO: We can include the announce_peer step depending on whether we can receive
1879 // inbound connections. We should probably only announce once every 15 mins too.
1880 if !t.wantAnyConns() {
1883 // TODO: Determine if there's a listener on the port we're announcing.
1884 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1895 err := t.timeboxedAnnounceToDht(s)
1897 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1903 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1904 for _, p := range peers {
1912 // The returned TorrentStats may require alignment in memory. See
1913 // https://github.com/anacrolix/torrent/issues/383.
1914 func (t *Torrent) Stats() TorrentStats {
1916 defer t.cl.rUnlock()
1917 return t.statsLocked()
1920 func (t *Torrent) statsLocked() (ret TorrentStats) {
1921 ret.ActivePeers = len(t.conns)
1922 ret.HalfOpenPeers = len(t.halfOpen)
1923 ret.PendingPeers = t.peers.Len()
1924 ret.TotalPeers = t.numTotalPeers()
1925 ret.ConnectedSeeders = 0
1926 for c := range t.conns {
1927 if all, ok := c.peerHasAllPieces(); all && ok {
1928 ret.ConnectedSeeders++
1931 ret.ConnStats = t.stats.Copy()
1932 ret.PiecesComplete = t.numPiecesCompleted()
1936 // The total number of peers in the torrent.
1937 func (t *Torrent) numTotalPeers() int {
1938 peers := make(map[string]struct{})
1939 for conn := range t.conns {
1940 ra := conn.conn.RemoteAddr()
1942 // It's been closed and doesn't support RemoteAddr.
1945 peers[ra.String()] = struct{}{}
1947 for addr := range t.halfOpen {
1948 peers[addr] = struct{}{}
1950 t.peers.Each(func(peer PeerInfo) {
1951 peers[peer.Addr.String()] = struct{}{}
1956 // Reconcile bytes transferred before connection was associated with a
1958 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1959 if c._stats != (ConnStats{
1960 // Handshakes should only increment these fields:
1961 BytesWritten: c._stats.BytesWritten,
1962 BytesRead: c._stats.BytesRead,
1966 c.postHandshakeStats(func(cs *ConnStats) {
1967 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1968 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1970 c.reconciledHandshakeStats = true
1973 // Returns true if the connection is added.
1974 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1977 torrent.Add("added connections", 1)
1980 if t.closed.IsSet() {
1981 return errors.New("torrent closed")
1983 for c0 := range t.conns {
1984 if c.PeerID != c0.PeerID {
1987 if !t.cl.config.DropDuplicatePeerIds {
1990 if c.hasPreferredNetworkOver(c0) {
1992 t.deletePeerConn(c0)
1994 return errors.New("existing connection preferred")
1997 if len(t.conns) >= t.maxEstablishedConns {
1998 numOutgoing := t.numOutgoingConns()
1999 numIncoming := len(t.conns) - numOutgoing
2000 c := t.worstBadConn(worseConnLensOpts{
2001 // We've already established that we have too many connections at this point, so we just
2002 // need to match what kind we have too many of vs. what we're trying to add now.
2003 incomingIsBad: (numIncoming-numOutgoing > 1) && c.outgoing,
2004 outgoingIsBad: (numOutgoing-numIncoming > 1) && !c.outgoing,
2007 return errors.New("don't want conn")
2012 if len(t.conns) >= t.maxEstablishedConns {
2015 t.conns[c] = struct{}{}
2016 t.cl.event.Broadcast()
2017 // We'll never receive the "p" extended handshake parameter.
2018 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
2024 func (t *Torrent) newConnsAllowed() bool {
2025 if !t.networkingEnabled.Bool() {
2028 if t.closed.IsSet() {
2031 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2037 func (t *Torrent) wantAnyConns() bool {
2038 if !t.networkingEnabled.Bool() {
2041 if t.closed.IsSet() {
2044 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2047 return len(t.conns) < t.maxEstablishedConns
2050 func (t *Torrent) wantOutgoingConns() bool {
2051 if !t.newConnsAllowed() {
2054 if len(t.conns) < t.maxEstablishedConns {
2057 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2058 return t.worstBadConn(worseConnLensOpts{
2059 incomingIsBad: numIncomingConns-t.numOutgoingConns() > 1,
2060 outgoingIsBad: false,
2064 func (t *Torrent) wantIncomingConns() bool {
2065 if !t.newConnsAllowed() {
2068 if len(t.conns) < t.maxEstablishedConns {
2071 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2072 return t.worstBadConn(worseConnLensOpts{
2073 incomingIsBad: false,
2074 outgoingIsBad: t.numOutgoingConns()-numIncomingConns > 1,
2078 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
2081 oldMax = t.maxEstablishedConns
2082 t.maxEstablishedConns = max
2083 wcs := worseConnSlice{
2084 conns: t.appendConns(nil, func(*PeerConn) bool {
2088 wcs.initKeys(worseConnLensOpts{})
2090 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
2091 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
2097 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
2098 t.logger.LazyLog(log.Debug, func() log.Msg {
2099 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
2103 t.cl.event.Broadcast()
2104 if t.closed.IsSet() {
2108 // Don't score the first time a piece is hashed, it could be an initial check.
2109 if p.storageCompletionOk {
2111 pieceHashedCorrect.Add(1)
2114 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
2115 ).AddValues(t, p).LogLevel(
2117 log.Debug, t.logger)
2119 pieceHashedNotCorrect.Add(1)
2124 t.publishPieceChange(piece)
2127 t.publishPieceChange(piece)
2131 if len(p.dirtiers) != 0 {
2132 // Don't increment stats above connection-level for every involved connection.
2133 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2135 for c := range p.dirtiers {
2136 c._stats.incrementPiecesDirtiedGood()
2138 t.clearPieceTouchers(piece)
2139 hasDirty := p.hasDirtyChunks()
2142 p.Flush() // You can be synchronous here!
2144 err := p.Storage().MarkComplete()
2146 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2150 if t.closed.IsSet() {
2153 t.pendAllChunkSpecs(piece)
2155 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2156 // Peers contributed to all the data for this piece hash failure, and the failure was
2157 // not due to errors in the storage (such as data being dropped in a cache).
2159 // Increment Torrent and above stats, and then specific connections.
2160 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2161 for c := range p.dirtiers {
2162 // Y u do dis peer?!
2163 c.stats().incrementPiecesDirtiedBad()
2166 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2167 for c := range p.dirtiers {
2169 bannableTouchers = append(bannableTouchers, c)
2172 t.clearPieceTouchers(piece)
2173 slices.Sort(bannableTouchers, connLessTrusted)
2175 if t.cl.config.Debug {
2177 "bannable conns by trust for piece %d: %v",
2179 func() (ret []connectionTrust) {
2180 for _, c := range bannableTouchers {
2181 ret = append(ret, c.trust())
2188 if len(bannableTouchers) >= 1 {
2189 c := bannableTouchers[0]
2190 if len(bannableTouchers) != 1 {
2191 t.logger.Levelf(log.Debug, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2193 // Turns out it's still useful to ban peers like this because if there's only a
2194 // single peer for a piece, and we never progress that piece to completion, we
2195 // will never smart-ban them. Discovered in
2196 // https://github.com/anacrolix/torrent/issues/715.
2197 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2202 t.onIncompletePiece(piece)
2203 p.Storage().MarkNotComplete()
2205 t.updatePieceCompletion(piece)
2208 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2209 start := t.pieceRequestIndexOffset(piece)
2210 end := start + t.pieceNumChunks(piece)
2211 for ri := start; ri < end; ri++ {
2216 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2217 t.pendAllChunkSpecs(piece)
2218 t.cancelRequestsForPiece(piece)
2219 t.piece(piece).readerCond.Broadcast()
2220 for conn := range t.conns {
2222 t.maybeDropMutuallyCompletePeer(conn)
2226 // Called when a piece is found to be not complete.
2227 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2228 if t.pieceAllDirty(piece) {
2229 t.pendAllChunkSpecs(piece)
2231 if !t.wantPieceIndex(piece) {
2232 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2235 // We could drop any connections that we told we have a piece that we
2236 // don't here. But there's a test failure, and it seems clients don't care
2237 // if you request pieces that you already claim to have. Pruning bad
2238 // connections might just remove any connections that aren't treating us
2239 // favourably anyway.
2241 // for c := range t.conns {
2242 // if c.sentHave(piece) {
2246 t.iterPeers(func(conn *Peer) {
2247 if conn.peerHasPiece(piece) {
2248 conn.updateRequests("piece incomplete")
2253 func (t *Torrent) tryCreateMorePieceHashers() {
2254 for !t.closed.IsSet() && t.activePieceHashes < t.cl.config.PieceHashersPerTorrent && t.tryCreatePieceHasher() {
2258 func (t *Torrent) tryCreatePieceHasher() bool {
2259 if t.storage == nil {
2262 pi, ok := t.getPieceToHash()
2267 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2269 t.publishPieceChange(pi)
2270 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2271 t.storageLock.RLock()
2272 t.activePieceHashes++
2273 go t.pieceHasher(pi)
2277 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2278 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2279 if t.piece(i).hashing {
2289 func (t *Torrent) dropBannedPeers() {
2290 t.iterPeers(func(p *Peer) {
2291 remoteIp := p.remoteIp()
2292 if remoteIp == nil {
2293 if p.bannableAddr.Ok {
2294 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2298 netipAddr := netip.MustParseAddr(remoteIp.String())
2299 if Some(netipAddr) != p.bannableAddr {
2300 t.logger.WithDefaultLevel(log.Debug).Printf(
2301 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2302 p, remoteIp, p.bannableAddr)
2304 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2305 // Should this be a close?
2307 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2312 func (t *Torrent) pieceHasher(index pieceIndex) {
2314 sum, failedPeers, copyErr := t.hashPiece(index)
2315 correct := sum == *p.hash
2319 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2321 t.storageLock.RUnlock()
2325 for peer := range failedPeers {
2326 t.cl.banPeerIP(peer.AsSlice())
2327 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2330 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2331 t.smartBanCache.ForgetBlock(ri)
2335 t.pieceHashed(index, correct, copyErr)
2336 t.updatePiecePriority(index, "Torrent.pieceHasher")
2337 t.activePieceHashes--
2338 t.tryCreateMorePieceHashers()
2341 // Return the connections that touched a piece, and clear the entries while doing it.
2342 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2344 for c := range p.dirtiers {
2345 delete(c.peerTouchedPieces, pi)
2346 delete(p.dirtiers, c)
2350 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2351 t.iterPeers(func(p *Peer) {
2352 ret = append(ret, p)
2357 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2358 piece := t.piece(pieceIndex)
2359 if piece.queuedForHash() {
2362 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2363 t.publishPieceChange(pieceIndex)
2364 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2365 t.tryCreateMorePieceHashers()
2368 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2369 // before the Info is available.
2370 func (t *Torrent) VerifyData() {
2371 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2372 t.Piece(i).VerifyData()
2376 func (t *Torrent) connectingToPeerAddr(addrStr string) bool {
2377 return len(t.halfOpen[addrStr]) != 0
2380 func (t *Torrent) hasPeerConnForAddr(x PeerRemoteAddr) bool {
2381 addrStr := x.String()
2382 for c := range t.conns {
2384 if ra.String() == addrStr {
2391 func (t *Torrent) getHalfOpenPath(
2393 attemptKey outgoingConnAttemptKey,
2394 ) nestedmaps.Path[*PeerInfo] {
2395 return nestedmaps.Next(nestedmaps.Next(nestedmaps.Begin(&t.halfOpen), addrStr), attemptKey)
2398 func (t *Torrent) addHalfOpen(addrStr string, attemptKey *PeerInfo) {
2399 path := t.getHalfOpenPath(addrStr, attemptKey)
2401 panic("should be unique")
2403 path.Set(attemptKey)
2407 // Start the process of connecting to the given peer for the given torrent if appropriate. I'm not
2408 // sure all the PeerInfo fields are being used.
2410 opts outgoingConnOpts,
2414 peer := opts.peerInfo
2415 if peer.Id == t.cl.peerID {
2418 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2422 addrStr := addr.String()
2424 if t.connectingToPeerAddr(addrStr) {
2428 if t.hasPeerConnForAddr(addr) {
2432 t.addHalfOpen(addrStr, attemptKey)
2433 go t.cl.outgoingConnection(
2439 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2440 // quickly make one Client visible to the Torrent of another Client.
2441 func (t *Torrent) AddClientPeer(cl *Client) int {
2442 return t.AddPeers(func() (ps []PeerInfo) {
2443 for _, la := range cl.ListenAddrs() {
2444 ps = append(ps, PeerInfo{
2453 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2455 func (t *Torrent) allStats(f func(*ConnStats)) {
2460 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2461 return t.pieces[i].hashing
2464 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2465 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2468 func (t *Torrent) dialTimeout() time.Duration {
2469 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2472 func (t *Torrent) piece(i int) *Piece {
2476 func (t *Torrent) onWriteChunkErr(err error) {
2477 if t.userOnWriteChunkErr != nil {
2478 go t.userOnWriteChunkErr(err)
2481 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2482 t.disallowDataDownloadLocked()
2485 func (t *Torrent) DisallowDataDownload() {
2486 t.disallowDataDownloadLocked()
2489 func (t *Torrent) disallowDataDownloadLocked() {
2490 t.dataDownloadDisallowed.Set()
2493 func (t *Torrent) AllowDataDownload() {
2494 t.dataDownloadDisallowed.Clear()
2497 // Enables uploading data, if it was disabled.
2498 func (t *Torrent) AllowDataUpload() {
2501 t.dataUploadDisallowed = false
2502 for c := range t.conns {
2503 c.updateRequests("allow data upload")
2507 // Disables uploading data, if it was enabled.
2508 func (t *Torrent) DisallowDataUpload() {
2511 t.dataUploadDisallowed = true
2512 for c := range t.conns {
2513 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2514 c.updateRequests("disallow data upload")
2518 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2519 // or if nil, a critical message is logged, and data download is disabled.
2520 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2523 t.userOnWriteChunkErr = f
2526 func (t *Torrent) iterPeers(f func(p *Peer)) {
2527 for pc := range t.conns {
2530 for _, ws := range t.webSeeds {
2535 func (t *Torrent) callbacks() *Callbacks {
2536 return &t.cl.config.Callbacks
2539 type AddWebSeedsOpt func(*webseed.Client)
2541 // Sets the WebSeed trailing path escaper for a webseed.Client.
2542 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2543 return func(c *webseed.Client) {
2544 c.PathEscaper = custom
2548 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2551 for _, u := range urls {
2552 t.addWebSeed(u, opts...)
2556 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2557 if t.cl.config.DisableWebseeds {
2560 if _, ok := t.webSeeds[url]; ok {
2563 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2564 // right away. This value should be some multiple of the number of connections to a host. I
2565 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2566 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2567 // "https://webtorrent.io/torrents/".
2568 const maxRequests = 16
2574 reconciledHandshakeStats: true,
2575 // This should affect how often we have to recompute requests for this peer. Note that
2576 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2577 // requests mark more often, so recomputation is probably sooner than with regular peer
2578 // conns. ~4x maxRequests would be about right.
2579 PeerMaxRequests: 128,
2580 // TODO: Set ban prefix?
2581 RemoteAddr: remoteAddrFromUrl(url),
2582 callbacks: t.callbacks(),
2584 client: webseed.Client{
2585 HttpClient: t.cl.httpClient,
2587 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2588 return &rateLimitedReader{
2589 l: t.cl.config.DownloadRateLimiter,
2594 activeRequests: make(map[Request]webseed.Request, maxRequests),
2596 ws.peer.initRequestState()
2597 for _, opt := range opts {
2600 ws.peer.initUpdateRequestsTimer()
2601 ws.requesterCond.L = t.cl.locker()
2602 for i := 0; i < maxRequests; i += 1 {
2605 for _, f := range t.callbacks().NewPeer {
2608 ws.peer.logger = t.logger.WithContextValue(&ws)
2609 ws.peer.peerImpl = &ws
2611 ws.onGotInfo(t.info)
2613 t.webSeeds[url] = &ws.peer
2616 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2617 t.iterPeers(func(p1 *Peer) {
2625 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2626 index := t.pieceIndexOfRequestIndex(ri)
2629 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2633 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2634 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2637 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2638 return RequestIndex(piece) * t.chunksPerRegularPiece()
2641 func (t *Torrent) updateComplete() {
2642 t.Complete.SetBool(t.haveAllPieces())
2645 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2646 p := t.requestingPeer(r)
2650 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2651 //delete(t.pendingRequests, r)
2652 if _, ok := t.requestState[r]; ok {
2653 panic("expected request state to be gone")
2658 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2659 return t.requestState[r].peer
2662 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2663 if t.connsWithAllPieces == nil {
2664 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2666 t.connsWithAllPieces[p] = struct{}{}
2669 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2670 _, ok := t.connsWithAllPieces[p]
2671 delete(t.connsWithAllPieces, p)
2675 func (t *Torrent) numActivePeers() int {
2676 return len(t.conns) + len(t.webSeeds)
2679 func (t *Torrent) hasStorageCap() bool {
2680 f := t.storage.Capacity
2688 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2689 return pieceIndex(ri / t.chunksPerRegularPiece())
2692 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2693 reuseIter *typedRoaring.Iterator[RequestIndex],
2695 f func(RequestIndex),
2697 reuseIter.Initialize(&t.dirtyChunks)
2698 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2699 iterBitmapUnsetInRange(
2701 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2706 type requestState struct {
2711 // Returns an error if a received chunk is out of bounds in someway.
2712 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2714 return errors.New("torrent missing info")
2716 if int(r.Index) >= t.numPieces() {
2717 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2719 pieceLength := t.pieceLength(pieceIndex(r.Index))
2720 if r.Begin >= pieceLength {
2721 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2723 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2724 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2725 // should be considerable checks elsewhere for this case due to the network overhead. We should
2726 // catch most of the overflow manipulation stuff by checking index and begin above.
2730 func (t *Torrent) peerConnsWithDialAddrPort(target netip.AddrPort) (ret []*PeerConn) {
2731 for pc := range t.conns {
2732 dialAddr, err := pc.remoteDialAddrPort()
2736 if dialAddr != target {
2739 ret = append(ret, pc)
2744 func wrapUtHolepunchMsgForPeerConn(
2745 recipient *PeerConn,
2746 msg utHolepunch.Msg,
2748 extendedPayload, err := msg.MarshalBinary()
2754 ExtendedID: MapMustGet(recipient.PeerExtensionIDs, utHolepunch.ExtensionName),
2755 ExtendedPayload: extendedPayload,
2759 func sendUtHolepunchMsg(
2761 msgType utHolepunch.MsgType,
2762 addrPort netip.AddrPort,
2763 errCode utHolepunch.ErrCode,
2765 holepunchMsg := utHolepunch.Msg{
2770 incHolepunchMessagesSent(holepunchMsg)
2771 ppMsg := wrapUtHolepunchMsgForPeerConn(pc, holepunchMsg)
2775 func incHolepunchMessages(msg utHolepunch.Msg, verb string) {
2778 "holepunch %v %v messages %v",
2780 addrPortProtocolStr(msg.AddrPort),
2787 func incHolepunchMessagesReceived(msg utHolepunch.Msg) {
2788 incHolepunchMessages(msg, "received")
2791 func incHolepunchMessagesSent(msg utHolepunch.Msg) {
2792 incHolepunchMessages(msg, "sent")
2795 func (t *Torrent) handleReceivedUtHolepunchMsg(msg utHolepunch.Msg, sender *PeerConn) error {
2796 incHolepunchMessagesReceived(msg)
2797 switch msg.MsgType {
2798 case utHolepunch.Rendezvous:
2799 t.logger.Printf("got holepunch rendezvous request for %v from %p", msg.AddrPort, sender)
2800 sendMsg := sendUtHolepunchMsg
2801 senderAddrPort, err := sender.remoteDialAddrPort()
2803 sender.logger.Levelf(
2805 "error getting ut_holepunch rendezvous sender's dial address: %v",
2808 // There's no better error code. The sender's address itself is invalid. I don't see
2809 // this error message being appropriate anywhere else anyway.
2810 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSuchPeer)
2812 targets := t.peerConnsWithDialAddrPort(msg.AddrPort)
2813 if len(targets) == 0 {
2814 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NotConnected)
2817 for _, pc := range targets {
2818 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2819 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSupport)
2822 sendMsg(sender, utHolepunch.Connect, msg.AddrPort, 0)
2823 sendMsg(pc, utHolepunch.Connect, senderAddrPort, 0)
2826 case utHolepunch.Connect:
2827 holepunchAddr := msg.AddrPort
2828 t.logger.Printf("got holepunch connect request for %v from %p", holepunchAddr, sender)
2829 if g.MapContains(t.cl.undialableWithoutHolepunch, holepunchAddr) {
2830 setAdd(&t.cl.undialableWithoutHolepunchDialedAfterHolepunchConnect, holepunchAddr)
2831 if g.MapContains(t.cl.accepted, holepunchAddr) {
2832 setAdd(&t.cl.probablyOnlyConnectedDueToHolepunch, holepunchAddr)
2835 opts := outgoingConnOpts{
2838 Source: PeerSourceUtHolepunch,
2839 PexPeerFlags: sender.pex.remoteLiveConns[msg.AddrPort].UnwrapOrZeroValue(),
2842 // Don't attempt to start our own rendezvous if we fail to connect.
2843 skipHolepunchRendezvous: true,
2844 receivedHolepunchConnect: true,
2845 // Assume that the other end initiated the rendezvous, and will use our preferred
2846 // encryption. So we will act normally.
2847 HeaderObfuscationPolicy: t.cl.config.HeaderObfuscationPolicy,
2849 initiateConn(opts, true)
2851 case utHolepunch.Error:
2852 torrent.Add("holepunch error messages received", 1)
2853 t.logger.Levelf(log.Debug, "received ut_holepunch error message from %v: %v", sender, msg.ErrCode)
2856 return fmt.Errorf("unhandled msg type %v", msg.MsgType)
2860 func addrPortProtocolStr(addrPort netip.AddrPort) string {
2861 addr := addrPort.Addr()
2872 func (t *Torrent) trySendHolepunchRendezvous(addrPort netip.AddrPort) error {
2874 for pc := range t.conns {
2875 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2878 if pc.supportsExtension(pp.ExtensionNamePex) {
2879 if !g.MapContains(pc.pex.remoteLiveConns, addrPort) {
2883 t.logger.Levelf(log.Debug, "sent ut_holepunch rendezvous message to %v for %v", pc, addrPort)
2884 sendUtHolepunchMsg(pc, utHolepunch.Rendezvous, addrPort, 0)
2888 return errors.New("no eligible relays")
2893 func (t *Torrent) numHalfOpenAttempts() (num int) {
2894 for _, attempts := range t.halfOpen {
2895 num += len(attempts)
2900 func (t *Torrent) getDialTimeoutUnlocked() time.Duration {
2904 return t.dialTimeout()