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() (initiated int) {
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 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1093 p := t.peers.PopMax()
1100 func (t *Torrent) getConnPieceInclination() []int {
1101 _ret := t.connPieceInclinationPool.Get()
1103 pieceInclinationsNew.Add(1)
1104 return rand.Perm(int(t.numPieces()))
1106 pieceInclinationsReused.Add(1)
1107 return *_ret.(*[]int)
1110 func (t *Torrent) putPieceInclination(pi []int) {
1111 t.connPieceInclinationPool.Put(&pi)
1112 pieceInclinationsPut.Add(1)
1115 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1117 uncached := t.pieceCompleteUncached(piece)
1118 cached := p.completion()
1119 changed := cached != uncached
1120 complete := uncached.Complete
1121 p.storageCompletionOk = uncached.Ok
1122 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1123 if complete && len(p.dirtiers) != 0 {
1124 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1127 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1128 t.pieceCompletionChanged(piece)
1133 // Non-blocking read. Client lock is not required.
1134 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1135 p := &t.pieces[off/t.info.PieceLength]
1136 p.waitNoPendingWrites()
1137 return p.Storage().ReadAt(b, off-p.Info().Offset())
1140 // Returns an error if the metadata was completed, but couldn't be set for
1141 // some reason. Blame it on the last peer to contribute.
1142 func (t *Torrent) maybeCompleteMetadata() error {
1147 if !t.haveAllMetadataPieces() {
1148 // Don't have enough metadata pieces.
1151 err := t.setInfoBytes(t.metadataBytes)
1153 t.invalidateMetadata()
1154 return fmt.Errorf("error setting info bytes: %s", err)
1156 if t.cl.config.Debug {
1157 t.logger.Printf("%s: got metadata from peers", t)
1162 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1163 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1165 now.Add(bitmap.BitIndex(begin))
1166 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1173 func (t *Torrent) needData() bool {
1174 if t.closed.IsSet() {
1180 return t._pendingPieces.Len() != 0
1183 func appendMissingStrings(old, new []string) (ret []string) {
1186 for _, n := range new {
1187 for _, o := range old {
1192 ret = append(ret, n)
1197 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1199 for minNumTiers > len(ret) {
1200 ret = append(ret, nil)
1205 func (t *Torrent) addTrackers(announceList [][]string) {
1206 fullAnnounceList := &t.metainfo.AnnounceList
1207 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1208 for tierIndex, trackerURLs := range announceList {
1209 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1211 t.startMissingTrackerScrapers()
1212 t.updateWantPeersEvent()
1215 // Don't call this before the info is available.
1216 func (t *Torrent) bytesCompleted() int64 {
1220 return t.info.TotalLength() - t.bytesLeft()
1223 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1226 return t.setInfoBytes(b)
1229 // Returns true if connection is removed from torrent.Conns.
1230 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1231 if !c.closed.IsSet() {
1232 panic("connection is not closed")
1233 // There are behaviours prevented by the closed state that will fail
1234 // if the connection has been deleted.
1238 if !t.cl.config.DisablePEX {
1241 torrent.Add("deleted connections", 1)
1242 c.deleteAllRequests()
1243 if t.numActivePeers() == 0 {
1244 t.assertNoPendingRequests()
1249 func (t *Torrent) numActivePeers() (num int) {
1250 t.iterPeers(func(*peer) {
1256 func (t *Torrent) assertNoPendingRequests() {
1257 if len(t.pendingRequests) != 0 {
1258 panic(t.pendingRequests)
1260 //if len(t.lastRequested) != 0 {
1261 // panic(t.lastRequested)
1265 func (t *Torrent) dropConnection(c *PeerConn) {
1266 t.cl.event.Broadcast()
1268 if t.deleteConnection(c) {
1273 func (t *Torrent) wantPeers() bool {
1274 if t.closed.IsSet() {
1277 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1280 return t.needData() || t.seeding()
1283 func (t *Torrent) updateWantPeersEvent() {
1285 t.wantPeersEvent.Set()
1287 t.wantPeersEvent.Clear()
1291 // Returns whether the client should make effort to seed the torrent.
1292 func (t *Torrent) seeding() bool {
1294 if t.closed.IsSet() {
1297 if t.dataUploadDisallowed {
1300 if cl.config.NoUpload {
1303 if !cl.config.Seed {
1306 if cl.config.DisableAggressiveUpload && t.needData() {
1312 func (t *Torrent) onWebRtcConn(
1313 c datachannel.ReadWriteCloser,
1314 dcc webtorrent.DataChannelContext,
1317 pc, err := t.cl.initiateProtocolHandshakes(
1318 context.Background(),
1319 webrtcNetConn{c, dcc},
1323 webrtcNetAddr{dcc.Remote},
1325 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1328 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1331 if dcc.LocalOffered {
1332 pc.Discovery = PeerSourceTracker
1334 pc.Discovery = PeerSourceIncoming
1338 err = t.cl.runHandshookConn(pc, t)
1340 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1344 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1345 err := t.cl.runHandshookConn(pc, t)
1346 if err != nil || logAll {
1347 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1351 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1352 t.logRunHandshookConn(pc, false, log.Debug)
1355 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1356 wtc, release := t.cl.websocketTrackers.Get(u.String())
1358 <-t.closed.LockedChan(t.cl.locker())
1361 wst := websocketTrackerStatus{u, wtc}
1363 err := wtc.Announce(tracker.Started, t.infoHash)
1365 t.logger.WithDefaultLevel(log.Warning).Printf(
1366 "error in initial announce to %q: %v",
1375 func (t *Torrent) startScrapingTracker(_url string) {
1379 u, err := url.Parse(_url)
1381 // URLs with a leading '*' appear to be a uTorrent convention to
1382 // disable trackers.
1384 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1388 if u.Scheme == "udp" {
1390 t.startScrapingTracker(u.String())
1392 t.startScrapingTracker(u.String())
1395 if _, ok := t.trackerAnnouncers[_url]; ok {
1398 sl := func() torrentTrackerAnnouncer {
1401 if t.cl.config.DisableWebtorrent {
1404 return t.startWebsocketAnnouncer(*u)
1406 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1410 if t.cl.config.DisableIPv6 {
1414 urlString := (*u).String()
1416 newAnnouncer := &trackerScraper{
1422 if cl.activeAnnounces == nil {
1423 cl.activeAnnounces = make(map[string]struct{})
1426 if _, ok := cl.activeAnnounces[urlString]; ok {
1432 cl.activeAnnounces[urlString] = struct{}{}
1437 delete(cl.activeAnnounces, urlString)
1438 cl.event.Broadcast()
1441 go newAnnouncer.Run()
1447 if t.trackerAnnouncers == nil {
1448 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1450 t.trackerAnnouncers[_url] = sl
1453 // Adds and starts tracker scrapers for tracker URLs that aren't already
1455 func (t *Torrent) startMissingTrackerScrapers() {
1456 if t.cl.config.DisableTrackers {
1459 t.startScrapingTracker(t.metainfo.Announce)
1460 for _, tier := range t.metainfo.AnnounceList {
1461 for _, url := range tier {
1462 t.startScrapingTracker(url)
1467 // Returns an AnnounceRequest with fields filled out to defaults and current
1469 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1470 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1471 // dependent on the network in use.
1472 return tracker.AnnounceRequest{
1474 NumWant: func() int32 {
1475 if t.wantPeers() && len(t.cl.dialers) > 0 {
1481 Port: uint16(t.cl.incomingPeerPort()),
1482 PeerId: t.cl.peerID,
1483 InfoHash: t.infoHash,
1484 Key: t.cl.announceKey(),
1486 // The following are vaguely described in BEP 3.
1488 Left: t.bytesLeftAnnounce(),
1489 Uploaded: t.stats.BytesWrittenData.Int64(),
1490 // There's no mention of wasted or unwanted download in the BEP.
1491 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1495 // Adds peers revealed in an announce until the announce ends, or we have
1497 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1499 for v := range pvs {
1501 for _, cp := range v.Peers {
1503 // Can't do anything with this.
1507 Addr: ipPortAddr{cp.IP, cp.Port},
1508 Source: PeerSourceDhtGetPeers,
1515 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1516 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1520 go t.consumeDhtAnnouncePeers(ps.Peers())
1522 case <-t.closed.LockedChan(t.cl.locker()):
1523 case <-time.After(5 * time.Minute):
1529 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1535 if t.closed.IsSet() {
1541 // TODO: Determine if there's a listener on the port we're announcing.
1542 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1553 err := t.announceToDht(true, s)
1555 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1561 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1562 for _, p := range peers {
1570 // The returned TorrentStats may require alignment in memory. See
1571 // https://github.com/anacrolix/torrent/issues/383.
1572 func (t *Torrent) Stats() TorrentStats {
1574 defer t.cl.rUnlock()
1575 return t.statsLocked()
1578 func (t *Torrent) statsLocked() (ret TorrentStats) {
1579 ret.ActivePeers = len(t.conns)
1580 ret.HalfOpenPeers = len(t.halfOpen)
1581 ret.PendingPeers = t.peers.Len()
1582 ret.TotalPeers = t.numTotalPeers()
1583 ret.ConnectedSeeders = 0
1584 for c := range t.conns {
1585 if all, ok := c.peerHasAllPieces(); all && ok {
1586 ret.ConnectedSeeders++
1589 ret.ConnStats = t.stats.Copy()
1593 // The total number of peers in the torrent.
1594 func (t *Torrent) numTotalPeers() int {
1595 peers := make(map[string]struct{})
1596 for conn := range t.conns {
1597 ra := conn.conn.RemoteAddr()
1599 // It's been closed and doesn't support RemoteAddr.
1602 peers[ra.String()] = struct{}{}
1604 for addr := range t.halfOpen {
1605 peers[addr] = struct{}{}
1607 t.peers.Each(func(peer PeerInfo) {
1608 peers[peer.Addr.String()] = struct{}{}
1613 // Reconcile bytes transferred before connection was associated with a
1615 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1616 if c._stats != (ConnStats{
1617 // Handshakes should only increment these fields:
1618 BytesWritten: c._stats.BytesWritten,
1619 BytesRead: c._stats.BytesRead,
1623 c.postHandshakeStats(func(cs *ConnStats) {
1624 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1625 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1627 c.reconciledHandshakeStats = true
1630 // Returns true if the connection is added.
1631 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1634 torrent.Add("added connections", 1)
1637 if t.closed.IsSet() {
1638 return errors.New("torrent closed")
1640 for c0 := range t.conns {
1641 if c.PeerID != c0.PeerID {
1644 if !t.cl.config.DropDuplicatePeerIds {
1647 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1649 t.deleteConnection(c0)
1651 return errors.New("existing connection preferred")
1654 if len(t.conns) >= t.maxEstablishedConns {
1655 c := t.worstBadConn()
1657 return errors.New("don't want conns")
1660 t.deleteConnection(c)
1662 if len(t.conns) >= t.maxEstablishedConns {
1665 t.conns[c] = struct{}{}
1666 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1667 t.pex.Add(c) // as no further extended handshake expected
1672 func (t *Torrent) wantConns() bool {
1673 if !t.networkingEnabled {
1676 if t.closed.IsSet() {
1679 if !t.seeding() && !t.needData() {
1682 if len(t.conns) < t.maxEstablishedConns {
1685 return t.worstBadConn() != nil
1688 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1691 oldMax = t.maxEstablishedConns
1692 t.maxEstablishedConns = max
1693 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1694 return worseConn(&l.peer, &r.peer)
1696 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1697 t.dropConnection(wcs.Pop().(*PeerConn))
1703 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1704 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1707 t.cl.event.Broadcast()
1708 if t.closed.IsSet() {
1712 // Don't score the first time a piece is hashed, it could be an initial check.
1713 if p.storageCompletionOk {
1715 pieceHashedCorrect.Add(1)
1717 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1718 pieceHashedNotCorrect.Add(1)
1723 if len(p.dirtiers) != 0 {
1724 // Don't increment stats above connection-level for every involved connection.
1725 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1727 for c := range p.dirtiers {
1728 c._stats.incrementPiecesDirtiedGood()
1730 t.clearPieceTouchers(piece)
1731 err := p.Storage().MarkComplete()
1733 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1735 t.pendAllChunkSpecs(piece)
1737 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1738 // Peers contributed to all the data for this piece hash failure, and the failure was
1739 // not due to errors in the storage (such as data being dropped in a cache).
1741 // Increment Torrent and above stats, and then specific connections.
1742 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1743 for c := range p.dirtiers {
1744 // Y u do dis peer?!
1745 c.stats().incrementPiecesDirtiedBad()
1748 bannableTouchers := make([]*peer, 0, len(p.dirtiers))
1749 for c := range p.dirtiers {
1751 bannableTouchers = append(bannableTouchers, c)
1754 t.clearPieceTouchers(piece)
1755 slices.Sort(bannableTouchers, connLessTrusted)
1757 if t.cl.config.Debug {
1759 "bannable conns by trust for piece %d: %v",
1761 func() (ret []connectionTrust) {
1762 for _, c := range bannableTouchers {
1763 ret = append(ret, c.trust())
1770 if len(bannableTouchers) >= 1 {
1771 c := bannableTouchers[0]
1772 t.cl.banPeerIP(c.remoteIp())
1776 t.onIncompletePiece(piece)
1777 p.Storage().MarkNotComplete()
1779 t.updatePieceCompletion(piece)
1782 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1783 // TODO: Make faster
1784 for cn := range t.conns {
1789 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1790 t.pendAllChunkSpecs(piece)
1791 t.cancelRequestsForPiece(piece)
1792 for conn := range t.conns {
1797 // Called when a piece is found to be not complete.
1798 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1799 if t.pieceAllDirty(piece) {
1800 t.pendAllChunkSpecs(piece)
1802 if !t.wantPieceIndex(piece) {
1803 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1806 // We could drop any connections that we told we have a piece that we
1807 // don't here. But there's a test failure, and it seems clients don't care
1808 // if you request pieces that you already claim to have. Pruning bad
1809 // connections might just remove any connections that aren't treating us
1810 // favourably anyway.
1812 // for c := range t.conns {
1813 // if c.sentHave(piece) {
1817 t.iterPeers(func(conn *peer) {
1818 if conn.peerHasPiece(piece) {
1819 conn.updateRequests()
1824 func (t *Torrent) tryCreateMorePieceHashers() {
1825 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1829 func (t *Torrent) tryCreatePieceHasher() bool {
1830 if t.storage == nil {
1833 pi, ok := t.getPieceToHash()
1838 t.piecesQueuedForHash.Remove(pi)
1840 t.publishPieceChange(pi)
1841 t.updatePiecePriority(pi)
1842 t.storageLock.RLock()
1843 t.activePieceHashes++
1844 go t.pieceHasher(pi)
1848 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1849 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1850 if t.piece(i).hashing {
1860 func (t *Torrent) pieceHasher(index pieceIndex) {
1862 sum, copyErr := t.hashPiece(index)
1863 correct := sum == *p.hash
1867 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1869 t.storageLock.RUnlock()
1873 t.updatePiecePriority(index)
1874 t.pieceHashed(index, correct, copyErr)
1875 t.publishPieceChange(index)
1876 t.activePieceHashes--
1877 t.tryCreateMorePieceHashers()
1880 // Return the connections that touched a piece, and clear the entries while doing it.
1881 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1883 for c := range p.dirtiers {
1884 delete(c.peerTouchedPieces, pi)
1885 delete(p.dirtiers, c)
1889 func (t *Torrent) peersAsSlice() (ret []*peer) {
1890 t.iterPeers(func(p *peer) {
1891 ret = append(ret, p)
1896 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1897 piece := t.piece(pieceIndex)
1898 if piece.queuedForHash() {
1901 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1902 t.publishPieceChange(pieceIndex)
1903 t.updatePiecePriority(pieceIndex)
1904 t.tryCreateMorePieceHashers()
1907 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1908 // before the Info is available.
1909 func (t *Torrent) VerifyData() {
1910 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1911 t.Piece(i).VerifyData()
1915 // Start the process of connecting to the given peer for the given torrent if appropriate.
1916 func (t *Torrent) initiateConn(peer PeerInfo) {
1917 if peer.Id == t.cl.peerID {
1920 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1924 if t.addrActive(addr.String()) {
1928 t.halfOpen[addr.String()] = peer
1929 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1932 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1933 // quickly make one Client visible to the Torrent of another Client.
1934 func (t *Torrent) AddClientPeer(cl *Client) int {
1935 return t.AddPeers(func() (ps []PeerInfo) {
1936 for _, la := range cl.ListenAddrs() {
1937 ps = append(ps, PeerInfo{
1946 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1948 func (t *Torrent) allStats(f func(*ConnStats)) {
1953 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1954 return t.pieces[i].hashing
1957 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1958 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1961 func (t *Torrent) dialTimeout() time.Duration {
1962 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1965 func (t *Torrent) piece(i int) *Piece {
1969 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1973 type torrentRequestStrategyCallbacks struct {
1977 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
1978 torrent.Add("request timeouts", 1)
1980 defer cb.t.cl.unlock()
1981 cb.t.iterPeers(func(cn *peer) {
1982 if cn.peerHasPiece(pieceIndex(r.Index)) {
1989 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
1990 return torrentRequestStrategyCallbacks{t}
1993 func (t *Torrent) onWriteChunkErr(err error) {
1994 if t.userOnWriteChunkErr != nil {
1995 go t.userOnWriteChunkErr(err)
1998 t.disallowDataDownloadLocked()
2001 func (t *Torrent) DisallowDataDownload() {
2004 t.disallowDataDownloadLocked()
2007 func (t *Torrent) disallowDataDownloadLocked() {
2008 t.dataDownloadDisallowed = true
2009 t.iterPeers(func(c *peer) {
2014 func (t *Torrent) AllowDataDownload() {
2017 t.dataDownloadDisallowed = false
2018 t.iterPeers(func(c *peer) {
2023 func (t *Torrent) AllowDataUpload() {
2026 t.dataUploadDisallowed = false
2027 for c := range t.conns {
2032 func (t *Torrent) DisallowDataUpload() {
2035 t.dataUploadDisallowed = true
2036 for c := range t.conns {
2041 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2044 t.userOnWriteChunkErr = f
2047 func (t *Torrent) iterPeers(f func(*peer)) {
2048 for pc := range t.conns {
2051 for _, ws := range t.webSeeds {
2056 func (t *Torrent) addWebSeed(url string) {
2057 if t.cl.config.DisableWebseeds {
2060 if _, ok := t.webSeeds[url]; ok {
2063 const maxRequests = 10
2069 reconciledHandshakeStats: true,
2070 peerSentHaveAll: true,
2071 PeerMaxRequests: maxRequests,
2073 client: webseed.Client{
2074 HttpClient: http.DefaultClient,
2077 requests: make(map[request]webseed.Request, maxRequests),
2079 ws.peer.logger = t.logger.WithContextValue(&ws)
2080 ws.peer.peerImpl = &ws
2082 ws.onGotInfo(t.info)
2084 t.webSeeds[url] = &ws.peer
2087 func (t *Torrent) peerIsActive(p *peer) (active bool) {
2088 t.iterPeers(func(p1 *peer) {