20 "github.com/RoaringBitmap/roaring"
21 "github.com/anacrolix/chansync"
22 "github.com/anacrolix/chansync/events"
23 "github.com/anacrolix/dht/v2"
24 . "github.com/anacrolix/generics"
25 g "github.com/anacrolix/generics"
26 "github.com/anacrolix/log"
27 "github.com/anacrolix/missinggo/perf"
28 "github.com/anacrolix/missinggo/slices"
29 "github.com/anacrolix/missinggo/v2"
30 "github.com/anacrolix/missinggo/v2/bitmap"
31 "github.com/anacrolix/missinggo/v2/pubsub"
32 "github.com/anacrolix/multiless"
33 "github.com/anacrolix/sync"
34 "github.com/davecgh/go-spew/spew"
35 "github.com/pion/datachannel"
36 "golang.org/x/exp/maps"
38 "github.com/anacrolix/torrent/bencode"
39 "github.com/anacrolix/torrent/common"
40 "github.com/anacrolix/torrent/metainfo"
41 pp "github.com/anacrolix/torrent/peer_protocol"
42 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
43 request_strategy "github.com/anacrolix/torrent/request-strategy"
44 "github.com/anacrolix/torrent/segments"
45 "github.com/anacrolix/torrent/storage"
46 "github.com/anacrolix/torrent/tracker"
47 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
48 "github.com/anacrolix/torrent/webseed"
49 "github.com/anacrolix/torrent/webtorrent"
52 // Maintains state of torrent within a Client. Many methods should not be called before the info is
53 // available, see .Info and .GotInfo.
55 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
56 // alignment. See #262.
61 networkingEnabled chansync.Flag
62 dataDownloadDisallowed chansync.Flag
63 dataUploadDisallowed bool
64 userOnWriteChunkErr func(error)
66 closed chansync.SetOnce
68 infoHash metainfo.Hash
71 // The order pieces are requested if there's no stronger reason like availability or priority.
72 pieceRequestOrder []int
73 // Values are the piece indices that changed.
74 pieceStateChanges pubsub.PubSub[PieceStateChange]
75 // The size of chunks to request from peers over the wire. This is
76 // normally 16KiB by convention these days.
79 // Total length of the torrent in bytes. Stored because it's not O(1) to
80 // get this from the info dict.
83 // The storage to open when the info dict becomes available.
84 storageOpener *storage.Client
85 // Storage for torrent data.
86 storage *storage.Torrent
87 // Read-locked for using storage, and write-locked for Closing.
88 storageLock sync.RWMutex
90 // TODO: Only announce stuff is used?
91 metainfo metainfo.MetaInfo
93 // The info dict. nil if we don't have it (yet).
95 fileIndex segments.Index
98 _chunksPerRegularPiece chunkIndexType
100 webSeeds map[string]*Peer
101 // Active peer connections, running message stream loops. TODO: Make this
102 // open (not-closed) connections only.
103 conns map[*PeerConn]struct{}
104 maxEstablishedConns int
105 // Set of addrs to which we're attempting to connect. Connections are
106 // half-open until all handshakes are completed.
107 halfOpen map[string]PeerInfo
108 // The final ess is not silent here as it's in the plural.
109 utHolepunchRendezvous map[netip.AddrPort]*utHolepunchRendezvous
111 // Reserve of peers to connect to. A peer can be both here and in the
112 // active connections if were told about the peer after connecting with
113 // them. That encourages us to reconnect to peers that are well known in
115 peers prioritizedPeers
116 // Whether we want to know more peers.
117 wantPeersEvent missinggo.Event
118 // An announcer for each tracker URL.
119 trackerAnnouncers map[string]torrentTrackerAnnouncer
120 // How many times we've initiated a DHT announce. TODO: Move into stats.
123 // Name used if the info name isn't available. Should be cleared when the
124 // Info does become available.
128 // The bencoded bytes of the info dict. This is actively manipulated if
129 // the info bytes aren't initially available, and we try to fetch them
132 // Each element corresponds to the 16KiB metadata pieces. If true, we have
133 // received that piece.
134 metadataCompletedChunks []bool
135 metadataChanged sync.Cond
137 // Closed when .Info is obtained.
138 gotMetainfoC chan struct{}
140 readers map[*reader]struct{}
141 _readerNowPieces bitmap.Bitmap
142 _readerReadaheadPieces bitmap.Bitmap
144 // A cache of pieces we need to get. Calculated from various piece and
145 // file priorities and completion states elsewhere.
146 _pendingPieces roaring.Bitmap
147 // A cache of completed piece indices.
148 _completedPieces roaring.Bitmap
149 // Pieces that need to be hashed.
150 piecesQueuedForHash bitmap.Bitmap
151 activePieceHashes int
152 initialPieceCheckDisabled bool
154 connsWithAllPieces map[*Peer]struct{}
156 requestState map[RequestIndex]requestState
157 // Chunks we've written to since the corresponding piece was last checked.
158 dirtyChunks typedRoaring.Bitmap[RequestIndex]
162 // Is On when all pieces are complete.
163 Complete chansync.Flag
165 // Torrent sources in use keyed by the source string.
166 activeSources sync.Map
167 sourcesLogger log.Logger
169 smartBanCache smartBanCache
171 // Large allocations reused between request state updates.
172 requestPieceStates []request_strategy.PieceRequestOrderState
173 requestIndexes []RequestIndex
176 func (t *Torrent) length() int64 {
177 return t._length.Value
180 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
181 // This could be done with roaring.BitSliceIndexing.
182 t.iterPeers(func(peer *Peer) {
183 if _, ok := t.connsWithAllPieces[peer]; ok {
186 if peer.peerHasPiece(i) {
193 func (t *Torrent) decPieceAvailability(i pieceIndex) {
198 if p.relativeAvailability <= 0 {
199 panic(p.relativeAvailability)
201 p.relativeAvailability--
202 t.updatePieceRequestOrder(i)
205 func (t *Torrent) incPieceAvailability(i pieceIndex) {
206 // If we don't the info, this should be reconciled when we do.
209 p.relativeAvailability++
210 t.updatePieceRequestOrder(i)
214 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
215 return t._readerNowPieces
218 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
219 return t._readerReadaheadPieces
222 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
223 return !t.wantPieceIndex(i)
226 // Returns a channel that is closed when the Torrent is closed.
227 func (t *Torrent) Closed() events.Done {
228 return t.closed.Done()
231 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
232 // pending, and half-open peers.
233 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
234 // Add pending peers to the list
235 t.peers.Each(func(peer PeerInfo) {
236 ks = append(ks, peer)
239 // Add half-open peers to the list
240 for _, peer := range t.halfOpen {
241 ks = append(ks, peer)
244 // Add active peers to the list
245 for conn := range t.conns {
246 ks = append(ks, PeerInfo{
248 Addr: conn.RemoteAddr,
249 Source: conn.Discovery,
250 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
251 // > But if we're not connected to them with an encrypted connection, I couldn't say
252 // > what's appropriate. We can carry forward the SupportsEncryption value as we
253 // > received it from trackers/DHT/PEX, or just use the encryption state for the
254 // > connection. It's probably easiest to do the latter for now.
255 // https://github.com/anacrolix/torrent/pull/188
256 SupportsEncryption: conn.headerEncrypted,
263 func (t *Torrent) setChunkSize(size pp.Integer) {
265 t.chunkPool = sync.Pool{
266 New: func() interface{} {
267 b := make([]byte, size)
273 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
274 return t._completedPieces.Contains(bitmap.BitIndex(piece))
277 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
278 if t.storage == nil {
279 return storage.Completion{Complete: false, Ok: true}
281 return t.pieces[piece].Storage().Completion()
284 // There's a connection to that address already.
285 func (t *Torrent) addrActive(addr string) bool {
286 if _, ok := t.halfOpen[addr]; ok {
289 for c := range t.conns {
291 if ra.String() == addr {
298 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
299 return t.appendConns(ret, func(conn *PeerConn) bool {
300 return !conn.closed.IsSet()
304 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
305 for c := range t.conns {
313 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
315 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
316 if t.closed.IsSet() {
319 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
320 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
321 torrent.Add("peers not added because of bad addr", 1)
322 // cl.logger.Printf("peers not added because of bad addr: %v", p)
326 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
327 torrent.Add("peers replaced", 1)
328 if !replaced.equal(p) {
329 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
336 for t.peers.Len() > cl.config.TorrentPeersHighWater {
337 _, ok := t.peers.DeleteMin()
339 torrent.Add("excess reserve peers discarded", 1)
345 func (t *Torrent) invalidateMetadata() {
346 for i := 0; i < len(t.metadataCompletedChunks); i++ {
347 t.metadataCompletedChunks[i] = false
350 t.gotMetainfoC = make(chan struct{})
355 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
359 if index >= len(t.metadataCompletedChunks) {
360 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
363 copy(t.metadataBytes[(1<<14)*index:], data)
364 t.metadataCompletedChunks[index] = true
367 func (t *Torrent) metadataPieceCount() int {
368 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
371 func (t *Torrent) haveMetadataPiece(piece int) bool {
373 return (1<<14)*piece < len(t.metadataBytes)
375 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
379 func (t *Torrent) metadataSize() int {
380 return len(t.metadataBytes)
383 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
384 for i := 0; i < len(info.Pieces); i += sha1.Size {
385 ret = append(ret, info.Pieces[i:i+sha1.Size])
390 func (t *Torrent) makePieces() {
391 hashes := infoPieceHashes(t.info)
392 t.pieces = make([]Piece, len(hashes))
393 for i, hash := range hashes {
394 piece := &t.pieces[i]
396 piece.index = pieceIndex(i)
397 piece.noPendingWrites.L = &piece.pendingWritesMutex
398 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
400 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
401 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
402 piece.files = files[beginFile:endFile]
406 // Returns the index of the first file containing the piece. files must be
407 // ordered by offset.
408 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
409 for i, f := range files {
410 if f.offset+f.length > pieceOffset {
417 // Returns the index after the last file containing the piece. files must be
418 // ordered by offset.
419 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
420 for i, f := range files {
421 if f.offset+f.length >= pieceEndOffset {
428 func (t *Torrent) cacheLength() {
430 for _, f := range t.info.UpvertedFiles() {
436 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
438 func (t *Torrent) setInfo(info *metainfo.Info) error {
439 if err := validateInfo(info); err != nil {
440 return fmt.Errorf("bad info: %s", err)
442 if t.storageOpener != nil {
444 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
446 return fmt.Errorf("error opening torrent storage: %s", err)
452 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
454 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
455 t.displayName = "" // Save a few bytes lol.
462 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
463 return request_strategy.PieceRequestOrderKey{
464 InfoHash: t.infoHash,
469 // This seems to be all the follow-up tasks after info is set, that can't fail.
470 func (t *Torrent) onSetInfo() {
471 t.pieceRequestOrder = rand.Perm(t.numPieces())
472 t.initPieceRequestOrder()
473 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
474 for i := range t.pieces {
476 // Need to add relativeAvailability before updating piece completion, as that may result in conns
478 if p.relativeAvailability != 0 {
479 panic(p.relativeAvailability)
481 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
482 t.addRequestOrderPiece(i)
483 t.updatePieceCompletion(i)
484 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
485 // t.logger.Printf("piece %s completion unknown, queueing check", p)
489 t.cl.event.Broadcast()
490 close(t.gotMetainfoC)
491 t.updateWantPeersEvent()
492 t.requestState = make(map[RequestIndex]requestState)
493 t.tryCreateMorePieceHashers()
494 t.iterPeers(func(p *Peer) {
496 p.updateRequests("onSetInfo")
500 // Called when metadata for a torrent becomes available.
501 func (t *Torrent) setInfoBytesLocked(b []byte) error {
502 if metainfo.HashBytes(b) != t.infoHash {
503 return errors.New("info bytes have wrong hash")
505 var info metainfo.Info
506 if err := bencode.Unmarshal(b, &info); err != nil {
507 return fmt.Errorf("error unmarshalling info bytes: %s", err)
510 t.metadataCompletedChunks = nil
514 if err := t.setInfo(&info); err != nil {
521 func (t *Torrent) haveAllMetadataPieces() bool {
525 if t.metadataCompletedChunks == nil {
528 for _, have := range t.metadataCompletedChunks {
536 // TODO: Propagate errors to disconnect peer.
537 func (t *Torrent) setMetadataSize(size int) (err error) {
539 // We already know the correct metadata size.
542 if uint32(size) > maxMetadataSize {
543 return log.WithLevel(log.Warning, errors.New("bad size"))
545 if len(t.metadataBytes) == size {
548 t.metadataBytes = make([]byte, size)
549 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
550 t.metadataChanged.Broadcast()
551 for c := range t.conns {
552 c.requestPendingMetadata()
557 // The current working name for the torrent. Either the name in the info dict,
558 // or a display name given such as by the dn value in a magnet link, or "".
559 func (t *Torrent) name() string {
561 defer t.nameMu.RUnlock()
563 return t.info.BestName()
565 if t.displayName != "" {
568 return "infohash:" + t.infoHash.HexString()
571 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
572 p := &t.pieces[index]
573 ret.Priority = t.piecePriority(index)
574 ret.Completion = p.completion()
575 ret.QueuedForHash = p.queuedForHash()
576 ret.Hashing = p.hashing
577 ret.Checking = ret.QueuedForHash || ret.Hashing
578 ret.Marking = p.marking
579 if !ret.Complete && t.piecePartiallyDownloaded(index) {
585 func (t *Torrent) metadataPieceSize(piece int) int {
586 return metadataPieceSize(len(t.metadataBytes), piece)
589 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
592 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
593 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
595 TotalSize: len(t.metadataBytes),
601 type pieceAvailabilityRun struct {
606 func (me pieceAvailabilityRun) String() string {
607 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
610 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
611 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
612 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
614 for i := range t.pieces {
615 rle.Append(t.pieces[i].availability(), 1)
621 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
622 freqs = make([]int, t.numActivePeers()+1)
623 for i := range t.pieces {
624 freqs[t.piece(i).availability()]++
629 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
630 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
631 ret = append(ret, PieceStateRun{
632 PieceState: el.(PieceState),
636 for index := range t.pieces {
637 rle.Append(t.pieceState(pieceIndex(index)), 1)
643 // Produces a small string representing a PieceStateRun.
644 func (psr PieceStateRun) String() (ret string) {
645 ret = fmt.Sprintf("%d", psr.Length)
646 ret += func() string {
647 switch psr.Priority {
648 case PiecePriorityNext:
650 case PiecePriorityNormal:
652 case PiecePriorityReadahead:
654 case PiecePriorityNow:
656 case PiecePriorityHigh:
665 if psr.QueuedForHash {
683 func (t *Torrent) writeStatus(w io.Writer) {
684 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
685 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
687 fmt.Fprintf(w, "Metadata have: ")
688 for _, h := range t.metadataCompletedChunks {
689 fmt.Fprintf(w, "%c", func() rune {
699 fmt.Fprintf(w, "Piece length: %s\n",
702 return fmt.Sprintf("%v (%v chunks)",
704 float64(t.usualPieceSize())/float64(t.chunkSize))
711 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
712 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
713 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
714 // availability frequencies instead.
716 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
717 for _, run := range t.pieceAvailabilityRuns() {
718 ret = append(ret, run.String())
723 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
724 func() (ret []string) {
725 for avail, freq := range t.pieceAvailabilityFrequencies() {
729 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
735 fmt.Fprintf(w, "Reader Pieces:")
736 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
737 fmt.Fprintf(w, " %d:%d", begin, end)
742 fmt.Fprintf(w, "Enabled trackers:\n")
744 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
745 fmt.Fprintf(tw, " URL\tExtra\n")
746 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
749 var luns, runs url.URL = *lu, *ru
752 var ml missinggo.MultiLess
753 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
754 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
756 }).([]torrentTrackerAnnouncer) {
757 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
762 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
764 spew.NewDefaultConfig()
765 spew.Fdump(w, t.statsLocked())
767 fmt.Fprintf(w, "webseeds:\n")
768 t.writePeerStatuses(w, maps.Values(t.webSeeds))
770 peerConns := maps.Keys(t.conns)
771 // Peers without priorities first, then those with. I'm undecided about how to order peers
772 // without priorities.
773 sort.Slice(peerConns, func(li, ri int) bool {
776 ml := multiless.New()
777 lpp := g.ResultFromTuple(l.peerPriority()).ToOption()
778 rpp := g.ResultFromTuple(r.peerPriority()).ToOption()
779 ml = ml.Bool(lpp.Ok, rpp.Ok)
780 ml = ml.Uint32(rpp.Value, lpp.Value)
784 fmt.Fprintf(w, "peer conns:\n")
785 t.writePeerStatuses(w, g.SliceMap(peerConns, func(pc *PeerConn) *Peer {
790 func (t *Torrent) writePeerStatuses(w io.Writer, peers []*Peer) {
792 for _, c := range peers {
796 w.Write(bytes.TrimRight(
797 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
802 func (t *Torrent) haveInfo() bool {
806 // Returns a run-time generated MetaInfo that includes the info bytes and
807 // announce-list as currently known to the client.
808 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
809 return metainfo.MetaInfo{
810 CreationDate: time.Now().Unix(),
811 Comment: "dynamic metainfo from client",
812 CreatedBy: "go.torrent",
813 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
814 InfoBytes: func() []byte {
816 return t.metadataBytes
821 UrlList: func() []string {
822 ret := make([]string, 0, len(t.webSeeds))
823 for url := range t.webSeeds {
824 ret = append(ret, url)
832 func (t *Torrent) BytesMissing() (n int64) {
834 n = t.bytesMissingLocked()
839 func (t *Torrent) bytesMissingLocked() int64 {
843 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
844 roaring.Flip(b, 0, end).Iterate(cb)
847 func (t *Torrent) bytesLeft() (left int64) {
848 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
849 p := t.piece(pieceIndex(x))
850 left += int64(p.length() - p.numDirtyBytes())
856 // Bytes left to give in tracker announces.
857 func (t *Torrent) bytesLeftAnnounce() int64 {
865 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
866 if t.pieceComplete(piece) {
869 if t.pieceAllDirty(piece) {
872 return t.pieces[piece].hasDirtyChunks()
875 func (t *Torrent) usualPieceSize() int {
876 return int(t.info.PieceLength)
879 func (t *Torrent) numPieces() pieceIndex {
880 return t.info.NumPieces()
883 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
884 return pieceIndex(t._completedPieces.GetCardinality())
887 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
889 err = errors.New("already closed")
892 for _, f := range t.onClose {
895 if t.storage != nil {
900 defer t.storageLock.Unlock()
901 if f := t.storage.Close; f != nil {
904 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
909 t.iterPeers(func(p *Peer) {
912 if t.storage != nil {
913 t.deletePieceRequestOrder()
915 t.assertAllPiecesRelativeAvailabilityZero()
917 t.cl.event.Broadcast()
918 t.pieceStateChanges.Close()
919 t.updateWantPeersEvent()
923 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
924 for i := range t.pieces {
926 if p.relativeAvailability != 0 {
927 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
932 func (t *Torrent) requestOffset(r Request) int64 {
933 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
936 // Return the request that would include the given offset into the torrent data. Returns !ok if
937 // there is no such request.
938 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
939 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
942 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
943 defer perf.ScopeTimerErr(&err)()
944 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
945 if err == nil && n != len(data) {
946 err = io.ErrShortWrite
951 func (t *Torrent) bitfield() (bf []bool) {
952 bf = make([]bool, t.numPieces())
953 t._completedPieces.Iterate(func(piece uint32) (again bool) {
960 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
961 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
964 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
965 return t._chunksPerRegularPiece
968 func (t *Torrent) numChunks() RequestIndex {
969 if t.numPieces() == 0 {
972 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
975 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
976 t.dirtyChunks.RemoveRange(
977 uint64(t.pieceRequestIndexOffset(pieceIndex)),
978 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
981 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
982 if t.info.PieceLength == 0 {
983 // There will be no variance amongst pieces. Only pain.
986 if piece == t.numPieces()-1 {
987 ret := pp.Integer(t.length() % t.info.PieceLength)
992 return pp.Integer(t.info.PieceLength)
995 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
996 return &blockCheckingWriter{
997 cache: &t.smartBanCache,
998 requestIndex: t.pieceRequestIndexOffset(piece),
999 chunkSize: t.chunkSize.Int(),
1003 func (t *Torrent) hashPiece(piece pieceIndex) (
1005 // These are peers that sent us blocks that differ from what we hash here.
1006 differingPeers map[bannableAddr]struct{},
1010 p.waitNoPendingWrites()
1011 storagePiece := t.pieces[piece].Storage()
1013 // Does the backend want to do its own hashing?
1014 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
1015 var sum metainfo.Hash
1016 // log.Printf("A piece decided to self-hash: %d", piece)
1017 sum, err = i.SelfHash()
1018 missinggo.CopyExact(&ret, sum)
1022 hash := pieceHash.New()
1023 const logPieceContents = false
1024 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1025 writers := []io.Writer{hash, smartBanWriter}
1026 var examineBuf bytes.Buffer
1027 if logPieceContents {
1028 writers = append(writers, &examineBuf)
1030 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1031 if logPieceContents {
1032 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1034 smartBanWriter.Flush()
1035 differingPeers = smartBanWriter.badPeers
1036 missinggo.CopyExact(&ret, hash.Sum(nil))
1040 func (t *Torrent) haveAnyPieces() bool {
1041 return !t._completedPieces.IsEmpty()
1044 func (t *Torrent) haveAllPieces() bool {
1048 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1051 func (t *Torrent) havePiece(index pieceIndex) bool {
1052 return t.haveInfo() && t.pieceComplete(index)
1055 func (t *Torrent) maybeDropMutuallyCompletePeer(
1056 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1060 if !t.cl.config.DropMutuallyCompletePeers {
1063 if !t.haveAllPieces() {
1066 if all, known := p.peerHasAllPieces(); !(known && all) {
1072 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1076 func (t *Torrent) haveChunk(r Request) (ret bool) {
1078 // log.Println("have chunk", r, ret)
1083 if t.pieceComplete(pieceIndex(r.Index)) {
1086 p := &t.pieces[r.Index]
1087 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1090 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1091 return chunkIndexType(cs.Begin / chunkSize)
1094 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1095 return t._pendingPieces.Contains(uint32(index))
1098 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1099 // conns (which is a map).
1100 var peerConnSlices sync.Pool
1102 func getPeerConnSlice(cap int) []*PeerConn {
1103 getInterface := peerConnSlices.Get()
1104 if getInterface == nil {
1105 return make([]*PeerConn, 0, cap)
1107 return getInterface.([]*PeerConn)[:0]
1111 // Calls the given function with a slice of unclosed conns. It uses a pool to reduce allocations as
1112 // this is a frequent occurrence.
1113 func (t *Torrent) withUnclosedConns(f func([]*PeerConn)) {
1114 sl := t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))
1116 peerConnSlices.Put(sl)
1119 func (t *Torrent) worstBadConnFromSlice(opts worseConnLensOpts, sl []*PeerConn) *PeerConn {
1120 wcs := worseConnSlice{conns: sl}
1123 for wcs.Len() != 0 {
1124 c := heap.Pop(&wcs).(*PeerConn)
1125 if opts.incomingIsBad && !c.outgoing {
1128 if opts.outgoingIsBad && c.outgoing {
1131 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1134 // If the connection is in the worst half of the established
1135 // connection quota and is older than a minute.
1136 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1137 // Give connections 1 minute to prove themselves.
1138 if time.Since(c.completedHandshake) > time.Minute {
1146 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1147 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1148 // established connections for more than a minute. This is O(n log n). If there was a way to not
1149 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1150 func (t *Torrent) worstBadConn(opts worseConnLensOpts) (ret *PeerConn) {
1151 t.withUnclosedConns(func(ucs []*PeerConn) {
1152 ret = t.worstBadConnFromSlice(opts, ucs)
1157 type PieceStateChange struct {
1162 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1163 t.cl._mu.Defer(func() {
1164 cur := t.pieceState(piece)
1165 p := &t.pieces[piece]
1166 if cur != p.publicPieceState {
1167 p.publicPieceState = cur
1168 t.pieceStateChanges.Publish(PieceStateChange{
1176 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1177 if t.pieceComplete(piece) {
1180 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1183 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1184 return t.pieces[piece].allChunksDirty()
1187 func (t *Torrent) readersChanged() {
1188 t.updateReaderPieces()
1189 t.updateAllPiecePriorities("Torrent.readersChanged")
1192 func (t *Torrent) updateReaderPieces() {
1193 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1196 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1200 t.updateReaderPieces()
1201 // Order the ranges, high and low.
1203 if l.begin > h.begin {
1206 if l.end < h.begin {
1207 // Two distinct ranges.
1208 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1209 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1216 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1220 func (t *Torrent) maybeNewConns() {
1221 // Tickle the accept routine.
1222 t.cl.event.Broadcast()
1226 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1227 if t._pendingPieces.Contains(uint32(piece)) {
1228 t.iterPeers(func(c *Peer) {
1229 // if c.requestState.Interested {
1232 if !c.isLowOnRequests() {
1235 if !c.peerHasPiece(piece) {
1238 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1241 c.updateRequests(reason)
1245 t.publishPieceChange(piece)
1248 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1249 if !t.closed.IsSet() {
1250 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1252 t.updatePieceRequestOrder(piece)
1254 p := &t.pieces[piece]
1255 newPrio := p.uncachedPriority()
1256 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1257 if newPrio == PiecePriorityNone {
1258 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1262 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1266 t.piecePriorityChanged(piece, reason)
1269 func (t *Torrent) updateAllPiecePriorities(reason string) {
1270 t.updatePiecePriorities(0, t.numPieces(), reason)
1273 // Update all piece priorities in one hit. This function should have the same
1274 // output as updatePiecePriority, but across all pieces.
1275 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1276 for i := begin; i < end; i++ {
1277 t.updatePiecePriority(i, reason)
1281 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1282 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1283 if off >= t.length() {
1293 begin = pieceIndex(off / t.info.PieceLength)
1294 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1295 if end > pieceIndex(t.info.NumPieces()) {
1296 end = pieceIndex(t.info.NumPieces())
1301 // Returns true if all iterations complete without breaking. Returns the read regions for all
1302 // readers. The reader regions should not be merged as some callers depend on this method to
1303 // enumerate readers.
1304 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1305 for r := range t.readers {
1307 if p.begin >= p.end {
1310 if !f(p.begin, p.end) {
1317 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1318 return t.piece(piece).uncachedPriority()
1321 func (t *Torrent) pendRequest(req RequestIndex) {
1322 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1325 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1326 t.cl.event.Broadcast()
1327 if t.pieceComplete(piece) {
1328 t.onPieceCompleted(piece)
1330 t.onIncompletePiece(piece)
1332 t.updatePiecePriority(piece, reason)
1335 func (t *Torrent) numReceivedConns() (ret int) {
1336 for c := range t.conns {
1337 if c.Discovery == PeerSourceIncoming {
1344 func (t *Torrent) numOutgoingConns() (ret int) {
1345 for c := range t.conns {
1353 func (t *Torrent) maxHalfOpen() int {
1354 // Note that if we somehow exceed the maximum established conns, we want
1355 // the negative value to have an effect.
1356 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1357 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1358 // We want to allow some experimentation with new peers, and to try to
1359 // upset an oversupply of received connections.
1361 max(5, extraIncoming)+establishedHeadroom,
1362 int64(t.cl.config.HalfOpenConnsPerTorrent),
1366 func (t *Torrent) openNewConns() (initiated int) {
1367 defer t.updateWantPeersEvent()
1368 for t.peers.Len() != 0 {
1369 if !t.wantOutgoingConns() {
1372 if len(t.halfOpen) >= t.maxHalfOpen() {
1375 if len(t.cl.dialers) == 0 {
1378 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1381 p := t.peers.PopMax()
1382 t.initiateConn(p, false, false)
1388 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1390 uncached := t.pieceCompleteUncached(piece)
1391 cached := p.completion()
1392 changed := cached != uncached
1393 complete := uncached.Complete
1394 p.storageCompletionOk = uncached.Ok
1397 t._completedPieces.Add(x)
1400 t._completedPieces.Remove(x)
1402 p.t.updatePieceRequestOrder(piece)
1404 if complete && len(p.dirtiers) != 0 {
1405 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1408 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1409 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1414 // Non-blocking read. Client lock is not required.
1415 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1417 p := &t.pieces[off/t.info.PieceLength]
1418 p.waitNoPendingWrites()
1420 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1431 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1432 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1433 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1434 func (t *Torrent) maybeCompleteMetadata() error {
1439 if !t.haveAllMetadataPieces() {
1440 // Don't have enough metadata pieces.
1443 err := t.setInfoBytesLocked(t.metadataBytes)
1445 t.invalidateMetadata()
1446 return fmt.Errorf("error setting info bytes: %s", err)
1448 if t.cl.config.Debug {
1449 t.logger.Printf("%s: got metadata from peers", t)
1454 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1455 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1457 now.Add(bitmap.BitIndex(begin))
1458 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1465 func (t *Torrent) needData() bool {
1466 if t.closed.IsSet() {
1472 return !t._pendingPieces.IsEmpty()
1475 func appendMissingStrings(old, new []string) (ret []string) {
1478 for _, n := range new {
1479 for _, o := range old {
1484 ret = append(ret, n)
1489 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1491 for minNumTiers > len(ret) {
1492 ret = append(ret, nil)
1497 func (t *Torrent) addTrackers(announceList [][]string) {
1498 fullAnnounceList := &t.metainfo.AnnounceList
1499 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1500 for tierIndex, trackerURLs := range announceList {
1501 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1503 t.startMissingTrackerScrapers()
1504 t.updateWantPeersEvent()
1507 // Don't call this before the info is available.
1508 func (t *Torrent) bytesCompleted() int64 {
1512 return t.length() - t.bytesLeft()
1515 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1518 return t.setInfoBytesLocked(b)
1521 // Returns true if connection is removed from torrent.Conns.
1522 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1523 if !c.closed.IsSet() {
1524 panic("connection is not closed")
1525 // There are behaviours prevented by the closed state that will fail
1526 // if the connection has been deleted.
1530 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1531 // the drop event against the PexConnState instead.
1533 if !t.cl.config.DisablePEX {
1537 torrent.Add("deleted connections", 1)
1538 c.deleteAllRequests("Torrent.deletePeerConn")
1539 t.assertPendingRequests()
1540 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1541 panic(t.connsWithAllPieces)
1546 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1547 if t.deleteConnWithAllPieces(p) {
1553 p.peerPieces().Iterate(func(i uint32) bool {
1554 p.t.decPieceAvailability(pieceIndex(i))
1559 func (t *Torrent) assertPendingRequests() {
1563 // var actual pendingRequests
1564 // if t.haveInfo() {
1565 // actual.m = make([]int, t.numChunks())
1567 // t.iterPeers(func(p *Peer) {
1568 // p.requestState.Requests.Iterate(func(x uint32) bool {
1573 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1579 func (t *Torrent) dropConnection(c *PeerConn) {
1580 t.cl.event.Broadcast()
1582 if t.deletePeerConn(c) {
1587 // Peers as in contact information for dialing out.
1588 func (t *Torrent) wantPeers() bool {
1589 if t.closed.IsSet() {
1592 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1595 return t.wantOutgoingConns()
1598 func (t *Torrent) updateWantPeersEvent() {
1600 t.wantPeersEvent.Set()
1602 t.wantPeersEvent.Clear()
1606 // Returns whether the client should make effort to seed the torrent.
1607 func (t *Torrent) seeding() bool {
1609 if t.closed.IsSet() {
1612 if t.dataUploadDisallowed {
1615 if cl.config.NoUpload {
1618 if !cl.config.Seed {
1621 if cl.config.DisableAggressiveUpload && t.needData() {
1627 func (t *Torrent) onWebRtcConn(
1628 c datachannel.ReadWriteCloser,
1629 dcc webtorrent.DataChannelContext,
1632 netConn := webrtcNetConn{
1634 DataChannelContext: dcc,
1636 peerRemoteAddr := netConn.RemoteAddr()
1637 //t.logger.Levelf(log.Critical, "onWebRtcConn remote addr: %v", peerRemoteAddr)
1638 if t.cl.badPeerAddr(peerRemoteAddr) {
1641 localAddrIpPort := missinggo.IpPortFromNetAddr(netConn.LocalAddr())
1642 pc, err := t.cl.initiateProtocolHandshakes(
1643 context.Background(),
1648 outgoing: dcc.LocalOffered,
1649 remoteAddr: peerRemoteAddr,
1650 localPublicAddr: localAddrIpPort,
1651 network: webrtcNetwork,
1652 connString: fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1656 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1659 if dcc.LocalOffered {
1660 pc.Discovery = PeerSourceTracker
1662 pc.Discovery = PeerSourceIncoming
1664 pc.conn.SetWriteDeadline(time.Time{})
1667 err = t.cl.runHandshookConn(pc, t)
1669 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1673 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1674 err := t.cl.runHandshookConn(pc, t)
1675 if err != nil || logAll {
1676 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1680 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1681 t.logRunHandshookConn(pc, false, log.Debug)
1684 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1685 wtc, release := t.cl.websocketTrackers.Get(u.String(), t.infoHash)
1686 // This needs to run before the Torrent is dropped from the Client, to prevent a new webtorrent.TrackerClient for
1687 // the same info hash before the old one is cleaned up.
1688 t.onClose = append(t.onClose, release)
1689 wst := websocketTrackerStatus{u, wtc}
1691 err := wtc.Announce(tracker.Started, t.infoHash)
1693 t.logger.WithDefaultLevel(log.Warning).Printf(
1694 "error in initial announce to %q: %v",
1702 func (t *Torrent) startScrapingTracker(_url string) {
1706 u, err := url.Parse(_url)
1708 // URLs with a leading '*' appear to be a uTorrent convention to
1709 // disable trackers.
1711 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1715 if u.Scheme == "udp" {
1717 t.startScrapingTracker(u.String())
1719 t.startScrapingTracker(u.String())
1722 if _, ok := t.trackerAnnouncers[_url]; ok {
1725 sl := func() torrentTrackerAnnouncer {
1728 if t.cl.config.DisableWebtorrent {
1731 return t.startWebsocketAnnouncer(*u)
1733 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1737 if t.cl.config.DisableIPv6 {
1741 newAnnouncer := &trackerScraper{
1744 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1746 go newAnnouncer.Run()
1752 if t.trackerAnnouncers == nil {
1753 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1755 t.trackerAnnouncers[_url] = sl
1758 // Adds and starts tracker scrapers for tracker URLs that aren't already
1760 func (t *Torrent) startMissingTrackerScrapers() {
1761 if t.cl.config.DisableTrackers {
1764 t.startScrapingTracker(t.metainfo.Announce)
1765 for _, tier := range t.metainfo.AnnounceList {
1766 for _, url := range tier {
1767 t.startScrapingTracker(url)
1772 // Returns an AnnounceRequest with fields filled out to defaults and current
1774 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1775 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1776 // dependent on the network in use.
1777 return tracker.AnnounceRequest{
1779 NumWant: func() int32 {
1780 if t.wantPeers() && len(t.cl.dialers) > 0 {
1781 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1786 Port: uint16(t.cl.incomingPeerPort()),
1787 PeerId: t.cl.peerID,
1788 InfoHash: t.infoHash,
1789 Key: t.cl.announceKey(),
1791 // The following are vaguely described in BEP 3.
1793 Left: t.bytesLeftAnnounce(),
1794 Uploaded: t.stats.BytesWrittenData.Int64(),
1795 // There's no mention of wasted or unwanted download in the BEP.
1796 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1800 // Adds peers revealed in an announce until the announce ends, or we have
1802 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1804 for v := range pvs {
1807 for _, cp := range v.Peers {
1809 // Can't do anything with this.
1812 if t.addPeer(PeerInfo{
1813 Addr: ipPortAddr{cp.IP, cp.Port},
1814 Source: PeerSourceDhtGetPeers,
1821 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1826 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1827 // announce ends. stop will force the announce to end.
1828 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1829 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1833 _done := make(chan struct{})
1837 t.consumeDhtAnnouncePeers(ps.Peers())
1843 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1844 _, stop, err := t.AnnounceToDht(s)
1849 case <-t.closed.Done():
1850 case <-time.After(5 * time.Minute):
1856 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1862 if t.closed.IsSet() {
1865 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1866 // TODO: We can include the announce_peer step depending on whether we can receive
1867 // inbound connections. We should probably only announce once every 15 mins too.
1868 if !t.wantAnyConns() {
1871 // TODO: Determine if there's a listener on the port we're announcing.
1872 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1883 err := t.timeboxedAnnounceToDht(s)
1885 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1891 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1892 for _, p := range peers {
1900 // The returned TorrentStats may require alignment in memory. See
1901 // https://github.com/anacrolix/torrent/issues/383.
1902 func (t *Torrent) Stats() TorrentStats {
1904 defer t.cl.rUnlock()
1905 return t.statsLocked()
1908 func (t *Torrent) statsLocked() (ret TorrentStats) {
1909 ret.ActivePeers = len(t.conns)
1910 ret.HalfOpenPeers = len(t.halfOpen)
1911 ret.PendingPeers = t.peers.Len()
1912 ret.TotalPeers = t.numTotalPeers()
1913 ret.ConnectedSeeders = 0
1914 for c := range t.conns {
1915 if all, ok := c.peerHasAllPieces(); all && ok {
1916 ret.ConnectedSeeders++
1919 ret.ConnStats = t.stats.Copy()
1920 ret.PiecesComplete = t.numPiecesCompleted()
1924 // The total number of peers in the torrent.
1925 func (t *Torrent) numTotalPeers() int {
1926 peers := make(map[string]struct{})
1927 for conn := range t.conns {
1928 ra := conn.conn.RemoteAddr()
1930 // It's been closed and doesn't support RemoteAddr.
1933 peers[ra.String()] = struct{}{}
1935 for addr := range t.halfOpen {
1936 peers[addr] = struct{}{}
1938 t.peers.Each(func(peer PeerInfo) {
1939 peers[peer.Addr.String()] = struct{}{}
1944 // Reconcile bytes transferred before connection was associated with a
1946 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1947 if c._stats != (ConnStats{
1948 // Handshakes should only increment these fields:
1949 BytesWritten: c._stats.BytesWritten,
1950 BytesRead: c._stats.BytesRead,
1954 c.postHandshakeStats(func(cs *ConnStats) {
1955 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1956 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1958 c.reconciledHandshakeStats = true
1961 // Returns true if the connection is added.
1962 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1965 torrent.Add("added connections", 1)
1968 if t.closed.IsSet() {
1969 return errors.New("torrent closed")
1971 for c0 := range t.conns {
1972 if c.PeerID != c0.PeerID {
1975 if !t.cl.config.DropDuplicatePeerIds {
1978 if c.hasPreferredNetworkOver(c0) {
1980 t.deletePeerConn(c0)
1982 return errors.New("existing connection preferred")
1985 if len(t.conns) >= t.maxEstablishedConns {
1986 numOutgoing := t.numOutgoingConns()
1987 numIncoming := len(t.conns) - numOutgoing
1988 c := t.worstBadConn(worseConnLensOpts{
1989 // We've already established that we have too many connections at this point, so we just
1990 // need to match what kind we have too many of vs. what we're trying to add now.
1991 incomingIsBad: (numIncoming-numOutgoing > 1) && c.outgoing,
1992 outgoingIsBad: (numOutgoing-numIncoming > 1) && !c.outgoing,
1995 return errors.New("don't want conn")
2000 if len(t.conns) >= t.maxEstablishedConns {
2003 t.conns[c] = struct{}{}
2004 t.cl.event.Broadcast()
2005 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
2006 t.pex.Add(c) // as no further extended handshake expected
2011 func (t *Torrent) newConnsAllowed() bool {
2012 if !t.networkingEnabled.Bool() {
2015 if t.closed.IsSet() {
2018 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2024 func (t *Torrent) wantAnyConns() bool {
2025 if !t.networkingEnabled.Bool() {
2028 if t.closed.IsSet() {
2031 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2034 return len(t.conns) < t.maxEstablishedConns
2037 func (t *Torrent) wantOutgoingConns() bool {
2038 if !t.newConnsAllowed() {
2041 if len(t.conns) < t.maxEstablishedConns {
2044 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2045 return t.worstBadConn(worseConnLensOpts{
2046 incomingIsBad: numIncomingConns-t.numOutgoingConns() > 1,
2047 outgoingIsBad: false,
2051 func (t *Torrent) wantIncomingConns() bool {
2052 if !t.newConnsAllowed() {
2055 if len(t.conns) < t.maxEstablishedConns {
2058 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2059 return t.worstBadConn(worseConnLensOpts{
2060 incomingIsBad: false,
2061 outgoingIsBad: t.numOutgoingConns()-numIncomingConns > 1,
2065 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
2068 oldMax = t.maxEstablishedConns
2069 t.maxEstablishedConns = max
2070 wcs := worseConnSlice{
2071 conns: t.appendConns(nil, func(*PeerConn) bool {
2075 wcs.initKeys(worseConnLensOpts{})
2077 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
2078 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
2084 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
2085 t.logger.LazyLog(log.Debug, func() log.Msg {
2086 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
2090 t.cl.event.Broadcast()
2091 if t.closed.IsSet() {
2095 // Don't score the first time a piece is hashed, it could be an initial check.
2096 if p.storageCompletionOk {
2098 pieceHashedCorrect.Add(1)
2101 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
2102 ).AddValues(t, p).LogLevel(
2104 log.Debug, t.logger)
2106 pieceHashedNotCorrect.Add(1)
2111 t.publishPieceChange(piece)
2114 t.publishPieceChange(piece)
2118 if len(p.dirtiers) != 0 {
2119 // Don't increment stats above connection-level for every involved connection.
2120 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2122 for c := range p.dirtiers {
2123 c._stats.incrementPiecesDirtiedGood()
2125 t.clearPieceTouchers(piece)
2126 hasDirty := p.hasDirtyChunks()
2129 p.Flush() // You can be synchronous here!
2131 err := p.Storage().MarkComplete()
2133 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2137 if t.closed.IsSet() {
2140 t.pendAllChunkSpecs(piece)
2142 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2143 // Peers contributed to all the data for this piece hash failure, and the failure was
2144 // not due to errors in the storage (such as data being dropped in a cache).
2146 // Increment Torrent and above stats, and then specific connections.
2147 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2148 for c := range p.dirtiers {
2149 // Y u do dis peer?!
2150 c.stats().incrementPiecesDirtiedBad()
2153 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2154 for c := range p.dirtiers {
2156 bannableTouchers = append(bannableTouchers, c)
2159 t.clearPieceTouchers(piece)
2160 slices.Sort(bannableTouchers, connLessTrusted)
2162 if t.cl.config.Debug {
2164 "bannable conns by trust for piece %d: %v",
2166 func() (ret []connectionTrust) {
2167 for _, c := range bannableTouchers {
2168 ret = append(ret, c.trust())
2175 if len(bannableTouchers) >= 1 {
2176 c := bannableTouchers[0]
2177 if len(bannableTouchers) != 1 {
2178 t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2180 // Turns out it's still useful to ban peers like this because if there's only a
2181 // single peer for a piece, and we never progress that piece to completion, we
2182 // will never smart-ban them. Discovered in
2183 // https://github.com/anacrolix/torrent/issues/715.
2184 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2189 t.onIncompletePiece(piece)
2190 p.Storage().MarkNotComplete()
2192 t.updatePieceCompletion(piece)
2195 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2196 start := t.pieceRequestIndexOffset(piece)
2197 end := start + t.pieceNumChunks(piece)
2198 for ri := start; ri < end; ri++ {
2203 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2204 t.pendAllChunkSpecs(piece)
2205 t.cancelRequestsForPiece(piece)
2206 t.piece(piece).readerCond.Broadcast()
2207 for conn := range t.conns {
2209 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2213 // Called when a piece is found to be not complete.
2214 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2215 if t.pieceAllDirty(piece) {
2216 t.pendAllChunkSpecs(piece)
2218 if !t.wantPieceIndex(piece) {
2219 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2222 // We could drop any connections that we told we have a piece that we
2223 // don't here. But there's a test failure, and it seems clients don't care
2224 // if you request pieces that you already claim to have. Pruning bad
2225 // connections might just remove any connections that aren't treating us
2226 // favourably anyway.
2228 // for c := range t.conns {
2229 // if c.sentHave(piece) {
2233 t.iterPeers(func(conn *Peer) {
2234 if conn.peerHasPiece(piece) {
2235 conn.updateRequests("piece incomplete")
2240 func (t *Torrent) tryCreateMorePieceHashers() {
2241 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2245 func (t *Torrent) tryCreatePieceHasher() bool {
2246 if t.storage == nil {
2249 pi, ok := t.getPieceToHash()
2254 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2256 t.publishPieceChange(pi)
2257 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2258 t.storageLock.RLock()
2259 t.activePieceHashes++
2260 go t.pieceHasher(pi)
2264 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2265 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2266 if t.piece(i).hashing {
2276 func (t *Torrent) dropBannedPeers() {
2277 t.iterPeers(func(p *Peer) {
2278 remoteIp := p.remoteIp()
2279 if remoteIp == nil {
2280 if p.bannableAddr.Ok {
2281 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2285 netipAddr := netip.MustParseAddr(remoteIp.String())
2286 if Some(netipAddr) != p.bannableAddr {
2287 t.logger.WithDefaultLevel(log.Debug).Printf(
2288 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2289 p, remoteIp, p.bannableAddr)
2291 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2292 // Should this be a close?
2294 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2299 func (t *Torrent) pieceHasher(index pieceIndex) {
2301 sum, failedPeers, copyErr := t.hashPiece(index)
2302 correct := sum == *p.hash
2306 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2308 t.storageLock.RUnlock()
2312 for peer := range failedPeers {
2313 t.cl.banPeerIP(peer.AsSlice())
2314 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2317 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2318 t.smartBanCache.ForgetBlock(ri)
2322 t.pieceHashed(index, correct, copyErr)
2323 t.updatePiecePriority(index, "Torrent.pieceHasher")
2324 t.activePieceHashes--
2325 t.tryCreateMorePieceHashers()
2328 // Return the connections that touched a piece, and clear the entries while doing it.
2329 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2331 for c := range p.dirtiers {
2332 delete(c.peerTouchedPieces, pi)
2333 delete(p.dirtiers, c)
2337 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2338 t.iterPeers(func(p *Peer) {
2339 ret = append(ret, p)
2344 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2345 piece := t.piece(pieceIndex)
2346 if piece.queuedForHash() {
2349 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2350 t.publishPieceChange(pieceIndex)
2351 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2352 t.tryCreateMorePieceHashers()
2355 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2356 // before the Info is available.
2357 func (t *Torrent) VerifyData() {
2358 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2359 t.Piece(i).VerifyData()
2363 // Start the process of connecting to the given peer for the given torrent if appropriate. I'm not
2364 // sure all the PeerInfo fields are being used.
2365 func (t *Torrent) initiateConn(
2367 requireRendezvous bool,
2368 skipHolepunchRendezvous bool,
2370 if peer.Id == t.cl.peerID {
2373 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2377 if t.addrActive(addr.String()) {
2381 t.halfOpen[addr.String()] = peer
2382 go t.cl.outgoingConnection(outgoingConnOpts{
2385 requireRendezvous: requireRendezvous,
2386 skipHolepunchRendezvous: skipHolepunchRendezvous,
2387 }, peer.Source, peer.Trusted)
2390 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2391 // quickly make one Client visible to the Torrent of another Client.
2392 func (t *Torrent) AddClientPeer(cl *Client) int {
2393 return t.AddPeers(func() (ps []PeerInfo) {
2394 for _, la := range cl.ListenAddrs() {
2395 ps = append(ps, PeerInfo{
2404 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2406 func (t *Torrent) allStats(f func(*ConnStats)) {
2411 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2412 return t.pieces[i].hashing
2415 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2416 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2419 func (t *Torrent) dialTimeout() time.Duration {
2420 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2423 func (t *Torrent) piece(i int) *Piece {
2427 func (t *Torrent) onWriteChunkErr(err error) {
2428 if t.userOnWriteChunkErr != nil {
2429 go t.userOnWriteChunkErr(err)
2432 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2433 t.disallowDataDownloadLocked()
2436 func (t *Torrent) DisallowDataDownload() {
2437 t.disallowDataDownloadLocked()
2440 func (t *Torrent) disallowDataDownloadLocked() {
2441 t.dataDownloadDisallowed.Set()
2444 func (t *Torrent) AllowDataDownload() {
2445 t.dataDownloadDisallowed.Clear()
2448 // Enables uploading data, if it was disabled.
2449 func (t *Torrent) AllowDataUpload() {
2452 t.dataUploadDisallowed = false
2453 for c := range t.conns {
2454 c.updateRequests("allow data upload")
2458 // Disables uploading data, if it was enabled.
2459 func (t *Torrent) DisallowDataUpload() {
2462 t.dataUploadDisallowed = true
2463 for c := range t.conns {
2464 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2465 c.updateRequests("disallow data upload")
2469 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2470 // or if nil, a critical message is logged, and data download is disabled.
2471 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2474 t.userOnWriteChunkErr = f
2477 func (t *Torrent) iterPeers(f func(p *Peer)) {
2478 for pc := range t.conns {
2481 for _, ws := range t.webSeeds {
2486 func (t *Torrent) callbacks() *Callbacks {
2487 return &t.cl.config.Callbacks
2490 type AddWebSeedsOpt func(*webseed.Client)
2492 // Sets the WebSeed trailing path escaper for a webseed.Client.
2493 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2494 return func(c *webseed.Client) {
2495 c.PathEscaper = custom
2499 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2502 for _, u := range urls {
2503 t.addWebSeed(u, opts...)
2507 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2508 if t.cl.config.DisableWebseeds {
2511 if _, ok := t.webSeeds[url]; ok {
2514 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2515 // right away. This value should be some multiple of the number of connections to a host. I
2516 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2517 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2518 // "https://webtorrent.io/torrents/".
2519 const maxRequests = 16
2525 reconciledHandshakeStats: true,
2526 // This should affect how often we have to recompute requests for this peer. Note that
2527 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2528 // requests mark more often, so recomputation is probably sooner than with regular peer
2529 // conns. ~4x maxRequests would be about right.
2530 PeerMaxRequests: 128,
2531 // TODO: Set ban prefix?
2532 RemoteAddr: remoteAddrFromUrl(url),
2533 callbacks: t.callbacks(),
2535 client: webseed.Client{
2536 HttpClient: t.cl.httpClient,
2538 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2539 return &rateLimitedReader{
2540 l: t.cl.config.DownloadRateLimiter,
2545 activeRequests: make(map[Request]webseed.Request, maxRequests),
2547 ws.peer.initRequestState()
2548 for _, opt := range opts {
2551 ws.peer.initUpdateRequestsTimer()
2552 ws.requesterCond.L = t.cl.locker()
2553 for i := 0; i < maxRequests; i += 1 {
2556 for _, f := range t.callbacks().NewPeer {
2559 ws.peer.logger = t.logger.WithContextValue(&ws)
2560 ws.peer.peerImpl = &ws
2562 ws.onGotInfo(t.info)
2564 t.webSeeds[url] = &ws.peer
2567 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2568 t.iterPeers(func(p1 *Peer) {
2576 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2577 index := t.pieceIndexOfRequestIndex(ri)
2580 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2584 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2585 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2588 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2589 return RequestIndex(piece) * t.chunksPerRegularPiece()
2592 func (t *Torrent) updateComplete() {
2593 t.Complete.SetBool(t.haveAllPieces())
2596 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2597 p := t.requestingPeer(r)
2601 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2602 //delete(t.pendingRequests, r)
2603 if _, ok := t.requestState[r]; ok {
2604 panic("expected request state to be gone")
2609 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2610 return t.requestState[r].peer
2613 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2614 if t.connsWithAllPieces == nil {
2615 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2617 t.connsWithAllPieces[p] = struct{}{}
2620 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2621 _, ok := t.connsWithAllPieces[p]
2622 delete(t.connsWithAllPieces, p)
2626 func (t *Torrent) numActivePeers() int {
2627 return len(t.conns) + len(t.webSeeds)
2630 func (t *Torrent) hasStorageCap() bool {
2631 f := t.storage.Capacity
2639 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2640 return pieceIndex(ri / t.chunksPerRegularPiece())
2643 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2644 reuseIter *typedRoaring.Iterator[RequestIndex],
2646 f func(RequestIndex),
2648 reuseIter.Initialize(&t.dirtyChunks)
2649 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2650 iterBitmapUnsetInRange(
2652 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2657 type requestState struct {
2662 // Returns an error if a received chunk is out of bounds in someway.
2663 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2665 return errors.New("torrent missing info")
2667 if int(r.Index) >= t.numPieces() {
2668 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2670 pieceLength := t.pieceLength(pieceIndex(r.Index))
2671 if r.Begin >= pieceLength {
2672 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2674 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2675 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2676 // should be considerable checks elsewhere for this case due to the network overhead. We should
2677 // catch most of the overflow manipulation stuff by checking index and begin above.
2681 func (t *Torrent) peerConnsWithRemoteAddrPort(addrPort netip.AddrPort) (ret []*PeerConn) {
2682 for pc := range t.conns {
2683 addr := pc.remoteAddrPort()
2684 if !(addr.Ok && addr.Value == addrPort) {
2687 ret = append(ret, pc)
2692 func makeUtHolepunchMsgForPeerConn(
2693 recipient *PeerConn,
2694 msgType utHolepunch.MsgType,
2695 addrPort netip.AddrPort,
2696 errCode utHolepunch.ErrCode,
2698 utHolepunchMsg := utHolepunch.Msg{
2703 extendedPayload, err := utHolepunchMsg.MarshalBinary()
2709 ExtendedID: MapMustGet(recipient.PeerExtensionIDs, utHolepunch.ExtensionName),
2710 ExtendedPayload: extendedPayload,
2714 func sendUtHolepunchMsg(
2716 msgType utHolepunch.MsgType,
2717 addrPort netip.AddrPort,
2718 errCode utHolepunch.ErrCode,
2720 pc.write(makeUtHolepunchMsgForPeerConn(pc, msgType, addrPort, errCode))
2723 func (t *Torrent) handleReceivedUtHolepunchMsg(msg utHolepunch.Msg, sender *PeerConn) error {
2724 switch msg.MsgType {
2725 case utHolepunch.Rendezvous:
2726 log.Printf("got holepunch rendezvous request for %v from %p", msg.AddrPort, sender)
2727 sendMsg := sendUtHolepunchMsg
2728 targets := t.peerConnsWithRemoteAddrPort(msg.AddrPort)
2729 if len(targets) == 0 {
2730 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NotConnected)
2733 for _, pc := range targets {
2734 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2735 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSupport)
2738 sendMsg(sender, utHolepunch.Connect, msg.AddrPort, 0)
2739 sendMsg(pc, utHolepunch.Connect, sender.remoteAddrPort().Unwrap(), 0)
2742 case utHolepunch.Connect:
2743 log.Printf("got holepunch connect from %v for %v", sender, msg.AddrPort)
2744 rz, ok := t.utHolepunchRendezvous[msg.AddrPort]
2746 delete(rz.relays, sender)
2748 rz.relayCond.Broadcast()
2750 // If the rendezvous was removed because we timed out or already got a connect signal,
2751 // it doesn't hurt to try again.
2752 t.initiateConn(PeerInfo{
2754 Source: PeerSourceUtHolepunch,
2758 case utHolepunch.Error:
2759 rz, ok := t.utHolepunchRendezvous[msg.AddrPort]
2761 delete(rz.relays, sender)
2762 rz.relayCond.Broadcast()
2764 log.Printf("received ut_holepunch error message from %v: %v", sender, msg.ErrCode)
2767 return fmt.Errorf("unhandled msg type %v", msg.MsgType)
2771 func (t *Torrent) startHolepunchRendezvous(addrPort netip.AddrPort) (rz *utHolepunchRendezvous, err error) {
2772 if MapContains(t.utHolepunchRendezvous, addrPort) {
2773 err = errors.New("rendezvous already exists")
2777 for pc := range t.conns {
2778 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2781 if pc.supportsExtension(pp.ExtensionNamePex) {
2782 if !g.MapContains(pc.pex.remoteLiveConns, addrPort) {
2786 sendUtHolepunchMsg(pc, utHolepunch.Rendezvous, addrPort, 0)
2787 MakeMapIfNilAndSet(&rz.relays, pc, struct{}{})
2789 if len(rz.relays) == 0 {
2790 err = fmt.Errorf("no eligible relays")
2793 if !MakeMapIfNilAndSet(&t.utHolepunchRendezvous, addrPort, rz) {
2794 panic("expected to fail earlier if rendezvous already exists")