19 "github.com/RoaringBitmap/roaring"
20 "github.com/anacrolix/chansync"
21 "github.com/anacrolix/chansync/events"
22 "github.com/anacrolix/dht/v2"
23 "github.com/anacrolix/log"
24 "github.com/anacrolix/missinggo/perf"
25 "github.com/anacrolix/missinggo/pubsub"
26 "github.com/anacrolix/missinggo/slices"
27 "github.com/anacrolix/missinggo/v2"
28 "github.com/anacrolix/missinggo/v2/bitmap"
29 "github.com/anacrolix/multiless"
30 "github.com/anacrolix/sync"
31 "github.com/anacrolix/torrent/option"
32 request_strategy "github.com/anacrolix/torrent/request-strategy"
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
90 // Active peer connections, running message stream loops. TODO: Make this
91 // open (not-closed) connections only.
92 conns map[*PeerConn]struct{}
93 maxEstablishedConns int
94 // Set of addrs to which we're attempting to connect. Connections are
95 // half-open until all handshakes are completed.
96 halfOpen map[string]PeerInfo
98 // Reserve of peers to connect to. A peer can be both here and in the
99 // active connections if were told about the peer after connecting with
100 // them. That encourages us to reconnect to peers that are well known in
102 peers prioritizedPeers
103 // Whether we want to know to know more peers.
104 wantPeersEvent missinggo.Event
105 // An announcer for each tracker URL.
106 trackerAnnouncers map[string]torrentTrackerAnnouncer
107 // How many times we've initiated a DHT announce. TODO: Move into stats.
110 // Name used if the info name isn't available. Should be cleared when the
111 // Info does become available.
115 // The bencoded bytes of the info dict. This is actively manipulated if
116 // the info bytes aren't initially available, and we try to fetch them
119 // Each element corresponds to the 16KiB metadata pieces. If true, we have
120 // received that piece.
121 metadataCompletedChunks []bool
122 metadataChanged sync.Cond
124 // Closed when .Info is obtained.
125 gotMetainfoC chan struct{}
127 readers map[*reader]struct{}
128 _readerNowPieces bitmap.Bitmap
129 _readerReadaheadPieces bitmap.Bitmap
131 // A cache of pieces we need to get. Calculated from various piece and
132 // file priorities and completion states elsewhere.
133 _pendingPieces roaring.Bitmap
134 // A cache of completed piece indices.
135 _completedPieces roaring.Bitmap
136 // Pieces that need to be hashed.
137 piecesQueuedForHash bitmap.Bitmap
138 activePieceHashes int
139 initialPieceCheckDisabled bool
141 connsWithAllPieces map[*Peer]struct{}
142 // Count of each request across active connections.
143 pendingRequests map[RequestIndex]*Peer
144 lastRequested map[RequestIndex]time.Time
145 // Chunks we've written to since the corresponding piece was last checked.
146 dirtyChunks roaring.Bitmap
150 // Is On when all pieces are complete.
151 Complete chansync.Flag
153 smartBanCache smartBanCache
156 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
157 // This could be done with roaring.BitSliceIndexing.
158 t.iterPeers(func(peer *Peer) {
159 if _, ok := t.connsWithAllPieces[peer]; ok {
162 if peer.peerHasPiece(i) {
169 func (t *Torrent) decPieceAvailability(i pieceIndex) {
174 if p.relativeAvailability <= 0 {
175 panic(p.relativeAvailability)
177 p.relativeAvailability--
178 t.updatePieceRequestOrder(i)
181 func (t *Torrent) incPieceAvailability(i pieceIndex) {
182 // If we don't the info, this should be reconciled when we do.
185 p.relativeAvailability++
186 t.updatePieceRequestOrder(i)
190 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
191 return t._readerNowPieces
194 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
195 return t._readerReadaheadPieces
198 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
199 return !t.wantPieceIndex(i)
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 {
222 ks = append(ks, PeerInfo{
224 Addr: conn.RemoteAddr,
225 Source: conn.Discovery,
226 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
227 // > But if we're not connected to them with an encrypted connection, I couldn't say
228 // > what's appropriate. We can carry forward the SupportsEncryption value as we
229 // > received it from trackers/DHT/PEX, or just use the encryption state for the
230 // > connection. It's probably easiest to do the latter for now.
231 // https://github.com/anacrolix/torrent/pull/188
232 SupportsEncryption: conn.headerEncrypted,
239 func (t *Torrent) setChunkSize(size pp.Integer) {
241 t.chunkPool = sync.Pool{
242 New: func() interface{} {
243 b := make([]byte, size)
249 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
250 return t._completedPieces.Contains(bitmap.BitIndex(piece))
253 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
254 if t.storage == nil {
255 return storage.Completion{Complete: false, Ok: true}
257 return t.pieces[piece].Storage().Completion()
260 // There's a connection to that address already.
261 func (t *Torrent) addrActive(addr string) bool {
262 if _, ok := t.halfOpen[addr]; ok {
265 for c := range t.conns {
267 if ra.String() == addr {
274 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
275 return t.appendConns(ret, func(conn *PeerConn) bool {
276 return !conn.closed.IsSet()
280 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
281 for c := range t.conns {
289 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
291 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
292 if t.closed.IsSet() {
295 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
296 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
297 torrent.Add("peers not added because of bad addr", 1)
298 // cl.logger.Printf("peers not added because of bad addr: %v", p)
302 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
303 torrent.Add("peers replaced", 1)
304 if !replaced.equal(p) {
305 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
312 for t.peers.Len() > cl.config.TorrentPeersHighWater {
313 _, ok := t.peers.DeleteMin()
315 torrent.Add("excess reserve peers discarded", 1)
321 func (t *Torrent) invalidateMetadata() {
322 for i := 0; i < len(t.metadataCompletedChunks); i++ {
323 t.metadataCompletedChunks[i] = false
326 t.gotMetainfoC = make(chan struct{})
331 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
335 if index >= len(t.metadataCompletedChunks) {
336 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
339 copy(t.metadataBytes[(1<<14)*index:], data)
340 t.metadataCompletedChunks[index] = true
343 func (t *Torrent) metadataPieceCount() int {
344 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
347 func (t *Torrent) haveMetadataPiece(piece int) bool {
349 return (1<<14)*piece < len(t.metadataBytes)
351 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
355 func (t *Torrent) metadataSize() int {
356 return len(t.metadataBytes)
359 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
360 for i := 0; i < len(info.Pieces); i += sha1.Size {
361 ret = append(ret, info.Pieces[i:i+sha1.Size])
366 func (t *Torrent) makePieces() {
367 hashes := infoPieceHashes(t.info)
368 t.pieces = make([]Piece, len(hashes))
369 for i, hash := range hashes {
370 piece := &t.pieces[i]
372 piece.index = pieceIndex(i)
373 piece.noPendingWrites.L = &piece.pendingWritesMutex
374 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
376 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
377 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
378 piece.files = files[beginFile:endFile]
379 piece.undirtiedChunksIter = undirtiedChunksIter{
380 TorrentDirtyChunks: &t.dirtyChunks,
381 StartRequestIndex: piece.requestIndexOffset(),
382 EndRequestIndex: piece.requestIndexOffset() + piece.numChunks(),
387 // Returns the index of the first file containing the piece. files must be
388 // ordered by offset.
389 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
390 for i, f := range files {
391 if f.offset+f.length > pieceOffset {
398 // Returns the index after the last file containing the piece. files must be
399 // ordered by offset.
400 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
401 for i, f := range files {
402 if f.offset+f.length >= pieceEndOffset {
409 func (t *Torrent) cacheLength() {
411 for _, f := range t.info.UpvertedFiles() {
417 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
419 func (t *Torrent) setInfo(info *metainfo.Info) error {
420 if err := validateInfo(info); err != nil {
421 return fmt.Errorf("bad info: %s", err)
423 if t.storageOpener != nil {
425 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
427 return fmt.Errorf("error opening torrent storage: %s", err)
434 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
435 t.displayName = "" // Save a few bytes lol.
442 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
443 return request_strategy.PieceRequestOrderKey{
444 InfoHash: t.infoHash,
449 // This seems to be all the follow-up tasks after info is set, that can't fail.
450 func (t *Torrent) onSetInfo() {
451 t.initPieceRequestOrder()
452 for i := range t.pieces {
454 // Need to add relativeAvailability before updating piece completion, as that may result in conns
456 if p.relativeAvailability != 0 {
457 panic(p.relativeAvailability)
459 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
460 t.addRequestOrderPiece(i)
461 t.updatePieceCompletion(pieceIndex(i))
462 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
463 // t.logger.Printf("piece %s completion unknown, queueing check", p)
464 t.queuePieceCheck(pieceIndex(i))
467 t.cl.event.Broadcast()
468 close(t.gotMetainfoC)
469 t.updateWantPeersEvent()
470 t.pendingRequests = make(map[RequestIndex]*Peer)
471 t.lastRequested = make(map[RequestIndex]time.Time)
472 t.tryCreateMorePieceHashers()
473 t.iterPeers(func(p *Peer) {
475 p.updateRequests("onSetInfo")
479 // Called when metadata for a torrent becomes available.
480 func (t *Torrent) setInfoBytesLocked(b []byte) error {
481 if metainfo.HashBytes(b) != t.infoHash {
482 return errors.New("info bytes have wrong hash")
484 var info metainfo.Info
485 if err := bencode.Unmarshal(b, &info); err != nil {
486 return fmt.Errorf("error unmarshalling info bytes: %s", err)
489 t.metadataCompletedChunks = nil
493 if err := t.setInfo(&info); err != nil {
500 func (t *Torrent) haveAllMetadataPieces() bool {
504 if t.metadataCompletedChunks == nil {
507 for _, have := range t.metadataCompletedChunks {
515 // TODO: Propagate errors to disconnect peer.
516 func (t *Torrent) setMetadataSize(size int) (err error) {
518 // We already know the correct metadata size.
521 if uint32(size) > maxMetadataSize {
522 return errors.New("bad size")
524 if len(t.metadataBytes) == size {
527 t.metadataBytes = make([]byte, size)
528 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
529 t.metadataChanged.Broadcast()
530 for c := range t.conns {
531 c.requestPendingMetadata()
536 // The current working name for the torrent. Either the name in the info dict,
537 // or a display name given such as by the dn value in a magnet link, or "".
538 func (t *Torrent) name() string {
540 defer t.nameMu.RUnlock()
544 if t.displayName != "" {
547 return "infohash:" + t.infoHash.HexString()
550 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
551 p := &t.pieces[index]
552 ret.Priority = t.piecePriority(index)
553 ret.Completion = p.completion()
554 ret.QueuedForHash = p.queuedForHash()
555 ret.Hashing = p.hashing
556 ret.Checking = ret.QueuedForHash || ret.Hashing
557 ret.Marking = p.marking
558 if !ret.Complete && t.piecePartiallyDownloaded(index) {
564 func (t *Torrent) metadataPieceSize(piece int) int {
565 return metadataPieceSize(len(t.metadataBytes), piece)
568 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
571 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
572 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
574 TotalSize: len(t.metadataBytes),
580 type pieceAvailabilityRun struct {
585 func (me pieceAvailabilityRun) String() string {
586 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
589 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
590 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
591 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
593 for i := range t.pieces {
594 rle.Append(t.pieces[i].availability(), 1)
600 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
601 freqs = make([]int, t.numActivePeers()+1)
602 for i := range t.pieces {
603 freqs[t.piece(i).availability()]++
608 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
609 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
610 ret = append(ret, PieceStateRun{
611 PieceState: el.(PieceState),
615 for index := range t.pieces {
616 rle.Append(t.pieceState(pieceIndex(index)), 1)
622 // Produces a small string representing a PieceStateRun.
623 func (psr PieceStateRun) String() (ret string) {
624 ret = fmt.Sprintf("%d", psr.Length)
625 ret += func() string {
626 switch psr.Priority {
627 case PiecePriorityNext:
629 case PiecePriorityNormal:
631 case PiecePriorityReadahead:
633 case PiecePriorityNow:
635 case PiecePriorityHigh:
644 if psr.QueuedForHash {
662 func (t *Torrent) writeStatus(w io.Writer) {
663 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
664 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
666 fmt.Fprintf(w, "Metadata have: ")
667 for _, h := range t.metadataCompletedChunks {
668 fmt.Fprintf(w, "%c", func() rune {
678 fmt.Fprintf(w, "Piece length: %s\n",
681 return fmt.Sprintf("%v (%v chunks)",
683 float64(t.usualPieceSize())/float64(t.chunkSize))
690 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
691 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
692 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
693 // availability frequencies instead.
695 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
696 for _, run := range t.pieceAvailabilityRuns() {
697 ret = append(ret, run.String())
702 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
703 func() (ret []string) {
704 for avail, freq := range t.pieceAvailabilityFrequencies() {
708 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
714 fmt.Fprintf(w, "Reader Pieces:")
715 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
716 fmt.Fprintf(w, " %d:%d", begin, end)
721 fmt.Fprintf(w, "Enabled trackers:\n")
723 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
724 fmt.Fprintf(tw, " URL\tExtra\n")
725 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
728 var luns, runs url.URL = *lu, *ru
731 var ml missinggo.MultiLess
732 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
733 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
735 }).([]torrentTrackerAnnouncer) {
736 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
741 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
743 spew.NewDefaultConfig()
744 spew.Fdump(w, t.statsLocked())
746 peers := t.peersAsSlice()
747 sort.Slice(peers, func(_i, _j int) bool {
750 if less, ok := multiless.New().EagerSameLess(
751 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
755 return worseConn(i, j)
757 for i, c := range peers {
758 fmt.Fprintf(w, "%2d. ", i+1)
763 func (t *Torrent) haveInfo() bool {
767 // Returns a run-time generated MetaInfo that includes the info bytes and
768 // announce-list as currently known to the client.
769 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
770 return metainfo.MetaInfo{
771 CreationDate: time.Now().Unix(),
772 Comment: "dynamic metainfo from client",
773 CreatedBy: "go.torrent",
774 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
775 InfoBytes: func() []byte {
777 return t.metadataBytes
782 UrlList: func() []string {
783 ret := make([]string, 0, len(t.webSeeds))
784 for url := range t.webSeeds {
785 ret = append(ret, url)
793 func (t *Torrent) BytesMissing() (n int64) {
795 n = t.bytesMissingLocked()
800 func (t *Torrent) bytesMissingLocked() int64 {
804 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
805 roaring.Flip(b, 0, end).Iterate(cb)
808 func (t *Torrent) bytesLeft() (left int64) {
809 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
810 p := t.piece(pieceIndex(x))
811 left += int64(p.length() - p.numDirtyBytes())
817 // Bytes left to give in tracker announces.
818 func (t *Torrent) bytesLeftAnnounce() int64 {
826 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
827 if t.pieceComplete(piece) {
830 if t.pieceAllDirty(piece) {
833 return t.pieces[piece].hasDirtyChunks()
836 func (t *Torrent) usualPieceSize() int {
837 return int(t.info.PieceLength)
840 func (t *Torrent) numPieces() pieceIndex {
841 return pieceIndex(t.info.NumPieces())
844 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
845 return pieceIndex(t._completedPieces.GetCardinality())
848 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
850 if t.storage != nil {
855 defer t.storageLock.Unlock()
856 if f := t.storage.Close; f != nil {
859 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
864 t.iterPeers(func(p *Peer) {
867 if t.storage != nil {
868 t.deletePieceRequestOrder()
870 for i := range t.pieces {
872 if p.relativeAvailability != 0 {
873 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
877 t.cl.event.Broadcast()
878 t.pieceStateChanges.Close()
879 t.updateWantPeersEvent()
883 func (t *Torrent) requestOffset(r Request) int64 {
884 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
887 // Return the request that would include the given offset into the torrent data. Returns !ok if
888 // there is no such request.
889 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
890 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
893 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
894 defer perf.ScopeTimerErr(&err)()
895 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
896 if err == nil && n != len(data) {
897 err = io.ErrShortWrite
902 func (t *Torrent) bitfield() (bf []bool) {
903 bf = make([]bool, t.numPieces())
904 t._completedPieces.Iterate(func(piece uint32) (again bool) {
911 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
912 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
915 func (t *Torrent) chunksPerRegularPiece() uint32 {
916 return uint32((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
919 func (t *Torrent) numRequests() RequestIndex {
920 if t.numPieces() == 0 {
923 return uint32(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
926 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
927 t.dirtyChunks.RemoveRange(
928 uint64(t.pieceRequestIndexOffset(pieceIndex)),
929 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
932 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
933 if t.info.PieceLength == 0 {
934 // There will be no variance amongst pieces. Only pain.
937 if piece == t.numPieces()-1 {
938 ret := pp.Integer(*t.length % t.info.PieceLength)
943 return pp.Integer(t.info.PieceLength)
946 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
947 return &blockCheckingWriter{
948 cache: &t.smartBanCache,
949 requestIndex: t.pieceRequestIndexOffset(piece),
950 chunkSize: t.chunkSize.Int(),
954 func (t *Torrent) hashPiece(piece pieceIndex) (
956 // These are peers that sent us blocks that differ from what we hash here.
957 differingPeers map[bannableAddr]struct{},
961 p.waitNoPendingWrites()
962 storagePiece := t.pieces[piece].Storage()
964 // Does the backend want to do its own hashing?
965 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
966 var sum metainfo.Hash
967 // log.Printf("A piece decided to self-hash: %d", piece)
968 sum, err = i.SelfHash()
969 missinggo.CopyExact(&ret, sum)
973 hash := pieceHash.New()
974 const logPieceContents = false
975 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
976 writers := []io.Writer{hash, smartBanWriter}
977 var examineBuf bytes.Buffer
978 if logPieceContents {
979 writers = append(writers, &examineBuf)
981 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
982 if logPieceContents {
983 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
985 smartBanWriter.Flush()
986 differingPeers = smartBanWriter.badPeers
987 missinggo.CopyExact(&ret, hash.Sum(nil))
991 func (t *Torrent) haveAnyPieces() bool {
992 return !t._completedPieces.IsEmpty()
995 func (t *Torrent) haveAllPieces() bool {
999 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1002 func (t *Torrent) havePiece(index pieceIndex) bool {
1003 return t.haveInfo() && t.pieceComplete(index)
1006 func (t *Torrent) maybeDropMutuallyCompletePeer(
1007 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1011 if !t.cl.config.DropMutuallyCompletePeers {
1014 if !t.haveAllPieces() {
1017 if all, known := p.peerHasAllPieces(); !(known && all) {
1023 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1027 func (t *Torrent) haveChunk(r Request) (ret bool) {
1029 // log.Println("have chunk", r, ret)
1034 if t.pieceComplete(pieceIndex(r.Index)) {
1037 p := &t.pieces[r.Index]
1038 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1041 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1042 return chunkIndexType(cs.Begin / chunkSize)
1045 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1046 return t._pendingPieces.Contains(uint32(index))
1049 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1050 // conns (which is a map).
1051 var peerConnSlices sync.Pool
1053 func getPeerConnSlice(cap int) []*PeerConn {
1054 getInterface := peerConnSlices.Get()
1055 if getInterface == nil {
1056 return make([]*PeerConn, 0, cap)
1058 return getInterface.([]*PeerConn)[:0]
1062 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1063 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1064 // established connections for more than a minute. This is O(n log n). If there was a way to not
1065 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1066 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1067 wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
1068 defer peerConnSlices.Put(wcs.conns)
1071 for wcs.Len() != 0 {
1072 c := heap.Pop(&wcs).(*PeerConn)
1073 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1076 // If the connection is in the worst half of the established
1077 // connection quota and is older than a minute.
1078 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1079 // Give connections 1 minute to prove themselves.
1080 if time.Since(c.completedHandshake) > time.Minute {
1088 type PieceStateChange struct {
1093 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1094 t.cl._mu.Defer(func() {
1095 cur := t.pieceState(piece)
1096 p := &t.pieces[piece]
1097 if cur != p.publicPieceState {
1098 p.publicPieceState = cur
1099 t.pieceStateChanges.Publish(PieceStateChange{
1107 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1108 if t.pieceComplete(piece) {
1111 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1114 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1115 return t.pieces[piece].allChunksDirty()
1118 func (t *Torrent) readersChanged() {
1119 t.updateReaderPieces()
1120 t.updateAllPiecePriorities("Torrent.readersChanged")
1123 func (t *Torrent) updateReaderPieces() {
1124 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1127 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1131 t.updateReaderPieces()
1132 // Order the ranges, high and low.
1134 if l.begin > h.begin {
1137 if l.end < h.begin {
1138 // Two distinct ranges.
1139 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1140 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1147 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1151 func (t *Torrent) maybeNewConns() {
1152 // Tickle the accept routine.
1153 t.cl.event.Broadcast()
1157 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1158 if t._pendingPieces.Contains(uint32(piece)) {
1159 t.iterPeers(func(c *Peer) {
1160 // if c.requestState.Interested {
1163 if !c.isLowOnRequests() {
1166 if !c.peerHasPiece(piece) {
1169 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(uint32(piece)) {
1172 c.updateRequests(reason)
1176 t.publishPieceChange(piece)
1179 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1180 if !t.closed.IsSet() {
1181 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1183 t.updatePieceRequestOrder(piece)
1185 p := &t.pieces[piece]
1186 newPrio := p.uncachedPriority()
1187 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1188 if newPrio == PiecePriorityNone {
1189 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1193 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1197 t.piecePriorityChanged(piece, reason)
1200 func (t *Torrent) updateAllPiecePriorities(reason string) {
1201 t.updatePiecePriorities(0, t.numPieces(), reason)
1204 // Update all piece priorities in one hit. This function should have the same
1205 // output as updatePiecePriority, but across all pieces.
1206 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1207 for i := begin; i < end; i++ {
1208 t.updatePiecePriority(i, reason)
1212 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1213 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1214 if off >= *t.length {
1224 begin = pieceIndex(off / t.info.PieceLength)
1225 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1226 if end > pieceIndex(t.info.NumPieces()) {
1227 end = pieceIndex(t.info.NumPieces())
1232 // Returns true if all iterations complete without breaking. Returns the read regions for all
1233 // readers. The reader regions should not be merged as some callers depend on this method to
1234 // enumerate readers.
1235 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1236 for r := range t.readers {
1238 if p.begin >= p.end {
1241 if !f(p.begin, p.end) {
1248 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1249 return t.piece(piece).uncachedPriority()
1252 func (t *Torrent) pendRequest(req RequestIndex) {
1253 t.piece(int(req / t.chunksPerRegularPiece())).pendChunkIndex(req % t.chunksPerRegularPiece())
1256 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1257 t.cl.event.Broadcast()
1258 if t.pieceComplete(piece) {
1259 t.onPieceCompleted(piece)
1261 t.onIncompletePiece(piece)
1263 t.updatePiecePriority(piece, reason)
1266 func (t *Torrent) numReceivedConns() (ret int) {
1267 for c := range t.conns {
1268 if c.Discovery == PeerSourceIncoming {
1275 func (t *Torrent) maxHalfOpen() int {
1276 // Note that if we somehow exceed the maximum established conns, we want
1277 // the negative value to have an effect.
1278 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1279 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1280 // We want to allow some experimentation with new peers, and to try to
1281 // upset an oversupply of received connections.
1282 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1285 func (t *Torrent) openNewConns() (initiated int) {
1286 defer t.updateWantPeersEvent()
1287 for t.peers.Len() != 0 {
1291 if len(t.halfOpen) >= t.maxHalfOpen() {
1294 if len(t.cl.dialers) == 0 {
1297 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1300 p := t.peers.PopMax()
1307 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1309 uncached := t.pieceCompleteUncached(piece)
1310 cached := p.completion()
1311 changed := cached != uncached
1312 complete := uncached.Complete
1313 p.storageCompletionOk = uncached.Ok
1316 t._completedPieces.Add(x)
1319 t._completedPieces.Remove(x)
1321 p.t.updatePieceRequestOrder(piece)
1323 if complete && len(p.dirtiers) != 0 {
1324 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1327 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1328 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1333 // Non-blocking read. Client lock is not required.
1334 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1336 p := &t.pieces[off/t.info.PieceLength]
1337 p.waitNoPendingWrites()
1339 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1350 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1351 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1352 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1353 func (t *Torrent) maybeCompleteMetadata() error {
1358 if !t.haveAllMetadataPieces() {
1359 // Don't have enough metadata pieces.
1362 err := t.setInfoBytesLocked(t.metadataBytes)
1364 t.invalidateMetadata()
1365 return fmt.Errorf("error setting info bytes: %s", err)
1367 if t.cl.config.Debug {
1368 t.logger.Printf("%s: got metadata from peers", t)
1373 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1374 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1376 now.Add(bitmap.BitIndex(begin))
1377 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1384 func (t *Torrent) needData() bool {
1385 if t.closed.IsSet() {
1391 return !t._pendingPieces.IsEmpty()
1394 func appendMissingStrings(old, new []string) (ret []string) {
1397 for _, n := range new {
1398 for _, o := range old {
1403 ret = append(ret, n)
1408 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1410 for minNumTiers > len(ret) {
1411 ret = append(ret, nil)
1416 func (t *Torrent) addTrackers(announceList [][]string) {
1417 fullAnnounceList := &t.metainfo.AnnounceList
1418 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1419 for tierIndex, trackerURLs := range announceList {
1420 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1422 t.startMissingTrackerScrapers()
1423 t.updateWantPeersEvent()
1426 // Don't call this before the info is available.
1427 func (t *Torrent) bytesCompleted() int64 {
1431 return *t.length - t.bytesLeft()
1434 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1437 return t.setInfoBytesLocked(b)
1440 // Returns true if connection is removed from torrent.Conns.
1441 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1442 if !c.closed.IsSet() {
1443 panic("connection is not closed")
1444 // There are behaviours prevented by the closed state that will fail
1445 // if the connection has been deleted.
1449 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1450 // the drop event against the PexConnState instead.
1452 if !t.cl.config.DisablePEX {
1456 torrent.Add("deleted connections", 1)
1457 if !c.deleteAllRequests().IsEmpty() {
1458 t.iterPeers(func(p *Peer) {
1459 if p.isLowOnRequests() {
1460 p.updateRequests("Torrent.deletePeerConn")
1464 t.assertPendingRequests()
1465 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1466 panic(t.connsWithAllPieces)
1471 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1472 if t.deleteConnWithAllPieces(p) {
1478 p.peerPieces().Iterate(func(i uint32) bool {
1479 p.t.decPieceAvailability(pieceIndex(i))
1484 func (t *Torrent) assertPendingRequests() {
1488 // var actual pendingRequests
1489 // if t.haveInfo() {
1490 // actual.m = make([]int, t.numRequests())
1492 // t.iterPeers(func(p *Peer) {
1493 // p.requestState.Requests.Iterate(func(x uint32) bool {
1498 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1504 func (t *Torrent) dropConnection(c *PeerConn) {
1505 t.cl.event.Broadcast()
1507 if t.deletePeerConn(c) {
1512 // Peers as in contact information for dialing out.
1513 func (t *Torrent) wantPeers() bool {
1514 if t.closed.IsSet() {
1517 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1520 return t.wantConns()
1523 func (t *Torrent) updateWantPeersEvent() {
1525 t.wantPeersEvent.Set()
1527 t.wantPeersEvent.Clear()
1531 // Returns whether the client should make effort to seed the torrent.
1532 func (t *Torrent) seeding() bool {
1534 if t.closed.IsSet() {
1537 if t.dataUploadDisallowed {
1540 if cl.config.NoUpload {
1543 if !cl.config.Seed {
1546 if cl.config.DisableAggressiveUpload && t.needData() {
1552 func (t *Torrent) onWebRtcConn(
1553 c datachannel.ReadWriteCloser,
1554 dcc webtorrent.DataChannelContext,
1557 netConn := webrtcNetConn{
1559 DataChannelContext: dcc,
1561 peerRemoteAddr := netConn.RemoteAddr()
1562 if t.cl.badPeerAddr(peerRemoteAddr) {
1565 pc, err := t.cl.initiateProtocolHandshakes(
1566 context.Background(),
1571 netConn.RemoteAddr(),
1573 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1576 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1579 if dcc.LocalOffered {
1580 pc.Discovery = PeerSourceTracker
1582 pc.Discovery = PeerSourceIncoming
1584 pc.conn.SetWriteDeadline(time.Time{})
1587 err = t.cl.runHandshookConn(pc, t)
1589 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1593 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1594 err := t.cl.runHandshookConn(pc, t)
1595 if err != nil || logAll {
1596 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1600 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1601 t.logRunHandshookConn(pc, false, log.Debug)
1604 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1605 wtc, release := t.cl.websocketTrackers.Get(u.String())
1610 wst := websocketTrackerStatus{u, wtc}
1612 err := wtc.Announce(tracker.Started, t.infoHash)
1614 t.logger.WithDefaultLevel(log.Warning).Printf(
1615 "error in initial announce to %q: %v",
1623 func (t *Torrent) startScrapingTracker(_url string) {
1627 u, err := url.Parse(_url)
1629 // URLs with a leading '*' appear to be a uTorrent convention to
1630 // disable trackers.
1632 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1636 if u.Scheme == "udp" {
1638 t.startScrapingTracker(u.String())
1640 t.startScrapingTracker(u.String())
1643 if _, ok := t.trackerAnnouncers[_url]; ok {
1646 sl := func() torrentTrackerAnnouncer {
1649 if t.cl.config.DisableWebtorrent {
1652 return t.startWebsocketAnnouncer(*u)
1654 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1658 if t.cl.config.DisableIPv6 {
1662 newAnnouncer := &trackerScraper{
1665 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1667 go newAnnouncer.Run()
1673 if t.trackerAnnouncers == nil {
1674 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1676 t.trackerAnnouncers[_url] = sl
1679 // Adds and starts tracker scrapers for tracker URLs that aren't already
1681 func (t *Torrent) startMissingTrackerScrapers() {
1682 if t.cl.config.DisableTrackers {
1685 t.startScrapingTracker(t.metainfo.Announce)
1686 for _, tier := range t.metainfo.AnnounceList {
1687 for _, url := range tier {
1688 t.startScrapingTracker(url)
1693 // Returns an AnnounceRequest with fields filled out to defaults and current
1695 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1696 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1697 // dependent on the network in use.
1698 return tracker.AnnounceRequest{
1700 NumWant: func() int32 {
1701 if t.wantPeers() && len(t.cl.dialers) > 0 {
1707 Port: uint16(t.cl.incomingPeerPort()),
1708 PeerId: t.cl.peerID,
1709 InfoHash: t.infoHash,
1710 Key: t.cl.announceKey(),
1712 // The following are vaguely described in BEP 3.
1714 Left: t.bytesLeftAnnounce(),
1715 Uploaded: t.stats.BytesWrittenData.Int64(),
1716 // There's no mention of wasted or unwanted download in the BEP.
1717 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1721 // Adds peers revealed in an announce until the announce ends, or we have
1723 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1725 for v := range pvs {
1728 for _, cp := range v.Peers {
1730 // Can't do anything with this.
1733 if t.addPeer(PeerInfo{
1734 Addr: ipPortAddr{cp.IP, cp.Port},
1735 Source: PeerSourceDhtGetPeers,
1742 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1747 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1748 // announce ends. stop will force the announce to end.
1749 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1750 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1754 _done := make(chan struct{})
1758 t.consumeDhtAnnouncePeers(ps.Peers())
1764 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1765 _, stop, err := t.AnnounceToDht(s)
1770 case <-t.closed.Done():
1771 case <-time.After(5 * time.Minute):
1777 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1783 if t.closed.IsSet() {
1786 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1787 // TODO: We can include the announce_peer step depending on whether we can receive
1788 // inbound connections. We should probably only announce once every 15 mins too.
1792 // TODO: Determine if there's a listener on the port we're announcing.
1793 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1804 err := t.timeboxedAnnounceToDht(s)
1806 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1812 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1813 for _, p := range peers {
1821 // The returned TorrentStats may require alignment in memory. See
1822 // https://github.com/anacrolix/torrent/issues/383.
1823 func (t *Torrent) Stats() TorrentStats {
1825 defer t.cl.rUnlock()
1826 return t.statsLocked()
1829 func (t *Torrent) statsLocked() (ret TorrentStats) {
1830 ret.ActivePeers = len(t.conns)
1831 ret.HalfOpenPeers = len(t.halfOpen)
1832 ret.PendingPeers = t.peers.Len()
1833 ret.TotalPeers = t.numTotalPeers()
1834 ret.ConnectedSeeders = 0
1835 for c := range t.conns {
1836 if all, ok := c.peerHasAllPieces(); all && ok {
1837 ret.ConnectedSeeders++
1840 ret.ConnStats = t.stats.Copy()
1841 ret.PiecesComplete = t.numPiecesCompleted()
1845 // The total number of peers in the torrent.
1846 func (t *Torrent) numTotalPeers() int {
1847 peers := make(map[string]struct{})
1848 for conn := range t.conns {
1849 ra := conn.conn.RemoteAddr()
1851 // It's been closed and doesn't support RemoteAddr.
1854 peers[ra.String()] = struct{}{}
1856 for addr := range t.halfOpen {
1857 peers[addr] = struct{}{}
1859 t.peers.Each(func(peer PeerInfo) {
1860 peers[peer.Addr.String()] = struct{}{}
1865 // Reconcile bytes transferred before connection was associated with a
1867 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1868 if c._stats != (ConnStats{
1869 // Handshakes should only increment these fields:
1870 BytesWritten: c._stats.BytesWritten,
1871 BytesRead: c._stats.BytesRead,
1875 c.postHandshakeStats(func(cs *ConnStats) {
1876 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1877 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1879 c.reconciledHandshakeStats = true
1882 // Returns true if the connection is added.
1883 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1886 torrent.Add("added connections", 1)
1889 if t.closed.IsSet() {
1890 return errors.New("torrent closed")
1892 for c0 := range t.conns {
1893 if c.PeerID != c0.PeerID {
1896 if !t.cl.config.DropDuplicatePeerIds {
1899 if c.hasPreferredNetworkOver(c0) {
1901 t.deletePeerConn(c0)
1903 return errors.New("existing connection preferred")
1906 if len(t.conns) >= t.maxEstablishedConns {
1907 c := t.worstBadConn()
1909 return errors.New("don't want conns")
1914 if len(t.conns) >= t.maxEstablishedConns {
1917 t.conns[c] = struct{}{}
1918 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1919 t.pex.Add(c) // as no further extended handshake expected
1924 func (t *Torrent) wantConns() bool {
1925 if !t.networkingEnabled.Bool() {
1928 if t.closed.IsSet() {
1931 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
1934 return len(t.conns) < t.maxEstablishedConns || t.worstBadConn() != nil
1937 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1940 oldMax = t.maxEstablishedConns
1941 t.maxEstablishedConns = max
1942 wcs := worseConnSlice{
1943 conns: t.appendConns(nil, func(*PeerConn) bool {
1949 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1950 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
1956 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1957 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1960 t.cl.event.Broadcast()
1961 if t.closed.IsSet() {
1965 // Don't score the first time a piece is hashed, it could be an initial check.
1966 if p.storageCompletionOk {
1968 pieceHashedCorrect.Add(1)
1971 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1972 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1973 pieceHashedNotCorrect.Add(1)
1978 t.publishPieceChange(piece)
1981 t.publishPieceChange(piece)
1985 if len(p.dirtiers) != 0 {
1986 // Don't increment stats above connection-level for every involved connection.
1987 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1989 for c := range p.dirtiers {
1990 c._stats.incrementPiecesDirtiedGood()
1992 t.clearPieceTouchers(piece)
1994 err := p.Storage().MarkComplete()
1996 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2000 if t.closed.IsSet() {
2003 t.pendAllChunkSpecs(piece)
2005 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2006 // Peers contributed to all the data for this piece hash failure, and the failure was
2007 // not due to errors in the storage (such as data being dropped in a cache).
2009 // Increment Torrent and above stats, and then specific connections.
2010 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2011 for c := range p.dirtiers {
2012 // Y u do dis peer?!
2013 c.stats().incrementPiecesDirtiedBad()
2016 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2017 for c := range p.dirtiers {
2019 bannableTouchers = append(bannableTouchers, c)
2022 t.clearPieceTouchers(piece)
2023 slices.Sort(bannableTouchers, connLessTrusted)
2025 if t.cl.config.Debug {
2027 "bannable conns by trust for piece %d: %v",
2029 func() (ret []connectionTrust) {
2030 for _, c := range bannableTouchers {
2031 ret = append(ret, c.trust())
2038 if len(bannableTouchers) >= 1 {
2039 c := bannableTouchers[0]
2040 log.Printf("would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2042 t.cl.banPeerIP(c.remoteIp())
2047 t.onIncompletePiece(piece)
2048 p.Storage().MarkNotComplete()
2050 t.updatePieceCompletion(piece)
2053 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2054 for ri := t.pieceRequestIndexOffset(piece); ri < t.pieceRequestIndexOffset(piece+1); ri++ {
2059 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2060 t.pendAllChunkSpecs(piece)
2061 t.cancelRequestsForPiece(piece)
2062 t.piece(piece).readerCond.Broadcast()
2063 for conn := range t.conns {
2065 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2069 // Called when a piece is found to be not complete.
2070 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2071 if t.pieceAllDirty(piece) {
2072 t.pendAllChunkSpecs(piece)
2074 if !t.wantPieceIndex(piece) {
2075 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2078 // We could drop any connections that we told we have a piece that we
2079 // don't here. But there's a test failure, and it seems clients don't care
2080 // if you request pieces that you already claim to have. Pruning bad
2081 // connections might just remove any connections that aren't treating us
2082 // favourably anyway.
2084 // for c := range t.conns {
2085 // if c.sentHave(piece) {
2089 t.iterPeers(func(conn *Peer) {
2090 if conn.peerHasPiece(piece) {
2091 conn.updateRequests("piece incomplete")
2096 func (t *Torrent) tryCreateMorePieceHashers() {
2097 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2101 func (t *Torrent) tryCreatePieceHasher() bool {
2102 if t.storage == nil {
2105 pi, ok := t.getPieceToHash()
2110 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2112 t.publishPieceChange(pi)
2113 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2114 t.storageLock.RLock()
2115 t.activePieceHashes++
2116 go t.pieceHasher(pi)
2120 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2121 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2122 if t.piece(i).hashing {
2132 func (t *Torrent) dropBannedPeers() {
2133 t.iterPeers(func(p *Peer) {
2134 remoteIp := p.remoteIp()
2135 if remoteIp == nil {
2136 if p.bannableAddr.Ok() {
2137 log.Printf("can't get remote ip for peer %v", p)
2141 netipAddr := netip.MustParseAddr(remoteIp.String())
2142 if option.Some(netipAddr) != p.bannableAddr {
2144 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2145 p, remoteIp, p.bannableAddr)
2147 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2149 log.Printf("dropped %v for banned remote IP %v", p, netipAddr)
2154 func (t *Torrent) pieceHasher(index pieceIndex) {
2156 sum, failedPeers, copyErr := t.hashPiece(index)
2157 correct := sum == *p.hash
2161 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2163 t.storageLock.RUnlock()
2167 for peer := range failedPeers {
2168 t.cl.banPeerIP(peer.AsSlice())
2169 log.Printf("smart banned %v for piece %v", peer, index)
2172 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2173 t.smartBanCache.ForgetBlock(ri)
2177 t.pieceHashed(index, correct, copyErr)
2178 t.updatePiecePriority(index, "Torrent.pieceHasher")
2179 t.activePieceHashes--
2180 t.tryCreateMorePieceHashers()
2183 // Return the connections that touched a piece, and clear the entries while doing it.
2184 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2186 for c := range p.dirtiers {
2187 delete(c.peerTouchedPieces, pi)
2188 delete(p.dirtiers, c)
2192 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2193 t.iterPeers(func(p *Peer) {
2194 ret = append(ret, p)
2199 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2200 piece := t.piece(pieceIndex)
2201 if piece.queuedForHash() {
2204 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2205 t.publishPieceChange(pieceIndex)
2206 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2207 t.tryCreateMorePieceHashers()
2210 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2211 // before the Info is available.
2212 func (t *Torrent) VerifyData() {
2213 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2214 t.Piece(i).VerifyData()
2218 // Start the process of connecting to the given peer for the given torrent if appropriate.
2219 func (t *Torrent) initiateConn(peer PeerInfo) {
2220 if peer.Id == t.cl.peerID {
2223 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2227 if t.addrActive(addr.String()) {
2231 t.halfOpen[addr.String()] = peer
2232 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2235 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2236 // quickly make one Client visible to the Torrent of another Client.
2237 func (t *Torrent) AddClientPeer(cl *Client) int {
2238 return t.AddPeers(func() (ps []PeerInfo) {
2239 for _, la := range cl.ListenAddrs() {
2240 ps = append(ps, PeerInfo{
2249 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2251 func (t *Torrent) allStats(f func(*ConnStats)) {
2256 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2257 return t.pieces[i].hashing
2260 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2261 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2264 func (t *Torrent) dialTimeout() time.Duration {
2265 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2268 func (t *Torrent) piece(i int) *Piece {
2272 func (t *Torrent) onWriteChunkErr(err error) {
2273 if t.userOnWriteChunkErr != nil {
2274 go t.userOnWriteChunkErr(err)
2277 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2278 t.disallowDataDownloadLocked()
2281 func (t *Torrent) DisallowDataDownload() {
2282 t.disallowDataDownloadLocked()
2285 func (t *Torrent) disallowDataDownloadLocked() {
2286 t.dataDownloadDisallowed.Set()
2289 func (t *Torrent) AllowDataDownload() {
2290 t.dataDownloadDisallowed.Clear()
2293 // Enables uploading data, if it was disabled.
2294 func (t *Torrent) AllowDataUpload() {
2297 t.dataUploadDisallowed = false
2298 for c := range t.conns {
2299 c.updateRequests("allow data upload")
2303 // Disables uploading data, if it was enabled.
2304 func (t *Torrent) DisallowDataUpload() {
2307 t.dataUploadDisallowed = true
2308 for c := range t.conns {
2309 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2310 c.updateRequests("disallow data upload")
2314 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2315 // or if nil, a critical message is logged, and data download is disabled.
2316 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2319 t.userOnWriteChunkErr = f
2322 func (t *Torrent) iterPeers(f func(p *Peer)) {
2323 for pc := range t.conns {
2326 for _, ws := range t.webSeeds {
2331 func (t *Torrent) callbacks() *Callbacks {
2332 return &t.cl.config.Callbacks
2335 func (t *Torrent) addWebSeed(url string) {
2336 if t.cl.config.DisableWebseeds {
2339 if _, ok := t.webSeeds[url]; ok {
2342 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2343 // right away. This value should be some multiple of the number of connections to a host. I
2344 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2345 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2346 // "https://webtorrent.io/torrents/".
2347 const maxRequests = 16
2353 reconciledHandshakeStats: true,
2354 // This should affect how often we have to recompute requests for this peer. Note that
2355 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2356 // requests mark more often, so recomputation is probably sooner than with regular peer
2357 // conns. ~4x maxRequests would be about right.
2358 PeerMaxRequests: 128,
2359 // TODO: Set ban prefix?
2360 RemoteAddr: remoteAddrFromUrl(url),
2361 callbacks: t.callbacks(),
2363 client: webseed.Client{
2364 HttpClient: t.cl.webseedHttpClient,
2366 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2367 return &rateLimitedReader{
2368 l: t.cl.config.DownloadRateLimiter,
2373 activeRequests: make(map[Request]webseed.Request, maxRequests),
2374 maxRequests: maxRequests,
2376 ws.peer.initUpdateRequestsTimer()
2377 ws.requesterCond.L = t.cl.locker()
2378 for i := 0; i < maxRequests; i += 1 {
2381 for _, f := range t.callbacks().NewPeer {
2384 ws.peer.logger = t.logger.WithContextValue(&ws)
2385 ws.peer.peerImpl = &ws
2387 ws.onGotInfo(t.info)
2389 t.webSeeds[url] = &ws.peer
2392 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2393 t.iterPeers(func(p1 *Peer) {
2401 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2402 index := ri / t.chunksPerRegularPiece()
2405 t.piece(int(index)).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2409 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2410 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + uint32(r.Begin/t.chunkSize)
2413 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2414 return RequestIndex(piece) * t.chunksPerRegularPiece()
2417 func (t *Torrent) updateComplete() {
2418 t.Complete.SetBool(t.haveAllPieces())
2421 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2422 p := t.pendingRequests[r]
2426 delete(t.pendingRequests, r)
2430 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2431 return t.pendingRequests[r]
2434 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2435 if t.connsWithAllPieces == nil {
2436 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2438 t.connsWithAllPieces[p] = struct{}{}
2441 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2442 _, ok := t.connsWithAllPieces[p]
2443 delete(t.connsWithAllPieces, p)
2447 func (t *Torrent) numActivePeers() int {
2448 return len(t.conns) + len(t.webSeeds)
2451 func (t *Torrent) hasStorageCap() bool {
2452 f := t.storage.Capacity