18 "github.com/anacrolix/dht"
19 "github.com/anacrolix/log"
20 "github.com/anacrolix/missinggo"
21 "github.com/anacrolix/missinggo/bitmap"
22 "github.com/anacrolix/missinggo/perf"
23 "github.com/anacrolix/missinggo/prioritybitmap"
24 "github.com/anacrolix/missinggo/pubsub"
25 "github.com/anacrolix/missinggo/slices"
26 "github.com/anacrolix/torrent/bencode"
27 "github.com/anacrolix/torrent/metainfo"
28 pp "github.com/anacrolix/torrent/peer_protocol"
29 "github.com/anacrolix/torrent/storage"
30 "github.com/anacrolix/torrent/tracker"
31 "github.com/davecgh/go-spew/spew"
34 func (t *Torrent) chunkIndexSpec(chunkIndex pp.Integer, piece pieceIndex) chunkSpec {
35 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
38 type peersKey struct {
43 // Maintains state of torrent within a Client.
45 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
46 // alignment. See #262.
51 networkingEnabled bool
53 // Determines what chunks to request from peers. 1: Favour higher priority
54 // pieces with some fuzzing to reduce overlaps and wastage across
55 // connections. 2: The fastest connection downloads strictly in order of
56 // priority, while all others adher to their piece inclications. 3:
57 // Requests are strictly by piece priority, and not duplicated until
58 // duplicateRequestTimeout is reached.
60 // How long to avoid duplicating a pending request.
61 duplicateRequestTimeout time.Duration
63 closed missinggo.Event
64 infoHash metainfo.Hash
66 // Values are the piece indices that changed.
67 pieceStateChanges *pubsub.PubSub
68 // The size of chunks to request from peers over the wire. This is
69 // normally 16KiB by convention these days.
72 // Total length of the torrent in bytes. Stored because it's not O(1) to
73 // get this from the info dict.
76 // The storage to open when the info dict becomes available.
77 storageOpener *storage.Client
78 // Storage for torrent data.
79 storage *storage.Torrent
80 // Read-locked for using storage, and write-locked for Closing.
81 storageLock sync.RWMutex
83 // TODO: Only announce stuff is used?
84 metainfo metainfo.MetaInfo
86 // The info dict. nil if we don't have it (yet).
90 // Active peer connections, running message stream loops. TODO: Make this
91 // open (not-closed) connections only.
92 conns map[*connection]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]Peer
97 fastestConn *connection
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 wantPeersEvent missinggo.Event
105 // An announcer for each tracker URL.
106 trackerAnnouncers map[string]*trackerScraper
107 // How many times we've initiated a DHT announce. TODO: Move into stats.
110 // Name used if the info name isn't available. Should be cleared when the
111 // Info does become available.
114 // The bencoded bytes of the info dict. This is actively manipulated if
115 // the info bytes aren't initially available, and we try to fetch them
118 // Each element corresponds to the 16KiB metadata pieces. If true, we have
119 // received that piece.
120 metadataCompletedChunks []bool
121 metadataChanged sync.Cond
123 // Set when .Info is obtained.
124 gotMetainfo missinggo.Event
126 readers map[*reader]struct{}
127 readerNowPieces bitmap.Bitmap
128 readerReadaheadPieces bitmap.Bitmap
130 // A cache of pieces we need to get. Calculated from various piece and
131 // file priorities and completion states elsewhere.
132 pendingPieces prioritybitmap.PriorityBitmap
133 // A cache of completed piece indices.
134 completedPieces bitmap.Bitmap
135 // Pieces that need to be hashed.
136 piecesQueuedForHash bitmap.Bitmap
138 // A pool of piece priorities []int for assignment to new connections.
139 // These "inclinations" are used to give connections preference for
141 connPieceInclinationPool sync.Pool
143 // Count of each request across active connections.
144 pendingRequests map[request]int
145 // The last time we requested a chunk. Deleting the request from any
146 // connection will clear this value.
147 lastRequested map[request]*time.Timer
150 func (t *Torrent) tickleReaders() {
151 t.cl.event.Broadcast()
154 // Returns a channel that is closed when the Torrent is closed.
155 func (t *Torrent) Closed() <-chan struct{} {
156 return t.closed.LockedChan(t.cl.locker())
159 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
160 // pending, and half-open peers.
161 func (t *Torrent) KnownSwarm() (ks []Peer) {
162 // Add pending peers to the list
163 t.peers.Each(func(peer Peer) {
164 ks = append(ks, peer)
167 // Add half-open peers to the list
168 for _, peer := range t.halfOpen {
169 ks = append(ks, peer)
172 // Add active peers to the list
173 for conn := range t.conns {
175 ks = append(ks, Peer{
177 IP: conn.remoteAddr.IP,
178 Port: int(conn.remoteAddr.Port),
179 Source: conn.Discovery,
180 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
181 // > But if we're not connected to them with an encrypted connection, I couldn't say
182 // > what's appropriate. We can carry forward the SupportsEncryption value as we
183 // > received it from trackers/DHT/PEX, or just use the encryption state for the
184 // > connection. It's probably easiest to do the latter for now.
185 // https://github.com/anacrolix/torrent/pull/188
186 SupportsEncryption: conn.headerEncrypted,
193 func (t *Torrent) setChunkSize(size pp.Integer) {
195 t.chunkPool = &sync.Pool{
196 New: func() interface{} {
197 b := make([]byte, size)
203 func (t *Torrent) setDisplayName(dn string) {
210 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
211 return t.completedPieces.Get(bitmap.BitIndex(piece))
214 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
215 return t.pieces[piece].Storage().Completion()
218 // There's a connection to that address already.
219 func (t *Torrent) addrActive(addr string) bool {
220 if _, ok := t.halfOpen[addr]; ok {
223 for c := range t.conns {
225 if ra.String() == addr {
232 func (t *Torrent) unclosedConnsAsSlice() (ret []*connection) {
233 ret = make([]*connection, 0, len(t.conns))
234 for c := range t.conns {
235 if !c.closed.IsSet() {
242 func (t *Torrent) addPeer(p Peer) {
244 peersAddedBySource.Add(string(p.Source), 1)
245 if t.closed.IsSet() {
248 if cl.badPeerIPPort(p.IP, p.Port) {
249 torrent.Add("peers not added because of bad addr", 1)
253 torrent.Add("peers replaced", 1)
256 for t.peers.Len() > cl.config.TorrentPeersHighWater {
257 _, ok := t.peers.DeleteMin()
259 torrent.Add("excess reserve peers discarded", 1)
264 func (t *Torrent) invalidateMetadata() {
265 for i := range t.metadataCompletedChunks {
266 t.metadataCompletedChunks[i] = false
271 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
275 if index >= len(t.metadataCompletedChunks) {
276 log.Printf("%s: ignoring metadata piece %d", t, index)
279 copy(t.metadataBytes[(1<<14)*index:], data)
280 t.metadataCompletedChunks[index] = true
283 func (t *Torrent) metadataPieceCount() int {
284 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
287 func (t *Torrent) haveMetadataPiece(piece int) bool {
289 return (1<<14)*piece < len(t.metadataBytes)
291 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
295 func (t *Torrent) metadataSizeKnown() bool {
296 return t.metadataBytes != nil
299 func (t *Torrent) metadataSize() int {
300 return len(t.metadataBytes)
303 func infoPieceHashes(info *metainfo.Info) (ret []string) {
304 for i := 0; i < len(info.Pieces); i += sha1.Size {
305 ret = append(ret, string(info.Pieces[i:i+sha1.Size]))
310 func (t *Torrent) makePieces() {
311 hashes := infoPieceHashes(t.info)
312 t.pieces = make([]Piece, len(hashes), len(hashes))
313 for i, hash := range hashes {
314 piece := &t.pieces[i]
316 piece.index = pieceIndex(i)
317 piece.noPendingWrites.L = &piece.pendingWritesMutex
318 missinggo.CopyExact(piece.hash[:], hash)
320 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
321 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
322 piece.files = files[beginFile:endFile]
326 // Returns the index of the first file containing the piece. files must be
327 // ordered by offset.
328 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
329 for i, f := range files {
330 if f.offset+f.length > pieceOffset {
337 // Returns the index after the last file containing the piece. files must be
338 // ordered by offset.
339 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
340 for i, f := range files {
341 if f.offset+f.length >= pieceEndOffset {
348 func (t *Torrent) cacheLength() {
350 for _, f := range t.info.UpvertedFiles() {
356 func (t *Torrent) setInfo(info *metainfo.Info) error {
357 if err := validateInfo(info); err != nil {
358 return fmt.Errorf("bad info: %s", err)
360 if t.storageOpener != nil {
362 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
364 return fmt.Errorf("error opening torrent storage: %s", err)
368 t.displayName = "" // Save a few bytes lol.
375 func (t *Torrent) onSetInfo() {
376 for conn := range t.conns {
377 if err := conn.setNumPieces(t.numPieces()); err != nil {
378 log.Printf("closing connection: %s", err)
382 for i := range t.pieces {
383 t.updatePieceCompletion(pieceIndex(i))
385 if !p.storageCompletionOk {
386 // log.Printf("piece %s completion unknown, queueing check", p)
387 t.queuePieceCheck(pieceIndex(i))
390 t.cl.event.Broadcast()
392 t.updateWantPeersEvent()
393 t.pendingRequests = make(map[request]int)
394 t.lastRequested = make(map[request]*time.Timer)
397 // Called when metadata for a torrent becomes available.
398 func (t *Torrent) setInfoBytes(b []byte) error {
399 if metainfo.HashBytes(b) != t.infoHash {
400 return errors.New("info bytes have wrong hash")
402 var info metainfo.Info
403 if err := bencode.Unmarshal(b, &info); err != nil {
404 return fmt.Errorf("error unmarshalling info bytes: %s", err)
406 if err := t.setInfo(&info); err != nil {
410 t.metadataCompletedChunks = nil
415 func (t *Torrent) haveAllMetadataPieces() bool {
419 if t.metadataCompletedChunks == nil {
422 for _, have := range t.metadataCompletedChunks {
430 // TODO: Propagate errors to disconnect peer.
431 func (t *Torrent) setMetadataSize(bytes int) (err error) {
433 // We already know the correct metadata size.
436 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
437 return errors.New("bad size")
439 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
442 t.metadataBytes = make([]byte, bytes)
443 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
444 t.metadataChanged.Broadcast()
445 for c := range t.conns {
446 c.requestPendingMetadata()
451 // The current working name for the torrent. Either the name in the info dict,
452 // or a display name given such as by the dn value in a magnet link, or "".
453 func (t *Torrent) name() string {
460 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
461 p := &t.pieces[index]
462 ret.Priority = t.piecePriority(index)
463 ret.Completion = p.completion()
464 if p.queuedForHash() || p.hashing {
467 if !ret.Complete && t.piecePartiallyDownloaded(index) {
473 func (t *Torrent) metadataPieceSize(piece int) int {
474 return metadataPieceSize(len(t.metadataBytes), piece)
477 func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
483 d["total_size"] = len(t.metadataBytes)
485 p := bencode.MustMarshal(d)
488 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
489 ExtendedPayload: append(p, data...),
493 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
494 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
495 ret = append(ret, PieceStateRun{
496 PieceState: el.(PieceState),
500 for index := range t.pieces {
501 rle.Append(t.pieceState(pieceIndex(index)), 1)
507 // Produces a small string representing a PieceStateRun.
508 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
509 ret = fmt.Sprintf("%d", psr.Length)
510 ret += func() string {
511 switch psr.Priority {
512 case PiecePriorityNext:
514 case PiecePriorityNormal:
516 case PiecePriorityReadahead:
518 case PiecePriorityNow:
520 case PiecePriorityHigh:
541 func (t *Torrent) writeStatus(w io.Writer) {
542 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
543 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
545 fmt.Fprintf(w, "Metadata have: ")
546 for _, h := range t.metadataCompletedChunks {
547 fmt.Fprintf(w, "%c", func() rune {
557 fmt.Fprintf(w, "Piece length: %s\n", func() string {
559 return fmt.Sprint(t.usualPieceSize())
565 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
566 fmt.Fprint(w, "Piece States:")
567 for _, psr := range t.pieceStateRuns() {
569 w.Write([]byte(pieceStateRunStatusChars(psr)))
573 fmt.Fprintf(w, "Reader Pieces:")
574 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
575 fmt.Fprintf(w, " %d:%d", begin, end)
580 fmt.Fprintf(w, "Enabled trackers:\n")
582 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
583 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
584 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
585 return l.u.String() < r.u.String()
586 }).([]*trackerScraper) {
587 fmt.Fprintf(tw, " %s\n", ta.statusLine())
592 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
594 spew.NewDefaultConfig()
595 spew.Fdump(w, t.statsLocked())
597 conns := t.connsAsSlice()
598 slices.Sort(conns, worseConn)
599 for i, c := range conns {
600 fmt.Fprintf(w, "%2d. ", i+1)
605 func (t *Torrent) haveInfo() bool {
609 // Returns a run-time generated MetaInfo that includes the info bytes and
610 // announce-list as currently known to the client.
611 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
612 return metainfo.MetaInfo{
613 CreationDate: time.Now().Unix(),
614 Comment: "dynamic metainfo from client",
615 CreatedBy: "go.torrent",
616 AnnounceList: t.metainfo.UpvertedAnnounceList(),
617 InfoBytes: func() []byte {
619 return t.metadataBytes
627 func (t *Torrent) BytesMissing() int64 {
630 return t.bytesMissingLocked()
633 func (t *Torrent) bytesMissingLocked() int64 {
637 func (t *Torrent) bytesLeft() (left int64) {
638 bitmap.Flip(t.completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
639 p := &t.pieces[piece]
640 left += int64(p.length() - p.numDirtyBytes())
646 // Bytes left to give in tracker announces.
647 func (t *Torrent) bytesLeftAnnounce() uint64 {
649 return uint64(t.bytesLeft())
651 return math.MaxUint64
655 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
656 if t.pieceComplete(piece) {
659 if t.pieceAllDirty(piece) {
662 return t.pieces[piece].hasDirtyChunks()
665 func (t *Torrent) usualPieceSize() int {
666 return int(t.info.PieceLength)
669 func (t *Torrent) numPieces() pieceIndex {
670 return pieceIndex(t.info.NumPieces())
673 func (t *Torrent) numPiecesCompleted() (num int) {
674 return t.completedPieces.Len()
677 func (t *Torrent) close() (err error) {
680 if t.storage != nil {
683 t.storageLock.Unlock()
685 for conn := range t.conns {
688 t.cl.event.Broadcast()
689 t.pieceStateChanges.Close()
690 t.updateWantPeersEvent()
694 func (t *Torrent) requestOffset(r request) int64 {
695 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
698 // Return the request that would include the given offset into the torrent
699 // data. Returns !ok if there is no such request.
700 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
701 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
704 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
705 defer perf.ScopeTimerErr(&err)()
706 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
707 if err == nil && n != len(data) {
708 err = io.ErrShortWrite
713 func (t *Torrent) bitfield() (bf []bool) {
714 bf = make([]bool, t.numPieces())
715 t.completedPieces.IterTyped(func(piece int) (again bool) {
722 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
723 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
726 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
727 t.pieces[pieceIndex].dirtyChunks.Clear()
730 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
731 if t.info.PieceLength == 0 {
732 // There will be no variance amongst pieces. Only pain.
735 if piece == t.numPieces()-1 {
736 ret := pp.Integer(*t.length % t.info.PieceLength)
741 return pp.Integer(t.info.PieceLength)
744 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash) {
745 hash := pieceHash.New()
746 p := &t.pieces[piece]
747 p.waitNoPendingWrites()
748 ip := t.info.Piece(int(piece))
750 n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
752 missinggo.CopyExact(&ret, hash.Sum(nil))
755 if err != io.ErrUnexpectedEOF && !os.IsNotExist(err) {
756 log.Printf("unexpected error hashing piece with %T: %s", t.storage.TorrentImpl, err)
761 func (t *Torrent) haveAnyPieces() bool {
762 return t.completedPieces.Len() != 0
765 func (t *Torrent) haveAllPieces() bool {
769 return t.completedPieces.Len() == bitmap.BitIndex(t.numPieces())
772 func (t *Torrent) havePiece(index pieceIndex) bool {
773 return t.haveInfo() && t.pieceComplete(index)
776 func (t *Torrent) haveChunk(r request) (ret bool) {
778 // log.Println("have chunk", r, ret)
783 if t.pieceComplete(pieceIndex(r.Index)) {
786 p := &t.pieces[r.Index]
787 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
790 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
791 return int(cs.Begin / chunkSize)
794 func (t *Torrent) wantPiece(r request) bool {
795 if !t.wantPieceIndex(pieceIndex(r.Index)) {
798 if t.pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
801 // TODO: What about pieces that were wanted, but aren't now, and aren't
802 // completed either? That used to be done here.
806 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
810 if index < 0 || index >= t.numPieces() {
813 p := &t.pieces[index]
814 if p.queuedForHash() {
820 if t.pieceComplete(index) {
823 if t.pendingPieces.Contains(bitmap.BitIndex(index)) {
826 // log.Printf("piece %d not pending", index)
827 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
828 return index < begin || index >= end
832 // The worst connection is one that hasn't been sent, or sent anything useful
833 // for the longest. A bad connection is one that usually sends us unwanted
834 // pieces, or has been in worser half of the established connections for more
836 func (t *Torrent) worstBadConn() *connection {
837 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
840 c := heap.Pop(&wcs).(*connection)
841 if c.stats.ChunksReadWasted.Int64() >= 6 && c.stats.ChunksReadWasted.Int64() > c.stats.ChunksReadUseful.Int64() {
844 // If the connection is in the worst half of the established
845 // connection quota and is older than a minute.
846 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
847 // Give connections 1 minute to prove themselves.
848 if time.Since(c.completedHandshake) > time.Minute {
856 type PieceStateChange struct {
861 func (t *Torrent) publishPieceChange(piece pieceIndex) {
862 cur := t.pieceState(piece)
863 p := &t.pieces[piece]
864 if cur != p.publicPieceState {
865 p.publicPieceState = cur
866 t.pieceStateChanges.Publish(PieceStateChange{
873 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
874 if t.pieceComplete(piece) {
877 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
880 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
881 return t.pieces[piece].dirtyChunks.Len() == int(t.pieceNumChunks(piece))
884 func (t *Torrent) readersChanged() {
885 t.updateReaderPieces()
886 t.updateAllPiecePriorities()
889 func (t *Torrent) updateReaderPieces() {
890 t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
893 func (t *Torrent) readerPosChanged(from, to pieceRange) {
897 t.updateReaderPieces()
898 // Order the ranges, high and low.
900 if l.begin > h.begin {
904 // Two distinct ranges.
905 t.updatePiecePriorities(l.begin, l.end)
906 t.updatePiecePriorities(h.begin, h.end)
913 t.updatePiecePriorities(l.begin, end)
917 func (t *Torrent) maybeNewConns() {
918 // Tickle the accept routine.
919 t.cl.event.Broadcast()
923 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
924 // log.Printf("piece %d priority changed", piece)
925 for c := range t.conns {
926 if c.updatePiecePriority(piece) {
927 // log.Print("conn piece priority changed")
932 t.publishPieceChange(piece)
935 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
936 p := &t.pieces[piece]
937 newPrio := p.uncachedPriority()
938 // log.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
939 if newPrio == PiecePriorityNone {
940 if !t.pendingPieces.Remove(bitmap.BitIndex(piece)) {
944 if !t.pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
948 t.piecePriorityChanged(piece)
951 func (t *Torrent) updateAllPiecePriorities() {
952 t.updatePiecePriorities(0, t.numPieces())
955 // Update all piece priorities in one hit. This function should have the same
956 // output as updatePiecePriority, but across all pieces.
957 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
958 for i := begin; i < end; i++ {
959 t.updatePiecePriority(i)
963 // Returns the range of pieces [begin, end) that contains the extent of bytes.
964 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
965 if off >= *t.length {
975 begin = pieceIndex(off / t.info.PieceLength)
976 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
977 if end > pieceIndex(t.info.NumPieces()) {
978 end = pieceIndex(t.info.NumPieces())
983 // Returns true if all iterations complete without breaking. Returns the read
984 // regions for all readers. The reader regions should not be merged as some
985 // callers depend on this method to enumerate readers.
986 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
987 for r := range t.readers {
989 if p.begin >= p.end {
992 if !f(p.begin, p.end) {
999 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1000 prio, ok := t.pendingPieces.GetPriority(bitmap.BitIndex(piece))
1002 return PiecePriorityNone
1007 ret := piecePriority(-prio)
1008 if ret == PiecePriorityNone {
1014 func (t *Torrent) pendRequest(req request) {
1015 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1016 t.pieces[req.Index].pendChunkIndex(ci)
1019 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1020 log.Call().Add("piece", piece).AddValue(debugLogValue).Log(t.logger)
1021 t.cl.event.Broadcast()
1022 if t.pieceComplete(piece) {
1023 t.onPieceCompleted(piece)
1025 t.onIncompletePiece(piece)
1027 t.updatePiecePriority(piece)
1030 func (t *Torrent) numReceivedConns() (ret int) {
1031 for c := range t.conns {
1032 if c.Discovery == peerSourceIncoming {
1039 func (t *Torrent) maxHalfOpen() int {
1040 // Note that if we somehow exceed the maximum established conns, we want
1041 // the negative value to have an effect.
1042 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1043 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1044 // We want to allow some experimentation with new peers, and to try to
1045 // upset an oversupply of received connections.
1046 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1049 func (t *Torrent) openNewConns() {
1050 defer t.updateWantPeersEvent()
1051 for t.peers.Len() != 0 {
1055 if len(t.halfOpen) >= t.maxHalfOpen() {
1058 p := t.peers.PopMax()
1063 func (t *Torrent) getConnPieceInclination() []int {
1064 _ret := t.connPieceInclinationPool.Get()
1066 pieceInclinationsNew.Add(1)
1067 return rand.Perm(int(t.numPieces()))
1069 pieceInclinationsReused.Add(1)
1070 return *_ret.(*[]int)
1073 func (t *Torrent) putPieceInclination(pi []int) {
1074 t.connPieceInclinationPool.Put(&pi)
1075 pieceInclinationsPut.Add(1)
1078 func (t *Torrent) updatePieceCompletion(piece pieceIndex) {
1079 pcu := t.pieceCompleteUncached(piece)
1080 p := &t.pieces[piece]
1081 changed := t.completedPieces.Get(bitmap.BitIndex(piece)) != pcu.Complete || p.storageCompletionOk != pcu.Ok
1082 log.Fmsg("piece %d completion: %v", piece, pcu.Ok).AddValue(debugLogValue).Log(t.logger)
1083 p.storageCompletionOk = pcu.Ok
1084 t.completedPieces.Set(bitmap.BitIndex(piece), pcu.Complete)
1086 // log.Printf("piece %d uncached completion: %v", piece, pcu.Complete)
1087 // log.Printf("piece %d changed: %v", piece, changed)
1089 t.pieceCompletionChanged(piece)
1093 // Non-blocking read. Client lock is not required.
1094 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1095 p := &t.pieces[off/t.info.PieceLength]
1096 p.waitNoPendingWrites()
1097 return p.Storage().ReadAt(b, off-p.Info().Offset())
1100 func (t *Torrent) updateAllPieceCompletions() {
1101 for i := pieceIndex(0); i < t.numPieces(); i++ {
1102 t.updatePieceCompletion(i)
1106 // Returns an error if the metadata was completed, but couldn't be set for
1107 // some reason. Blame it on the last peer to contribute.
1108 func (t *Torrent) maybeCompleteMetadata() error {
1113 if !t.haveAllMetadataPieces() {
1114 // Don't have enough metadata pieces.
1117 err := t.setInfoBytes(t.metadataBytes)
1119 t.invalidateMetadata()
1120 return fmt.Errorf("error setting info bytes: %s", err)
1122 if t.cl.config.Debug {
1123 log.Printf("%s: got metadata from peers", t)
1128 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1129 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1130 ret.AddRange(bitmap.BitIndex(begin), bitmap.BitIndex(end))
1136 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1137 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1139 now.Add(bitmap.BitIndex(begin))
1140 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1147 func (t *Torrent) needData() bool {
1148 if t.closed.IsSet() {
1154 return t.pendingPieces.Len() != 0
1157 func appendMissingStrings(old, new []string) (ret []string) {
1160 for _, n := range new {
1161 for _, o := range old {
1166 ret = append(ret, n)
1171 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1173 for minNumTiers > len(ret) {
1174 ret = append(ret, nil)
1179 func (t *Torrent) addTrackers(announceList [][]string) {
1180 fullAnnounceList := &t.metainfo.AnnounceList
1181 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1182 for tierIndex, trackerURLs := range announceList {
1183 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1185 t.startMissingTrackerScrapers()
1186 t.updateWantPeersEvent()
1189 // Don't call this before the info is available.
1190 func (t *Torrent) bytesCompleted() int64 {
1194 return t.info.TotalLength() - t.bytesLeft()
1197 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1200 return t.setInfoBytes(b)
1203 // Returns true if connection is removed from torrent.Conns.
1204 func (t *Torrent) deleteConnection(c *connection) (ret bool) {
1205 if !c.closed.IsSet() {
1206 panic("connection is not closed")
1207 // There are behaviours prevented by the closed state that will fail
1208 // if the connection has been deleted.
1212 torrent.Add("deleted connections", 1)
1213 c.deleteAllRequests()
1214 if len(t.conns) == 0 {
1215 t.assertNoPendingRequests()
1220 func (t *Torrent) assertNoPendingRequests() {
1221 if len(t.pendingRequests) != 0 {
1222 panic(t.pendingRequests)
1224 if len(t.lastRequested) != 0 {
1225 panic(t.lastRequested)
1229 func (t *Torrent) dropConnection(c *connection) {
1230 t.cl.event.Broadcast()
1232 if t.deleteConnection(c) {
1237 func (t *Torrent) wantPeers() bool {
1238 if t.closed.IsSet() {
1241 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1244 return t.needData() || t.seeding()
1247 func (t *Torrent) updateWantPeersEvent() {
1249 t.wantPeersEvent.Set()
1251 t.wantPeersEvent.Clear()
1255 // Returns whether the client should make effort to seed the torrent.
1256 func (t *Torrent) seeding() bool {
1258 if t.closed.IsSet() {
1261 if cl.config.NoUpload {
1264 if !cl.config.Seed {
1267 if cl.config.DisableAggressiveUpload && t.needData() {
1273 func (t *Torrent) startScrapingTracker(_url string) {
1277 u, err := url.Parse(_url)
1279 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1280 // TODO: Handle urls with leading '*', some kind of silly uTorrent
1284 if u.Scheme == "udp" {
1286 t.startScrapingTracker(u.String())
1288 t.startScrapingTracker(u.String())
1291 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1294 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1297 if _, ok := t.trackerAnnouncers[_url]; ok {
1300 newAnnouncer := &trackerScraper{
1304 if t.trackerAnnouncers == nil {
1305 t.trackerAnnouncers = make(map[string]*trackerScraper)
1307 t.trackerAnnouncers[_url] = newAnnouncer
1308 go newAnnouncer.Run()
1311 // Adds and starts tracker scrapers for tracker URLs that aren't already
1313 func (t *Torrent) startMissingTrackerScrapers() {
1314 if t.cl.config.DisableTrackers {
1317 t.startScrapingTracker(t.metainfo.Announce)
1318 for _, tier := range t.metainfo.AnnounceList {
1319 for _, url := range tier {
1320 t.startScrapingTracker(url)
1325 // Returns an AnnounceRequest with fields filled out to defaults and current
1327 func (t *Torrent) announceRequest() tracker.AnnounceRequest {
1328 // Note that IPAddress is not set. It's set for UDP inside the tracker
1329 // code, since it's dependent on the network in use.
1330 return tracker.AnnounceRequest{
1331 Event: tracker.None,
1333 Port: uint16(t.cl.incomingPeerPort()),
1334 PeerId: t.cl.peerID,
1335 InfoHash: t.infoHash,
1336 Key: t.cl.announceKey(),
1338 // The following are vaguely described in BEP 3.
1340 Left: t.bytesLeftAnnounce(),
1341 Uploaded: t.stats.BytesWrittenData.Int64(),
1342 // There's no mention of wasted or unwanted download in the BEP.
1343 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1347 // Adds peers revealed in an announce until the announce ends, or we have
1349 func (t *Torrent) consumeDHTAnnounce(pvs <-chan dht.PeersValues) {
1351 // Count all the unique addresses we got during this announce.
1352 allAddrs := make(map[string]struct{})
1355 case v, ok := <-pvs:
1359 addPeers := make([]Peer, 0, len(v.Peers))
1360 for _, cp := range v.Peers {
1362 // Can't do anything with this.
1365 addPeers = append(addPeers, Peer{
1368 Source: peerSourceDHTGetPeers,
1370 key := (&net.UDPAddr{
1374 allAddrs[key] = struct{}{}
1377 t.addPeers(addPeers)
1378 numPeers := t.peers.Len()
1380 if numPeers >= cl.config.TorrentPeersHighWater {
1383 case <-t.closed.LockedChan(cl.locker()):
1389 func (t *Torrent) announceDHT(impliedPort bool, s *dht.Server) (err error) {
1391 ps, err := s.Announce(t.infoHash, cl.incomingPeerPort(), impliedPort)
1395 t.consumeDHTAnnounce(ps.Peers)
1400 func (t *Torrent) dhtAnnouncer(s *dht.Server) {
1404 case <-t.wantPeersEvent.LockedChan(cl.locker()):
1405 case <-t.closed.LockedChan(cl.locker()):
1408 err := t.announceDHT(true, s)
1415 log.Printf("error announcing %q to DHT: %s", t, err)
1419 case <-t.closed.LockedChan(cl.locker()):
1421 case <-time.After(5 * time.Minute):
1426 func (t *Torrent) addPeers(peers []Peer) {
1427 for _, p := range peers {
1432 func (t *Torrent) Stats() TorrentStats {
1434 defer t.cl.rUnlock()
1435 return t.statsLocked()
1438 func (t *Torrent) statsLocked() (ret TorrentStats) {
1439 ret.ActivePeers = len(t.conns)
1440 ret.HalfOpenPeers = len(t.halfOpen)
1441 ret.PendingPeers = t.peers.Len()
1442 ret.TotalPeers = t.numTotalPeers()
1443 ret.ConnectedSeeders = 0
1444 for c := range t.conns {
1445 if all, ok := c.peerHasAllPieces(); all && ok {
1446 ret.ConnectedSeeders++
1449 ret.ConnStats = t.stats.Copy()
1453 // The total number of peers in the torrent.
1454 func (t *Torrent) numTotalPeers() int {
1455 peers := make(map[string]struct{})
1456 for conn := range t.conns {
1457 ra := conn.conn.RemoteAddr()
1459 // It's been closed and doesn't support RemoteAddr.
1462 peers[ra.String()] = struct{}{}
1464 for addr := range t.halfOpen {
1465 peers[addr] = struct{}{}
1467 t.peers.Each(func(peer Peer) {
1468 peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{}
1473 // Reconcile bytes transferred before connection was associated with a
1475 func (t *Torrent) reconcileHandshakeStats(c *connection) {
1476 if c.stats != (ConnStats{
1477 // Handshakes should only increment these fields:
1478 BytesWritten: c.stats.BytesWritten,
1479 BytesRead: c.stats.BytesRead,
1483 c.postHandshakeStats(func(cs *ConnStats) {
1484 cs.BytesRead.Add(c.stats.BytesRead.Int64())
1485 cs.BytesWritten.Add(c.stats.BytesWritten.Int64())
1487 c.reconciledHandshakeStats = true
1490 // Returns true if the connection is added.
1491 func (t *Torrent) addConnection(c *connection) (err error) {
1494 torrent.Add("added connections", 1)
1497 if t.closed.IsSet() {
1498 return errors.New("torrent closed")
1500 for c0 := range t.conns {
1501 if c.PeerID != c0.PeerID {
1504 if !t.cl.config.dropDuplicatePeerIds {
1507 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1509 t.deleteConnection(c0)
1511 return errors.New("existing connection preferred")
1514 if len(t.conns) >= t.maxEstablishedConns {
1515 c := t.worstBadConn()
1517 return errors.New("don't want conns")
1520 t.deleteConnection(c)
1522 if len(t.conns) >= t.maxEstablishedConns {
1525 t.conns[c] = struct{}{}
1529 func (t *Torrent) wantConns() bool {
1530 if !t.networkingEnabled {
1533 if t.closed.IsSet() {
1536 if !t.seeding() && !t.needData() {
1539 if len(t.conns) < t.maxEstablishedConns {
1542 return t.worstBadConn() != nil
1545 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1548 oldMax = t.maxEstablishedConns
1549 t.maxEstablishedConns = max
1550 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1551 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1552 t.dropConnection(wcs.Pop().(*connection))
1558 func (t *Torrent) pieceHashed(piece pieceIndex, correct bool) {
1559 log.Fmsg("hashed piece %d", piece).Add("piece", piece).Add("passed", correct).AddValue(debugLogValue).Log(t.logger)
1560 if t.closed.IsSet() {
1563 p := &t.pieces[piece]
1564 touchers := t.reapPieceTouchers(piece)
1565 if p.storageCompletionOk {
1566 // Don't score the first time a piece is hashed, it could be an
1569 pieceHashedCorrect.Add(1)
1571 log.Printf("%s: piece %d (%s) failed hash: %d connections contributed", t, piece, p.hash, len(touchers))
1572 pieceHashedNotCorrect.Add(1)
1576 if len(touchers) != 0 {
1577 // Don't increment stats above connection-level for every involved
1579 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1581 for _, c := range touchers {
1582 c.stats.incrementPiecesDirtiedGood()
1584 err := p.Storage().MarkComplete()
1586 log.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1589 if len(touchers) != 0 {
1590 // Don't increment stats above connection-level for every involved
1592 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1593 for _, c := range touchers {
1594 // Y u do dis peer?!
1595 c.stats.incrementPiecesDirtiedBad()
1597 slices.Sort(touchers, connLessTrusted)
1598 if t.cl.config.Debug {
1599 log.Printf("dropping first corresponding conn from trust: %v", func() (ret []int64) {
1600 for _, c := range touchers {
1601 ret = append(ret, c.netGoodPiecesDirtied())
1607 t.cl.banPeerIP(c.remoteAddr.IP)
1610 t.onIncompletePiece(piece)
1611 p.Storage().MarkNotComplete()
1613 t.updatePieceCompletion(piece)
1616 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1617 // TODO: Make faster
1618 for cn := range t.conns {
1623 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1624 t.pendAllChunkSpecs(piece)
1625 t.cancelRequestsForPiece(piece)
1626 for conn := range t.conns {
1631 // Called when a piece is found to be not complete.
1632 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1633 if t.pieceAllDirty(piece) {
1634 t.pendAllChunkSpecs(piece)
1636 if !t.wantPieceIndex(piece) {
1637 // log.Printf("piece %d incomplete and unwanted", piece)
1640 // We could drop any connections that we told we have a piece that we
1641 // don't here. But there's a test failure, and it seems clients don't care
1642 // if you request pieces that you already claim to have. Pruning bad
1643 // connections might just remove any connections that aren't treating us
1644 // favourably anyway.
1646 // for c := range t.conns {
1647 // if c.sentHave(piece) {
1651 for conn := range t.conns {
1652 if conn.PeerHasPiece(piece) {
1653 conn.updateRequests()
1658 func (t *Torrent) verifyPiece(piece pieceIndex) {
1662 p := &t.pieces[piece]
1665 cl.event.Broadcast()
1667 for p.hashing || t.storage == nil {
1670 if !p.t.piecesQueuedForHash.Remove(bitmap.BitIndex(piece)) {
1671 panic("piece was not queued")
1673 t.updatePiecePriority(piece)
1674 if t.closed.IsSet() || t.pieceComplete(piece) {
1678 t.publishPieceChange(piece)
1679 t.updatePiecePriority(piece)
1680 t.storageLock.RLock()
1682 sum := t.hashPiece(piece)
1683 t.storageLock.RUnlock()
1686 t.updatePiecePriority(piece)
1687 t.pieceHashed(piece, sum == p.hash)
1688 t.publishPieceChange(piece)
1691 // Return the connections that touched a piece, and clear the entries while
1693 func (t *Torrent) reapPieceTouchers(piece pieceIndex) (ret []*connection) {
1694 for c := range t.pieces[piece].dirtiers {
1695 delete(c.peerTouchedPieces, piece)
1696 ret = append(ret, c)
1698 t.pieces[piece].dirtiers = nil
1702 func (t *Torrent) connsAsSlice() (ret []*connection) {
1703 for c := range t.conns {
1704 ret = append(ret, c)
1709 // Currently doesn't really queue, but should in the future.
1710 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1711 piece := &t.pieces[pieceIndex]
1712 if piece.queuedForHash() {
1715 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1716 t.publishPieceChange(pieceIndex)
1717 t.updatePiecePriority(pieceIndex)
1718 go t.verifyPiece(pieceIndex)
1721 func (t *Torrent) VerifyData() {
1722 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1723 t.Piece(i).VerifyData()
1727 // Start the process of connecting to the given peer for the given torrent if
1729 func (t *Torrent) initiateConn(peer Peer) {
1730 if peer.Id == t.cl.peerID {
1733 if t.cl.badPeerIPPort(peer.IP, peer.Port) {
1736 addr := IpPort{peer.IP, uint16(peer.Port)}
1737 if t.addrActive(addr.String()) {
1740 t.halfOpen[addr.String()] = peer
1741 go t.cl.outgoingConnection(t, addr, peer.Source)
1744 func (t *Torrent) AddClientPeer(cl *Client) {
1745 t.AddPeers(func() (ps []Peer) {
1746 for _, la := range cl.ListenAddrs() {
1747 ps = append(ps, Peer{
1748 IP: missinggo.AddrIP(la),
1749 Port: missinggo.AddrPort(la),
1756 // All stats that include this Torrent. Useful when we want to increment
1757 // ConnStats but not for every connection.
1758 func (t *Torrent) allStats(f func(*ConnStats)) {
1763 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1764 return t.pieces[i].hashing
1767 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1768 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1771 func (t *Torrent) dialTimeout() time.Duration {
1772 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())