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/bradfitz/iter"
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, piece int) chunkSpec {
37 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
40 type peersKey struct {
45 // Maintains state of torrent within a Client.
50 networkingEnabled bool
51 // Determines what chunks to request from peers. 1: Favour higher priority
52 // pieces with some fuzzing to reduce overlaps and wastage across
53 // connections. 2: The fastest connection downloads strictly in order of
54 // priority, while all others adher to their piece inclications.
57 closed missinggo.Event
58 infoHash metainfo.Hash
60 // Values are the piece indices that changed.
61 pieceStateChanges *pubsub.PubSub
62 // The size of chunks to request from peers over the wire. This is
63 // normally 16KiB by convention these days.
66 // Total length of the torrent in bytes. Stored because it's not O(1) to
67 // get this from the info dict.
70 // The storage to open when the info dict becomes available.
71 storageOpener *storage.Client
72 // Storage for torrent data.
73 storage *storage.Torrent
74 // Read-locked for using storage, and write-locked for Closing.
75 storageLock sync.RWMutex
77 metainfo metainfo.MetaInfo
79 // The info dict. nil if we don't have it (yet).
83 // Active peer connections, running message stream loops.
84 conns map[*connection]struct{}
85 maxEstablishedConns int
86 // Set of addrs to which we're attempting to connect. Connections are
87 // half-open until all handshakes are completed.
88 halfOpen map[string]Peer
89 fastestConn *connection
91 // Reserve of peers to connect to. A peer can be both here and in the
92 // active connections if were told about the peer after connecting with
93 // them. That encourages us to reconnect to peers that are well known in
95 peers map[peersKey]Peer
96 wantPeersEvent missinggo.Event
97 // An announcer for each tracker URL.
98 trackerAnnouncers map[string]*trackerScraper
99 // How many times we've initiated a DHT announce. TODO: Move into stats.
102 // Name used if the info name isn't available. Should be cleared when the
103 // Info does become available.
106 // The bencoded bytes of the info dict. This is actively manipulated if
107 // the info bytes aren't initially available, and we try to fetch them
110 // Each element corresponds to the 16KiB metadata pieces. If true, we have
111 // received that piece.
112 metadataCompletedChunks []bool
113 metadataChanged sync.Cond
115 // Set when .Info is obtained.
116 gotMetainfo missinggo.Event
118 readers map[*reader]struct{}
119 readerNowPieces bitmap.Bitmap
120 readerReadaheadPieces bitmap.Bitmap
122 // A cache of pieces we need to get. Calculated from various piece and
123 // file priorities and completion states elsewhere.
124 pendingPieces prioritybitmap.PriorityBitmap
125 // A cache of completed piece indices.
126 completedPieces bitmap.Bitmap
127 // Pieces that need to be hashed.
128 piecesQueuedForHash bitmap.Bitmap
130 // A pool of piece priorities []int for assignment to new connections.
131 // These "inclinations" are used to give connections preference for
133 connPieceInclinationPool sync.Pool
134 // Torrent-level statistics.
137 pendingRequests map[request]int
140 // Returns a channel that is closed when the Torrent is closed.
141 func (t *Torrent) Closed() <-chan struct{} {
142 return t.closed.LockedChan(&t.cl.mu)
145 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
146 // pending, and half-open peers.
147 func (t *Torrent) KnownSwarm() (ks []Peer) {
148 // Add pending peers to the list
149 for _, peer := range t.peers {
150 ks = append(ks, peer)
153 // Add half-open peers to the list
154 for _, peer := range t.halfOpen {
155 ks = append(ks, peer)
158 // Add active peers to the list
159 for conn := range t.conns {
160 host, portString, err := net.SplitHostPort(conn.remoteAddr().String())
165 ip := net.ParseIP(host)
166 port, err := strconv.Atoi(portString)
171 ks = append(ks, Peer{
175 Source: conn.Discovery,
176 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
177 // > But if we're not connected to them with an encrypted connection, I couldn't say
178 // > what's appropriate. We can carry forward the SupportsEncryption value as we
179 // > received it from trackers/DHT/PEX, or just use the encryption state for the
180 // > connection. It's probably easiest to do the latter for now.
181 // https://github.com/anacrolix/torrent/pull/188
182 SupportsEncryption: conn.headerEncrypted,
189 func (t *Torrent) setChunkSize(size pp.Integer) {
191 t.chunkPool = &sync.Pool{
192 New: func() interface{} {
193 b := make([]byte, size)
199 func (t *Torrent) setDisplayName(dn string) {
206 func (t *Torrent) pieceComplete(piece int) bool {
207 return t.completedPieces.Get(piece)
210 func (t *Torrent) pieceCompleteUncached(piece int) storage.Completion {
211 return t.pieces[piece].Storage().Completion()
214 // There's a connection to that address already.
215 func (t *Torrent) addrActive(addr string) bool {
216 if _, ok := t.halfOpen[addr]; ok {
219 for c := range t.conns {
224 if ra.String() == addr {
231 func (t *Torrent) unclosedConnsAsSlice() (ret []*connection) {
232 ret = make([]*connection, 0, len(t.conns))
233 for c := range t.conns {
234 if !c.closed.IsSet() {
241 func (t *Torrent) addPeer(p Peer) {
244 if len(t.peers) >= cl.config.TorrentPeersHighWater {
247 key := peersKey{string(p.IP), p.Port}
248 if _, ok := t.peers[key]; ok {
252 peersAddedBySource.Add(string(p.Source), 1)
257 func (t *Torrent) invalidateMetadata() {
258 for i := range t.metadataCompletedChunks {
259 t.metadataCompletedChunks[i] = false
264 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
268 if index >= len(t.metadataCompletedChunks) {
269 log.Printf("%s: ignoring metadata piece %d", t, index)
272 copy(t.metadataBytes[(1<<14)*index:], data)
273 t.metadataCompletedChunks[index] = true
276 func (t *Torrent) metadataPieceCount() int {
277 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
280 func (t *Torrent) haveMetadataPiece(piece int) bool {
282 return (1<<14)*piece < len(t.metadataBytes)
284 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
288 func (t *Torrent) metadataSizeKnown() bool {
289 return t.metadataBytes != nil
292 func (t *Torrent) metadataSize() int {
293 return len(t.metadataBytes)
296 func infoPieceHashes(info *metainfo.Info) (ret []string) {
297 for i := 0; i < len(info.Pieces); i += sha1.Size {
298 ret = append(ret, string(info.Pieces[i:i+sha1.Size]))
303 func (t *Torrent) makePieces() {
304 hashes := infoPieceHashes(t.info)
305 t.pieces = make([]Piece, len(hashes))
306 for i, hash := range hashes {
307 piece := &t.pieces[i]
310 piece.noPendingWrites.L = &piece.pendingWritesMutex
311 missinggo.CopyExact(piece.hash[:], hash)
313 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
314 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
315 piece.files = files[beginFile:endFile]
319 // Returns the index of the first file containing the piece. files must be
320 // ordered by offset.
321 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
322 for i, f := range files {
323 if f.offset+f.length > pieceOffset {
330 // Returns the index after the last file containing the piece. files must be
331 // ordered by offset.
332 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
333 for i, f := range files {
334 if f.offset+f.length >= pieceEndOffset {
341 func (t *Torrent) cacheLength() {
343 for _, f := range t.info.UpvertedFiles() {
349 func (t *Torrent) setInfo(info *metainfo.Info) error {
350 if err := validateInfo(info); err != nil {
351 return fmt.Errorf("bad info: %s", err)
353 if t.storageOpener != nil {
355 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
357 return fmt.Errorf("error opening torrent storage: %s", err)
361 t.displayName = "" // Save a few bytes lol.
368 func (t *Torrent) onSetInfo() {
369 for conn := range t.conns {
370 if err := conn.setNumPieces(t.numPieces()); err != nil {
371 log.Printf("closing connection: %s", err)
375 for i := range t.pieces {
376 t.updatePieceCompletion(i)
378 if !p.storageCompletionOk {
379 // log.Printf("piece %s completion unknown, queueing check", p)
383 t.cl.event.Broadcast()
385 t.updateWantPeersEvent()
386 t.pendingRequests = make(map[request]int)
389 // Called when metadata for a torrent becomes available.
390 func (t *Torrent) setInfoBytes(b []byte) error {
391 if metainfo.HashBytes(b) != t.infoHash {
392 return errors.New("info bytes have wrong hash")
394 var info metainfo.Info
395 if err := bencode.Unmarshal(b, &info); err != nil {
396 return fmt.Errorf("error unmarshalling info bytes: %s", err)
398 if err := t.setInfo(&info); err != nil {
402 t.metadataCompletedChunks = nil
407 func (t *Torrent) haveAllMetadataPieces() bool {
411 if t.metadataCompletedChunks == nil {
414 for _, have := range t.metadataCompletedChunks {
422 // TODO: Propagate errors to disconnect peer.
423 func (t *Torrent) setMetadataSize(bytes int64) (err error) {
425 // We already know the correct metadata size.
428 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
429 return errors.New("bad size")
431 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
434 t.metadataBytes = make([]byte, bytes)
435 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
436 t.metadataChanged.Broadcast()
437 for c := range t.conns {
438 c.requestPendingMetadata()
443 // The current working name for the torrent. Either the name in the info dict,
444 // or a display name given such as by the dn value in a magnet link, or "".
445 func (t *Torrent) name() string {
452 func (t *Torrent) pieceState(index int) (ret PieceState) {
453 p := &t.pieces[index]
454 ret.Priority = t.piecePriority(index)
455 ret.Completion = p.completion()
456 if p.queuedForHash() || p.hashing {
459 if !ret.Complete && t.piecePartiallyDownloaded(index) {
465 func (t *Torrent) metadataPieceSize(piece int) int {
466 return metadataPieceSize(len(t.metadataBytes), piece)
469 func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
475 d["total_size"] = len(t.metadataBytes)
477 p, err := bencode.Marshal(d)
483 ExtendedID: c.PeerExtensionIDs["ut_metadata"],
484 ExtendedPayload: append(p, data...),
488 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
489 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
490 ret = append(ret, PieceStateRun{
491 PieceState: el.(PieceState),
495 for index := range t.pieces {
496 rle.Append(t.pieceState(index), 1)
502 // Produces a small string representing a PieceStateRun.
503 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
504 ret = fmt.Sprintf("%d", psr.Length)
505 ret += func() string {
506 switch psr.Priority {
507 case PiecePriorityNext:
509 case PiecePriorityNormal:
511 case PiecePriorityReadahead:
513 case PiecePriorityNow:
515 case PiecePriorityHigh:
536 func (t *Torrent) writeStatus(w io.Writer) {
537 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
538 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
540 fmt.Fprintf(w, "Metadata have: ")
541 for _, h := range t.metadataCompletedChunks {
542 fmt.Fprintf(w, "%c", func() rune {
552 fmt.Fprintf(w, "Piece length: %s\n", func() string {
554 return fmt.Sprint(t.usualPieceSize())
560 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
561 fmt.Fprint(w, "Piece States:")
562 for _, psr := range t.pieceStateRuns() {
564 w.Write([]byte(pieceStateRunStatusChars(psr)))
568 fmt.Fprintf(w, "Reader Pieces:")
569 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
570 fmt.Fprintf(w, " %d:%d", begin, end)
575 fmt.Fprintf(w, "Trackers:\n")
577 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
578 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
579 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
581 }).([]*trackerScraper) {
582 fmt.Fprintf(tw, " %s\n", ta.statusLine())
587 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
589 spew.NewDefaultConfig()
590 spew.Fdump(w, t.statsLocked())
592 conns := t.connsAsSlice()
593 slices.Sort(conns, worseConn)
594 for i, c := range conns {
595 fmt.Fprintf(w, "%2d. ", i+1)
600 func (t *Torrent) haveInfo() bool {
604 // Returns a run-time generated MetaInfo that includes the info bytes and
605 // announce-list as currently known to the client.
606 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
607 return metainfo.MetaInfo{
608 CreationDate: time.Now().Unix(),
609 Comment: "dynamic metainfo from client",
610 CreatedBy: "go.torrent",
611 AnnounceList: t.metainfo.UpvertedAnnounceList(),
612 InfoBytes: func() []byte {
614 return t.metadataBytes
622 func (t *Torrent) BytesMissing() int64 {
624 defer t.mu().RUnlock()
625 return t.bytesMissingLocked()
628 func (t *Torrent) bytesMissingLocked() int64 {
632 func (t *Torrent) bytesLeft() (left int64) {
633 bitmap.Flip(t.completedPieces, 0, t.numPieces()).IterTyped(func(piece int) bool {
634 p := &t.pieces[piece]
635 left += int64(p.length() - p.numDirtyBytes())
641 // Bytes left to give in tracker announces.
642 func (t *Torrent) bytesLeftAnnounce() uint64 {
644 return uint64(t.bytesLeft())
646 return math.MaxUint64
650 func (t *Torrent) piecePartiallyDownloaded(piece int) bool {
651 if t.pieceComplete(piece) {
654 if t.pieceAllDirty(piece) {
657 return t.pieces[piece].hasDirtyChunks()
660 func (t *Torrent) usualPieceSize() int {
661 return int(t.info.PieceLength)
664 func (t *Torrent) numPieces() int {
665 return t.info.NumPieces()
668 func (t *Torrent) numPiecesCompleted() (num int) {
669 return t.completedPieces.Len()
672 func (t *Torrent) close() (err error) {
674 if t.storage != nil {
677 t.storageLock.Unlock()
679 for conn := range t.conns {
682 t.cl.event.Broadcast()
683 t.pieceStateChanges.Close()
684 t.updateWantPeersEvent()
688 func (t *Torrent) requestOffset(r request) int64 {
689 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
692 // Return the request that would include the given offset into the torrent
693 // data. Returns !ok if there is no such request.
694 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
695 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
698 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
699 tr := perf.NewTimer()
701 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
702 if err == nil && n != len(data) {
703 err = io.ErrShortWrite
706 tr.Mark("write chunk")
711 func (t *Torrent) bitfield() (bf []bool) {
712 bf = make([]bool, t.numPieces())
713 t.completedPieces.IterTyped(func(piece int) (again bool) {
720 func (t *Torrent) pieceNumChunks(piece int) int {
721 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
724 func (t *Torrent) pendAllChunkSpecs(pieceIndex int) {
725 t.pieces[pieceIndex].dirtyChunks.Clear()
733 // Peer is known to support encryption.
734 SupportsEncryption bool
737 func (t *Torrent) pieceLength(piece int) pp.Integer {
738 if piece == t.numPieces()-1 {
739 ret := pp.Integer(*t.length % t.info.PieceLength)
744 return pp.Integer(t.info.PieceLength)
747 func (t *Torrent) hashPiece(piece int) (ret metainfo.Hash) {
748 hash := pieceHash.New()
749 p := &t.pieces[piece]
750 p.waitNoPendingWrites()
751 ip := t.info.Piece(piece)
753 n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
755 missinggo.CopyExact(&ret, hash.Sum(nil))
758 if err != io.ErrUnexpectedEOF && !os.IsNotExist(err) {
759 log.Printf("unexpected error hashing piece with %T: %s", t.storage.TorrentImpl, err)
764 func (t *Torrent) haveAnyPieces() bool {
765 for i := range t.pieces {
766 if t.pieceComplete(i) {
773 func (t *Torrent) havePiece(index int) bool {
774 return t.haveInfo() && t.pieceComplete(index)
777 func (t *Torrent) haveChunk(r request) (ret bool) {
779 // log.Println("have chunk", r, ret)
784 if t.pieceComplete(int(r.Index)) {
787 p := &t.pieces[r.Index]
788 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
791 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
792 return int(cs.Begin / chunkSize)
795 func (t *Torrent) wantPiece(r request) bool {
796 if !t.wantPieceIndex(int(r.Index)) {
799 if t.pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
802 // TODO: What about pieces that were wanted, but aren't now, and aren't
803 // completed either? That used to be done here.
807 func (t *Torrent) wantPieceIndex(index int) bool {
811 if index < 0 || index >= t.numPieces() {
814 p := &t.pieces[index]
815 if p.queuedForHash() {
821 if t.pieceComplete(index) {
824 if t.pendingPieces.Contains(index) {
827 // log.Printf("piece %d not pending", index)
828 return !t.forReaderOffsetPieces(func(begin, end int) bool {
829 return index < begin || index >= end
833 // The worst connection is one that hasn't been sent, or sent anything useful
834 // for the longest. A bad connection is one that usually sends us unwanted
835 // pieces, or has been in worser half of the established connections for more
837 func (t *Torrent) worstBadConn() *connection {
838 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
841 c := heap.Pop(&wcs).(*connection)
842 if c.stats.ChunksReadUnwanted >= 6 && c.stats.ChunksReadUnwanted > c.stats.ChunksReadUseful {
845 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
846 // Give connections 1 minute to prove themselves.
847 if time.Since(c.completedHandshake) > time.Minute {
855 type PieceStateChange struct {
860 func (t *Torrent) publishPieceChange(piece int) {
861 cur := t.pieceState(piece)
862 p := &t.pieces[piece]
863 if cur != p.publicPieceState {
864 p.publicPieceState = cur
865 t.pieceStateChanges.Publish(PieceStateChange{
872 func (t *Torrent) pieceNumPendingChunks(piece int) int {
873 if t.pieceComplete(piece) {
876 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
879 func (t *Torrent) pieceAllDirty(piece int) bool {
880 return t.pieces[piece].dirtyChunks.Len() == t.pieceNumChunks(piece)
883 func (t *Torrent) readersChanged() {
884 t.updateReaderPieces()
885 t.updateAllPiecePriorities()
888 func (t *Torrent) updateReaderPieces() {
889 t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
892 func (t *Torrent) readerPosChanged(from, to pieceRange) {
896 t.updateReaderPieces()
897 // Order the ranges, high and low.
899 if l.begin > h.begin {
903 // Two distinct ranges.
904 t.updatePiecePriorities(l.begin, l.end)
905 t.updatePiecePriorities(h.begin, h.end)
912 t.updatePiecePriorities(l.begin, end)
916 func (t *Torrent) maybeNewConns() {
917 // Tickle the accept routine.
918 t.cl.event.Broadcast()
922 func (t *Torrent) piecePriorityChanged(piece int) {
923 // log.Printf("piece %d priority changed", piece)
924 for c := range t.conns {
925 if c.updatePiecePriority(piece) {
926 // log.Print("conn piece priority changed")
931 t.publishPieceChange(piece)
934 func (t *Torrent) updatePiecePriority(piece int) {
935 p := &t.pieces[piece]
936 newPrio := p.uncachedPriority()
937 // log.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
938 if newPrio == PiecePriorityNone {
939 if !t.pendingPieces.Remove(piece) {
943 if !t.pendingPieces.Set(piece, newPrio.BitmapPriority()) {
947 t.piecePriorityChanged(piece)
950 func (t *Torrent) updateAllPiecePriorities() {
951 t.updatePiecePriorities(0, len(t.pieces))
954 // Update all piece priorities in one hit. This function should have the same
955 // output as updatePiecePriority, but across all pieces.
956 func (t *Torrent) updatePiecePriorities(begin, end int) {
957 for i := begin; i < end; i++ {
958 t.updatePiecePriority(i)
962 // Returns the range of pieces [begin, end) that contains the extent of bytes.
963 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end int) {
964 if off >= *t.length {
974 begin = int(off / t.info.PieceLength)
975 end = int((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
976 if end > t.info.NumPieces() {
977 end = t.info.NumPieces()
982 // Returns true if all iterations complete without breaking. Returns the read
983 // regions for all readers. The reader regions should not be merged as some
984 // callers depend on this method to enumerate readers.
985 func (t *Torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
986 for r := range t.readers {
988 if p.begin >= p.end {
991 if !f(p.begin, p.end) {
998 func (t *Torrent) piecePriority(piece int) piecePriority {
999 prio, ok := t.pendingPieces.GetPriority(piece)
1001 return PiecePriorityNone
1006 ret := piecePriority(-prio)
1007 if ret == PiecePriorityNone {
1013 func (t *Torrent) pendRequest(req request) {
1014 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1015 t.pieces[req.Index].pendChunkIndex(ci)
1018 func (t *Torrent) pieceCompletionChanged(piece int) {
1019 log.Call().Add("piece", piece).AddValue(debugLogValue).Log(t.logger)
1020 t.cl.event.Broadcast()
1021 if t.pieceComplete(piece) {
1022 t.onPieceCompleted(piece)
1024 t.onIncompletePiece(piece)
1026 t.updatePiecePriority(piece)
1029 func (t *Torrent) openNewConns() {
1030 t.cl.openNewConns(t)
1033 func (t *Torrent) getConnPieceInclination() []int {
1034 _ret := t.connPieceInclinationPool.Get()
1036 pieceInclinationsNew.Add(1)
1037 return rand.Perm(t.numPieces())
1039 pieceInclinationsReused.Add(1)
1040 return *_ret.(*[]int)
1043 func (t *Torrent) putPieceInclination(pi []int) {
1044 t.connPieceInclinationPool.Put(&pi)
1045 pieceInclinationsPut.Add(1)
1048 func (t *Torrent) updatePieceCompletion(piece int) {
1049 pcu := t.pieceCompleteUncached(piece)
1050 p := &t.pieces[piece]
1051 changed := t.completedPieces.Get(piece) != pcu.Complete || p.storageCompletionOk != pcu.Ok
1052 log.Fmsg("piece %d completion: %v", piece, pcu.Ok).AddValue(debugLogValue).Log(t.logger)
1053 p.storageCompletionOk = pcu.Ok
1054 t.completedPieces.Set(piece, pcu.Complete)
1055 // log.Printf("piece %d uncached completion: %v", piece, pcu.Complete)
1056 // log.Printf("piece %d changed: %v", piece, changed)
1058 t.pieceCompletionChanged(piece)
1062 // Non-blocking read. Client lock is not required.
1063 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1064 p := &t.pieces[off/t.info.PieceLength]
1065 p.waitNoPendingWrites()
1066 return p.Storage().ReadAt(b, off-p.Info().Offset())
1069 func (t *Torrent) updateAllPieceCompletions() {
1070 for i := range iter.N(t.numPieces()) {
1071 t.updatePieceCompletion(i)
1075 // Returns an error if the metadata was completed, but couldn't be set for
1076 // some reason. Blame it on the last peer to contribute.
1077 func (t *Torrent) maybeCompleteMetadata() error {
1082 if !t.haveAllMetadataPieces() {
1083 // Don't have enough metadata pieces.
1086 err := t.setInfoBytes(t.metadataBytes)
1088 t.invalidateMetadata()
1089 return fmt.Errorf("error setting info bytes: %s", err)
1091 if t.cl.config.Debug {
1092 log.Printf("%s: got metadata from peers", t)
1097 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1098 t.forReaderOffsetPieces(func(begin, end int) bool {
1099 ret.AddRange(begin, end)
1105 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1106 t.forReaderOffsetPieces(func(begin, end int) bool {
1109 readahead.AddRange(begin+1, end)
1116 func (t *Torrent) needData() bool {
1117 if t.closed.IsSet() {
1123 return t.pendingPieces.Len() != 0
1126 func appendMissingStrings(old, new []string) (ret []string) {
1129 for _, n := range new {
1130 for _, o := range old {
1135 ret = append(ret, n)
1140 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1142 for minNumTiers > len(ret) {
1143 ret = append(ret, nil)
1148 func (t *Torrent) addTrackers(announceList [][]string) {
1149 fullAnnounceList := &t.metainfo.AnnounceList
1150 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1151 for tierIndex, trackerURLs := range announceList {
1152 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1154 t.startMissingTrackerScrapers()
1155 t.updateWantPeersEvent()
1158 // Don't call this before the info is available.
1159 func (t *Torrent) bytesCompleted() int64 {
1163 return t.info.TotalLength() - t.bytesLeft()
1166 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1168 defer t.cl.mu.Unlock()
1169 return t.setInfoBytes(b)
1172 // Returns true if connection is removed from torrent.Conns.
1173 func (t *Torrent) deleteConnection(c *connection) (ret bool) {
1174 if !c.closed.IsSet() {
1175 panic("connection is not closed")
1176 // There are behaviours prevented by the closed state that will fail
1177 // if the connection has been deleted.
1181 c.deleteAllRequests()
1182 if len(t.conns) == 0 {
1183 t.assertNoPendingRequests()
1188 func (t *Torrent) assertNoPendingRequests() {
1189 for _, num := range t.pendingRequests {
1196 func (t *Torrent) dropConnection(c *connection) {
1197 t.cl.event.Broadcast()
1199 if t.deleteConnection(c) {
1204 func (t *Torrent) wantPeers() bool {
1205 if t.closed.IsSet() {
1208 if len(t.peers) > t.cl.config.TorrentPeersLowWater {
1211 return t.needData() || t.seeding()
1214 func (t *Torrent) updateWantPeersEvent() {
1216 t.wantPeersEvent.Set()
1218 t.wantPeersEvent.Clear()
1222 // Returns whether the client should make effort to seed the torrent.
1223 func (t *Torrent) seeding() bool {
1225 if t.closed.IsSet() {
1228 if cl.config.NoUpload {
1231 if !cl.config.Seed {
1234 if cl.config.DisableAggressiveUpload && t.needData() {
1240 func (t *Torrent) startScrapingTracker(url string) {
1244 if _, ok := t.trackerAnnouncers[url]; ok {
1247 newAnnouncer := &trackerScraper{
1251 if t.trackerAnnouncers == nil {
1252 t.trackerAnnouncers = make(map[string]*trackerScraper)
1254 t.trackerAnnouncers[url] = newAnnouncer
1255 go newAnnouncer.Run()
1258 // Adds and starts tracker scrapers for tracker URLs that aren't already
1260 func (t *Torrent) startMissingTrackerScrapers() {
1261 if t.cl.config.DisableTrackers {
1264 t.startScrapingTracker(t.metainfo.Announce)
1265 for _, tier := range t.metainfo.AnnounceList {
1266 for _, url := range tier {
1267 t.startScrapingTracker(url)
1272 // Returns an AnnounceRequest with fields filled out to defaults and current
1274 func (t *Torrent) announceRequest() tracker.AnnounceRequest {
1275 return tracker.AnnounceRequest{
1276 Event: tracker.None,
1278 Port: uint16(t.cl.incomingPeerPort()),
1279 PeerId: t.cl.peerID,
1280 InfoHash: t.infoHash,
1281 Left: t.bytesLeftAnnounce(),
1285 // Adds peers revealed in an announce until the announce ends, or we have
1287 func (t *Torrent) consumeDHTAnnounce(pvs <-chan dht.PeersValues) {
1289 // Count all the unique addresses we got during this announce.
1290 allAddrs := make(map[string]struct{})
1293 case v, ok := <-pvs:
1297 addPeers := make([]Peer, 0, len(v.Peers))
1298 for _, cp := range v.Peers {
1300 // Can't do anything with this.
1303 addPeers = append(addPeers, Peer{
1306 Source: peerSourceDHTGetPeers,
1308 key := (&net.UDPAddr{
1312 allAddrs[key] = struct{}{}
1315 t.addPeers(addPeers)
1316 numPeers := len(t.peers)
1318 if numPeers >= cl.config.TorrentPeersHighWater {
1321 case <-t.closed.LockedChan(&cl.mu):
1327 func (t *Torrent) announceDHT(impliedPort bool) (err error) {
1329 ps, err := cl.dHT.Announce(t.infoHash, cl.incomingPeerPort(), impliedPort)
1333 t.consumeDHTAnnounce(ps.Peers)
1338 func (t *Torrent) dhtAnnouncer() {
1342 case <-t.wantPeersEvent.LockedChan(&cl.mu):
1343 case <-t.closed.LockedChan(&cl.mu):
1346 err := t.announceDHT(true)
1349 defer cl.mu.Unlock()
1353 log.Printf("error announcing %q to DHT: %s", t, err)
1357 case <-t.closed.LockedChan(&cl.mu):
1359 case <-time.After(5 * time.Minute):
1364 func (t *Torrent) addPeers(peers []Peer) {
1365 for _, p := range peers {
1366 if t.cl.badPeerIPPort(p.IP, p.Port) {
1373 func (t *Torrent) Stats() TorrentStats {
1375 defer t.cl.mu.Unlock()
1376 return t.statsLocked()
1379 func (t *Torrent) statsLocked() TorrentStats {
1380 t.stats.ActivePeers = len(t.conns)
1381 t.stats.HalfOpenPeers = len(t.halfOpen)
1382 t.stats.PendingPeers = len(t.peers)
1383 t.stats.TotalPeers = t.numTotalPeers()
1384 t.stats.ConnectedSeeders = 0
1385 for c := range t.conns {
1386 if all, ok := c.peerHasAllPieces(); all && ok {
1387 t.stats.ConnectedSeeders++
1393 // The total number of peers in the torrent.
1394 func (t *Torrent) numTotalPeers() int {
1395 peers := make(map[string]struct{})
1396 for conn := range t.conns {
1397 ra := conn.conn.RemoteAddr()
1399 // It's been closed and doesn't support RemoteAddr.
1402 peers[ra.String()] = struct{}{}
1404 for addr := range t.halfOpen {
1405 peers[addr] = struct{}{}
1407 for _, peer := range t.peers {
1408 peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{}
1413 // Reconcile bytes transferred before connection was associated with a
1415 func (t *Torrent) reconcileHandshakeStats(c *connection) {
1416 t.stats.wroteBytes(c.stats.BytesWritten)
1417 t.stats.readBytes(c.stats.BytesRead)
1420 // Returns true if the connection is added.
1421 func (t *Torrent) addConnection(c *connection, outgoing bool) bool {
1422 if t.cl.closed.IsSet() {
1428 for c0 := range t.conns {
1429 if c.PeerID == c0.PeerID {
1430 // Already connected to a client with that ID.
1431 duplicateClientConns.Add(1)
1432 lower := string(t.cl.peerID[:]) < string(c.PeerID[:])
1433 // Retain the connection from initiated from lower peer ID to
1435 if outgoing == lower {
1436 // Close the other one.
1438 // TODO: Is it safe to delete from the map while we're
1439 // iterating over it?
1440 t.deleteConnection(c0)
1442 // Abandon this one.
1447 if len(t.conns) >= t.maxEstablishedConns {
1448 c := t.worstBadConn()
1452 if t.cl.config.Debug && missinggo.CryHeard() {
1453 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1456 t.deleteConnection(c)
1458 if len(t.conns) >= t.maxEstablishedConns {
1465 func (t *Torrent) wantConns() bool {
1466 if !t.networkingEnabled {
1469 if t.closed.IsSet() {
1472 if !t.seeding() && !t.needData() {
1475 if len(t.conns) < t.maxEstablishedConns {
1478 return t.worstBadConn() != nil
1481 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1483 defer t.cl.mu.Unlock()
1484 oldMax = t.maxEstablishedConns
1485 t.maxEstablishedConns = max
1486 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1487 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1488 t.dropConnection(wcs.Pop().(*connection))
1494 func (t *Torrent) mu() missinggo.RWLocker {
1498 func (t *Torrent) pieceHashed(piece int, correct bool) {
1499 log.Fmsg("hashed piece %d", piece).Add("piece", piece).Add("passed", correct).AddValue(debugLogValue).Log(t.logger)
1500 if t.closed.IsSet() {
1503 p := &t.pieces[piece]
1504 touchers := t.reapPieceTouchers(piece)
1506 // Don't score the first time a piece is hashed, it could be an
1509 pieceHashedCorrect.Add(1)
1511 log.Printf("%s: piece %d (%s) failed hash: %d connections contributed", t, piece, p.hash, len(touchers))
1512 pieceHashedNotCorrect.Add(1)
1517 if len(touchers) != 0 {
1518 t.stats.PiecesDirtiedGood++
1520 for _, c := range touchers {
1521 c.stats.PiecesDirtiedGood++
1523 err := p.Storage().MarkComplete()
1525 log.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1528 if len(touchers) != 0 {
1529 t.stats.PiecesDirtiedBad++
1530 for _, c := range touchers {
1531 // Y u do dis peer?!
1532 c.stats.PiecesDirtiedBad++
1534 slices.Sort(touchers, connLessTrusted)
1535 if t.cl.config.Debug {
1536 log.Printf("dropping first corresponding conn from trust: %v", func() (ret []int64) {
1537 for _, c := range touchers {
1538 ret = append(ret, c.netGoodPiecesDirtied())
1544 t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1547 t.onIncompletePiece(piece)
1548 p.Storage().MarkNotComplete()
1550 t.updatePieceCompletion(piece)
1553 func (t *Torrent) cancelRequestsForPiece(piece int) {
1554 // TODO: Make faster
1555 for cn := range t.conns {
1560 func (t *Torrent) onPieceCompleted(piece int) {
1561 t.pendAllChunkSpecs(piece)
1562 t.cancelRequestsForPiece(piece)
1563 for conn := range t.conns {
1568 // Called when a piece is found to be not complete.
1569 func (t *Torrent) onIncompletePiece(piece int) {
1570 if t.pieceAllDirty(piece) {
1571 t.pendAllChunkSpecs(piece)
1573 if !t.wantPieceIndex(piece) {
1574 // log.Printf("piece %d incomplete and unwanted", piece)
1577 // We could drop any connections that we told we have a piece that we
1578 // don't here. But there's a test failure, and it seems clients don't care
1579 // if you request pieces that you already claim to have. Pruning bad
1580 // connections might just remove any connections that aren't treating us
1581 // favourably anyway.
1583 // for c := range t.conns {
1584 // if c.sentHave(piece) {
1588 for conn := range t.conns {
1589 if conn.PeerHasPiece(piece) {
1590 conn.updateRequests()
1595 func (t *Torrent) verifyPiece(piece int) {
1598 defer cl.mu.Unlock()
1599 p := &t.pieces[piece]
1602 cl.event.Broadcast()
1604 for p.hashing || t.storage == nil {
1607 if !p.t.piecesQueuedForHash.Remove(piece) {
1608 panic("piece was not queued")
1610 if t.closed.IsSet() || t.pieceComplete(piece) {
1611 t.updatePiecePriority(piece)
1615 t.publishPieceChange(piece)
1616 t.storageLock.RLock()
1618 sum := t.hashPiece(piece)
1619 t.storageLock.RUnlock()
1622 t.pieceHashed(piece, sum == p.hash)
1623 t.publishPieceChange(piece)
1626 // Return the connections that touched a piece, and clear the entries while
1628 func (t *Torrent) reapPieceTouchers(piece int) (ret []*connection) {
1629 for c := range t.pieces[piece].dirtiers {
1630 delete(c.peerTouchedPieces, piece)
1631 ret = append(ret, c)
1633 t.pieces[piece].dirtiers = nil
1637 func (t *Torrent) connsAsSlice() (ret []*connection) {
1638 for c := range t.conns {
1639 ret = append(ret, c)
1644 // Currently doesn't really queue, but should in the future.
1645 func (t *Torrent) queuePieceCheck(pieceIndex int) {
1646 piece := &t.pieces[pieceIndex]
1647 if piece.queuedForHash() {
1650 t.piecesQueuedForHash.Add(pieceIndex)
1651 t.publishPieceChange(pieceIndex)
1652 go t.verifyPiece(pieceIndex)
1655 func (t *Torrent) VerifyData() {
1656 for i := range iter.N(t.NumPieces()) {
1657 t.Piece(i).VerifyData()