17 "github.com/davecgh/go-spew/spew"
18 "github.com/pion/datachannel"
20 "github.com/anacrolix/dht/v2"
21 "github.com/anacrolix/log"
22 "github.com/anacrolix/missinggo"
23 "github.com/anacrolix/missinggo/perf"
24 "github.com/anacrolix/missinggo/pubsub"
25 "github.com/anacrolix/missinggo/slices"
26 "github.com/anacrolix/missinggo/v2/bitmap"
27 "github.com/anacrolix/missinggo/v2/prioritybitmap"
29 "github.com/anacrolix/torrent/bencode"
30 "github.com/anacrolix/torrent/metainfo"
31 pp "github.com/anacrolix/torrent/peer_protocol"
32 "github.com/anacrolix/torrent/storage"
33 "github.com/anacrolix/torrent/tracker"
34 "github.com/anacrolix/torrent/webtorrent"
37 // Maintains state of torrent within a Client. Many methods should not be called before the info is
38 // available, see .Info and .GotInfo.
40 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
41 // alignment. See #262.
46 networkingEnabled bool
47 dataDownloadDisallowed bool
48 userOnWriteChunkErr func(error)
50 // Determines what chunks to request from peers.
51 requestStrategy requestStrategy
53 closed missinggo.Event
54 infoHash metainfo.Hash
56 // Values are the piece indices that changed.
57 pieceStateChanges *pubsub.PubSub
58 // The size of chunks to request from peers over the wire. This is
59 // normally 16KiB by convention these days.
62 // Total length of the torrent in bytes. Stored because it's not O(1) to
63 // get this from the info dict.
66 // The storage to open when the info dict becomes available.
67 storageOpener *storage.Client
68 // Storage for torrent data.
69 storage *storage.Torrent
70 // Read-locked for using storage, and write-locked for Closing.
71 storageLock sync.RWMutex
73 // TODO: Only announce stuff is used?
74 metainfo metainfo.MetaInfo
76 // The info dict. nil if we don't have it (yet).
80 // Active peer connections, running message stream loops. TODO: Make this
81 // open (not-closed) connections only.
82 conns map[*PeerConn]struct{}
83 maxEstablishedConns int
84 // Set of addrs to which we're attempting to connect. Connections are
85 // half-open until all handshakes are completed.
86 halfOpen map[string]Peer
89 // Reserve of peers to connect to. A peer can be both here and in the
90 // active connections if were told about the peer after connecting with
91 // them. That encourages us to reconnect to peers that are well known in
93 peers prioritizedPeers
94 wantPeersEvent missinggo.Event
95 // An announcer for each tracker URL.
96 trackerAnnouncers map[string]torrentTrackerAnnouncer
97 // How many times we've initiated a DHT announce. TODO: Move into stats.
100 // Name used if the info name isn't available. Should be cleared when the
101 // Info does become available.
105 // The bencoded bytes of the info dict. This is actively manipulated if
106 // the info bytes aren't initially available, and we try to fetch them
109 // Each element corresponds to the 16KiB metadata pieces. If true, we have
110 // received that piece.
111 metadataCompletedChunks []bool
112 metadataChanged sync.Cond
114 // Set when .Info is obtained.
115 gotMetainfo missinggo.Event
117 readers map[*reader]struct{}
118 _readerNowPieces bitmap.Bitmap
119 _readerReadaheadPieces bitmap.Bitmap
121 // A cache of pieces we need to get. Calculated from various piece and
122 // file priorities and completion states elsewhere.
123 _pendingPieces prioritybitmap.PriorityBitmap
124 // A cache of completed piece indices.
125 _completedPieces bitmap.Bitmap
126 // Pieces that need to be hashed.
127 piecesQueuedForHash bitmap.Bitmap
128 activePieceHashes int
130 // A pool of piece priorities []int for assignment to new connections.
131 // These "inclinations" are used to give connections preference for
133 connPieceInclinationPool sync.Pool
135 // Count of each request across active connections.
136 pendingRequests map[request]int
139 func (t *Torrent) numConns() int {
143 func (t *Torrent) numReaders() int {
144 return len(t.readers)
147 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
148 return t._readerNowPieces
151 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
152 return t._readerReadaheadPieces
155 func (t *Torrent) ignorePieces() bitmap.Bitmap {
156 ret := t._completedPieces.Copy()
157 ret.Union(t.piecesQueuedForHash)
158 for i := 0; i < t.numPieces(); i++ {
159 if t.piece(i).hashing {
166 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
167 return &t._pendingPieces
170 func (t *Torrent) tickleReaders() {
171 t.cl.event.Broadcast()
174 // Returns a channel that is closed when the Torrent is closed.
175 func (t *Torrent) Closed() <-chan struct{} {
176 return t.closed.LockedChan(t.cl.locker())
179 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
180 // pending, and half-open peers.
181 func (t *Torrent) KnownSwarm() (ks []Peer) {
182 // Add pending peers to the list
183 t.peers.Each(func(peer Peer) {
184 ks = append(ks, peer)
187 // Add half-open peers to the list
188 for _, peer := range t.halfOpen {
189 ks = append(ks, peer)
192 // Add active peers to the list
193 for conn := range t.conns {
195 ks = append(ks, Peer{
197 Addr: conn.remoteAddr,
198 Source: conn.Discovery,
199 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
200 // > But if we're not connected to them with an encrypted connection, I couldn't say
201 // > what's appropriate. We can carry forward the SupportsEncryption value as we
202 // > received it from trackers/DHT/PEX, or just use the encryption state for the
203 // > connection. It's probably easiest to do the latter for now.
204 // https://github.com/anacrolix/torrent/pull/188
205 SupportsEncryption: conn.headerEncrypted,
212 func (t *Torrent) setChunkSize(size pp.Integer) {
214 t.chunkPool = &sync.Pool{
215 New: func() interface{} {
216 b := make([]byte, size)
222 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
223 return t._completedPieces.Get(bitmap.BitIndex(piece))
226 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
227 return t.pieces[piece].Storage().Completion()
230 // There's a connection to that address already.
231 func (t *Torrent) addrActive(addr string) bool {
232 if _, ok := t.halfOpen[addr]; ok {
235 for c := range t.conns {
237 if ra.String() == addr {
244 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
245 ret = make([]*PeerConn, 0, len(t.conns))
246 for c := range t.conns {
247 if !c.closed.IsSet() {
254 func (t *Torrent) addPeer(p Peer) {
256 peersAddedBySource.Add(string(p.Source), 1)
257 if t.closed.IsSet() {
260 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
261 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
262 torrent.Add("peers not added because of bad addr", 1)
267 torrent.Add("peers replaced", 1)
270 for t.peers.Len() > cl.config.TorrentPeersHighWater {
271 _, ok := t.peers.DeleteMin()
273 torrent.Add("excess reserve peers discarded", 1)
278 func (t *Torrent) invalidateMetadata() {
279 for i := range t.metadataCompletedChunks {
280 t.metadataCompletedChunks[i] = false
287 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
291 if index >= len(t.metadataCompletedChunks) {
292 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
295 copy(t.metadataBytes[(1<<14)*index:], data)
296 t.metadataCompletedChunks[index] = true
299 func (t *Torrent) metadataPieceCount() int {
300 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
303 func (t *Torrent) haveMetadataPiece(piece int) bool {
305 return (1<<14)*piece < len(t.metadataBytes)
307 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
311 func (t *Torrent) metadataSize() int {
312 return len(t.metadataBytes)
315 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
316 for i := 0; i < len(info.Pieces); i += sha1.Size {
317 ret = append(ret, info.Pieces[i:i+sha1.Size])
322 func (t *Torrent) makePieces() {
323 hashes := infoPieceHashes(t.info)
324 t.pieces = make([]Piece, len(hashes))
325 for i, hash := range hashes {
326 piece := &t.pieces[i]
328 piece.index = pieceIndex(i)
329 piece.noPendingWrites.L = &piece.pendingWritesMutex
330 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
332 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
333 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
334 piece.files = files[beginFile:endFile]
338 // Returns the index of the first file containing the piece. files must be
339 // ordered by offset.
340 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
341 for i, f := range files {
342 if f.offset+f.length > pieceOffset {
349 // Returns the index after the last file containing the piece. files must be
350 // ordered by offset.
351 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
352 for i, f := range files {
353 if f.offset+f.length >= pieceEndOffset {
360 func (t *Torrent) cacheLength() {
362 for _, f := range t.info.UpvertedFiles() {
368 func (t *Torrent) setInfo(info *metainfo.Info) error {
369 if err := validateInfo(info); err != nil {
370 return fmt.Errorf("bad info: %s", err)
372 if t.storageOpener != nil {
374 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
376 return fmt.Errorf("error opening torrent storage: %s", err)
382 t.displayName = "" // Save a few bytes lol.
389 func (t *Torrent) onSetInfo() {
390 for conn := range t.conns {
391 if err := conn.setNumPieces(t.numPieces()); err != nil {
392 t.logger.Printf("closing connection: %s", err)
396 for i := range t.pieces {
397 t.updatePieceCompletion(pieceIndex(i))
399 if !p.storageCompletionOk {
400 // t.logger.Printf("piece %s completion unknown, queueing check", p)
401 t.queuePieceCheck(pieceIndex(i))
404 t.cl.event.Broadcast()
406 t.updateWantPeersEvent()
407 t.pendingRequests = make(map[request]int)
408 t.tryCreateMorePieceHashers()
411 // Called when metadata for a torrent becomes available.
412 func (t *Torrent) setInfoBytes(b []byte) error {
413 if metainfo.HashBytes(b) != t.infoHash {
414 return errors.New("info bytes have wrong hash")
416 var info metainfo.Info
417 if err := bencode.Unmarshal(b, &info); err != nil {
418 return fmt.Errorf("error unmarshalling info bytes: %s", err)
420 if err := t.setInfo(&info); err != nil {
424 t.metadataCompletedChunks = nil
429 func (t *Torrent) haveAllMetadataPieces() bool {
433 if t.metadataCompletedChunks == nil {
436 for _, have := range t.metadataCompletedChunks {
444 // TODO: Propagate errors to disconnect peer.
445 func (t *Torrent) setMetadataSize(bytes int) (err error) {
447 // We already know the correct metadata size.
450 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
451 return errors.New("bad size")
453 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
456 t.metadataBytes = make([]byte, bytes)
457 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
458 t.metadataChanged.Broadcast()
459 for c := range t.conns {
460 c.requestPendingMetadata()
465 // The current working name for the torrent. Either the name in the info dict,
466 // or a display name given such as by the dn value in a magnet link, or "".
467 func (t *Torrent) name() string {
469 defer t.nameMu.RUnlock()
476 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
477 p := &t.pieces[index]
478 ret.Priority = t.piecePriority(index)
479 ret.Completion = p.completion()
480 if p.queuedForHash() || p.hashing {
483 if !ret.Complete && t.piecePartiallyDownloaded(index) {
489 func (t *Torrent) metadataPieceSize(piece int) int {
490 return metadataPieceSize(len(t.metadataBytes), piece)
493 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
499 d["total_size"] = len(t.metadataBytes)
501 p := bencode.MustMarshal(d)
504 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
505 ExtendedPayload: append(p, data...),
509 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
510 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
511 ret = append(ret, PieceStateRun{
512 PieceState: el.(PieceState),
516 for index := range t.pieces {
517 rle.Append(t.pieceState(pieceIndex(index)), 1)
523 // Produces a small string representing a PieceStateRun.
524 func (psr PieceStateRun) String() (ret string) {
525 ret = fmt.Sprintf("%d", psr.Length)
526 ret += func() string {
527 switch psr.Priority {
528 case PiecePriorityNext:
530 case PiecePriorityNormal:
532 case PiecePriorityReadahead:
534 case PiecePriorityNow:
536 case PiecePriorityHigh:
557 func (t *Torrent) writeStatus(w io.Writer) {
558 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
559 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
561 fmt.Fprintf(w, "Metadata have: ")
562 for _, h := range t.metadataCompletedChunks {
563 fmt.Fprintf(w, "%c", func() rune {
573 fmt.Fprintf(w, "Piece length: %s\n", func() string {
575 return fmt.Sprint(t.usualPieceSize())
581 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
582 fmt.Fprintf(w, "Piece States: %s", t.pieceStateRuns())
585 fmt.Fprintf(w, "Reader Pieces:")
586 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
587 fmt.Fprintf(w, " %d:%d", begin, end)
592 fmt.Fprintf(w, "Enabled trackers:\n")
594 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
595 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
596 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
599 var luns, runs url.URL = lu, ru
602 var ml missinggo.MultiLess
603 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
604 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
606 }).([]torrentTrackerAnnouncer) {
607 fmt.Fprintf(tw, " %s\n", ta.statusLine())
612 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
614 spew.NewDefaultConfig()
615 spew.Fdump(w, t.statsLocked())
617 conns := t.connsAsSlice()
618 slices.Sort(conns, worseConn)
619 for i, c := range conns {
620 fmt.Fprintf(w, "%2d. ", i+1)
625 func (t *Torrent) haveInfo() bool {
629 // Returns a run-time generated MetaInfo that includes the info bytes and
630 // announce-list as currently known to the client.
631 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
632 return metainfo.MetaInfo{
633 CreationDate: time.Now().Unix(),
634 Comment: "dynamic metainfo from client",
635 CreatedBy: "go.torrent",
636 AnnounceList: t.metainfo.UpvertedAnnounceList(),
637 InfoBytes: func() []byte {
639 return t.metadataBytes
647 func (t *Torrent) BytesMissing() int64 {
650 return t.bytesMissingLocked()
653 func (t *Torrent) bytesMissingLocked() int64 {
657 func (t *Torrent) bytesLeft() (left int64) {
658 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
659 p := &t.pieces[piece]
660 left += int64(p.length() - p.numDirtyBytes())
666 // Bytes left to give in tracker announces.
667 func (t *Torrent) bytesLeftAnnounce() int64 {
675 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
676 if t.pieceComplete(piece) {
679 if t.pieceAllDirty(piece) {
682 return t.pieces[piece].hasDirtyChunks()
685 func (t *Torrent) usualPieceSize() int {
686 return int(t.info.PieceLength)
689 func (t *Torrent) numPieces() pieceIndex {
690 return pieceIndex(t.info.NumPieces())
693 func (t *Torrent) numPiecesCompleted() (num int) {
694 return t._completedPieces.Len()
697 func (t *Torrent) close() (err error) {
700 if t.storage != nil {
703 t.storageLock.Unlock()
705 for conn := range t.conns {
708 t.cl.event.Broadcast()
709 t.pieceStateChanges.Close()
710 t.updateWantPeersEvent()
714 func (t *Torrent) requestOffset(r request) int64 {
715 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
718 // Return the request that would include the given offset into the torrent
719 // data. Returns !ok if there is no such request.
720 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
721 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
724 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
725 defer perf.ScopeTimerErr(&err)()
726 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
727 if err == nil && n != len(data) {
728 err = io.ErrShortWrite
733 func (t *Torrent) bitfield() (bf []bool) {
734 bf = make([]bool, t.numPieces())
735 t._completedPieces.IterTyped(func(piece int) (again bool) {
742 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
743 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
746 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
747 t.pieces[pieceIndex]._dirtyChunks.Clear()
750 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
751 if t.info.PieceLength == 0 {
752 // There will be no variance amongst pieces. Only pain.
755 if piece == t.numPieces()-1 {
756 ret := pp.Integer(*t.length % t.info.PieceLength)
761 return pp.Integer(t.info.PieceLength)
764 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, copyErr error) {
765 hash := pieceHash.New()
767 p.waitNoPendingWrites()
768 ip := t.info.Piece(int(piece))
770 _, copyErr = io.CopyN( // Return no error iff pl bytes are copied.
771 hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl), pl)
772 missinggo.CopyExact(&ret, hash.Sum(nil))
776 func (t *Torrent) haveAnyPieces() bool {
777 return t._completedPieces.Len() != 0
780 func (t *Torrent) haveAllPieces() bool {
784 return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
787 func (t *Torrent) havePiece(index pieceIndex) bool {
788 return t.haveInfo() && t.pieceComplete(index)
791 func (t *Torrent) haveChunk(r request) (ret bool) {
793 // log.Println("have chunk", r, ret)
798 if t.pieceComplete(pieceIndex(r.Index)) {
801 p := &t.pieces[r.Index]
802 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
805 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
806 return int(cs.Begin / chunkSize)
809 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
813 if index < 0 || index >= t.numPieces() {
816 p := &t.pieces[index]
817 if p.queuedForHash() {
823 if t.pieceComplete(index) {
826 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
829 // t.logger.Printf("piece %d not pending", index)
830 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
831 return index < begin || index >= end
835 // The worst connection is one that hasn't been sent, or sent anything useful
836 // for the longest. A bad connection is one that usually sends us unwanted
837 // pieces, or has been in worser half of the established connections for more
839 func (t *Torrent) worstBadConn() *PeerConn {
840 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
843 c := heap.Pop(&wcs).(*PeerConn)
844 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
847 // If the connection is in the worst half of the established
848 // connection quota and is older than a minute.
849 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
850 // Give connections 1 minute to prove themselves.
851 if time.Since(c.completedHandshake) > time.Minute {
859 type PieceStateChange struct {
864 func (t *Torrent) publishPieceChange(piece pieceIndex) {
865 t.cl._mu.Defer(func() {
866 cur := t.pieceState(piece)
867 p := &t.pieces[piece]
868 if cur != p.publicPieceState {
869 p.publicPieceState = cur
870 t.pieceStateChanges.Publish(PieceStateChange{
878 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
879 if t.pieceComplete(piece) {
882 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
885 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
886 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
889 func (t *Torrent) readersChanged() {
890 t.updateReaderPieces()
891 t.updateAllPiecePriorities()
894 func (t *Torrent) updateReaderPieces() {
895 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
898 func (t *Torrent) readerPosChanged(from, to pieceRange) {
902 t.updateReaderPieces()
903 // Order the ranges, high and low.
905 if l.begin > h.begin {
909 // Two distinct ranges.
910 t.updatePiecePriorities(l.begin, l.end)
911 t.updatePiecePriorities(h.begin, h.end)
918 t.updatePiecePriorities(l.begin, end)
922 func (t *Torrent) maybeNewConns() {
923 // Tickle the accept routine.
924 t.cl.event.Broadcast()
928 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
929 // t.logger.Printf("piece %d priority changed", piece)
930 for c := range t.conns {
931 if c.updatePiecePriority(piece) {
932 // log.Print("conn piece priority changed")
937 t.publishPieceChange(piece)
940 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
941 p := &t.pieces[piece]
942 newPrio := p.uncachedPriority()
943 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
944 if newPrio == PiecePriorityNone {
945 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
949 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
953 t.piecePriorityChanged(piece)
956 func (t *Torrent) updateAllPiecePriorities() {
957 t.updatePiecePriorities(0, t.numPieces())
960 // Update all piece priorities in one hit. This function should have the same
961 // output as updatePiecePriority, but across all pieces.
962 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
963 for i := begin; i < end; i++ {
964 t.updatePiecePriority(i)
968 // Returns the range of pieces [begin, end) that contains the extent of bytes.
969 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
970 if off >= *t.length {
980 begin = pieceIndex(off / t.info.PieceLength)
981 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
982 if end > pieceIndex(t.info.NumPieces()) {
983 end = pieceIndex(t.info.NumPieces())
988 // Returns true if all iterations complete without breaking. Returns the read
989 // regions for all readers. The reader regions should not be merged as some
990 // callers depend on this method to enumerate readers.
991 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
992 for r := range t.readers {
994 if p.begin >= p.end {
997 if !f(p.begin, p.end) {
1004 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1005 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1007 return PiecePriorityNone
1012 ret := piecePriority(-prio)
1013 if ret == PiecePriorityNone {
1019 func (t *Torrent) pendRequest(req request) {
1020 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1021 t.pieces[req.Index].pendChunkIndex(ci)
1024 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1026 t.cl.event.Broadcast()
1027 if t.pieceComplete(piece) {
1028 t.onPieceCompleted(piece)
1030 t.onIncompletePiece(piece)
1032 t.updatePiecePriority(piece)
1035 func (t *Torrent) numReceivedConns() (ret int) {
1036 for c := range t.conns {
1037 if c.Discovery == PeerSourceIncoming {
1044 func (t *Torrent) maxHalfOpen() int {
1045 // Note that if we somehow exceed the maximum established conns, we want
1046 // the negative value to have an effect.
1047 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1048 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1049 // We want to allow some experimentation with new peers, and to try to
1050 // upset an oversupply of received connections.
1051 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1054 func (t *Torrent) openNewConns() {
1055 defer t.updateWantPeersEvent()
1056 for t.peers.Len() != 0 {
1060 if len(t.halfOpen) >= t.maxHalfOpen() {
1063 p := t.peers.PopMax()
1068 func (t *Torrent) getConnPieceInclination() []int {
1069 _ret := t.connPieceInclinationPool.Get()
1071 pieceInclinationsNew.Add(1)
1072 return rand.Perm(int(t.numPieces()))
1074 pieceInclinationsReused.Add(1)
1075 return *_ret.(*[]int)
1078 func (t *Torrent) putPieceInclination(pi []int) {
1079 t.connPieceInclinationPool.Put(&pi)
1080 pieceInclinationsPut.Add(1)
1083 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1085 uncached := t.pieceCompleteUncached(piece)
1086 cached := p.completion()
1087 changed := cached != uncached
1088 complete := uncached.Complete
1089 p.storageCompletionOk = uncached.Ok
1090 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1091 if complete && len(p.dirtiers) != 0 {
1092 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1095 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).WithValues(debugLogValue).Log(t.logger)
1096 t.pieceCompletionChanged(piece)
1101 // Non-blocking read. Client lock is not required.
1102 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1103 p := &t.pieces[off/t.info.PieceLength]
1104 p.waitNoPendingWrites()
1105 return p.Storage().ReadAt(b, off-p.Info().Offset())
1108 // Returns an error if the metadata was completed, but couldn't be set for
1109 // some reason. Blame it on the last peer to contribute.
1110 func (t *Torrent) maybeCompleteMetadata() error {
1115 if !t.haveAllMetadataPieces() {
1116 // Don't have enough metadata pieces.
1119 err := t.setInfoBytes(t.metadataBytes)
1121 t.invalidateMetadata()
1122 return fmt.Errorf("error setting info bytes: %s", err)
1124 if t.cl.config.Debug {
1125 t.logger.Printf("%s: got metadata from peers", t)
1130 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1131 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1133 now.Add(bitmap.BitIndex(begin))
1134 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1141 func (t *Torrent) needData() bool {
1142 if t.closed.IsSet() {
1148 return t._pendingPieces.Len() != 0
1151 func appendMissingStrings(old, new []string) (ret []string) {
1154 for _, n := range new {
1155 for _, o := range old {
1160 ret = append(ret, n)
1165 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1167 for minNumTiers > len(ret) {
1168 ret = append(ret, nil)
1173 func (t *Torrent) addTrackers(announceList [][]string) {
1174 fullAnnounceList := &t.metainfo.AnnounceList
1175 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1176 for tierIndex, trackerURLs := range announceList {
1177 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1179 t.startMissingTrackerScrapers()
1180 t.updateWantPeersEvent()
1183 // Don't call this before the info is available.
1184 func (t *Torrent) bytesCompleted() int64 {
1188 return t.info.TotalLength() - t.bytesLeft()
1191 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1194 return t.setInfoBytes(b)
1197 // Returns true if connection is removed from torrent.Conns.
1198 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1199 if !c.closed.IsSet() {
1200 panic("connection is not closed")
1201 // There are behaviours prevented by the closed state that will fail
1202 // if the connection has been deleted.
1206 torrent.Add("deleted connections", 1)
1207 c.deleteAllRequests()
1208 if len(t.conns) == 0 {
1209 t.assertNoPendingRequests()
1214 func (t *Torrent) assertNoPendingRequests() {
1215 if len(t.pendingRequests) != 0 {
1216 panic(t.pendingRequests)
1218 //if len(t.lastRequested) != 0 {
1219 // panic(t.lastRequested)
1223 func (t *Torrent) dropConnection(c *PeerConn) {
1224 t.cl.event.Broadcast()
1226 if t.deleteConnection(c) {
1231 func (t *Torrent) wantPeers() bool {
1232 if t.closed.IsSet() {
1235 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1238 return t.needData() || t.seeding()
1241 func (t *Torrent) updateWantPeersEvent() {
1243 t.wantPeersEvent.Set()
1245 t.wantPeersEvent.Clear()
1249 // Returns whether the client should make effort to seed the torrent.
1250 func (t *Torrent) seeding() bool {
1252 if t.closed.IsSet() {
1255 if cl.config.NoUpload {
1258 if !cl.config.Seed {
1261 if cl.config.DisableAggressiveUpload && t.needData() {
1267 func (t *Torrent) onWebRtcConn(
1268 c datachannel.ReadWriteCloser,
1269 dcc webtorrent.DataChannelContext,
1272 pc, err := t.cl.handshakesConnection(
1273 context.Background(),
1274 webrtcNetConn{c, dcc},
1277 webrtcNetAddr{dcc.Remote},
1281 t.logger.Printf("error in handshaking webrtc connection: %v", err)
1283 if dcc.LocalOffered {
1284 pc.Discovery = PeerSourceTracker
1286 pc.Discovery = PeerSourceIncoming
1290 t.cl.runHandshookConn(pc, t)
1293 func (t *Torrent) startScrapingTracker(_url string) {
1297 u, err := url.Parse(_url)
1299 // URLs with a leading '*' appear to be a uTorrent convention to
1300 // disable trackers.
1302 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1306 if u.Scheme == "udp" {
1308 t.startScrapingTracker(u.String())
1310 t.startScrapingTracker(u.String())
1313 if _, ok := t.trackerAnnouncers[_url]; ok {
1316 sl := func() torrentTrackerAnnouncer {
1319 wst := websocketTracker{*u, webtorrent.NewClient(t.cl.peerID, t.infoHash, t.onWebRtcConn, t.logger)}
1321 err := wst.Client.Run(t.announceRequest(tracker.Started), u.String())
1323 t.logger.WithValues(log.Error).Printf("error running websocket tracker announcer: %v", err)
1328 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1331 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1334 newAnnouncer := &trackerScraper{
1338 go newAnnouncer.Run()
1341 if t.trackerAnnouncers == nil {
1342 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1344 t.trackerAnnouncers[_url] = sl
1347 // Adds and starts tracker scrapers for tracker URLs that aren't already
1349 func (t *Torrent) startMissingTrackerScrapers() {
1350 if t.cl.config.DisableTrackers {
1353 t.startScrapingTracker(t.metainfo.Announce)
1354 for _, tier := range t.metainfo.AnnounceList {
1355 for _, url := range tier {
1356 t.startScrapingTracker(url)
1361 // Returns an AnnounceRequest with fields filled out to defaults and current
1363 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1364 // Note that IPAddress is not set. It's set for UDP inside the tracker
1365 // code, since it's dependent on the network in use.
1366 return tracker.AnnounceRequest{
1369 Port: uint16(t.cl.incomingPeerPort()),
1370 PeerId: t.cl.peerID,
1371 InfoHash: t.infoHash,
1372 Key: t.cl.announceKey(),
1374 // The following are vaguely described in BEP 3.
1376 Left: t.bytesLeftAnnounce(),
1377 Uploaded: t.stats.BytesWrittenData.Int64(),
1378 // There's no mention of wasted or unwanted download in the BEP.
1379 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1383 // Adds peers revealed in an announce until the announce ends, or we have
1385 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1387 for v := range pvs {
1389 for _, cp := range v.Peers {
1391 // Can't do anything with this.
1395 Addr: ipPortAddr{cp.IP, cp.Port},
1396 Source: PeerSourceDhtGetPeers,
1403 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1404 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1408 go t.consumeDhtAnnouncePeers(ps.Peers())
1410 case <-t.closed.LockedChan(t.cl.locker()):
1411 case <-time.After(5 * time.Minute):
1417 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1421 case <-t.closed.LockedChan(cl.locker()):
1423 case <-t.wantPeersEvent.LockedChan(cl.locker()):
1428 err := t.announceToDht(true, s)
1430 t.logger.WithValues(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1435 func (t *Torrent) addPeers(peers []Peer) {
1436 for _, p := range peers {
1441 // The returned TorrentStats may require alignment in memory. See
1442 // https://github.com/anacrolix/torrent/issues/383.
1443 func (t *Torrent) Stats() TorrentStats {
1445 defer t.cl.rUnlock()
1446 return t.statsLocked()
1449 func (t *Torrent) statsLocked() (ret TorrentStats) {
1450 ret.ActivePeers = len(t.conns)
1451 ret.HalfOpenPeers = len(t.halfOpen)
1452 ret.PendingPeers = t.peers.Len()
1453 ret.TotalPeers = t.numTotalPeers()
1454 ret.ConnectedSeeders = 0
1455 for c := range t.conns {
1456 if all, ok := c.peerHasAllPieces(); all && ok {
1457 ret.ConnectedSeeders++
1460 ret.ConnStats = t.stats.Copy()
1464 // The total number of peers in the torrent.
1465 func (t *Torrent) numTotalPeers() int {
1466 peers := make(map[string]struct{})
1467 for conn := range t.conns {
1468 ra := conn.conn.RemoteAddr()
1470 // It's been closed and doesn't support RemoteAddr.
1473 peers[ra.String()] = struct{}{}
1475 for addr := range t.halfOpen {
1476 peers[addr] = struct{}{}
1478 t.peers.Each(func(peer Peer) {
1479 peers[peer.Addr.String()] = struct{}{}
1484 // Reconcile bytes transferred before connection was associated with a
1486 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1487 if c._stats != (ConnStats{
1488 // Handshakes should only increment these fields:
1489 BytesWritten: c._stats.BytesWritten,
1490 BytesRead: c._stats.BytesRead,
1494 c.postHandshakeStats(func(cs *ConnStats) {
1495 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1496 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1498 c.reconciledHandshakeStats = true
1501 // Returns true if the connection is added.
1502 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1505 torrent.Add("added connections", 1)
1508 if t.closed.IsSet() {
1509 return errors.New("torrent closed")
1511 for c0 := range t.conns {
1512 if c.PeerID != c0.PeerID {
1515 if !t.cl.config.dropDuplicatePeerIds {
1518 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1520 t.deleteConnection(c0)
1522 return errors.New("existing connection preferred")
1525 if len(t.conns) >= t.maxEstablishedConns {
1526 c := t.worstBadConn()
1528 return errors.New("don't want conns")
1531 t.deleteConnection(c)
1533 if len(t.conns) >= t.maxEstablishedConns {
1536 t.conns[c] = struct{}{}
1540 func (t *Torrent) wantConns() bool {
1541 if !t.networkingEnabled {
1544 if t.closed.IsSet() {
1547 if !t.seeding() && !t.needData() {
1550 if len(t.conns) < t.maxEstablishedConns {
1553 return t.worstBadConn() != nil
1556 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1559 oldMax = t.maxEstablishedConns
1560 t.maxEstablishedConns = max
1561 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1562 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1563 t.dropConnection(wcs.Pop().(*PeerConn))
1569 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1570 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).WithValues(debugLogValue))
1573 t.cl.event.Broadcast()
1574 if t.closed.IsSet() {
1578 // Don't score the first time a piece is hashed, it could be an initial check.
1579 if p.storageCompletionOk {
1581 pieceHashedCorrect.Add(1)
1583 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1584 pieceHashedNotCorrect.Add(1)
1589 if len(p.dirtiers) != 0 {
1590 // Don't increment stats above connection-level for every involved connection.
1591 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1593 for c := range p.dirtiers {
1594 c._stats.incrementPiecesDirtiedGood()
1596 t.clearPieceTouchers(piece)
1597 err := p.Storage().MarkComplete()
1599 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1601 t.pendAllChunkSpecs(piece)
1603 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1604 // Peers contributed to all the data for this piece hash failure, and the failure was
1605 // not due to errors in the storage (such as data being dropped in a cache).
1607 // Increment Torrent and above stats, and then specific connections.
1608 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1609 for c := range p.dirtiers {
1610 // Y u do dis peer?!
1611 c.stats().incrementPiecesDirtiedBad()
1614 bannableTouchers := make([]*PeerConn, 0, len(p.dirtiers))
1615 for c := range p.dirtiers {
1617 bannableTouchers = append(bannableTouchers, c)
1620 t.clearPieceTouchers(piece)
1621 slices.Sort(bannableTouchers, connLessTrusted)
1623 if t.cl.config.Debug {
1625 "bannable conns by trust for piece %d: %v",
1627 func() (ret []connectionTrust) {
1628 for _, c := range bannableTouchers {
1629 ret = append(ret, c.trust())
1636 if len(bannableTouchers) >= 1 {
1637 c := bannableTouchers[0]
1638 t.cl.banPeerIP(c.remoteIp())
1642 t.onIncompletePiece(piece)
1643 p.Storage().MarkNotComplete()
1645 t.updatePieceCompletion(piece)
1648 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1649 // TODO: Make faster
1650 for cn := range t.conns {
1655 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1656 t.pendAllChunkSpecs(piece)
1657 t.cancelRequestsForPiece(piece)
1658 for conn := range t.conns {
1663 // Called when a piece is found to be not complete.
1664 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1665 if t.pieceAllDirty(piece) {
1666 t.pendAllChunkSpecs(piece)
1668 if !t.wantPieceIndex(piece) {
1669 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1672 // We could drop any connections that we told we have a piece that we
1673 // don't here. But there's a test failure, and it seems clients don't care
1674 // if you request pieces that you already claim to have. Pruning bad
1675 // connections might just remove any connections that aren't treating us
1676 // favourably anyway.
1678 // for c := range t.conns {
1679 // if c.sentHave(piece) {
1683 for conn := range t.conns {
1684 if conn.peerHasPiece(piece) {
1685 conn.updateRequests()
1690 func (t *Torrent) tryCreateMorePieceHashers() {
1691 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1695 func (t *Torrent) tryCreatePieceHasher() bool {
1696 if t.storage == nil {
1699 pi, ok := t.getPieceToHash()
1704 t.piecesQueuedForHash.Remove(pi)
1706 t.publishPieceChange(pi)
1707 t.updatePiecePriority(pi)
1708 t.storageLock.RLock()
1709 t.activePieceHashes++
1710 go t.pieceHasher(pi)
1714 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1715 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1716 if t.piece(i).hashing {
1726 func (t *Torrent) pieceHasher(index pieceIndex) {
1728 sum, copyErr := t.hashPiece(index)
1729 correct := sum == *p.hash
1733 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1735 t.storageLock.RUnlock()
1739 t.updatePiecePriority(index)
1740 t.pieceHashed(index, correct, copyErr)
1741 t.publishPieceChange(index)
1742 t.activePieceHashes--
1743 t.tryCreateMorePieceHashers()
1746 // Return the connections that touched a piece, and clear the entries while doing it.
1747 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1749 for c := range p.dirtiers {
1750 delete(c.peerTouchedPieces, pi)
1751 delete(p.dirtiers, c)
1755 func (t *Torrent) connsAsSlice() (ret []*PeerConn) {
1756 for c := range t.conns {
1757 ret = append(ret, c)
1762 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1763 piece := t.piece(pieceIndex)
1764 if piece.queuedForHash() {
1767 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1768 t.publishPieceChange(pieceIndex)
1769 t.updatePiecePriority(pieceIndex)
1770 t.tryCreateMorePieceHashers()
1773 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1774 // before the Info is available.
1775 func (t *Torrent) VerifyData() {
1776 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1777 t.Piece(i).VerifyData()
1781 // Start the process of connecting to the given peer for the given torrent if appropriate.
1782 func (t *Torrent) initiateConn(peer Peer) {
1783 if peer.Id == t.cl.peerID {
1787 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1791 if t.addrActive(addr.String()) {
1794 t.halfOpen[addr.String()] = peer
1795 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1798 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1799 // quickly make one Client visible to the Torrent of another Client.
1800 func (t *Torrent) AddClientPeer(cl *Client) {
1801 t.AddPeers(func() (ps []Peer) {
1802 for _, la := range cl.ListenAddrs() {
1803 ps = append(ps, Peer{
1812 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1814 func (t *Torrent) allStats(f func(*ConnStats)) {
1819 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1820 return t.pieces[i].hashing
1823 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1824 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1827 func (t *Torrent) dialTimeout() time.Duration {
1828 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1831 func (t *Torrent) piece(i int) *Piece {
1835 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1839 type torrentRequestStrategyCallbacks struct {
1843 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
1844 torrent.Add("request timeouts", 1)
1846 defer cb.t.cl.unlock()
1847 for cn := range cb.t.conns {
1848 if cn.peerHasPiece(pieceIndex(r.Index)) {
1855 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
1856 return torrentRequestStrategyCallbacks{t}
1859 func (t *Torrent) onWriteChunkErr(err error) {
1860 if t.userOnWriteChunkErr != nil {
1861 go t.userOnWriteChunkErr(err)
1864 t.disallowDataDownloadLocked()
1867 func (t *Torrent) DisallowDataDownload() {
1870 t.disallowDataDownloadLocked()
1873 func (t *Torrent) disallowDataDownloadLocked() {
1874 log.Printf("disallowing data download")
1875 t.dataDownloadDisallowed = true
1876 for c := range t.conns {
1881 func (t *Torrent) AllowDataDownload() {
1884 log.Printf("AllowDataDownload")
1885 t.dataDownloadDisallowed = false
1886 for c := range t.conns {
1892 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
1895 t.userOnWriteChunkErr = f