18 "github.com/RoaringBitmap/roaring"
19 "github.com/anacrolix/chansync"
20 "github.com/anacrolix/chansync/events"
21 "github.com/anacrolix/dht/v2"
22 "github.com/anacrolix/log"
23 "github.com/anacrolix/missinggo/perf"
24 "github.com/anacrolix/missinggo/pubsub"
25 "github.com/anacrolix/missinggo/slices"
26 "github.com/anacrolix/missinggo/v2"
27 "github.com/anacrolix/missinggo/v2/bitmap"
28 "github.com/anacrolix/multiless"
29 "github.com/anacrolix/sync"
30 "github.com/davecgh/go-spew/spew"
31 "github.com/pion/datachannel"
33 "github.com/anacrolix/torrent/bencode"
34 "github.com/anacrolix/torrent/common"
35 "github.com/anacrolix/torrent/metainfo"
36 pp "github.com/anacrolix/torrent/peer_protocol"
37 "github.com/anacrolix/torrent/segments"
38 "github.com/anacrolix/torrent/storage"
39 "github.com/anacrolix/torrent/tracker"
40 "github.com/anacrolix/torrent/webseed"
41 "github.com/anacrolix/torrent/webtorrent"
44 // Maintains state of torrent within a Client. Many methods should not be called before the info is
45 // available, see .Info and .GotInfo.
47 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
48 // alignment. See #262.
53 networkingEnabled chansync.Flag
54 dataDownloadDisallowed chansync.Flag
55 dataUploadDisallowed bool
56 userOnWriteChunkErr func(error)
58 closed chansync.SetOnce
59 infoHash metainfo.Hash
61 // Values are the piece indices that changed.
62 pieceStateChanges *pubsub.PubSub
63 // The size of chunks to request from peers over the wire. This is
64 // normally 16KiB by convention these days.
67 // Total length of the torrent in bytes. Stored because it's not O(1) to
68 // get this from the info dict.
71 // The storage to open when the info dict becomes available.
72 storageOpener *storage.Client
73 // Storage for torrent data.
74 storage *storage.Torrent
75 // Read-locked for using storage, and write-locked for Closing.
76 storageLock sync.RWMutex
78 // TODO: Only announce stuff is used?
79 metainfo metainfo.MetaInfo
81 // The info dict. nil if we don't have it (yet).
83 fileIndex segments.Index
86 webSeeds map[string]*Peer
88 // Active peer connections, running message stream loops. TODO: Make this
89 // open (not-closed) connections only.
90 conns map[*PeerConn]struct{}
91 maxEstablishedConns int
92 // Set of addrs to which we're attempting to connect. Connections are
93 // half-open until all handshakes are completed.
94 halfOpen map[string]PeerInfo
96 // Reserve of peers to connect to. A peer can be both here and in the
97 // active connections if were told about the peer after connecting with
98 // them. That encourages us to reconnect to peers that are well known in
100 peers prioritizedPeers
101 // Whether we want to know to know more peers.
102 wantPeersEvent missinggo.Event
103 // An announcer for each tracker URL.
104 trackerAnnouncers map[string]torrentTrackerAnnouncer
105 // How many times we've initiated a DHT announce. TODO: Move into stats.
108 // Name used if the info name isn't available. Should be cleared when the
109 // Info does become available.
113 // The bencoded bytes of the info dict. This is actively manipulated if
114 // the info bytes aren't initially available, and we try to fetch them
117 // Each element corresponds to the 16KiB metadata pieces. If true, we have
118 // received that piece.
119 metadataCompletedChunks []bool
120 metadataChanged sync.Cond
122 // Closed when .Info is obtained.
123 gotMetainfoC chan struct{}
125 readers map[*reader]struct{}
126 _readerNowPieces bitmap.Bitmap
127 _readerReadaheadPieces bitmap.Bitmap
129 // A cache of pieces we need to get. Calculated from various piece and
130 // file priorities and completion states elsewhere.
131 _pendingPieces roaring.Bitmap
132 // A cache of completed piece indices.
133 _completedPieces roaring.Bitmap
134 // Pieces that need to be hashed.
135 piecesQueuedForHash bitmap.Bitmap
136 activePieceHashes int
137 initialPieceCheckDisabled bool
139 // Count of each request across active connections.
140 pendingRequests pendingRequests
141 // Chunks we've written to since the corresponding piece was last checked.
142 dirtyChunks roaring.Bitmap
146 // Is On when all pieces are complete.
147 Complete chansync.Flag
150 func (t *Torrent) pieceAvailabilityFromPeers(i pieceIndex) (count int) {
151 t.iterPeers(func(peer *Peer) {
152 if peer.peerHasPiece(i) {
159 func (t *Torrent) decPieceAvailability(i pieceIndex) {
164 if p.availability <= 0 {
165 panic(p.availability)
170 func (t *Torrent) incPieceAvailability(i pieceIndex) {
171 // If we don't the info, this should be reconciled when we do.
178 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
179 return t._readerNowPieces
182 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
183 return t._readerReadaheadPieces
186 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
187 return !t.wantPieceIndex(i)
190 // Returns a channel that is closed when the Torrent is closed.
191 func (t *Torrent) Closed() events.Done {
192 return t.closed.Done()
195 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
196 // pending, and half-open peers.
197 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
198 // Add pending peers to the list
199 t.peers.Each(func(peer PeerInfo) {
200 ks = append(ks, peer)
203 // Add half-open peers to the list
204 for _, peer := range t.halfOpen {
205 ks = append(ks, peer)
208 // Add active peers to the list
209 for conn := range t.conns {
210 ks = append(ks, PeerInfo{
212 Addr: conn.RemoteAddr,
213 Source: conn.Discovery,
214 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
215 // > But if we're not connected to them with an encrypted connection, I couldn't say
216 // > what's appropriate. We can carry forward the SupportsEncryption value as we
217 // > received it from trackers/DHT/PEX, or just use the encryption state for the
218 // > connection. It's probably easiest to do the latter for now.
219 // https://github.com/anacrolix/torrent/pull/188
220 SupportsEncryption: conn.headerEncrypted,
227 func (t *Torrent) setChunkSize(size pp.Integer) {
229 t.chunkPool = sync.Pool{
230 New: func() interface{} {
231 b := make([]byte, size)
237 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
238 return t._completedPieces.Contains(bitmap.BitIndex(piece))
241 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
242 return t.pieces[piece].Storage().Completion()
245 // There's a connection to that address already.
246 func (t *Torrent) addrActive(addr string) bool {
247 if _, ok := t.halfOpen[addr]; ok {
250 for c := range t.conns {
252 if ra.String() == addr {
259 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
260 return t.appendConns(ret, func(conn *PeerConn) bool {
261 return !conn.closed.IsSet()
265 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
266 for c := range t.conns {
274 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
276 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
277 if t.closed.IsSet() {
280 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
281 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
282 torrent.Add("peers not added because of bad addr", 1)
283 // cl.logger.Printf("peers not added because of bad addr: %v", p)
287 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
288 torrent.Add("peers replaced", 1)
289 if !replaced.equal(p) {
290 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
297 for t.peers.Len() > cl.config.TorrentPeersHighWater {
298 _, ok := t.peers.DeleteMin()
300 torrent.Add("excess reserve peers discarded", 1)
306 func (t *Torrent) invalidateMetadata() {
307 for i := 0; i < len(t.metadataCompletedChunks); i++ {
308 t.metadataCompletedChunks[i] = false
311 t.gotMetainfoC = make(chan struct{})
316 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
320 if index >= len(t.metadataCompletedChunks) {
321 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
324 copy(t.metadataBytes[(1<<14)*index:], data)
325 t.metadataCompletedChunks[index] = true
328 func (t *Torrent) metadataPieceCount() int {
329 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
332 func (t *Torrent) haveMetadataPiece(piece int) bool {
334 return (1<<14)*piece < len(t.metadataBytes)
336 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
340 func (t *Torrent) metadataSize() int {
341 return len(t.metadataBytes)
344 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
345 for i := 0; i < len(info.Pieces); i += sha1.Size {
346 ret = append(ret, info.Pieces[i:i+sha1.Size])
351 func (t *Torrent) makePieces() {
352 hashes := infoPieceHashes(t.info)
353 t.pieces = make([]Piece, len(hashes))
354 for i, hash := range hashes {
355 piece := &t.pieces[i]
357 piece.index = pieceIndex(i)
358 piece.noPendingWrites.L = &piece.pendingWritesMutex
359 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
361 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
362 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
363 piece.files = files[beginFile:endFile]
364 piece.undirtiedChunksIter = undirtiedChunksIter{
365 TorrentDirtyChunks: &t.dirtyChunks,
366 StartRequestIndex: piece.requestIndexOffset(),
367 EndRequestIndex: piece.requestIndexOffset() + piece.numChunks(),
372 // Returns the index of the first file containing the piece. files must be
373 // ordered by offset.
374 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
375 for i, f := range files {
376 if f.offset+f.length > pieceOffset {
383 // Returns the index after the last file containing the piece. files must be
384 // ordered by offset.
385 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
386 for i, f := range files {
387 if f.offset+f.length >= pieceEndOffset {
394 func (t *Torrent) cacheLength() {
396 for _, f := range t.info.UpvertedFiles() {
402 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
404 func (t *Torrent) setInfo(info *metainfo.Info) error {
405 if err := validateInfo(info); err != nil {
406 return fmt.Errorf("bad info: %s", err)
408 if t.storageOpener != nil {
410 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
412 return fmt.Errorf("error opening torrent storage: %s", err)
419 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
420 t.displayName = "" // Save a few bytes lol.
427 // This seems to be all the follow-up tasks after info is set, that can't fail.
428 func (t *Torrent) onSetInfo() {
429 for i := range t.pieces {
431 // Need to add availability before updating piece completion, as that may result in conns
433 if p.availability != 0 {
434 panic(p.availability)
436 p.availability = int64(t.pieceAvailabilityFromPeers(i))
437 t.updatePieceCompletion(pieceIndex(i))
438 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
439 // t.logger.Printf("piece %s completion unknown, queueing check", p)
440 t.queuePieceCheck(pieceIndex(i))
443 t.cl.event.Broadcast()
444 close(t.gotMetainfoC)
445 t.updateWantPeersEvent()
446 t.pendingRequests.Init(t.numRequests())
447 t.tryCreateMorePieceHashers()
448 t.iterPeers(func(p *Peer) {
450 p.updateRequests("onSetInfo")
454 // Called when metadata for a torrent becomes available.
455 func (t *Torrent) setInfoBytesLocked(b []byte) error {
456 if metainfo.HashBytes(b) != t.infoHash {
457 return errors.New("info bytes have wrong hash")
459 var info metainfo.Info
460 if err := bencode.Unmarshal(b, &info); err != nil {
461 return fmt.Errorf("error unmarshalling info bytes: %s", err)
464 t.metadataCompletedChunks = nil
468 if err := t.setInfo(&info); err != nil {
475 func (t *Torrent) haveAllMetadataPieces() bool {
479 if t.metadataCompletedChunks == nil {
482 for _, have := range t.metadataCompletedChunks {
490 // TODO: Propagate errors to disconnect peer.
491 func (t *Torrent) setMetadataSize(size int) (err error) {
493 // We already know the correct metadata size.
496 if uint32(size) > maxMetadataSize {
497 return errors.New("bad size")
499 if len(t.metadataBytes) == size {
502 t.metadataBytes = make([]byte, size)
503 t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
504 t.metadataChanged.Broadcast()
505 for c := range t.conns {
506 c.requestPendingMetadata()
511 // The current working name for the torrent. Either the name in the info dict,
512 // or a display name given such as by the dn value in a magnet link, or "".
513 func (t *Torrent) name() string {
515 defer t.nameMu.RUnlock()
519 if t.displayName != "" {
522 return "infohash:" + t.infoHash.HexString()
525 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
526 p := &t.pieces[index]
527 ret.Priority = t.piecePriority(index)
528 ret.Completion = p.completion()
529 ret.QueuedForHash = p.queuedForHash()
530 ret.Hashing = p.hashing
531 ret.Checking = ret.QueuedForHash || ret.Hashing
532 ret.Marking = p.marking
533 if !ret.Complete && t.piecePartiallyDownloaded(index) {
539 func (t *Torrent) metadataPieceSize(piece int) int {
540 return metadataPieceSize(len(t.metadataBytes), piece)
543 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
546 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
547 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
549 TotalSize: len(t.metadataBytes),
555 type pieceAvailabilityRun struct {
560 func (me pieceAvailabilityRun) String() string {
561 return fmt.Sprintf("%v(%v)", me.count, me.availability)
564 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
565 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
566 ret = append(ret, pieceAvailabilityRun{availability: el.(int64), count: int(count)})
568 for i := range t.pieces {
569 rle.Append(t.pieces[i].availability, 1)
575 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
576 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
577 ret = append(ret, PieceStateRun{
578 PieceState: el.(PieceState),
582 for index := range t.pieces {
583 rle.Append(t.pieceState(pieceIndex(index)), 1)
589 // Produces a small string representing a PieceStateRun.
590 func (psr PieceStateRun) String() (ret string) {
591 ret = fmt.Sprintf("%d", psr.Length)
592 ret += func() string {
593 switch psr.Priority {
594 case PiecePriorityNext:
596 case PiecePriorityNormal:
598 case PiecePriorityReadahead:
600 case PiecePriorityNow:
602 case PiecePriorityHigh:
611 if psr.QueuedForHash {
629 func (t *Torrent) writeStatus(w io.Writer) {
630 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
631 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
633 fmt.Fprintf(w, "Metadata have: ")
634 for _, h := range t.metadataCompletedChunks {
635 fmt.Fprintf(w, "%c", func() rune {
645 fmt.Fprintf(w, "Piece length: %s\n",
648 return fmt.Sprintf("%v (%v chunks)",
650 float64(t.usualPieceSize())/float64(t.chunkSize))
657 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
658 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
659 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
660 for _, run := range t.pieceAvailabilityRuns() {
661 ret = append(ret, run.String())
666 fmt.Fprintf(w, "Reader Pieces:")
667 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
668 fmt.Fprintf(w, " %d:%d", begin, end)
673 fmt.Fprintf(w, "Enabled trackers:\n")
675 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
676 fmt.Fprintf(tw, " URL\tExtra\n")
677 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
680 var luns, runs url.URL = *lu, *ru
683 var ml missinggo.MultiLess
684 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
685 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
687 }).([]torrentTrackerAnnouncer) {
688 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
693 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
695 spew.NewDefaultConfig()
696 spew.Fdump(w, t.statsLocked())
698 peers := t.peersAsSlice()
699 sort.Slice(peers, func(_i, _j int) bool {
702 if less, ok := multiless.New().EagerSameLess(
703 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
707 return worseConn(i, j)
709 for i, c := range peers {
710 fmt.Fprintf(w, "%2d. ", i+1)
715 func (t *Torrent) haveInfo() bool {
719 // Returns a run-time generated MetaInfo that includes the info bytes and
720 // announce-list as currently known to the client.
721 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
722 return metainfo.MetaInfo{
723 CreationDate: time.Now().Unix(),
724 Comment: "dynamic metainfo from client",
725 CreatedBy: "go.torrent",
726 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
727 InfoBytes: func() []byte {
729 return t.metadataBytes
734 UrlList: func() []string {
735 ret := make([]string, 0, len(t.webSeeds))
736 for url := range t.webSeeds {
737 ret = append(ret, url)
745 func (t *Torrent) BytesMissing() (n int64) {
747 n = t.bytesMissingLocked()
752 func (t *Torrent) bytesMissingLocked() int64 {
756 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
757 roaring.Flip(b, 0, end).Iterate(cb)
760 func (t *Torrent) bytesLeft() (left int64) {
761 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
762 p := t.piece(pieceIndex(x))
763 left += int64(p.length() - p.numDirtyBytes())
769 // Bytes left to give in tracker announces.
770 func (t *Torrent) bytesLeftAnnounce() int64 {
778 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
779 if t.pieceComplete(piece) {
782 if t.pieceAllDirty(piece) {
785 return t.pieces[piece].hasDirtyChunks()
788 func (t *Torrent) usualPieceSize() int {
789 return int(t.info.PieceLength)
792 func (t *Torrent) numPieces() pieceIndex {
793 return pieceIndex(t.info.NumPieces())
796 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
797 return pieceIndex(t._completedPieces.GetCardinality())
800 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
802 if t.storage != nil {
807 defer t.storageLock.Unlock()
808 if f := t.storage.Close; f != nil {
811 t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
816 t.iterPeers(func(p *Peer) {
820 t.cl.event.Broadcast()
821 t.pieceStateChanges.Close()
822 t.updateWantPeersEvent()
826 func (t *Torrent) requestOffset(r Request) int64 {
827 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
830 // Return the request that would include the given offset into the torrent data. Returns !ok if
831 // there is no such request.
832 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
833 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
836 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
837 defer perf.ScopeTimerErr(&err)()
838 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
839 if err == nil && n != len(data) {
840 err = io.ErrShortWrite
845 func (t *Torrent) bitfield() (bf []bool) {
846 bf = make([]bool, t.numPieces())
847 t._completedPieces.Iterate(func(piece uint32) (again bool) {
854 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
855 return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
858 func (t *Torrent) chunksPerRegularPiece() uint32 {
859 return uint32((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
862 func (t *Torrent) numRequests() RequestIndex {
863 if t.numPieces() == 0 {
866 return uint32(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
869 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
870 t.dirtyChunks.RemoveRange(
871 uint64(t.pieceRequestIndexOffset(pieceIndex)),
872 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
875 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
876 if t.info.PieceLength == 0 {
877 // There will be no variance amongst pieces. Only pain.
880 if piece == t.numPieces()-1 {
881 ret := pp.Integer(*t.length % t.info.PieceLength)
886 return pp.Integer(t.info.PieceLength)
889 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
891 p.waitNoPendingWrites()
892 storagePiece := t.pieces[piece].Storage()
894 // Does the backend want to do its own hashing?
895 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
896 var sum metainfo.Hash
897 // log.Printf("A piece decided to self-hash: %d", piece)
898 sum, err = i.SelfHash()
899 missinggo.CopyExact(&ret, sum)
903 hash := pieceHash.New()
904 const logPieceContents = false
905 if logPieceContents {
906 var examineBuf bytes.Buffer
907 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
908 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
910 _, err = storagePiece.WriteTo(hash)
912 missinggo.CopyExact(&ret, hash.Sum(nil))
916 func (t *Torrent) haveAnyPieces() bool {
917 return !t._completedPieces.IsEmpty()
920 func (t *Torrent) haveAllPieces() bool {
924 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
927 func (t *Torrent) havePiece(index pieceIndex) bool {
928 return t.haveInfo() && t.pieceComplete(index)
931 func (t *Torrent) maybeDropMutuallyCompletePeer(
932 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
936 if !t.cl.config.DropMutuallyCompletePeers {
939 if !t.haveAllPieces() {
942 if all, known := p.peerHasAllPieces(); !(known && all) {
948 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
952 func (t *Torrent) haveChunk(r Request) (ret bool) {
954 // log.Println("have chunk", r, ret)
959 if t.pieceComplete(pieceIndex(r.Index)) {
962 p := &t.pieces[r.Index]
963 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
966 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
967 return chunkIndexType(cs.Begin / chunkSize)
970 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
971 return t._pendingPieces.Contains(uint32(index))
974 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
975 // conns (which is a map).
976 var peerConnSlices sync.Pool
978 func getPeerConnSlice(cap int) []*PeerConn {
979 getInterface := peerConnSlices.Get()
980 if getInterface == nil {
981 return make([]*PeerConn, 0, cap)
983 return getInterface.([]*PeerConn)[:0]
987 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
988 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
989 // established connections for more than a minute. This is O(n log n). If there was a way to not
990 // consider the position of a conn relative to the total number, it could be reduced to O(n).
991 func (t *Torrent) worstBadConn() (ret *PeerConn) {
992 wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
993 defer peerConnSlices.Put(wcs.conns)
997 c := heap.Pop(&wcs).(*PeerConn)
998 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1001 // If the connection is in the worst half of the established
1002 // connection quota and is older than a minute.
1003 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1004 // Give connections 1 minute to prove themselves.
1005 if time.Since(c.completedHandshake) > time.Minute {
1013 type PieceStateChange struct {
1018 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1019 t.cl._mu.Defer(func() {
1020 cur := t.pieceState(piece)
1021 p := &t.pieces[piece]
1022 if cur != p.publicPieceState {
1023 p.publicPieceState = cur
1024 t.pieceStateChanges.Publish(PieceStateChange{
1032 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1033 if t.pieceComplete(piece) {
1036 return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1039 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1040 return t.pieces[piece].allChunksDirty()
1043 func (t *Torrent) readersChanged() {
1044 t.updateReaderPieces()
1045 t.updateAllPiecePriorities("Torrent.readersChanged")
1048 func (t *Torrent) updateReaderPieces() {
1049 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1052 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1056 t.updateReaderPieces()
1057 // Order the ranges, high and low.
1059 if l.begin > h.begin {
1062 if l.end < h.begin {
1063 // Two distinct ranges.
1064 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1065 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1072 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1076 func (t *Torrent) maybeNewConns() {
1077 // Tickle the accept routine.
1078 t.cl.event.Broadcast()
1082 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1083 if t._pendingPieces.Contains(uint32(piece)) {
1084 t.iterPeers(func(c *Peer) {
1085 if c.actualRequestState.Interested {
1088 if !c.isLowOnRequests() {
1091 if !c.peerHasPiece(piece) {
1094 if c.peerChoking && !c.peerAllowedFast.Contains(uint32(piece)) {
1097 c.updateRequests(reason)
1101 t.publishPieceChange(piece)
1104 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1105 p := &t.pieces[piece]
1106 newPrio := p.uncachedPriority()
1107 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1108 if newPrio == PiecePriorityNone {
1109 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1113 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1117 t.piecePriorityChanged(piece, reason)
1120 func (t *Torrent) updateAllPiecePriorities(reason string) {
1121 t.updatePiecePriorities(0, t.numPieces(), reason)
1124 // Update all piece priorities in one hit. This function should have the same
1125 // output as updatePiecePriority, but across all pieces.
1126 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1127 for i := begin; i < end; i++ {
1128 t.updatePiecePriority(i, reason)
1132 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1133 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1134 if off >= *t.length {
1144 begin = pieceIndex(off / t.info.PieceLength)
1145 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1146 if end > pieceIndex(t.info.NumPieces()) {
1147 end = pieceIndex(t.info.NumPieces())
1152 // Returns true if all iterations complete without breaking. Returns the read regions for all
1153 // readers. The reader regions should not be merged as some callers depend on this method to
1154 // enumerate readers.
1155 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1156 for r := range t.readers {
1158 if p.begin >= p.end {
1161 if !f(p.begin, p.end) {
1168 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1169 return t.piece(piece).uncachedPriority()
1172 func (t *Torrent) pendRequest(req RequestIndex) {
1173 t.piece(int(req / t.chunksPerRegularPiece())).pendChunkIndex(req % t.chunksPerRegularPiece())
1176 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1177 t.cl.event.Broadcast()
1178 if t.pieceComplete(piece) {
1179 t.onPieceCompleted(piece)
1181 t.onIncompletePiece(piece)
1183 t.updatePiecePriority(piece, reason)
1186 func (t *Torrent) numReceivedConns() (ret int) {
1187 for c := range t.conns {
1188 if c.Discovery == PeerSourceIncoming {
1195 func (t *Torrent) maxHalfOpen() int {
1196 // Note that if we somehow exceed the maximum established conns, we want
1197 // the negative value to have an effect.
1198 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1199 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1200 // We want to allow some experimentation with new peers, and to try to
1201 // upset an oversupply of received connections.
1202 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1205 func (t *Torrent) openNewConns() (initiated int) {
1206 defer t.updateWantPeersEvent()
1207 for t.peers.Len() != 0 {
1211 if len(t.halfOpen) >= t.maxHalfOpen() {
1214 if len(t.cl.dialers) == 0 {
1217 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1220 p := t.peers.PopMax()
1227 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1229 uncached := t.pieceCompleteUncached(piece)
1230 cached := p.completion()
1231 changed := cached != uncached
1232 complete := uncached.Complete
1233 p.storageCompletionOk = uncached.Ok
1236 t._completedPieces.Add(x)
1239 t._completedPieces.Remove(x)
1242 if complete && len(p.dirtiers) != 0 {
1243 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1246 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1247 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1252 // Non-blocking read. Client lock is not required.
1253 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1255 p := &t.pieces[off/t.info.PieceLength]
1256 p.waitNoPendingWrites()
1258 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1269 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1270 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1271 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1272 func (t *Torrent) maybeCompleteMetadata() error {
1277 if !t.haveAllMetadataPieces() {
1278 // Don't have enough metadata pieces.
1281 err := t.setInfoBytesLocked(t.metadataBytes)
1283 t.invalidateMetadata()
1284 return fmt.Errorf("error setting info bytes: %s", err)
1286 if t.cl.config.Debug {
1287 t.logger.Printf("%s: got metadata from peers", t)
1292 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1293 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1295 now.Add(bitmap.BitIndex(begin))
1296 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1303 func (t *Torrent) needData() bool {
1304 if t.closed.IsSet() {
1310 return !t._pendingPieces.IsEmpty()
1313 func appendMissingStrings(old, new []string) (ret []string) {
1316 for _, n := range new {
1317 for _, o := range old {
1322 ret = append(ret, n)
1327 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1329 for minNumTiers > len(ret) {
1330 ret = append(ret, nil)
1335 func (t *Torrent) addTrackers(announceList [][]string) {
1336 fullAnnounceList := &t.metainfo.AnnounceList
1337 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1338 for tierIndex, trackerURLs := range announceList {
1339 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1341 t.startMissingTrackerScrapers()
1342 t.updateWantPeersEvent()
1345 // Don't call this before the info is available.
1346 func (t *Torrent) bytesCompleted() int64 {
1350 return *t.length - t.bytesLeft()
1353 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1356 return t.setInfoBytesLocked(b)
1359 // Returns true if connection is removed from torrent.Conns.
1360 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1361 if !c.closed.IsSet() {
1362 panic("connection is not closed")
1363 // There are behaviours prevented by the closed state that will fail
1364 // if the connection has been deleted.
1368 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1369 // the drop event against the PexConnState instead.
1371 if !t.cl.config.DisablePEX {
1375 torrent.Add("deleted connections", 1)
1376 c.deleteAllRequests()
1377 t.assertPendingRequests()
1381 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1385 p.newPeerPieces().Iterate(func(i uint32) bool {
1386 p.t.decPieceAvailability(pieceIndex(i))
1391 func (t *Torrent) assertPendingRequests() {
1395 // var actual pendingRequests
1396 // if t.haveInfo() {
1397 // actual.m = make([]int, t.numRequests())
1399 // t.iterPeers(func(p *Peer) {
1400 // p.actualRequestState.Requests.Iterate(func(x uint32) bool {
1405 // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1411 func (t *Torrent) dropConnection(c *PeerConn) {
1412 t.cl.event.Broadcast()
1414 if t.deletePeerConn(c) {
1419 // Peers as in contact information for dialing out.
1420 func (t *Torrent) wantPeers() bool {
1421 if t.closed.IsSet() {
1424 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1427 return t.wantConns()
1430 func (t *Torrent) updateWantPeersEvent() {
1432 t.wantPeersEvent.Set()
1434 t.wantPeersEvent.Clear()
1438 // Returns whether the client should make effort to seed the torrent.
1439 func (t *Torrent) seeding() bool {
1441 if t.closed.IsSet() {
1444 if t.dataUploadDisallowed {
1447 if cl.config.NoUpload {
1450 if !cl.config.Seed {
1453 if cl.config.DisableAggressiveUpload && t.needData() {
1459 func (t *Torrent) onWebRtcConn(
1460 c datachannel.ReadWriteCloser,
1461 dcc webtorrent.DataChannelContext,
1464 pc, err := t.cl.initiateProtocolHandshakes(
1465 context.Background(),
1466 webrtcNetConn{c, dcc},
1470 webrtcNetAddr{dcc.Remote},
1472 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1475 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1478 if dcc.LocalOffered {
1479 pc.Discovery = PeerSourceTracker
1481 pc.Discovery = PeerSourceIncoming
1483 pc.conn.SetWriteDeadline(time.Time{})
1486 err = t.cl.runHandshookConn(pc, t)
1488 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1492 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1493 err := t.cl.runHandshookConn(pc, t)
1494 if err != nil || logAll {
1495 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1499 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1500 t.logRunHandshookConn(pc, false, log.Debug)
1503 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1504 wtc, release := t.cl.websocketTrackers.Get(u.String())
1509 wst := websocketTrackerStatus{u, wtc}
1511 err := wtc.Announce(tracker.Started, t.infoHash)
1513 t.logger.WithDefaultLevel(log.Warning).Printf(
1514 "error in initial announce to %q: %v",
1522 func (t *Torrent) startScrapingTracker(_url string) {
1526 u, err := url.Parse(_url)
1528 // URLs with a leading '*' appear to be a uTorrent convention to
1529 // disable trackers.
1531 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1535 if u.Scheme == "udp" {
1537 t.startScrapingTracker(u.String())
1539 t.startScrapingTracker(u.String())
1542 if _, ok := t.trackerAnnouncers[_url]; ok {
1545 sl := func() torrentTrackerAnnouncer {
1548 if t.cl.config.DisableWebtorrent {
1551 return t.startWebsocketAnnouncer(*u)
1553 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1557 if t.cl.config.DisableIPv6 {
1561 newAnnouncer := &trackerScraper{
1564 lookupTrackerIp: t.cl.config.LookupTrackerIp,
1566 go newAnnouncer.Run()
1572 if t.trackerAnnouncers == nil {
1573 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1575 t.trackerAnnouncers[_url] = sl
1578 // Adds and starts tracker scrapers for tracker URLs that aren't already
1580 func (t *Torrent) startMissingTrackerScrapers() {
1581 if t.cl.config.DisableTrackers {
1584 t.startScrapingTracker(t.metainfo.Announce)
1585 for _, tier := range t.metainfo.AnnounceList {
1586 for _, url := range tier {
1587 t.startScrapingTracker(url)
1592 // Returns an AnnounceRequest with fields filled out to defaults and current
1594 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1595 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1596 // dependent on the network in use.
1597 return tracker.AnnounceRequest{
1599 NumWant: func() int32 {
1600 if t.wantPeers() && len(t.cl.dialers) > 0 {
1606 Port: uint16(t.cl.incomingPeerPort()),
1607 PeerId: t.cl.peerID,
1608 InfoHash: t.infoHash,
1609 Key: t.cl.announceKey(),
1611 // The following are vaguely described in BEP 3.
1613 Left: t.bytesLeftAnnounce(),
1614 Uploaded: t.stats.BytesWrittenData.Int64(),
1615 // There's no mention of wasted or unwanted download in the BEP.
1616 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1620 // Adds peers revealed in an announce until the announce ends, or we have
1622 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1624 for v := range pvs {
1627 for _, cp := range v.Peers {
1629 // Can't do anything with this.
1632 if t.addPeer(PeerInfo{
1633 Addr: ipPortAddr{cp.IP, cp.Port},
1634 Source: PeerSourceDhtGetPeers,
1641 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1646 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1647 // announce ends. stop will force the announce to end.
1648 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1649 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1653 _done := make(chan struct{})
1657 t.consumeDhtAnnouncePeers(ps.Peers())
1663 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1664 _, stop, err := t.AnnounceToDht(s)
1669 case <-t.closed.Done():
1670 case <-time.After(5 * time.Minute):
1676 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1682 if t.closed.IsSet() {
1685 // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1686 // TODO: We can include the announce_peer step depending on whether we can receive
1687 // inbound connections. We should probably only announce once every 15 mins too.
1691 // TODO: Determine if there's a listener on the port we're announcing.
1692 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1703 err := t.timeboxedAnnounceToDht(s)
1705 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1711 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1712 for _, p := range peers {
1720 // The returned TorrentStats may require alignment in memory. See
1721 // https://github.com/anacrolix/torrent/issues/383.
1722 func (t *Torrent) Stats() TorrentStats {
1724 defer t.cl.rUnlock()
1725 return t.statsLocked()
1728 func (t *Torrent) statsLocked() (ret TorrentStats) {
1729 ret.ActivePeers = len(t.conns)
1730 ret.HalfOpenPeers = len(t.halfOpen)
1731 ret.PendingPeers = t.peers.Len()
1732 ret.TotalPeers = t.numTotalPeers()
1733 ret.ConnectedSeeders = 0
1734 for c := range t.conns {
1735 if all, ok := c.peerHasAllPieces(); all && ok {
1736 ret.ConnectedSeeders++
1739 ret.ConnStats = t.stats.Copy()
1740 ret.PiecesComplete = t.numPiecesCompleted()
1744 // The total number of peers in the torrent.
1745 func (t *Torrent) numTotalPeers() int {
1746 peers := make(map[string]struct{})
1747 for conn := range t.conns {
1748 ra := conn.conn.RemoteAddr()
1750 // It's been closed and doesn't support RemoteAddr.
1753 peers[ra.String()] = struct{}{}
1755 for addr := range t.halfOpen {
1756 peers[addr] = struct{}{}
1758 t.peers.Each(func(peer PeerInfo) {
1759 peers[peer.Addr.String()] = struct{}{}
1764 // Reconcile bytes transferred before connection was associated with a
1766 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1767 if c._stats != (ConnStats{
1768 // Handshakes should only increment these fields:
1769 BytesWritten: c._stats.BytesWritten,
1770 BytesRead: c._stats.BytesRead,
1774 c.postHandshakeStats(func(cs *ConnStats) {
1775 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1776 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1778 c.reconciledHandshakeStats = true
1781 // Returns true if the connection is added.
1782 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1785 torrent.Add("added connections", 1)
1788 if t.closed.IsSet() {
1789 return errors.New("torrent closed")
1791 for c0 := range t.conns {
1792 if c.PeerID != c0.PeerID {
1795 if !t.cl.config.DropDuplicatePeerIds {
1798 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1800 t.deletePeerConn(c0)
1802 return errors.New("existing connection preferred")
1805 if len(t.conns) >= t.maxEstablishedConns {
1806 c := t.worstBadConn()
1808 return errors.New("don't want conns")
1813 if len(t.conns) >= t.maxEstablishedConns {
1816 t.conns[c] = struct{}{}
1817 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1818 t.pex.Add(c) // as no further extended handshake expected
1823 func (t *Torrent) wantConns() bool {
1824 if !t.networkingEnabled.Bool() {
1827 if t.closed.IsSet() {
1830 if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
1833 return len(t.conns) < t.maxEstablishedConns || t.worstBadConn() != nil
1836 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1839 oldMax = t.maxEstablishedConns
1840 t.maxEstablishedConns = max
1841 wcs := worseConnSlice{
1842 conns: t.appendConns(nil, func(*PeerConn) bool {
1848 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1849 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
1855 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1856 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1859 t.cl.event.Broadcast()
1860 if t.closed.IsSet() {
1864 // Don't score the first time a piece is hashed, it could be an initial check.
1865 if p.storageCompletionOk {
1867 pieceHashedCorrect.Add(1)
1870 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1871 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1872 pieceHashedNotCorrect.Add(1)
1877 t.publishPieceChange(piece)
1880 t.publishPieceChange(piece)
1884 if len(p.dirtiers) != 0 {
1885 // Don't increment stats above connection-level for every involved connection.
1886 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1888 for c := range p.dirtiers {
1889 c._stats.incrementPiecesDirtiedGood()
1891 t.clearPieceTouchers(piece)
1893 err := p.Storage().MarkComplete()
1895 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1899 if t.closed.IsSet() {
1902 t.pendAllChunkSpecs(piece)
1904 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1905 // Peers contributed to all the data for this piece hash failure, and the failure was
1906 // not due to errors in the storage (such as data being dropped in a cache).
1908 // Increment Torrent and above stats, and then specific connections.
1909 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1910 for c := range p.dirtiers {
1911 // Y u do dis peer?!
1912 c.stats().incrementPiecesDirtiedBad()
1915 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1916 for c := range p.dirtiers {
1918 bannableTouchers = append(bannableTouchers, c)
1921 t.clearPieceTouchers(piece)
1922 slices.Sort(bannableTouchers, connLessTrusted)
1924 if t.cl.config.Debug {
1926 "bannable conns by trust for piece %d: %v",
1928 func() (ret []connectionTrust) {
1929 for _, c := range bannableTouchers {
1930 ret = append(ret, c.trust())
1937 if len(bannableTouchers) >= 1 {
1938 c := bannableTouchers[0]
1939 t.cl.banPeerIP(c.remoteIp())
1943 t.onIncompletePiece(piece)
1944 p.Storage().MarkNotComplete()
1946 t.updatePieceCompletion(piece)
1949 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1950 // TODO: Make faster
1951 for cn := range t.conns {
1956 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1957 t.pendAllChunkSpecs(piece)
1958 t.cancelRequestsForPiece(piece)
1959 t.piece(piece).readerCond.Broadcast()
1960 for conn := range t.conns {
1962 t.maybeDropMutuallyCompletePeer(&conn.Peer)
1966 // Called when a piece is found to be not complete.
1967 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1968 if t.pieceAllDirty(piece) {
1969 t.pendAllChunkSpecs(piece)
1971 if !t.wantPieceIndex(piece) {
1972 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1975 // We could drop any connections that we told we have a piece that we
1976 // don't here. But there's a test failure, and it seems clients don't care
1977 // if you request pieces that you already claim to have. Pruning bad
1978 // connections might just remove any connections that aren't treating us
1979 // favourably anyway.
1981 // for c := range t.conns {
1982 // if c.sentHave(piece) {
1986 t.iterPeers(func(conn *Peer) {
1987 if conn.peerHasPiece(piece) {
1988 conn.updateRequests("piece incomplete")
1993 func (t *Torrent) tryCreateMorePieceHashers() {
1994 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1998 func (t *Torrent) tryCreatePieceHasher() bool {
1999 if t.storage == nil {
2002 pi, ok := t.getPieceToHash()
2007 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2009 t.publishPieceChange(pi)
2010 t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2011 t.storageLock.RLock()
2012 t.activePieceHashes++
2013 go t.pieceHasher(pi)
2017 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2018 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2019 if t.piece(i).hashing {
2029 func (t *Torrent) pieceHasher(index pieceIndex) {
2031 sum, copyErr := t.hashPiece(index)
2032 correct := sum == *p.hash
2036 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2038 t.storageLock.RUnlock()
2042 t.pieceHashed(index, correct, copyErr)
2043 t.updatePiecePriority(index, "Torrent.pieceHasher")
2044 t.activePieceHashes--
2045 t.tryCreateMorePieceHashers()
2048 // Return the connections that touched a piece, and clear the entries while doing it.
2049 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2051 for c := range p.dirtiers {
2052 delete(c.peerTouchedPieces, pi)
2053 delete(p.dirtiers, c)
2057 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2058 t.iterPeers(func(p *Peer) {
2059 ret = append(ret, p)
2064 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2065 piece := t.piece(pieceIndex)
2066 if piece.queuedForHash() {
2069 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2070 t.publishPieceChange(pieceIndex)
2071 t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2072 t.tryCreateMorePieceHashers()
2075 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2076 // before the Info is available.
2077 func (t *Torrent) VerifyData() {
2078 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2079 t.Piece(i).VerifyData()
2083 // Start the process of connecting to the given peer for the given torrent if appropriate.
2084 func (t *Torrent) initiateConn(peer PeerInfo) {
2085 if peer.Id == t.cl.peerID {
2088 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2092 if t.addrActive(addr.String()) {
2096 t.halfOpen[addr.String()] = peer
2097 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2100 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2101 // quickly make one Client visible to the Torrent of another Client.
2102 func (t *Torrent) AddClientPeer(cl *Client) int {
2103 return t.AddPeers(func() (ps []PeerInfo) {
2104 for _, la := range cl.ListenAddrs() {
2105 ps = append(ps, PeerInfo{
2114 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2116 func (t *Torrent) allStats(f func(*ConnStats)) {
2121 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2122 return t.pieces[i].hashing
2125 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2126 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2129 func (t *Torrent) dialTimeout() time.Duration {
2130 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2133 func (t *Torrent) piece(i int) *Piece {
2137 func (t *Torrent) onWriteChunkErr(err error) {
2138 if t.userOnWriteChunkErr != nil {
2139 go t.userOnWriteChunkErr(err)
2142 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2143 t.disallowDataDownloadLocked()
2146 func (t *Torrent) DisallowDataDownload() {
2147 t.disallowDataDownloadLocked()
2150 func (t *Torrent) disallowDataDownloadLocked() {
2151 t.dataDownloadDisallowed.Set()
2154 func (t *Torrent) AllowDataDownload() {
2155 t.dataDownloadDisallowed.Clear()
2158 // Enables uploading data, if it was disabled.
2159 func (t *Torrent) AllowDataUpload() {
2162 t.dataUploadDisallowed = false
2163 for c := range t.conns {
2164 c.updateRequests("allow data upload")
2168 // Disables uploading data, if it was enabled.
2169 func (t *Torrent) DisallowDataUpload() {
2172 t.dataUploadDisallowed = true
2173 for c := range t.conns {
2174 c.updateRequests("disallow data upload")
2178 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2179 // or if nil, a critical message is logged, and data download is disabled.
2180 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2183 t.userOnWriteChunkErr = f
2186 func (t *Torrent) iterPeers(f func(p *Peer)) {
2187 for pc := range t.conns {
2190 for _, ws := range t.webSeeds {
2195 func (t *Torrent) callbacks() *Callbacks {
2196 return &t.cl.config.Callbacks
2199 func (t *Torrent) addWebSeed(url string) {
2200 if t.cl.config.DisableWebseeds {
2203 if _, ok := t.webSeeds[url]; ok {
2206 // I don't think Go http supports pipelining requests. However, we can have more ready to go
2207 // right away. This value should be some multiple of the number of connections to a host. I
2208 // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2209 // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2210 // "https://webtorrent.io/torrents/".
2211 const maxRequests = 16
2217 reconciledHandshakeStats: true,
2218 // This should affect how often we have to recompute requests for this peer. Note that
2219 // because we can request more than 1 thing at a time over HTTP, we will hit the low
2220 // requests mark more often, so recomputation is probably sooner than with regular peer
2221 // conns. ~4x maxRequests would be about right.
2222 PeerMaxRequests: 128,
2223 RemoteAddr: remoteAddrFromUrl(url),
2224 callbacks: t.callbacks(),
2226 client: webseed.Client{
2227 HttpClient: t.cl.webseedHttpClient,
2230 activeRequests: make(map[Request]webseed.Request, maxRequests),
2231 maxRequests: maxRequests,
2233 ws.peer.initUpdateRequestsTimer()
2234 ws.requesterCond.L = t.cl.locker()
2235 for i := 0; i < maxRequests; i += 1 {
2238 for _, f := range t.callbacks().NewPeer {
2241 ws.peer.logger = t.logger.WithContextValue(&ws)
2242 ws.peer.peerImpl = &ws
2244 ws.onGotInfo(t.info)
2246 t.webSeeds[url] = &ws.peer
2249 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2250 t.iterPeers(func(p1 *Peer) {
2258 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2259 index := ri / t.chunksPerRegularPiece()
2262 t.piece(int(index)).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2266 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2267 return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + uint32(r.Begin/t.chunkSize)
2270 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2271 return RequestIndex(piece) * t.chunksPerRegularPiece()
2274 func (t *Torrent) updateComplete() {
2275 t.Complete.SetBool(t.haveAllPieces())