21 "github.com/RoaringBitmap/roaring"
22 "github.com/anacrolix/dht/v2"
23 "github.com/anacrolix/log"
24 "github.com/anacrolix/missinggo/iter"
25 "github.com/anacrolix/missinggo/perf"
26 "github.com/anacrolix/missinggo/pubsub"
27 "github.com/anacrolix/missinggo/slices"
28 "github.com/anacrolix/missinggo/v2"
29 "github.com/anacrolix/missinggo/v2/bitmap"
30 "github.com/anacrolix/missinggo/v2/prioritybitmap"
31 "github.com/anacrolix/multiless"
32 "github.com/davecgh/go-spew/spew"
33 "github.com/pion/datachannel"
35 "github.com/anacrolix/torrent/bencode"
36 "github.com/anacrolix/torrent/common"
37 "github.com/anacrolix/torrent/metainfo"
38 pp "github.com/anacrolix/torrent/peer_protocol"
39 "github.com/anacrolix/torrent/segments"
40 "github.com/anacrolix/torrent/storage"
41 "github.com/anacrolix/torrent/tracker"
42 "github.com/anacrolix/torrent/webseed"
43 "github.com/anacrolix/torrent/webtorrent"
46 // Maintains state of torrent within a Client. Many methods should not be called before the info is
47 // available, see .Info and .GotInfo.
49 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
50 // alignment. See #262.
55 networkingEnabled bool
56 dataDownloadDisallowed bool
57 dataUploadDisallowed bool
58 userOnWriteChunkErr func(error)
60 closed missinggo.Event
61 infoHash metainfo.Hash
63 // Values are the piece indices that changed.
64 pieceStateChanges *pubsub.PubSub
65 // The size of chunks to request from peers over the wire. This is
66 // normally 16KiB by convention these days.
69 // Total length of the torrent in bytes. Stored because it's not O(1) to
70 // get this from the info dict.
73 // The storage to open when the info dict becomes available.
74 storageOpener *storage.Client
75 // Storage for torrent data.
76 storage *storage.Torrent
77 // Read-locked for using storage, and write-locked for Closing.
78 storageLock sync.RWMutex
80 // TODO: Only announce stuff is used?
81 metainfo metainfo.MetaInfo
83 // The info dict. nil if we don't have it (yet).
85 fileIndex segments.Index
88 webSeeds map[string]*Peer
90 // Active peer connections, running message stream loops. TODO: Make this
91 // open (not-closed) connections only.
92 conns map[*PeerConn]struct{}
93 maxEstablishedConns int
94 // Set of addrs to which we're attempting to connect. Connections are
95 // half-open until all handshakes are completed.
96 halfOpen map[string]PeerInfo
98 // Reserve of peers to connect to. A peer can be both here and in the
99 // active connections if were told about the peer after connecting with
100 // them. That encourages us to reconnect to peers that are well known in
102 peers prioritizedPeers
103 // Whether we want to know to know more peers.
104 wantPeersEvent missinggo.Event
105 // An announcer for each tracker URL.
106 trackerAnnouncers map[string]torrentTrackerAnnouncer
107 // How many times we've initiated a DHT announce. TODO: Move into stats.
110 // Name used if the info name isn't available. Should be cleared when the
111 // Info does become available.
115 // The bencoded bytes of the info dict. This is actively manipulated if
116 // the info bytes aren't initially available, and we try to fetch them
119 // Each element corresponds to the 16KiB metadata pieces. If true, we have
120 // received that piece.
121 metadataCompletedChunks []bool
122 metadataChanged sync.Cond
124 // Set when .Info is obtained.
125 gotMetainfo missinggo.Event
127 readers map[*reader]struct{}
128 _readerNowPieces bitmap.Bitmap
129 _readerReadaheadPieces bitmap.Bitmap
131 // A cache of pieces we need to get. Calculated from various piece and
132 // file priorities and completion states elsewhere.
133 _pendingPieces prioritybitmap.PriorityBitmap
134 // A cache of completed piece indices.
135 _completedPieces roaring.Bitmap
136 // Pieces that need to be hashed.
137 piecesQueuedForHash bitmap.Bitmap
138 activePieceHashes int
140 // A pool of piece priorities []int for assignment to new connections.
141 // These "inclinations" are used to give connections preference for
143 connPieceInclinationPool sync.Pool
145 // Count of each request across active connections.
146 pendingRequests map[Request]int
151 func (t *Torrent) pieceAvailabilityFromPeers(i pieceIndex) (count int) {
152 t.iterPeers(func(peer *Peer) {
153 if peer.peerHasPiece(i) {
160 func (t *Torrent) decPieceAvailability(i pieceIndex) {
165 if p.availability <= 0 {
166 panic(p.availability)
171 func (t *Torrent) incPieceAvailability(i pieceIndex) {
172 // If we don't the info, this should be reconciled when we do.
179 func (t *Torrent) numConns() int {
183 func (t *Torrent) numReaders() int {
184 return len(t.readers)
187 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
188 return t._readerNowPieces
191 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
192 return t._readerReadaheadPieces
195 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
196 return !t.wantPieceIndex(i)
199 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
200 return &t._pendingPieces
203 func (t *Torrent) tickleReaders() {
204 t.cl.event.Broadcast()
207 // Returns a channel that is closed when the Torrent is closed.
208 func (t *Torrent) Closed() <-chan struct{} {
209 return t.closed.LockedChan(t.cl.locker())
212 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
213 // pending, and half-open peers.
214 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
215 // Add pending peers to the list
216 t.peers.Each(func(peer PeerInfo) {
217 ks = append(ks, peer)
220 // Add half-open peers to the list
221 for _, peer := range t.halfOpen {
222 ks = append(ks, peer)
225 // Add active peers to the list
226 for conn := range t.conns {
228 ks = append(ks, PeerInfo{
230 Addr: conn.RemoteAddr,
231 Source: conn.Discovery,
232 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
233 // > But if we're not connected to them with an encrypted connection, I couldn't say
234 // > what's appropriate. We can carry forward the SupportsEncryption value as we
235 // > received it from trackers/DHT/PEX, or just use the encryption state for the
236 // > connection. It's probably easiest to do the latter for now.
237 // https://github.com/anacrolix/torrent/pull/188
238 SupportsEncryption: conn.headerEncrypted,
245 func (t *Torrent) setChunkSize(size pp.Integer) {
247 t.chunkPool = &sync.Pool{
248 New: func() interface{} {
249 b := make([]byte, size)
255 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
256 return t._completedPieces.Contains(bitmap.BitIndex(piece))
259 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
260 return t.pieces[piece].Storage().Completion()
263 // There's a connection to that address already.
264 func (t *Torrent) addrActive(addr string) bool {
265 if _, ok := t.halfOpen[addr]; ok {
268 for c := range t.conns {
270 if ra.String() == addr {
277 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
278 ret = make([]*PeerConn, 0, len(t.conns))
279 for c := range t.conns {
280 if !c.closed.IsSet() {
287 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
289 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
290 if t.closed.IsSet() {
293 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
294 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
295 torrent.Add("peers not added because of bad addr", 1)
296 // cl.logger.Printf("peers not added because of bad addr: %v", p)
300 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
301 torrent.Add("peers replaced", 1)
302 if !replaced.equal(p) {
303 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
310 for t.peers.Len() > cl.config.TorrentPeersHighWater {
311 _, ok := t.peers.DeleteMin()
313 torrent.Add("excess reserve peers discarded", 1)
319 func (t *Torrent) invalidateMetadata() {
320 for i := range t.metadataCompletedChunks {
321 t.metadataCompletedChunks[i] = false
328 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
332 if index >= len(t.metadataCompletedChunks) {
333 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
336 copy(t.metadataBytes[(1<<14)*index:], data)
337 t.metadataCompletedChunks[index] = true
340 func (t *Torrent) metadataPieceCount() int {
341 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
344 func (t *Torrent) haveMetadataPiece(piece int) bool {
346 return (1<<14)*piece < len(t.metadataBytes)
348 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
352 func (t *Torrent) metadataSize() int {
353 return len(t.metadataBytes)
356 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
357 for i := 0; i < len(info.Pieces); i += sha1.Size {
358 ret = append(ret, info.Pieces[i:i+sha1.Size])
363 func (t *Torrent) makePieces() {
364 hashes := infoPieceHashes(t.info)
365 t.pieces = make([]Piece, len(hashes))
366 for i, hash := range hashes {
367 piece := &t.pieces[i]
369 piece.index = pieceIndex(i)
370 piece.noPendingWrites.L = &piece.pendingWritesMutex
371 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
373 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
374 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
375 piece.files = files[beginFile:endFile]
379 // Returns the index of the first file containing the piece. files must be
380 // ordered by offset.
381 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
382 for i, f := range files {
383 if f.offset+f.length > pieceOffset {
390 // Returns the index after the last file containing the piece. files must be
391 // ordered by offset.
392 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
393 for i, f := range files {
394 if f.offset+f.length >= pieceEndOffset {
401 func (t *Torrent) cacheLength() {
403 for _, f := range t.info.UpvertedFiles() {
409 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
411 func (t *Torrent) setInfo(info *metainfo.Info) error {
412 if err := validateInfo(info); err != nil {
413 return fmt.Errorf("bad info: %s", err)
415 if t.storageOpener != nil {
417 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
419 return fmt.Errorf("error opening torrent storage: %s", err)
425 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
426 t.displayName = "" // Save a few bytes lol.
433 // This seems to be all the follow-up tasks after info is set, that can't fail.
434 func (t *Torrent) onSetInfo() {
435 t.iterPeers(func(p *Peer) {
438 for i := range t.pieces {
440 // Need to add availability before updating piece completion, as that may result in conns
442 if p.availability != 0 {
443 panic(p.availability)
445 p.availability = int64(t.pieceAvailabilityFromPeers(i))
446 t.updatePieceCompletion(pieceIndex(i))
447 if !p.storageCompletionOk {
448 // t.logger.Printf("piece %s completion unknown, queueing check", p)
449 t.queuePieceCheck(pieceIndex(i))
452 t.cl.event.Broadcast()
454 t.updateWantPeersEvent()
455 t.pendingRequests = make(map[Request]int)
456 t.tryCreateMorePieceHashers()
459 // Called when metadata for a torrent becomes available.
460 func (t *Torrent) setInfoBytes(b []byte) error {
461 if metainfo.HashBytes(b) != t.infoHash {
462 return errors.New("info bytes have wrong hash")
464 var info metainfo.Info
465 if err := bencode.Unmarshal(b, &info); err != nil {
466 return fmt.Errorf("error unmarshalling info bytes: %s", err)
469 t.metadataCompletedChunks = nil
473 if err := t.setInfo(&info); err != nil {
480 func (t *Torrent) haveAllMetadataPieces() bool {
484 if t.metadataCompletedChunks == nil {
487 for _, have := range t.metadataCompletedChunks {
495 // TODO: Propagate errors to disconnect peer.
496 func (t *Torrent) setMetadataSize(bytes int) (err error) {
498 // We already know the correct metadata size.
501 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
502 return errors.New("bad size")
504 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
507 t.metadataBytes = make([]byte, bytes)
508 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
509 t.metadataChanged.Broadcast()
510 for c := range t.conns {
511 c.requestPendingMetadata()
516 // The current working name for the torrent. Either the name in the info dict,
517 // or a display name given such as by the dn value in a magnet link, or "".
518 func (t *Torrent) name() string {
520 defer t.nameMu.RUnlock()
524 if t.displayName != "" {
527 return "infohash:" + t.infoHash.HexString()
530 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
531 p := &t.pieces[index]
532 ret.Priority = t.piecePriority(index)
533 ret.Completion = p.completion()
534 ret.QueuedForHash = p.queuedForHash()
535 ret.Hashing = p.hashing
536 ret.Checking = ret.QueuedForHash || ret.Hashing
537 ret.Marking = p.marking
538 if !ret.Complete && t.piecePartiallyDownloaded(index) {
544 func (t *Torrent) metadataPieceSize(piece int) int {
545 return metadataPieceSize(len(t.metadataBytes), piece)
548 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
551 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
552 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
554 TotalSize: len(t.metadataBytes),
560 type pieceAvailabilityRun struct {
565 func (me pieceAvailabilityRun) String() string {
566 return fmt.Sprintf("%v(%v)", me.count, me.availability)
569 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
570 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
571 ret = append(ret, pieceAvailabilityRun{availability: el.(int64), count: int(count)})
573 for i := range t.pieces {
574 rle.Append(t.pieces[i].availability, 1)
580 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
581 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
582 ret = append(ret, PieceStateRun{
583 PieceState: el.(PieceState),
587 for index := range t.pieces {
588 rle.Append(t.pieceState(pieceIndex(index)), 1)
594 // Produces a small string representing a PieceStateRun.
595 func (psr PieceStateRun) String() (ret string) {
596 ret = fmt.Sprintf("%d", psr.Length)
597 ret += func() string {
598 switch psr.Priority {
599 case PiecePriorityNext:
601 case PiecePriorityNormal:
603 case PiecePriorityReadahead:
605 case PiecePriorityNow:
607 case PiecePriorityHigh:
616 if psr.QueuedForHash {
634 func (t *Torrent) writeStatus(w io.Writer) {
635 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
636 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
638 fmt.Fprintf(w, "Metadata have: ")
639 for _, h := range t.metadataCompletedChunks {
640 fmt.Fprintf(w, "%c", func() rune {
650 fmt.Fprintf(w, "Piece length: %s\n",
653 return fmt.Sprintf("%v (%v chunks)",
655 float64(t.usualPieceSize())/float64(t.chunkSize))
662 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
663 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
664 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
665 for _, run := range t.pieceAvailabilityRuns() {
666 ret = append(ret, run.String())
671 fmt.Fprintf(w, "Reader Pieces:")
672 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
673 fmt.Fprintf(w, " %d:%d", begin, end)
678 fmt.Fprintf(w, "Enabled trackers:\n")
680 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
681 fmt.Fprintf(tw, " URL\tExtra\n")
682 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
685 var luns, runs url.URL = *lu, *ru
688 var ml missinggo.MultiLess
689 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
690 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
692 }).([]torrentTrackerAnnouncer) {
693 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
698 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
700 spew.NewDefaultConfig()
701 spew.Fdump(w, t.statsLocked())
703 peers := t.peersAsSlice()
704 sort.Slice(peers, func(_i, _j int) bool {
707 if less, ok := multiless.New().EagerSameLess(
708 i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
712 return worseConn(i, j)
714 for i, c := range peers {
715 fmt.Fprintf(w, "%2d. ", i+1)
720 func (t *Torrent) haveInfo() bool {
724 // Returns a run-time generated MetaInfo that includes the info bytes and
725 // announce-list as currently known to the client.
726 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
727 return metainfo.MetaInfo{
728 CreationDate: time.Now().Unix(),
729 Comment: "dynamic metainfo from client",
730 CreatedBy: "go.torrent",
731 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
732 InfoBytes: func() []byte {
734 return t.metadataBytes
739 UrlList: func() []string {
740 ret := make([]string, 0, len(t.webSeeds))
741 for url := range t.webSeeds {
742 ret = append(ret, url)
749 func (t *Torrent) BytesMissing() int64 {
752 return t.bytesMissingLocked()
755 func (t *Torrent) bytesMissingLocked() int64 {
759 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
760 roaring.Flip(b, 0, end).Iterate(cb)
763 func (t *Torrent) bytesLeft() (left int64) {
764 iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
765 p := t.piece(pieceIndex(x))
766 left += int64(p.length() - p.numDirtyBytes())
772 // Bytes left to give in tracker announces.
773 func (t *Torrent) bytesLeftAnnounce() int64 {
781 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
782 if t.pieceComplete(piece) {
785 if t.pieceAllDirty(piece) {
788 return t.pieces[piece].hasDirtyChunks()
791 func (t *Torrent) usualPieceSize() int {
792 return int(t.info.PieceLength)
795 func (t *Torrent) numPieces() pieceIndex {
796 return pieceIndex(t.info.NumPieces())
799 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
800 return pieceIndex(t._completedPieces.GetCardinality())
803 func (t *Torrent) close() (err error) {
806 if t.storage != nil {
809 defer t.storageLock.Unlock()
810 if f := t.storage.Close; f != nil {
815 t.iterPeers(func(p *Peer) {
819 t.cl.event.Broadcast()
820 t.pieceStateChanges.Close()
821 t.updateWantPeersEvent()
825 func (t *Torrent) requestOffset(r Request) int64 {
826 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
829 // Return the request that would include the given offset into the torrent data. Returns !ok if
830 // there is no such request.
831 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
832 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
835 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
836 defer perf.ScopeTimerErr(&err)()
837 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
838 if err == nil && n != len(data) {
839 err = io.ErrShortWrite
844 func (t *Torrent) bitfield() (bf []bool) {
845 bf = make([]bool, t.numPieces())
846 t._completedPieces.Iterate(func(piece uint32) (again bool) {
853 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
854 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
857 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
858 t.pieces[pieceIndex]._dirtyChunks.Clear()
861 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
862 if t.info.PieceLength == 0 {
863 // There will be no variance amongst pieces. Only pain.
866 if piece == t.numPieces()-1 {
867 ret := pp.Integer(*t.length % t.info.PieceLength)
872 return pp.Integer(t.info.PieceLength)
875 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
877 p.waitNoPendingWrites()
878 storagePiece := t.pieces[piece].Storage()
880 //Does the backend want to do its own hashing?
881 if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
882 var sum metainfo.Hash
883 //log.Printf("A piece decided to self-hash: %d", piece)
884 sum, err = i.SelfHash()
885 missinggo.CopyExact(&ret, sum)
889 hash := pieceHash.New()
890 const logPieceContents = false
891 if logPieceContents {
892 var examineBuf bytes.Buffer
893 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
894 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
896 _, err = storagePiece.WriteTo(hash)
898 missinggo.CopyExact(&ret, hash.Sum(nil))
902 func (t *Torrent) haveAnyPieces() bool {
903 return t._completedPieces.GetCardinality() != 0
906 func (t *Torrent) haveAllPieces() bool {
910 return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
913 func (t *Torrent) havePiece(index pieceIndex) bool {
914 return t.haveInfo() && t.pieceComplete(index)
917 func (t *Torrent) maybeDropMutuallyCompletePeer(
918 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's okay?
921 if !t.cl.config.DropMutuallyCompletePeers {
924 if !t.haveAllPieces() {
927 if all, known := p.peerHasAllPieces(); !(known && all) {
933 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
937 func (t *Torrent) haveChunk(r Request) (ret bool) {
939 // log.Println("have chunk", r, ret)
944 if t.pieceComplete(pieceIndex(r.Index)) {
947 p := &t.pieces[r.Index]
948 return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
951 func chunkIndex(cs ChunkSpec, chunkSize pp.Integer) int {
952 return int(cs.Begin / chunkSize)
955 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
956 // TODO: Are these overly conservative, should we be guarding this here?
961 if index < 0 || index >= t.numPieces() {
965 p := &t.pieces[index]
966 if p.queuedForHash() {
972 if t.pieceComplete(index) {
975 if t._pendingPieces.Contains(int(index)) {
978 // t.logger.Printf("piece %d not pending", index)
979 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
980 return index < begin || index >= end
984 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
985 // connection is one that usually sends us unwanted pieces, or has been in worser half of the
986 // established connections for more than a minute.
987 func (t *Torrent) worstBadConn() *PeerConn {
988 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
991 c := heap.Pop(&wcs).(*PeerConn)
992 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
995 // If the connection is in the worst half of the established
996 // connection quota and is older than a minute.
997 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
998 // Give connections 1 minute to prove themselves.
999 if time.Since(c.completedHandshake) > time.Minute {
1007 type PieceStateChange struct {
1012 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1013 t.cl._mu.Defer(func() {
1014 cur := t.pieceState(piece)
1015 p := &t.pieces[piece]
1016 if cur != p.publicPieceState {
1017 p.publicPieceState = cur
1018 t.pieceStateChanges.Publish(PieceStateChange{
1026 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1027 if t.pieceComplete(piece) {
1030 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
1033 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1034 return t.pieces[piece]._dirtyChunks.Len() == bitmap.BitRange(t.pieceNumChunks(piece))
1037 func (t *Torrent) readersChanged() {
1038 t.updateReaderPieces()
1039 t.updateAllPiecePriorities()
1042 func (t *Torrent) updateReaderPieces() {
1043 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1046 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1050 t.updateReaderPieces()
1051 // Order the ranges, high and low.
1053 if l.begin > h.begin {
1056 if l.end < h.begin {
1057 // Two distinct ranges.
1058 t.updatePiecePriorities(l.begin, l.end)
1059 t.updatePiecePriorities(h.begin, h.end)
1066 t.updatePiecePriorities(l.begin, end)
1070 func (t *Torrent) maybeNewConns() {
1071 // Tickle the accept routine.
1072 t.cl.event.Broadcast()
1076 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
1077 // t.logger.Printf("piece %d priority changed", piece)
1078 t.iterPeers(func(c *Peer) {
1079 if c.updatePiecePriority(piece) {
1080 // log.Print("conn piece priority changed")
1085 t.publishPieceChange(piece)
1088 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
1089 p := &t.pieces[piece]
1090 newPrio := p.uncachedPriority()
1091 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1092 if newPrio == PiecePriorityNone {
1093 if !t._pendingPieces.Remove(int(piece)) {
1097 if !t._pendingPieces.Set(int(piece), newPrio.BitmapPriority()) {
1101 t.piecePriorityChanged(piece)
1104 func (t *Torrent) updateAllPiecePriorities() {
1105 t.updatePiecePriorities(0, t.numPieces())
1108 // Update all piece priorities in one hit. This function should have the same
1109 // output as updatePiecePriority, but across all pieces.
1110 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
1111 for i := begin; i < end; i++ {
1112 t.updatePiecePriority(i)
1116 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1117 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1118 if off >= *t.length {
1128 begin = pieceIndex(off / t.info.PieceLength)
1129 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1130 if end > pieceIndex(t.info.NumPieces()) {
1131 end = pieceIndex(t.info.NumPieces())
1136 // Returns true if all iterations complete without breaking. Returns the read
1137 // regions for all readers. The reader regions should not be merged as some
1138 // callers depend on this method to enumerate readers.
1139 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1140 for r := range t.readers {
1142 if p.begin >= p.end {
1145 if !f(p.begin, p.end) {
1152 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1153 prio, ok := t._pendingPieces.GetPriority(piece)
1155 return PiecePriorityNone
1160 ret := piecePriority(-prio)
1161 if ret == PiecePriorityNone {
1167 func (t *Torrent) pendRequest(req Request) {
1168 ci := chunkIndex(req.ChunkSpec, t.chunkSize)
1169 t.pieces[req.Index].pendChunkIndex(ci)
1172 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1174 t.cl.event.Broadcast()
1175 if t.pieceComplete(piece) {
1176 t.onPieceCompleted(piece)
1178 t.onIncompletePiece(piece)
1180 t.updatePiecePriority(piece)
1183 func (t *Torrent) numReceivedConns() (ret int) {
1184 for c := range t.conns {
1185 if c.Discovery == PeerSourceIncoming {
1192 func (t *Torrent) maxHalfOpen() int {
1193 // Note that if we somehow exceed the maximum established conns, we want
1194 // the negative value to have an effect.
1195 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1196 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1197 // We want to allow some experimentation with new peers, and to try to
1198 // upset an oversupply of received connections.
1199 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1202 func (t *Torrent) openNewConns() (initiated int) {
1203 defer t.updateWantPeersEvent()
1204 for t.peers.Len() != 0 {
1208 if len(t.halfOpen) >= t.maxHalfOpen() {
1211 if len(t.cl.dialers) == 0 {
1214 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1217 p := t.peers.PopMax()
1224 func (t *Torrent) getConnPieceInclination() []int {
1225 _ret := t.connPieceInclinationPool.Get()
1227 pieceInclinationsNew.Add(1)
1228 return rand.Perm(int(t.numPieces()))
1230 pieceInclinationsReused.Add(1)
1231 return *_ret.(*[]int)
1234 func (t *Torrent) putPieceInclination(pi []int) {
1235 t.connPieceInclinationPool.Put(&pi)
1236 pieceInclinationsPut.Add(1)
1239 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1241 uncached := t.pieceCompleteUncached(piece)
1242 cached := p.completion()
1243 changed := cached != uncached
1244 complete := uncached.Complete
1245 p.storageCompletionOk = uncached.Ok
1248 t._completedPieces.Add(x)
1250 t._completedPieces.Remove(x)
1252 if complete && len(p.dirtiers) != 0 {
1253 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1256 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1257 t.pieceCompletionChanged(piece)
1262 // Non-blocking read. Client lock is not required.
1263 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1265 p := &t.pieces[off/t.info.PieceLength]
1266 p.waitNoPendingWrites()
1268 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1279 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1280 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1281 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1282 func (t *Torrent) maybeCompleteMetadata() error {
1287 if !t.haveAllMetadataPieces() {
1288 // Don't have enough metadata pieces.
1291 err := t.setInfoBytes(t.metadataBytes)
1293 t.invalidateMetadata()
1294 return fmt.Errorf("error setting info bytes: %s", err)
1296 if t.cl.config.Debug {
1297 t.logger.Printf("%s: got metadata from peers", t)
1302 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1303 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1305 now.Add(bitmap.BitIndex(begin))
1306 readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1313 func (t *Torrent) needData() bool {
1314 if t.closed.IsSet() {
1320 return t._pendingPieces.Len() != 0
1323 func appendMissingStrings(old, new []string) (ret []string) {
1326 for _, n := range new {
1327 for _, o := range old {
1332 ret = append(ret, n)
1337 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1339 for minNumTiers > len(ret) {
1340 ret = append(ret, nil)
1345 func (t *Torrent) addTrackers(announceList [][]string) {
1346 fullAnnounceList := &t.metainfo.AnnounceList
1347 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1348 for tierIndex, trackerURLs := range announceList {
1349 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1351 t.startMissingTrackerScrapers()
1352 t.updateWantPeersEvent()
1355 // Don't call this before the info is available.
1356 func (t *Torrent) bytesCompleted() int64 {
1360 return *t.length - t.bytesLeft()
1363 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1366 return t.setInfoBytes(b)
1369 // Returns true if connection is removed from torrent.Conns.
1370 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1371 if !c.closed.IsSet() {
1372 panic("connection is not closed")
1373 // There are behaviours prevented by the closed state that will fail
1374 // if the connection has been deleted.
1378 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1379 // the drop event against the PexConnState instead.
1381 if !t.cl.config.DisablePEX {
1385 torrent.Add("deleted connections", 1)
1386 c.deleteAllRequests()
1387 if t.numActivePeers() == 0 {
1388 t.assertNoPendingRequests()
1393 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1397 p.newPeerPieces().IterTyped(func(i int) bool {
1398 p.t.decPieceAvailability(i)
1403 func (t *Torrent) numActivePeers() (num int) {
1404 t.iterPeers(func(*Peer) {
1410 func (t *Torrent) assertNoPendingRequests() {
1411 if len(t.pendingRequests) != 0 {
1412 panic(t.pendingRequests)
1414 //if len(t.lastRequested) != 0 {
1415 // panic(t.lastRequested)
1419 func (t *Torrent) dropConnection(c *PeerConn) {
1420 t.cl.event.Broadcast()
1422 if t.deletePeerConn(c) {
1427 func (t *Torrent) wantPeers() bool {
1428 if t.closed.IsSet() {
1431 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1434 return t.needData() || t.seeding()
1437 func (t *Torrent) updateWantPeersEvent() {
1439 t.wantPeersEvent.Set()
1441 t.wantPeersEvent.Clear()
1445 // Returns whether the client should make effort to seed the torrent.
1446 func (t *Torrent) seeding() bool {
1448 if t.closed.IsSet() {
1451 if t.dataUploadDisallowed {
1454 if cl.config.NoUpload {
1457 if !cl.config.Seed {
1460 if cl.config.DisableAggressiveUpload && t.needData() {
1466 func (t *Torrent) onWebRtcConn(
1467 c datachannel.ReadWriteCloser,
1468 dcc webtorrent.DataChannelContext,
1471 pc, err := t.cl.initiateProtocolHandshakes(
1472 context.Background(),
1473 webrtcNetConn{c, dcc},
1477 webrtcNetAddr{dcc.Remote},
1479 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1482 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1485 if dcc.LocalOffered {
1486 pc.Discovery = PeerSourceTracker
1488 pc.Discovery = PeerSourceIncoming
1492 err = t.cl.runHandshookConn(pc, t)
1494 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1498 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1499 err := t.cl.runHandshookConn(pc, t)
1500 if err != nil || logAll {
1501 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1505 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1506 t.logRunHandshookConn(pc, false, log.Debug)
1509 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1510 wtc, release := t.cl.websocketTrackers.Get(u.String())
1512 <-t.closed.LockedChan(t.cl.locker())
1515 wst := websocketTrackerStatus{u, wtc}
1517 err := wtc.Announce(tracker.Started, t.infoHash)
1519 t.logger.WithDefaultLevel(log.Warning).Printf(
1520 "error in initial announce to %q: %v",
1529 func (t *Torrent) startScrapingTracker(_url string) {
1533 u, err := url.Parse(_url)
1535 // URLs with a leading '*' appear to be a uTorrent convention to
1536 // disable trackers.
1538 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1542 if u.Scheme == "udp" {
1544 t.startScrapingTracker(u.String())
1546 t.startScrapingTracker(u.String())
1549 if _, ok := t.trackerAnnouncers[_url]; ok {
1552 sl := func() torrentTrackerAnnouncer {
1555 if t.cl.config.DisableWebtorrent {
1558 return t.startWebsocketAnnouncer(*u)
1560 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1564 if t.cl.config.DisableIPv6 {
1568 newAnnouncer := &trackerScraper{
1572 go newAnnouncer.Run()
1578 if t.trackerAnnouncers == nil {
1579 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1581 t.trackerAnnouncers[_url] = sl
1584 // Adds and starts tracker scrapers for tracker URLs that aren't already
1586 func (t *Torrent) startMissingTrackerScrapers() {
1587 if t.cl.config.DisableTrackers {
1590 t.startScrapingTracker(t.metainfo.Announce)
1591 for _, tier := range t.metainfo.AnnounceList {
1592 for _, url := range tier {
1593 t.startScrapingTracker(url)
1598 // Returns an AnnounceRequest with fields filled out to defaults and current
1600 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1601 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1602 // dependent on the network in use.
1603 return tracker.AnnounceRequest{
1605 NumWant: func() int32 {
1606 if t.wantPeers() && len(t.cl.dialers) > 0 {
1612 Port: uint16(t.cl.incomingPeerPort()),
1613 PeerId: t.cl.peerID,
1614 InfoHash: t.infoHash,
1615 Key: t.cl.announceKey(),
1617 // The following are vaguely described in BEP 3.
1619 Left: t.bytesLeftAnnounce(),
1620 Uploaded: t.stats.BytesWrittenData.Int64(),
1621 // There's no mention of wasted or unwanted download in the BEP.
1622 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1626 // Adds peers revealed in an announce until the announce ends, or we have
1628 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1630 for v := range pvs {
1633 for _, cp := range v.Peers {
1635 // Can't do anything with this.
1638 if t.addPeer(PeerInfo{
1639 Addr: ipPortAddr{cp.IP, cp.Port},
1640 Source: PeerSourceDhtGetPeers,
1647 // log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1652 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1653 // announce ends. stop will force the announce to end.
1654 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1655 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1659 _done := make(chan struct{})
1663 t.consumeDhtAnnouncePeers(ps.Peers())
1669 func (t *Torrent) announceToDht(s DhtServer) error {
1670 _, stop, err := t.AnnounceToDht(s)
1675 case <-t.closed.LockedChan(t.cl.locker()):
1676 case <-time.After(5 * time.Minute):
1682 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1688 if t.closed.IsSet() {
1694 // TODO: Determine if there's a listener on the port we're announcing.
1695 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1706 err := t.announceToDht(s)
1708 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1714 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1715 for _, p := range peers {
1723 // The returned TorrentStats may require alignment in memory. See
1724 // https://github.com/anacrolix/torrent/issues/383.
1725 func (t *Torrent) Stats() TorrentStats {
1727 defer t.cl.rUnlock()
1728 return t.statsLocked()
1731 func (t *Torrent) statsLocked() (ret TorrentStats) {
1732 ret.ActivePeers = len(t.conns)
1733 ret.HalfOpenPeers = len(t.halfOpen)
1734 ret.PendingPeers = t.peers.Len()
1735 ret.TotalPeers = t.numTotalPeers()
1736 ret.ConnectedSeeders = 0
1737 for c := range t.conns {
1738 if all, ok := c.peerHasAllPieces(); all && ok {
1739 ret.ConnectedSeeders++
1742 ret.ConnStats = t.stats.Copy()
1746 // The total number of peers in the torrent.
1747 func (t *Torrent) numTotalPeers() int {
1748 peers := make(map[string]struct{})
1749 for conn := range t.conns {
1750 ra := conn.conn.RemoteAddr()
1752 // It's been closed and doesn't support RemoteAddr.
1755 peers[ra.String()] = struct{}{}
1757 for addr := range t.halfOpen {
1758 peers[addr] = struct{}{}
1760 t.peers.Each(func(peer PeerInfo) {
1761 peers[peer.Addr.String()] = struct{}{}
1766 // Reconcile bytes transferred before connection was associated with a
1768 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1769 if c._stats != (ConnStats{
1770 // Handshakes should only increment these fields:
1771 BytesWritten: c._stats.BytesWritten,
1772 BytesRead: c._stats.BytesRead,
1776 c.postHandshakeStats(func(cs *ConnStats) {
1777 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1778 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1780 c.reconciledHandshakeStats = true
1783 // Returns true if the connection is added.
1784 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1787 torrent.Add("added connections", 1)
1790 if t.closed.IsSet() {
1791 return errors.New("torrent closed")
1793 for c0 := range t.conns {
1794 if c.PeerID != c0.PeerID {
1797 if !t.cl.config.DropDuplicatePeerIds {
1800 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1802 t.deletePeerConn(c0)
1804 return errors.New("existing connection preferred")
1807 if len(t.conns) >= t.maxEstablishedConns {
1808 c := t.worstBadConn()
1810 return errors.New("don't want conns")
1815 if len(t.conns) >= t.maxEstablishedConns {
1818 t.conns[c] = struct{}{}
1819 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1820 t.pex.Add(c) // as no further extended handshake expected
1825 func (t *Torrent) wantConns() bool {
1826 if !t.networkingEnabled {
1829 if t.closed.IsSet() {
1832 if !t.seeding() && !t.needData() {
1835 if len(t.conns) < t.maxEstablishedConns {
1838 return t.worstBadConn() != nil
1841 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1844 oldMax = t.maxEstablishedConns
1845 t.maxEstablishedConns = max
1846 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1847 return worseConn(&l.Peer, &r.Peer)
1849 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1850 t.dropConnection(wcs.Pop().(*PeerConn))
1856 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1857 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1860 t.cl.event.Broadcast()
1861 if t.closed.IsSet() {
1865 // Don't score the first time a piece is hashed, it could be an initial check.
1866 if p.storageCompletionOk {
1868 pieceHashedCorrect.Add(1)
1871 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1872 ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1873 pieceHashedNotCorrect.Add(1)
1878 t.publishPieceChange(piece)
1881 t.publishPieceChange(piece)
1885 if len(p.dirtiers) != 0 {
1886 // Don't increment stats above connection-level for every involved connection.
1887 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1889 for c := range p.dirtiers {
1890 c._stats.incrementPiecesDirtiedGood()
1892 t.clearPieceTouchers(piece)
1894 err := p.Storage().MarkComplete()
1896 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1900 if t.closed.IsSet() {
1903 t.pendAllChunkSpecs(piece)
1905 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1906 // Peers contributed to all the data for this piece hash failure, and the failure was
1907 // not due to errors in the storage (such as data being dropped in a cache).
1909 // Increment Torrent and above stats, and then specific connections.
1910 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1911 for c := range p.dirtiers {
1912 // Y u do dis peer?!
1913 c.stats().incrementPiecesDirtiedBad()
1916 bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1917 for c := range p.dirtiers {
1919 bannableTouchers = append(bannableTouchers, c)
1922 t.clearPieceTouchers(piece)
1923 slices.Sort(bannableTouchers, connLessTrusted)
1925 if t.cl.config.Debug {
1927 "bannable conns by trust for piece %d: %v",
1929 func() (ret []connectionTrust) {
1930 for _, c := range bannableTouchers {
1931 ret = append(ret, c.trust())
1938 if len(bannableTouchers) >= 1 {
1939 c := bannableTouchers[0]
1940 t.cl.banPeerIP(c.remoteIp())
1944 t.onIncompletePiece(piece)
1945 p.Storage().MarkNotComplete()
1947 t.updatePieceCompletion(piece)
1950 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1951 // TODO: Make faster
1952 for cn := range t.conns {
1957 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1958 t.pendAllChunkSpecs(piece)
1959 t.cancelRequestsForPiece(piece)
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()
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)
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.updatePiecePriority(index)
2043 t.pieceHashed(index, correct, copyErr)
2044 t.publishPieceChange(index)
2045 t.activePieceHashes--
2046 t.tryCreateMorePieceHashers()
2049 // Return the connections that touched a piece, and clear the entries while doing it.
2050 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2052 for c := range p.dirtiers {
2053 delete(c.peerTouchedPieces, pi)
2054 delete(p.dirtiers, c)
2058 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2059 t.iterPeers(func(p *Peer) {
2060 ret = append(ret, p)
2065 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2066 piece := t.piece(pieceIndex)
2067 if piece.queuedForHash() {
2070 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2071 t.publishPieceChange(pieceIndex)
2072 t.updatePiecePriority(pieceIndex)
2073 t.tryCreateMorePieceHashers()
2076 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2077 // before the Info is available.
2078 func (t *Torrent) VerifyData() {
2079 for i := pieceIndex(0); i < t.NumPieces(); i++ {
2080 t.Piece(i).VerifyData()
2084 // Start the process of connecting to the given peer for the given torrent if appropriate.
2085 func (t *Torrent) initiateConn(peer PeerInfo) {
2086 if peer.Id == t.cl.peerID {
2089 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2093 if t.addrActive(addr.String()) {
2097 t.halfOpen[addr.String()] = peer
2098 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2101 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2102 // quickly make one Client visible to the Torrent of another Client.
2103 func (t *Torrent) AddClientPeer(cl *Client) int {
2104 return t.AddPeers(func() (ps []PeerInfo) {
2105 for _, la := range cl.ListenAddrs() {
2106 ps = append(ps, PeerInfo{
2115 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2117 func (t *Torrent) allStats(f func(*ConnStats)) {
2122 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2123 return t.pieces[i].hashing
2126 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2127 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2130 func (t *Torrent) dialTimeout() time.Duration {
2131 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2134 func (t *Torrent) piece(i int) *Piece {
2138 func (t *Torrent) onWriteChunkErr(err error) {
2139 if t.userOnWriteChunkErr != nil {
2140 go t.userOnWriteChunkErr(err)
2143 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2144 t.disallowDataDownloadLocked()
2147 func (t *Torrent) DisallowDataDownload() {
2150 t.disallowDataDownloadLocked()
2153 func (t *Torrent) disallowDataDownloadLocked() {
2154 t.dataDownloadDisallowed = true
2155 t.iterPeers(func(c *Peer) {
2161 func (t *Torrent) AllowDataDownload() {
2164 t.dataDownloadDisallowed = false
2166 t.iterPeers(func(c *Peer) {
2171 // Enables uploading data, if it was disabled.
2172 func (t *Torrent) AllowDataUpload() {
2175 t.dataUploadDisallowed = false
2176 for c := range t.conns {
2181 // Disables uploading data, if it was enabled.
2182 func (t *Torrent) DisallowDataUpload() {
2185 t.dataUploadDisallowed = true
2186 for c := range t.conns {
2191 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2192 // or if nil, a critical message is logged, and data download is disabled.
2193 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2196 t.userOnWriteChunkErr = f
2199 func (t *Torrent) iterPeers(f func(p *Peer)) {
2200 for pc := range t.conns {
2203 for _, ws := range t.webSeeds {
2208 func (t *Torrent) callbacks() *Callbacks {
2209 return &t.cl.config.Callbacks
2212 var WebseedHttpClient = &http.Client{
2213 Transport: &http.Transport{
2214 MaxConnsPerHost: 10,
2218 func (t *Torrent) addWebSeed(url string) {
2219 if t.cl.config.DisableWebseeds {
2222 if _, ok := t.webSeeds[url]; ok {
2225 const maxRequests = 10
2231 reconciledHandshakeStats: true,
2232 // TODO: Raise this limit, and instead limit concurrent fetches.
2233 PeerMaxRequests: 32,
2234 RemoteAddr: remoteAddrFromUrl(url),
2235 callbacks: t.callbacks(),
2237 client: webseed.Client{
2238 // Consider a MaxConnsPerHost in the transport for this, possibly in a global Client.
2239 HttpClient: WebseedHttpClient,
2242 activeRequests: make(map[Request]webseed.Request, maxRequests),
2244 ws.requesterCond.L = t.cl.locker()
2245 for range iter.N(maxRequests) {
2248 for _, f := range t.callbacks().NewPeer {
2251 ws.peer.logger = t.logger.WithContextValue(&ws)
2252 ws.peer.peerImpl = &ws
2254 ws.onGotInfo(t.info)
2256 t.webSeeds[url] = &ws.peer
2257 ws.peer.onPeerHasAllPieces()
2260 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2261 t.iterPeers(func(p1 *Peer) {