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 userOnWriteChunkErr func(error)
55 // Determines what chunks to request from peers.
56 requestStrategy requestStrategy
58 closed missinggo.Event
59 infoHash metainfo.Hash
61 // Values are the piece indices that changed.
62 pieceStateChanges *pubsub.PubSub
63 // The size of chunks to request from peers over the wire. This is
64 // normally 16KiB by convention these days.
67 // Total length of the torrent in bytes. Stored because it's not O(1) to
68 // get this from the info dict.
71 // The storage to open when the info dict becomes available.
72 storageOpener *storage.Client
73 // Storage for torrent data.
74 storage *storage.Torrent
75 // Read-locked for using storage, and write-locked for Closing.
76 storageLock sync.RWMutex
78 // TODO: Only announce stuff is used?
79 metainfo metainfo.MetaInfo
81 // The info dict. nil if we don't have it (yet).
83 fileIndex segments.Index
86 webSeeds map[string]*peer
88 // Active peer connections, running message stream loops. TODO: Make this
89 // open (not-closed) connections only.
90 conns map[*PeerConn]struct{}
91 maxEstablishedConns int
92 // Set of addrs to which we're attempting to connect. Connections are
93 // half-open until all handshakes are completed.
94 halfOpen map[string]PeerInfo
97 // Reserve of peers to connect to. A peer can be both here and in the
98 // active connections if were told about the peer after connecting with
99 // them. That encourages us to reconnect to peers that are well known in
101 peers prioritizedPeers
102 // Whether we want to know to know more peers.
103 wantPeersEvent missinggo.Event
104 // An announcer for each tracker URL.
105 trackerAnnouncers map[string]torrentTrackerAnnouncer
106 // How many times we've initiated a DHT announce. TODO: Move into stats.
109 // Name used if the info name isn't available. Should be cleared when the
110 // Info does become available.
114 // The bencoded bytes of the info dict. This is actively manipulated if
115 // the info bytes aren't initially available, and we try to fetch them
118 // Each element corresponds to the 16KiB metadata pieces. If true, we have
119 // received that piece.
120 metadataCompletedChunks []bool
121 metadataChanged sync.Cond
123 // Set when .Info is obtained.
124 gotMetainfo missinggo.Event
126 readers map[*reader]struct{}
127 _readerNowPieces bitmap.Bitmap
128 _readerReadaheadPieces bitmap.Bitmap
130 // A cache of pieces we need to get. Calculated from various piece and
131 // file priorities and completion states elsewhere.
132 _pendingPieces prioritybitmap.PriorityBitmap
133 // A cache of completed piece indices.
134 _completedPieces bitmap.Bitmap
135 // Pieces that need to be hashed.
136 piecesQueuedForHash bitmap.Bitmap
137 activePieceHashes int
139 // A pool of piece priorities []int for assignment to new connections.
140 // These "inclinations" are used to give connections preference for
142 connPieceInclinationPool sync.Pool
144 // Count of each request across active connections.
145 pendingRequests map[request]int
150 func (t *Torrent) numConns() int {
154 func (t *Torrent) numReaders() int {
155 return len(t.readers)
158 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
159 return t._readerNowPieces
162 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
163 return t._readerReadaheadPieces
166 func (t *Torrent) ignorePieces() bitmap.Bitmap {
167 ret := t._completedPieces.Copy()
168 ret.Union(t.piecesQueuedForHash)
169 for i := 0; i < t.numPieces(); i++ {
170 if t.piece(i).hashing {
177 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
178 return &t._pendingPieces
181 func (t *Torrent) tickleReaders() {
182 t.cl.event.Broadcast()
185 // Returns a channel that is closed when the Torrent is closed.
186 func (t *Torrent) Closed() <-chan struct{} {
187 return t.closed.LockedChan(t.cl.locker())
190 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
191 // pending, and half-open peers.
192 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
193 // Add pending peers to the list
194 t.peers.Each(func(peer PeerInfo) {
195 ks = append(ks, peer)
198 // Add half-open peers to the list
199 for _, peer := range t.halfOpen {
200 ks = append(ks, peer)
203 // Add active peers to the list
204 for conn := range t.conns {
206 ks = append(ks, PeerInfo{
208 Addr: conn.remoteAddr,
209 Source: conn.Discovery,
210 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
211 // > But if we're not connected to them with an encrypted connection, I couldn't say
212 // > what's appropriate. We can carry forward the SupportsEncryption value as we
213 // > received it from trackers/DHT/PEX, or just use the encryption state for the
214 // > connection. It's probably easiest to do the latter for now.
215 // https://github.com/anacrolix/torrent/pull/188
216 SupportsEncryption: conn.headerEncrypted,
223 func (t *Torrent) setChunkSize(size pp.Integer) {
225 t.chunkPool = &sync.Pool{
226 New: func() interface{} {
227 b := make([]byte, size)
233 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
234 return t._completedPieces.Get(bitmap.BitIndex(piece))
237 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
238 return t.pieces[piece].Storage().Completion()
241 // There's a connection to that address already.
242 func (t *Torrent) addrActive(addr string) bool {
243 if _, ok := t.halfOpen[addr]; ok {
246 for c := range t.conns {
248 if ra.String() == addr {
255 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
256 ret = make([]*PeerConn, 0, len(t.conns))
257 for c := range t.conns {
258 if !c.closed.IsSet() {
265 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
267 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
268 if t.closed.IsSet() {
271 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
272 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
273 torrent.Add("peers not added because of bad addr", 1)
274 // cl.logger.Printf("peers not added because of bad addr: %v", p)
278 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
279 torrent.Add("peers replaced", 1)
280 if !replaced.Equal(p) {
281 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
288 for t.peers.Len() > cl.config.TorrentPeersHighWater {
289 _, ok := t.peers.DeleteMin()
291 torrent.Add("excess reserve peers discarded", 1)
297 func (t *Torrent) invalidateMetadata() {
298 for i := range t.metadataCompletedChunks {
299 t.metadataCompletedChunks[i] = false
306 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
310 if index >= len(t.metadataCompletedChunks) {
311 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
314 copy(t.metadataBytes[(1<<14)*index:], data)
315 t.metadataCompletedChunks[index] = true
318 func (t *Torrent) metadataPieceCount() int {
319 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
322 func (t *Torrent) haveMetadataPiece(piece int) bool {
324 return (1<<14)*piece < len(t.metadataBytes)
326 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
330 func (t *Torrent) metadataSize() int {
331 return len(t.metadataBytes)
334 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
335 for i := 0; i < len(info.Pieces); i += sha1.Size {
336 ret = append(ret, info.Pieces[i:i+sha1.Size])
341 func (t *Torrent) makePieces() {
342 hashes := infoPieceHashes(t.info)
343 t.pieces = make([]Piece, len(hashes))
344 for i, hash := range hashes {
345 piece := &t.pieces[i]
347 piece.index = pieceIndex(i)
348 piece.noPendingWrites.L = &piece.pendingWritesMutex
349 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
351 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
352 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
353 piece.files = files[beginFile:endFile]
357 // Returns the index of the first file containing the piece. files must be
358 // ordered by offset.
359 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
360 for i, f := range files {
361 if f.offset+f.length > pieceOffset {
368 // Returns the index after the last file containing the piece. files must be
369 // ordered by offset.
370 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
371 for i, f := range files {
372 if f.offset+f.length >= pieceEndOffset {
379 func (t *Torrent) cacheLength() {
381 for _, f := range t.info.UpvertedFiles() {
387 func (t *Torrent) setInfo(info *metainfo.Info) error {
388 if err := validateInfo(info); err != nil {
389 return fmt.Errorf("bad info: %s", err)
391 if t.storageOpener != nil {
393 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
395 return fmt.Errorf("error opening torrent storage: %s", err)
401 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
402 t.displayName = "" // Save a few bytes lol.
409 func (t *Torrent) onSetInfo() {
410 for conn := range t.conns {
411 if err := conn.setNumPieces(t.numPieces()); err != nil {
412 t.logger.Printf("closing connection: %s", err)
416 for i := range t.pieces {
417 t.updatePieceCompletion(pieceIndex(i))
419 if !p.storageCompletionOk {
420 // t.logger.Printf("piece %s completion unknown, queueing check", p)
421 t.queuePieceCheck(pieceIndex(i))
424 t.cl.event.Broadcast()
426 t.updateWantPeersEvent()
427 t.pendingRequests = make(map[request]int)
428 t.tryCreateMorePieceHashers()
431 // Called when metadata for a torrent becomes available.
432 func (t *Torrent) setInfoBytes(b []byte) error {
433 if metainfo.HashBytes(b) != t.infoHash {
434 return errors.New("info bytes have wrong hash")
436 var info metainfo.Info
437 if err := bencode.Unmarshal(b, &info); err != nil {
438 return fmt.Errorf("error unmarshalling info bytes: %s", err)
441 t.metadataCompletedChunks = nil
445 if err := t.setInfo(&info); err != nil {
452 func (t *Torrent) haveAllMetadataPieces() bool {
456 if t.metadataCompletedChunks == nil {
459 for _, have := range t.metadataCompletedChunks {
467 // TODO: Propagate errors to disconnect peer.
468 func (t *Torrent) setMetadataSize(bytes int) (err error) {
470 // We already know the correct metadata size.
473 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
474 return errors.New("bad size")
476 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
479 t.metadataBytes = make([]byte, bytes)
480 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
481 t.metadataChanged.Broadcast()
482 for c := range t.conns {
483 c.requestPendingMetadata()
488 // The current working name for the torrent. Either the name in the info dict,
489 // or a display name given such as by the dn value in a magnet link, or "".
490 func (t *Torrent) name() string {
492 defer t.nameMu.RUnlock()
499 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
500 p := &t.pieces[index]
501 ret.Priority = t.piecePriority(index)
502 ret.Completion = p.completion()
503 if p.queuedForHash() || p.hashing {
506 if !ret.Complete && t.piecePartiallyDownloaded(index) {
512 func (t *Torrent) metadataPieceSize(piece int) int {
513 return metadataPieceSize(len(t.metadataBytes), piece)
516 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
522 d["total_size"] = len(t.metadataBytes)
524 p := bencode.MustMarshal(d)
527 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
528 ExtendedPayload: append(p, data...),
532 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
533 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
534 ret = append(ret, PieceStateRun{
535 PieceState: el.(PieceState),
539 for index := range t.pieces {
540 rle.Append(t.pieceState(pieceIndex(index)), 1)
546 // Produces a small string representing a PieceStateRun.
547 func (psr PieceStateRun) String() (ret string) {
548 ret = fmt.Sprintf("%d", psr.Length)
549 ret += func() string {
550 switch psr.Priority {
551 case PiecePriorityNext:
553 case PiecePriorityNormal:
555 case PiecePriorityReadahead:
557 case PiecePriorityNow:
559 case PiecePriorityHigh:
580 func (t *Torrent) writeStatus(w io.Writer) {
581 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
582 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
584 fmt.Fprintf(w, "Metadata have: ")
585 for _, h := range t.metadataCompletedChunks {
586 fmt.Fprintf(w, "%c", func() rune {
596 fmt.Fprintf(w, "Piece length: %s\n", func() string {
598 return fmt.Sprint(t.usualPieceSize())
604 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
605 fmt.Fprintf(w, "Piece States: %s", t.pieceStateRuns())
608 fmt.Fprintf(w, "Reader Pieces:")
609 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
610 fmt.Fprintf(w, " %d:%d", begin, end)
615 fmt.Fprintf(w, "Enabled trackers:\n")
617 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
618 fmt.Fprintf(tw, " URL\tExtra\n")
619 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
622 var luns, runs url.URL = *lu, *ru
625 var ml missinggo.MultiLess
626 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
627 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
629 }).([]torrentTrackerAnnouncer) {
630 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
635 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
637 spew.NewDefaultConfig()
638 spew.Fdump(w, t.statsLocked())
640 peers := t.peersAsSlice()
641 sort.Slice(peers, func(i, j int) bool {
642 return worseConn(peers[i], peers[j])
644 for i, c := range peers {
645 fmt.Fprintf(w, "%2d. ", i+1)
650 func (t *Torrent) haveInfo() bool {
654 // Returns a run-time generated MetaInfo that includes the info bytes and
655 // announce-list as currently known to the client.
656 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
657 return metainfo.MetaInfo{
658 CreationDate: time.Now().Unix(),
659 Comment: "dynamic metainfo from client",
660 CreatedBy: "go.torrent",
661 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
662 InfoBytes: func() []byte {
664 return t.metadataBytes
672 func (t *Torrent) BytesMissing() int64 {
675 return t.bytesMissingLocked()
678 func (t *Torrent) bytesMissingLocked() int64 {
682 func (t *Torrent) bytesLeft() (left int64) {
683 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
684 p := &t.pieces[piece]
685 left += int64(p.length() - p.numDirtyBytes())
691 // Bytes left to give in tracker announces.
692 func (t *Torrent) bytesLeftAnnounce() int64 {
700 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
701 if t.pieceComplete(piece) {
704 if t.pieceAllDirty(piece) {
707 return t.pieces[piece].hasDirtyChunks()
710 func (t *Torrent) usualPieceSize() int {
711 return int(t.info.PieceLength)
714 func (t *Torrent) numPieces() pieceIndex {
715 return pieceIndex(t.info.NumPieces())
718 func (t *Torrent) numPiecesCompleted() (num int) {
719 return t._completedPieces.Len()
722 func (t *Torrent) close() (err error) {
725 if t.storage != nil {
728 t.storageLock.Unlock()
730 for conn := range t.conns {
734 t.cl.event.Broadcast()
735 t.pieceStateChanges.Close()
736 t.updateWantPeersEvent()
740 func (t *Torrent) requestOffset(r request) int64 {
741 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
744 // Return the request that would include the given offset into the torrent data. Returns !ok if
745 // there is no such request.
746 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
747 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
750 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
751 defer perf.ScopeTimerErr(&err)()
752 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
753 if err == nil && n != len(data) {
754 err = io.ErrShortWrite
759 func (t *Torrent) bitfield() (bf []bool) {
760 bf = make([]bool, t.numPieces())
761 t._completedPieces.IterTyped(func(piece int) (again bool) {
768 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
769 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
772 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
773 t.pieces[pieceIndex]._dirtyChunks.Clear()
776 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
777 if t.info.PieceLength == 0 {
778 // There will be no variance amongst pieces. Only pain.
781 if piece == t.numPieces()-1 {
782 ret := pp.Integer(*t.length % t.info.PieceLength)
787 return pp.Integer(t.info.PieceLength)
790 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, copyErr error) {
791 hash := pieceHash.New()
793 p.waitNoPendingWrites()
794 ip := t.info.Piece(int(piece))
796 _, copyErr = io.CopyN( // Return no error iff pl bytes are copied.
797 hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl), pl)
798 missinggo.CopyExact(&ret, hash.Sum(nil))
802 func (t *Torrent) haveAnyPieces() bool {
803 return t._completedPieces.Len() != 0
806 func (t *Torrent) haveAllPieces() bool {
810 return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
813 func (t *Torrent) havePiece(index pieceIndex) bool {
814 return t.haveInfo() && t.pieceComplete(index)
817 func (t *Torrent) haveChunk(r request) (ret bool) {
819 // log.Println("have chunk", r, ret)
824 if t.pieceComplete(pieceIndex(r.Index)) {
827 p := &t.pieces[r.Index]
828 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
831 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
832 return int(cs.Begin / chunkSize)
835 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
839 if index < 0 || index >= t.numPieces() {
842 p := &t.pieces[index]
843 if p.queuedForHash() {
849 if t.pieceComplete(index) {
852 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
855 // t.logger.Printf("piece %d not pending", index)
856 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
857 return index < begin || index >= end
861 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
862 // connection is one that usually sends us unwanted pieces, or has been in worser half of the
863 // established connections for more than a minute.
864 func (t *Torrent) worstBadConn() *PeerConn {
865 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
868 c := heap.Pop(&wcs).(*PeerConn)
869 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
872 // If the connection is in the worst half of the established
873 // connection quota and is older than a minute.
874 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
875 // Give connections 1 minute to prove themselves.
876 if time.Since(c.completedHandshake) > time.Minute {
884 type PieceStateChange struct {
889 func (t *Torrent) publishPieceChange(piece pieceIndex) {
890 t.cl._mu.Defer(func() {
891 cur := t.pieceState(piece)
892 p := &t.pieces[piece]
893 if cur != p.publicPieceState {
894 p.publicPieceState = cur
895 t.pieceStateChanges.Publish(PieceStateChange{
903 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
904 if t.pieceComplete(piece) {
907 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
910 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
911 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
914 func (t *Torrent) readersChanged() {
915 t.updateReaderPieces()
916 t.updateAllPiecePriorities()
919 func (t *Torrent) updateReaderPieces() {
920 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
923 func (t *Torrent) readerPosChanged(from, to pieceRange) {
927 t.updateReaderPieces()
928 // Order the ranges, high and low.
930 if l.begin > h.begin {
934 // Two distinct ranges.
935 t.updatePiecePriorities(l.begin, l.end)
936 t.updatePiecePriorities(h.begin, h.end)
943 t.updatePiecePriorities(l.begin, end)
947 func (t *Torrent) maybeNewConns() {
948 // Tickle the accept routine.
949 t.cl.event.Broadcast()
953 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
954 // t.logger.Printf("piece %d priority changed", piece)
955 t.iterPeers(func(c *peer) {
956 if c.updatePiecePriority(piece) {
957 // log.Print("conn piece priority changed")
962 t.publishPieceChange(piece)
965 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
966 p := &t.pieces[piece]
967 newPrio := p.uncachedPriority()
968 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
969 if newPrio == PiecePriorityNone {
970 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
974 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
978 t.piecePriorityChanged(piece)
981 func (t *Torrent) updateAllPiecePriorities() {
982 t.updatePiecePriorities(0, t.numPieces())
985 // Update all piece priorities in one hit. This function should have the same
986 // output as updatePiecePriority, but across all pieces.
987 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
988 for i := begin; i < end; i++ {
989 t.updatePiecePriority(i)
993 // Returns the range of pieces [begin, end) that contains the extent of bytes.
994 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
995 if off >= *t.length {
1005 begin = pieceIndex(off / t.info.PieceLength)
1006 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1007 if end > pieceIndex(t.info.NumPieces()) {
1008 end = pieceIndex(t.info.NumPieces())
1013 // Returns true if all iterations complete without breaking. Returns the read
1014 // regions for all readers. The reader regions should not be merged as some
1015 // callers depend on this method to enumerate readers.
1016 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1017 for r := range t.readers {
1019 if p.begin >= p.end {
1022 if !f(p.begin, p.end) {
1029 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1030 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1032 return PiecePriorityNone
1037 ret := piecePriority(-prio)
1038 if ret == PiecePriorityNone {
1044 func (t *Torrent) pendRequest(req request) {
1045 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1046 t.pieces[req.Index].pendChunkIndex(ci)
1049 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1051 t.cl.event.Broadcast()
1052 if t.pieceComplete(piece) {
1053 t.onPieceCompleted(piece)
1055 t.onIncompletePiece(piece)
1057 t.updatePiecePriority(piece)
1060 func (t *Torrent) numReceivedConns() (ret int) {
1061 for c := range t.conns {
1062 if c.Discovery == PeerSourceIncoming {
1069 func (t *Torrent) maxHalfOpen() int {
1070 // Note that if we somehow exceed the maximum established conns, we want
1071 // the negative value to have an effect.
1072 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1073 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1074 // We want to allow some experimentation with new peers, and to try to
1075 // upset an oversupply of received connections.
1076 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1079 func (t *Torrent) openNewConns() {
1080 defer t.updateWantPeersEvent()
1081 for t.peers.Len() != 0 {
1085 if len(t.halfOpen) >= t.maxHalfOpen() {
1088 if len(t.cl.dialers) == 0 {
1091 p := t.peers.PopMax()
1096 func (t *Torrent) getConnPieceInclination() []int {
1097 _ret := t.connPieceInclinationPool.Get()
1099 pieceInclinationsNew.Add(1)
1100 return rand.Perm(int(t.numPieces()))
1102 pieceInclinationsReused.Add(1)
1103 return *_ret.(*[]int)
1106 func (t *Torrent) putPieceInclination(pi []int) {
1107 t.connPieceInclinationPool.Put(&pi)
1108 pieceInclinationsPut.Add(1)
1111 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1113 uncached := t.pieceCompleteUncached(piece)
1114 cached := p.completion()
1115 changed := cached != uncached
1116 complete := uncached.Complete
1117 p.storageCompletionOk = uncached.Ok
1118 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1119 if complete && len(p.dirtiers) != 0 {
1120 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1123 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1124 t.pieceCompletionChanged(piece)
1129 // Non-blocking read. Client lock is not required.
1130 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1131 p := &t.pieces[off/t.info.PieceLength]
1132 p.waitNoPendingWrites()
1133 return p.Storage().ReadAt(b, off-p.Info().Offset())
1136 // Returns an error if the metadata was completed, but couldn't be set for
1137 // some reason. Blame it on the last peer to contribute.
1138 func (t *Torrent) maybeCompleteMetadata() error {
1143 if !t.haveAllMetadataPieces() {
1144 // Don't have enough metadata pieces.
1147 err := t.setInfoBytes(t.metadataBytes)
1149 t.invalidateMetadata()
1150 return fmt.Errorf("error setting info bytes: %s", err)
1152 if t.cl.config.Debug {
1153 t.logger.Printf("%s: got metadata from peers", t)
1158 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1159 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1161 now.Add(bitmap.BitIndex(begin))
1162 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1169 func (t *Torrent) needData() bool {
1170 if t.closed.IsSet() {
1176 return t._pendingPieces.Len() != 0
1179 func appendMissingStrings(old, new []string) (ret []string) {
1182 for _, n := range new {
1183 for _, o := range old {
1188 ret = append(ret, n)
1193 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1195 for minNumTiers > len(ret) {
1196 ret = append(ret, nil)
1201 func (t *Torrent) addTrackers(announceList [][]string) {
1202 fullAnnounceList := &t.metainfo.AnnounceList
1203 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1204 for tierIndex, trackerURLs := range announceList {
1205 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1207 t.startMissingTrackerScrapers()
1208 t.updateWantPeersEvent()
1211 // Don't call this before the info is available.
1212 func (t *Torrent) bytesCompleted() int64 {
1216 return t.info.TotalLength() - t.bytesLeft()
1219 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1222 return t.setInfoBytes(b)
1225 // Returns true if connection is removed from torrent.Conns.
1226 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1227 if !c.closed.IsSet() {
1228 panic("connection is not closed")
1229 // There are behaviours prevented by the closed state that will fail
1230 // if the connection has been deleted.
1234 if !t.cl.config.DisablePEX {
1237 torrent.Add("deleted connections", 1)
1238 c.deleteAllRequests()
1239 if t.numActivePeers() == 0 {
1240 t.assertNoPendingRequests()
1245 func (t *Torrent) numActivePeers() (num int) {
1246 t.iterPeers(func(*peer) {
1252 func (t *Torrent) assertNoPendingRequests() {
1253 if len(t.pendingRequests) != 0 {
1254 panic(t.pendingRequests)
1256 //if len(t.lastRequested) != 0 {
1257 // panic(t.lastRequested)
1261 func (t *Torrent) dropConnection(c *PeerConn) {
1262 t.cl.event.Broadcast()
1264 if t.deleteConnection(c) {
1269 func (t *Torrent) wantPeers() bool {
1270 if t.closed.IsSet() {
1273 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1276 return t.needData() || t.seeding()
1279 func (t *Torrent) updateWantPeersEvent() {
1281 t.wantPeersEvent.Set()
1283 t.wantPeersEvent.Clear()
1287 // Returns whether the client should make effort to seed the torrent.
1288 func (t *Torrent) seeding() bool {
1290 if t.closed.IsSet() {
1293 if cl.config.NoUpload {
1296 if !cl.config.Seed {
1299 if cl.config.DisableAggressiveUpload && t.needData() {
1305 func (t *Torrent) onWebRtcConn(
1306 c datachannel.ReadWriteCloser,
1307 dcc webtorrent.DataChannelContext,
1310 pc, err := t.cl.initiateProtocolHandshakes(
1311 context.Background(),
1312 webrtcNetConn{c, dcc},
1316 webrtcNetAddr{dcc.Remote},
1318 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1321 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1324 if dcc.LocalOffered {
1325 pc.Discovery = PeerSourceTracker
1327 pc.Discovery = PeerSourceIncoming
1331 err = t.cl.runHandshookConn(pc, t)
1333 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1337 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1338 err := t.cl.runHandshookConn(pc, t)
1339 if err != nil || logAll {
1340 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1344 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1345 t.logRunHandshookConn(pc, false, log.Debug)
1348 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1349 wtc, release := t.cl.websocketTrackers.Get(u.String())
1351 <-t.closed.LockedChan(t.cl.locker())
1354 wst := websocketTrackerStatus{u, wtc}
1356 err := wtc.Announce(tracker.Started, t.infoHash)
1358 t.logger.WithDefaultLevel(log.Warning).Printf(
1359 "error in initial announce to %q: %v",
1368 func (t *Torrent) startScrapingTracker(_url string) {
1372 u, err := url.Parse(_url)
1374 // URLs with a leading '*' appear to be a uTorrent convention to
1375 // disable trackers.
1377 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1381 if u.Scheme == "udp" {
1383 t.startScrapingTracker(u.String())
1385 t.startScrapingTracker(u.String())
1388 if _, ok := t.trackerAnnouncers[_url]; ok {
1391 sl := func() torrentTrackerAnnouncer {
1394 if t.cl.config.DisableWebtorrent {
1397 return t.startWebsocketAnnouncer(*u)
1399 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1402 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1405 newAnnouncer := &trackerScraper{
1409 go newAnnouncer.Run()
1415 if t.trackerAnnouncers == nil {
1416 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1418 t.trackerAnnouncers[_url] = sl
1421 // Adds and starts tracker scrapers for tracker URLs that aren't already
1423 func (t *Torrent) startMissingTrackerScrapers() {
1424 if t.cl.config.DisableTrackers {
1427 t.startScrapingTracker(t.metainfo.Announce)
1428 for _, tier := range t.metainfo.AnnounceList {
1429 for _, url := range tier {
1430 t.startScrapingTracker(url)
1435 // Returns an AnnounceRequest with fields filled out to defaults and current
1437 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1438 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1439 // dependent on the network in use.
1440 return tracker.AnnounceRequest{
1442 NumWant: func() int32 {
1443 if t.wantPeers() && len(t.cl.dialers) > 0 {
1449 Port: uint16(t.cl.incomingPeerPort()),
1450 PeerId: t.cl.peerID,
1451 InfoHash: t.infoHash,
1452 Key: t.cl.announceKey(),
1454 // The following are vaguely described in BEP 3.
1456 Left: t.bytesLeftAnnounce(),
1457 Uploaded: t.stats.BytesWrittenData.Int64(),
1458 // There's no mention of wasted or unwanted download in the BEP.
1459 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1463 // Adds peers revealed in an announce until the announce ends, or we have
1465 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1467 for v := range pvs {
1469 for _, cp := range v.Peers {
1471 // Can't do anything with this.
1475 Addr: ipPortAddr{cp.IP, cp.Port},
1476 Source: PeerSourceDhtGetPeers,
1483 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1484 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1488 go t.consumeDhtAnnouncePeers(ps.Peers())
1490 case <-t.closed.LockedChan(t.cl.locker()):
1491 case <-time.After(5 * time.Minute):
1497 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1503 if t.closed.IsSet() {
1509 // TODO: Determine if there's a listener on the port we're announcing.
1510 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1521 err := t.announceToDht(true, s)
1523 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1529 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1530 for _, p := range peers {
1538 // The returned TorrentStats may require alignment in memory. See
1539 // https://github.com/anacrolix/torrent/issues/383.
1540 func (t *Torrent) Stats() TorrentStats {
1542 defer t.cl.rUnlock()
1543 return t.statsLocked()
1546 func (t *Torrent) statsLocked() (ret TorrentStats) {
1547 ret.ActivePeers = len(t.conns)
1548 ret.HalfOpenPeers = len(t.halfOpen)
1549 ret.PendingPeers = t.peers.Len()
1550 ret.TotalPeers = t.numTotalPeers()
1551 ret.ConnectedSeeders = 0
1552 for c := range t.conns {
1553 if all, ok := c.peerHasAllPieces(); all && ok {
1554 ret.ConnectedSeeders++
1557 ret.ConnStats = t.stats.Copy()
1561 // The total number of peers in the torrent.
1562 func (t *Torrent) numTotalPeers() int {
1563 peers := make(map[string]struct{})
1564 for conn := range t.conns {
1565 ra := conn.conn.RemoteAddr()
1567 // It's been closed and doesn't support RemoteAddr.
1570 peers[ra.String()] = struct{}{}
1572 for addr := range t.halfOpen {
1573 peers[addr] = struct{}{}
1575 t.peers.Each(func(peer PeerInfo) {
1576 peers[peer.Addr.String()] = struct{}{}
1581 // Reconcile bytes transferred before connection was associated with a
1583 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1584 if c._stats != (ConnStats{
1585 // Handshakes should only increment these fields:
1586 BytesWritten: c._stats.BytesWritten,
1587 BytesRead: c._stats.BytesRead,
1591 c.postHandshakeStats(func(cs *ConnStats) {
1592 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1593 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1595 c.reconciledHandshakeStats = true
1598 // Returns true if the connection is added.
1599 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1602 torrent.Add("added connections", 1)
1605 if t.closed.IsSet() {
1606 return errors.New("torrent closed")
1608 for c0 := range t.conns {
1609 if c.PeerID != c0.PeerID {
1612 if !t.cl.config.DropDuplicatePeerIds {
1615 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1617 t.deleteConnection(c0)
1619 return errors.New("existing connection preferred")
1622 if len(t.conns) >= t.maxEstablishedConns {
1623 c := t.worstBadConn()
1625 return errors.New("don't want conns")
1628 t.deleteConnection(c)
1630 if len(t.conns) >= t.maxEstablishedConns {
1633 t.conns[c] = struct{}{}
1634 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1635 t.pex.Add(c) // as no further extended handshake expected
1640 func (t *Torrent) wantConns() bool {
1641 if !t.networkingEnabled {
1644 if t.closed.IsSet() {
1647 if !t.seeding() && !t.needData() {
1650 if len(t.conns) < t.maxEstablishedConns {
1653 return t.worstBadConn() != nil
1656 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1659 oldMax = t.maxEstablishedConns
1660 t.maxEstablishedConns = max
1661 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1662 return worseConn(&l.peer, &r.peer)
1664 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1665 t.dropConnection(wcs.Pop().(*PeerConn))
1671 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1672 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1675 t.cl.event.Broadcast()
1676 if t.closed.IsSet() {
1680 // Don't score the first time a piece is hashed, it could be an initial check.
1681 if p.storageCompletionOk {
1683 pieceHashedCorrect.Add(1)
1685 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1686 pieceHashedNotCorrect.Add(1)
1691 if len(p.dirtiers) != 0 {
1692 // Don't increment stats above connection-level for every involved connection.
1693 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1695 for c := range p.dirtiers {
1696 c._stats.incrementPiecesDirtiedGood()
1698 t.clearPieceTouchers(piece)
1699 err := p.Storage().MarkComplete()
1701 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1703 t.pendAllChunkSpecs(piece)
1705 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1706 // Peers contributed to all the data for this piece hash failure, and the failure was
1707 // not due to errors in the storage (such as data being dropped in a cache).
1709 // Increment Torrent and above stats, and then specific connections.
1710 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1711 for c := range p.dirtiers {
1712 // Y u do dis peer?!
1713 c.stats().incrementPiecesDirtiedBad()
1716 bannableTouchers := make([]*peer, 0, len(p.dirtiers))
1717 for c := range p.dirtiers {
1719 bannableTouchers = append(bannableTouchers, c)
1722 t.clearPieceTouchers(piece)
1723 slices.Sort(bannableTouchers, connLessTrusted)
1725 if t.cl.config.Debug {
1727 "bannable conns by trust for piece %d: %v",
1729 func() (ret []connectionTrust) {
1730 for _, c := range bannableTouchers {
1731 ret = append(ret, c.trust())
1738 if len(bannableTouchers) >= 1 {
1739 c := bannableTouchers[0]
1740 t.cl.banPeerIP(c.remoteIp())
1744 t.onIncompletePiece(piece)
1745 p.Storage().MarkNotComplete()
1747 t.updatePieceCompletion(piece)
1750 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1751 // TODO: Make faster
1752 for cn := range t.conns {
1757 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1758 t.pendAllChunkSpecs(piece)
1759 t.cancelRequestsForPiece(piece)
1760 for conn := range t.conns {
1765 // Called when a piece is found to be not complete.
1766 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1767 if t.pieceAllDirty(piece) {
1768 t.pendAllChunkSpecs(piece)
1770 if !t.wantPieceIndex(piece) {
1771 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1774 // We could drop any connections that we told we have a piece that we
1775 // don't here. But there's a test failure, and it seems clients don't care
1776 // if you request pieces that you already claim to have. Pruning bad
1777 // connections might just remove any connections that aren't treating us
1778 // favourably anyway.
1780 // for c := range t.conns {
1781 // if c.sentHave(piece) {
1785 t.iterPeers(func(conn *peer) {
1786 if conn.peerHasPiece(piece) {
1787 conn.UpdateRequests()
1792 func (t *Torrent) tryCreateMorePieceHashers() {
1793 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1797 func (t *Torrent) tryCreatePieceHasher() bool {
1798 if t.storage == nil {
1801 pi, ok := t.getPieceToHash()
1806 t.piecesQueuedForHash.Remove(pi)
1808 t.publishPieceChange(pi)
1809 t.updatePiecePriority(pi)
1810 t.storageLock.RLock()
1811 t.activePieceHashes++
1812 go t.pieceHasher(pi)
1816 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1817 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1818 if t.piece(i).hashing {
1828 func (t *Torrent) pieceHasher(index pieceIndex) {
1830 sum, copyErr := t.hashPiece(index)
1831 correct := sum == *p.hash
1835 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1837 t.storageLock.RUnlock()
1841 t.updatePiecePriority(index)
1842 t.pieceHashed(index, correct, copyErr)
1843 t.publishPieceChange(index)
1844 t.activePieceHashes--
1845 t.tryCreateMorePieceHashers()
1848 // Return the connections that touched a piece, and clear the entries while doing it.
1849 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1851 for c := range p.dirtiers {
1852 delete(c.peerTouchedPieces, pi)
1853 delete(p.dirtiers, c)
1857 func (t *Torrent) peersAsSlice() (ret []*peer) {
1858 t.iterPeers(func(p *peer) {
1859 ret = append(ret, p)
1864 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1865 piece := t.piece(pieceIndex)
1866 if piece.queuedForHash() {
1869 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1870 t.publishPieceChange(pieceIndex)
1871 t.updatePiecePriority(pieceIndex)
1872 t.tryCreateMorePieceHashers()
1875 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1876 // before the Info is available.
1877 func (t *Torrent) VerifyData() {
1878 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1879 t.Piece(i).VerifyData()
1883 // Start the process of connecting to the given peer for the given torrent if appropriate.
1884 func (t *Torrent) initiateConn(peer PeerInfo) {
1885 if peer.Id == t.cl.peerID {
1889 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1893 if t.addrActive(addr.String()) {
1896 t.halfOpen[addr.String()] = peer
1897 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1900 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1901 // quickly make one Client visible to the Torrent of another Client.
1902 func (t *Torrent) AddClientPeer(cl *Client) int {
1903 return t.AddPeers(func() (ps []PeerInfo) {
1904 for _, la := range cl.ListenAddrs() {
1905 ps = append(ps, PeerInfo{
1914 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1916 func (t *Torrent) allStats(f func(*ConnStats)) {
1921 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1922 return t.pieces[i].hashing
1925 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1926 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1929 func (t *Torrent) dialTimeout() time.Duration {
1930 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1933 func (t *Torrent) piece(i int) *Piece {
1937 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1941 type torrentRequestStrategyCallbacks struct {
1945 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
1946 torrent.Add("request timeouts", 1)
1948 defer cb.t.cl.unlock()
1949 cb.t.iterPeers(func(cn *peer) {
1950 if cn.peerHasPiece(pieceIndex(r.Index)) {
1957 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
1958 return torrentRequestStrategyCallbacks{t}
1961 func (t *Torrent) onWriteChunkErr(err error) {
1962 if t.userOnWriteChunkErr != nil {
1963 go t.userOnWriteChunkErr(err)
1966 t.disallowDataDownloadLocked()
1969 func (t *Torrent) DisallowDataDownload() {
1972 t.disallowDataDownloadLocked()
1975 func (t *Torrent) disallowDataDownloadLocked() {
1976 log.Printf("disallowing data download")
1977 t.dataDownloadDisallowed = true
1978 t.iterPeers(func(c *peer) {
1983 func (t *Torrent) AllowDataDownload() {
1986 log.Printf("AllowDataDownload")
1987 t.dataDownloadDisallowed = false
1988 t.iterPeers(func(c *peer) {
1993 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
1996 t.userOnWriteChunkErr = f
1999 func (t *Torrent) iterPeers(f func(*peer)) {
2000 for pc := range t.conns {
2003 for _, ws := range t.webSeeds {
2008 func (t *Torrent) addWebSeed(url string) {
2009 if _, ok := t.webSeeds[url]; ok {
2018 reconciledHandshakeStats: true,
2019 peerSentHaveAll: true,
2020 PeerMaxRequests: 10,
2022 client: webseed.Client{
2023 HttpClient: http.DefaultClient,
2025 FileIndex: t.fileIndex,
2027 Events: make(chan webseed.ClientEvent),
2030 go ws.eventProcessor()
2031 ws.peer.PeerImpl = &ws
2032 t.webSeeds[url] = &ws.peer
2035 func (t *Torrent) peerIsActive(p *peer) (active bool) {
2036 t.iterPeers(func(p1 *peer) {