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
45 // Determines what chunks to request from peers.
46 requestStrategy requestStrategy
48 closed missinggo.Event
49 infoHash metainfo.Hash
51 // Values are the piece indices that changed.
52 pieceStateChanges *pubsub.PubSub
53 // The size of chunks to request from peers over the wire. This is
54 // normally 16KiB by convention these days.
57 // Total length of the torrent in bytes. Stored because it's not O(1) to
58 // get this from the info dict.
61 // The storage to open when the info dict becomes available.
62 storageOpener *storage.Client
63 // Storage for torrent data.
64 storage *storage.Torrent
65 // Read-locked for using storage, and write-locked for Closing.
66 storageLock sync.RWMutex
68 // TODO: Only announce stuff is used?
69 metainfo metainfo.MetaInfo
71 // The info dict. nil if we don't have it (yet).
75 // Active peer connections, running message stream loops. TODO: Make this
76 // open (not-closed) connections only.
77 conns map[*PeerConn]struct{}
78 maxEstablishedConns int
79 // Set of addrs to which we're attempting to connect. Connections are
80 // half-open until all handshakes are completed.
81 halfOpen map[string]Peer
84 // Reserve of peers to connect to. A peer can be both here and in the
85 // active connections if were told about the peer after connecting with
86 // them. That encourages us to reconnect to peers that are well known in
88 peers prioritizedPeers
89 wantPeersEvent missinggo.Event
90 // An announcer for each tracker URL.
91 trackerAnnouncers map[string]*trackerScraper
92 // How many times we've initiated a DHT announce. TODO: Move into stats.
95 // Name used if the info name isn't available. Should be cleared when the
96 // Info does become available.
100 // The bencoded bytes of the info dict. This is actively manipulated if
101 // the info bytes aren't initially available, and we try to fetch them
104 // Each element corresponds to the 16KiB metadata pieces. If true, we have
105 // received that piece.
106 metadataCompletedChunks []bool
107 metadataChanged sync.Cond
109 // Set when .Info is obtained.
110 gotMetainfo missinggo.Event
112 readers map[*reader]struct{}
113 _readerNowPieces bitmap.Bitmap
114 _readerReadaheadPieces bitmap.Bitmap
116 // A cache of pieces we need to get. Calculated from various piece and
117 // file priorities and completion states elsewhere.
118 _pendingPieces prioritybitmap.PriorityBitmap
119 // A cache of completed piece indices.
120 _completedPieces bitmap.Bitmap
121 // Pieces that need to be hashed.
122 piecesQueuedForHash bitmap.Bitmap
123 activePieceHashes int
125 // A pool of piece priorities []int for assignment to new connections.
126 // These "inclinations" are used to give connections preference for
128 connPieceInclinationPool sync.Pool
130 // Count of each request across active connections.
131 pendingRequests map[request]int
134 func (t *Torrent) numConns() int {
138 func (t *Torrent) numReaders() int {
139 return len(t.readers)
142 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
143 return t._readerNowPieces
146 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
147 return t._readerReadaheadPieces
150 func (t *Torrent) ignorePieces() bitmap.Bitmap {
151 ret := t._completedPieces.Copy()
152 ret.Union(t.piecesQueuedForHash)
153 for i := 0; i < t.numPieces(); i++ {
154 if t.piece(i).hashing {
161 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
162 return &t._pendingPieces
165 func (t *Torrent) tickleReaders() {
166 t.cl.event.Broadcast()
169 // Returns a channel that is closed when the Torrent is closed.
170 func (t *Torrent) Closed() <-chan struct{} {
171 return t.closed.LockedChan(t.cl.locker())
174 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
175 // pending, and half-open peers.
176 func (t *Torrent) KnownSwarm() (ks []Peer) {
177 // Add pending peers to the list
178 t.peers.Each(func(peer Peer) {
179 ks = append(ks, peer)
182 // Add half-open peers to the list
183 for _, peer := range t.halfOpen {
184 ks = append(ks, peer)
187 // Add active peers to the list
188 for conn := range t.conns {
190 ks = append(ks, Peer{
192 Addr: conn.remoteAddr,
193 Source: conn.Discovery,
194 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
195 // > But if we're not connected to them with an encrypted connection, I couldn't say
196 // > what's appropriate. We can carry forward the SupportsEncryption value as we
197 // > received it from trackers/DHT/PEX, or just use the encryption state for the
198 // > connection. It's probably easiest to do the latter for now.
199 // https://github.com/anacrolix/torrent/pull/188
200 SupportsEncryption: conn.headerEncrypted,
207 func (t *Torrent) setChunkSize(size pp.Integer) {
209 t.chunkPool = &sync.Pool{
210 New: func() interface{} {
211 b := make([]byte, size)
217 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
218 return t._completedPieces.Get(bitmap.BitIndex(piece))
221 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
222 return t.pieces[piece].Storage().Completion()
225 // There's a connection to that address already.
226 func (t *Torrent) addrActive(addr string) bool {
227 if _, ok := t.halfOpen[addr]; ok {
230 for c := range t.conns {
232 if ra.String() == addr {
239 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
240 ret = make([]*PeerConn, 0, len(t.conns))
241 for c := range t.conns {
242 if !c.closed.IsSet() {
249 func (t *Torrent) addPeer(p Peer) {
251 peersAddedBySource.Add(string(p.Source), 1)
252 if t.closed.IsSet() {
255 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
256 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
257 torrent.Add("peers not added because of bad addr", 1)
262 torrent.Add("peers replaced", 1)
265 for t.peers.Len() > cl.config.TorrentPeersHighWater {
266 _, ok := t.peers.DeleteMin()
268 torrent.Add("excess reserve peers discarded", 1)
273 func (t *Torrent) invalidateMetadata() {
274 for i := range t.metadataCompletedChunks {
275 t.metadataCompletedChunks[i] = false
282 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
286 if index >= len(t.metadataCompletedChunks) {
287 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
290 copy(t.metadataBytes[(1<<14)*index:], data)
291 t.metadataCompletedChunks[index] = true
294 func (t *Torrent) metadataPieceCount() int {
295 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
298 func (t *Torrent) haveMetadataPiece(piece int) bool {
300 return (1<<14)*piece < len(t.metadataBytes)
302 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
306 func (t *Torrent) metadataSize() int {
307 return len(t.metadataBytes)
310 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
311 for i := 0; i < len(info.Pieces); i += sha1.Size {
312 ret = append(ret, info.Pieces[i:i+sha1.Size])
317 func (t *Torrent) makePieces() {
318 hashes := infoPieceHashes(t.info)
319 t.pieces = make([]Piece, len(hashes))
320 for i, hash := range hashes {
321 piece := &t.pieces[i]
323 piece.index = pieceIndex(i)
324 piece.noPendingWrites.L = &piece.pendingWritesMutex
325 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
327 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
328 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
329 piece.files = files[beginFile:endFile]
333 // Returns the index of the first file containing the piece. files must be
334 // ordered by offset.
335 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
336 for i, f := range files {
337 if f.offset+f.length > pieceOffset {
344 // Returns the index after the last file containing the piece. files must be
345 // ordered by offset.
346 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
347 for i, f := range files {
348 if f.offset+f.length >= pieceEndOffset {
355 func (t *Torrent) cacheLength() {
357 for _, f := range t.info.UpvertedFiles() {
363 func (t *Torrent) setInfo(info *metainfo.Info) error {
364 if err := validateInfo(info); err != nil {
365 return fmt.Errorf("bad info: %s", err)
367 if t.storageOpener != nil {
369 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
371 return fmt.Errorf("error opening torrent storage: %s", err)
377 t.displayName = "" // Save a few bytes lol.
384 func (t *Torrent) onSetInfo() {
385 for conn := range t.conns {
386 if err := conn.setNumPieces(t.numPieces()); err != nil {
387 t.logger.Printf("closing connection: %s", err)
391 for i := range t.pieces {
392 t.updatePieceCompletion(pieceIndex(i))
394 if !p.storageCompletionOk {
395 // t.logger.Printf("piece %s completion unknown, queueing check", p)
396 t.queuePieceCheck(pieceIndex(i))
399 t.cl.event.Broadcast()
401 t.updateWantPeersEvent()
402 t.pendingRequests = make(map[request]int)
403 t.tryCreateMorePieceHashers()
406 // Called when metadata for a torrent becomes available.
407 func (t *Torrent) setInfoBytes(b []byte) error {
408 if metainfo.HashBytes(b) != t.infoHash {
409 return errors.New("info bytes have wrong hash")
411 var info metainfo.Info
412 if err := bencode.Unmarshal(b, &info); err != nil {
413 return fmt.Errorf("error unmarshalling info bytes: %s", err)
415 if err := t.setInfo(&info); err != nil {
419 t.metadataCompletedChunks = nil
424 func (t *Torrent) haveAllMetadataPieces() bool {
428 if t.metadataCompletedChunks == nil {
431 for _, have := range t.metadataCompletedChunks {
439 // TODO: Propagate errors to disconnect peer.
440 func (t *Torrent) setMetadataSize(bytes int) (err error) {
442 // We already know the correct metadata size.
445 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
446 return errors.New("bad size")
448 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
451 t.metadataBytes = make([]byte, bytes)
452 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
453 t.metadataChanged.Broadcast()
454 for c := range t.conns {
455 c.requestPendingMetadata()
460 // The current working name for the torrent. Either the name in the info dict,
461 // or a display name given such as by the dn value in a magnet link, or "".
462 func (t *Torrent) name() string {
464 defer t.nameMu.RUnlock()
471 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
472 p := &t.pieces[index]
473 ret.Priority = t.piecePriority(index)
474 ret.Completion = p.completion()
475 if p.queuedForHash() || p.hashing {
478 if !ret.Complete && t.piecePartiallyDownloaded(index) {
484 func (t *Torrent) metadataPieceSize(piece int) int {
485 return metadataPieceSize(len(t.metadataBytes), piece)
488 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
494 d["total_size"] = len(t.metadataBytes)
496 p := bencode.MustMarshal(d)
499 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
500 ExtendedPayload: append(p, data...),
504 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
505 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
506 ret = append(ret, PieceStateRun{
507 PieceState: el.(PieceState),
511 for index := range t.pieces {
512 rle.Append(t.pieceState(pieceIndex(index)), 1)
518 // Produces a small string representing a PieceStateRun.
519 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
520 ret = fmt.Sprintf("%d", psr.Length)
521 ret += func() string {
522 switch psr.Priority {
523 case PiecePriorityNext:
525 case PiecePriorityNormal:
527 case PiecePriorityReadahead:
529 case PiecePriorityNow:
531 case PiecePriorityHigh:
552 func (t *Torrent) writeStatus(w io.Writer) {
553 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
554 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
556 fmt.Fprintf(w, "Metadata have: ")
557 for _, h := range t.metadataCompletedChunks {
558 fmt.Fprintf(w, "%c", func() rune {
568 fmt.Fprintf(w, "Piece length: %s\n", func() string {
570 return fmt.Sprint(t.usualPieceSize())
576 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
577 fmt.Fprint(w, "Piece States:")
578 for _, psr := range t.pieceStateRuns() {
580 w.Write([]byte(pieceStateRunStatusChars(psr)))
584 fmt.Fprintf(w, "Reader Pieces:")
585 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
586 fmt.Fprintf(w, " %d:%d", begin, end)
591 fmt.Fprintf(w, "Enabled trackers:\n")
593 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
594 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
595 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
598 var luns, runs url.URL = lu, ru
601 var ml missinggo.MultiLess
602 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
603 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
605 }).([]*trackerScraper) {
606 fmt.Fprintf(tw, " %s\n", ta.statusLine())
611 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
613 spew.NewDefaultConfig()
614 spew.Fdump(w, t.statsLocked())
616 conns := t.connsAsSlice()
617 slices.Sort(conns, worseConn)
618 for i, c := range conns {
619 fmt.Fprintf(w, "%2d. ", i+1)
624 func (t *Torrent) haveInfo() bool {
628 // Returns a run-time generated MetaInfo that includes the info bytes and
629 // announce-list as currently known to the client.
630 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
631 return metainfo.MetaInfo{
632 CreationDate: time.Now().Unix(),
633 Comment: "dynamic metainfo from client",
634 CreatedBy: "go.torrent",
635 AnnounceList: t.metainfo.UpvertedAnnounceList(),
636 InfoBytes: func() []byte {
638 return t.metadataBytes
646 func (t *Torrent) BytesMissing() int64 {
649 return t.bytesMissingLocked()
652 func (t *Torrent) bytesMissingLocked() int64 {
656 func (t *Torrent) bytesLeft() (left int64) {
657 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
658 p := &t.pieces[piece]
659 left += int64(p.length() - p.numDirtyBytes())
665 // Bytes left to give in tracker announces.
666 func (t *Torrent) bytesLeftAnnounce() int64 {
674 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
675 if t.pieceComplete(piece) {
678 if t.pieceAllDirty(piece) {
681 return t.pieces[piece].hasDirtyChunks()
684 func (t *Torrent) usualPieceSize() int {
685 return int(t.info.PieceLength)
688 func (t *Torrent) numPieces() pieceIndex {
689 return pieceIndex(t.info.NumPieces())
692 func (t *Torrent) numPiecesCompleted() (num int) {
693 return t._completedPieces.Len()
696 func (t *Torrent) close() (err error) {
699 if t.storage != nil {
702 t.storageLock.Unlock()
704 for conn := range t.conns {
707 t.cl.event.Broadcast()
708 t.pieceStateChanges.Close()
709 t.updateWantPeersEvent()
713 func (t *Torrent) requestOffset(r request) int64 {
714 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
717 // Return the request that would include the given offset into the torrent
718 // data. Returns !ok if there is no such request.
719 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
720 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
723 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
724 defer perf.ScopeTimerErr(&err)()
725 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
726 if err == nil && n != len(data) {
727 err = io.ErrShortWrite
732 func (t *Torrent) bitfield() (bf []bool) {
733 bf = make([]bool, t.numPieces())
734 t._completedPieces.IterTyped(func(piece int) (again bool) {
741 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
742 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
745 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
746 t.pieces[pieceIndex]._dirtyChunks.Clear()
749 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
750 if t.info.PieceLength == 0 {
751 // There will be no variance amongst pieces. Only pain.
754 if piece == t.numPieces()-1 {
755 ret := pp.Integer(*t.length % t.info.PieceLength)
760 return pp.Integer(t.info.PieceLength)
763 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, copyErr error) {
764 hash := pieceHash.New()
766 p.waitNoPendingWrites()
767 ip := t.info.Piece(int(piece))
769 _, copyErr = io.CopyN( // Return no error iff pl bytes are copied.
770 hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl), pl)
771 missinggo.CopyExact(&ret, hash.Sum(nil))
775 func (t *Torrent) haveAnyPieces() bool {
776 return t._completedPieces.Len() != 0
779 func (t *Torrent) haveAllPieces() bool {
783 return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
786 func (t *Torrent) havePiece(index pieceIndex) bool {
787 return t.haveInfo() && t.pieceComplete(index)
790 func (t *Torrent) haveChunk(r request) (ret bool) {
792 // log.Println("have chunk", r, ret)
797 if t.pieceComplete(pieceIndex(r.Index)) {
800 p := &t.pieces[r.Index]
801 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
804 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
805 return int(cs.Begin / chunkSize)
808 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
812 if index < 0 || index >= t.numPieces() {
815 p := &t.pieces[index]
816 if p.queuedForHash() {
822 if t.pieceComplete(index) {
825 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
828 // t.logger.Printf("piece %d not pending", index)
829 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
830 return index < begin || index >= end
834 // The worst connection is one that hasn't been sent, or sent anything useful
835 // for the longest. A bad connection is one that usually sends us unwanted
836 // pieces, or has been in worser half of the established connections for more
838 func (t *Torrent) worstBadConn() *PeerConn {
839 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
842 c := heap.Pop(&wcs).(*PeerConn)
843 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
846 // If the connection is in the worst half of the established
847 // connection quota and is older than a minute.
848 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
849 // Give connections 1 minute to prove themselves.
850 if time.Since(c.completedHandshake) > time.Minute {
858 type PieceStateChange struct {
863 func (t *Torrent) publishPieceChange(piece pieceIndex) {
864 t.cl._mu.Defer(func() {
865 cur := t.pieceState(piece)
866 p := &t.pieces[piece]
867 if cur != p.publicPieceState {
868 p.publicPieceState = cur
869 t.pieceStateChanges.Publish(PieceStateChange{
877 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
878 if t.pieceComplete(piece) {
881 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
884 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
885 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
888 func (t *Torrent) readersChanged() {
889 t.updateReaderPieces()
890 t.updateAllPiecePriorities()
893 func (t *Torrent) updateReaderPieces() {
894 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
897 func (t *Torrent) readerPosChanged(from, to pieceRange) {
901 t.updateReaderPieces()
902 // Order the ranges, high and low.
904 if l.begin > h.begin {
908 // Two distinct ranges.
909 t.updatePiecePriorities(l.begin, l.end)
910 t.updatePiecePriorities(h.begin, h.end)
917 t.updatePiecePriorities(l.begin, end)
921 func (t *Torrent) maybeNewConns() {
922 // Tickle the accept routine.
923 t.cl.event.Broadcast()
927 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
928 // t.logger.Printf("piece %d priority changed", piece)
929 for c := range t.conns {
930 if c.updatePiecePriority(piece) {
931 // log.Print("conn piece priority changed")
936 t.publishPieceChange(piece)
939 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
940 p := &t.pieces[piece]
941 newPrio := p.uncachedPriority()
942 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
943 if newPrio == PiecePriorityNone {
944 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
948 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
952 t.piecePriorityChanged(piece)
955 func (t *Torrent) updateAllPiecePriorities() {
956 t.updatePiecePriorities(0, t.numPieces())
959 // Update all piece priorities in one hit. This function should have the same
960 // output as updatePiecePriority, but across all pieces.
961 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
962 for i := begin; i < end; i++ {
963 t.updatePiecePriority(i)
967 // Returns the range of pieces [begin, end) that contains the extent of bytes.
968 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
969 if off >= *t.length {
979 begin = pieceIndex(off / t.info.PieceLength)
980 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
981 if end > pieceIndex(t.info.NumPieces()) {
982 end = pieceIndex(t.info.NumPieces())
987 // Returns true if all iterations complete without breaking. Returns the read
988 // regions for all readers. The reader regions should not be merged as some
989 // callers depend on this method to enumerate readers.
990 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
991 for r := range t.readers {
993 if p.begin >= p.end {
996 if !f(p.begin, p.end) {
1003 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1004 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1006 return PiecePriorityNone
1011 ret := piecePriority(-prio)
1012 if ret == PiecePriorityNone {
1018 func (t *Torrent) pendRequest(req request) {
1019 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1020 t.pieces[req.Index].pendChunkIndex(ci)
1023 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1025 t.cl.event.Broadcast()
1026 if t.pieceComplete(piece) {
1027 t.onPieceCompleted(piece)
1029 t.onIncompletePiece(piece)
1031 t.updatePiecePriority(piece)
1034 func (t *Torrent) numReceivedConns() (ret int) {
1035 for c := range t.conns {
1036 if c.Discovery == PeerSourceIncoming {
1043 func (t *Torrent) maxHalfOpen() int {
1044 // Note that if we somehow exceed the maximum established conns, we want
1045 // the negative value to have an effect.
1046 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1047 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1048 // We want to allow some experimentation with new peers, and to try to
1049 // upset an oversupply of received connections.
1050 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1053 func (t *Torrent) openNewConns() {
1054 defer t.updateWantPeersEvent()
1055 for t.peers.Len() != 0 {
1059 if len(t.halfOpen) >= t.maxHalfOpen() {
1062 p := t.peers.PopMax()
1067 func (t *Torrent) getConnPieceInclination() []int {
1068 _ret := t.connPieceInclinationPool.Get()
1070 pieceInclinationsNew.Add(1)
1071 return rand.Perm(int(t.numPieces()))
1073 pieceInclinationsReused.Add(1)
1074 return *_ret.(*[]int)
1077 func (t *Torrent) putPieceInclination(pi []int) {
1078 t.connPieceInclinationPool.Put(&pi)
1079 pieceInclinationsPut.Add(1)
1082 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1084 uncached := t.pieceCompleteUncached(piece)
1085 cached := p.completion()
1086 changed := cached != uncached
1087 complete := uncached.Complete
1088 p.storageCompletionOk = uncached.Ok
1089 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1090 if complete && len(p.dirtiers) != 0 {
1091 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1094 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).WithValues(debugLogValue).Log(t.logger)
1095 t.pieceCompletionChanged(piece)
1100 // Non-blocking read. Client lock is not required.
1101 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1102 p := &t.pieces[off/t.info.PieceLength]
1103 p.waitNoPendingWrites()
1104 return p.Storage().ReadAt(b, off-p.Info().Offset())
1107 // Returns an error if the metadata was completed, but couldn't be set for
1108 // some reason. Blame it on the last peer to contribute.
1109 func (t *Torrent) maybeCompleteMetadata() error {
1114 if !t.haveAllMetadataPieces() {
1115 // Don't have enough metadata pieces.
1118 err := t.setInfoBytes(t.metadataBytes)
1120 t.invalidateMetadata()
1121 return fmt.Errorf("error setting info bytes: %s", err)
1123 if t.cl.config.Debug {
1124 t.logger.Printf("%s: got metadata from peers", t)
1129 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1130 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1132 now.Add(bitmap.BitIndex(begin))
1133 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1140 func (t *Torrent) needData() bool {
1141 if t.closed.IsSet() {
1147 return t._pendingPieces.Len() != 0
1150 func appendMissingStrings(old, new []string) (ret []string) {
1153 for _, n := range new {
1154 for _, o := range old {
1159 ret = append(ret, n)
1164 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1166 for minNumTiers > len(ret) {
1167 ret = append(ret, nil)
1172 func (t *Torrent) addTrackers(announceList [][]string) {
1173 fullAnnounceList := &t.metainfo.AnnounceList
1174 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1175 for tierIndex, trackerURLs := range announceList {
1176 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1178 t.startMissingTrackerScrapers()
1179 t.updateWantPeersEvent()
1182 // Don't call this before the info is available.
1183 func (t *Torrent) bytesCompleted() int64 {
1187 return t.info.TotalLength() - t.bytesLeft()
1190 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1193 return t.setInfoBytes(b)
1196 // Returns true if connection is removed from torrent.Conns.
1197 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1198 if !c.closed.IsSet() {
1199 panic("connection is not closed")
1200 // There are behaviours prevented by the closed state that will fail
1201 // if the connection has been deleted.
1205 torrent.Add("deleted connections", 1)
1206 c.deleteAllRequests()
1207 if len(t.conns) == 0 {
1208 t.assertNoPendingRequests()
1213 func (t *Torrent) assertNoPendingRequests() {
1214 if len(t.pendingRequests) != 0 {
1215 panic(t.pendingRequests)
1217 //if len(t.lastRequested) != 0 {
1218 // panic(t.lastRequested)
1222 func (t *Torrent) dropConnection(c *PeerConn) {
1223 t.cl.event.Broadcast()
1225 if t.deleteConnection(c) {
1230 func (t *Torrent) wantPeers() bool {
1231 if t.closed.IsSet() {
1234 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1237 return t.needData() || t.seeding()
1240 func (t *Torrent) updateWantPeersEvent() {
1242 t.wantPeersEvent.Set()
1244 t.wantPeersEvent.Clear()
1248 // Returns whether the client should make effort to seed the torrent.
1249 func (t *Torrent) seeding() bool {
1251 if t.closed.IsSet() {
1254 if cl.config.NoUpload {
1257 if !cl.config.Seed {
1260 if cl.config.DisableAggressiveUpload && t.needData() {
1266 func (t *Torrent) startScrapingTracker(_url string) {
1270 u, err := url.Parse(_url)
1272 // URLs with a leading '*' appear to be a uTorrent convention to
1273 // disable trackers.
1275 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1279 if u.Scheme == "udp" {
1281 t.startScrapingTracker(u.String())
1283 t.startScrapingTracker(u.String())
1286 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1289 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1292 if _, ok := t.trackerAnnouncers[_url]; ok {
1295 newAnnouncer := &trackerScraper{
1299 if t.trackerAnnouncers == nil {
1300 t.trackerAnnouncers = make(map[string]*trackerScraper)
1302 t.trackerAnnouncers[_url] = newAnnouncer
1303 go newAnnouncer.Run()
1306 // Adds and starts tracker scrapers for tracker URLs that aren't already
1308 func (t *Torrent) startMissingTrackerScrapers() {
1309 if t.cl.config.DisableTrackers {
1312 t.startScrapingTracker(t.metainfo.Announce)
1313 for _, tier := range t.metainfo.AnnounceList {
1314 for _, url := range tier {
1315 t.startScrapingTracker(url)
1320 // Returns an AnnounceRequest with fields filled out to defaults and current
1322 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1323 // Note that IPAddress is not set. It's set for UDP inside the tracker
1324 // code, since it's dependent on the network in use.
1325 return tracker.AnnounceRequest{
1328 Port: uint16(t.cl.incomingPeerPort()),
1329 PeerId: t.cl.peerID,
1330 InfoHash: t.infoHash,
1331 Key: t.cl.announceKey(),
1333 // The following are vaguely described in BEP 3.
1335 Left: t.bytesLeftAnnounce(),
1336 Uploaded: t.stats.BytesWrittenData.Int64(),
1337 // There's no mention of wasted or unwanted download in the BEP.
1338 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1342 // Adds peers revealed in an announce until the announce ends, or we have
1344 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1346 for v := range pvs {
1348 for _, cp := range v.Peers {
1350 // Can't do anything with this.
1354 Addr: ipPortAddr{cp.IP, cp.Port},
1355 Source: PeerSourceDhtGetPeers,
1362 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1363 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1367 go t.consumeDhtAnnouncePeers(ps.Peers())
1369 case <-t.closed.LockedChan(t.cl.locker()):
1370 case <-time.After(5 * time.Minute):
1376 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1380 case <-t.closed.LockedChan(cl.locker()):
1382 case <-t.wantPeersEvent.LockedChan(cl.locker()):
1387 err := t.announceToDht(true, s)
1389 t.logger.Printf("error announcing %q to DHT: %s", t, err)
1394 func (t *Torrent) addPeers(peers []Peer) {
1395 for _, p := range peers {
1400 func (t *Torrent) Stats() TorrentStats {
1402 defer t.cl.rUnlock()
1403 return t.statsLocked()
1406 func (t *Torrent) statsLocked() (ret TorrentStats) {
1407 ret.ActivePeers = len(t.conns)
1408 ret.HalfOpenPeers = len(t.halfOpen)
1409 ret.PendingPeers = t.peers.Len()
1410 ret.TotalPeers = t.numTotalPeers()
1411 ret.ConnectedSeeders = 0
1412 for c := range t.conns {
1413 if all, ok := c.peerHasAllPieces(); all && ok {
1414 ret.ConnectedSeeders++
1417 ret.ConnStats = t.stats.Copy()
1421 // The total number of peers in the torrent.
1422 func (t *Torrent) numTotalPeers() int {
1423 peers := make(map[string]struct{})
1424 for conn := range t.conns {
1425 ra := conn.conn.RemoteAddr()
1427 // It's been closed and doesn't support RemoteAddr.
1430 peers[ra.String()] = struct{}{}
1432 for addr := range t.halfOpen {
1433 peers[addr] = struct{}{}
1435 t.peers.Each(func(peer Peer) {
1436 peers[peer.Addr.String()] = struct{}{}
1441 // Reconcile bytes transferred before connection was associated with a
1443 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1444 if c._stats != (ConnStats{
1445 // Handshakes should only increment these fields:
1446 BytesWritten: c._stats.BytesWritten,
1447 BytesRead: c._stats.BytesRead,
1451 c.postHandshakeStats(func(cs *ConnStats) {
1452 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1453 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1455 c.reconciledHandshakeStats = true
1458 // Returns true if the connection is added.
1459 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1462 torrent.Add("added connections", 1)
1465 if t.closed.IsSet() {
1466 return errors.New("torrent closed")
1468 for c0 := range t.conns {
1469 if c.PeerID != c0.PeerID {
1472 if !t.cl.config.dropDuplicatePeerIds {
1475 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1477 t.deleteConnection(c0)
1479 return errors.New("existing connection preferred")
1482 if len(t.conns) >= t.maxEstablishedConns {
1483 c := t.worstBadConn()
1485 return errors.New("don't want conns")
1488 t.deleteConnection(c)
1490 if len(t.conns) >= t.maxEstablishedConns {
1493 t.conns[c] = struct{}{}
1497 func (t *Torrent) wantConns() bool {
1498 if !t.networkingEnabled {
1501 if t.closed.IsSet() {
1504 if !t.seeding() && !t.needData() {
1507 if len(t.conns) < t.maxEstablishedConns {
1510 return t.worstBadConn() != nil
1513 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1516 oldMax = t.maxEstablishedConns
1517 t.maxEstablishedConns = max
1518 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1519 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1520 t.dropConnection(wcs.Pop().(*PeerConn))
1526 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1527 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).WithValues(debugLogValue))
1530 t.cl.event.Broadcast()
1531 if t.closed.IsSet() {
1535 // Don't score the first time a piece is hashed, it could be an initial check.
1536 if p.storageCompletionOk {
1538 pieceHashedCorrect.Add(1)
1540 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1541 pieceHashedNotCorrect.Add(1)
1546 if len(p.dirtiers) != 0 {
1547 // Don't increment stats above connection-level for every involved connection.
1548 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1550 for c := range p.dirtiers {
1551 c._stats.incrementPiecesDirtiedGood()
1553 t.clearPieceTouchers(piece)
1554 err := p.Storage().MarkComplete()
1556 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1558 t.pendAllChunkSpecs(piece)
1560 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1561 // Peers contributed to all the data for this piece hash failure, and the failure was
1562 // not due to errors in the storage (such as data being dropped in a cache).
1564 // Increment Torrent and above stats, and then specific connections.
1565 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1566 for c := range p.dirtiers {
1567 // Y u do dis peer?!
1568 c.stats().incrementPiecesDirtiedBad()
1571 bannableTouchers := make([]*PeerConn, 0, len(p.dirtiers))
1572 for c := range p.dirtiers {
1574 bannableTouchers = append(bannableTouchers, c)
1577 t.clearPieceTouchers(piece)
1578 slices.Sort(bannableTouchers, connLessTrusted)
1580 if t.cl.config.Debug {
1582 "bannable conns by trust for piece %d: %v",
1584 func() (ret []connectionTrust) {
1585 for _, c := range bannableTouchers {
1586 ret = append(ret, c.trust())
1593 if len(bannableTouchers) >= 1 {
1594 c := bannableTouchers[0]
1595 t.cl.banPeerIP(c.remoteIp())
1599 t.onIncompletePiece(piece)
1600 p.Storage().MarkNotComplete()
1602 t.updatePieceCompletion(piece)
1605 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1606 // TODO: Make faster
1607 for cn := range t.conns {
1612 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1613 t.pendAllChunkSpecs(piece)
1614 t.cancelRequestsForPiece(piece)
1615 for conn := range t.conns {
1620 // Called when a piece is found to be not complete.
1621 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1622 if t.pieceAllDirty(piece) {
1623 t.pendAllChunkSpecs(piece)
1625 if !t.wantPieceIndex(piece) {
1626 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1629 // We could drop any connections that we told we have a piece that we
1630 // don't here. But there's a test failure, and it seems clients don't care
1631 // if you request pieces that you already claim to have. Pruning bad
1632 // connections might just remove any connections that aren't treating us
1633 // favourably anyway.
1635 // for c := range t.conns {
1636 // if c.sentHave(piece) {
1640 for conn := range t.conns {
1641 if conn.peerHasPiece(piece) {
1642 conn.updateRequests()
1647 func (t *Torrent) tryCreateMorePieceHashers() {
1648 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1652 func (t *Torrent) tryCreatePieceHasher() bool {
1653 if t.storage == nil {
1656 pi, ok := t.getPieceToHash()
1661 t.piecesQueuedForHash.Remove(pi)
1663 t.publishPieceChange(pi)
1664 t.updatePiecePriority(pi)
1665 t.storageLock.RLock()
1666 t.activePieceHashes++
1667 go t.pieceHasher(pi)
1671 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1672 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1673 if t.piece(i).hashing {
1683 func (t *Torrent) pieceHasher(index pieceIndex) {
1685 sum, copyErr := t.hashPiece(index)
1686 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}