21 "github.com/RoaringBitmap/roaring"
22 "github.com/anacrolix/chansync"
23 "github.com/anacrolix/chansync/events"
24 "github.com/anacrolix/dht/v2"
25 . "github.com/anacrolix/generics"
26 g "github.com/anacrolix/generics"
27 "github.com/anacrolix/log"
28 "github.com/anacrolix/missinggo/slices"
29 "github.com/anacrolix/missinggo/v2"
30 "github.com/anacrolix/missinggo/v2/bitmap"
31 "github.com/anacrolix/missinggo/v2/pubsub"
32 "github.com/anacrolix/multiless"
33 "github.com/anacrolix/sync"
34 "github.com/pion/datachannel"
35 "golang.org/x/exp/maps"
36 "golang.org/x/sync/errgroup"
38 "github.com/anacrolix/torrent/bencode"
39 "github.com/anacrolix/torrent/internal/check"
40 "github.com/anacrolix/torrent/internal/nestedmaps"
41 "github.com/anacrolix/torrent/merkle"
42 "github.com/anacrolix/torrent/metainfo"
43 pp "github.com/anacrolix/torrent/peer_protocol"
44 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
45 request_strategy "github.com/anacrolix/torrent/request-strategy"
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/types/infohash"
50 infohash_v2 "github.com/anacrolix/torrent/types/infohash-v2"
51 "github.com/anacrolix/torrent/webseed"
52 "github.com/anacrolix/torrent/webtorrent"
55 // Maintains state of torrent within a Client. Many methods should not be called before the info is
56 // available, see .Info and .GotInfo.
58 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
59 // alignment. See #262.
64 networkingEnabled chansync.Flag
65 dataDownloadDisallowed chansync.Flag
66 dataUploadDisallowed bool
67 userOnWriteChunkErr func(error)
69 closed chansync.SetOnce
72 infoHash g.Option[metainfo.Hash]
73 infoHashV2 g.Option[infohash_v2.T]
77 // The order pieces are requested if there's no stronger reason like availability or priority.
78 pieceRequestOrder []int
79 // Values are the piece indices that changed.
80 pieceStateChanges pubsub.PubSub[PieceStateChange]
81 // The size of chunks to request from peers over the wire. This is
82 // normally 16KiB by convention these days.
85 // Total length of the torrent in bytes. Stored because it's not O(1) to
86 // get this from the info dict.
89 // The storage to open when the info dict becomes available.
90 storageOpener *storage.Client
91 // Storage for torrent data.
92 storage *storage.Torrent
93 // Read-locked for using storage, and write-locked for Closing.
94 storageLock sync.RWMutex
96 // TODO: Only announce stuff is used?
97 metainfo metainfo.MetaInfo
99 // The info dict. nil if we don't have it (yet).
103 _chunksPerRegularPiece chunkIndexType
105 webSeeds map[string]*Peer
106 // Active peer connections, running message stream loops. TODO: Make this
107 // open (not-closed) connections only.
108 conns map[*PeerConn]struct{}
109 maxEstablishedConns int
110 // Set of addrs to which we're attempting to connect. Connections are
111 // half-open until all handshakes are completed.
112 halfOpen map[string]map[outgoingConnAttemptKey]*PeerInfo
114 // Reserve of peers to connect to. A peer can be both here and in the
115 // active connections if were told about the peer after connecting with
116 // them. That encourages us to reconnect to peers that are well known in
118 peers prioritizedPeers
119 // Whether we want to know more peers.
120 wantPeersEvent missinggo.Event
121 // An announcer for each tracker URL.
122 trackerAnnouncers map[torrentTrackerAnnouncerKey]torrentTrackerAnnouncer
123 // How many times we've initiated a DHT announce. TODO: Move into stats.
126 // Name used if the info name isn't available. Should be cleared when the
127 // Info does become available.
131 // The bencoded bytes of the info dict. This is actively manipulated if
132 // the info bytes aren't initially available, and we try to fetch them
135 // Each element corresponds to the 16KiB metadata pieces. If true, we have
136 // received that piece.
137 metadataCompletedChunks []bool
138 metadataChanged sync.Cond
140 // Closed when .Info is obtained.
141 gotMetainfoC chan struct{}
143 readers map[*reader]struct{}
144 _readerNowPieces bitmap.Bitmap
145 _readerReadaheadPieces bitmap.Bitmap
147 // A cache of pieces we need to get. Calculated from various piece and file priorities and
148 // completion states elsewhere. Includes piece data and piece v2 hashes.
149 _pendingPieces roaring.Bitmap
150 // A cache of completed piece indices.
151 _completedPieces roaring.Bitmap
152 // Pieces that need to be hashed.
153 piecesQueuedForHash bitmap.Bitmap
154 activePieceHashes int
155 initialPieceCheckDisabled bool
157 connsWithAllPieces map[*Peer]struct{}
159 requestState map[RequestIndex]requestState
160 // Chunks we've written to since the corresponding piece was last checked.
161 dirtyChunks typedRoaring.Bitmap[RequestIndex]
165 // Is On when all pieces are complete.
166 Complete chansync.Flag
168 // Torrent sources in use keyed by the source string.
169 activeSources sync.Map
170 sourcesLogger log.Logger
172 smartBanCache smartBanCache
174 // Large allocations reused between request state updates.
175 requestPieceStates []request_strategy.PieceRequestOrderState
176 requestIndexes []RequestIndex
181 type torrentTrackerAnnouncerKey struct {
182 shortInfohash [20]byte
186 type outgoingConnAttemptKey = *PeerInfo
188 func (t *Torrent) length() int64 {
189 return t._length.Value
192 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
193 // This could be done with roaring.BitSliceIndexing.
194 t.iterPeers(func(peer *Peer) {
195 if _, ok := t.connsWithAllPieces[peer]; ok {
198 if peer.peerHasPiece(i) {
205 func (t *Torrent) decPieceAvailability(i pieceIndex) {
210 if p.relativeAvailability <= 0 {
211 panic(p.relativeAvailability)
213 p.relativeAvailability--
214 t.updatePieceRequestOrderPiece(i)
217 func (t *Torrent) incPieceAvailability(i pieceIndex) {
218 // If we don't the info, this should be reconciled when we do.
221 p.relativeAvailability++
222 t.updatePieceRequestOrderPiece(i)
226 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
227 return t._readerNowPieces
230 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
231 return t._readerReadaheadPieces
234 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
235 return t.piece(i).ignoreForRequests()
238 // Returns a channel that is closed when the Torrent is closed.
239 func (t *Torrent) Closed() events.Done {
240 return t.closed.Done()
243 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
244 // pending, and half-open peers.
245 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
246 // Add pending peers to the list
247 t.peers.Each(func(peer PeerInfo) {
248 ks = append(ks, peer)
251 // Add half-open peers to the list
252 for _, attempts := range t.halfOpen {
253 for _, peer := range attempts {
254 ks = append(ks, *peer)
258 // Add active peers to the list
261 for conn := range t.conns {
262 ks = append(ks, PeerInfo{
264 Addr: conn.RemoteAddr,
265 Source: conn.Discovery,
266 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
267 // > But if we're not connected to them with an encrypted connection, I couldn't say
268 // > what's appropriate. We can carry forward the SupportsEncryption value as we
269 // > received it from trackers/DHT/PEX, or just use the encryption state for the
270 // > connection. It's probably easiest to do the latter for now.
271 // https://github.com/anacrolix/torrent/pull/188
272 SupportsEncryption: conn.headerEncrypted,
279 func (t *Torrent) setChunkSize(size pp.Integer) {
281 t.chunkPool = sync.Pool{
282 New: func() interface{} {
283 b := make([]byte, size)
289 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
290 return t._completedPieces.Contains(bitmap.BitIndex(piece))
293 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
294 if t.storage == nil {
295 return storage.Completion{Complete: false, Ok: true}
297 return t.pieces[piece].Storage().Completion()
300 // There's a connection to that address already.
301 func (t *Torrent) addrActive(addr string) bool {
302 if _, ok := t.halfOpen[addr]; ok {
305 for c := range t.conns {
307 if ra.String() == addr {
314 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
315 return t.appendConns(ret, func(conn *PeerConn) bool {
316 return !conn.closed.IsSet()
320 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
321 for c := range t.conns {
329 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
331 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
332 if t.closed.IsSet() {
335 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
336 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
337 torrent.Add("peers not added because of bad addr", 1)
338 // cl.logger.Printf("peers not added because of bad addr: %v", p)
342 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
343 torrent.Add("peers replaced", 1)
344 if !replaced.equal(p) {
345 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
352 for t.peers.Len() > cl.config.TorrentPeersHighWater {
353 _, ok := t.peers.DeleteMin()
355 torrent.Add("excess reserve peers discarded", 1)
361 func (t *Torrent) invalidateMetadata() {
362 for i := 0; i < len(t.metadataCompletedChunks); i++ {
363 t.metadataCompletedChunks[i] = false
370 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
374 if index >= len(t.metadataCompletedChunks) {
375 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
378 copy(t.metadataBytes[(1<<14)*index:], data)
379 t.metadataCompletedChunks[index] = true
382 func (t *Torrent) metadataPieceCount() int {
383 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
386 func (t *Torrent) haveMetadataPiece(piece int) bool {
388 return (1<<14)*piece < len(t.metadataBytes)
390 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
394 func (t *Torrent) metadataSize() int {
395 return len(t.metadataBytes)
398 func (t *Torrent) makePieces() {
399 t.pieces = make([]Piece, t.info.NumPieces())
400 for i := range t.pieces {
401 piece := &t.pieces[i]
404 piece.noPendingWrites.L = &piece.pendingWritesMutex
406 piece.hash = (*metainfo.Hash)(unsafe.Pointer(
407 unsafe.SliceData(t.info.Pieces[i*sha1.Size : (i+1)*sha1.Size])))
410 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
411 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
412 piece.files = files[beginFile:endFile]
413 if t.info.FilesArePieceAligned() {
414 numFiles := len(piece.files)
416 panic(fmt.Sprintf("%v:%v", beginFile, endFile))
419 file := piece.mustGetOnlyFile()
420 if file.numPieces() == 1 {
421 piece.hashV2.Set(file.piecesRoot.Unwrap())
428 func (t *Torrent) AddPieceLayers(layers map[string]string) (errs []error) {
433 for _, f := range *t.files {
434 if !f.piecesRoot.Ok {
435 err := fmt.Errorf("no piece root set for file %v", f)
436 errs = append(errs, err)
439 compactLayer, ok := layers[string(f.piecesRoot.Value[:])]
440 var hashes [][32]byte
443 hashes, err = merkle.CompactLayerToSliceHashes(compactLayer)
445 err = fmt.Errorf("bad piece layers for file %q: %w", f, err)
446 errs = append(errs, err)
449 } else if f.length > t.info.PieceLength {
450 // BEP 52 is pretty strongly worded about this, even though we should be able to
451 // recover: If a v2 torrent is added by magnet link or infohash, we need to fetch piece
452 // layers ourselves anyway, and that's how we can recover from this.
453 t.logger.Levelf(log.Warning, "no piece layers for file %q", f)
456 hashes = [][32]byte{f.piecesRoot.Value}
458 if len(hashes) != f.numPieces() {
461 fmt.Errorf("file %q: got %v hashes expected %v", f, len(hashes), f.numPieces()),
465 root := merkle.RootWithPadHash(hashes, metainfo.HashForPiecePad(t.info.PieceLength))
466 if root != f.piecesRoot.Value {
467 errs = append(errs, fmt.Errorf("%v: expected hash %x got %x", f, f.piecesRoot.Value, root))
470 for i := range f.numPieces() {
471 pi := f.BeginPieceIndex() + i
473 p.setV2Hash(hashes[i])
479 // Returns the index of the first file containing the piece. files must be
480 // ordered by offset.
481 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
482 for i, f := range files {
483 if f.offset+f.length > pieceOffset {
490 // Returns the index after the last file containing the piece. files must be
491 // ordered by offset.
492 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
493 for i, f := range files {
494 if f.offset >= pieceEndOffset {
501 func (t *Torrent) cacheLength() {
503 for _, f := range t.info.UpvertedFiles() {
509 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
511 func (t *Torrent) setInfo(info *metainfo.Info) error {
512 if err := validateInfo(info); err != nil {
513 return fmt.Errorf("bad info: %s", err)
515 if t.storageOpener != nil {
517 t.storage, err = t.storageOpener.OpenTorrent(info, *t.canonicalShortInfohash())
519 return fmt.Errorf("error opening torrent storage: %s", err)
525 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
527 t.displayName = "" // Save a few bytes lol.
534 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
535 return request_strategy.PieceRequestOrderKey{
536 InfoHash: *t.canonicalShortInfohash(),
541 // This seems to be all the follow-up tasks after info is set, that can't fail.
542 func (t *Torrent) onSetInfo() {
543 t.pieceRequestOrder = rand.Perm(t.numPieces())
544 t.initPieceRequestOrder()
545 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
546 for i := range t.pieces {
548 // Need to add relativeAvailability before updating piece completion, as that may result in conns
550 if p.relativeAvailability != 0 {
551 panic(p.relativeAvailability)
553 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
554 t.addRequestOrderPiece(i)
555 t.updatePieceCompletion(i)
556 t.queueInitialPieceCheck(i)
558 t.cl.event.Broadcast()
559 close(t.gotMetainfoC)
560 t.updateWantPeersEvent()
561 t.requestState = make(map[RequestIndex]requestState)
562 t.tryCreateMorePieceHashers()
563 t.iterPeers(func(p *Peer) {
565 p.updateRequests("onSetInfo")
569 // Checks the info bytes hash to expected values. Fills in any missing infohashes.
570 func (t *Torrent) hashInfoBytes(b []byte, info *metainfo.Info) error {
571 v1Hash := infohash.HashBytes(b)
572 v2Hash := infohash_v2.HashBytes(b)
574 if t.infoHash.Ok && !t.infoHashV2.Ok {
575 if v1Hash == t.infoHash.Value {
577 t.infoHashV2.Set(v2Hash)
578 cl.torrentsByShortHash[*v2Hash.ToShort()] = t
580 } else if *v2Hash.ToShort() == t.infoHash.Value {
582 return errors.New("invalid v2 info")
584 t.infoHashV2.Set(v2Hash)
587 cl.torrentsByShortHash[v1Hash] = t
588 t.infoHash.Set(v1Hash)
591 } else if t.infoHash.Ok && t.infoHashV2.Ok {
592 if v1Hash != t.infoHash.Value {
593 return errors.New("incorrect v1 infohash")
595 if v2Hash != t.infoHashV2.Value {
596 return errors.New("incorrect v2 infohash")
598 } else if !t.infoHash.Ok && t.infoHashV2.Ok {
599 if v2Hash != t.infoHashV2.Value {
600 return errors.New("incorrect v2 infohash")
603 t.infoHash.Set(v1Hash)
604 cl.torrentsByShortHash[v1Hash] = t
607 panic("no expected infohashes")
612 // Called when metadata for a torrent becomes available.
613 func (t *Torrent) setInfoBytesLocked(b []byte) (err error) {
614 var info metainfo.Info
615 err = bencode.Unmarshal(b, &info)
617 err = fmt.Errorf("unmarshalling info bytes: %w", err)
620 err = t.hashInfoBytes(b, &info)
625 t.metadataCompletedChunks = nil
629 if err := t.setInfo(&info); err != nil {
636 func (t *Torrent) haveAllMetadataPieces() bool {
640 if t.metadataCompletedChunks == nil {
643 for _, have := range t.metadataCompletedChunks {
651 // TODO: Propagate errors to disconnect peer.
652 func (t *Torrent) setMetadataSize(size int) (err error) {
654 // We already know the correct metadata size.
657 if uint32(size) > maxMetadataSize {
658 return log.WithLevel(log.Warning, errors.New("bad size"))
660 if len(t.metadataBytes) == size {
663 t.metadataBytes = make([]byte, size)
664 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
665 t.metadataChanged.Broadcast()
666 for c := range t.conns {
667 c.requestPendingMetadata()
672 // The current working name for the torrent. Either the name in the info dict,
673 // or a display name given such as by the dn value in a magnet link, or "".
674 func (t *Torrent) name() string {
676 defer t.nameMu.RUnlock()
678 return t.info.BestName()
680 if t.displayName != "" {
683 return "infohash:" + t.canonicalShortInfohash().HexString()
686 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
687 p := &t.pieces[index]
688 ret.Priority = t.piecePriority(index)
689 ret.Completion = p.completion()
690 ret.QueuedForHash = p.queuedForHash()
691 ret.Hashing = p.hashing
692 ret.Checking = ret.QueuedForHash || ret.Hashing
693 ret.Marking = p.marking
694 if !ret.Complete && t.piecePartiallyDownloaded(index) {
697 if t.info.HasV2() && !p.hashV2.Ok {
698 ret.MissingPieceLayerHash = true
703 func (t *Torrent) metadataPieceSize(piece int) int {
704 return metadataPieceSize(len(t.metadataBytes), piece)
707 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
710 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
711 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
713 TotalSize: len(t.metadataBytes),
719 type pieceAvailabilityRun struct {
724 func (me pieceAvailabilityRun) String() string {
725 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
728 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
729 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
730 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
732 for i := range t.pieces {
733 rle.Append(t.pieces[i].availability(), 1)
739 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
740 freqs = make([]int, t.numActivePeers()+1)
741 for i := range t.pieces {
742 freqs[t.piece(i).availability()]++
747 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
748 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
749 ret = append(ret, PieceStateRun{
750 PieceState: el.(PieceState),
754 for index := range t.pieces {
755 rle.Append(t.pieceState(index), 1)
761 // Produces a small string representing a PieceStateRun.
762 func (psr PieceStateRun) String() (ret string) {
763 ret = fmt.Sprintf("%d", psr.Length)
764 ret += func() string {
765 switch psr.Priority {
766 case PiecePriorityNext:
768 case PiecePriorityNormal:
770 case PiecePriorityReadahead:
772 case PiecePriorityNow:
774 case PiecePriorityHigh:
783 if psr.QueuedForHash {
798 if psr.MissingPieceLayerHash {
804 func (t *Torrent) writeStatus(w io.Writer) {
806 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.Value.HexString())
809 fmt.Fprintf(w, "Infohash v2: %s\n", t.infoHashV2.Value.HexString())
811 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
813 fmt.Fprintf(w, "Metadata have: ")
814 for _, h := range t.metadataCompletedChunks {
815 fmt.Fprintf(w, "%c", func() rune {
825 fmt.Fprintf(w, "Piece length: %s\n",
828 return fmt.Sprintf("%v (%v chunks)",
830 float64(t.usualPieceSize())/float64(t.chunkSize))
837 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
838 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
839 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
840 // availability frequencies instead.
842 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
843 for _, run := range t.pieceAvailabilityRuns() {
844 ret = append(ret, run.String())
849 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
850 func() (ret []string) {
851 for avail, freq := range t.pieceAvailabilityFrequencies() {
855 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
861 fmt.Fprintf(w, "Reader Pieces:")
862 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
863 fmt.Fprintf(w, " %d:%d", begin, end)
868 fmt.Fprintf(w, "Enabled trackers:\n")
870 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
871 fmt.Fprintf(tw, " URL\tExtra\n")
872 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
875 var luns, runs url.URL = *lu, *ru
878 var ml missinggo.MultiLess
879 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
880 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
882 }).([]torrentTrackerAnnouncer) {
883 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
888 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
890 dumpStats(w, t.statsLocked())
892 fmt.Fprintf(w, "webseeds:\n")
893 t.writePeerStatuses(w, maps.Values(t.webSeeds))
895 peerConns := maps.Keys(t.conns)
896 // Peers without priorities first, then those with. I'm undecided about how to order peers
897 // without priorities.
898 sort.Slice(peerConns, func(li, ri int) bool {
901 ml := multiless.New()
902 lpp := g.ResultFromTuple(l.peerPriority()).ToOption()
903 rpp := g.ResultFromTuple(r.peerPriority()).ToOption()
904 ml = ml.Bool(lpp.Ok, rpp.Ok)
905 ml = ml.Uint32(rpp.Value, lpp.Value)
909 fmt.Fprintf(w, "%v peer conns:\n", len(peerConns))
910 t.writePeerStatuses(w, g.SliceMap(peerConns, func(pc *PeerConn) *Peer {
915 func (t *Torrent) writePeerStatuses(w io.Writer, peers []*Peer) {
917 for _, c := range peers {
921 w.Write(bytes.TrimRight(
922 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
927 func (t *Torrent) haveInfo() bool {
931 // Returns a run-time generated MetaInfo that includes the info bytes and
932 // announce-list as currently known to the client.
933 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
934 return metainfo.MetaInfo{
935 CreationDate: time.Now().Unix(),
936 Comment: "dynamic metainfo from client",
937 CreatedBy: "https://github.com/anacrolix/torrent",
938 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
939 InfoBytes: func() []byte {
941 return t.metadataBytes
946 UrlList: func() []string {
947 ret := make([]string, 0, len(t.webSeeds))
948 for url := range t.webSeeds {
949 ret = append(ret, url)
953 PieceLayers: t.pieceLayers(),
957 // Returns a count of bytes that are not complete in storage, and not pending being written to
958 // storage. This value is from the perspective of the download manager, and may not agree with the
959 // actual state in storage. If you want read data synchronously you should use a Reader. See
960 // https://github.com/anacrolix/torrent/issues/828.
961 func (t *Torrent) BytesMissing() (n int64) {
963 n = t.bytesMissingLocked()
968 func (t *Torrent) bytesMissingLocked() int64 {
972 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
973 roaring.Flip(b, 0, end).Iterate(cb)
976 func (t *Torrent) bytesLeft() (left int64) {
977 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
978 p := t.piece(pieceIndex(x))
979 left += int64(p.length() - p.numDirtyBytes())
985 // Bytes left to give in tracker announces.
986 func (t *Torrent) bytesLeftAnnounce() int64 {
994 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
995 if t.pieceComplete(piece) {
998 if t.pieceAllDirty(piece) {
1001 return t.pieces[piece].hasDirtyChunks()
1004 func (t *Torrent) usualPieceSize() int {
1005 return int(t.info.PieceLength)
1008 func (t *Torrent) numPieces() pieceIndex {
1009 return t.info.NumPieces()
1012 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
1013 return pieceIndex(t._completedPieces.GetCardinality())
1016 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
1017 if !t.closed.Set() {
1018 err = errors.New("already closed")
1021 for _, f := range t.onClose {
1024 if t.storage != nil {
1028 t.storageLock.Lock()
1029 defer t.storageLock.Unlock()
1030 if f := t.storage.Close; f != nil {
1033 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
1038 t.iterPeers(func(p *Peer) {
1041 if t.storage != nil {
1042 t.deletePieceRequestOrder()
1044 t.assertAllPiecesRelativeAvailabilityZero()
1046 t.cl.event.Broadcast()
1047 t.pieceStateChanges.Close()
1048 t.updateWantPeersEvent()
1052 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
1053 for i := range t.pieces {
1055 if p.relativeAvailability != 0 {
1056 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
1061 func (t *Torrent) requestOffset(r Request) int64 {
1062 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
1065 // Return the request that would include the given offset into the torrent data. Returns !ok if
1066 // there is no such request.
1067 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
1068 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
1071 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
1072 //defer perf.ScopeTimerErr(&err)()
1073 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
1074 if err == nil && n != len(data) {
1075 err = io.ErrShortWrite
1080 func (t *Torrent) bitfield() (bf []bool) {
1081 bf = make([]bool, t.numPieces())
1082 t._completedPieces.Iterate(func(piece uint32) (again bool) {
1089 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
1090 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
1093 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
1094 return t._chunksPerRegularPiece
1097 func (t *Torrent) numChunks() RequestIndex {
1098 if t.numPieces() == 0 {
1101 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
1104 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
1105 t.dirtyChunks.RemoveRange(
1106 uint64(t.pieceRequestIndexOffset(pieceIndex)),
1107 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
1110 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
1111 if t.info.PieceLength == 0 {
1112 // There will be no variance amongst pieces. Only pain.
1115 if t.info.FilesArePieceAligned() {
1117 file := p.mustGetOnlyFile()
1118 if piece == file.EndPieceIndex()-1 {
1119 return pp.Integer(file.length - (p.torrentBeginOffset() - file.offset))
1121 return pp.Integer(t.usualPieceSize())
1123 if piece == t.numPieces()-1 {
1124 ret := pp.Integer(t.length() % t.info.PieceLength)
1129 return pp.Integer(t.info.PieceLength)
1132 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
1133 return &blockCheckingWriter{
1134 cache: &t.smartBanCache,
1135 requestIndex: t.pieceRequestIndexOffset(piece),
1136 chunkSize: t.chunkSize.Int(),
1140 func (t *Torrent) hashPiece(piece pieceIndex) (
1142 // These are peers that sent us blocks that differ from what we hash here.
1143 differingPeers map[bannableAddr]struct{},
1147 p.waitNoPendingWrites()
1148 storagePiece := p.Storage()
1154 // Does the backend want to do its own hashing?
1155 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
1156 var sum metainfo.Hash
1157 // log.Printf("A piece decided to self-hash: %d", piece)
1158 sum, err = i.SelfHash()
1159 correct = sum == *p.hash
1160 // Can't do smart banning without reading the piece. The smartBanCache is still cleared
1161 // in pieceHasher regardless.
1165 } else if p.hashV2.Ok {
1166 h = merkle.NewHash()
1171 const logPieceContents = false
1172 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1173 writers := []io.Writer{h, smartBanWriter}
1174 var examineBuf bytes.Buffer
1175 if logPieceContents {
1176 writers = append(writers, &examineBuf)
1179 written, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1180 if err == nil && written != int64(p.length()) {
1181 err = fmt.Errorf("wrote %v bytes from storage, piece has length %v", written, p.length())
1183 if logPieceContents {
1184 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1186 smartBanWriter.Flush()
1187 differingPeers = smartBanWriter.badPeers
1190 n := len(h.Sum(sum[:0]))
1194 correct = sum == *p.hash
1195 } else if p.hashV2.Ok {
1197 n := len(h.Sum(sum[:0]))
1201 correct = sum == p.hashV2.Value
1208 func (t *Torrent) haveAnyPieces() bool {
1209 return !t._completedPieces.IsEmpty()
1212 func (t *Torrent) haveAllPieces() bool {
1216 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1219 func (t *Torrent) havePiece(index pieceIndex) bool {
1220 return t.haveInfo() && t.pieceComplete(index)
1223 func (t *Torrent) maybeDropMutuallyCompletePeer(
1224 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1228 if !t.cl.config.DropMutuallyCompletePeers {
1231 if !t.haveAllPieces() {
1234 if all, known := p.peerHasAllPieces(); !(known && all) {
1240 p.logger.Levelf(log.Debug, "is mutually complete; dropping")
1244 func (t *Torrent) haveChunk(r Request) (ret bool) {
1246 // log.Println("have chunk", r, ret)
1251 if t.pieceComplete(pieceIndex(r.Index)) {
1254 p := &t.pieces[r.Index]
1255 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1258 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1259 return chunkIndexType(cs.Begin / chunkSize)
1262 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1263 return !t._pendingPieces.IsEmpty() && t._pendingPieces.Contains(uint32(index))
1266 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1267 // conns (which is a map).
1268 var peerConnSlices sync.Pool
1270 func getPeerConnSlice(cap int) []*PeerConn {
1271 getInterface := peerConnSlices.Get()
1272 if getInterface == nil {
1273 return make([]*PeerConn, 0, cap)
1275 return getInterface.([]*PeerConn)[:0]
1279 // Calls the given function with a slice of unclosed conns. It uses a pool to reduce allocations as
1280 // this is a frequent occurrence.
1281 func (t *Torrent) withUnclosedConns(f func([]*PeerConn)) {
1282 sl := t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))
1284 peerConnSlices.Put(sl)
1287 func (t *Torrent) worstBadConnFromSlice(opts worseConnLensOpts, sl []*PeerConn) *PeerConn {
1288 wcs := worseConnSlice{conns: sl}
1291 for wcs.Len() != 0 {
1292 c := heap.Pop(&wcs).(*PeerConn)
1293 if opts.incomingIsBad && !c.outgoing {
1296 if opts.outgoingIsBad && c.outgoing {
1299 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1302 // If the connection is in the worst half of the established
1303 // connection quota and is older than a minute.
1304 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1305 // Give connections 1 minute to prove themselves.
1306 if time.Since(c.completedHandshake) > time.Minute {
1314 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1315 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1316 // established connections for more than a minute. This is O(n log n). If there was a way to not
1317 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1318 func (t *Torrent) worstBadConn(opts worseConnLensOpts) (ret *PeerConn) {
1319 t.withUnclosedConns(func(ucs []*PeerConn) {
1320 ret = t.worstBadConnFromSlice(opts, ucs)
1325 type PieceStateChange struct {
1330 func (t *Torrent) publishPieceStateChange(piece pieceIndex) {
1331 t.cl._mu.Defer(func() {
1332 cur := t.pieceState(piece)
1333 p := &t.pieces[piece]
1334 if cur != p.publicPieceState {
1335 p.publicPieceState = cur
1336 t.pieceStateChanges.Publish(PieceStateChange{
1344 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1345 if t.pieceComplete(piece) {
1348 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1351 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1352 return t.pieces[piece].allChunksDirty()
1355 func (t *Torrent) readersChanged() {
1356 t.updateReaderPieces()
1357 t.updateAllPiecePriorities("Torrent.readersChanged")
1360 func (t *Torrent) updateReaderPieces() {
1361 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1364 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1368 t.updateReaderPieces()
1369 // Order the ranges, high and low.
1371 if l.begin > h.begin {
1374 if l.end < h.begin {
1375 // Two distinct ranges.
1376 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1377 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1384 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1388 func (t *Torrent) maybeNewConns() {
1389 // Tickle the accept routine.
1390 t.cl.event.Broadcast()
1394 func (t *Torrent) onPiecePendingTriggers(piece pieceIndex, reason string) {
1395 if t._pendingPieces.Contains(uint32(piece)) {
1396 t.iterPeers(func(c *Peer) {
1397 // if c.requestState.Interested {
1400 if !c.isLowOnRequests() {
1403 if !c.peerHasPiece(piece) {
1406 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1409 c.updateRequests(reason)
1413 t.publishPieceStateChange(piece)
1416 func (t *Torrent) updatePiecePriorityNoTriggers(piece pieceIndex) (pendingChanged bool) {
1417 if !t.closed.IsSet() {
1418 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1420 t.updatePieceRequestOrderPiece(piece)
1423 newPrio := p.uncachedPriority()
1424 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1425 if newPrio == PiecePriorityNone && p.haveHash() {
1426 return t._pendingPieces.CheckedRemove(uint32(piece))
1428 return t._pendingPieces.CheckedAdd(uint32(piece))
1432 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1433 if t.updatePiecePriorityNoTriggers(piece) && !t.disableTriggers {
1434 t.onPiecePendingTriggers(piece, reason)
1436 t.updatePieceRequestOrderPiece(piece)
1439 func (t *Torrent) updateAllPiecePriorities(reason string) {
1440 t.updatePiecePriorities(0, t.numPieces(), reason)
1443 // Update all piece priorities in one hit. This function should have the same
1444 // output as updatePiecePriority, but across all pieces.
1445 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1446 for i := begin; i < end; i++ {
1447 t.updatePiecePriority(i, reason)
1451 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1452 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1453 if off >= t.length() {
1463 begin = pieceIndex(off / t.info.PieceLength)
1464 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1465 if end > pieceIndex(t.info.NumPieces()) {
1466 end = pieceIndex(t.info.NumPieces())
1471 // Returns true if all iterations complete without breaking. Returns the read regions for all
1472 // readers. The reader regions should not be merged as some callers depend on this method to
1473 // enumerate readers.
1474 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1475 for r := range t.readers {
1477 if p.begin >= p.end {
1480 if !f(p.begin, p.end) {
1487 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1488 return t.piece(piece).uncachedPriority()
1491 func (t *Torrent) pendRequest(req RequestIndex) {
1492 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1495 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1496 t.cl.event.Broadcast()
1497 if t.pieceComplete(piece) {
1498 t.onPieceCompleted(piece)
1500 t.onIncompletePiece(piece)
1502 t.updatePiecePriority(piece, reason)
1505 func (t *Torrent) numReceivedConns() (ret int) {
1506 for c := range t.conns {
1507 if c.Discovery == PeerSourceIncoming {
1514 func (t *Torrent) numOutgoingConns() (ret int) {
1515 for c := range t.conns {
1523 func (t *Torrent) maxHalfOpen() int {
1524 // Note that if we somehow exceed the maximum established conns, we want
1525 // the negative value to have an effect.
1526 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1527 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1528 // We want to allow some experimentation with new peers, and to try to
1529 // upset an oversupply of received connections.
1531 max(5, extraIncoming)+establishedHeadroom,
1532 int64(t.cl.config.HalfOpenConnsPerTorrent),
1536 func (t *Torrent) openNewConns() (initiated int) {
1537 defer t.updateWantPeersEvent()
1538 for t.peers.Len() != 0 {
1539 if !t.wantOutgoingConns() {
1542 if len(t.halfOpen) >= t.maxHalfOpen() {
1545 if len(t.cl.dialers) == 0 {
1548 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1551 p := t.peers.PopMax()
1552 opts := outgoingConnOpts{
1555 requireRendezvous: false,
1556 skipHolepunchRendezvous: false,
1557 receivedHolepunchConnect: false,
1558 HeaderObfuscationPolicy: t.cl.config.HeaderObfuscationPolicy,
1560 initiateConn(opts, false)
1566 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1568 uncached := t.pieceCompleteUncached(piece)
1569 cached := p.completion()
1570 changed := cached != uncached
1571 complete := uncached.Complete
1572 p.storageCompletionOk = uncached.Ok
1575 t._completedPieces.Add(x)
1578 t._completedPieces.Remove(x)
1580 p.t.updatePieceRequestOrderPiece(piece)
1582 if complete && len(p.dirtiers) != 0 {
1583 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1587 // "piece completion changed",
1588 // slog.Int("piece", piece),
1589 // slog.Any("from", cached),
1590 // slog.Any("to", uncached))
1591 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1596 // Non-blocking read. Client lock is not required.
1597 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1599 p := &t.pieces[off/t.info.PieceLength]
1600 p.waitNoPendingWrites()
1602 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1613 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1614 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1615 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1616 func (t *Torrent) maybeCompleteMetadata() error {
1621 if !t.haveAllMetadataPieces() {
1622 // Don't have enough metadata pieces.
1625 err := t.setInfoBytesLocked(t.metadataBytes)
1627 t.invalidateMetadata()
1628 return fmt.Errorf("error setting info bytes: %s", err)
1630 if t.cl.config.Debug {
1631 t.logger.Printf("%s: got metadata from peers", t)
1636 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1637 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1639 now.Add(bitmap.BitIndex(begin))
1640 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1647 func (t *Torrent) needData() bool {
1648 if t.closed.IsSet() {
1654 return !t._pendingPieces.IsEmpty()
1657 func appendMissingStrings(old, new []string) (ret []string) {
1660 for _, n := range new {
1661 for _, o := range old {
1666 ret = append(ret, n)
1671 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1673 for minNumTiers > len(ret) {
1674 ret = append(ret, nil)
1679 func (t *Torrent) addTrackers(announceList [][]string) {
1680 fullAnnounceList := &t.metainfo.AnnounceList
1681 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1682 for tierIndex, trackerURLs := range announceList {
1683 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1685 t.startMissingTrackerScrapers()
1686 t.updateWantPeersEvent()
1689 // Don't call this before the info is available.
1690 func (t *Torrent) bytesCompleted() int64 {
1694 return t.length() - t.bytesLeft()
1697 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1700 return t.setInfoBytesLocked(b)
1703 // Returns true if connection is removed from torrent.Conns.
1704 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1705 if !c.closed.IsSet() {
1706 panic("connection is not closed")
1707 // There are behaviours prevented by the closed state that will fail
1708 // if the connection has been deleted.
1712 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1713 // the drop event against the PexConnState instead.
1715 if !t.cl.config.DisablePEX {
1719 torrent.Add("deleted connections", 1)
1720 c.deleteAllRequests("Torrent.deletePeerConn")
1721 t.assertPendingRequests()
1722 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1723 panic(t.connsWithAllPieces)
1728 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1729 if t.deleteConnWithAllPieces(p) {
1735 p.peerPieces().Iterate(func(i uint32) bool {
1736 p.t.decPieceAvailability(pieceIndex(i))
1741 func (t *Torrent) assertPendingRequests() {
1745 // var actual pendingRequests
1746 // if t.haveInfo() {
1747 // actual.m = make([]int, t.numChunks())
1749 // t.iterPeers(func(p *Peer) {
1750 // p.requestState.Requests.Iterate(func(x uint32) bool {
1755 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1761 func (t *Torrent) dropConnection(c *PeerConn) {
1762 t.cl.event.Broadcast()
1764 if t.deletePeerConn(c) {
1769 // Peers as in contact information for dialing out.
1770 func (t *Torrent) wantPeers() bool {
1771 if t.closed.IsSet() {
1774 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1777 return t.wantOutgoingConns()
1780 func (t *Torrent) updateWantPeersEvent() {
1782 t.wantPeersEvent.Set()
1784 t.wantPeersEvent.Clear()
1788 // Returns whether the client should make effort to seed the torrent.
1789 func (t *Torrent) seeding() bool {
1791 if t.closed.IsSet() {
1794 if t.dataUploadDisallowed {
1797 if cl.config.NoUpload {
1800 if !cl.config.Seed {
1803 if cl.config.DisableAggressiveUpload && t.needData() {
1809 func (t *Torrent) onWebRtcConn(
1810 c datachannel.ReadWriteCloser,
1811 dcc webtorrent.DataChannelContext,
1814 netConn := webrtcNetConn{
1816 DataChannelContext: dcc,
1818 peerRemoteAddr := netConn.RemoteAddr()
1819 //t.logger.Levelf(log.Critical, "onWebRtcConn remote addr: %v", peerRemoteAddr)
1820 if t.cl.badPeerAddr(peerRemoteAddr) {
1823 localAddrIpPort := missinggo.IpPortFromNetAddr(netConn.LocalAddr())
1824 pc, err := t.cl.initiateProtocolHandshakes(
1825 context.Background(),
1830 outgoing: dcc.LocalOffered,
1831 remoteAddr: peerRemoteAddr,
1832 localPublicAddr: localAddrIpPort,
1833 network: webrtcNetwork,
1834 connString: fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1838 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1841 if dcc.LocalOffered {
1842 pc.Discovery = PeerSourceTracker
1844 pc.Discovery = PeerSourceIncoming
1846 pc.conn.SetWriteDeadline(time.Time{})
1849 err = t.runHandshookConn(pc)
1851 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1855 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1856 err := t.runHandshookConn(pc)
1857 if err != nil || logAll {
1858 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1862 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1863 t.logRunHandshookConn(pc, false, log.Debug)
1866 func (t *Torrent) startWebsocketAnnouncer(u url.URL, shortInfohash [20]byte) torrentTrackerAnnouncer {
1867 wtc, release := t.cl.websocketTrackers.Get(u.String(), shortInfohash)
1868 // This needs to run before the Torrent is dropped from the Client, to prevent a new
1869 // webtorrent.TrackerClient for the same info hash before the old one is cleaned up.
1870 t.onClose = append(t.onClose, release)
1871 wst := websocketTrackerStatus{u, wtc}
1873 err := wtc.Announce(tracker.Started, shortInfohash)
1875 t.logger.WithDefaultLevel(log.Warning).Printf(
1876 "error in initial announce to %q: %v",
1884 func (t *Torrent) startScrapingTracker(_url string) {
1888 u, err := url.Parse(_url)
1890 // URLs with a leading '*' appear to be a uTorrent convention to disable trackers.
1892 t.logger.Levelf(log.Warning, "error parsing tracker url: %v", err)
1896 if u.Scheme == "udp" {
1898 t.startScrapingTracker(u.String())
1900 t.startScrapingTracker(u.String())
1904 t.startScrapingTrackerWithInfohash(u, _url, t.infoHash.Value)
1906 if t.infoHashV2.Ok {
1907 t.startScrapingTrackerWithInfohash(u, _url, *t.infoHashV2.Value.ToShort())
1911 func (t *Torrent) startScrapingTrackerWithInfohash(u *url.URL, urlStr string, shortInfohash [20]byte) {
1912 announcerKey := torrentTrackerAnnouncerKey{
1913 shortInfohash: shortInfohash,
1916 if _, ok := t.trackerAnnouncers[announcerKey]; ok {
1919 sl := func() torrentTrackerAnnouncer {
1922 if t.cl.config.DisableWebtorrent {
1925 return t.startWebsocketAnnouncer(*u, shortInfohash)
1927 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1931 if t.cl.config.DisableIPv6 {
1935 newAnnouncer := &trackerScraper{
1936 shortInfohash: shortInfohash,
1939 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1941 go newAnnouncer.Run()
1947 g.MakeMapIfNil(&t.trackerAnnouncers)
1948 if g.MapInsert(t.trackerAnnouncers, announcerKey, sl).Ok {
1949 panic("tracker announcer already exists")
1953 // Adds and starts tracker scrapers for tracker URLs that aren't already
1955 func (t *Torrent) startMissingTrackerScrapers() {
1956 if t.cl.config.DisableTrackers {
1959 t.startScrapingTracker(t.metainfo.Announce)
1960 for _, tier := range t.metainfo.AnnounceList {
1961 for _, url := range tier {
1962 t.startScrapingTracker(url)
1967 // Returns an AnnounceRequest with fields filled out to defaults and current
1969 func (t *Torrent) announceRequest(
1970 event tracker.AnnounceEvent,
1971 shortInfohash [20]byte,
1972 ) tracker.AnnounceRequest {
1973 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1974 // dependent on the network in use.
1975 return tracker.AnnounceRequest{
1977 NumWant: func() int32 {
1978 if t.wantPeers() && len(t.cl.dialers) > 0 {
1979 // Windozer has UDP packet limit. See:
1980 // https://github.com/anacrolix/torrent/issues/764
1986 Port: uint16(t.cl.incomingPeerPort()),
1987 PeerId: t.cl.peerID,
1988 InfoHash: shortInfohash,
1989 Key: t.cl.announceKey(),
1991 // The following are vaguely described in BEP 3.
1993 Left: t.bytesLeftAnnounce(),
1994 Uploaded: t.stats.BytesWrittenData.Int64(),
1995 // There's no mention of wasted or unwanted download in the BEP.
1996 Downloaded: t.stats.BytesReadUsefulData.Int64(),
2000 // Adds peers revealed in an announce until the announce ends, or we have
2002 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
2004 for v := range pvs {
2007 for _, cp := range v.Peers {
2009 // Can't do anything with this.
2012 if t.addPeer(PeerInfo{
2013 Addr: ipPortAddr{cp.IP, cp.Port},
2014 Source: PeerSourceDhtGetPeers,
2021 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
2026 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
2027 // announce ends. stop will force the announce to end. This interface is really old-school, and
2028 // calls a private one that is much more modern. Both v1 and v2 info hashes are announced if they
2030 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
2033 t.eachShortInfohash(func(short [20]byte) {
2034 ihs = append(ihs, short)
2037 ctx, stop := context.WithCancel(context.Background())
2038 eg, ctx := errgroup.WithContext(ctx)
2039 for _, ih := range ihs {
2041 ann, err = s.Announce(ih, t.cl.incomingPeerPort(), true)
2046 eg.Go(func() error {
2047 return t.dhtAnnounceConsumer(ctx, ann)
2050 _done := make(chan struct{})
2060 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
2061 // announce ends. stop will force the announce to end.
2062 func (t *Torrent) dhtAnnounceConsumer(
2063 ctx context.Context,
2069 done := make(chan struct{})
2072 t.consumeDhtAnnouncePeers(ps.Peers())
2076 return context.Cause(ctx)
2082 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
2083 _, stop, err := t.AnnounceToDht(s)
2088 case <-t.closed.Done():
2089 case <-time.After(5 * time.Minute):
2095 func (t *Torrent) dhtAnnouncer(s DhtServer) {
2101 if t.closed.IsSet() {
2104 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
2105 // TODO: We can include the announce_peer step depending on whether we can receive
2106 // inbound connections. We should probably only announce once every 15 mins too.
2107 if !t.wantAnyConns() {
2110 // TODO: Determine if there's a listener on the port we're announcing.
2111 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
2122 err := t.timeboxedAnnounceToDht(s)
2124 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
2130 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
2131 for _, p := range peers {
2139 // The returned TorrentStats may require alignment in memory. See
2140 // https://github.com/anacrolix/torrent/issues/383.
2141 func (t *Torrent) Stats() TorrentStats {
2143 defer t.cl.rUnlock()
2144 return t.statsLocked()
2147 func (t *Torrent) statsLocked() (ret TorrentStats) {
2148 ret.ActivePeers = len(t.conns)
2149 ret.HalfOpenPeers = len(t.halfOpen)
2150 ret.PendingPeers = t.peers.Len()
2151 ret.TotalPeers = t.numTotalPeers()
2152 ret.ConnectedSeeders = 0
2153 for c := range t.conns {
2154 if all, ok := c.peerHasAllPieces(); all && ok {
2155 ret.ConnectedSeeders++
2158 ret.ConnStats = t.stats.Copy()
2159 ret.PiecesComplete = t.numPiecesCompleted()
2163 // The total number of peers in the torrent.
2164 func (t *Torrent) numTotalPeers() int {
2165 peers := make(map[string]struct{})
2166 for conn := range t.conns {
2167 ra := conn.conn.RemoteAddr()
2169 // It's been closed and doesn't support RemoteAddr.
2172 peers[ra.String()] = struct{}{}
2174 for addr := range t.halfOpen {
2175 peers[addr] = struct{}{}
2177 t.peers.Each(func(peer PeerInfo) {
2178 peers[peer.Addr.String()] = struct{}{}
2183 // Reconcile bytes transferred before connection was associated with a
2185 func (t *Torrent) reconcileHandshakeStats(c *Peer) {
2186 if c._stats != (ConnStats{
2187 // Handshakes should only increment these fields:
2188 BytesWritten: c._stats.BytesWritten,
2189 BytesRead: c._stats.BytesRead,
2193 c.postHandshakeStats(func(cs *ConnStats) {
2194 cs.BytesRead.Add(c._stats.BytesRead.Int64())
2195 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
2197 c.reconciledHandshakeStats = true
2200 // Returns true if the connection is added.
2201 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
2204 torrent.Add("added connections", 1)
2207 if t.closed.IsSet() {
2208 return errors.New("torrent closed")
2210 for c0 := range t.conns {
2211 if c.PeerID != c0.PeerID {
2214 if !t.cl.config.DropDuplicatePeerIds {
2217 if c.hasPreferredNetworkOver(c0) {
2219 t.deletePeerConn(c0)
2221 return errors.New("existing connection preferred")
2224 if len(t.conns) >= t.maxEstablishedConns {
2225 numOutgoing := t.numOutgoingConns()
2226 numIncoming := len(t.conns) - numOutgoing
2227 c := t.worstBadConn(worseConnLensOpts{
2228 // We've already established that we have too many connections at this point, so we just
2229 // need to match what kind we have too many of vs. what we're trying to add now.
2230 incomingIsBad: (numIncoming-numOutgoing > 1) && c.outgoing,
2231 outgoingIsBad: (numOutgoing-numIncoming > 1) && !c.outgoing,
2234 return errors.New("don't want conn")
2239 if len(t.conns) >= t.maxEstablishedConns {
2242 t.conns[c] = struct{}{}
2243 t.cl.event.Broadcast()
2244 // We'll never receive the "p" extended handshake parameter.
2245 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
2251 func (t *Torrent) newConnsAllowed() bool {
2252 if !t.networkingEnabled.Bool() {
2255 if t.closed.IsSet() {
2258 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2264 func (t *Torrent) wantAnyConns() bool {
2265 if !t.networkingEnabled.Bool() {
2268 if t.closed.IsSet() {
2271 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2274 return len(t.conns) < t.maxEstablishedConns
2277 func (t *Torrent) wantOutgoingConns() bool {
2278 if !t.newConnsAllowed() {
2281 if len(t.conns) < t.maxEstablishedConns {
2284 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2285 return t.worstBadConn(worseConnLensOpts{
2286 incomingIsBad: numIncomingConns-t.numOutgoingConns() > 1,
2287 outgoingIsBad: false,
2291 func (t *Torrent) wantIncomingConns() bool {
2292 if !t.newConnsAllowed() {
2295 if len(t.conns) < t.maxEstablishedConns {
2298 numIncomingConns := len(t.conns) - t.numOutgoingConns()
2299 return t.worstBadConn(worseConnLensOpts{
2300 incomingIsBad: false,
2301 outgoingIsBad: t.numOutgoingConns()-numIncomingConns > 1,
2305 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
2308 oldMax = t.maxEstablishedConns
2309 t.maxEstablishedConns = max
2310 wcs := worseConnSlice{
2311 conns: t.appendConns(nil, func(*PeerConn) bool {
2315 wcs.initKeys(worseConnLensOpts{})
2317 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
2318 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
2324 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
2325 t.logger.LazyLog(log.Debug, func() log.Msg {
2326 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
2330 t.cl.event.Broadcast()
2331 if t.closed.IsSet() {
2335 // Don't score the first time a piece is hashed, it could be an initial check.
2336 if p.storageCompletionOk {
2338 pieceHashedCorrect.Add(1)
2341 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
2342 ).AddValues(t, p).LogLevel(log.Info, t.logger)
2343 pieceHashedNotCorrect.Add(1)
2348 t.publishPieceStateChange(piece)
2351 t.publishPieceStateChange(piece)
2355 if len(p.dirtiers) != 0 {
2356 // Don't increment stats above connection-level for every involved connection.
2357 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2359 for c := range p.dirtiers {
2360 c._stats.incrementPiecesDirtiedGood()
2362 t.clearPieceTouchers(piece)
2363 hasDirty := p.hasDirtyChunks()
2366 p.Flush() // You can be synchronous here!
2368 err := p.Storage().MarkComplete()
2370 t.logger.Levelf(log.Warning, "%T: error marking piece complete %d: %s", t.storage, piece, err)
2374 if t.closed.IsSet() {
2377 t.pendAllChunkSpecs(piece)
2379 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2380 // Peers contributed to all the data for this piece hash failure, and the failure was
2381 // not due to errors in the storage (such as data being dropped in a cache).
2383 // Increment Torrent and above stats, and then specific connections.
2384 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2385 for c := range p.dirtiers {
2386 // Y u do dis peer?!
2387 c.stats().incrementPiecesDirtiedBad()
2390 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2391 for c := range p.dirtiers {
2393 bannableTouchers = append(bannableTouchers, c)
2396 t.clearPieceTouchers(piece)
2397 slices.Sort(bannableTouchers, connLessTrusted)
2399 if t.cl.config.Debug {
2401 "bannable conns by trust for piece %d: %v",
2403 func() (ret []connectionTrust) {
2404 for _, c := range bannableTouchers {
2405 ret = append(ret, c.trust())
2412 if len(bannableTouchers) >= 1 {
2413 c := bannableTouchers[0]
2414 if len(bannableTouchers) != 1 {
2415 t.logger.Levelf(log.Debug, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2417 // Turns out it's still useful to ban peers like this because if there's only a
2418 // single peer for a piece, and we never progress that piece to completion, we
2419 // will never smart-ban them. Discovered in
2420 // https://github.com/anacrolix/torrent/issues/715.
2421 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2426 t.onIncompletePiece(piece)
2427 p.Storage().MarkNotComplete()
2429 t.updatePieceCompletion(piece)
2432 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2433 start := t.pieceRequestIndexOffset(piece)
2434 end := start + t.pieceNumChunks(piece)
2435 for ri := start; ri < end; ri++ {
2440 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2441 t.pendAllChunkSpecs(piece)
2442 t.cancelRequestsForPiece(piece)
2443 t.piece(piece).readerCond.Broadcast()
2444 for conn := range t.conns {
2446 t.maybeDropMutuallyCompletePeer(conn)
2450 // Called when a piece is found to be not complete.
2451 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2452 if t.pieceAllDirty(piece) {
2453 t.pendAllChunkSpecs(piece)
2455 if !t.wantPieceIndex(piece) {
2456 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2459 // We could drop any connections that we told we have a piece that we
2460 // don't here. But there's a test failure, and it seems clients don't care
2461 // if you request pieces that you already claim to have. Pruning bad
2462 // connections might just remove any connections that aren't treating us
2463 // favourably anyway.
2465 // for c := range t.conns {
2466 // if c.sentHave(piece) {
2470 t.iterPeers(func(conn *Peer) {
2471 if conn.peerHasPiece(piece) {
2472 conn.updateRequests("piece incomplete")
2477 func (t *Torrent) tryCreateMorePieceHashers() {
2478 for !t.closed.IsSet() && t.activePieceHashes < t.cl.config.PieceHashersPerTorrent && t.tryCreatePieceHasher() {
2482 func (t *Torrent) tryCreatePieceHasher() bool {
2483 if t.storage == nil {
2486 pi, ok := t.getPieceToHash()
2491 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2493 t.publishPieceStateChange(pi)
2494 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2495 t.storageLock.RLock()
2496 t.activePieceHashes++
2497 go t.pieceHasher(pi)
2501 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2502 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2503 if t.piece(i).hashing {
2513 func (t *Torrent) dropBannedPeers() {
2514 t.iterPeers(func(p *Peer) {
2515 remoteIp := p.remoteIp()
2516 if remoteIp == nil {
2517 if p.bannableAddr.Ok {
2518 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2522 netipAddr := netip.MustParseAddr(remoteIp.String())
2523 if Some(netipAddr) != p.bannableAddr {
2524 t.logger.WithDefaultLevel(log.Debug).Printf(
2525 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2526 p, remoteIp, p.bannableAddr)
2528 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2529 // Should this be a close?
2531 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2536 func (t *Torrent) pieceHasher(index pieceIndex) {
2538 // Do we really need to spell out that it's a copy error? If it's a failure to hash the hash
2539 // will just be wrong.
2540 correct, failedPeers, copyErr := t.hashPiece(index)
2546 "error hashing piece %v: %v", index, copyErr)
2548 t.storageLock.RUnlock()
2552 for peer := range failedPeers {
2553 t.cl.banPeerIP(peer.AsSlice())
2554 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2557 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2558 t.smartBanCache.ForgetBlock(ri)
2562 t.pieceHashed(index, correct, copyErr)
2563 t.updatePiecePriority(index, "Torrent.pieceHasher")
2564 t.activePieceHashes--
2565 t.tryCreateMorePieceHashers()
2568 // Return the connections that touched a piece, and clear the entries while doing it.
2569 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2571 for c := range p.dirtiers {
2572 delete(c.peerTouchedPieces, pi)
2573 delete(p.dirtiers, c)
2577 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2578 t.iterPeers(func(p *Peer) {
2579 ret = append(ret, p)
2584 func (t *Torrent) queueInitialPieceCheck(i pieceIndex) {
2585 if !t.initialPieceCheckDisabled && !t.piece(i).storageCompletionOk {
2586 t.queuePieceCheck(i)
2590 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2591 piece := t.piece(pieceIndex)
2592 if piece.hash == nil && !piece.hashV2.Ok {
2595 if piece.queuedForHash() {
2598 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2599 t.publishPieceStateChange(pieceIndex)
2600 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2601 t.tryCreateMorePieceHashers()
2604 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2605 // before the Info is available.
2606 func (t *Torrent) VerifyData() {
2607 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2608 t.Piece(i).VerifyData()
2612 func (t *Torrent) connectingToPeerAddr(addrStr string) bool {
2613 return len(t.halfOpen[addrStr]) != 0
2616 func (t *Torrent) hasPeerConnForAddr(x PeerRemoteAddr) bool {
2617 addrStr := x.String()
2618 for c := range t.conns {
2620 if ra.String() == addrStr {
2627 func (t *Torrent) getHalfOpenPath(
2629 attemptKey outgoingConnAttemptKey,
2630 ) nestedmaps.Path[*PeerInfo] {
2631 return nestedmaps.Next(nestedmaps.Next(nestedmaps.Begin(&t.halfOpen), addrStr), attemptKey)
2634 func (t *Torrent) addHalfOpen(addrStr string, attemptKey *PeerInfo) {
2635 path := t.getHalfOpenPath(addrStr, attemptKey)
2637 panic("should be unique")
2639 path.Set(attemptKey)
2643 // Start the process of connecting to the given peer for the given torrent if appropriate. I'm not
2644 // sure all the PeerInfo fields are being used.
2646 opts outgoingConnOpts,
2650 peer := opts.peerInfo
2651 if peer.Id == t.cl.peerID {
2654 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2658 addrStr := addr.String()
2660 if t.connectingToPeerAddr(addrStr) {
2664 if t.hasPeerConnForAddr(addr) {
2668 t.addHalfOpen(addrStr, attemptKey)
2669 go t.cl.outgoingConnection(
2675 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2676 // quickly make one Client visible to the Torrent of another Client.
2677 func (t *Torrent) AddClientPeer(cl *Client) int {
2678 return t.AddPeers(func() (ps []PeerInfo) {
2679 for _, la := range cl.ListenAddrs() {
2680 ps = append(ps, PeerInfo{
2689 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2691 func (t *Torrent) allStats(f func(*ConnStats)) {
2696 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2697 return t.pieces[i].hashing
2700 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2701 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2704 func (t *Torrent) dialTimeout() time.Duration {
2705 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2708 func (t *Torrent) piece(i int) *Piece {
2712 func (t *Torrent) onWriteChunkErr(err error) {
2713 if t.userOnWriteChunkErr != nil {
2714 go t.userOnWriteChunkErr(err)
2717 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2718 t.disallowDataDownloadLocked()
2721 func (t *Torrent) DisallowDataDownload() {
2724 t.disallowDataDownloadLocked()
2727 func (t *Torrent) disallowDataDownloadLocked() {
2728 t.dataDownloadDisallowed.Set()
2729 t.iterPeers(func(p *Peer) {
2730 // Could check if peer request state is empty/not interested?
2731 p.updateRequests("disallow data download")
2732 p.cancelAllRequests()
2736 func (t *Torrent) AllowDataDownload() {
2739 t.dataDownloadDisallowed.Clear()
2740 t.iterPeers(func(p *Peer) {
2741 p.updateRequests("allow data download")
2745 // Enables uploading data, if it was disabled.
2746 func (t *Torrent) AllowDataUpload() {
2749 t.dataUploadDisallowed = false
2750 t.iterPeers(func(p *Peer) {
2751 p.updateRequests("allow data upload")
2755 // Disables uploading data, if it was enabled.
2756 func (t *Torrent) DisallowDataUpload() {
2759 t.dataUploadDisallowed = true
2760 for c := range t.conns {
2761 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2762 c.updateRequests("disallow data upload")
2766 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2767 // or if nil, a critical message is logged, and data download is disabled.
2768 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2771 t.userOnWriteChunkErr = f
2774 func (t *Torrent) iterPeers(f func(p *Peer)) {
2775 for pc := range t.conns {
2778 for _, ws := range t.webSeeds {
2783 func (t *Torrent) callbacks() *Callbacks {
2784 return &t.cl.config.Callbacks
2787 type AddWebSeedsOpt func(*webseed.Client)
2789 // Sets the WebSeed trailing path escaper for a webseed.Client.
2790 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2791 return func(c *webseed.Client) {
2792 c.PathEscaper = custom
2796 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2799 for _, u := range urls {
2800 t.addWebSeed(u, opts...)
2804 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2805 if t.cl.config.DisableWebseeds {
2808 if _, ok := t.webSeeds[url]; ok {
2811 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2812 // right away. This value should be some multiple of the number of connections to a host. I
2813 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2814 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2815 // "https://webtorrent.io/torrents/".
2816 const maxRequests = 16
2822 reconciledHandshakeStats: true,
2823 // This should affect how often we have to recompute requests for this peer. Note that
2824 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2825 // requests mark more often, so recomputation is probably sooner than with regular peer
2826 // conns. ~4x maxRequests would be about right.
2827 PeerMaxRequests: 128,
2828 // TODO: Set ban prefix?
2829 RemoteAddr: remoteAddrFromUrl(url),
2830 callbacks: t.callbacks(),
2832 client: webseed.Client{
2833 HttpClient: t.cl.httpClient,
2835 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2836 return &rateLimitedReader{
2837 l: t.cl.config.DownloadRateLimiter,
2842 activeRequests: make(map[Request]webseed.Request, maxRequests),
2844 ws.peer.initRequestState()
2845 for _, opt := range opts {
2848 ws.peer.initUpdateRequestsTimer()
2849 ws.requesterCond.L = t.cl.locker()
2850 for i := 0; i < maxRequests; i += 1 {
2853 for _, f := range t.callbacks().NewPeer {
2856 ws.peer.logger = t.logger.WithContextValue(&ws)
2857 ws.peer.peerImpl = &ws
2859 ws.onGotInfo(t.info)
2861 t.webSeeds[url] = &ws.peer
2864 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2865 t.iterPeers(func(p1 *Peer) {
2873 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2874 index := t.pieceIndexOfRequestIndex(ri)
2877 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2881 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2882 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2885 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2886 return RequestIndex(piece) * t.chunksPerRegularPiece()
2889 func (t *Torrent) updateComplete() {
2890 t.Complete.SetBool(t.haveAllPieces())
2893 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2894 p := t.requestingPeer(r)
2898 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2899 //delete(t.pendingRequests, r)
2900 if _, ok := t.requestState[r]; ok {
2901 panic("expected request state to be gone")
2906 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2907 return t.requestState[r].peer
2910 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2911 if t.connsWithAllPieces == nil {
2912 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2914 t.connsWithAllPieces[p] = struct{}{}
2917 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2918 _, ok := t.connsWithAllPieces[p]
2919 delete(t.connsWithAllPieces, p)
2923 func (t *Torrent) numActivePeers() int {
2924 return len(t.conns) + len(t.webSeeds)
2927 func (t *Torrent) hasStorageCap() bool {
2928 f := t.storage.Capacity
2936 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2937 return pieceIndex(ri / t.chunksPerRegularPiece())
2940 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2941 reuseIter *typedRoaring.Iterator[RequestIndex],
2943 f func(RequestIndex),
2945 reuseIter.Initialize(&t.dirtyChunks)
2946 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2947 iterBitmapUnsetInRange(
2949 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2954 type requestState struct {
2959 // Returns an error if a received chunk is out of bounds in someway.
2960 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2962 return errors.New("torrent missing info")
2964 if int(r.Index) >= t.numPieces() {
2965 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2967 pieceLength := t.pieceLength(pieceIndex(r.Index))
2968 if r.Begin >= pieceLength {
2969 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2971 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2972 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2973 // should be considerable checks elsewhere for this case due to the network overhead. We should
2974 // catch most of the overflow manipulation stuff by checking index and begin above.
2978 func (t *Torrent) peerConnsWithDialAddrPort(target netip.AddrPort) (ret []*PeerConn) {
2979 for pc := range t.conns {
2980 dialAddr, err := pc.remoteDialAddrPort()
2984 if dialAddr != target {
2987 ret = append(ret, pc)
2992 func wrapUtHolepunchMsgForPeerConn(
2993 recipient *PeerConn,
2994 msg utHolepunch.Msg,
2996 extendedPayload, err := msg.MarshalBinary()
3002 ExtendedID: MapMustGet(recipient.PeerExtensionIDs, utHolepunch.ExtensionName),
3003 ExtendedPayload: extendedPayload,
3007 func sendUtHolepunchMsg(
3009 msgType utHolepunch.MsgType,
3010 addrPort netip.AddrPort,
3011 errCode utHolepunch.ErrCode,
3013 holepunchMsg := utHolepunch.Msg{
3018 incHolepunchMessagesSent(holepunchMsg)
3019 ppMsg := wrapUtHolepunchMsgForPeerConn(pc, holepunchMsg)
3023 func incHolepunchMessages(msg utHolepunch.Msg, verb string) {
3026 "holepunch %v %v messages %v",
3028 addrPortProtocolStr(msg.AddrPort),
3035 func incHolepunchMessagesReceived(msg utHolepunch.Msg) {
3036 incHolepunchMessages(msg, "received")
3039 func incHolepunchMessagesSent(msg utHolepunch.Msg) {
3040 incHolepunchMessages(msg, "sent")
3043 func (t *Torrent) handleReceivedUtHolepunchMsg(msg utHolepunch.Msg, sender *PeerConn) error {
3044 incHolepunchMessagesReceived(msg)
3045 switch msg.MsgType {
3046 case utHolepunch.Rendezvous:
3047 t.logger.Printf("got holepunch rendezvous request for %v from %p", msg.AddrPort, sender)
3048 sendMsg := sendUtHolepunchMsg
3049 senderAddrPort, err := sender.remoteDialAddrPort()
3051 sender.logger.Levelf(
3053 "error getting ut_holepunch rendezvous sender's dial address: %v",
3056 // There's no better error code. The sender's address itself is invalid. I don't see
3057 // this error message being appropriate anywhere else anyway.
3058 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSuchPeer)
3060 targets := t.peerConnsWithDialAddrPort(msg.AddrPort)
3061 if len(targets) == 0 {
3062 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NotConnected)
3065 for _, pc := range targets {
3066 if !pc.supportsExtension(utHolepunch.ExtensionName) {
3067 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSupport)
3070 sendMsg(sender, utHolepunch.Connect, msg.AddrPort, 0)
3071 sendMsg(pc, utHolepunch.Connect, senderAddrPort, 0)
3074 case utHolepunch.Connect:
3075 holepunchAddr := msg.AddrPort
3076 t.logger.Printf("got holepunch connect request for %v from %p", holepunchAddr, sender)
3077 if g.MapContains(t.cl.undialableWithoutHolepunch, holepunchAddr) {
3078 setAdd(&t.cl.undialableWithoutHolepunchDialedAfterHolepunchConnect, holepunchAddr)
3079 if g.MapContains(t.cl.accepted, holepunchAddr) {
3080 setAdd(&t.cl.probablyOnlyConnectedDueToHolepunch, holepunchAddr)
3083 opts := outgoingConnOpts{
3086 Source: PeerSourceUtHolepunch,
3087 PexPeerFlags: sender.pex.remoteLiveConns[msg.AddrPort].UnwrapOrZeroValue(),
3090 // Don't attempt to start our own rendezvous if we fail to connect.
3091 skipHolepunchRendezvous: true,
3092 receivedHolepunchConnect: true,
3093 // Assume that the other end initiated the rendezvous, and will use our preferred
3094 // encryption. So we will act normally.
3095 HeaderObfuscationPolicy: t.cl.config.HeaderObfuscationPolicy,
3097 initiateConn(opts, true)
3099 case utHolepunch.Error:
3100 torrent.Add("holepunch error messages received", 1)
3101 t.logger.Levelf(log.Debug, "received ut_holepunch error message from %v: %v", sender, msg.ErrCode)
3104 return fmt.Errorf("unhandled msg type %v", msg.MsgType)
3108 func addrPortProtocolStr(addrPort netip.AddrPort) string {
3109 addr := addrPort.Addr()
3120 func (t *Torrent) trySendHolepunchRendezvous(addrPort netip.AddrPort) error {
3122 for pc := range t.conns {
3123 if !pc.supportsExtension(utHolepunch.ExtensionName) {
3126 if pc.supportsExtension(pp.ExtensionNamePex) {
3127 if !g.MapContains(pc.pex.remoteLiveConns, addrPort) {
3131 t.logger.Levelf(log.Debug, "sent ut_holepunch rendezvous message to %v for %v", pc, addrPort)
3132 sendUtHolepunchMsg(pc, utHolepunch.Rendezvous, addrPort, 0)
3136 return errors.New("no eligible relays")
3141 func (t *Torrent) numHalfOpenAttempts() (num int) {
3142 for _, attempts := range t.halfOpen {
3143 num += len(attempts)
3148 func (t *Torrent) getDialTimeoutUnlocked() time.Duration {
3152 return t.dialTimeout()
3155 func (t *Torrent) canonicalShortInfohash() *infohash.T {
3157 return &t.infoHash.Value
3159 return t.infoHashV2.UnwrapPtr().ToShort()
3162 func (t *Torrent) eachShortInfohash(each func(short [20]byte)) {
3163 if t.infoHash.Value == *t.infoHashV2.Value.ToShort() {
3164 // This includes zero values, since they both should not be zero. Plus Option should not
3165 // allow non-zero values for None.
3166 panic("v1 and v2 info hashes should not be the same")
3169 each(t.infoHash.Value)
3171 if t.infoHashV2.Ok {
3172 v2Short := *t.infoHashV2.Value.ToShort()
3177 func (t *Torrent) getFileByPiecesRoot(hash [32]byte) *File {
3178 for _, f := range *t.files {
3179 if f.piecesRoot.Unwrap() == hash {
3186 func (t *Torrent) pieceLayers() (pieceLayers map[string]string) {
3191 g.MakeMapWithCap(&pieceLayers, len(files))
3193 for _, f := range files {
3194 if !f.piecesRoot.Ok {
3197 key := f.piecesRoot.Value
3198 var value strings.Builder
3199 for i := f.BeginPieceIndex(); i < f.EndPieceIndex(); i++ {
3200 hashOpt := t.piece(i).hashV2
3202 // All hashes must be present. This implementation should handle missing files, so move on to the next file.
3205 value.Write(hashOpt.Value[:])
3207 if value.Len() == 0 {
3208 // Non-empty files are not recorded in piece layers.
3211 // If multiple files have the same root that shouldn't matter.
3212 pieceLayers[string(key[:])] = value.String()