20 "github.com/RoaringBitmap/roaring"
21 "github.com/anacrolix/chansync"
22 "github.com/anacrolix/dht/v2"
23 "github.com/anacrolix/log"
24 "github.com/anacrolix/missinggo/iter"
25 "github.com/anacrolix/missinggo/perf"
26 "github.com/anacrolix/missinggo/pubsub"
27 "github.com/anacrolix/missinggo/slices"
28 "github.com/anacrolix/missinggo/v2"
29 "github.com/anacrolix/missinggo/v2/bitmap"
30 "github.com/anacrolix/missinggo/v2/prioritybitmap"
31 "github.com/anacrolix/multiless"
32 "github.com/anacrolix/sync"
33 "github.com/davecgh/go-spew/spew"
34 "github.com/pion/datachannel"
36 "github.com/anacrolix/torrent/bencode"
37 "github.com/anacrolix/torrent/common"
38 "github.com/anacrolix/torrent/metainfo"
39 pp "github.com/anacrolix/torrent/peer_protocol"
40 "github.com/anacrolix/torrent/segments"
41 "github.com/anacrolix/torrent/storage"
42 "github.com/anacrolix/torrent/tracker"
43 "github.com/anacrolix/torrent/webseed"
44 "github.com/anacrolix/torrent/webtorrent"
47 // Maintains state of torrent within a Client. Many methods should not be called before the info is
48 // available, see .Info and .GotInfo.
50 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
51 // alignment. See #262.
56 networkingEnabled chansync.Flag
57 dataDownloadDisallowed chansync.Flag
58 dataUploadDisallowed bool
59 userOnWriteChunkErr func(error)
61 closed chansync.SetOnce
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
99 // Reserve of peers to connect to. A peer can be both here and in the
100 // active connections if were told about the peer after connecting with
101 // them. That encourages us to reconnect to peers that are well known in
103 peers prioritizedPeers
104 // Whether we want to know to know more peers.
105 wantPeersEvent missinggo.Event
106 // An announcer for each tracker URL.
107 trackerAnnouncers map[string]torrentTrackerAnnouncer
108 // How many times we've initiated a DHT announce. TODO: Move into stats.
111 // Name used if the info name isn't available. Should be cleared when the
112 // Info does become available.
116 // The bencoded bytes of the info dict. This is actively manipulated if
117 // the info bytes aren't initially available, and we try to fetch them
120 // Each element corresponds to the 16KiB metadata pieces. If true, we have
121 // received that piece.
122 metadataCompletedChunks []bool
123 metadataChanged sync.Cond
125 // Set when .Info is obtained.
126 gotMetainfo missinggo.Event
128 readers map[*reader]struct{}
129 _readerNowPieces bitmap.Bitmap
130 _readerReadaheadPieces bitmap.Bitmap
132 // A cache of pieces we need to get. Calculated from various piece and
133 // file priorities and completion states elsewhere.
134 _pendingPieces prioritybitmap.PriorityBitmap
135 // A cache of completed piece indices.
136 _completedPieces roaring.Bitmap
137 // Pieces that need to be hashed.
138 piecesQueuedForHash bitmap.Bitmap
139 activePieceHashes int
141 // A pool of piece priorities []int for assignment to new connections.
142 // These "inclinations" are used to give connections preference for
144 connPieceInclinationPool sync.Pool
146 // Count of each request across active connections.
147 pendingRequests map[Request]int
152 func (t *Torrent) pieceAvailabilityFromPeers(i pieceIndex) (count int) {
153 t.iterPeers(func(peer *Peer) {
154 if peer.peerHasPiece(i) {
161 func (t *Torrent) decPieceAvailability(i pieceIndex) {
166 if p.availability <= 0 {
167 panic(p.availability)
172 func (t *Torrent) incPieceAvailability(i pieceIndex) {
173 // If we don't the info, this should be reconciled when we do.
180 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
181 return t._readerNowPieces
184 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
185 return t._readerReadaheadPieces
188 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
189 return !t.wantPieceIndex(i)
192 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
193 return &t._pendingPieces
196 // Returns a channel that is closed when the Torrent is closed.
197 func (t *Torrent) Closed() chansync.Done {
198 return t.closed.Done()
201 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
202 // pending, and half-open peers.
203 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
204 // Add pending peers to the list
205 t.peers.Each(func(peer PeerInfo) {
206 ks = append(ks, peer)
209 // Add half-open peers to the list
210 for _, peer := range t.halfOpen {
211 ks = append(ks, peer)
214 // Add active peers to the list
215 for conn := range t.conns {
217 ks = append(ks, PeerInfo{
219 Addr: conn.RemoteAddr,
220 Source: conn.Discovery,
221 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
222 // > But if we're not connected to them with an encrypted connection, I couldn't say
223 // > what's appropriate. We can carry forward the SupportsEncryption value as we
224 // > received it from trackers/DHT/PEX, or just use the encryption state for the
225 // > connection. It's probably easiest to do the latter for now.
226 // https://github.com/anacrolix/torrent/pull/188
227 SupportsEncryption: conn.headerEncrypted,
234 func (t *Torrent) setChunkSize(size pp.Integer) {
236 t.chunkPool = sync.Pool{
237 New: func() interface{} {
238 b := make([]byte, size)
244 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
245 return t._completedPieces.Contains(bitmap.BitIndex(piece))
248 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
249 return t.pieces[piece].Storage().Completion()
252 // There's a connection to that address already.
253 func (t *Torrent) addrActive(addr string) bool {
254 if _, ok := t.halfOpen[addr]; ok {
257 for c := range t.conns {
259 if ra.String() == addr {
266 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
267 for c := range t.conns {
268 if !c.closed.IsSet() {
275 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
277 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
278 if t.closed.IsSet() {
281 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
282 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
283 torrent.Add("peers not added because of bad addr", 1)
284 // cl.logger.Printf("peers not added because of bad addr: %v", p)
288 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
289 torrent.Add("peers replaced", 1)
290 if !replaced.equal(p) {
291 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
298 for t.peers.Len() > cl.config.TorrentPeersHighWater {
299 _, ok := t.peers.DeleteMin()
301 torrent.Add("excess reserve peers discarded", 1)
307 func (t *Torrent) invalidateMetadata() {
308 for i := range t.metadataCompletedChunks {
309 t.metadataCompletedChunks[i] = false
316 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
320 if index >= len(t.metadataCompletedChunks) {
321 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
324 copy(t.metadataBytes[(1<<14)*index:], data)
325 t.metadataCompletedChunks[index] = true
328 func (t *Torrent) metadataPieceCount() int {
329 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
332 func (t *Torrent) haveMetadataPiece(piece int) bool {
334 return (1<<14)*piece < len(t.metadataBytes)
336 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
340 func (t *Torrent) metadataSize() int {
341 return len(t.metadataBytes)
344 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
345 for i := 0; i < len(info.Pieces); i += sha1.Size {
346 ret = append(ret, info.Pieces[i:i+sha1.Size])
351 func (t *Torrent) makePieces() {
352 hashes := infoPieceHashes(t.info)
353 t.pieces = make([]Piece, len(hashes))
354 for i, hash := range hashes {
355 piece := &t.pieces[i]
357 piece.index = pieceIndex(i)
358 piece.noPendingWrites.L = &piece.pendingWritesMutex
359 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
361 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
362 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
363 piece.files = files[beginFile:endFile]
367 // Returns the index of the first file containing the piece. files must be
368 // ordered by offset.
369 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
370 for i, f := range files {
371 if f.offset+f.length > pieceOffset {
378 // Returns the index after the last file containing the piece. files must be
379 // ordered by offset.
380 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
381 for i, f := range files {
382 if f.offset+f.length >= pieceEndOffset {
389 func (t *Torrent) cacheLength() {
391 for _, f := range t.info.UpvertedFiles() {
397 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
399 func (t *Torrent) setInfo(info *metainfo.Info) error {
400 if err := validateInfo(info); err != nil {
401 return fmt.Errorf("bad info: %s", err)
403 if t.storageOpener != nil {
405 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
407 return fmt.Errorf("error opening torrent storage: %s", err)
413 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
414 t.displayName = "" // Save a few bytes lol.
421 // This seems to be all the follow-up tasks after info is set, that can't fail.
422 func (t *Torrent) onSetInfo() {
423 t.iterPeers(func(p *Peer) {
426 for i := range t.pieces {
428 // Need to add availability before updating piece completion, as that may result in conns
430 if p.availability != 0 {
431 panic(p.availability)
433 p.availability = int64(t.pieceAvailabilityFromPeers(i))
434 t.updatePieceCompletion(pieceIndex(i))
435 if !p.storageCompletionOk {
436 // t.logger.Printf("piece %s completion unknown, queueing check", p)
437 t.queuePieceCheck(pieceIndex(i))
440 t.cl.event.Broadcast()
442 t.updateWantPeersEvent()
443 t.pendingRequests = make(map[Request]int)
444 t.tryCreateMorePieceHashers()
447 // Called when metadata for a torrent becomes available.
448 func (t *Torrent) setInfoBytesLocked(b []byte) error {
449 if metainfo.HashBytes(b) != t.infoHash {
450 return errors.New("info bytes have wrong hash")
452 var info metainfo.Info
453 if err := bencode.Unmarshal(b, &info); err != nil {
454 return fmt.Errorf("error unmarshalling info bytes: %s", err)
457 t.metadataCompletedChunks = nil
461 if err := t.setInfo(&info); err != nil {
468 func (t *Torrent) haveAllMetadataPieces() bool {
472 if t.metadataCompletedChunks == nil {
475 for _, have := range t.metadataCompletedChunks {
483 // TODO: Propagate errors to disconnect peer.
484 func (t *Torrent) setMetadataSize(bytes int) (err error) {
486 // We already know the correct metadata size.
489 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
490 return errors.New("bad size")
492 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
495 t.metadataBytes = make([]byte, bytes)
496 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
497 t.metadataChanged.Broadcast()
498 for c := range t.conns {
499 c.requestPendingMetadata()
504 // The current working name for the torrent. Either the name in the info dict,
505 // or a display name given such as by the dn value in a magnet link, or "".
506 func (t *Torrent) name() string {
508 defer t.nameMu.RUnlock()
512 if t.displayName != "" {
515 return "infohash:" + t.infoHash.HexString()
518 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
519 p := &t.pieces[index]
520 ret.Priority = t.piecePriority(index)
521 ret.Completion = p.completion()
522 ret.QueuedForHash = p.queuedForHash()
523 ret.Hashing = p.hashing
524 ret.Checking = ret.QueuedForHash || ret.Hashing
525 ret.Marking = p.marking
526 if !ret.Complete && t.piecePartiallyDownloaded(index) {
532 func (t *Torrent) metadataPieceSize(piece int) int {
533 return metadataPieceSize(len(t.metadataBytes), piece)
536 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
539 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
540 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
542 TotalSize: len(t.metadataBytes),
548 type pieceAvailabilityRun struct {
553 func (me pieceAvailabilityRun) String() string {
554 return fmt.Sprintf("%v(%v)", me.count, me.availability)
557 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
558 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
559 ret = append(ret, pieceAvailabilityRun{availability: el.(int64), count: int(count)})
561 for i := range t.pieces {
562 rle.Append(t.pieces[i].availability, 1)
568 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
569 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
570 ret = append(ret, PieceStateRun{
571 PieceState: el.(PieceState),
575 for index := range t.pieces {
576 rle.Append(t.pieceState(pieceIndex(index)), 1)
582 // Produces a small string representing a PieceStateRun.
583 func (psr PieceStateRun) String() (ret string) {
584 ret = fmt.Sprintf("%d", psr.Length)
585 ret += func() string {
586 switch psr.Priority {
587 case PiecePriorityNext:
589 case PiecePriorityNormal:
591 case PiecePriorityReadahead:
593 case PiecePriorityNow:
595 case PiecePriorityHigh:
604 if psr.QueuedForHash {
622 func (t *Torrent) writeStatus(w io.Writer) {
623 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
624 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
626 fmt.Fprintf(w, "Metadata have: ")
627 for _, h := range t.metadataCompletedChunks {
628 fmt.Fprintf(w, "%c", func() rune {
638 fmt.Fprintf(w, "Piece length: %s\n",
641 return fmt.Sprintf("%v (%v chunks)",
643 float64(t.usualPieceSize())/float64(t.chunkSize))
650 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
651 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
652 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
653 for _, run := range t.pieceAvailabilityRuns() {
654 ret = append(ret, run.String())
659 fmt.Fprintf(w, "Reader Pieces:")
660 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
661 fmt.Fprintf(w, " %d:%d", begin, end)
666 fmt.Fprintf(w, "Enabled trackers:\n")
668 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
669 fmt.Fprintf(tw, " URL\tExtra\n")
670 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
673 var luns, runs url.URL = *lu, *ru
676 var ml missinggo.MultiLess
677 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
678 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
680 }).([]torrentTrackerAnnouncer) {
681 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
686 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
688 spew.NewDefaultConfig()
689 spew.Fdump(w, t.statsLocked())
691 peers := t.peersAsSlice()
692 sort.Slice(peers, func(_i, _j int) bool {
695 if less, ok := multiless.New().EagerSameLess(
696 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
700 return worseConn(i, j)
702 for i, c := range peers {
703 fmt.Fprintf(w, "%2d. ", i+1)
708 func (t *Torrent) haveInfo() bool {
712 // Returns a run-time generated MetaInfo that includes the info bytes and
713 // announce-list as currently known to the client.
714 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
715 return metainfo.MetaInfo{
716 CreationDate: time.Now().Unix(),
717 Comment: "dynamic metainfo from client",
718 CreatedBy: "go.torrent",
719 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
720 InfoBytes: func() []byte {
722 return t.metadataBytes
727 UrlList: func() []string {
728 ret := make([]string, 0, len(t.webSeeds))
729 for url := range t.webSeeds {
730 ret = append(ret, url)
737 func (t *Torrent) BytesMissing() int64 {
740 return t.bytesMissingLocked()
743 func (t *Torrent) bytesMissingLocked() int64 {
747 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
748 roaring.Flip(b, 0, end).Iterate(cb)
751 func (t *Torrent) bytesLeft() (left int64) {
752 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
753 p := t.piece(pieceIndex(x))
754 left += int64(p.length() - p.numDirtyBytes())
760 // Bytes left to give in tracker announces.
761 func (t *Torrent) bytesLeftAnnounce() int64 {
769 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
770 if t.pieceComplete(piece) {
773 if t.pieceAllDirty(piece) {
776 return t.pieces[piece].hasDirtyChunks()
779 func (t *Torrent) usualPieceSize() int {
780 return int(t.info.PieceLength)
783 func (t *Torrent) numPieces() pieceIndex {
784 return pieceIndex(t.info.NumPieces())
787 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
788 return pieceIndex(t._completedPieces.GetCardinality())
791 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
793 if t.storage != nil {
798 defer t.storageLock.Unlock()
799 if f := t.storage.Close; f != nil {
802 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
807 t.iterPeers(func(p *Peer) {
811 t.cl.event.Broadcast()
812 t.pieceStateChanges.Close()
813 t.updateWantPeersEvent()
817 func (t *Torrent) requestOffset(r Request) int64 {
818 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
821 // Return the request that would include the given offset into the torrent data. Returns !ok if
822 // there is no such request.
823 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
824 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
827 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
828 defer perf.ScopeTimerErr(&err)()
829 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
830 if err == nil && n != len(data) {
831 err = io.ErrShortWrite
836 func (t *Torrent) bitfield() (bf []bool) {
837 bf = make([]bool, t.numPieces())
838 t._completedPieces.Iterate(func(piece uint32) (again bool) {
845 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
846 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
849 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
850 t.pieces[pieceIndex]._dirtyChunks.Clear()
853 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
854 if t.info.PieceLength == 0 {
855 // There will be no variance amongst pieces. Only pain.
858 if piece == t.numPieces()-1 {
859 ret := pp.Integer(*t.length % t.info.PieceLength)
864 return pp.Integer(t.info.PieceLength)
867 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
869 p.waitNoPendingWrites()
870 storagePiece := t.pieces[piece].Storage()
872 //Does the backend want to do its own hashing?
873 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
874 var sum metainfo.Hash
875 //log.Printf("A piece decided to self-hash: %d", piece)
876 sum, err = i.SelfHash()
877 missinggo.CopyExact(&ret, sum)
881 hash := pieceHash.New()
882 const logPieceContents = false
883 if logPieceContents {
884 var examineBuf bytes.Buffer
885 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
886 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
888 _, err = storagePiece.WriteTo(hash)
890 missinggo.CopyExact(&ret, hash.Sum(nil))
894 func (t *Torrent) haveAnyPieces() bool {
895 return t._completedPieces.GetCardinality() != 0
898 func (t *Torrent) haveAllPieces() bool {
902 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
905 func (t *Torrent) havePiece(index pieceIndex) bool {
906 return t.haveInfo() && t.pieceComplete(index)
909 func (t *Torrent) maybeDropMutuallyCompletePeer(
910 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's okay?
913 if !t.cl.config.DropMutuallyCompletePeers {
916 if !t.haveAllPieces() {
919 if all, known := p.peerHasAllPieces(); !(known && all) {
925 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
929 func (t *Torrent) haveChunk(r Request) (ret bool) {
931 // log.Println("have chunk", r, ret)
936 if t.pieceComplete(pieceIndex(r.Index)) {
939 p := &t.pieces[r.Index]
940 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
943 func chunkIndex(cs ChunkSpec, chunkSize pp.Integer) int {
944 return int(cs.Begin / chunkSize)
947 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
948 // TODO: Are these overly conservative, should we be guarding this here?
953 if index < 0 || index >= t.numPieces() {
957 p := &t.pieces[index]
958 if p.queuedForHash() {
964 if t.pieceComplete(index) {
967 if t._pendingPieces.Contains(int(index)) {
970 // t.logger.Printf("piece %d not pending", index)
971 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
972 return index < begin || index >= end
976 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
977 // conns (which is a map).
978 var peerConnSlices sync.Pool
980 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
981 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
982 // established connections for more than a minute. This is O(n log n). If there was a way to not
983 // consider the position of a conn relative to the total number, it could be reduced to O(n).
984 func (t *Torrent) worstBadConn() (ret *PeerConn) {
986 getInterface := peerConnSlices.Get()
987 if getInterface == nil {
988 sl = make([]*PeerConn, 0, len(t.conns))
990 sl = getInterface.([]*PeerConn)[:0]
992 sl = t.appendUnclosedConns(sl)
993 defer peerConnSlices.Put(sl)
994 wcs := worseConnSlice{sl}
997 c := heap.Pop(&wcs).(*PeerConn)
998 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1001 // If the connection is in the worst half of the established
1002 // connection quota and is older than a minute.
1003 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1004 // Give connections 1 minute to prove themselves.
1005 if time.Since(c.completedHandshake) > time.Minute {
1013 type PieceStateChange struct {
1018 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1019 t.cl._mu.Defer(func() {
1020 cur := t.pieceState(piece)
1021 p := &t.pieces[piece]
1022 if cur != p.publicPieceState {
1023 p.publicPieceState = cur
1024 t.pieceStateChanges.Publish(PieceStateChange{
1032 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1033 if t.pieceComplete(piece) {
1036 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
1039 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1040 return t.pieces[piece]._dirtyChunks.Len() == bitmap.BitRange(t.pieceNumChunks(piece))
1043 func (t *Torrent) readersChanged() {
1044 t.updateReaderPieces()
1045 t.updateAllPiecePriorities()
1048 func (t *Torrent) updateReaderPieces() {
1049 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1052 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1056 t.updateReaderPieces()
1057 // Order the ranges, high and low.
1059 if l.begin > h.begin {
1062 if l.end < h.begin {
1063 // Two distinct ranges.
1064 t.updatePiecePriorities(l.begin, l.end)
1065 t.updatePiecePriorities(h.begin, h.end)
1072 t.updatePiecePriorities(l.begin, end)
1076 func (t *Torrent) maybeNewConns() {
1077 // Tickle the accept routine.
1078 t.cl.event.Broadcast()
1082 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
1083 // t.logger.Printf("piece %d priority changed", piece)
1084 t.iterPeers(func(c *Peer) {
1085 if c.updatePiecePriority(piece) {
1086 // log.Print("conn piece priority changed")
1091 t.publishPieceChange(piece)
1094 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
1095 p := &t.pieces[piece]
1096 newPrio := p.uncachedPriority()
1097 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1098 if newPrio == PiecePriorityNone {
1099 if !t._pendingPieces.Remove(int(piece)) {
1103 if !t._pendingPieces.Set(int(piece), newPrio.BitmapPriority()) {
1107 t.piecePriorityChanged(piece)
1110 func (t *Torrent) updateAllPiecePriorities() {
1111 t.updatePiecePriorities(0, t.numPieces())
1114 // Update all piece priorities in one hit. This function should have the same
1115 // output as updatePiecePriority, but across all pieces.
1116 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
1117 for i := begin; i < end; i++ {
1118 t.updatePiecePriority(i)
1122 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1123 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1124 if off >= *t.length {
1134 begin = pieceIndex(off / t.info.PieceLength)
1135 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1136 if end > pieceIndex(t.info.NumPieces()) {
1137 end = pieceIndex(t.info.NumPieces())
1142 // Returns true if all iterations complete without breaking. Returns the read
1143 // regions for all readers. The reader regions should not be merged as some
1144 // callers depend on this method to enumerate readers.
1145 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1146 for r := range t.readers {
1148 if p.begin >= p.end {
1151 if !f(p.begin, p.end) {
1158 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1159 prio, ok := t._pendingPieces.GetPriority(piece)
1161 return PiecePriorityNone
1166 ret := piecePriority(-prio)
1167 if ret == PiecePriorityNone {
1173 func (t *Torrent) pendRequest(req Request) {
1174 ci := chunkIndex(req.ChunkSpec, t.chunkSize)
1175 t.pieces[req.Index].pendChunkIndex(ci)
1178 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1179 t.cl.event.Broadcast()
1180 if t.pieceComplete(piece) {
1181 t.onPieceCompleted(piece)
1183 t.onIncompletePiece(piece)
1185 t.updatePiecePriority(piece)
1188 func (t *Torrent) numReceivedConns() (ret int) {
1189 for c := range t.conns {
1190 if c.Discovery == PeerSourceIncoming {
1197 func (t *Torrent) maxHalfOpen() int {
1198 // Note that if we somehow exceed the maximum established conns, we want
1199 // the negative value to have an effect.
1200 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1201 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1202 // We want to allow some experimentation with new peers, and to try to
1203 // upset an oversupply of received connections.
1204 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1207 func (t *Torrent) openNewConns() (initiated int) {
1208 defer t.updateWantPeersEvent()
1209 for t.peers.Len() != 0 {
1213 if len(t.halfOpen) >= t.maxHalfOpen() {
1216 if len(t.cl.dialers) == 0 {
1219 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1222 p := t.peers.PopMax()
1229 func (t *Torrent) getConnPieceInclination() []int {
1230 _ret := t.connPieceInclinationPool.Get()
1232 pieceInclinationsNew.Add(1)
1233 return rand.Perm(int(t.numPieces()))
1235 pieceInclinationsReused.Add(1)
1236 return *_ret.(*[]int)
1239 func (t *Torrent) putPieceInclination(pi []int) {
1240 t.connPieceInclinationPool.Put(&pi)
1241 pieceInclinationsPut.Add(1)
1244 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1246 uncached := t.pieceCompleteUncached(piece)
1247 cached := p.completion()
1248 changed := cached != uncached
1249 complete := uncached.Complete
1250 p.storageCompletionOk = uncached.Ok
1253 t._completedPieces.Add(x)
1255 t._completedPieces.Remove(x)
1257 if complete && len(p.dirtiers) != 0 {
1258 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1261 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1262 t.pieceCompletionChanged(piece)
1267 // Non-blocking read. Client lock is not required.
1268 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1270 p := &t.pieces[off/t.info.PieceLength]
1271 p.waitNoPendingWrites()
1273 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1284 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1285 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1286 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1287 func (t *Torrent) maybeCompleteMetadata() error {
1292 if !t.haveAllMetadataPieces() {
1293 // Don't have enough metadata pieces.
1296 err := t.setInfoBytesLocked(t.metadataBytes)
1298 t.invalidateMetadata()
1299 return fmt.Errorf("error setting info bytes: %s", err)
1301 if t.cl.config.Debug {
1302 t.logger.Printf("%s: got metadata from peers", t)
1307 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1308 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1310 now.Add(bitmap.BitIndex(begin))
1311 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1318 func (t *Torrent) needData() bool {
1319 if t.closed.IsSet() {
1325 return t._pendingPieces.Len() != 0
1328 func appendMissingStrings(old, new []string) (ret []string) {
1331 for _, n := range new {
1332 for _, o := range old {
1337 ret = append(ret, n)
1342 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1344 for minNumTiers > len(ret) {
1345 ret = append(ret, nil)
1350 func (t *Torrent) addTrackers(announceList [][]string) {
1351 fullAnnounceList := &t.metainfo.AnnounceList
1352 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1353 for tierIndex, trackerURLs := range announceList {
1354 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1356 t.startMissingTrackerScrapers()
1357 t.updateWantPeersEvent()
1360 // Don't call this before the info is available.
1361 func (t *Torrent) bytesCompleted() int64 {
1365 return *t.length - t.bytesLeft()
1368 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1371 return t.setInfoBytesLocked(b)
1374 // Returns true if connection is removed from torrent.Conns.
1375 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1376 if !c.closed.IsSet() {
1377 panic("connection is not closed")
1378 // There are behaviours prevented by the closed state that will fail
1379 // if the connection has been deleted.
1383 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1384 // the drop event against the PexConnState instead.
1386 if !t.cl.config.DisablePEX {
1390 torrent.Add("deleted connections", 1)
1391 c.deleteAllRequests()
1392 if t.numActivePeers() == 0 {
1393 t.assertNoPendingRequests()
1398 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1402 p.newPeerPieces().IterTyped(func(i int) bool {
1403 p.t.decPieceAvailability(i)
1408 func (t *Torrent) numActivePeers() (num int) {
1409 t.iterPeers(func(*Peer) {
1415 func (t *Torrent) assertNoPendingRequests() {
1416 if len(t.pendingRequests) != 0 {
1417 panic(t.pendingRequests)
1419 //if len(t.lastRequested) != 0 {
1420 // panic(t.lastRequested)
1424 func (t *Torrent) dropConnection(c *PeerConn) {
1425 t.cl.event.Broadcast()
1427 if t.deletePeerConn(c) {
1432 func (t *Torrent) wantPeers() bool {
1433 if t.closed.IsSet() {
1436 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1439 return t.needData() || t.seeding()
1442 func (t *Torrent) updateWantPeersEvent() {
1444 t.wantPeersEvent.Set()
1446 t.wantPeersEvent.Clear()
1450 // Returns whether the client should make effort to seed the torrent.
1451 func (t *Torrent) seeding() bool {
1453 if t.closed.IsSet() {
1456 if t.dataUploadDisallowed {
1459 if cl.config.NoUpload {
1462 if !cl.config.Seed {
1465 if cl.config.DisableAggressiveUpload && t.needData() {
1471 func (t *Torrent) onWebRtcConn(
1472 c datachannel.ReadWriteCloser,
1473 dcc webtorrent.DataChannelContext,
1476 pc, err := t.cl.initiateProtocolHandshakes(
1477 context.Background(),
1478 webrtcNetConn{c, dcc},
1482 webrtcNetAddr{dcc.Remote},
1484 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1487 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1490 if dcc.LocalOffered {
1491 pc.Discovery = PeerSourceTracker
1493 pc.Discovery = PeerSourceIncoming
1497 err = t.cl.runHandshookConn(pc, t)
1499 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1503 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1504 err := t.cl.runHandshookConn(pc, t)
1505 if err != nil || logAll {
1506 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1510 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1511 t.logRunHandshookConn(pc, false, log.Debug)
1514 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1515 wtc, release := t.cl.websocketTrackers.Get(u.String())
1520 wst := websocketTrackerStatus{u, wtc}
1522 err := wtc.Announce(tracker.Started, t.infoHash)
1524 t.logger.WithDefaultLevel(log.Warning).Printf(
1525 "error in initial announce to %q: %v",
1534 func (t *Torrent) startScrapingTracker(_url string) {
1538 u, err := url.Parse(_url)
1540 // URLs with a leading '*' appear to be a uTorrent convention to
1541 // disable trackers.
1543 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1547 if u.Scheme == "udp" {
1549 t.startScrapingTracker(u.String())
1551 t.startScrapingTracker(u.String())
1554 if _, ok := t.trackerAnnouncers[_url]; ok {
1557 sl := func() torrentTrackerAnnouncer {
1560 if t.cl.config.DisableWebtorrent {
1563 return t.startWebsocketAnnouncer(*u)
1565 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1569 if t.cl.config.DisableIPv6 {
1573 newAnnouncer := &trackerScraper{
1577 go newAnnouncer.Run()
1583 if t.trackerAnnouncers == nil {
1584 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1586 t.trackerAnnouncers[_url] = sl
1589 // Adds and starts tracker scrapers for tracker URLs that aren't already
1591 func (t *Torrent) startMissingTrackerScrapers() {
1592 if t.cl.config.DisableTrackers {
1595 t.startScrapingTracker(t.metainfo.Announce)
1596 for _, tier := range t.metainfo.AnnounceList {
1597 for _, url := range tier {
1598 t.startScrapingTracker(url)
1603 // Returns an AnnounceRequest with fields filled out to defaults and current
1605 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1606 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1607 // dependent on the network in use.
1608 return tracker.AnnounceRequest{
1610 NumWant: func() int32 {
1611 if t.wantPeers() && len(t.cl.dialers) > 0 {
1617 Port: uint16(t.cl.incomingPeerPort()),
1618 PeerId: t.cl.peerID,
1619 InfoHash: t.infoHash,
1620 Key: t.cl.announceKey(),
1622 // The following are vaguely described in BEP 3.
1624 Left: t.bytesLeftAnnounce(),
1625 Uploaded: t.stats.BytesWrittenData.Int64(),
1626 // There's no mention of wasted or unwanted download in the BEP.
1627 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1631 // Adds peers revealed in an announce until the announce ends, or we have
1633 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1635 for v := range pvs {
1638 for _, cp := range v.Peers {
1640 // Can't do anything with this.
1643 if t.addPeer(PeerInfo{
1644 Addr: ipPortAddr{cp.IP, cp.Port},
1645 Source: PeerSourceDhtGetPeers,
1652 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1657 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1658 // announce ends. stop will force the announce to end.
1659 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1660 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1664 _done := make(chan struct{})
1668 t.consumeDhtAnnouncePeers(ps.Peers())
1674 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1675 _, stop, err := t.AnnounceToDht(s)
1680 case <-t.closed.Done():
1681 case <-time.After(5 * time.Minute):
1687 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1693 if t.closed.IsSet() {
1699 // TODO: Determine if there's a listener on the port we're announcing.
1700 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1711 err := t.timeboxedAnnounceToDht(s)
1713 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1719 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1720 for _, p := range peers {
1728 // The returned TorrentStats may require alignment in memory. See
1729 // https://github.com/anacrolix/torrent/issues/383.
1730 func (t *Torrent) Stats() TorrentStats {
1732 defer t.cl.rUnlock()
1733 return t.statsLocked()
1736 func (t *Torrent) statsLocked() (ret TorrentStats) {
1737 ret.ActivePeers = len(t.conns)
1738 ret.HalfOpenPeers = len(t.halfOpen)
1739 ret.PendingPeers = t.peers.Len()
1740 ret.TotalPeers = t.numTotalPeers()
1741 ret.ConnectedSeeders = 0
1742 for c := range t.conns {
1743 if all, ok := c.peerHasAllPieces(); all && ok {
1744 ret.ConnectedSeeders++
1747 ret.ConnStats = t.stats.Copy()
1751 // The total number of peers in the torrent.
1752 func (t *Torrent) numTotalPeers() int {
1753 peers := make(map[string]struct{})
1754 for conn := range t.conns {
1755 ra := conn.conn.RemoteAddr()
1757 // It's been closed and doesn't support RemoteAddr.
1760 peers[ra.String()] = struct{}{}
1762 for addr := range t.halfOpen {
1763 peers[addr] = struct{}{}
1765 t.peers.Each(func(peer PeerInfo) {
1766 peers[peer.Addr.String()] = struct{}{}
1771 // Reconcile bytes transferred before connection was associated with a
1773 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1774 if c._stats != (ConnStats{
1775 // Handshakes should only increment these fields:
1776 BytesWritten: c._stats.BytesWritten,
1777 BytesRead: c._stats.BytesRead,
1781 c.postHandshakeStats(func(cs *ConnStats) {
1782 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1783 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1785 c.reconciledHandshakeStats = true
1788 // Returns true if the connection is added.
1789 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1792 torrent.Add("added connections", 1)
1795 if t.closed.IsSet() {
1796 return errors.New("torrent closed")
1798 for c0 := range t.conns {
1799 if c.PeerID != c0.PeerID {
1802 if !t.cl.config.DropDuplicatePeerIds {
1805 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1807 t.deletePeerConn(c0)
1809 return errors.New("existing connection preferred")
1812 if len(t.conns) >= t.maxEstablishedConns {
1813 c := t.worstBadConn()
1815 return errors.New("don't want conns")
1820 if len(t.conns) >= t.maxEstablishedConns {
1823 t.conns[c] = struct{}{}
1824 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1825 t.pex.Add(c) // as no further extended handshake expected
1830 func (t *Torrent) wantConns() bool {
1831 if !t.networkingEnabled.Bool() {
1834 if t.closed.IsSet() {
1837 if !t.seeding() && !t.needData() {
1840 if len(t.conns) < t.maxEstablishedConns {
1843 return t.worstBadConn() != nil
1846 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1849 oldMax = t.maxEstablishedConns
1850 t.maxEstablishedConns = max
1851 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1852 return worseConn(&l.Peer, &r.Peer)
1854 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1855 t.dropConnection(wcs.Pop().(*PeerConn))
1861 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1862 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1865 t.cl.event.Broadcast()
1866 if t.closed.IsSet() {
1870 // Don't score the first time a piece is hashed, it could be an initial check.
1871 if p.storageCompletionOk {
1873 pieceHashedCorrect.Add(1)
1876 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1877 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1878 pieceHashedNotCorrect.Add(1)
1883 t.publishPieceChange(piece)
1886 t.publishPieceChange(piece)
1890 if len(p.dirtiers) != 0 {
1891 // Don't increment stats above connection-level for every involved connection.
1892 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1894 for c := range p.dirtiers {
1895 c._stats.incrementPiecesDirtiedGood()
1897 t.clearPieceTouchers(piece)
1899 err := p.Storage().MarkComplete()
1901 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1905 if t.closed.IsSet() {
1908 t.pendAllChunkSpecs(piece)
1910 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1911 // Peers contributed to all the data for this piece hash failure, and the failure was
1912 // not due to errors in the storage (such as data being dropped in a cache).
1914 // Increment Torrent and above stats, and then specific connections.
1915 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1916 for c := range p.dirtiers {
1917 // Y u do dis peer?!
1918 c.stats().incrementPiecesDirtiedBad()
1921 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1922 for c := range p.dirtiers {
1924 bannableTouchers = append(bannableTouchers, c)
1927 t.clearPieceTouchers(piece)
1928 slices.Sort(bannableTouchers, connLessTrusted)
1930 if t.cl.config.Debug {
1932 "bannable conns by trust for piece %d: %v",
1934 func() (ret []connectionTrust) {
1935 for _, c := range bannableTouchers {
1936 ret = append(ret, c.trust())
1943 if len(bannableTouchers) >= 1 {
1944 c := bannableTouchers[0]
1945 t.cl.banPeerIP(c.remoteIp())
1949 t.onIncompletePiece(piece)
1950 p.Storage().MarkNotComplete()
1952 t.updatePieceCompletion(piece)
1955 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1956 // TODO: Make faster
1957 for cn := range t.conns {
1962 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1963 t.pendAllChunkSpecs(piece)
1964 t.cancelRequestsForPiece(piece)
1965 t.piece(piece).readerCond.Broadcast()
1966 for conn := range t.conns {
1968 t.maybeDropMutuallyCompletePeer(&conn.Peer)
1972 // Called when a piece is found to be not complete.
1973 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1974 if t.pieceAllDirty(piece) {
1975 t.pendAllChunkSpecs(piece)
1977 if !t.wantPieceIndex(piece) {
1978 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1981 // We could drop any connections that we told we have a piece that we
1982 // don't here. But there's a test failure, and it seems clients don't care
1983 // if you request pieces that you already claim to have. Pruning bad
1984 // connections might just remove any connections that aren't treating us
1985 // favourably anyway.
1987 // for c := range t.conns {
1988 // if c.sentHave(piece) {
1992 t.iterPeers(func(conn *Peer) {
1993 if conn.peerHasPiece(piece) {
1994 conn.updateRequests()
1999 func (t *Torrent) tryCreateMorePieceHashers() {
2000 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2004 func (t *Torrent) tryCreatePieceHasher() bool {
2005 if t.storage == nil {
2008 pi, ok := t.getPieceToHash()
2013 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2015 t.publishPieceChange(pi)
2016 t.updatePiecePriority(pi)
2017 t.storageLock.RLock()
2018 t.activePieceHashes++
2019 go t.pieceHasher(pi)
2023 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2024 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2025 if t.piece(i).hashing {
2035 func (t *Torrent) pieceHasher(index pieceIndex) {
2037 sum, copyErr := t.hashPiece(index)
2038 correct := sum == *p.hash
2042 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2044 t.storageLock.RUnlock()
2048 t.updatePiecePriority(index)
2049 t.pieceHashed(index, correct, copyErr)
2050 t.publishPieceChange(index)
2051 t.activePieceHashes--
2052 t.tryCreateMorePieceHashers()
2055 // Return the connections that touched a piece, and clear the entries while doing it.
2056 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2058 for c := range p.dirtiers {
2059 delete(c.peerTouchedPieces, pi)
2060 delete(p.dirtiers, c)
2064 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2065 t.iterPeers(func(p *Peer) {
2066 ret = append(ret, p)
2071 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2072 piece := t.piece(pieceIndex)
2073 if piece.queuedForHash() {
2076 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2077 t.publishPieceChange(pieceIndex)
2078 t.updatePiecePriority(pieceIndex)
2079 t.tryCreateMorePieceHashers()
2082 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2083 // before the Info is available.
2084 func (t *Torrent) VerifyData() {
2085 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2086 t.Piece(i).VerifyData()
2090 // Start the process of connecting to the given peer for the given torrent if appropriate.
2091 func (t *Torrent) initiateConn(peer PeerInfo) {
2092 if peer.Id == t.cl.peerID {
2095 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2099 if t.addrActive(addr.String()) {
2103 t.halfOpen[addr.String()] = peer
2104 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2107 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2108 // quickly make one Client visible to the Torrent of another Client.
2109 func (t *Torrent) AddClientPeer(cl *Client) int {
2110 return t.AddPeers(func() (ps []PeerInfo) {
2111 for _, la := range cl.ListenAddrs() {
2112 ps = append(ps, PeerInfo{
2121 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2123 func (t *Torrent) allStats(f func(*ConnStats)) {
2128 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2129 return t.pieces[i].hashing
2132 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2133 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2136 func (t *Torrent) dialTimeout() time.Duration {
2137 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2140 func (t *Torrent) piece(i int) *Piece {
2144 func (t *Torrent) onWriteChunkErr(err error) {
2145 if t.userOnWriteChunkErr != nil {
2146 go t.userOnWriteChunkErr(err)
2149 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2150 t.disallowDataDownloadLocked()
2153 func (t *Torrent) DisallowDataDownload() {
2154 t.disallowDataDownloadLocked()
2157 func (t *Torrent) disallowDataDownloadLocked() {
2158 t.dataDownloadDisallowed.Set()
2161 func (t *Torrent) AllowDataDownload() {
2162 t.dataDownloadDisallowed.Clear()
2165 // Enables uploading data, if it was disabled.
2166 func (t *Torrent) AllowDataUpload() {
2169 t.dataUploadDisallowed = false
2170 for c := range t.conns {
2175 // Disables uploading data, if it was enabled.
2176 func (t *Torrent) DisallowDataUpload() {
2179 t.dataUploadDisallowed = true
2180 for c := range t.conns {
2185 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2186 // or if nil, a critical message is logged, and data download is disabled.
2187 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2190 t.userOnWriteChunkErr = f
2193 func (t *Torrent) iterPeers(f func(p *Peer)) {
2194 for pc := range t.conns {
2197 for _, ws := range t.webSeeds {
2202 func (t *Torrent) callbacks() *Callbacks {
2203 return &t.cl.config.Callbacks
2206 var WebseedHttpClient = &http.Client{
2207 Transport: &http.Transport{
2208 MaxConnsPerHost: 10,
2212 func (t *Torrent) addWebSeed(url string) {
2213 if t.cl.config.DisableWebseeds {
2216 if _, ok := t.webSeeds[url]; ok {
2219 const maxRequests = 10
2225 reconciledHandshakeStats: true,
2226 // TODO: Raise this limit, and instead limit concurrent fetches.
2227 PeerMaxRequests: 32,
2228 RemoteAddr: remoteAddrFromUrl(url),
2229 callbacks: t.callbacks(),
2231 client: webseed.Client{
2232 // Consider a MaxConnsPerHost in the transport for this, possibly in a global Client.
2233 HttpClient: WebseedHttpClient,
2236 activeRequests: make(map[Request]webseed.Request, maxRequests),
2238 ws.requesterCond.L = t.cl.locker()
2239 for range iter.N(maxRequests) {
2242 for _, f := range t.callbacks().NewPeer {
2245 ws.peer.logger = t.logger.WithContextValue(&ws)
2246 ws.peer.peerImpl = &ws
2248 ws.onGotInfo(t.info)
2250 t.webSeeds[url] = &ws.peer
2251 ws.peer.onPeerHasAllPieces()
2254 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2255 t.iterPeers(func(p1 *Peer) {