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 request_strategy "github.com/anacrolix/torrent/request-strategy"
31 "github.com/davecgh/go-spew/spew"
32 "github.com/pion/datachannel"
34 "github.com/anacrolix/torrent/bencode"
35 "github.com/anacrolix/torrent/common"
36 "github.com/anacrolix/torrent/metainfo"
37 pp "github.com/anacrolix/torrent/peer_protocol"
38 "github.com/anacrolix/torrent/segments"
39 "github.com/anacrolix/torrent/storage"
40 "github.com/anacrolix/torrent/tracker"
41 "github.com/anacrolix/torrent/webseed"
42 "github.com/anacrolix/torrent/webtorrent"
45 // Maintains state of torrent within a Client. Many methods should not be called before the info is
46 // available, see .Info and .GotInfo.
48 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
49 // alignment. See #262.
54 networkingEnabled chansync.Flag
55 dataDownloadDisallowed chansync.Flag
56 dataUploadDisallowed bool
57 userOnWriteChunkErr func(error)
59 closed chansync.SetOnce
60 infoHash metainfo.Hash
62 // Values are the piece indices that changed.
63 pieceStateChanges *pubsub.PubSub
64 // The size of chunks to request from peers over the wire. This is
65 // normally 16KiB by convention these days.
68 // Total length of the torrent in bytes. Stored because it's not O(1) to
69 // get this from the info dict.
72 // The storage to open when the info dict becomes available.
73 storageOpener *storage.Client
74 // Storage for torrent data.
75 storage *storage.Torrent
76 // Read-locked for using storage, and write-locked for Closing.
77 storageLock sync.RWMutex
79 // TODO: Only announce stuff is used?
80 metainfo metainfo.MetaInfo
82 // The info dict. nil if we don't have it (yet).
84 fileIndex segments.Index
87 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 connsWithAllPieces map[*Peer]struct{}
140 // Count of each request across active connections.
141 pendingRequests map[RequestIndex]*Peer
142 lastRequested map[RequestIndex]time.Time
143 // Chunks we've written to since the corresponding piece was last checked.
144 dirtyChunks roaring.Bitmap
148 // Is On when all pieces are complete.
149 Complete chansync.Flag
151 smartBanCache smartBanCache
154 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
155 // This could be done with roaring.BitSliceIndexing.
156 t.iterPeers(func(peer *Peer) {
157 if _, ok := t.connsWithAllPieces[peer]; ok {
160 if peer.peerHasPiece(i) {
167 func (t *Torrent) decPieceAvailability(i pieceIndex) {
172 if p.relativeAvailability <= 0 {
173 panic(p.relativeAvailability)
175 p.relativeAvailability--
176 t.updatePieceRequestOrder(i)
179 func (t *Torrent) incPieceAvailability(i pieceIndex) {
180 // If we don't the info, this should be reconciled when we do.
183 p.relativeAvailability++
184 t.updatePieceRequestOrder(i)
188 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
189 return t._readerNowPieces
192 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
193 return t._readerReadaheadPieces
196 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
197 return !t.wantPieceIndex(i)
200 // Returns a channel that is closed when the Torrent is closed.
201 func (t *Torrent) Closed() events.Done {
202 return t.closed.Done()
205 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
206 // pending, and half-open peers.
207 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
208 // Add pending peers to the list
209 t.peers.Each(func(peer PeerInfo) {
210 ks = append(ks, peer)
213 // Add half-open peers to the list
214 for _, peer := range t.halfOpen {
215 ks = append(ks, peer)
218 // Add active peers to the list
219 for conn := range t.conns {
220 ks = append(ks, PeerInfo{
222 Addr: conn.RemoteAddr,
223 Source: conn.Discovery,
224 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
225 // > But if we're not connected to them with an encrypted connection, I couldn't say
226 // > what's appropriate. We can carry forward the SupportsEncryption value as we
227 // > received it from trackers/DHT/PEX, or just use the encryption state for the
228 // > connection. It's probably easiest to do the latter for now.
229 // https://github.com/anacrolix/torrent/pull/188
230 SupportsEncryption: conn.headerEncrypted,
237 func (t *Torrent) setChunkSize(size pp.Integer) {
239 t.chunkPool = sync.Pool{
240 New: func() interface{} {
241 b := make([]byte, size)
247 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
248 return t._completedPieces.Contains(bitmap.BitIndex(piece))
251 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
252 if t.storage == nil {
253 return storage.Completion{Complete: false, Ok: true}
255 return t.pieces[piece].Storage().Completion()
258 // There's a connection to that address already.
259 func (t *Torrent) addrActive(addr string) bool {
260 if _, ok := t.halfOpen[addr]; ok {
263 for c := range t.conns {
265 if ra.String() == addr {
272 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
273 return t.appendConns(ret, func(conn *PeerConn) bool {
274 return !conn.closed.IsSet()
278 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
279 for c := range t.conns {
287 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
289 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
290 if t.closed.IsSet() {
293 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
294 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
295 torrent.Add("peers not added because of bad addr", 1)
296 // cl.logger.Printf("peers not added because of bad addr: %v", p)
300 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
301 torrent.Add("peers replaced", 1)
302 if !replaced.equal(p) {
303 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
310 for t.peers.Len() > cl.config.TorrentPeersHighWater {
311 _, ok := t.peers.DeleteMin()
313 torrent.Add("excess reserve peers discarded", 1)
319 func (t *Torrent) invalidateMetadata() {
320 for i := 0; i < len(t.metadataCompletedChunks); i++ {
321 t.metadataCompletedChunks[i] = false
324 t.gotMetainfoC = make(chan struct{})
329 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
333 if index >= len(t.metadataCompletedChunks) {
334 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
337 copy(t.metadataBytes[(1<<14)*index:], data)
338 t.metadataCompletedChunks[index] = true
341 func (t *Torrent) metadataPieceCount() int {
342 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
345 func (t *Torrent) haveMetadataPiece(piece int) bool {
347 return (1<<14)*piece < len(t.metadataBytes)
349 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
353 func (t *Torrent) metadataSize() int {
354 return len(t.metadataBytes)
357 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
358 for i := 0; i < len(info.Pieces); i += sha1.Size {
359 ret = append(ret, info.Pieces[i:i+sha1.Size])
364 func (t *Torrent) makePieces() {
365 hashes := infoPieceHashes(t.info)
366 t.pieces = make([]Piece, len(hashes))
367 for i, hash := range hashes {
368 piece := &t.pieces[i]
370 piece.index = pieceIndex(i)
371 piece.noPendingWrites.L = &piece.pendingWritesMutex
372 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
374 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
375 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
376 piece.files = files[beginFile:endFile]
377 piece.undirtiedChunksIter = undirtiedChunksIter{
378 TorrentDirtyChunks: &t.dirtyChunks,
379 StartRequestIndex: piece.requestIndexOffset(),
380 EndRequestIndex: piece.requestIndexOffset() + piece.numChunks(),
385 // Returns the index of the first file containing the piece. files must be
386 // ordered by offset.
387 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
388 for i, f := range files {
389 if f.offset+f.length > pieceOffset {
396 // Returns the index after the last file containing the piece. files must be
397 // ordered by offset.
398 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
399 for i, f := range files {
400 if f.offset+f.length >= pieceEndOffset {
407 func (t *Torrent) cacheLength() {
409 for _, f := range t.info.UpvertedFiles() {
415 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
417 func (t *Torrent) setInfo(info *metainfo.Info) error {
418 if err := validateInfo(info); err != nil {
419 return fmt.Errorf("bad info: %s", err)
421 if t.storageOpener != nil {
423 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
425 return fmt.Errorf("error opening torrent storage: %s", err)
432 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
433 t.displayName = "" // Save a few bytes lol.
440 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
441 return request_strategy.PieceRequestOrderKey{
442 InfoHash: t.infoHash,
447 // This seems to be all the follow-up tasks after info is set, that can't fail.
448 func (t *Torrent) onSetInfo() {
449 t.initPieceRequestOrder()
450 for i := range t.pieces {
452 // Need to add relativeAvailability before updating piece completion, as that may result in conns
454 if p.relativeAvailability != 0 {
455 panic(p.relativeAvailability)
457 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
458 t.addRequestOrderPiece(i)
459 t.updatePieceCompletion(pieceIndex(i))
460 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
461 // t.logger.Printf("piece %s completion unknown, queueing check", p)
462 t.queuePieceCheck(pieceIndex(i))
465 t.cl.event.Broadcast()
466 close(t.gotMetainfoC)
467 t.updateWantPeersEvent()
468 t.pendingRequests = make(map[RequestIndex]*Peer)
469 t.lastRequested = make(map[RequestIndex]time.Time)
470 t.tryCreateMorePieceHashers()
471 t.iterPeers(func(p *Peer) {
473 p.updateRequests("onSetInfo")
477 // Called when metadata for a torrent becomes available.
478 func (t *Torrent) setInfoBytesLocked(b []byte) error {
479 if metainfo.HashBytes(b) != t.infoHash {
480 return errors.New("info bytes have wrong hash")
482 var info metainfo.Info
483 if err := bencode.Unmarshal(b, &info); err != nil {
484 return fmt.Errorf("error unmarshalling info bytes: %s", err)
487 t.metadataCompletedChunks = nil
491 if err := t.setInfo(&info); err != nil {
498 func (t *Torrent) haveAllMetadataPieces() bool {
502 if t.metadataCompletedChunks == nil {
505 for _, have := range t.metadataCompletedChunks {
513 // TODO: Propagate errors to disconnect peer.
514 func (t *Torrent) setMetadataSize(size int) (err error) {
516 // We already know the correct metadata size.
519 if uint32(size) > maxMetadataSize {
520 return errors.New("bad size")
522 if len(t.metadataBytes) == size {
525 t.metadataBytes = make([]byte, size)
526 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
527 t.metadataChanged.Broadcast()
528 for c := range t.conns {
529 c.requestPendingMetadata()
534 // The current working name for the torrent. Either the name in the info dict,
535 // or a display name given such as by the dn value in a magnet link, or "".
536 func (t *Torrent) name() string {
538 defer t.nameMu.RUnlock()
542 if t.displayName != "" {
545 return "infohash:" + t.infoHash.HexString()
548 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
549 p := &t.pieces[index]
550 ret.Priority = t.piecePriority(index)
551 ret.Completion = p.completion()
552 ret.QueuedForHash = p.queuedForHash()
553 ret.Hashing = p.hashing
554 ret.Checking = ret.QueuedForHash || ret.Hashing
555 ret.Marking = p.marking
556 if !ret.Complete && t.piecePartiallyDownloaded(index) {
562 func (t *Torrent) metadataPieceSize(piece int) int {
563 return metadataPieceSize(len(t.metadataBytes), piece)
566 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
569 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
570 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
572 TotalSize: len(t.metadataBytes),
578 type pieceAvailabilityRun struct {
583 func (me pieceAvailabilityRun) String() string {
584 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
587 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
588 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
589 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
591 for i := range t.pieces {
592 rle.Append(t.pieces[i].availability(), 1)
598 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
599 freqs = make([]int, t.numActivePeers()+1)
600 for i := range t.pieces {
601 freqs[t.piece(i).availability()]++
606 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
607 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
608 ret = append(ret, PieceStateRun{
609 PieceState: el.(PieceState),
613 for index := range t.pieces {
614 rle.Append(t.pieceState(pieceIndex(index)), 1)
620 // Produces a small string representing a PieceStateRun.
621 func (psr PieceStateRun) String() (ret string) {
622 ret = fmt.Sprintf("%d", psr.Length)
623 ret += func() string {
624 switch psr.Priority {
625 case PiecePriorityNext:
627 case PiecePriorityNormal:
629 case PiecePriorityReadahead:
631 case PiecePriorityNow:
633 case PiecePriorityHigh:
642 if psr.QueuedForHash {
660 func (t *Torrent) writeStatus(w io.Writer) {
661 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
662 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
664 fmt.Fprintf(w, "Metadata have: ")
665 for _, h := range t.metadataCompletedChunks {
666 fmt.Fprintf(w, "%c", func() rune {
676 fmt.Fprintf(w, "Piece length: %s\n",
679 return fmt.Sprintf("%v (%v chunks)",
681 float64(t.usualPieceSize())/float64(t.chunkSize))
688 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
689 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
690 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
691 // availability frequencies instead.
693 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
694 for _, run := range t.pieceAvailabilityRuns() {
695 ret = append(ret, run.String())
700 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
701 func() (ret []string) {
702 for avail, freq := range t.pieceAvailabilityFrequencies() {
706 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
712 fmt.Fprintf(w, "Reader Pieces:")
713 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
714 fmt.Fprintf(w, " %d:%d", begin, end)
719 fmt.Fprintf(w, "Enabled trackers:\n")
721 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
722 fmt.Fprintf(tw, " URL\tExtra\n")
723 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
726 var luns, runs url.URL = *lu, *ru
729 var ml missinggo.MultiLess
730 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
731 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
733 }).([]torrentTrackerAnnouncer) {
734 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
739 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
741 spew.NewDefaultConfig()
742 spew.Fdump(w, t.statsLocked())
744 peers := t.peersAsSlice()
745 sort.Slice(peers, func(_i, _j int) bool {
748 if less, ok := multiless.New().EagerSameLess(
749 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
753 return worseConn(i, j)
755 for i, c := range peers {
756 fmt.Fprintf(w, "%2d. ", i+1)
761 func (t *Torrent) haveInfo() bool {
765 // Returns a run-time generated MetaInfo that includes the info bytes and
766 // announce-list as currently known to the client.
767 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
768 return metainfo.MetaInfo{
769 CreationDate: time.Now().Unix(),
770 Comment: "dynamic metainfo from client",
771 CreatedBy: "go.torrent",
772 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
773 InfoBytes: func() []byte {
775 return t.metadataBytes
780 UrlList: func() []string {
781 ret := make([]string, 0, len(t.webSeeds))
782 for url := range t.webSeeds {
783 ret = append(ret, url)
791 func (t *Torrent) BytesMissing() (n int64) {
793 n = t.bytesMissingLocked()
798 func (t *Torrent) bytesMissingLocked() int64 {
802 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
803 roaring.Flip(b, 0, end).Iterate(cb)
806 func (t *Torrent) bytesLeft() (left int64) {
807 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
808 p := t.piece(pieceIndex(x))
809 left += int64(p.length() - p.numDirtyBytes())
815 // Bytes left to give in tracker announces.
816 func (t *Torrent) bytesLeftAnnounce() int64 {
824 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
825 if t.pieceComplete(piece) {
828 if t.pieceAllDirty(piece) {
831 return t.pieces[piece].hasDirtyChunks()
834 func (t *Torrent) usualPieceSize() int {
835 return int(t.info.PieceLength)
838 func (t *Torrent) numPieces() pieceIndex {
839 return pieceIndex(t.info.NumPieces())
842 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
843 return pieceIndex(t._completedPieces.GetCardinality())
846 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
848 if t.storage != nil {
853 defer t.storageLock.Unlock()
854 if f := t.storage.Close; f != nil {
857 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
862 t.iterPeers(func(p *Peer) {
865 if t.storage != nil {
866 t.deletePieceRequestOrder()
868 for i := range t.pieces {
870 if p.relativeAvailability != 0 {
871 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
875 t.cl.event.Broadcast()
876 t.pieceStateChanges.Close()
877 t.updateWantPeersEvent()
881 func (t *Torrent) requestOffset(r Request) int64 {
882 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
885 // Return the request that would include the given offset into the torrent data. Returns !ok if
886 // there is no such request.
887 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
888 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
891 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
892 defer perf.ScopeTimerErr(&err)()
893 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
894 if err == nil && n != len(data) {
895 err = io.ErrShortWrite
900 func (t *Torrent) bitfield() (bf []bool) {
901 bf = make([]bool, t.numPieces())
902 t._completedPieces.Iterate(func(piece uint32) (again bool) {
909 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
910 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
913 func (t *Torrent) chunksPerRegularPiece() uint32 {
914 return uint32((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
917 func (t *Torrent) numRequests() RequestIndex {
918 if t.numPieces() == 0 {
921 return uint32(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
924 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
925 t.dirtyChunks.RemoveRange(
926 uint64(t.pieceRequestIndexOffset(pieceIndex)),
927 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
930 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
931 if t.info.PieceLength == 0 {
932 // There will be no variance amongst pieces. Only pain.
935 if piece == t.numPieces()-1 {
936 ret := pp.Integer(*t.length % t.info.PieceLength)
941 return pp.Integer(t.info.PieceLength)
944 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
945 return &blockCheckingWriter{
946 cache: &t.smartBanCache,
947 requestIndex: t.pieceRequestIndexOffset(piece),
948 chunkSize: t.chunkSize.Int(),
952 func (t *Torrent) hashPiece(piece pieceIndex) (
954 // These are peers that sent us blocks that differ from what we hash here.
955 differingPeers map[banPrefix]struct{},
959 p.waitNoPendingWrites()
960 storagePiece := t.pieces[piece].Storage()
962 // Does the backend want to do its own hashing?
963 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
964 var sum metainfo.Hash
965 // log.Printf("A piece decided to self-hash: %d", piece)
966 sum, err = i.SelfHash()
967 missinggo.CopyExact(&ret, sum)
971 hash := pieceHash.New()
972 const logPieceContents = false
973 smartBanWriter := t.smartBanBlockCheckingWriter(piece)
974 writers := []io.Writer{hash, smartBanWriter}
975 var examineBuf bytes.Buffer
976 if logPieceContents {
977 writers = append(writers, &examineBuf)
979 _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
980 if logPieceContents {
981 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
983 smartBanWriter.Flush()
984 differingPeers = smartBanWriter.badPeers
985 missinggo.CopyExact(&ret, hash.Sum(nil))
989 func (t *Torrent) haveAnyPieces() bool {
990 return !t._completedPieces.IsEmpty()
993 func (t *Torrent) haveAllPieces() bool {
997 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1000 func (t *Torrent) havePiece(index pieceIndex) bool {
1001 return t.haveInfo() && t.pieceComplete(index)
1004 func (t *Torrent) maybeDropMutuallyCompletePeer(
1005 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1009 if !t.cl.config.DropMutuallyCompletePeers {
1012 if !t.haveAllPieces() {
1015 if all, known := p.peerHasAllPieces(); !(known && all) {
1021 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1025 func (t *Torrent) haveChunk(r Request) (ret bool) {
1027 // log.Println("have chunk", r, ret)
1032 if t.pieceComplete(pieceIndex(r.Index)) {
1035 p := &t.pieces[r.Index]
1036 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1039 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1040 return chunkIndexType(cs.Begin / chunkSize)
1043 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1044 return t._pendingPieces.Contains(uint32(index))
1047 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1048 // conns (which is a map).
1049 var peerConnSlices sync.Pool
1051 func getPeerConnSlice(cap int) []*PeerConn {
1052 getInterface := peerConnSlices.Get()
1053 if getInterface == nil {
1054 return make([]*PeerConn, 0, cap)
1056 return getInterface.([]*PeerConn)[:0]
1060 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1061 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1062 // established connections for more than a minute. This is O(n log n). If there was a way to not
1063 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1064 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1065 wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
1066 defer peerConnSlices.Put(wcs.conns)
1069 for wcs.Len() != 0 {
1070 c := heap.Pop(&wcs).(*PeerConn)
1071 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1074 // If the connection is in the worst half of the established
1075 // connection quota and is older than a minute.
1076 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1077 // Give connections 1 minute to prove themselves.
1078 if time.Since(c.completedHandshake) > time.Minute {
1086 type PieceStateChange struct {
1091 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1092 t.cl._mu.Defer(func() {
1093 cur := t.pieceState(piece)
1094 p := &t.pieces[piece]
1095 if cur != p.publicPieceState {
1096 p.publicPieceState = cur
1097 t.pieceStateChanges.Publish(PieceStateChange{
1105 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1106 if t.pieceComplete(piece) {
1109 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1112 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1113 return t.pieces[piece].allChunksDirty()
1116 func (t *Torrent) readersChanged() {
1117 t.updateReaderPieces()
1118 t.updateAllPiecePriorities("Torrent.readersChanged")
1121 func (t *Torrent) updateReaderPieces() {
1122 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1125 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1129 t.updateReaderPieces()
1130 // Order the ranges, high and low.
1132 if l.begin > h.begin {
1135 if l.end < h.begin {
1136 // Two distinct ranges.
1137 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1138 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1145 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1149 func (t *Torrent) maybeNewConns() {
1150 // Tickle the accept routine.
1151 t.cl.event.Broadcast()
1155 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1156 if t._pendingPieces.Contains(uint32(piece)) {
1157 t.iterPeers(func(c *Peer) {
1158 // if c.requestState.Interested {
1161 if !c.isLowOnRequests() {
1164 if !c.peerHasPiece(piece) {
1167 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(uint32(piece)) {
1170 c.updateRequests(reason)
1174 t.publishPieceChange(piece)
1177 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1178 if !t.closed.IsSet() {
1179 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1181 t.updatePieceRequestOrder(piece)
1183 p := &t.pieces[piece]
1184 newPrio := p.uncachedPriority()
1185 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1186 if newPrio == PiecePriorityNone {
1187 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1191 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1195 t.piecePriorityChanged(piece, reason)
1198 func (t *Torrent) updateAllPiecePriorities(reason string) {
1199 t.updatePiecePriorities(0, t.numPieces(), reason)
1202 // Update all piece priorities in one hit. This function should have the same
1203 // output as updatePiecePriority, but across all pieces.
1204 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1205 for i := begin; i < end; i++ {
1206 t.updatePiecePriority(i, reason)
1210 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1211 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1212 if off >= *t.length {
1222 begin = pieceIndex(off / t.info.PieceLength)
1223 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1224 if end > pieceIndex(t.info.NumPieces()) {
1225 end = pieceIndex(t.info.NumPieces())
1230 // Returns true if all iterations complete without breaking. Returns the read regions for all
1231 // readers. The reader regions should not be merged as some callers depend on this method to
1232 // enumerate readers.
1233 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1234 for r := range t.readers {
1236 if p.begin >= p.end {
1239 if !f(p.begin, p.end) {
1246 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1247 return t.piece(piece).uncachedPriority()
1250 func (t *Torrent) pendRequest(req RequestIndex) {
1251 t.piece(int(req / t.chunksPerRegularPiece())).pendChunkIndex(req % t.chunksPerRegularPiece())
1254 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1255 t.cl.event.Broadcast()
1256 if t.pieceComplete(piece) {
1257 t.onPieceCompleted(piece)
1259 t.onIncompletePiece(piece)
1261 t.updatePiecePriority(piece, reason)
1264 func (t *Torrent) numReceivedConns() (ret int) {
1265 for c := range t.conns {
1266 if c.Discovery == PeerSourceIncoming {
1273 func (t *Torrent) maxHalfOpen() int {
1274 // Note that if we somehow exceed the maximum established conns, we want
1275 // the negative value to have an effect.
1276 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1277 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1278 // We want to allow some experimentation with new peers, and to try to
1279 // upset an oversupply of received connections.
1280 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1283 func (t *Torrent) openNewConns() (initiated int) {
1284 defer t.updateWantPeersEvent()
1285 for t.peers.Len() != 0 {
1289 if len(t.halfOpen) >= t.maxHalfOpen() {
1292 if len(t.cl.dialers) == 0 {
1295 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1298 p := t.peers.PopMax()
1305 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1307 uncached := t.pieceCompleteUncached(piece)
1308 cached := p.completion()
1309 changed := cached != uncached
1310 complete := uncached.Complete
1311 p.storageCompletionOk = uncached.Ok
1314 t._completedPieces.Add(x)
1317 t._completedPieces.Remove(x)
1319 p.t.updatePieceRequestOrder(piece)
1321 if complete && len(p.dirtiers) != 0 {
1322 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1325 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1326 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1331 // Non-blocking read. Client lock is not required.
1332 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1334 p := &t.pieces[off/t.info.PieceLength]
1335 p.waitNoPendingWrites()
1337 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1348 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1349 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1350 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1351 func (t *Torrent) maybeCompleteMetadata() error {
1356 if !t.haveAllMetadataPieces() {
1357 // Don't have enough metadata pieces.
1360 err := t.setInfoBytesLocked(t.metadataBytes)
1362 t.invalidateMetadata()
1363 return fmt.Errorf("error setting info bytes: %s", err)
1365 if t.cl.config.Debug {
1366 t.logger.Printf("%s: got metadata from peers", t)
1371 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1372 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1374 now.Add(bitmap.BitIndex(begin))
1375 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1382 func (t *Torrent) needData() bool {
1383 if t.closed.IsSet() {
1389 return !t._pendingPieces.IsEmpty()
1392 func appendMissingStrings(old, new []string) (ret []string) {
1395 for _, n := range new {
1396 for _, o := range old {
1401 ret = append(ret, n)
1406 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1408 for minNumTiers > len(ret) {
1409 ret = append(ret, nil)
1414 func (t *Torrent) addTrackers(announceList [][]string) {
1415 fullAnnounceList := &t.metainfo.AnnounceList
1416 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1417 for tierIndex, trackerURLs := range announceList {
1418 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1420 t.startMissingTrackerScrapers()
1421 t.updateWantPeersEvent()
1424 // Don't call this before the info is available.
1425 func (t *Torrent) bytesCompleted() int64 {
1429 return *t.length - t.bytesLeft()
1432 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1435 return t.setInfoBytesLocked(b)
1438 // Returns true if connection is removed from torrent.Conns.
1439 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1440 if !c.closed.IsSet() {
1441 panic("connection is not closed")
1442 // There are behaviours prevented by the closed state that will fail
1443 // if the connection has been deleted.
1447 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1448 // the drop event against the PexConnState instead.
1450 if !t.cl.config.DisablePEX {
1454 torrent.Add("deleted connections", 1)
1455 if !c.deleteAllRequests().IsEmpty() {
1456 t.iterPeers(func(p *Peer) {
1457 if p.isLowOnRequests() {
1458 p.updateRequests("Torrent.deletePeerConn")
1462 t.assertPendingRequests()
1463 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1464 panic(t.connsWithAllPieces)
1469 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1470 if t.deleteConnWithAllPieces(p) {
1476 p.peerPieces().Iterate(func(i uint32) bool {
1477 p.t.decPieceAvailability(pieceIndex(i))
1482 func (t *Torrent) assertPendingRequests() {
1486 // var actual pendingRequests
1487 // if t.haveInfo() {
1488 // actual.m = make([]int, t.numRequests())
1490 // t.iterPeers(func(p *Peer) {
1491 // p.requestState.Requests.Iterate(func(x uint32) bool {
1496 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1502 func (t *Torrent) dropConnection(c *PeerConn) {
1503 t.cl.event.Broadcast()
1505 if t.deletePeerConn(c) {
1510 // Peers as in contact information for dialing out.
1511 func (t *Torrent) wantPeers() bool {
1512 if t.closed.IsSet() {
1515 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1518 return t.wantConns()
1521 func (t *Torrent) updateWantPeersEvent() {
1523 t.wantPeersEvent.Set()
1525 t.wantPeersEvent.Clear()
1529 // Returns whether the client should make effort to seed the torrent.
1530 func (t *Torrent) seeding() bool {
1532 if t.closed.IsSet() {
1535 if t.dataUploadDisallowed {
1538 if cl.config.NoUpload {
1541 if !cl.config.Seed {
1544 if cl.config.DisableAggressiveUpload && t.needData() {
1550 func (t *Torrent) onWebRtcConn(
1551 c datachannel.ReadWriteCloser,
1552 dcc webtorrent.DataChannelContext,
1555 netConn := webrtcNetConn{
1557 DataChannelContext: dcc,
1559 peerRemoteAddr := netConn.RemoteAddr()
1560 if t.cl.badPeerAddr(peerRemoteAddr) {
1563 pc, err := t.cl.initiateProtocolHandshakes(
1564 context.Background(),
1569 netConn.RemoteAddr(),
1571 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1574 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1577 if dcc.LocalOffered {
1578 pc.Discovery = PeerSourceTracker
1580 pc.Discovery = PeerSourceIncoming
1582 pc.conn.SetWriteDeadline(time.Time{})
1585 err = t.cl.runHandshookConn(pc, t)
1587 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1591 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1592 err := t.cl.runHandshookConn(pc, t)
1593 if err != nil || logAll {
1594 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1598 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1599 t.logRunHandshookConn(pc, false, log.Debug)
1602 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1603 wtc, release := t.cl.websocketTrackers.Get(u.String())
1608 wst := websocketTrackerStatus{u, wtc}
1610 err := wtc.Announce(tracker.Started, t.infoHash)
1612 t.logger.WithDefaultLevel(log.Warning).Printf(
1613 "error in initial announce to %q: %v",
1621 func (t *Torrent) startScrapingTracker(_url string) {
1625 u, err := url.Parse(_url)
1627 // URLs with a leading '*' appear to be a uTorrent convention to
1628 // disable trackers.
1630 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1634 if u.Scheme == "udp" {
1636 t.startScrapingTracker(u.String())
1638 t.startScrapingTracker(u.String())
1641 if _, ok := t.trackerAnnouncers[_url]; ok {
1644 sl := func() torrentTrackerAnnouncer {
1647 if t.cl.config.DisableWebtorrent {
1650 return t.startWebsocketAnnouncer(*u)
1652 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1656 if t.cl.config.DisableIPv6 {
1660 newAnnouncer := &trackerScraper{
1663 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1665 go newAnnouncer.Run()
1671 if t.trackerAnnouncers == nil {
1672 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1674 t.trackerAnnouncers[_url] = sl
1677 // Adds and starts tracker scrapers for tracker URLs that aren't already
1679 func (t *Torrent) startMissingTrackerScrapers() {
1680 if t.cl.config.DisableTrackers {
1683 t.startScrapingTracker(t.metainfo.Announce)
1684 for _, tier := range t.metainfo.AnnounceList {
1685 for _, url := range tier {
1686 t.startScrapingTracker(url)
1691 // Returns an AnnounceRequest with fields filled out to defaults and current
1693 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1694 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1695 // dependent on the network in use.
1696 return tracker.AnnounceRequest{
1698 NumWant: func() int32 {
1699 if t.wantPeers() && len(t.cl.dialers) > 0 {
1705 Port: uint16(t.cl.incomingPeerPort()),
1706 PeerId: t.cl.peerID,
1707 InfoHash: t.infoHash,
1708 Key: t.cl.announceKey(),
1710 // The following are vaguely described in BEP 3.
1712 Left: t.bytesLeftAnnounce(),
1713 Uploaded: t.stats.BytesWrittenData.Int64(),
1714 // There's no mention of wasted or unwanted download in the BEP.
1715 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1719 // Adds peers revealed in an announce until the announce ends, or we have
1721 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1723 for v := range pvs {
1726 for _, cp := range v.Peers {
1728 // Can't do anything with this.
1731 if t.addPeer(PeerInfo{
1732 Addr: ipPortAddr{cp.IP, cp.Port},
1733 Source: PeerSourceDhtGetPeers,
1740 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1745 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1746 // announce ends. stop will force the announce to end.
1747 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1748 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1752 _done := make(chan struct{})
1756 t.consumeDhtAnnouncePeers(ps.Peers())
1762 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1763 _, stop, err := t.AnnounceToDht(s)
1768 case <-t.closed.Done():
1769 case <-time.After(5 * time.Minute):
1775 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1781 if t.closed.IsSet() {
1784 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1785 // TODO: We can include the announce_peer step depending on whether we can receive
1786 // inbound connections. We should probably only announce once every 15 mins too.
1790 // TODO: Determine if there's a listener on the port we're announcing.
1791 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1802 err := t.timeboxedAnnounceToDht(s)
1804 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1810 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1811 for _, p := range peers {
1819 // The returned TorrentStats may require alignment in memory. See
1820 // https://github.com/anacrolix/torrent/issues/383.
1821 func (t *Torrent) Stats() TorrentStats {
1823 defer t.cl.rUnlock()
1824 return t.statsLocked()
1827 func (t *Torrent) statsLocked() (ret TorrentStats) {
1828 ret.ActivePeers = len(t.conns)
1829 ret.HalfOpenPeers = len(t.halfOpen)
1830 ret.PendingPeers = t.peers.Len()
1831 ret.TotalPeers = t.numTotalPeers()
1832 ret.ConnectedSeeders = 0
1833 for c := range t.conns {
1834 if all, ok := c.peerHasAllPieces(); all && ok {
1835 ret.ConnectedSeeders++
1838 ret.ConnStats = t.stats.Copy()
1839 ret.PiecesComplete = t.numPiecesCompleted()
1843 // The total number of peers in the torrent.
1844 func (t *Torrent) numTotalPeers() int {
1845 peers := make(map[string]struct{})
1846 for conn := range t.conns {
1847 ra := conn.conn.RemoteAddr()
1849 // It's been closed and doesn't support RemoteAddr.
1852 peers[ra.String()] = struct{}{}
1854 for addr := range t.halfOpen {
1855 peers[addr] = struct{}{}
1857 t.peers.Each(func(peer PeerInfo) {
1858 peers[peer.Addr.String()] = struct{}{}
1863 // Reconcile bytes transferred before connection was associated with a
1865 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1866 if c._stats != (ConnStats{
1867 // Handshakes should only increment these fields:
1868 BytesWritten: c._stats.BytesWritten,
1869 BytesRead: c._stats.BytesRead,
1873 c.postHandshakeStats(func(cs *ConnStats) {
1874 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1875 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1877 c.reconciledHandshakeStats = true
1880 // Returns true if the connection is added.
1881 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1884 torrent.Add("added connections", 1)
1887 if t.closed.IsSet() {
1888 return errors.New("torrent closed")
1890 for c0 := range t.conns {
1891 if c.PeerID != c0.PeerID {
1894 if !t.cl.config.DropDuplicatePeerIds {
1897 if c.hasPreferredNetworkOver(c0) {
1899 t.deletePeerConn(c0)
1901 return errors.New("existing connection preferred")
1904 if len(t.conns) >= t.maxEstablishedConns {
1905 c := t.worstBadConn()
1907 return errors.New("don't want conns")
1912 if len(t.conns) >= t.maxEstablishedConns {
1915 t.conns[c] = struct{}{}
1916 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1917 t.pex.Add(c) // as no further extended handshake expected
1922 func (t *Torrent) wantConns() bool {
1923 if !t.networkingEnabled.Bool() {
1926 if t.closed.IsSet() {
1929 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
1932 return len(t.conns) < t.maxEstablishedConns || t.worstBadConn() != nil
1935 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1938 oldMax = t.maxEstablishedConns
1939 t.maxEstablishedConns = max
1940 wcs := worseConnSlice{
1941 conns: t.appendConns(nil, func(*PeerConn) bool {
1947 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1948 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
1954 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1955 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1958 t.cl.event.Broadcast()
1959 if t.closed.IsSet() {
1963 // Don't score the first time a piece is hashed, it could be an initial check.
1964 if p.storageCompletionOk {
1966 pieceHashedCorrect.Add(1)
1969 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1970 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1971 pieceHashedNotCorrect.Add(1)
1976 t.publishPieceChange(piece)
1979 t.publishPieceChange(piece)
1983 if len(p.dirtiers) != 0 {
1984 // Don't increment stats above connection-level for every involved connection.
1985 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1987 for c := range p.dirtiers {
1988 c._stats.incrementPiecesDirtiedGood()
1990 t.clearPieceTouchers(piece)
1992 err := p.Storage().MarkComplete()
1994 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1998 if t.closed.IsSet() {
2001 t.pendAllChunkSpecs(piece)
2003 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2004 // Peers contributed to all the data for this piece hash failure, and the failure was
2005 // not due to errors in the storage (such as data being dropped in a cache).
2007 // Increment Torrent and above stats, and then specific connections.
2008 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2009 for c := range p.dirtiers {
2010 // Y u do dis peer?!
2011 c.stats().incrementPiecesDirtiedBad()
2014 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2015 for c := range p.dirtiers {
2017 bannableTouchers = append(bannableTouchers, c)
2020 t.clearPieceTouchers(piece)
2021 slices.Sort(bannableTouchers, connLessTrusted)
2023 if t.cl.config.Debug {
2025 "bannable conns by trust for piece %d: %v",
2027 func() (ret []connectionTrust) {
2028 for _, c := range bannableTouchers {
2029 ret = append(ret, c.trust())
2036 if len(bannableTouchers) >= 1 {
2037 c := bannableTouchers[0]
2038 t.cl.banPeerIP(c.remoteIp())
2042 t.onIncompletePiece(piece)
2043 p.Storage().MarkNotComplete()
2045 t.updatePieceCompletion(piece)
2048 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2049 for ri := t.pieceRequestIndexOffset(piece); ri < t.pieceRequestIndexOffset(piece+1); ri++ {
2054 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2055 t.pendAllChunkSpecs(piece)
2056 t.cancelRequestsForPiece(piece)
2057 t.piece(piece).readerCond.Broadcast()
2058 for conn := range t.conns {
2060 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2064 // Called when a piece is found to be not complete.
2065 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2066 if t.pieceAllDirty(piece) {
2067 t.pendAllChunkSpecs(piece)
2069 if !t.wantPieceIndex(piece) {
2070 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2073 // We could drop any connections that we told we have a piece that we
2074 // don't here. But there's a test failure, and it seems clients don't care
2075 // if you request pieces that you already claim to have. Pruning bad
2076 // connections might just remove any connections that aren't treating us
2077 // favourably anyway.
2079 // for c := range t.conns {
2080 // if c.sentHave(piece) {
2084 t.iterPeers(func(conn *Peer) {
2085 if conn.peerHasPiece(piece) {
2086 conn.updateRequests("piece incomplete")
2091 func (t *Torrent) tryCreateMorePieceHashers() {
2092 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2096 func (t *Torrent) tryCreatePieceHasher() bool {
2097 if t.storage == nil {
2100 pi, ok := t.getPieceToHash()
2105 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2107 t.publishPieceChange(pi)
2108 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2109 t.storageLock.RLock()
2110 t.activePieceHashes++
2111 go t.pieceHasher(pi)
2115 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2116 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2117 if t.piece(i).hashing {
2127 func (t *Torrent) pieceHasher(index pieceIndex) {
2129 sum, failedPeers, copyErr := t.hashPiece(index)
2130 correct := sum == *p.hash
2132 for peer := range failedPeers {
2133 log.Printf("would smart ban %q for %v here", peer, p)
2134 t.cl.banPrefix(peer)
2140 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2142 t.storageLock.RUnlock()
2146 t.pieceHashed(index, correct, copyErr)
2147 t.updatePiecePriority(index, "Torrent.pieceHasher")
2148 t.activePieceHashes--
2149 t.tryCreateMorePieceHashers()
2152 // Return the connections that touched a piece, and clear the entries while doing it.
2153 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2155 for c := range p.dirtiers {
2156 delete(c.peerTouchedPieces, pi)
2157 delete(p.dirtiers, c)
2161 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2162 t.iterPeers(func(p *Peer) {
2163 ret = append(ret, p)
2168 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2169 piece := t.piece(pieceIndex)
2170 if piece.queuedForHash() {
2173 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2174 t.publishPieceChange(pieceIndex)
2175 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2176 t.tryCreateMorePieceHashers()
2179 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2180 // before the Info is available.
2181 func (t *Torrent) VerifyData() {
2182 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2183 t.Piece(i).VerifyData()
2187 // Start the process of connecting to the given peer for the given torrent if appropriate.
2188 func (t *Torrent) initiateConn(peer PeerInfo) {
2189 if peer.Id == t.cl.peerID {
2192 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2196 if t.addrActive(addr.String()) {
2200 t.halfOpen[addr.String()] = peer
2201 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2204 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2205 // quickly make one Client visible to the Torrent of another Client.
2206 func (t *Torrent) AddClientPeer(cl *Client) int {
2207 return t.AddPeers(func() (ps []PeerInfo) {
2208 for _, la := range cl.ListenAddrs() {
2209 ps = append(ps, PeerInfo{
2218 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2220 func (t *Torrent) allStats(f func(*ConnStats)) {
2225 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2226 return t.pieces[i].hashing
2229 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2230 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2233 func (t *Torrent) dialTimeout() time.Duration {
2234 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2237 func (t *Torrent) piece(i int) *Piece {
2241 func (t *Torrent) onWriteChunkErr(err error) {
2242 if t.userOnWriteChunkErr != nil {
2243 go t.userOnWriteChunkErr(err)
2246 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2247 t.disallowDataDownloadLocked()
2250 func (t *Torrent) DisallowDataDownload() {
2251 t.disallowDataDownloadLocked()
2254 func (t *Torrent) disallowDataDownloadLocked() {
2255 t.dataDownloadDisallowed.Set()
2258 func (t *Torrent) AllowDataDownload() {
2259 t.dataDownloadDisallowed.Clear()
2262 // Enables uploading data, if it was disabled.
2263 func (t *Torrent) AllowDataUpload() {
2266 t.dataUploadDisallowed = false
2267 for c := range t.conns {
2268 c.updateRequests("allow data upload")
2272 // Disables uploading data, if it was enabled.
2273 func (t *Torrent) DisallowDataUpload() {
2276 t.dataUploadDisallowed = true
2277 for c := range t.conns {
2278 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2279 c.updateRequests("disallow data upload")
2283 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2284 // or if nil, a critical message is logged, and data download is disabled.
2285 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2288 t.userOnWriteChunkErr = f
2291 func (t *Torrent) iterPeers(f func(p *Peer)) {
2292 for pc := range t.conns {
2295 for _, ws := range t.webSeeds {
2300 func (t *Torrent) callbacks() *Callbacks {
2301 return &t.cl.config.Callbacks
2304 func (t *Torrent) addWebSeed(url string) {
2305 if t.cl.config.DisableWebseeds {
2308 if _, ok := t.webSeeds[url]; ok {
2311 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2312 // right away. This value should be some multiple of the number of connections to a host. I
2313 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2314 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2315 // "https://webtorrent.io/torrents/".
2316 const maxRequests = 16
2322 reconciledHandshakeStats: true,
2323 // This should affect how often we have to recompute requests for this peer. Note that
2324 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2325 // requests mark more often, so recomputation is probably sooner than with regular peer
2326 // conns. ~4x maxRequests would be about right.
2327 PeerMaxRequests: 128,
2328 // TODO: Set ban prefix?
2329 RemoteAddr: remoteAddrFromUrl(url),
2330 callbacks: t.callbacks(),
2332 client: webseed.Client{
2333 HttpClient: t.cl.webseedHttpClient,
2335 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2336 return &rateLimitedReader{
2337 l: t.cl.config.DownloadRateLimiter,
2342 activeRequests: make(map[Request]webseed.Request, maxRequests),
2343 maxRequests: maxRequests,
2345 ws.peer.initUpdateRequestsTimer()
2346 ws.requesterCond.L = t.cl.locker()
2347 for i := 0; i < maxRequests; i += 1 {
2350 for _, f := range t.callbacks().NewPeer {
2353 ws.peer.logger = t.logger.WithContextValue(&ws)
2354 ws.peer.peerImpl = &ws
2356 ws.onGotInfo(t.info)
2358 t.webSeeds[url] = &ws.peer
2361 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2362 t.iterPeers(func(p1 *Peer) {
2370 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2371 index := ri / t.chunksPerRegularPiece()
2374 t.piece(int(index)).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2378 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2379 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + uint32(r.Begin/t.chunkSize)
2382 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2383 return RequestIndex(piece) * t.chunksPerRegularPiece()
2386 func (t *Torrent) updateComplete() {
2387 t.Complete.SetBool(t.haveAllPieces())
2390 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2391 p := t.pendingRequests[r]
2395 delete(t.pendingRequests, r)
2399 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2400 return t.pendingRequests[r]
2403 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2404 if t.connsWithAllPieces == nil {
2405 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2407 t.connsWithAllPieces[p] = struct{}{}
2410 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2411 _, ok := t.connsWithAllPieces[p]
2412 delete(t.connsWithAllPieces, p)
2416 func (t *Torrent) numActivePeers() int {
2417 return len(t.conns) + len(t.webSeeds)
2420 func (t *Torrent) hasStorageCap() bool {
2421 f := t.storage.Capacity