20 "github.com/anacrolix/torrent/common"
21 "github.com/anacrolix/torrent/segments"
22 "github.com/anacrolix/torrent/webseed"
23 "github.com/davecgh/go-spew/spew"
24 "github.com/pion/datachannel"
26 "github.com/anacrolix/dht/v2"
27 "github.com/anacrolix/log"
28 "github.com/anacrolix/missinggo"
29 "github.com/anacrolix/missinggo/iter"
30 "github.com/anacrolix/missinggo/perf"
31 "github.com/anacrolix/missinggo/pubsub"
32 "github.com/anacrolix/missinggo/slices"
33 "github.com/anacrolix/missinggo/v2/bitmap"
34 "github.com/anacrolix/missinggo/v2/prioritybitmap"
36 "github.com/anacrolix/torrent/bencode"
37 "github.com/anacrolix/torrent/metainfo"
38 pp "github.com/anacrolix/torrent/peer_protocol"
39 "github.com/anacrolix/torrent/storage"
40 "github.com/anacrolix/torrent/tracker"
41 "github.com/anacrolix/torrent/webtorrent"
44 // Maintains state of torrent within a Client. Many methods should not be called before the info is
45 // available, see .Info and .GotInfo.
47 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
48 // alignment. See #262.
53 networkingEnabled bool
54 dataDownloadDisallowed bool
55 dataUploadDisallowed bool
56 userOnWriteChunkErr func(error)
58 // Determines what chunks to request from peers.
59 requestStrategy requestStrategy
61 closed missinggo.Event
62 infoHash metainfo.Hash
64 // Values are the piece indices that changed.
65 pieceStateChanges *pubsub.PubSub
66 // The size of chunks to request from peers over the wire. This is
67 // normally 16KiB by convention these days.
70 // Total length of the torrent in bytes. Stored because it's not O(1) to
71 // get this from the info dict.
74 // The storage to open when the info dict becomes available.
75 storageOpener *storage.Client
76 // Storage for torrent data.
77 storage *storage.Torrent
78 // Read-locked for using storage, and write-locked for Closing.
79 storageLock sync.RWMutex
81 // TODO: Only announce stuff is used?
82 metainfo metainfo.MetaInfo
84 // The info dict. nil if we don't have it (yet).
86 fileIndex segments.Index
89 webSeeds map[string]*Peer
91 // Active peer connections, running message stream loops. TODO: Make this
92 // open (not-closed) connections only.
93 conns map[*PeerConn]struct{}
94 maxEstablishedConns int
95 // Set of addrs to which we're attempting to connect. Connections are
96 // half-open until all handshakes are completed.
97 halfOpen map[string]PeerInfo
100 // Reserve of peers to connect to. A peer can be both here and in the
101 // active connections if were told about the peer after connecting with
102 // them. That encourages us to reconnect to peers that are well known in
104 peers prioritizedPeers
105 // Whether we want to know to know more peers.
106 wantPeersEvent missinggo.Event
107 // An announcer for each tracker URL.
108 trackerAnnouncers map[string]torrentTrackerAnnouncer
109 // How many times we've initiated a DHT announce. TODO: Move into stats.
112 // Name used if the info name isn't available. Should be cleared when the
113 // Info does become available.
117 // The bencoded bytes of the info dict. This is actively manipulated if
118 // the info bytes aren't initially available, and we try to fetch them
121 // Each element corresponds to the 16KiB metadata pieces. If true, we have
122 // received that piece.
123 metadataCompletedChunks []bool
124 metadataChanged sync.Cond
126 // Set when .Info is obtained.
127 gotMetainfo missinggo.Event
129 readers map[*reader]struct{}
130 _readerNowPieces bitmap.Bitmap
131 _readerReadaheadPieces bitmap.Bitmap
133 // A cache of pieces we need to get. Calculated from various piece and
134 // file priorities and completion states elsewhere.
135 _pendingPieces prioritybitmap.PriorityBitmap
136 // A cache of completed piece indices.
137 _completedPieces bitmap.Bitmap
138 // Pieces that need to be hashed.
139 piecesQueuedForHash bitmap.Bitmap
140 activePieceHashes int
142 // A pool of piece priorities []int for assignment to new connections.
143 // These "inclinations" are used to give connections preference for
145 connPieceInclinationPool sync.Pool
147 // Count of each request across active connections.
148 pendingRequests map[Request]int
153 func (t *Torrent) numConns() int {
157 func (t *Torrent) numReaders() int {
158 return len(t.readers)
161 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
162 return t._readerNowPieces
165 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
166 return t._readerReadaheadPieces
169 func (t *Torrent) ignorePieces() bitmap.Bitmap {
170 ret := t._completedPieces.Copy()
171 ret.Union(t.piecesQueuedForHash)
172 for i := 0; i < t.numPieces(); i++ {
173 if t.piece(i).hashing {
180 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
181 return &t._pendingPieces
184 func (t *Torrent) tickleReaders() {
185 t.cl.event.Broadcast()
188 // Returns a channel that is closed when the Torrent is closed.
189 func (t *Torrent) Closed() <-chan struct{} {
190 return t.closed.LockedChan(t.cl.locker())
193 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
194 // pending, and half-open peers.
195 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
196 // Add pending peers to the list
197 t.peers.Each(func(peer PeerInfo) {
198 ks = append(ks, peer)
201 // Add half-open peers to the list
202 for _, peer := range t.halfOpen {
203 ks = append(ks, peer)
206 // Add active peers to the list
207 for conn := range t.conns {
209 ks = append(ks, PeerInfo{
211 Addr: conn.RemoteAddr,
212 Source: conn.Discovery,
213 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
214 // > But if we're not connected to them with an encrypted connection, I couldn't say
215 // > what's appropriate. We can carry forward the SupportsEncryption value as we
216 // > received it from trackers/DHT/PEX, or just use the encryption state for the
217 // > connection. It's probably easiest to do the latter for now.
218 // https://github.com/anacrolix/torrent/pull/188
219 SupportsEncryption: conn.headerEncrypted,
226 func (t *Torrent) setChunkSize(size pp.Integer) {
228 t.chunkPool = &sync.Pool{
229 New: func() interface{} {
230 b := make([]byte, size)
236 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
237 return t._completedPieces.Get(bitmap.BitIndex(piece))
240 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
241 return t.pieces[piece].Storage().Completion()
244 // There's a connection to that address already.
245 func (t *Torrent) addrActive(addr string) bool {
246 if _, ok := t.halfOpen[addr]; ok {
249 for c := range t.conns {
251 if ra.String() == addr {
258 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
259 ret = make([]*PeerConn, 0, len(t.conns))
260 for c := range t.conns {
261 if !c.closed.IsSet() {
268 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
270 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
271 if t.closed.IsSet() {
274 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
275 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
276 torrent.Add("peers not added because of bad addr", 1)
277 // cl.logger.Printf("peers not added because of bad addr: %v", p)
281 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
282 torrent.Add("peers replaced", 1)
283 if !replaced.equal(p) {
284 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
291 for t.peers.Len() > cl.config.TorrentPeersHighWater {
292 _, ok := t.peers.DeleteMin()
294 torrent.Add("excess reserve peers discarded", 1)
300 func (t *Torrent) invalidateMetadata() {
301 for i := range t.metadataCompletedChunks {
302 t.metadataCompletedChunks[i] = false
309 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
313 if index >= len(t.metadataCompletedChunks) {
314 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
317 copy(t.metadataBytes[(1<<14)*index:], data)
318 t.metadataCompletedChunks[index] = true
321 func (t *Torrent) metadataPieceCount() int {
322 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
325 func (t *Torrent) haveMetadataPiece(piece int) bool {
327 return (1<<14)*piece < len(t.metadataBytes)
329 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
333 func (t *Torrent) metadataSize() int {
334 return len(t.metadataBytes)
337 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
338 for i := 0; i < len(info.Pieces); i += sha1.Size {
339 ret = append(ret, info.Pieces[i:i+sha1.Size])
344 func (t *Torrent) makePieces() {
345 hashes := infoPieceHashes(t.info)
346 t.pieces = make([]Piece, len(hashes))
347 for i, hash := range hashes {
348 piece := &t.pieces[i]
350 piece.index = pieceIndex(i)
351 piece.noPendingWrites.L = &piece.pendingWritesMutex
352 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
354 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
355 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
356 piece.files = files[beginFile:endFile]
360 // Returns the index of the first file containing the piece. files must be
361 // ordered by offset.
362 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
363 for i, f := range files {
364 if f.offset+f.length > pieceOffset {
371 // Returns the index after the last file containing the piece. files must be
372 // ordered by offset.
373 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
374 for i, f := range files {
375 if f.offset+f.length >= pieceEndOffset {
382 func (t *Torrent) cacheLength() {
384 for _, f := range t.info.UpvertedFiles() {
390 func (t *Torrent) setInfo(info *metainfo.Info) error {
391 if err := validateInfo(info); err != nil {
392 return fmt.Errorf("bad info: %s", err)
394 if t.storageOpener != nil {
396 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
398 return fmt.Errorf("error opening torrent storage: %s", err)
404 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
405 t.displayName = "" // Save a few bytes lol.
412 // This seems to be all the follow-up tasks after info is set, that can't fail.
413 func (t *Torrent) onSetInfo() {
414 t.iterPeers(func(p *Peer) {
417 for i := range t.pieces {
418 t.updatePieceCompletion(pieceIndex(i))
420 if !p.storageCompletionOk {
421 // t.logger.Printf("piece %s completion unknown, queueing check", p)
422 t.queuePieceCheck(pieceIndex(i))
425 t.cl.event.Broadcast()
427 t.updateWantPeersEvent()
428 t.pendingRequests = make(map[Request]int)
429 t.tryCreateMorePieceHashers()
432 // Called when metadata for a torrent becomes available.
433 func (t *Torrent) setInfoBytes(b []byte) error {
434 if metainfo.HashBytes(b) != t.infoHash {
435 return errors.New("info bytes have wrong hash")
437 var info metainfo.Info
438 if err := bencode.Unmarshal(b, &info); err != nil {
439 return fmt.Errorf("error unmarshalling info bytes: %s", err)
442 t.metadataCompletedChunks = nil
446 if err := t.setInfo(&info); err != nil {
453 func (t *Torrent) haveAllMetadataPieces() bool {
457 if t.metadataCompletedChunks == nil {
460 for _, have := range t.metadataCompletedChunks {
468 // TODO: Propagate errors to disconnect peer.
469 func (t *Torrent) setMetadataSize(bytes int) (err error) {
471 // We already know the correct metadata size.
474 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
475 return errors.New("bad size")
477 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
480 t.metadataBytes = make([]byte, bytes)
481 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
482 t.metadataChanged.Broadcast()
483 for c := range t.conns {
484 c.requestPendingMetadata()
489 // The current working name for the torrent. Either the name in the info dict,
490 // or a display name given such as by the dn value in a magnet link, or "".
491 func (t *Torrent) name() string {
493 defer t.nameMu.RUnlock()
497 if t.displayName != "" {
500 return "infohash:" + t.infoHash.HexString()
503 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
504 p := &t.pieces[index]
505 ret.Priority = t.piecePriority(index)
506 ret.Completion = p.completion()
507 ret.QueuedForHash = p.queuedForHash()
508 ret.Hashing = p.hashing
509 ret.Checking = ret.QueuedForHash || ret.Hashing
510 ret.Marking = p.marking
511 if !ret.Complete && t.piecePartiallyDownloaded(index) {
517 func (t *Torrent) metadataPieceSize(piece int) int {
518 return metadataPieceSize(len(t.metadataBytes), piece)
521 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
527 d["total_size"] = len(t.metadataBytes)
529 p := bencode.MustMarshal(d)
532 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
533 ExtendedPayload: append(p, data...),
537 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
538 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
539 ret = append(ret, PieceStateRun{
540 PieceState: el.(PieceState),
544 for index := range t.pieces {
545 rle.Append(t.pieceState(pieceIndex(index)), 1)
551 // Produces a small string representing a PieceStateRun.
552 func (psr PieceStateRun) String() (ret string) {
553 ret = fmt.Sprintf("%d", psr.Length)
554 ret += func() string {
555 switch psr.Priority {
556 case PiecePriorityNext:
558 case PiecePriorityNormal:
560 case PiecePriorityReadahead:
562 case PiecePriorityNow:
564 case PiecePriorityHigh:
573 if psr.QueuedForHash {
591 func (t *Torrent) writeStatus(w io.Writer) {
592 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
593 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
595 fmt.Fprintf(w, "Metadata have: ")
596 for _, h := range t.metadataCompletedChunks {
597 fmt.Fprintf(w, "%c", func() rune {
607 fmt.Fprintf(w, "Piece length: %s\n", func() string {
609 return fmt.Sprint(t.usualPieceSize())
615 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
616 fmt.Fprintf(w, "Piece States: %s", t.pieceStateRuns())
619 fmt.Fprintf(w, "Reader Pieces:")
620 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
621 fmt.Fprintf(w, " %d:%d", begin, end)
626 fmt.Fprintf(w, "Enabled trackers:\n")
628 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
629 fmt.Fprintf(tw, " URL\tExtra\n")
630 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
633 var luns, runs url.URL = *lu, *ru
636 var ml missinggo.MultiLess
637 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
638 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
640 }).([]torrentTrackerAnnouncer) {
641 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
646 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
648 spew.NewDefaultConfig()
649 spew.Fdump(w, t.statsLocked())
651 peers := t.peersAsSlice()
652 sort.Slice(peers, func(i, j int) bool {
653 return worseConn(peers[i], peers[j])
655 for i, c := range peers {
656 fmt.Fprintf(w, "%2d. ", i+1)
661 func (t *Torrent) haveInfo() bool {
665 // Returns a run-time generated MetaInfo that includes the info bytes and
666 // announce-list as currently known to the client.
667 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
668 return metainfo.MetaInfo{
669 CreationDate: time.Now().Unix(),
670 Comment: "dynamic metainfo from client",
671 CreatedBy: "go.torrent",
672 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
673 InfoBytes: func() []byte {
675 return t.metadataBytes
680 UrlList: func() []string {
681 ret := make([]string, 0, len(t.webSeeds))
682 for url := range t.webSeeds {
683 ret = append(ret, url)
690 func (t *Torrent) BytesMissing() int64 {
693 return t.bytesMissingLocked()
696 func (t *Torrent) bytesMissingLocked() int64 {
700 func (t *Torrent) bytesLeft() (left int64) {
701 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
702 p := &t.pieces[piece]
703 left += int64(p.length() - p.numDirtyBytes())
709 // Bytes left to give in tracker announces.
710 func (t *Torrent) bytesLeftAnnounce() int64 {
718 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
719 if t.pieceComplete(piece) {
722 if t.pieceAllDirty(piece) {
725 return t.pieces[piece].hasDirtyChunks()
728 func (t *Torrent) usualPieceSize() int {
729 return int(t.info.PieceLength)
732 func (t *Torrent) numPieces() pieceIndex {
733 return pieceIndex(t.info.NumPieces())
736 func (t *Torrent) numPiecesCompleted() (num int) {
737 return t._completedPieces.Len()
740 func (t *Torrent) close() (err error) {
743 if t.storage != nil {
746 t.storageLock.Unlock()
748 t.iterPeers(func(p *Peer) {
752 t.cl.event.Broadcast()
753 t.pieceStateChanges.Close()
754 t.updateWantPeersEvent()
758 func (t *Torrent) requestOffset(r Request) int64 {
759 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
762 // Return the request that would include the given offset into the torrent data. Returns !ok if
763 // there is no such request.
764 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
765 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
768 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
769 defer perf.ScopeTimerErr(&err)()
770 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
771 if err == nil && n != len(data) {
772 err = io.ErrShortWrite
777 func (t *Torrent) bitfield() (bf []bool) {
778 bf = make([]bool, t.numPieces())
779 t._completedPieces.IterTyped(func(piece int) (again bool) {
786 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
787 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
790 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
791 t.pieces[pieceIndex]._dirtyChunks.Clear()
794 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
795 if t.info.PieceLength == 0 {
796 // There will be no variance amongst pieces. Only pain.
799 if piece == t.numPieces()-1 {
800 ret := pp.Integer(*t.length % t.info.PieceLength)
805 return pp.Integer(t.info.PieceLength)
808 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
809 hash := pieceHash.New()
811 p.waitNoPendingWrites()
812 storagePiece := t.pieces[piece].Storage()
813 const logPieceContents = false
814 if logPieceContents {
815 var examineBuf bytes.Buffer
816 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
817 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
819 _, err = storagePiece.WriteTo(hash)
821 missinggo.CopyExact(&ret, hash.Sum(nil))
825 func (t *Torrent) haveAnyPieces() bool {
826 return t._completedPieces.Len() != 0
829 func (t *Torrent) haveAllPieces() bool {
833 return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
836 func (t *Torrent) havePiece(index pieceIndex) bool {
837 return t.haveInfo() && t.pieceComplete(index)
840 func (t *Torrent) maybeDropMutuallyCompletePeer(
841 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's okay?
844 if !t.cl.config.DropMutuallyCompletePeers {
847 if !t.haveAllPieces() {
850 if all, known := p.peerHasAllPieces(); !(known && all) {
856 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
860 func (t *Torrent) haveChunk(r Request) (ret bool) {
862 // log.Println("have chunk", r, ret)
867 if t.pieceComplete(pieceIndex(r.Index)) {
870 p := &t.pieces[r.Index]
871 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
874 func chunkIndex(cs ChunkSpec, chunkSize pp.Integer) int {
875 return int(cs.Begin / chunkSize)
878 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
882 if index < 0 || index >= t.numPieces() {
885 p := &t.pieces[index]
886 if p.queuedForHash() {
892 if t.pieceComplete(index) {
895 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
898 // t.logger.Printf("piece %d not pending", index)
899 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
900 return index < begin || index >= end
904 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
905 // connection is one that usually sends us unwanted pieces, or has been in worser half of the
906 // established connections for more than a minute.
907 func (t *Torrent) worstBadConn() *PeerConn {
908 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
911 c := heap.Pop(&wcs).(*PeerConn)
912 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
915 // If the connection is in the worst half of the established
916 // connection quota and is older than a minute.
917 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
918 // Give connections 1 minute to prove themselves.
919 if time.Since(c.completedHandshake) > time.Minute {
927 type PieceStateChange struct {
932 func (t *Torrent) publishPieceChange(piece pieceIndex) {
933 t.cl._mu.Defer(func() {
934 cur := t.pieceState(piece)
935 p := &t.pieces[piece]
936 if cur != p.publicPieceState {
937 p.publicPieceState = cur
938 t.pieceStateChanges.Publish(PieceStateChange{
946 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
947 if t.pieceComplete(piece) {
950 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
953 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
954 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
957 func (t *Torrent) readersChanged() {
958 t.updateReaderPieces()
959 t.updateAllPiecePriorities()
962 func (t *Torrent) updateReaderPieces() {
963 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
966 func (t *Torrent) readerPosChanged(from, to pieceRange) {
970 t.updateReaderPieces()
971 // Order the ranges, high and low.
973 if l.begin > h.begin {
977 // Two distinct ranges.
978 t.updatePiecePriorities(l.begin, l.end)
979 t.updatePiecePriorities(h.begin, h.end)
986 t.updatePiecePriorities(l.begin, end)
990 func (t *Torrent) maybeNewConns() {
991 // Tickle the accept routine.
992 t.cl.event.Broadcast()
996 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
997 // t.logger.Printf("piece %d priority changed", piece)
998 t.iterPeers(func(c *Peer) {
999 if c.updatePiecePriority(piece) {
1000 // log.Print("conn piece priority changed")
1005 t.publishPieceChange(piece)
1008 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
1009 p := &t.pieces[piece]
1010 newPrio := p.uncachedPriority()
1011 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1012 if newPrio == PiecePriorityNone {
1013 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
1017 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
1021 t.piecePriorityChanged(piece)
1024 func (t *Torrent) updateAllPiecePriorities() {
1025 t.updatePiecePriorities(0, t.numPieces())
1028 // Update all piece priorities in one hit. This function should have the same
1029 // output as updatePiecePriority, but across all pieces.
1030 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
1031 for i := begin; i < end; i++ {
1032 t.updatePiecePriority(i)
1036 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1037 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1038 if off >= *t.length {
1048 begin = pieceIndex(off / t.info.PieceLength)
1049 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1050 if end > pieceIndex(t.info.NumPieces()) {
1051 end = pieceIndex(t.info.NumPieces())
1056 // Returns true if all iterations complete without breaking. Returns the read
1057 // regions for all readers. The reader regions should not be merged as some
1058 // callers depend on this method to enumerate readers.
1059 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1060 for r := range t.readers {
1062 if p.begin >= p.end {
1065 if !f(p.begin, p.end) {
1072 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1073 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1075 return PiecePriorityNone
1080 ret := piecePriority(-prio)
1081 if ret == PiecePriorityNone {
1087 func (t *Torrent) pendRequest(req Request) {
1088 ci := chunkIndex(req.ChunkSpec, t.chunkSize)
1089 t.pieces[req.Index].pendChunkIndex(ci)
1092 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1094 t.cl.event.Broadcast()
1095 if t.pieceComplete(piece) {
1096 t.onPieceCompleted(piece)
1098 t.onIncompletePiece(piece)
1100 t.updatePiecePriority(piece)
1103 func (t *Torrent) numReceivedConns() (ret int) {
1104 for c := range t.conns {
1105 if c.Discovery == PeerSourceIncoming {
1112 func (t *Torrent) maxHalfOpen() int {
1113 // Note that if we somehow exceed the maximum established conns, we want
1114 // the negative value to have an effect.
1115 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1116 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1117 // We want to allow some experimentation with new peers, and to try to
1118 // upset an oversupply of received connections.
1119 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1122 func (t *Torrent) openNewConns() (initiated int) {
1123 defer t.updateWantPeersEvent()
1124 for t.peers.Len() != 0 {
1128 if len(t.halfOpen) >= t.maxHalfOpen() {
1131 if len(t.cl.dialers) == 0 {
1134 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1137 p := t.peers.PopMax()
1144 func (t *Torrent) getConnPieceInclination() []int {
1145 _ret := t.connPieceInclinationPool.Get()
1147 pieceInclinationsNew.Add(1)
1148 return rand.Perm(int(t.numPieces()))
1150 pieceInclinationsReused.Add(1)
1151 return *_ret.(*[]int)
1154 func (t *Torrent) putPieceInclination(pi []int) {
1155 t.connPieceInclinationPool.Put(&pi)
1156 pieceInclinationsPut.Add(1)
1159 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1161 uncached := t.pieceCompleteUncached(piece)
1162 cached := p.completion()
1163 changed := cached != uncached
1164 complete := uncached.Complete
1165 p.storageCompletionOk = uncached.Ok
1166 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1167 if complete && len(p.dirtiers) != 0 {
1168 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1171 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1172 t.pieceCompletionChanged(piece)
1177 // Non-blocking read. Client lock is not required.
1178 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1180 p := &t.pieces[off/t.info.PieceLength]
1181 p.waitNoPendingWrites()
1183 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1194 // Returns an error if the metadata was completed, but couldn't be set for
1195 // some reason. Blame it on the last peer to contribute.
1196 func (t *Torrent) maybeCompleteMetadata() error {
1201 if !t.haveAllMetadataPieces() {
1202 // Don't have enough metadata pieces.
1205 err := t.setInfoBytes(t.metadataBytes)
1207 t.invalidateMetadata()
1208 return fmt.Errorf("error setting info bytes: %s", err)
1210 if t.cl.config.Debug {
1211 t.logger.Printf("%s: got metadata from peers", t)
1216 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1217 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1219 now.Add(bitmap.BitIndex(begin))
1220 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1227 func (t *Torrent) needData() bool {
1228 if t.closed.IsSet() {
1234 return t._pendingPieces.Len() != 0
1237 func appendMissingStrings(old, new []string) (ret []string) {
1240 for _, n := range new {
1241 for _, o := range old {
1246 ret = append(ret, n)
1251 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1253 for minNumTiers > len(ret) {
1254 ret = append(ret, nil)
1259 func (t *Torrent) addTrackers(announceList [][]string) {
1260 fullAnnounceList := &t.metainfo.AnnounceList
1261 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1262 for tierIndex, trackerURLs := range announceList {
1263 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1265 t.startMissingTrackerScrapers()
1266 t.updateWantPeersEvent()
1269 // Don't call this before the info is available.
1270 func (t *Torrent) bytesCompleted() int64 {
1274 return t.info.TotalLength() - t.bytesLeft()
1277 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1280 return t.setInfoBytes(b)
1283 // Returns true if connection is removed from torrent.Conns.
1284 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1285 if !c.closed.IsSet() {
1286 panic("connection is not closed")
1287 // There are behaviours prevented by the closed state that will fail
1288 // if the connection has been deleted.
1292 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1293 // the drop event against the PexConnState instead.
1295 if !t.cl.config.DisablePEX {
1299 torrent.Add("deleted connections", 1)
1300 c.deleteAllRequests()
1301 if t.numActivePeers() == 0 {
1302 t.assertNoPendingRequests()
1307 func (t *Torrent) numActivePeers() (num int) {
1308 t.iterPeers(func(*Peer) {
1314 func (t *Torrent) assertNoPendingRequests() {
1315 if len(t.pendingRequests) != 0 {
1316 panic(t.pendingRequests)
1318 //if len(t.lastRequested) != 0 {
1319 // panic(t.lastRequested)
1323 func (t *Torrent) dropConnection(c *PeerConn) {
1324 t.cl.event.Broadcast()
1326 if t.deleteConnection(c) {
1331 func (t *Torrent) wantPeers() bool {
1332 if t.closed.IsSet() {
1335 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1338 return t.needData() || t.seeding()
1341 func (t *Torrent) updateWantPeersEvent() {
1343 t.wantPeersEvent.Set()
1345 t.wantPeersEvent.Clear()
1349 // Returns whether the client should make effort to seed the torrent.
1350 func (t *Torrent) seeding() bool {
1352 if t.closed.IsSet() {
1355 if t.dataUploadDisallowed {
1358 if cl.config.NoUpload {
1361 if !cl.config.Seed {
1364 if cl.config.DisableAggressiveUpload && t.needData() {
1370 func (t *Torrent) onWebRtcConn(
1371 c datachannel.ReadWriteCloser,
1372 dcc webtorrent.DataChannelContext,
1375 pc, err := t.cl.initiateProtocolHandshakes(
1376 context.Background(),
1377 webrtcNetConn{c, dcc},
1381 webrtcNetAddr{dcc.Remote},
1383 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1386 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1389 if dcc.LocalOffered {
1390 pc.Discovery = PeerSourceTracker
1392 pc.Discovery = PeerSourceIncoming
1396 err = t.cl.runHandshookConn(pc, t)
1398 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1402 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1403 err := t.cl.runHandshookConn(pc, t)
1404 if err != nil || logAll {
1405 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1409 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1410 t.logRunHandshookConn(pc, false, log.Debug)
1413 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1414 wtc, release := t.cl.websocketTrackers.Get(u.String())
1416 <-t.closed.LockedChan(t.cl.locker())
1419 wst := websocketTrackerStatus{u, wtc}
1421 err := wtc.Announce(tracker.Started, t.infoHash)
1423 t.logger.WithDefaultLevel(log.Warning).Printf(
1424 "error in initial announce to %q: %v",
1433 func (t *Torrent) startScrapingTracker(_url string) {
1437 u, err := url.Parse(_url)
1439 // URLs with a leading '*' appear to be a uTorrent convention to
1440 // disable trackers.
1442 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1446 if u.Scheme == "udp" {
1448 t.startScrapingTracker(u.String())
1450 t.startScrapingTracker(u.String())
1453 if _, ok := t.trackerAnnouncers[_url]; ok {
1456 sl := func() torrentTrackerAnnouncer {
1459 if t.cl.config.DisableWebtorrent {
1462 return t.startWebsocketAnnouncer(*u)
1464 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1468 if t.cl.config.DisableIPv6 {
1472 newAnnouncer := &trackerScraper{
1476 go newAnnouncer.Run()
1482 if t.trackerAnnouncers == nil {
1483 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1485 t.trackerAnnouncers[_url] = sl
1488 // Adds and starts tracker scrapers for tracker URLs that aren't already
1490 func (t *Torrent) startMissingTrackerScrapers() {
1491 if t.cl.config.DisableTrackers {
1494 t.startScrapingTracker(t.metainfo.Announce)
1495 for _, tier := range t.metainfo.AnnounceList {
1496 for _, url := range tier {
1497 t.startScrapingTracker(url)
1502 // Returns an AnnounceRequest with fields filled out to defaults and current
1504 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1505 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1506 // dependent on the network in use.
1507 return tracker.AnnounceRequest{
1509 NumWant: func() int32 {
1510 if t.wantPeers() && len(t.cl.dialers) > 0 {
1516 Port: uint16(t.cl.incomingPeerPort()),
1517 PeerId: t.cl.peerID,
1518 InfoHash: t.infoHash,
1519 Key: t.cl.announceKey(),
1521 // The following are vaguely described in BEP 3.
1523 Left: t.bytesLeftAnnounce(),
1524 Uploaded: t.stats.BytesWrittenData.Int64(),
1525 // There's no mention of wasted or unwanted download in the BEP.
1526 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1530 // Adds peers revealed in an announce until the announce ends, or we have
1532 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1534 for v := range pvs {
1536 for _, cp := range v.Peers {
1538 // Can't do anything with this.
1542 Addr: ipPortAddr{cp.IP, cp.Port},
1543 Source: PeerSourceDhtGetPeers,
1550 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1551 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1555 go t.consumeDhtAnnouncePeers(ps.Peers())
1557 case <-t.closed.LockedChan(t.cl.locker()):
1558 case <-time.After(5 * time.Minute):
1564 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1570 if t.closed.IsSet() {
1576 // TODO: Determine if there's a listener on the port we're announcing.
1577 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1588 err := t.announceToDht(true, s)
1590 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1596 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1597 for _, p := range peers {
1605 // The returned TorrentStats may require alignment in memory. See
1606 // https://github.com/anacrolix/torrent/issues/383.
1607 func (t *Torrent) Stats() TorrentStats {
1609 defer t.cl.rUnlock()
1610 return t.statsLocked()
1613 func (t *Torrent) statsLocked() (ret TorrentStats) {
1614 ret.ActivePeers = len(t.conns)
1615 ret.HalfOpenPeers = len(t.halfOpen)
1616 ret.PendingPeers = t.peers.Len()
1617 ret.TotalPeers = t.numTotalPeers()
1618 ret.ConnectedSeeders = 0
1619 for c := range t.conns {
1620 if all, ok := c.peerHasAllPieces(); all && ok {
1621 ret.ConnectedSeeders++
1624 ret.ConnStats = t.stats.Copy()
1628 // The total number of peers in the torrent.
1629 func (t *Torrent) numTotalPeers() int {
1630 peers := make(map[string]struct{})
1631 for conn := range t.conns {
1632 ra := conn.conn.RemoteAddr()
1634 // It's been closed and doesn't support RemoteAddr.
1637 peers[ra.String()] = struct{}{}
1639 for addr := range t.halfOpen {
1640 peers[addr] = struct{}{}
1642 t.peers.Each(func(peer PeerInfo) {
1643 peers[peer.Addr.String()] = struct{}{}
1648 // Reconcile bytes transferred before connection was associated with a
1650 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1651 if c._stats != (ConnStats{
1652 // Handshakes should only increment these fields:
1653 BytesWritten: c._stats.BytesWritten,
1654 BytesRead: c._stats.BytesRead,
1658 c.postHandshakeStats(func(cs *ConnStats) {
1659 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1660 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1662 c.reconciledHandshakeStats = true
1665 // Returns true if the connection is added.
1666 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1669 torrent.Add("added connections", 1)
1672 if t.closed.IsSet() {
1673 return errors.New("torrent closed")
1675 for c0 := range t.conns {
1676 if c.PeerID != c0.PeerID {
1679 if !t.cl.config.DropDuplicatePeerIds {
1682 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1684 t.deleteConnection(c0)
1686 return errors.New("existing connection preferred")
1689 if len(t.conns) >= t.maxEstablishedConns {
1690 c := t.worstBadConn()
1692 return errors.New("don't want conns")
1695 t.deleteConnection(c)
1697 if len(t.conns) >= t.maxEstablishedConns {
1700 t.conns[c] = struct{}{}
1701 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1702 t.pex.Add(c) // as no further extended handshake expected
1707 func (t *Torrent) wantConns() bool {
1708 if !t.networkingEnabled {
1711 if t.closed.IsSet() {
1714 if !t.seeding() && !t.needData() {
1717 if len(t.conns) < t.maxEstablishedConns {
1720 return t.worstBadConn() != nil
1723 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1726 oldMax = t.maxEstablishedConns
1727 t.maxEstablishedConns = max
1728 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1729 return worseConn(&l.Peer, &r.Peer)
1731 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1732 t.dropConnection(wcs.Pop().(*PeerConn))
1738 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1739 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1742 t.cl.event.Broadcast()
1743 if t.closed.IsSet() {
1747 // Don't score the first time a piece is hashed, it could be an initial check.
1748 if p.storageCompletionOk {
1750 pieceHashedCorrect.Add(1)
1752 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1753 pieceHashedNotCorrect.Add(1)
1758 t.publishPieceChange(piece)
1761 t.publishPieceChange(piece)
1765 if len(p.dirtiers) != 0 {
1766 // Don't increment stats above connection-level for every involved connection.
1767 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1769 for c := range p.dirtiers {
1770 c._stats.incrementPiecesDirtiedGood()
1772 t.clearPieceTouchers(piece)
1774 err := p.Storage().MarkComplete()
1776 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1780 if t.closed.IsSet() {
1783 t.pendAllChunkSpecs(piece)
1785 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1786 // Peers contributed to all the data for this piece hash failure, and the failure was
1787 // not due to errors in the storage (such as data being dropped in a cache).
1789 // Increment Torrent and above stats, and then specific connections.
1790 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1791 for c := range p.dirtiers {
1792 // Y u do dis peer?!
1793 c.stats().incrementPiecesDirtiedBad()
1796 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1797 for c := range p.dirtiers {
1799 bannableTouchers = append(bannableTouchers, c)
1802 t.clearPieceTouchers(piece)
1803 slices.Sort(bannableTouchers, connLessTrusted)
1805 if t.cl.config.Debug {
1807 "bannable conns by trust for piece %d: %v",
1809 func() (ret []connectionTrust) {
1810 for _, c := range bannableTouchers {
1811 ret = append(ret, c.trust())
1818 if len(bannableTouchers) >= 1 {
1819 c := bannableTouchers[0]
1820 t.cl.banPeerIP(c.remoteIp())
1824 t.onIncompletePiece(piece)
1825 p.Storage().MarkNotComplete()
1827 t.updatePieceCompletion(piece)
1830 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1831 // TODO: Make faster
1832 for cn := range t.conns {
1837 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1838 t.pendAllChunkSpecs(piece)
1839 t.cancelRequestsForPiece(piece)
1840 for conn := range t.conns {
1842 t.maybeDropMutuallyCompletePeer(&conn.Peer)
1846 // Called when a piece is found to be not complete.
1847 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1848 if t.pieceAllDirty(piece) {
1849 t.pendAllChunkSpecs(piece)
1851 if !t.wantPieceIndex(piece) {
1852 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1855 // We could drop any connections that we told we have a piece that we
1856 // don't here. But there's a test failure, and it seems clients don't care
1857 // if you request pieces that you already claim to have. Pruning bad
1858 // connections might just remove any connections that aren't treating us
1859 // favourably anyway.
1861 // for c := range t.conns {
1862 // if c.sentHave(piece) {
1866 t.iterPeers(func(conn *Peer) {
1867 if conn.peerHasPiece(piece) {
1868 conn.updateRequests()
1873 func (t *Torrent) tryCreateMorePieceHashers() {
1874 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1878 func (t *Torrent) tryCreatePieceHasher() bool {
1879 if t.storage == nil {
1882 pi, ok := t.getPieceToHash()
1887 t.piecesQueuedForHash.Remove(pi)
1889 t.publishPieceChange(pi)
1890 t.updatePiecePriority(pi)
1891 t.storageLock.RLock()
1892 t.activePieceHashes++
1893 go t.pieceHasher(pi)
1897 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1898 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1899 if t.piece(i).hashing {
1909 func (t *Torrent) pieceHasher(index pieceIndex) {
1911 sum, copyErr := t.hashPiece(index)
1912 correct := sum == *p.hash
1916 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1918 t.storageLock.RUnlock()
1922 t.updatePiecePriority(index)
1923 t.pieceHashed(index, correct, copyErr)
1924 t.publishPieceChange(index)
1925 t.activePieceHashes--
1926 t.tryCreateMorePieceHashers()
1929 // Return the connections that touched a piece, and clear the entries while doing it.
1930 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1932 for c := range p.dirtiers {
1933 delete(c.peerTouchedPieces, pi)
1934 delete(p.dirtiers, c)
1938 func (t *Torrent) peersAsSlice() (ret []*Peer) {
1939 t.iterPeers(func(p *Peer) {
1940 ret = append(ret, p)
1945 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1946 piece := t.piece(pieceIndex)
1947 if piece.queuedForHash() {
1950 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1951 t.publishPieceChange(pieceIndex)
1952 t.updatePiecePriority(pieceIndex)
1953 t.tryCreateMorePieceHashers()
1956 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1957 // before the Info is available.
1958 func (t *Torrent) VerifyData() {
1959 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1960 t.Piece(i).VerifyData()
1964 // Start the process of connecting to the given peer for the given torrent if appropriate.
1965 func (t *Torrent) initiateConn(peer PeerInfo) {
1966 if peer.Id == t.cl.peerID {
1969 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1973 if t.addrActive(addr.String()) {
1977 t.halfOpen[addr.String()] = peer
1978 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1981 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1982 // quickly make one Client visible to the Torrent of another Client.
1983 func (t *Torrent) AddClientPeer(cl *Client) int {
1984 return t.AddPeers(func() (ps []PeerInfo) {
1985 for _, la := range cl.ListenAddrs() {
1986 ps = append(ps, PeerInfo{
1995 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1997 func (t *Torrent) allStats(f func(*ConnStats)) {
2002 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2003 return t.pieces[i].hashing
2006 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2007 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2010 func (t *Torrent) dialTimeout() time.Duration {
2011 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2014 func (t *Torrent) piece(i int) *Piece {
2018 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
2022 type torrentRequestStrategyCallbacks struct {
2026 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r Request) {
2027 torrent.Add("Request timeouts", 1)
2029 defer cb.t.cl.unlock()
2030 cb.t.iterPeers(func(cn *Peer) {
2031 if cn.peerHasPiece(pieceIndex(r.Index)) {
2038 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
2039 return torrentRequestStrategyCallbacks{t}
2042 func (t *Torrent) onWriteChunkErr(err error) {
2043 if t.userOnWriteChunkErr != nil {
2044 go t.userOnWriteChunkErr(err)
2047 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2048 t.disallowDataDownloadLocked()
2051 func (t *Torrent) DisallowDataDownload() {
2054 t.disallowDataDownloadLocked()
2057 func (t *Torrent) disallowDataDownloadLocked() {
2058 t.dataDownloadDisallowed = true
2059 t.iterPeers(func(c *Peer) {
2065 func (t *Torrent) AllowDataDownload() {
2068 t.dataDownloadDisallowed = false
2070 t.iterPeers(func(c *Peer) {
2075 // Enables uploading data, if it was disabled.
2076 func (t *Torrent) AllowDataUpload() {
2079 t.dataUploadDisallowed = false
2080 for c := range t.conns {
2085 // Disables uploading data, if it was enabled.
2086 func (t *Torrent) DisallowDataUpload() {
2089 t.dataUploadDisallowed = true
2090 for c := range t.conns {
2095 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2096 // or if nil, a critical message is logged, and data download is disabled.
2097 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2100 t.userOnWriteChunkErr = f
2103 func (t *Torrent) iterPeers(f func(*Peer)) {
2104 for pc := range t.conns {
2107 for _, ws := range t.webSeeds {
2112 func (t *Torrent) callbacks() *Callbacks {
2113 return &t.cl.config.Callbacks
2116 var WebseedHttpClient = &http.Client{
2117 Transport: &http.Transport{
2118 MaxConnsPerHost: 10,
2122 func (t *Torrent) addWebSeed(url string) {
2123 if t.cl.config.DisableWebseeds {
2126 if _, ok := t.webSeeds[url]; ok {
2129 const maxRequests = 10
2135 reconciledHandshakeStats: true,
2136 peerSentHaveAll: true,
2137 // TODO: Raise this limit, and instead limit concurrent fetches.
2138 PeerMaxRequests: 32,
2139 RemoteAddr: remoteAddrFromUrl(url),
2140 callbacks: t.callbacks(),
2142 client: webseed.Client{
2143 // Consider a MaxConnsPerHost in the transport for this, possibly in a global Client.
2144 HttpClient: WebseedHttpClient,
2147 activeRequests: make(map[Request]webseed.Request, maxRequests),
2149 ws.requesterCond.L = t.cl.locker()
2150 for range iter.N(maxRequests) {
2153 for _, f := range t.callbacks().NewPeer {
2156 ws.peer.logger = t.logger.WithContextValue(&ws)
2157 ws.peer.peerImpl = &ws
2159 ws.onGotInfo(t.info)
2161 t.webSeeds[url] = &ws.peer
2164 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2165 t.iterPeers(func(p1 *Peer) {