18 "github.com/anacrolix/dht"
19 "github.com/anacrolix/missinggo"
20 "github.com/anacrolix/missinggo/bitmap"
21 "github.com/anacrolix/missinggo/perf"
22 "github.com/anacrolix/missinggo/pubsub"
23 "github.com/anacrolix/missinggo/slices"
24 "github.com/bradfitz/iter"
26 "github.com/anacrolix/torrent/bencode"
27 "github.com/anacrolix/torrent/metainfo"
28 pp "github.com/anacrolix/torrent/peer_protocol"
29 "github.com/anacrolix/torrent/storage"
30 "github.com/anacrolix/torrent/tracker"
33 func (t *Torrent) chunkIndexSpec(chunkIndex, piece int) chunkSpec {
34 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
37 type peersKey struct {
42 // Maintains state of torrent within a Client.
46 closed missinggo.Event
47 infoHash metainfo.Hash
49 // Values are the piece indices that changed.
50 pieceStateChanges *pubsub.PubSub
51 // The size of chunks to request from peers over the wire. This is
52 // normally 16KiB by convention these days.
55 // Total length of the torrent in bytes. Stored because it's not O(1) to
56 // get this from the info dict.
59 // The storage to open when the info dict becomes available.
60 storageOpener *storage.Client
61 // Storage for torrent data.
62 storage *storage.Torrent
64 metainfo metainfo.MetaInfo
66 // The info dict. nil if we don't have it (yet).
68 // Active peer connections, running message stream loops.
69 conns map[*connection]struct{}
70 maxEstablishedConns int
71 // Set of addrs to which we're attempting to connect. Connections are
72 // half-open until all handshakes are completed.
73 halfOpen map[string]struct{}
75 // Reserve of peers to connect to. A peer can be both here and in the
76 // active connections if were told about the peer after connecting with
77 // them. That encourages us to reconnect to peers that are well known in
79 peers map[peersKey]Peer
80 wantPeersEvent missinggo.Event
81 // An announcer for each tracker URL.
82 trackerAnnouncers map[string]*trackerScraper
83 // How many times we've initiated a DHT announce. TODO: Move into stats.
86 // Name used if the info name isn't available. Should be cleared when the
87 // Info does become available.
89 // The bencoded bytes of the info dict. This is actively manipulated if
90 // the info bytes aren't initially available, and we try to fetch them
93 // Each element corresponds to the 16KiB metadata pieces. If true, we have
94 // received that piece.
95 metadataCompletedChunks []bool
97 // Set when .Info is obtained.
98 gotMetainfo missinggo.Event
100 readers map[*Reader]struct{}
101 readerNowPieces bitmap.Bitmap
102 readerReadaheadPieces bitmap.Bitmap
104 // The indexes of pieces we want with normal priority, that aren't
105 // currently available.
106 pendingPieces bitmap.Bitmap
107 // A cache of completed piece indices.
108 completedPieces bitmap.Bitmap
110 // A pool of piece priorities []int for assignment to new connections.
111 // These "inclinations" are used to give connections preference for
113 connPieceInclinationPool sync.Pool
114 // Torrent-level statistics.
118 // Returns a channel that is closed when the Torrent is closed.
119 func (t *Torrent) Closed() <-chan struct{} {
120 return t.closed.LockedChan(&t.cl.mu)
123 func (t *Torrent) setChunkSize(size pp.Integer) {
125 t.chunkPool = &sync.Pool{
126 New: func() interface{} {
127 return make([]byte, size)
132 func (t *Torrent) setDisplayName(dn string) {
139 func (t *Torrent) pieceComplete(piece int) bool {
140 return t.completedPieces.Get(piece)
143 func (t *Torrent) pieceCompleteUncached(piece int) bool {
144 return t.pieces[piece].Storage().GetIsComplete()
147 // There's a connection to that address already.
148 func (t *Torrent) addrActive(addr string) bool {
149 if _, ok := t.halfOpen[addr]; ok {
152 for c := range t.conns {
153 if c.remoteAddr().String() == addr {
160 func (t *Torrent) worstUnclosedConns() (ret []*connection) {
161 ret = make([]*connection, 0, len(t.conns))
162 for c := range t.conns {
163 if !c.closed.IsSet() {
170 func (t *Torrent) addPeer(p Peer) {
173 if len(t.peers) >= torrentPeersHighWater {
176 key := peersKey{string(p.IP), p.Port}
177 if _, ok := t.peers[key]; ok {
181 peersAddedBySource.Add(string(p.Source), 1)
186 func (t *Torrent) invalidateMetadata() {
187 for i := range t.metadataCompletedChunks {
188 t.metadataCompletedChunks[i] = false
193 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
197 if index >= len(t.metadataCompletedChunks) {
198 log.Printf("%s: ignoring metadata piece %d", t, index)
201 copy(t.metadataBytes[(1<<14)*index:], data)
202 t.metadataCompletedChunks[index] = true
205 func (t *Torrent) metadataPieceCount() int {
206 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
209 func (t *Torrent) haveMetadataPiece(piece int) bool {
211 return (1<<14)*piece < len(t.metadataBytes)
213 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
217 func (t *Torrent) metadataSizeKnown() bool {
218 return t.metadataBytes != nil
221 func (t *Torrent) metadataSize() int {
222 return len(t.metadataBytes)
225 func infoPieceHashes(info *metainfo.Info) (ret []string) {
226 for i := 0; i < len(info.Pieces); i += sha1.Size {
227 ret = append(ret, string(info.Pieces[i:i+sha1.Size]))
232 func (t *Torrent) makePieces() {
233 hashes := infoPieceHashes(t.info)
234 t.pieces = make([]piece, len(hashes))
235 for i, hash := range hashes {
236 piece := &t.pieces[i]
239 piece.noPendingWrites.L = &piece.pendingWritesMutex
240 missinggo.CopyExact(piece.Hash[:], hash)
244 // Called when metadata for a torrent becomes available.
245 func (t *Torrent) setInfoBytes(b []byte) error {
249 if metainfo.HashBytes(b) != t.infoHash {
250 return errors.New("info bytes have wrong hash")
252 var info metainfo.Info
253 err := bencode.Unmarshal(b, &info)
255 return fmt.Errorf("error unmarshalling info bytes: %s", err)
257 err = validateInfo(&info)
259 return fmt.Errorf("bad info: %s", err)
261 defer t.updateWantPeersEvent()
263 t.displayName = "" // Save a few bytes lol.
264 t.cl.event.Broadcast()
266 t.storage, err = t.storageOpener.OpenTorrent(t.info, t.infoHash)
268 return fmt.Errorf("error opening torrent storage: %s", err)
271 for _, f := range t.info.UpvertedFiles() {
275 t.metadataCompletedChunks = nil
277 for conn := range t.conns {
278 if err := conn.setNumPieces(t.numPieces()); err != nil {
279 log.Printf("closing connection: %s", err)
283 for i := range t.pieces {
284 t.updatePieceCompletion(i)
285 t.pieces[i].QueuedForHash = true
288 for i := range t.pieces {
295 func (t *Torrent) haveAllMetadataPieces() bool {
299 if t.metadataCompletedChunks == nil {
302 for _, have := range t.metadataCompletedChunks {
310 // TODO: Propagate errors to disconnect peer.
311 func (t *Torrent) setMetadataSize(bytes int64) (err error) {
313 // We already know the correct metadata size.
316 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
317 return errors.New("bad size")
319 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
322 t.metadataBytes = make([]byte, bytes)
323 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
324 for c := range t.conns {
325 c.requestPendingMetadata()
330 // The current working name for the torrent. Either the name in the info dict,
331 // or a display name given such as by the dn value in a magnet link, or "".
332 func (t *Torrent) name() string {
339 func (t *Torrent) pieceState(index int) (ret PieceState) {
340 p := &t.pieces[index]
341 ret.Priority = t.piecePriority(index)
342 if t.pieceComplete(index) {
345 if p.QueuedForHash || p.Hashing {
348 if !ret.Complete && t.piecePartiallyDownloaded(index) {
354 func (t *Torrent) metadataPieceSize(piece int) int {
355 return metadataPieceSize(len(t.metadataBytes), piece)
358 func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
364 d["total_size"] = len(t.metadataBytes)
366 p, err := bencode.Marshal(d)
372 ExtendedID: c.PeerExtensionIDs["ut_metadata"],
373 ExtendedPayload: append(p, data...),
377 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
378 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
379 ret = append(ret, PieceStateRun{
380 PieceState: el.(PieceState),
384 for index := range t.pieces {
385 rle.Append(t.pieceState(index), 1)
391 // Produces a small string representing a PieceStateRun.
392 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
393 ret = fmt.Sprintf("%d", psr.Length)
394 ret += func() string {
395 switch psr.Priority {
396 case PiecePriorityNext:
398 case PiecePriorityNormal:
400 case PiecePriorityReadahead:
402 case PiecePriorityNow:
420 func (t *Torrent) writeStatus(w io.Writer) {
421 fmt.Fprintf(w, "Infohash: %x\n", t.infoHash)
422 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
424 fmt.Fprintf(w, "Metadata have: ")
425 for _, h := range t.metadataCompletedChunks {
426 fmt.Fprintf(w, "%c", func() rune {
436 fmt.Fprintf(w, "Piece length: %s\n", func() string {
438 return fmt.Sprint(t.usualPieceSize())
444 fmt.Fprintf(w, "Num Pieces: %d\n", t.numPieces())
445 fmt.Fprint(w, "Piece States:")
446 for _, psr := range t.pieceStateRuns() {
448 w.Write([]byte(pieceStateRunStatusChars(psr)))
452 fmt.Fprintf(w, "Reader Pieces:")
453 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
454 fmt.Fprintf(w, " %d:%d", begin, end)
459 fmt.Fprintf(w, "Trackers:\n")
461 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
462 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
463 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
465 }).([]*trackerScraper) {
466 fmt.Fprintf(tw, " %s\n", ta.statusLine())
471 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
473 fmt.Fprintf(w, "Pending peers: %d\n", len(t.peers))
474 fmt.Fprintf(w, "Half open: %d\n", len(t.halfOpen))
475 fmt.Fprintf(w, "Active peers: %d\n", len(t.conns))
476 conns := t.connsAsSlice()
477 slices.Sort(conns, worseConn)
478 for i, c := range conns {
479 fmt.Fprintf(w, "%2d. ", i+1)
484 func (t *Torrent) haveInfo() bool {
488 // TODO: Include URIs that weren't converted to tracker clients.
489 func (t *Torrent) announceList() (al [][]string) {
490 return t.metainfo.AnnounceList
493 // Returns a run-time generated MetaInfo that includes the info bytes and
494 // announce-list as currently known to the client.
495 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
496 return metainfo.MetaInfo{
497 CreationDate: time.Now().Unix(),
498 Comment: "dynamic metainfo from client",
499 CreatedBy: "go.torrent",
500 AnnounceList: t.announceList(),
501 InfoBytes: t.metadataBytes,
505 func (t *Torrent) BytesMissing() int64 {
507 defer t.mu().RUnlock()
508 return t.bytesMissingLocked()
511 func (t *Torrent) bytesMissingLocked() int64 {
515 func (t *Torrent) bytesLeft() (left int64) {
516 for i := 0; i < t.numPieces(); i++ {
517 left += int64(t.pieces[i].bytesLeft())
522 // Bytes left to give in tracker announces.
523 func (t *Torrent) bytesLeftAnnounce() uint64 {
525 return uint64(t.bytesLeft())
527 return math.MaxUint64
531 func (t *Torrent) piecePartiallyDownloaded(piece int) bool {
532 if t.pieceComplete(piece) {
535 if t.pieceAllDirty(piece) {
538 return t.pieces[piece].hasDirtyChunks()
541 func (t *Torrent) usualPieceSize() int {
542 return int(t.info.PieceLength)
545 func (t *Torrent) numPieces() int {
546 return t.info.NumPieces()
549 func (t *Torrent) numPiecesCompleted() (num int) {
550 return t.completedPieces.Len()
553 func (t *Torrent) close() (err error) {
555 if t.storage != nil {
558 for conn := range t.conns {
561 t.pieceStateChanges.Close()
562 t.updateWantPeersEvent()
566 func (t *Torrent) requestOffset(r request) int64 {
567 return torrentRequestOffset(t.length, int64(t.usualPieceSize()), r)
570 // Return the request that would include the given offset into the torrent
571 // data. Returns !ok if there is no such request.
572 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
573 return torrentOffsetRequest(t.length, t.info.PieceLength, int64(t.chunkSize), off)
576 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
577 tr := perf.NewTimer()
579 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
580 if err == nil && n != len(data) {
581 err = io.ErrShortWrite
584 tr.Stop("write chunk")
589 func (t *Torrent) bitfield() (bf []bool) {
590 bf = make([]bool, t.numPieces())
591 t.completedPieces.IterTyped(func(piece int) (again bool) {
598 func (t *Torrent) pieceNumChunks(piece int) int {
599 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
602 func (t *Torrent) pendAllChunkSpecs(pieceIndex int) {
603 t.pieces[pieceIndex].DirtyChunks.Clear()
611 // Peer is known to support encryption.
612 SupportsEncryption bool
615 func (t *Torrent) pieceLength(piece int) (len_ pp.Integer) {
616 if piece < 0 || piece >= t.info.NumPieces() {
619 if piece == t.numPieces()-1 {
620 len_ = pp.Integer(t.length % t.info.PieceLength)
623 len_ = pp.Integer(t.info.PieceLength)
628 func (t *Torrent) hashPiece(piece int) (ret metainfo.Hash) {
629 hash := pieceHash.New()
630 p := &t.pieces[piece]
631 p.waitNoPendingWrites()
632 ip := t.info.Piece(piece)
634 n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
636 missinggo.CopyExact(&ret, hash.Sum(nil))
639 if err != io.ErrUnexpectedEOF && !os.IsNotExist(err) {
640 log.Printf("unexpected error hashing piece with %T: %s", t.storage.TorrentImpl, err)
645 func (t *Torrent) haveAllPieces() bool {
649 return t.completedPieces.Len() == t.numPieces()
652 func (t *Torrent) haveAnyPieces() bool {
653 for i := range t.pieces {
654 if t.pieceComplete(i) {
661 func (t *Torrent) havePiece(index int) bool {
662 return t.haveInfo() && t.pieceComplete(index)
665 func (t *Torrent) haveChunk(r request) (ret bool) {
667 // log.Println("have chunk", r, ret)
672 if t.pieceComplete(int(r.Index)) {
675 p := &t.pieces[r.Index]
676 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
679 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
680 return int(cs.Begin / chunkSize)
683 func (t *Torrent) wantPiece(r request) bool {
684 if !t.wantPieceIndex(int(r.Index)) {
687 if t.pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
690 // TODO: What about pieces that were wanted, but aren't now, and aren't
691 // completed either? That used to be done here.
695 func (t *Torrent) wantPieceIndex(index int) bool {
699 if index < 0 || index >= t.numPieces() {
702 p := &t.pieces[index]
709 if t.pieceComplete(index) {
712 if t.pendingPieces.Contains(index) {
715 return !t.forReaderOffsetPieces(func(begin, end int) bool {
716 return index < begin || index >= end
720 func (t *Torrent) connHasWantedPieces(c *connection) bool {
721 return !c.pieceRequestOrder.IsEmpty()
724 // The worst connection is one that hasn't been sent, or sent anything useful
725 // for the longest. A bad connection is one that usually sends us unwanted
726 // pieces, or has been in worser half of the established connections for more
728 func (t *Torrent) worstBadConn() *connection {
729 wcs := worseConnSlice{t.worstUnclosedConns()}
731 c := heap.Pop(&wcs).(*connection)
732 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
735 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
736 // Give connections 1 minute to prove themselves.
737 if time.Since(c.completedHandshake) > time.Minute {
745 type PieceStateChange struct {
750 func (t *Torrent) publishPieceChange(piece int) {
751 cur := t.pieceState(piece)
752 p := &t.pieces[piece]
753 if cur != p.PublicPieceState {
754 p.PublicPieceState = cur
755 t.pieceStateChanges.Publish(PieceStateChange{
762 func (t *Torrent) pieceNumPendingChunks(piece int) int {
763 if t.pieceComplete(piece) {
766 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
769 func (t *Torrent) pieceAllDirty(piece int) bool {
770 return t.pieces[piece].DirtyChunks.Len() == t.pieceNumChunks(piece)
773 func (t *Torrent) readersChanged() {
774 t.updateReaderPieces()
775 t.updateAllPiecePriorities()
778 func (t *Torrent) updateReaderPieces() {
779 t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
782 func (t *Torrent) readerPosChanged(from, to pieceRange) {
786 t.updateReaderPieces()
787 // Order the ranges, high and low.
789 if l.begin > h.begin {
793 // Two distinct ranges.
794 t.updatePiecePriorities(l.begin, l.end)
795 t.updatePiecePriorities(h.begin, h.end)
802 t.updatePiecePriorities(l.begin, end)
806 func (t *Torrent) maybeNewConns() {
807 // Tickle the accept routine.
808 t.cl.event.Broadcast()
812 func (t *Torrent) piecePriorityChanged(piece int) {
813 for c := range t.conns {
814 c.updatePiecePriority(piece)
817 t.publishPieceChange(piece)
820 func (t *Torrent) updatePiecePriority(piece int) {
821 p := &t.pieces[piece]
822 newPrio := t.piecePriorityUncached(piece)
823 if newPrio == p.priority {
827 t.piecePriorityChanged(piece)
830 func (t *Torrent) updateAllPiecePriorities() {
831 t.updatePiecePriorities(0, len(t.pieces))
834 // Update all piece priorities in one hit. This function should have the same
835 // output as updatePiecePriority, but across all pieces.
836 func (t *Torrent) updatePiecePriorities(begin, end int) {
837 for i := begin; i < end; i++ {
838 t.updatePiecePriority(i)
842 // Returns the range of pieces [begin, end) that contains the extent of bytes.
843 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end int) {
854 begin = int(off / t.info.PieceLength)
855 end = int((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
856 if end > t.info.NumPieces() {
857 end = t.info.NumPieces()
862 // Returns true if all iterations complete without breaking. Returns the read
863 // regions for all readers. The reader regions should not be merged as some
864 // callers depend on this method to enumerate readers.
865 func (t *Torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
866 for r := range t.readers {
868 if p.begin >= p.end {
871 if !f(p.begin, p.end) {
878 func (t *Torrent) piecePriority(piece int) piecePriority {
880 return PiecePriorityNone
882 return t.pieces[piece].priority
885 func (t *Torrent) piecePriorityUncached(piece int) piecePriority {
886 if t.pieceComplete(piece) {
887 return PiecePriorityNone
889 if t.readerNowPieces.Contains(piece) {
890 return PiecePriorityNow
892 // if t.readerNowPieces.Contains(piece - 1) {
893 // return PiecePriorityNext
895 if t.readerReadaheadPieces.Contains(piece) {
896 return PiecePriorityReadahead
898 if t.pendingPieces.Contains(piece) {
899 return PiecePriorityNormal
901 return PiecePriorityNone
904 func (t *Torrent) pendPiece(piece int) {
905 if t.pendingPieces.Contains(piece) {
908 if t.havePiece(piece) {
911 t.pendingPieces.Add(piece)
912 t.updatePiecePriority(piece)
915 func (t *Torrent) unpendPieces(unpend *bitmap.Bitmap) {
916 t.pendingPieces.Sub(unpend)
917 unpend.IterTyped(func(piece int) (again bool) {
918 t.updatePiecePriority(piece)
923 func (t *Torrent) pendPieceRange(begin, end int) {
924 for i := begin; i < end; i++ {
929 func (t *Torrent) unpendPieceRange(begin, end int) {
931 bm.AddRange(begin, end)
935 func (t *Torrent) pendRequest(req request) {
936 ci := chunkIndex(req.chunkSpec, t.chunkSize)
937 t.pieces[req.Index].pendChunkIndex(ci)
940 func (t *Torrent) pieceCompletionChanged(piece int) {
941 t.cl.event.Broadcast()
942 if t.pieceComplete(piece) {
943 t.onPieceCompleted(piece)
945 t.onIncompletePiece(piece)
947 t.updatePiecePriority(piece)
950 func (t *Torrent) openNewConns() {
954 func (t *Torrent) getConnPieceInclination() []int {
955 _ret := t.connPieceInclinationPool.Get()
957 pieceInclinationsNew.Add(1)
958 return rand.Perm(t.numPieces())
960 pieceInclinationsReused.Add(1)
964 func (t *Torrent) putPieceInclination(pi []int) {
965 t.connPieceInclinationPool.Put(pi)
966 pieceInclinationsPut.Add(1)
969 func (t *Torrent) updatePieceCompletion(piece int) {
970 pcu := t.pieceCompleteUncached(piece)
971 changed := t.completedPieces.Get(piece) != pcu
972 t.completedPieces.Set(piece, pcu)
974 t.pieceCompletionChanged(piece)
978 // Non-blocking read. Client lock is not required.
979 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
980 p := &t.pieces[off/t.info.PieceLength]
981 p.waitNoPendingWrites()
982 return p.Storage().ReadAt(b, off-p.Info().Offset())
985 func (t *Torrent) updateAllPieceCompletions() {
986 for i := range iter.N(t.numPieces()) {
987 t.updatePieceCompletion(i)
991 // Returns an error if the metadata was completed, but couldn't be set for
992 // some reason. Blame it on the last peer to contribute.
993 func (t *Torrent) maybeCompleteMetadata() error {
998 if !t.haveAllMetadataPieces() {
999 // Don't have enough metadata pieces.
1002 err := t.setInfoBytes(t.metadataBytes)
1004 t.invalidateMetadata()
1005 return fmt.Errorf("error setting info bytes: %s", err)
1007 if t.cl.config.Debug {
1008 log.Printf("%s: got metadata from peers", t)
1013 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1014 t.forReaderOffsetPieces(func(begin, end int) bool {
1015 ret.AddRange(begin, end)
1021 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1022 t.forReaderOffsetPieces(func(begin, end int) bool {
1025 readahead.AddRange(begin+1, end)
1032 func (t *Torrent) needData() bool {
1033 if t.closed.IsSet() {
1039 if t.pendingPieces.Len() != 0 {
1042 // Read as "not all complete".
1043 return !t.readerPieces().IterTyped(func(piece int) bool {
1044 return t.pieceComplete(piece)
1048 func appendMissingStrings(old, new []string) (ret []string) {
1051 for _, n := range new {
1052 for _, o := range old {
1057 ret = append(ret, n)
1062 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1064 for minNumTiers > len(ret) {
1065 ret = append(ret, nil)
1070 func (t *Torrent) addTrackers(announceList [][]string) {
1071 fullAnnounceList := &t.metainfo.AnnounceList
1072 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1073 for tierIndex, trackerURLs := range announceList {
1074 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1076 t.startMissingTrackerScrapers()
1077 t.updateWantPeersEvent()
1080 // Don't call this before the info is available.
1081 func (t *Torrent) bytesCompleted() int64 {
1085 return t.info.TotalLength() - t.bytesLeft()
1088 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1090 defer t.cl.mu.Unlock()
1091 return t.setInfoBytes(b)
1094 // Returns true if connection is removed from torrent.Conns.
1095 func (t *Torrent) deleteConnection(c *connection) (ret bool) {
1101 func (t *Torrent) dropConnection(c *connection) {
1102 t.cl.event.Broadcast()
1104 if t.deleteConnection(c) {
1109 func (t *Torrent) wantPeers() bool {
1110 if t.closed.IsSet() {
1113 if len(t.peers) > torrentPeersLowWater {
1116 return t.needData() || t.seeding()
1119 func (t *Torrent) updateWantPeersEvent() {
1121 t.wantPeersEvent.Set()
1123 t.wantPeersEvent.Clear()
1127 // Returns whether the client should make effort to seed the torrent.
1128 func (t *Torrent) seeding() bool {
1130 if t.closed.IsSet() {
1133 if cl.config.NoUpload {
1136 if !cl.config.Seed {
1145 // Adds and starts tracker scrapers for tracker URLs that aren't already
1147 func (t *Torrent) startMissingTrackerScrapers() {
1148 if t.cl.config.DisableTrackers {
1151 for _, tier := range t.announceList() {
1152 for _, trackerURL := range tier {
1153 if _, ok := t.trackerAnnouncers[trackerURL]; ok {
1156 newAnnouncer := &trackerScraper{
1160 if t.trackerAnnouncers == nil {
1161 t.trackerAnnouncers = make(map[string]*trackerScraper)
1163 t.trackerAnnouncers[trackerURL] = newAnnouncer
1164 go newAnnouncer.Run()
1169 // Returns an AnnounceRequest with fields filled out to defaults and current
1171 func (t *Torrent) announceRequest() tracker.AnnounceRequest {
1172 return tracker.AnnounceRequest{
1173 Event: tracker.None,
1175 Port: uint16(t.cl.incomingPeerPort()),
1176 PeerId: t.cl.peerID,
1177 InfoHash: t.infoHash,
1178 Left: t.bytesLeftAnnounce(),
1182 // Adds peers revealed in an announce until the announce ends, or we have
1184 func (t *Torrent) consumeDHTAnnounce(pvs <-chan dht.PeersValues) {
1186 // Count all the unique addresses we got during this announce.
1187 allAddrs := make(map[string]struct{})
1190 case v, ok := <-pvs:
1194 addPeers := make([]Peer, 0, len(v.Peers))
1195 for _, cp := range v.Peers {
1197 // Can't do anything with this.
1200 addPeers = append(addPeers, Peer{
1203 Source: peerSourceDHTGetPeers,
1205 key := (&net.UDPAddr{
1209 allAddrs[key] = struct{}{}
1212 t.addPeers(addPeers)
1213 numPeers := len(t.peers)
1215 if numPeers >= torrentPeersHighWater {
1218 case <-t.closed.LockedChan(&cl.mu):
1224 func (t *Torrent) announceDHT(impliedPort bool) (err error) {
1226 ps, err := cl.dHT.Announce(string(t.infoHash[:]), cl.incomingPeerPort(), impliedPort)
1230 t.consumeDHTAnnounce(ps.Peers)
1235 func (t *Torrent) dhtAnnouncer() {
1239 case <-t.wantPeersEvent.LockedChan(&cl.mu):
1240 case <-t.closed.LockedChan(&cl.mu):
1243 err := t.announceDHT(true)
1249 log.Printf("error announcing %q to DHT: %s", t, err)
1252 case <-t.closed.LockedChan(&cl.mu):
1254 case <-time.After(5 * time.Minute):
1259 func (t *Torrent) addPeers(peers []Peer) {
1260 for _, p := range peers {
1261 if t.cl.badPeerIPPort(p.IP, p.Port) {
1268 func (t *Torrent) Stats() TorrentStats {
1270 defer t.cl.mu.Unlock()
1274 // Returns true if the connection is added.
1275 func (t *Torrent) addConnection(c *connection) bool {
1276 if t.cl.closed.IsSet() {
1282 for c0 := range t.conns {
1283 if c.PeerID == c0.PeerID {
1284 // Already connected to a client with that ID.
1285 duplicateClientConns.Add(1)
1289 if len(t.conns) >= t.maxEstablishedConns {
1290 c := t.worstBadConn()
1294 if t.cl.config.Debug && missinggo.CryHeard() {
1295 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1298 t.deleteConnection(c)
1300 if len(t.conns) >= t.maxEstablishedConns {
1304 panic("connection already associated with a torrent")
1306 // Reconcile bytes transferred before connection was associated with a
1308 t.stats.wroteBytes(c.stats.BytesWritten)
1309 t.stats.readBytes(c.stats.BytesRead)
1311 t.conns[c] = struct{}{}
1315 func (t *Torrent) wantConns() bool {
1316 if t.closed.IsSet() {
1319 if !t.seeding() && !t.needData() {
1322 if len(t.conns) < t.maxEstablishedConns {
1325 return t.worstBadConn() != nil
1328 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1330 defer t.cl.mu.Unlock()
1331 oldMax = t.maxEstablishedConns
1332 t.maxEstablishedConns = max
1333 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1334 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1335 t.dropConnection(wcs.Pop().(*connection))
1341 func (t *Torrent) mu() missinggo.RWLocker {
1345 func (t *Torrent) pieceHashed(piece int, correct bool) {
1346 if t.closed.IsSet() {
1349 p := &t.pieces[piece]
1350 touchers := t.reapPieceTouchers(piece)
1352 // Don't score the first time a piece is hashed, it could be an
1355 pieceHashedCorrect.Add(1)
1357 log.Printf("%s: piece %d (%x) failed hash: %d connections contributed", t, piece, p.Hash, len(touchers))
1358 pieceHashedNotCorrect.Add(1)
1363 for _, c := range touchers {
1364 c.goodPiecesDirtied++
1366 err := p.Storage().MarkComplete()
1368 log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
1370 t.updatePieceCompletion(piece)
1372 if len(touchers) != 0 {
1373 for _, c := range touchers {
1374 // Y u do dis peer?!
1375 c.badPiecesDirtied++
1377 slices.Sort(touchers, connLessTrusted)
1378 log.Printf("dropping first corresponding conn from trust: %v", func() (ret []int) {
1379 for _, c := range touchers {
1380 ret = append(ret, c.netGoodPiecesDirtied())
1385 t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1388 t.onIncompletePiece(piece)
1392 func (t *Torrent) onPieceCompleted(piece int) {
1393 t.pendingPieces.Remove(piece)
1394 t.pendAllChunkSpecs(piece)
1395 for conn := range t.conns {
1397 for r := range conn.Requests {
1398 if int(r.Index) == piece {
1402 // Could check here if peer doesn't have piece, but due to caching
1403 // some peers may have said they have a piece but they don't.
1408 func (t *Torrent) onIncompletePiece(piece int) {
1409 if t.pieceAllDirty(piece) {
1410 t.pendAllChunkSpecs(piece)
1412 if !t.wantPieceIndex(piece) {
1415 // We could drop any connections that we told we have a piece that we
1416 // don't here. But there's a test failure, and it seems clients don't care
1417 // if you request pieces that you already claim to have. Pruning bad
1418 // connections might just remove any connections that aren't treating us
1419 // favourably anyway.
1421 // for c := range t.conns {
1422 // if c.sentHave(piece) {
1426 for conn := range t.conns {
1427 if conn.PeerHasPiece(piece) {
1428 conn.updateRequests()
1433 func (t *Torrent) verifyPiece(piece int) {
1436 defer cl.mu.Unlock()
1437 p := &t.pieces[piece]
1438 for p.Hashing || t.storage == nil {
1441 p.QueuedForHash = false
1442 if t.closed.IsSet() || t.pieceComplete(piece) {
1443 t.updatePiecePriority(piece)
1447 t.publishPieceChange(piece)
1449 sum := t.hashPiece(piece)
1452 t.pieceHashed(piece, sum == p.Hash)
1455 // Return the connections that touched a piece, and clear the entry while
1457 func (t *Torrent) reapPieceTouchers(piece int) (ret []*connection) {
1458 for c := range t.conns {
1459 if _, ok := c.peerTouchedPieces[piece]; ok {
1460 ret = append(ret, c)
1461 delete(c.peerTouchedPieces, piece)
1467 func (t *Torrent) connsAsSlice() (ret []*connection) {
1468 for c := range t.conns {
1469 ret = append(ret, c)
1474 // Currently doesn't really queue, but should in the future.
1475 func (t *Torrent) queuePieceCheck(pieceIndex int) {
1476 piece := &t.pieces[pieceIndex]
1477 if piece.QueuedForHash {
1480 piece.QueuedForHash = true
1481 t.publishPieceChange(pieceIndex)
1482 go t.verifyPiece(pieceIndex)