19 "github.com/anacrolix/torrent/common"
20 "github.com/anacrolix/torrent/segments"
21 "github.com/anacrolix/torrent/webseed"
22 "github.com/davecgh/go-spew/spew"
23 "github.com/pion/datachannel"
25 "github.com/anacrolix/dht/v2"
26 "github.com/anacrolix/log"
27 "github.com/anacrolix/missinggo"
28 "github.com/anacrolix/missinggo/perf"
29 "github.com/anacrolix/missinggo/pubsub"
30 "github.com/anacrolix/missinggo/slices"
31 "github.com/anacrolix/missinggo/v2/bitmap"
32 "github.com/anacrolix/missinggo/v2/prioritybitmap"
34 "github.com/anacrolix/torrent/bencode"
35 "github.com/anacrolix/torrent/metainfo"
36 pp "github.com/anacrolix/torrent/peer_protocol"
37 "github.com/anacrolix/torrent/storage"
38 "github.com/anacrolix/torrent/tracker"
39 "github.com/anacrolix/torrent/webtorrent"
42 // Maintains state of torrent within a Client. Many methods should not be called before the info is
43 // available, see .Info and .GotInfo.
45 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
46 // alignment. See #262.
51 networkingEnabled bool
52 dataDownloadDisallowed bool
53 dataUploadDisallowed bool
54 userOnWriteChunkErr func(error)
56 // Determines what chunks to request from peers.
57 requestStrategy requestStrategy
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).
84 fileIndex segments.Index
87 webSeeds map[string]*peer
89 // Active peer connections, running message stream loops. TODO: Make this
90 // open (not-closed) connections only.
91 conns map[*PeerConn]struct{}
92 maxEstablishedConns int
93 // Set of addrs to which we're attempting to connect. Connections are
94 // half-open until all handshakes are completed.
95 halfOpen map[string]PeerInfo
98 // Reserve of peers to connect to. A peer can be both here and in the
99 // active connections if were told about the peer after connecting with
100 // them. That encourages us to reconnect to peers that are well known in
102 peers prioritizedPeers
103 // Whether we want to know to know more peers.
104 wantPeersEvent missinggo.Event
105 // An announcer for each tracker URL.
106 trackerAnnouncers map[string]torrentTrackerAnnouncer
107 // How many times we've initiated a DHT announce. TODO: Move into stats.
110 // Name used if the info name isn't available. Should be cleared when the
111 // Info does become available.
115 // The bencoded bytes of the info dict. This is actively manipulated if
116 // the info bytes aren't initially available, and we try to fetch them
119 // Each element corresponds to the 16KiB metadata pieces. If true, we have
120 // received that piece.
121 metadataCompletedChunks []bool
122 metadataChanged sync.Cond
124 // Set when .Info is obtained.
125 gotMetainfo missinggo.Event
127 readers map[*reader]struct{}
128 _readerNowPieces bitmap.Bitmap
129 _readerReadaheadPieces bitmap.Bitmap
131 // A cache of pieces we need to get. Calculated from various piece and
132 // file priorities and completion states elsewhere.
133 _pendingPieces prioritybitmap.PriorityBitmap
134 // A cache of completed piece indices.
135 _completedPieces bitmap.Bitmap
136 // Pieces that need to be hashed.
137 piecesQueuedForHash bitmap.Bitmap
138 activePieceHashes int
140 // A pool of piece priorities []int for assignment to new connections.
141 // These "inclinations" are used to give connections preference for
143 connPieceInclinationPool sync.Pool
145 // Count of each request across active connections.
146 pendingRequests map[request]int
151 func (t *Torrent) numConns() int {
155 func (t *Torrent) numReaders() int {
156 return len(t.readers)
159 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
160 return t._readerNowPieces
163 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
164 return t._readerReadaheadPieces
167 func (t *Torrent) ignorePieces() bitmap.Bitmap {
168 ret := t._completedPieces.Copy()
169 ret.Union(t.piecesQueuedForHash)
170 for i := 0; i < t.numPieces(); i++ {
171 if t.piece(i).hashing {
178 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
179 return &t._pendingPieces
182 func (t *Torrent) tickleReaders() {
183 t.cl.event.Broadcast()
186 // Returns a channel that is closed when the Torrent is closed.
187 func (t *Torrent) Closed() <-chan struct{} {
188 return t.closed.LockedChan(t.cl.locker())
191 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
192 // pending, and half-open peers.
193 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
194 // Add pending peers to the list
195 t.peers.Each(func(peer PeerInfo) {
196 ks = append(ks, peer)
199 // Add half-open peers to the list
200 for _, peer := range t.halfOpen {
201 ks = append(ks, peer)
204 // Add active peers to the list
205 for conn := range t.conns {
207 ks = append(ks, PeerInfo{
209 Addr: conn.remoteAddr,
210 Source: conn.Discovery,
211 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
212 // > But if we're not connected to them with an encrypted connection, I couldn't say
213 // > what's appropriate. We can carry forward the SupportsEncryption value as we
214 // > received it from trackers/DHT/PEX, or just use the encryption state for the
215 // > connection. It's probably easiest to do the latter for now.
216 // https://github.com/anacrolix/torrent/pull/188
217 SupportsEncryption: conn.headerEncrypted,
224 func (t *Torrent) setChunkSize(size pp.Integer) {
226 t.chunkPool = &sync.Pool{
227 New: func() interface{} {
228 b := make([]byte, size)
234 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
235 return t._completedPieces.Get(bitmap.BitIndex(piece))
238 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
239 return t.pieces[piece].Storage().Completion()
242 // There's a connection to that address already.
243 func (t *Torrent) addrActive(addr string) bool {
244 if _, ok := t.halfOpen[addr]; ok {
247 for c := range t.conns {
249 if ra.String() == addr {
256 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
257 ret = make([]*PeerConn, 0, len(t.conns))
258 for c := range t.conns {
259 if !c.closed.IsSet() {
266 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
268 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
269 if t.closed.IsSet() {
272 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
273 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
274 torrent.Add("peers not added because of bad addr", 1)
275 // cl.logger.Printf("peers not added because of bad addr: %v", p)
279 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
280 torrent.Add("peers replaced", 1)
281 if !replaced.equal(p) {
282 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
289 for t.peers.Len() > cl.config.TorrentPeersHighWater {
290 _, ok := t.peers.DeleteMin()
292 torrent.Add("excess reserve peers discarded", 1)
298 func (t *Torrent) invalidateMetadata() {
299 for i := range t.metadataCompletedChunks {
300 t.metadataCompletedChunks[i] = false
307 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
311 if index >= len(t.metadataCompletedChunks) {
312 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
315 copy(t.metadataBytes[(1<<14)*index:], data)
316 t.metadataCompletedChunks[index] = true
319 func (t *Torrent) metadataPieceCount() int {
320 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
323 func (t *Torrent) haveMetadataPiece(piece int) bool {
325 return (1<<14)*piece < len(t.metadataBytes)
327 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
331 func (t *Torrent) metadataSize() int {
332 return len(t.metadataBytes)
335 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
336 for i := 0; i < len(info.Pieces); i += sha1.Size {
337 ret = append(ret, info.Pieces[i:i+sha1.Size])
342 func (t *Torrent) makePieces() {
343 hashes := infoPieceHashes(t.info)
344 t.pieces = make([]Piece, len(hashes))
345 for i, hash := range hashes {
346 piece := &t.pieces[i]
348 piece.index = pieceIndex(i)
349 piece.noPendingWrites.L = &piece.pendingWritesMutex
350 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
352 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
353 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
354 piece.files = files[beginFile:endFile]
358 // Returns the index of the first file containing the piece. files must be
359 // ordered by offset.
360 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
361 for i, f := range files {
362 if f.offset+f.length > pieceOffset {
369 // Returns the index after the last file containing the piece. files must be
370 // ordered by offset.
371 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
372 for i, f := range files {
373 if f.offset+f.length >= pieceEndOffset {
380 func (t *Torrent) cacheLength() {
382 for _, f := range t.info.UpvertedFiles() {
388 func (t *Torrent) setInfo(info *metainfo.Info) error {
389 if err := validateInfo(info); err != nil {
390 return fmt.Errorf("bad info: %s", err)
392 if t.storageOpener != nil {
394 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
396 return fmt.Errorf("error opening torrent storage: %s", err)
402 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
403 t.displayName = "" // Save a few bytes lol.
410 // This seems to be all the follow-up tasks after info is set, that can't fail.
411 func (t *Torrent) onSetInfo() {
412 t.iterPeers(func(p *peer) {
415 for i := range t.pieces {
416 t.updatePieceCompletion(pieceIndex(i))
418 if !p.storageCompletionOk {
419 // t.logger.Printf("piece %s completion unknown, queueing check", p)
420 t.queuePieceCheck(pieceIndex(i))
423 t.cl.event.Broadcast()
425 t.updateWantPeersEvent()
426 t.pendingRequests = make(map[request]int)
427 t.tryCreateMorePieceHashers()
430 // Called when metadata for a torrent becomes available.
431 func (t *Torrent) setInfoBytes(b []byte) error {
432 if metainfo.HashBytes(b) != t.infoHash {
433 return errors.New("info bytes have wrong hash")
435 var info metainfo.Info
436 if err := bencode.Unmarshal(b, &info); err != nil {
437 return fmt.Errorf("error unmarshalling info bytes: %s", err)
440 t.metadataCompletedChunks = nil
444 if err := t.setInfo(&info); err != nil {
451 func (t *Torrent) haveAllMetadataPieces() bool {
455 if t.metadataCompletedChunks == nil {
458 for _, have := range t.metadataCompletedChunks {
466 // TODO: Propagate errors to disconnect peer.
467 func (t *Torrent) setMetadataSize(bytes int) (err error) {
469 // We already know the correct metadata size.
472 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
473 return errors.New("bad size")
475 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
478 t.metadataBytes = make([]byte, bytes)
479 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
480 t.metadataChanged.Broadcast()
481 for c := range t.conns {
482 c.requestPendingMetadata()
487 // The current working name for the torrent. Either the name in the info dict,
488 // or a display name given such as by the dn value in a magnet link, or "".
489 func (t *Torrent) name() string {
491 defer t.nameMu.RUnlock()
498 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
499 p := &t.pieces[index]
500 ret.Priority = t.piecePriority(index)
501 ret.Completion = p.completion()
502 if p.queuedForHash() || p.hashing {
505 if !ret.Complete && t.piecePartiallyDownloaded(index) {
511 func (t *Torrent) metadataPieceSize(piece int) int {
512 return metadataPieceSize(len(t.metadataBytes), piece)
515 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
521 d["total_size"] = len(t.metadataBytes)
523 p := bencode.MustMarshal(d)
526 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
527 ExtendedPayload: append(p, data...),
531 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
532 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
533 ret = append(ret, PieceStateRun{
534 PieceState: el.(PieceState),
538 for index := range t.pieces {
539 rle.Append(t.pieceState(pieceIndex(index)), 1)
545 // Produces a small string representing a PieceStateRun.
546 func (psr PieceStateRun) String() (ret string) {
547 ret = fmt.Sprintf("%d", psr.Length)
548 ret += func() string {
549 switch psr.Priority {
550 case PiecePriorityNext:
552 case PiecePriorityNormal:
554 case PiecePriorityReadahead:
556 case PiecePriorityNow:
558 case PiecePriorityHigh:
579 func (t *Torrent) writeStatus(w io.Writer) {
580 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
581 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
583 fmt.Fprintf(w, "Metadata have: ")
584 for _, h := range t.metadataCompletedChunks {
585 fmt.Fprintf(w, "%c", func() rune {
595 fmt.Fprintf(w, "Piece length: %s\n", func() string {
597 return fmt.Sprint(t.usualPieceSize())
603 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
604 fmt.Fprintf(w, "Piece States: %s", t.pieceStateRuns())
607 fmt.Fprintf(w, "Reader Pieces:")
608 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
609 fmt.Fprintf(w, " %d:%d", begin, end)
614 fmt.Fprintf(w, "Enabled trackers:\n")
616 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
617 fmt.Fprintf(tw, " URL\tExtra\n")
618 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
621 var luns, runs url.URL = *lu, *ru
624 var ml missinggo.MultiLess
625 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
626 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
628 }).([]torrentTrackerAnnouncer) {
629 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
634 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
636 spew.NewDefaultConfig()
637 spew.Fdump(w, t.statsLocked())
639 peers := t.peersAsSlice()
640 sort.Slice(peers, func(i, j int) bool {
641 return worseConn(peers[i], peers[j])
643 for i, c := range peers {
644 fmt.Fprintf(w, "%2d. ", i+1)
649 func (t *Torrent) haveInfo() bool {
653 // Returns a run-time generated MetaInfo that includes the info bytes and
654 // announce-list as currently known to the client.
655 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
656 return metainfo.MetaInfo{
657 CreationDate: time.Now().Unix(),
658 Comment: "dynamic metainfo from client",
659 CreatedBy: "go.torrent",
660 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
661 InfoBytes: func() []byte {
663 return t.metadataBytes
671 func (t *Torrent) BytesMissing() int64 {
674 return t.bytesMissingLocked()
677 func (t *Torrent) bytesMissingLocked() int64 {
681 func (t *Torrent) bytesLeft() (left int64) {
682 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
683 p := &t.pieces[piece]
684 left += int64(p.length() - p.numDirtyBytes())
690 // Bytes left to give in tracker announces.
691 func (t *Torrent) bytesLeftAnnounce() int64 {
699 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
700 if t.pieceComplete(piece) {
703 if t.pieceAllDirty(piece) {
706 return t.pieces[piece].hasDirtyChunks()
709 func (t *Torrent) usualPieceSize() int {
710 return int(t.info.PieceLength)
713 func (t *Torrent) numPieces() pieceIndex {
714 return pieceIndex(t.info.NumPieces())
717 func (t *Torrent) numPiecesCompleted() (num int) {
718 return t._completedPieces.Len()
721 func (t *Torrent) close() (err error) {
724 if t.storage != nil {
727 t.storageLock.Unlock()
729 for conn := range t.conns {
733 t.cl.event.Broadcast()
734 t.pieceStateChanges.Close()
735 t.updateWantPeersEvent()
739 func (t *Torrent) requestOffset(r request) int64 {
740 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
743 // Return the request that would include the given offset into the torrent data. Returns !ok if
744 // there is no such request.
745 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
746 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
749 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
750 defer perf.ScopeTimerErr(&err)()
751 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
752 if err == nil && n != len(data) {
753 err = io.ErrShortWrite
758 func (t *Torrent) bitfield() (bf []bool) {
759 bf = make([]bool, t.numPieces())
760 t._completedPieces.IterTyped(func(piece int) (again bool) {
767 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
768 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
771 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
772 t.pieces[pieceIndex]._dirtyChunks.Clear()
775 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
776 if t.info.PieceLength == 0 {
777 // There will be no variance amongst pieces. Only pain.
780 if piece == t.numPieces()-1 {
781 ret := pp.Integer(*t.length % t.info.PieceLength)
786 return pp.Integer(t.info.PieceLength)
789 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, copyErr error) {
790 hash := pieceHash.New()
792 p.waitNoPendingWrites()
793 ip := t.info.Piece(int(piece))
795 _, copyErr = io.CopyN( // Return no error iff pl bytes are copied.
796 hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl), pl)
797 missinggo.CopyExact(&ret, hash.Sum(nil))
801 func (t *Torrent) haveAnyPieces() bool {
802 return t._completedPieces.Len() != 0
805 func (t *Torrent) haveAllPieces() bool {
809 return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
812 func (t *Torrent) havePiece(index pieceIndex) bool {
813 return t.haveInfo() && t.pieceComplete(index)
816 func (t *Torrent) haveChunk(r request) (ret bool) {
818 // log.Println("have chunk", r, ret)
823 if t.pieceComplete(pieceIndex(r.Index)) {
826 p := &t.pieces[r.Index]
827 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
830 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
831 return int(cs.Begin / chunkSize)
834 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
838 if index < 0 || index >= t.numPieces() {
841 p := &t.pieces[index]
842 if p.queuedForHash() {
848 if t.pieceComplete(index) {
851 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
854 // t.logger.Printf("piece %d not pending", index)
855 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
856 return index < begin || index >= end
860 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
861 // connection is one that usually sends us unwanted pieces, or has been in worser half of the
862 // established connections for more than a minute.
863 func (t *Torrent) worstBadConn() *PeerConn {
864 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
867 c := heap.Pop(&wcs).(*PeerConn)
868 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
871 // If the connection is in the worst half of the established
872 // connection quota and is older than a minute.
873 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
874 // Give connections 1 minute to prove themselves.
875 if time.Since(c.completedHandshake) > time.Minute {
883 type PieceStateChange struct {
888 func (t *Torrent) publishPieceChange(piece pieceIndex) {
889 t.cl._mu.Defer(func() {
890 cur := t.pieceState(piece)
891 p := &t.pieces[piece]
892 if cur != p.publicPieceState {
893 p.publicPieceState = cur
894 t.pieceStateChanges.Publish(PieceStateChange{
902 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
903 if t.pieceComplete(piece) {
906 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
909 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
910 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
913 func (t *Torrent) readersChanged() {
914 t.updateReaderPieces()
915 t.updateAllPiecePriorities()
918 func (t *Torrent) updateReaderPieces() {
919 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
922 func (t *Torrent) readerPosChanged(from, to pieceRange) {
926 t.updateReaderPieces()
927 // Order the ranges, high and low.
929 if l.begin > h.begin {
933 // Two distinct ranges.
934 t.updatePiecePriorities(l.begin, l.end)
935 t.updatePiecePriorities(h.begin, h.end)
942 t.updatePiecePriorities(l.begin, end)
946 func (t *Torrent) maybeNewConns() {
947 // Tickle the accept routine.
948 t.cl.event.Broadcast()
952 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
953 // t.logger.Printf("piece %d priority changed", piece)
954 t.iterPeers(func(c *peer) {
955 if c.updatePiecePriority(piece) {
956 // log.Print("conn piece priority changed")
961 t.publishPieceChange(piece)
964 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
965 p := &t.pieces[piece]
966 newPrio := p.uncachedPriority()
967 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
968 if newPrio == PiecePriorityNone {
969 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
973 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
977 t.piecePriorityChanged(piece)
980 func (t *Torrent) updateAllPiecePriorities() {
981 t.updatePiecePriorities(0, t.numPieces())
984 // Update all piece priorities in one hit. This function should have the same
985 // output as updatePiecePriority, but across all pieces.
986 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
987 for i := begin; i < end; i++ {
988 t.updatePiecePriority(i)
992 // Returns the range of pieces [begin, end) that contains the extent of bytes.
993 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
994 if off >= *t.length {
1004 begin = pieceIndex(off / t.info.PieceLength)
1005 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1006 if end > pieceIndex(t.info.NumPieces()) {
1007 end = pieceIndex(t.info.NumPieces())
1012 // Returns true if all iterations complete without breaking. Returns the read
1013 // regions for all readers. The reader regions should not be merged as some
1014 // callers depend on this method to enumerate readers.
1015 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1016 for r := range t.readers {
1018 if p.begin >= p.end {
1021 if !f(p.begin, p.end) {
1028 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1029 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1031 return PiecePriorityNone
1036 ret := piecePriority(-prio)
1037 if ret == PiecePriorityNone {
1043 func (t *Torrent) pendRequest(req request) {
1044 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1045 t.pieces[req.Index].pendChunkIndex(ci)
1048 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1050 t.cl.event.Broadcast()
1051 if t.pieceComplete(piece) {
1052 t.onPieceCompleted(piece)
1054 t.onIncompletePiece(piece)
1056 t.updatePiecePriority(piece)
1059 func (t *Torrent) numReceivedConns() (ret int) {
1060 for c := range t.conns {
1061 if c.Discovery == PeerSourceIncoming {
1068 func (t *Torrent) maxHalfOpen() int {
1069 // Note that if we somehow exceed the maximum established conns, we want
1070 // the negative value to have an effect.
1071 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1072 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1073 // We want to allow some experimentation with new peers, and to try to
1074 // upset an oversupply of received connections.
1075 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1078 func (t *Torrent) openNewConns() {
1079 defer t.updateWantPeersEvent()
1080 for t.peers.Len() != 0 {
1084 if len(t.halfOpen) >= t.maxHalfOpen() {
1087 if len(t.cl.dialers) == 0 {
1090 p := t.peers.PopMax()
1095 func (t *Torrent) getConnPieceInclination() []int {
1096 _ret := t.connPieceInclinationPool.Get()
1098 pieceInclinationsNew.Add(1)
1099 return rand.Perm(int(t.numPieces()))
1101 pieceInclinationsReused.Add(1)
1102 return *_ret.(*[]int)
1105 func (t *Torrent) putPieceInclination(pi []int) {
1106 t.connPieceInclinationPool.Put(&pi)
1107 pieceInclinationsPut.Add(1)
1110 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1112 uncached := t.pieceCompleteUncached(piece)
1113 cached := p.completion()
1114 changed := cached != uncached
1115 complete := uncached.Complete
1116 p.storageCompletionOk = uncached.Ok
1117 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1118 if complete && len(p.dirtiers) != 0 {
1119 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1122 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1123 t.pieceCompletionChanged(piece)
1128 // Non-blocking read. Client lock is not required.
1129 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1130 p := &t.pieces[off/t.info.PieceLength]
1131 p.waitNoPendingWrites()
1132 return p.Storage().ReadAt(b, off-p.Info().Offset())
1135 // Returns an error if the metadata was completed, but couldn't be set for
1136 // some reason. Blame it on the last peer to contribute.
1137 func (t *Torrent) maybeCompleteMetadata() error {
1142 if !t.haveAllMetadataPieces() {
1143 // Don't have enough metadata pieces.
1146 err := t.setInfoBytes(t.metadataBytes)
1148 t.invalidateMetadata()
1149 return fmt.Errorf("error setting info bytes: %s", err)
1151 if t.cl.config.Debug {
1152 t.logger.Printf("%s: got metadata from peers", t)
1157 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1158 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1160 now.Add(bitmap.BitIndex(begin))
1161 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1168 func (t *Torrent) needData() bool {
1169 if t.closed.IsSet() {
1175 return t._pendingPieces.Len() != 0
1178 func appendMissingStrings(old, new []string) (ret []string) {
1181 for _, n := range new {
1182 for _, o := range old {
1187 ret = append(ret, n)
1192 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1194 for minNumTiers > len(ret) {
1195 ret = append(ret, nil)
1200 func (t *Torrent) addTrackers(announceList [][]string) {
1201 fullAnnounceList := &t.metainfo.AnnounceList
1202 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1203 for tierIndex, trackerURLs := range announceList {
1204 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1206 t.startMissingTrackerScrapers()
1207 t.updateWantPeersEvent()
1210 // Don't call this before the info is available.
1211 func (t *Torrent) bytesCompleted() int64 {
1215 return t.info.TotalLength() - t.bytesLeft()
1218 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1221 return t.setInfoBytes(b)
1224 // Returns true if connection is removed from torrent.Conns.
1225 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1226 if !c.closed.IsSet() {
1227 panic("connection is not closed")
1228 // There are behaviours prevented by the closed state that will fail
1229 // if the connection has been deleted.
1233 if !t.cl.config.DisablePEX {
1236 torrent.Add("deleted connections", 1)
1237 c.deleteAllRequests()
1238 if t.numActivePeers() == 0 {
1239 t.assertNoPendingRequests()
1244 func (t *Torrent) numActivePeers() (num int) {
1245 t.iterPeers(func(*peer) {
1251 func (t *Torrent) assertNoPendingRequests() {
1252 if len(t.pendingRequests) != 0 {
1253 panic(t.pendingRequests)
1255 //if len(t.lastRequested) != 0 {
1256 // panic(t.lastRequested)
1260 func (t *Torrent) dropConnection(c *PeerConn) {
1261 t.cl.event.Broadcast()
1263 if t.deleteConnection(c) {
1268 func (t *Torrent) wantPeers() bool {
1269 if t.closed.IsSet() {
1272 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1275 return t.needData() || t.seeding()
1278 func (t *Torrent) updateWantPeersEvent() {
1280 t.wantPeersEvent.Set()
1282 t.wantPeersEvent.Clear()
1286 // Returns whether the client should make effort to seed the torrent.
1287 func (t *Torrent) seeding() bool {
1289 if t.closed.IsSet() {
1292 if t.dataUploadDisallowed {
1295 if cl.config.NoUpload {
1298 if !cl.config.Seed {
1301 if cl.config.DisableAggressiveUpload && t.needData() {
1307 func (t *Torrent) onWebRtcConn(
1308 c datachannel.ReadWriteCloser,
1309 dcc webtorrent.DataChannelContext,
1312 pc, err := t.cl.initiateProtocolHandshakes(
1313 context.Background(),
1314 webrtcNetConn{c, dcc},
1318 webrtcNetAddr{dcc.Remote},
1320 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1323 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1326 if dcc.LocalOffered {
1327 pc.Discovery = PeerSourceTracker
1329 pc.Discovery = PeerSourceIncoming
1333 err = t.cl.runHandshookConn(pc, t)
1335 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1339 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1340 err := t.cl.runHandshookConn(pc, t)
1341 if err != nil || logAll {
1342 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1346 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1347 t.logRunHandshookConn(pc, false, log.Debug)
1350 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1351 wtc, release := t.cl.websocketTrackers.Get(u.String())
1353 <-t.closed.LockedChan(t.cl.locker())
1356 wst := websocketTrackerStatus{u, wtc}
1358 err := wtc.Announce(tracker.Started, t.infoHash)
1360 t.logger.WithDefaultLevel(log.Warning).Printf(
1361 "error in initial announce to %q: %v",
1370 func (t *Torrent) startScrapingTracker(_url string) {
1374 u, err := url.Parse(_url)
1376 // URLs with a leading '*' appear to be a uTorrent convention to
1377 // disable trackers.
1379 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1383 if u.Scheme == "udp" {
1385 t.startScrapingTracker(u.String())
1387 t.startScrapingTracker(u.String())
1390 if _, ok := t.trackerAnnouncers[_url]; ok {
1393 sl := func() torrentTrackerAnnouncer {
1396 if t.cl.config.DisableWebtorrent {
1399 return t.startWebsocketAnnouncer(*u)
1401 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1405 if t.cl.config.DisableIPv6 {
1409 newAnnouncer := &trackerScraper{
1413 go newAnnouncer.Run()
1419 if t.trackerAnnouncers == nil {
1420 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1422 t.trackerAnnouncers[_url] = sl
1425 // Adds and starts tracker scrapers for tracker URLs that aren't already
1427 func (t *Torrent) startMissingTrackerScrapers() {
1428 if t.cl.config.DisableTrackers {
1431 t.startScrapingTracker(t.metainfo.Announce)
1432 for _, tier := range t.metainfo.AnnounceList {
1433 for _, url := range tier {
1434 t.startScrapingTracker(url)
1439 // Returns an AnnounceRequest with fields filled out to defaults and current
1441 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1442 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1443 // dependent on the network in use.
1444 return tracker.AnnounceRequest{
1446 NumWant: func() int32 {
1447 if t.wantPeers() && len(t.cl.dialers) > 0 {
1453 Port: uint16(t.cl.incomingPeerPort()),
1454 PeerId: t.cl.peerID,
1455 InfoHash: t.infoHash,
1456 Key: t.cl.announceKey(),
1458 // The following are vaguely described in BEP 3.
1460 Left: t.bytesLeftAnnounce(),
1461 Uploaded: t.stats.BytesWrittenData.Int64(),
1462 // There's no mention of wasted or unwanted download in the BEP.
1463 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1467 // Adds peers revealed in an announce until the announce ends, or we have
1469 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1471 for v := range pvs {
1473 for _, cp := range v.Peers {
1475 // Can't do anything with this.
1479 Addr: ipPortAddr{cp.IP, cp.Port},
1480 Source: PeerSourceDhtGetPeers,
1487 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1488 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1492 go t.consumeDhtAnnouncePeers(ps.Peers())
1494 case <-t.closed.LockedChan(t.cl.locker()):
1495 case <-time.After(5 * time.Minute):
1501 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1507 if t.closed.IsSet() {
1513 // TODO: Determine if there's a listener on the port we're announcing.
1514 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1525 err := t.announceToDht(true, s)
1527 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1533 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1534 for _, p := range peers {
1542 // The returned TorrentStats may require alignment in memory. See
1543 // https://github.com/anacrolix/torrent/issues/383.
1544 func (t *Torrent) Stats() TorrentStats {
1546 defer t.cl.rUnlock()
1547 return t.statsLocked()
1550 func (t *Torrent) statsLocked() (ret TorrentStats) {
1551 ret.ActivePeers = len(t.conns)
1552 ret.HalfOpenPeers = len(t.halfOpen)
1553 ret.PendingPeers = t.peers.Len()
1554 ret.TotalPeers = t.numTotalPeers()
1555 ret.ConnectedSeeders = 0
1556 for c := range t.conns {
1557 if all, ok := c.peerHasAllPieces(); all && ok {
1558 ret.ConnectedSeeders++
1561 ret.ConnStats = t.stats.Copy()
1565 // The total number of peers in the torrent.
1566 func (t *Torrent) numTotalPeers() int {
1567 peers := make(map[string]struct{})
1568 for conn := range t.conns {
1569 ra := conn.conn.RemoteAddr()
1571 // It's been closed and doesn't support RemoteAddr.
1574 peers[ra.String()] = struct{}{}
1576 for addr := range t.halfOpen {
1577 peers[addr] = struct{}{}
1579 t.peers.Each(func(peer PeerInfo) {
1580 peers[peer.Addr.String()] = struct{}{}
1585 // Reconcile bytes transferred before connection was associated with a
1587 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1588 if c._stats != (ConnStats{
1589 // Handshakes should only increment these fields:
1590 BytesWritten: c._stats.BytesWritten,
1591 BytesRead: c._stats.BytesRead,
1595 c.postHandshakeStats(func(cs *ConnStats) {
1596 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1597 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1599 c.reconciledHandshakeStats = true
1602 // Returns true if the connection is added.
1603 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1606 torrent.Add("added connections", 1)
1609 if t.closed.IsSet() {
1610 return errors.New("torrent closed")
1612 for c0 := range t.conns {
1613 if c.PeerID != c0.PeerID {
1616 if !t.cl.config.DropDuplicatePeerIds {
1619 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1621 t.deleteConnection(c0)
1623 return errors.New("existing connection preferred")
1626 if len(t.conns) >= t.maxEstablishedConns {
1627 c := t.worstBadConn()
1629 return errors.New("don't want conns")
1632 t.deleteConnection(c)
1634 if len(t.conns) >= t.maxEstablishedConns {
1637 t.conns[c] = struct{}{}
1638 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1639 t.pex.Add(c) // as no further extended handshake expected
1644 func (t *Torrent) wantConns() bool {
1645 if !t.networkingEnabled {
1648 if t.closed.IsSet() {
1651 if !t.seeding() && !t.needData() {
1654 if len(t.conns) < t.maxEstablishedConns {
1657 return t.worstBadConn() != nil
1660 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1663 oldMax = t.maxEstablishedConns
1664 t.maxEstablishedConns = max
1665 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1666 return worseConn(&l.peer, &r.peer)
1668 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1669 t.dropConnection(wcs.Pop().(*PeerConn))
1675 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1676 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1679 t.cl.event.Broadcast()
1680 if t.closed.IsSet() {
1684 // Don't score the first time a piece is hashed, it could be an initial check.
1685 if p.storageCompletionOk {
1687 pieceHashedCorrect.Add(1)
1689 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1690 pieceHashedNotCorrect.Add(1)
1695 if len(p.dirtiers) != 0 {
1696 // Don't increment stats above connection-level for every involved connection.
1697 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1699 for c := range p.dirtiers {
1700 c._stats.incrementPiecesDirtiedGood()
1702 t.clearPieceTouchers(piece)
1703 err := p.Storage().MarkComplete()
1705 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1707 t.pendAllChunkSpecs(piece)
1709 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1710 // Peers contributed to all the data for this piece hash failure, and the failure was
1711 // not due to errors in the storage (such as data being dropped in a cache).
1713 // Increment Torrent and above stats, and then specific connections.
1714 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1715 for c := range p.dirtiers {
1716 // Y u do dis peer?!
1717 c.stats().incrementPiecesDirtiedBad()
1720 bannableTouchers := make([]*peer, 0, len(p.dirtiers))
1721 for c := range p.dirtiers {
1723 bannableTouchers = append(bannableTouchers, c)
1726 t.clearPieceTouchers(piece)
1727 slices.Sort(bannableTouchers, connLessTrusted)
1729 if t.cl.config.Debug {
1731 "bannable conns by trust for piece %d: %v",
1733 func() (ret []connectionTrust) {
1734 for _, c := range bannableTouchers {
1735 ret = append(ret, c.trust())
1742 if len(bannableTouchers) >= 1 {
1743 c := bannableTouchers[0]
1744 t.cl.banPeerIP(c.remoteIp())
1748 t.onIncompletePiece(piece)
1749 p.Storage().MarkNotComplete()
1751 t.updatePieceCompletion(piece)
1754 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1755 // TODO: Make faster
1756 for cn := range t.conns {
1761 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1762 t.pendAllChunkSpecs(piece)
1763 t.cancelRequestsForPiece(piece)
1764 for conn := range t.conns {
1769 // Called when a piece is found to be not complete.
1770 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1771 if t.pieceAllDirty(piece) {
1772 t.pendAllChunkSpecs(piece)
1774 if !t.wantPieceIndex(piece) {
1775 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1778 // We could drop any connections that we told we have a piece that we
1779 // don't here. But there's a test failure, and it seems clients don't care
1780 // if you request pieces that you already claim to have. Pruning bad
1781 // connections might just remove any connections that aren't treating us
1782 // favourably anyway.
1784 // for c := range t.conns {
1785 // if c.sentHave(piece) {
1789 t.iterPeers(func(conn *peer) {
1790 if conn.peerHasPiece(piece) {
1791 conn.updateRequests()
1796 func (t *Torrent) tryCreateMorePieceHashers() {
1797 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1801 func (t *Torrent) tryCreatePieceHasher() bool {
1802 if t.storage == nil {
1805 pi, ok := t.getPieceToHash()
1810 t.piecesQueuedForHash.Remove(pi)
1812 t.publishPieceChange(pi)
1813 t.updatePiecePriority(pi)
1814 t.storageLock.RLock()
1815 t.activePieceHashes++
1816 go t.pieceHasher(pi)
1820 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1821 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1822 if t.piece(i).hashing {
1832 func (t *Torrent) pieceHasher(index pieceIndex) {
1834 sum, copyErr := t.hashPiece(index)
1835 correct := sum == *p.hash
1839 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1841 t.storageLock.RUnlock()
1845 t.updatePiecePriority(index)
1846 t.pieceHashed(index, correct, copyErr)
1847 t.publishPieceChange(index)
1848 t.activePieceHashes--
1849 t.tryCreateMorePieceHashers()
1852 // Return the connections that touched a piece, and clear the entries while doing it.
1853 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1855 for c := range p.dirtiers {
1856 delete(c.peerTouchedPieces, pi)
1857 delete(p.dirtiers, c)
1861 func (t *Torrent) peersAsSlice() (ret []*peer) {
1862 t.iterPeers(func(p *peer) {
1863 ret = append(ret, p)
1868 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1869 piece := t.piece(pieceIndex)
1870 if piece.queuedForHash() {
1873 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1874 t.publishPieceChange(pieceIndex)
1875 t.updatePiecePriority(pieceIndex)
1876 t.tryCreateMorePieceHashers()
1879 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1880 // before the Info is available.
1881 func (t *Torrent) VerifyData() {
1882 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1883 t.Piece(i).VerifyData()
1887 // Start the process of connecting to the given peer for the given torrent if appropriate.
1888 func (t *Torrent) initiateConn(peer PeerInfo) {
1889 if peer.Id == t.cl.peerID {
1893 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1897 if t.addrActive(addr.String()) {
1900 t.halfOpen[addr.String()] = peer
1901 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1904 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1905 // quickly make one Client visible to the Torrent of another Client.
1906 func (t *Torrent) AddClientPeer(cl *Client) int {
1907 return t.AddPeers(func() (ps []PeerInfo) {
1908 for _, la := range cl.ListenAddrs() {
1909 ps = append(ps, PeerInfo{
1918 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1920 func (t *Torrent) allStats(f func(*ConnStats)) {
1925 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1926 return t.pieces[i].hashing
1929 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1930 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1933 func (t *Torrent) dialTimeout() time.Duration {
1934 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1937 func (t *Torrent) piece(i int) *Piece {
1941 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1945 type torrentRequestStrategyCallbacks struct {
1949 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
1950 torrent.Add("request timeouts", 1)
1952 defer cb.t.cl.unlock()
1953 cb.t.iterPeers(func(cn *peer) {
1954 if cn.peerHasPiece(pieceIndex(r.Index)) {
1961 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
1962 return torrentRequestStrategyCallbacks{t}
1965 func (t *Torrent) onWriteChunkErr(err error) {
1966 if t.userOnWriteChunkErr != nil {
1967 go t.userOnWriteChunkErr(err)
1970 t.disallowDataDownloadLocked()
1973 func (t *Torrent) DisallowDataDownload() {
1976 t.disallowDataDownloadLocked()
1979 func (t *Torrent) disallowDataDownloadLocked() {
1980 t.dataDownloadDisallowed = true
1981 t.iterPeers(func(c *peer) {
1986 func (t *Torrent) AllowDataDownload() {
1989 t.dataDownloadDisallowed = false
1990 t.iterPeers(func(c *peer) {
1995 func (t *Torrent) AllowDataUpload() {
1998 t.dataUploadDisallowed = false
1999 for c := range t.conns {
2004 func (t *Torrent) DisallowDataUpload() {
2007 t.dataUploadDisallowed = true
2008 for c := range t.conns {
2013 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2016 t.userOnWriteChunkErr = f
2019 func (t *Torrent) iterPeers(f func(*peer)) {
2020 for pc := range t.conns {
2023 for _, ws := range t.webSeeds {
2028 func (t *Torrent) addWebSeed(url string) {
2029 if t.cl.config.DisableWebseeds {
2032 if _, ok := t.webSeeds[url]; ok {
2035 const maxRequests = 10
2042 reconciledHandshakeStats: true,
2043 peerSentHaveAll: true,
2044 PeerMaxRequests: maxRequests,
2046 client: webseed.Client{
2047 HttpClient: http.DefaultClient,
2050 requests: make(map[request]webseed.Request, maxRequests),
2052 ws.peer.logger = t.logger.WithContextValue(&ws)
2053 ws.peer.peerImpl = &ws
2055 ws.onGotInfo(t.info)
2057 t.webSeeds[url] = &ws.peer
2060 func (t *Torrent) peerIsActive(p *peer) (active bool) {
2061 t.iterPeers(func(p1 *peer) {