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) haveChunk(r request) (ret bool) {
831 // log.Println("have chunk", r, ret)
836 if t.pieceComplete(pieceIndex(r.Index)) {
839 p := &t.pieces[r.Index]
840 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
843 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
844 return int(cs.Begin / chunkSize)
847 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
851 if index < 0 || index >= t.numPieces() {
854 p := &t.pieces[index]
855 if p.queuedForHash() {
861 if t.pieceComplete(index) {
864 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
867 // t.logger.Printf("piece %d not pending", index)
868 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
869 return index < begin || index >= end
873 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
874 // connection is one that usually sends us unwanted pieces, or has been in worser half of the
875 // established connections for more than a minute.
876 func (t *Torrent) worstBadConn() *PeerConn {
877 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
880 c := heap.Pop(&wcs).(*PeerConn)
881 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
884 // If the connection is in the worst half of the established
885 // connection quota and is older than a minute.
886 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
887 // Give connections 1 minute to prove themselves.
888 if time.Since(c.completedHandshake) > time.Minute {
896 type PieceStateChange struct {
901 func (t *Torrent) publishPieceChange(piece pieceIndex) {
902 t.cl._mu.Defer(func() {
903 cur := t.pieceState(piece)
904 p := &t.pieces[piece]
905 if cur != p.publicPieceState {
906 p.publicPieceState = cur
907 t.pieceStateChanges.Publish(PieceStateChange{
915 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
916 if t.pieceComplete(piece) {
919 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
922 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
923 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
926 func (t *Torrent) readersChanged() {
927 t.updateReaderPieces()
928 t.updateAllPiecePriorities()
931 func (t *Torrent) updateReaderPieces() {
932 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
935 func (t *Torrent) readerPosChanged(from, to pieceRange) {
939 t.updateReaderPieces()
940 // Order the ranges, high and low.
942 if l.begin > h.begin {
946 // Two distinct ranges.
947 t.updatePiecePriorities(l.begin, l.end)
948 t.updatePiecePriorities(h.begin, h.end)
955 t.updatePiecePriorities(l.begin, end)
959 func (t *Torrent) maybeNewConns() {
960 // Tickle the accept routine.
961 t.cl.event.Broadcast()
965 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
966 // t.logger.Printf("piece %d priority changed", piece)
967 t.iterPeers(func(c *peer) {
968 if c.updatePiecePriority(piece) {
969 // log.Print("conn piece priority changed")
974 t.publishPieceChange(piece)
977 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
978 p := &t.pieces[piece]
979 newPrio := p.uncachedPriority()
980 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
981 if newPrio == PiecePriorityNone {
982 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
986 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
990 t.piecePriorityChanged(piece)
993 func (t *Torrent) updateAllPiecePriorities() {
994 t.updatePiecePriorities(0, t.numPieces())
997 // Update all piece priorities in one hit. This function should have the same
998 // output as updatePiecePriority, but across all pieces.
999 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
1000 for i := begin; i < end; i++ {
1001 t.updatePiecePriority(i)
1005 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1006 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1007 if off >= *t.length {
1017 begin = pieceIndex(off / t.info.PieceLength)
1018 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1019 if end > pieceIndex(t.info.NumPieces()) {
1020 end = pieceIndex(t.info.NumPieces())
1025 // Returns true if all iterations complete without breaking. Returns the read
1026 // regions for all readers. The reader regions should not be merged as some
1027 // callers depend on this method to enumerate readers.
1028 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1029 for r := range t.readers {
1031 if p.begin >= p.end {
1034 if !f(p.begin, p.end) {
1041 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1042 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1044 return PiecePriorityNone
1049 ret := piecePriority(-prio)
1050 if ret == PiecePriorityNone {
1056 func (t *Torrent) pendRequest(req request) {
1057 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1058 t.pieces[req.Index].pendChunkIndex(ci)
1061 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1063 t.cl.event.Broadcast()
1064 if t.pieceComplete(piece) {
1065 t.onPieceCompleted(piece)
1067 t.onIncompletePiece(piece)
1069 t.updatePiecePriority(piece)
1072 func (t *Torrent) numReceivedConns() (ret int) {
1073 for c := range t.conns {
1074 if c.Discovery == PeerSourceIncoming {
1081 func (t *Torrent) maxHalfOpen() int {
1082 // Note that if we somehow exceed the maximum established conns, we want
1083 // the negative value to have an effect.
1084 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1085 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1086 // We want to allow some experimentation with new peers, and to try to
1087 // upset an oversupply of received connections.
1088 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1091 func (t *Torrent) openNewConns() (initiated int) {
1092 defer t.updateWantPeersEvent()
1093 for t.peers.Len() != 0 {
1097 if len(t.halfOpen) >= t.maxHalfOpen() {
1100 if len(t.cl.dialers) == 0 {
1103 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1106 p := t.peers.PopMax()
1113 func (t *Torrent) getConnPieceInclination() []int {
1114 _ret := t.connPieceInclinationPool.Get()
1116 pieceInclinationsNew.Add(1)
1117 return rand.Perm(int(t.numPieces()))
1119 pieceInclinationsReused.Add(1)
1120 return *_ret.(*[]int)
1123 func (t *Torrent) putPieceInclination(pi []int) {
1124 t.connPieceInclinationPool.Put(&pi)
1125 pieceInclinationsPut.Add(1)
1128 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1130 uncached := t.pieceCompleteUncached(piece)
1131 cached := p.completion()
1132 changed := cached != uncached
1133 complete := uncached.Complete
1134 p.storageCompletionOk = uncached.Ok
1135 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1136 if complete && len(p.dirtiers) != 0 {
1137 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1140 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1141 t.pieceCompletionChanged(piece)
1146 // Non-blocking read. Client lock is not required.
1147 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1149 p := &t.pieces[off/t.info.PieceLength]
1150 p.waitNoPendingWrites()
1152 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1163 // Returns an error if the metadata was completed, but couldn't be set for
1164 // some reason. Blame it on the last peer to contribute.
1165 func (t *Torrent) maybeCompleteMetadata() error {
1170 if !t.haveAllMetadataPieces() {
1171 // Don't have enough metadata pieces.
1174 err := t.setInfoBytes(t.metadataBytes)
1176 t.invalidateMetadata()
1177 return fmt.Errorf("error setting info bytes: %s", err)
1179 if t.cl.config.Debug {
1180 t.logger.Printf("%s: got metadata from peers", t)
1185 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1186 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1188 now.Add(bitmap.BitIndex(begin))
1189 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1196 func (t *Torrent) needData() bool {
1197 if t.closed.IsSet() {
1203 return t._pendingPieces.Len() != 0
1206 func appendMissingStrings(old, new []string) (ret []string) {
1209 for _, n := range new {
1210 for _, o := range old {
1215 ret = append(ret, n)
1220 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1222 for minNumTiers > len(ret) {
1223 ret = append(ret, nil)
1228 func (t *Torrent) addTrackers(announceList [][]string) {
1229 fullAnnounceList := &t.metainfo.AnnounceList
1230 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1231 for tierIndex, trackerURLs := range announceList {
1232 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1234 t.startMissingTrackerScrapers()
1235 t.updateWantPeersEvent()
1238 // Don't call this before the info is available.
1239 func (t *Torrent) bytesCompleted() int64 {
1243 return t.info.TotalLength() - t.bytesLeft()
1246 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1249 return t.setInfoBytes(b)
1252 // Returns true if connection is removed from torrent.Conns.
1253 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1254 if !c.closed.IsSet() {
1255 panic("connection is not closed")
1256 // There are behaviours prevented by the closed state that will fail
1257 // if the connection has been deleted.
1261 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1262 // the drop event against the PexConnState instead.
1264 if !t.cl.config.DisablePEX {
1268 torrent.Add("deleted connections", 1)
1269 c.deleteAllRequests()
1270 if t.numActivePeers() == 0 {
1271 t.assertNoPendingRequests()
1276 func (t *Torrent) numActivePeers() (num int) {
1277 t.iterPeers(func(*peer) {
1283 func (t *Torrent) assertNoPendingRequests() {
1284 if len(t.pendingRequests) != 0 {
1285 panic(t.pendingRequests)
1287 //if len(t.lastRequested) != 0 {
1288 // panic(t.lastRequested)
1292 func (t *Torrent) dropConnection(c *PeerConn) {
1293 t.cl.event.Broadcast()
1295 if t.deleteConnection(c) {
1300 func (t *Torrent) wantPeers() bool {
1301 if t.closed.IsSet() {
1304 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1307 return t.needData() || t.seeding()
1310 func (t *Torrent) updateWantPeersEvent() {
1312 t.wantPeersEvent.Set()
1314 t.wantPeersEvent.Clear()
1318 // Returns whether the client should make effort to seed the torrent.
1319 func (t *Torrent) seeding() bool {
1321 if t.closed.IsSet() {
1324 if t.dataUploadDisallowed {
1327 if cl.config.NoUpload {
1330 if !cl.config.Seed {
1333 if cl.config.DisableAggressiveUpload && t.needData() {
1339 func (t *Torrent) onWebRtcConn(
1340 c datachannel.ReadWriteCloser,
1341 dcc webtorrent.DataChannelContext,
1344 pc, err := t.cl.initiateProtocolHandshakes(
1345 context.Background(),
1346 webrtcNetConn{c, dcc},
1350 webrtcNetAddr{dcc.Remote},
1352 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1355 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1358 if dcc.LocalOffered {
1359 pc.Discovery = PeerSourceTracker
1361 pc.Discovery = PeerSourceIncoming
1365 err = t.cl.runHandshookConn(pc, t)
1367 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1371 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1372 err := t.cl.runHandshookConn(pc, t)
1373 if err != nil || logAll {
1374 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1378 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1379 t.logRunHandshookConn(pc, false, log.Debug)
1382 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1383 wtc, release := t.cl.websocketTrackers.Get(u.String())
1385 <-t.closed.LockedChan(t.cl.locker())
1388 wst := websocketTrackerStatus{u, wtc}
1390 err := wtc.Announce(tracker.Started, t.infoHash)
1392 t.logger.WithDefaultLevel(log.Warning).Printf(
1393 "error in initial announce to %q: %v",
1402 func (t *Torrent) startScrapingTracker(_url string) {
1406 u, err := url.Parse(_url)
1408 // URLs with a leading '*' appear to be a uTorrent convention to
1409 // disable trackers.
1411 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1415 if u.Scheme == "udp" {
1417 t.startScrapingTracker(u.String())
1419 t.startScrapingTracker(u.String())
1422 if _, ok := t.trackerAnnouncers[_url]; ok {
1425 sl := func() torrentTrackerAnnouncer {
1428 if t.cl.config.DisableWebtorrent {
1431 return t.startWebsocketAnnouncer(*u)
1433 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1437 if t.cl.config.DisableIPv6 {
1441 newAnnouncer := &trackerScraper{
1445 go newAnnouncer.Run()
1451 if t.trackerAnnouncers == nil {
1452 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1454 t.trackerAnnouncers[_url] = sl
1457 // Adds and starts tracker scrapers for tracker URLs that aren't already
1459 func (t *Torrent) startMissingTrackerScrapers() {
1460 if t.cl.config.DisableTrackers {
1463 t.startScrapingTracker(t.metainfo.Announce)
1464 for _, tier := range t.metainfo.AnnounceList {
1465 for _, url := range tier {
1466 t.startScrapingTracker(url)
1471 // Returns an AnnounceRequest with fields filled out to defaults and current
1473 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1474 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1475 // dependent on the network in use.
1476 return tracker.AnnounceRequest{
1478 NumWant: func() int32 {
1479 if t.wantPeers() && len(t.cl.dialers) > 0 {
1485 Port: uint16(t.cl.incomingPeerPort()),
1486 PeerId: t.cl.peerID,
1487 InfoHash: t.infoHash,
1488 Key: t.cl.announceKey(),
1490 // The following are vaguely described in BEP 3.
1492 Left: t.bytesLeftAnnounce(),
1493 Uploaded: t.stats.BytesWrittenData.Int64(),
1494 // There's no mention of wasted or unwanted download in the BEP.
1495 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1499 // Adds peers revealed in an announce until the announce ends, or we have
1501 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1503 for v := range pvs {
1505 for _, cp := range v.Peers {
1507 // Can't do anything with this.
1511 Addr: ipPortAddr{cp.IP, cp.Port},
1512 Source: PeerSourceDhtGetPeers,
1519 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1520 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1524 go t.consumeDhtAnnouncePeers(ps.Peers())
1526 case <-t.closed.LockedChan(t.cl.locker()):
1527 case <-time.After(5 * time.Minute):
1533 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1539 if t.closed.IsSet() {
1545 // TODO: Determine if there's a listener on the port we're announcing.
1546 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1557 err := t.announceToDht(true, s)
1559 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1565 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1566 for _, p := range peers {
1574 // The returned TorrentStats may require alignment in memory. See
1575 // https://github.com/anacrolix/torrent/issues/383.
1576 func (t *Torrent) Stats() TorrentStats {
1578 defer t.cl.rUnlock()
1579 return t.statsLocked()
1582 func (t *Torrent) statsLocked() (ret TorrentStats) {
1583 ret.ActivePeers = len(t.conns)
1584 ret.HalfOpenPeers = len(t.halfOpen)
1585 ret.PendingPeers = t.peers.Len()
1586 ret.TotalPeers = t.numTotalPeers()
1587 ret.ConnectedSeeders = 0
1588 for c := range t.conns {
1589 if all, ok := c.peerHasAllPieces(); all && ok {
1590 ret.ConnectedSeeders++
1593 ret.ConnStats = t.stats.Copy()
1597 // The total number of peers in the torrent.
1598 func (t *Torrent) numTotalPeers() int {
1599 peers := make(map[string]struct{})
1600 for conn := range t.conns {
1601 ra := conn.conn.RemoteAddr()
1603 // It's been closed and doesn't support RemoteAddr.
1606 peers[ra.String()] = struct{}{}
1608 for addr := range t.halfOpen {
1609 peers[addr] = struct{}{}
1611 t.peers.Each(func(peer PeerInfo) {
1612 peers[peer.Addr.String()] = struct{}{}
1617 // Reconcile bytes transferred before connection was associated with a
1619 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1620 if c._stats != (ConnStats{
1621 // Handshakes should only increment these fields:
1622 BytesWritten: c._stats.BytesWritten,
1623 BytesRead: c._stats.BytesRead,
1627 c.postHandshakeStats(func(cs *ConnStats) {
1628 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1629 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1631 c.reconciledHandshakeStats = true
1634 // Returns true if the connection is added.
1635 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1638 torrent.Add("added connections", 1)
1641 if t.closed.IsSet() {
1642 return errors.New("torrent closed")
1644 for c0 := range t.conns {
1645 if c.PeerID != c0.PeerID {
1648 if !t.cl.config.DropDuplicatePeerIds {
1651 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1653 t.deleteConnection(c0)
1655 return errors.New("existing connection preferred")
1658 if len(t.conns) >= t.maxEstablishedConns {
1659 c := t.worstBadConn()
1661 return errors.New("don't want conns")
1664 t.deleteConnection(c)
1666 if len(t.conns) >= t.maxEstablishedConns {
1669 t.conns[c] = struct{}{}
1670 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1671 t.pex.Add(c) // as no further extended handshake expected
1676 func (t *Torrent) wantConns() bool {
1677 if !t.networkingEnabled {
1680 if t.closed.IsSet() {
1683 if !t.seeding() && !t.needData() {
1686 if len(t.conns) < t.maxEstablishedConns {
1689 return t.worstBadConn() != nil
1692 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1695 oldMax = t.maxEstablishedConns
1696 t.maxEstablishedConns = max
1697 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1698 return worseConn(&l.peer, &r.peer)
1700 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1701 t.dropConnection(wcs.Pop().(*PeerConn))
1707 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1708 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1711 t.cl.event.Broadcast()
1712 if t.closed.IsSet() {
1716 // Don't score the first time a piece is hashed, it could be an initial check.
1717 if p.storageCompletionOk {
1719 pieceHashedCorrect.Add(1)
1721 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1722 pieceHashedNotCorrect.Add(1)
1727 t.publishPieceChange(piece)
1730 t.publishPieceChange(piece)
1734 if len(p.dirtiers) != 0 {
1735 // Don't increment stats above connection-level for every involved connection.
1736 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1738 for c := range p.dirtiers {
1739 c._stats.incrementPiecesDirtiedGood()
1741 t.clearPieceTouchers(piece)
1743 err := p.Storage().MarkComplete()
1745 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1749 if t.closed.IsSet() {
1752 t.pendAllChunkSpecs(piece)
1754 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1755 // Peers contributed to all the data for this piece hash failure, and the failure was
1756 // not due to errors in the storage (such as data being dropped in a cache).
1758 // Increment Torrent and above stats, and then specific connections.
1759 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1760 for c := range p.dirtiers {
1761 // Y u do dis peer?!
1762 c.stats().incrementPiecesDirtiedBad()
1765 bannableTouchers := make([]*peer, 0, len(p.dirtiers))
1766 for c := range p.dirtiers {
1768 bannableTouchers = append(bannableTouchers, c)
1771 t.clearPieceTouchers(piece)
1772 slices.Sort(bannableTouchers, connLessTrusted)
1774 if t.cl.config.Debug {
1776 "bannable conns by trust for piece %d: %v",
1778 func() (ret []connectionTrust) {
1779 for _, c := range bannableTouchers {
1780 ret = append(ret, c.trust())
1787 if len(bannableTouchers) >= 1 {
1788 c := bannableTouchers[0]
1789 t.cl.banPeerIP(c.remoteIp())
1793 t.onIncompletePiece(piece)
1794 p.Storage().MarkNotComplete()
1796 t.updatePieceCompletion(piece)
1799 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1800 // TODO: Make faster
1801 for cn := range t.conns {
1806 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1807 t.pendAllChunkSpecs(piece)
1808 t.cancelRequestsForPiece(piece)
1809 for conn := range t.conns {
1814 // Called when a piece is found to be not complete.
1815 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1816 if t.pieceAllDirty(piece) {
1817 t.pendAllChunkSpecs(piece)
1819 if !t.wantPieceIndex(piece) {
1820 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1823 // We could drop any connections that we told we have a piece that we
1824 // don't here. But there's a test failure, and it seems clients don't care
1825 // if you request pieces that you already claim to have. Pruning bad
1826 // connections might just remove any connections that aren't treating us
1827 // favourably anyway.
1829 // for c := range t.conns {
1830 // if c.sentHave(piece) {
1834 t.iterPeers(func(conn *peer) {
1835 if conn.peerHasPiece(piece) {
1836 conn.updateRequests()
1841 func (t *Torrent) tryCreateMorePieceHashers() {
1842 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1846 func (t *Torrent) tryCreatePieceHasher() bool {
1847 if t.storage == nil {
1850 pi, ok := t.getPieceToHash()
1855 t.piecesQueuedForHash.Remove(pi)
1857 t.publishPieceChange(pi)
1858 t.updatePiecePriority(pi)
1859 t.storageLock.RLock()
1860 t.activePieceHashes++
1861 go t.pieceHasher(pi)
1865 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1866 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1867 if t.piece(i).hashing {
1877 func (t *Torrent) pieceHasher(index pieceIndex) {
1879 sum, copyErr := t.hashPiece(index)
1880 correct := sum == *p.hash
1884 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1886 t.storageLock.RUnlock()
1890 t.updatePiecePriority(index)
1891 t.pieceHashed(index, correct, copyErr)
1892 t.publishPieceChange(index)
1893 t.activePieceHashes--
1894 t.tryCreateMorePieceHashers()
1897 // Return the connections that touched a piece, and clear the entries while doing it.
1898 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1900 for c := range p.dirtiers {
1901 delete(c.peerTouchedPieces, pi)
1902 delete(p.dirtiers, c)
1906 func (t *Torrent) peersAsSlice() (ret []*peer) {
1907 t.iterPeers(func(p *peer) {
1908 ret = append(ret, p)
1913 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1914 piece := t.piece(pieceIndex)
1915 if piece.queuedForHash() {
1918 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1919 t.publishPieceChange(pieceIndex)
1920 t.updatePiecePriority(pieceIndex)
1921 t.tryCreateMorePieceHashers()
1924 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1925 // before the Info is available.
1926 func (t *Torrent) VerifyData() {
1927 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1928 t.Piece(i).VerifyData()
1932 // Start the process of connecting to the given peer for the given torrent if appropriate.
1933 func (t *Torrent) initiateConn(peer PeerInfo) {
1934 if peer.Id == t.cl.peerID {
1937 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1941 if t.addrActive(addr.String()) {
1945 t.halfOpen[addr.String()] = peer
1946 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1949 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1950 // quickly make one Client visible to the Torrent of another Client.
1951 func (t *Torrent) AddClientPeer(cl *Client) int {
1952 return t.AddPeers(func() (ps []PeerInfo) {
1953 for _, la := range cl.ListenAddrs() {
1954 ps = append(ps, PeerInfo{
1963 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1965 func (t *Torrent) allStats(f func(*ConnStats)) {
1970 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1971 return t.pieces[i].hashing
1974 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1975 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1978 func (t *Torrent) dialTimeout() time.Duration {
1979 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1982 func (t *Torrent) piece(i int) *Piece {
1986 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1990 type torrentRequestStrategyCallbacks struct {
1994 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
1995 torrent.Add("request timeouts", 1)
1997 defer cb.t.cl.unlock()
1998 cb.t.iterPeers(func(cn *peer) {
1999 if cn.peerHasPiece(pieceIndex(r.Index)) {
2006 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
2007 return torrentRequestStrategyCallbacks{t}
2010 func (t *Torrent) onWriteChunkErr(err error) {
2011 if t.userOnWriteChunkErr != nil {
2012 go t.userOnWriteChunkErr(err)
2015 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2016 t.disallowDataDownloadLocked()
2019 func (t *Torrent) DisallowDataDownload() {
2022 t.disallowDataDownloadLocked()
2025 func (t *Torrent) disallowDataDownloadLocked() {
2026 t.dataDownloadDisallowed = true
2027 t.iterPeers(func(c *peer) {
2033 func (t *Torrent) AllowDataDownload() {
2036 t.dataDownloadDisallowed = false
2038 t.iterPeers(func(c *peer) {
2043 // Enables uploading data, if it was disabled.
2044 func (t *Torrent) AllowDataUpload() {
2047 t.dataUploadDisallowed = false
2048 for c := range t.conns {
2053 // Disables uploading data, if it was enabled.
2054 func (t *Torrent) DisallowDataUpload() {
2057 t.dataUploadDisallowed = true
2058 for c := range t.conns {
2063 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2064 // or if nil, a critical message is logged, and data download is disabled.
2065 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2068 t.userOnWriteChunkErr = f
2071 func (t *Torrent) iterPeers(f func(*peer)) {
2072 for pc := range t.conns {
2075 for _, ws := range t.webSeeds {
2080 func (t *Torrent) addWebSeed(url string) {
2081 if t.cl.config.DisableWebseeds {
2084 if _, ok := t.webSeeds[url]; ok {
2087 const maxRequests = 10
2093 reconciledHandshakeStats: true,
2094 peerSentHaveAll: true,
2095 PeerMaxRequests: maxRequests,
2097 client: webseed.Client{
2098 HttpClient: http.DefaultClient,
2101 requests: make(map[request]webseed.Request, maxRequests),
2103 ws.peer.logger = t.logger.WithContextValue(&ws)
2104 ws.peer.peerImpl = &ws
2106 ws.onGotInfo(t.info)
2108 t.webSeeds[url] = &ws.peer
2111 func (t *Torrent) peerIsActive(p *peer) (active bool) {
2112 t.iterPeers(func(p1 *peer) {