19 "github.com/RoaringBitmap/roaring"
20 "github.com/anacrolix/chansync"
21 "github.com/anacrolix/chansync/events"
22 "github.com/anacrolix/dht/v2"
23 . "github.com/anacrolix/generics"
24 "github.com/anacrolix/log"
25 "github.com/anacrolix/missinggo/perf"
26 "github.com/anacrolix/missinggo/slices"
27 "github.com/anacrolix/missinggo/v2"
28 "github.com/anacrolix/missinggo/v2/bitmap"
29 "github.com/anacrolix/missinggo/v2/pubsub"
30 "github.com/anacrolix/multiless"
31 "github.com/anacrolix/sync"
32 "github.com/davecgh/go-spew/spew"
34 "github.com/anacrolix/torrent/bencode"
35 "github.com/anacrolix/torrent/common"
36 "github.com/anacrolix/torrent/metainfo"
37 pp "github.com/anacrolix/torrent/peer_protocol"
38 request_strategy "github.com/anacrolix/torrent/request-strategy"
39 "github.com/anacrolix/torrent/segments"
40 "github.com/anacrolix/torrent/storage"
41 "github.com/anacrolix/torrent/tracker"
42 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
43 "github.com/anacrolix/torrent/webseed"
46 // Maintains state of torrent within a Client. Many methods should not be called before the info is
47 // available, see .Info and .GotInfo.
49 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
50 // alignment. See #262.
55 networkingEnabled chansync.Flag
56 dataDownloadDisallowed chansync.Flag
57 dataUploadDisallowed bool
58 userOnWriteChunkErr func(error)
60 closed chansync.SetOnce
62 infoHash metainfo.Hash
65 // The order pieces are requested if there's no stronger reason like availability or priority.
66 pieceRequestOrder []int
67 // Values are the piece indices that changed.
68 pieceStateChanges pubsub.PubSub[PieceStateChange]
69 // The size of chunks to request from peers over the wire. This is
70 // normally 16KiB by convention these days.
73 // Total length of the torrent in bytes. Stored because it's not O(1) to
74 // get this from the info dict.
77 // The storage to open when the info dict becomes available.
78 storageOpener *storage.Client
79 // Storage for torrent data.
80 storage *storage.Torrent
81 // Read-locked for using storage, and write-locked for Closing.
82 storageLock sync.RWMutex
84 // TODO: Only announce stuff is used?
85 metainfo metainfo.MetaInfo
87 // The info dict. nil if we don't have it (yet).
89 fileIndex segments.Index
92 _chunksPerRegularPiece chunkIndexType
94 webSeeds map[string]*Peer
95 // Active peer connections, running message stream loops. TODO: Make this
96 // open (not-closed) connections only.
97 conns map[*PeerConn]struct{}
98 maxEstablishedConns int
99 // Set of addrs to which we're attempting to connect. Connections are
100 // half-open until all handshakes are completed.
101 halfOpen map[string]PeerInfo
103 // Reserve of peers to connect to. A peer can be both here and in the
104 // active connections if were told about the peer after connecting with
105 // them. That encourages us to reconnect to peers that are well known in
107 peers prioritizedPeers
108 // Whether we want to know to know more peers.
109 wantPeersEvent missinggo.Event
110 // An announcer for each tracker URL.
111 trackerAnnouncers map[string]torrentTrackerAnnouncer
112 // How many times we've initiated a DHT announce. TODO: Move into stats.
115 // Name used if the info name isn't available. Should be cleared when the
116 // Info does become available.
120 // The bencoded bytes of the info dict. This is actively manipulated if
121 // the info bytes aren't initially available, and we try to fetch them
124 // Each element corresponds to the 16KiB metadata pieces. If true, we have
125 // received that piece.
126 metadataCompletedChunks []bool
127 metadataChanged sync.Cond
129 // Closed when .Info is obtained.
130 gotMetainfoC chan struct{}
132 readers map[*reader]struct{}
133 _readerNowPieces bitmap.Bitmap
134 _readerReadaheadPieces bitmap.Bitmap
136 // A cache of pieces we need to get. Calculated from various piece and
137 // file priorities and completion states elsewhere.
138 _pendingPieces roaring.Bitmap
139 // A cache of completed piece indices.
140 _completedPieces roaring.Bitmap
141 // Pieces that need to be hashed.
142 piecesQueuedForHash bitmap.Bitmap
143 activePieceHashes int
144 initialPieceCheckDisabled bool
146 connsWithAllPieces map[*Peer]struct{}
148 requestState map[RequestIndex]requestState
149 // Chunks we've written to since the corresponding piece was last checked.
150 dirtyChunks typedRoaring.Bitmap[RequestIndex]
154 // Is On when all pieces are complete.
155 Complete chansync.Flag
157 // Torrent sources in use keyed by the source string.
158 activeSources sync.Map
159 sourcesLogger log.Logger
161 smartBanCache smartBanCache
163 // Large allocations reused between request state updates.
164 requestPieceStates []request_strategy.PieceRequestOrderState
165 requestIndexes []RequestIndex
168 func (t *Torrent) length() int64 {
169 return t._length.Value
172 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
173 // This could be done with roaring.BitSliceIndexing.
174 t.iterPeers(func(peer *Peer) {
175 if _, ok := t.connsWithAllPieces[peer]; ok {
178 if peer.peerHasPiece(i) {
185 func (t *Torrent) decPieceAvailability(i pieceIndex) {
190 if p.relativeAvailability <= 0 {
191 panic(p.relativeAvailability)
193 p.relativeAvailability--
194 t.updatePieceRequestOrder(i)
197 func (t *Torrent) incPieceAvailability(i pieceIndex) {
198 // If we don't the info, this should be reconciled when we do.
201 p.relativeAvailability++
202 t.updatePieceRequestOrder(i)
206 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
207 return t._readerNowPieces
210 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
211 return t._readerReadaheadPieces
214 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
215 return !t.wantPieceIndex(i)
218 // Returns a channel that is closed when the Torrent is closed.
219 func (t *Torrent) Closed() events.Done {
220 return t.closed.Done()
223 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
224 // pending, and half-open peers.
225 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
226 // Add pending peers to the list
227 t.peers.Each(func(peer PeerInfo) {
228 ks = append(ks, peer)
231 // Add half-open peers to the list
232 for _, peer := range t.halfOpen {
233 ks = append(ks, peer)
236 // Add active peers to the list
237 for conn := range t.conns {
238 ks = append(ks, PeerInfo{
240 Addr: conn.RemoteAddr,
241 Source: conn.Discovery,
242 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
243 // > But if we're not connected to them with an encrypted connection, I couldn't say
244 // > what's appropriate. We can carry forward the SupportsEncryption value as we
245 // > received it from trackers/DHT/PEX, or just use the encryption state for the
246 // > connection. It's probably easiest to do the latter for now.
247 // https://github.com/anacrolix/torrent/pull/188
248 SupportsEncryption: conn.headerEncrypted,
255 func (t *Torrent) setChunkSize(size pp.Integer) {
257 t.chunkPool = sync.Pool{
258 New: func() interface{} {
259 b := make([]byte, size)
265 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
266 return t._completedPieces.Contains(bitmap.BitIndex(piece))
269 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
270 if t.storage == nil {
271 return storage.Completion{Complete: false, Ok: true}
273 return t.pieces[piece].Storage().Completion()
276 // There's a connection to that address already.
277 func (t *Torrent) addrActive(addr string) bool {
278 if _, ok := t.halfOpen[addr]; ok {
281 for c := range t.conns {
283 if ra.String() == addr {
290 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
291 return t.appendConns(ret, func(conn *PeerConn) bool {
292 return !conn.closed.IsSet()
296 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
297 for c := range t.conns {
305 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
307 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
308 if t.closed.IsSet() {
311 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
312 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
313 torrent.Add("peers not added because of bad addr", 1)
314 // cl.logger.Printf("peers not added because of bad addr: %v", p)
318 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
319 torrent.Add("peers replaced", 1)
320 if !replaced.equal(p) {
321 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
328 for t.peers.Len() > cl.config.TorrentPeersHighWater {
329 _, ok := t.peers.DeleteMin()
331 torrent.Add("excess reserve peers discarded", 1)
337 func (t *Torrent) invalidateMetadata() {
338 for i := 0; i < len(t.metadataCompletedChunks); i++ {
339 t.metadataCompletedChunks[i] = false
342 t.gotMetainfoC = make(chan struct{})
347 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
351 if index >= len(t.metadataCompletedChunks) {
352 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
355 copy(t.metadataBytes[(1<<14)*index:], data)
356 t.metadataCompletedChunks[index] = true
359 func (t *Torrent) metadataPieceCount() int {
360 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
363 func (t *Torrent) haveMetadataPiece(piece int) bool {
365 return (1<<14)*piece < len(t.metadataBytes)
367 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
371 func (t *Torrent) metadataSize() int {
372 return len(t.metadataBytes)
375 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
376 for i := 0; i < len(info.Pieces); i += sha1.Size {
377 ret = append(ret, info.Pieces[i:i+sha1.Size])
382 func (t *Torrent) makePieces() {
383 hashes := infoPieceHashes(t.info)
384 t.pieces = make([]Piece, len(hashes))
385 for i, hash := range hashes {
386 piece := &t.pieces[i]
388 piece.index = pieceIndex(i)
389 piece.noPendingWrites.L = &piece.pendingWritesMutex
390 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
392 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
393 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
394 piece.files = files[beginFile:endFile]
398 // Returns the index of the first file containing the piece. files must be
399 // ordered by offset.
400 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
401 for i, f := range files {
402 if f.offset+f.length > pieceOffset {
409 // Returns the index after the last file containing the piece. files must be
410 // ordered by offset.
411 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
412 for i, f := range files {
413 if f.offset+f.length >= pieceEndOffset {
420 func (t *Torrent) cacheLength() {
422 for _, f := range t.info.UpvertedFiles() {
428 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
430 func (t *Torrent) setInfo(info *metainfo.Info) error {
431 if err := validateInfo(info); err != nil {
432 return fmt.Errorf("bad info: %s", err)
434 if t.storageOpener != nil {
436 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
438 return fmt.Errorf("error opening torrent storage: %s", err)
444 t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
446 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
447 t.displayName = "" // Save a few bytes lol.
454 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
455 return request_strategy.PieceRequestOrderKey{
456 InfoHash: t.infoHash,
461 // This seems to be all the follow-up tasks after info is set, that can't fail.
462 func (t *Torrent) onSetInfo() {
463 t.pieceRequestOrder = rand.Perm(t.numPieces())
464 t.initPieceRequestOrder()
465 MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
466 for i := range t.pieces {
468 // Need to add relativeAvailability before updating piece completion, as that may result in conns
470 if p.relativeAvailability != 0 {
471 panic(p.relativeAvailability)
473 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
474 t.addRequestOrderPiece(i)
475 t.updatePieceCompletion(i)
476 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
477 // t.logger.Printf("piece %s completion unknown, queueing check", p)
481 t.cl.event.Broadcast()
482 close(t.gotMetainfoC)
483 t.updateWantPeersEvent()
484 t.requestState = make(map[RequestIndex]requestState)
485 t.tryCreateMorePieceHashers()
486 t.iterPeers(func(p *Peer) {
488 p.updateRequests("onSetInfo")
492 // Called when metadata for a torrent becomes available.
493 func (t *Torrent) setInfoBytesLocked(b []byte) error {
494 if metainfo.HashBytes(b) != t.infoHash {
495 return errors.New("info bytes have wrong hash")
497 var info metainfo.Info
498 if err := bencode.Unmarshal(b, &info); err != nil {
499 return fmt.Errorf("error unmarshalling info bytes: %s", err)
502 t.metadataCompletedChunks = nil
506 if err := t.setInfo(&info); err != nil {
513 func (t *Torrent) haveAllMetadataPieces() bool {
517 if t.metadataCompletedChunks == nil {
520 for _, have := range t.metadataCompletedChunks {
528 // TODO: Propagate errors to disconnect peer.
529 func (t *Torrent) setMetadataSize(size int) (err error) {
531 // We already know the correct metadata size.
534 if uint32(size) > maxMetadataSize {
535 return log.WithLevel(log.Warning, errors.New("bad size"))
537 if len(t.metadataBytes) == size {
540 t.metadataBytes = make([]byte, size)
541 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
542 t.metadataChanged.Broadcast()
543 for c := range t.conns {
544 c.requestPendingMetadata()
549 // The current working name for the torrent. Either the name in the info dict,
550 // or a display name given such as by the dn value in a magnet link, or "".
551 func (t *Torrent) name() string {
553 defer t.nameMu.RUnlock()
555 return t.info.BestName()
557 if t.displayName != "" {
560 return "infohash:" + t.infoHash.HexString()
563 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
564 p := &t.pieces[index]
565 ret.Priority = t.piecePriority(index)
566 ret.Completion = p.completion()
567 ret.QueuedForHash = p.queuedForHash()
568 ret.Hashing = p.hashing
569 ret.Checking = ret.QueuedForHash || ret.Hashing
570 ret.Marking = p.marking
571 if !ret.Complete && t.piecePartiallyDownloaded(index) {
577 func (t *Torrent) metadataPieceSize(piece int) int {
578 return metadataPieceSize(len(t.metadataBytes), piece)
581 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
584 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
585 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
587 TotalSize: len(t.metadataBytes),
593 type pieceAvailabilityRun struct {
598 func (me pieceAvailabilityRun) String() string {
599 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
602 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
603 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
604 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
606 for i := range t.pieces {
607 rle.Append(t.pieces[i].availability(), 1)
613 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
614 freqs = make([]int, t.numActivePeers()+1)
615 for i := range t.pieces {
616 freqs[t.piece(i).availability()]++
621 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
622 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
623 ret = append(ret, PieceStateRun{
624 PieceState: el.(PieceState),
628 for index := range t.pieces {
629 rle.Append(t.pieceState(pieceIndex(index)), 1)
635 // Produces a small string representing a PieceStateRun.
636 func (psr PieceStateRun) String() (ret string) {
637 ret = fmt.Sprintf("%d", psr.Length)
638 ret += func() string {
639 switch psr.Priority {
640 case PiecePriorityNext:
642 case PiecePriorityNormal:
644 case PiecePriorityReadahead:
646 case PiecePriorityNow:
648 case PiecePriorityHigh:
657 if psr.QueuedForHash {
675 func (t *Torrent) writeStatus(w io.Writer) {
676 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
677 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
679 fmt.Fprintf(w, "Metadata have: ")
680 for _, h := range t.metadataCompletedChunks {
681 fmt.Fprintf(w, "%c", func() rune {
691 fmt.Fprintf(w, "Piece length: %s\n",
694 return fmt.Sprintf("%v (%v chunks)",
696 float64(t.usualPieceSize())/float64(t.chunkSize))
703 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
704 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
705 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
706 // availability frequencies instead.
708 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
709 for _, run := range t.pieceAvailabilityRuns() {
710 ret = append(ret, run.String())
715 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
716 func() (ret []string) {
717 for avail, freq := range t.pieceAvailabilityFrequencies() {
721 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
727 fmt.Fprintf(w, "Reader Pieces:")
728 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
729 fmt.Fprintf(w, " %d:%d", begin, end)
734 fmt.Fprintf(w, "Enabled trackers:\n")
736 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
737 fmt.Fprintf(tw, " URL\tExtra\n")
738 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
741 var luns, runs url.URL = *lu, *ru
744 var ml missinggo.MultiLess
745 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
746 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
748 }).([]torrentTrackerAnnouncer) {
749 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
754 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
756 spew.NewDefaultConfig()
757 spew.Fdump(w, t.statsLocked())
759 peers := t.peersAsSlice()
760 sort.Slice(peers, func(_i, _j int) bool {
763 if less, ok := multiless.New().EagerSameLess(
764 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
768 return worseConn(i, j)
771 for i, c := range peers {
772 fmt.Fprintf(w, "%2d. ", i+1)
774 c.writeStatus(&buf, t)
775 w.Write(bytes.TrimRight(
776 bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n ")),
781 func (t *Torrent) haveInfo() bool {
785 // Returns a run-time generated MetaInfo that includes the info bytes and
786 // announce-list as currently known to the client.
787 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
788 return metainfo.MetaInfo{
789 CreationDate: time.Now().Unix(),
790 Comment: "dynamic metainfo from client",
791 CreatedBy: "go.torrent",
792 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
793 InfoBytes: func() []byte {
795 return t.metadataBytes
800 UrlList: func() []string {
801 ret := make([]string, 0, len(t.webSeeds))
802 for url := range t.webSeeds {
803 ret = append(ret, url)
811 func (t *Torrent) BytesMissing() (n int64) {
813 n = t.bytesMissingLocked()
818 func (t *Torrent) bytesMissingLocked() int64 {
822 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
823 roaring.Flip(b, 0, end).Iterate(cb)
826 func (t *Torrent) bytesLeft() (left int64) {
827 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
828 p := t.piece(pieceIndex(x))
829 left += int64(p.length() - p.numDirtyBytes())
835 // Bytes left to give in tracker announces.
836 func (t *Torrent) bytesLeftAnnounce() int64 {
844 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
845 if t.pieceComplete(piece) {
848 if t.pieceAllDirty(piece) {
851 return t.pieces[piece].hasDirtyChunks()
854 func (t *Torrent) usualPieceSize() int {
855 return int(t.info.PieceLength)
858 func (t *Torrent) numPieces() pieceIndex {
859 return t.info.NumPieces()
862 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
863 return pieceIndex(t._completedPieces.GetCardinality())
866 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
868 err = errors.New("already closed")
871 for _, f := range t.onClose {
874 if t.storage != nil {
879 defer t.storageLock.Unlock()
880 if f := t.storage.Close; f != nil {
883 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
888 t.iterPeers(func(p *Peer) {
891 if t.storage != nil {
892 t.deletePieceRequestOrder()
894 t.assertAllPiecesRelativeAvailabilityZero()
896 t.cl.event.Broadcast()
897 t.pieceStateChanges.Close()
898 t.updateWantPeersEvent()
902 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
903 for i := range t.pieces {
905 if p.relativeAvailability != 0 {
906 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
911 func (t *Torrent) requestOffset(r Request) int64 {
912 return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
915 // Return the request that would include the given offset into the torrent data. Returns !ok if
916 // there is no such request.
917 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
918 return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
921 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
922 defer perf.ScopeTimerErr(&err)()
923 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
924 if err == nil && n != len(data) {
925 err = io.ErrShortWrite
930 func (t *Torrent) bitfield() (bf []bool) {
931 bf = make([]bool, t.numPieces())
932 t._completedPieces.Iterate(func(piece uint32) (again bool) {
939 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
940 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
943 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
944 return t._chunksPerRegularPiece
947 func (t *Torrent) numChunks() RequestIndex {
948 if t.numPieces() == 0 {
951 return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
954 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
955 t.dirtyChunks.RemoveRange(
956 uint64(t.pieceRequestIndexOffset(pieceIndex)),
957 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
960 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
961 if t.info.PieceLength == 0 {
962 // There will be no variance amongst pieces. Only pain.
965 if piece == t.numPieces()-1 {
966 ret := pp.Integer(t.length() % t.info.PieceLength)
971 return pp.Integer(t.info.PieceLength)
974 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
975 return &blockCheckingWriter{
976 cache: &t.smartBanCache,
977 requestIndex: t.pieceRequestIndexOffset(piece),
978 chunkSize: t.chunkSize.Int(),
982 func (t *Torrent) hashPiece(piece pieceIndex) (
984 // These are peers that sent us blocks that differ from what we hash here.
985 differingPeers map[bannableAddr]struct{},
989 p.waitNoPendingWrites()
990 storagePiece := t.pieces[piece].Storage()
992 // Does the backend want to do its own hashing?
993 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
994 var sum metainfo.Hash
995 // log.Printf("A piece decided to self-hash: %d", piece)
996 sum, err = i.SelfHash()
997 missinggo.CopyExact(&ret, sum)
1001 hash := pieceHash.New()
1002 const logPieceContents = false
1003 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1004 writers := []io.Writer{hash, smartBanWriter}
1005 var examineBuf bytes.Buffer
1006 if logPieceContents {
1007 writers = append(writers, &examineBuf)
1009 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1010 if logPieceContents {
1011 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1013 smartBanWriter.Flush()
1014 differingPeers = smartBanWriter.badPeers
1015 missinggo.CopyExact(&ret, hash.Sum(nil))
1019 func (t *Torrent) haveAnyPieces() bool {
1020 return !t._completedPieces.IsEmpty()
1023 func (t *Torrent) haveAllPieces() bool {
1027 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1030 func (t *Torrent) havePiece(index pieceIndex) bool {
1031 return t.haveInfo() && t.pieceComplete(index)
1034 func (t *Torrent) maybeDropMutuallyCompletePeer(
1035 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1039 if !t.cl.config.DropMutuallyCompletePeers {
1042 if !t.haveAllPieces() {
1045 if all, known := p.peerHasAllPieces(); !(known && all) {
1051 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1055 func (t *Torrent) haveChunk(r Request) (ret bool) {
1057 // log.Println("have chunk", r, ret)
1062 if t.pieceComplete(pieceIndex(r.Index)) {
1065 p := &t.pieces[r.Index]
1066 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1069 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1070 return chunkIndexType(cs.Begin / chunkSize)
1073 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1074 return t._pendingPieces.Contains(uint32(index))
1077 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1078 // conns (which is a map).
1079 var peerConnSlices sync.Pool
1081 func getPeerConnSlice(cap int) []*PeerConn {
1082 getInterface := peerConnSlices.Get()
1083 if getInterface == nil {
1084 return make([]*PeerConn, 0, cap)
1086 return getInterface.([]*PeerConn)[:0]
1090 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1091 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1092 // established connections for more than a minute. This is O(n log n). If there was a way to not
1093 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1094 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1095 wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
1096 defer peerConnSlices.Put(wcs.conns)
1099 for wcs.Len() != 0 {
1100 c := heap.Pop(&wcs).(*PeerConn)
1101 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1104 // If the connection is in the worst half of the established
1105 // connection quota and is older than a minute.
1106 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1107 // Give connections 1 minute to prove themselves.
1108 if time.Since(c.completedHandshake) > time.Minute {
1116 type PieceStateChange struct {
1121 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1122 t.cl._mu.Defer(func() {
1123 cur := t.pieceState(piece)
1124 p := &t.pieces[piece]
1125 if cur != p.publicPieceState {
1126 p.publicPieceState = cur
1127 t.pieceStateChanges.Publish(PieceStateChange{
1135 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1136 if t.pieceComplete(piece) {
1139 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1142 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1143 return t.pieces[piece].allChunksDirty()
1146 func (t *Torrent) readersChanged() {
1147 t.updateReaderPieces()
1148 t.updateAllPiecePriorities("Torrent.readersChanged")
1151 func (t *Torrent) updateReaderPieces() {
1152 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1155 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1159 t.updateReaderPieces()
1160 // Order the ranges, high and low.
1162 if l.begin > h.begin {
1165 if l.end < h.begin {
1166 // Two distinct ranges.
1167 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1168 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1175 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1179 func (t *Torrent) maybeNewConns() {
1180 // Tickle the accept routine.
1181 t.cl.event.Broadcast()
1185 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1186 if t._pendingPieces.Contains(uint32(piece)) {
1187 t.iterPeers(func(c *Peer) {
1188 // if c.requestState.Interested {
1191 if !c.isLowOnRequests() {
1194 if !c.peerHasPiece(piece) {
1197 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1200 c.updateRequests(reason)
1204 t.publishPieceChange(piece)
1207 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1208 if !t.closed.IsSet() {
1209 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1211 t.updatePieceRequestOrder(piece)
1213 p := &t.pieces[piece]
1214 newPrio := p.uncachedPriority()
1215 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1216 if newPrio == PiecePriorityNone {
1217 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1221 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1225 t.piecePriorityChanged(piece, reason)
1228 func (t *Torrent) updateAllPiecePriorities(reason string) {
1229 t.updatePiecePriorities(0, t.numPieces(), reason)
1232 // Update all piece priorities in one hit. This function should have the same
1233 // output as updatePiecePriority, but across all pieces.
1234 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1235 for i := begin; i < end; i++ {
1236 t.updatePiecePriority(i, reason)
1240 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1241 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1242 if off >= t.length() {
1252 begin = pieceIndex(off / t.info.PieceLength)
1253 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1254 if end > pieceIndex(t.info.NumPieces()) {
1255 end = pieceIndex(t.info.NumPieces())
1260 // Returns true if all iterations complete without breaking. Returns the read regions for all
1261 // readers. The reader regions should not be merged as some callers depend on this method to
1262 // enumerate readers.
1263 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1264 for r := range t.readers {
1266 if p.begin >= p.end {
1269 if !f(p.begin, p.end) {
1276 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1277 return t.piece(piece).uncachedPriority()
1280 func (t *Torrent) pendRequest(req RequestIndex) {
1281 t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1284 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1285 t.cl.event.Broadcast()
1286 if t.pieceComplete(piece) {
1287 t.onPieceCompleted(piece)
1289 t.onIncompletePiece(piece)
1291 t.updatePiecePriority(piece, reason)
1294 func (t *Torrent) numReceivedConns() (ret int) {
1295 for c := range t.conns {
1296 if c.Discovery == PeerSourceIncoming {
1303 func (t *Torrent) maxHalfOpen() int {
1304 // Note that if we somehow exceed the maximum established conns, we want
1305 // the negative value to have an effect.
1306 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1307 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1308 // We want to allow some experimentation with new peers, and to try to
1309 // upset an oversupply of received connections.
1310 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1313 func (t *Torrent) openNewConns() (initiated int) {
1314 defer t.updateWantPeersEvent()
1315 for t.peers.Len() != 0 {
1319 if len(t.halfOpen) >= t.maxHalfOpen() {
1322 if len(t.cl.dialers) == 0 {
1325 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1328 p := t.peers.PopMax()
1335 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1337 uncached := t.pieceCompleteUncached(piece)
1338 cached := p.completion()
1339 changed := cached != uncached
1340 complete := uncached.Complete
1341 p.storageCompletionOk = uncached.Ok
1344 t._completedPieces.Add(x)
1347 t._completedPieces.Remove(x)
1349 p.t.updatePieceRequestOrder(piece)
1351 if complete && len(p.dirtiers) != 0 {
1352 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1355 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1356 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1361 // Non-blocking read. Client lock is not required.
1362 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1364 p := &t.pieces[off/t.info.PieceLength]
1365 p.waitNoPendingWrites()
1367 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1378 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1379 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1380 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1381 func (t *Torrent) maybeCompleteMetadata() error {
1386 if !t.haveAllMetadataPieces() {
1387 // Don't have enough metadata pieces.
1390 err := t.setInfoBytesLocked(t.metadataBytes)
1392 t.invalidateMetadata()
1393 return fmt.Errorf("error setting info bytes: %s", err)
1395 if t.cl.config.Debug {
1396 t.logger.Printf("%s: got metadata from peers", t)
1401 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1402 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1404 now.Add(bitmap.BitIndex(begin))
1405 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1412 func (t *Torrent) needData() bool {
1413 if t.closed.IsSet() {
1419 return !t._pendingPieces.IsEmpty()
1422 func appendMissingStrings(old, new []string) (ret []string) {
1425 for _, n := range new {
1426 for _, o := range old {
1431 ret = append(ret, n)
1436 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1438 for minNumTiers > len(ret) {
1439 ret = append(ret, nil)
1444 func (t *Torrent) addTrackers(announceList [][]string) {
1445 fullAnnounceList := &t.metainfo.AnnounceList
1446 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1447 for tierIndex, trackerURLs := range announceList {
1448 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1450 t.startMissingTrackerScrapers()
1451 t.updateWantPeersEvent()
1454 // Don't call this before the info is available.
1455 func (t *Torrent) bytesCompleted() int64 {
1459 return t.length() - t.bytesLeft()
1462 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1465 return t.setInfoBytesLocked(b)
1468 // Returns true if connection is removed from torrent.Conns.
1469 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1470 if !c.closed.IsSet() {
1471 panic("connection is not closed")
1472 // There are behaviours prevented by the closed state that will fail
1473 // if the connection has been deleted.
1477 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1478 // the drop event against the PexConnState instead.
1480 if !t.cl.config.DisablePEX {
1484 torrent.Add("deleted connections", 1)
1485 c.deleteAllRequests("Torrent.deletePeerConn")
1486 t.assertPendingRequests()
1487 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1488 panic(t.connsWithAllPieces)
1493 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1494 if t.deleteConnWithAllPieces(p) {
1500 p.peerPieces().Iterate(func(i uint32) bool {
1501 p.t.decPieceAvailability(pieceIndex(i))
1506 func (t *Torrent) assertPendingRequests() {
1510 // var actual pendingRequests
1511 // if t.haveInfo() {
1512 // actual.m = make([]int, t.numChunks())
1514 // t.iterPeers(func(p *Peer) {
1515 // p.requestState.Requests.Iterate(func(x uint32) bool {
1520 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1526 func (t *Torrent) dropConnection(c *PeerConn) {
1527 t.cl.event.Broadcast()
1529 if t.deletePeerConn(c) {
1534 // Peers as in contact information for dialing out.
1535 func (t *Torrent) wantPeers() bool {
1536 if t.closed.IsSet() {
1539 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1542 return t.wantConns()
1545 func (t *Torrent) updateWantPeersEvent() {
1547 t.wantPeersEvent.Set()
1549 t.wantPeersEvent.Clear()
1553 // Returns whether the client should make effort to seed the torrent.
1554 func (t *Torrent) seeding() bool {
1556 if t.closed.IsSet() {
1559 if t.dataUploadDisallowed {
1562 if cl.config.NoUpload {
1565 if !cl.config.Seed {
1568 if cl.config.DisableAggressiveUpload && t.needData() {
1574 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1575 err := t.cl.runHandshookConn(pc, t)
1576 if err != nil || logAll {
1577 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1581 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1582 t.logRunHandshookConn(pc, false, log.Debug)
1585 func (t *Torrent) startScrapingTracker(_url string) {
1589 u, err := url.Parse(_url)
1591 // URLs with a leading '*' appear to be a uTorrent convention to
1592 // disable trackers.
1594 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1598 if u.Scheme == "udp" {
1600 t.startScrapingTracker(u.String())
1602 t.startScrapingTracker(u.String())
1605 if _, ok := t.trackerAnnouncers[_url]; ok {
1608 sl := func() torrentTrackerAnnouncer {
1611 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1615 if t.cl.config.DisableIPv6 {
1619 newAnnouncer := &trackerScraper{
1622 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1624 go newAnnouncer.Run()
1630 if t.trackerAnnouncers == nil {
1631 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1633 t.trackerAnnouncers[_url] = sl
1636 // Adds and starts tracker scrapers for tracker URLs that aren't already
1638 func (t *Torrent) startMissingTrackerScrapers() {
1639 if t.cl.config.DisableTrackers {
1642 t.startScrapingTracker(t.metainfo.Announce)
1643 for _, tier := range t.metainfo.AnnounceList {
1644 for _, url := range tier {
1645 t.startScrapingTracker(url)
1650 // Returns an AnnounceRequest with fields filled out to defaults and current
1652 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1653 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1654 // dependent on the network in use.
1655 return tracker.AnnounceRequest{
1657 NumWant: func() int32 {
1658 if t.wantPeers() && len(t.cl.dialers) > 0 {
1659 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1664 Port: uint16(t.cl.incomingPeerPort()),
1665 PeerId: t.cl.peerID,
1666 InfoHash: t.infoHash,
1667 Key: t.cl.announceKey(),
1669 // The following are vaguely described in BEP 3.
1671 Left: t.bytesLeftAnnounce(),
1672 Uploaded: t.stats.BytesWrittenData.Int64(),
1673 // There's no mention of wasted or unwanted download in the BEP.
1674 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1678 // Adds peers revealed in an announce until the announce ends, or we have
1680 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1682 for v := range pvs {
1685 for _, cp := range v.Peers {
1687 // Can't do anything with this.
1690 if t.addPeer(PeerInfo{
1691 Addr: ipPortAddr{cp.IP, cp.Port},
1692 Source: PeerSourceDhtGetPeers,
1699 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1704 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1705 // announce ends. stop will force the announce to end.
1706 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1707 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1711 _done := make(chan struct{})
1715 t.consumeDhtAnnouncePeers(ps.Peers())
1721 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1722 _, stop, err := t.AnnounceToDht(s)
1727 case <-t.closed.Done():
1728 case <-time.After(5 * time.Minute):
1734 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1740 if t.closed.IsSet() {
1743 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1744 // TODO: We can include the announce_peer step depending on whether we can receive
1745 // inbound connections. We should probably only announce once every 15 mins too.
1749 // TODO: Determine if there's a listener on the port we're announcing.
1750 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1761 err := t.timeboxedAnnounceToDht(s)
1763 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1769 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1770 for _, p := range peers {
1778 // The returned TorrentStats may require alignment in memory. See
1779 // https://github.com/anacrolix/torrent/issues/383.
1780 func (t *Torrent) Stats() TorrentStats {
1782 defer t.cl.rUnlock()
1783 return t.statsLocked()
1786 func (t *Torrent) statsLocked() (ret TorrentStats) {
1787 ret.ActivePeers = len(t.conns)
1788 ret.HalfOpenPeers = len(t.halfOpen)
1789 ret.PendingPeers = t.peers.Len()
1790 ret.TotalPeers = t.numTotalPeers()
1791 ret.ConnectedSeeders = 0
1792 for c := range t.conns {
1793 if all, ok := c.peerHasAllPieces(); all && ok {
1794 ret.ConnectedSeeders++
1797 ret.ConnStats = t.stats.Copy()
1798 ret.PiecesComplete = t.numPiecesCompleted()
1802 // The total number of peers in the torrent.
1803 func (t *Torrent) numTotalPeers() int {
1804 peers := make(map[string]struct{})
1805 for conn := range t.conns {
1806 ra := conn.conn.RemoteAddr()
1808 // It's been closed and doesn't support RemoteAddr.
1811 peers[ra.String()] = struct{}{}
1813 for addr := range t.halfOpen {
1814 peers[addr] = struct{}{}
1816 t.peers.Each(func(peer PeerInfo) {
1817 peers[peer.Addr.String()] = struct{}{}
1822 // Reconcile bytes transferred before connection was associated with a
1824 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1825 if c._stats != (ConnStats{
1826 // Handshakes should only increment these fields:
1827 BytesWritten: c._stats.BytesWritten,
1828 BytesRead: c._stats.BytesRead,
1832 c.postHandshakeStats(func(cs *ConnStats) {
1833 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1834 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1836 c.reconciledHandshakeStats = true
1839 // Returns true if the connection is added.
1840 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1843 torrent.Add("added connections", 1)
1846 if t.closed.IsSet() {
1847 return errors.New("torrent closed")
1849 for c0 := range t.conns {
1850 if c.PeerID != c0.PeerID {
1853 if !t.cl.config.DropDuplicatePeerIds {
1856 if c.hasPreferredNetworkOver(c0) {
1858 t.deletePeerConn(c0)
1860 return errors.New("existing connection preferred")
1863 if len(t.conns) >= t.maxEstablishedConns {
1864 c := t.worstBadConn()
1866 return errors.New("don't want conns")
1871 if len(t.conns) >= t.maxEstablishedConns {
1874 t.conns[c] = struct{}{}
1875 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1876 t.pex.Add(c) // as no further extended handshake expected
1881 func (t *Torrent) wantConns() bool {
1882 if !t.networkingEnabled.Bool() {
1885 if t.closed.IsSet() {
1888 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
1891 return len(t.conns) < t.maxEstablishedConns || t.worstBadConn() != nil
1894 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1897 oldMax = t.maxEstablishedConns
1898 t.maxEstablishedConns = max
1899 wcs := worseConnSlice{
1900 conns: t.appendConns(nil, func(*PeerConn) bool {
1906 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1907 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
1913 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1914 t.logger.LazyLog(log.Debug, func() log.Msg {
1915 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
1919 t.cl.event.Broadcast()
1920 if t.closed.IsSet() {
1924 // Don't score the first time a piece is hashed, it could be an initial check.
1925 if p.storageCompletionOk {
1927 pieceHashedCorrect.Add(1)
1930 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1931 ).AddValues(t, p).LogLevel(
1933 log.Debug, t.logger)
1935 pieceHashedNotCorrect.Add(1)
1940 t.publishPieceChange(piece)
1943 t.publishPieceChange(piece)
1947 if len(p.dirtiers) != 0 {
1948 // Don't increment stats above connection-level for every involved connection.
1949 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1951 for c := range p.dirtiers {
1952 c._stats.incrementPiecesDirtiedGood()
1954 t.clearPieceTouchers(piece)
1955 hasDirty := p.hasDirtyChunks()
1958 p.Flush() // You can be synchronous here!
1960 err := p.Storage().MarkComplete()
1962 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1966 if t.closed.IsSet() {
1969 t.pendAllChunkSpecs(piece)
1971 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1972 // Peers contributed to all the data for this piece hash failure, and the failure was
1973 // not due to errors in the storage (such as data being dropped in a cache).
1975 // Increment Torrent and above stats, and then specific connections.
1976 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1977 for c := range p.dirtiers {
1978 // Y u do dis peer?!
1979 c.stats().incrementPiecesDirtiedBad()
1982 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1983 for c := range p.dirtiers {
1985 bannableTouchers = append(bannableTouchers, c)
1988 t.clearPieceTouchers(piece)
1989 slices.Sort(bannableTouchers, connLessTrusted)
1991 if t.cl.config.Debug {
1993 "bannable conns by trust for piece %d: %v",
1995 func() (ret []connectionTrust) {
1996 for _, c := range bannableTouchers {
1997 ret = append(ret, c.trust())
2004 if len(bannableTouchers) >= 1 {
2005 c := bannableTouchers[0]
2006 if len(bannableTouchers) != 1 {
2007 t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2009 // Turns out it's still useful to ban peers like this because if there's only a
2010 // single peer for a piece, and we never progress that piece to completion, we
2011 // will never smart-ban them. Discovered in
2012 // https://github.com/anacrolix/torrent/issues/715.
2013 t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2018 t.onIncompletePiece(piece)
2019 p.Storage().MarkNotComplete()
2021 t.updatePieceCompletion(piece)
2024 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2025 start := t.pieceRequestIndexOffset(piece)
2026 end := start + t.pieceNumChunks(piece)
2027 for ri := start; ri < end; ri++ {
2032 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2033 t.pendAllChunkSpecs(piece)
2034 t.cancelRequestsForPiece(piece)
2035 t.piece(piece).readerCond.Broadcast()
2036 for conn := range t.conns {
2038 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2042 // Called when a piece is found to be not complete.
2043 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2044 if t.pieceAllDirty(piece) {
2045 t.pendAllChunkSpecs(piece)
2047 if !t.wantPieceIndex(piece) {
2048 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2051 // We could drop any connections that we told we have a piece that we
2052 // don't here. But there's a test failure, and it seems clients don't care
2053 // if you request pieces that you already claim to have. Pruning bad
2054 // connections might just remove any connections that aren't treating us
2055 // favourably anyway.
2057 // for c := range t.conns {
2058 // if c.sentHave(piece) {
2062 t.iterPeers(func(conn *Peer) {
2063 if conn.peerHasPiece(piece) {
2064 conn.updateRequests("piece incomplete")
2069 func (t *Torrent) tryCreateMorePieceHashers() {
2070 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2074 func (t *Torrent) tryCreatePieceHasher() bool {
2075 if t.storage == nil {
2078 pi, ok := t.getPieceToHash()
2083 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2085 t.publishPieceChange(pi)
2086 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2087 t.storageLock.RLock()
2088 t.activePieceHashes++
2089 go t.pieceHasher(pi)
2093 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2094 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2095 if t.piece(i).hashing {
2105 func (t *Torrent) dropBannedPeers() {
2106 t.iterPeers(func(p *Peer) {
2107 remoteIp := p.remoteIp()
2108 if remoteIp == nil {
2109 if p.bannableAddr.Ok {
2110 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2114 netipAddr := netip.MustParseAddr(remoteIp.String())
2115 if Some(netipAddr) != p.bannableAddr {
2116 t.logger.WithDefaultLevel(log.Debug).Printf(
2117 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2118 p, remoteIp, p.bannableAddr)
2120 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2121 // Should this be a close?
2123 t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2128 func (t *Torrent) pieceHasher(index pieceIndex) {
2130 sum, failedPeers, copyErr := t.hashPiece(index)
2131 correct := sum == *p.hash
2135 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2137 t.storageLock.RUnlock()
2141 for peer := range failedPeers {
2142 t.cl.banPeerIP(peer.AsSlice())
2143 t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2146 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2147 t.smartBanCache.ForgetBlock(ri)
2151 t.pieceHashed(index, correct, copyErr)
2152 t.updatePiecePriority(index, "Torrent.pieceHasher")
2153 t.activePieceHashes--
2154 t.tryCreateMorePieceHashers()
2157 // Return the connections that touched a piece, and clear the entries while doing it.
2158 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2160 for c := range p.dirtiers {
2161 delete(c.peerTouchedPieces, pi)
2162 delete(p.dirtiers, c)
2166 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2167 t.iterPeers(func(p *Peer) {
2168 ret = append(ret, p)
2173 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2174 piece := t.piece(pieceIndex)
2175 if piece.queuedForHash() {
2178 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2179 t.publishPieceChange(pieceIndex)
2180 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2181 t.tryCreateMorePieceHashers()
2184 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2185 // before the Info is available.
2186 func (t *Torrent) VerifyData() {
2187 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2188 t.Piece(i).VerifyData()
2192 // Start the process of connecting to the given peer for the given torrent if appropriate.
2193 func (t *Torrent) initiateConn(peer PeerInfo) {
2194 if peer.Id == t.cl.peerID {
2197 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2201 if t.addrActive(addr.String()) {
2205 t.halfOpen[addr.String()] = peer
2206 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2209 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2210 // quickly make one Client visible to the Torrent of another Client.
2211 func (t *Torrent) AddClientPeer(cl *Client) int {
2212 return t.AddPeers(func() (ps []PeerInfo) {
2213 for _, la := range cl.ListenAddrs() {
2214 ps = append(ps, PeerInfo{
2223 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2225 func (t *Torrent) allStats(f func(*ConnStats)) {
2230 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2231 return t.pieces[i].hashing
2234 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2235 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2238 func (t *Torrent) dialTimeout() time.Duration {
2239 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2242 func (t *Torrent) piece(i int) *Piece {
2246 func (t *Torrent) onWriteChunkErr(err error) {
2247 if t.userOnWriteChunkErr != nil {
2248 go t.userOnWriteChunkErr(err)
2251 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2252 t.disallowDataDownloadLocked()
2255 func (t *Torrent) DisallowDataDownload() {
2256 t.disallowDataDownloadLocked()
2259 func (t *Torrent) disallowDataDownloadLocked() {
2260 t.dataDownloadDisallowed.Set()
2263 func (t *Torrent) AllowDataDownload() {
2264 t.dataDownloadDisallowed.Clear()
2267 // Enables uploading data, if it was disabled.
2268 func (t *Torrent) AllowDataUpload() {
2271 t.dataUploadDisallowed = false
2272 for c := range t.conns {
2273 c.updateRequests("allow data upload")
2277 // Disables uploading data, if it was enabled.
2278 func (t *Torrent) DisallowDataUpload() {
2281 t.dataUploadDisallowed = true
2282 for c := range t.conns {
2283 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2284 c.updateRequests("disallow data upload")
2288 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2289 // or if nil, a critical message is logged, and data download is disabled.
2290 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2293 t.userOnWriteChunkErr = f
2296 func (t *Torrent) iterPeers(f func(p *Peer)) {
2297 for pc := range t.conns {
2300 for _, ws := range t.webSeeds {
2305 func (t *Torrent) callbacks() *Callbacks {
2306 return &t.cl.config.Callbacks
2309 type AddWebSeedsOpt func(*webseed.Client)
2311 // Sets the WebSeed trailing path escaper for a webseed.Client.
2312 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2313 return func(c *webseed.Client) {
2314 c.PathEscaper = custom
2318 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2321 for _, u := range urls {
2322 t.addWebSeed(u, opts...)
2326 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2327 if t.cl.config.DisableWebseeds {
2330 if _, ok := t.webSeeds[url]; ok {
2333 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2334 // right away. This value should be some multiple of the number of connections to a host. I
2335 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2336 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2337 // "https://webtorrent.io/torrents/".
2338 const maxRequests = 16
2344 reconciledHandshakeStats: true,
2345 // This should affect how often we have to recompute requests for this peer. Note that
2346 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2347 // requests mark more often, so recomputation is probably sooner than with regular peer
2348 // conns. ~4x maxRequests would be about right.
2349 PeerMaxRequests: 128,
2350 // TODO: Set ban prefix?
2351 RemoteAddr: remoteAddrFromUrl(url),
2352 callbacks: t.callbacks(),
2354 client: webseed.Client{
2355 HttpClient: t.cl.httpClient,
2357 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2358 return &rateLimitedReader{
2359 l: t.cl.config.DownloadRateLimiter,
2364 activeRequests: make(map[Request]webseed.Request, maxRequests),
2366 ws.peer.initRequestState()
2367 for _, opt := range opts {
2370 ws.peer.initUpdateRequestsTimer()
2371 ws.requesterCond.L = t.cl.locker()
2372 for i := 0; i < maxRequests; i += 1 {
2375 for _, f := range t.callbacks().NewPeer {
2378 ws.peer.logger = t.logger.WithContextValue(&ws)
2379 ws.peer.peerImpl = &ws
2381 ws.onGotInfo(t.info)
2383 t.webSeeds[url] = &ws.peer
2386 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2387 t.iterPeers(func(p1 *Peer) {
2395 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2396 index := t.pieceIndexOfRequestIndex(ri)
2399 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2403 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2404 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2407 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2408 return RequestIndex(piece) * t.chunksPerRegularPiece()
2411 func (t *Torrent) updateComplete() {
2412 t.Complete.SetBool(t.haveAllPieces())
2415 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2416 p := t.requestingPeer(r)
2420 // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2421 //delete(t.pendingRequests, r)
2422 if _, ok := t.requestState[r]; ok {
2423 panic("expected request state to be gone")
2428 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2429 return t.requestState[r].peer
2432 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2433 if t.connsWithAllPieces == nil {
2434 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2436 t.connsWithAllPieces[p] = struct{}{}
2439 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2440 _, ok := t.connsWithAllPieces[p]
2441 delete(t.connsWithAllPieces, p)
2445 func (t *Torrent) numActivePeers() int {
2446 return len(t.conns) + len(t.webSeeds)
2449 func (t *Torrent) hasStorageCap() bool {
2450 f := t.storage.Capacity
2458 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2459 return pieceIndex(ri / t.chunksPerRegularPiece())
2462 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2463 reuseIter *typedRoaring.Iterator[RequestIndex],
2465 f func(RequestIndex),
2467 reuseIter.Initialize(&t.dirtyChunks)
2468 pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2469 iterBitmapUnsetInRange(
2471 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2476 type requestState struct {
2481 // Returns an error if a received chunk is out of bounds in someway.
2482 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2484 return errors.New("torrent missing info")
2486 if int(r.Index) >= t.numPieces() {
2487 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2489 pieceLength := t.pieceLength(pieceIndex(r.Index))
2490 if r.Begin >= pieceLength {
2491 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2493 // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2494 // for peers to manipulate as they need to send potentially large buffers to begin with. There
2495 // should be considerable checks elsewhere for this case due to the network overhead. We should
2496 // catch most of the overflow manipulation stuff by checking index and begin above.