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 if p.queuedForHash() || p.hashing {
506 if !ret.Complete && t.piecePartiallyDownloaded(index) {
512 func (t *Torrent) metadataPieceSize(piece int) int {
513 return metadataPieceSize(len(t.metadataBytes), piece)
516 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
522 d["total_size"] = len(t.metadataBytes)
524 p := bencode.MustMarshal(d)
527 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
528 ExtendedPayload: append(p, data...),
532 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
533 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
534 ret = append(ret, PieceStateRun{
535 PieceState: el.(PieceState),
539 for index := range t.pieces {
540 rle.Append(t.pieceState(pieceIndex(index)), 1)
546 // Produces a small string representing a PieceStateRun.
547 func (psr PieceStateRun) String() (ret string) {
548 ret = fmt.Sprintf("%d", psr.Length)
549 ret += func() string {
550 switch psr.Priority {
551 case PiecePriorityNext:
553 case PiecePriorityNormal:
555 case PiecePriorityReadahead:
557 case PiecePriorityNow:
559 case PiecePriorityHigh:
580 func (t *Torrent) writeStatus(w io.Writer) {
581 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
582 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
584 fmt.Fprintf(w, "Metadata have: ")
585 for _, h := range t.metadataCompletedChunks {
586 fmt.Fprintf(w, "%c", func() rune {
596 fmt.Fprintf(w, "Piece length: %s\n", func() string {
598 return fmt.Sprint(t.usualPieceSize())
604 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
605 fmt.Fprintf(w, "Piece States: %s", t.pieceStateRuns())
608 fmt.Fprintf(w, "Reader Pieces:")
609 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
610 fmt.Fprintf(w, " %d:%d", begin, end)
615 fmt.Fprintf(w, "Enabled trackers:\n")
617 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
618 fmt.Fprintf(tw, " URL\tExtra\n")
619 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
622 var luns, runs url.URL = *lu, *ru
625 var ml missinggo.MultiLess
626 ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
627 ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
629 }).([]torrentTrackerAnnouncer) {
630 fmt.Fprintf(tw, " %q\t%v\n", ta.URL(), ta.statusLine())
635 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
637 spew.NewDefaultConfig()
638 spew.Fdump(w, t.statsLocked())
640 peers := t.peersAsSlice()
641 sort.Slice(peers, func(i, j int) bool {
642 return worseConn(peers[i], peers[j])
644 for i, c := range peers {
645 fmt.Fprintf(w, "%2d. ", i+1)
650 func (t *Torrent) haveInfo() bool {
654 // Returns a run-time generated MetaInfo that includes the info bytes and
655 // announce-list as currently known to the client.
656 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
657 return metainfo.MetaInfo{
658 CreationDate: time.Now().Unix(),
659 Comment: "dynamic metainfo from client",
660 CreatedBy: "go.torrent",
661 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
662 InfoBytes: func() []byte {
664 return t.metadataBytes
672 func (t *Torrent) BytesMissing() int64 {
675 return t.bytesMissingLocked()
678 func (t *Torrent) bytesMissingLocked() int64 {
682 func (t *Torrent) bytesLeft() (left int64) {
683 bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
684 p := &t.pieces[piece]
685 left += int64(p.length() - p.numDirtyBytes())
691 // Bytes left to give in tracker announces.
692 func (t *Torrent) bytesLeftAnnounce() int64 {
700 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
701 if t.pieceComplete(piece) {
704 if t.pieceAllDirty(piece) {
707 return t.pieces[piece].hasDirtyChunks()
710 func (t *Torrent) usualPieceSize() int {
711 return int(t.info.PieceLength)
714 func (t *Torrent) numPieces() pieceIndex {
715 return pieceIndex(t.info.NumPieces())
718 func (t *Torrent) numPiecesCompleted() (num int) {
719 return t._completedPieces.Len()
722 func (t *Torrent) close() (err error) {
725 if t.storage != nil {
728 t.storageLock.Unlock()
730 for conn := range t.conns {
734 t.cl.event.Broadcast()
735 t.pieceStateChanges.Close()
736 t.updateWantPeersEvent()
740 func (t *Torrent) requestOffset(r request) int64 {
741 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
744 // Return the request that would include the given offset into the torrent data. Returns !ok if
745 // there is no such request.
746 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
747 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
750 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
751 defer perf.ScopeTimerErr(&err)()
752 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
753 if err == nil && n != len(data) {
754 err = io.ErrShortWrite
759 func (t *Torrent) bitfield() (bf []bool) {
760 bf = make([]bool, t.numPieces())
761 t._completedPieces.IterTyped(func(piece int) (again bool) {
768 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
769 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
772 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
773 t.pieces[pieceIndex]._dirtyChunks.Clear()
776 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
777 if t.info.PieceLength == 0 {
778 // There will be no variance amongst pieces. Only pain.
781 if piece == t.numPieces()-1 {
782 ret := pp.Integer(*t.length % t.info.PieceLength)
787 return pp.Integer(t.info.PieceLength)
790 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
791 hash := pieceHash.New()
793 p.waitNoPendingWrites()
794 storagePiece := t.pieces[piece].Storage()
795 const logPieceContents = false
796 if logPieceContents {
797 var examineBuf bytes.Buffer
798 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
799 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
801 _, err = storagePiece.WriteTo(hash)
803 missinggo.CopyExact(&ret, hash.Sum(nil))
807 func (t *Torrent) haveAnyPieces() bool {
808 return t._completedPieces.Len() != 0
811 func (t *Torrent) haveAllPieces() bool {
815 return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
818 func (t *Torrent) havePiece(index pieceIndex) bool {
819 return t.haveInfo() && t.pieceComplete(index)
822 func (t *Torrent) haveChunk(r request) (ret bool) {
824 // log.Println("have chunk", r, ret)
829 if t.pieceComplete(pieceIndex(r.Index)) {
832 p := &t.pieces[r.Index]
833 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
836 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
837 return int(cs.Begin / chunkSize)
840 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
844 if index < 0 || index >= t.numPieces() {
847 p := &t.pieces[index]
848 if p.queuedForHash() {
854 if t.pieceComplete(index) {
857 if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
860 // t.logger.Printf("piece %d not pending", index)
861 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
862 return index < begin || index >= end
866 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
867 // connection is one that usually sends us unwanted pieces, or has been in worser half of the
868 // established connections for more than a minute.
869 func (t *Torrent) worstBadConn() *PeerConn {
870 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
873 c := heap.Pop(&wcs).(*PeerConn)
874 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
877 // If the connection is in the worst half of the established
878 // connection quota and is older than a minute.
879 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
880 // Give connections 1 minute to prove themselves.
881 if time.Since(c.completedHandshake) > time.Minute {
889 type PieceStateChange struct {
894 func (t *Torrent) publishPieceChange(piece pieceIndex) {
895 t.cl._mu.Defer(func() {
896 cur := t.pieceState(piece)
897 p := &t.pieces[piece]
898 if cur != p.publicPieceState {
899 p.publicPieceState = cur
900 t.pieceStateChanges.Publish(PieceStateChange{
908 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
909 if t.pieceComplete(piece) {
912 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
915 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
916 return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
919 func (t *Torrent) readersChanged() {
920 t.updateReaderPieces()
921 t.updateAllPiecePriorities()
924 func (t *Torrent) updateReaderPieces() {
925 t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
928 func (t *Torrent) readerPosChanged(from, to pieceRange) {
932 t.updateReaderPieces()
933 // Order the ranges, high and low.
935 if l.begin > h.begin {
939 // Two distinct ranges.
940 t.updatePiecePriorities(l.begin, l.end)
941 t.updatePiecePriorities(h.begin, h.end)
948 t.updatePiecePriorities(l.begin, end)
952 func (t *Torrent) maybeNewConns() {
953 // Tickle the accept routine.
954 t.cl.event.Broadcast()
958 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
959 // t.logger.Printf("piece %d priority changed", piece)
960 t.iterPeers(func(c *peer) {
961 if c.updatePiecePriority(piece) {
962 // log.Print("conn piece priority changed")
967 t.publishPieceChange(piece)
970 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
971 p := &t.pieces[piece]
972 newPrio := p.uncachedPriority()
973 // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
974 if newPrio == PiecePriorityNone {
975 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
979 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
983 t.piecePriorityChanged(piece)
986 func (t *Torrent) updateAllPiecePriorities() {
987 t.updatePiecePriorities(0, t.numPieces())
990 // Update all piece priorities in one hit. This function should have the same
991 // output as updatePiecePriority, but across all pieces.
992 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
993 for i := begin; i < end; i++ {
994 t.updatePiecePriority(i)
998 // Returns the range of pieces [begin, end) that contains the extent of bytes.
999 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1000 if off >= *t.length {
1010 begin = pieceIndex(off / t.info.PieceLength)
1011 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1012 if end > pieceIndex(t.info.NumPieces()) {
1013 end = pieceIndex(t.info.NumPieces())
1018 // Returns true if all iterations complete without breaking. Returns the read
1019 // regions for all readers. The reader regions should not be merged as some
1020 // callers depend on this method to enumerate readers.
1021 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1022 for r := range t.readers {
1024 if p.begin >= p.end {
1027 if !f(p.begin, p.end) {
1034 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1035 prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1037 return PiecePriorityNone
1042 ret := piecePriority(-prio)
1043 if ret == PiecePriorityNone {
1049 func (t *Torrent) pendRequest(req request) {
1050 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1051 t.pieces[req.Index].pendChunkIndex(ci)
1054 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1056 t.cl.event.Broadcast()
1057 if t.pieceComplete(piece) {
1058 t.onPieceCompleted(piece)
1060 t.onIncompletePiece(piece)
1062 t.updatePiecePriority(piece)
1065 func (t *Torrent) numReceivedConns() (ret int) {
1066 for c := range t.conns {
1067 if c.Discovery == PeerSourceIncoming {
1074 func (t *Torrent) maxHalfOpen() int {
1075 // Note that if we somehow exceed the maximum established conns, we want
1076 // the negative value to have an effect.
1077 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1078 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1079 // We want to allow some experimentation with new peers, and to try to
1080 // upset an oversupply of received connections.
1081 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1084 func (t *Torrent) openNewConns() (initiated int) {
1085 defer t.updateWantPeersEvent()
1086 for t.peers.Len() != 0 {
1090 if len(t.halfOpen) >= t.maxHalfOpen() {
1093 if len(t.cl.dialers) == 0 {
1096 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1099 p := t.peers.PopMax()
1106 func (t *Torrent) getConnPieceInclination() []int {
1107 _ret := t.connPieceInclinationPool.Get()
1109 pieceInclinationsNew.Add(1)
1110 return rand.Perm(int(t.numPieces()))
1112 pieceInclinationsReused.Add(1)
1113 return *_ret.(*[]int)
1116 func (t *Torrent) putPieceInclination(pi []int) {
1117 t.connPieceInclinationPool.Put(&pi)
1118 pieceInclinationsPut.Add(1)
1121 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1123 uncached := t.pieceCompleteUncached(piece)
1124 cached := p.completion()
1125 changed := cached != uncached
1126 complete := uncached.Complete
1127 p.storageCompletionOk = uncached.Ok
1128 t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1129 if complete && len(p.dirtiers) != 0 {
1130 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1133 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1134 t.pieceCompletionChanged(piece)
1139 // Non-blocking read. Client lock is not required.
1140 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1142 p := &t.pieces[off/t.info.PieceLength]
1143 p.waitNoPendingWrites()
1145 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1156 // Returns an error if the metadata was completed, but couldn't be set for
1157 // some reason. Blame it on the last peer to contribute.
1158 func (t *Torrent) maybeCompleteMetadata() error {
1163 if !t.haveAllMetadataPieces() {
1164 // Don't have enough metadata pieces.
1167 err := t.setInfoBytes(t.metadataBytes)
1169 t.invalidateMetadata()
1170 return fmt.Errorf("error setting info bytes: %s", err)
1172 if t.cl.config.Debug {
1173 t.logger.Printf("%s: got metadata from peers", t)
1178 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1179 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1181 now.Add(bitmap.BitIndex(begin))
1182 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1189 func (t *Torrent) needData() bool {
1190 if t.closed.IsSet() {
1196 return t._pendingPieces.Len() != 0
1199 func appendMissingStrings(old, new []string) (ret []string) {
1202 for _, n := range new {
1203 for _, o := range old {
1208 ret = append(ret, n)
1213 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1215 for minNumTiers > len(ret) {
1216 ret = append(ret, nil)
1221 func (t *Torrent) addTrackers(announceList [][]string) {
1222 fullAnnounceList := &t.metainfo.AnnounceList
1223 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1224 for tierIndex, trackerURLs := range announceList {
1225 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1227 t.startMissingTrackerScrapers()
1228 t.updateWantPeersEvent()
1231 // Don't call this before the info is available.
1232 func (t *Torrent) bytesCompleted() int64 {
1236 return t.info.TotalLength() - t.bytesLeft()
1239 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1242 return t.setInfoBytes(b)
1245 // Returns true if connection is removed from torrent.Conns.
1246 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1247 if !c.closed.IsSet() {
1248 panic("connection is not closed")
1249 // There are behaviours prevented by the closed state that will fail
1250 // if the connection has been deleted.
1254 // Avoid adding a drop event more than once. Probably we should track whether we've generated
1255 // the drop event against the PexConnState instead.
1257 if !t.cl.config.DisablePEX {
1261 torrent.Add("deleted connections", 1)
1262 c.deleteAllRequests()
1263 if t.numActivePeers() == 0 {
1264 t.assertNoPendingRequests()
1269 func (t *Torrent) numActivePeers() (num int) {
1270 t.iterPeers(func(*peer) {
1276 func (t *Torrent) assertNoPendingRequests() {
1277 if len(t.pendingRequests) != 0 {
1278 panic(t.pendingRequests)
1280 //if len(t.lastRequested) != 0 {
1281 // panic(t.lastRequested)
1285 func (t *Torrent) dropConnection(c *PeerConn) {
1286 t.cl.event.Broadcast()
1288 if t.deleteConnection(c) {
1293 func (t *Torrent) wantPeers() bool {
1294 if t.closed.IsSet() {
1297 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1300 return t.needData() || t.seeding()
1303 func (t *Torrent) updateWantPeersEvent() {
1305 t.wantPeersEvent.Set()
1307 t.wantPeersEvent.Clear()
1311 // Returns whether the client should make effort to seed the torrent.
1312 func (t *Torrent) seeding() bool {
1314 if t.closed.IsSet() {
1317 if t.dataUploadDisallowed {
1320 if cl.config.NoUpload {
1323 if !cl.config.Seed {
1326 if cl.config.DisableAggressiveUpload && t.needData() {
1332 func (t *Torrent) onWebRtcConn(
1333 c datachannel.ReadWriteCloser,
1334 dcc webtorrent.DataChannelContext,
1337 pc, err := t.cl.initiateProtocolHandshakes(
1338 context.Background(),
1339 webrtcNetConn{c, dcc},
1343 webrtcNetAddr{dcc.Remote},
1345 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1348 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1351 if dcc.LocalOffered {
1352 pc.Discovery = PeerSourceTracker
1354 pc.Discovery = PeerSourceIncoming
1358 err = t.cl.runHandshookConn(pc, t)
1360 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1364 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1365 err := t.cl.runHandshookConn(pc, t)
1366 if err != nil || logAll {
1367 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1371 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1372 t.logRunHandshookConn(pc, false, log.Debug)
1375 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1376 wtc, release := t.cl.websocketTrackers.Get(u.String())
1378 <-t.closed.LockedChan(t.cl.locker())
1381 wst := websocketTrackerStatus{u, wtc}
1383 err := wtc.Announce(tracker.Started, t.infoHash)
1385 t.logger.WithDefaultLevel(log.Warning).Printf(
1386 "error in initial announce to %q: %v",
1395 func (t *Torrent) startScrapingTracker(_url string) {
1399 u, err := url.Parse(_url)
1401 // URLs with a leading '*' appear to be a uTorrent convention to
1402 // disable trackers.
1404 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1408 if u.Scheme == "udp" {
1410 t.startScrapingTracker(u.String())
1412 t.startScrapingTracker(u.String())
1415 if _, ok := t.trackerAnnouncers[_url]; ok {
1418 sl := func() torrentTrackerAnnouncer {
1421 if t.cl.config.DisableWebtorrent {
1424 return t.startWebsocketAnnouncer(*u)
1426 if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1430 if t.cl.config.DisableIPv6 {
1434 urlString := (*u).String()
1436 newAnnouncer := &trackerScraper{
1442 if cl.activeAnnounces == nil {
1443 cl.activeAnnounces = make(map[string]struct{})
1446 if _, ok := cl.activeAnnounces[urlString]; ok {
1452 cl.activeAnnounces[urlString] = struct{}{}
1454 done: func(slowdown bool) {
1457 delete(cl.activeAnnounces, urlString)
1458 cl.event.Broadcast()
1461 go newAnnouncer.Run()
1467 if t.trackerAnnouncers == nil {
1468 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1470 t.trackerAnnouncers[_url] = sl
1473 // Adds and starts tracker scrapers for tracker URLs that aren't already
1475 func (t *Torrent) startMissingTrackerScrapers() {
1476 if t.cl.config.DisableTrackers {
1479 t.startScrapingTracker(t.metainfo.Announce)
1480 for _, tier := range t.metainfo.AnnounceList {
1481 for _, url := range tier {
1482 t.startScrapingTracker(url)
1487 // Returns an AnnounceRequest with fields filled out to defaults and current
1489 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1490 // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1491 // dependent on the network in use.
1492 return tracker.AnnounceRequest{
1494 NumWant: func() int32 {
1495 if t.wantPeers() && len(t.cl.dialers) > 0 {
1501 Port: uint16(t.cl.incomingPeerPort()),
1502 PeerId: t.cl.peerID,
1503 InfoHash: t.infoHash,
1504 Key: t.cl.announceKey(),
1506 // The following are vaguely described in BEP 3.
1508 Left: t.bytesLeftAnnounce(),
1509 Uploaded: t.stats.BytesWrittenData.Int64(),
1510 // There's no mention of wasted or unwanted download in the BEP.
1511 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1515 // Adds peers revealed in an announce until the announce ends, or we have
1517 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1519 for v := range pvs {
1521 for _, cp := range v.Peers {
1523 // Can't do anything with this.
1527 Addr: ipPortAddr{cp.IP, cp.Port},
1528 Source: PeerSourceDhtGetPeers,
1535 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1536 ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1540 go t.consumeDhtAnnouncePeers(ps.Peers())
1542 case <-t.closed.LockedChan(t.cl.locker()):
1543 case <-time.After(5 * time.Minute):
1549 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1555 if t.closed.IsSet() {
1561 // TODO: Determine if there's a listener on the port we're announcing.
1562 if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1573 err := t.announceToDht(true, s)
1575 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1581 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1582 for _, p := range peers {
1590 // The returned TorrentStats may require alignment in memory. See
1591 // https://github.com/anacrolix/torrent/issues/383.
1592 func (t *Torrent) Stats() TorrentStats {
1594 defer t.cl.rUnlock()
1595 return t.statsLocked()
1598 func (t *Torrent) statsLocked() (ret TorrentStats) {
1599 ret.ActivePeers = len(t.conns)
1600 ret.HalfOpenPeers = len(t.halfOpen)
1601 ret.PendingPeers = t.peers.Len()
1602 ret.TotalPeers = t.numTotalPeers()
1603 ret.ConnectedSeeders = 0
1604 for c := range t.conns {
1605 if all, ok := c.peerHasAllPieces(); all && ok {
1606 ret.ConnectedSeeders++
1609 ret.ConnStats = t.stats.Copy()
1613 // The total number of peers in the torrent.
1614 func (t *Torrent) numTotalPeers() int {
1615 peers := make(map[string]struct{})
1616 for conn := range t.conns {
1617 ra := conn.conn.RemoteAddr()
1619 // It's been closed and doesn't support RemoteAddr.
1622 peers[ra.String()] = struct{}{}
1624 for addr := range t.halfOpen {
1625 peers[addr] = struct{}{}
1627 t.peers.Each(func(peer PeerInfo) {
1628 peers[peer.Addr.String()] = struct{}{}
1633 // Reconcile bytes transferred before connection was associated with a
1635 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1636 if c._stats != (ConnStats{
1637 // Handshakes should only increment these fields:
1638 BytesWritten: c._stats.BytesWritten,
1639 BytesRead: c._stats.BytesRead,
1643 c.postHandshakeStats(func(cs *ConnStats) {
1644 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1645 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1647 c.reconciledHandshakeStats = true
1650 // Returns true if the connection is added.
1651 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1654 torrent.Add("added connections", 1)
1657 if t.closed.IsSet() {
1658 return errors.New("torrent closed")
1660 for c0 := range t.conns {
1661 if c.PeerID != c0.PeerID {
1664 if !t.cl.config.DropDuplicatePeerIds {
1667 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1669 t.deleteConnection(c0)
1671 return errors.New("existing connection preferred")
1674 if len(t.conns) >= t.maxEstablishedConns {
1675 c := t.worstBadConn()
1677 return errors.New("don't want conns")
1680 t.deleteConnection(c)
1682 if len(t.conns) >= t.maxEstablishedConns {
1685 t.conns[c] = struct{}{}
1686 if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1687 t.pex.Add(c) // as no further extended handshake expected
1692 func (t *Torrent) wantConns() bool {
1693 if !t.networkingEnabled {
1696 if t.closed.IsSet() {
1699 if !t.seeding() && !t.needData() {
1702 if len(t.conns) < t.maxEstablishedConns {
1705 return t.worstBadConn() != nil
1708 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1711 oldMax = t.maxEstablishedConns
1712 t.maxEstablishedConns = max
1713 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1714 return worseConn(&l.peer, &r.peer)
1716 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1717 t.dropConnection(wcs.Pop().(*PeerConn))
1723 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1724 t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1727 t.cl.event.Broadcast()
1728 if t.closed.IsSet() {
1732 // Don't score the first time a piece is hashed, it could be an initial check.
1733 if p.storageCompletionOk {
1735 pieceHashedCorrect.Add(1)
1737 log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1738 pieceHashedNotCorrect.Add(1)
1743 if len(p.dirtiers) != 0 {
1744 // Don't increment stats above connection-level for every involved connection.
1745 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1747 for c := range p.dirtiers {
1748 c._stats.incrementPiecesDirtiedGood()
1750 t.clearPieceTouchers(piece)
1752 err := p.Storage().MarkComplete()
1754 t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1758 if t.closed.IsSet() {
1761 t.pendAllChunkSpecs(piece)
1763 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1764 // Peers contributed to all the data for this piece hash failure, and the failure was
1765 // not due to errors in the storage (such as data being dropped in a cache).
1767 // Increment Torrent and above stats, and then specific connections.
1768 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1769 for c := range p.dirtiers {
1770 // Y u do dis peer?!
1771 c.stats().incrementPiecesDirtiedBad()
1774 bannableTouchers := make([]*peer, 0, len(p.dirtiers))
1775 for c := range p.dirtiers {
1777 bannableTouchers = append(bannableTouchers, c)
1780 t.clearPieceTouchers(piece)
1781 slices.Sort(bannableTouchers, connLessTrusted)
1783 if t.cl.config.Debug {
1785 "bannable conns by trust for piece %d: %v",
1787 func() (ret []connectionTrust) {
1788 for _, c := range bannableTouchers {
1789 ret = append(ret, c.trust())
1796 if len(bannableTouchers) >= 1 {
1797 c := bannableTouchers[0]
1798 t.cl.banPeerIP(c.remoteIp())
1802 t.onIncompletePiece(piece)
1803 p.Storage().MarkNotComplete()
1805 t.updatePieceCompletion(piece)
1808 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1809 // TODO: Make faster
1810 for cn := range t.conns {
1815 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1816 t.pendAllChunkSpecs(piece)
1817 t.cancelRequestsForPiece(piece)
1818 for conn := range t.conns {
1823 // Called when a piece is found to be not complete.
1824 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1825 if t.pieceAllDirty(piece) {
1826 t.pendAllChunkSpecs(piece)
1828 if !t.wantPieceIndex(piece) {
1829 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1832 // We could drop any connections that we told we have a piece that we
1833 // don't here. But there's a test failure, and it seems clients don't care
1834 // if you request pieces that you already claim to have. Pruning bad
1835 // connections might just remove any connections that aren't treating us
1836 // favourably anyway.
1838 // for c := range t.conns {
1839 // if c.sentHave(piece) {
1843 t.iterPeers(func(conn *peer) {
1844 if conn.peerHasPiece(piece) {
1845 conn.updateRequests()
1850 func (t *Torrent) tryCreateMorePieceHashers() {
1851 for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1855 func (t *Torrent) tryCreatePieceHasher() bool {
1856 if t.storage == nil {
1859 pi, ok := t.getPieceToHash()
1864 t.piecesQueuedForHash.Remove(pi)
1866 t.publishPieceChange(pi)
1867 t.updatePiecePriority(pi)
1868 t.storageLock.RLock()
1869 t.activePieceHashes++
1870 go t.pieceHasher(pi)
1874 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1875 t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1876 if t.piece(i).hashing {
1886 func (t *Torrent) pieceHasher(index pieceIndex) {
1888 sum, copyErr := t.hashPiece(index)
1889 correct := sum == *p.hash
1893 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1895 t.storageLock.RUnlock()
1899 t.updatePiecePriority(index)
1900 t.pieceHashed(index, correct, copyErr)
1901 t.publishPieceChange(index)
1902 t.activePieceHashes--
1903 t.tryCreateMorePieceHashers()
1906 // Return the connections that touched a piece, and clear the entries while doing it.
1907 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1909 for c := range p.dirtiers {
1910 delete(c.peerTouchedPieces, pi)
1911 delete(p.dirtiers, c)
1915 func (t *Torrent) peersAsSlice() (ret []*peer) {
1916 t.iterPeers(func(p *peer) {
1917 ret = append(ret, p)
1922 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1923 piece := t.piece(pieceIndex)
1924 if piece.queuedForHash() {
1927 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1928 t.publishPieceChange(pieceIndex)
1929 t.updatePiecePriority(pieceIndex)
1930 t.tryCreateMorePieceHashers()
1933 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1934 // before the Info is available.
1935 func (t *Torrent) VerifyData() {
1936 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1937 t.Piece(i).VerifyData()
1941 // Start the process of connecting to the given peer for the given torrent if appropriate.
1942 func (t *Torrent) initiateConn(peer PeerInfo) {
1943 if peer.Id == t.cl.peerID {
1946 if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1950 if t.addrActive(addr.String()) {
1954 t.halfOpen[addr.String()] = peer
1955 go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1958 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1959 // quickly make one Client visible to the Torrent of another Client.
1960 func (t *Torrent) AddClientPeer(cl *Client) int {
1961 return t.AddPeers(func() (ps []PeerInfo) {
1962 for _, la := range cl.ListenAddrs() {
1963 ps = append(ps, PeerInfo{
1972 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1974 func (t *Torrent) allStats(f func(*ConnStats)) {
1979 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1980 return t.pieces[i].hashing
1983 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1984 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1987 func (t *Torrent) dialTimeout() time.Duration {
1988 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1991 func (t *Torrent) piece(i int) *Piece {
1995 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1999 type torrentRequestStrategyCallbacks struct {
2003 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
2004 torrent.Add("request timeouts", 1)
2006 defer cb.t.cl.unlock()
2007 cb.t.iterPeers(func(cn *peer) {
2008 if cn.peerHasPiece(pieceIndex(r.Index)) {
2015 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
2016 return torrentRequestStrategyCallbacks{t}
2019 func (t *Torrent) onWriteChunkErr(err error) {
2020 if t.userOnWriteChunkErr != nil {
2021 go t.userOnWriteChunkErr(err)
2024 t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2025 t.disallowDataDownloadLocked()
2028 func (t *Torrent) DisallowDataDownload() {
2031 t.disallowDataDownloadLocked()
2034 func (t *Torrent) disallowDataDownloadLocked() {
2035 t.dataDownloadDisallowed = true
2036 t.iterPeers(func(c *peer) {
2042 func (t *Torrent) AllowDataDownload() {
2045 t.dataDownloadDisallowed = false
2047 t.iterPeers(func(c *peer) {
2052 // Enables uploading data, if it was disabled.
2053 func (t *Torrent) AllowDataUpload() {
2056 t.dataUploadDisallowed = false
2057 for c := range t.conns {
2062 // Disables uploading data, if it was enabled.
2063 func (t *Torrent) DisallowDataUpload() {
2066 t.dataUploadDisallowed = true
2067 for c := range t.conns {
2072 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2073 // or if nil, a critical message is logged, and data download is disabled.
2074 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2077 t.userOnWriteChunkErr = f
2080 func (t *Torrent) iterPeers(f func(*peer)) {
2081 for pc := range t.conns {
2084 for _, ws := range t.webSeeds {
2089 func (t *Torrent) addWebSeed(url string) {
2090 if t.cl.config.DisableWebseeds {
2093 if _, ok := t.webSeeds[url]; ok {
2096 const maxRequests = 10
2102 reconciledHandshakeStats: true,
2103 peerSentHaveAll: true,
2104 PeerMaxRequests: maxRequests,
2106 client: webseed.Client{
2107 HttpClient: http.DefaultClient,
2110 requests: make(map[request]webseed.Request, maxRequests),
2112 ws.peer.logger = t.logger.WithContextValue(&ws)
2113 ws.peer.peerImpl = &ws
2115 ws.onGotInfo(t.info)
2117 t.webSeeds[url] = &ws.peer
2120 func (t *Torrent) peerIsActive(p *peer) (active bool) {
2121 t.iterPeers(func(p1 *peer) {