20 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
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/perf"
30 "github.com/anacrolix/missinggo/slices"
31 "github.com/anacrolix/missinggo/v2"
32 "github.com/anacrolix/missinggo/v2/bitmap"
33 "github.com/anacrolix/missinggo/v2/pubsub"
34 "github.com/anacrolix/multiless"
35 "github.com/anacrolix/sync"
36 "github.com/davecgh/go-spew/spew"
37 "github.com/pion/datachannel"
38 "golang.org/x/exp/maps"
40 "github.com/anacrolix/torrent/bencode"
41 "github.com/anacrolix/torrent/common"
42 "github.com/anacrolix/torrent/metainfo"
43 pp "github.com/anacrolix/torrent/peer_protocol"
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]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 func (t *Torrent) length() int64 {
176 return t._length.Value
179 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
180 // This could be done with roaring.BitSliceIndexing.
181 t.iterPeers(func(peer *Peer) {
182 if _, ok := t.connsWithAllPieces[peer]; ok {
185 if peer.peerHasPiece(i) {
192 func (t *Torrent) decPieceAvailability(i pieceIndex) {
197 if p.relativeAvailability <= 0 {
198 panic(p.relativeAvailability)
200 p.relativeAvailability--
201 t.updatePieceRequestOrder(i)
204 func (t *Torrent) incPieceAvailability(i pieceIndex) {
205 // If we don't the info, this should be reconciled when we do.
208 p.relativeAvailability++
209 t.updatePieceRequestOrder(i)
213 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
214 return t._readerNowPieces
217 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
218 return t._readerReadaheadPieces
221 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
222 return !t.wantPieceIndex(i)
225 // Returns a channel that is closed when the Torrent is closed.
226 func (t *Torrent) Closed() events.Done {
227 return t.closed.Done()
230 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
231 // pending, and half-open peers.
232 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
233 // Add pending peers to the list
234 t.peers.Each(func(peer PeerInfo) {
235 ks = append(ks, peer)
238 // Add half-open peers to the list
239 for _, peer := range t.halfOpen {
240 ks = append(ks, peer)
243 // Add active peers to the list
244 for conn := range t.conns {
245 ks = append(ks, PeerInfo{
247 Addr: conn.RemoteAddr,
248 Source: conn.Discovery,
249 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
250 // > But if we're not connected to them with an encrypted connection, I couldn't say
251 // > what's appropriate. We can carry forward the SupportsEncryption value as we
252 // > received it from trackers/DHT/PEX, or just use the encryption state for the
253 // > connection. It's probably easiest to do the latter for now.
254 // https://github.com/anacrolix/torrent/pull/188
255 SupportsEncryption: conn.headerEncrypted,
262 func (t *Torrent) setChunkSize(size pp.Integer) {
264 t.chunkPool = sync.Pool{
265 New: func() interface{} {
266 b := make([]byte, size)
272 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
273 return t._completedPieces.Contains(bitmap.BitIndex(piece))
276 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
277 if t.storage == nil {
278 return storage.Completion{Complete: false, Ok: true}
280 return t.pieces[piece].Storage().Completion()
283 // There's a connection to that address already.
284 func (t *Torrent) addrActive(addr string) bool {
285 if _, ok := t.halfOpen[addr]; ok {
288 for c := range t.conns {
290 if ra.String() == addr {
297 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
298 return t.appendConns(ret, func(conn *PeerConn) bool {
299 return !conn.closed.IsSet()
303 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
304 for c := range t.conns {
312 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
314 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
315 if t.closed.IsSet() {
318 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
319 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
320 torrent.Add("peers not added because of bad addr", 1)
321 // cl.logger.Printf("peers not added because of bad addr: %v", p)
325 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
326 torrent.Add("peers replaced", 1)
327 if !replaced.equal(p) {
328 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
335 for t.peers.Len() > cl.config.TorrentPeersHighWater {
336 _, ok := t.peers.DeleteMin()
338 torrent.Add("excess reserve peers discarded", 1)
344 func (t *Torrent) invalidateMetadata() {
345 for i := 0; i < len(t.metadataCompletedChunks); i++ {
346 t.metadataCompletedChunks[i] = false
349 t.gotMetainfoC = make(chan struct{})
354 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
358 if index >= len(t.metadataCompletedChunks) {
359 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
362 copy(t.metadataBytes[(1<<14)*index:], data)
363 t.metadataCompletedChunks[index] = true
366 func (t *Torrent) metadataPieceCount() int {
367 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
370 func (t *Torrent) haveMetadataPiece(piece int) bool {
372 return (1<<14)*piece < len(t.metadataBytes)
374 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
378 func (t *Torrent) metadataSize() int {
379 return len(t.metadataBytes)
382 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
383 for i := 0; i < len(info.Pieces); i += sha1.Size {
384 ret = append(ret, info.Pieces[i:i+sha1.Size])
389 func (t *Torrent) makePieces() {
390 hashes := infoPieceHashes(t.info)
391 t.pieces = make([]Piece, len(hashes))
392 for i, hash := range hashes {
393 piece := &t.pieces[i]
395 piece.index = pieceIndex(i)
396 piece.noPendingWrites.L = &piece.pendingWritesMutex
397 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
399 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
400 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
401 piece.files = files[beginFile:endFile]
405 // Returns the index of the first file containing the piece. files must be
406 // ordered by offset.
407 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
408 for i, f := range files {
409 if f.offset+f.length > pieceOffset {
416 // Returns the index after the last file containing the piece. files must be
417 // ordered by offset.
418 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
419 for i, f := range files {
420 if f.offset+f.length >= pieceEndOffset {
427 func (t *Torrent) cacheLength() {
429 for _, f := range t.info.UpvertedFiles() {
435 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
437 func (t *Torrent) setInfo(info *metainfo.Info) error {
438 if err := validateInfo(info); err != nil {
439 return fmt.Errorf("bad info: %s", err)
441 if t.storageOpener != nil {
443 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
445 return fmt.Errorf("error opening torrent storage: %s", err)
451 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
453 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
454 t.displayName = "" // Save a few bytes lol.
461 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
462 return request_strategy.PieceRequestOrderKey{
463 InfoHash: t.infoHash,
468 // This seems to be all the follow-up tasks after info is set, that can't fail.
469 func (t *Torrent) onSetInfo() {
470 t.pieceRequestOrder = rand.Perm(t.numPieces())
471 t.initPieceRequestOrder()
472 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
473 for i := range t.pieces {
475 // Need to add relativeAvailability before updating piece completion, as that may result in conns
477 if p.relativeAvailability != 0 {
478 panic(p.relativeAvailability)
480 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
481 t.addRequestOrderPiece(i)
482 t.updatePieceCompletion(i)
483 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
484 // t.logger.Printf("piece %s completion unknown, queueing check", p)
488 t.cl.event.Broadcast()
489 close(t.gotMetainfoC)
490 t.updateWantPeersEvent()
491 t.requestState = make(map[RequestIndex]requestState)
492 t.tryCreateMorePieceHashers()
493 t.iterPeers(func(p *Peer) {
495 p.updateRequests("onSetInfo")
499 // Called when metadata for a torrent becomes available.
500 func (t *Torrent) setInfoBytesLocked(b []byte) error {
501 if metainfo.HashBytes(b) != t.infoHash {
502 return errors.New("info bytes have wrong hash")
504 var info metainfo.Info
505 if err := bencode.Unmarshal(b, &info); err != nil {
506 return fmt.Errorf("error unmarshalling info bytes: %s", err)
509 t.metadataCompletedChunks = nil
513 if err := t.setInfo(&info); err != nil {
520 func (t *Torrent) haveAllMetadataPieces() bool {
524 if t.metadataCompletedChunks == nil {
527 for _, have := range t.metadataCompletedChunks {
535 // TODO: Propagate errors to disconnect peer.
536 func (t *Torrent) setMetadataSize(size int) (err error) {
538 // We already know the correct metadata size.
541 if uint32(size) > maxMetadataSize {
542 return log.WithLevel(log.Warning, errors.New("bad size"))
544 if len(t.metadataBytes) == size {
547 t.metadataBytes = make([]byte, size)
548 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
549 t.metadataChanged.Broadcast()
550 for c := range t.conns {
551 c.requestPendingMetadata()
556 // The current working name for the torrent. Either the name in the info dict,
557 // or a display name given such as by the dn value in a magnet link, or "".
558 func (t *Torrent) name() string {
560 defer t.nameMu.RUnlock()
562 return t.info.BestName()
564 if t.displayName != "" {
567 return "infohash:" + t.infoHash.HexString()
570 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
571 p := &t.pieces[index]
572 ret.Priority = t.piecePriority(index)
573 ret.Completion = p.completion()
574 ret.QueuedForHash = p.queuedForHash()
575 ret.Hashing = p.hashing
576 ret.Checking = ret.QueuedForHash || ret.Hashing
577 ret.Marking = p.marking
578 if !ret.Complete && t.piecePartiallyDownloaded(index) {
584 func (t *Torrent) metadataPieceSize(piece int) int {
585 return metadataPieceSize(len(t.metadataBytes), piece)
588 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
591 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
592 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
594 TotalSize: len(t.metadataBytes),
600 type pieceAvailabilityRun struct {
605 func (me pieceAvailabilityRun) String() string {
606 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
609 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
610 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
611 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
613 for i := range t.pieces {
614 rle.Append(t.pieces[i].availability(), 1)
620 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
621 freqs = make([]int, t.numActivePeers()+1)
622 for i := range t.pieces {
623 freqs[t.piece(i).availability()]++
628 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
629 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
630 ret = append(ret, PieceStateRun{
631 PieceState: el.(PieceState),
635 for index := range t.pieces {
636 rle.Append(t.pieceState(pieceIndex(index)), 1)
642 // Produces a small string representing a PieceStateRun.
643 func (psr PieceStateRun) String() (ret string) {
644 ret = fmt.Sprintf("%d", psr.Length)
645 ret += func() string {
646 switch psr.Priority {
647 case PiecePriorityNext:
649 case PiecePriorityNormal:
651 case PiecePriorityReadahead:
653 case PiecePriorityNow:
655 case PiecePriorityHigh:
664 if psr.QueuedForHash {
682 func (t *Torrent) writeStatus(w io.Writer) {
683 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
684 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
686 fmt.Fprintf(w, "Metadata have: ")
687 for _, h := range t.metadataCompletedChunks {
688 fmt.Fprintf(w, "%c", func() rune {
698 fmt.Fprintf(w, "Piece length: %s\n",
701 return fmt.Sprintf("%v (%v chunks)",
703 float64(t.usualPieceSize())/float64(t.chunkSize))
710 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
711 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
712 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
713 // availability frequencies instead.
715 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
716 for _, run := range t.pieceAvailabilityRuns() {
717 ret = append(ret, run.String())
722 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
723 func() (ret []string) {
724 for avail, freq := range t.pieceAvailabilityFrequencies() {
728 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
734 fmt.Fprintf(w, "Reader Pieces:")
735 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
736 fmt.Fprintf(w, " %d:%d", begin, end)
741 fmt.Fprintf(w, "Enabled trackers:\n")
743 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
744 fmt.Fprintf(tw, " URL\tExtra\n")
745 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
748 var luns, runs url.URL = *lu, *ru
751 var ml missinggo.MultiLess
752 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
753 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
755 }).([]torrentTrackerAnnouncer) {
756 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
761 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
763 spew.NewDefaultConfig()
764 spew.Fdump(w, t.statsLocked())
766 fmt.Fprintf(w, "webseeds:\n")
767 t.writePeerStatuses(w, maps.Values(t.webSeeds))
769 peerConns := maps.Keys(t.conns)
770 // Peers without priorities first, then those with. I'm undecided about how to order peers
771 // without priorities.
772 sort.Slice(peerConns, func(li, ri int) bool {
775 ml := multiless.New()
776 lpp := g.ResultFromTuple(l.peerPriority()).ToOption()
777 rpp := g.ResultFromTuple(r.peerPriority()).ToOption()
778 ml = ml.Bool(lpp.Ok, rpp.Ok)
779 ml = ml.Uint32(rpp.Value, lpp.Value)
783 fmt.Fprintf(w, "peer conns:\n")
784 t.writePeerStatuses(w, g.SliceMap(peerConns, func(pc *PeerConn) *Peer {
789 func (t *Torrent) writePeerStatuses(w io.Writer, peers []*Peer) {
791 for _, c := range peers {
795 w.Write(bytes.TrimRight(
796 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
801 func (t *Torrent) haveInfo() bool {
805 // Returns a run-time generated MetaInfo that includes the info bytes and
806 // announce-list as currently known to the client.
807 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
808 return metainfo.MetaInfo{
809 CreationDate: time.Now().Unix(),
810 Comment: "dynamic metainfo from client",
811 CreatedBy: "go.torrent",
812 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
813 InfoBytes: func() []byte {
815 return t.metadataBytes
820 UrlList: func() []string {
821 ret := make([]string, 0, len(t.webSeeds))
822 for url := range t.webSeeds {
823 ret = append(ret, url)
831 func (t *Torrent) BytesMissing() (n int64) {
833 n = t.bytesMissingLocked()
838 func (t *Torrent) bytesMissingLocked() int64 {
842 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
843 roaring.Flip(b, 0, end).Iterate(cb)
846 func (t *Torrent) bytesLeft() (left int64) {
847 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
848 p := t.piece(pieceIndex(x))
849 left += int64(p.length() - p.numDirtyBytes())
855 // Bytes left to give in tracker announces.
856 func (t *Torrent) bytesLeftAnnounce() int64 {
864 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
865 if t.pieceComplete(piece) {
868 if t.pieceAllDirty(piece) {
871 return t.pieces[piece].hasDirtyChunks()
874 func (t *Torrent) usualPieceSize() int {
875 return int(t.info.PieceLength)
878 func (t *Torrent) numPieces() pieceIndex {
879 return t.info.NumPieces()
882 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
883 return pieceIndex(t._completedPieces.GetCardinality())
886 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
888 err = errors.New("already closed")
891 for _, f := range t.onClose {
894 if t.storage != nil {
899 defer t.storageLock.Unlock()
900 if f := t.storage.Close; f != nil {
903 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
908 t.iterPeers(func(p *Peer) {
911 if t.storage != nil {
912 t.deletePieceRequestOrder()
914 t.assertAllPiecesRelativeAvailabilityZero()
916 t.cl.event.Broadcast()
917 t.pieceStateChanges.Close()
918 t.updateWantPeersEvent()
922 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
923 for i := range t.pieces {
925 if p.relativeAvailability != 0 {
926 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
931 func (t *Torrent) requestOffset(r Request) int64 {
932 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
935 // Return the request that would include the given offset into the torrent data. Returns !ok if
936 // there is no such request.
937 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
938 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
941 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
942 defer perf.ScopeTimerErr(&err)()
943 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
944 if err == nil && n != len(data) {
945 err = io.ErrShortWrite
950 func (t *Torrent) bitfield() (bf []bool) {
951 bf = make([]bool, t.numPieces())
952 t._completedPieces.Iterate(func(piece uint32) (again bool) {
959 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
960 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
963 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
964 return t._chunksPerRegularPiece
967 func (t *Torrent) numChunks() RequestIndex {
968 if t.numPieces() == 0 {
971 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
974 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
975 t.dirtyChunks.RemoveRange(
976 uint64(t.pieceRequestIndexOffset(pieceIndex)),
977 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
980 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
981 if t.info.PieceLength == 0 {
982 // There will be no variance amongst pieces. Only pain.
985 if piece == t.numPieces()-1 {
986 ret := pp.Integer(t.length() % t.info.PieceLength)
991 return pp.Integer(t.info.PieceLength)
994 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
995 return &blockCheckingWriter{
996 cache: &t.smartBanCache,
997 requestIndex: t.pieceRequestIndexOffset(piece),
998 chunkSize: t.chunkSize.Int(),
1002 func (t *Torrent) hashPiece(piece pieceIndex) (
1004 // These are peers that sent us blocks that differ from what we hash here.
1005 differingPeers map[bannableAddr]struct{},
1009 p.waitNoPendingWrites()
1010 storagePiece := t.pieces[piece].Storage()
1012 // Does the backend want to do its own hashing?
1013 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
1014 var sum metainfo.Hash
1015 // log.Printf("A piece decided to self-hash: %d", piece)
1016 sum, err = i.SelfHash()
1017 missinggo.CopyExact(&ret, sum)
1021 hash := pieceHash.New()
1022 const logPieceContents = false
1023 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1024 writers := []io.Writer{hash, smartBanWriter}
1025 var examineBuf bytes.Buffer
1026 if logPieceContents {
1027 writers = append(writers, &examineBuf)
1029 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1030 if logPieceContents {
1031 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1033 smartBanWriter.Flush()
1034 differingPeers = smartBanWriter.badPeers
1035 missinggo.CopyExact(&ret, hash.Sum(nil))
1039 func (t *Torrent) haveAnyPieces() bool {
1040 return !t._completedPieces.IsEmpty()
1043 func (t *Torrent) haveAllPieces() bool {
1047 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1050 func (t *Torrent) havePiece(index pieceIndex) bool {
1051 return t.haveInfo() && t.pieceComplete(index)
1054 func (t *Torrent) maybeDropMutuallyCompletePeer(
1055 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1059 if !t.cl.config.DropMutuallyCompletePeers {
1062 if !t.haveAllPieces() {
1065 if all, known := p.peerHasAllPieces(); !(known && all) {
1071 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1075 func (t *Torrent) haveChunk(r Request) (ret bool) {
1077 // log.Println("have chunk", r, ret)
1082 if t.pieceComplete(pieceIndex(r.Index)) {
1085 p := &t.pieces[r.Index]
1086 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1089 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1090 return chunkIndexType(cs.Begin / chunkSize)
1093 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1094 return t._pendingPieces.Contains(uint32(index))
1097 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1098 // conns (which is a map).
1099 var peerConnSlices sync.Pool
1101 func getPeerConnSlice(cap int) []*PeerConn {
1102 getInterface := peerConnSlices.Get()
1103 if getInterface == nil {
1104 return make([]*PeerConn, 0, cap)
1106 return getInterface.([]*PeerConn)[:0]
1110 // Calls the given function with a slice of unclosed conns. It uses a pool to reduce allocations as
1111 // this is a frequent occurrence.
1112 func (t *Torrent) withUnclosedConns(f func([]*PeerConn)) {
1113 sl := t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))
1115 peerConnSlices.Put(sl)
1118 func (t *Torrent) worstBadConnFromSlice(opts worseConnLensOpts, sl []*PeerConn) *PeerConn {
1119 wcs := worseConnSlice{conns: sl}
1122 for wcs.Len() != 0 {
1123 c := heap.Pop(&wcs).(*PeerConn)
1124 if opts.incomingIsBad && !c.outgoing {
1127 if opts.outgoingIsBad && c.outgoing {
1130 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1133 // If the connection is in the worst half of the established
1134 // connection quota and is older than a minute.
1135 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1136 // Give connections 1 minute to prove themselves.
1137 if time.Since(c.completedHandshake) > time.Minute {
1145 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1146 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1147 // established connections for more than a minute. This is O(n log n). If there was a way to not
1148 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1149 func (t *Torrent) worstBadConn(opts worseConnLensOpts) (ret *PeerConn) {
1150 t.withUnclosedConns(func(ucs []*PeerConn) {
1151 ret = t.worstBadConnFromSlice(opts, ucs)
1156 type PieceStateChange struct {
1161 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1162 t.cl._mu.Defer(func() {
1163 cur := t.pieceState(piece)
1164 p := &t.pieces[piece]
1165 if cur != p.publicPieceState {
1166 p.publicPieceState = cur
1167 t.pieceStateChanges.Publish(PieceStateChange{
1175 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1176 if t.pieceComplete(piece) {
1179 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1182 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1183 return t.pieces[piece].allChunksDirty()
1186 func (t *Torrent) readersChanged() {
1187 t.updateReaderPieces()
1188 t.updateAllPiecePriorities("Torrent.readersChanged")
1191 func (t *Torrent) updateReaderPieces() {
1192 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1195 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1199 t.updateReaderPieces()
1200 // Order the ranges, high and low.
1202 if l.begin > h.begin {
1205 if l.end < h.begin {
1206 // Two distinct ranges.
1207 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1208 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1215 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1219 func (t *Torrent) maybeNewConns() {
1220 // Tickle the accept routine.
1221 t.cl.event.Broadcast()
1225 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1226 if t._pendingPieces.Contains(uint32(piece)) {
1227 t.iterPeers(func(c *Peer) {
1228 // if c.requestState.Interested {
1231 if !c.isLowOnRequests() {
1234 if !c.peerHasPiece(piece) {
1237 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1240 c.updateRequests(reason)
1244 t.publishPieceChange(piece)
1247 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1248 if !t.closed.IsSet() {
1249 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1251 t.updatePieceRequestOrder(piece)
1253 p := &t.pieces[piece]
1254 newPrio := p.uncachedPriority()
1255 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1256 if newPrio == PiecePriorityNone {
1257 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1261 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1265 t.piecePriorityChanged(piece, reason)
1268 func (t *Torrent) updateAllPiecePriorities(reason string) {
1269 t.updatePiecePriorities(0, t.numPieces(), reason)
1272 // Update all piece priorities in one hit. This function should have the same
1273 // output as updatePiecePriority, but across all pieces.
1274 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1275 for i := begin; i < end; i++ {
1276 t.updatePiecePriority(i, reason)
1280 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1281 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1282 if off >= t.length() {
1292 begin = pieceIndex(off / t.info.PieceLength)
1293 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1294 if end > pieceIndex(t.info.NumPieces()) {
1295 end = pieceIndex(t.info.NumPieces())
1300 // Returns true if all iterations complete without breaking. Returns the read regions for all
1301 // readers. The reader regions should not be merged as some callers depend on this method to
1302 // enumerate readers.
1303 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1304 for r := range t.readers {
1306 if p.begin >= p.end {
1309 if !f(p.begin, p.end) {
1316 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1317 return t.piece(piece).uncachedPriority()
1320 func (t *Torrent) pendRequest(req RequestIndex) {
1321 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1324 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1325 t.cl.event.Broadcast()
1326 if t.pieceComplete(piece) {
1327 t.onPieceCompleted(piece)
1329 t.onIncompletePiece(piece)
1331 t.updatePiecePriority(piece, reason)
1334 func (t *Torrent) numReceivedConns() (ret int) {
1335 for c := range t.conns {
1336 if c.Discovery == PeerSourceIncoming {
1343 func (t *Torrent) numOutgoingConns() (ret int) {
1344 for c := range t.conns {
1352 func (t *Torrent) maxHalfOpen() int {
1353 // Note that if we somehow exceed the maximum established conns, we want
1354 // the negative value to have an effect.
1355 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1356 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1357 // We want to allow some experimentation with new peers, and to try to
1358 // upset an oversupply of received connections.
1360 max(5, extraIncoming)+establishedHeadroom,
1361 int64(t.cl.config.HalfOpenConnsPerTorrent),
1365 func (t *Torrent) openNewConns() (initiated int) {
1366 defer t.updateWantPeersEvent()
1367 for t.peers.Len() != 0 {
1368 if !t.wantOutgoingConns() {
1371 if len(t.halfOpen) >= t.maxHalfOpen() {
1374 if len(t.cl.dialers) == 0 {
1377 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1380 p := t.peers.PopMax()
1387 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1389 uncached := t.pieceCompleteUncached(piece)
1390 cached := p.completion()
1391 changed := cached != uncached
1392 complete := uncached.Complete
1393 p.storageCompletionOk = uncached.Ok
1396 t._completedPieces.Add(x)
1399 t._completedPieces.Remove(x)
1401 p.t.updatePieceRequestOrder(piece)
1403 if complete && len(p.dirtiers) != 0 {
1404 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1407 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1408 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1413 // Non-blocking read. Client lock is not required.
1414 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1416 p := &t.pieces[off/t.info.PieceLength]
1417 p.waitNoPendingWrites()
1419 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1430 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1431 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1432 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1433 func (t *Torrent) maybeCompleteMetadata() error {
1438 if !t.haveAllMetadataPieces() {
1439 // Don't have enough metadata pieces.
1442 err := t.setInfoBytesLocked(t.metadataBytes)
1444 t.invalidateMetadata()
1445 return fmt.Errorf("error setting info bytes: %s", err)
1447 if t.cl.config.Debug {
1448 t.logger.Printf("%s: got metadata from peers", t)
1453 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1454 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1456 now.Add(bitmap.BitIndex(begin))
1457 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1464 func (t *Torrent) needData() bool {
1465 if t.closed.IsSet() {
1471 return !t._pendingPieces.IsEmpty()
1474 func appendMissingStrings(old, new []string) (ret []string) {
1477 for _, n := range new {
1478 for _, o := range old {
1483 ret = append(ret, n)
1488 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1490 for minNumTiers > len(ret) {
1491 ret = append(ret, nil)
1496 func (t *Torrent) addTrackers(announceList [][]string) {
1497 fullAnnounceList := &t.metainfo.AnnounceList
1498 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1499 for tierIndex, trackerURLs := range announceList {
1500 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1502 t.startMissingTrackerScrapers()
1503 t.updateWantPeersEvent()
1506 // Don't call this before the info is available.
1507 func (t *Torrent) bytesCompleted() int64 {
1511 return t.length() - t.bytesLeft()
1514 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1517 return t.setInfoBytesLocked(b)
1520 // Returns true if connection is removed from torrent.Conns.
1521 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1522 if !c.closed.IsSet() {
1523 panic("connection is not closed")
1524 // There are behaviours prevented by the closed state that will fail
1525 // if the connection has been deleted.
1529 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1530 // the drop event against the PexConnState instead.
1532 if !t.cl.config.DisablePEX {
1536 torrent.Add("deleted connections", 1)
1537 c.deleteAllRequests("Torrent.deletePeerConn")
1538 t.assertPendingRequests()
1539 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1540 panic(t.connsWithAllPieces)
1545 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1546 if t.deleteConnWithAllPieces(p) {
1552 p.peerPieces().Iterate(func(i uint32) bool {
1553 p.t.decPieceAvailability(pieceIndex(i))
1558 func (t *Torrent) assertPendingRequests() {
1562 // var actual pendingRequests
1563 // if t.haveInfo() {
1564 // actual.m = make([]int, t.numChunks())
1566 // t.iterPeers(func(p *Peer) {
1567 // p.requestState.Requests.Iterate(func(x uint32) bool {
1572 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1578 func (t *Torrent) dropConnection(c *PeerConn) {
1579 t.cl.event.Broadcast()
1581 if t.deletePeerConn(c) {
1586 // Peers as in contact information for dialing out.
1587 func (t *Torrent) wantPeers() bool {
1588 if t.closed.IsSet() {
1591 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1594 return t.wantOutgoingConns()
1597 func (t *Torrent) updateWantPeersEvent() {
1599 t.wantPeersEvent.Set()
1601 t.wantPeersEvent.Clear()
1605 // Returns whether the client should make effort to seed the torrent.
1606 func (t *Torrent) seeding() bool {
1608 if t.closed.IsSet() {
1611 if t.dataUploadDisallowed {
1614 if cl.config.NoUpload {
1617 if !cl.config.Seed {
1620 if cl.config.DisableAggressiveUpload && t.needData() {
1626 func (t *Torrent) onWebRtcConn(
1627 c datachannel.ReadWriteCloser,
1628 dcc webtorrent.DataChannelContext,
1631 netConn := webrtcNetConn{
1633 DataChannelContext: dcc,
1635 peerRemoteAddr := netConn.RemoteAddr()
1636 //t.logger.Levelf(log.Critical, "onWebRtcConn remote addr: %v", peerRemoteAddr)
1637 if t.cl.badPeerAddr(peerRemoteAddr) {
1640 localAddrIpPort := missinggo.IpPortFromNetAddr(netConn.LocalAddr())
1641 pc, err := t.cl.initiateProtocolHandshakes(
1642 context.Background(),
1647 outgoing: dcc.LocalOffered,
1648 remoteAddr: peerRemoteAddr,
1649 localPublicAddr: localAddrIpPort,
1650 network: webrtcNetwork,
1651 connString: fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1655 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1658 if dcc.LocalOffered {
1659 pc.Discovery = PeerSourceTracker
1661 pc.Discovery = PeerSourceIncoming
1663 pc.conn.SetWriteDeadline(time.Time{})
1666 err = t.cl.runHandshookConn(pc, t)
1668 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1672 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1673 err := t.cl.runHandshookConn(pc, t)
1674 if err != nil || logAll {
1675 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1679 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1680 t.logRunHandshookConn(pc, false, log.Debug)
1683 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1684 wtc, release := t.cl.websocketTrackers.Get(u.String(), t.infoHash)
1685 // This needs to run before the Torrent is dropped from the Client, to prevent a new webtorrent.TrackerClient for
1686 // the same info hash before the old one is cleaned up.
1687 t.onClose = append(t.onClose, release)
1688 wst := websocketTrackerStatus{u, wtc}
1690 err := wtc.Announce(tracker.Started, t.infoHash)
1692 t.logger.WithDefaultLevel(log.Warning).Printf(
1693 "error in initial announce to %q: %v",
1701 func (t *Torrent) startScrapingTracker(_url string) {
1705 u, err := url.Parse(_url)
1707 // URLs with a leading '*' appear to be a uTorrent convention to
1708 // disable trackers.
1710 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1714 if u.Scheme == "udp" {
1716 t.startScrapingTracker(u.String())
1718 t.startScrapingTracker(u.String())
1721 if _, ok := t.trackerAnnouncers[_url]; ok {
1724 sl := func() torrentTrackerAnnouncer {
1727 if t.cl.config.DisableWebtorrent {
1730 return t.startWebsocketAnnouncer(*u)
1732 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1736 if t.cl.config.DisableIPv6 {
1740 newAnnouncer := &trackerScraper{
1743 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1745 go newAnnouncer.Run()
1751 if t.trackerAnnouncers == nil {
1752 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1754 t.trackerAnnouncers[_url] = sl
1757 // Adds and starts tracker scrapers for tracker URLs that aren't already
1759 func (t *Torrent) startMissingTrackerScrapers() {
1760 if t.cl.config.DisableTrackers {
1763 t.startScrapingTracker(t.metainfo.Announce)
1764 for _, tier := range t.metainfo.AnnounceList {
1765 for _, url := range tier {
1766 t.startScrapingTracker(url)
1771 // Returns an AnnounceRequest with fields filled out to defaults and current
1773 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1774 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1775 // dependent on the network in use.
1776 return tracker.AnnounceRequest{
1778 NumWant: func() int32 {
1779 if t.wantPeers() && len(t.cl.dialers) > 0 {
1780 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1785 Port: uint16(t.cl.incomingPeerPort()),
1786 PeerId: t.cl.peerID,
1787 InfoHash: t.infoHash,
1788 Key: t.cl.announceKey(),
1790 // The following are vaguely described in BEP 3.
1792 Left: t.bytesLeftAnnounce(),
1793 Uploaded: t.stats.BytesWrittenData.Int64(),
1794 // There's no mention of wasted or unwanted download in the BEP.
1795 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1799 // Adds peers revealed in an announce until the announce ends, or we have
1801 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1803 for v := range pvs {
1806 for _, cp := range v.Peers {
1808 // Can't do anything with this.
1811 if t.addPeer(PeerInfo{
1812 Addr: ipPortAddr{cp.IP, cp.Port},
1813 Source: PeerSourceDhtGetPeers,
1820 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1825 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1826 // announce ends. stop will force the announce to end.
1827 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1828 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1832 _done := make(chan struct{})
1836 t.consumeDhtAnnouncePeers(ps.Peers())
1842 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1843 _, stop, err := t.AnnounceToDht(s)
1848 case <-t.closed.Done():
1849 case <-time.After(5 * time.Minute):
1855 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1861 if t.closed.IsSet() {
1864 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1865 // TODO: We can include the announce_peer step depending on whether we can receive
1866 // inbound connections. We should probably only announce once every 15 mins too.
1867 if !t.wantAnyConns() {
1870 // TODO: Determine if there's a listener on the port we're announcing.
1871 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1882 err := t.timeboxedAnnounceToDht(s)
1884 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1890 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1891 for _, p := range peers {
1899 // The returned TorrentStats may require alignment in memory. See
1900 // https://github.com/anacrolix/torrent/issues/383.
1901 func (t *Torrent) Stats() TorrentStats {
1903 defer t.cl.rUnlock()
1904 return t.statsLocked()
1907 func (t *Torrent) statsLocked() (ret TorrentStats) {
1908 ret.ActivePeers = len(t.conns)
1909 ret.HalfOpenPeers = len(t.halfOpen)
1910 ret.PendingPeers = t.peers.Len()
1911 ret.TotalPeers = t.numTotalPeers()
1912 ret.ConnectedSeeders = 0
1913 for c := range t.conns {
1914 if all, ok := c.peerHasAllPieces(); all && ok {
1915 ret.ConnectedSeeders++
1918 ret.ConnStats = t.stats.Copy()
1919 ret.PiecesComplete = t.numPiecesCompleted()
1923 // The total number of peers in the torrent.
1924 func (t *Torrent) numTotalPeers() int {
1925 peers := make(map[string]struct{})
1926 for conn := range t.conns {
1927 ra := conn.conn.RemoteAddr()
1929 // It's been closed and doesn't support RemoteAddr.
1932 peers[ra.String()] = struct{}{}
1934 for addr := range t.halfOpen {
1935 peers[addr] = struct{}{}
1937 t.peers.Each(func(peer PeerInfo) {
1938 peers[peer.Addr.String()] = struct{}{}
1943 // Reconcile bytes transferred before connection was associated with a
1945 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1946 if c._stats != (ConnStats{
1947 // Handshakes should only increment these fields:
1948 BytesWritten: c._stats.BytesWritten,
1949 BytesRead: c._stats.BytesRead,
1953 c.postHandshakeStats(func(cs *ConnStats) {
1954 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1955 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1957 c.reconciledHandshakeStats = true
1960 // Returns true if the connection is added.
1961 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1964 torrent.Add("added connections", 1)
1967 if t.closed.IsSet() {
1968 return errors.New("torrent closed")
1970 for c0 := range t.conns {
1971 if c.PeerID != c0.PeerID {
1974 if !t.cl.config.DropDuplicatePeerIds {
1977 if c.hasPreferredNetworkOver(c0) {
1979 t.deletePeerConn(c0)
1981 return errors.New("existing connection preferred")
1984 if len(t.conns) >= t.maxEstablishedConns {
1985 numOutgoing := t.numOutgoingConns()
1986 numIncoming := len(t.conns) - numOutgoing
1987 c := t.worstBadConn(worseConnLensOpts{
1988 // We've already established that we have too many connections at this point, so we just
1989 // need to match what kind we have too many of vs. what we're trying to add now.
1990 incomingIsBad: (numIncoming-numOutgoing > 1) && c.outgoing,
1991 outgoingIsBad: (numOutgoing-numIncoming > 1) && !c.outgoing,
1994 return errors.New("don't want conn")
1999 if len(t.conns) >= t.maxEstablishedConns {
2002 t.conns[c] = struct{}{}
2003 t.cl.event.Broadcast()
2004 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
2005 t.pex.Add(c) // as no further extended handshake expected
2010 func (t *Torrent) newConnsAllowed() bool {
2011 if !t.networkingEnabled.Bool() {
2014 if t.closed.IsSet() {
2017 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2023 func (t *Torrent) wantAnyConns() bool {
2024 if !t.networkingEnabled.Bool() {
2027 if t.closed.IsSet() {
2030 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2033 return len(t.conns) < t.maxEstablishedConns
2036 func (t *Torrent) wantOutgoingConns() bool {
2037 if !t.newConnsAllowed() {
2040 if len(t.conns) < t.maxEstablishedConns {
2043 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2044 return t.worstBadConn(worseConnLensOpts{
2045 incomingIsBad: numIncomingConns-t.numOutgoingConns() > 1,
2046 outgoingIsBad: false,
2050 func (t *Torrent) wantIncomingConns() 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: false,
2060 outgoingIsBad: t.numOutgoingConns()-numIncomingConns > 1,
2064 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
2067 oldMax = t.maxEstablishedConns
2068 t.maxEstablishedConns = max
2069 wcs := worseConnSlice{
2070 conns: t.appendConns(nil, func(*PeerConn) bool {
2074 wcs.initKeys(worseConnLensOpts{})
2076 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
2077 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
2083 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
2084 t.logger.LazyLog(log.Debug, func() log.Msg {
2085 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
2089 t.cl.event.Broadcast()
2090 if t.closed.IsSet() {
2094 // Don't score the first time a piece is hashed, it could be an initial check.
2095 if p.storageCompletionOk {
2097 pieceHashedCorrect.Add(1)
2100 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
2101 ).AddValues(t, p).LogLevel(
2103 log.Debug, t.logger)
2105 pieceHashedNotCorrect.Add(1)
2110 t.publishPieceChange(piece)
2113 t.publishPieceChange(piece)
2117 if len(p.dirtiers) != 0 {
2118 // Don't increment stats above connection-level for every involved connection.
2119 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2121 for c := range p.dirtiers {
2122 c._stats.incrementPiecesDirtiedGood()
2124 t.clearPieceTouchers(piece)
2125 hasDirty := p.hasDirtyChunks()
2128 p.Flush() // You can be synchronous here!
2130 err := p.Storage().MarkComplete()
2132 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2136 if t.closed.IsSet() {
2139 t.pendAllChunkSpecs(piece)
2141 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2142 // Peers contributed to all the data for this piece hash failure, and the failure was
2143 // not due to errors in the storage (such as data being dropped in a cache).
2145 // Increment Torrent and above stats, and then specific connections.
2146 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2147 for c := range p.dirtiers {
2148 // Y u do dis peer?!
2149 c.stats().incrementPiecesDirtiedBad()
2152 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2153 for c := range p.dirtiers {
2155 bannableTouchers = append(bannableTouchers, c)
2158 t.clearPieceTouchers(piece)
2159 slices.Sort(bannableTouchers, connLessTrusted)
2161 if t.cl.config.Debug {
2163 "bannable conns by trust for piece %d: %v",
2165 func() (ret []connectionTrust) {
2166 for _, c := range bannableTouchers {
2167 ret = append(ret, c.trust())
2174 if len(bannableTouchers) >= 1 {
2175 c := bannableTouchers[0]
2176 if len(bannableTouchers) != 1 {
2177 t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2179 // Turns out it's still useful to ban peers like this because if there's only a
2180 // single peer for a piece, and we never progress that piece to completion, we
2181 // will never smart-ban them. Discovered in
2182 // https://github.com/anacrolix/torrent/issues/715.
2183 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2188 t.onIncompletePiece(piece)
2189 p.Storage().MarkNotComplete()
2191 t.updatePieceCompletion(piece)
2194 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2195 start := t.pieceRequestIndexOffset(piece)
2196 end := start + t.pieceNumChunks(piece)
2197 for ri := start; ri < end; ri++ {
2202 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2203 t.pendAllChunkSpecs(piece)
2204 t.cancelRequestsForPiece(piece)
2205 t.piece(piece).readerCond.Broadcast()
2206 for conn := range t.conns {
2208 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2212 // Called when a piece is found to be not complete.
2213 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2214 if t.pieceAllDirty(piece) {
2215 t.pendAllChunkSpecs(piece)
2217 if !t.wantPieceIndex(piece) {
2218 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2221 // We could drop any connections that we told we have a piece that we
2222 // don't here. But there's a test failure, and it seems clients don't care
2223 // if you request pieces that you already claim to have. Pruning bad
2224 // connections might just remove any connections that aren't treating us
2225 // favourably anyway.
2227 // for c := range t.conns {
2228 // if c.sentHave(piece) {
2232 t.iterPeers(func(conn *Peer) {
2233 if conn.peerHasPiece(piece) {
2234 conn.updateRequests("piece incomplete")
2239 func (t *Torrent) tryCreateMorePieceHashers() {
2240 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2244 func (t *Torrent) tryCreatePieceHasher() bool {
2245 if t.storage == nil {
2248 pi, ok := t.getPieceToHash()
2253 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2255 t.publishPieceChange(pi)
2256 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2257 t.storageLock.RLock()
2258 t.activePieceHashes++
2259 go t.pieceHasher(pi)
2263 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2264 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2265 if t.piece(i).hashing {
2275 func (t *Torrent) dropBannedPeers() {
2276 t.iterPeers(func(p *Peer) {
2277 remoteIp := p.remoteIp()
2278 if remoteIp == nil {
2279 if p.bannableAddr.Ok {
2280 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2284 netipAddr := netip.MustParseAddr(remoteIp.String())
2285 if Some(netipAddr) != p.bannableAddr {
2286 t.logger.WithDefaultLevel(log.Debug).Printf(
2287 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2288 p, remoteIp, p.bannableAddr)
2290 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2291 // Should this be a close?
2293 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2298 func (t *Torrent) pieceHasher(index pieceIndex) {
2300 sum, failedPeers, copyErr := t.hashPiece(index)
2301 correct := sum == *p.hash
2305 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2307 t.storageLock.RUnlock()
2311 for peer := range failedPeers {
2312 t.cl.banPeerIP(peer.AsSlice())
2313 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2316 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2317 t.smartBanCache.ForgetBlock(ri)
2321 t.pieceHashed(index, correct, copyErr)
2322 t.updatePiecePriority(index, "Torrent.pieceHasher")
2323 t.activePieceHashes--
2324 t.tryCreateMorePieceHashers()
2327 // Return the connections that touched a piece, and clear the entries while doing it.
2328 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2330 for c := range p.dirtiers {
2331 delete(c.peerTouchedPieces, pi)
2332 delete(p.dirtiers, c)
2336 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2337 t.iterPeers(func(p *Peer) {
2338 ret = append(ret, p)
2343 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2344 piece := t.piece(pieceIndex)
2345 if piece.queuedForHash() {
2348 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2349 t.publishPieceChange(pieceIndex)
2350 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2351 t.tryCreateMorePieceHashers()
2354 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2355 // before the Info is available.
2356 func (t *Torrent) VerifyData() {
2357 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2358 t.Piece(i).VerifyData()
2362 // Start the process of connecting to the given peer for the given torrent if appropriate. I'm not
2363 // sure all the PeerInfo fields are being used.
2364 func (t *Torrent) initiateConn(peer PeerInfo) {
2365 if peer.Id == t.cl.peerID {
2368 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2372 if t.addrActive(addr.String()) {
2376 t.halfOpen[addr.String()] = peer
2377 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2380 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2381 // quickly make one Client visible to the Torrent of another Client.
2382 func (t *Torrent) AddClientPeer(cl *Client) int {
2383 return t.AddPeers(func() (ps []PeerInfo) {
2384 for _, la := range cl.ListenAddrs() {
2385 ps = append(ps, PeerInfo{
2394 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2396 func (t *Torrent) allStats(f func(*ConnStats)) {
2401 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2402 return t.pieces[i].hashing
2405 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2406 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2409 func (t *Torrent) dialTimeout() time.Duration {
2410 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2413 func (t *Torrent) piece(i int) *Piece {
2417 func (t *Torrent) onWriteChunkErr(err error) {
2418 if t.userOnWriteChunkErr != nil {
2419 go t.userOnWriteChunkErr(err)
2422 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2423 t.disallowDataDownloadLocked()
2426 func (t *Torrent) DisallowDataDownload() {
2427 t.disallowDataDownloadLocked()
2430 func (t *Torrent) disallowDataDownloadLocked() {
2431 t.dataDownloadDisallowed.Set()
2434 func (t *Torrent) AllowDataDownload() {
2435 t.dataDownloadDisallowed.Clear()
2438 // Enables uploading data, if it was disabled.
2439 func (t *Torrent) AllowDataUpload() {
2442 t.dataUploadDisallowed = false
2443 for c := range t.conns {
2444 c.updateRequests("allow data upload")
2448 // Disables uploading data, if it was enabled.
2449 func (t *Torrent) DisallowDataUpload() {
2452 t.dataUploadDisallowed = true
2453 for c := range t.conns {
2454 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2455 c.updateRequests("disallow data upload")
2459 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2460 // or if nil, a critical message is logged, and data download is disabled.
2461 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2464 t.userOnWriteChunkErr = f
2467 func (t *Torrent) iterPeers(f func(p *Peer)) {
2468 for pc := range t.conns {
2471 for _, ws := range t.webSeeds {
2476 func (t *Torrent) callbacks() *Callbacks {
2477 return &t.cl.config.Callbacks
2480 type AddWebSeedsOpt func(*webseed.Client)
2482 // Sets the WebSeed trailing path escaper for a webseed.Client.
2483 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2484 return func(c *webseed.Client) {
2485 c.PathEscaper = custom
2489 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2492 for _, u := range urls {
2493 t.addWebSeed(u, opts...)
2497 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2498 if t.cl.config.DisableWebseeds {
2501 if _, ok := t.webSeeds[url]; ok {
2504 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2505 // right away. This value should be some multiple of the number of connections to a host. I
2506 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2507 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2508 // "https://webtorrent.io/torrents/".
2509 const maxRequests = 16
2515 reconciledHandshakeStats: true,
2516 // This should affect how often we have to recompute requests for this peer. Note that
2517 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2518 // requests mark more often, so recomputation is probably sooner than with regular peer
2519 // conns. ~4x maxRequests would be about right.
2520 PeerMaxRequests: 128,
2521 // TODO: Set ban prefix?
2522 RemoteAddr: remoteAddrFromUrl(url),
2523 callbacks: t.callbacks(),
2525 client: webseed.Client{
2526 HttpClient: t.cl.httpClient,
2528 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2529 return &rateLimitedReader{
2530 l: t.cl.config.DownloadRateLimiter,
2535 activeRequests: make(map[Request]webseed.Request, maxRequests),
2537 ws.peer.initRequestState()
2538 for _, opt := range opts {
2541 ws.peer.initUpdateRequestsTimer()
2542 ws.requesterCond.L = t.cl.locker()
2543 for i := 0; i < maxRequests; i += 1 {
2546 for _, f := range t.callbacks().NewPeer {
2549 ws.peer.logger = t.logger.WithContextValue(&ws)
2550 ws.peer.peerImpl = &ws
2552 ws.onGotInfo(t.info)
2554 t.webSeeds[url] = &ws.peer
2557 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2558 t.iterPeers(func(p1 *Peer) {
2566 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2567 index := t.pieceIndexOfRequestIndex(ri)
2570 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2574 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2575 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2578 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2579 return RequestIndex(piece) * t.chunksPerRegularPiece()
2582 func (t *Torrent) updateComplete() {
2583 t.Complete.SetBool(t.haveAllPieces())
2586 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2587 p := t.requestingPeer(r)
2591 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2592 //delete(t.pendingRequests, r)
2593 if _, ok := t.requestState[r]; ok {
2594 panic("expected request state to be gone")
2599 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2600 return t.requestState[r].peer
2603 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2604 if t.connsWithAllPieces == nil {
2605 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2607 t.connsWithAllPieces[p] = struct{}{}
2610 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2611 _, ok := t.connsWithAllPieces[p]
2612 delete(t.connsWithAllPieces, p)
2616 func (t *Torrent) numActivePeers() int {
2617 return len(t.conns) + len(t.webSeeds)
2620 func (t *Torrent) hasStorageCap() bool {
2621 f := t.storage.Capacity
2629 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2630 return pieceIndex(ri / t.chunksPerRegularPiece())
2633 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2634 reuseIter *typedRoaring.Iterator[RequestIndex],
2636 f func(RequestIndex),
2638 reuseIter.Initialize(&t.dirtyChunks)
2639 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2640 iterBitmapUnsetInRange(
2642 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2647 type requestState struct {
2652 // Returns an error if a received chunk is out of bounds in someway.
2653 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2655 return errors.New("torrent missing info")
2657 if int(r.Index) >= t.numPieces() {
2658 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2660 pieceLength := t.pieceLength(pieceIndex(r.Index))
2661 if r.Begin >= pieceLength {
2662 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2664 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2665 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2666 // should be considerable checks elsewhere for this case due to the network overhead. We should
2667 // catch most of the overflow manipulation stuff by checking index and begin above.
2671 func (t *Torrent) peerConnsWithRemoteAddrPort(addrPort netip.AddrPort) (ret []*PeerConn) {
2672 for pc := range t.conns {
2673 addr := pc.remoteAddrPort()
2674 if !(addr.Ok && addr.Value == addrPort) {
2677 ret = append(ret, pc)
2682 func makeUtHolepunchMsgForPeerConn(
2683 recipient *PeerConn,
2684 msgType utHolepunch.MsgType,
2685 addrPort netip.AddrPort,
2686 errCode utHolepunch.ErrCode,
2688 utHolepunchMsg := utHolepunch.Msg{
2693 extendedPayload, err := utHolepunchMsg.MarshalBinary()
2699 ExtendedID: MapMustGet(recipient.PeerExtensionIDs, utHolepunch.ExtensionName),
2700 ExtendedPayload: extendedPayload,
2704 func (t *Torrent) handleReceivedUtHolepunchMsg(msg utHolepunch.Msg, sender *PeerConn) error {
2705 switch msg.MsgType {
2706 case utHolepunch.Rendezvous:
2709 msgType utHolepunch.MsgType,
2710 addrPort netip.AddrPort,
2711 errCode utHolepunch.ErrCode,
2713 pc.write(makeUtHolepunchMsgForPeerConn(pc, msgType, addrPort, errCode))
2715 targets := t.peerConnsWithRemoteAddrPort(msg.AddrPort)
2716 if len(targets) == 0 {
2717 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NotConnected)
2720 for _, pc := range targets {
2721 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2722 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSupport)
2725 sendMsg(sender, utHolepunch.Connect, msg.AddrPort, 0)
2726 sendMsg(pc, utHolepunch.Connect, sender.remoteAddrPort().Unwrap(), 0)
2728 case utHolepunch.Connect:
2729 t.initiateConn(PeerInfo{
2731 Source: PeerSourceUtHolepunch,
2733 case utHolepunch.Error:
2736 return fmt.Errorf("unhandled msg type %v", msg.MsgType)