20 "github.com/RoaringBitmap/roaring"
21 "github.com/anacrolix/chansync"
22 "github.com/anacrolix/chansync/events"
23 "github.com/anacrolix/dht/v2"
24 . "github.com/anacrolix/generics"
25 g "github.com/anacrolix/generics"
26 "github.com/anacrolix/log"
27 "github.com/anacrolix/missinggo/perf"
28 "github.com/anacrolix/missinggo/slices"
29 "github.com/anacrolix/missinggo/v2"
30 "github.com/anacrolix/missinggo/v2/bitmap"
31 "github.com/anacrolix/missinggo/v2/pubsub"
32 "github.com/anacrolix/multiless"
33 "github.com/anacrolix/sync"
34 "github.com/davecgh/go-spew/spew"
35 "github.com/pion/datachannel"
36 "golang.org/x/exp/maps"
38 "github.com/anacrolix/torrent/bencode"
39 "github.com/anacrolix/torrent/common"
40 "github.com/anacrolix/torrent/internal/check"
41 "github.com/anacrolix/torrent/metainfo"
42 pp "github.com/anacrolix/torrent/peer_protocol"
43 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
44 request_strategy "github.com/anacrolix/torrent/request-strategy"
45 "github.com/anacrolix/torrent/segments"
46 "github.com/anacrolix/torrent/storage"
47 "github.com/anacrolix/torrent/tracker"
48 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
49 "github.com/anacrolix/torrent/webseed"
50 "github.com/anacrolix/torrent/webtorrent"
53 // Maintains state of torrent within a Client. Many methods should not be called before the info is
54 // available, see .Info and .GotInfo.
56 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
57 // alignment. See #262.
62 networkingEnabled chansync.Flag
63 dataDownloadDisallowed chansync.Flag
64 dataUploadDisallowed bool
65 userOnWriteChunkErr func(error)
67 closed chansync.SetOnce
69 infoHash metainfo.Hash
72 // The order pieces are requested if there's no stronger reason like availability or priority.
73 pieceRequestOrder []int
74 // Values are the piece indices that changed.
75 pieceStateChanges pubsub.PubSub[PieceStateChange]
76 // The size of chunks to request from peers over the wire. This is
77 // normally 16KiB by convention these days.
80 // Total length of the torrent in bytes. Stored because it's not O(1) to
81 // get this from the info dict.
84 // The storage to open when the info dict becomes available.
85 storageOpener *storage.Client
86 // Storage for torrent data.
87 storage *storage.Torrent
88 // Read-locked for using storage, and write-locked for Closing.
89 storageLock sync.RWMutex
91 // TODO: Only announce stuff is used?
92 metainfo metainfo.MetaInfo
94 // The info dict. nil if we don't have it (yet).
96 fileIndex segments.Index
99 _chunksPerRegularPiece chunkIndexType
101 webSeeds map[string]*Peer
102 // Active peer connections, running message stream loops. TODO: Make this
103 // open (not-closed) connections only.
104 conns map[*PeerConn]struct{}
105 maxEstablishedConns int
106 // Set of addrs to which we're attempting to connect. Connections are
107 // half-open until all handshakes are completed.
108 halfOpen map[string]PeerInfo
109 // The final ess is not silent here as it's in the plural.
110 utHolepunchRendezvous map[netip.AddrPort]*utHolepunchRendezvous
112 // Reserve of peers to connect to. A peer can be both here and in the
113 // active connections if were told about the peer after connecting with
114 // them. That encourages us to reconnect to peers that are well known in
116 peers prioritizedPeers
117 // Whether we want to know more peers.
118 wantPeersEvent missinggo.Event
119 // An announcer for each tracker URL.
120 trackerAnnouncers map[string]torrentTrackerAnnouncer
121 // How many times we've initiated a DHT announce. TODO: Move into stats.
124 // Name used if the info name isn't available. Should be cleared when the
125 // Info does become available.
129 // The bencoded bytes of the info dict. This is actively manipulated if
130 // the info bytes aren't initially available, and we try to fetch them
133 // Each element corresponds to the 16KiB metadata pieces. If true, we have
134 // received that piece.
135 metadataCompletedChunks []bool
136 metadataChanged sync.Cond
138 // Closed when .Info is obtained.
139 gotMetainfoC chan struct{}
141 readers map[*reader]struct{}
142 _readerNowPieces bitmap.Bitmap
143 _readerReadaheadPieces bitmap.Bitmap
145 // A cache of pieces we need to get. Calculated from various piece and
146 // file priorities and completion states elsewhere.
147 _pendingPieces roaring.Bitmap
148 // A cache of completed piece indices.
149 _completedPieces roaring.Bitmap
150 // Pieces that need to be hashed.
151 piecesQueuedForHash bitmap.Bitmap
152 activePieceHashes int
153 initialPieceCheckDisabled bool
155 connsWithAllPieces map[*Peer]struct{}
157 requestState map[RequestIndex]requestState
158 // Chunks we've written to since the corresponding piece was last checked.
159 dirtyChunks typedRoaring.Bitmap[RequestIndex]
163 // Is On when all pieces are complete.
164 Complete chansync.Flag
166 // Torrent sources in use keyed by the source string.
167 activeSources sync.Map
168 sourcesLogger log.Logger
170 smartBanCache smartBanCache
172 // Large allocations reused between request state updates.
173 requestPieceStates []request_strategy.PieceRequestOrderState
174 requestIndexes []RequestIndex
177 func (t *Torrent) length() int64 {
178 return t._length.Value
181 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
182 // This could be done with roaring.BitSliceIndexing.
183 t.iterPeers(func(peer *Peer) {
184 if _, ok := t.connsWithAllPieces[peer]; ok {
187 if peer.peerHasPiece(i) {
194 func (t *Torrent) decPieceAvailability(i pieceIndex) {
199 if p.relativeAvailability <= 0 {
200 panic(p.relativeAvailability)
202 p.relativeAvailability--
203 t.updatePieceRequestOrder(i)
206 func (t *Torrent) incPieceAvailability(i pieceIndex) {
207 // If we don't the info, this should be reconciled when we do.
210 p.relativeAvailability++
211 t.updatePieceRequestOrder(i)
215 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
216 return t._readerNowPieces
219 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
220 return t._readerReadaheadPieces
223 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
224 return !t.wantPieceIndex(i)
227 // Returns a channel that is closed when the Torrent is closed.
228 func (t *Torrent) Closed() events.Done {
229 return t.closed.Done()
232 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
233 // pending, and half-open peers.
234 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
235 // Add pending peers to the list
236 t.peers.Each(func(peer PeerInfo) {
237 ks = append(ks, peer)
240 // Add half-open peers to the list
241 for _, peer := range t.halfOpen {
242 ks = append(ks, peer)
245 // Add active peers to the list
246 for conn := range t.conns {
247 ks = append(ks, PeerInfo{
249 Addr: conn.RemoteAddr,
250 Source: conn.Discovery,
251 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
252 // > But if we're not connected to them with an encrypted connection, I couldn't say
253 // > what's appropriate. We can carry forward the SupportsEncryption value as we
254 // > received it from trackers/DHT/PEX, or just use the encryption state for the
255 // > connection. It's probably easiest to do the latter for now.
256 // https://github.com/anacrolix/torrent/pull/188
257 SupportsEncryption: conn.headerEncrypted,
264 func (t *Torrent) setChunkSize(size pp.Integer) {
266 t.chunkPool = sync.Pool{
267 New: func() interface{} {
268 b := make([]byte, size)
274 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
275 return t._completedPieces.Contains(bitmap.BitIndex(piece))
278 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
279 if t.storage == nil {
280 return storage.Completion{Complete: false, Ok: true}
282 return t.pieces[piece].Storage().Completion()
285 // There's a connection to that address already.
286 func (t *Torrent) addrActive(addr string) bool {
287 if _, ok := t.halfOpen[addr]; ok {
290 for c := range t.conns {
292 if ra.String() == addr {
299 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
300 return t.appendConns(ret, func(conn *PeerConn) bool {
301 return !conn.closed.IsSet()
305 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
306 for c := range t.conns {
314 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
316 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
317 if t.closed.IsSet() {
320 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
321 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
322 torrent.Add("peers not added because of bad addr", 1)
323 // cl.logger.Printf("peers not added because of bad addr: %v", p)
327 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
328 torrent.Add("peers replaced", 1)
329 if !replaced.equal(p) {
330 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
337 for t.peers.Len() > cl.config.TorrentPeersHighWater {
338 _, ok := t.peers.DeleteMin()
340 torrent.Add("excess reserve peers discarded", 1)
346 func (t *Torrent) invalidateMetadata() {
347 for i := 0; i < len(t.metadataCompletedChunks); i++ {
348 t.metadataCompletedChunks[i] = false
351 t.gotMetainfoC = make(chan struct{})
356 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
360 if index >= len(t.metadataCompletedChunks) {
361 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
364 copy(t.metadataBytes[(1<<14)*index:], data)
365 t.metadataCompletedChunks[index] = true
368 func (t *Torrent) metadataPieceCount() int {
369 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
372 func (t *Torrent) haveMetadataPiece(piece int) bool {
374 return (1<<14)*piece < len(t.metadataBytes)
376 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
380 func (t *Torrent) metadataSize() int {
381 return len(t.metadataBytes)
384 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
385 for i := 0; i < len(info.Pieces); i += sha1.Size {
386 ret = append(ret, info.Pieces[i:i+sha1.Size])
391 func (t *Torrent) makePieces() {
392 hashes := infoPieceHashes(t.info)
393 t.pieces = make([]Piece, len(hashes))
394 for i, hash := range hashes {
395 piece := &t.pieces[i]
397 piece.index = pieceIndex(i)
398 piece.noPendingWrites.L = &piece.pendingWritesMutex
399 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
401 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
402 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
403 piece.files = files[beginFile:endFile]
407 // Returns the index of the first file containing the piece. files must be
408 // ordered by offset.
409 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
410 for i, f := range files {
411 if f.offset+f.length > pieceOffset {
418 // Returns the index after the last file containing the piece. files must be
419 // ordered by offset.
420 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
421 for i, f := range files {
422 if f.offset+f.length >= pieceEndOffset {
429 func (t *Torrent) cacheLength() {
431 for _, f := range t.info.UpvertedFiles() {
437 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
439 func (t *Torrent) setInfo(info *metainfo.Info) error {
440 if err := validateInfo(info); err != nil {
441 return fmt.Errorf("bad info: %s", err)
443 if t.storageOpener != nil {
445 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
447 return fmt.Errorf("error opening torrent storage: %s", err)
453 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
455 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
456 t.displayName = "" // Save a few bytes lol.
463 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
464 return request_strategy.PieceRequestOrderKey{
465 InfoHash: t.infoHash,
470 // This seems to be all the follow-up tasks after info is set, that can't fail.
471 func (t *Torrent) onSetInfo() {
472 t.pieceRequestOrder = rand.Perm(t.numPieces())
473 t.initPieceRequestOrder()
474 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
475 for i := range t.pieces {
477 // Need to add relativeAvailability before updating piece completion, as that may result in conns
479 if p.relativeAvailability != 0 {
480 panic(p.relativeAvailability)
482 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
483 t.addRequestOrderPiece(i)
484 t.updatePieceCompletion(i)
485 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
486 // t.logger.Printf("piece %s completion unknown, queueing check", p)
490 t.cl.event.Broadcast()
491 close(t.gotMetainfoC)
492 t.updateWantPeersEvent()
493 t.requestState = make(map[RequestIndex]requestState)
494 t.tryCreateMorePieceHashers()
495 t.iterPeers(func(p *Peer) {
497 p.updateRequests("onSetInfo")
501 // Called when metadata for a torrent becomes available.
502 func (t *Torrent) setInfoBytesLocked(b []byte) error {
503 if metainfo.HashBytes(b) != t.infoHash {
504 return errors.New("info bytes have wrong hash")
506 var info metainfo.Info
507 if err := bencode.Unmarshal(b, &info); err != nil {
508 return fmt.Errorf("error unmarshalling info bytes: %s", err)
511 t.metadataCompletedChunks = nil
515 if err := t.setInfo(&info); err != nil {
522 func (t *Torrent) haveAllMetadataPieces() bool {
526 if t.metadataCompletedChunks == nil {
529 for _, have := range t.metadataCompletedChunks {
537 // TODO: Propagate errors to disconnect peer.
538 func (t *Torrent) setMetadataSize(size int) (err error) {
540 // We already know the correct metadata size.
543 if uint32(size) > maxMetadataSize {
544 return log.WithLevel(log.Warning, errors.New("bad size"))
546 if len(t.metadataBytes) == size {
549 t.metadataBytes = make([]byte, size)
550 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
551 t.metadataChanged.Broadcast()
552 for c := range t.conns {
553 c.requestPendingMetadata()
558 // The current working name for the torrent. Either the name in the info dict,
559 // or a display name given such as by the dn value in a magnet link, or "".
560 func (t *Torrent) name() string {
562 defer t.nameMu.RUnlock()
564 return t.info.BestName()
566 if t.displayName != "" {
569 return "infohash:" + t.infoHash.HexString()
572 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
573 p := &t.pieces[index]
574 ret.Priority = t.piecePriority(index)
575 ret.Completion = p.completion()
576 ret.QueuedForHash = p.queuedForHash()
577 ret.Hashing = p.hashing
578 ret.Checking = ret.QueuedForHash || ret.Hashing
579 ret.Marking = p.marking
580 if !ret.Complete && t.piecePartiallyDownloaded(index) {
586 func (t *Torrent) metadataPieceSize(piece int) int {
587 return metadataPieceSize(len(t.metadataBytes), piece)
590 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
593 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
594 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
596 TotalSize: len(t.metadataBytes),
602 type pieceAvailabilityRun struct {
607 func (me pieceAvailabilityRun) String() string {
608 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
611 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
612 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
613 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
615 for i := range t.pieces {
616 rle.Append(t.pieces[i].availability(), 1)
622 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
623 freqs = make([]int, t.numActivePeers()+1)
624 for i := range t.pieces {
625 freqs[t.piece(i).availability()]++
630 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
631 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
632 ret = append(ret, PieceStateRun{
633 PieceState: el.(PieceState),
637 for index := range t.pieces {
638 rle.Append(t.pieceState(pieceIndex(index)), 1)
644 // Produces a small string representing a PieceStateRun.
645 func (psr PieceStateRun) String() (ret string) {
646 ret = fmt.Sprintf("%d", psr.Length)
647 ret += func() string {
648 switch psr.Priority {
649 case PiecePriorityNext:
651 case PiecePriorityNormal:
653 case PiecePriorityReadahead:
655 case PiecePriorityNow:
657 case PiecePriorityHigh:
666 if psr.QueuedForHash {
684 func (t *Torrent) writeStatus(w io.Writer) {
685 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
686 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
688 fmt.Fprintf(w, "Metadata have: ")
689 for _, h := range t.metadataCompletedChunks {
690 fmt.Fprintf(w, "%c", func() rune {
700 fmt.Fprintf(w, "Piece length: %s\n",
703 return fmt.Sprintf("%v (%v chunks)",
705 float64(t.usualPieceSize())/float64(t.chunkSize))
712 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
713 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
714 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
715 // availability frequencies instead.
717 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
718 for _, run := range t.pieceAvailabilityRuns() {
719 ret = append(ret, run.String())
724 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
725 func() (ret []string) {
726 for avail, freq := range t.pieceAvailabilityFrequencies() {
730 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
736 fmt.Fprintf(w, "Reader Pieces:")
737 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
738 fmt.Fprintf(w, " %d:%d", begin, end)
743 fmt.Fprintf(w, "Enabled trackers:\n")
745 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
746 fmt.Fprintf(tw, " URL\tExtra\n")
747 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
750 var luns, runs url.URL = *lu, *ru
753 var ml missinggo.MultiLess
754 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
755 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
757 }).([]torrentTrackerAnnouncer) {
758 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
763 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
765 spew.NewDefaultConfig()
766 spew.Fdump(w, t.statsLocked())
768 fmt.Fprintf(w, "webseeds:\n")
769 t.writePeerStatuses(w, maps.Values(t.webSeeds))
771 peerConns := maps.Keys(t.conns)
772 // Peers without priorities first, then those with. I'm undecided about how to order peers
773 // without priorities.
774 sort.Slice(peerConns, func(li, ri int) bool {
777 ml := multiless.New()
778 lpp := g.ResultFromTuple(l.peerPriority()).ToOption()
779 rpp := g.ResultFromTuple(r.peerPriority()).ToOption()
780 ml = ml.Bool(lpp.Ok, rpp.Ok)
781 ml = ml.Uint32(rpp.Value, lpp.Value)
785 fmt.Fprintf(w, "peer conns:\n")
786 t.writePeerStatuses(w, g.SliceMap(peerConns, func(pc *PeerConn) *Peer {
791 func (t *Torrent) writePeerStatuses(w io.Writer, peers []*Peer) {
793 for _, c := range peers {
797 w.Write(bytes.TrimRight(
798 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
803 func (t *Torrent) haveInfo() bool {
807 // Returns a run-time generated MetaInfo that includes the info bytes and
808 // announce-list as currently known to the client.
809 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
810 return metainfo.MetaInfo{
811 CreationDate: time.Now().Unix(),
812 Comment: "dynamic metainfo from client",
813 CreatedBy: "go.torrent",
814 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
815 InfoBytes: func() []byte {
817 return t.metadataBytes
822 UrlList: func() []string {
823 ret := make([]string, 0, len(t.webSeeds))
824 for url := range t.webSeeds {
825 ret = append(ret, url)
833 func (t *Torrent) BytesMissing() (n int64) {
835 n = t.bytesMissingLocked()
840 func (t *Torrent) bytesMissingLocked() int64 {
844 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
845 roaring.Flip(b, 0, end).Iterate(cb)
848 func (t *Torrent) bytesLeft() (left int64) {
849 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
850 p := t.piece(pieceIndex(x))
851 left += int64(p.length() - p.numDirtyBytes())
857 // Bytes left to give in tracker announces.
858 func (t *Torrent) bytesLeftAnnounce() int64 {
866 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
867 if t.pieceComplete(piece) {
870 if t.pieceAllDirty(piece) {
873 return t.pieces[piece].hasDirtyChunks()
876 func (t *Torrent) usualPieceSize() int {
877 return int(t.info.PieceLength)
880 func (t *Torrent) numPieces() pieceIndex {
881 return t.info.NumPieces()
884 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
885 return pieceIndex(t._completedPieces.GetCardinality())
888 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
890 err = errors.New("already closed")
893 for _, f := range t.onClose {
896 if t.storage != nil {
901 defer t.storageLock.Unlock()
902 if f := t.storage.Close; f != nil {
905 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
910 t.iterPeers(func(p *Peer) {
913 if t.storage != nil {
914 t.deletePieceRequestOrder()
916 t.assertAllPiecesRelativeAvailabilityZero()
918 t.cl.event.Broadcast()
919 t.pieceStateChanges.Close()
920 t.updateWantPeersEvent()
924 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
925 for i := range t.pieces {
927 if p.relativeAvailability != 0 {
928 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
933 func (t *Torrent) requestOffset(r Request) int64 {
934 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
937 // Return the request that would include the given offset into the torrent data. Returns !ok if
938 // there is no such request.
939 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
940 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
943 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
944 defer perf.ScopeTimerErr(&err)()
945 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
946 if err == nil && n != len(data) {
947 err = io.ErrShortWrite
952 func (t *Torrent) bitfield() (bf []bool) {
953 bf = make([]bool, t.numPieces())
954 t._completedPieces.Iterate(func(piece uint32) (again bool) {
961 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
962 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
965 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
966 return t._chunksPerRegularPiece
969 func (t *Torrent) numChunks() RequestIndex {
970 if t.numPieces() == 0 {
973 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
976 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
977 t.dirtyChunks.RemoveRange(
978 uint64(t.pieceRequestIndexOffset(pieceIndex)),
979 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
982 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
983 if t.info.PieceLength == 0 {
984 // There will be no variance amongst pieces. Only pain.
987 if piece == t.numPieces()-1 {
988 ret := pp.Integer(t.length() % t.info.PieceLength)
993 return pp.Integer(t.info.PieceLength)
996 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
997 return &blockCheckingWriter{
998 cache: &t.smartBanCache,
999 requestIndex: t.pieceRequestIndexOffset(piece),
1000 chunkSize: t.chunkSize.Int(),
1004 func (t *Torrent) hashPiece(piece pieceIndex) (
1006 // These are peers that sent us blocks that differ from what we hash here.
1007 differingPeers map[bannableAddr]struct{},
1011 p.waitNoPendingWrites()
1012 storagePiece := t.pieces[piece].Storage()
1014 // Does the backend want to do its own hashing?
1015 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
1016 var sum metainfo.Hash
1017 // log.Printf("A piece decided to self-hash: %d", piece)
1018 sum, err = i.SelfHash()
1019 missinggo.CopyExact(&ret, sum)
1023 hash := pieceHash.New()
1024 const logPieceContents = false
1025 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1026 writers := []io.Writer{hash, smartBanWriter}
1027 var examineBuf bytes.Buffer
1028 if logPieceContents {
1029 writers = append(writers, &examineBuf)
1031 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1032 if logPieceContents {
1033 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1035 smartBanWriter.Flush()
1036 differingPeers = smartBanWriter.badPeers
1037 missinggo.CopyExact(&ret, hash.Sum(nil))
1041 func (t *Torrent) haveAnyPieces() bool {
1042 return !t._completedPieces.IsEmpty()
1045 func (t *Torrent) haveAllPieces() bool {
1049 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1052 func (t *Torrent) havePiece(index pieceIndex) bool {
1053 return t.haveInfo() && t.pieceComplete(index)
1056 func (t *Torrent) maybeDropMutuallyCompletePeer(
1057 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1061 if !t.cl.config.DropMutuallyCompletePeers {
1064 if !t.haveAllPieces() {
1067 if all, known := p.peerHasAllPieces(); !(known && all) {
1073 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1077 func (t *Torrent) haveChunk(r Request) (ret bool) {
1079 // log.Println("have chunk", r, ret)
1084 if t.pieceComplete(pieceIndex(r.Index)) {
1087 p := &t.pieces[r.Index]
1088 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1091 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1092 return chunkIndexType(cs.Begin / chunkSize)
1095 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1096 return t._pendingPieces.Contains(uint32(index))
1099 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1100 // conns (which is a map).
1101 var peerConnSlices sync.Pool
1103 func getPeerConnSlice(cap int) []*PeerConn {
1104 getInterface := peerConnSlices.Get()
1105 if getInterface == nil {
1106 return make([]*PeerConn, 0, cap)
1108 return getInterface.([]*PeerConn)[:0]
1112 // Calls the given function with a slice of unclosed conns. It uses a pool to reduce allocations as
1113 // this is a frequent occurrence.
1114 func (t *Torrent) withUnclosedConns(f func([]*PeerConn)) {
1115 sl := t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))
1117 peerConnSlices.Put(sl)
1120 func (t *Torrent) worstBadConnFromSlice(opts worseConnLensOpts, sl []*PeerConn) *PeerConn {
1121 wcs := worseConnSlice{conns: sl}
1124 for wcs.Len() != 0 {
1125 c := heap.Pop(&wcs).(*PeerConn)
1126 if opts.incomingIsBad && !c.outgoing {
1129 if opts.outgoingIsBad && c.outgoing {
1132 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1135 // If the connection is in the worst half of the established
1136 // connection quota and is older than a minute.
1137 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1138 // Give connections 1 minute to prove themselves.
1139 if time.Since(c.completedHandshake) > time.Minute {
1147 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1148 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1149 // established connections for more than a minute. This is O(n log n). If there was a way to not
1150 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1151 func (t *Torrent) worstBadConn(opts worseConnLensOpts) (ret *PeerConn) {
1152 t.withUnclosedConns(func(ucs []*PeerConn) {
1153 ret = t.worstBadConnFromSlice(opts, ucs)
1158 type PieceStateChange struct {
1163 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1164 t.cl._mu.Defer(func() {
1165 cur := t.pieceState(piece)
1166 p := &t.pieces[piece]
1167 if cur != p.publicPieceState {
1168 p.publicPieceState = cur
1169 t.pieceStateChanges.Publish(PieceStateChange{
1177 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1178 if t.pieceComplete(piece) {
1181 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1184 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1185 return t.pieces[piece].allChunksDirty()
1188 func (t *Torrent) readersChanged() {
1189 t.updateReaderPieces()
1190 t.updateAllPiecePriorities("Torrent.readersChanged")
1193 func (t *Torrent) updateReaderPieces() {
1194 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1197 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1201 t.updateReaderPieces()
1202 // Order the ranges, high and low.
1204 if l.begin > h.begin {
1207 if l.end < h.begin {
1208 // Two distinct ranges.
1209 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1210 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1217 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1221 func (t *Torrent) maybeNewConns() {
1222 // Tickle the accept routine.
1223 t.cl.event.Broadcast()
1227 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1228 if t._pendingPieces.Contains(uint32(piece)) {
1229 t.iterPeers(func(c *Peer) {
1230 // if c.requestState.Interested {
1233 if !c.isLowOnRequests() {
1236 if !c.peerHasPiece(piece) {
1239 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1242 c.updateRequests(reason)
1246 t.publishPieceChange(piece)
1249 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1250 if !t.closed.IsSet() {
1251 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1253 t.updatePieceRequestOrder(piece)
1255 p := &t.pieces[piece]
1256 newPrio := p.uncachedPriority()
1257 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1258 if newPrio == PiecePriorityNone {
1259 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1263 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1267 t.piecePriorityChanged(piece, reason)
1270 func (t *Torrent) updateAllPiecePriorities(reason string) {
1271 t.updatePiecePriorities(0, t.numPieces(), reason)
1274 // Update all piece priorities in one hit. This function should have the same
1275 // output as updatePiecePriority, but across all pieces.
1276 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1277 for i := begin; i < end; i++ {
1278 t.updatePiecePriority(i, reason)
1282 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1283 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1284 if off >= t.length() {
1294 begin = pieceIndex(off / t.info.PieceLength)
1295 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1296 if end > pieceIndex(t.info.NumPieces()) {
1297 end = pieceIndex(t.info.NumPieces())
1302 // Returns true if all iterations complete without breaking. Returns the read regions for all
1303 // readers. The reader regions should not be merged as some callers depend on this method to
1304 // enumerate readers.
1305 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1306 for r := range t.readers {
1308 if p.begin >= p.end {
1311 if !f(p.begin, p.end) {
1318 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1319 return t.piece(piece).uncachedPriority()
1322 func (t *Torrent) pendRequest(req RequestIndex) {
1323 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1326 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1327 t.cl.event.Broadcast()
1328 if t.pieceComplete(piece) {
1329 t.onPieceCompleted(piece)
1331 t.onIncompletePiece(piece)
1333 t.updatePiecePriority(piece, reason)
1336 func (t *Torrent) numReceivedConns() (ret int) {
1337 for c := range t.conns {
1338 if c.Discovery == PeerSourceIncoming {
1345 func (t *Torrent) numOutgoingConns() (ret int) {
1346 for c := range t.conns {
1354 func (t *Torrent) maxHalfOpen() int {
1355 // Note that if we somehow exceed the maximum established conns, we want
1356 // the negative value to have an effect.
1357 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1358 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1359 // We want to allow some experimentation with new peers, and to try to
1360 // upset an oversupply of received connections.
1362 max(5, extraIncoming)+establishedHeadroom,
1363 int64(t.cl.config.HalfOpenConnsPerTorrent),
1367 func (t *Torrent) openNewConns() (initiated int) {
1368 defer t.updateWantPeersEvent()
1369 for t.peers.Len() != 0 {
1370 if !t.wantOutgoingConns() {
1373 if len(t.halfOpen) >= t.maxHalfOpen() {
1376 if len(t.cl.dialers) == 0 {
1379 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1382 p := t.peers.PopMax()
1383 t.initiateConn(p, false, false)
1389 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1391 uncached := t.pieceCompleteUncached(piece)
1392 cached := p.completion()
1393 changed := cached != uncached
1394 complete := uncached.Complete
1395 p.storageCompletionOk = uncached.Ok
1398 t._completedPieces.Add(x)
1401 t._completedPieces.Remove(x)
1403 p.t.updatePieceRequestOrder(piece)
1405 if complete && len(p.dirtiers) != 0 {
1406 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1409 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1410 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1415 // Non-blocking read. Client lock is not required.
1416 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1418 p := &t.pieces[off/t.info.PieceLength]
1419 p.waitNoPendingWrites()
1421 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1432 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1433 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1434 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1435 func (t *Torrent) maybeCompleteMetadata() error {
1440 if !t.haveAllMetadataPieces() {
1441 // Don't have enough metadata pieces.
1444 err := t.setInfoBytesLocked(t.metadataBytes)
1446 t.invalidateMetadata()
1447 return fmt.Errorf("error setting info bytes: %s", err)
1449 if t.cl.config.Debug {
1450 t.logger.Printf("%s: got metadata from peers", t)
1455 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1456 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1458 now.Add(bitmap.BitIndex(begin))
1459 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1466 func (t *Torrent) needData() bool {
1467 if t.closed.IsSet() {
1473 return !t._pendingPieces.IsEmpty()
1476 func appendMissingStrings(old, new []string) (ret []string) {
1479 for _, n := range new {
1480 for _, o := range old {
1485 ret = append(ret, n)
1490 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1492 for minNumTiers > len(ret) {
1493 ret = append(ret, nil)
1498 func (t *Torrent) addTrackers(announceList [][]string) {
1499 fullAnnounceList := &t.metainfo.AnnounceList
1500 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1501 for tierIndex, trackerURLs := range announceList {
1502 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1504 t.startMissingTrackerScrapers()
1505 t.updateWantPeersEvent()
1508 // Don't call this before the info is available.
1509 func (t *Torrent) bytesCompleted() int64 {
1513 return t.length() - t.bytesLeft()
1516 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1519 return t.setInfoBytesLocked(b)
1522 // Returns true if connection is removed from torrent.Conns.
1523 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1524 if !c.closed.IsSet() {
1525 panic("connection is not closed")
1526 // There are behaviours prevented by the closed state that will fail
1527 // if the connection has been deleted.
1531 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1532 // the drop event against the PexConnState instead.
1534 if !t.cl.config.DisablePEX {
1538 torrent.Add("deleted connections", 1)
1539 c.deleteAllRequests("Torrent.deletePeerConn")
1540 t.assertPendingRequests()
1541 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1542 panic(t.connsWithAllPieces)
1547 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1548 if t.deleteConnWithAllPieces(p) {
1554 p.peerPieces().Iterate(func(i uint32) bool {
1555 p.t.decPieceAvailability(pieceIndex(i))
1560 func (t *Torrent) assertPendingRequests() {
1564 // var actual pendingRequests
1565 // if t.haveInfo() {
1566 // actual.m = make([]int, t.numChunks())
1568 // t.iterPeers(func(p *Peer) {
1569 // p.requestState.Requests.Iterate(func(x uint32) bool {
1574 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1580 func (t *Torrent) dropConnection(c *PeerConn) {
1581 t.cl.event.Broadcast()
1583 if t.deletePeerConn(c) {
1588 // Peers as in contact information for dialing out.
1589 func (t *Torrent) wantPeers() bool {
1590 if t.closed.IsSet() {
1593 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1596 return t.wantOutgoingConns()
1599 func (t *Torrent) updateWantPeersEvent() {
1601 t.wantPeersEvent.Set()
1603 t.wantPeersEvent.Clear()
1607 // Returns whether the client should make effort to seed the torrent.
1608 func (t *Torrent) seeding() bool {
1610 if t.closed.IsSet() {
1613 if t.dataUploadDisallowed {
1616 if cl.config.NoUpload {
1619 if !cl.config.Seed {
1622 if cl.config.DisableAggressiveUpload && t.needData() {
1628 func (t *Torrent) onWebRtcConn(
1629 c datachannel.ReadWriteCloser,
1630 dcc webtorrent.DataChannelContext,
1633 netConn := webrtcNetConn{
1635 DataChannelContext: dcc,
1637 peerRemoteAddr := netConn.RemoteAddr()
1638 //t.logger.Levelf(log.Critical, "onWebRtcConn remote addr: %v", peerRemoteAddr)
1639 if t.cl.badPeerAddr(peerRemoteAddr) {
1642 localAddrIpPort := missinggo.IpPortFromNetAddr(netConn.LocalAddr())
1643 pc, err := t.cl.initiateProtocolHandshakes(
1644 context.Background(),
1649 outgoing: dcc.LocalOffered,
1650 remoteAddr: peerRemoteAddr,
1651 localPublicAddr: localAddrIpPort,
1652 network: webrtcNetwork,
1653 connString: fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1657 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1660 if dcc.LocalOffered {
1661 pc.Discovery = PeerSourceTracker
1663 pc.Discovery = PeerSourceIncoming
1665 pc.conn.SetWriteDeadline(time.Time{})
1668 err = t.cl.runHandshookConn(pc, t)
1670 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1674 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1675 err := t.cl.runHandshookConn(pc, t)
1676 if err != nil || logAll {
1677 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1681 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1682 t.logRunHandshookConn(pc, false, log.Debug)
1685 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1686 wtc, release := t.cl.websocketTrackers.Get(u.String(), t.infoHash)
1687 // This needs to run before the Torrent is dropped from the Client, to prevent a new webtorrent.TrackerClient for
1688 // the same info hash before the old one is cleaned up.
1689 t.onClose = append(t.onClose, release)
1690 wst := websocketTrackerStatus{u, wtc}
1692 err := wtc.Announce(tracker.Started, t.infoHash)
1694 t.logger.WithDefaultLevel(log.Warning).Printf(
1695 "error in initial announce to %q: %v",
1703 func (t *Torrent) startScrapingTracker(_url string) {
1707 u, err := url.Parse(_url)
1709 // URLs with a leading '*' appear to be a uTorrent convention to
1710 // disable trackers.
1712 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1716 if u.Scheme == "udp" {
1718 t.startScrapingTracker(u.String())
1720 t.startScrapingTracker(u.String())
1723 if _, ok := t.trackerAnnouncers[_url]; ok {
1726 sl := func() torrentTrackerAnnouncer {
1729 if t.cl.config.DisableWebtorrent {
1732 return t.startWebsocketAnnouncer(*u)
1734 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1738 if t.cl.config.DisableIPv6 {
1742 newAnnouncer := &trackerScraper{
1745 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1747 go newAnnouncer.Run()
1753 if t.trackerAnnouncers == nil {
1754 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1756 t.trackerAnnouncers[_url] = sl
1759 // Adds and starts tracker scrapers for tracker URLs that aren't already
1761 func (t *Torrent) startMissingTrackerScrapers() {
1762 if t.cl.config.DisableTrackers {
1765 t.startScrapingTracker(t.metainfo.Announce)
1766 for _, tier := range t.metainfo.AnnounceList {
1767 for _, url := range tier {
1768 t.startScrapingTracker(url)
1773 // Returns an AnnounceRequest with fields filled out to defaults and current
1775 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1776 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1777 // dependent on the network in use.
1778 return tracker.AnnounceRequest{
1780 NumWant: func() int32 {
1781 if t.wantPeers() && len(t.cl.dialers) > 0 {
1782 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1787 Port: uint16(t.cl.incomingPeerPort()),
1788 PeerId: t.cl.peerID,
1789 InfoHash: t.infoHash,
1790 Key: t.cl.announceKey(),
1792 // The following are vaguely described in BEP 3.
1794 Left: t.bytesLeftAnnounce(),
1795 Uploaded: t.stats.BytesWrittenData.Int64(),
1796 // There's no mention of wasted or unwanted download in the BEP.
1797 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1801 // Adds peers revealed in an announce until the announce ends, or we have
1803 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1805 for v := range pvs {
1808 for _, cp := range v.Peers {
1810 // Can't do anything with this.
1813 if t.addPeer(PeerInfo{
1814 Addr: ipPortAddr{cp.IP, cp.Port},
1815 Source: PeerSourceDhtGetPeers,
1822 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1827 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1828 // announce ends. stop will force the announce to end.
1829 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1830 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1834 _done := make(chan struct{})
1838 t.consumeDhtAnnouncePeers(ps.Peers())
1844 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1845 _, stop, err := t.AnnounceToDht(s)
1850 case <-t.closed.Done():
1851 case <-time.After(5 * time.Minute):
1857 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1863 if t.closed.IsSet() {
1866 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1867 // TODO: We can include the announce_peer step depending on whether we can receive
1868 // inbound connections. We should probably only announce once every 15 mins too.
1869 if !t.wantAnyConns() {
1872 // TODO: Determine if there's a listener on the port we're announcing.
1873 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1884 err := t.timeboxedAnnounceToDht(s)
1886 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1892 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1893 for _, p := range peers {
1901 // The returned TorrentStats may require alignment in memory. See
1902 // https://github.com/anacrolix/torrent/issues/383.
1903 func (t *Torrent) Stats() TorrentStats {
1905 defer t.cl.rUnlock()
1906 return t.statsLocked()
1909 func (t *Torrent) statsLocked() (ret TorrentStats) {
1910 ret.ActivePeers = len(t.conns)
1911 ret.HalfOpenPeers = len(t.halfOpen)
1912 ret.PendingPeers = t.peers.Len()
1913 ret.TotalPeers = t.numTotalPeers()
1914 ret.ConnectedSeeders = 0
1915 for c := range t.conns {
1916 if all, ok := c.peerHasAllPieces(); all && ok {
1917 ret.ConnectedSeeders++
1920 ret.ConnStats = t.stats.Copy()
1921 ret.PiecesComplete = t.numPiecesCompleted()
1925 // The total number of peers in the torrent.
1926 func (t *Torrent) numTotalPeers() int {
1927 peers := make(map[string]struct{})
1928 for conn := range t.conns {
1929 ra := conn.conn.RemoteAddr()
1931 // It's been closed and doesn't support RemoteAddr.
1934 peers[ra.String()] = struct{}{}
1936 for addr := range t.halfOpen {
1937 peers[addr] = struct{}{}
1939 t.peers.Each(func(peer PeerInfo) {
1940 peers[peer.Addr.String()] = struct{}{}
1945 // Reconcile bytes transferred before connection was associated with a
1947 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1948 if c._stats != (ConnStats{
1949 // Handshakes should only increment these fields:
1950 BytesWritten: c._stats.BytesWritten,
1951 BytesRead: c._stats.BytesRead,
1955 c.postHandshakeStats(func(cs *ConnStats) {
1956 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1957 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1959 c.reconciledHandshakeStats = true
1962 // Returns true if the connection is added.
1963 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1966 torrent.Add("added connections", 1)
1969 if t.closed.IsSet() {
1970 return errors.New("torrent closed")
1972 for c0 := range t.conns {
1973 if c.PeerID != c0.PeerID {
1976 if !t.cl.config.DropDuplicatePeerIds {
1979 if c.hasPreferredNetworkOver(c0) {
1981 t.deletePeerConn(c0)
1983 return errors.New("existing connection preferred")
1986 if len(t.conns) >= t.maxEstablishedConns {
1987 numOutgoing := t.numOutgoingConns()
1988 numIncoming := len(t.conns) - numOutgoing
1989 c := t.worstBadConn(worseConnLensOpts{
1990 // We've already established that we have too many connections at this point, so we just
1991 // need to match what kind we have too many of vs. what we're trying to add now.
1992 incomingIsBad: (numIncoming-numOutgoing > 1) && c.outgoing,
1993 outgoingIsBad: (numOutgoing-numIncoming > 1) && !c.outgoing,
1996 return errors.New("don't want conn")
2001 if len(t.conns) >= t.maxEstablishedConns {
2004 t.conns[c] = struct{}{}
2005 t.cl.event.Broadcast()
2006 // We'll never receive the "p" extended handshake parameter.
2007 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
2013 func (t *Torrent) newConnsAllowed() bool {
2014 if !t.networkingEnabled.Bool() {
2017 if t.closed.IsSet() {
2020 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2026 func (t *Torrent) wantAnyConns() bool {
2027 if !t.networkingEnabled.Bool() {
2030 if t.closed.IsSet() {
2033 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2036 return len(t.conns) < t.maxEstablishedConns
2039 func (t *Torrent) wantOutgoingConns() bool {
2040 if !t.newConnsAllowed() {
2043 if len(t.conns) < t.maxEstablishedConns {
2046 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2047 return t.worstBadConn(worseConnLensOpts{
2048 incomingIsBad: numIncomingConns-t.numOutgoingConns() > 1,
2049 outgoingIsBad: false,
2053 func (t *Torrent) wantIncomingConns() bool {
2054 if !t.newConnsAllowed() {
2057 if len(t.conns) < t.maxEstablishedConns {
2060 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2061 return t.worstBadConn(worseConnLensOpts{
2062 incomingIsBad: false,
2063 outgoingIsBad: t.numOutgoingConns()-numIncomingConns > 1,
2067 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
2070 oldMax = t.maxEstablishedConns
2071 t.maxEstablishedConns = max
2072 wcs := worseConnSlice{
2073 conns: t.appendConns(nil, func(*PeerConn) bool {
2077 wcs.initKeys(worseConnLensOpts{})
2079 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
2080 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
2086 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
2087 t.logger.LazyLog(log.Debug, func() log.Msg {
2088 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
2092 t.cl.event.Broadcast()
2093 if t.closed.IsSet() {
2097 // Don't score the first time a piece is hashed, it could be an initial check.
2098 if p.storageCompletionOk {
2100 pieceHashedCorrect.Add(1)
2103 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
2104 ).AddValues(t, p).LogLevel(
2106 log.Debug, t.logger)
2108 pieceHashedNotCorrect.Add(1)
2113 t.publishPieceChange(piece)
2116 t.publishPieceChange(piece)
2120 if len(p.dirtiers) != 0 {
2121 // Don't increment stats above connection-level for every involved connection.
2122 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2124 for c := range p.dirtiers {
2125 c._stats.incrementPiecesDirtiedGood()
2127 t.clearPieceTouchers(piece)
2128 hasDirty := p.hasDirtyChunks()
2131 p.Flush() // You can be synchronous here!
2133 err := p.Storage().MarkComplete()
2135 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2139 if t.closed.IsSet() {
2142 t.pendAllChunkSpecs(piece)
2144 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2145 // Peers contributed to all the data for this piece hash failure, and the failure was
2146 // not due to errors in the storage (such as data being dropped in a cache).
2148 // Increment Torrent and above stats, and then specific connections.
2149 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2150 for c := range p.dirtiers {
2151 // Y u do dis peer?!
2152 c.stats().incrementPiecesDirtiedBad()
2155 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2156 for c := range p.dirtiers {
2158 bannableTouchers = append(bannableTouchers, c)
2161 t.clearPieceTouchers(piece)
2162 slices.Sort(bannableTouchers, connLessTrusted)
2164 if t.cl.config.Debug {
2166 "bannable conns by trust for piece %d: %v",
2168 func() (ret []connectionTrust) {
2169 for _, c := range bannableTouchers {
2170 ret = append(ret, c.trust())
2177 if len(bannableTouchers) >= 1 {
2178 c := bannableTouchers[0]
2179 if len(bannableTouchers) != 1 {
2180 t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2182 // Turns out it's still useful to ban peers like this because if there's only a
2183 // single peer for a piece, and we never progress that piece to completion, we
2184 // will never smart-ban them. Discovered in
2185 // https://github.com/anacrolix/torrent/issues/715.
2186 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2191 t.onIncompletePiece(piece)
2192 p.Storage().MarkNotComplete()
2194 t.updatePieceCompletion(piece)
2197 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2198 start := t.pieceRequestIndexOffset(piece)
2199 end := start + t.pieceNumChunks(piece)
2200 for ri := start; ri < end; ri++ {
2205 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2206 t.pendAllChunkSpecs(piece)
2207 t.cancelRequestsForPiece(piece)
2208 t.piece(piece).readerCond.Broadcast()
2209 for conn := range t.conns {
2211 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2215 // Called when a piece is found to be not complete.
2216 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2217 if t.pieceAllDirty(piece) {
2218 t.pendAllChunkSpecs(piece)
2220 if !t.wantPieceIndex(piece) {
2221 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2224 // We could drop any connections that we told we have a piece that we
2225 // don't here. But there's a test failure, and it seems clients don't care
2226 // if you request pieces that you already claim to have. Pruning bad
2227 // connections might just remove any connections that aren't treating us
2228 // favourably anyway.
2230 // for c := range t.conns {
2231 // if c.sentHave(piece) {
2235 t.iterPeers(func(conn *Peer) {
2236 if conn.peerHasPiece(piece) {
2237 conn.updateRequests("piece incomplete")
2242 func (t *Torrent) tryCreateMorePieceHashers() {
2243 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2247 func (t *Torrent) tryCreatePieceHasher() bool {
2248 if t.storage == nil {
2251 pi, ok := t.getPieceToHash()
2256 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2258 t.publishPieceChange(pi)
2259 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2260 t.storageLock.RLock()
2261 t.activePieceHashes++
2262 go t.pieceHasher(pi)
2266 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2267 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2268 if t.piece(i).hashing {
2278 func (t *Torrent) dropBannedPeers() {
2279 t.iterPeers(func(p *Peer) {
2280 remoteIp := p.remoteIp()
2281 if remoteIp == nil {
2282 if p.bannableAddr.Ok {
2283 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2287 netipAddr := netip.MustParseAddr(remoteIp.String())
2288 if Some(netipAddr) != p.bannableAddr {
2289 t.logger.WithDefaultLevel(log.Debug).Printf(
2290 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2291 p, remoteIp, p.bannableAddr)
2293 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2294 // Should this be a close?
2296 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2301 func (t *Torrent) pieceHasher(index pieceIndex) {
2303 sum, failedPeers, copyErr := t.hashPiece(index)
2304 correct := sum == *p.hash
2308 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2310 t.storageLock.RUnlock()
2314 for peer := range failedPeers {
2315 t.cl.banPeerIP(peer.AsSlice())
2316 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2319 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2320 t.smartBanCache.ForgetBlock(ri)
2324 t.pieceHashed(index, correct, copyErr)
2325 t.updatePiecePriority(index, "Torrent.pieceHasher")
2326 t.activePieceHashes--
2327 t.tryCreateMorePieceHashers()
2330 // Return the connections that touched a piece, and clear the entries while doing it.
2331 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2333 for c := range p.dirtiers {
2334 delete(c.peerTouchedPieces, pi)
2335 delete(p.dirtiers, c)
2339 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2340 t.iterPeers(func(p *Peer) {
2341 ret = append(ret, p)
2346 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2347 piece := t.piece(pieceIndex)
2348 if piece.queuedForHash() {
2351 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2352 t.publishPieceChange(pieceIndex)
2353 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2354 t.tryCreateMorePieceHashers()
2357 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2358 // before the Info is available.
2359 func (t *Torrent) VerifyData() {
2360 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2361 t.Piece(i).VerifyData()
2365 // Start the process of connecting to the given peer for the given torrent if appropriate. I'm not
2366 // sure all the PeerInfo fields are being used.
2367 func (t *Torrent) initiateConn(
2369 requireRendezvous bool,
2370 skipHolepunchRendezvous bool,
2372 if peer.Id == t.cl.peerID {
2375 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2379 if t.addrActive(addr.String()) {
2383 t.halfOpen[addr.String()] = peer
2384 go t.cl.outgoingConnection(outgoingConnOpts{
2387 requireRendezvous: requireRendezvous,
2388 skipHolepunchRendezvous: skipHolepunchRendezvous,
2389 }, peer.Source, peer.Trusted)
2392 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2393 // quickly make one Client visible to the Torrent of another Client.
2394 func (t *Torrent) AddClientPeer(cl *Client) int {
2395 return t.AddPeers(func() (ps []PeerInfo) {
2396 for _, la := range cl.ListenAddrs() {
2397 ps = append(ps, PeerInfo{
2406 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2408 func (t *Torrent) allStats(f func(*ConnStats)) {
2413 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2414 return t.pieces[i].hashing
2417 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2418 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2421 func (t *Torrent) dialTimeout() time.Duration {
2422 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2425 func (t *Torrent) piece(i int) *Piece {
2429 func (t *Torrent) onWriteChunkErr(err error) {
2430 if t.userOnWriteChunkErr != nil {
2431 go t.userOnWriteChunkErr(err)
2434 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2435 t.disallowDataDownloadLocked()
2438 func (t *Torrent) DisallowDataDownload() {
2439 t.disallowDataDownloadLocked()
2442 func (t *Torrent) disallowDataDownloadLocked() {
2443 t.dataDownloadDisallowed.Set()
2446 func (t *Torrent) AllowDataDownload() {
2447 t.dataDownloadDisallowed.Clear()
2450 // Enables uploading data, if it was disabled.
2451 func (t *Torrent) AllowDataUpload() {
2454 t.dataUploadDisallowed = false
2455 for c := range t.conns {
2456 c.updateRequests("allow data upload")
2460 // Disables uploading data, if it was enabled.
2461 func (t *Torrent) DisallowDataUpload() {
2464 t.dataUploadDisallowed = true
2465 for c := range t.conns {
2466 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2467 c.updateRequests("disallow data upload")
2471 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2472 // or if nil, a critical message is logged, and data download is disabled.
2473 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2476 t.userOnWriteChunkErr = f
2479 func (t *Torrent) iterPeers(f func(p *Peer)) {
2480 for pc := range t.conns {
2483 for _, ws := range t.webSeeds {
2488 func (t *Torrent) callbacks() *Callbacks {
2489 return &t.cl.config.Callbacks
2492 type AddWebSeedsOpt func(*webseed.Client)
2494 // Sets the WebSeed trailing path escaper for a webseed.Client.
2495 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2496 return func(c *webseed.Client) {
2497 c.PathEscaper = custom
2501 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2504 for _, u := range urls {
2505 t.addWebSeed(u, opts...)
2509 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2510 if t.cl.config.DisableWebseeds {
2513 if _, ok := t.webSeeds[url]; ok {
2516 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2517 // right away. This value should be some multiple of the number of connections to a host. I
2518 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2519 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2520 // "https://webtorrent.io/torrents/".
2521 const maxRequests = 16
2527 reconciledHandshakeStats: true,
2528 // This should affect how often we have to recompute requests for this peer. Note that
2529 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2530 // requests mark more often, so recomputation is probably sooner than with regular peer
2531 // conns. ~4x maxRequests would be about right.
2532 PeerMaxRequests: 128,
2533 // TODO: Set ban prefix?
2534 RemoteAddr: remoteAddrFromUrl(url),
2535 callbacks: t.callbacks(),
2537 client: webseed.Client{
2538 HttpClient: t.cl.httpClient,
2540 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2541 return &rateLimitedReader{
2542 l: t.cl.config.DownloadRateLimiter,
2547 activeRequests: make(map[Request]webseed.Request, maxRequests),
2549 ws.peer.initRequestState()
2550 for _, opt := range opts {
2553 ws.peer.initUpdateRequestsTimer()
2554 ws.requesterCond.L = t.cl.locker()
2555 for i := 0; i < maxRequests; i += 1 {
2558 for _, f := range t.callbacks().NewPeer {
2561 ws.peer.logger = t.logger.WithContextValue(&ws)
2562 ws.peer.peerImpl = &ws
2564 ws.onGotInfo(t.info)
2566 t.webSeeds[url] = &ws.peer
2569 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2570 t.iterPeers(func(p1 *Peer) {
2578 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2579 index := t.pieceIndexOfRequestIndex(ri)
2582 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2586 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2587 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2590 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2591 return RequestIndex(piece) * t.chunksPerRegularPiece()
2594 func (t *Torrent) updateComplete() {
2595 t.Complete.SetBool(t.haveAllPieces())
2598 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2599 p := t.requestingPeer(r)
2603 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2604 //delete(t.pendingRequests, r)
2605 if _, ok := t.requestState[r]; ok {
2606 panic("expected request state to be gone")
2611 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2612 return t.requestState[r].peer
2615 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2616 if t.connsWithAllPieces == nil {
2617 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2619 t.connsWithAllPieces[p] = struct{}{}
2622 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2623 _, ok := t.connsWithAllPieces[p]
2624 delete(t.connsWithAllPieces, p)
2628 func (t *Torrent) numActivePeers() int {
2629 return len(t.conns) + len(t.webSeeds)
2632 func (t *Torrent) hasStorageCap() bool {
2633 f := t.storage.Capacity
2641 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2642 return pieceIndex(ri / t.chunksPerRegularPiece())
2645 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2646 reuseIter *typedRoaring.Iterator[RequestIndex],
2648 f func(RequestIndex),
2650 reuseIter.Initialize(&t.dirtyChunks)
2651 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2652 iterBitmapUnsetInRange(
2654 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2659 type requestState struct {
2664 // Returns an error if a received chunk is out of bounds in someway.
2665 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2667 return errors.New("torrent missing info")
2669 if int(r.Index) >= t.numPieces() {
2670 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2672 pieceLength := t.pieceLength(pieceIndex(r.Index))
2673 if r.Begin >= pieceLength {
2674 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2676 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2677 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2678 // should be considerable checks elsewhere for this case due to the network overhead. We should
2679 // catch most of the overflow manipulation stuff by checking index and begin above.
2683 func (t *Torrent) peerConnsWithDialAddrPort(target netip.AddrPort) (ret []*PeerConn) {
2684 for pc := range t.conns {
2685 dialAddr, err := pc.remoteDialAddrPort()
2689 if dialAddr != target {
2692 ret = append(ret, pc)
2697 func makeUtHolepunchMsgForPeerConn(
2698 recipient *PeerConn,
2699 msgType utHolepunch.MsgType,
2700 addrPort netip.AddrPort,
2701 errCode utHolepunch.ErrCode,
2703 utHolepunchMsg := utHolepunch.Msg{
2708 extendedPayload, err := utHolepunchMsg.MarshalBinary()
2714 ExtendedID: MapMustGet(recipient.PeerExtensionIDs, utHolepunch.ExtensionName),
2715 ExtendedPayload: extendedPayload,
2719 func sendUtHolepunchMsg(
2721 msgType utHolepunch.MsgType,
2722 addrPort netip.AddrPort,
2723 errCode utHolepunch.ErrCode,
2725 pc.write(makeUtHolepunchMsgForPeerConn(pc, msgType, addrPort, errCode))
2728 func (t *Torrent) handleReceivedUtHolepunchMsg(msg utHolepunch.Msg, sender *PeerConn) error {
2729 switch msg.MsgType {
2730 case utHolepunch.Rendezvous:
2731 t.logger.Printf("got holepunch rendezvous request for %v from %p", msg.AddrPort, sender)
2732 sendMsg := sendUtHolepunchMsg
2733 senderAddrPort, err := sender.remoteDialAddrPort()
2735 sender.logger.Levelf(
2737 "error getting ut_holepunch rendezvous sender's dial address: %v",
2740 // There's no better error code. The sender's address itself is invalid. I don't see
2741 // this error message being appropriate anywhere else anyway.
2742 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSuchPeer)
2744 targets := t.peerConnsWithDialAddrPort(msg.AddrPort)
2745 if len(targets) == 0 {
2746 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NotConnected)
2749 for _, pc := range targets {
2750 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2751 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSupport)
2754 sendMsg(sender, utHolepunch.Connect, msg.AddrPort, 0)
2755 sendMsg(pc, utHolepunch.Connect, senderAddrPort, 0)
2758 case utHolepunch.Connect:
2759 t.logger.Printf("got holepunch connect from %v for %v", sender, msg.AddrPort)
2760 rz, ok := t.utHolepunchRendezvous[msg.AddrPort]
2762 delete(rz.relays, sender)
2764 rz.relayCond.Broadcast()
2766 // If the rendezvous was removed because we timed out or already got a connect signal,
2767 // it doesn't hurt to try again.
2768 t.initiateConn(PeerInfo{
2770 Source: PeerSourceUtHolepunch,
2774 case utHolepunch.Error:
2775 rz, ok := t.utHolepunchRendezvous[msg.AddrPort]
2777 delete(rz.relays, sender)
2778 rz.relayCond.Broadcast()
2780 t.logger.Printf("received ut_holepunch error message from %v: %v", sender, msg.ErrCode)
2783 return fmt.Errorf("unhandled msg type %v", msg.MsgType)
2787 func (t *Torrent) startHolepunchRendezvous(addrPort netip.AddrPort) (rz *utHolepunchRendezvous, err error) {
2788 if MapContains(t.utHolepunchRendezvous, addrPort) {
2789 err = errors.New("rendezvous already exists")
2793 for pc := range t.conns {
2794 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2797 if pc.supportsExtension(pp.ExtensionNamePex) {
2798 if !g.MapContains(pc.pex.remoteLiveConns, addrPort) {
2802 sendUtHolepunchMsg(pc, utHolepunch.Rendezvous, addrPort, 0)
2803 MakeMapIfNilAndSet(&rz.relays, pc, struct{}{})
2805 if len(rz.relays) == 0 {
2806 err = fmt.Errorf("no eligible relays")
2809 if !MakeMapIfNilAndSet(&t.utHolepunchRendezvous, addrPort, rz) {
2810 panic("expected to fail earlier if rendezvous already exists")