20 "github.com/RoaringBitmap/roaring"
21 "github.com/anacrolix/chansync"
22 "github.com/anacrolix/chansync/events"
23 "github.com/anacrolix/dht/v2"
24 "github.com/anacrolix/log"
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 // Closed when .Info is obtained.
126 gotMetainfoC chan struct{}
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
140 initialPieceCheckDisabled bool
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 pendingRequests
149 // Chunks we've written to since the corresponding piece was last checked.
150 dirtyChunks roaring.Bitmap
154 // Is On when all pieces are complete.
155 Complete chansync.Flag
158 func (t *Torrent) pieceAvailabilityFromPeers(i pieceIndex) (count int) {
159 t.iterPeers(func(peer *Peer) {
160 if peer.peerHasPiece(i) {
167 func (t *Torrent) decPieceAvailability(i pieceIndex) {
172 if p.availability <= 0 {
173 panic(p.availability)
178 func (t *Torrent) incPieceAvailability(i pieceIndex) {
179 // If we don't the info, this should be reconciled when we do.
186 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
187 return t._readerNowPieces
190 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
191 return t._readerReadaheadPieces
194 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
195 return !t.wantPieceIndex(i)
198 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
199 return &t._pendingPieces
202 // Returns a channel that is closed when the Torrent is closed.
203 func (t *Torrent) Closed() events.Done {
204 return t.closed.Done()
207 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
208 // pending, and half-open peers.
209 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
210 // Add pending peers to the list
211 t.peers.Each(func(peer PeerInfo) {
212 ks = append(ks, peer)
215 // Add half-open peers to the list
216 for _, peer := range t.halfOpen {
217 ks = append(ks, peer)
220 // Add active peers to the list
221 for conn := range t.conns {
223 ks = append(ks, PeerInfo{
225 Addr: conn.RemoteAddr,
226 Source: conn.Discovery,
227 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
228 // > But if we're not connected to them with an encrypted connection, I couldn't say
229 // > what's appropriate. We can carry forward the SupportsEncryption value as we
230 // > received it from trackers/DHT/PEX, or just use the encryption state for the
231 // > connection. It's probably easiest to do the latter for now.
232 // https://github.com/anacrolix/torrent/pull/188
233 SupportsEncryption: conn.headerEncrypted,
240 func (t *Torrent) setChunkSize(size pp.Integer) {
242 t.chunkPool = sync.Pool{
243 New: func() interface{} {
244 b := make([]byte, size)
250 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
251 return t._completedPieces.Contains(bitmap.BitIndex(piece))
254 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
255 return t.pieces[piece].Storage().Completion()
258 // There's a connection to that address already.
259 func (t *Torrent) addrActive(addr string) bool {
260 if _, ok := t.halfOpen[addr]; ok {
263 for c := range t.conns {
265 if ra.String() == addr {
272 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
273 for c := range t.conns {
274 if !c.closed.IsSet() {
281 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
283 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
284 if t.closed.IsSet() {
287 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
288 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
289 torrent.Add("peers not added because of bad addr", 1)
290 // cl.logger.Printf("peers not added because of bad addr: %v", p)
294 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
295 torrent.Add("peers replaced", 1)
296 if !replaced.equal(p) {
297 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
304 for t.peers.Len() > cl.config.TorrentPeersHighWater {
305 _, ok := t.peers.DeleteMin()
307 torrent.Add("excess reserve peers discarded", 1)
313 func (t *Torrent) invalidateMetadata() {
314 for i := 0; i < len(t.metadataCompletedChunks); i++ {
315 t.metadataCompletedChunks[i] = false
318 t.gotMetainfoC = make(chan struct{})
323 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
327 if index >= len(t.metadataCompletedChunks) {
328 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
331 copy(t.metadataBytes[(1<<14)*index:], data)
332 t.metadataCompletedChunks[index] = true
335 func (t *Torrent) metadataPieceCount() int {
336 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
339 func (t *Torrent) haveMetadataPiece(piece int) bool {
341 return (1<<14)*piece < len(t.metadataBytes)
343 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
347 func (t *Torrent) metadataSize() int {
348 return len(t.metadataBytes)
351 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
352 for i := 0; i < len(info.Pieces); i += sha1.Size {
353 ret = append(ret, info.Pieces[i:i+sha1.Size])
358 func (t *Torrent) makePieces() {
359 hashes := infoPieceHashes(t.info)
360 t.pieces = make([]Piece, len(hashes))
361 for i, hash := range hashes {
362 piece := &t.pieces[i]
364 piece.index = pieceIndex(i)
365 piece.noPendingWrites.L = &piece.pendingWritesMutex
366 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
368 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
369 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
370 piece.files = files[beginFile:endFile]
374 // Returns the index of the first file containing the piece. files must be
375 // ordered by offset.
376 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
377 for i, f := range files {
378 if f.offset+f.length > pieceOffset {
385 // Returns the index after the last file containing the piece. files must be
386 // ordered by offset.
387 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
388 for i, f := range files {
389 if f.offset+f.length >= pieceEndOffset {
396 func (t *Torrent) cacheLength() {
398 for _, f := range t.info.UpvertedFiles() {
404 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
406 func (t *Torrent) setInfo(info *metainfo.Info) error {
407 if err := validateInfo(info); err != nil {
408 return fmt.Errorf("bad info: %s", err)
410 if t.storageOpener != nil {
412 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
414 return fmt.Errorf("error opening torrent storage: %s", err)
421 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
422 t.displayName = "" // Save a few bytes lol.
429 // This seems to be all the follow-up tasks after info is set, that can't fail.
430 func (t *Torrent) onSetInfo() {
431 for i := range t.pieces {
433 // Need to add availability before updating piece completion, as that may result in conns
435 if p.availability != 0 {
436 panic(p.availability)
438 p.availability = int64(t.pieceAvailabilityFromPeers(i))
439 t.updatePieceCompletion(pieceIndex(i))
440 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
441 // t.logger.Printf("piece %s completion unknown, queueing check", p)
442 t.queuePieceCheck(pieceIndex(i))
445 t.cl.event.Broadcast()
446 close(t.gotMetainfoC)
447 t.updateWantPeersEvent()
448 t.pendingRequests.Init(t.numRequests())
449 t.tryCreateMorePieceHashers()
450 t.iterPeers(func(p *Peer) {
452 p.updateRequests("onSetInfo")
456 // Called when metadata for a torrent becomes available.
457 func (t *Torrent) setInfoBytesLocked(b []byte) error {
458 if metainfo.HashBytes(b) != t.infoHash {
459 return errors.New("info bytes have wrong hash")
461 var info metainfo.Info
462 if err := bencode.Unmarshal(b, &info); err != nil {
463 return fmt.Errorf("error unmarshalling info bytes: %s", err)
466 t.metadataCompletedChunks = nil
470 if err := t.setInfo(&info); err != nil {
477 func (t *Torrent) haveAllMetadataPieces() bool {
481 if t.metadataCompletedChunks == nil {
484 for _, have := range t.metadataCompletedChunks {
492 // TODO: Propagate errors to disconnect peer.
493 func (t *Torrent) setMetadataSize(size int) (err error) {
495 // We already know the correct metadata size.
498 if uint32(size) > maxMetadataSize {
499 return errors.New("bad size")
501 if len(t.metadataBytes) == size {
504 t.metadataBytes = make([]byte, size)
505 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
506 t.metadataChanged.Broadcast()
507 for c := range t.conns {
508 c.requestPendingMetadata()
513 // The current working name for the torrent. Either the name in the info dict,
514 // or a display name given such as by the dn value in a magnet link, or "".
515 func (t *Torrent) name() string {
517 defer t.nameMu.RUnlock()
521 if t.displayName != "" {
524 return "infohash:" + t.infoHash.HexString()
527 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
528 p := &t.pieces[index]
529 ret.Priority = t.piecePriority(index)
530 ret.Completion = p.completion()
531 ret.QueuedForHash = p.queuedForHash()
532 ret.Hashing = p.hashing
533 ret.Checking = ret.QueuedForHash || ret.Hashing
534 ret.Marking = p.marking
535 if !ret.Complete && t.piecePartiallyDownloaded(index) {
541 func (t *Torrent) metadataPieceSize(piece int) int {
542 return metadataPieceSize(len(t.metadataBytes), piece)
545 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
548 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
549 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
551 TotalSize: len(t.metadataBytes),
557 type pieceAvailabilityRun struct {
562 func (me pieceAvailabilityRun) String() string {
563 return fmt.Sprintf("%v(%v)", me.count, me.availability)
566 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
567 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
568 ret = append(ret, pieceAvailabilityRun{availability: el.(int64), count: int(count)})
570 for i := range t.pieces {
571 rle.Append(t.pieces[i].availability, 1)
577 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
578 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
579 ret = append(ret, PieceStateRun{
580 PieceState: el.(PieceState),
584 for index := range t.pieces {
585 rle.Append(t.pieceState(pieceIndex(index)), 1)
591 // Produces a small string representing a PieceStateRun.
592 func (psr PieceStateRun) String() (ret string) {
593 ret = fmt.Sprintf("%d", psr.Length)
594 ret += func() string {
595 switch psr.Priority {
596 case PiecePriorityNext:
598 case PiecePriorityNormal:
600 case PiecePriorityReadahead:
602 case PiecePriorityNow:
604 case PiecePriorityHigh:
613 if psr.QueuedForHash {
631 func (t *Torrent) writeStatus(w io.Writer) {
632 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
633 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
635 fmt.Fprintf(w, "Metadata have: ")
636 for _, h := range t.metadataCompletedChunks {
637 fmt.Fprintf(w, "%c", func() rune {
647 fmt.Fprintf(w, "Piece length: %s\n",
650 return fmt.Sprintf("%v (%v chunks)",
652 float64(t.usualPieceSize())/float64(t.chunkSize))
659 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
660 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
661 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
662 for _, run := range t.pieceAvailabilityRuns() {
663 ret = append(ret, run.String())
668 fmt.Fprintf(w, "Reader Pieces:")
669 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
670 fmt.Fprintf(w, " %d:%d", begin, end)
675 fmt.Fprintf(w, "Enabled trackers:\n")
677 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
678 fmt.Fprintf(tw, " URL\tExtra\n")
679 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
682 var luns, runs url.URL = *lu, *ru
685 var ml missinggo.MultiLess
686 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
687 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
689 }).([]torrentTrackerAnnouncer) {
690 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
695 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
697 spew.NewDefaultConfig()
698 spew.Fdump(w, t.statsLocked())
700 peers := t.peersAsSlice()
701 sort.Slice(peers, func(_i, _j int) bool {
704 if less, ok := multiless.New().EagerSameLess(
705 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
709 return worseConn(i, j)
711 for i, c := range peers {
712 fmt.Fprintf(w, "%2d. ", i+1)
717 func (t *Torrent) haveInfo() bool {
721 // Returns a run-time generated MetaInfo that includes the info bytes and
722 // announce-list as currently known to the client.
723 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
724 return metainfo.MetaInfo{
725 CreationDate: time.Now().Unix(),
726 Comment: "dynamic metainfo from client",
727 CreatedBy: "go.torrent",
728 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
729 InfoBytes: func() []byte {
731 return t.metadataBytes
736 UrlList: func() []string {
737 ret := make([]string, 0, len(t.webSeeds))
738 for url := range t.webSeeds {
739 ret = append(ret, url)
747 func (t *Torrent) BytesMissing() (n int64) {
749 n = t.bytesMissingLocked()
754 func (t *Torrent) bytesMissingLocked() int64 {
758 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
759 roaring.Flip(b, 0, end).Iterate(cb)
762 func (t *Torrent) bytesLeft() (left int64) {
763 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
764 p := t.piece(pieceIndex(x))
765 left += int64(p.length() - p.numDirtyBytes())
771 // Bytes left to give in tracker announces.
772 func (t *Torrent) bytesLeftAnnounce() int64 {
780 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
781 if t.pieceComplete(piece) {
784 if t.pieceAllDirty(piece) {
787 return t.pieces[piece].hasDirtyChunks()
790 func (t *Torrent) usualPieceSize() int {
791 return int(t.info.PieceLength)
794 func (t *Torrent) numPieces() pieceIndex {
795 return pieceIndex(t.info.NumPieces())
798 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
799 return pieceIndex(t._completedPieces.GetCardinality())
802 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
804 if t.storage != nil {
809 defer t.storageLock.Unlock()
810 if f := t.storage.Close; f != nil {
813 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
818 t.iterPeers(func(p *Peer) {
822 t.cl.event.Broadcast()
823 t.pieceStateChanges.Close()
824 t.updateWantPeersEvent()
828 func (t *Torrent) requestOffset(r Request) int64 {
829 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
832 // Return the request that would include the given offset into the torrent data. Returns !ok if
833 // there is no such request.
834 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
835 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
838 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
839 defer perf.ScopeTimerErr(&err)()
840 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
841 if err == nil && n != len(data) {
842 err = io.ErrShortWrite
847 func (t *Torrent) bitfield() (bf []bool) {
848 bf = make([]bool, t.numPieces())
849 t._completedPieces.Iterate(func(piece uint32) (again bool) {
856 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
857 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
860 func (t *Torrent) chunksPerRegularPiece() uint32 {
861 return uint32((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
864 func (t *Torrent) numRequests() RequestIndex {
865 if t.numPieces() == 0 {
868 return uint32(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
871 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
872 t.dirtyChunks.RemoveRange(
873 uint64(t.pieceRequestIndexOffset(pieceIndex)),
874 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
877 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
878 if t.info.PieceLength == 0 {
879 // There will be no variance amongst pieces. Only pain.
882 if piece == t.numPieces()-1 {
883 ret := pp.Integer(*t.length % t.info.PieceLength)
888 return pp.Integer(t.info.PieceLength)
891 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
893 p.waitNoPendingWrites()
894 storagePiece := t.pieces[piece].Storage()
896 //Does the backend want to do its own hashing?
897 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
898 var sum metainfo.Hash
899 //log.Printf("A piece decided to self-hash: %d", piece)
900 sum, err = i.SelfHash()
901 missinggo.CopyExact(&ret, sum)
905 hash := pieceHash.New()
906 const logPieceContents = false
907 if logPieceContents {
908 var examineBuf bytes.Buffer
909 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
910 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
912 _, err = storagePiece.WriteTo(hash)
914 missinggo.CopyExact(&ret, hash.Sum(nil))
918 func (t *Torrent) haveAnyPieces() bool {
919 return t._completedPieces.GetCardinality() != 0
922 func (t *Torrent) haveAllPieces() bool {
926 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
929 func (t *Torrent) havePiece(index pieceIndex) bool {
930 return t.haveInfo() && t.pieceComplete(index)
933 func (t *Torrent) maybeDropMutuallyCompletePeer(
934 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
938 if !t.cl.config.DropMutuallyCompletePeers {
941 if !t.haveAllPieces() {
944 if all, known := p.peerHasAllPieces(); !(known && all) {
950 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
954 func (t *Torrent) haveChunk(r Request) (ret bool) {
956 // log.Println("have chunk", r, ret)
961 if t.pieceComplete(pieceIndex(r.Index)) {
964 p := &t.pieces[r.Index]
965 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
968 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
969 return chunkIndexType(cs.Begin / chunkSize)
972 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
973 // TODO: Are these overly conservative, should we be guarding this here?
978 if index < 0 || index >= t.numPieces() {
982 p := &t.pieces[index]
983 if p.queuedForHash() {
989 if t.pieceComplete(index) {
992 if t._pendingPieces.Contains(int(index)) {
995 // t.logger.Printf("piece %d not pending", index)
996 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
997 return index < begin || index >= end
1001 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1002 // conns (which is a map).
1003 var peerConnSlices sync.Pool
1005 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1006 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1007 // established connections for more than a minute. This is O(n log n). If there was a way to not
1008 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1009 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1011 getInterface := peerConnSlices.Get()
1012 if getInterface == nil {
1013 sl = make([]*PeerConn, 0, len(t.conns))
1015 sl = getInterface.([]*PeerConn)[:0]
1017 sl = t.appendUnclosedConns(sl)
1018 defer peerConnSlices.Put(sl)
1019 wcs := worseConnSlice{sl}
1021 for wcs.Len() != 0 {
1022 c := heap.Pop(&wcs).(*PeerConn)
1023 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1026 // If the connection is in the worst half of the established
1027 // connection quota and is older than a minute.
1028 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1029 // Give connections 1 minute to prove themselves.
1030 if time.Since(c.completedHandshake) > time.Minute {
1038 type PieceStateChange struct {
1043 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1044 t.cl._mu.Defer(func() {
1045 cur := t.pieceState(piece)
1046 p := &t.pieces[piece]
1047 if cur != p.publicPieceState {
1048 p.publicPieceState = cur
1049 t.pieceStateChanges.Publish(PieceStateChange{
1057 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1058 if t.pieceComplete(piece) {
1061 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1064 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1065 return t.pieces[piece].allChunksDirty()
1068 func (t *Torrent) readersChanged() {
1069 t.updateReaderPieces()
1070 t.updateAllPiecePriorities("Torrent.readersChanged")
1073 func (t *Torrent) updateReaderPieces() {
1074 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1077 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1081 t.updateReaderPieces()
1082 // Order the ranges, high and low.
1084 if l.begin > h.begin {
1087 if l.end < h.begin {
1088 // Two distinct ranges.
1089 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1090 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1097 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1101 func (t *Torrent) maybeNewConns() {
1102 // Tickle the accept routine.
1103 t.cl.event.Broadcast()
1107 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1108 if t._pendingPieces.Contains(piece) {
1109 t.iterPeers(func(c *Peer) {
1110 c.updateRequests(reason)
1114 t.publishPieceChange(piece)
1117 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1118 p := &t.pieces[piece]
1119 newPrio := p.uncachedPriority()
1120 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1121 if newPrio == PiecePriorityNone {
1122 if !t._pendingPieces.Remove(int(piece)) {
1126 if !t._pendingPieces.Set(int(piece), newPrio.BitmapPriority()) {
1130 t.piecePriorityChanged(piece, reason)
1133 func (t *Torrent) updateAllPiecePriorities(reason string) {
1134 t.updatePiecePriorities(0, t.numPieces(), reason)
1137 // Update all piece priorities in one hit. This function should have the same
1138 // output as updatePiecePriority, but across all pieces.
1139 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1140 for i := begin; i < end; i++ {
1141 t.updatePiecePriority(i, reason)
1145 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1146 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1147 if off >= *t.length {
1157 begin = pieceIndex(off / t.info.PieceLength)
1158 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1159 if end > pieceIndex(t.info.NumPieces()) {
1160 end = pieceIndex(t.info.NumPieces())
1165 // Returns true if all iterations complete without breaking. Returns the read regions for all
1166 // readers. The reader regions should not be merged as some callers depend on this method to
1167 // enumerate readers.
1168 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1169 for r := range t.readers {
1171 if p.begin >= p.end {
1174 if !f(p.begin, p.end) {
1181 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1182 prio, ok := t._pendingPieces.GetPriority(piece)
1184 return PiecePriorityNone
1189 ret := piecePriority(-prio)
1190 if ret == PiecePriorityNone {
1196 func (t *Torrent) pendRequest(req RequestIndex) {
1197 t.piece(int(req / t.chunksPerRegularPiece())).pendChunkIndex(req % t.chunksPerRegularPiece())
1200 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1201 t.cl.event.Broadcast()
1202 if t.pieceComplete(piece) {
1203 t.onPieceCompleted(piece)
1205 t.onIncompletePiece(piece)
1207 t.updatePiecePriority(piece, reason)
1210 func (t *Torrent) numReceivedConns() (ret int) {
1211 for c := range t.conns {
1212 if c.Discovery == PeerSourceIncoming {
1219 func (t *Torrent) maxHalfOpen() int {
1220 // Note that if we somehow exceed the maximum established conns, we want
1221 // the negative value to have an effect.
1222 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1223 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1224 // We want to allow some experimentation with new peers, and to try to
1225 // upset an oversupply of received connections.
1226 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1229 func (t *Torrent) openNewConns() (initiated int) {
1230 defer t.updateWantPeersEvent()
1231 for t.peers.Len() != 0 {
1235 if len(t.halfOpen) >= t.maxHalfOpen() {
1238 if len(t.cl.dialers) == 0 {
1241 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1244 p := t.peers.PopMax()
1251 func (t *Torrent) getConnPieceInclination() []int {
1252 _ret := t.connPieceInclinationPool.Get()
1254 pieceInclinationsNew.Add(1)
1255 return rand.Perm(int(t.numPieces()))
1257 pieceInclinationsReused.Add(1)
1258 return *_ret.(*[]int)
1261 func (t *Torrent) putPieceInclination(pi []int) {
1262 t.connPieceInclinationPool.Put(&pi)
1263 pieceInclinationsPut.Add(1)
1266 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1268 uncached := t.pieceCompleteUncached(piece)
1269 cached := p.completion()
1270 changed := cached != uncached
1271 complete := uncached.Complete
1272 p.storageCompletionOk = uncached.Ok
1275 t._completedPieces.Add(x)
1277 t._completedPieces.Remove(x)
1280 if complete && len(p.dirtiers) != 0 {
1281 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1284 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1285 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1290 // Non-blocking read. Client lock is not required.
1291 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1293 p := &t.pieces[off/t.info.PieceLength]
1294 p.waitNoPendingWrites()
1296 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1307 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1308 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1309 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1310 func (t *Torrent) maybeCompleteMetadata() error {
1315 if !t.haveAllMetadataPieces() {
1316 // Don't have enough metadata pieces.
1319 err := t.setInfoBytesLocked(t.metadataBytes)
1321 t.invalidateMetadata()
1322 return fmt.Errorf("error setting info bytes: %s", err)
1324 if t.cl.config.Debug {
1325 t.logger.Printf("%s: got metadata from peers", t)
1330 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1331 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1333 now.Add(bitmap.BitIndex(begin))
1334 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1341 func (t *Torrent) needData() bool {
1342 if t.closed.IsSet() {
1348 return t._pendingPieces.Len() != 0
1351 func appendMissingStrings(old, new []string) (ret []string) {
1354 for _, n := range new {
1355 for _, o := range old {
1360 ret = append(ret, n)
1365 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1367 for minNumTiers > len(ret) {
1368 ret = append(ret, nil)
1373 func (t *Torrent) addTrackers(announceList [][]string) {
1374 fullAnnounceList := &t.metainfo.AnnounceList
1375 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1376 for tierIndex, trackerURLs := range announceList {
1377 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1379 t.startMissingTrackerScrapers()
1380 t.updateWantPeersEvent()
1383 // Don't call this before the info is available.
1384 func (t *Torrent) bytesCompleted() int64 {
1388 return *t.length - t.bytesLeft()
1391 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1394 return t.setInfoBytesLocked(b)
1397 // Returns true if connection is removed from torrent.Conns.
1398 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1399 if !c.closed.IsSet() {
1400 panic("connection is not closed")
1401 // There are behaviours prevented by the closed state that will fail
1402 // if the connection has been deleted.
1406 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1407 // the drop event against the PexConnState instead.
1409 if !t.cl.config.DisablePEX {
1413 torrent.Add("deleted connections", 1)
1414 c.deleteAllRequests()
1415 if t.numActivePeers() == 0 && t.haveInfo() {
1416 t.assertNoPendingRequests()
1421 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1425 p.newPeerPieces().Iterate(func(i uint32) bool {
1426 p.t.decPieceAvailability(pieceIndex(i))
1431 func (t *Torrent) numActivePeers() (num int) {
1432 t.iterPeers(func(*Peer) {
1438 func (t *Torrent) assertNoPendingRequests() {
1439 t.pendingRequests.AssertEmpty()
1442 func (t *Torrent) dropConnection(c *PeerConn) {
1443 t.cl.event.Broadcast()
1445 if t.deletePeerConn(c) {
1450 func (t *Torrent) wantPeers() bool {
1451 if t.closed.IsSet() {
1454 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1457 return t.needData() || t.seeding()
1460 func (t *Torrent) updateWantPeersEvent() {
1462 t.wantPeersEvent.Set()
1464 t.wantPeersEvent.Clear()
1468 // Returns whether the client should make effort to seed the torrent.
1469 func (t *Torrent) seeding() bool {
1471 if t.closed.IsSet() {
1474 if t.dataUploadDisallowed {
1477 if cl.config.NoUpload {
1480 if !cl.config.Seed {
1483 if cl.config.DisableAggressiveUpload && t.needData() {
1489 func (t *Torrent) onWebRtcConn(
1490 c datachannel.ReadWriteCloser,
1491 dcc webtorrent.DataChannelContext,
1494 pc, err := t.cl.initiateProtocolHandshakes(
1495 context.Background(),
1496 webrtcNetConn{c, dcc},
1500 webrtcNetAddr{dcc.Remote},
1502 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1505 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1508 if dcc.LocalOffered {
1509 pc.Discovery = PeerSourceTracker
1511 pc.Discovery = PeerSourceIncoming
1515 err = t.cl.runHandshookConn(pc, t)
1517 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1521 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1522 err := t.cl.runHandshookConn(pc, t)
1523 if err != nil || logAll {
1524 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1528 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1529 t.logRunHandshookConn(pc, false, log.Warning)
1532 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1533 wtc, release := t.cl.websocketTrackers.Get(u.String())
1538 wst := websocketTrackerStatus{u, wtc}
1540 err := wtc.Announce(tracker.Started, t.infoHash)
1542 t.logger.WithDefaultLevel(log.Warning).Printf(
1543 "error in initial announce to %q: %v",
1552 func (t *Torrent) startScrapingTracker(_url string) {
1556 u, err := url.Parse(_url)
1558 // URLs with a leading '*' appear to be a uTorrent convention to
1559 // disable trackers.
1561 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1565 if u.Scheme == "udp" {
1567 t.startScrapingTracker(u.String())
1569 t.startScrapingTracker(u.String())
1572 if _, ok := t.trackerAnnouncers[_url]; ok {
1575 sl := func() torrentTrackerAnnouncer {
1578 if t.cl.config.DisableWebtorrent {
1581 return t.startWebsocketAnnouncer(*u)
1583 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1587 if t.cl.config.DisableIPv6 {
1591 newAnnouncer := &trackerScraper{
1595 go newAnnouncer.Run()
1601 if t.trackerAnnouncers == nil {
1602 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1604 t.trackerAnnouncers[_url] = sl
1607 // Adds and starts tracker scrapers for tracker URLs that aren't already
1609 func (t *Torrent) startMissingTrackerScrapers() {
1610 if t.cl.config.DisableTrackers {
1613 t.startScrapingTracker(t.metainfo.Announce)
1614 for _, tier := range t.metainfo.AnnounceList {
1615 for _, url := range tier {
1616 t.startScrapingTracker(url)
1621 // Returns an AnnounceRequest with fields filled out to defaults and current
1623 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1624 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1625 // dependent on the network in use.
1626 return tracker.AnnounceRequest{
1628 NumWant: func() int32 {
1629 if t.wantPeers() && len(t.cl.dialers) > 0 {
1635 Port: uint16(t.cl.incomingPeerPort()),
1636 PeerId: t.cl.peerID,
1637 InfoHash: t.infoHash,
1638 Key: t.cl.announceKey(),
1640 // The following are vaguely described in BEP 3.
1642 Left: t.bytesLeftAnnounce(),
1643 Uploaded: t.stats.BytesWrittenData.Int64(),
1644 // There's no mention of wasted or unwanted download in the BEP.
1645 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1649 // Adds peers revealed in an announce until the announce ends, or we have
1651 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1653 for v := range pvs {
1656 for _, cp := range v.Peers {
1658 // Can't do anything with this.
1661 if t.addPeer(PeerInfo{
1662 Addr: ipPortAddr{cp.IP, cp.Port},
1663 Source: PeerSourceDhtGetPeers,
1670 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1675 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1676 // announce ends. stop will force the announce to end.
1677 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1678 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1682 _done := make(chan struct{})
1686 t.consumeDhtAnnouncePeers(ps.Peers())
1692 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1693 _, stop, err := t.AnnounceToDht(s)
1698 case <-t.closed.Done():
1699 case <-time.After(5 * time.Minute):
1705 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1711 if t.closed.IsSet() {
1717 // TODO: Determine if there's a listener on the port we're announcing.
1718 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1729 err := t.timeboxedAnnounceToDht(s)
1731 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1737 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1738 for _, p := range peers {
1746 // The returned TorrentStats may require alignment in memory. See
1747 // https://github.com/anacrolix/torrent/issues/383.
1748 func (t *Torrent) Stats() TorrentStats {
1750 defer t.cl.rUnlock()
1751 return t.statsLocked()
1754 func (t *Torrent) statsLocked() (ret TorrentStats) {
1755 ret.ActivePeers = len(t.conns)
1756 ret.HalfOpenPeers = len(t.halfOpen)
1757 ret.PendingPeers = t.peers.Len()
1758 ret.TotalPeers = t.numTotalPeers()
1759 ret.ConnectedSeeders = 0
1760 for c := range t.conns {
1761 if all, ok := c.peerHasAllPieces(); all && ok {
1762 ret.ConnectedSeeders++
1765 ret.ConnStats = t.stats.Copy()
1766 ret.PiecesComplete = t.numPiecesCompleted()
1770 // The total number of peers in the torrent.
1771 func (t *Torrent) numTotalPeers() int {
1772 peers := make(map[string]struct{})
1773 for conn := range t.conns {
1774 ra := conn.conn.RemoteAddr()
1776 // It's been closed and doesn't support RemoteAddr.
1779 peers[ra.String()] = struct{}{}
1781 for addr := range t.halfOpen {
1782 peers[addr] = struct{}{}
1784 t.peers.Each(func(peer PeerInfo) {
1785 peers[peer.Addr.String()] = struct{}{}
1790 // Reconcile bytes transferred before connection was associated with a
1792 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1793 if c._stats != (ConnStats{
1794 // Handshakes should only increment these fields:
1795 BytesWritten: c._stats.BytesWritten,
1796 BytesRead: c._stats.BytesRead,
1800 c.postHandshakeStats(func(cs *ConnStats) {
1801 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1802 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1804 c.reconciledHandshakeStats = true
1807 // Returns true if the connection is added.
1808 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1811 torrent.Add("added connections", 1)
1814 if t.closed.IsSet() {
1815 return errors.New("torrent closed")
1817 for c0 := range t.conns {
1818 if c.PeerID != c0.PeerID {
1821 if !t.cl.config.DropDuplicatePeerIds {
1824 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1826 t.deletePeerConn(c0)
1828 return errors.New("existing connection preferred")
1831 if len(t.conns) >= t.maxEstablishedConns {
1832 c := t.worstBadConn()
1834 return errors.New("don't want conns")
1839 if len(t.conns) >= t.maxEstablishedConns {
1842 t.conns[c] = struct{}{}
1843 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1844 t.pex.Add(c) // as no further extended handshake expected
1849 func (t *Torrent) wantConns() bool {
1850 if !t.networkingEnabled.Bool() {
1853 if t.closed.IsSet() {
1856 if !t.seeding() && !t.needData() {
1859 if len(t.conns) < t.maxEstablishedConns {
1862 return t.worstBadConn() != nil
1865 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1868 oldMax = t.maxEstablishedConns
1869 t.maxEstablishedConns = max
1870 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1871 return worseConn(&l.Peer, &r.Peer)
1873 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1874 t.dropConnection(wcs.Pop().(*PeerConn))
1880 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1881 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1884 t.cl.event.Broadcast()
1885 if t.closed.IsSet() {
1889 // Don't score the first time a piece is hashed, it could be an initial check.
1890 if p.storageCompletionOk {
1892 pieceHashedCorrect.Add(1)
1895 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1896 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1897 pieceHashedNotCorrect.Add(1)
1902 t.publishPieceChange(piece)
1905 t.publishPieceChange(piece)
1909 if len(p.dirtiers) != 0 {
1910 // Don't increment stats above connection-level for every involved connection.
1911 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1913 for c := range p.dirtiers {
1914 c._stats.incrementPiecesDirtiedGood()
1916 t.clearPieceTouchers(piece)
1918 err := p.Storage().MarkComplete()
1920 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1924 if t.closed.IsSet() {
1927 t.pendAllChunkSpecs(piece)
1929 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1930 // Peers contributed to all the data for this piece hash failure, and the failure was
1931 // not due to errors in the storage (such as data being dropped in a cache).
1933 // Increment Torrent and above stats, and then specific connections.
1934 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1935 for c := range p.dirtiers {
1936 // Y u do dis peer?!
1937 c.stats().incrementPiecesDirtiedBad()
1940 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1941 for c := range p.dirtiers {
1943 bannableTouchers = append(bannableTouchers, c)
1946 t.clearPieceTouchers(piece)
1947 slices.Sort(bannableTouchers, connLessTrusted)
1949 if t.cl.config.Debug {
1951 "bannable conns by trust for piece %d: %v",
1953 func() (ret []connectionTrust) {
1954 for _, c := range bannableTouchers {
1955 ret = append(ret, c.trust())
1962 if len(bannableTouchers) >= 1 {
1963 c := bannableTouchers[0]
1964 t.cl.banPeerIP(c.remoteIp())
1968 t.onIncompletePiece(piece)
1969 p.Storage().MarkNotComplete()
1971 t.updatePieceCompletion(piece)
1974 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1975 // TODO: Make faster
1976 for cn := range t.conns {
1981 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1982 t.pendAllChunkSpecs(piece)
1983 t.cancelRequestsForPiece(piece)
1984 t.piece(piece).readerCond.Broadcast()
1985 for conn := range t.conns {
1987 t.maybeDropMutuallyCompletePeer(&conn.Peer)
1991 // Called when a piece is found to be not complete.
1992 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1993 if t.pieceAllDirty(piece) {
1994 t.pendAllChunkSpecs(piece)
1996 if !t.wantPieceIndex(piece) {
1997 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2000 // We could drop any connections that we told we have a piece that we
2001 // don't here. But there's a test failure, and it seems clients don't care
2002 // if you request pieces that you already claim to have. Pruning bad
2003 // connections might just remove any connections that aren't treating us
2004 // favourably anyway.
2006 // for c := range t.conns {
2007 // if c.sentHave(piece) {
2011 t.iterPeers(func(conn *Peer) {
2012 if conn.peerHasPiece(piece) {
2013 conn.updateRequests("piece incomplete")
2018 func (t *Torrent) tryCreateMorePieceHashers() {
2019 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2023 func (t *Torrent) tryCreatePieceHasher() bool {
2024 if t.storage == nil {
2027 pi, ok := t.getPieceToHash()
2032 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2034 t.publishPieceChange(pi)
2035 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2036 t.storageLock.RLock()
2037 t.activePieceHashes++
2038 go t.pieceHasher(pi)
2042 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2043 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2044 if t.piece(i).hashing {
2054 func (t *Torrent) pieceHasher(index pieceIndex) {
2056 sum, copyErr := t.hashPiece(index)
2057 correct := sum == *p.hash
2061 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2063 t.storageLock.RUnlock()
2067 t.pieceHashed(index, correct, copyErr)
2068 t.updatePiecePriority(index, "Torrent.pieceHasher")
2069 t.activePieceHashes--
2070 t.tryCreateMorePieceHashers()
2073 // Return the connections that touched a piece, and clear the entries while doing it.
2074 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2076 for c := range p.dirtiers {
2077 delete(c.peerTouchedPieces, pi)
2078 delete(p.dirtiers, c)
2082 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2083 t.iterPeers(func(p *Peer) {
2084 ret = append(ret, p)
2089 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2090 piece := t.piece(pieceIndex)
2091 if piece.queuedForHash() {
2094 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2095 t.publishPieceChange(pieceIndex)
2096 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2097 t.tryCreateMorePieceHashers()
2100 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2101 // before the Info is available.
2102 func (t *Torrent) VerifyData() {
2103 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2104 t.Piece(i).VerifyData()
2108 // Start the process of connecting to the given peer for the given torrent if appropriate.
2109 func (t *Torrent) initiateConn(peer PeerInfo) {
2110 if peer.Id == t.cl.peerID {
2113 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2117 if t.addrActive(addr.String()) {
2121 t.halfOpen[addr.String()] = peer
2122 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2125 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2126 // quickly make one Client visible to the Torrent of another Client.
2127 func (t *Torrent) AddClientPeer(cl *Client) int {
2128 return t.AddPeers(func() (ps []PeerInfo) {
2129 for _, la := range cl.ListenAddrs() {
2130 ps = append(ps, PeerInfo{
2139 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2141 func (t *Torrent) allStats(f func(*ConnStats)) {
2146 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2147 return t.pieces[i].hashing
2150 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2151 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2154 func (t *Torrent) dialTimeout() time.Duration {
2155 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2158 func (t *Torrent) piece(i int) *Piece {
2162 func (t *Torrent) onWriteChunkErr(err error) {
2163 if t.userOnWriteChunkErr != nil {
2164 go t.userOnWriteChunkErr(err)
2167 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2168 t.disallowDataDownloadLocked()
2171 func (t *Torrent) DisallowDataDownload() {
2172 t.disallowDataDownloadLocked()
2175 func (t *Torrent) disallowDataDownloadLocked() {
2176 t.dataDownloadDisallowed.Set()
2179 func (t *Torrent) AllowDataDownload() {
2180 t.dataDownloadDisallowed.Clear()
2183 // Enables uploading data, if it was disabled.
2184 func (t *Torrent) AllowDataUpload() {
2187 t.dataUploadDisallowed = false
2188 for c := range t.conns {
2189 c.updateRequests("allow data upload")
2193 // Disables uploading data, if it was enabled.
2194 func (t *Torrent) DisallowDataUpload() {
2197 t.dataUploadDisallowed = true
2198 for c := range t.conns {
2199 c.updateRequests("disallow data upload")
2203 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2204 // or if nil, a critical message is logged, and data download is disabled.
2205 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2208 t.userOnWriteChunkErr = f
2211 func (t *Torrent) iterPeers(f func(p *Peer)) {
2212 for pc := range t.conns {
2215 for _, ws := range t.webSeeds {
2220 func (t *Torrent) callbacks() *Callbacks {
2221 return &t.cl.config.Callbacks
2224 var WebseedHttpClient = &http.Client{
2225 Transport: &http.Transport{
2226 MaxConnsPerHost: 10,
2230 func (t *Torrent) addWebSeed(url string) {
2231 if t.cl.config.DisableWebseeds {
2234 if _, ok := t.webSeeds[url]; ok {
2237 const maxRequests = 10
2243 reconciledHandshakeStats: true,
2244 // TODO: Raise this limit, and instead limit concurrent fetches.
2245 PeerMaxRequests: 32,
2246 RemoteAddr: remoteAddrFromUrl(url),
2247 callbacks: t.callbacks(),
2249 client: webseed.Client{
2250 // Consider a MaxConnsPerHost in the transport for this, possibly in a global Client.
2251 HttpClient: WebseedHttpClient,
2254 activeRequests: make(map[Request]webseed.Request, maxRequests),
2256 ws.requesterCond.L = t.cl.locker()
2257 for i := 0; i < maxRequests; i += 1 {
2260 for _, f := range t.callbacks().NewPeer {
2263 ws.peer.logger = t.logger.WithContextValue(&ws)
2264 ws.peer.peerImpl = &ws
2266 ws.onGotInfo(t.info)
2268 t.webSeeds[url] = &ws.peer
2269 ws.peer.onPeerHasAllPieces()
2272 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2273 t.iterPeers(func(p1 *Peer) {
2281 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2282 index := ri / t.chunksPerRegularPiece()
2285 t.piece(int(index)).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2289 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2290 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + uint32(r.Begin/t.chunkSize)
2293 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2294 return RequestIndex(piece) * t.chunksPerRegularPiece()
2297 func (t *Torrent) updateComplete() {
2298 t.Complete.SetBool(t.haveAllPieces())