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/bradfitz/iter"
28 "github.com/davecgh/go-spew/spew"
30 "github.com/anacrolix/torrent/bencode"
31 "github.com/anacrolix/torrent/metainfo"
32 pp "github.com/anacrolix/torrent/peer_protocol"
33 "github.com/anacrolix/torrent/storage"
34 "github.com/anacrolix/torrent/tracker"
37 func (t *Torrent) chunkIndexSpec(chunkIndex, piece int) chunkSpec {
38 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
41 type peersKey struct {
46 // Maintains state of torrent within a Client.
51 networkingEnabled bool
52 // Determines what chunks to request from peers. 1: Favour higher priority
53 // pieces with some fuzzing to reduce overlaps and wastage across
54 // connections. 2: The fastest connection downloads strictly in order of
55 // priority, while all others adher to their piece inclications.
58 closed missinggo.Event
59 infoHash metainfo.Hash
61 // Values are the piece indices that changed.
62 pieceStateChanges *pubsub.PubSub
63 // The size of chunks to request from peers over the wire. This is
64 // normally 16KiB by convention these days.
67 // Total length of the torrent in bytes. Stored because it's not O(1) to
68 // get this from the info dict.
71 // The storage to open when the info dict becomes available.
72 storageOpener *storage.Client
73 // Storage for torrent data.
74 storage *storage.Torrent
75 // Read-locked for using storage, and write-locked for Closing.
76 storageLock sync.RWMutex
78 // TODO: Only announce stuff is used?
79 metainfo metainfo.MetaInfo
81 // The info dict. nil if we don't have it (yet).
85 // Active peer connections, running message stream loops. TODO: Make this
86 // open (not-closed) connections only.
87 conns map[*connection]struct{}
88 maxEstablishedConns int
89 // Set of addrs to which we're attempting to connect. Connections are
90 // half-open until all handshakes are completed.
91 halfOpen map[string]Peer
92 fastestConn *connection
94 // Reserve of peers to connect to. A peer can be both here and in the
95 // active connections if were told about the peer after connecting with
96 // them. That encourages us to reconnect to peers that are well known in
98 peers prioritizedPeers
99 wantPeersEvent missinggo.Event
100 // An announcer for each tracker URL.
101 trackerAnnouncers map[string]*trackerScraper
102 // How many times we've initiated a DHT announce. TODO: Move into stats.
105 // Name used if the info name isn't available. Should be cleared when the
106 // Info does become available.
109 // The bencoded bytes of the info dict. This is actively manipulated if
110 // the info bytes aren't initially available, and we try to fetch them
113 // Each element corresponds to the 16KiB metadata pieces. If true, we have
114 // received that piece.
115 metadataCompletedChunks []bool
116 metadataChanged sync.Cond
118 // Set when .Info is obtained.
119 gotMetainfo missinggo.Event
121 readers map[*reader]struct{}
122 readerNowPieces bitmap.Bitmap
123 readerReadaheadPieces bitmap.Bitmap
125 // A cache of pieces we need to get. Calculated from various piece and
126 // file priorities and completion states elsewhere.
127 pendingPieces prioritybitmap.PriorityBitmap
128 // A cache of completed piece indices.
129 completedPieces bitmap.Bitmap
130 // Pieces that need to be hashed.
131 piecesQueuedForHash bitmap.Bitmap
133 // A pool of piece priorities []int for assignment to new connections.
134 // These "inclinations" are used to give connections preference for
136 connPieceInclinationPool sync.Pool
137 // Torrent-level statistics.
140 // Count of each request across active connections.
141 pendingRequests map[request]int
144 func (t *Torrent) tickleReaders() {
145 t.cl.event.Broadcast()
148 // Returns a channel that is closed when the Torrent is closed.
149 func (t *Torrent) Closed() <-chan struct{} {
150 return t.closed.LockedChan(&t.cl.mu)
153 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
154 // pending, and half-open peers.
155 func (t *Torrent) KnownSwarm() (ks []Peer) {
156 // Add pending peers to the list
157 t.peers.Each(func(peer Peer) {
158 ks = append(ks, peer)
161 // Add half-open peers to the list
162 for _, peer := range t.halfOpen {
163 ks = append(ks, peer)
166 // Add active peers to the list
167 for conn := range t.conns {
168 host, portString, err := net.SplitHostPort(conn.remoteAddr().String())
173 ip := net.ParseIP(host)
174 port, err := strconv.Atoi(portString)
179 ks = append(ks, Peer{
183 Source: conn.Discovery,
184 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
185 // > But if we're not connected to them with an encrypted connection, I couldn't say
186 // > what's appropriate. We can carry forward the SupportsEncryption value as we
187 // > received it from trackers/DHT/PEX, or just use the encryption state for the
188 // > connection. It's probably easiest to do the latter for now.
189 // https://github.com/anacrolix/torrent/pull/188
190 SupportsEncryption: conn.headerEncrypted,
197 func (t *Torrent) setChunkSize(size pp.Integer) {
199 t.chunkPool = &sync.Pool{
200 New: func() interface{} {
201 b := make([]byte, size)
207 func (t *Torrent) setDisplayName(dn string) {
214 func (t *Torrent) pieceComplete(piece int) bool {
215 return t.completedPieces.Get(piece)
218 func (t *Torrent) pieceCompleteUncached(piece int) storage.Completion {
219 return t.pieces[piece].Storage().Completion()
222 // There's a connection to that address already.
223 func (t *Torrent) addrActive(addr string) bool {
224 if _, ok := t.halfOpen[addr]; ok {
227 for c := range t.conns {
232 if ra.String() == addr {
239 func (t *Torrent) unclosedConnsAsSlice() (ret []*connection) {
240 ret = make([]*connection, 0, len(t.conns))
241 for c := range t.conns {
242 if !c.closed.IsSet() {
249 func (t *Torrent) addPeer(p Peer) {
251 peersAddedBySource.Add(string(p.Source), 1)
252 if t.closed.IsSet() {
255 if cl.badPeerIPPort(p.IP, p.Port) {
256 torrent.Add("peers not added because of bad addr", 1)
260 torrent.Add("peers replaced", 1)
263 for t.peers.Len() > cl.config.TorrentPeersHighWater {
264 _, ok := t.peers.DeleteMin()
266 torrent.Add("excess reserve peers discarded", 1)
271 func (t *Torrent) invalidateMetadata() {
272 for i := range t.metadataCompletedChunks {
273 t.metadataCompletedChunks[i] = false
278 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
282 if index >= len(t.metadataCompletedChunks) {
283 log.Printf("%s: ignoring metadata piece %d", t, index)
286 copy(t.metadataBytes[(1<<14)*index:], data)
287 t.metadataCompletedChunks[index] = true
290 func (t *Torrent) metadataPieceCount() int {
291 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
294 func (t *Torrent) haveMetadataPiece(piece int) bool {
296 return (1<<14)*piece < len(t.metadataBytes)
298 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
302 func (t *Torrent) metadataSizeKnown() bool {
303 return t.metadataBytes != nil
306 func (t *Torrent) metadataSize() int {
307 return len(t.metadataBytes)
310 func infoPieceHashes(info *metainfo.Info) (ret []string) {
311 for i := 0; i < len(info.Pieces); i += sha1.Size {
312 ret = append(ret, string(info.Pieces[i:i+sha1.Size]))
317 func (t *Torrent) makePieces() {
318 hashes := infoPieceHashes(t.info)
319 t.pieces = make([]Piece, len(hashes))
320 for i, hash := range hashes {
321 piece := &t.pieces[i]
324 piece.noPendingWrites.L = &piece.pendingWritesMutex
325 missinggo.CopyExact(piece.hash[:], hash)
327 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
328 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
329 piece.files = files[beginFile:endFile]
333 // Returns the index of the first file containing the piece. files must be
334 // ordered by offset.
335 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
336 for i, f := range files {
337 if f.offset+f.length > pieceOffset {
344 // Returns the index after the last file containing the piece. files must be
345 // ordered by offset.
346 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
347 for i, f := range files {
348 if f.offset+f.length >= pieceEndOffset {
355 func (t *Torrent) cacheLength() {
357 for _, f := range t.info.UpvertedFiles() {
363 func (t *Torrent) setInfo(info *metainfo.Info) error {
364 if err := validateInfo(info); err != nil {
365 return fmt.Errorf("bad info: %s", err)
367 if t.storageOpener != nil {
369 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
371 return fmt.Errorf("error opening torrent storage: %s", err)
375 t.displayName = "" // Save a few bytes lol.
382 func (t *Torrent) onSetInfo() {
383 for conn := range t.conns {
384 if err := conn.setNumPieces(t.numPieces()); err != nil {
385 log.Printf("closing connection: %s", err)
389 for i := range t.pieces {
390 t.updatePieceCompletion(i)
392 if !p.storageCompletionOk {
393 // log.Printf("piece %s completion unknown, queueing check", p)
397 t.cl.event.Broadcast()
399 t.updateWantPeersEvent()
400 t.pendingRequests = make(map[request]int)
403 // Called when metadata for a torrent becomes available.
404 func (t *Torrent) setInfoBytes(b []byte) error {
405 if metainfo.HashBytes(b) != t.infoHash {
406 return errors.New("info bytes have wrong hash")
408 var info metainfo.Info
409 if err := bencode.Unmarshal(b, &info); err != nil {
410 return fmt.Errorf("error unmarshalling info bytes: %s", err)
412 if err := t.setInfo(&info); err != nil {
416 t.metadataCompletedChunks = nil
421 func (t *Torrent) haveAllMetadataPieces() bool {
425 if t.metadataCompletedChunks == nil {
428 for _, have := range t.metadataCompletedChunks {
436 // TODO: Propagate errors to disconnect peer.
437 func (t *Torrent) setMetadataSize(bytes int64) (err error) {
439 // We already know the correct metadata size.
442 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
443 return errors.New("bad size")
445 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
448 t.metadataBytes = make([]byte, bytes)
449 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
450 t.metadataChanged.Broadcast()
451 for c := range t.conns {
452 c.requestPendingMetadata()
457 // The current working name for the torrent. Either the name in the info dict,
458 // or a display name given such as by the dn value in a magnet link, or "".
459 func (t *Torrent) name() string {
466 func (t *Torrent) pieceState(index int) (ret PieceState) {
467 p := &t.pieces[index]
468 ret.Priority = t.piecePriority(index)
469 ret.Completion = p.completion()
470 if p.queuedForHash() || p.hashing {
473 if !ret.Complete && t.piecePartiallyDownloaded(index) {
479 func (t *Torrent) metadataPieceSize(piece int) int {
480 return metadataPieceSize(len(t.metadataBytes), piece)
483 func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
489 d["total_size"] = len(t.metadataBytes)
491 p, err := bencode.Marshal(d)
497 ExtendedID: c.PeerExtensionIDs["ut_metadata"],
498 ExtendedPayload: append(p, data...),
502 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
503 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
504 ret = append(ret, PieceStateRun{
505 PieceState: el.(PieceState),
509 for index := range t.pieces {
510 rle.Append(t.pieceState(index), 1)
516 // Produces a small string representing a PieceStateRun.
517 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
518 ret = fmt.Sprintf("%d", psr.Length)
519 ret += func() string {
520 switch psr.Priority {
521 case PiecePriorityNext:
523 case PiecePriorityNormal:
525 case PiecePriorityReadahead:
527 case PiecePriorityNow:
529 case PiecePriorityHigh:
550 func (t *Torrent) writeStatus(w io.Writer) {
551 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
552 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
554 fmt.Fprintf(w, "Metadata have: ")
555 for _, h := range t.metadataCompletedChunks {
556 fmt.Fprintf(w, "%c", func() rune {
566 fmt.Fprintf(w, "Piece length: %s\n", func() string {
568 return fmt.Sprint(t.usualPieceSize())
574 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
575 fmt.Fprint(w, "Piece States:")
576 for _, psr := range t.pieceStateRuns() {
578 w.Write([]byte(pieceStateRunStatusChars(psr)))
582 fmt.Fprintf(w, "Reader Pieces:")
583 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
584 fmt.Fprintf(w, " %d:%d", begin, end)
589 fmt.Fprintf(w, "Enabled trackers:\n")
591 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
592 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
593 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
594 return l.u.String() < r.u.String()
595 }).([]*trackerScraper) {
596 fmt.Fprintf(tw, " %s\n", ta.statusLine())
601 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
603 spew.NewDefaultConfig()
604 spew.Fdump(w, t.statsLocked())
606 conns := t.connsAsSlice()
607 slices.Sort(conns, worseConn)
608 for i, c := range conns {
609 fmt.Fprintf(w, "%2d. ", i+1)
614 func (t *Torrent) haveInfo() bool {
618 // Returns a run-time generated MetaInfo that includes the info bytes and
619 // announce-list as currently known to the client.
620 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
621 return metainfo.MetaInfo{
622 CreationDate: time.Now().Unix(),
623 Comment: "dynamic metainfo from client",
624 CreatedBy: "go.torrent",
625 AnnounceList: t.metainfo.UpvertedAnnounceList(),
626 InfoBytes: func() []byte {
628 return t.metadataBytes
636 func (t *Torrent) BytesMissing() int64 {
638 defer t.mu().RUnlock()
639 return t.bytesMissingLocked()
642 func (t *Torrent) bytesMissingLocked() int64 {
646 func (t *Torrent) bytesLeft() (left int64) {
647 bitmap.Flip(t.completedPieces, 0, t.numPieces()).IterTyped(func(piece int) bool {
648 p := &t.pieces[piece]
649 left += int64(p.length() - p.numDirtyBytes())
655 // Bytes left to give in tracker announces.
656 func (t *Torrent) bytesLeftAnnounce() uint64 {
658 return uint64(t.bytesLeft())
660 return math.MaxUint64
664 func (t *Torrent) piecePartiallyDownloaded(piece int) bool {
665 if t.pieceComplete(piece) {
668 if t.pieceAllDirty(piece) {
671 return t.pieces[piece].hasDirtyChunks()
674 func (t *Torrent) usualPieceSize() int {
675 return int(t.info.PieceLength)
678 func (t *Torrent) numPieces() int {
679 return t.info.NumPieces()
682 func (t *Torrent) numPiecesCompleted() (num int) {
683 return t.completedPieces.Len()
686 func (t *Torrent) close() (err error) {
689 if t.storage != nil {
692 t.storageLock.Unlock()
694 for conn := range t.conns {
697 t.cl.event.Broadcast()
698 t.pieceStateChanges.Close()
699 t.updateWantPeersEvent()
703 func (t *Torrent) requestOffset(r request) int64 {
704 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
707 // Return the request that would include the given offset into the torrent
708 // data. Returns !ok if there is no such request.
709 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
710 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
713 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
714 tr := perf.NewTimer()
716 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
717 if err == nil && n != len(data) {
718 err = io.ErrShortWrite
721 tr.Mark("write chunk")
726 func (t *Torrent) bitfield() (bf []bool) {
727 bf = make([]bool, t.numPieces())
728 t.completedPieces.IterTyped(func(piece int) (again bool) {
735 func (t *Torrent) pieceNumChunks(piece int) int {
736 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
739 func (t *Torrent) pendAllChunkSpecs(pieceIndex int) {
740 t.pieces[pieceIndex].dirtyChunks.Clear()
743 func (t *Torrent) pieceLength(piece int) pp.Integer {
744 if t.info.PieceLength == 0 {
745 // There will be no variance amongst pieces. Only pain.
748 if piece == t.numPieces()-1 {
749 ret := pp.Integer(*t.length % t.info.PieceLength)
754 return pp.Integer(t.info.PieceLength)
757 func (t *Torrent) hashPiece(piece int) (ret metainfo.Hash) {
758 hash := pieceHash.New()
759 p := &t.pieces[piece]
760 p.waitNoPendingWrites()
761 ip := t.info.Piece(piece)
763 n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
765 missinggo.CopyExact(&ret, hash.Sum(nil))
768 if err != io.ErrUnexpectedEOF && !os.IsNotExist(err) {
769 log.Printf("unexpected error hashing piece with %T: %s", t.storage.TorrentImpl, err)
774 func (t *Torrent) haveAnyPieces() bool {
775 return t.completedPieces.Len() != 0
778 func (t *Torrent) haveAllPieces() bool {
782 return t.completedPieces.Len() == t.numPieces()
785 func (t *Torrent) havePiece(index int) bool {
786 return t.haveInfo() && t.pieceComplete(index)
789 func (t *Torrent) haveChunk(r request) (ret bool) {
791 // log.Println("have chunk", r, ret)
796 if t.pieceComplete(int(r.Index)) {
799 p := &t.pieces[r.Index]
800 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
803 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
804 return int(cs.Begin / chunkSize)
807 func (t *Torrent) wantPiece(r request) bool {
808 if !t.wantPieceIndex(int(r.Index)) {
811 if t.pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
814 // TODO: What about pieces that were wanted, but aren't now, and aren't
815 // completed either? That used to be done here.
819 func (t *Torrent) wantPieceIndex(index int) bool {
823 if index < 0 || index >= t.numPieces() {
826 p := &t.pieces[index]
827 if p.queuedForHash() {
833 if t.pieceComplete(index) {
836 if t.pendingPieces.Contains(index) {
839 // log.Printf("piece %d not pending", index)
840 return !t.forReaderOffsetPieces(func(begin, end int) bool {
841 return index < begin || index >= end
845 // The worst connection is one that hasn't been sent, or sent anything useful
846 // for the longest. A bad connection is one that usually sends us unwanted
847 // pieces, or has been in worser half of the established connections for more
849 func (t *Torrent) worstBadConn() *connection {
850 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
853 c := heap.Pop(&wcs).(*connection)
854 if c.stats.ChunksReadUnwanted.Int64() >= 6 && c.stats.ChunksReadUnwanted.Int64() > c.stats.ChunksReadUseful.Int64() {
857 // If the connection is in the worst half of the established
858 // connection quota and is older than a minute.
859 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
860 // Give connections 1 minute to prove themselves.
861 if time.Since(c.completedHandshake) > time.Minute {
869 type PieceStateChange struct {
874 func (t *Torrent) publishPieceChange(piece int) {
875 cur := t.pieceState(piece)
876 p := &t.pieces[piece]
877 if cur != p.publicPieceState {
878 p.publicPieceState = cur
879 t.pieceStateChanges.Publish(PieceStateChange{
886 func (t *Torrent) pieceNumPendingChunks(piece int) int {
887 if t.pieceComplete(piece) {
890 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
893 func (t *Torrent) pieceAllDirty(piece int) bool {
894 return t.pieces[piece].dirtyChunks.Len() == t.pieceNumChunks(piece)
897 func (t *Torrent) readersChanged() {
898 t.updateReaderPieces()
899 t.updateAllPiecePriorities()
902 func (t *Torrent) updateReaderPieces() {
903 t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
906 func (t *Torrent) readerPosChanged(from, to pieceRange) {
910 t.updateReaderPieces()
911 // Order the ranges, high and low.
913 if l.begin > h.begin {
917 // Two distinct ranges.
918 t.updatePiecePriorities(l.begin, l.end)
919 t.updatePiecePriorities(h.begin, h.end)
926 t.updatePiecePriorities(l.begin, end)
930 func (t *Torrent) maybeNewConns() {
931 // Tickle the accept routine.
932 t.cl.event.Broadcast()
936 func (t *Torrent) piecePriorityChanged(piece int) {
937 // log.Printf("piece %d priority changed", piece)
938 for c := range t.conns {
939 if c.updatePiecePriority(piece) {
940 // log.Print("conn piece priority changed")
945 t.publishPieceChange(piece)
948 func (t *Torrent) updatePiecePriority(piece int) {
949 p := &t.pieces[piece]
950 newPrio := p.uncachedPriority()
951 // log.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
952 if newPrio == PiecePriorityNone {
953 if !t.pendingPieces.Remove(piece) {
957 if !t.pendingPieces.Set(piece, newPrio.BitmapPriority()) {
961 t.piecePriorityChanged(piece)
964 func (t *Torrent) updateAllPiecePriorities() {
965 t.updatePiecePriorities(0, len(t.pieces))
968 // Update all piece priorities in one hit. This function should have the same
969 // output as updatePiecePriority, but across all pieces.
970 func (t *Torrent) updatePiecePriorities(begin, end int) {
971 for i := begin; i < end; i++ {
972 t.updatePiecePriority(i)
976 // Returns the range of pieces [begin, end) that contains the extent of bytes.
977 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end int) {
978 if off >= *t.length {
988 begin = int(off / t.info.PieceLength)
989 end = int((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
990 if end > t.info.NumPieces() {
991 end = t.info.NumPieces()
996 // Returns true if all iterations complete without breaking. Returns the read
997 // regions for all readers. The reader regions should not be merged as some
998 // callers depend on this method to enumerate readers.
999 func (t *Torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
1000 for r := range t.readers {
1002 if p.begin >= p.end {
1005 if !f(p.begin, p.end) {
1012 func (t *Torrent) piecePriority(piece int) piecePriority {
1013 prio, ok := t.pendingPieces.GetPriority(piece)
1015 return PiecePriorityNone
1020 ret := piecePriority(-prio)
1021 if ret == PiecePriorityNone {
1027 func (t *Torrent) pendRequest(req request) {
1028 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1029 t.pieces[req.Index].pendChunkIndex(ci)
1032 func (t *Torrent) pieceCompletionChanged(piece int) {
1033 log.Call().Add("piece", piece).AddValue(debugLogValue).Log(t.logger)
1034 t.cl.event.Broadcast()
1035 if t.pieceComplete(piece) {
1036 t.onPieceCompleted(piece)
1038 t.onIncompletePiece(piece)
1040 t.updatePiecePriority(piece)
1043 func (t *Torrent) numReceivedConns() (ret int) {
1044 for c := range t.conns {
1045 if c.Discovery == peerSourceIncoming {
1052 func (t *Torrent) maxHalfOpen() int {
1053 // Note that if we somehow exceed the maximum established conns, we want
1054 // the negative value to have an effect.
1055 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1056 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1057 // We want to allow some experimentation with new peers, and to try to
1058 // upset an oversupply of received connections.
1059 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.halfOpenLimit)))
1062 func (t *Torrent) openNewConns() {
1063 defer t.updateWantPeersEvent()
1064 for t.peers.Len() != 0 {
1068 if len(t.halfOpen) >= t.maxHalfOpen() {
1071 p := t.peers.PopMax()
1076 func (t *Torrent) getConnPieceInclination() []int {
1077 _ret := t.connPieceInclinationPool.Get()
1079 pieceInclinationsNew.Add(1)
1080 return rand.Perm(t.numPieces())
1082 pieceInclinationsReused.Add(1)
1083 return *_ret.(*[]int)
1086 func (t *Torrent) putPieceInclination(pi []int) {
1087 t.connPieceInclinationPool.Put(&pi)
1088 pieceInclinationsPut.Add(1)
1091 func (t *Torrent) updatePieceCompletion(piece int) {
1092 pcu := t.pieceCompleteUncached(piece)
1093 p := &t.pieces[piece]
1094 changed := t.completedPieces.Get(piece) != pcu.Complete || p.storageCompletionOk != pcu.Ok
1095 log.Fmsg("piece %d completion: %v", piece, pcu.Ok).AddValue(debugLogValue).Log(t.logger)
1096 p.storageCompletionOk = pcu.Ok
1097 t.completedPieces.Set(piece, pcu.Complete)
1099 // log.Printf("piece %d uncached completion: %v", piece, pcu.Complete)
1100 // log.Printf("piece %d changed: %v", piece, changed)
1102 t.pieceCompletionChanged(piece)
1106 // Non-blocking read. Client lock is not required.
1107 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1108 p := &t.pieces[off/t.info.PieceLength]
1109 p.waitNoPendingWrites()
1110 return p.Storage().ReadAt(b, off-p.Info().Offset())
1113 func (t *Torrent) updateAllPieceCompletions() {
1114 for i := range iter.N(t.numPieces()) {
1115 t.updatePieceCompletion(i)
1119 // Returns an error if the metadata was completed, but couldn't be set for
1120 // some reason. Blame it on the last peer to contribute.
1121 func (t *Torrent) maybeCompleteMetadata() error {
1126 if !t.haveAllMetadataPieces() {
1127 // Don't have enough metadata pieces.
1130 err := t.setInfoBytes(t.metadataBytes)
1132 t.invalidateMetadata()
1133 return fmt.Errorf("error setting info bytes: %s", err)
1135 if t.cl.config.Debug {
1136 log.Printf("%s: got metadata from peers", t)
1141 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1142 t.forReaderOffsetPieces(func(begin, end int) bool {
1143 ret.AddRange(begin, end)
1149 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1150 t.forReaderOffsetPieces(func(begin, end int) bool {
1153 readahead.AddRange(begin+1, end)
1160 func (t *Torrent) needData() bool {
1161 if t.closed.IsSet() {
1167 return t.pendingPieces.Len() != 0
1170 func appendMissingStrings(old, new []string) (ret []string) {
1173 for _, n := range new {
1174 for _, o := range old {
1179 ret = append(ret, n)
1184 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1186 for minNumTiers > len(ret) {
1187 ret = append(ret, nil)
1192 func (t *Torrent) addTrackers(announceList [][]string) {
1193 fullAnnounceList := &t.metainfo.AnnounceList
1194 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1195 for tierIndex, trackerURLs := range announceList {
1196 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1198 t.startMissingTrackerScrapers()
1199 t.updateWantPeersEvent()
1202 // Don't call this before the info is available.
1203 func (t *Torrent) bytesCompleted() int64 {
1207 return t.info.TotalLength() - t.bytesLeft()
1210 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1212 defer t.cl.mu.Unlock()
1213 return t.setInfoBytes(b)
1216 // Returns true if connection is removed from torrent.Conns.
1217 func (t *Torrent) deleteConnection(c *connection) (ret bool) {
1218 if !c.closed.IsSet() {
1219 panic("connection is not closed")
1220 // There are behaviours prevented by the closed state that will fail
1221 // if the connection has been deleted.
1225 torrent.Add("deleted connections", 1)
1226 c.deleteAllRequests()
1227 if len(t.conns) == 0 {
1228 t.assertNoPendingRequests()
1233 func (t *Torrent) assertNoPendingRequests() {
1234 for _, num := range t.pendingRequests {
1241 func (t *Torrent) dropConnection(c *connection) {
1242 t.cl.event.Broadcast()
1244 if t.deleteConnection(c) {
1249 func (t *Torrent) wantPeers() bool {
1250 if t.closed.IsSet() {
1253 if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1256 return t.needData() || t.seeding()
1259 func (t *Torrent) updateWantPeersEvent() {
1261 t.wantPeersEvent.Set()
1263 t.wantPeersEvent.Clear()
1267 // Returns whether the client should make effort to seed the torrent.
1268 func (t *Torrent) seeding() bool {
1270 if t.closed.IsSet() {
1273 if cl.config.NoUpload {
1276 if !cl.config.Seed {
1279 if cl.config.DisableAggressiveUpload && t.needData() {
1285 func (t *Torrent) startScrapingTracker(_url string) {
1289 u, _ := url.Parse(_url)
1290 if u.Scheme == "udp" {
1292 t.startScrapingTracker(u.String())
1294 t.startScrapingTracker(u.String())
1297 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1300 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1303 if _, ok := t.trackerAnnouncers[_url]; ok {
1306 newAnnouncer := &trackerScraper{
1310 if t.trackerAnnouncers == nil {
1311 t.trackerAnnouncers = make(map[string]*trackerScraper)
1313 t.trackerAnnouncers[_url] = newAnnouncer
1314 go newAnnouncer.Run()
1317 // Adds and starts tracker scrapers for tracker URLs that aren't already
1319 func (t *Torrent) startMissingTrackerScrapers() {
1320 if t.cl.config.DisableTrackers {
1323 t.startScrapingTracker(t.metainfo.Announce)
1324 for _, tier := range t.metainfo.AnnounceList {
1325 for _, url := range tier {
1326 t.startScrapingTracker(url)
1331 // Returns an AnnounceRequest with fields filled out to defaults and current
1333 func (t *Torrent) announceRequest() tracker.AnnounceRequest {
1334 // Note that IPAddress is not set. It's set for UDP inside the tracker
1335 // code, since it's dependent on the network in use.
1336 return tracker.AnnounceRequest{
1337 Event: tracker.None,
1339 Port: uint16(t.cl.incomingPeerPort()),
1340 PeerId: t.cl.peerID,
1341 InfoHash: t.infoHash,
1342 Key: t.cl.announceKey(),
1344 // The following are vaguely described in BEP 3.
1346 Left: t.bytesLeftAnnounce(),
1347 Uploaded: t.stats.BytesWrittenData.Int64(),
1348 // There's no mention of wasted or unwanted download in the BEP.
1349 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1353 // Adds peers revealed in an announce until the announce ends, or we have
1355 func (t *Torrent) consumeDHTAnnounce(pvs <-chan dht.PeersValues) {
1357 // Count all the unique addresses we got during this announce.
1358 allAddrs := make(map[string]struct{})
1361 case v, ok := <-pvs:
1365 addPeers := make([]Peer, 0, len(v.Peers))
1366 for _, cp := range v.Peers {
1368 // Can't do anything with this.
1371 addPeers = append(addPeers, Peer{
1374 Source: peerSourceDHTGetPeers,
1376 key := (&net.UDPAddr{
1380 allAddrs[key] = struct{}{}
1383 t.addPeers(addPeers)
1384 numPeers := t.peers.Len()
1386 if numPeers >= cl.config.TorrentPeersHighWater {
1389 case <-t.closed.LockedChan(&cl.mu):
1395 func (t *Torrent) announceDHT(impliedPort bool, s *dht.Server) (err error) {
1397 ps, err := s.Announce(t.infoHash, cl.incomingPeerPort(), impliedPort)
1401 t.consumeDHTAnnounce(ps.Peers)
1406 func (t *Torrent) dhtAnnouncer(s *dht.Server) {
1410 case <-t.wantPeersEvent.LockedChan(&cl.mu):
1411 case <-t.closed.LockedChan(&cl.mu):
1414 err := t.announceDHT(true, s)
1417 defer cl.mu.Unlock()
1421 log.Printf("error announcing %q to DHT: %s", t, err)
1425 case <-t.closed.LockedChan(&cl.mu):
1427 case <-time.After(5 * time.Minute):
1432 func (t *Torrent) addPeers(peers []Peer) {
1433 for _, p := range peers {
1438 func (t *Torrent) Stats() TorrentStats {
1440 defer t.cl.mu.Unlock()
1441 return t.statsLocked()
1444 func (t *Torrent) statsLocked() (ret TorrentStats) {
1445 ret.ActivePeers = len(t.conns)
1446 ret.HalfOpenPeers = len(t.halfOpen)
1447 ret.PendingPeers = t.peers.Len()
1448 ret.TotalPeers = t.numTotalPeers()
1449 ret.ConnectedSeeders = 0
1450 for c := range t.conns {
1451 if all, ok := c.peerHasAllPieces(); all && ok {
1452 ret.ConnectedSeeders++
1455 ret.ConnStats = t.stats.Copy()
1459 // The total number of peers in the torrent.
1460 func (t *Torrent) numTotalPeers() int {
1461 peers := make(map[string]struct{})
1462 for conn := range t.conns {
1463 ra := conn.conn.RemoteAddr()
1465 // It's been closed and doesn't support RemoteAddr.
1468 peers[ra.String()] = struct{}{}
1470 for addr := range t.halfOpen {
1471 peers[addr] = struct{}{}
1473 t.peers.Each(func(peer Peer) {
1474 peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{}
1479 // Reconcile bytes transferred before connection was associated with a
1481 func (t *Torrent) reconcileHandshakeStats(c *connection) {
1482 if c.stats != (ConnStats{
1483 // Handshakes should only increment these fields:
1484 BytesWritten: c.stats.BytesWritten,
1485 BytesRead: c.stats.BytesRead,
1489 c.postHandshakeStats(func(cs *ConnStats) {
1490 cs.BytesRead.Add(c.stats.BytesRead.Int64())
1491 cs.BytesWritten.Add(c.stats.BytesWritten.Int64())
1493 c.reconciledHandshakeStats = true
1496 // Returns true if the connection is added.
1497 func (t *Torrent) addConnection(c *connection) (err error) {
1500 torrent.Add("added connections", 1)
1503 if t.closed.IsSet() {
1504 return errors.New("torrent closed")
1507 return errors.New("don't want conns")
1509 if len(t.conns) >= t.maxEstablishedConns {
1510 c := t.worstBadConn()
1511 if t.cl.config.Debug && missinggo.CryHeard() {
1512 log.Printf("%s: dropping connection to make room for new one:\n %v", t, c)
1515 t.deleteConnection(c)
1517 if len(t.conns) >= t.maxEstablishedConns {
1520 t.conns[c] = struct{}{}
1524 func (t *Torrent) wantConns() bool {
1525 if !t.networkingEnabled {
1528 if t.closed.IsSet() {
1531 if !t.seeding() && !t.needData() {
1534 if len(t.conns) < t.maxEstablishedConns {
1537 return t.worstBadConn() != nil
1540 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1542 defer t.cl.mu.Unlock()
1543 oldMax = t.maxEstablishedConns
1544 t.maxEstablishedConns = max
1545 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1546 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1547 t.dropConnection(wcs.Pop().(*connection))
1553 func (t *Torrent) mu() missinggo.RWLocker {
1557 func (t *Torrent) pieceHashed(piece int, correct bool) {
1558 log.Fmsg("hashed piece %d", piece).Add("piece", piece).Add("passed", correct).AddValue(debugLogValue).Log(t.logger)
1559 if t.closed.IsSet() {
1562 p := &t.pieces[piece]
1563 touchers := t.reapPieceTouchers(piece)
1564 if p.storageCompletionOk {
1565 // Don't score the first time a piece is hashed, it could be an
1568 pieceHashedCorrect.Add(1)
1570 log.Printf("%s: piece %d (%s) failed hash: %d connections contributed", t, piece, p.hash, len(touchers))
1571 pieceHashedNotCorrect.Add(1)
1575 if len(touchers) != 0 {
1576 // Don't increment stats above connection-level for every involved
1578 t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1580 for _, c := range touchers {
1581 c.stats.incrementPiecesDirtiedGood()
1583 err := p.Storage().MarkComplete()
1585 log.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1588 if len(touchers) != 0 {
1589 // Don't increment stats above connection-level for every involved
1591 t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1592 for _, c := range touchers {
1593 // Y u do dis peer?!
1594 c.stats.incrementPiecesDirtiedBad()
1596 slices.Sort(touchers, connLessTrusted)
1597 if t.cl.config.Debug {
1598 log.Printf("dropping first corresponding conn from trust: %v", func() (ret []int64) {
1599 for _, c := range touchers {
1600 ret = append(ret, c.netGoodPiecesDirtied())
1606 t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1609 t.onIncompletePiece(piece)
1610 p.Storage().MarkNotComplete()
1612 t.updatePieceCompletion(piece)
1615 func (t *Torrent) cancelRequestsForPiece(piece int) {
1616 // TODO: Make faster
1617 for cn := range t.conns {
1622 func (t *Torrent) onPieceCompleted(piece int) {
1623 t.pendAllChunkSpecs(piece)
1624 t.cancelRequestsForPiece(piece)
1625 for conn := range t.conns {
1630 // Called when a piece is found to be not complete.
1631 func (t *Torrent) onIncompletePiece(piece int) {
1632 if t.pieceAllDirty(piece) {
1633 t.pendAllChunkSpecs(piece)
1635 if !t.wantPieceIndex(piece) {
1636 // log.Printf("piece %d incomplete and unwanted", piece)
1639 // We could drop any connections that we told we have a piece that we
1640 // don't here. But there's a test failure, and it seems clients don't care
1641 // if you request pieces that you already claim to have. Pruning bad
1642 // connections might just remove any connections that aren't treating us
1643 // favourably anyway.
1645 // for c := range t.conns {
1646 // if c.sentHave(piece) {
1650 for conn := range t.conns {
1651 if conn.PeerHasPiece(piece) {
1652 conn.updateRequests()
1657 func (t *Torrent) verifyPiece(piece int) {
1660 defer cl.mu.Unlock()
1661 p := &t.pieces[piece]
1664 cl.event.Broadcast()
1666 for p.hashing || t.storage == nil {
1669 if !p.t.piecesQueuedForHash.Remove(piece) {
1670 panic("piece was not queued")
1672 if t.closed.IsSet() || t.pieceComplete(piece) {
1673 t.updatePiecePriority(piece)
1677 t.publishPieceChange(piece)
1678 t.storageLock.RLock()
1680 sum := t.hashPiece(piece)
1681 t.storageLock.RUnlock()
1684 t.pieceHashed(piece, sum == p.hash)
1685 t.publishPieceChange(piece)
1688 // Return the connections that touched a piece, and clear the entries while
1690 func (t *Torrent) reapPieceTouchers(piece int) (ret []*connection) {
1691 for c := range t.pieces[piece].dirtiers {
1692 delete(c.peerTouchedPieces, piece)
1693 ret = append(ret, c)
1695 t.pieces[piece].dirtiers = nil
1699 func (t *Torrent) connsAsSlice() (ret []*connection) {
1700 for c := range t.conns {
1701 ret = append(ret, c)
1706 // Currently doesn't really queue, but should in the future.
1707 func (t *Torrent) queuePieceCheck(pieceIndex int) {
1708 piece := &t.pieces[pieceIndex]
1709 if piece.queuedForHash() {
1712 t.piecesQueuedForHash.Add(pieceIndex)
1713 t.publishPieceChange(pieceIndex)
1714 go t.verifyPiece(pieceIndex)
1717 func (t *Torrent) VerifyData() {
1718 for i := range iter.N(t.NumPieces()) {
1719 t.Piece(i).VerifyData()
1723 // Start the process of connecting to the given peer for the given torrent if
1725 func (t *Torrent) initiateConn(peer Peer) {
1726 if peer.Id == t.cl.peerID {
1729 if t.cl.badPeerIPPort(peer.IP, peer.Port) {
1732 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
1733 if t.addrActive(addr) {
1736 t.halfOpen[addr] = peer
1737 go t.cl.outgoingConnection(t, addr, peer.Source)
1740 func (t *Torrent) AddClientPeer(cl *Client) {
1741 t.AddPeers(func() (ps []Peer) {
1742 for _, la := range cl.ListenAddrs() {
1743 ps = append(ps, Peer{
1744 IP: missinggo.AddrIP(la),
1745 Port: missinggo.AddrPort(la),
1752 // All stats that include this Torrent. Useful when we want to increment
1753 // ConnStats but not for every connection.
1754 func (t *Torrent) allStats(f func(*ConnStats)) {