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
152 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
153 // This could be done with roaring.BitSliceIndexing.
154 t.iterPeers(func(peer *Peer) {
155 if _, ok := t.connsWithAllPieces[peer]; ok {
158 if peer.peerHasPiece(i) {
165 func (t *Torrent) decPieceAvailability(i pieceIndex) {
170 if p.relativeAvailability <= 0 {
171 panic(p.relativeAvailability)
173 p.relativeAvailability--
174 t.updatePieceRequestOrder(i)
177 func (t *Torrent) incPieceAvailability(i pieceIndex) {
178 // If we don't the info, this should be reconciled when we do.
181 p.relativeAvailability++
182 t.updatePieceRequestOrder(i)
186 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
187 return t._readerNowPieces
190 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
191 return t._readerReadaheadPieces
194 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
195 return !t.wantPieceIndex(i)
198 // Returns a channel that is closed when the Torrent is closed.
199 func (t *Torrent) Closed() events.Done {
200 return t.closed.Done()
203 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
204 // pending, and half-open peers.
205 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
206 // Add pending peers to the list
207 t.peers.Each(func(peer PeerInfo) {
208 ks = append(ks, peer)
211 // Add half-open peers to the list
212 for _, peer := range t.halfOpen {
213 ks = append(ks, peer)
216 // Add active peers to the list
217 for conn := range t.conns {
218 ks = append(ks, PeerInfo{
220 Addr: conn.RemoteAddr,
221 Source: conn.Discovery,
222 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
223 // > But if we're not connected to them with an encrypted connection, I couldn't say
224 // > what's appropriate. We can carry forward the SupportsEncryption value as we
225 // > received it from trackers/DHT/PEX, or just use the encryption state for the
226 // > connection. It's probably easiest to do the latter for now.
227 // https://github.com/anacrolix/torrent/pull/188
228 SupportsEncryption: conn.headerEncrypted,
235 func (t *Torrent) setChunkSize(size pp.Integer) {
237 t.chunkPool = sync.Pool{
238 New: func() interface{} {
239 b := make([]byte, size)
245 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
246 return t._completedPieces.Contains(bitmap.BitIndex(piece))
249 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
250 if t.storage == nil {
251 return storage.Completion{Complete: false, Ok: true}
253 return t.pieces[piece].Storage().Completion()
256 // There's a connection to that address already.
257 func (t *Torrent) addrActive(addr string) bool {
258 if _, ok := t.halfOpen[addr]; ok {
261 for c := range t.conns {
263 if ra.String() == addr {
270 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
271 return t.appendConns(ret, func(conn *PeerConn) bool {
272 return !conn.closed.IsSet()
276 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
277 for c := range t.conns {
285 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
287 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
288 if t.closed.IsSet() {
291 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
292 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
293 torrent.Add("peers not added because of bad addr", 1)
294 // cl.logger.Printf("peers not added because of bad addr: %v", p)
298 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
299 torrent.Add("peers replaced", 1)
300 if !replaced.equal(p) {
301 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
308 for t.peers.Len() > cl.config.TorrentPeersHighWater {
309 _, ok := t.peers.DeleteMin()
311 torrent.Add("excess reserve peers discarded", 1)
317 func (t *Torrent) invalidateMetadata() {
318 for i := 0; i < len(t.metadataCompletedChunks); i++ {
319 t.metadataCompletedChunks[i] = false
322 t.gotMetainfoC = make(chan struct{})
327 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
331 if index >= len(t.metadataCompletedChunks) {
332 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
335 copy(t.metadataBytes[(1<<14)*index:], data)
336 t.metadataCompletedChunks[index] = true
339 func (t *Torrent) metadataPieceCount() int {
340 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
343 func (t *Torrent) haveMetadataPiece(piece int) bool {
345 return (1<<14)*piece < len(t.metadataBytes)
347 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
351 func (t *Torrent) metadataSize() int {
352 return len(t.metadataBytes)
355 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
356 for i := 0; i < len(info.Pieces); i += sha1.Size {
357 ret = append(ret, info.Pieces[i:i+sha1.Size])
362 func (t *Torrent) makePieces() {
363 hashes := infoPieceHashes(t.info)
364 t.pieces = make([]Piece, len(hashes))
365 for i, hash := range hashes {
366 piece := &t.pieces[i]
368 piece.index = pieceIndex(i)
369 piece.noPendingWrites.L = &piece.pendingWritesMutex
370 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
372 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
373 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
374 piece.files = files[beginFile:endFile]
375 piece.undirtiedChunksIter = undirtiedChunksIter{
376 TorrentDirtyChunks: &t.dirtyChunks,
377 StartRequestIndex: piece.requestIndexOffset(),
378 EndRequestIndex: piece.requestIndexOffset() + piece.numChunks(),
383 // Returns the index of the first file containing the piece. files must be
384 // ordered by offset.
385 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
386 for i, f := range files {
387 if f.offset+f.length > pieceOffset {
394 // Returns the index after the last file containing the piece. files must be
395 // ordered by offset.
396 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
397 for i, f := range files {
398 if f.offset+f.length >= pieceEndOffset {
405 func (t *Torrent) cacheLength() {
407 for _, f := range t.info.UpvertedFiles() {
413 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
415 func (t *Torrent) setInfo(info *metainfo.Info) error {
416 if err := validateInfo(info); err != nil {
417 return fmt.Errorf("bad info: %s", err)
419 if t.storageOpener != nil {
421 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
423 return fmt.Errorf("error opening torrent storage: %s", err)
430 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
431 t.displayName = "" // Save a few bytes lol.
438 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
439 return request_strategy.PieceRequestOrderKey{
440 InfoHash: t.infoHash,
445 // This seems to be all the follow-up tasks after info is set, that can't fail.
446 func (t *Torrent) onSetInfo() {
447 t.initPieceRequestOrder()
448 for i := range t.pieces {
450 // Need to add relativeAvailability before updating piece completion, as that may result in conns
452 if p.relativeAvailability != 0 {
453 panic(p.relativeAvailability)
455 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
456 t.addRequestOrderPiece(i)
457 t.updatePieceCompletion(pieceIndex(i))
458 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
459 // t.logger.Printf("piece %s completion unknown, queueing check", p)
460 t.queuePieceCheck(pieceIndex(i))
463 t.cl.event.Broadcast()
464 close(t.gotMetainfoC)
465 t.updateWantPeersEvent()
466 t.pendingRequests = make(map[RequestIndex]*Peer)
467 t.lastRequested = make(map[RequestIndex]time.Time)
468 t.tryCreateMorePieceHashers()
469 t.iterPeers(func(p *Peer) {
471 p.updateRequests("onSetInfo")
475 // Called when metadata for a torrent becomes available.
476 func (t *Torrent) setInfoBytesLocked(b []byte) error {
477 if metainfo.HashBytes(b) != t.infoHash {
478 return errors.New("info bytes have wrong hash")
480 var info metainfo.Info
481 if err := bencode.Unmarshal(b, &info); err != nil {
482 return fmt.Errorf("error unmarshalling info bytes: %s", err)
485 t.metadataCompletedChunks = nil
489 if err := t.setInfo(&info); err != nil {
496 func (t *Torrent) haveAllMetadataPieces() bool {
500 if t.metadataCompletedChunks == nil {
503 for _, have := range t.metadataCompletedChunks {
511 // TODO: Propagate errors to disconnect peer.
512 func (t *Torrent) setMetadataSize(size int) (err error) {
514 // We already know the correct metadata size.
517 if uint32(size) > maxMetadataSize {
518 return errors.New("bad size")
520 if len(t.metadataBytes) == size {
523 t.metadataBytes = make([]byte, size)
524 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
525 t.metadataChanged.Broadcast()
526 for c := range t.conns {
527 c.requestPendingMetadata()
532 // The current working name for the torrent. Either the name in the info dict,
533 // or a display name given such as by the dn value in a magnet link, or "".
534 func (t *Torrent) name() string {
536 defer t.nameMu.RUnlock()
540 if t.displayName != "" {
543 return "infohash:" + t.infoHash.HexString()
546 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
547 p := &t.pieces[index]
548 ret.Priority = t.piecePriority(index)
549 ret.Completion = p.completion()
550 ret.QueuedForHash = p.queuedForHash()
551 ret.Hashing = p.hashing
552 ret.Checking = ret.QueuedForHash || ret.Hashing
553 ret.Marking = p.marking
554 if !ret.Complete && t.piecePartiallyDownloaded(index) {
560 func (t *Torrent) metadataPieceSize(piece int) int {
561 return metadataPieceSize(len(t.metadataBytes), piece)
564 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
567 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
568 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
570 TotalSize: len(t.metadataBytes),
576 type pieceAvailabilityRun struct {
581 func (me pieceAvailabilityRun) String() string {
582 return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
585 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
586 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
587 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
589 for i := range t.pieces {
590 rle.Append(t.pieces[i].availability(), 1)
596 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
597 freqs = make([]int, t.numActivePeers()+1)
598 for i := range t.pieces {
599 freqs[t.piece(i).availability()]++
604 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
605 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
606 ret = append(ret, PieceStateRun{
607 PieceState: el.(PieceState),
611 for index := range t.pieces {
612 rle.Append(t.pieceState(pieceIndex(index)), 1)
618 // Produces a small string representing a PieceStateRun.
619 func (psr PieceStateRun) String() (ret string) {
620 ret = fmt.Sprintf("%d", psr.Length)
621 ret += func() string {
622 switch psr.Priority {
623 case PiecePriorityNext:
625 case PiecePriorityNormal:
627 case PiecePriorityReadahead:
629 case PiecePriorityNow:
631 case PiecePriorityHigh:
640 if psr.QueuedForHash {
658 func (t *Torrent) writeStatus(w io.Writer) {
659 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
660 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
662 fmt.Fprintf(w, "Metadata have: ")
663 for _, h := range t.metadataCompletedChunks {
664 fmt.Fprintf(w, "%c", func() rune {
674 fmt.Fprintf(w, "Piece length: %s\n",
677 return fmt.Sprintf("%v (%v chunks)",
679 float64(t.usualPieceSize())/float64(t.chunkSize))
686 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
687 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
688 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
689 // availability frequencies instead.
691 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
692 for _, run := range t.pieceAvailabilityRuns() {
693 ret = append(ret, run.String())
698 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
699 func() (ret []string) {
700 for avail, freq := range t.pieceAvailabilityFrequencies() {
704 ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
710 fmt.Fprintf(w, "Reader Pieces:")
711 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
712 fmt.Fprintf(w, " %d:%d", begin, end)
717 fmt.Fprintf(w, "Enabled trackers:\n")
719 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
720 fmt.Fprintf(tw, " URL\tExtra\n")
721 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
724 var luns, runs url.URL = *lu, *ru
727 var ml missinggo.MultiLess
728 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
729 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
731 }).([]torrentTrackerAnnouncer) {
732 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
737 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
739 spew.NewDefaultConfig()
740 spew.Fdump(w, t.statsLocked())
742 peers := t.peersAsSlice()
743 sort.Slice(peers, func(_i, _j int) bool {
746 if less, ok := multiless.New().EagerSameLess(
747 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
751 return worseConn(i, j)
753 for i, c := range peers {
754 fmt.Fprintf(w, "%2d. ", i+1)
759 func (t *Torrent) haveInfo() bool {
763 // Returns a run-time generated MetaInfo that includes the info bytes and
764 // announce-list as currently known to the client.
765 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
766 return metainfo.MetaInfo{
767 CreationDate: time.Now().Unix(),
768 Comment: "dynamic metainfo from client",
769 CreatedBy: "go.torrent",
770 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
771 InfoBytes: func() []byte {
773 return t.metadataBytes
778 UrlList: func() []string {
779 ret := make([]string, 0, len(t.webSeeds))
780 for url := range t.webSeeds {
781 ret = append(ret, url)
789 func (t *Torrent) BytesMissing() (n int64) {
791 n = t.bytesMissingLocked()
796 func (t *Torrent) bytesMissingLocked() int64 {
800 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
801 roaring.Flip(b, 0, end).Iterate(cb)
804 func (t *Torrent) bytesLeft() (left int64) {
805 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
806 p := t.piece(pieceIndex(x))
807 left += int64(p.length() - p.numDirtyBytes())
813 // Bytes left to give in tracker announces.
814 func (t *Torrent) bytesLeftAnnounce() int64 {
822 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
823 if t.pieceComplete(piece) {
826 if t.pieceAllDirty(piece) {
829 return t.pieces[piece].hasDirtyChunks()
832 func (t *Torrent) usualPieceSize() int {
833 return int(t.info.PieceLength)
836 func (t *Torrent) numPieces() pieceIndex {
837 return pieceIndex(t.info.NumPieces())
840 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
841 return pieceIndex(t._completedPieces.GetCardinality())
844 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
846 if t.storage != nil {
851 defer t.storageLock.Unlock()
852 if f := t.storage.Close; f != nil {
855 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
860 t.iterPeers(func(p *Peer) {
863 if t.storage != nil {
864 t.deletePieceRequestOrder()
866 for i := range t.pieces {
868 if p.relativeAvailability != 0 {
869 panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
873 t.cl.event.Broadcast()
874 t.pieceStateChanges.Close()
875 t.updateWantPeersEvent()
879 func (t *Torrent) requestOffset(r Request) int64 {
880 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
883 // Return the request that would include the given offset into the torrent data. Returns !ok if
884 // there is no such request.
885 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
886 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
889 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
890 defer perf.ScopeTimerErr(&err)()
891 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
892 if err == nil && n != len(data) {
893 err = io.ErrShortWrite
898 func (t *Torrent) bitfield() (bf []bool) {
899 bf = make([]bool, t.numPieces())
900 t._completedPieces.Iterate(func(piece uint32) (again bool) {
907 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
908 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
911 func (t *Torrent) chunksPerRegularPiece() uint32 {
912 return uint32((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
915 func (t *Torrent) numRequests() RequestIndex {
916 if t.numPieces() == 0 {
919 return uint32(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
922 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
923 t.dirtyChunks.RemoveRange(
924 uint64(t.pieceRequestIndexOffset(pieceIndex)),
925 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
928 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
929 if t.info.PieceLength == 0 {
930 // There will be no variance amongst pieces. Only pain.
933 if piece == t.numPieces()-1 {
934 ret := pp.Integer(*t.length % t.info.PieceLength)
939 return pp.Integer(t.info.PieceLength)
942 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
944 p.waitNoPendingWrites()
945 storagePiece := t.pieces[piece].Storage()
947 // Does the backend want to do its own hashing?
948 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
949 var sum metainfo.Hash
950 // log.Printf("A piece decided to self-hash: %d", piece)
951 sum, err = i.SelfHash()
952 missinggo.CopyExact(&ret, sum)
956 hash := pieceHash.New()
957 const logPieceContents = false
958 if logPieceContents {
959 var examineBuf bytes.Buffer
960 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
961 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
963 _, err = storagePiece.WriteTo(hash)
965 missinggo.CopyExact(&ret, hash.Sum(nil))
969 func (t *Torrent) haveAnyPieces() bool {
970 return !t._completedPieces.IsEmpty()
973 func (t *Torrent) haveAllPieces() bool {
977 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
980 func (t *Torrent) havePiece(index pieceIndex) bool {
981 return t.haveInfo() && t.pieceComplete(index)
984 func (t *Torrent) maybeDropMutuallyCompletePeer(
985 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
989 if !t.cl.config.DropMutuallyCompletePeers {
992 if !t.haveAllPieces() {
995 if all, known := p.peerHasAllPieces(); !(known && all) {
1001 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1005 func (t *Torrent) haveChunk(r Request) (ret bool) {
1007 // log.Println("have chunk", r, ret)
1012 if t.pieceComplete(pieceIndex(r.Index)) {
1015 p := &t.pieces[r.Index]
1016 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1019 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1020 return chunkIndexType(cs.Begin / chunkSize)
1023 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1024 return t._pendingPieces.Contains(uint32(index))
1027 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1028 // conns (which is a map).
1029 var peerConnSlices sync.Pool
1031 func getPeerConnSlice(cap int) []*PeerConn {
1032 getInterface := peerConnSlices.Get()
1033 if getInterface == nil {
1034 return make([]*PeerConn, 0, cap)
1036 return getInterface.([]*PeerConn)[:0]
1040 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1041 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1042 // established connections for more than a minute. This is O(n log n). If there was a way to not
1043 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1044 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1045 wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
1046 defer peerConnSlices.Put(wcs.conns)
1049 for wcs.Len() != 0 {
1050 c := heap.Pop(&wcs).(*PeerConn)
1051 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1054 // If the connection is in the worst half of the established
1055 // connection quota and is older than a minute.
1056 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1057 // Give connections 1 minute to prove themselves.
1058 if time.Since(c.completedHandshake) > time.Minute {
1066 type PieceStateChange struct {
1071 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1072 t.cl._mu.Defer(func() {
1073 cur := t.pieceState(piece)
1074 p := &t.pieces[piece]
1075 if cur != p.publicPieceState {
1076 p.publicPieceState = cur
1077 t.pieceStateChanges.Publish(PieceStateChange{
1085 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1086 if t.pieceComplete(piece) {
1089 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1092 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1093 return t.pieces[piece].allChunksDirty()
1096 func (t *Torrent) readersChanged() {
1097 t.updateReaderPieces()
1098 t.updateAllPiecePriorities("Torrent.readersChanged")
1101 func (t *Torrent) updateReaderPieces() {
1102 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1105 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1109 t.updateReaderPieces()
1110 // Order the ranges, high and low.
1112 if l.begin > h.begin {
1115 if l.end < h.begin {
1116 // Two distinct ranges.
1117 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1118 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1125 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1129 func (t *Torrent) maybeNewConns() {
1130 // Tickle the accept routine.
1131 t.cl.event.Broadcast()
1135 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1136 if t._pendingPieces.Contains(uint32(piece)) {
1137 t.iterPeers(func(c *Peer) {
1138 // if c.requestState.Interested {
1141 if !c.isLowOnRequests() {
1144 if !c.peerHasPiece(piece) {
1147 if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(uint32(piece)) {
1150 c.updateRequests(reason)
1154 t.publishPieceChange(piece)
1157 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1158 if !t.closed.IsSet() {
1159 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1161 t.updatePieceRequestOrder(piece)
1163 p := &t.pieces[piece]
1164 newPrio := p.uncachedPriority()
1165 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1166 if newPrio == PiecePriorityNone {
1167 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1171 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1175 t.piecePriorityChanged(piece, reason)
1178 func (t *Torrent) updateAllPiecePriorities(reason string) {
1179 t.updatePiecePriorities(0, t.numPieces(), reason)
1182 // Update all piece priorities in one hit. This function should have the same
1183 // output as updatePiecePriority, but across all pieces.
1184 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1185 for i := begin; i < end; i++ {
1186 t.updatePiecePriority(i, reason)
1190 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1191 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1192 if off >= *t.length {
1202 begin = pieceIndex(off / t.info.PieceLength)
1203 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1204 if end > pieceIndex(t.info.NumPieces()) {
1205 end = pieceIndex(t.info.NumPieces())
1210 // Returns true if all iterations complete without breaking. Returns the read regions for all
1211 // readers. The reader regions should not be merged as some callers depend on this method to
1212 // enumerate readers.
1213 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1214 for r := range t.readers {
1216 if p.begin >= p.end {
1219 if !f(p.begin, p.end) {
1226 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1227 return t.piece(piece).uncachedPriority()
1230 func (t *Torrent) pendRequest(req RequestIndex) {
1231 t.piece(int(req / t.chunksPerRegularPiece())).pendChunkIndex(req % t.chunksPerRegularPiece())
1234 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1235 t.cl.event.Broadcast()
1236 if t.pieceComplete(piece) {
1237 t.onPieceCompleted(piece)
1239 t.onIncompletePiece(piece)
1241 t.updatePiecePriority(piece, reason)
1244 func (t *Torrent) numReceivedConns() (ret int) {
1245 for c := range t.conns {
1246 if c.Discovery == PeerSourceIncoming {
1253 func (t *Torrent) maxHalfOpen() int {
1254 // Note that if we somehow exceed the maximum established conns, we want
1255 // the negative value to have an effect.
1256 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1257 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1258 // We want to allow some experimentation with new peers, and to try to
1259 // upset an oversupply of received connections.
1260 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1263 func (t *Torrent) openNewConns() (initiated int) {
1264 defer t.updateWantPeersEvent()
1265 for t.peers.Len() != 0 {
1269 if len(t.halfOpen) >= t.maxHalfOpen() {
1272 if len(t.cl.dialers) == 0 {
1275 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1278 p := t.peers.PopMax()
1285 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1287 uncached := t.pieceCompleteUncached(piece)
1288 cached := p.completion()
1289 changed := cached != uncached
1290 complete := uncached.Complete
1291 p.storageCompletionOk = uncached.Ok
1294 t._completedPieces.Add(x)
1297 t._completedPieces.Remove(x)
1299 p.t.updatePieceRequestOrder(piece)
1301 if complete && len(p.dirtiers) != 0 {
1302 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1305 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1306 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1311 // Non-blocking read. Client lock is not required.
1312 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1314 p := &t.pieces[off/t.info.PieceLength]
1315 p.waitNoPendingWrites()
1317 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1328 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1329 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1330 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1331 func (t *Torrent) maybeCompleteMetadata() error {
1336 if !t.haveAllMetadataPieces() {
1337 // Don't have enough metadata pieces.
1340 err := t.setInfoBytesLocked(t.metadataBytes)
1342 t.invalidateMetadata()
1343 return fmt.Errorf("error setting info bytes: %s", err)
1345 if t.cl.config.Debug {
1346 t.logger.Printf("%s: got metadata from peers", t)
1351 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1352 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1354 now.Add(bitmap.BitIndex(begin))
1355 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1362 func (t *Torrent) needData() bool {
1363 if t.closed.IsSet() {
1369 return !t._pendingPieces.IsEmpty()
1372 func appendMissingStrings(old, new []string) (ret []string) {
1375 for _, n := range new {
1376 for _, o := range old {
1381 ret = append(ret, n)
1386 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1388 for minNumTiers > len(ret) {
1389 ret = append(ret, nil)
1394 func (t *Torrent) addTrackers(announceList [][]string) {
1395 fullAnnounceList := &t.metainfo.AnnounceList
1396 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1397 for tierIndex, trackerURLs := range announceList {
1398 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1400 t.startMissingTrackerScrapers()
1401 t.updateWantPeersEvent()
1404 // Don't call this before the info is available.
1405 func (t *Torrent) bytesCompleted() int64 {
1409 return *t.length - t.bytesLeft()
1412 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1415 return t.setInfoBytesLocked(b)
1418 // Returns true if connection is removed from torrent.Conns.
1419 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1420 if !c.closed.IsSet() {
1421 panic("connection is not closed")
1422 // There are behaviours prevented by the closed state that will fail
1423 // if the connection has been deleted.
1427 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1428 // the drop event against the PexConnState instead.
1430 if !t.cl.config.DisablePEX {
1434 torrent.Add("deleted connections", 1)
1435 if !c.deleteAllRequests().IsEmpty() {
1436 t.iterPeers(func(p *Peer) {
1437 if p.isLowOnRequests() {
1438 p.updateRequests("Torrent.deletePeerConn")
1442 t.assertPendingRequests()
1443 if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1444 panic(t.connsWithAllPieces)
1449 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1450 if t.deleteConnWithAllPieces(p) {
1456 p.peerPieces().Iterate(func(i uint32) bool {
1457 p.t.decPieceAvailability(pieceIndex(i))
1462 func (t *Torrent) assertPendingRequests() {
1466 // var actual pendingRequests
1467 // if t.haveInfo() {
1468 // actual.m = make([]int, t.numRequests())
1470 // t.iterPeers(func(p *Peer) {
1471 // p.requestState.Requests.Iterate(func(x uint32) bool {
1476 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1482 func (t *Torrent) dropConnection(c *PeerConn) {
1483 t.cl.event.Broadcast()
1485 if t.deletePeerConn(c) {
1490 // Peers as in contact information for dialing out.
1491 func (t *Torrent) wantPeers() bool {
1492 if t.closed.IsSet() {
1495 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1498 return t.wantConns()
1501 func (t *Torrent) updateWantPeersEvent() {
1503 t.wantPeersEvent.Set()
1505 t.wantPeersEvent.Clear()
1509 // Returns whether the client should make effort to seed the torrent.
1510 func (t *Torrent) seeding() bool {
1512 if t.closed.IsSet() {
1515 if t.dataUploadDisallowed {
1518 if cl.config.NoUpload {
1521 if !cl.config.Seed {
1524 if cl.config.DisableAggressiveUpload && t.needData() {
1530 func (t *Torrent) onWebRtcConn(
1531 c datachannel.ReadWriteCloser,
1532 dcc webtorrent.DataChannelContext,
1535 netConn := webrtcNetConn{
1537 DataChannelContext: dcc,
1539 peerRemoteAddr := netConn.RemoteAddr()
1540 if t.cl.badPeerAddr(peerRemoteAddr) {
1543 pc, err := t.cl.initiateProtocolHandshakes(
1544 context.Background(),
1549 netConn.RemoteAddr(),
1551 fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1554 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1557 if dcc.LocalOffered {
1558 pc.Discovery = PeerSourceTracker
1560 pc.Discovery = PeerSourceIncoming
1562 pc.conn.SetWriteDeadline(time.Time{})
1565 err = t.cl.runHandshookConn(pc, t)
1567 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1571 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1572 err := t.cl.runHandshookConn(pc, t)
1573 if err != nil || logAll {
1574 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1578 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1579 t.logRunHandshookConn(pc, false, log.Debug)
1582 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1583 wtc, release := t.cl.websocketTrackers.Get(u.String())
1588 wst := websocketTrackerStatus{u, wtc}
1590 err := wtc.Announce(tracker.Started, t.infoHash)
1592 t.logger.WithDefaultLevel(log.Warning).Printf(
1593 "error in initial announce to %q: %v",
1601 func (t *Torrent) startScrapingTracker(_url string) {
1605 u, err := url.Parse(_url)
1607 // URLs with a leading '*' appear to be a uTorrent convention to
1608 // disable trackers.
1610 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1614 if u.Scheme == "udp" {
1616 t.startScrapingTracker(u.String())
1618 t.startScrapingTracker(u.String())
1621 if _, ok := t.trackerAnnouncers[_url]; ok {
1624 sl := func() torrentTrackerAnnouncer {
1627 if t.cl.config.DisableWebtorrent {
1630 return t.startWebsocketAnnouncer(*u)
1632 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1636 if t.cl.config.DisableIPv6 {
1640 newAnnouncer := &trackerScraper{
1643 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1645 go newAnnouncer.Run()
1651 if t.trackerAnnouncers == nil {
1652 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1654 t.trackerAnnouncers[_url] = sl
1657 // Adds and starts tracker scrapers for tracker URLs that aren't already
1659 func (t *Torrent) startMissingTrackerScrapers() {
1660 if t.cl.config.DisableTrackers {
1663 t.startScrapingTracker(t.metainfo.Announce)
1664 for _, tier := range t.metainfo.AnnounceList {
1665 for _, url := range tier {
1666 t.startScrapingTracker(url)
1671 // Returns an AnnounceRequest with fields filled out to defaults and current
1673 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1674 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1675 // dependent on the network in use.
1676 return tracker.AnnounceRequest{
1678 NumWant: func() int32 {
1679 if t.wantPeers() && len(t.cl.dialers) > 0 {
1685 Port: uint16(t.cl.incomingPeerPort()),
1686 PeerId: t.cl.peerID,
1687 InfoHash: t.infoHash,
1688 Key: t.cl.announceKey(),
1690 // The following are vaguely described in BEP 3.
1692 Left: t.bytesLeftAnnounce(),
1693 Uploaded: t.stats.BytesWrittenData.Int64(),
1694 // There's no mention of wasted or unwanted download in the BEP.
1695 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1699 // Adds peers revealed in an announce until the announce ends, or we have
1701 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1703 for v := range pvs {
1706 for _, cp := range v.Peers {
1708 // Can't do anything with this.
1711 if t.addPeer(PeerInfo{
1712 Addr: ipPortAddr{cp.IP, cp.Port},
1713 Source: PeerSourceDhtGetPeers,
1720 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1725 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1726 // announce ends. stop will force the announce to end.
1727 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1728 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1732 _done := make(chan struct{})
1736 t.consumeDhtAnnouncePeers(ps.Peers())
1742 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1743 _, stop, err := t.AnnounceToDht(s)
1748 case <-t.closed.Done():
1749 case <-time.After(5 * time.Minute):
1755 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1761 if t.closed.IsSet() {
1764 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1765 // TODO: We can include the announce_peer step depending on whether we can receive
1766 // inbound connections. We should probably only announce once every 15 mins too.
1770 // TODO: Determine if there's a listener on the port we're announcing.
1771 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1782 err := t.timeboxedAnnounceToDht(s)
1784 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1790 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1791 for _, p := range peers {
1799 // The returned TorrentStats may require alignment in memory. See
1800 // https://github.com/anacrolix/torrent/issues/383.
1801 func (t *Torrent) Stats() TorrentStats {
1803 defer t.cl.rUnlock()
1804 return t.statsLocked()
1807 func (t *Torrent) statsLocked() (ret TorrentStats) {
1808 ret.ActivePeers = len(t.conns)
1809 ret.HalfOpenPeers = len(t.halfOpen)
1810 ret.PendingPeers = t.peers.Len()
1811 ret.TotalPeers = t.numTotalPeers()
1812 ret.ConnectedSeeders = 0
1813 for c := range t.conns {
1814 if all, ok := c.peerHasAllPieces(); all && ok {
1815 ret.ConnectedSeeders++
1818 ret.ConnStats = t.stats.Copy()
1819 ret.PiecesComplete = t.numPiecesCompleted()
1823 // The total number of peers in the torrent.
1824 func (t *Torrent) numTotalPeers() int {
1825 peers := make(map[string]struct{})
1826 for conn := range t.conns {
1827 ra := conn.conn.RemoteAddr()
1829 // It's been closed and doesn't support RemoteAddr.
1832 peers[ra.String()] = struct{}{}
1834 for addr := range t.halfOpen {
1835 peers[addr] = struct{}{}
1837 t.peers.Each(func(peer PeerInfo) {
1838 peers[peer.Addr.String()] = struct{}{}
1843 // Reconcile bytes transferred before connection was associated with a
1845 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1846 if c._stats != (ConnStats{
1847 // Handshakes should only increment these fields:
1848 BytesWritten: c._stats.BytesWritten,
1849 BytesRead: c._stats.BytesRead,
1853 c.postHandshakeStats(func(cs *ConnStats) {
1854 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1855 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1857 c.reconciledHandshakeStats = true
1860 // Returns true if the connection is added.
1861 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1864 torrent.Add("added connections", 1)
1867 if t.closed.IsSet() {
1868 return errors.New("torrent closed")
1870 for c0 := range t.conns {
1871 if c.PeerID != c0.PeerID {
1874 if !t.cl.config.DropDuplicatePeerIds {
1877 if c.hasPreferredNetworkOver(c0) {
1879 t.deletePeerConn(c0)
1881 return errors.New("existing connection preferred")
1884 if len(t.conns) >= t.maxEstablishedConns {
1885 c := t.worstBadConn()
1887 return errors.New("don't want conns")
1892 if len(t.conns) >= t.maxEstablishedConns {
1895 t.conns[c] = struct{}{}
1896 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1897 t.pex.Add(c) // as no further extended handshake expected
1902 func (t *Torrent) wantConns() bool {
1903 if !t.networkingEnabled.Bool() {
1906 if t.closed.IsSet() {
1909 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
1912 return len(t.conns) < t.maxEstablishedConns || t.worstBadConn() != nil
1915 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1918 oldMax = t.maxEstablishedConns
1919 t.maxEstablishedConns = max
1920 wcs := worseConnSlice{
1921 conns: t.appendConns(nil, func(*PeerConn) bool {
1927 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1928 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
1934 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1935 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1938 t.cl.event.Broadcast()
1939 if t.closed.IsSet() {
1943 // Don't score the first time a piece is hashed, it could be an initial check.
1944 if p.storageCompletionOk {
1946 pieceHashedCorrect.Add(1)
1949 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1950 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1951 pieceHashedNotCorrect.Add(1)
1956 t.publishPieceChange(piece)
1959 t.publishPieceChange(piece)
1963 if len(p.dirtiers) != 0 {
1964 // Don't increment stats above connection-level for every involved connection.
1965 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1967 for c := range p.dirtiers {
1968 c._stats.incrementPiecesDirtiedGood()
1970 t.clearPieceTouchers(piece)
1972 err := p.Storage().MarkComplete()
1974 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1978 if t.closed.IsSet() {
1981 t.pendAllChunkSpecs(piece)
1983 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1984 // Peers contributed to all the data for this piece hash failure, and the failure was
1985 // not due to errors in the storage (such as data being dropped in a cache).
1987 // Increment Torrent and above stats, and then specific connections.
1988 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1989 for c := range p.dirtiers {
1990 // Y u do dis peer?!
1991 c.stats().incrementPiecesDirtiedBad()
1994 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1995 for c := range p.dirtiers {
1997 bannableTouchers = append(bannableTouchers, c)
2000 t.clearPieceTouchers(piece)
2001 slices.Sort(bannableTouchers, connLessTrusted)
2003 if t.cl.config.Debug {
2005 "bannable conns by trust for piece %d: %v",
2007 func() (ret []connectionTrust) {
2008 for _, c := range bannableTouchers {
2009 ret = append(ret, c.trust())
2016 if len(bannableTouchers) >= 1 {
2017 c := bannableTouchers[0]
2018 t.cl.banPeerIP(c.remoteIp())
2022 t.onIncompletePiece(piece)
2023 p.Storage().MarkNotComplete()
2025 t.updatePieceCompletion(piece)
2028 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2029 for ri := t.pieceRequestIndexOffset(piece); ri < t.pieceRequestIndexOffset(piece+1); ri++ {
2034 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2035 t.pendAllChunkSpecs(piece)
2036 t.cancelRequestsForPiece(piece)
2037 t.piece(piece).readerCond.Broadcast()
2038 for conn := range t.conns {
2040 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2044 // Called when a piece is found to be not complete.
2045 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2046 if t.pieceAllDirty(piece) {
2047 t.pendAllChunkSpecs(piece)
2049 if !t.wantPieceIndex(piece) {
2050 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2053 // We could drop any connections that we told we have a piece that we
2054 // don't here. But there's a test failure, and it seems clients don't care
2055 // if you request pieces that you already claim to have. Pruning bad
2056 // connections might just remove any connections that aren't treating us
2057 // favourably anyway.
2059 // for c := range t.conns {
2060 // if c.sentHave(piece) {
2064 t.iterPeers(func(conn *Peer) {
2065 if conn.peerHasPiece(piece) {
2066 conn.updateRequests("piece incomplete")
2071 func (t *Torrent) tryCreateMorePieceHashers() {
2072 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2076 func (t *Torrent) tryCreatePieceHasher() bool {
2077 if t.storage == nil {
2080 pi, ok := t.getPieceToHash()
2085 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2087 t.publishPieceChange(pi)
2088 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2089 t.storageLock.RLock()
2090 t.activePieceHashes++
2091 go t.pieceHasher(pi)
2095 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2096 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2097 if t.piece(i).hashing {
2107 func (t *Torrent) pieceHasher(index pieceIndex) {
2109 sum, copyErr := t.hashPiece(index)
2110 correct := sum == *p.hash
2114 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2116 t.storageLock.RUnlock()
2120 t.pieceHashed(index, correct, copyErr)
2121 t.updatePiecePriority(index, "Torrent.pieceHasher")
2122 t.activePieceHashes--
2123 t.tryCreateMorePieceHashers()
2126 // Return the connections that touched a piece, and clear the entries while doing it.
2127 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2129 for c := range p.dirtiers {
2130 delete(c.peerTouchedPieces, pi)
2131 delete(p.dirtiers, c)
2135 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2136 t.iterPeers(func(p *Peer) {
2137 ret = append(ret, p)
2142 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2143 piece := t.piece(pieceIndex)
2144 if piece.queuedForHash() {
2147 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2148 t.publishPieceChange(pieceIndex)
2149 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2150 t.tryCreateMorePieceHashers()
2153 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2154 // before the Info is available.
2155 func (t *Torrent) VerifyData() {
2156 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2157 t.Piece(i).VerifyData()
2161 // Start the process of connecting to the given peer for the given torrent if appropriate.
2162 func (t *Torrent) initiateConn(peer PeerInfo) {
2163 if peer.Id == t.cl.peerID {
2166 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2170 if t.addrActive(addr.String()) {
2174 t.halfOpen[addr.String()] = peer
2175 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2178 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2179 // quickly make one Client visible to the Torrent of another Client.
2180 func (t *Torrent) AddClientPeer(cl *Client) int {
2181 return t.AddPeers(func() (ps []PeerInfo) {
2182 for _, la := range cl.ListenAddrs() {
2183 ps = append(ps, PeerInfo{
2192 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2194 func (t *Torrent) allStats(f func(*ConnStats)) {
2199 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2200 return t.pieces[i].hashing
2203 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2204 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2207 func (t *Torrent) dialTimeout() time.Duration {
2208 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2211 func (t *Torrent) piece(i int) *Piece {
2215 func (t *Torrent) onWriteChunkErr(err error) {
2216 if t.userOnWriteChunkErr != nil {
2217 go t.userOnWriteChunkErr(err)
2220 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2221 t.disallowDataDownloadLocked()
2224 func (t *Torrent) DisallowDataDownload() {
2225 t.disallowDataDownloadLocked()
2228 func (t *Torrent) disallowDataDownloadLocked() {
2229 t.dataDownloadDisallowed.Set()
2232 func (t *Torrent) AllowDataDownload() {
2233 t.dataDownloadDisallowed.Clear()
2236 // Enables uploading data, if it was disabled.
2237 func (t *Torrent) AllowDataUpload() {
2240 t.dataUploadDisallowed = false
2241 for c := range t.conns {
2242 c.updateRequests("allow data upload")
2246 // Disables uploading data, if it was enabled.
2247 func (t *Torrent) DisallowDataUpload() {
2250 t.dataUploadDisallowed = true
2251 for c := range t.conns {
2252 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2253 c.updateRequests("disallow data upload")
2257 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2258 // or if nil, a critical message is logged, and data download is disabled.
2259 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2262 t.userOnWriteChunkErr = f
2265 func (t *Torrent) iterPeers(f func(p *Peer)) {
2266 for pc := range t.conns {
2269 for _, ws := range t.webSeeds {
2274 func (t *Torrent) callbacks() *Callbacks {
2275 return &t.cl.config.Callbacks
2278 func (t *Torrent) addWebSeed(url string) {
2279 if t.cl.config.DisableWebseeds {
2282 if _, ok := t.webSeeds[url]; ok {
2285 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2286 // right away. This value should be some multiple of the number of connections to a host. I
2287 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2288 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2289 // "https://webtorrent.io/torrents/".
2290 const maxRequests = 16
2296 reconciledHandshakeStats: true,
2297 // This should affect how often we have to recompute requests for this peer. Note that
2298 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2299 // requests mark more often, so recomputation is probably sooner than with regular peer
2300 // conns. ~4x maxRequests would be about right.
2301 PeerMaxRequests: 128,
2302 RemoteAddr: remoteAddrFromUrl(url),
2303 callbacks: t.callbacks(),
2305 client: webseed.Client{
2306 HttpClient: t.cl.webseedHttpClient,
2308 ResponseBodyWrapper: func(r io.Reader) io.Reader {
2309 return &rateLimitedReader{
2310 l: t.cl.config.DownloadRateLimiter,
2315 activeRequests: make(map[Request]webseed.Request, maxRequests),
2316 maxRequests: maxRequests,
2318 ws.peer.initUpdateRequestsTimer()
2319 ws.requesterCond.L = t.cl.locker()
2320 for i := 0; i < maxRequests; i += 1 {
2323 for _, f := range t.callbacks().NewPeer {
2326 ws.peer.logger = t.logger.WithContextValue(&ws)
2327 ws.peer.peerImpl = &ws
2329 ws.onGotInfo(t.info)
2331 t.webSeeds[url] = &ws.peer
2334 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2335 t.iterPeers(func(p1 *Peer) {
2343 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2344 index := ri / t.chunksPerRegularPiece()
2347 t.piece(int(index)).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2351 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2352 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + uint32(r.Begin/t.chunkSize)
2355 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2356 return RequestIndex(piece) * t.chunksPerRegularPiece()
2359 func (t *Torrent) updateComplete() {
2360 t.Complete.SetBool(t.haveAllPieces())
2363 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2364 p := t.pendingRequests[r]
2368 delete(t.pendingRequests, r)
2372 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2373 return t.pendingRequests[r]
2376 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2377 if t.connsWithAllPieces == nil {
2378 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2380 t.connsWithAllPieces[p] = struct{}{}
2383 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2384 _, ok := t.connsWithAllPieces[p]
2385 delete(t.connsWithAllPieces, p)
2389 func (t *Torrent) numActivePeers() int {
2390 return len(t.conns) + len(t.webSeeds)
2393 func (t *Torrent) hasStorageCap() bool {
2394 f := t.storage.Capacity