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 PieceStateRuns) {
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 (psr PieceStateRun) String() (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.Fprintf(w, "Piece States: %s", t.pieceStateRuns())
582 fmt.Fprintf(w, "Reader Pieces:")
583 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
584 fmt.Fprintf(w, " %d:%d", begin, end)
589 fmt.Fprintf(w, "Enabled trackers:\n")
591 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
592 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
593 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
596 var luns, runs url.URL = lu, ru
599 var ml missinggo.MultiLess
600 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
601 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
603 }).([]*trackerScraper) {
604 fmt.Fprintf(tw, " %s\n", ta.statusLine())
609 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
611 spew.NewDefaultConfig()
612 spew.Fdump(w, t.statsLocked())
614 conns := t.connsAsSlice()
615 slices.Sort(conns, worseConn)
616 for i, c := range conns {
617 fmt.Fprintf(w, "%2d. ", i+1)
622 func (t *Torrent) haveInfo() bool {
626 // Returns a run-time generated MetaInfo that includes the info bytes and
627 // announce-list as currently known to the client.
628 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
629 return metainfo.MetaInfo{
630 CreationDate: time.Now().Unix(),
631 Comment: "dynamic metainfo from client",
632 CreatedBy: "go.torrent",
633 AnnounceList: t.metainfo.UpvertedAnnounceList(),
634 InfoBytes: func() []byte {
636 return t.metadataBytes
644 func (t *Torrent) BytesMissing() int64 {
647 return t.bytesMissingLocked()
650 func (t *Torrent) bytesMissingLocked() int64 {
654 func (t *Torrent) bytesLeft() (left int64) {
655 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
656 p := &t.pieces[piece]
657 left += int64(p.length() - p.numDirtyBytes())
663 // Bytes left to give in tracker announces.
664 func (t *Torrent) bytesLeftAnnounce() int64 {
672 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
673 if t.pieceComplete(piece) {
676 if t.pieceAllDirty(piece) {
679 return t.pieces[piece].hasDirtyChunks()
682 func (t *Torrent) usualPieceSize() int {
683 return int(t.info.PieceLength)
686 func (t *Torrent) numPieces() pieceIndex {
687 return pieceIndex(t.info.NumPieces())
690 func (t *Torrent) numPiecesCompleted() (num int) {
691 return t._completedPieces.Len()
694 func (t *Torrent) close() (err error) {
697 if t.storage != nil {
700 t.storageLock.Unlock()
702 for conn := range t.conns {
705 t.cl.event.Broadcast()
706 t.pieceStateChanges.Close()
707 t.updateWantPeersEvent()
711 func (t *Torrent) requestOffset(r request) int64 {
712 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
715 // Return the request that would include the given offset into the torrent
716 // data. Returns !ok if there is no such request.
717 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
718 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
721 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
722 defer perf.ScopeTimerErr(&err)()
723 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
724 if err == nil && n != len(data) {
725 err = io.ErrShortWrite
730 func (t *Torrent) bitfield() (bf []bool) {
731 bf = make([]bool, t.numPieces())
732 t._completedPieces.IterTyped(func(piece int) (again bool) {
739 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
740 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
743 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
744 t.pieces[pieceIndex]._dirtyChunks.Clear()
747 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
748 if t.info.PieceLength == 0 {
749 // There will be no variance amongst pieces. Only pain.
752 if piece == t.numPieces()-1 {
753 ret := pp.Integer(*t.length % t.info.PieceLength)
758 return pp.Integer(t.info.PieceLength)
761 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, copyErr error) {
762 hash := pieceHash.New()
764 p.waitNoPendingWrites()
765 ip := t.info.Piece(int(piece))
767 _, copyErr = io.CopyN( // Return no error iff pl bytes are copied.
768 hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl), pl)
769 missinggo.CopyExact(&ret, hash.Sum(nil))
773 func (t *Torrent) haveAnyPieces() bool {
774 return t._completedPieces.Len() != 0
777 func (t *Torrent) haveAllPieces() bool {
781 return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
784 func (t *Torrent) havePiece(index pieceIndex) bool {
785 return t.haveInfo() && t.pieceComplete(index)
788 func (t *Torrent) haveChunk(r request) (ret bool) {
790 // log.Println("have chunk", r, ret)
795 if t.pieceComplete(pieceIndex(r.Index)) {
798 p := &t.pieces[r.Index]
799 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
802 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
803 return int(cs.Begin / chunkSize)
806 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
810 if index < 0 || index >= t.numPieces() {
813 p := &t.pieces[index]
814 if p.queuedForHash() {
820 if t.pieceComplete(index) {
823 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
826 // t.logger.Printf("piece %d not pending", index)
827 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
828 return index < begin || index >= end
832 // The worst connection is one that hasn't been sent, or sent anything useful
833 // for the longest. A bad connection is one that usually sends us unwanted
834 // pieces, or has been in worser half of the established connections for more
836 func (t *Torrent) worstBadConn() *PeerConn {
837 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
840 c := heap.Pop(&wcs).(*PeerConn)
841 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
844 // If the connection is in the worst half of the established
845 // connection quota and is older than a minute.
846 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
847 // Give connections 1 minute to prove themselves.
848 if time.Since(c.completedHandshake) > time.Minute {
856 type PieceStateChange struct {
861 func (t *Torrent) publishPieceChange(piece pieceIndex) {
862 t.cl._mu.Defer(func() {
863 cur := t.pieceState(piece)
864 p := &t.pieces[piece]
865 if cur != p.publicPieceState {
866 p.publicPieceState = cur
867 t.pieceStateChanges.Publish(PieceStateChange{
875 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
876 if t.pieceComplete(piece) {
879 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
882 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
883 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
886 func (t *Torrent) readersChanged() {
887 t.updateReaderPieces()
888 t.updateAllPiecePriorities()
891 func (t *Torrent) updateReaderPieces() {
892 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
895 func (t *Torrent) readerPosChanged(from, to pieceRange) {
899 t.updateReaderPieces()
900 // Order the ranges, high and low.
902 if l.begin > h.begin {
906 // Two distinct ranges.
907 t.updatePiecePriorities(l.begin, l.end)
908 t.updatePiecePriorities(h.begin, h.end)
915 t.updatePiecePriorities(l.begin, end)
919 func (t *Torrent) maybeNewConns() {
920 // Tickle the accept routine.
921 t.cl.event.Broadcast()
925 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
926 // t.logger.Printf("piece %d priority changed", piece)
927 for c := range t.conns {
928 if c.updatePiecePriority(piece) {
929 // log.Print("conn piece priority changed")
934 t.publishPieceChange(piece)
937 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
938 p := &t.pieces[piece]
939 newPrio := p.uncachedPriority()
940 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
941 if newPrio == PiecePriorityNone {
942 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
946 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
950 t.piecePriorityChanged(piece)
953 func (t *Torrent) updateAllPiecePriorities() {
954 t.updatePiecePriorities(0, t.numPieces())
957 // Update all piece priorities in one hit. This function should have the same
958 // output as updatePiecePriority, but across all pieces.
959 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
960 for i := begin; i < end; i++ {
961 t.updatePiecePriority(i)
965 // Returns the range of pieces [begin, end) that contains the extent of bytes.
966 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
967 if off >= *t.length {
977 begin = pieceIndex(off / t.info.PieceLength)
978 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
979 if end > pieceIndex(t.info.NumPieces()) {
980 end = pieceIndex(t.info.NumPieces())
985 // Returns true if all iterations complete without breaking. Returns the read
986 // regions for all readers. The reader regions should not be merged as some
987 // callers depend on this method to enumerate readers.
988 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
989 for r := range t.readers {
991 if p.begin >= p.end {
994 if !f(p.begin, p.end) {
1001 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1002 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1004 return PiecePriorityNone
1009 ret := piecePriority(-prio)
1010 if ret == PiecePriorityNone {
1016 func (t *Torrent) pendRequest(req request) {
1017 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1018 t.pieces[req.Index].pendChunkIndex(ci)
1021 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1023 t.cl.event.Broadcast()
1024 if t.pieceComplete(piece) {
1025 t.onPieceCompleted(piece)
1027 t.onIncompletePiece(piece)
1029 t.updatePiecePriority(piece)
1032 func (t *Torrent) numReceivedConns() (ret int) {
1033 for c := range t.conns {
1034 if c.Discovery == PeerSourceIncoming {
1041 func (t *Torrent) maxHalfOpen() int {
1042 // Note that if we somehow exceed the maximum established conns, we want
1043 // the negative value to have an effect.
1044 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1045 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1046 // We want to allow some experimentation with new peers, and to try to
1047 // upset an oversupply of received connections.
1048 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1051 func (t *Torrent) openNewConns() {
1052 defer t.updateWantPeersEvent()
1053 for t.peers.Len() != 0 {
1057 if len(t.halfOpen) >= t.maxHalfOpen() {
1060 p := t.peers.PopMax()
1065 func (t *Torrent) getConnPieceInclination() []int {
1066 _ret := t.connPieceInclinationPool.Get()
1068 pieceInclinationsNew.Add(1)
1069 return rand.Perm(int(t.numPieces()))
1071 pieceInclinationsReused.Add(1)
1072 return *_ret.(*[]int)
1075 func (t *Torrent) putPieceInclination(pi []int) {
1076 t.connPieceInclinationPool.Put(&pi)
1077 pieceInclinationsPut.Add(1)
1080 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1082 uncached := t.pieceCompleteUncached(piece)
1083 cached := p.completion()
1084 changed := cached != uncached
1085 complete := uncached.Complete
1086 p.storageCompletionOk = uncached.Ok
1087 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1088 if complete && len(p.dirtiers) != 0 {
1089 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1092 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).WithValues(debugLogValue).Log(t.logger)
1093 t.pieceCompletionChanged(piece)
1098 // Non-blocking read. Client lock is not required.
1099 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1100 p := &t.pieces[off/t.info.PieceLength]
1101 p.waitNoPendingWrites()
1102 return p.Storage().ReadAt(b, off-p.Info().Offset())
1105 // Returns an error if the metadata was completed, but couldn't be set for
1106 // some reason. Blame it on the last peer to contribute.
1107 func (t *Torrent) maybeCompleteMetadata() error {
1112 if !t.haveAllMetadataPieces() {
1113 // Don't have enough metadata pieces.
1116 err := t.setInfoBytes(t.metadataBytes)
1118 t.invalidateMetadata()
1119 return fmt.Errorf("error setting info bytes: %s", err)
1121 if t.cl.config.Debug {
1122 t.logger.Printf("%s: got metadata from peers", t)
1127 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1128 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1130 now.Add(bitmap.BitIndex(begin))
1131 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1138 func (t *Torrent) needData() bool {
1139 if t.closed.IsSet() {
1145 return t._pendingPieces.Len() != 0
1148 func appendMissingStrings(old, new []string) (ret []string) {
1151 for _, n := range new {
1152 for _, o := range old {
1157 ret = append(ret, n)
1162 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1164 for minNumTiers > len(ret) {
1165 ret = append(ret, nil)
1170 func (t *Torrent) addTrackers(announceList [][]string) {
1171 fullAnnounceList := &t.metainfo.AnnounceList
1172 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1173 for tierIndex, trackerURLs := range announceList {
1174 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1176 t.startMissingTrackerScrapers()
1177 t.updateWantPeersEvent()
1180 // Don't call this before the info is available.
1181 func (t *Torrent) bytesCompleted() int64 {
1185 return t.info.TotalLength() - t.bytesLeft()
1188 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1191 return t.setInfoBytes(b)
1194 // Returns true if connection is removed from torrent.Conns.
1195 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1196 if !c.closed.IsSet() {
1197 panic("connection is not closed")
1198 // There are behaviours prevented by the closed state that will fail
1199 // if the connection has been deleted.
1203 torrent.Add("deleted connections", 1)
1204 c.deleteAllRequests()
1205 if len(t.conns) == 0 {
1206 t.assertNoPendingRequests()
1211 func (t *Torrent) assertNoPendingRequests() {
1212 if len(t.pendingRequests) != 0 {
1213 panic(t.pendingRequests)
1215 //if len(t.lastRequested) != 0 {
1216 // panic(t.lastRequested)
1220 func (t *Torrent) dropConnection(c *PeerConn) {
1221 t.cl.event.Broadcast()
1223 if t.deleteConnection(c) {
1228 func (t *Torrent) wantPeers() bool {
1229 if t.closed.IsSet() {
1232 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1235 return t.needData() || t.seeding()
1238 func (t *Torrent) updateWantPeersEvent() {
1240 t.wantPeersEvent.Set()
1242 t.wantPeersEvent.Clear()
1246 // Returns whether the client should make effort to seed the torrent.
1247 func (t *Torrent) seeding() bool {
1249 if t.closed.IsSet() {
1252 if cl.config.NoUpload {
1255 if !cl.config.Seed {
1258 if cl.config.DisableAggressiveUpload && t.needData() {
1264 func (t *Torrent) startScrapingTracker(_url string) {
1268 u, err := url.Parse(_url)
1270 // URLs with a leading '*' appear to be a uTorrent convention to
1271 // disable trackers.
1273 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1277 if u.Scheme == "udp" {
1279 t.startScrapingTracker(u.String())
1281 t.startScrapingTracker(u.String())
1284 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1287 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1290 if _, ok := t.trackerAnnouncers[_url]; ok {
1293 newAnnouncer := &trackerScraper{
1297 if t.trackerAnnouncers == nil {
1298 t.trackerAnnouncers = make(map[string]*trackerScraper)
1300 t.trackerAnnouncers[_url] = newAnnouncer
1301 go newAnnouncer.Run()
1304 // Adds and starts tracker scrapers for tracker URLs that aren't already
1306 func (t *Torrent) startMissingTrackerScrapers() {
1307 if t.cl.config.DisableTrackers {
1310 t.startScrapingTracker(t.metainfo.Announce)
1311 for _, tier := range t.metainfo.AnnounceList {
1312 for _, url := range tier {
1313 t.startScrapingTracker(url)
1318 // Returns an AnnounceRequest with fields filled out to defaults and current
1320 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1321 // Note that IPAddress is not set. It's set for UDP inside the tracker
1322 // code, since it's dependent on the network in use.
1323 return tracker.AnnounceRequest{
1326 Port: uint16(t.cl.incomingPeerPort()),
1327 PeerId: t.cl.peerID,
1328 InfoHash: t.infoHash,
1329 Key: t.cl.announceKey(),
1331 // The following are vaguely described in BEP 3.
1333 Left: t.bytesLeftAnnounce(),
1334 Uploaded: t.stats.BytesWrittenData.Int64(),
1335 // There's no mention of wasted or unwanted download in the BEP.
1336 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1340 // Adds peers revealed in an announce until the announce ends, or we have
1342 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1344 for v := range pvs {
1346 for _, cp := range v.Peers {
1348 // Can't do anything with this.
1352 Addr: ipPortAddr{cp.IP, cp.Port},
1353 Source: PeerSourceDhtGetPeers,
1360 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1361 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1365 go t.consumeDhtAnnouncePeers(ps.Peers())
1367 case <-t.closed.LockedChan(t.cl.locker()):
1368 case <-time.After(5 * time.Minute):
1374 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1378 case <-t.closed.LockedChan(cl.locker()):
1380 case <-t.wantPeersEvent.LockedChan(cl.locker()):
1385 err := t.announceToDht(true, s)
1387 t.logger.Printf("error announcing %q to DHT: %s", t, err)
1392 func (t *Torrent) addPeers(peers []Peer) {
1393 for _, p := range peers {
1398 func (t *Torrent) Stats() TorrentStats {
1400 defer t.cl.rUnlock()
1401 return t.statsLocked()
1404 func (t *Torrent) statsLocked() (ret TorrentStats) {
1405 ret.ActivePeers = len(t.conns)
1406 ret.HalfOpenPeers = len(t.halfOpen)
1407 ret.PendingPeers = t.peers.Len()
1408 ret.TotalPeers = t.numTotalPeers()
1409 ret.ConnectedSeeders = 0
1410 for c := range t.conns {
1411 if all, ok := c.peerHasAllPieces(); all && ok {
1412 ret.ConnectedSeeders++
1415 ret.ConnStats = t.stats.Copy()
1419 // The total number of peers in the torrent.
1420 func (t *Torrent) numTotalPeers() int {
1421 peers := make(map[string]struct{})
1422 for conn := range t.conns {
1423 ra := conn.conn.RemoteAddr()
1425 // It's been closed and doesn't support RemoteAddr.
1428 peers[ra.String()] = struct{}{}
1430 for addr := range t.halfOpen {
1431 peers[addr] = struct{}{}
1433 t.peers.Each(func(peer Peer) {
1434 peers[peer.Addr.String()] = struct{}{}
1439 // Reconcile bytes transferred before connection was associated with a
1441 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1442 if c._stats != (ConnStats{
1443 // Handshakes should only increment these fields:
1444 BytesWritten: c._stats.BytesWritten,
1445 BytesRead: c._stats.BytesRead,
1449 c.postHandshakeStats(func(cs *ConnStats) {
1450 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1451 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1453 c.reconciledHandshakeStats = true
1456 // Returns true if the connection is added.
1457 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1460 torrent.Add("added connections", 1)
1463 if t.closed.IsSet() {
1464 return errors.New("torrent closed")
1466 for c0 := range t.conns {
1467 if c.PeerID != c0.PeerID {
1470 if !t.cl.config.dropDuplicatePeerIds {
1473 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1475 t.deleteConnection(c0)
1477 return errors.New("existing connection preferred")
1480 if len(t.conns) >= t.maxEstablishedConns {
1481 c := t.worstBadConn()
1483 return errors.New("don't want conns")
1486 t.deleteConnection(c)
1488 if len(t.conns) >= t.maxEstablishedConns {
1491 t.conns[c] = struct{}{}
1495 func (t *Torrent) wantConns() bool {
1496 if !t.networkingEnabled {
1499 if t.closed.IsSet() {
1502 if !t.seeding() && !t.needData() {
1505 if len(t.conns) < t.maxEstablishedConns {
1508 return t.worstBadConn() != nil
1511 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1514 oldMax = t.maxEstablishedConns
1515 t.maxEstablishedConns = max
1516 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1517 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1518 t.dropConnection(wcs.Pop().(*PeerConn))
1524 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1525 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).WithValues(debugLogValue))
1528 t.cl.event.Broadcast()
1529 if t.closed.IsSet() {
1533 // Don't score the first time a piece is hashed, it could be an initial check.
1534 if p.storageCompletionOk {
1536 pieceHashedCorrect.Add(1)
1538 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1539 pieceHashedNotCorrect.Add(1)
1544 if len(p.dirtiers) != 0 {
1545 // Don't increment stats above connection-level for every involved connection.
1546 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1548 for c := range p.dirtiers {
1549 c._stats.incrementPiecesDirtiedGood()
1551 t.clearPieceTouchers(piece)
1552 err := p.Storage().MarkComplete()
1554 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1556 t.pendAllChunkSpecs(piece)
1558 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1559 // Peers contributed to all the data for this piece hash failure, and the failure was
1560 // not due to errors in the storage (such as data being dropped in a cache).
1562 // Increment Torrent and above stats, and then specific connections.
1563 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1564 for c := range p.dirtiers {
1565 // Y u do dis peer?!
1566 c.stats().incrementPiecesDirtiedBad()
1569 bannableTouchers := make([]*PeerConn, 0, len(p.dirtiers))
1570 for c := range p.dirtiers {
1572 bannableTouchers = append(bannableTouchers, c)
1575 t.clearPieceTouchers(piece)
1576 slices.Sort(bannableTouchers, connLessTrusted)
1578 if t.cl.config.Debug {
1580 "bannable conns by trust for piece %d: %v",
1582 func() (ret []connectionTrust) {
1583 for _, c := range bannableTouchers {
1584 ret = append(ret, c.trust())
1591 if len(bannableTouchers) >= 1 {
1592 c := bannableTouchers[0]
1593 t.cl.banPeerIP(c.remoteIp())
1597 t.onIncompletePiece(piece)
1598 p.Storage().MarkNotComplete()
1600 t.updatePieceCompletion(piece)
1603 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1604 // TODO: Make faster
1605 for cn := range t.conns {
1610 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1611 t.pendAllChunkSpecs(piece)
1612 t.cancelRequestsForPiece(piece)
1613 for conn := range t.conns {
1618 // Called when a piece is found to be not complete.
1619 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1620 if t.pieceAllDirty(piece) {
1621 t.pendAllChunkSpecs(piece)
1623 if !t.wantPieceIndex(piece) {
1624 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1627 // We could drop any connections that we told we have a piece that we
1628 // don't here. But there's a test failure, and it seems clients don't care
1629 // if you request pieces that you already claim to have. Pruning bad
1630 // connections might just remove any connections that aren't treating us
1631 // favourably anyway.
1633 // for c := range t.conns {
1634 // if c.sentHave(piece) {
1638 for conn := range t.conns {
1639 if conn.peerHasPiece(piece) {
1640 conn.updateRequests()
1645 func (t *Torrent) tryCreateMorePieceHashers() {
1646 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1650 func (t *Torrent) tryCreatePieceHasher() bool {
1651 if t.storage == nil {
1654 pi, ok := t.getPieceToHash()
1659 t.piecesQueuedForHash.Remove(pi)
1661 t.publishPieceChange(pi)
1662 t.updatePiecePriority(pi)
1663 t.storageLock.RLock()
1664 t.activePieceHashes++
1665 go t.pieceHasher(pi)
1669 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1670 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1671 if t.piece(i).hashing {
1681 func (t *Torrent) pieceHasher(index pieceIndex) {
1683 sum, copyErr := t.hashPiece(index)
1684 correct := sum == *p.hash
1688 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1690 t.storageLock.RUnlock()
1694 t.updatePiecePriority(index)
1695 t.pieceHashed(index, correct, copyErr)
1696 t.publishPieceChange(index)
1697 t.activePieceHashes--
1698 t.tryCreateMorePieceHashers()
1701 // Return the connections that touched a piece, and clear the entries while doing it.
1702 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1704 for c := range p.dirtiers {
1705 delete(c.peerTouchedPieces, pi)
1706 delete(p.dirtiers, c)
1710 func (t *Torrent) connsAsSlice() (ret []*PeerConn) {
1711 for c := range t.conns {
1712 ret = append(ret, c)
1717 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1718 piece := t.piece(pieceIndex)
1719 if piece.queuedForHash() {
1722 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1723 t.publishPieceChange(pieceIndex)
1724 t.updatePiecePriority(pieceIndex)
1725 t.tryCreateMorePieceHashers()
1728 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1729 // before the Info is available.
1730 func (t *Torrent) VerifyData() {
1731 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1732 t.Piece(i).VerifyData()
1736 // Start the process of connecting to the given peer for the given torrent if appropriate.
1737 func (t *Torrent) initiateConn(peer Peer) {
1738 if peer.Id == t.cl.peerID {
1742 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1746 if t.addrActive(addr.String()) {
1749 t.halfOpen[addr.String()] = peer
1750 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1753 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1754 // quickly make one Client visible to the Torrent of another Client.
1755 func (t *Torrent) AddClientPeer(cl *Client) {
1756 t.AddPeers(func() (ps []Peer) {
1757 for _, la := range cl.ListenAddrs() {
1758 ps = append(ps, Peer{
1767 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1769 func (t *Torrent) allStats(f func(*ConnStats)) {
1774 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1775 return t.pieces[i].hashing
1778 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1779 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1782 func (t *Torrent) dialTimeout() time.Duration {
1783 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1786 func (t *Torrent) piece(i int) *Piece {
1790 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1794 type torrentRequestStrategyCallbacks struct {
1798 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
1799 torrent.Add("request timeouts", 1)
1801 defer cb.t.cl.unlock()
1802 for cn := range cb.t.conns {
1803 if cn.peerHasPiece(pieceIndex(r.Index)) {
1810 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
1811 return torrentRequestStrategyCallbacks{t}
1814 func (t *Torrent) onWriteChunkErr(err error) {
1815 if t.userOnWriteChunkErr != nil {
1816 go t.userOnWriteChunkErr(err)
1819 t.disallowDataDownloadLocked()
1822 func (t *Torrent) DisallowDataDownload() {
1825 t.disallowDataDownloadLocked()
1828 func (t *Torrent) disallowDataDownloadLocked() {
1829 log.Printf("disallowing data download")
1830 t.dataDownloadDisallowed = true
1831 for c := range t.conns {
1836 func (t *Torrent) AllowDataDownload() {
1839 log.Printf("AllowDataDownload")
1840 t.dataDownloadDisallowed = false
1841 for c := range t.conns {
1847 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
1850 t.userOnWriteChunkErr = f