19 "github.com/anacrolix/dht"
20 "github.com/anacrolix/log"
21 "github.com/anacrolix/missinggo"
22 "github.com/anacrolix/missinggo/bitmap"
23 "github.com/anacrolix/missinggo/perf"
24 "github.com/anacrolix/missinggo/prioritybitmap"
25 "github.com/anacrolix/missinggo/pubsub"
26 "github.com/anacrolix/missinggo/slices"
27 "github.com/davecgh/go-spew/spew"
29 "github.com/anacrolix/torrent/bencode"
30 "github.com/anacrolix/torrent/metainfo"
31 pp "github.com/anacrolix/torrent/peer_protocol"
32 "github.com/anacrolix/torrent/storage"
33 "github.com/anacrolix/torrent/tracker"
36 func (t *Torrent) chunkIndexSpec(chunkIndex pp.Integer, piece pieceIndex) chunkSpec {
37 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
40 type peersKey struct {
45 // Maintains state of torrent within a Client.
47 // Torrent-level aggregate statistics. First in struct to ensure 64-bit
48 // alignment. See #262.
53 networkingEnabled bool
55 // Determines what chunks to request from peers. 1: Favour higher priority
56 // pieces with some fuzzing to reduce overlaps and wastage across
57 // connections. 2: The fastest connection downloads strictly in order of
58 // priority, while all others adher to their piece inclications. 3:
59 // Requests are strictly by piece priority, and not duplicated until
60 // duplicateRequestTimeout is reached.
62 // How long to avoid duplicating a pending request.
63 duplicateRequestTimeout time.Duration
65 closed missinggo.Event
66 infoHash metainfo.Hash
68 // Values are the piece indices that changed.
69 pieceStateChanges *pubsub.PubSub
70 // The size of chunks to request from peers over the wire. This is
71 // normally 16KiB by convention these days.
74 // Total length of the torrent in bytes. Stored because it's not O(1) to
75 // get this from the info dict.
78 // The storage to open when the info dict becomes available.
79 storageOpener *storage.Client
80 // Storage for torrent data.
81 storage *storage.Torrent
82 // Read-locked for using storage, and write-locked for Closing.
83 storageLock sync.RWMutex
85 // TODO: Only announce stuff is used?
86 metainfo metainfo.MetaInfo
88 // The info dict. nil if we don't have it (yet).
92 // Active peer connections, running message stream loops. TODO: Make this
93 // open (not-closed) connections only.
94 conns map[*connection]struct{}
95 maxEstablishedConns int
96 // Set of addrs to which we're attempting to connect. Connections are
97 // half-open until all handshakes are completed.
98 halfOpen map[string]Peer
99 fastestConn *connection
101 // Reserve of peers to connect to. A peer can be both here and in the
102 // active connections if were told about the peer after connecting with
103 // them. That encourages us to reconnect to peers that are well known in
105 peers prioritizedPeers
106 wantPeersEvent missinggo.Event
107 // An announcer for each tracker URL.
108 trackerAnnouncers map[string]*trackerScraper
109 // How many times we've initiated a DHT announce. TODO: Move into stats.
112 // Name used if the info name isn't available. Should be cleared when the
113 // 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
140 // A pool of piece priorities []int for assignment to new connections.
141 // These "inclinations" are used to give connections preference for
143 connPieceInclinationPool sync.Pool
145 // Count of each request across active connections.
146 pendingRequests map[request]int
147 // The last time we requested a chunk. Deleting the request from any
148 // connection will clear this value.
149 lastRequested map[request]*time.Timer
152 func (t *Torrent) tickleReaders() {
153 t.cl.event.Broadcast()
156 // Returns a channel that is closed when the Torrent is closed.
157 func (t *Torrent) Closed() <-chan struct{} {
158 return t.closed.LockedChan(&t.cl.mu)
161 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
162 // pending, and half-open peers.
163 func (t *Torrent) KnownSwarm() (ks []Peer) {
164 // Add pending peers to the list
165 t.peers.Each(func(peer Peer) {
166 ks = append(ks, peer)
169 // Add half-open peers to the list
170 for _, peer := range t.halfOpen {
171 ks = append(ks, peer)
174 // Add active peers to the list
175 for conn := range t.conns {
176 host, portString, err := net.SplitHostPort(conn.remoteAddr().String())
181 ip := net.ParseIP(host)
182 port, err := strconv.Atoi(portString)
187 ks = append(ks, Peer{
191 Source: conn.Discovery,
192 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
193 // > But if we're not connected to them with an encrypted connection, I couldn't say
194 // > what's appropriate. We can carry forward the SupportsEncryption value as we
195 // > received it from trackers/DHT/PEX, or just use the encryption state for the
196 // > connection. It's probably easiest to do the latter for now.
197 // https://github.com/anacrolix/torrent/pull/188
198 SupportsEncryption: conn.headerEncrypted,
205 func (t *Torrent) setChunkSize(size pp.Integer) {
207 t.chunkPool = &sync.Pool{
208 New: func() interface{} {
209 b := make([]byte, size)
215 func (t *Torrent) setDisplayName(dn string) {
222 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
223 return t.completedPieces.Get(bitmap.BitIndex(piece))
226 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
227 return t.pieces[piece].Storage().Completion()
230 // There's a connection to that address already.
231 func (t *Torrent) addrActive(addr string) bool {
232 if _, ok := t.halfOpen[addr]; ok {
235 for c := range t.conns {
240 if ra.String() == addr {
247 func (t *Torrent) unclosedConnsAsSlice() (ret []*connection) {
248 ret = make([]*connection, 0, len(t.conns))
249 for c := range t.conns {
250 if !c.closed.IsSet() {
257 func (t *Torrent) addPeer(p Peer) {
259 peersAddedBySource.Add(string(p.Source), 1)
260 if t.closed.IsSet() {
263 if cl.badPeerIPPort(p.IP, p.Port) {
264 torrent.Add("peers not added because of bad addr", 1)
268 torrent.Add("peers replaced", 1)
271 for t.peers.Len() > cl.config.TorrentPeersHighWater {
272 _, ok := t.peers.DeleteMin()
274 torrent.Add("excess reserve peers discarded", 1)
279 func (t *Torrent) invalidateMetadata() {
280 for i := range t.metadataCompletedChunks {
281 t.metadataCompletedChunks[i] = false
286 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
290 if index >= len(t.metadataCompletedChunks) {
291 log.Printf("%s: ignoring metadata piece %d", t, index)
294 copy(t.metadataBytes[(1<<14)*index:], data)
295 t.metadataCompletedChunks[index] = true
298 func (t *Torrent) metadataPieceCount() int {
299 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
302 func (t *Torrent) haveMetadataPiece(piece int) bool {
304 return (1<<14)*piece < len(t.metadataBytes)
306 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
310 func (t *Torrent) metadataSizeKnown() bool {
311 return t.metadataBytes != nil
314 func (t *Torrent) metadataSize() int {
315 return len(t.metadataBytes)
318 func infoPieceHashes(info *metainfo.Info) (ret []string) {
319 for i := 0; i < len(info.Pieces); i += sha1.Size {
320 ret = append(ret, string(info.Pieces[i:i+sha1.Size]))
325 func (t *Torrent) makePieces() {
326 hashes := infoPieceHashes(t.info)
327 t.pieces = make([]Piece, len(hashes), len(hashes))
328 for i, hash := range hashes {
329 piece := &t.pieces[i]
331 piece.index = pieceIndex(i)
332 piece.noPendingWrites.L = &piece.pendingWritesMutex
333 missinggo.CopyExact(piece.hash[:], hash)
335 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
336 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
337 piece.files = files[beginFile:endFile]
341 // Returns the index of the first file containing the piece. files must be
342 // ordered by offset.
343 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
344 for i, f := range files {
345 if f.offset+f.length > pieceOffset {
352 // Returns the index after the last file containing the piece. files must be
353 // ordered by offset.
354 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
355 for i, f := range files {
356 if f.offset+f.length >= pieceEndOffset {
363 func (t *Torrent) cacheLength() {
365 for _, f := range t.info.UpvertedFiles() {
371 func (t *Torrent) setInfo(info *metainfo.Info) error {
372 if err := validateInfo(info); err != nil {
373 return fmt.Errorf("bad info: %s", err)
375 if t.storageOpener != nil {
377 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
379 return fmt.Errorf("error opening torrent storage: %s", err)
383 t.displayName = "" // Save a few bytes lol.
390 func (t *Torrent) onSetInfo() {
391 for conn := range t.conns {
392 if err := conn.setNumPieces(t.numPieces()); err != nil {
393 log.Printf("closing connection: %s", err)
397 for i := range t.pieces {
398 t.updatePieceCompletion(pieceIndex(i))
400 if !p.storageCompletionOk {
401 // log.Printf("piece %s completion unknown, queueing check", p)
402 t.queuePieceCheck(pieceIndex(i))
405 t.cl.event.Broadcast()
407 t.updateWantPeersEvent()
408 t.pendingRequests = make(map[request]int)
409 t.lastRequested = make(map[request]*time.Timer)
412 // Called when metadata for a torrent becomes available.
413 func (t *Torrent) setInfoBytes(b []byte) error {
414 if metainfo.HashBytes(b) != t.infoHash {
415 return errors.New("info bytes have wrong hash")
417 var info metainfo.Info
418 if err := bencode.Unmarshal(b, &info); err != nil {
419 return fmt.Errorf("error unmarshalling info bytes: %s", err)
421 if err := t.setInfo(&info); err != nil {
425 t.metadataCompletedChunks = nil
430 func (t *Torrent) haveAllMetadataPieces() bool {
434 if t.metadataCompletedChunks == nil {
437 for _, have := range t.metadataCompletedChunks {
445 // TODO: Propagate errors to disconnect peer.
446 func (t *Torrent) setMetadataSize(bytes int) (err error) {
448 // We already know the correct metadata size.
451 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
452 return errors.New("bad size")
454 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
457 t.metadataBytes = make([]byte, bytes)
458 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
459 t.metadataChanged.Broadcast()
460 for c := range t.conns {
461 c.requestPendingMetadata()
466 // The current working name for the torrent. Either the name in the info dict,
467 // or a display name given such as by the dn value in a magnet link, or "".
468 func (t *Torrent) name() string {
475 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
476 p := &t.pieces[index]
477 ret.Priority = t.piecePriority(index)
478 ret.Completion = p.completion()
479 if p.queuedForHash() || p.hashing {
482 if !ret.Complete && t.piecePartiallyDownloaded(index) {
488 func (t *Torrent) metadataPieceSize(piece int) int {
489 return metadataPieceSize(len(t.metadataBytes), piece)
492 func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
498 d["total_size"] = len(t.metadataBytes)
500 p := bencode.MustMarshal(d)
503 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
504 ExtendedPayload: append(p, data...),
508 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
509 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
510 ret = append(ret, PieceStateRun{
511 PieceState: el.(PieceState),
515 for index := range t.pieces {
516 rle.Append(t.pieceState(pieceIndex(index)), 1)
522 // Produces a small string representing a PieceStateRun.
523 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
524 ret = fmt.Sprintf("%d", psr.Length)
525 ret += func() string {
526 switch psr.Priority {
527 case PiecePriorityNext:
529 case PiecePriorityNormal:
531 case PiecePriorityReadahead:
533 case PiecePriorityNow:
535 case PiecePriorityHigh:
556 func (t *Torrent) writeStatus(w io.Writer) {
557 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
558 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
560 fmt.Fprintf(w, "Metadata have: ")
561 for _, h := range t.metadataCompletedChunks {
562 fmt.Fprintf(w, "%c", func() rune {
572 fmt.Fprintf(w, "Piece length: %s\n", func() string {
574 return fmt.Sprint(t.usualPieceSize())
580 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
581 fmt.Fprint(w, "Piece States:")
582 for _, psr := range t.pieceStateRuns() {
584 w.Write([]byte(pieceStateRunStatusChars(psr)))
588 fmt.Fprintf(w, "Reader Pieces:")
589 t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
590 fmt.Fprintf(w, " %d:%d", begin, end)
595 fmt.Fprintf(w, "Enabled trackers:\n")
597 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
598 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
599 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
600 return l.u.String() < r.u.String()
601 }).([]*trackerScraper) {
602 fmt.Fprintf(tw, " %s\n", ta.statusLine())
607 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
609 spew.NewDefaultConfig()
610 spew.Fdump(w, t.statsLocked())
612 conns := t.connsAsSlice()
613 slices.Sort(conns, worseConn)
614 for i, c := range conns {
615 fmt.Fprintf(w, "%2d. ", i+1)
620 func (t *Torrent) haveInfo() bool {
624 // Returns a run-time generated MetaInfo that includes the info bytes and
625 // announce-list as currently known to the client.
626 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
627 return metainfo.MetaInfo{
628 CreationDate: time.Now().Unix(),
629 Comment: "dynamic metainfo from client",
630 CreatedBy: "go.torrent",
631 AnnounceList: t.metainfo.UpvertedAnnounceList(),
632 InfoBytes: func() []byte {
634 return t.metadataBytes
642 func (t *Torrent) BytesMissing() int64 {
644 defer t.mu().RUnlock()
645 return t.bytesMissingLocked()
648 func (t *Torrent) bytesMissingLocked() int64 {
652 func (t *Torrent) bytesLeft() (left int64) {
653 bitmap.Flip(t.completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
654 p := &t.pieces[piece]
655 left += int64(p.length() - p.numDirtyBytes())
661 // Bytes left to give in tracker announces.
662 func (t *Torrent) bytesLeftAnnounce() uint64 {
664 return uint64(t.bytesLeft())
666 return math.MaxUint64
670 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
671 if t.pieceComplete(piece) {
674 if t.pieceAllDirty(piece) {
677 return t.pieces[piece].hasDirtyChunks()
680 func (t *Torrent) usualPieceSize() int {
681 return int(t.info.PieceLength)
684 func (t *Torrent) numPieces() pieceIndex {
685 return pieceIndex(t.info.NumPieces())
688 func (t *Torrent) numPiecesCompleted() (num int) {
689 return t.completedPieces.Len()
692 func (t *Torrent) close() (err error) {
695 if t.storage != nil {
698 t.storageLock.Unlock()
700 for conn := range t.conns {
703 t.cl.event.Broadcast()
704 t.pieceStateChanges.Close()
705 t.updateWantPeersEvent()
709 func (t *Torrent) requestOffset(r request) int64 {
710 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
713 // Return the request that would include the given offset into the torrent
714 // data. Returns !ok if there is no such request.
715 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
716 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
719 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
720 defer perf.ScopeTimerErr(&err)()
721 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
722 if err == nil && n != len(data) {
723 err = io.ErrShortWrite
728 func (t *Torrent) bitfield() (bf []bool) {
729 bf = make([]bool, t.numPieces())
730 t.completedPieces.IterTyped(func(piece int) (again bool) {
737 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
738 return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
741 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
742 t.pieces[pieceIndex].dirtyChunks.Clear()
745 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
746 if t.info.PieceLength == 0 {
747 // There will be no variance amongst pieces. Only pain.
750 if piece == t.numPieces()-1 {
751 ret := pp.Integer(*t.length % t.info.PieceLength)
756 return pp.Integer(t.info.PieceLength)
759 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash) {
760 hash := pieceHash.New()
761 p := &t.pieces[piece]
762 p.waitNoPendingWrites()
763 ip := t.info.Piece(int(piece))
765 n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
767 missinggo.CopyExact(&ret, hash.Sum(nil))
770 if err != io.ErrUnexpectedEOF && !os.IsNotExist(err) {
771 log.Printf("unexpected error hashing piece with %T: %s", t.storage.TorrentImpl, err)
776 func (t *Torrent) haveAnyPieces() bool {
777 return t.completedPieces.Len() != 0
780 func (t *Torrent) haveAllPieces() bool {
784 return t.completedPieces.Len() == bitmap.BitIndex(t.numPieces())
787 func (t *Torrent) havePiece(index pieceIndex) bool {
788 return t.haveInfo() && t.pieceComplete(index)
791 func (t *Torrent) haveChunk(r request) (ret bool) {
793 // log.Println("have chunk", r, ret)
798 if t.pieceComplete(pieceIndex(r.Index)) {
801 p := &t.pieces[r.Index]
802 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
805 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
806 return int(cs.Begin / chunkSize)
809 func (t *Torrent) wantPiece(r request) bool {
810 if !t.wantPieceIndex(pieceIndex(r.Index)) {
813 if t.pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
816 // TODO: What about pieces that were wanted, but aren't now, and aren't
817 // completed either? That used to be done here.
821 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
825 if index < 0 || index >= t.numPieces() {
828 p := &t.pieces[index]
829 if p.queuedForHash() {
835 if t.pieceComplete(index) {
838 if t.pendingPieces.Contains(bitmap.BitIndex(index)) {
841 // log.Printf("piece %d not pending", index)
842 return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
843 return index < begin || index >= end
847 // The worst connection is one that hasn't been sent, or sent anything useful
848 // for the longest. A bad connection is one that usually sends us unwanted
849 // pieces, or has been in worser half of the established connections for more
851 func (t *Torrent) worstBadConn() *connection {
852 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
855 c := heap.Pop(&wcs).(*connection)
856 if c.stats.ChunksReadWasted.Int64() >= 6 && c.stats.ChunksReadWasted.Int64() > c.stats.ChunksReadUseful.Int64() {
859 // If the connection is in the worst half of the established
860 // connection quota and is older than a minute.
861 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
862 // Give connections 1 minute to prove themselves.
863 if time.Since(c.completedHandshake) > time.Minute {
871 type PieceStateChange struct {
876 func (t *Torrent) publishPieceChange(piece pieceIndex) {
877 cur := t.pieceState(piece)
878 p := &t.pieces[piece]
879 if cur != p.publicPieceState {
880 p.publicPieceState = cur
881 t.pieceStateChanges.Publish(PieceStateChange{
888 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
889 if t.pieceComplete(piece) {
892 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
895 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
896 return t.pieces[piece].dirtyChunks.Len() == int(t.pieceNumChunks(piece))
899 func (t *Torrent) readersChanged() {
900 t.updateReaderPieces()
901 t.updateAllPiecePriorities()
904 func (t *Torrent) updateReaderPieces() {
905 t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
908 func (t *Torrent) readerPosChanged(from, to pieceRange) {
912 t.updateReaderPieces()
913 // Order the ranges, high and low.
915 if l.begin > h.begin {
919 // Two distinct ranges.
920 t.updatePiecePriorities(l.begin, l.end)
921 t.updatePiecePriorities(h.begin, h.end)
928 t.updatePiecePriorities(l.begin, end)
932 func (t *Torrent) maybeNewConns() {
933 // Tickle the accept routine.
934 t.cl.event.Broadcast()
938 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
939 // log.Printf("piece %d priority changed", piece)
940 for c := range t.conns {
941 if c.updatePiecePriority(piece) {
942 // log.Print("conn piece priority changed")
947 t.publishPieceChange(piece)
950 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
951 p := &t.pieces[piece]
952 newPrio := p.uncachedPriority()
953 // log.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
954 if newPrio == PiecePriorityNone {
955 if !t.pendingPieces.Remove(bitmap.BitIndex(piece)) {
959 if !t.pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
963 t.piecePriorityChanged(piece)
966 func (t *Torrent) updateAllPiecePriorities() {
967 t.updatePiecePriorities(0, t.numPieces())
970 // Update all piece priorities in one hit. This function should have the same
971 // output as updatePiecePriority, but across all pieces.
972 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
973 for i := begin; i < end; i++ {
974 t.updatePiecePriority(i)
978 // Returns the range of pieces [begin, end) that contains the extent of bytes.
979 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
980 if off >= *t.length {
990 begin = pieceIndex(off / t.info.PieceLength)
991 end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
992 if end > pieceIndex(t.info.NumPieces()) {
993 end = pieceIndex(t.info.NumPieces())
998 // Returns true if all iterations complete without breaking. Returns the read
999 // regions for all readers. The reader regions should not be merged as some
1000 // callers depend on this method to enumerate readers.
1001 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1002 for r := range t.readers {
1004 if p.begin >= p.end {
1007 if !f(p.begin, p.end) {
1014 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1015 prio, ok := t.pendingPieces.GetPriority(bitmap.BitIndex(piece))
1017 return PiecePriorityNone
1022 ret := piecePriority(-prio)
1023 if ret == PiecePriorityNone {
1029 func (t *Torrent) pendRequest(req request) {
1030 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1031 t.pieces[req.Index].pendChunkIndex(ci)
1034 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1035 log.Call().Add("piece", piece).AddValue(debugLogValue).Log(t.logger)
1036 t.cl.event.Broadcast()
1037 if t.pieceComplete(piece) {
1038 t.onPieceCompleted(piece)
1040 t.onIncompletePiece(piece)
1042 t.updatePiecePriority(piece)
1045 func (t *Torrent) numReceivedConns() (ret int) {
1046 for c := range t.conns {
1047 if c.Discovery == peerSourceIncoming {
1054 func (t *Torrent) maxHalfOpen() int {
1055 // Note that if we somehow exceed the maximum established conns, we want
1056 // the negative value to have an effect.
1057 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1058 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1059 // We want to allow some experimentation with new peers, and to try to
1060 // upset an oversupply of received connections.
1061 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1064 func (t *Torrent) openNewConns() {
1065 defer t.updateWantPeersEvent()
1066 for t.peers.Len() != 0 {
1070 if len(t.halfOpen) >= t.maxHalfOpen() {
1073 p := t.peers.PopMax()
1078 func (t *Torrent) getConnPieceInclination() []int {
1079 _ret := t.connPieceInclinationPool.Get()
1081 pieceInclinationsNew.Add(1)
1082 return rand.Perm(int(t.numPieces()))
1084 pieceInclinationsReused.Add(1)
1085 return *_ret.(*[]int)
1088 func (t *Torrent) putPieceInclination(pi []int) {
1089 t.connPieceInclinationPool.Put(&pi)
1090 pieceInclinationsPut.Add(1)
1093 func (t *Torrent) updatePieceCompletion(piece pieceIndex) {
1094 pcu := t.pieceCompleteUncached(piece)
1095 p := &t.pieces[piece]
1096 changed := t.completedPieces.Get(bitmap.BitIndex(piece)) != pcu.Complete || p.storageCompletionOk != pcu.Ok
1097 log.Fmsg("piece %d completion: %v", piece, pcu.Ok).AddValue(debugLogValue).Log(t.logger)
1098 p.storageCompletionOk = pcu.Ok
1099 t.completedPieces.Set(bitmap.BitIndex(piece), pcu.Complete)
1101 // log.Printf("piece %d uncached completion: %v", piece, pcu.Complete)
1102 // log.Printf("piece %d changed: %v", piece, changed)
1104 t.pieceCompletionChanged(piece)
1108 // Non-blocking read. Client lock is not required.
1109 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1110 p := &t.pieces[off/t.info.PieceLength]
1111 p.waitNoPendingWrites()
1112 return p.Storage().ReadAt(b, off-p.Info().Offset())
1115 func (t *Torrent) updateAllPieceCompletions() {
1116 for i := pieceIndex(0); i < t.numPieces(); i++ {
1117 t.updatePieceCompletion(i)
1121 // Returns an error if the metadata was completed, but couldn't be set for
1122 // some reason. Blame it on the last peer to contribute.
1123 func (t *Torrent) maybeCompleteMetadata() error {
1128 if !t.haveAllMetadataPieces() {
1129 // Don't have enough metadata pieces.
1132 err := t.setInfoBytes(t.metadataBytes)
1134 t.invalidateMetadata()
1135 return fmt.Errorf("error setting info bytes: %s", err)
1137 if t.cl.config.Debug {
1138 log.Printf("%s: got metadata from peers", t)
1143 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1144 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1145 ret.AddRange(bitmap.BitIndex(begin), bitmap.BitIndex(end))
1151 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1152 t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1154 now.Add(bitmap.BitIndex(begin))
1155 readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1162 func (t *Torrent) needData() bool {
1163 if t.closed.IsSet() {
1169 return t.pendingPieces.Len() != 0
1172 func appendMissingStrings(old, new []string) (ret []string) {
1175 for _, n := range new {
1176 for _, o := range old {
1181 ret = append(ret, n)
1186 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1188 for minNumTiers > len(ret) {
1189 ret = append(ret, nil)
1194 func (t *Torrent) addTrackers(announceList [][]string) {
1195 fullAnnounceList := &t.metainfo.AnnounceList
1196 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1197 for tierIndex, trackerURLs := range announceList {
1198 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1200 t.startMissingTrackerScrapers()
1201 t.updateWantPeersEvent()
1204 // Don't call this before the info is available.
1205 func (t *Torrent) bytesCompleted() int64 {
1209 return t.info.TotalLength() - t.bytesLeft()
1212 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1214 defer t.cl.mu.Unlock()
1215 return t.setInfoBytes(b)
1218 // Returns true if connection is removed from torrent.Conns.
1219 func (t *Torrent) deleteConnection(c *connection) (ret bool) {
1220 if !c.closed.IsSet() {
1221 panic("connection is not closed")
1222 // There are behaviours prevented by the closed state that will fail
1223 // if the connection has been deleted.
1227 torrent.Add("deleted connections", 1)
1228 c.deleteAllRequests()
1229 if len(t.conns) == 0 {
1230 t.assertNoPendingRequests()
1235 func (t *Torrent) assertNoPendingRequests() {
1236 if len(t.pendingRequests) != 0 {
1237 panic(t.pendingRequests)
1239 if len(t.lastRequested) != 0 {
1240 panic(t.lastRequested)
1244 func (t *Torrent) dropConnection(c *connection) {
1245 t.cl.event.Broadcast()
1247 if t.deleteConnection(c) {
1252 func (t *Torrent) wantPeers() bool {
1253 if t.closed.IsSet() {
1256 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1259 return t.needData() || t.seeding()
1262 func (t *Torrent) updateWantPeersEvent() {
1264 t.wantPeersEvent.Set()
1266 t.wantPeersEvent.Clear()
1270 // Returns whether the client should make effort to seed the torrent.
1271 func (t *Torrent) seeding() bool {
1273 if t.closed.IsSet() {
1276 if cl.config.NoUpload {
1279 if !cl.config.Seed {
1282 if cl.config.DisableAggressiveUpload && t.needData() {
1288 func (t *Torrent) startScrapingTracker(_url string) {
1292 u, err := url.Parse(_url)
1294 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1295 // TODO: Handle urls with leading '*', some kind of silly uTorrent
1299 if u.Scheme == "udp" {
1301 t.startScrapingTracker(u.String())
1303 t.startScrapingTracker(u.String())
1306 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1309 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1312 if _, ok := t.trackerAnnouncers[_url]; ok {
1315 newAnnouncer := &trackerScraper{
1319 if t.trackerAnnouncers == nil {
1320 t.trackerAnnouncers = make(map[string]*trackerScraper)
1322 t.trackerAnnouncers[_url] = newAnnouncer
1323 go newAnnouncer.Run()
1326 // Adds and starts tracker scrapers for tracker URLs that aren't already
1328 func (t *Torrent) startMissingTrackerScrapers() {
1329 if t.cl.config.DisableTrackers {
1332 t.startScrapingTracker(t.metainfo.Announce)
1333 for _, tier := range t.metainfo.AnnounceList {
1334 for _, url := range tier {
1335 t.startScrapingTracker(url)
1340 // Returns an AnnounceRequest with fields filled out to defaults and current
1342 func (t *Torrent) announceRequest() tracker.AnnounceRequest {
1343 // Note that IPAddress is not set. It's set for UDP inside the tracker
1344 // code, since it's dependent on the network in use.
1345 return tracker.AnnounceRequest{
1346 Event: tracker.None,
1348 Port: uint16(t.cl.incomingPeerPort()),
1349 PeerId: t.cl.peerID,
1350 InfoHash: t.infoHash,
1351 Key: t.cl.announceKey(),
1353 // The following are vaguely described in BEP 3.
1355 Left: t.bytesLeftAnnounce(),
1356 Uploaded: t.stats.BytesWrittenData.Int64(),
1357 // There's no mention of wasted or unwanted download in the BEP.
1358 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1362 // Adds peers revealed in an announce until the announce ends, or we have
1364 func (t *Torrent) consumeDHTAnnounce(pvs <-chan dht.PeersValues) {
1366 // Count all the unique addresses we got during this announce.
1367 allAddrs := make(map[string]struct{})
1370 case v, ok := <-pvs:
1374 addPeers := make([]Peer, 0, len(v.Peers))
1375 for _, cp := range v.Peers {
1377 // Can't do anything with this.
1380 addPeers = append(addPeers, Peer{
1383 Source: peerSourceDHTGetPeers,
1385 key := (&net.UDPAddr{
1389 allAddrs[key] = struct{}{}
1392 t.addPeers(addPeers)
1393 numPeers := t.peers.Len()
1395 if numPeers >= cl.config.TorrentPeersHighWater {
1398 case <-t.closed.LockedChan(&cl.mu):
1404 func (t *Torrent) announceDHT(impliedPort bool, s *dht.Server) (err error) {
1406 ps, err := s.Announce(t.infoHash, cl.incomingPeerPort(), impliedPort)
1410 t.consumeDHTAnnounce(ps.Peers)
1415 func (t *Torrent) dhtAnnouncer(s *dht.Server) {
1419 case <-t.wantPeersEvent.LockedChan(&cl.mu):
1420 case <-t.closed.LockedChan(&cl.mu):
1423 err := t.announceDHT(true, s)
1426 defer cl.mu.Unlock()
1430 log.Printf("error announcing %q to DHT: %s", t, err)
1434 case <-t.closed.LockedChan(&cl.mu):
1436 case <-time.After(5 * time.Minute):
1441 func (t *Torrent) addPeers(peers []Peer) {
1442 for _, p := range peers {
1447 func (t *Torrent) Stats() TorrentStats {
1449 defer t.cl.mu.RUnlock()
1450 return t.statsLocked()
1453 func (t *Torrent) statsLocked() (ret TorrentStats) {
1454 ret.ActivePeers = len(t.conns)
1455 ret.HalfOpenPeers = len(t.halfOpen)
1456 ret.PendingPeers = t.peers.Len()
1457 ret.TotalPeers = t.numTotalPeers()
1458 ret.ConnectedSeeders = 0
1459 for c := range t.conns {
1460 if all, ok := c.peerHasAllPieces(); all && ok {
1461 ret.ConnectedSeeders++
1464 ret.ConnStats = t.stats.Copy()
1468 // The total number of peers in the torrent.
1469 func (t *Torrent) numTotalPeers() int {
1470 peers := make(map[string]struct{})
1471 for conn := range t.conns {
1472 ra := conn.conn.RemoteAddr()
1474 // It's been closed and doesn't support RemoteAddr.
1477 peers[ra.String()] = struct{}{}
1479 for addr := range t.halfOpen {
1480 peers[addr] = struct{}{}
1482 t.peers.Each(func(peer Peer) {
1483 peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{}
1488 // Reconcile bytes transferred before connection was associated with a
1490 func (t *Torrent) reconcileHandshakeStats(c *connection) {
1491 if c.stats != (ConnStats{
1492 // Handshakes should only increment these fields:
1493 BytesWritten: c.stats.BytesWritten,
1494 BytesRead: c.stats.BytesRead,
1498 c.postHandshakeStats(func(cs *ConnStats) {
1499 cs.BytesRead.Add(c.stats.BytesRead.Int64())
1500 cs.BytesWritten.Add(c.stats.BytesWritten.Int64())
1502 c.reconciledHandshakeStats = true
1505 // Returns true if the connection is added.
1506 func (t *Torrent) addConnection(c *connection) (err error) {
1509 torrent.Add("added connections", 1)
1512 if t.closed.IsSet() {
1513 return errors.New("torrent closed")
1515 for c0 := range t.conns {
1516 if c.PeerID != c0.PeerID {
1519 if !t.cl.config.dropDuplicatePeerIds {
1522 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1524 t.deleteConnection(c0)
1526 return errors.New("existing connection preferred")
1529 if len(t.conns) >= t.maxEstablishedConns {
1530 c := t.worstBadConn()
1532 return errors.New("don't want conns")
1534 if t.cl.config.Debug && missinggo.CryHeard() {
1535 log.Printf("%s: dropping connection to make room for new one:\n %v", t, c)
1538 t.deleteConnection(c)
1540 if len(t.conns) >= t.maxEstablishedConns {
1543 t.conns[c] = struct{}{}
1547 func (t *Torrent) wantConns() bool {
1548 if !t.networkingEnabled {
1551 if t.closed.IsSet() {
1554 if !t.seeding() && !t.needData() {
1557 if len(t.conns) < t.maxEstablishedConns {
1560 return t.worstBadConn() != nil
1563 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1565 defer t.cl.mu.Unlock()
1566 oldMax = t.maxEstablishedConns
1567 t.maxEstablishedConns = max
1568 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1569 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1570 t.dropConnection(wcs.Pop().(*connection))
1576 func (t *Torrent) mu() missinggo.RWLocker {
1580 func (t *Torrent) pieceHashed(piece pieceIndex, correct bool) {
1581 log.Fmsg("hashed piece %d", piece).Add("piece", piece).Add("passed", correct).AddValue(debugLogValue).Log(t.logger)
1582 if t.closed.IsSet() {
1585 p := &t.pieces[piece]
1586 touchers := t.reapPieceTouchers(piece)
1587 if p.storageCompletionOk {
1588 // Don't score the first time a piece is hashed, it could be an
1591 pieceHashedCorrect.Add(1)
1593 log.Printf("%s: piece %d (%s) failed hash: %d connections contributed", t, piece, p.hash, len(touchers))
1594 pieceHashedNotCorrect.Add(1)
1598 if len(touchers) != 0 {
1599 // Don't increment stats above connection-level for every involved
1601 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1603 for _, c := range touchers {
1604 c.stats.incrementPiecesDirtiedGood()
1606 err := p.Storage().MarkComplete()
1608 log.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1611 if len(touchers) != 0 {
1612 // Don't increment stats above connection-level for every involved
1614 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1615 for _, c := range touchers {
1616 // Y u do dis peer?!
1617 c.stats.incrementPiecesDirtiedBad()
1619 slices.Sort(touchers, connLessTrusted)
1620 if t.cl.config.Debug {
1621 log.Printf("dropping first corresponding conn from trust: %v", func() (ret []int64) {
1622 for _, c := range touchers {
1623 ret = append(ret, c.netGoodPiecesDirtied())
1629 t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1632 t.onIncompletePiece(piece)
1633 p.Storage().MarkNotComplete()
1635 t.updatePieceCompletion(piece)
1638 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1639 // TODO: Make faster
1640 for cn := range t.conns {
1645 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1646 t.pendAllChunkSpecs(piece)
1647 t.cancelRequestsForPiece(piece)
1648 for conn := range t.conns {
1653 // Called when a piece is found to be not complete.
1654 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1655 if t.pieceAllDirty(piece) {
1656 t.pendAllChunkSpecs(piece)
1658 if !t.wantPieceIndex(piece) {
1659 // log.Printf("piece %d incomplete and unwanted", piece)
1662 // We could drop any connections that we told we have a piece that we
1663 // don't here. But there's a test failure, and it seems clients don't care
1664 // if you request pieces that you already claim to have. Pruning bad
1665 // connections might just remove any connections that aren't treating us
1666 // favourably anyway.
1668 // for c := range t.conns {
1669 // if c.sentHave(piece) {
1673 for conn := range t.conns {
1674 if conn.PeerHasPiece(piece) {
1675 conn.updateRequests()
1680 func (t *Torrent) verifyPiece(piece pieceIndex) {
1683 defer cl.mu.Unlock()
1684 p := &t.pieces[piece]
1687 cl.event.Broadcast()
1689 for p.hashing || t.storage == nil {
1692 if !p.t.piecesQueuedForHash.Remove(bitmap.BitIndex(piece)) {
1693 panic("piece was not queued")
1695 t.updatePiecePriority(piece)
1696 if t.closed.IsSet() || t.pieceComplete(piece) {
1700 t.publishPieceChange(piece)
1701 t.updatePiecePriority(piece)
1702 t.storageLock.RLock()
1704 sum := t.hashPiece(piece)
1705 t.storageLock.RUnlock()
1708 t.updatePiecePriority(piece)
1709 t.pieceHashed(piece, sum == p.hash)
1710 t.publishPieceChange(piece)
1713 // Return the connections that touched a piece, and clear the entries while
1715 func (t *Torrent) reapPieceTouchers(piece pieceIndex) (ret []*connection) {
1716 for c := range t.pieces[piece].dirtiers {
1717 delete(c.peerTouchedPieces, piece)
1718 ret = append(ret, c)
1720 t.pieces[piece].dirtiers = nil
1724 func (t *Torrent) connsAsSlice() (ret []*connection) {
1725 for c := range t.conns {
1726 ret = append(ret, c)
1731 // Currently doesn't really queue, but should in the future.
1732 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1733 piece := &t.pieces[pieceIndex]
1734 if piece.queuedForHash() {
1737 t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1738 t.publishPieceChange(pieceIndex)
1739 t.updatePiecePriority(pieceIndex)
1740 go t.verifyPiece(pieceIndex)
1743 func (t *Torrent) VerifyData() {
1744 for i := pieceIndex(0); i < t.NumPieces(); i++ {
1745 t.Piece(i).VerifyData()
1749 // Start the process of connecting to the given peer for the given torrent if
1751 func (t *Torrent) initiateConn(peer Peer) {
1752 if peer.Id == t.cl.peerID {
1755 if t.cl.badPeerIPPort(peer.IP, peer.Port) {
1758 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
1759 if t.addrActive(addr) {
1762 t.halfOpen[addr] = peer
1763 go t.cl.outgoingConnection(t, addr, peer.Source)
1766 func (t *Torrent) AddClientPeer(cl *Client) {
1767 t.AddPeers(func() (ps []Peer) {
1768 for _, la := range cl.ListenAddrs() {
1769 ps = append(ps, Peer{
1770 IP: missinggo.AddrIP(la),
1771 Port: missinggo.AddrPort(la),
1778 // All stats that include this Torrent. Useful when we want to increment
1779 // ConnStats but not for every connection.
1780 func (t *Torrent) allStats(f func(*ConnStats)) {
1785 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1786 return t.pieces[i].hashing
1789 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1790 return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1793 func (t *Torrent) dialTimeout() time.Duration {
1794 return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())