20 "github.com/anacrolix/torrent/common"
21 "github.com/anacrolix/torrent/segments"
22 "github.com/anacrolix/torrent/webseed"
23 "github.com/davecgh/go-spew/spew"
24 "github.com/pion/datachannel"
26 "github.com/anacrolix/dht/v2"
27 "github.com/anacrolix/log"
28 "github.com/anacrolix/missinggo"
29 "github.com/anacrolix/missinggo/perf"
30 "github.com/anacrolix/missinggo/pubsub"
31 "github.com/anacrolix/missinggo/slices"
32 "github.com/anacrolix/missinggo/v2/bitmap"
33 "github.com/anacrolix/missinggo/v2/prioritybitmap"
35 "github.com/anacrolix/torrent/bencode"
36 "github.com/anacrolix/torrent/metainfo"
37 pp "github.com/anacrolix/torrent/peer_protocol"
38 "github.com/anacrolix/torrent/storage"
39 "github.com/anacrolix/torrent/tracker"
40 "github.com/anacrolix/torrent/webtorrent"
43 // Maintains state of torrent within a Client. Many methods should not be called before the info is
44 // available, see .Info and .GotInfo.
46 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
47 // alignment. See #262.
52 networkingEnabled bool
53 dataDownloadDisallowed bool
54 dataUploadDisallowed bool
55 userOnWriteChunkErr func(error)
57 // Determines what chunks to request from peers.
58 requestStrategy requestStrategy
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
99 // Reserve of peers to connect to. A peer can be both here and in the
100 // active connections if were told about the peer after connecting with
101 // them. That encourages us to reconnect to peers that are well known in
103 peers prioritizedPeers
104 // Whether we want to know to know more peers.
105 wantPeersEvent missinggo.Event
106 // An announcer for each tracker URL.
107 trackerAnnouncers map[string]torrentTrackerAnnouncer
108 // How many times we've initiated a DHT announce. TODO: Move into stats.
111 // Name used if the info name isn't available. Should be cleared when the
112 // Info does become available.
116 // The bencoded bytes of the info dict. This is actively manipulated if
117 // the info bytes aren't initially available, and we try to fetch them
120 // Each element corresponds to the 16KiB metadata pieces. If true, we have
121 // received that piece.
122 metadataCompletedChunks []bool
123 metadataChanged sync.Cond
125 // Set when .Info is obtained.
126 gotMetainfo missinggo.Event
128 readers map[*reader]struct{}
129 _readerNowPieces bitmap.Bitmap
130 _readerReadaheadPieces bitmap.Bitmap
132 // A cache of pieces we need to get. Calculated from various piece and
133 // file priorities and completion states elsewhere.
134 _pendingPieces prioritybitmap.PriorityBitmap
135 // A cache of completed piece indices.
136 _completedPieces bitmap.Bitmap
137 // Pieces that need to be hashed.
138 piecesQueuedForHash bitmap.Bitmap
139 activePieceHashes int
141 // A pool of piece priorities []int for assignment to new connections.
142 // These "inclinations" are used to give connections preference for
144 connPieceInclinationPool sync.Pool
146 // Count of each request across active connections.
147 pendingRequests map[request]int
152 func (t *Torrent) numConns() int {
156 func (t *Torrent) numReaders() int {
157 return len(t.readers)
160 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
161 return t._readerNowPieces
164 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
165 return t._readerReadaheadPieces
168 func (t *Torrent) ignorePieces() bitmap.Bitmap {
169 ret := t._completedPieces.Copy()
170 ret.Union(t.piecesQueuedForHash)
171 for i := 0; i < t.numPieces(); i++ {
172 if t.piece(i).hashing {
179 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
180 return &t._pendingPieces
183 func (t *Torrent) tickleReaders() {
184 t.cl.event.Broadcast()
187 // Returns a channel that is closed when the Torrent is closed.
188 func (t *Torrent) Closed() <-chan struct{} {
189 return t.closed.LockedChan(t.cl.locker())
192 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
193 // pending, and half-open peers.
194 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
195 // Add pending peers to the list
196 t.peers.Each(func(peer PeerInfo) {
197 ks = append(ks, peer)
200 // Add half-open peers to the list
201 for _, peer := range t.halfOpen {
202 ks = append(ks, peer)
205 // Add active peers to the list
206 for conn := range t.conns {
208 ks = append(ks, PeerInfo{
210 Addr: conn.RemoteAddr,
211 Source: conn.Discovery,
212 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
213 // > But if we're not connected to them with an encrypted connection, I couldn't say
214 // > what's appropriate. We can carry forward the SupportsEncryption value as we
215 // > received it from trackers/DHT/PEX, or just use the encryption state for the
216 // > connection. It's probably easiest to do the latter for now.
217 // https://github.com/anacrolix/torrent/pull/188
218 SupportsEncryption: conn.headerEncrypted,
225 func (t *Torrent) setChunkSize(size pp.Integer) {
227 t.chunkPool = &sync.Pool{
228 New: func() interface{} {
229 b := make([]byte, size)
235 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
236 return t._completedPieces.Get(bitmap.BitIndex(piece))
239 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
240 return t.pieces[piece].Storage().Completion()
243 // There's a connection to that address already.
244 func (t *Torrent) addrActive(addr string) bool {
245 if _, ok := t.halfOpen[addr]; ok {
248 for c := range t.conns {
250 if ra.String() == addr {
257 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
258 ret = make([]*PeerConn, 0, len(t.conns))
259 for c := range t.conns {
260 if !c.closed.IsSet() {
267 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
269 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
270 if t.closed.IsSet() {
273 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
274 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
275 torrent.Add("peers not added because of bad addr", 1)
276 // cl.logger.Printf("peers not added because of bad addr: %v", p)
280 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
281 torrent.Add("peers replaced", 1)
282 if !replaced.equal(p) {
283 t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
290 for t.peers.Len() > cl.config.TorrentPeersHighWater {
291 _, ok := t.peers.DeleteMin()
293 torrent.Add("excess reserve peers discarded", 1)
299 func (t *Torrent) invalidateMetadata() {
300 for i := range t.metadataCompletedChunks {
301 t.metadataCompletedChunks[i] = false
308 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
312 if index >= len(t.metadataCompletedChunks) {
313 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
316 copy(t.metadataBytes[(1<<14)*index:], data)
317 t.metadataCompletedChunks[index] = true
320 func (t *Torrent) metadataPieceCount() int {
321 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
324 func (t *Torrent) haveMetadataPiece(piece int) bool {
326 return (1<<14)*piece < len(t.metadataBytes)
328 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
332 func (t *Torrent) metadataSize() int {
333 return len(t.metadataBytes)
336 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
337 for i := 0; i < len(info.Pieces); i += sha1.Size {
338 ret = append(ret, info.Pieces[i:i+sha1.Size])
343 func (t *Torrent) makePieces() {
344 hashes := infoPieceHashes(t.info)
345 t.pieces = make([]Piece, len(hashes))
346 for i, hash := range hashes {
347 piece := &t.pieces[i]
349 piece.index = pieceIndex(i)
350 piece.noPendingWrites.L = &piece.pendingWritesMutex
351 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
353 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
354 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
355 piece.files = files[beginFile:endFile]
359 // Returns the index of the first file containing the piece. files must be
360 // ordered by offset.
361 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
362 for i, f := range files {
363 if f.offset+f.length > pieceOffset {
370 // Returns the index after the last file containing the piece. files must be
371 // ordered by offset.
372 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
373 for i, f := range files {
374 if f.offset+f.length >= pieceEndOffset {
381 func (t *Torrent) cacheLength() {
383 for _, f := range t.info.UpvertedFiles() {
389 func (t *Torrent) setInfo(info *metainfo.Info) error {
390 if err := validateInfo(info); err != nil {
391 return fmt.Errorf("bad info: %s", err)
393 if t.storageOpener != nil {
395 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
397 return fmt.Errorf("error opening torrent storage: %s", err)
403 t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
404 t.displayName = "" // Save a few bytes lol.
411 // This seems to be all the follow-up tasks after info is set, that can't fail.
412 func (t *Torrent) onSetInfo() {
413 t.iterPeers(func(p *peer) {
416 for i := range t.pieces {
417 t.updatePieceCompletion(pieceIndex(i))
419 if !p.storageCompletionOk {
420 // t.logger.Printf("piece %s completion unknown, queueing check", p)
421 t.queuePieceCheck(pieceIndex(i))
424 t.cl.event.Broadcast()
426 t.updateWantPeersEvent()
427 t.pendingRequests = make(map[request]int)
428 t.tryCreateMorePieceHashers()
431 // Called when metadata for a torrent becomes available.
432 func (t *Torrent) setInfoBytes(b []byte) error {
433 if metainfo.HashBytes(b) != t.infoHash {
434 return errors.New("info bytes have wrong hash")
436 var info metainfo.Info
437 if err := bencode.Unmarshal(b, &info); err != nil {
438 return fmt.Errorf("error unmarshalling info bytes: %s", err)
441 t.metadataCompletedChunks = nil
445 if err := t.setInfo(&info); err != nil {
452 func (t *Torrent) haveAllMetadataPieces() bool {
456 if t.metadataCompletedChunks == nil {
459 for _, have := range t.metadataCompletedChunks {
467 // TODO: Propagate errors to disconnect peer.
468 func (t *Torrent) setMetadataSize(bytes int) (err error) {
470 // We already know the correct metadata size.
473 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
474 return errors.New("bad size")
476 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
479 t.metadataBytes = make([]byte, bytes)
480 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
481 t.metadataChanged.Broadcast()
482 for c := range t.conns {
483 c.requestPendingMetadata()
488 // The current working name for the torrent. Either the name in the info dict,
489 // or a display name given such as by the dn value in a magnet link, or "".
490 func (t *Torrent) name() string {
492 defer t.nameMu.RUnlock()
499 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
500 p := &t.pieces[index]
501 ret.Priority = t.piecePriority(index)
502 ret.Completion = p.completion()
503 ret.QueuedForHash = p.queuedForHash()
504 ret.Hashing = p.hashing
505 ret.Checking = ret.QueuedForHash || ret.Hashing
506 ret.Marking = p.marking
507 if !ret.Complete && t.piecePartiallyDownloaded(index) {
513 func (t *Torrent) metadataPieceSize(piece int) int {
514 return metadataPieceSize(len(t.metadataBytes), piece)
517 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
523 d["total_size"] = len(t.metadataBytes)
525 p := bencode.MustMarshal(d)
528 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
529 ExtendedPayload: append(p, data...),
533 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
534 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
535 ret = append(ret, PieceStateRun{
536 PieceState: el.(PieceState),
540 for index := range t.pieces {
541 rle.Append(t.pieceState(pieceIndex(index)), 1)
547 // Produces a small string representing a PieceStateRun.
548 func (psr PieceStateRun) String() (ret string) {
549 ret = fmt.Sprintf("%d", psr.Length)
550 ret += func() string {
551 switch psr.Priority {
552 case PiecePriorityNext:
554 case PiecePriorityNormal:
556 case PiecePriorityReadahead:
558 case PiecePriorityNow:
560 case PiecePriorityHigh:
569 if psr.QueuedForHash {
587 func (t *Torrent) writeStatus(w io.Writer) {
588 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
589 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
591 fmt.Fprintf(w, "Metadata have: ")
592 for _, h := range t.metadataCompletedChunks {
593 fmt.Fprintf(w, "%c", func() rune {
603 fmt.Fprintf(w, "Piece length: %s\n", func() string {
605 return fmt.Sprint(t.usualPieceSize())
611 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
612 fmt.Fprintf(w, "Piece States: %s", t.pieceStateRuns())
615 fmt.Fprintf(w, "Reader Pieces:")
616 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
617 fmt.Fprintf(w, " %d:%d", begin, end)
622 fmt.Fprintf(w, "Enabled trackers:\n")
624 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
625 fmt.Fprintf(tw, " URL\tExtra\n")
626 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
629 var luns, runs url.URL = *lu, *ru
632 var ml missinggo.MultiLess
633 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
634 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
636 }).([]torrentTrackerAnnouncer) {
637 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
642 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
644 spew.NewDefaultConfig()
645 spew.Fdump(w, t.statsLocked())
647 peers := t.peersAsSlice()
648 sort.Slice(peers, func(i, j int) bool {
649 return worseConn(peers[i], peers[j])
651 for i, c := range peers {
652 fmt.Fprintf(w, "%2d. ", i+1)
657 func (t *Torrent) haveInfo() bool {
661 // Returns a run-time generated MetaInfo that includes the info bytes and
662 // announce-list as currently known to the client.
663 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
664 return metainfo.MetaInfo{
665 CreationDate: time.Now().Unix(),
666 Comment: "dynamic metainfo from client",
667 CreatedBy: "go.torrent",
668 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
669 InfoBytes: func() []byte {
671 return t.metadataBytes
679 func (t *Torrent) BytesMissing() int64 {
682 return t.bytesMissingLocked()
685 func (t *Torrent) bytesMissingLocked() int64 {
689 func (t *Torrent) bytesLeft() (left int64) {
690 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
691 p := &t.pieces[piece]
692 left += int64(p.length() - p.numDirtyBytes())
698 // Bytes left to give in tracker announces.
699 func (t *Torrent) bytesLeftAnnounce() int64 {
707 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
708 if t.pieceComplete(piece) {
711 if t.pieceAllDirty(piece) {
714 return t.pieces[piece].hasDirtyChunks()
717 func (t *Torrent) usualPieceSize() int {
718 return int(t.info.PieceLength)
721 func (t *Torrent) numPieces() pieceIndex {
722 return pieceIndex(t.info.NumPieces())
725 func (t *Torrent) numPiecesCompleted() (num int) {
726 return t._completedPieces.Len()
729 func (t *Torrent) close() (err error) {
732 if t.storage != nil {
735 t.storageLock.Unlock()
737 for conn := range t.conns {
741 t.cl.event.Broadcast()
742 t.pieceStateChanges.Close()
743 t.updateWantPeersEvent()
747 func (t *Torrent) requestOffset(r request) int64 {
748 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
751 // Return the request that would include the given offset into the torrent data. Returns !ok if
752 // there is no such request.
753 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
754 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
757 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
758 defer perf.ScopeTimerErr(&err)()
759 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
760 if err == nil && n != len(data) {
761 err = io.ErrShortWrite
766 func (t *Torrent) bitfield() (bf []bool) {
767 bf = make([]bool, t.numPieces())
768 t._completedPieces.IterTyped(func(piece int) (again bool) {
775 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
776 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
779 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
780 t.pieces[pieceIndex]._dirtyChunks.Clear()
783 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
784 if t.info.PieceLength == 0 {
785 // There will be no variance amongst pieces. Only pain.
788 if piece == t.numPieces()-1 {
789 ret := pp.Integer(*t.length % t.info.PieceLength)
794 return pp.Integer(t.info.PieceLength)
797 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
798 hash := pieceHash.New()
800 p.waitNoPendingWrites()
801 storagePiece := t.pieces[piece].Storage()
802 const logPieceContents = false
803 if logPieceContents {
804 var examineBuf bytes.Buffer
805 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
806 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
808 _, err = storagePiece.WriteTo(hash)
810 missinggo.CopyExact(&ret, hash.Sum(nil))
814 func (t *Torrent) haveAnyPieces() bool {
815 return t._completedPieces.Len() != 0
818 func (t *Torrent) haveAllPieces() bool {
822 return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
825 func (t *Torrent) havePiece(index pieceIndex) bool {
826 return t.haveInfo() && t.pieceComplete(index)
829 func (t *Torrent) maybeDropMutuallyCompletePeer(
830 // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's okay?
833 if !t.cl.config.DropMutuallyCompletePeers {
836 if !t.haveAllPieces() {
839 if all, known := p.peerHasAllPieces(); !(known && all) {
845 t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
849 func (t *Torrent) haveChunk(r request) (ret bool) {
851 // log.Println("have chunk", r, ret)
856 if t.pieceComplete(pieceIndex(r.Index)) {
859 p := &t.pieces[r.Index]
860 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
863 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
864 return int(cs.Begin / chunkSize)
867 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
871 if index < 0 || index >= t.numPieces() {
874 p := &t.pieces[index]
875 if p.queuedForHash() {
881 if t.pieceComplete(index) {
884 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
887 // t.logger.Printf("piece %d not pending", index)
888 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
889 return index < begin || index >= end
893 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
894 // connection is one that usually sends us unwanted pieces, or has been in worser half of the
895 // established connections for more than a minute.
896 func (t *Torrent) worstBadConn() *PeerConn {
897 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
900 c := heap.Pop(&wcs).(*PeerConn)
901 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
904 // If the connection is in the worst half of the established
905 // connection quota and is older than a minute.
906 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
907 // Give connections 1 minute to prove themselves.
908 if time.Since(c.completedHandshake) > time.Minute {
916 type PieceStateChange struct {
921 func (t *Torrent) publishPieceChange(piece pieceIndex) {
922 t.cl._mu.Defer(func() {
923 cur := t.pieceState(piece)
924 p := &t.pieces[piece]
925 if cur != p.publicPieceState {
926 p.publicPieceState = cur
927 t.pieceStateChanges.Publish(PieceStateChange{
935 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
936 if t.pieceComplete(piece) {
939 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
942 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
943 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
946 func (t *Torrent) readersChanged() {
947 t.updateReaderPieces()
948 t.updateAllPiecePriorities()
951 func (t *Torrent) updateReaderPieces() {
952 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
955 func (t *Torrent) readerPosChanged(from, to pieceRange) {
959 t.updateReaderPieces()
960 // Order the ranges, high and low.
962 if l.begin > h.begin {
966 // Two distinct ranges.
967 t.updatePiecePriorities(l.begin, l.end)
968 t.updatePiecePriorities(h.begin, h.end)
975 t.updatePiecePriorities(l.begin, end)
979 func (t *Torrent) maybeNewConns() {
980 // Tickle the accept routine.
981 t.cl.event.Broadcast()
985 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
986 // t.logger.Printf("piece %d priority changed", piece)
987 t.iterPeers(func(c *peer) {
988 if c.updatePiecePriority(piece) {
989 // log.Print("conn piece priority changed")
994 t.publishPieceChange(piece)
997 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
998 p := &t.pieces[piece]
999 newPrio := p.uncachedPriority()
1000 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1001 if newPrio == PiecePriorityNone {
1002 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
1006 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
1010 t.piecePriorityChanged(piece)
1013 func (t *Torrent) updateAllPiecePriorities() {
1014 t.updatePiecePriorities(0, t.numPieces())
1017 // Update all piece priorities in one hit. This function should have the same
1018 // output as updatePiecePriority, but across all pieces.
1019 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
1020 for i := begin; i < end; i++ {
1021 t.updatePiecePriority(i)
1025 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1026 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1027 if off >= *t.length {
1037 begin = pieceIndex(off / t.info.PieceLength)
1038 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1039 if end > pieceIndex(t.info.NumPieces()) {
1040 end = pieceIndex(t.info.NumPieces())
1045 // Returns true if all iterations complete without breaking. Returns the read
1046 // regions for all readers. The reader regions should not be merged as some
1047 // callers depend on this method to enumerate readers.
1048 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1049 for r := range t.readers {
1051 if p.begin >= p.end {
1054 if !f(p.begin, p.end) {
1061 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1062 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1064 return PiecePriorityNone
1069 ret := piecePriority(-prio)
1070 if ret == PiecePriorityNone {
1076 func (t *Torrent) pendRequest(req request) {
1077 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1078 t.pieces[req.Index].pendChunkIndex(ci)
1081 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1083 t.cl.event.Broadcast()
1084 if t.pieceComplete(piece) {
1085 t.onPieceCompleted(piece)
1087 t.onIncompletePiece(piece)
1089 t.updatePiecePriority(piece)
1092 func (t *Torrent) numReceivedConns() (ret int) {
1093 for c := range t.conns {
1094 if c.Discovery == PeerSourceIncoming {
1101 func (t *Torrent) maxHalfOpen() int {
1102 // Note that if we somehow exceed the maximum established conns, we want
1103 // the negative value to have an effect.
1104 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1105 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1106 // We want to allow some experimentation with new peers, and to try to
1107 // upset an oversupply of received connections.
1108 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1111 func (t *Torrent) openNewConns() (initiated int) {
1112 defer t.updateWantPeersEvent()
1113 for t.peers.Len() != 0 {
1117 if len(t.halfOpen) >= t.maxHalfOpen() {
1120 if len(t.cl.dialers) == 0 {
1123 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1126 p := t.peers.PopMax()
1133 func (t *Torrent) getConnPieceInclination() []int {
1134 _ret := t.connPieceInclinationPool.Get()
1136 pieceInclinationsNew.Add(1)
1137 return rand.Perm(int(t.numPieces()))
1139 pieceInclinationsReused.Add(1)
1140 return *_ret.(*[]int)
1143 func (t *Torrent) putPieceInclination(pi []int) {
1144 t.connPieceInclinationPool.Put(&pi)
1145 pieceInclinationsPut.Add(1)
1148 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1150 uncached := t.pieceCompleteUncached(piece)
1151 cached := p.completion()
1152 changed := cached != uncached
1153 complete := uncached.Complete
1154 p.storageCompletionOk = uncached.Ok
1155 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1156 if complete && len(p.dirtiers) != 0 {
1157 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1160 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1161 t.pieceCompletionChanged(piece)
1166 // Non-blocking read. Client lock is not required.
1167 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1169 p := &t.pieces[off/t.info.PieceLength]
1170 p.waitNoPendingWrites()
1172 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1183 // Returns an error if the metadata was completed, but couldn't be set for
1184 // some reason. Blame it on the last peer to contribute.
1185 func (t *Torrent) maybeCompleteMetadata() error {
1190 if !t.haveAllMetadataPieces() {
1191 // Don't have enough metadata pieces.
1194 err := t.setInfoBytes(t.metadataBytes)
1196 t.invalidateMetadata()
1197 return fmt.Errorf("error setting info bytes: %s", err)
1199 if t.cl.config.Debug {
1200 t.logger.Printf("%s: got metadata from peers", t)
1205 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1206 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1208 now.Add(bitmap.BitIndex(begin))
1209 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1216 func (t *Torrent) needData() bool {
1217 if t.closed.IsSet() {
1223 return t._pendingPieces.Len() != 0
1226 func appendMissingStrings(old, new []string) (ret []string) {
1229 for _, n := range new {
1230 for _, o := range old {
1235 ret = append(ret, n)
1240 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1242 for minNumTiers > len(ret) {
1243 ret = append(ret, nil)
1248 func (t *Torrent) addTrackers(announceList [][]string) {
1249 fullAnnounceList := &t.metainfo.AnnounceList
1250 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1251 for tierIndex, trackerURLs := range announceList {
1252 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1254 t.startMissingTrackerScrapers()
1255 t.updateWantPeersEvent()
1258 // Don't call this before the info is available.
1259 func (t *Torrent) bytesCompleted() int64 {
1263 return t.info.TotalLength() - t.bytesLeft()
1266 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1269 return t.setInfoBytes(b)
1272 // Returns true if connection is removed from torrent.Conns.
1273 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1274 if !c.closed.IsSet() {
1275 panic("connection is not closed")
1276 // There are behaviours prevented by the closed state that will fail
1277 // if the connection has been deleted.
1281 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1282 // the drop event against the PexConnState instead.
1284 if !t.cl.config.DisablePEX {
1288 torrent.Add("deleted connections", 1)
1289 c.deleteAllRequests()
1290 if t.numActivePeers() == 0 {
1291 t.assertNoPendingRequests()
1296 func (t *Torrent) numActivePeers() (num int) {
1297 t.iterPeers(func(*peer) {
1303 func (t *Torrent) assertNoPendingRequests() {
1304 if len(t.pendingRequests) != 0 {
1305 panic(t.pendingRequests)
1307 //if len(t.lastRequested) != 0 {
1308 // panic(t.lastRequested)
1312 func (t *Torrent) dropConnection(c *PeerConn) {
1313 t.cl.event.Broadcast()
1315 if t.deleteConnection(c) {
1320 func (t *Torrent) wantPeers() bool {
1321 if t.closed.IsSet() {
1324 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1327 return t.needData() || t.seeding()
1330 func (t *Torrent) updateWantPeersEvent() {
1332 t.wantPeersEvent.Set()
1334 t.wantPeersEvent.Clear()
1338 // Returns whether the client should make effort to seed the torrent.
1339 func (t *Torrent) seeding() bool {
1341 if t.closed.IsSet() {
1344 if t.dataUploadDisallowed {
1347 if cl.config.NoUpload {
1350 if !cl.config.Seed {
1353 if cl.config.DisableAggressiveUpload && t.needData() {
1359 func (t *Torrent) onWebRtcConn(
1360 c datachannel.ReadWriteCloser,
1361 dcc webtorrent.DataChannelContext,
1364 pc, err := t.cl.initiateProtocolHandshakes(
1365 context.Background(),
1366 webrtcNetConn{c, dcc},
1370 webrtcNetAddr{dcc.Remote},
1372 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1375 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1378 if dcc.LocalOffered {
1379 pc.Discovery = PeerSourceTracker
1381 pc.Discovery = PeerSourceIncoming
1385 err = t.cl.runHandshookConn(pc, t)
1387 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1391 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1392 err := t.cl.runHandshookConn(pc, t)
1393 if err != nil || logAll {
1394 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1398 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1399 t.logRunHandshookConn(pc, false, log.Debug)
1402 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1403 wtc, release := t.cl.websocketTrackers.Get(u.String())
1405 <-t.closed.LockedChan(t.cl.locker())
1408 wst := websocketTrackerStatus{u, wtc}
1410 err := wtc.Announce(tracker.Started, t.infoHash)
1412 t.logger.WithDefaultLevel(log.Warning).Printf(
1413 "error in initial announce to %q: %v",
1422 func (t *Torrent) startScrapingTracker(_url string) {
1426 u, err := url.Parse(_url)
1428 // URLs with a leading '*' appear to be a uTorrent convention to
1429 // disable trackers.
1431 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1435 if u.Scheme == "udp" {
1437 t.startScrapingTracker(u.String())
1439 t.startScrapingTracker(u.String())
1442 if _, ok := t.trackerAnnouncers[_url]; ok {
1445 sl := func() torrentTrackerAnnouncer {
1448 if t.cl.config.DisableWebtorrent {
1451 return t.startWebsocketAnnouncer(*u)
1453 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1457 if t.cl.config.DisableIPv6 {
1461 newAnnouncer := &trackerScraper{
1465 go newAnnouncer.Run()
1471 if t.trackerAnnouncers == nil {
1472 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1474 t.trackerAnnouncers[_url] = sl
1477 // Adds and starts tracker scrapers for tracker URLs that aren't already
1479 func (t *Torrent) startMissingTrackerScrapers() {
1480 if t.cl.config.DisableTrackers {
1483 t.startScrapingTracker(t.metainfo.Announce)
1484 for _, tier := range t.metainfo.AnnounceList {
1485 for _, url := range tier {
1486 t.startScrapingTracker(url)
1491 // Returns an AnnounceRequest with fields filled out to defaults and current
1493 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1494 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1495 // dependent on the network in use.
1496 return tracker.AnnounceRequest{
1498 NumWant: func() int32 {
1499 if t.wantPeers() && len(t.cl.dialers) > 0 {
1505 Port: uint16(t.cl.incomingPeerPort()),
1506 PeerId: t.cl.peerID,
1507 InfoHash: t.infoHash,
1508 Key: t.cl.announceKey(),
1510 // The following are vaguely described in BEP 3.
1512 Left: t.bytesLeftAnnounce(),
1513 Uploaded: t.stats.BytesWrittenData.Int64(),
1514 // There's no mention of wasted or unwanted download in the BEP.
1515 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1519 // Adds peers revealed in an announce until the announce ends, or we have
1521 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1523 for v := range pvs {
1525 for _, cp := range v.Peers {
1527 // Can't do anything with this.
1531 Addr: ipPortAddr{cp.IP, cp.Port},
1532 Source: PeerSourceDhtGetPeers,
1539 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1540 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1544 go t.consumeDhtAnnouncePeers(ps.Peers())
1546 case <-t.closed.LockedChan(t.cl.locker()):
1547 case <-time.After(5 * time.Minute):
1553 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1559 if t.closed.IsSet() {
1565 // TODO: Determine if there's a listener on the port we're announcing.
1566 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1577 err := t.announceToDht(true, s)
1579 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1585 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1586 for _, p := range peers {
1594 // The returned TorrentStats may require alignment in memory. See
1595 // https://github.com/anacrolix/torrent/issues/383.
1596 func (t *Torrent) Stats() TorrentStats {
1598 defer t.cl.rUnlock()
1599 return t.statsLocked()
1602 func (t *Torrent) statsLocked() (ret TorrentStats) {
1603 ret.ActivePeers = len(t.conns)
1604 ret.HalfOpenPeers = len(t.halfOpen)
1605 ret.PendingPeers = t.peers.Len()
1606 ret.TotalPeers = t.numTotalPeers()
1607 ret.ConnectedSeeders = 0
1608 for c := range t.conns {
1609 if all, ok := c.peerHasAllPieces(); all && ok {
1610 ret.ConnectedSeeders++
1613 ret.ConnStats = t.stats.Copy()
1617 // The total number of peers in the torrent.
1618 func (t *Torrent) numTotalPeers() int {
1619 peers := make(map[string]struct{})
1620 for conn := range t.conns {
1621 ra := conn.conn.RemoteAddr()
1623 // It's been closed and doesn't support RemoteAddr.
1626 peers[ra.String()] = struct{}{}
1628 for addr := range t.halfOpen {
1629 peers[addr] = struct{}{}
1631 t.peers.Each(func(peer PeerInfo) {
1632 peers[peer.Addr.String()] = struct{}{}
1637 // Reconcile bytes transferred before connection was associated with a
1639 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1640 if c._stats != (ConnStats{
1641 // Handshakes should only increment these fields:
1642 BytesWritten: c._stats.BytesWritten,
1643 BytesRead: c._stats.BytesRead,
1647 c.postHandshakeStats(func(cs *ConnStats) {
1648 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1649 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1651 c.reconciledHandshakeStats = true
1654 // Returns true if the connection is added.
1655 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1658 torrent.Add("added connections", 1)
1661 if t.closed.IsSet() {
1662 return errors.New("torrent closed")
1664 for c0 := range t.conns {
1665 if c.PeerID != c0.PeerID {
1668 if !t.cl.config.DropDuplicatePeerIds {
1671 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1673 t.deleteConnection(c0)
1675 return errors.New("existing connection preferred")
1678 if len(t.conns) >= t.maxEstablishedConns {
1679 c := t.worstBadConn()
1681 return errors.New("don't want conns")
1684 t.deleteConnection(c)
1686 if len(t.conns) >= t.maxEstablishedConns {
1689 t.conns[c] = struct{}{}
1690 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1691 t.pex.Add(c) // as no further extended handshake expected
1696 func (t *Torrent) wantConns() bool {
1697 if !t.networkingEnabled {
1700 if t.closed.IsSet() {
1703 if !t.seeding() && !t.needData() {
1706 if len(t.conns) < t.maxEstablishedConns {
1709 return t.worstBadConn() != nil
1712 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1715 oldMax = t.maxEstablishedConns
1716 t.maxEstablishedConns = max
1717 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1718 return worseConn(&l.peer, &r.peer)
1720 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1721 t.dropConnection(wcs.Pop().(*PeerConn))
1727 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1728 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1731 t.cl.event.Broadcast()
1732 if t.closed.IsSet() {
1736 // Don't score the first time a piece is hashed, it could be an initial check.
1737 if p.storageCompletionOk {
1739 pieceHashedCorrect.Add(1)
1741 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1742 pieceHashedNotCorrect.Add(1)
1747 t.publishPieceChange(piece)
1750 t.publishPieceChange(piece)
1754 if len(p.dirtiers) != 0 {
1755 // Don't increment stats above connection-level for every involved connection.
1756 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1758 for c := range p.dirtiers {
1759 c._stats.incrementPiecesDirtiedGood()
1761 t.clearPieceTouchers(piece)
1763 err := p.Storage().MarkComplete()
1765 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1769 if t.closed.IsSet() {
1772 t.pendAllChunkSpecs(piece)
1774 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1775 // Peers contributed to all the data for this piece hash failure, and the failure was
1776 // not due to errors in the storage (such as data being dropped in a cache).
1778 // Increment Torrent and above stats, and then specific connections.
1779 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1780 for c := range p.dirtiers {
1781 // Y u do dis peer?!
1782 c.stats().incrementPiecesDirtiedBad()
1785 bannableTouchers := make([]*peer, 0, len(p.dirtiers))
1786 for c := range p.dirtiers {
1788 bannableTouchers = append(bannableTouchers, c)
1791 t.clearPieceTouchers(piece)
1792 slices.Sort(bannableTouchers, connLessTrusted)
1794 if t.cl.config.Debug {
1796 "bannable conns by trust for piece %d: %v",
1798 func() (ret []connectionTrust) {
1799 for _, c := range bannableTouchers {
1800 ret = append(ret, c.trust())
1807 if len(bannableTouchers) >= 1 {
1808 c := bannableTouchers[0]
1809 t.cl.banPeerIP(c.remoteIp())
1813 t.onIncompletePiece(piece)
1814 p.Storage().MarkNotComplete()
1816 t.updatePieceCompletion(piece)
1819 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1820 // TODO: Make faster
1821 for cn := range t.conns {
1826 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1827 t.pendAllChunkSpecs(piece)
1828 t.cancelRequestsForPiece(piece)
1829 for conn := range t.conns {
1831 t.maybeDropMutuallyCompletePeer(&conn.peer)
1835 // Called when a piece is found to be not complete.
1836 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1837 if t.pieceAllDirty(piece) {
1838 t.pendAllChunkSpecs(piece)
1840 if !t.wantPieceIndex(piece) {
1841 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1844 // We could drop any connections that we told we have a piece that we
1845 // don't here. But there's a test failure, and it seems clients don't care
1846 // if you request pieces that you already claim to have. Pruning bad
1847 // connections might just remove any connections that aren't treating us
1848 // favourably anyway.
1850 // for c := range t.conns {
1851 // if c.sentHave(piece) {
1855 t.iterPeers(func(conn *peer) {
1856 if conn.peerHasPiece(piece) {
1857 conn.updateRequests()
1862 func (t *Torrent) tryCreateMorePieceHashers() {
1863 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1867 func (t *Torrent) tryCreatePieceHasher() bool {
1868 if t.storage == nil {
1871 pi, ok := t.getPieceToHash()
1876 t.piecesQueuedForHash.Remove(pi)
1878 t.publishPieceChange(pi)
1879 t.updatePiecePriority(pi)
1880 t.storageLock.RLock()
1881 t.activePieceHashes++
1882 go t.pieceHasher(pi)
1886 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1887 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1888 if t.piece(i).hashing {
1898 func (t *Torrent) pieceHasher(index pieceIndex) {
1900 sum, copyErr := t.hashPiece(index)
1901 correct := sum == *p.hash
1905 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1907 t.storageLock.RUnlock()
1911 t.updatePiecePriority(index)
1912 t.pieceHashed(index, correct, copyErr)
1913 t.publishPieceChange(index)
1914 t.activePieceHashes--
1915 t.tryCreateMorePieceHashers()
1918 // Return the connections that touched a piece, and clear the entries while doing it.
1919 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1921 for c := range p.dirtiers {
1922 delete(c.peerTouchedPieces, pi)
1923 delete(p.dirtiers, c)
1927 func (t *Torrent) peersAsSlice() (ret []*peer) {
1928 t.iterPeers(func(p *peer) {
1929 ret = append(ret, p)
1934 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1935 piece := t.piece(pieceIndex)
1936 if piece.queuedForHash() {
1939 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1940 t.publishPieceChange(pieceIndex)
1941 t.updatePiecePriority(pieceIndex)
1942 t.tryCreateMorePieceHashers()
1945 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1946 // before the Info is available.
1947 func (t *Torrent) VerifyData() {
1948 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1949 t.Piece(i).VerifyData()
1953 // Start the process of connecting to the given peer for the given torrent if appropriate.
1954 func (t *Torrent) initiateConn(peer PeerInfo) {
1955 if peer.Id == t.cl.peerID {
1958 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1962 if t.addrActive(addr.String()) {
1966 t.halfOpen[addr.String()] = peer
1967 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1970 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1971 // quickly make one Client visible to the Torrent of another Client.
1972 func (t *Torrent) AddClientPeer(cl *Client) int {
1973 return t.AddPeers(func() (ps []PeerInfo) {
1974 for _, la := range cl.ListenAddrs() {
1975 ps = append(ps, PeerInfo{
1984 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1986 func (t *Torrent) allStats(f func(*ConnStats)) {
1991 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1992 return t.pieces[i].hashing
1995 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1996 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1999 func (t *Torrent) dialTimeout() time.Duration {
2000 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2003 func (t *Torrent) piece(i int) *Piece {
2007 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
2011 type torrentRequestStrategyCallbacks struct {
2015 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
2016 torrent.Add("request timeouts", 1)
2018 defer cb.t.cl.unlock()
2019 cb.t.iterPeers(func(cn *peer) {
2020 if cn.peerHasPiece(pieceIndex(r.Index)) {
2027 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
2028 return torrentRequestStrategyCallbacks{t}
2031 func (t *Torrent) onWriteChunkErr(err error) {
2032 if t.userOnWriteChunkErr != nil {
2033 go t.userOnWriteChunkErr(err)
2036 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2037 t.disallowDataDownloadLocked()
2040 func (t *Torrent) DisallowDataDownload() {
2043 t.disallowDataDownloadLocked()
2046 func (t *Torrent) disallowDataDownloadLocked() {
2047 t.dataDownloadDisallowed = true
2048 t.iterPeers(func(c *peer) {
2054 func (t *Torrent) AllowDataDownload() {
2057 t.dataDownloadDisallowed = false
2059 t.iterPeers(func(c *peer) {
2064 // Enables uploading data, if it was disabled.
2065 func (t *Torrent) AllowDataUpload() {
2068 t.dataUploadDisallowed = false
2069 for c := range t.conns {
2074 // Disables uploading data, if it was enabled.
2075 func (t *Torrent) DisallowDataUpload() {
2078 t.dataUploadDisallowed = true
2079 for c := range t.conns {
2084 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2085 // or if nil, a critical message is logged, and data download is disabled.
2086 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2089 t.userOnWriteChunkErr = f
2092 func (t *Torrent) iterPeers(f func(*peer)) {
2093 for pc := range t.conns {
2096 for _, ws := range t.webSeeds {
2101 func (t *Torrent) addWebSeed(url string) {
2102 if t.cl.config.DisableWebseeds {
2105 if _, ok := t.webSeeds[url]; ok {
2108 const maxRequests = 10
2114 reconciledHandshakeStats: true,
2115 peerSentHaveAll: true,
2116 PeerMaxRequests: maxRequests,
2118 client: webseed.Client{
2119 HttpClient: http.DefaultClient,
2122 requests: make(map[request]webseed.Request, maxRequests),
2124 ws.peer.logger = t.logger.WithContextValue(&ws)
2125 ws.peer.peerImpl = &ws
2127 ws.onGotInfo(t.info)
2129 t.webSeeds[url] = &ws.peer
2132 func (t *Torrent) peerIsActive(p *peer) (active bool) {
2133 t.iterPeers(func(p1 *peer) {