21 "github.com/anacrolix/dht/v2"
22 "github.com/anacrolix/log"
23 "github.com/anacrolix/missinggo/iter"
24 "github.com/anacrolix/missinggo/perf"
25 "github.com/anacrolix/missinggo/pubsub"
26 "github.com/anacrolix/missinggo/slices"
27 "github.com/anacrolix/missinggo/v2"
28 "github.com/anacrolix/missinggo/v2/bitmap"
29 "github.com/anacrolix/missinggo/v2/prioritybitmap"
30 "github.com/anacrolix/multiless"
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 bool
55 dataDownloadDisallowed bool
56 dataUploadDisallowed bool
57 userOnWriteChunkErr func(error)
59 closed missinggo.Event
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
89 // Active peer connections, running message stream loops. TODO: Make this
90 // open (not-closed) connections only.
91 conns map[*PeerConn]struct{}
92 maxEstablishedConns int
93 // Set of addrs to which we're attempting to connect. Connections are
94 // half-open until all handshakes are completed.
95 halfOpen map[string]PeerInfo
97 // Reserve of peers to connect to. A peer can be both here and in the
98 // active connections if were told about the peer after connecting with
99 // them. That encourages us to reconnect to peers that are well known in
101 peers prioritizedPeers
102 // Whether we want to know to know more peers.
103 wantPeersEvent missinggo.Event
104 // An announcer for each tracker URL.
105 trackerAnnouncers map[string]torrentTrackerAnnouncer
106 // How many times we've initiated a DHT announce. TODO: Move into stats.
109 // Name used if the info name isn't available. Should be cleared when the
110 // Info does become available.
114 // The bencoded bytes of the info dict. This is actively manipulated if
115 // the info bytes aren't initially available, and we try to fetch them
118 // Each element corresponds to the 16KiB metadata pieces. If true, we have
119 // received that piece.
120 metadataCompletedChunks []bool
121 metadataChanged sync.Cond
123 // Set when .Info is obtained.
124 gotMetainfo missinggo.Event
126 readers map[*reader]struct{}
127 _readerNowPieces bitmap.Bitmap
128 _readerReadaheadPieces bitmap.Bitmap
130 // A cache of pieces we need to get. Calculated from various piece and
131 // file priorities and completion states elsewhere.
132 _pendingPieces prioritybitmap.PriorityBitmap
133 // A cache of completed piece indices.
134 _completedPieces bitmap.Bitmap
135 // Pieces that need to be hashed.
136 piecesQueuedForHash bitmap.Bitmap
137 activePieceHashes int
139 // A pool of piece priorities []int for assignment to new connections.
140 // These "inclinations" are used to give connections preference for
142 connPieceInclinationPool sync.Pool
144 // Count of each request across active connections.
145 pendingRequests map[Request]int
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) numConns() int {
182 func (t *Torrent) numReaders() int {
183 return len(t.readers)
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 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
199 return &t._pendingPieces
202 func (t *Torrent) tickleReaders() {
203 t.cl.event.Broadcast()
206 // Returns a channel that is closed when the Torrent is closed.
207 func (t *Torrent) Closed() <-chan struct{} {
208 return t.closed.LockedChan(t.cl.locker())
211 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
212 // pending, and half-open peers.
213 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
214 // Add pending peers to the list
215 t.peers.Each(func(peer PeerInfo) {
216 ks = append(ks, peer)
219 // Add half-open peers to the list
220 for _, peer := range t.halfOpen {
221 ks = append(ks, peer)
224 // Add active peers to the list
225 for conn := range t.conns {
227 ks = append(ks, PeerInfo{
229 Addr: conn.RemoteAddr,
230 Source: conn.Discovery,
231 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
232 // > But if we're not connected to them with an encrypted connection, I couldn't say
233 // > what's appropriate. We can carry forward the SupportsEncryption value as we
234 // > received it from trackers/DHT/PEX, or just use the encryption state for the
235 // > connection. It's probably easiest to do the latter for now.
236 // https://github.com/anacrolix/torrent/pull/188
237 SupportsEncryption: conn.headerEncrypted,
244 func (t *Torrent) setChunkSize(size pp.Integer) {
246 t.chunkPool = &sync.Pool{
247 New: func() interface{} {
248 b := make([]byte, size)
254 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
255 return t._completedPieces.Get(bitmap.BitIndex(piece))
258 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
259 return t.pieces[piece].Storage().Completion()
262 // There's a connection to that address already.
263 func (t *Torrent) addrActive(addr string) bool {
264 if _, ok := t.halfOpen[addr]; ok {
267 for c := range t.conns {
269 if ra.String() == addr {
276 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
277 ret = make([]*PeerConn, 0, len(t.conns))
278 for c := range t.conns {
279 if !c.closed.IsSet() {
286 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
288 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
289 if t.closed.IsSet() {
292 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
293 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
294 torrent.Add("peers not added because of bad addr", 1)
295 // cl.logger.Printf("peers not added because of bad addr: %v", p)
299 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
300 torrent.Add("peers replaced", 1)
301 if !replaced.equal(p) {
302 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
309 for t.peers.Len() > cl.config.TorrentPeersHighWater {
310 _, ok := t.peers.DeleteMin()
312 torrent.Add("excess reserve peers discarded", 1)
318 func (t *Torrent) invalidateMetadata() {
319 for i := range t.metadataCompletedChunks {
320 t.metadataCompletedChunks[i] = false
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]
378 // Returns the index of the first file containing the piece. files must be
379 // ordered by offset.
380 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
381 for i, f := range files {
382 if f.offset+f.length > pieceOffset {
389 // Returns the index after the last file containing the piece. files must be
390 // ordered by offset.
391 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
392 for i, f := range files {
393 if f.offset+f.length >= pieceEndOffset {
400 func (t *Torrent) cacheLength() {
402 for _, f := range t.info.UpvertedFiles() {
408 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
410 func (t *Torrent) setInfo(info *metainfo.Info) error {
411 if err := validateInfo(info); err != nil {
412 return fmt.Errorf("bad info: %s", err)
414 if t.storageOpener != nil {
416 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
418 return fmt.Errorf("error opening torrent storage: %s", err)
424 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
425 t.displayName = "" // Save a few bytes lol.
432 // This seems to be all the follow-up tasks after info is set, that can't fail.
433 func (t *Torrent) onSetInfo() {
434 t.iterPeers(func(p *Peer) {
437 for i := range t.pieces {
439 // Need to add availability before updating piece completion, as that may result in conns
441 if p.availability != 0 {
442 panic(p.availability)
444 p.availability = int64(t.pieceAvailabilityFromPeers(i))
445 t.updatePieceCompletion(pieceIndex(i))
446 if !p.storageCompletionOk {
447 // t.logger.Printf("piece %s completion unknown, queueing check", p)
448 t.queuePieceCheck(pieceIndex(i))
451 t.cl.event.Broadcast()
453 t.updateWantPeersEvent()
454 t.pendingRequests = make(map[Request]int)
455 t.tryCreateMorePieceHashers()
458 // Called when metadata for a torrent becomes available.
459 func (t *Torrent) setInfoBytes(b []byte) error {
460 if metainfo.HashBytes(b) != t.infoHash {
461 return errors.New("info bytes have wrong hash")
463 var info metainfo.Info
464 if err := bencode.Unmarshal(b, &info); err != nil {
465 return fmt.Errorf("error unmarshalling info bytes: %s", err)
468 t.metadataCompletedChunks = nil
472 if err := t.setInfo(&info); err != nil {
479 func (t *Torrent) haveAllMetadataPieces() bool {
483 if t.metadataCompletedChunks == nil {
486 for _, have := range t.metadataCompletedChunks {
494 // TODO: Propagate errors to disconnect peer.
495 func (t *Torrent) setMetadataSize(bytes int) (err error) {
497 // We already know the correct metadata size.
500 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
501 return errors.New("bad size")
503 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
506 t.metadataBytes = make([]byte, bytes)
507 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
508 t.metadataChanged.Broadcast()
509 for c := range t.conns {
510 c.requestPendingMetadata()
515 // The current working name for the torrent. Either the name in the info dict,
516 // or a display name given such as by the dn value in a magnet link, or "".
517 func (t *Torrent) name() string {
519 defer t.nameMu.RUnlock()
523 if t.displayName != "" {
526 return "infohash:" + t.infoHash.HexString()
529 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
530 p := &t.pieces[index]
531 ret.Priority = t.piecePriority(index)
532 ret.Completion = p.completion()
533 ret.QueuedForHash = p.queuedForHash()
534 ret.Hashing = p.hashing
535 ret.Checking = ret.QueuedForHash || ret.Hashing
536 ret.Marking = p.marking
537 if !ret.Complete && t.piecePartiallyDownloaded(index) {
543 func (t *Torrent) metadataPieceSize(piece int) int {
544 return metadataPieceSize(len(t.metadataBytes), piece)
547 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
550 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
551 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
553 TotalSize: len(t.metadataBytes),
559 type pieceAvailabilityRun struct {
564 func (me pieceAvailabilityRun) String() string {
565 return fmt.Sprintf("%v(%v)", me.count, me.availability)
568 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
569 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
570 ret = append(ret, pieceAvailabilityRun{availability: el.(int64), count: int(count)})
572 for i := range t.pieces {
573 rle.Append(t.pieces[i].availability, 1)
579 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
580 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
581 ret = append(ret, PieceStateRun{
582 PieceState: el.(PieceState),
586 for index := range t.pieces {
587 rle.Append(t.pieceState(pieceIndex(index)), 1)
593 // Produces a small string representing a PieceStateRun.
594 func (psr PieceStateRun) String() (ret string) {
595 ret = fmt.Sprintf("%d", psr.Length)
596 ret += func() string {
597 switch psr.Priority {
598 case PiecePriorityNext:
600 case PiecePriorityNormal:
602 case PiecePriorityReadahead:
604 case PiecePriorityNow:
606 case PiecePriorityHigh:
615 if psr.QueuedForHash {
633 func (t *Torrent) writeStatus(w io.Writer) {
634 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
635 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
637 fmt.Fprintf(w, "Metadata have: ")
638 for _, h := range t.metadataCompletedChunks {
639 fmt.Fprintf(w, "%c", func() rune {
649 fmt.Fprintf(w, "Piece length: %s\n",
652 return fmt.Sprintf("%v (%v chunks)",
654 float64(t.usualPieceSize())/float64(t.chunkSize))
661 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
662 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
663 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
664 for _, run := range t.pieceAvailabilityRuns() {
665 ret = append(ret, run.String())
670 fmt.Fprintf(w, "Reader Pieces:")
671 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
672 fmt.Fprintf(w, " %d:%d", begin, end)
677 fmt.Fprintf(w, "Enabled trackers:\n")
679 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
680 fmt.Fprintf(tw, " URL\tExtra\n")
681 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
684 var luns, runs url.URL = *lu, *ru
687 var ml missinggo.MultiLess
688 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
689 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
691 }).([]torrentTrackerAnnouncer) {
692 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
697 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
699 spew.NewDefaultConfig()
700 spew.Fdump(w, t.statsLocked())
702 peers := t.peersAsSlice()
703 sort.Slice(peers, func(_i, _j int) bool {
706 if less, ok := multiless.New().EagerSameLess(
707 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
711 return worseConn(i, j)
713 for i, c := range peers {
714 fmt.Fprintf(w, "%2d. ", i+1)
719 func (t *Torrent) haveInfo() bool {
723 // Returns a run-time generated MetaInfo that includes the info bytes and
724 // announce-list as currently known to the client.
725 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
726 return metainfo.MetaInfo{
727 CreationDate: time.Now().Unix(),
728 Comment: "dynamic metainfo from client",
729 CreatedBy: "go.torrent",
730 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
731 InfoBytes: func() []byte {
733 return t.metadataBytes
738 UrlList: func() []string {
739 ret := make([]string, 0, len(t.webSeeds))
740 for url := range t.webSeeds {
741 ret = append(ret, url)
748 func (t *Torrent) BytesMissing() int64 {
751 return t.bytesMissingLocked()
754 func (t *Torrent) bytesMissingLocked() int64 {
758 func (t *Torrent) bytesLeft() (left int64) {
759 bitmap.Flip(t._completedPieces, 0, bitmap.BitRange(t.numPieces())).IterTyped(func(piece int) bool {
760 p := &t.pieces[piece]
761 left += int64(p.length() - p.numDirtyBytes())
767 // Bytes left to give in tracker announces.
768 func (t *Torrent) bytesLeftAnnounce() int64 {
776 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
777 if t.pieceComplete(piece) {
780 if t.pieceAllDirty(piece) {
783 return t.pieces[piece].hasDirtyChunks()
786 func (t *Torrent) usualPieceSize() int {
787 return int(t.info.PieceLength)
790 func (t *Torrent) numPieces() pieceIndex {
791 return pieceIndex(t.info.NumPieces())
794 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
795 return pieceIndex(t._completedPieces.Len())
798 func (t *Torrent) close() (err error) {
801 if t.storage != nil {
804 defer t.storageLock.Unlock()
805 if f := t.storage.Close; f != nil {
810 t.iterPeers(func(p *Peer) {
814 t.cl.event.Broadcast()
815 t.pieceStateChanges.Close()
816 t.updateWantPeersEvent()
820 func (t *Torrent) requestOffset(r Request) int64 {
821 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
824 // Return the request that would include the given offset into the torrent data. Returns !ok if
825 // there is no such request.
826 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
827 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
830 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
831 defer perf.ScopeTimerErr(&err)()
832 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
833 if err == nil && n != len(data) {
834 err = io.ErrShortWrite
839 func (t *Torrent) bitfield() (bf []bool) {
840 bf = make([]bool, t.numPieces())
841 t._completedPieces.IterTyped(func(piece int) (again bool) {
848 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
849 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
852 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
853 t.pieces[pieceIndex]._dirtyChunks.Clear()
856 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
857 if t.info.PieceLength == 0 {
858 // There will be no variance amongst pieces. Only pain.
861 if piece == t.numPieces()-1 {
862 ret := pp.Integer(*t.length % t.info.PieceLength)
867 return pp.Integer(t.info.PieceLength)
870 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
872 p.waitNoPendingWrites()
873 storagePiece := t.pieces[piece].Storage()
875 //Does the backend want to do its own hashing?
876 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
877 var sum metainfo.Hash
878 //log.Printf("A piece decided to self-hash: %d", piece)
879 sum, err = i.SelfHash()
880 missinggo.CopyExact(&ret, sum)
884 hash := pieceHash.New()
885 const logPieceContents = false
886 if logPieceContents {
887 var examineBuf bytes.Buffer
888 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
889 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
891 _, err = storagePiece.WriteTo(hash)
893 missinggo.CopyExact(&ret, hash.Sum(nil))
897 func (t *Torrent) haveAnyPieces() bool {
898 return t._completedPieces.Len() != 0
901 func (t *Torrent) haveAllPieces() bool {
905 return t._completedPieces.Len() == bitmap.BitRange(t.numPieces())
908 func (t *Torrent) havePiece(index pieceIndex) bool {
909 return t.haveInfo() && t.pieceComplete(index)
912 func (t *Torrent) maybeDropMutuallyCompletePeer(
913 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's okay?
916 if !t.cl.config.DropMutuallyCompletePeers {
919 if !t.haveAllPieces() {
922 if all, known := p.peerHasAllPieces(); !(known && all) {
928 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
932 func (t *Torrent) haveChunk(r Request) (ret bool) {
934 // log.Println("have chunk", r, ret)
939 if t.pieceComplete(pieceIndex(r.Index)) {
942 p := &t.pieces[r.Index]
943 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
946 func chunkIndex(cs ChunkSpec, chunkSize pp.Integer) int {
947 return int(cs.Begin / chunkSize)
950 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
951 // TODO: Are these overly conservative, should we be guarding this here?
956 if index < 0 || index >= t.numPieces() {
960 p := &t.pieces[index]
961 if p.queuedForHash() {
967 if t.pieceComplete(index) {
970 if t._pendingPieces.Contains(int(index)) {
973 // t.logger.Printf("piece %d not pending", index)
974 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
975 return index < begin || index >= end
979 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
980 // connection is one that usually sends us unwanted pieces, or has been in worser half of the
981 // established connections for more than a minute.
982 func (t *Torrent) worstBadConn() *PeerConn {
983 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
986 c := heap.Pop(&wcs).(*PeerConn)
987 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
990 // If the connection is in the worst half of the established
991 // connection quota and is older than a minute.
992 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
993 // Give connections 1 minute to prove themselves.
994 if time.Since(c.completedHandshake) > time.Minute {
1002 type PieceStateChange struct {
1007 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1008 t.cl._mu.Defer(func() {
1009 cur := t.pieceState(piece)
1010 p := &t.pieces[piece]
1011 if cur != p.publicPieceState {
1012 p.publicPieceState = cur
1013 t.pieceStateChanges.Publish(PieceStateChange{
1021 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1022 if t.pieceComplete(piece) {
1025 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
1028 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1029 return t.pieces[piece]._dirtyChunks.Len() == bitmap.BitRange(t.pieceNumChunks(piece))
1032 func (t *Torrent) readersChanged() {
1033 t.updateReaderPieces()
1034 t.updateAllPiecePriorities()
1037 func (t *Torrent) updateReaderPieces() {
1038 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1041 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1045 t.updateReaderPieces()
1046 // Order the ranges, high and low.
1048 if l.begin > h.begin {
1051 if l.end < h.begin {
1052 // Two distinct ranges.
1053 t.updatePiecePriorities(l.begin, l.end)
1054 t.updatePiecePriorities(h.begin, h.end)
1061 t.updatePiecePriorities(l.begin, end)
1065 func (t *Torrent) maybeNewConns() {
1066 // Tickle the accept routine.
1067 t.cl.event.Broadcast()
1071 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
1072 // t.logger.Printf("piece %d priority changed", piece)
1073 t.iterPeers(func(c *Peer) {
1074 if c.updatePiecePriority(piece) {
1075 // log.Print("conn piece priority changed")
1080 t.publishPieceChange(piece)
1083 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
1084 p := &t.pieces[piece]
1085 newPrio := p.uncachedPriority()
1086 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1087 if newPrio == PiecePriorityNone {
1088 if !t._pendingPieces.Remove(int(piece)) {
1092 if !t._pendingPieces.Set(int(piece), newPrio.BitmapPriority()) {
1096 t.piecePriorityChanged(piece)
1099 func (t *Torrent) updateAllPiecePriorities() {
1100 t.updatePiecePriorities(0, t.numPieces())
1103 // Update all piece priorities in one hit. This function should have the same
1104 // output as updatePiecePriority, but across all pieces.
1105 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
1106 for i := begin; i < end; i++ {
1107 t.updatePiecePriority(i)
1111 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1112 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1113 if off >= *t.length {
1123 begin = pieceIndex(off / t.info.PieceLength)
1124 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1125 if end > pieceIndex(t.info.NumPieces()) {
1126 end = pieceIndex(t.info.NumPieces())
1131 // Returns true if all iterations complete without breaking. Returns the read
1132 // regions for all readers. The reader regions should not be merged as some
1133 // callers depend on this method to enumerate readers.
1134 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1135 for r := range t.readers {
1137 if p.begin >= p.end {
1140 if !f(p.begin, p.end) {
1147 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1148 prio, ok := t._pendingPieces.GetPriority(piece)
1150 return PiecePriorityNone
1155 ret := piecePriority(-prio)
1156 if ret == PiecePriorityNone {
1162 func (t *Torrent) pendRequest(req Request) {
1163 ci := chunkIndex(req.ChunkSpec, t.chunkSize)
1164 t.pieces[req.Index].pendChunkIndex(ci)
1167 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1169 t.cl.event.Broadcast()
1170 if t.pieceComplete(piece) {
1171 t.onPieceCompleted(piece)
1173 t.onIncompletePiece(piece)
1175 t.updatePiecePriority(piece)
1178 func (t *Torrent) numReceivedConns() (ret int) {
1179 for c := range t.conns {
1180 if c.Discovery == PeerSourceIncoming {
1187 func (t *Torrent) maxHalfOpen() int {
1188 // Note that if we somehow exceed the maximum established conns, we want
1189 // the negative value to have an effect.
1190 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1191 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1192 // We want to allow some experimentation with new peers, and to try to
1193 // upset an oversupply of received connections.
1194 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1197 func (t *Torrent) openNewConns() (initiated int) {
1198 defer t.updateWantPeersEvent()
1199 for t.peers.Len() != 0 {
1203 if len(t.halfOpen) >= t.maxHalfOpen() {
1206 if len(t.cl.dialers) == 0 {
1209 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1212 p := t.peers.PopMax()
1219 func (t *Torrent) getConnPieceInclination() []int {
1220 _ret := t.connPieceInclinationPool.Get()
1222 pieceInclinationsNew.Add(1)
1223 return rand.Perm(int(t.numPieces()))
1225 pieceInclinationsReused.Add(1)
1226 return *_ret.(*[]int)
1229 func (t *Torrent) putPieceInclination(pi []int) {
1230 t.connPieceInclinationPool.Put(&pi)
1231 pieceInclinationsPut.Add(1)
1234 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1236 uncached := t.pieceCompleteUncached(piece)
1237 cached := p.completion()
1238 changed := cached != uncached
1239 complete := uncached.Complete
1240 p.storageCompletionOk = uncached.Ok
1241 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
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)
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.setInfoBytes(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.Len() != 0
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.info.TotalLength() - t.bytesLeft()
1353 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1356 return t.setInfoBytes(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 if t.numActivePeers() == 0 {
1378 t.assertNoPendingRequests()
1383 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1387 p.newPeerPieces().IterTyped(func(i int) bool {
1388 p.t.decPieceAvailability(i)
1393 func (t *Torrent) numActivePeers() (num int) {
1394 t.iterPeers(func(*Peer) {
1400 func (t *Torrent) assertNoPendingRequests() {
1401 if len(t.pendingRequests) != 0 {
1402 panic(t.pendingRequests)
1404 //if len(t.lastRequested) != 0 {
1405 // panic(t.lastRequested)
1409 func (t *Torrent) dropConnection(c *PeerConn) {
1410 t.cl.event.Broadcast()
1412 if t.deletePeerConn(c) {
1417 func (t *Torrent) wantPeers() bool {
1418 if t.closed.IsSet() {
1421 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1424 return t.needData() || t.seeding()
1427 func (t *Torrent) updateWantPeersEvent() {
1429 t.wantPeersEvent.Set()
1431 t.wantPeersEvent.Clear()
1435 // Returns whether the client should make effort to seed the torrent.
1436 func (t *Torrent) seeding() bool {
1438 if t.closed.IsSet() {
1441 if t.dataUploadDisallowed {
1444 if cl.config.NoUpload {
1447 if !cl.config.Seed {
1450 if cl.config.DisableAggressiveUpload && t.needData() {
1456 func (t *Torrent) onWebRtcConn(
1457 c datachannel.ReadWriteCloser,
1458 dcc webtorrent.DataChannelContext,
1461 pc, err := t.cl.initiateProtocolHandshakes(
1462 context.Background(),
1463 webrtcNetConn{c, dcc},
1467 webrtcNetAddr{dcc.Remote},
1469 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1472 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1475 if dcc.LocalOffered {
1476 pc.Discovery = PeerSourceTracker
1478 pc.Discovery = PeerSourceIncoming
1482 err = t.cl.runHandshookConn(pc, t)
1484 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1488 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1489 err := t.cl.runHandshookConn(pc, t)
1490 if err != nil || logAll {
1491 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1495 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1496 t.logRunHandshookConn(pc, false, log.Debug)
1499 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1500 wtc, release := t.cl.websocketTrackers.Get(u.String())
1502 <-t.closed.LockedChan(t.cl.locker())
1505 wst := websocketTrackerStatus{u, wtc}
1507 err := wtc.Announce(tracker.Started, t.infoHash)
1509 t.logger.WithDefaultLevel(log.Warning).Printf(
1510 "error in initial announce to %q: %v",
1519 func (t *Torrent) startScrapingTracker(_url string) {
1523 u, err := url.Parse(_url)
1525 // URLs with a leading '*' appear to be a uTorrent convention to
1526 // disable trackers.
1528 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1532 if u.Scheme == "udp" {
1534 t.startScrapingTracker(u.String())
1536 t.startScrapingTracker(u.String())
1539 if _, ok := t.trackerAnnouncers[_url]; ok {
1542 sl := func() torrentTrackerAnnouncer {
1545 if t.cl.config.DisableWebtorrent {
1548 return t.startWebsocketAnnouncer(*u)
1550 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1554 if t.cl.config.DisableIPv6 {
1558 newAnnouncer := &trackerScraper{
1562 go newAnnouncer.Run()
1568 if t.trackerAnnouncers == nil {
1569 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1571 t.trackerAnnouncers[_url] = sl
1574 // Adds and starts tracker scrapers for tracker URLs that aren't already
1576 func (t *Torrent) startMissingTrackerScrapers() {
1577 if t.cl.config.DisableTrackers {
1580 t.startScrapingTracker(t.metainfo.Announce)
1581 for _, tier := range t.metainfo.AnnounceList {
1582 for _, url := range tier {
1583 t.startScrapingTracker(url)
1588 // Returns an AnnounceRequest with fields filled out to defaults and current
1590 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1591 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1592 // dependent on the network in use.
1593 return tracker.AnnounceRequest{
1595 NumWant: func() int32 {
1596 if t.wantPeers() && len(t.cl.dialers) > 0 {
1602 Port: uint16(t.cl.incomingPeerPort()),
1603 PeerId: t.cl.peerID,
1604 InfoHash: t.infoHash,
1605 Key: t.cl.announceKey(),
1607 // The following are vaguely described in BEP 3.
1609 Left: t.bytesLeftAnnounce(),
1610 Uploaded: t.stats.BytesWrittenData.Int64(),
1611 // There's no mention of wasted or unwanted download in the BEP.
1612 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1616 // Adds peers revealed in an announce until the announce ends, or we have
1618 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1620 for v := range pvs {
1623 for _, cp := range v.Peers {
1625 // Can't do anything with this.
1628 if t.addPeer(PeerInfo{
1629 Addr: ipPortAddr{cp.IP, cp.Port},
1630 Source: PeerSourceDhtGetPeers,
1637 //log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1642 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1643 // announce ends. stop will force the announce to end.
1644 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1645 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1649 _done := make(chan struct{})
1653 t.consumeDhtAnnouncePeers(ps.Peers())
1659 func (t *Torrent) announceToDht(s DhtServer) error {
1660 _, stop, err := t.AnnounceToDht(s)
1665 case <-t.closed.LockedChan(t.cl.locker()):
1666 case <-time.After(5 * time.Minute):
1672 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1678 if t.closed.IsSet() {
1684 // TODO: Determine if there's a listener on the port we're announcing.
1685 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1696 err := t.announceToDht(s)
1698 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1704 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1705 for _, p := range peers {
1713 // The returned TorrentStats may require alignment in memory. See
1714 // https://github.com/anacrolix/torrent/issues/383.
1715 func (t *Torrent) Stats() TorrentStats {
1717 defer t.cl.rUnlock()
1718 return t.statsLocked()
1721 func (t *Torrent) statsLocked() (ret TorrentStats) {
1722 ret.ActivePeers = len(t.conns)
1723 ret.HalfOpenPeers = len(t.halfOpen)
1724 ret.PendingPeers = t.peers.Len()
1725 ret.TotalPeers = t.numTotalPeers()
1726 ret.ConnectedSeeders = 0
1727 for c := range t.conns {
1728 if all, ok := c.peerHasAllPieces(); all && ok {
1729 ret.ConnectedSeeders++
1732 ret.ConnStats = t.stats.Copy()
1736 // The total number of peers in the torrent.
1737 func (t *Torrent) numTotalPeers() int {
1738 peers := make(map[string]struct{})
1739 for conn := range t.conns {
1740 ra := conn.conn.RemoteAddr()
1742 // It's been closed and doesn't support RemoteAddr.
1745 peers[ra.String()] = struct{}{}
1747 for addr := range t.halfOpen {
1748 peers[addr] = struct{}{}
1750 t.peers.Each(func(peer PeerInfo) {
1751 peers[peer.Addr.String()] = struct{}{}
1756 // Reconcile bytes transferred before connection was associated with a
1758 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1759 if c._stats != (ConnStats{
1760 // Handshakes should only increment these fields:
1761 BytesWritten: c._stats.BytesWritten,
1762 BytesRead: c._stats.BytesRead,
1766 c.postHandshakeStats(func(cs *ConnStats) {
1767 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1768 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1770 c.reconciledHandshakeStats = true
1773 // Returns true if the connection is added.
1774 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1777 torrent.Add("added connections", 1)
1780 if t.closed.IsSet() {
1781 return errors.New("torrent closed")
1783 for c0 := range t.conns {
1784 if c.PeerID != c0.PeerID {
1787 if !t.cl.config.DropDuplicatePeerIds {
1790 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1792 t.deletePeerConn(c0)
1794 return errors.New("existing connection preferred")
1797 if len(t.conns) >= t.maxEstablishedConns {
1798 c := t.worstBadConn()
1800 return errors.New("don't want conns")
1805 if len(t.conns) >= t.maxEstablishedConns {
1808 t.conns[c] = struct{}{}
1809 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1810 t.pex.Add(c) // as no further extended handshake expected
1815 func (t *Torrent) wantConns() bool {
1816 if !t.networkingEnabled {
1819 if t.closed.IsSet() {
1822 if !t.seeding() && !t.needData() {
1825 if len(t.conns) < t.maxEstablishedConns {
1828 return t.worstBadConn() != nil
1831 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1834 oldMax = t.maxEstablishedConns
1835 t.maxEstablishedConns = max
1836 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1837 return worseConn(&l.Peer, &r.Peer)
1839 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1840 t.dropConnection(wcs.Pop().(*PeerConn))
1846 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1847 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1850 t.cl.event.Broadcast()
1851 if t.closed.IsSet() {
1855 // Don't score the first time a piece is hashed, it could be an initial check.
1856 if p.storageCompletionOk {
1858 pieceHashedCorrect.Add(1)
1861 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1862 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1863 pieceHashedNotCorrect.Add(1)
1868 t.publishPieceChange(piece)
1871 t.publishPieceChange(piece)
1875 if len(p.dirtiers) != 0 {
1876 // Don't increment stats above connection-level for every involved connection.
1877 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1879 for c := range p.dirtiers {
1880 c._stats.incrementPiecesDirtiedGood()
1882 t.clearPieceTouchers(piece)
1884 err := p.Storage().MarkComplete()
1886 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1890 if t.closed.IsSet() {
1893 t.pendAllChunkSpecs(piece)
1895 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1896 // Peers contributed to all the data for this piece hash failure, and the failure was
1897 // not due to errors in the storage (such as data being dropped in a cache).
1899 // Increment Torrent and above stats, and then specific connections.
1900 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1901 for c := range p.dirtiers {
1902 // Y u do dis peer?!
1903 c.stats().incrementPiecesDirtiedBad()
1906 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1907 for c := range p.dirtiers {
1909 bannableTouchers = append(bannableTouchers, c)
1912 t.clearPieceTouchers(piece)
1913 slices.Sort(bannableTouchers, connLessTrusted)
1915 if t.cl.config.Debug {
1917 "bannable conns by trust for piece %d: %v",
1919 func() (ret []connectionTrust) {
1920 for _, c := range bannableTouchers {
1921 ret = append(ret, c.trust())
1928 if len(bannableTouchers) >= 1 {
1929 c := bannableTouchers[0]
1930 t.cl.banPeerIP(c.remoteIp())
1934 t.onIncompletePiece(piece)
1935 p.Storage().MarkNotComplete()
1937 t.updatePieceCompletion(piece)
1940 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1941 // TODO: Make faster
1942 for cn := range t.conns {
1947 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1948 t.pendAllChunkSpecs(piece)
1949 t.cancelRequestsForPiece(piece)
1950 for conn := range t.conns {
1952 t.maybeDropMutuallyCompletePeer(&conn.Peer)
1956 // Called when a piece is found to be not complete.
1957 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1958 if t.pieceAllDirty(piece) {
1959 t.pendAllChunkSpecs(piece)
1961 if !t.wantPieceIndex(piece) {
1962 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1965 // We could drop any connections that we told we have a piece that we
1966 // don't here. But there's a test failure, and it seems clients don't care
1967 // if you request pieces that you already claim to have. Pruning bad
1968 // connections might just remove any connections that aren't treating us
1969 // favourably anyway.
1971 // for c := range t.conns {
1972 // if c.sentHave(piece) {
1976 t.iterPeers(func(conn *Peer) {
1977 if conn.peerHasPiece(piece) {
1978 conn.updateRequests()
1983 func (t *Torrent) tryCreateMorePieceHashers() {
1984 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1988 func (t *Torrent) tryCreatePieceHasher() bool {
1989 if t.storage == nil {
1992 pi, ok := t.getPieceToHash()
1997 t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
1999 t.publishPieceChange(pi)
2000 t.updatePiecePriority(pi)
2001 t.storageLock.RLock()
2002 t.activePieceHashes++
2003 go t.pieceHasher(pi)
2007 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2008 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2009 if t.piece(i).hashing {
2019 func (t *Torrent) pieceHasher(index pieceIndex) {
2021 sum, copyErr := t.hashPiece(index)
2022 correct := sum == *p.hash
2026 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2028 t.storageLock.RUnlock()
2032 t.updatePiecePriority(index)
2033 t.pieceHashed(index, correct, copyErr)
2034 t.publishPieceChange(index)
2035 t.activePieceHashes--
2036 t.tryCreateMorePieceHashers()
2039 // Return the connections that touched a piece, and clear the entries while doing it.
2040 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2042 for c := range p.dirtiers {
2043 delete(c.peerTouchedPieces, pi)
2044 delete(p.dirtiers, c)
2048 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2049 t.iterPeers(func(p *Peer) {
2050 ret = append(ret, p)
2055 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2056 piece := t.piece(pieceIndex)
2057 if piece.queuedForHash() {
2060 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2061 t.publishPieceChange(pieceIndex)
2062 t.updatePiecePriority(pieceIndex)
2063 t.tryCreateMorePieceHashers()
2066 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2067 // before the Info is available.
2068 func (t *Torrent) VerifyData() {
2069 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2070 t.Piece(i).VerifyData()
2074 // Start the process of connecting to the given peer for the given torrent if appropriate.
2075 func (t *Torrent) initiateConn(peer PeerInfo) {
2076 if peer.Id == t.cl.peerID {
2079 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2083 if t.addrActive(addr.String()) {
2087 t.halfOpen[addr.String()] = peer
2088 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2091 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2092 // quickly make one Client visible to the Torrent of another Client.
2093 func (t *Torrent) AddClientPeer(cl *Client) int {
2094 return t.AddPeers(func() (ps []PeerInfo) {
2095 for _, la := range cl.ListenAddrs() {
2096 ps = append(ps, PeerInfo{
2105 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2107 func (t *Torrent) allStats(f func(*ConnStats)) {
2112 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2113 return t.pieces[i].hashing
2116 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2117 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2120 func (t *Torrent) dialTimeout() time.Duration {
2121 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2124 func (t *Torrent) piece(i int) *Piece {
2128 func (t *Torrent) onWriteChunkErr(err error) {
2129 if t.userOnWriteChunkErr != nil {
2130 go t.userOnWriteChunkErr(err)
2133 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2134 t.disallowDataDownloadLocked()
2137 func (t *Torrent) DisallowDataDownload() {
2140 t.disallowDataDownloadLocked()
2143 func (t *Torrent) disallowDataDownloadLocked() {
2144 t.dataDownloadDisallowed = true
2145 t.iterPeers(func(c *Peer) {
2151 func (t *Torrent) AllowDataDownload() {
2154 t.dataDownloadDisallowed = false
2156 t.iterPeers(func(c *Peer) {
2161 // Enables uploading data, if it was disabled.
2162 func (t *Torrent) AllowDataUpload() {
2165 t.dataUploadDisallowed = false
2166 for c := range t.conns {
2171 // Disables uploading data, if it was enabled.
2172 func (t *Torrent) DisallowDataUpload() {
2175 t.dataUploadDisallowed = true
2176 for c := range t.conns {
2181 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2182 // or if nil, a critical message is logged, and data download is disabled.
2183 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2186 t.userOnWriteChunkErr = f
2189 func (t *Torrent) iterPeers(f func(p *Peer)) {
2190 for pc := range t.conns {
2193 for _, ws := range t.webSeeds {
2198 func (t *Torrent) callbacks() *Callbacks {
2199 return &t.cl.config.Callbacks
2202 var WebseedHttpClient = &http.Client{
2203 Transport: &http.Transport{
2204 MaxConnsPerHost: 10,
2208 func (t *Torrent) addWebSeed(url string) {
2209 if t.cl.config.DisableWebseeds {
2212 if _, ok := t.webSeeds[url]; ok {
2215 const maxRequests = 10
2221 reconciledHandshakeStats: true,
2222 // TODO: Raise this limit, and instead limit concurrent fetches.
2223 PeerMaxRequests: 32,
2224 RemoteAddr: remoteAddrFromUrl(url),
2225 callbacks: t.callbacks(),
2227 client: webseed.Client{
2228 // Consider a MaxConnsPerHost in the transport for this, possibly in a global Client.
2229 HttpClient: WebseedHttpClient,
2232 activeRequests: make(map[Request]webseed.Request, maxRequests),
2234 ws.requesterCond.L = t.cl.locker()
2235 for range iter.N(maxRequests) {
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
2247 ws.peer.onPeerHasAllPieces()
2250 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2251 t.iterPeers(func(p1 *Peer) {