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
136 func (t *Torrent) numConns() int {
140 func (t *Torrent) numReaders() int {
141 return len(t.readers)
144 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
145 return t._readerNowPieces
148 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
149 return t._readerReadaheadPieces
152 func (t *Torrent) ignorePieces() bitmap.Bitmap {
153 ret := t._completedPieces.Copy()
154 ret.Union(t.piecesQueuedForHash)
155 for i := 0; i < t.numPieces(); i++ {
156 if t.piece(i).hashing {
163 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
164 return &t._pendingPieces
167 func (t *Torrent) tickleReaders() {
168 t.cl.event.Broadcast()
171 // Returns a channel that is closed when the Torrent is closed.
172 func (t *Torrent) Closed() <-chan struct{} {
173 return t.closed.LockedChan(t.cl.locker())
176 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
177 // pending, and half-open peers.
178 func (t *Torrent) KnownSwarm() (ks []Peer) {
179 // Add pending peers to the list
180 t.peers.Each(func(peer Peer) {
181 ks = append(ks, peer)
184 // Add half-open peers to the list
185 for _, peer := range t.halfOpen {
186 ks = append(ks, peer)
189 // Add active peers to the list
190 for conn := range t.conns {
192 ks = append(ks, Peer{
194 Addr: conn.remoteAddr,
195 Source: conn.Discovery,
196 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
197 // > But if we're not connected to them with an encrypted connection, I couldn't say
198 // > what's appropriate. We can carry forward the SupportsEncryption value as we
199 // > received it from trackers/DHT/PEX, or just use the encryption state for the
200 // > connection. It's probably easiest to do the latter for now.
201 // https://github.com/anacrolix/torrent/pull/188
202 SupportsEncryption: conn.headerEncrypted,
209 func (t *Torrent) setChunkSize(size pp.Integer) {
211 t.chunkPool = &sync.Pool{
212 New: func() interface{} {
213 b := make([]byte, size)
219 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
220 return t._completedPieces.Get(bitmap.BitIndex(piece))
223 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
224 return t.pieces[piece].Storage().Completion()
227 // There's a connection to that address already.
228 func (t *Torrent) addrActive(addr string) bool {
229 if _, ok := t.halfOpen[addr]; ok {
232 for c := range t.conns {
234 if ra.String() == addr {
241 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
242 ret = make([]*PeerConn, 0, len(t.conns))
243 for c := range t.conns {
244 if !c.closed.IsSet() {
251 func (t *Torrent) addPeer(p Peer) {
253 peersAddedBySource.Add(string(p.Source), 1)
254 if t.closed.IsSet() {
257 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
258 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
259 torrent.Add("peers not added because of bad addr", 1)
264 torrent.Add("peers replaced", 1)
267 for t.peers.Len() > cl.config.TorrentPeersHighWater {
268 _, ok := t.peers.DeleteMin()
270 torrent.Add("excess reserve peers discarded", 1)
275 func (t *Torrent) invalidateMetadata() {
276 for i := range t.metadataCompletedChunks {
277 t.metadataCompletedChunks[i] = false
284 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
288 if index >= len(t.metadataCompletedChunks) {
289 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
292 copy(t.metadataBytes[(1<<14)*index:], data)
293 t.metadataCompletedChunks[index] = true
296 func (t *Torrent) metadataPieceCount() int {
297 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
300 func (t *Torrent) haveMetadataPiece(piece int) bool {
302 return (1<<14)*piece < len(t.metadataBytes)
304 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
308 func (t *Torrent) metadataSize() int {
309 return len(t.metadataBytes)
312 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
313 for i := 0; i < len(info.Pieces); i += sha1.Size {
314 ret = append(ret, info.Pieces[i:i+sha1.Size])
319 func (t *Torrent) makePieces() {
320 hashes := infoPieceHashes(t.info)
321 t.pieces = make([]Piece, len(hashes))
322 for i, hash := range hashes {
323 piece := &t.pieces[i]
325 piece.index = pieceIndex(i)
326 piece.noPendingWrites.L = &piece.pendingWritesMutex
327 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
329 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
330 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
331 piece.files = files[beginFile:endFile]
335 // Returns the index of the first file containing the piece. files must be
336 // ordered by offset.
337 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
338 for i, f := range files {
339 if f.offset+f.length > pieceOffset {
346 // Returns the index after the last file containing the piece. files must be
347 // ordered by offset.
348 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
349 for i, f := range files {
350 if f.offset+f.length >= pieceEndOffset {
357 func (t *Torrent) cacheLength() {
359 for _, f := range t.info.UpvertedFiles() {
365 func (t *Torrent) setInfo(info *metainfo.Info) error {
366 if err := validateInfo(info); err != nil {
367 return fmt.Errorf("bad info: %s", err)
369 if t.storageOpener != nil {
371 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
373 return fmt.Errorf("error opening torrent storage: %s", err)
379 t.displayName = "" // Save a few bytes lol.
386 func (t *Torrent) onSetInfo() {
387 for conn := range t.conns {
388 if err := conn.setNumPieces(t.numPieces()); err != nil {
389 t.logger.Printf("closing connection: %s", err)
393 for i := range t.pieces {
394 t.updatePieceCompletion(pieceIndex(i))
396 if !p.storageCompletionOk {
397 // t.logger.Printf("piece %s completion unknown, queueing check", p)
398 t.queuePieceCheck(pieceIndex(i))
401 t.cl.event.Broadcast()
403 t.updateWantPeersEvent()
404 t.pendingRequests = make(map[request]int)
405 t.tryCreateMorePieceHashers()
408 // Called when metadata for a torrent becomes available.
409 func (t *Torrent) setInfoBytes(b []byte) error {
410 if metainfo.HashBytes(b) != t.infoHash {
411 return errors.New("info bytes have wrong hash")
413 var info metainfo.Info
414 if err := bencode.Unmarshal(b, &info); err != nil {
415 return fmt.Errorf("error unmarshalling info bytes: %s", err)
417 if err := t.setInfo(&info); err != nil {
421 t.metadataCompletedChunks = nil
426 func (t *Torrent) haveAllMetadataPieces() bool {
430 if t.metadataCompletedChunks == nil {
433 for _, have := range t.metadataCompletedChunks {
441 // TODO: Propagate errors to disconnect peer.
442 func (t *Torrent) setMetadataSize(bytes int) (err error) {
444 // We already know the correct metadata size.
447 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
448 return errors.New("bad size")
450 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
453 t.metadataBytes = make([]byte, bytes)
454 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
455 t.metadataChanged.Broadcast()
456 for c := range t.conns {
457 c.requestPendingMetadata()
462 // The current working name for the torrent. Either the name in the info dict,
463 // or a display name given such as by the dn value in a magnet link, or "".
464 func (t *Torrent) name() string {
466 defer t.nameMu.RUnlock()
473 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
474 p := &t.pieces[index]
475 ret.Priority = t.piecePriority(index)
476 ret.Completion = p.completion()
477 if p.queuedForHash() || p.hashing {
480 if !ret.Complete && t.piecePartiallyDownloaded(index) {
486 func (t *Torrent) metadataPieceSize(piece int) int {
487 return metadataPieceSize(len(t.metadataBytes), piece)
490 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
496 d["total_size"] = len(t.metadataBytes)
498 p := bencode.MustMarshal(d)
501 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
502 ExtendedPayload: append(p, data...),
506 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
507 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
508 ret = append(ret, PieceStateRun{
509 PieceState: el.(PieceState),
513 for index := range t.pieces {
514 rle.Append(t.pieceState(pieceIndex(index)), 1)
520 // Produces a small string representing a PieceStateRun.
521 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
522 ret = fmt.Sprintf("%d", psr.Length)
523 ret += func() string {
524 switch psr.Priority {
525 case PiecePriorityNext:
527 case PiecePriorityNormal:
529 case PiecePriorityReadahead:
531 case PiecePriorityNow:
533 case PiecePriorityHigh:
554 func (t *Torrent) writeStatus(w io.Writer) {
555 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
556 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
558 fmt.Fprintf(w, "Metadata have: ")
559 for _, h := range t.metadataCompletedChunks {
560 fmt.Fprintf(w, "%c", func() rune {
570 fmt.Fprintf(w, "Piece length: %s\n", func() string {
572 return fmt.Sprint(t.usualPieceSize())
578 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
579 fmt.Fprint(w, "Piece States:")
580 for _, psr := range t.pieceStateRuns() {
582 w.Write([]byte(pieceStateRunStatusChars(psr)))
586 fmt.Fprintf(w, "Reader Pieces:")
587 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
588 fmt.Fprintf(w, " %d:%d", begin, end)
593 fmt.Fprintf(w, "Enabled trackers:\n")
595 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
596 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
597 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
600 var luns, runs url.URL = lu, ru
603 var ml missinggo.MultiLess
604 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
605 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
607 }).([]*trackerScraper) {
608 fmt.Fprintf(tw, " %s\n", ta.statusLine())
613 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
615 spew.NewDefaultConfig()
616 spew.Fdump(w, t.statsLocked())
618 conns := t.connsAsSlice()
619 slices.Sort(conns, worseConn)
620 for i, c := range conns {
621 fmt.Fprintf(w, "%2d. ", i+1)
626 func (t *Torrent) haveInfo() bool {
630 // Returns a run-time generated MetaInfo that includes the info bytes and
631 // announce-list as currently known to the client.
632 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
633 return metainfo.MetaInfo{
634 CreationDate: time.Now().Unix(),
635 Comment: "dynamic metainfo from client",
636 CreatedBy: "go.torrent",
637 AnnounceList: t.metainfo.UpvertedAnnounceList(),
638 InfoBytes: func() []byte {
640 return t.metadataBytes
648 func (t *Torrent) BytesMissing() int64 {
651 return t.bytesMissingLocked()
654 func (t *Torrent) bytesMissingLocked() int64 {
658 func (t *Torrent) bytesLeft() (left int64) {
659 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
660 p := &t.pieces[piece]
661 left += int64(p.length() - p.numDirtyBytes())
667 // Bytes left to give in tracker announces.
668 func (t *Torrent) bytesLeftAnnounce() int64 {
676 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
677 if t.pieceComplete(piece) {
680 if t.pieceAllDirty(piece) {
683 return t.pieces[piece].hasDirtyChunks()
686 func (t *Torrent) usualPieceSize() int {
687 return int(t.info.PieceLength)
690 func (t *Torrent) numPieces() pieceIndex {
691 return pieceIndex(t.info.NumPieces())
694 func (t *Torrent) numPiecesCompleted() (num int) {
695 return t._completedPieces.Len()
698 func (t *Torrent) close() (err error) {
701 if t.storage != nil {
704 t.storageLock.Unlock()
706 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 torrent.Add("deleted connections", 1)
1208 c.deleteAllRequests()
1209 if len(t.conns) == 0 {
1210 t.assertNoPendingRequests()
1215 func (t *Torrent) assertNoPendingRequests() {
1216 if len(t.pendingRequests) != 0 {
1217 panic(t.pendingRequests)
1219 //if len(t.lastRequested) != 0 {
1220 // panic(t.lastRequested)
1224 func (t *Torrent) dropConnection(c *PeerConn) {
1225 t.cl.event.Broadcast()
1227 if t.deleteConnection(c) {
1232 func (t *Torrent) wantPeers() bool {
1233 if t.closed.IsSet() {
1236 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1239 return t.needData() || t.seeding()
1242 func (t *Torrent) updateWantPeersEvent() {
1244 t.wantPeersEvent.Set()
1246 t.wantPeersEvent.Clear()
1250 // Returns whether the client should make effort to seed the torrent.
1251 func (t *Torrent) seeding() bool {
1253 if t.closed.IsSet() {
1256 if cl.config.NoUpload {
1259 if !cl.config.Seed {
1262 if cl.config.DisableAggressiveUpload && t.needData() {
1268 func (t *Torrent) startScrapingTracker(_url string) {
1272 u, err := url.Parse(_url)
1274 // URLs with a leading '*' appear to be a uTorrent convention to
1275 // disable trackers.
1277 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1281 if u.Scheme == "udp" {
1283 t.startScrapingTracker(u.String())
1285 t.startScrapingTracker(u.String())
1288 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1291 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1294 if _, ok := t.trackerAnnouncers[_url]; ok {
1297 newAnnouncer := &trackerScraper{
1301 if t.trackerAnnouncers == nil {
1302 t.trackerAnnouncers = make(map[string]*trackerScraper)
1304 t.trackerAnnouncers[_url] = newAnnouncer
1305 go newAnnouncer.Run()
1308 // Adds and starts tracker scrapers for tracker URLs that aren't already
1310 func (t *Torrent) startMissingTrackerScrapers() {
1311 if t.cl.config.DisableTrackers {
1314 t.startScrapingTracker(t.metainfo.Announce)
1315 for _, tier := range t.metainfo.AnnounceList {
1316 for _, url := range tier {
1317 t.startScrapingTracker(url)
1322 // Returns an AnnounceRequest with fields filled out to defaults and current
1324 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1325 // Note that IPAddress is not set. It's set for UDP inside the tracker
1326 // code, since it's dependent on the network in use.
1327 return tracker.AnnounceRequest{
1330 Port: uint16(t.cl.incomingPeerPort()),
1331 PeerId: t.cl.peerID,
1332 InfoHash: t.infoHash,
1333 Key: t.cl.announceKey(),
1335 // The following are vaguely described in BEP 3.
1337 Left: t.bytesLeftAnnounce(),
1338 Uploaded: t.stats.BytesWrittenData.Int64(),
1339 // There's no mention of wasted or unwanted download in the BEP.
1340 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1344 // Adds peers revealed in an announce until the announce ends, or we have
1346 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1348 for v := range pvs {
1350 for _, cp := range v.Peers {
1352 // Can't do anything with this.
1356 Addr: ipPortAddr{cp.IP, cp.Port},
1357 Source: PeerSourceDhtGetPeers,
1364 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1365 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1369 go t.consumeDhtAnnouncePeers(ps.Peers())
1371 case <-t.closed.LockedChan(t.cl.locker()):
1372 case <-time.After(5 * time.Minute):
1378 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1382 case <-t.closed.LockedChan(cl.locker()):
1384 case <-t.wantPeersEvent.LockedChan(cl.locker()):
1389 err := t.announceToDht(true, s)
1391 t.logger.Printf("error announcing %q to DHT: %s", t, err)
1396 func (t *Torrent) addPeers(peers []Peer) {
1397 for _, p := range peers {
1402 func (t *Torrent) Stats() TorrentStats {
1404 defer t.cl.rUnlock()
1405 return t.statsLocked()
1408 func (t *Torrent) statsLocked() (ret TorrentStats) {
1409 ret.ActivePeers = len(t.conns)
1410 ret.HalfOpenPeers = len(t.halfOpen)
1411 ret.PendingPeers = t.peers.Len()
1412 ret.TotalPeers = t.numTotalPeers()
1413 ret.ConnectedSeeders = 0
1414 for c := range t.conns {
1415 if all, ok := c.peerHasAllPieces(); all && ok {
1416 ret.ConnectedSeeders++
1419 ret.ConnStats = t.stats.Copy()
1423 // The total number of peers in the torrent.
1424 func (t *Torrent) numTotalPeers() int {
1425 peers := make(map[string]struct{})
1426 for conn := range t.conns {
1427 ra := conn.conn.RemoteAddr()
1429 // It's been closed and doesn't support RemoteAddr.
1432 peers[ra.String()] = struct{}{}
1434 for addr := range t.halfOpen {
1435 peers[addr] = struct{}{}
1437 t.peers.Each(func(peer Peer) {
1438 peers[peer.Addr.String()] = struct{}{}
1443 // Reconcile bytes transferred before connection was associated with a
1445 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1446 if c._stats != (ConnStats{
1447 // Handshakes should only increment these fields:
1448 BytesWritten: c._stats.BytesWritten,
1449 BytesRead: c._stats.BytesRead,
1453 c.postHandshakeStats(func(cs *ConnStats) {
1454 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1455 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1457 c.reconciledHandshakeStats = true
1460 // Returns true if the connection is added.
1461 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1464 torrent.Add("added connections", 1)
1467 if t.closed.IsSet() {
1468 return errors.New("torrent closed")
1470 for c0 := range t.conns {
1471 if c.PeerID != c0.PeerID {
1474 if !t.cl.config.dropDuplicatePeerIds {
1477 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1479 t.deleteConnection(c0)
1481 return errors.New("existing connection preferred")
1484 if len(t.conns) >= t.maxEstablishedConns {
1485 c := t.worstBadConn()
1487 return errors.New("don't want conns")
1490 t.deleteConnection(c)
1492 if len(t.conns) >= t.maxEstablishedConns {
1495 t.conns[c] = struct{}{}
1499 func (t *Torrent) wantConns() bool {
1500 if !t.networkingEnabled {
1503 if t.closed.IsSet() {
1506 if !t.seeding() && !t.needData() {
1509 if len(t.conns) < t.maxEstablishedConns {
1512 return t.worstBadConn() != nil
1515 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1518 oldMax = t.maxEstablishedConns
1519 t.maxEstablishedConns = max
1520 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1521 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1522 t.dropConnection(wcs.Pop().(*PeerConn))
1528 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1529 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).WithValues(debugLogValue))
1532 t.cl.event.Broadcast()
1533 if t.closed.IsSet() {
1537 // Don't score the first time a piece is hashed, it could be an initial check.
1538 if p.storageCompletionOk {
1540 pieceHashedCorrect.Add(1)
1542 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1543 pieceHashedNotCorrect.Add(1)
1548 if len(p.dirtiers) != 0 {
1549 // Don't increment stats above connection-level for every involved connection.
1550 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1552 for c := range p.dirtiers {
1553 c._stats.incrementPiecesDirtiedGood()
1555 t.clearPieceTouchers(piece)
1556 err := p.Storage().MarkComplete()
1558 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1560 t.pendAllChunkSpecs(piece)
1562 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1563 // Peers contributed to all the data for this piece hash failure, and the failure was
1564 // not due to errors in the storage (such as data being dropped in a cache).
1566 // Increment Torrent and above stats, and then specific connections.
1567 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1568 for c := range p.dirtiers {
1569 // Y u do dis peer?!
1570 c.stats().incrementPiecesDirtiedBad()
1573 bannableTouchers := make([]*PeerConn, 0, len(p.dirtiers))
1574 for c := range p.dirtiers {
1576 bannableTouchers = append(bannableTouchers, c)
1579 t.clearPieceTouchers(piece)
1580 slices.Sort(bannableTouchers, connLessTrusted)
1582 if t.cl.config.Debug {
1584 "bannable conns by trust for piece %d: %v",
1586 func() (ret []connectionTrust) {
1587 for _, c := range bannableTouchers {
1588 ret = append(ret, c.trust())
1595 if len(bannableTouchers) >= 1 {
1596 c := bannableTouchers[0]
1597 t.cl.banPeerIP(c.remoteIp())
1601 t.onIncompletePiece(piece)
1602 p.Storage().MarkNotComplete()
1604 t.updatePieceCompletion(piece)
1607 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1608 // TODO: Make faster
1609 for cn := range t.conns {
1614 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1615 t.pendAllChunkSpecs(piece)
1616 t.cancelRequestsForPiece(piece)
1617 for conn := range t.conns {
1622 // Called when a piece is found to be not complete.
1623 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1624 if t.pieceAllDirty(piece) {
1625 t.pendAllChunkSpecs(piece)
1627 if !t.wantPieceIndex(piece) {
1628 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1631 // We could drop any connections that we told we have a piece that we
1632 // don't here. But there's a test failure, and it seems clients don't care
1633 // if you request pieces that you already claim to have. Pruning bad
1634 // connections might just remove any connections that aren't treating us
1635 // favourably anyway.
1637 // for c := range t.conns {
1638 // if c.sentHave(piece) {
1642 for conn := range t.conns {
1643 if conn.peerHasPiece(piece) {
1644 conn.updateRequests()
1649 func (t *Torrent) tryCreateMorePieceHashers() {
1650 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1654 func (t *Torrent) tryCreatePieceHasher() bool {
1655 if t.storage == nil {
1658 pi, ok := t.getPieceToHash()
1663 t.piecesQueuedForHash.Remove(pi)
1665 t.publishPieceChange(pi)
1666 t.updatePiecePriority(pi)
1667 t.storageLock.RLock()
1668 t.activePieceHashes++
1669 go t.pieceHasher(pi)
1673 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1674 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1675 if t.piece(i).hashing {
1685 func (t *Torrent) pieceHasher(index pieceIndex) {
1687 sum, copyErr := t.hashPiece(index)
1688 correct := sum == *p.hash
1690 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1692 t.storageLock.RUnlock()
1696 t.updatePiecePriority(index)
1697 t.pieceHashed(index, correct, copyErr)
1698 t.publishPieceChange(index)
1699 t.activePieceHashes--
1700 t.tryCreateMorePieceHashers()
1703 // Return the connections that touched a piece, and clear the entries while doing it.
1704 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1706 for c := range p.dirtiers {
1707 delete(c.peerTouchedPieces, pi)
1708 delete(p.dirtiers, c)
1712 func (t *Torrent) connsAsSlice() (ret []*PeerConn) {
1713 for c := range t.conns {
1714 ret = append(ret, c)
1719 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1720 piece := t.piece(pieceIndex)
1721 if piece.queuedForHash() {
1724 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1725 t.publishPieceChange(pieceIndex)
1726 t.updatePiecePriority(pieceIndex)
1727 t.tryCreateMorePieceHashers()
1730 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1731 // before the Info is available.
1732 func (t *Torrent) VerifyData() {
1733 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1734 t.Piece(i).VerifyData()
1738 // Start the process of connecting to the given peer for the given torrent if appropriate.
1739 func (t *Torrent) initiateConn(peer Peer) {
1740 if peer.Id == t.cl.peerID {
1744 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1748 if t.addrActive(addr.String()) {
1751 t.halfOpen[addr.String()] = peer
1752 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1755 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1756 // quickly make one Client visible to the Torrent of another Client.
1757 func (t *Torrent) AddClientPeer(cl *Client) {
1758 t.AddPeers(func() (ps []Peer) {
1759 for _, la := range cl.ListenAddrs() {
1760 ps = append(ps, Peer{
1769 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1771 func (t *Torrent) allStats(f func(*ConnStats)) {
1776 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1777 return t.pieces[i].hashing
1780 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1781 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1784 func (t *Torrent) dialTimeout() time.Duration {
1785 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1788 func (t *Torrent) piece(i int) *Piece {
1792 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1796 type torrentRequestStrategyCallbacks struct {
1800 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
1801 torrent.Add("request timeouts", 1)
1803 defer cb.t.cl.unlock()
1804 for cn := range cb.t.conns {
1805 if cn.peerHasPiece(pieceIndex(r.Index)) {
1812 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
1813 return torrentRequestStrategyCallbacks{t}
1816 func (t *Torrent) onWriteChunkErr(err error) {
1817 if t.userOnWriteChunkErr != nil {
1818 go t.userOnWriteChunkErr(err)
1821 t.disallowDataDownloadLocked()
1824 func (t *Torrent) DisallowDataDownload() {
1827 t.disallowDataDownloadLocked()
1830 func (t *Torrent) disallowDataDownloadLocked() {
1831 log.Printf("disallowing data download")
1832 t.dataDownloadDisallowed = true
1833 for c := range t.conns {
1838 func (t *Torrent) AllowDataDownload() {
1841 log.Printf("AllowDataDownload")
1842 t.dataDownloadDisallowed = false
1843 for c := range t.conns {
1849 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
1852 t.userOnWriteChunkErr = f