17 "github.com/davecgh/go-spew/spew"
18 "github.com/pion/datachannel"
20 "github.com/anacrolix/dht/v2"
21 "github.com/anacrolix/log"
22 "github.com/anacrolix/missinggo"
23 "github.com/anacrolix/missinggo/perf"
24 "github.com/anacrolix/missinggo/pubsub"
25 "github.com/anacrolix/missinggo/slices"
26 "github.com/anacrolix/missinggo/v2/bitmap"
27 "github.com/anacrolix/missinggo/v2/prioritybitmap"
29 "github.com/anacrolix/torrent/bencode"
30 "github.com/anacrolix/torrent/metainfo"
31 pp "github.com/anacrolix/torrent/peer_protocol"
32 "github.com/anacrolix/torrent/storage"
33 "github.com/anacrolix/torrent/tracker"
34 "github.com/anacrolix/torrent/webtorrent"
37 // Maintains state of torrent within a Client. Many methods should not be called before the info is
38 // available, see .Info and .GotInfo.
40 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
41 // alignment. See #262.
46 networkingEnabled bool
47 dataDownloadDisallowed bool
48 userOnWriteChunkErr func(error)
50 // Determines what chunks to request from peers.
51 requestStrategy requestStrategy
53 closed missinggo.Event
54 infoHash metainfo.Hash
56 // Values are the piece indices that changed.
57 pieceStateChanges *pubsub.PubSub
58 // The size of chunks to request from peers over the wire. This is
59 // normally 16KiB by convention these days.
62 // Total length of the torrent in bytes. Stored because it's not O(1) to
63 // get this from the info dict.
66 // The storage to open when the info dict becomes available.
67 storageOpener *storage.Client
68 // Storage for torrent data.
69 storage *storage.Torrent
70 // Read-locked for using storage, and write-locked for Closing.
71 storageLock sync.RWMutex
73 // TODO: Only announce stuff is used?
74 metainfo metainfo.MetaInfo
76 // The info dict. nil if we don't have it (yet).
80 // Active peer connections, running message stream loops. TODO: Make this
81 // open (not-closed) connections only.
82 conns map[*PeerConn]struct{}
83 maxEstablishedConns int
84 // Set of addrs to which we're attempting to connect. Connections are
85 // half-open until all handshakes are completed.
86 halfOpen map[string]Peer
89 // Reserve of peers to connect to. A peer can be both here and in the
90 // active connections if were told about the peer after connecting with
91 // them. That encourages us to reconnect to peers that are well known in
93 peers prioritizedPeers
94 // Whether we want to know to know more peers.
95 wantPeersEvent missinggo.Event
96 // An announcer for each tracker URL.
97 trackerAnnouncers map[string]torrentTrackerAnnouncer
98 // How many times we've initiated a DHT announce. TODO: Move into stats.
101 // Name used if the info name isn't available. Should be cleared when the
102 // Info does become available.
106 // The bencoded bytes of the info dict. This is actively manipulated if
107 // the info bytes aren't initially available, and we try to fetch them
110 // Each element corresponds to the 16KiB metadata pieces. If true, we have
111 // received that piece.
112 metadataCompletedChunks []bool
113 metadataChanged sync.Cond
115 // Set when .Info is obtained.
116 gotMetainfo missinggo.Event
118 readers map[*reader]struct{}
119 _readerNowPieces bitmap.Bitmap
120 _readerReadaheadPieces bitmap.Bitmap
122 // A cache of pieces we need to get. Calculated from various piece and
123 // file priorities and completion states elsewhere.
124 _pendingPieces prioritybitmap.PriorityBitmap
125 // A cache of completed piece indices.
126 _completedPieces bitmap.Bitmap
127 // Pieces that need to be hashed.
128 piecesQueuedForHash bitmap.Bitmap
129 activePieceHashes int
131 // A pool of piece priorities []int for assignment to new connections.
132 // These "inclinations" are used to give connections preference for
134 connPieceInclinationPool sync.Pool
136 // Count of each request across active connections.
137 pendingRequests map[request]int
142 func (t *Torrent) numConns() int {
146 func (t *Torrent) numReaders() int {
147 return len(t.readers)
150 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
151 return t._readerNowPieces
154 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
155 return t._readerReadaheadPieces
158 func (t *Torrent) ignorePieces() bitmap.Bitmap {
159 ret := t._completedPieces.Copy()
160 ret.Union(t.piecesQueuedForHash)
161 for i := 0; i < t.numPieces(); i++ {
162 if t.piece(i).hashing {
169 func (t *Torrent) pendingPieces() *prioritybitmap.PriorityBitmap {
170 return &t._pendingPieces
173 func (t *Torrent) tickleReaders() {
174 t.cl.event.Broadcast()
177 // Returns a channel that is closed when the Torrent is closed.
178 func (t *Torrent) Closed() <-chan struct{} {
179 return t.closed.LockedChan(t.cl.locker())
182 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
183 // pending, and half-open peers.
184 func (t *Torrent) KnownSwarm() (ks []Peer) {
185 // Add pending peers to the list
186 t.peers.Each(func(peer Peer) {
187 ks = append(ks, peer)
190 // Add half-open peers to the list
191 for _, peer := range t.halfOpen {
192 ks = append(ks, peer)
195 // Add active peers to the list
196 for conn := range t.conns {
198 ks = append(ks, Peer{
200 Addr: conn.remoteAddr,
201 Source: conn.Discovery,
202 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
203 // > But if we're not connected to them with an encrypted connection, I couldn't say
204 // > what's appropriate. We can carry forward the SupportsEncryption value as we
205 // > received it from trackers/DHT/PEX, or just use the encryption state for the
206 // > connection. It's probably easiest to do the latter for now.
207 // https://github.com/anacrolix/torrent/pull/188
208 SupportsEncryption: conn.headerEncrypted,
215 func (t *Torrent) setChunkSize(size pp.Integer) {
217 t.chunkPool = &sync.Pool{
218 New: func() interface{} {
219 b := make([]byte, size)
225 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
226 return t._completedPieces.Get(bitmap.BitIndex(piece))
229 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
230 return t.pieces[piece].Storage().Completion()
233 // There's a connection to that address already.
234 func (t *Torrent) addrActive(addr string) bool {
235 if _, ok := t.halfOpen[addr]; ok {
238 for c := range t.conns {
240 if ra.String() == addr {
247 func (t *Torrent) unclosedConnsAsSlice() (ret []*PeerConn) {
248 ret = make([]*PeerConn, 0, len(t.conns))
249 for c := range t.conns {
250 if !c.closed.IsSet() {
257 func (t *Torrent) addPeer(p Peer) (added bool) {
259 torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
260 if t.closed.IsSet() {
263 if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
264 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
265 torrent.Add("peers not added because of bad addr", 1)
266 // cl.logger.Printf("peers not added because of bad addr: %v", p)
270 if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
271 torrent.Add("peers replaced", 1)
272 if !replaced.Equal(p) {
273 t.logger.Printf("added %v replacing %v", p, replaced)
280 for t.peers.Len() > cl.config.TorrentPeersHighWater {
281 _, ok := t.peers.DeleteMin()
283 torrent.Add("excess reserve peers discarded", 1)
289 func (t *Torrent) invalidateMetadata() {
290 for i := range t.metadataCompletedChunks {
291 t.metadataCompletedChunks[i] = false
298 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
302 if index >= len(t.metadataCompletedChunks) {
303 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
306 copy(t.metadataBytes[(1<<14)*index:], data)
307 t.metadataCompletedChunks[index] = true
310 func (t *Torrent) metadataPieceCount() int {
311 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
314 func (t *Torrent) haveMetadataPiece(piece int) bool {
316 return (1<<14)*piece < len(t.metadataBytes)
318 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
322 func (t *Torrent) metadataSize() int {
323 return len(t.metadataBytes)
326 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
327 for i := 0; i < len(info.Pieces); i += sha1.Size {
328 ret = append(ret, info.Pieces[i:i+sha1.Size])
333 func (t *Torrent) makePieces() {
334 hashes := infoPieceHashes(t.info)
335 t.pieces = make([]Piece, len(hashes))
336 for i, hash := range hashes {
337 piece := &t.pieces[i]
339 piece.index = pieceIndex(i)
340 piece.noPendingWrites.L = &piece.pendingWritesMutex
341 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
343 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
344 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
345 piece.files = files[beginFile:endFile]
349 // Returns the index of the first file containing the piece. files must be
350 // ordered by offset.
351 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
352 for i, f := range files {
353 if f.offset+f.length > pieceOffset {
360 // Returns the index after the last file containing the piece. files must be
361 // ordered by offset.
362 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
363 for i, f := range files {
364 if f.offset+f.length >= pieceEndOffset {
371 func (t *Torrent) cacheLength() {
373 for _, f := range t.info.UpvertedFiles() {
379 func (t *Torrent) setInfo(info *metainfo.Info) error {
380 if err := validateInfo(info); err != nil {
381 return fmt.Errorf("bad info: %s", err)
383 if t.storageOpener != nil {
385 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
387 return fmt.Errorf("error opening torrent storage: %s", err)
393 t.displayName = "" // Save a few bytes lol.
400 func (t *Torrent) onSetInfo() {
401 for conn := range t.conns {
402 if err := conn.setNumPieces(t.numPieces()); err != nil {
403 t.logger.Printf("closing connection: %s", err)
407 for i := range t.pieces {
408 t.updatePieceCompletion(pieceIndex(i))
410 if !p.storageCompletionOk {
411 // t.logger.Printf("piece %s completion unknown, queueing check", p)
412 t.queuePieceCheck(pieceIndex(i))
415 t.cl.event.Broadcast()
417 t.updateWantPeersEvent()
418 t.pendingRequests = make(map[request]int)
419 t.tryCreateMorePieceHashers()
422 // Called when metadata for a torrent becomes available.
423 func (t *Torrent) setInfoBytes(b []byte) error {
424 if metainfo.HashBytes(b) != t.infoHash {
425 return errors.New("info bytes have wrong hash")
427 var info metainfo.Info
428 if err := bencode.Unmarshal(b, &info); err != nil {
429 return fmt.Errorf("error unmarshalling info bytes: %s", err)
431 if err := t.setInfo(&info); err != nil {
435 t.metadataCompletedChunks = nil
440 func (t *Torrent) haveAllMetadataPieces() bool {
444 if t.metadataCompletedChunks == nil {
447 for _, have := range t.metadataCompletedChunks {
455 // TODO: Propagate errors to disconnect peer.
456 func (t *Torrent) setMetadataSize(bytes int) (err error) {
458 // We already know the correct metadata size.
461 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
462 return errors.New("bad size")
464 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
467 t.metadataBytes = make([]byte, bytes)
468 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
469 t.metadataChanged.Broadcast()
470 for c := range t.conns {
471 c.requestPendingMetadata()
476 // The current working name for the torrent. Either the name in the info dict,
477 // or a display name given such as by the dn value in a magnet link, or "".
478 func (t *Torrent) name() string {
480 defer t.nameMu.RUnlock()
487 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
488 p := &t.pieces[index]
489 ret.Priority = t.piecePriority(index)
490 ret.Completion = p.completion()
491 if p.queuedForHash() || p.hashing {
494 if !ret.Complete && t.piecePartiallyDownloaded(index) {
500 func (t *Torrent) metadataPieceSize(piece int) int {
501 return metadataPieceSize(len(t.metadataBytes), piece)
504 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
510 d["total_size"] = len(t.metadataBytes)
512 p := bencode.MustMarshal(d)
515 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
516 ExtendedPayload: append(p, data...),
520 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
521 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
522 ret = append(ret, PieceStateRun{
523 PieceState: el.(PieceState),
527 for index := range t.pieces {
528 rle.Append(t.pieceState(pieceIndex(index)), 1)
534 // Produces a small string representing a PieceStateRun.
535 func (psr PieceStateRun) String() (ret string) {
536 ret = fmt.Sprintf("%d", psr.Length)
537 ret += func() string {
538 switch psr.Priority {
539 case PiecePriorityNext:
541 case PiecePriorityNormal:
543 case PiecePriorityReadahead:
545 case PiecePriorityNow:
547 case PiecePriorityHigh:
568 func (t *Torrent) writeStatus(w io.Writer) {
569 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
570 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
572 fmt.Fprintf(w, "Metadata have: ")
573 for _, h := range t.metadataCompletedChunks {
574 fmt.Fprintf(w, "%c", func() rune {
584 fmt.Fprintf(w, "Piece length: %s\n", func() string {
586 return fmt.Sprint(t.usualPieceSize())
592 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
593 fmt.Fprintf(w, "Piece States: %s", t.pieceStateRuns())
596 fmt.Fprintf(w, "Reader Pieces:")
597 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
598 fmt.Fprintf(w, " %d:%d", begin, end)
603 fmt.Fprintf(w, "Enabled trackers:\n")
605 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
606 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
607 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
610 var luns, runs url.URL = lu, ru
613 var ml missinggo.MultiLess
614 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
615 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
617 }).([]torrentTrackerAnnouncer) {
618 fmt.Fprintf(tw, " %s\n", ta.statusLine())
623 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
625 spew.NewDefaultConfig()
626 spew.Fdump(w, t.statsLocked())
628 conns := t.connsAsSlice()
629 slices.Sort(conns, worseConn)
630 for i, c := range conns {
631 fmt.Fprintf(w, "%2d. ", i+1)
636 func (t *Torrent) haveInfo() bool {
640 // Returns a run-time generated MetaInfo that includes the info bytes and
641 // announce-list as currently known to the client.
642 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
643 return metainfo.MetaInfo{
644 CreationDate: time.Now().Unix(),
645 Comment: "dynamic metainfo from client",
646 CreatedBy: "go.torrent",
647 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
648 InfoBytes: func() []byte {
650 return t.metadataBytes
658 func (t *Torrent) BytesMissing() int64 {
661 return t.bytesMissingLocked()
664 func (t *Torrent) bytesMissingLocked() int64 {
668 func (t *Torrent) bytesLeft() (left int64) {
669 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
670 p := &t.pieces[piece]
671 left += int64(p.length() - p.numDirtyBytes())
677 // Bytes left to give in tracker announces.
678 func (t *Torrent) bytesLeftAnnounce() int64 {
686 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
687 if t.pieceComplete(piece) {
690 if t.pieceAllDirty(piece) {
693 return t.pieces[piece].hasDirtyChunks()
696 func (t *Torrent) usualPieceSize() int {
697 return int(t.info.PieceLength)
700 func (t *Torrent) numPieces() pieceIndex {
701 return pieceIndex(t.info.NumPieces())
704 func (t *Torrent) numPiecesCompleted() (num int) {
705 return t._completedPieces.Len()
708 func (t *Torrent) close() (err error) {
711 if t.storage != nil {
714 t.storageLock.Unlock()
716 for conn := range t.conns {
720 t.cl.event.Broadcast()
721 t.pieceStateChanges.Close()
722 t.updateWantPeersEvent()
726 func (t *Torrent) requestOffset(r request) int64 {
727 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
730 // Return the request that would include the given offset into the torrent
731 // data. Returns !ok if there is no such request.
732 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
733 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
736 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
737 defer perf.ScopeTimerErr(&err)()
738 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
739 if err == nil && n != len(data) {
740 err = io.ErrShortWrite
745 func (t *Torrent) bitfield() (bf []bool) {
746 bf = make([]bool, t.numPieces())
747 t._completedPieces.IterTyped(func(piece int) (again bool) {
754 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
755 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
758 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
759 t.pieces[pieceIndex]._dirtyChunks.Clear()
762 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
763 if t.info.PieceLength == 0 {
764 // There will be no variance amongst pieces. Only pain.
767 if piece == t.numPieces()-1 {
768 ret := pp.Integer(*t.length % t.info.PieceLength)
773 return pp.Integer(t.info.PieceLength)
776 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, copyErr error) {
777 hash := pieceHash.New()
779 p.waitNoPendingWrites()
780 ip := t.info.Piece(int(piece))
782 _, copyErr = io.CopyN( // Return no error iff pl bytes are copied.
783 hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl), pl)
784 missinggo.CopyExact(&ret, hash.Sum(nil))
788 func (t *Torrent) haveAnyPieces() bool {
789 return t._completedPieces.Len() != 0
792 func (t *Torrent) haveAllPieces() bool {
796 return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
799 func (t *Torrent) havePiece(index pieceIndex) bool {
800 return t.haveInfo() && t.pieceComplete(index)
803 func (t *Torrent) haveChunk(r request) (ret bool) {
805 // log.Println("have chunk", r, ret)
810 if t.pieceComplete(pieceIndex(r.Index)) {
813 p := &t.pieces[r.Index]
814 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
817 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
818 return int(cs.Begin / chunkSize)
821 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
825 if index < 0 || index >= t.numPieces() {
828 p := &t.pieces[index]
829 if p.queuedForHash() {
835 if t.pieceComplete(index) {
838 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
841 // t.logger.Printf("piece %d not pending", index)
842 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
843 return index < begin || index >= end
847 // The worst connection is one that hasn't been sent, or sent anything useful
848 // for the longest. A bad connection is one that usually sends us unwanted
849 // pieces, or has been in worser half of the established connections for more
851 func (t *Torrent) worstBadConn() *PeerConn {
852 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
855 c := heap.Pop(&wcs).(*PeerConn)
856 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
859 // If the connection is in the worst half of the established
860 // connection quota and is older than a minute.
861 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
862 // Give connections 1 minute to prove themselves.
863 if time.Since(c.completedHandshake) > time.Minute {
871 type PieceStateChange struct {
876 func (t *Torrent) publishPieceChange(piece pieceIndex) {
877 t.cl._mu.Defer(func() {
878 cur := t.pieceState(piece)
879 p := &t.pieces[piece]
880 if cur != p.publicPieceState {
881 p.publicPieceState = cur
882 t.pieceStateChanges.Publish(PieceStateChange{
890 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
891 if t.pieceComplete(piece) {
894 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
897 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
898 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
901 func (t *Torrent) readersChanged() {
902 t.updateReaderPieces()
903 t.updateAllPiecePriorities()
906 func (t *Torrent) updateReaderPieces() {
907 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
910 func (t *Torrent) readerPosChanged(from, to pieceRange) {
914 t.updateReaderPieces()
915 // Order the ranges, high and low.
917 if l.begin > h.begin {
921 // Two distinct ranges.
922 t.updatePiecePriorities(l.begin, l.end)
923 t.updatePiecePriorities(h.begin, h.end)
930 t.updatePiecePriorities(l.begin, end)
934 func (t *Torrent) maybeNewConns() {
935 // Tickle the accept routine.
936 t.cl.event.Broadcast()
940 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
941 // t.logger.Printf("piece %d priority changed", piece)
942 for c := range t.conns {
943 if c.updatePiecePriority(piece) {
944 // log.Print("conn piece priority changed")
949 t.publishPieceChange(piece)
952 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
953 p := &t.pieces[piece]
954 newPrio := p.uncachedPriority()
955 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
956 if newPrio == PiecePriorityNone {
957 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
961 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
965 t.piecePriorityChanged(piece)
968 func (t *Torrent) updateAllPiecePriorities() {
969 t.updatePiecePriorities(0, t.numPieces())
972 // Update all piece priorities in one hit. This function should have the same
973 // output as updatePiecePriority, but across all pieces.
974 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
975 for i := begin; i < end; i++ {
976 t.updatePiecePriority(i)
980 // Returns the range of pieces [begin, end) that contains the extent of bytes.
981 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
982 if off >= *t.length {
992 begin = pieceIndex(off / t.info.PieceLength)
993 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
994 if end > pieceIndex(t.info.NumPieces()) {
995 end = pieceIndex(t.info.NumPieces())
1000 // Returns true if all iterations complete without breaking. Returns the read
1001 // regions for all readers. The reader regions should not be merged as some
1002 // callers depend on this method to enumerate readers.
1003 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1004 for r := range t.readers {
1006 if p.begin >= p.end {
1009 if !f(p.begin, p.end) {
1016 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1017 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1019 return PiecePriorityNone
1024 ret := piecePriority(-prio)
1025 if ret == PiecePriorityNone {
1031 func (t *Torrent) pendRequest(req request) {
1032 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1033 t.pieces[req.Index].pendChunkIndex(ci)
1036 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1038 t.cl.event.Broadcast()
1039 if t.pieceComplete(piece) {
1040 t.onPieceCompleted(piece)
1042 t.onIncompletePiece(piece)
1044 t.updatePiecePriority(piece)
1047 func (t *Torrent) numReceivedConns() (ret int) {
1048 for c := range t.conns {
1049 if c.Discovery == PeerSourceIncoming {
1056 func (t *Torrent) maxHalfOpen() int {
1057 // Note that if we somehow exceed the maximum established conns, we want
1058 // the negative value to have an effect.
1059 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1060 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1061 // We want to allow some experimentation with new peers, and to try to
1062 // upset an oversupply of received connections.
1063 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1066 func (t *Torrent) openNewConns() {
1067 defer t.updateWantPeersEvent()
1068 for t.peers.Len() != 0 {
1072 if len(t.halfOpen) >= t.maxHalfOpen() {
1075 if len(t.cl.dialers) == 0 {
1078 p := t.peers.PopMax()
1083 func (t *Torrent) getConnPieceInclination() []int {
1084 _ret := t.connPieceInclinationPool.Get()
1086 pieceInclinationsNew.Add(1)
1087 return rand.Perm(int(t.numPieces()))
1089 pieceInclinationsReused.Add(1)
1090 return *_ret.(*[]int)
1093 func (t *Torrent) putPieceInclination(pi []int) {
1094 t.connPieceInclinationPool.Put(&pi)
1095 pieceInclinationsPut.Add(1)
1098 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1100 uncached := t.pieceCompleteUncached(piece)
1101 cached := p.completion()
1102 changed := cached != uncached
1103 complete := uncached.Complete
1104 p.storageCompletionOk = uncached.Ok
1105 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1106 if complete && len(p.dirtiers) != 0 {
1107 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1110 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).WithValues(debugLogValue).Log(t.logger)
1111 t.pieceCompletionChanged(piece)
1116 // Non-blocking read. Client lock is not required.
1117 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1118 p := &t.pieces[off/t.info.PieceLength]
1119 p.waitNoPendingWrites()
1120 return p.Storage().ReadAt(b, off-p.Info().Offset())
1123 // Returns an error if the metadata was completed, but couldn't be set for
1124 // some reason. Blame it on the last peer to contribute.
1125 func (t *Torrent) maybeCompleteMetadata() error {
1130 if !t.haveAllMetadataPieces() {
1131 // Don't have enough metadata pieces.
1134 err := t.setInfoBytes(t.metadataBytes)
1136 t.invalidateMetadata()
1137 return fmt.Errorf("error setting info bytes: %s", err)
1139 if t.cl.config.Debug {
1140 t.logger.Printf("%s: got metadata from peers", t)
1145 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1146 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1148 now.Add(bitmap.BitIndex(begin))
1149 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1156 func (t *Torrent) needData() bool {
1157 if t.closed.IsSet() {
1163 return t._pendingPieces.Len() != 0
1166 func appendMissingStrings(old, new []string) (ret []string) {
1169 for _, n := range new {
1170 for _, o := range old {
1175 ret = append(ret, n)
1180 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1182 for minNumTiers > len(ret) {
1183 ret = append(ret, nil)
1188 func (t *Torrent) addTrackers(announceList [][]string) {
1189 fullAnnounceList := &t.metainfo.AnnounceList
1190 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1191 for tierIndex, trackerURLs := range announceList {
1192 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1194 t.startMissingTrackerScrapers()
1195 t.updateWantPeersEvent()
1198 // Don't call this before the info is available.
1199 func (t *Torrent) bytesCompleted() int64 {
1203 return t.info.TotalLength() - t.bytesLeft()
1206 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1209 return t.setInfoBytes(b)
1212 // Returns true if connection is removed from torrent.Conns.
1213 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1214 if !c.closed.IsSet() {
1215 panic("connection is not closed")
1216 // There are behaviours prevented by the closed state that will fail
1217 // if the connection has been deleted.
1221 if !t.cl.config.DisablePEX {
1224 torrent.Add("deleted connections", 1)
1225 c.deleteAllRequests()
1226 if len(t.conns) == 0 {
1227 t.assertNoPendingRequests()
1232 func (t *Torrent) assertNoPendingRequests() {
1233 if len(t.pendingRequests) != 0 {
1234 panic(t.pendingRequests)
1236 //if len(t.lastRequested) != 0 {
1237 // panic(t.lastRequested)
1241 func (t *Torrent) dropConnection(c *PeerConn) {
1242 t.cl.event.Broadcast()
1244 if t.deleteConnection(c) {
1249 func (t *Torrent) wantPeers() bool {
1250 if t.closed.IsSet() {
1253 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1256 return t.needData() || t.seeding()
1259 func (t *Torrent) updateWantPeersEvent() {
1261 t.wantPeersEvent.Set()
1263 t.wantPeersEvent.Clear()
1267 // Returns whether the client should make effort to seed the torrent.
1268 func (t *Torrent) seeding() bool {
1270 if t.closed.IsSet() {
1273 if cl.config.NoUpload {
1276 if !cl.config.Seed {
1279 if cl.config.DisableAggressiveUpload && t.needData() {
1285 func (t *Torrent) onWebRtcConn(
1286 c datachannel.ReadWriteCloser,
1287 dcc webtorrent.DataChannelContext,
1290 pc, err := t.cl.handshakesConnection(
1291 context.Background(),
1292 webrtcNetConn{c, dcc},
1295 webrtcNetAddr{dcc.Remote},
1297 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1300 t.logger.Printf("error in handshaking webrtc connection: %v", err)
1302 if dcc.LocalOffered {
1303 pc.Discovery = PeerSourceTracker
1305 pc.Discovery = PeerSourceIncoming
1309 t.cl.runHandshookConn(pc, t)
1312 func (t *Torrent) startScrapingTracker(_url string) {
1316 u, err := url.Parse(_url)
1318 // URLs with a leading '*' appear to be a uTorrent convention to
1319 // disable trackers.
1321 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1325 if u.Scheme == "udp" {
1327 t.startScrapingTracker(u.String())
1329 t.startScrapingTracker(u.String())
1332 if _, ok := t.trackerAnnouncers[_url]; ok {
1335 sl := func() torrentTrackerAnnouncer {
1338 wst := websocketTracker{*u, webtorrent.NewTrackerClient(t.cl.peerID, t.infoHash, t.onWebRtcConn,
1339 t.logger.WithText(func(m log.Msg) string {
1340 return fmt.Sprintf("%q: %v", u.String(), m.Text())
1341 }).WithValues(log.Debug))}
1342 ar := t.announceRequest(tracker.Started)
1344 err := wst.TrackerClient.Run(ar, u.String())
1346 t.logger.WithValues(log.Error).Printf(
1347 "error running websocket tracker announcer for %q: %v",
1353 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1356 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1359 newAnnouncer := &trackerScraper{
1363 go newAnnouncer.Run()
1366 if t.trackerAnnouncers == nil {
1367 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1369 t.trackerAnnouncers[_url] = sl
1372 // Adds and starts tracker scrapers for tracker URLs that aren't already
1374 func (t *Torrent) startMissingTrackerScrapers() {
1375 if t.cl.config.DisableTrackers {
1378 t.startScrapingTracker(t.metainfo.Announce)
1379 for _, tier := range t.metainfo.AnnounceList {
1380 for _, url := range tier {
1381 t.startScrapingTracker(url)
1386 // Returns an AnnounceRequest with fields filled out to defaults and current
1388 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1389 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1390 // dependent on the network in use.
1391 return tracker.AnnounceRequest{
1393 NumWant: func() int32 {
1394 if t.wantPeers() && len(t.cl.dialers) > 0 {
1400 Port: uint16(t.cl.incomingPeerPort()),
1401 PeerId: t.cl.peerID,
1402 InfoHash: t.infoHash,
1403 Key: t.cl.announceKey(),
1405 // The following are vaguely described in BEP 3.
1407 Left: t.bytesLeftAnnounce(),
1408 Uploaded: t.stats.BytesWrittenData.Int64(),
1409 // There's no mention of wasted or unwanted download in the BEP.
1410 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1414 // Adds peers revealed in an announce until the announce ends, or we have
1416 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1418 for v := range pvs {
1420 for _, cp := range v.Peers {
1422 // Can't do anything with this.
1426 Addr: ipPortAddr{cp.IP, cp.Port},
1427 Source: PeerSourceDhtGetPeers,
1434 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1435 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1439 go t.consumeDhtAnnouncePeers(ps.Peers())
1441 case <-t.closed.LockedChan(t.cl.locker()):
1442 case <-time.After(5 * time.Minute):
1448 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1454 if t.closed.IsSet() {
1460 // TODO: Determine if there's a listener on the port we're announcing.
1461 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1472 err := t.announceToDht(true, s)
1474 t.logger.WithValues(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1480 func (t *Torrent) addPeers(peers []Peer) (added int) {
1481 for _, p := range peers {
1489 // The returned TorrentStats may require alignment in memory. See
1490 // https://github.com/anacrolix/torrent/issues/383.
1491 func (t *Torrent) Stats() TorrentStats {
1493 defer t.cl.rUnlock()
1494 return t.statsLocked()
1497 func (t *Torrent) statsLocked() (ret TorrentStats) {
1498 ret.ActivePeers = len(t.conns)
1499 ret.HalfOpenPeers = len(t.halfOpen)
1500 ret.PendingPeers = t.peers.Len()
1501 ret.TotalPeers = t.numTotalPeers()
1502 ret.ConnectedSeeders = 0
1503 for c := range t.conns {
1504 if all, ok := c.peerHasAllPieces(); all && ok {
1505 ret.ConnectedSeeders++
1508 ret.ConnStats = t.stats.Copy()
1512 // The total number of peers in the torrent.
1513 func (t *Torrent) numTotalPeers() int {
1514 peers := make(map[string]struct{})
1515 for conn := range t.conns {
1516 ra := conn.conn.RemoteAddr()
1518 // It's been closed and doesn't support RemoteAddr.
1521 peers[ra.String()] = struct{}{}
1523 for addr := range t.halfOpen {
1524 peers[addr] = struct{}{}
1526 t.peers.Each(func(peer Peer) {
1527 peers[peer.Addr.String()] = struct{}{}
1532 // Reconcile bytes transferred before connection was associated with a
1534 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1535 if c._stats != (ConnStats{
1536 // Handshakes should only increment these fields:
1537 BytesWritten: c._stats.BytesWritten,
1538 BytesRead: c._stats.BytesRead,
1542 c.postHandshakeStats(func(cs *ConnStats) {
1543 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1544 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1546 c.reconciledHandshakeStats = true
1549 // Returns true if the connection is added.
1550 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1553 torrent.Add("added connections", 1)
1556 if t.closed.IsSet() {
1557 return errors.New("torrent closed")
1559 for c0 := range t.conns {
1560 if c.PeerID != c0.PeerID {
1563 if !t.cl.config.DropDuplicatePeerIds {
1566 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1568 t.deleteConnection(c0)
1570 return errors.New("existing connection preferred")
1573 if len(t.conns) >= t.maxEstablishedConns {
1574 c := t.worstBadConn()
1576 return errors.New("don't want conns")
1579 t.deleteConnection(c)
1581 if len(t.conns) >= t.maxEstablishedConns {
1584 t.conns[c] = struct{}{}
1585 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1586 t.pex.Add(c) // as no further extended handshake expected
1591 func (t *Torrent) wantConns() bool {
1592 if !t.networkingEnabled {
1595 if t.closed.IsSet() {
1598 if !t.seeding() && !t.needData() {
1601 if len(t.conns) < t.maxEstablishedConns {
1604 return t.worstBadConn() != nil
1607 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1610 oldMax = t.maxEstablishedConns
1611 t.maxEstablishedConns = max
1612 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1613 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1614 t.dropConnection(wcs.Pop().(*PeerConn))
1620 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1621 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).WithValues(debugLogValue))
1624 t.cl.event.Broadcast()
1625 if t.closed.IsSet() {
1629 // Don't score the first time a piece is hashed, it could be an initial check.
1630 if p.storageCompletionOk {
1632 pieceHashedCorrect.Add(1)
1634 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1635 pieceHashedNotCorrect.Add(1)
1640 if len(p.dirtiers) != 0 {
1641 // Don't increment stats above connection-level for every involved connection.
1642 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1644 for c := range p.dirtiers {
1645 c._stats.incrementPiecesDirtiedGood()
1647 t.clearPieceTouchers(piece)
1648 err := p.Storage().MarkComplete()
1650 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1652 t.pendAllChunkSpecs(piece)
1654 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1655 // Peers contributed to all the data for this piece hash failure, and the failure was
1656 // not due to errors in the storage (such as data being dropped in a cache).
1658 // Increment Torrent and above stats, and then specific connections.
1659 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1660 for c := range p.dirtiers {
1661 // Y u do dis peer?!
1662 c.stats().incrementPiecesDirtiedBad()
1665 bannableTouchers := make([]*PeerConn, 0, len(p.dirtiers))
1666 for c := range p.dirtiers {
1668 bannableTouchers = append(bannableTouchers, c)
1671 t.clearPieceTouchers(piece)
1672 slices.Sort(bannableTouchers, connLessTrusted)
1674 if t.cl.config.Debug {
1676 "bannable conns by trust for piece %d: %v",
1678 func() (ret []connectionTrust) {
1679 for _, c := range bannableTouchers {
1680 ret = append(ret, c.trust())
1687 if len(bannableTouchers) >= 1 {
1688 c := bannableTouchers[0]
1689 t.cl.banPeerIP(c.remoteIp())
1693 t.onIncompletePiece(piece)
1694 p.Storage().MarkNotComplete()
1696 t.updatePieceCompletion(piece)
1699 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1700 // TODO: Make faster
1701 for cn := range t.conns {
1706 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1707 t.pendAllChunkSpecs(piece)
1708 t.cancelRequestsForPiece(piece)
1709 for conn := range t.conns {
1714 // Called when a piece is found to be not complete.
1715 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1716 if t.pieceAllDirty(piece) {
1717 t.pendAllChunkSpecs(piece)
1719 if !t.wantPieceIndex(piece) {
1720 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1723 // We could drop any connections that we told we have a piece that we
1724 // don't here. But there's a test failure, and it seems clients don't care
1725 // if you request pieces that you already claim to have. Pruning bad
1726 // connections might just remove any connections that aren't treating us
1727 // favourably anyway.
1729 // for c := range t.conns {
1730 // if c.sentHave(piece) {
1734 for conn := range t.conns {
1735 if conn.peerHasPiece(piece) {
1736 conn.updateRequests()
1741 func (t *Torrent) tryCreateMorePieceHashers() {
1742 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1746 func (t *Torrent) tryCreatePieceHasher() bool {
1747 if t.storage == nil {
1750 pi, ok := t.getPieceToHash()
1755 t.piecesQueuedForHash.Remove(pi)
1757 t.publishPieceChange(pi)
1758 t.updatePiecePriority(pi)
1759 t.storageLock.RLock()
1760 t.activePieceHashes++
1761 go t.pieceHasher(pi)
1765 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1766 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1767 if t.piece(i).hashing {
1777 func (t *Torrent) pieceHasher(index pieceIndex) {
1779 sum, copyErr := t.hashPiece(index)
1780 correct := sum == *p.hash
1784 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1786 t.storageLock.RUnlock()
1790 t.updatePiecePriority(index)
1791 t.pieceHashed(index, correct, copyErr)
1792 t.publishPieceChange(index)
1793 t.activePieceHashes--
1794 t.tryCreateMorePieceHashers()
1797 // Return the connections that touched a piece, and clear the entries while doing it.
1798 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1800 for c := range p.dirtiers {
1801 delete(c.peerTouchedPieces, pi)
1802 delete(p.dirtiers, c)
1806 func (t *Torrent) connsAsSlice() (ret []*PeerConn) {
1807 for c := range t.conns {
1808 ret = append(ret, c)
1813 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1814 piece := t.piece(pieceIndex)
1815 if piece.queuedForHash() {
1818 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1819 t.publishPieceChange(pieceIndex)
1820 t.updatePiecePriority(pieceIndex)
1821 t.tryCreateMorePieceHashers()
1824 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1825 // before the Info is available.
1826 func (t *Torrent) VerifyData() {
1827 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1828 t.Piece(i).VerifyData()
1832 // Start the process of connecting to the given peer for the given torrent if appropriate.
1833 func (t *Torrent) initiateConn(peer Peer) {
1834 if peer.Id == t.cl.peerID {
1838 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1842 if t.addrActive(addr.String()) {
1845 t.halfOpen[addr.String()] = peer
1846 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1849 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1850 // quickly make one Client visible to the Torrent of another Client.
1851 func (t *Torrent) AddClientPeer(cl *Client) int {
1852 return t.AddPeers(func() (ps []Peer) {
1853 for _, la := range cl.ListenAddrs() {
1854 ps = append(ps, Peer{
1863 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1865 func (t *Torrent) allStats(f func(*ConnStats)) {
1870 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1871 return t.pieces[i].hashing
1874 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1875 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1878 func (t *Torrent) dialTimeout() time.Duration {
1879 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1882 func (t *Torrent) piece(i int) *Piece {
1886 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1890 type torrentRequestStrategyCallbacks struct {
1894 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
1895 torrent.Add("request timeouts", 1)
1897 defer cb.t.cl.unlock()
1898 for cn := range cb.t.conns {
1899 if cn.peerHasPiece(pieceIndex(r.Index)) {
1906 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
1907 return torrentRequestStrategyCallbacks{t}
1910 func (t *Torrent) onWriteChunkErr(err error) {
1911 if t.userOnWriteChunkErr != nil {
1912 go t.userOnWriteChunkErr(err)
1915 t.disallowDataDownloadLocked()
1918 func (t *Torrent) DisallowDataDownload() {
1921 t.disallowDataDownloadLocked()
1924 func (t *Torrent) disallowDataDownloadLocked() {
1925 log.Printf("disallowing data download")
1926 t.dataDownloadDisallowed = true
1927 for c := range t.conns {
1932 func (t *Torrent) AllowDataDownload() {
1935 log.Printf("AllowDataDownload")
1936 t.dataDownloadDisallowed = false
1937 for c := range t.conns {
1943 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
1946 t.userOnWriteChunkErr = f