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/bitmap"
22 "github.com/anacrolix/missinggo/perf"
23 "github.com/anacrolix/missinggo/prioritybitmap"
24 "github.com/anacrolix/missinggo/pubsub"
25 "github.com/anacrolix/missinggo/slices"
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 func (t *Torrent) chunkIndexSpec(chunkIndex pp.Integer, piece pieceIndex) chunkSpec {
35 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
38 // Maintains state of torrent within a Client. Many methods should not be called before the info is
39 // available, see .Info and .GotInfo.
41 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
42 // alignment. See #262.
47 networkingEnabled bool
49 // Determines what chunks to request from peers. 1: Favour higher priority
50 // pieces with some fuzzing to reduce overlaps and wastage across
51 // connections. 2: The fastest connection downloads strictly in order of
52 // priority, while all others adher to their piece inclications. 3:
53 // Requests are strictly by piece priority, and not duplicated until
54 // duplicateRequestTimeout is reached.
56 // How long to avoid duplicating a pending request.
57 duplicateRequestTimeout time.Duration
59 closed missinggo.Event
60 infoHash metainfo.Hash
62 // Values are the piece indices that changed.
63 pieceStateChanges *pubsub.PubSub
64 // The size of chunks to request from peers over the wire. This is
65 // normally 16KiB by convention these days.
68 // Total length of the torrent in bytes. Stored because it's not O(1) to
69 // get this from the info dict.
72 // The storage to open when the info dict becomes available.
73 storageOpener *storage.Client
74 // Storage for torrent data.
75 storage *storage.Torrent
76 // Read-locked for using storage, and write-locked for Closing.
77 storageLock sync.RWMutex
79 // TODO: Only announce stuff is used?
80 metainfo metainfo.MetaInfo
82 // The info dict. nil if we don't have it (yet).
86 // Active peer connections, running message stream loops. TODO: Make this
87 // open (not-closed) connections only.
88 conns map[*connection]struct{}
89 maxEstablishedConns int
90 // Set of addrs to which we're attempting to connect. Connections are
91 // half-open until all handshakes are completed.
92 halfOpen map[string]Peer
93 fastestConn *connection
95 // Reserve of peers to connect to. A peer can be both here and in the
96 // active connections if were told about the peer after connecting with
97 // them. That encourages us to reconnect to peers that are well known in
99 peers prioritizedPeers
100 wantPeersEvent missinggo.Event
101 // An announcer for each tracker URL.
102 trackerAnnouncers map[string]*trackerScraper
103 // How many times we've initiated a DHT announce. TODO: Move into stats.
106 // Name used if the info name isn't available. Should be cleared when the
107 // Info does become available.
111 // The bencoded bytes of the info dict. This is actively manipulated if
112 // the info bytes aren't initially available, and we try to fetch them
115 // Each element corresponds to the 16KiB metadata pieces. If true, we have
116 // received that piece.
117 metadataCompletedChunks []bool
118 metadataChanged sync.Cond
120 // Set when .Info is obtained.
121 gotMetainfo missinggo.Event
123 readers map[*reader]struct{}
124 readerNowPieces bitmap.Bitmap
125 readerReadaheadPieces bitmap.Bitmap
127 // A cache of pieces we need to get. Calculated from various piece and
128 // file priorities and completion states elsewhere.
129 pendingPieces prioritybitmap.PriorityBitmap
130 // A cache of completed piece indices.
131 completedPieces bitmap.Bitmap
132 // Pieces that need to be hashed.
133 piecesQueuedForHash bitmap.Bitmap
134 activePieceHashes int
136 // A pool of piece priorities []int for assignment to new connections.
137 // These "inclinations" are used to give connections preference for
139 connPieceInclinationPool sync.Pool
141 // Count of each request across active connections.
142 pendingRequests map[request]int
143 // The last time we requested a chunk. Deleting the request from any
144 // connection will clear this value.
145 lastRequested map[request]*time.Timer
148 func (t *Torrent) tickleReaders() {
149 t.cl.event.Broadcast()
152 // Returns a channel that is closed when the Torrent is closed.
153 func (t *Torrent) Closed() <-chan struct{} {
154 return t.closed.LockedChan(t.cl.locker())
157 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
158 // pending, and half-open peers.
159 func (t *Torrent) KnownSwarm() (ks []Peer) {
160 // Add pending peers to the list
161 t.peers.Each(func(peer Peer) {
162 ks = append(ks, peer)
165 // Add half-open peers to the list
166 for _, peer := range t.halfOpen {
167 ks = append(ks, peer)
170 // Add active peers to the list
171 for conn := range t.conns {
173 ks = append(ks, Peer{
175 IP: conn.remoteAddr.IP,
176 Port: int(conn.remoteAddr.Port),
177 Source: conn.Discovery,
178 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
179 // > But if we're not connected to them with an encrypted connection, I couldn't say
180 // > what's appropriate. We can carry forward the SupportsEncryption value as we
181 // > received it from trackers/DHT/PEX, or just use the encryption state for the
182 // > connection. It's probably easiest to do the latter for now.
183 // https://github.com/anacrolix/torrent/pull/188
184 SupportsEncryption: conn.headerEncrypted,
191 func (t *Torrent) setChunkSize(size pp.Integer) {
193 t.chunkPool = &sync.Pool{
194 New: func() interface{} {
195 b := make([]byte, size)
201 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
202 return t.completedPieces.Get(bitmap.BitIndex(piece))
205 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
206 return t.pieces[piece].Storage().Completion()
209 // There's a connection to that address already.
210 func (t *Torrent) addrActive(addr string) bool {
211 if _, ok := t.halfOpen[addr]; ok {
214 for c := range t.conns {
216 if ra.String() == addr {
223 func (t *Torrent) unclosedConnsAsSlice() (ret []*connection) {
224 ret = make([]*connection, 0, len(t.conns))
225 for c := range t.conns {
226 if !c.closed.IsSet() {
233 func (t *Torrent) addPeer(p Peer) {
235 peersAddedBySource.Add(string(p.Source), 1)
236 if t.closed.IsSet() {
239 if cl.badPeerIPPort(p.IP, p.Port) {
240 torrent.Add("peers not added because of bad addr", 1)
244 torrent.Add("peers replaced", 1)
247 for t.peers.Len() > cl.config.TorrentPeersHighWater {
248 _, ok := t.peers.DeleteMin()
250 torrent.Add("excess reserve peers discarded", 1)
255 func (t *Torrent) invalidateMetadata() {
256 for i := range t.metadataCompletedChunks {
257 t.metadataCompletedChunks[i] = false
264 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
268 if index >= len(t.metadataCompletedChunks) {
269 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
272 copy(t.metadataBytes[(1<<14)*index:], data)
273 t.metadataCompletedChunks[index] = true
276 func (t *Torrent) metadataPieceCount() int {
277 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
280 func (t *Torrent) haveMetadataPiece(piece int) bool {
282 return (1<<14)*piece < len(t.metadataBytes)
284 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
288 func (t *Torrent) metadataSize() int {
289 return len(t.metadataBytes)
292 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
293 for i := 0; i < len(info.Pieces); i += sha1.Size {
294 ret = append(ret, info.Pieces[i:i+sha1.Size])
299 func (t *Torrent) makePieces() {
300 hashes := infoPieceHashes(t.info)
301 t.pieces = make([]Piece, len(hashes), len(hashes))
302 for i, hash := range hashes {
303 piece := &t.pieces[i]
305 piece.index = pieceIndex(i)
306 piece.noPendingWrites.L = &piece.pendingWritesMutex
307 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
309 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
310 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
311 piece.files = files[beginFile:endFile]
315 // Returns the index of the first file containing the piece. files must be
316 // ordered by offset.
317 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
318 for i, f := range files {
319 if f.offset+f.length > pieceOffset {
326 // Returns the index after the last file containing the piece. files must be
327 // ordered by offset.
328 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
329 for i, f := range files {
330 if f.offset+f.length >= pieceEndOffset {
337 func (t *Torrent) cacheLength() {
339 for _, f := range t.info.UpvertedFiles() {
345 func (t *Torrent) setInfo(info *metainfo.Info) error {
346 if err := validateInfo(info); err != nil {
347 return fmt.Errorf("bad info: %s", err)
349 if t.storageOpener != nil {
351 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
353 return fmt.Errorf("error opening torrent storage: %s", err)
359 t.displayName = "" // Save a few bytes lol.
366 func (t *Torrent) onSetInfo() {
367 for conn := range t.conns {
368 if err := conn.setNumPieces(t.numPieces()); err != nil {
369 t.logger.Printf("closing connection: %s", err)
373 for i := range t.pieces {
374 t.updatePieceCompletion(pieceIndex(i))
376 if !p.storageCompletionOk {
377 // t.logger.Printf("piece %s completion unknown, queueing check", p)
378 t.queuePieceCheck(pieceIndex(i))
381 t.cl.event.Broadcast()
383 t.updateWantPeersEvent()
384 t.pendingRequests = make(map[request]int)
385 t.lastRequested = make(map[request]*time.Timer)
386 t.tryCreateMorePieceHashers()
389 // Called when metadata for a torrent becomes available.
390 func (t *Torrent) setInfoBytes(b []byte) error {
391 if metainfo.HashBytes(b) != t.infoHash {
392 return errors.New("info bytes have wrong hash")
394 var info metainfo.Info
395 if err := bencode.Unmarshal(b, &info); err != nil {
396 return fmt.Errorf("error unmarshalling info bytes: %s", err)
398 if err := t.setInfo(&info); err != nil {
402 t.metadataCompletedChunks = nil
407 func (t *Torrent) haveAllMetadataPieces() bool {
411 if t.metadataCompletedChunks == nil {
414 for _, have := range t.metadataCompletedChunks {
422 // TODO: Propagate errors to disconnect peer.
423 func (t *Torrent) setMetadataSize(bytes int) (err error) {
425 // We already know the correct metadata size.
428 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
429 return errors.New("bad size")
431 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
434 t.metadataBytes = make([]byte, bytes)
435 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
436 t.metadataChanged.Broadcast()
437 for c := range t.conns {
438 c.requestPendingMetadata()
443 // The current working name for the torrent. Either the name in the info dict,
444 // or a display name given such as by the dn value in a magnet link, or "".
445 func (t *Torrent) name() string {
447 defer t.nameMu.RUnlock()
454 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
455 p := &t.pieces[index]
456 ret.Priority = t.piecePriority(index)
457 ret.Completion = p.completion()
458 if p.queuedForHash() || p.hashing {
461 if !ret.Complete && t.piecePartiallyDownloaded(index) {
467 func (t *Torrent) metadataPieceSize(piece int) int {
468 return metadataPieceSize(len(t.metadataBytes), piece)
471 func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
477 d["total_size"] = len(t.metadataBytes)
479 p := bencode.MustMarshal(d)
482 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
483 ExtendedPayload: append(p, data...),
487 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
488 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
489 ret = append(ret, PieceStateRun{
490 PieceState: el.(PieceState),
494 for index := range t.pieces {
495 rle.Append(t.pieceState(pieceIndex(index)), 1)
501 // Produces a small string representing a PieceStateRun.
502 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
503 ret = fmt.Sprintf("%d", psr.Length)
504 ret += func() string {
505 switch psr.Priority {
506 case PiecePriorityNext:
508 case PiecePriorityNormal:
510 case PiecePriorityReadahead:
512 case PiecePriorityNow:
514 case PiecePriorityHigh:
535 func (t *Torrent) writeStatus(w io.Writer) {
536 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
537 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
539 fmt.Fprintf(w, "Metadata have: ")
540 for _, h := range t.metadataCompletedChunks {
541 fmt.Fprintf(w, "%c", func() rune {
551 fmt.Fprintf(w, "Piece length: %s\n", func() string {
553 return fmt.Sprint(t.usualPieceSize())
559 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
560 fmt.Fprint(w, "Piece States:")
561 for _, psr := range t.pieceStateRuns() {
563 w.Write([]byte(pieceStateRunStatusChars(psr)))
567 fmt.Fprintf(w, "Reader Pieces:")
568 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
569 fmt.Fprintf(w, " %d:%d", begin, end)
574 fmt.Fprintf(w, "Enabled trackers:\n")
576 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
577 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
578 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
581 var luns, runs url.URL = lu, ru
584 var ml missinggo.MultiLess
585 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
586 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
588 }).([]*trackerScraper) {
589 fmt.Fprintf(tw, " %s\n", ta.statusLine())
594 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
596 spew.NewDefaultConfig()
597 spew.Fdump(w, t.statsLocked())
599 conns := t.connsAsSlice()
600 slices.Sort(conns, worseConn)
601 for i, c := range conns {
602 fmt.Fprintf(w, "%2d. ", i+1)
607 func (t *Torrent) haveInfo() bool {
611 // Returns a run-time generated MetaInfo that includes the info bytes and
612 // announce-list as currently known to the client.
613 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
614 return metainfo.MetaInfo{
615 CreationDate: time.Now().Unix(),
616 Comment: "dynamic metainfo from client",
617 CreatedBy: "go.torrent",
618 AnnounceList: t.metainfo.UpvertedAnnounceList(),
619 InfoBytes: func() []byte {
621 return t.metadataBytes
629 func (t *Torrent) BytesMissing() int64 {
632 return t.bytesMissingLocked()
635 func (t *Torrent) bytesMissingLocked() int64 {
639 func (t *Torrent) bytesLeft() (left int64) {
640 bitmap.Flip(t.completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
641 p := &t.pieces[piece]
642 left += int64(p.length() - p.numDirtyBytes())
648 // Bytes left to give in tracker announces.
649 func (t *Torrent) bytesLeftAnnounce() int64 {
657 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
658 if t.pieceComplete(piece) {
661 if t.pieceAllDirty(piece) {
664 return t.pieces[piece].hasDirtyChunks()
667 func (t *Torrent) usualPieceSize() int {
668 return int(t.info.PieceLength)
671 func (t *Torrent) numPieces() pieceIndex {
672 return pieceIndex(t.info.NumPieces())
675 func (t *Torrent) numPiecesCompleted() (num int) {
676 return t.completedPieces.Len()
679 func (t *Torrent) close() (err error) {
682 if t.storage != nil {
685 t.storageLock.Unlock()
687 for conn := range t.conns {
690 t.cl.event.Broadcast()
691 t.pieceStateChanges.Close()
692 t.updateWantPeersEvent()
696 func (t *Torrent) requestOffset(r request) int64 {
697 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
700 // Return the request that would include the given offset into the torrent
701 // data. Returns !ok if there is no such request.
702 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
703 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
706 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
707 defer perf.ScopeTimerErr(&err)()
708 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
709 if err == nil && n != len(data) {
710 err = io.ErrShortWrite
715 func (t *Torrent) bitfield() (bf []bool) {
716 bf = make([]bool, t.numPieces())
717 t.completedPieces.IterTyped(func(piece int) (again bool) {
724 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
725 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
728 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
729 t.pieces[pieceIndex].dirtyChunks.Clear()
732 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
733 if t.info.PieceLength == 0 {
734 // There will be no variance amongst pieces. Only pain.
737 if piece == t.numPieces()-1 {
738 ret := pp.Integer(*t.length % t.info.PieceLength)
743 return pp.Integer(t.info.PieceLength)
746 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, copyErr error) {
747 hash := pieceHash.New()
749 p.waitNoPendingWrites()
750 ip := t.info.Piece(int(piece))
752 _, copyErr = io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
753 missinggo.CopyExact(&ret, hash.Sum(nil))
757 func (t *Torrent) haveAnyPieces() bool {
758 return t.completedPieces.Len() != 0
761 func (t *Torrent) haveAllPieces() bool {
765 return t.completedPieces.Len() == bitmap.BitIndex(t.numPieces())
768 func (t *Torrent) havePiece(index pieceIndex) bool {
769 return t.haveInfo() && t.pieceComplete(index)
772 func (t *Torrent) haveChunk(r request) (ret bool) {
774 // log.Println("have chunk", r, ret)
779 if t.pieceComplete(pieceIndex(r.Index)) {
782 p := &t.pieces[r.Index]
783 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
786 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
787 return int(cs.Begin / chunkSize)
790 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
794 if index < 0 || index >= t.numPieces() {
797 p := &t.pieces[index]
798 if p.queuedForHash() {
804 if t.pieceComplete(index) {
807 if t.pendingPieces.Contains(bitmap.BitIndex(index)) {
810 // t.logger.Printf("piece %d not pending", index)
811 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
812 return index < begin || index >= end
816 // The worst connection is one that hasn't been sent, or sent anything useful
817 // for the longest. A bad connection is one that usually sends us unwanted
818 // pieces, or has been in worser half of the established connections for more
820 func (t *Torrent) worstBadConn() *connection {
821 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
824 c := heap.Pop(&wcs).(*connection)
825 if c.stats.ChunksReadWasted.Int64() >= 6 && c.stats.ChunksReadWasted.Int64() > c.stats.ChunksReadUseful.Int64() {
828 // If the connection is in the worst half of the established
829 // connection quota and is older than a minute.
830 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
831 // Give connections 1 minute to prove themselves.
832 if time.Since(c.completedHandshake) > time.Minute {
840 type PieceStateChange struct {
845 func (t *Torrent) publishPieceChange(piece pieceIndex) {
846 t.cl._mu.Defer(func() {
847 cur := t.pieceState(piece)
848 p := &t.pieces[piece]
849 if cur != p.publicPieceState {
850 p.publicPieceState = cur
851 t.pieceStateChanges.Publish(PieceStateChange{
859 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
860 if t.pieceComplete(piece) {
863 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
866 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
867 return t.pieces[piece].dirtyChunks.Len() == int(t.pieceNumChunks(piece))
870 func (t *Torrent) readersChanged() {
871 t.updateReaderPieces()
872 t.updateAllPiecePriorities()
875 func (t *Torrent) updateReaderPieces() {
876 t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
879 func (t *Torrent) readerPosChanged(from, to pieceRange) {
883 t.updateReaderPieces()
884 // Order the ranges, high and low.
886 if l.begin > h.begin {
890 // Two distinct ranges.
891 t.updatePiecePriorities(l.begin, l.end)
892 t.updatePiecePriorities(h.begin, h.end)
899 t.updatePiecePriorities(l.begin, end)
903 func (t *Torrent) maybeNewConns() {
904 // Tickle the accept routine.
905 t.cl.event.Broadcast()
909 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
910 // t.logger.Printf("piece %d priority changed", piece)
911 for c := range t.conns {
912 if c.updatePiecePriority(piece) {
913 // log.Print("conn piece priority changed")
918 t.publishPieceChange(piece)
921 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
922 p := &t.pieces[piece]
923 newPrio := p.uncachedPriority()
924 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
925 if newPrio == PiecePriorityNone {
926 if !t.pendingPieces.Remove(bitmap.BitIndex(piece)) {
930 if !t.pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
934 t.piecePriorityChanged(piece)
937 func (t *Torrent) updateAllPiecePriorities() {
938 t.updatePiecePriorities(0, t.numPieces())
941 // Update all piece priorities in one hit. This function should have the same
942 // output as updatePiecePriority, but across all pieces.
943 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
944 for i := begin; i < end; i++ {
945 t.updatePiecePriority(i)
949 // Returns the range of pieces [begin, end) that contains the extent of bytes.
950 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
951 if off >= *t.length {
961 begin = pieceIndex(off / t.info.PieceLength)
962 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
963 if end > pieceIndex(t.info.NumPieces()) {
964 end = pieceIndex(t.info.NumPieces())
969 // Returns true if all iterations complete without breaking. Returns the read
970 // regions for all readers. The reader regions should not be merged as some
971 // callers depend on this method to enumerate readers.
972 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
973 for r := range t.readers {
975 if p.begin >= p.end {
978 if !f(p.begin, p.end) {
985 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
986 prio, ok := t.pendingPieces.GetPriority(bitmap.BitIndex(piece))
988 return PiecePriorityNone
993 ret := piecePriority(-prio)
994 if ret == PiecePriorityNone {
1000 func (t *Torrent) pendRequest(req request) {
1001 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1002 t.pieces[req.Index].pendChunkIndex(ci)
1005 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1007 t.cl.event.Broadcast()
1008 if t.pieceComplete(piece) {
1009 t.onPieceCompleted(piece)
1011 t.onIncompletePiece(piece)
1013 t.updatePiecePriority(piece)
1016 func (t *Torrent) numReceivedConns() (ret int) {
1017 for c := range t.conns {
1018 if c.Discovery == peerSourceIncoming {
1025 func (t *Torrent) maxHalfOpen() int {
1026 // Note that if we somehow exceed the maximum established conns, we want
1027 // the negative value to have an effect.
1028 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1029 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1030 // We want to allow some experimentation with new peers, and to try to
1031 // upset an oversupply of received connections.
1032 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1035 func (t *Torrent) openNewConns() {
1036 defer t.updateWantPeersEvent()
1037 for t.peers.Len() != 0 {
1041 if len(t.halfOpen) >= t.maxHalfOpen() {
1044 p := t.peers.PopMax()
1049 func (t *Torrent) getConnPieceInclination() []int {
1050 _ret := t.connPieceInclinationPool.Get()
1052 pieceInclinationsNew.Add(1)
1053 return rand.Perm(int(t.numPieces()))
1055 pieceInclinationsReused.Add(1)
1056 return *_ret.(*[]int)
1059 func (t *Torrent) putPieceInclination(pi []int) {
1060 t.connPieceInclinationPool.Put(&pi)
1061 pieceInclinationsPut.Add(1)
1064 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1066 uncached := t.pieceCompleteUncached(piece)
1067 cached := p.completion()
1068 changed := cached != uncached
1069 complete := uncached.Complete
1070 p.storageCompletionOk = uncached.Ok
1071 t.completedPieces.Set(bitmap.BitIndex(piece), complete)
1072 if complete && len(p.dirtiers) != 0 {
1073 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1076 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).WithValues(debugLogValue).Log(t.logger)
1077 t.pieceCompletionChanged(piece)
1082 // Non-blocking read. Client lock is not required.
1083 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1084 p := &t.pieces[off/t.info.PieceLength]
1085 p.waitNoPendingWrites()
1086 return p.Storage().ReadAt(b, off-p.Info().Offset())
1089 func (t *Torrent) updateAllPieceCompletions() {
1090 for i := pieceIndex(0); i < t.numPieces(); i++ {
1091 t.updatePieceCompletion(i)
1095 // Returns an error if the metadata was completed, but couldn't be set for
1096 // some reason. Blame it on the last peer to contribute.
1097 func (t *Torrent) maybeCompleteMetadata() error {
1102 if !t.haveAllMetadataPieces() {
1103 // Don't have enough metadata pieces.
1106 err := t.setInfoBytes(t.metadataBytes)
1108 t.invalidateMetadata()
1109 return fmt.Errorf("error setting info bytes: %s", err)
1111 if t.cl.config.Debug {
1112 t.logger.Printf("%s: got metadata from peers", t)
1117 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1118 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1120 now.Add(bitmap.BitIndex(begin))
1121 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1128 func (t *Torrent) needData() bool {
1129 if t.closed.IsSet() {
1135 return t.pendingPieces.Len() != 0
1138 func appendMissingStrings(old, new []string) (ret []string) {
1141 for _, n := range new {
1142 for _, o := range old {
1147 ret = append(ret, n)
1152 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1154 for minNumTiers > len(ret) {
1155 ret = append(ret, nil)
1160 func (t *Torrent) addTrackers(announceList [][]string) {
1161 fullAnnounceList := &t.metainfo.AnnounceList
1162 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1163 for tierIndex, trackerURLs := range announceList {
1164 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1166 t.startMissingTrackerScrapers()
1167 t.updateWantPeersEvent()
1170 // Don't call this before the info is available.
1171 func (t *Torrent) bytesCompleted() int64 {
1175 return t.info.TotalLength() - t.bytesLeft()
1178 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1181 return t.setInfoBytes(b)
1184 // Returns true if connection is removed from torrent.Conns.
1185 func (t *Torrent) deleteConnection(c *connection) (ret bool) {
1186 if !c.closed.IsSet() {
1187 panic("connection is not closed")
1188 // There are behaviours prevented by the closed state that will fail
1189 // if the connection has been deleted.
1193 torrent.Add("deleted connections", 1)
1194 c.deleteAllRequests()
1195 if len(t.conns) == 0 {
1196 t.assertNoPendingRequests()
1201 func (t *Torrent) assertNoPendingRequests() {
1202 if len(t.pendingRequests) != 0 {
1203 panic(t.pendingRequests)
1205 if len(t.lastRequested) != 0 {
1206 panic(t.lastRequested)
1210 func (t *Torrent) dropConnection(c *connection) {
1211 t.cl.event.Broadcast()
1213 if t.deleteConnection(c) {
1218 func (t *Torrent) wantPeers() bool {
1219 if t.closed.IsSet() {
1222 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1225 return t.needData() || t.seeding()
1228 func (t *Torrent) updateWantPeersEvent() {
1230 t.wantPeersEvent.Set()
1232 t.wantPeersEvent.Clear()
1236 // Returns whether the client should make effort to seed the torrent.
1237 func (t *Torrent) seeding() bool {
1239 if t.closed.IsSet() {
1242 if cl.config.NoUpload {
1245 if !cl.config.Seed {
1248 if cl.config.DisableAggressiveUpload && t.needData() {
1254 func (t *Torrent) startScrapingTracker(_url string) {
1258 u, err := url.Parse(_url)
1260 // URLs with a leading '*' appear to be a uTorrent convention to
1261 // disable trackers.
1263 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1267 if u.Scheme == "udp" {
1269 t.startScrapingTracker(u.String())
1271 t.startScrapingTracker(u.String())
1274 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1277 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1280 if _, ok := t.trackerAnnouncers[_url]; ok {
1283 newAnnouncer := &trackerScraper{
1287 if t.trackerAnnouncers == nil {
1288 t.trackerAnnouncers = make(map[string]*trackerScraper)
1290 t.trackerAnnouncers[_url] = newAnnouncer
1291 go newAnnouncer.Run()
1294 // Adds and starts tracker scrapers for tracker URLs that aren't already
1296 func (t *Torrent) startMissingTrackerScrapers() {
1297 if t.cl.config.DisableTrackers {
1300 t.startScrapingTracker(t.metainfo.Announce)
1301 for _, tier := range t.metainfo.AnnounceList {
1302 for _, url := range tier {
1303 t.startScrapingTracker(url)
1308 // Returns an AnnounceRequest with fields filled out to defaults and current
1310 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1311 // Note that IPAddress is not set. It's set for UDP inside the tracker
1312 // code, since it's dependent on the network in use.
1313 return tracker.AnnounceRequest{
1316 Port: uint16(t.cl.incomingPeerPort()),
1317 PeerId: t.cl.peerID,
1318 InfoHash: t.infoHash,
1319 Key: t.cl.announceKey(),
1321 // The following are vaguely described in BEP 3.
1323 Left: t.bytesLeftAnnounce(),
1324 Uploaded: t.stats.BytesWrittenData.Int64(),
1325 // There's no mention of wasted or unwanted download in the BEP.
1326 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1330 // Adds peers revealed in an announce until the announce ends, or we have
1332 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1334 for v := range pvs {
1336 for _, cp := range v.Peers {
1338 // Can't do anything with this.
1344 Source: peerSourceDhtGetPeers,
1351 func (t *Torrent) announceToDht(impliedPort bool, s *dht.Server) error {
1352 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1356 go t.consumeDhtAnnouncePeers(ps.Peers)
1358 case <-t.closed.LockedChan(t.cl.locker()):
1359 case <-time.After(5 * time.Minute):
1365 func (t *Torrent) dhtAnnouncer(s *dht.Server) {
1369 case <-t.closed.LockedChan(cl.locker()):
1371 case <-t.wantPeersEvent.LockedChan(cl.locker()):
1376 err := t.announceToDht(true, s)
1378 t.logger.Printf("error announcing %q to DHT: %s", t, err)
1383 func (t *Torrent) addPeers(peers []Peer) {
1384 for _, p := range peers {
1389 func (t *Torrent) Stats() TorrentStats {
1391 defer t.cl.rUnlock()
1392 return t.statsLocked()
1395 func (t *Torrent) statsLocked() (ret TorrentStats) {
1396 ret.ActivePeers = len(t.conns)
1397 ret.HalfOpenPeers = len(t.halfOpen)
1398 ret.PendingPeers = t.peers.Len()
1399 ret.TotalPeers = t.numTotalPeers()
1400 ret.ConnectedSeeders = 0
1401 for c := range t.conns {
1402 if all, ok := c.peerHasAllPieces(); all && ok {
1403 ret.ConnectedSeeders++
1406 ret.ConnStats = t.stats.Copy()
1410 // The total number of peers in the torrent.
1411 func (t *Torrent) numTotalPeers() int {
1412 peers := make(map[string]struct{})
1413 for conn := range t.conns {
1414 ra := conn.conn.RemoteAddr()
1416 // It's been closed and doesn't support RemoteAddr.
1419 peers[ra.String()] = struct{}{}
1421 for addr := range t.halfOpen {
1422 peers[addr] = struct{}{}
1424 t.peers.Each(func(peer Peer) {
1425 peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{}
1430 // Reconcile bytes transferred before connection was associated with a
1432 func (t *Torrent) reconcileHandshakeStats(c *connection) {
1433 if c.stats != (ConnStats{
1434 // Handshakes should only increment these fields:
1435 BytesWritten: c.stats.BytesWritten,
1436 BytesRead: c.stats.BytesRead,
1440 c.postHandshakeStats(func(cs *ConnStats) {
1441 cs.BytesRead.Add(c.stats.BytesRead.Int64())
1442 cs.BytesWritten.Add(c.stats.BytesWritten.Int64())
1444 c.reconciledHandshakeStats = true
1447 // Returns true if the connection is added.
1448 func (t *Torrent) addConnection(c *connection) (err error) {
1451 torrent.Add("added connections", 1)
1454 if t.closed.IsSet() {
1455 return errors.New("torrent closed")
1457 for c0 := range t.conns {
1458 if c.PeerID != c0.PeerID {
1461 if !t.cl.config.dropDuplicatePeerIds {
1464 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1466 t.deleteConnection(c0)
1468 return errors.New("existing connection preferred")
1471 if len(t.conns) >= t.maxEstablishedConns {
1472 c := t.worstBadConn()
1474 return errors.New("don't want conns")
1477 t.deleteConnection(c)
1479 if len(t.conns) >= t.maxEstablishedConns {
1482 t.conns[c] = struct{}{}
1486 func (t *Torrent) wantConns() bool {
1487 if !t.networkingEnabled {
1490 if t.closed.IsSet() {
1493 if !t.seeding() && !t.needData() {
1496 if len(t.conns) < t.maxEstablishedConns {
1499 return t.worstBadConn() != nil
1502 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1505 oldMax = t.maxEstablishedConns
1506 t.maxEstablishedConns = max
1507 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1508 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1509 t.dropConnection(wcs.Pop().(*connection))
1515 func (t *Torrent) pieceHashed(piece pieceIndex, correct bool) {
1516 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, correct).WithValues(debugLogValue))
1519 t.cl.event.Broadcast()
1520 if t.closed.IsSet() {
1524 // Don't score the first time a piece is hashed, it could be an initial check.
1525 if p.storageCompletionOk {
1527 pieceHashedCorrect.Add(1)
1529 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1530 pieceHashedNotCorrect.Add(1)
1535 if len(p.dirtiers) != 0 {
1536 // Don't increment stats above connection-level for every involved connection.
1537 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1539 for c := range p.dirtiers {
1540 c.stats.incrementPiecesDirtiedGood()
1542 t.clearPieceTouchers(piece)
1543 err := p.Storage().MarkComplete()
1545 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1548 if len(p.dirtiers) != 0 && p.allChunksDirty() {
1550 // Increment Torrent and above stats, and then specific connections.
1551 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1552 for c := range p.dirtiers {
1553 // Y u do dis peer?!
1554 c.stats.incrementPiecesDirtiedBad()
1557 bannableTouchers := make([]*connection, 0, len(p.dirtiers))
1558 for c := range p.dirtiers {
1560 bannableTouchers = append(bannableTouchers, c)
1563 t.clearPieceTouchers(piece)
1564 slices.Sort(bannableTouchers, connLessTrusted)
1566 if t.cl.config.Debug {
1568 "bannable conns by trust for piece %d: %v",
1570 func() (ret []connectionTrust) {
1571 for _, c := range bannableTouchers {
1572 ret = append(ret, c.trust())
1579 if len(bannableTouchers) >= 1 {
1580 c := bannableTouchers[0]
1581 t.cl.banPeerIP(c.remoteAddr.IP)
1585 t.onIncompletePiece(piece)
1586 p.Storage().MarkNotComplete()
1588 t.updatePieceCompletion(piece)
1591 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1592 // TODO: Make faster
1593 for cn := range t.conns {
1598 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1599 t.pendAllChunkSpecs(piece)
1600 t.cancelRequestsForPiece(piece)
1601 for conn := range t.conns {
1606 // Called when a piece is found to be not complete.
1607 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1608 if t.pieceAllDirty(piece) {
1609 t.pendAllChunkSpecs(piece)
1611 if !t.wantPieceIndex(piece) {
1612 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1615 // We could drop any connections that we told we have a piece that we
1616 // don't here. But there's a test failure, and it seems clients don't care
1617 // if you request pieces that you already claim to have. Pruning bad
1618 // connections might just remove any connections that aren't treating us
1619 // favourably anyway.
1621 // for c := range t.conns {
1622 // if c.sentHave(piece) {
1626 for conn := range t.conns {
1627 if conn.PeerHasPiece(piece) {
1628 conn.updateRequests()
1633 func (t *Torrent) tryCreateMorePieceHashers() {
1634 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1638 func (t *Torrent) tryCreatePieceHasher() bool {
1639 if t.storage == nil {
1642 pi, ok := t.getPieceToHash()
1647 t.piecesQueuedForHash.Remove(pi)
1649 t.publishPieceChange(pi)
1650 t.updatePiecePriority(pi)
1651 t.storageLock.RLock()
1652 t.activePieceHashes++
1653 go t.pieceHasher(pi)
1657 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1658 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1659 if t.piece(i).hashing {
1669 func (t *Torrent) pieceHasher(index pieceIndex) {
1671 sum, copyErr := t.hashPiece(index)
1672 correct := sum == *p.hash
1674 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1676 t.storageLock.RUnlock()
1680 t.updatePiecePriority(index)
1681 t.pieceHashed(index, correct)
1682 t.publishPieceChange(index)
1683 t.activePieceHashes--
1684 t.tryCreateMorePieceHashers()
1687 // Return the connections that touched a piece, and clear the entries while doing it.
1688 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1690 for c := range p.dirtiers {
1691 delete(c.peerTouchedPieces, pi)
1692 delete(p.dirtiers, c)
1696 func (t *Torrent) connsAsSlice() (ret []*connection) {
1697 for c := range t.conns {
1698 ret = append(ret, c)
1703 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1704 piece := t.piece(pieceIndex)
1705 if piece.queuedForHash() {
1708 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1709 t.publishPieceChange(pieceIndex)
1710 t.updatePiecePriority(pieceIndex)
1711 t.tryCreateMorePieceHashers()
1714 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1715 // before the Info is available.
1716 func (t *Torrent) VerifyData() {
1717 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1718 t.Piece(i).VerifyData()
1722 // Start the process of connecting to the given peer for the given torrent if appropriate.
1723 func (t *Torrent) initiateConn(peer Peer) {
1724 if peer.Id == t.cl.peerID {
1727 if t.cl.badPeerIPPort(peer.IP, peer.Port) && !peer.Trusted {
1730 addr := IpPort{peer.IP, uint16(peer.Port)}
1731 if t.addrActive(addr.String()) {
1734 t.halfOpen[addr.String()] = peer
1735 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1738 // Adds each a trusted, pending peer for each of the Client's addresses.
1739 func (t *Torrent) AddClientPeer(cl *Client) {
1740 t.AddPeers(func() (ps []Peer) {
1741 for _, la := range cl.ListenAddrs() {
1742 ps = append(ps, Peer{
1743 IP: missinggo.AddrIP(la),
1744 Port: missinggo.AddrPort(la),
1752 // All stats that include this Torrent. Useful when we want to increment
1753 // ConnStats but not for every connection.
1754 func (t *Torrent) allStats(f func(*ConnStats)) {
1759 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1760 return t.pieces[i].hashing
1763 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1764 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1767 func (t *Torrent) dialTimeout() time.Duration {
1768 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1771 func (t *Torrent) piece(i int) *Piece {