16 "github.com/davecgh/go-spew/spew"
18 "github.com/anacrolix/dht/v2"
19 "github.com/anacrolix/log"
20 "github.com/anacrolix/missinggo"
21 "github.com/anacrolix/missinggo/perf"
22 "github.com/anacrolix/missinggo/pubsub"
23 "github.com/anacrolix/missinggo/slices"
24 "github.com/anacrolix/missinggo/v2/bitmap"
25 "github.com/anacrolix/missinggo/v2/prioritybitmap"
27 "github.com/anacrolix/torrent/bencode"
28 "github.com/anacrolix/torrent/metainfo"
29 pp "github.com/anacrolix/torrent/peer_protocol"
30 "github.com/anacrolix/torrent/storage"
31 "github.com/anacrolix/torrent/tracker"
34 // Maintains state of torrent within a Client. Many methods should not be called before the info is
35 // available, see .Info and .GotInfo.
37 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
38 // alignment. See #262.
43 networkingEnabled bool
44 dataDownloadDisallowed bool
45 userOnWriteChunkErr func(error)
47 // Determines what chunks to request from peers.
48 requestStrategy requestStrategy
50 closed missinggo.Event
51 infoHash metainfo.Hash
53 // Values are the piece indices that changed.
54 pieceStateChanges *pubsub.PubSub
55 // The size of chunks to request from peers over the wire. This is
56 // normally 16KiB by convention these days.
59 // Total length of the torrent in bytes. Stored because it's not O(1) to
60 // get this from the info dict.
63 // The storage to open when the info dict becomes available.
64 storageOpener *storage.Client
65 // Storage for torrent data.
66 storage *storage.Torrent
67 // Read-locked for using storage, and write-locked for Closing.
68 storageLock sync.RWMutex
70 // TODO: Only announce stuff is used?
71 metainfo metainfo.MetaInfo
73 // The info dict. nil if we don't have it (yet).
77 // Active peer connections, running message stream loops. TODO: Make this
78 // open (not-closed) connections only.
79 conns map[*PeerConn]struct{}
80 maxEstablishedConns int
81 // Set of addrs to which we're attempting to connect. Connections are
82 // half-open until all handshakes are completed.
83 halfOpen map[string]Peer
86 // Reserve of peers to connect to. A peer can be both here and in the
87 // active connections if were told about the peer after connecting with
88 // them. That encourages us to reconnect to peers that are well known in
90 peers prioritizedPeers
91 wantPeersEvent missinggo.Event
92 // An announcer for each tracker URL.
93 trackerAnnouncers map[string]*trackerScraper
94 // How many times we've initiated a DHT announce. TODO: Move into stats.
97 // Name used if the info name isn't available. Should be cleared when the
98 // Info does become available.
102 // The bencoded bytes of the info dict. This is actively manipulated if
103 // the info bytes aren't initially available, and we try to fetch them
106 // Each element corresponds to the 16KiB metadata pieces. If true, we have
107 // received that piece.
108 metadataCompletedChunks []bool
109 metadataChanged sync.Cond
111 // Set when .Info is obtained.
112 gotMetainfo missinggo.Event
114 readers map[*reader]struct{}
115 _readerNowPieces bitmap.Bitmap
116 _readerReadaheadPieces bitmap.Bitmap
118 // A cache of pieces we need to get. Calculated from various piece and
119 // file priorities and completion states elsewhere.
120 _pendingPieces prioritybitmap.PriorityBitmap
121 // A cache of completed piece indices.
122 _completedPieces bitmap.Bitmap
123 // Pieces that need to be hashed.
124 piecesQueuedForHash bitmap.Bitmap
125 activePieceHashes int
127 // A pool of piece priorities []int for assignment to new connections.
128 // These "inclinations" are used to give connections preference for
130 connPieceInclinationPool sync.Pool
132 // Count of each request across active connections.
133 pendingRequests map[request]int
138 func (t *Torrent) numConns() int {
142 func (t *Torrent) numReaders() int {
143 return len(t.readers)
146 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
147 return t._readerNowPieces
150 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
151 return t._readerReadaheadPieces
154 func (t *Torrent) ignorePieces() bitmap.Bitmap {
155 ret := t._completedPieces.Copy()
156 ret.Union(t.piecesQueuedForHash)
157 for i := 0; i < t.numPieces(); i++ {
158 if t.piece(i).hashing {
165 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
166 return &t._pendingPieces
169 func (t *Torrent) tickleReaders() {
170 t.cl.event.Broadcast()
173 // Returns a channel that is closed when the Torrent is closed.
174 func (t *Torrent) Closed() <-chan struct{} {
175 return t.closed.LockedChan(t.cl.locker())
178 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
179 // pending, and half-open peers.
180 func (t *Torrent) KnownSwarm() (ks []Peer) {
181 // Add pending peers to the list
182 t.peers.Each(func(peer Peer) {
183 ks = append(ks, peer)
186 // Add half-open peers to the list
187 for _, peer := range t.halfOpen {
188 ks = append(ks, peer)
191 // Add active peers to the list
192 for conn := range t.conns {
194 ks = append(ks, Peer{
196 Addr: conn.remoteAddr,
197 Source: conn.Discovery,
198 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
199 // > But if we're not connected to them with an encrypted connection, I couldn't say
200 // > what's appropriate. We can carry forward the SupportsEncryption value as we
201 // > received it from trackers/DHT/PEX, or just use the encryption state for the
202 // > connection. It's probably easiest to do the latter for now.
203 // https://github.com/anacrolix/torrent/pull/188
204 SupportsEncryption: conn.headerEncrypted,
211 func (t *Torrent) setChunkSize(size pp.Integer) {
213 t.chunkPool = &sync.Pool{
214 New: func() interface{} {
215 b := make([]byte, size)
221 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
222 return t._completedPieces.Get(bitmap.BitIndex(piece))
225 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
226 return t.pieces[piece].Storage().Completion()
229 // There's a connection to that address already.
230 func (t *Torrent) addrActive(addr string) bool {
231 if _, ok := t.halfOpen[addr]; ok {
234 for c := range t.conns {
236 if ra.String() == addr {
243 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
244 ret = make([]*PeerConn, 0, len(t.conns))
245 for c := range t.conns {
246 if !c.closed.IsSet() {
253 func (t *Torrent) addPeer(p Peer) {
255 peersAddedBySource.Add(string(p.Source), 1)
256 if t.closed.IsSet() {
259 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
260 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
261 torrent.Add("peers not added because of bad addr", 1)
262 // cl.logger.Printf("peers not added because of bad addr: %v", p)
267 torrent.Add("peers replaced", 1)
270 for t.peers.Len() > cl.config.TorrentPeersHighWater {
271 _, ok := t.peers.DeleteMin()
273 torrent.Add("excess reserve peers discarded", 1)
278 func (t *Torrent) invalidateMetadata() {
279 for i := range t.metadataCompletedChunks {
280 t.metadataCompletedChunks[i] = false
287 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
291 if index >= len(t.metadataCompletedChunks) {
292 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
295 copy(t.metadataBytes[(1<<14)*index:], data)
296 t.metadataCompletedChunks[index] = true
299 func (t *Torrent) metadataPieceCount() int {
300 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
303 func (t *Torrent) haveMetadataPiece(piece int) bool {
305 return (1<<14)*piece < len(t.metadataBytes)
307 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
311 func (t *Torrent) metadataSize() int {
312 return len(t.metadataBytes)
315 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
316 for i := 0; i < len(info.Pieces); i += sha1.Size {
317 ret = append(ret, info.Pieces[i:i+sha1.Size])
322 func (t *Torrent) makePieces() {
323 hashes := infoPieceHashes(t.info)
324 t.pieces = make([]Piece, len(hashes))
325 for i, hash := range hashes {
326 piece := &t.pieces[i]
328 piece.index = pieceIndex(i)
329 piece.noPendingWrites.L = &piece.pendingWritesMutex
330 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
332 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
333 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
334 piece.files = files[beginFile:endFile]
338 // Returns the index of the first file containing the piece. files must be
339 // ordered by offset.
340 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
341 for i, f := range files {
342 if f.offset+f.length > pieceOffset {
349 // Returns the index after the last file containing the piece. files must be
350 // ordered by offset.
351 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
352 for i, f := range files {
353 if f.offset+f.length >= pieceEndOffset {
360 func (t *Torrent) cacheLength() {
362 for _, f := range t.info.UpvertedFiles() {
368 func (t *Torrent) setInfo(info *metainfo.Info) error {
369 if err := validateInfo(info); err != nil {
370 return fmt.Errorf("bad info: %s", err)
372 if t.storageOpener != nil {
374 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
376 return fmt.Errorf("error opening torrent storage: %s", err)
382 t.displayName = "" // Save a few bytes lol.
389 func (t *Torrent) onSetInfo() {
390 for conn := range t.conns {
391 if err := conn.setNumPieces(t.numPieces()); err != nil {
392 t.logger.Printf("closing connection: %s", err)
396 for i := range t.pieces {
397 t.updatePieceCompletion(pieceIndex(i))
399 if !p.storageCompletionOk {
400 // t.logger.Printf("piece %s completion unknown, queueing check", p)
401 t.queuePieceCheck(pieceIndex(i))
404 t.cl.event.Broadcast()
406 t.updateWantPeersEvent()
407 t.pendingRequests = make(map[request]int)
408 t.tryCreateMorePieceHashers()
411 // Called when metadata for a torrent becomes available.
412 func (t *Torrent) setInfoBytes(b []byte) error {
413 if metainfo.HashBytes(b) != t.infoHash {
414 return errors.New("info bytes have wrong hash")
416 var info metainfo.Info
417 if err := bencode.Unmarshal(b, &info); err != nil {
418 return fmt.Errorf("error unmarshalling info bytes: %s", err)
420 if err := t.setInfo(&info); err != nil {
424 t.metadataCompletedChunks = nil
429 func (t *Torrent) haveAllMetadataPieces() bool {
433 if t.metadataCompletedChunks == nil {
436 for _, have := range t.metadataCompletedChunks {
444 // TODO: Propagate errors to disconnect peer.
445 func (t *Torrent) setMetadataSize(bytes int) (err error) {
447 // We already know the correct metadata size.
450 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
451 return errors.New("bad size")
453 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
456 t.metadataBytes = make([]byte, bytes)
457 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
458 t.metadataChanged.Broadcast()
459 for c := range t.conns {
460 c.requestPendingMetadata()
465 // The current working name for the torrent. Either the name in the info dict,
466 // or a display name given such as by the dn value in a magnet link, or "".
467 func (t *Torrent) name() string {
469 defer t.nameMu.RUnlock()
476 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
477 p := &t.pieces[index]
478 ret.Priority = t.piecePriority(index)
479 ret.Completion = p.completion()
480 if p.queuedForHash() || p.hashing {
483 if !ret.Complete && t.piecePartiallyDownloaded(index) {
489 func (t *Torrent) metadataPieceSize(piece int) int {
490 return metadataPieceSize(len(t.metadataBytes), piece)
493 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
499 d["total_size"] = len(t.metadataBytes)
501 p := bencode.MustMarshal(d)
504 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
505 ExtendedPayload: append(p, data...),
509 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
510 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
511 ret = append(ret, PieceStateRun{
512 PieceState: el.(PieceState),
516 for index := range t.pieces {
517 rle.Append(t.pieceState(pieceIndex(index)), 1)
523 // Produces a small string representing a PieceStateRun.
524 func (psr PieceStateRun) String() (ret string) {
525 ret = fmt.Sprintf("%d", psr.Length)
526 ret += func() string {
527 switch psr.Priority {
528 case PiecePriorityNext:
530 case PiecePriorityNormal:
532 case PiecePriorityReadahead:
534 case PiecePriorityNow:
536 case PiecePriorityHigh:
557 func (t *Torrent) writeStatus(w io.Writer) {
558 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
559 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
561 fmt.Fprintf(w, "Metadata have: ")
562 for _, h := range t.metadataCompletedChunks {
563 fmt.Fprintf(w, "%c", func() rune {
573 fmt.Fprintf(w, "Piece length: %s\n", func() string {
575 return fmt.Sprint(t.usualPieceSize())
581 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
582 fmt.Fprintf(w, "Piece States: %s", t.pieceStateRuns())
585 fmt.Fprintf(w, "Reader Pieces:")
586 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
587 fmt.Fprintf(w, " %d:%d", begin, end)
592 fmt.Fprintf(w, "Enabled trackers:\n")
594 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
595 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
596 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
599 var luns, runs url.URL = lu, ru
602 var ml missinggo.MultiLess
603 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
604 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
606 }).([]*trackerScraper) {
607 fmt.Fprintf(tw, " %s\n", ta.statusLine())
612 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
614 spew.NewDefaultConfig()
615 spew.Fdump(w, t.statsLocked())
617 conns := t.connsAsSlice()
618 slices.Sort(conns, worseConn)
619 for i, c := range conns {
620 fmt.Fprintf(w, "%2d. ", i+1)
625 func (t *Torrent) haveInfo() bool {
629 // Returns a run-time generated MetaInfo that includes the info bytes and
630 // announce-list as currently known to the client.
631 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
632 return metainfo.MetaInfo{
633 CreationDate: time.Now().Unix(),
634 Comment: "dynamic metainfo from client",
635 CreatedBy: "go.torrent",
636 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
637 InfoBytes: func() []byte {
639 return t.metadataBytes
647 func (t *Torrent) BytesMissing() int64 {
650 return t.bytesMissingLocked()
653 func (t *Torrent) bytesMissingLocked() int64 {
657 func (t *Torrent) bytesLeft() (left int64) {
658 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
659 p := &t.pieces[piece]
660 left += int64(p.length() - p.numDirtyBytes())
666 // Bytes left to give in tracker announces.
667 func (t *Torrent) bytesLeftAnnounce() int64 {
675 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
676 if t.pieceComplete(piece) {
679 if t.pieceAllDirty(piece) {
682 return t.pieces[piece].hasDirtyChunks()
685 func (t *Torrent) usualPieceSize() int {
686 return int(t.info.PieceLength)
689 func (t *Torrent) numPieces() pieceIndex {
690 return pieceIndex(t.info.NumPieces())
693 func (t *Torrent) numPiecesCompleted() (num int) {
694 return t._completedPieces.Len()
697 func (t *Torrent) close() (err error) {
700 if t.storage != nil {
703 t.storageLock.Unlock()
705 for conn := range t.conns {
709 t.cl.event.Broadcast()
710 t.pieceStateChanges.Close()
711 t.updateWantPeersEvent()
715 func (t *Torrent) requestOffset(r request) int64 {
716 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
719 // Return the request that would include the given offset into the torrent
720 // data. Returns !ok if there is no such request.
721 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
722 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
725 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
726 defer perf.ScopeTimerErr(&err)()
727 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
728 if err == nil && n != len(data) {
729 err = io.ErrShortWrite
734 func (t *Torrent) bitfield() (bf []bool) {
735 bf = make([]bool, t.numPieces())
736 t._completedPieces.IterTyped(func(piece int) (again bool) {
743 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
744 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
747 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
748 t.pieces[pieceIndex]._dirtyChunks.Clear()
751 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
752 if t.info.PieceLength == 0 {
753 // There will be no variance amongst pieces. Only pain.
756 if piece == t.numPieces()-1 {
757 ret := pp.Integer(*t.length % t.info.PieceLength)
762 return pp.Integer(t.info.PieceLength)
765 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, copyErr error) {
766 hash := pieceHash.New()
768 p.waitNoPendingWrites()
769 ip := t.info.Piece(int(piece))
771 _, copyErr = io.CopyN( // Return no error iff pl bytes are copied.
772 hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl), pl)
773 missinggo.CopyExact(&ret, hash.Sum(nil))
777 func (t *Torrent) haveAnyPieces() bool {
778 return t._completedPieces.Len() != 0
781 func (t *Torrent) haveAllPieces() bool {
785 return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
788 func (t *Torrent) havePiece(index pieceIndex) bool {
789 return t.haveInfo() && t.pieceComplete(index)
792 func (t *Torrent) haveChunk(r request) (ret bool) {
794 // log.Println("have chunk", r, ret)
799 if t.pieceComplete(pieceIndex(r.Index)) {
802 p := &t.pieces[r.Index]
803 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
806 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
807 return int(cs.Begin / chunkSize)
810 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
814 if index < 0 || index >= t.numPieces() {
817 p := &t.pieces[index]
818 if p.queuedForHash() {
824 if t.pieceComplete(index) {
827 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
830 // t.logger.Printf("piece %d not pending", index)
831 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
832 return index < begin || index >= end
836 // The worst connection is one that hasn't been sent, or sent anything useful
837 // for the longest. A bad connection is one that usually sends us unwanted
838 // pieces, or has been in worser half of the established connections for more
840 func (t *Torrent) worstBadConn() *PeerConn {
841 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
844 c := heap.Pop(&wcs).(*PeerConn)
845 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
848 // If the connection is in the worst half of the established
849 // connection quota and is older than a minute.
850 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
851 // Give connections 1 minute to prove themselves.
852 if time.Since(c.completedHandshake) > time.Minute {
860 type PieceStateChange struct {
865 func (t *Torrent) publishPieceChange(piece pieceIndex) {
866 t.cl._mu.Defer(func() {
867 cur := t.pieceState(piece)
868 p := &t.pieces[piece]
869 if cur != p.publicPieceState {
870 p.publicPieceState = cur
871 t.pieceStateChanges.Publish(PieceStateChange{
879 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
880 if t.pieceComplete(piece) {
883 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
886 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
887 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
890 func (t *Torrent) readersChanged() {
891 t.updateReaderPieces()
892 t.updateAllPiecePriorities()
895 func (t *Torrent) updateReaderPieces() {
896 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
899 func (t *Torrent) readerPosChanged(from, to pieceRange) {
903 t.updateReaderPieces()
904 // Order the ranges, high and low.
906 if l.begin > h.begin {
910 // Two distinct ranges.
911 t.updatePiecePriorities(l.begin, l.end)
912 t.updatePiecePriorities(h.begin, h.end)
919 t.updatePiecePriorities(l.begin, end)
923 func (t *Torrent) maybeNewConns() {
924 // Tickle the accept routine.
925 t.cl.event.Broadcast()
929 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
930 // t.logger.Printf("piece %d priority changed", piece)
931 for c := range t.conns {
932 if c.updatePiecePriority(piece) {
933 // log.Print("conn piece priority changed")
938 t.publishPieceChange(piece)
941 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
942 p := &t.pieces[piece]
943 newPrio := p.uncachedPriority()
944 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
945 if newPrio == PiecePriorityNone {
946 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
950 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
954 t.piecePriorityChanged(piece)
957 func (t *Torrent) updateAllPiecePriorities() {
958 t.updatePiecePriorities(0, t.numPieces())
961 // Update all piece priorities in one hit. This function should have the same
962 // output as updatePiecePriority, but across all pieces.
963 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
964 for i := begin; i < end; i++ {
965 t.updatePiecePriority(i)
969 // Returns the range of pieces [begin, end) that contains the extent of bytes.
970 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
971 if off >= *t.length {
981 begin = pieceIndex(off / t.info.PieceLength)
982 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
983 if end > pieceIndex(t.info.NumPieces()) {
984 end = pieceIndex(t.info.NumPieces())
989 // Returns true if all iterations complete without breaking. Returns the read
990 // regions for all readers. The reader regions should not be merged as some
991 // callers depend on this method to enumerate readers.
992 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
993 for r := range t.readers {
995 if p.begin >= p.end {
998 if !f(p.begin, p.end) {
1005 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1006 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1008 return PiecePriorityNone
1013 ret := piecePriority(-prio)
1014 if ret == PiecePriorityNone {
1020 func (t *Torrent) pendRequest(req request) {
1021 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1022 t.pieces[req.Index].pendChunkIndex(ci)
1025 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1027 t.cl.event.Broadcast()
1028 if t.pieceComplete(piece) {
1029 t.onPieceCompleted(piece)
1031 t.onIncompletePiece(piece)
1033 t.updatePiecePriority(piece)
1036 func (t *Torrent) numReceivedConns() (ret int) {
1037 for c := range t.conns {
1038 if c.Discovery == PeerSourceIncoming {
1045 func (t *Torrent) maxHalfOpen() int {
1046 // Note that if we somehow exceed the maximum established conns, we want
1047 // the negative value to have an effect.
1048 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1049 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1050 // We want to allow some experimentation with new peers, and to try to
1051 // upset an oversupply of received connections.
1052 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1055 func (t *Torrent) openNewConns() {
1056 defer t.updateWantPeersEvent()
1057 for t.peers.Len() != 0 {
1061 if len(t.halfOpen) >= t.maxHalfOpen() {
1064 p := t.peers.PopMax()
1069 func (t *Torrent) getConnPieceInclination() []int {
1070 _ret := t.connPieceInclinationPool.Get()
1072 pieceInclinationsNew.Add(1)
1073 return rand.Perm(int(t.numPieces()))
1075 pieceInclinationsReused.Add(1)
1076 return *_ret.(*[]int)
1079 func (t *Torrent) putPieceInclination(pi []int) {
1080 t.connPieceInclinationPool.Put(&pi)
1081 pieceInclinationsPut.Add(1)
1084 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1086 uncached := t.pieceCompleteUncached(piece)
1087 cached := p.completion()
1088 changed := cached != uncached
1089 complete := uncached.Complete
1090 p.storageCompletionOk = uncached.Ok
1091 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1092 if complete && len(p.dirtiers) != 0 {
1093 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1096 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).WithValues(debugLogValue).Log(t.logger)
1097 t.pieceCompletionChanged(piece)
1102 // Non-blocking read. Client lock is not required.
1103 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1104 p := &t.pieces[off/t.info.PieceLength]
1105 p.waitNoPendingWrites()
1106 return p.Storage().ReadAt(b, off-p.Info().Offset())
1109 // Returns an error if the metadata was completed, but couldn't be set for
1110 // some reason. Blame it on the last peer to contribute.
1111 func (t *Torrent) maybeCompleteMetadata() error {
1116 if !t.haveAllMetadataPieces() {
1117 // Don't have enough metadata pieces.
1120 err := t.setInfoBytes(t.metadataBytes)
1122 t.invalidateMetadata()
1123 return fmt.Errorf("error setting info bytes: %s", err)
1125 if t.cl.config.Debug {
1126 t.logger.Printf("%s: got metadata from peers", t)
1131 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1132 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1134 now.Add(bitmap.BitIndex(begin))
1135 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1142 func (t *Torrent) needData() bool {
1143 if t.closed.IsSet() {
1149 return t._pendingPieces.Len() != 0
1152 func appendMissingStrings(old, new []string) (ret []string) {
1155 for _, n := range new {
1156 for _, o := range old {
1161 ret = append(ret, n)
1166 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1168 for minNumTiers > len(ret) {
1169 ret = append(ret, nil)
1174 func (t *Torrent) addTrackers(announceList [][]string) {
1175 fullAnnounceList := &t.metainfo.AnnounceList
1176 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1177 for tierIndex, trackerURLs := range announceList {
1178 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1180 t.startMissingTrackerScrapers()
1181 t.updateWantPeersEvent()
1184 // Don't call this before the info is available.
1185 func (t *Torrent) bytesCompleted() int64 {
1189 return t.info.TotalLength() - t.bytesLeft()
1192 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1195 return t.setInfoBytes(b)
1198 // Returns true if connection is removed from torrent.Conns.
1199 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1200 if !c.closed.IsSet() {
1201 panic("connection is not closed")
1202 // There are behaviours prevented by the closed state that will fail
1203 // if the connection has been deleted.
1207 if !t.cl.config.DisablePEX {
1210 torrent.Add("deleted connections", 1)
1211 c.deleteAllRequests()
1212 if len(t.conns) == 0 {
1213 t.assertNoPendingRequests()
1218 func (t *Torrent) assertNoPendingRequests() {
1219 if len(t.pendingRequests) != 0 {
1220 panic(t.pendingRequests)
1222 //if len(t.lastRequested) != 0 {
1223 // panic(t.lastRequested)
1227 func (t *Torrent) dropConnection(c *PeerConn) {
1228 t.cl.event.Broadcast()
1230 if t.deleteConnection(c) {
1235 func (t *Torrent) wantPeers() bool {
1236 if t.closed.IsSet() {
1239 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1242 return t.needData() || t.seeding()
1245 func (t *Torrent) updateWantPeersEvent() {
1247 t.wantPeersEvent.Set()
1249 t.wantPeersEvent.Clear()
1253 // Returns whether the client should make effort to seed the torrent.
1254 func (t *Torrent) seeding() bool {
1256 if t.closed.IsSet() {
1259 if cl.config.NoUpload {
1262 if !cl.config.Seed {
1265 if cl.config.DisableAggressiveUpload && t.needData() {
1271 func (t *Torrent) startScrapingTracker(_url string) {
1275 u, err := url.Parse(_url)
1277 // URLs with a leading '*' appear to be a uTorrent convention to
1278 // disable trackers.
1280 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1284 if u.Scheme == "udp" {
1286 t.startScrapingTracker(u.String())
1288 t.startScrapingTracker(u.String())
1291 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1294 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1297 if _, ok := t.trackerAnnouncers[_url]; ok {
1300 newAnnouncer := &trackerScraper{
1304 if t.trackerAnnouncers == nil {
1305 t.trackerAnnouncers = make(map[string]*trackerScraper)
1307 t.trackerAnnouncers[_url] = newAnnouncer
1308 go newAnnouncer.Run()
1311 // Adds and starts tracker scrapers for tracker URLs that aren't already
1313 func (t *Torrent) startMissingTrackerScrapers() {
1314 if t.cl.config.DisableTrackers {
1317 t.startScrapingTracker(t.metainfo.Announce)
1318 for _, tier := range t.metainfo.AnnounceList {
1319 for _, url := range tier {
1320 t.startScrapingTracker(url)
1325 // Returns an AnnounceRequest with fields filled out to defaults and current
1327 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1328 // Note that IPAddress is not set. It's set for UDP inside the tracker
1329 // code, since it's dependent on the network in use.
1330 return tracker.AnnounceRequest{
1333 Port: uint16(t.cl.incomingPeerPort()),
1334 PeerId: t.cl.peerID,
1335 InfoHash: t.infoHash,
1336 Key: t.cl.announceKey(),
1338 // The following are vaguely described in BEP 3.
1340 Left: t.bytesLeftAnnounce(),
1341 Uploaded: t.stats.BytesWrittenData.Int64(),
1342 // There's no mention of wasted or unwanted download in the BEP.
1343 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1347 // Adds peers revealed in an announce until the announce ends, or we have
1349 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1351 for v := range pvs {
1353 for _, cp := range v.Peers {
1355 // Can't do anything with this.
1359 Addr: ipPortAddr{cp.IP, cp.Port},
1360 Source: PeerSourceDhtGetPeers,
1367 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1368 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1372 go t.consumeDhtAnnouncePeers(ps.Peers())
1374 case <-t.closed.LockedChan(t.cl.locker()):
1375 case <-time.After(5 * time.Minute):
1381 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1385 case <-t.closed.LockedChan(cl.locker()):
1387 case <-t.wantPeersEvent.LockedChan(cl.locker()):
1392 err := t.announceToDht(true, s)
1394 t.logger.WithValues(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1399 func (t *Torrent) addPeers(peers []Peer) {
1400 for _, p := range peers {
1405 // The returned TorrentStats may require alignment in memory. See
1406 // https://github.com/anacrolix/torrent/issues/383.
1407 func (t *Torrent) Stats() TorrentStats {
1409 defer t.cl.rUnlock()
1410 return t.statsLocked()
1413 func (t *Torrent) statsLocked() (ret TorrentStats) {
1414 ret.ActivePeers = len(t.conns)
1415 ret.HalfOpenPeers = len(t.halfOpen)
1416 ret.PendingPeers = t.peers.Len()
1417 ret.TotalPeers = t.numTotalPeers()
1418 ret.ConnectedSeeders = 0
1419 for c := range t.conns {
1420 if all, ok := c.peerHasAllPieces(); all && ok {
1421 ret.ConnectedSeeders++
1424 ret.ConnStats = t.stats.Copy()
1428 // The total number of peers in the torrent.
1429 func (t *Torrent) numTotalPeers() int {
1430 peers := make(map[string]struct{})
1431 for conn := range t.conns {
1432 ra := conn.conn.RemoteAddr()
1434 // It's been closed and doesn't support RemoteAddr.
1437 peers[ra.String()] = struct{}{}
1439 for addr := range t.halfOpen {
1440 peers[addr] = struct{}{}
1442 t.peers.Each(func(peer Peer) {
1443 peers[peer.Addr.String()] = struct{}{}
1448 // Reconcile bytes transferred before connection was associated with a
1450 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1451 if c._stats != (ConnStats{
1452 // Handshakes should only increment these fields:
1453 BytesWritten: c._stats.BytesWritten,
1454 BytesRead: c._stats.BytesRead,
1458 c.postHandshakeStats(func(cs *ConnStats) {
1459 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1460 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1462 c.reconciledHandshakeStats = true
1465 // Returns true if the connection is added.
1466 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1469 torrent.Add("added connections", 1)
1472 if t.closed.IsSet() {
1473 return errors.New("torrent closed")
1475 for c0 := range t.conns {
1476 if c.PeerID != c0.PeerID {
1479 if !t.cl.config.dropDuplicatePeerIds {
1482 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1484 t.deleteConnection(c0)
1486 return errors.New("existing connection preferred")
1489 if len(t.conns) >= t.maxEstablishedConns {
1490 c := t.worstBadConn()
1492 return errors.New("don't want conns")
1495 t.deleteConnection(c)
1497 if len(t.conns) >= t.maxEstablishedConns {
1500 t.conns[c] = struct{}{}
1501 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1502 t.pex.Add(c) // as no further extended handshake expected
1507 func (t *Torrent) wantConns() bool {
1508 if !t.networkingEnabled {
1511 if t.closed.IsSet() {
1514 if !t.seeding() && !t.needData() {
1517 if len(t.conns) < t.maxEstablishedConns {
1520 return t.worstBadConn() != nil
1523 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1526 oldMax = t.maxEstablishedConns
1527 t.maxEstablishedConns = max
1528 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1529 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1530 t.dropConnection(wcs.Pop().(*PeerConn))
1536 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1537 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).WithValues(debugLogValue))
1540 t.cl.event.Broadcast()
1541 if t.closed.IsSet() {
1545 // Don't score the first time a piece is hashed, it could be an initial check.
1546 if p.storageCompletionOk {
1548 pieceHashedCorrect.Add(1)
1550 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1551 pieceHashedNotCorrect.Add(1)
1556 if len(p.dirtiers) != 0 {
1557 // Don't increment stats above connection-level for every involved connection.
1558 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1560 for c := range p.dirtiers {
1561 c._stats.incrementPiecesDirtiedGood()
1563 t.clearPieceTouchers(piece)
1564 err := p.Storage().MarkComplete()
1566 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1568 t.pendAllChunkSpecs(piece)
1570 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1571 // Peers contributed to all the data for this piece hash failure, and the failure was
1572 // not due to errors in the storage (such as data being dropped in a cache).
1574 // Increment Torrent and above stats, and then specific connections.
1575 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1576 for c := range p.dirtiers {
1577 // Y u do dis peer?!
1578 c.stats().incrementPiecesDirtiedBad()
1581 bannableTouchers := make([]*PeerConn, 0, len(p.dirtiers))
1582 for c := range p.dirtiers {
1584 bannableTouchers = append(bannableTouchers, c)
1587 t.clearPieceTouchers(piece)
1588 slices.Sort(bannableTouchers, connLessTrusted)
1590 if t.cl.config.Debug {
1592 "bannable conns by trust for piece %d: %v",
1594 func() (ret []connectionTrust) {
1595 for _, c := range bannableTouchers {
1596 ret = append(ret, c.trust())
1603 if len(bannableTouchers) >= 1 {
1604 c := bannableTouchers[0]
1605 t.cl.banPeerIP(c.remoteIp())
1609 t.onIncompletePiece(piece)
1610 p.Storage().MarkNotComplete()
1612 t.updatePieceCompletion(piece)
1615 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1616 // TODO: Make faster
1617 for cn := range t.conns {
1622 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1623 t.pendAllChunkSpecs(piece)
1624 t.cancelRequestsForPiece(piece)
1625 for conn := range t.conns {
1630 // Called when a piece is found to be not complete.
1631 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1632 if t.pieceAllDirty(piece) {
1633 t.pendAllChunkSpecs(piece)
1635 if !t.wantPieceIndex(piece) {
1636 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1639 // We could drop any connections that we told we have a piece that we
1640 // don't here. But there's a test failure, and it seems clients don't care
1641 // if you request pieces that you already claim to have. Pruning bad
1642 // connections might just remove any connections that aren't treating us
1643 // favourably anyway.
1645 // for c := range t.conns {
1646 // if c.sentHave(piece) {
1650 for conn := range t.conns {
1651 if conn.peerHasPiece(piece) {
1652 conn.updateRequests()
1657 func (t *Torrent) tryCreateMorePieceHashers() {
1658 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1662 func (t *Torrent) tryCreatePieceHasher() bool {
1663 if t.storage == nil {
1666 pi, ok := t.getPieceToHash()
1671 t.piecesQueuedForHash.Remove(pi)
1673 t.publishPieceChange(pi)
1674 t.updatePiecePriority(pi)
1675 t.storageLock.RLock()
1676 t.activePieceHashes++
1677 go t.pieceHasher(pi)
1681 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1682 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1683 if t.piece(i).hashing {
1693 func (t *Torrent) pieceHasher(index pieceIndex) {
1695 sum, copyErr := t.hashPiece(index)
1696 correct := sum == *p.hash
1700 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1702 t.storageLock.RUnlock()
1706 t.updatePiecePriority(index)
1707 t.pieceHashed(index, correct, copyErr)
1708 t.publishPieceChange(index)
1709 t.activePieceHashes--
1710 t.tryCreateMorePieceHashers()
1713 // Return the connections that touched a piece, and clear the entries while doing it.
1714 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1716 for c := range p.dirtiers {
1717 delete(c.peerTouchedPieces, pi)
1718 delete(p.dirtiers, c)
1722 func (t *Torrent) connsAsSlice() (ret []*PeerConn) {
1723 for c := range t.conns {
1724 ret = append(ret, c)
1729 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1730 piece := t.piece(pieceIndex)
1731 if piece.queuedForHash() {
1734 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1735 t.publishPieceChange(pieceIndex)
1736 t.updatePiecePriority(pieceIndex)
1737 t.tryCreateMorePieceHashers()
1740 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1741 // before the Info is available.
1742 func (t *Torrent) VerifyData() {
1743 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1744 t.Piece(i).VerifyData()
1748 // Start the process of connecting to the given peer for the given torrent if appropriate.
1749 func (t *Torrent) initiateConn(peer Peer) {
1750 if peer.Id == t.cl.peerID {
1754 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1758 if t.addrActive(addr.String()) {
1761 t.halfOpen[addr.String()] = peer
1762 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1765 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1766 // quickly make one Client visible to the Torrent of another Client.
1767 func (t *Torrent) AddClientPeer(cl *Client) {
1768 t.AddPeers(func() (ps []Peer) {
1769 for _, la := range cl.ListenAddrs() {
1770 ps = append(ps, Peer{
1779 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1781 func (t *Torrent) allStats(f func(*ConnStats)) {
1786 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1787 return t.pieces[i].hashing
1790 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1791 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1794 func (t *Torrent) dialTimeout() time.Duration {
1795 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1798 func (t *Torrent) piece(i int) *Piece {
1802 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1806 type torrentRequestStrategyCallbacks struct {
1810 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
1811 torrent.Add("request timeouts", 1)
1813 defer cb.t.cl.unlock()
1814 for cn := range cb.t.conns {
1815 if cn.peerHasPiece(pieceIndex(r.Index)) {
1822 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
1823 return torrentRequestStrategyCallbacks{t}
1826 func (t *Torrent) onWriteChunkErr(err error) {
1827 if t.userOnWriteChunkErr != nil {
1828 go t.userOnWriteChunkErr(err)
1831 t.disallowDataDownloadLocked()
1834 func (t *Torrent) DisallowDataDownload() {
1837 t.disallowDataDownloadLocked()
1840 func (t *Torrent) disallowDataDownloadLocked() {
1841 log.Printf("disallowing data download")
1842 t.dataDownloadDisallowed = true
1843 for c := range t.conns {
1848 func (t *Torrent) AllowDataDownload() {
1851 log.Printf("AllowDataDownload")
1852 t.dataDownloadDisallowed = false
1853 for c := range t.conns {
1859 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
1862 t.userOnWriteChunkErr = f