18 "github.com/RoaringBitmap/roaring"
19 "github.com/anacrolix/chansync"
20 "github.com/anacrolix/chansync/events"
21 "github.com/anacrolix/dht/v2"
22 "github.com/anacrolix/log"
23 "github.com/anacrolix/missinggo/perf"
24 "github.com/anacrolix/missinggo/pubsub"
25 "github.com/anacrolix/missinggo/slices"
26 "github.com/anacrolix/missinggo/v2"
27 "github.com/anacrolix/missinggo/v2/bitmap"
28 "github.com/anacrolix/multiless"
29 "github.com/anacrolix/sync"
30 "github.com/davecgh/go-spew/spew"
31 "github.com/pion/datachannel"
33 "github.com/anacrolix/torrent/bencode"
34 "github.com/anacrolix/torrent/common"
35 "github.com/anacrolix/torrent/metainfo"
36 pp "github.com/anacrolix/torrent/peer_protocol"
37 "github.com/anacrolix/torrent/segments"
38 "github.com/anacrolix/torrent/storage"
39 "github.com/anacrolix/torrent/tracker"
40 "github.com/anacrolix/torrent/webseed"
41 "github.com/anacrolix/torrent/webtorrent"
44 // Maintains state of torrent within a Client. Many methods should not be called before the info is
45 // available, see .Info and .GotInfo.
47 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
48 // alignment. See #262.
53 networkingEnabled chansync.Flag
54 dataDownloadDisallowed chansync.Flag
55 dataUploadDisallowed bool
56 userOnWriteChunkErr func(error)
58 closed chansync.SetOnce
59 infoHash metainfo.Hash
61 // Values are the piece indices that changed.
62 pieceStateChanges *pubsub.PubSub
63 // The size of chunks to request from peers over the wire. This is
64 // normally 16KiB by convention these days.
67 // Total length of the torrent in bytes. Stored because it's not O(1) to
68 // get this from the info dict.
71 // The storage to open when the info dict becomes available.
72 storageOpener *storage.Client
73 // Storage for torrent data.
74 storage *storage.Torrent
75 // Read-locked for using storage, and write-locked for Closing.
76 storageLock sync.RWMutex
78 // TODO: Only announce stuff is used?
79 metainfo metainfo.MetaInfo
81 // The info dict. nil if we don't have it (yet).
83 fileIndex segments.Index
86 webSeeds map[string]*Peer
88 // Active peer connections, running message stream loops. TODO: Make this
89 // open (not-closed) connections only.
90 conns map[*PeerConn]struct{}
91 maxEstablishedConns int
92 // Set of addrs to which we're attempting to connect. Connections are
93 // half-open until all handshakes are completed.
94 halfOpen map[string]PeerInfo
96 // Reserve of peers to connect to. A peer can be both here and in the
97 // active connections if were told about the peer after connecting with
98 // them. That encourages us to reconnect to peers that are well known in
100 peers prioritizedPeers
101 // Whether we want to know to know more peers.
102 wantPeersEvent missinggo.Event
103 // An announcer for each tracker URL.
104 trackerAnnouncers map[string]torrentTrackerAnnouncer
105 // How many times we've initiated a DHT announce. TODO: Move into stats.
108 // Name used if the info name isn't available. Should be cleared when the
109 // Info does become available.
113 // The bencoded bytes of the info dict. This is actively manipulated if
114 // the info bytes aren't initially available, and we try to fetch them
117 // Each element corresponds to the 16KiB metadata pieces. If true, we have
118 // received that piece.
119 metadataCompletedChunks []bool
120 metadataChanged sync.Cond
122 // Closed when .Info is obtained.
123 gotMetainfoC chan struct{}
125 readers map[*reader]struct{}
126 _readerNowPieces bitmap.Bitmap
127 _readerReadaheadPieces bitmap.Bitmap
129 // A cache of pieces we need to get. Calculated from various piece and
130 // file priorities and completion states elsewhere.
131 _pendingPieces roaring.Bitmap
132 // A cache of completed piece indices.
133 _completedPieces roaring.Bitmap
134 // Pieces that need to be hashed.
135 piecesQueuedForHash bitmap.Bitmap
136 activePieceHashes int
137 initialPieceCheckDisabled bool
139 // Count of each request across active connections.
140 pendingRequests pendingRequests
141 // Chunks we've written to since the corresponding piece was last checked.
142 dirtyChunks roaring.Bitmap
146 // Is On when all pieces are complete.
147 Complete chansync.Flag
150 func (t *Torrent) pieceAvailabilityFromPeers(i pieceIndex) (count int) {
151 t.iterPeers(func(peer *Peer) {
152 if peer.peerHasPiece(i) {
159 func (t *Torrent) decPieceAvailability(i pieceIndex) {
164 if p.availability <= 0 {
165 panic(p.availability)
170 func (t *Torrent) incPieceAvailability(i pieceIndex) {
171 // If we don't the info, this should be reconciled when we do.
178 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
179 return t._readerNowPieces
182 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
183 return t._readerReadaheadPieces
186 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
187 return !t.wantPieceIndex(i)
190 // Returns a channel that is closed when the Torrent is closed.
191 func (t *Torrent) Closed() events.Done {
192 return t.closed.Done()
195 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
196 // pending, and half-open peers.
197 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
198 // Add pending peers to the list
199 t.peers.Each(func(peer PeerInfo) {
200 ks = append(ks, peer)
203 // Add half-open peers to the list
204 for _, peer := range t.halfOpen {
205 ks = append(ks, peer)
208 // Add active peers to the list
209 for conn := range t.conns {
210 ks = append(ks, PeerInfo{
212 Addr: conn.RemoteAddr,
213 Source: conn.Discovery,
214 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
215 // > But if we're not connected to them with an encrypted connection, I couldn't say
216 // > what's appropriate. We can carry forward the SupportsEncryption value as we
217 // > received it from trackers/DHT/PEX, or just use the encryption state for the
218 // > connection. It's probably easiest to do the latter for now.
219 // https://github.com/anacrolix/torrent/pull/188
220 SupportsEncryption: conn.headerEncrypted,
227 func (t *Torrent) setChunkSize(size pp.Integer) {
229 t.chunkPool = sync.Pool{
230 New: func() interface{} {
231 b := make([]byte, size)
237 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
238 return t._completedPieces.Contains(bitmap.BitIndex(piece))
241 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
242 return t.pieces[piece].Storage().Completion()
245 // There's a connection to that address already.
246 func (t *Torrent) addrActive(addr string) bool {
247 if _, ok := t.halfOpen[addr]; ok {
250 for c := range t.conns {
252 if ra.String() == addr {
259 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
260 for c := range t.conns {
261 if !c.closed.IsSet() {
268 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
270 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
271 if t.closed.IsSet() {
274 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
275 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
276 torrent.Add("peers not added because of bad addr", 1)
277 // cl.logger.Printf("peers not added because of bad addr: %v", p)
281 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
282 torrent.Add("peers replaced", 1)
283 if !replaced.equal(p) {
284 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
291 for t.peers.Len() > cl.config.TorrentPeersHighWater {
292 _, ok := t.peers.DeleteMin()
294 torrent.Add("excess reserve peers discarded", 1)
300 func (t *Torrent) invalidateMetadata() {
301 for i := 0; i < len(t.metadataCompletedChunks); i++ {
302 t.metadataCompletedChunks[i] = false
305 t.gotMetainfoC = make(chan struct{})
310 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
314 if index >= len(t.metadataCompletedChunks) {
315 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
318 copy(t.metadataBytes[(1<<14)*index:], data)
319 t.metadataCompletedChunks[index] = true
322 func (t *Torrent) metadataPieceCount() int {
323 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
326 func (t *Torrent) haveMetadataPiece(piece int) bool {
328 return (1<<14)*piece < len(t.metadataBytes)
330 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
334 func (t *Torrent) metadataSize() int {
335 return len(t.metadataBytes)
338 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
339 for i := 0; i < len(info.Pieces); i += sha1.Size {
340 ret = append(ret, info.Pieces[i:i+sha1.Size])
345 func (t *Torrent) makePieces() {
346 hashes := infoPieceHashes(t.info)
347 t.pieces = make([]Piece, len(hashes))
348 for i, hash := range hashes {
349 piece := &t.pieces[i]
351 piece.index = pieceIndex(i)
352 piece.noPendingWrites.L = &piece.pendingWritesMutex
353 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
355 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
356 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
357 piece.files = files[beginFile:endFile]
358 piece.undirtiedChunksIter = undirtiedChunksIter{
359 TorrentDirtyChunks: &t.dirtyChunks,
360 StartRequestIndex: piece.requestIndexOffset(),
361 EndRequestIndex: piece.requestIndexOffset() + piece.numChunks(),
366 // Returns the index of the first file containing the piece. files must be
367 // ordered by offset.
368 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
369 for i, f := range files {
370 if f.offset+f.length > pieceOffset {
377 // Returns the index after the last file containing the piece. files must be
378 // ordered by offset.
379 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
380 for i, f := range files {
381 if f.offset+f.length >= pieceEndOffset {
388 func (t *Torrent) cacheLength() {
390 for _, f := range t.info.UpvertedFiles() {
396 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
398 func (t *Torrent) setInfo(info *metainfo.Info) error {
399 if err := validateInfo(info); err != nil {
400 return fmt.Errorf("bad info: %s", err)
402 if t.storageOpener != nil {
404 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
406 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 for i := range t.pieces {
425 // Need to add availability before updating piece completion, as that may result in conns
427 if p.availability != 0 {
428 panic(p.availability)
430 p.availability = int64(t.pieceAvailabilityFromPeers(i))
431 t.updatePieceCompletion(pieceIndex(i))
432 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
433 // t.logger.Printf("piece %s completion unknown, queueing check", p)
434 t.queuePieceCheck(pieceIndex(i))
437 t.cl.event.Broadcast()
438 close(t.gotMetainfoC)
439 t.updateWantPeersEvent()
440 t.pendingRequests.Init(t.numRequests())
441 t.tryCreateMorePieceHashers()
442 t.iterPeers(func(p *Peer) {
444 p.updateRequests("onSetInfo")
448 // Called when metadata for a torrent becomes available.
449 func (t *Torrent) setInfoBytesLocked(b []byte) error {
450 if metainfo.HashBytes(b) != t.infoHash {
451 return errors.New("info bytes have wrong hash")
453 var info metainfo.Info
454 if err := bencode.Unmarshal(b, &info); err != nil {
455 return fmt.Errorf("error unmarshalling info bytes: %s", err)
458 t.metadataCompletedChunks = nil
462 if err := t.setInfo(&info); err != nil {
469 func (t *Torrent) haveAllMetadataPieces() bool {
473 if t.metadataCompletedChunks == nil {
476 for _, have := range t.metadataCompletedChunks {
484 // TODO: Propagate errors to disconnect peer.
485 func (t *Torrent) setMetadataSize(size int) (err error) {
487 // We already know the correct metadata size.
490 if uint32(size) > maxMetadataSize {
491 return errors.New("bad size")
493 if len(t.metadataBytes) == size {
496 t.metadataBytes = make([]byte, size)
497 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
498 t.metadataChanged.Broadcast()
499 for c := range t.conns {
500 c.requestPendingMetadata()
505 // The current working name for the torrent. Either the name in the info dict,
506 // or a display name given such as by the dn value in a magnet link, or "".
507 func (t *Torrent) name() string {
509 defer t.nameMu.RUnlock()
513 if t.displayName != "" {
516 return "infohash:" + t.infoHash.HexString()
519 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
520 p := &t.pieces[index]
521 ret.Priority = t.piecePriority(index)
522 ret.Completion = p.completion()
523 ret.QueuedForHash = p.queuedForHash()
524 ret.Hashing = p.hashing
525 ret.Checking = ret.QueuedForHash || ret.Hashing
526 ret.Marking = p.marking
527 if !ret.Complete && t.piecePartiallyDownloaded(index) {
533 func (t *Torrent) metadataPieceSize(piece int) int {
534 return metadataPieceSize(len(t.metadataBytes), piece)
537 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
540 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
541 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
543 TotalSize: len(t.metadataBytes),
549 type pieceAvailabilityRun struct {
554 func (me pieceAvailabilityRun) String() string {
555 return fmt.Sprintf("%v(%v)", me.count, me.availability)
558 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
559 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
560 ret = append(ret, pieceAvailabilityRun{availability: el.(int64), count: int(count)})
562 for i := range t.pieces {
563 rle.Append(t.pieces[i].availability, 1)
569 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
570 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
571 ret = append(ret, PieceStateRun{
572 PieceState: el.(PieceState),
576 for index := range t.pieces {
577 rle.Append(t.pieceState(pieceIndex(index)), 1)
583 // Produces a small string representing a PieceStateRun.
584 func (psr PieceStateRun) String() (ret string) {
585 ret = fmt.Sprintf("%d", psr.Length)
586 ret += func() string {
587 switch psr.Priority {
588 case PiecePriorityNext:
590 case PiecePriorityNormal:
592 case PiecePriorityReadahead:
594 case PiecePriorityNow:
596 case PiecePriorityHigh:
605 if psr.QueuedForHash {
623 func (t *Torrent) writeStatus(w io.Writer) {
624 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
625 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
627 fmt.Fprintf(w, "Metadata have: ")
628 for _, h := range t.metadataCompletedChunks {
629 fmt.Fprintf(w, "%c", func() rune {
639 fmt.Fprintf(w, "Piece length: %s\n",
642 return fmt.Sprintf("%v (%v chunks)",
644 float64(t.usualPieceSize())/float64(t.chunkSize))
651 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
652 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
653 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
654 for _, run := range t.pieceAvailabilityRuns() {
655 ret = append(ret, run.String())
660 fmt.Fprintf(w, "Reader Pieces:")
661 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
662 fmt.Fprintf(w, " %d:%d", begin, end)
667 fmt.Fprintf(w, "Enabled trackers:\n")
669 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
670 fmt.Fprintf(tw, " URL\tExtra\n")
671 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
674 var luns, runs url.URL = *lu, *ru
677 var ml missinggo.MultiLess
678 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
679 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
681 }).([]torrentTrackerAnnouncer) {
682 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
687 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
689 spew.NewDefaultConfig()
690 spew.Fdump(w, t.statsLocked())
692 peers := t.peersAsSlice()
693 sort.Slice(peers, func(_i, _j int) bool {
696 if less, ok := multiless.New().EagerSameLess(
697 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
701 return worseConn(i, j)
703 for i, c := range peers {
704 fmt.Fprintf(w, "%2d. ", i+1)
709 func (t *Torrent) haveInfo() bool {
713 // Returns a run-time generated MetaInfo that includes the info bytes and
714 // announce-list as currently known to the client.
715 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
716 return metainfo.MetaInfo{
717 CreationDate: time.Now().Unix(),
718 Comment: "dynamic metainfo from client",
719 CreatedBy: "go.torrent",
720 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
721 InfoBytes: func() []byte {
723 return t.metadataBytes
728 UrlList: func() []string {
729 ret := make([]string, 0, len(t.webSeeds))
730 for url := range t.webSeeds {
731 ret = append(ret, url)
739 func (t *Torrent) BytesMissing() (n int64) {
741 n = t.bytesMissingLocked()
746 func (t *Torrent) bytesMissingLocked() int64 {
750 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
751 roaring.Flip(b, 0, end).Iterate(cb)
754 func (t *Torrent) bytesLeft() (left int64) {
755 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
756 p := t.piece(pieceIndex(x))
757 left += int64(p.length() - p.numDirtyBytes())
763 // Bytes left to give in tracker announces.
764 func (t *Torrent) bytesLeftAnnounce() int64 {
772 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
773 if t.pieceComplete(piece) {
776 if t.pieceAllDirty(piece) {
779 return t.pieces[piece].hasDirtyChunks()
782 func (t *Torrent) usualPieceSize() int {
783 return int(t.info.PieceLength)
786 func (t *Torrent) numPieces() pieceIndex {
787 return pieceIndex(t.info.NumPieces())
790 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
791 return pieceIndex(t._completedPieces.GetCardinality())
794 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
796 if t.storage != nil {
801 defer t.storageLock.Unlock()
802 if f := t.storage.Close; f != nil {
805 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
810 t.iterPeers(func(p *Peer) {
814 t.cl.event.Broadcast()
815 t.pieceStateChanges.Close()
816 t.updateWantPeersEvent()
820 func (t *Torrent) requestOffset(r Request) int64 {
821 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
824 // Return the request that would include the given offset into the torrent data. Returns !ok if
825 // there is no such request.
826 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
827 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
830 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
831 defer perf.ScopeTimerErr(&err)()
832 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
833 if err == nil && n != len(data) {
834 err = io.ErrShortWrite
839 func (t *Torrent) bitfield() (bf []bool) {
840 bf = make([]bool, t.numPieces())
841 t._completedPieces.Iterate(func(piece uint32) (again bool) {
848 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
849 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
852 func (t *Torrent) chunksPerRegularPiece() uint32 {
853 return uint32((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
856 func (t *Torrent) numRequests() RequestIndex {
857 if t.numPieces() == 0 {
860 return uint32(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
863 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
864 t.dirtyChunks.RemoveRange(
865 uint64(t.pieceRequestIndexOffset(pieceIndex)),
866 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
869 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
870 if t.info.PieceLength == 0 {
871 // There will be no variance amongst pieces. Only pain.
874 if piece == t.numPieces()-1 {
875 ret := pp.Integer(*t.length % t.info.PieceLength)
880 return pp.Integer(t.info.PieceLength)
883 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
885 p.waitNoPendingWrites()
886 storagePiece := t.pieces[piece].Storage()
888 // Does the backend want to do its own hashing?
889 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
890 var sum metainfo.Hash
891 // log.Printf("A piece decided to self-hash: %d", piece)
892 sum, err = i.SelfHash()
893 missinggo.CopyExact(&ret, sum)
897 hash := pieceHash.New()
898 const logPieceContents = false
899 if logPieceContents {
900 var examineBuf bytes.Buffer
901 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
902 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
904 _, err = storagePiece.WriteTo(hash)
906 missinggo.CopyExact(&ret, hash.Sum(nil))
910 func (t *Torrent) haveAnyPieces() bool {
911 return t._completedPieces.GetCardinality() != 0
914 func (t *Torrent) haveAllPieces() bool {
918 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
921 func (t *Torrent) havePiece(index pieceIndex) bool {
922 return t.haveInfo() && t.pieceComplete(index)
925 func (t *Torrent) maybeDropMutuallyCompletePeer(
926 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
930 if !t.cl.config.DropMutuallyCompletePeers {
933 if !t.haveAllPieces() {
936 if all, known := p.peerHasAllPieces(); !(known && all) {
942 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
946 func (t *Torrent) haveChunk(r Request) (ret bool) {
948 // log.Println("have chunk", r, ret)
953 if t.pieceComplete(pieceIndex(r.Index)) {
956 p := &t.pieces[r.Index]
957 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
960 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
961 return chunkIndexType(cs.Begin / chunkSize)
964 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
965 return t._pendingPieces.Contains(uint32(index))
968 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
969 // conns (which is a map).
970 var peerConnSlices sync.Pool
972 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
973 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
974 // established connections for more than a minute. This is O(n log n). If there was a way to not
975 // consider the position of a conn relative to the total number, it could be reduced to O(n).
976 func (t *Torrent) worstBadConn() (ret *PeerConn) {
978 getInterface := peerConnSlices.Get()
979 if getInterface == nil {
980 sl = make([]*PeerConn, 0, len(t.conns))
982 sl = getInterface.([]*PeerConn)[:0]
984 sl = t.appendUnclosedConns(sl)
985 defer peerConnSlices.Put(sl)
986 wcs := worseConnSlice{sl}
989 c := heap.Pop(&wcs).(*PeerConn)
990 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
993 // If the connection is in the worst half of the established
994 // connection quota and is older than a minute.
995 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
996 // Give connections 1 minute to prove themselves.
997 if time.Since(c.completedHandshake) > time.Minute {
1005 type PieceStateChange struct {
1010 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1011 t.cl._mu.Defer(func() {
1012 cur := t.pieceState(piece)
1013 p := &t.pieces[piece]
1014 if cur != p.publicPieceState {
1015 p.publicPieceState = cur
1016 t.pieceStateChanges.Publish(PieceStateChange{
1024 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1025 if t.pieceComplete(piece) {
1028 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1031 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1032 return t.pieces[piece].allChunksDirty()
1035 func (t *Torrent) readersChanged() {
1036 t.updateReaderPieces()
1037 t.updateAllPiecePriorities("Torrent.readersChanged")
1040 func (t *Torrent) updateReaderPieces() {
1041 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1044 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1048 t.updateReaderPieces()
1049 // Order the ranges, high and low.
1051 if l.begin > h.begin {
1054 if l.end < h.begin {
1055 // Two distinct ranges.
1056 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1057 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1064 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1068 func (t *Torrent) maybeNewConns() {
1069 // Tickle the accept routine.
1070 t.cl.event.Broadcast()
1074 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1075 if t._pendingPieces.Contains(uint32(piece)) {
1076 t.iterPeers(func(c *Peer) {
1077 if c.actualRequestState.Interested {
1080 if !c.isLowOnRequests() {
1083 if !c.peerHasPiece(piece) {
1086 c.updateRequests(reason)
1090 t.publishPieceChange(piece)
1093 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1094 p := &t.pieces[piece]
1095 newPrio := p.uncachedPriority()
1096 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1097 if newPrio == PiecePriorityNone {
1098 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1102 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1106 t.piecePriorityChanged(piece, reason)
1109 func (t *Torrent) updateAllPiecePriorities(reason string) {
1110 t.updatePiecePriorities(0, t.numPieces(), reason)
1113 // Update all piece priorities in one hit. This function should have the same
1114 // output as updatePiecePriority, but across all pieces.
1115 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1116 for i := begin; i < end; i++ {
1117 t.updatePiecePriority(i, reason)
1121 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1122 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1123 if off >= *t.length {
1133 begin = pieceIndex(off / t.info.PieceLength)
1134 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1135 if end > pieceIndex(t.info.NumPieces()) {
1136 end = pieceIndex(t.info.NumPieces())
1141 // Returns true if all iterations complete without breaking. Returns the read regions for all
1142 // readers. The reader regions should not be merged as some callers depend on this method to
1143 // enumerate readers.
1144 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1145 for r := range t.readers {
1147 if p.begin >= p.end {
1150 if !f(p.begin, p.end) {
1157 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1158 return t.piece(piece).uncachedPriority()
1161 func (t *Torrent) pendRequest(req RequestIndex) {
1162 t.piece(int(req / t.chunksPerRegularPiece())).pendChunkIndex(req % t.chunksPerRegularPiece())
1165 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1166 t.cl.event.Broadcast()
1167 if t.pieceComplete(piece) {
1168 t.onPieceCompleted(piece)
1170 t.onIncompletePiece(piece)
1172 t.updatePiecePriority(piece, reason)
1175 func (t *Torrent) numReceivedConns() (ret int) {
1176 for c := range t.conns {
1177 if c.Discovery == PeerSourceIncoming {
1184 func (t *Torrent) maxHalfOpen() int {
1185 // Note that if we somehow exceed the maximum established conns, we want
1186 // the negative value to have an effect.
1187 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1188 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1189 // We want to allow some experimentation with new peers, and to try to
1190 // upset an oversupply of received connections.
1191 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1194 func (t *Torrent) openNewConns() (initiated int) {
1195 defer t.updateWantPeersEvent()
1196 for t.peers.Len() != 0 {
1200 if len(t.halfOpen) >= t.maxHalfOpen() {
1203 if len(t.cl.dialers) == 0 {
1206 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1209 p := t.peers.PopMax()
1216 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1218 uncached := t.pieceCompleteUncached(piece)
1219 cached := p.completion()
1220 changed := cached != uncached
1221 complete := uncached.Complete
1222 p.storageCompletionOk = uncached.Ok
1225 t._completedPieces.Add(x)
1228 t._completedPieces.Remove(x)
1231 if complete && len(p.dirtiers) != 0 {
1232 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1235 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1236 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1241 // Non-blocking read. Client lock is not required.
1242 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1244 p := &t.pieces[off/t.info.PieceLength]
1245 p.waitNoPendingWrites()
1247 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1258 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1259 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1260 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1261 func (t *Torrent) maybeCompleteMetadata() error {
1266 if !t.haveAllMetadataPieces() {
1267 // Don't have enough metadata pieces.
1270 err := t.setInfoBytesLocked(t.metadataBytes)
1272 t.invalidateMetadata()
1273 return fmt.Errorf("error setting info bytes: %s", err)
1275 if t.cl.config.Debug {
1276 t.logger.Printf("%s: got metadata from peers", t)
1281 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1282 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1284 now.Add(bitmap.BitIndex(begin))
1285 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1292 func (t *Torrent) needData() bool {
1293 if t.closed.IsSet() {
1299 return !t._pendingPieces.IsEmpty()
1302 func appendMissingStrings(old, new []string) (ret []string) {
1305 for _, n := range new {
1306 for _, o := range old {
1311 ret = append(ret, n)
1316 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1318 for minNumTiers > len(ret) {
1319 ret = append(ret, nil)
1324 func (t *Torrent) addTrackers(announceList [][]string) {
1325 fullAnnounceList := &t.metainfo.AnnounceList
1326 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1327 for tierIndex, trackerURLs := range announceList {
1328 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1330 t.startMissingTrackerScrapers()
1331 t.updateWantPeersEvent()
1334 // Don't call this before the info is available.
1335 func (t *Torrent) bytesCompleted() int64 {
1339 return *t.length - t.bytesLeft()
1342 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1345 return t.setInfoBytesLocked(b)
1348 // Returns true if connection is removed from torrent.Conns.
1349 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1350 if !c.closed.IsSet() {
1351 panic("connection is not closed")
1352 // There are behaviours prevented by the closed state that will fail
1353 // if the connection has been deleted.
1357 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1358 // the drop event against the PexConnState instead.
1360 if !t.cl.config.DisablePEX {
1364 torrent.Add("deleted connections", 1)
1365 c.deleteAllRequests()
1366 t.assertPendingRequests()
1370 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1374 p.newPeerPieces().Iterate(func(i uint32) bool {
1375 p.t.decPieceAvailability(pieceIndex(i))
1380 func (t *Torrent) assertPendingRequests() {
1384 // var actual pendingRequests
1385 // if t.haveInfo() {
1386 // actual.m = make([]int, t.numRequests())
1388 // t.iterPeers(func(p *Peer) {
1389 // p.actualRequestState.Requests.Iterate(func(x uint32) bool {
1394 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1400 func (t *Torrent) dropConnection(c *PeerConn) {
1401 t.cl.event.Broadcast()
1403 if t.deletePeerConn(c) {
1408 // Peers as in contact information for dialing out.
1409 func (t *Torrent) wantPeers() bool {
1410 if t.closed.IsSet() {
1413 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1416 return t.wantConns()
1419 func (t *Torrent) updateWantPeersEvent() {
1421 t.wantPeersEvent.Set()
1423 t.wantPeersEvent.Clear()
1427 // Returns whether the client should make effort to seed the torrent.
1428 func (t *Torrent) seeding() bool {
1430 if t.closed.IsSet() {
1433 if t.dataUploadDisallowed {
1436 if cl.config.NoUpload {
1439 if !cl.config.Seed {
1442 if cl.config.DisableAggressiveUpload && t.needData() {
1448 func (t *Torrent) onWebRtcConn(
1449 c datachannel.ReadWriteCloser,
1450 dcc webtorrent.DataChannelContext,
1453 pc, err := t.cl.initiateProtocolHandshakes(
1454 context.Background(),
1455 webrtcNetConn{c, dcc},
1459 webrtcNetAddr{dcc.Remote},
1461 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1464 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1467 if dcc.LocalOffered {
1468 pc.Discovery = PeerSourceTracker
1470 pc.Discovery = PeerSourceIncoming
1472 pc.conn.SetWriteDeadline(time.Time{})
1475 err = t.cl.runHandshookConn(pc, t)
1477 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1481 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1482 err := t.cl.runHandshookConn(pc, t)
1483 if err != nil || logAll {
1484 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1488 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1489 t.logRunHandshookConn(pc, false, log.Debug)
1492 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1493 wtc, release := t.cl.websocketTrackers.Get(u.String())
1498 wst := websocketTrackerStatus{u, wtc}
1500 err := wtc.Announce(tracker.Started, t.infoHash)
1502 t.logger.WithDefaultLevel(log.Warning).Printf(
1503 "error in initial announce to %q: %v",
1511 func (t *Torrent) startScrapingTracker(_url string) {
1515 u, err := url.Parse(_url)
1517 // URLs with a leading '*' appear to be a uTorrent convention to
1518 // disable trackers.
1520 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1524 if u.Scheme == "udp" {
1526 t.startScrapingTracker(u.String())
1528 t.startScrapingTracker(u.String())
1531 if _, ok := t.trackerAnnouncers[_url]; ok {
1534 sl := func() torrentTrackerAnnouncer {
1537 if t.cl.config.DisableWebtorrent {
1540 return t.startWebsocketAnnouncer(*u)
1542 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1546 if t.cl.config.DisableIPv6 {
1550 newAnnouncer := &trackerScraper{
1553 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1555 go newAnnouncer.Run()
1561 if t.trackerAnnouncers == nil {
1562 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1564 t.trackerAnnouncers[_url] = sl
1567 // Adds and starts tracker scrapers for tracker URLs that aren't already
1569 func (t *Torrent) startMissingTrackerScrapers() {
1570 if t.cl.config.DisableTrackers {
1573 t.startScrapingTracker(t.metainfo.Announce)
1574 for _, tier := range t.metainfo.AnnounceList {
1575 for _, url := range tier {
1576 t.startScrapingTracker(url)
1581 // Returns an AnnounceRequest with fields filled out to defaults and current
1583 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1584 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1585 // dependent on the network in use.
1586 return tracker.AnnounceRequest{
1588 NumWant: func() int32 {
1589 if t.wantPeers() && len(t.cl.dialers) > 0 {
1595 Port: uint16(t.cl.incomingPeerPort()),
1596 PeerId: t.cl.peerID,
1597 InfoHash: t.infoHash,
1598 Key: t.cl.announceKey(),
1600 // The following are vaguely described in BEP 3.
1602 Left: t.bytesLeftAnnounce(),
1603 Uploaded: t.stats.BytesWrittenData.Int64(),
1604 // There's no mention of wasted or unwanted download in the BEP.
1605 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1609 // Adds peers revealed in an announce until the announce ends, or we have
1611 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1613 for v := range pvs {
1616 for _, cp := range v.Peers {
1618 // Can't do anything with this.
1621 if t.addPeer(PeerInfo{
1622 Addr: ipPortAddr{cp.IP, cp.Port},
1623 Source: PeerSourceDhtGetPeers,
1630 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1635 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1636 // announce ends. stop will force the announce to end.
1637 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1638 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1642 _done := make(chan struct{})
1646 t.consumeDhtAnnouncePeers(ps.Peers())
1652 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1653 _, stop, err := t.AnnounceToDht(s)
1658 case <-t.closed.Done():
1659 case <-time.After(5 * time.Minute):
1665 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1671 if t.closed.IsSet() {
1677 // TODO: Determine if there's a listener on the port we're announcing.
1678 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1689 err := t.timeboxedAnnounceToDht(s)
1691 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1697 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1698 for _, p := range peers {
1706 // The returned TorrentStats may require alignment in memory. See
1707 // https://github.com/anacrolix/torrent/issues/383.
1708 func (t *Torrent) Stats() TorrentStats {
1710 defer t.cl.rUnlock()
1711 return t.statsLocked()
1714 func (t *Torrent) statsLocked() (ret TorrentStats) {
1715 ret.ActivePeers = len(t.conns)
1716 ret.HalfOpenPeers = len(t.halfOpen)
1717 ret.PendingPeers = t.peers.Len()
1718 ret.TotalPeers = t.numTotalPeers()
1719 ret.ConnectedSeeders = 0
1720 for c := range t.conns {
1721 if all, ok := c.peerHasAllPieces(); all && ok {
1722 ret.ConnectedSeeders++
1725 ret.ConnStats = t.stats.Copy()
1726 ret.PiecesComplete = t.numPiecesCompleted()
1730 // The total number of peers in the torrent.
1731 func (t *Torrent) numTotalPeers() int {
1732 peers := make(map[string]struct{})
1733 for conn := range t.conns {
1734 ra := conn.conn.RemoteAddr()
1736 // It's been closed and doesn't support RemoteAddr.
1739 peers[ra.String()] = struct{}{}
1741 for addr := range t.halfOpen {
1742 peers[addr] = struct{}{}
1744 t.peers.Each(func(peer PeerInfo) {
1745 peers[peer.Addr.String()] = struct{}{}
1750 // Reconcile bytes transferred before connection was associated with a
1752 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1753 if c._stats != (ConnStats{
1754 // Handshakes should only increment these fields:
1755 BytesWritten: c._stats.BytesWritten,
1756 BytesRead: c._stats.BytesRead,
1760 c.postHandshakeStats(func(cs *ConnStats) {
1761 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1762 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1764 c.reconciledHandshakeStats = true
1767 // Returns true if the connection is added.
1768 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1771 torrent.Add("added connections", 1)
1774 if t.closed.IsSet() {
1775 return errors.New("torrent closed")
1777 for c0 := range t.conns {
1778 if c.PeerID != c0.PeerID {
1781 if !t.cl.config.DropDuplicatePeerIds {
1784 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1786 t.deletePeerConn(c0)
1788 return errors.New("existing connection preferred")
1791 if len(t.conns) >= t.maxEstablishedConns {
1792 c := t.worstBadConn()
1794 return errors.New("don't want conns")
1799 if len(t.conns) >= t.maxEstablishedConns {
1802 t.conns[c] = struct{}{}
1803 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1804 t.pex.Add(c) // as no further extended handshake expected
1809 func (t *Torrent) wantConns() bool {
1810 if !t.networkingEnabled.Bool() {
1813 if t.closed.IsSet() {
1816 if len(t.conns) >= t.maxEstablishedConns && t.worstBadConn() == nil {
1819 if t.seeding() && t.haveAnyPieces() {
1825 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1828 oldMax = t.maxEstablishedConns
1829 t.maxEstablishedConns = max
1830 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1831 return worseConn(&l.Peer, &r.Peer)
1833 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1834 t.dropConnection(wcs.Pop().(*PeerConn))
1840 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1841 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1844 t.cl.event.Broadcast()
1845 if t.closed.IsSet() {
1849 // Don't score the first time a piece is hashed, it could be an initial check.
1850 if p.storageCompletionOk {
1852 pieceHashedCorrect.Add(1)
1855 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1856 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1857 pieceHashedNotCorrect.Add(1)
1862 t.publishPieceChange(piece)
1865 t.publishPieceChange(piece)
1869 if len(p.dirtiers) != 0 {
1870 // Don't increment stats above connection-level for every involved connection.
1871 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1873 for c := range p.dirtiers {
1874 c._stats.incrementPiecesDirtiedGood()
1876 t.clearPieceTouchers(piece)
1878 err := p.Storage().MarkComplete()
1880 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1884 if t.closed.IsSet() {
1887 t.pendAllChunkSpecs(piece)
1889 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1890 // Peers contributed to all the data for this piece hash failure, and the failure was
1891 // not due to errors in the storage (such as data being dropped in a cache).
1893 // Increment Torrent and above stats, and then specific connections.
1894 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1895 for c := range p.dirtiers {
1896 // Y u do dis peer?!
1897 c.stats().incrementPiecesDirtiedBad()
1900 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1901 for c := range p.dirtiers {
1903 bannableTouchers = append(bannableTouchers, c)
1906 t.clearPieceTouchers(piece)
1907 slices.Sort(bannableTouchers, connLessTrusted)
1909 if t.cl.config.Debug {
1911 "bannable conns by trust for piece %d: %v",
1913 func() (ret []connectionTrust) {
1914 for _, c := range bannableTouchers {
1915 ret = append(ret, c.trust())
1922 if len(bannableTouchers) >= 1 {
1923 c := bannableTouchers[0]
1924 t.cl.banPeerIP(c.remoteIp())
1928 t.onIncompletePiece(piece)
1929 p.Storage().MarkNotComplete()
1931 t.updatePieceCompletion(piece)
1934 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1935 // TODO: Make faster
1936 for cn := range t.conns {
1941 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1942 t.pendAllChunkSpecs(piece)
1943 t.cancelRequestsForPiece(piece)
1944 t.piece(piece).readerCond.Broadcast()
1945 for conn := range t.conns {
1947 t.maybeDropMutuallyCompletePeer(&conn.Peer)
1951 // Called when a piece is found to be not complete.
1952 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1953 if t.pieceAllDirty(piece) {
1954 t.pendAllChunkSpecs(piece)
1956 if !t.wantPieceIndex(piece) {
1957 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1960 // We could drop any connections that we told we have a piece that we
1961 // don't here. But there's a test failure, and it seems clients don't care
1962 // if you request pieces that you already claim to have. Pruning bad
1963 // connections might just remove any connections that aren't treating us
1964 // favourably anyway.
1966 // for c := range t.conns {
1967 // if c.sentHave(piece) {
1971 t.iterPeers(func(conn *Peer) {
1972 if conn.peerHasPiece(piece) {
1973 conn.updateRequests("piece incomplete")
1978 func (t *Torrent) tryCreateMorePieceHashers() {
1979 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1983 func (t *Torrent) tryCreatePieceHasher() bool {
1984 if t.storage == nil {
1987 pi, ok := t.getPieceToHash()
1992 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
1994 t.publishPieceChange(pi)
1995 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
1996 t.storageLock.RLock()
1997 t.activePieceHashes++
1998 go t.pieceHasher(pi)
2002 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2003 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2004 if t.piece(i).hashing {
2014 func (t *Torrent) pieceHasher(index pieceIndex) {
2016 sum, copyErr := t.hashPiece(index)
2017 correct := sum == *p.hash
2021 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2023 t.storageLock.RUnlock()
2027 t.pieceHashed(index, correct, copyErr)
2028 t.updatePiecePriority(index, "Torrent.pieceHasher")
2029 t.activePieceHashes--
2030 t.tryCreateMorePieceHashers()
2033 // Return the connections that touched a piece, and clear the entries while doing it.
2034 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2036 for c := range p.dirtiers {
2037 delete(c.peerTouchedPieces, pi)
2038 delete(p.dirtiers, c)
2042 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2043 t.iterPeers(func(p *Peer) {
2044 ret = append(ret, p)
2049 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2050 piece := t.piece(pieceIndex)
2051 if piece.queuedForHash() {
2054 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2055 t.publishPieceChange(pieceIndex)
2056 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2057 t.tryCreateMorePieceHashers()
2060 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2061 // before the Info is available.
2062 func (t *Torrent) VerifyData() {
2063 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2064 t.Piece(i).VerifyData()
2068 // Start the process of connecting to the given peer for the given torrent if appropriate.
2069 func (t *Torrent) initiateConn(peer PeerInfo) {
2070 if peer.Id == t.cl.peerID {
2073 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2077 if t.addrActive(addr.String()) {
2081 t.halfOpen[addr.String()] = peer
2082 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2085 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2086 // quickly make one Client visible to the Torrent of another Client.
2087 func (t *Torrent) AddClientPeer(cl *Client) int {
2088 return t.AddPeers(func() (ps []PeerInfo) {
2089 for _, la := range cl.ListenAddrs() {
2090 ps = append(ps, PeerInfo{
2099 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2101 func (t *Torrent) allStats(f func(*ConnStats)) {
2106 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2107 return t.pieces[i].hashing
2110 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2111 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2114 func (t *Torrent) dialTimeout() time.Duration {
2115 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2118 func (t *Torrent) piece(i int) *Piece {
2122 func (t *Torrent) onWriteChunkErr(err error) {
2123 if t.userOnWriteChunkErr != nil {
2124 go t.userOnWriteChunkErr(err)
2127 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2128 t.disallowDataDownloadLocked()
2131 func (t *Torrent) DisallowDataDownload() {
2132 t.disallowDataDownloadLocked()
2135 func (t *Torrent) disallowDataDownloadLocked() {
2136 t.dataDownloadDisallowed.Set()
2139 func (t *Torrent) AllowDataDownload() {
2140 t.dataDownloadDisallowed.Clear()
2143 // Enables uploading data, if it was disabled.
2144 func (t *Torrent) AllowDataUpload() {
2147 t.dataUploadDisallowed = false
2148 for c := range t.conns {
2149 c.updateRequests("allow data upload")
2153 // Disables uploading data, if it was enabled.
2154 func (t *Torrent) DisallowDataUpload() {
2157 t.dataUploadDisallowed = true
2158 for c := range t.conns {
2159 c.updateRequests("disallow data upload")
2163 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2164 // or if nil, a critical message is logged, and data download is disabled.
2165 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2168 t.userOnWriteChunkErr = f
2171 func (t *Torrent) iterPeers(f func(p *Peer)) {
2172 for pc := range t.conns {
2175 for _, ws := range t.webSeeds {
2180 func (t *Torrent) callbacks() *Callbacks {
2181 return &t.cl.config.Callbacks
2184 func (t *Torrent) addWebSeed(url string) {
2185 if t.cl.config.DisableWebseeds {
2188 if _, ok := t.webSeeds[url]; ok {
2191 // I don't think Go http supports pipelining requests. However we can have more ready to go
2192 // right away. This value should be some multiple of the number of connections to a host. I
2193 // would expect that double maxRequests plus a bit would be appropriate.
2194 const maxRequests = 32
2200 reconciledHandshakeStats: true,
2201 // This should affect how often we have to recompute requests for this peer. Note that
2202 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2203 // requests mark more often, so recomputation is probably sooner than with regular peer
2204 // conns. ~4x maxRequests would be about right.
2205 PeerMaxRequests: 128,
2206 RemoteAddr: remoteAddrFromUrl(url),
2207 callbacks: t.callbacks(),
2209 client: webseed.Client{
2210 HttpClient: t.cl.webseedHttpClient,
2213 activeRequests: make(map[Request]webseed.Request, maxRequests),
2214 maxRequests: maxRequests,
2216 ws.peer.initUpdateRequestsTimer()
2217 ws.requesterCond.L = t.cl.locker()
2218 for i := 0; i < maxRequests; i += 1 {
2221 for _, f := range t.callbacks().NewPeer {
2224 ws.peer.logger = t.logger.WithContextValue(&ws)
2225 ws.peer.peerImpl = &ws
2227 ws.onGotInfo(t.info)
2229 t.webSeeds[url] = &ws.peer
2232 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2233 t.iterPeers(func(p1 *Peer) {
2241 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2242 index := ri / t.chunksPerRegularPiece()
2245 t.piece(int(index)).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2249 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2250 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + uint32(r.Begin/t.chunkSize)
2253 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2254 return RequestIndex(piece) * t.chunksPerRegularPiece()
2257 func (t *Torrent) updateComplete() {
2258 t.Complete.SetBool(t.haveAllPieces())