19 "github.com/anacrolix/dht"
20 "github.com/anacrolix/missinggo"
21 "github.com/anacrolix/missinggo/bitmap"
22 "github.com/anacrolix/missinggo/perf"
23 "github.com/anacrolix/missinggo/pubsub"
24 "github.com/anacrolix/missinggo/slices"
25 "github.com/bradfitz/iter"
27 "github.com/anacrolix/torrent/bencode"
28 "github.com/anacrolix/torrent/metainfo"
29 pp "github.com/anacrolix/torrent/peer_protocol"
30 "github.com/anacrolix/torrent/storage"
31 "github.com/anacrolix/torrent/tracker"
34 func (t *Torrent) chunkIndexSpec(chunkIndex, piece int) chunkSpec {
35 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
38 type peersKey struct {
43 // Maintains state of torrent within a Client.
47 networkingEnabled bool
50 closed missinggo.Event
51 infoHash metainfo.Hash
53 // Values are the piece indices that changed.
54 pieceStateChanges *pubsub.PubSub
55 // The size of chunks to request from peers over the wire. This is
56 // normally 16KiB by convention these days.
59 // Total length of the torrent in bytes. Stored because it's not O(1) to
60 // get this from the info dict.
63 // The storage to open when the info dict becomes available.
64 storageOpener *storage.Client
65 // Storage for torrent data.
66 storage *storage.Torrent
68 metainfo metainfo.MetaInfo
70 // The info dict. nil if we don't have it (yet).
73 // Active peer connections, running message stream loops.
74 conns map[*connection]struct{}
75 maxEstablishedConns int
76 // Set of addrs to which we're attempting to connect. Connections are
77 // half-open until all handshakes are completed.
78 halfOpen map[string]Peer
79 fastestConn *connection
81 // Reserve of peers to connect to. A peer can be both here and in the
82 // active connections if were told about the peer after connecting with
83 // them. That encourages us to reconnect to peers that are well known in
85 peers map[peersKey]Peer
86 wantPeersEvent missinggo.Event
87 // An announcer for each tracker URL.
88 trackerAnnouncers map[string]*trackerScraper
89 // How many times we've initiated a DHT announce. TODO: Move into stats.
92 // Name used if the info name isn't available. Should be cleared when the
93 // Info does become available.
95 // The bencoded bytes of the info dict. This is actively manipulated if
96 // the info bytes aren't initially available, and we try to fetch them
99 // Each element corresponds to the 16KiB metadata pieces. If true, we have
100 // received that piece.
101 metadataCompletedChunks []bool
103 // Set when .Info is obtained.
104 gotMetainfo missinggo.Event
106 readers map[*Reader]struct{}
107 readerNowPieces bitmap.Bitmap
108 readerReadaheadPieces bitmap.Bitmap
110 // The indexes of pieces we want with normal priority, that aren't
111 // currently available.
112 pendingPieces bitmap.Bitmap
113 // A cache of completed piece indices.
114 completedPieces bitmap.Bitmap
115 // Pieces that need to be hashed.
116 piecesQueuedForHash bitmap.Bitmap
118 // A pool of piece priorities []int for assignment to new connections.
119 // These "inclinations" are used to give connections preference for
121 connPieceInclinationPool sync.Pool
122 // Torrent-level statistics.
126 // Returns a channel that is closed when the Torrent is closed.
127 func (t *Torrent) Closed() <-chan struct{} {
128 return t.closed.LockedChan(&t.cl.mu)
131 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
132 // pending, and half-open peers.
133 func (t *Torrent) KnownSwarm() (ks []Peer) {
134 // Add pending peers to the list
135 for _, peer := range t.peers {
136 ks = append(ks, peer)
139 // Add half-open peers to the list
140 for _, peer := range t.halfOpen {
141 ks = append(ks, peer)
144 // Add active peers to the list
145 for conn := range t.conns {
146 host, portString, err := net.SplitHostPort(conn.remoteAddr().String())
151 ip := net.ParseIP(host)
152 port, err := strconv.Atoi(portString)
157 ks = append(ks, Peer{
161 Source: conn.Discovery,
162 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
163 // > But if we're not connected to them with an encrypted connection, I couldn't say
164 // > what's appropriate. We can carry forward the SupportsEncryption value as we
165 // > received it from trackers/DHT/PEX, or just use the encryption state for the
166 // > connection. It's probably easiest to do the latter for now.
167 // https://github.com/anacrolix/torrent/pull/188
168 SupportsEncryption: conn.headerEncrypted,
175 func (t *Torrent) setChunkSize(size pp.Integer) {
177 t.chunkPool = &sync.Pool{
178 New: func() interface{} {
179 b := make([]byte, size)
185 func (t *Torrent) setDisplayName(dn string) {
192 func (t *Torrent) pieceComplete(piece int) bool {
193 return t.completedPieces.Get(piece)
196 func (t *Torrent) pieceCompleteUncached(piece int) storage.Completion {
197 return t.pieces[piece].Storage().Completion()
200 // There's a connection to that address already.
201 func (t *Torrent) addrActive(addr string) bool {
202 if _, ok := t.halfOpen[addr]; ok {
205 for c := range t.conns {
206 if c.remoteAddr().String() == addr {
213 func (t *Torrent) unclosedConnsAsSlice() (ret []*connection) {
214 ret = make([]*connection, 0, len(t.conns))
215 for c := range t.conns {
216 if !c.closed.IsSet() {
223 func (t *Torrent) addPeer(p Peer) {
226 if len(t.peers) >= torrentPeersHighWater {
229 key := peersKey{string(p.IP), p.Port}
230 if _, ok := t.peers[key]; ok {
234 peersAddedBySource.Add(string(p.Source), 1)
239 func (t *Torrent) invalidateMetadata() {
240 for i := range t.metadataCompletedChunks {
241 t.metadataCompletedChunks[i] = false
246 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
250 if index >= len(t.metadataCompletedChunks) {
251 log.Printf("%s: ignoring metadata piece %d", t, index)
254 copy(t.metadataBytes[(1<<14)*index:], data)
255 t.metadataCompletedChunks[index] = true
258 func (t *Torrent) metadataPieceCount() int {
259 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
262 func (t *Torrent) haveMetadataPiece(piece int) bool {
264 return (1<<14)*piece < len(t.metadataBytes)
266 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
270 func (t *Torrent) metadataSizeKnown() bool {
271 return t.metadataBytes != nil
274 func (t *Torrent) metadataSize() int {
275 return len(t.metadataBytes)
278 func infoPieceHashes(info *metainfo.Info) (ret []string) {
279 for i := 0; i < len(info.Pieces); i += sha1.Size {
280 ret = append(ret, string(info.Pieces[i:i+sha1.Size]))
285 func (t *Torrent) makePieces() {
286 hashes := infoPieceHashes(t.info)
287 t.pieces = make([]Piece, len(hashes))
288 for i, hash := range hashes {
289 piece := &t.pieces[i]
292 piece.noPendingWrites.L = &piece.pendingWritesMutex
293 missinggo.CopyExact(piece.hash[:], hash)
297 // Called when metadata for a torrent becomes available.
298 func (t *Torrent) setInfoBytes(b []byte) error {
302 if metainfo.HashBytes(b) != t.infoHash {
303 return errors.New("info bytes have wrong hash")
305 var info metainfo.Info
306 err := bencode.Unmarshal(b, &info)
308 return fmt.Errorf("error unmarshalling info bytes: %s", err)
310 err = validateInfo(&info)
312 return fmt.Errorf("bad info: %s", err)
314 defer t.updateWantPeersEvent()
316 t.displayName = "" // Save a few bytes lol.
317 t.cl.event.Broadcast()
319 t.storage, err = t.storageOpener.OpenTorrent(t.info, t.infoHash)
321 return fmt.Errorf("error opening torrent storage: %s", err)
324 for _, f := range t.info.UpvertedFiles() {
328 t.metadataCompletedChunks = nil
330 for conn := range t.conns {
331 if err := conn.setNumPieces(t.numPieces()); err != nil {
332 log.Printf("closing connection: %s", err)
336 for i := range t.pieces {
337 t.updatePieceCompletion(i)
339 if !p.storageCompletionOk {
340 // log.Printf("piece %s completion unknown, queueing check", p)
347 func (t *Torrent) haveAllMetadataPieces() bool {
351 if t.metadataCompletedChunks == nil {
354 for _, have := range t.metadataCompletedChunks {
362 // TODO: Propagate errors to disconnect peer.
363 func (t *Torrent) setMetadataSize(bytes int64) (err error) {
365 // We already know the correct metadata size.
368 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
369 return errors.New("bad size")
371 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
374 t.metadataBytes = make([]byte, bytes)
375 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
376 for c := range t.conns {
377 c.requestPendingMetadata()
382 // The current working name for the torrent. Either the name in the info dict,
383 // or a display name given such as by the dn value in a magnet link, or "".
384 func (t *Torrent) name() string {
391 func (t *Torrent) pieceState(index int) (ret PieceState) {
392 p := &t.pieces[index]
393 ret.Priority = t.piecePriority(index)
394 if t.pieceComplete(index) {
397 if p.queuedForHash() || p.hashing {
400 if !ret.Complete && t.piecePartiallyDownloaded(index) {
406 func (t *Torrent) metadataPieceSize(piece int) int {
407 return metadataPieceSize(len(t.metadataBytes), piece)
410 func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
416 d["total_size"] = len(t.metadataBytes)
418 p, err := bencode.Marshal(d)
424 ExtendedID: c.PeerExtensionIDs["ut_metadata"],
425 ExtendedPayload: append(p, data...),
429 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
430 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
431 ret = append(ret, PieceStateRun{
432 PieceState: el.(PieceState),
436 for index := range t.pieces {
437 rle.Append(t.pieceState(index), 1)
443 // Produces a small string representing a PieceStateRun.
444 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
445 ret = fmt.Sprintf("%d", psr.Length)
446 ret += func() string {
447 switch psr.Priority {
448 case PiecePriorityNext:
450 case PiecePriorityNormal:
452 case PiecePriorityReadahead:
454 case PiecePriorityNow:
472 func (t *Torrent) writeStatus(w io.Writer) {
473 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
474 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
476 fmt.Fprintf(w, "Metadata have: ")
477 for _, h := range t.metadataCompletedChunks {
478 fmt.Fprintf(w, "%c", func() rune {
488 fmt.Fprintf(w, "Piece length: %s\n", func() string {
490 return fmt.Sprint(t.usualPieceSize())
496 fmt.Fprintf(w, "Num Pieces: %d\n", t.numPieces())
497 fmt.Fprint(w, "Piece States:")
498 for _, psr := range t.pieceStateRuns() {
500 w.Write([]byte(pieceStateRunStatusChars(psr)))
504 fmt.Fprintf(w, "Reader Pieces:")
505 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
506 fmt.Fprintf(w, " %d:%d", begin, end)
511 fmt.Fprintf(w, "Trackers:\n")
513 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
514 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
515 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
517 }).([]*trackerScraper) {
518 fmt.Fprintf(tw, " %s\n", ta.statusLine())
523 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
525 fmt.Fprintf(w, "Pending peers: %d\n", len(t.peers))
526 fmt.Fprintf(w, "Half open: %d\n", len(t.halfOpen))
527 fmt.Fprintf(w, "Active peers: %d\n", len(t.conns))
528 conns := t.connsAsSlice()
529 slices.Sort(conns, worseConn)
530 for i, c := range conns {
531 fmt.Fprintf(w, "%2d. ", i+1)
536 func (t *Torrent) haveInfo() bool {
540 // Returns a run-time generated MetaInfo that includes the info bytes and
541 // announce-list as currently known to the client.
542 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
543 return metainfo.MetaInfo{
544 CreationDate: time.Now().Unix(),
545 Comment: "dynamic metainfo from client",
546 CreatedBy: "go.torrent",
547 AnnounceList: t.metainfo.UpvertedAnnounceList(),
548 InfoBytes: t.metadataBytes,
552 func (t *Torrent) BytesMissing() int64 {
554 defer t.mu().RUnlock()
555 return t.bytesMissingLocked()
558 func (t *Torrent) bytesMissingLocked() int64 {
562 func (t *Torrent) bytesLeft() (left int64) {
563 bitmap.Flip(t.completedPieces, 0, t.numPieces()).IterTyped(func(piece int) bool {
565 left += int64(p.length() - p.numDirtyBytes())
571 // Bytes left to give in tracker announces.
572 func (t *Torrent) bytesLeftAnnounce() uint64 {
574 return uint64(t.bytesLeft())
576 return math.MaxUint64
580 func (t *Torrent) piecePartiallyDownloaded(piece int) bool {
581 if t.pieceComplete(piece) {
584 if t.pieceAllDirty(piece) {
587 return t.pieces[piece].hasDirtyChunks()
590 func (t *Torrent) usualPieceSize() int {
591 return int(t.info.PieceLength)
594 func (t *Torrent) numPieces() int {
595 return t.info.NumPieces()
598 func (t *Torrent) numPiecesCompleted() (num int) {
599 return t.completedPieces.Len()
602 func (t *Torrent) close() (err error) {
604 if t.storage != nil {
607 for conn := range t.conns {
610 t.cl.event.Broadcast()
611 t.pieceStateChanges.Close()
612 t.updateWantPeersEvent()
616 func (t *Torrent) requestOffset(r request) int64 {
617 return torrentRequestOffset(t.length, int64(t.usualPieceSize()), r)
620 // Return the request that would include the given offset into the torrent
621 // data. Returns !ok if there is no such request.
622 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
623 return torrentOffsetRequest(t.length, t.info.PieceLength, int64(t.chunkSize), off)
626 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
627 tr := perf.NewTimer()
629 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
630 if err == nil && n != len(data) {
631 err = io.ErrShortWrite
634 tr.Mark("write chunk")
639 func (t *Torrent) bitfield() (bf []bool) {
640 bf = make([]bool, t.numPieces())
641 t.completedPieces.IterTyped(func(piece int) (again bool) {
648 func (t *Torrent) pieceNumChunks(piece int) int {
649 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
652 func (t *Torrent) pendAllChunkSpecs(pieceIndex int) {
653 t.pieces[pieceIndex].dirtyChunks.Clear()
661 // Peer is known to support encryption.
662 SupportsEncryption bool
665 func (t *Torrent) pieceLength(piece int) pp.Integer {
666 if piece == t.numPieces()-1 {
667 ret := pp.Integer(t.length % t.info.PieceLength)
672 return pp.Integer(t.info.PieceLength)
675 func (t *Torrent) hashPiece(piece int) (ret metainfo.Hash) {
676 hash := pieceHash.New()
677 p := &t.pieces[piece]
678 p.waitNoPendingWrites()
679 ip := t.info.Piece(piece)
681 n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
683 missinggo.CopyExact(&ret, hash.Sum(nil))
686 if err != io.ErrUnexpectedEOF && !os.IsNotExist(err) {
687 log.Printf("unexpected error hashing piece with %T: %s", t.storage.TorrentImpl, err)
692 func (t *Torrent) haveAnyPieces() bool {
693 for i := range t.pieces {
694 if t.pieceComplete(i) {
701 func (t *Torrent) havePiece(index int) bool {
702 return t.haveInfo() && t.pieceComplete(index)
705 func (t *Torrent) haveChunk(r request) (ret bool) {
707 // log.Println("have chunk", r, ret)
712 if t.pieceComplete(int(r.Index)) {
715 p := &t.pieces[r.Index]
716 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
719 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
720 return int(cs.Begin / chunkSize)
723 func (t *Torrent) wantPiece(r request) bool {
724 if !t.wantPieceIndex(int(r.Index)) {
727 if t.pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
730 // TODO: What about pieces that were wanted, but aren't now, and aren't
731 // completed either? That used to be done here.
735 func (t *Torrent) wantPieceIndex(index int) bool {
739 if index < 0 || index >= t.numPieces() {
742 p := &t.pieces[index]
743 if p.queuedForHash() {
749 if t.pieceComplete(index) {
752 if t.pendingPieces.Contains(index) {
755 return !t.forReaderOffsetPieces(func(begin, end int) bool {
756 return index < begin || index >= end
760 // The worst connection is one that hasn't been sent, or sent anything useful
761 // for the longest. A bad connection is one that usually sends us unwanted
762 // pieces, or has been in worser half of the established connections for more
764 func (t *Torrent) worstBadConn() *connection {
765 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
768 c := heap.Pop(&wcs).(*connection)
769 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
772 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
773 // Give connections 1 minute to prove themselves.
774 if time.Since(c.completedHandshake) > time.Minute {
782 type PieceStateChange struct {
787 func (t *Torrent) publishPieceChange(piece int) {
788 cur := t.pieceState(piece)
789 p := &t.pieces[piece]
790 if cur != p.publicPieceState {
791 p.publicPieceState = cur
792 t.pieceStateChanges.Publish(PieceStateChange{
799 func (t *Torrent) pieceNumPendingChunks(piece int) int {
800 if t.pieceComplete(piece) {
803 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
806 func (t *Torrent) pieceAllDirty(piece int) bool {
807 return t.pieces[piece].dirtyChunks.Len() == t.pieceNumChunks(piece)
810 func (t *Torrent) readersChanged() {
811 t.updateReaderPieces()
812 t.updateAllPiecePriorities()
815 func (t *Torrent) updateReaderPieces() {
816 t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
819 func (t *Torrent) readerPosChanged(from, to pieceRange) {
823 t.updateReaderPieces()
824 // Order the ranges, high and low.
826 if l.begin > h.begin {
830 // Two distinct ranges.
831 t.updatePiecePriorities(l.begin, l.end)
832 t.updatePiecePriorities(h.begin, h.end)
839 t.updatePiecePriorities(l.begin, end)
843 func (t *Torrent) maybeNewConns() {
844 // Tickle the accept routine.
845 t.cl.event.Broadcast()
849 func (t *Torrent) piecePriorityChanged(piece int) {
850 for c := range t.conns {
851 if c.updatePiecePriority(piece) {
856 t.publishPieceChange(piece)
859 func (t *Torrent) updatePiecePriority(piece int) {
860 p := &t.pieces[piece]
861 newPrio := t.piecePriorityUncached(piece)
862 if newPrio == p.priority {
866 t.piecePriorityChanged(piece)
869 func (t *Torrent) updateAllPiecePriorities() {
870 t.updatePiecePriorities(0, len(t.pieces))
873 // Update all piece priorities in one hit. This function should have the same
874 // output as updatePiecePriority, but across all pieces.
875 func (t *Torrent) updatePiecePriorities(begin, end int) {
876 for i := begin; i < end; i++ {
877 t.updatePiecePriority(i)
881 // Returns the range of pieces [begin, end) that contains the extent of bytes.
882 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end int) {
893 begin = int(off / t.info.PieceLength)
894 end = int((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
895 if end > t.info.NumPieces() {
896 end = t.info.NumPieces()
901 // Returns true if all iterations complete without breaking. Returns the read
902 // regions for all readers. The reader regions should not be merged as some
903 // callers depend on this method to enumerate readers.
904 func (t *Torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
905 for r := range t.readers {
907 if p.begin >= p.end {
910 if !f(p.begin, p.end) {
917 func (t *Torrent) piecePriority(piece int) piecePriority {
919 return PiecePriorityNone
921 return t.pieces[piece].priority
924 func (t *Torrent) piecePriorityUncached(piece int) piecePriority {
925 if t.pieceComplete(piece) {
926 return PiecePriorityNone
928 if t.readerNowPieces.Contains(piece) {
929 return PiecePriorityNow
931 // if t.readerNowPieces.Contains(piece - 1) {
932 // return PiecePriorityNext
934 if t.readerReadaheadPieces.Contains(piece) {
935 return PiecePriorityReadahead
937 if t.pendingPieces.Contains(piece) {
938 return PiecePriorityNormal
940 return PiecePriorityNone
943 func (t *Torrent) pendPiece(piece int) {
944 if t.pendingPieces.Contains(piece) {
947 if t.havePiece(piece) {
950 t.pendingPieces.Add(piece)
951 t.updatePiecePriority(piece)
954 func (t *Torrent) unpendPieces(unpend bitmap.Bitmap) {
955 t.pendingPieces.Sub(unpend)
956 unpend.IterTyped(func(piece int) (again bool) {
957 t.updatePiecePriority(piece)
962 func (t *Torrent) pendPieceRange(begin, end int) {
963 for i := begin; i < end; i++ {
968 func (t *Torrent) unpendPieceRange(begin, end int) {
970 bm.AddRange(begin, end)
974 func (t *Torrent) pendRequest(req request) {
975 ci := chunkIndex(req.chunkSpec, t.chunkSize)
976 t.pieces[req.Index].pendChunkIndex(ci)
979 func (t *Torrent) pieceCompletionChanged(piece int) {
980 t.cl.event.Broadcast()
981 if t.pieceComplete(piece) {
982 t.onPieceCompleted(piece)
984 t.onIncompletePiece(piece)
986 t.updatePiecePriority(piece)
989 func (t *Torrent) openNewConns() {
993 func (t *Torrent) getConnPieceInclination() []int {
994 _ret := t.connPieceInclinationPool.Get()
996 pieceInclinationsNew.Add(1)
997 return rand.Perm(t.numPieces())
999 pieceInclinationsReused.Add(1)
1003 func (t *Torrent) putPieceInclination(pi []int) {
1004 t.connPieceInclinationPool.Put(&pi)
1005 pieceInclinationsPut.Add(1)
1008 func (t *Torrent) updatePieceCompletion(piece int) {
1009 pcu := t.pieceCompleteUncached(piece)
1010 p := &t.pieces[piece]
1011 changed := t.completedPieces.Get(piece) != pcu.Complete || p.storageCompletionOk != pcu.Ok
1012 p.storageCompletionOk = pcu.Ok
1013 t.completedPieces.Set(piece, pcu.Complete)
1015 t.pieceCompletionChanged(piece)
1019 // Non-blocking read. Client lock is not required.
1020 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1021 p := &t.pieces[off/t.info.PieceLength]
1022 p.waitNoPendingWrites()
1023 return p.Storage().ReadAt(b, off-p.Info().Offset())
1026 func (t *Torrent) updateAllPieceCompletions() {
1027 for i := range iter.N(t.numPieces()) {
1028 t.updatePieceCompletion(i)
1032 // Returns an error if the metadata was completed, but couldn't be set for
1033 // some reason. Blame it on the last peer to contribute.
1034 func (t *Torrent) maybeCompleteMetadata() error {
1039 if !t.haveAllMetadataPieces() {
1040 // Don't have enough metadata pieces.
1043 err := t.setInfoBytes(t.metadataBytes)
1045 t.invalidateMetadata()
1046 return fmt.Errorf("error setting info bytes: %s", err)
1048 if t.cl.config.Debug {
1049 log.Printf("%s: got metadata from peers", t)
1054 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1055 t.forReaderOffsetPieces(func(begin, end int) bool {
1056 ret.AddRange(begin, end)
1062 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1063 t.forReaderOffsetPieces(func(begin, end int) bool {
1066 readahead.AddRange(begin+1, end)
1073 func (t *Torrent) needData() bool {
1074 if t.closed.IsSet() {
1080 if t.pendingPieces.Len() != 0 {
1083 // Read as "not all complete".
1084 return !t.readerPieces().IterTyped(func(piece int) bool {
1085 return t.pieceComplete(piece)
1089 func appendMissingStrings(old, new []string) (ret []string) {
1092 for _, n := range new {
1093 for _, o := range old {
1098 ret = append(ret, n)
1103 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1105 for minNumTiers > len(ret) {
1106 ret = append(ret, nil)
1111 func (t *Torrent) addTrackers(announceList [][]string) {
1112 fullAnnounceList := &t.metainfo.AnnounceList
1113 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1114 for tierIndex, trackerURLs := range announceList {
1115 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1117 t.startMissingTrackerScrapers()
1118 t.updateWantPeersEvent()
1121 // Don't call this before the info is available.
1122 func (t *Torrent) bytesCompleted() int64 {
1126 return t.info.TotalLength() - t.bytesLeft()
1129 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1131 defer t.cl.mu.Unlock()
1132 return t.setInfoBytes(b)
1135 // Returns true if connection is removed from torrent.Conns.
1136 func (t *Torrent) deleteConnection(c *connection) (ret bool) {
1142 func (t *Torrent) dropConnection(c *connection) {
1143 t.cl.event.Broadcast()
1145 if t.deleteConnection(c) {
1150 func (t *Torrent) wantPeers() bool {
1151 if t.closed.IsSet() {
1154 if len(t.peers) > torrentPeersLowWater {
1157 return t.needData() || t.seeding()
1160 func (t *Torrent) updateWantPeersEvent() {
1162 t.wantPeersEvent.Set()
1164 t.wantPeersEvent.Clear()
1168 // Returns whether the client should make effort to seed the torrent.
1169 func (t *Torrent) seeding() bool {
1171 if t.closed.IsSet() {
1174 if cl.config.NoUpload {
1177 if !cl.config.Seed {
1180 if cl.config.DisableAggressiveUpload && t.needData() {
1186 func (t *Torrent) startScrapingTracker(url string) {
1190 if _, ok := t.trackerAnnouncers[url]; ok {
1193 newAnnouncer := &trackerScraper{
1197 if t.trackerAnnouncers == nil {
1198 t.trackerAnnouncers = make(map[string]*trackerScraper)
1200 t.trackerAnnouncers[url] = newAnnouncer
1201 go newAnnouncer.Run()
1204 // Adds and starts tracker scrapers for tracker URLs that aren't already
1206 func (t *Torrent) startMissingTrackerScrapers() {
1207 if t.cl.config.DisableTrackers {
1210 t.startScrapingTracker(t.metainfo.Announce)
1211 for _, tier := range t.metainfo.AnnounceList {
1212 for _, url := range tier {
1213 t.startScrapingTracker(url)
1218 // Returns an AnnounceRequest with fields filled out to defaults and current
1220 func (t *Torrent) announceRequest() tracker.AnnounceRequest {
1221 return tracker.AnnounceRequest{
1222 Event: tracker.None,
1224 Port: uint16(t.cl.incomingPeerPort()),
1225 PeerId: t.cl.peerID,
1226 InfoHash: t.infoHash,
1227 Left: t.bytesLeftAnnounce(),
1231 // Adds peers revealed in an announce until the announce ends, or we have
1233 func (t *Torrent) consumeDHTAnnounce(pvs <-chan dht.PeersValues) {
1235 // Count all the unique addresses we got during this announce.
1236 allAddrs := make(map[string]struct{})
1239 case v, ok := <-pvs:
1243 addPeers := make([]Peer, 0, len(v.Peers))
1244 for _, cp := range v.Peers {
1246 // Can't do anything with this.
1249 addPeers = append(addPeers, Peer{
1252 Source: peerSourceDHTGetPeers,
1254 key := (&net.UDPAddr{
1258 allAddrs[key] = struct{}{}
1261 t.addPeers(addPeers)
1262 numPeers := len(t.peers)
1264 if numPeers >= torrentPeersHighWater {
1267 case <-t.closed.LockedChan(&cl.mu):
1273 func (t *Torrent) announceDHT(impliedPort bool) (err error) {
1275 ps, err := cl.dHT.Announce(t.infoHash, cl.incomingPeerPort(), impliedPort)
1279 t.consumeDHTAnnounce(ps.Peers)
1284 func (t *Torrent) dhtAnnouncer() {
1288 case <-t.wantPeersEvent.LockedChan(&cl.mu):
1289 case <-t.closed.LockedChan(&cl.mu):
1292 err := t.announceDHT(true)
1295 defer cl.mu.Unlock()
1299 log.Printf("error announcing %q to DHT: %s", t, err)
1303 case <-t.closed.LockedChan(&cl.mu):
1305 case <-time.After(5 * time.Minute):
1310 func (t *Torrent) addPeers(peers []Peer) {
1311 for _, p := range peers {
1312 if t.cl.badPeerIPPort(p.IP, p.Port) {
1319 func (t *Torrent) Stats() TorrentStats {
1321 defer t.cl.mu.Unlock()
1323 t.stats.ActivePeers = len(t.conns)
1324 t.stats.HalfOpenPeers = len(t.halfOpen)
1325 t.stats.PendingPeers = len(t.peers)
1326 t.stats.TotalPeers = t.numTotalPeers()
1331 // The total number of peers in the torrent.
1332 func (t *Torrent) numTotalPeers() int {
1333 peers := make(map[string]struct{})
1334 for conn := range t.conns {
1335 peers[conn.conn.RemoteAddr().String()] = struct{}{}
1337 for addr := range t.halfOpen {
1338 peers[addr] = struct{}{}
1340 for _, peer := range t.peers {
1341 peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{}
1346 // Returns true if the connection is added.
1347 func (t *Torrent) addConnection(c *connection, outgoing bool) bool {
1348 if t.cl.closed.IsSet() {
1354 for c0 := range t.conns {
1355 if c.PeerID == c0.PeerID {
1356 // Already connected to a client with that ID.
1357 duplicateClientConns.Add(1)
1358 lower := string(t.cl.peerID[:]) < string(c.PeerID[:])
1359 // Retain the connection from initiated from lower peer ID to
1361 if outgoing == lower {
1362 // Close the other one.
1364 // Is it safe to delete from the map while we're iterating
1366 t.deleteConnection(c0)
1368 // Abandon this one.
1373 if len(t.conns) >= t.maxEstablishedConns {
1374 c := t.worstBadConn()
1378 if t.cl.config.Debug && missinggo.CryHeard() {
1379 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1382 t.deleteConnection(c)
1384 if len(t.conns) >= t.maxEstablishedConns {
1388 panic("connection already associated with a torrent")
1390 // Reconcile bytes transferred before connection was associated with a
1392 t.stats.wroteBytes(c.stats.BytesWritten)
1393 t.stats.readBytes(c.stats.BytesRead)
1395 t.conns[c] = struct{}{}
1399 func (t *Torrent) wantConns() bool {
1400 if !t.networkingEnabled {
1403 if t.closed.IsSet() {
1406 if !t.seeding() && !t.needData() {
1409 if len(t.conns) < t.maxEstablishedConns {
1412 return t.worstBadConn() != nil
1415 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1417 defer t.cl.mu.Unlock()
1418 oldMax = t.maxEstablishedConns
1419 t.maxEstablishedConns = max
1420 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1421 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1422 t.dropConnection(wcs.Pop().(*connection))
1428 func (t *Torrent) mu() missinggo.RWLocker {
1432 func (t *Torrent) pieceHashed(piece int, correct bool) {
1433 if t.closed.IsSet() {
1436 p := &t.pieces[piece]
1437 touchers := t.reapPieceTouchers(piece)
1439 // Don't score the first time a piece is hashed, it could be an
1442 pieceHashedCorrect.Add(1)
1444 log.Printf("%s: piece %d (%s) failed hash: %d connections contributed", t, piece, p.hash, len(touchers))
1445 pieceHashedNotCorrect.Add(1)
1450 for _, c := range touchers {
1451 c.goodPiecesDirtied++
1453 err := p.Storage().MarkComplete()
1455 log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
1457 t.updatePieceCompletion(piece)
1459 if len(touchers) != 0 {
1460 for _, c := range touchers {
1461 // Y u do dis peer?!
1462 c.badPiecesDirtied++
1464 slices.Sort(touchers, connLessTrusted)
1465 log.Printf("dropping first corresponding conn from trust: %v", func() (ret []int) {
1466 for _, c := range touchers {
1467 ret = append(ret, c.netGoodPiecesDirtied())
1472 t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1475 t.onIncompletePiece(piece)
1479 func (t *Torrent) cancelRequestsForPiece(piece int) {
1480 // TODO: Make faster
1481 for cn := range t.conns {
1486 func (t *Torrent) onPieceCompleted(piece int) {
1487 t.pendingPieces.Remove(piece)
1488 t.pendAllChunkSpecs(piece)
1489 t.cancelRequestsForPiece(piece)
1490 for conn := range t.conns {
1495 func (t *Torrent) onIncompletePiece(piece int) {
1496 if t.pieceAllDirty(piece) {
1497 t.pendAllChunkSpecs(piece)
1499 if !t.wantPieceIndex(piece) {
1502 // We could drop any connections that we told we have a piece that we
1503 // don't here. But there's a test failure, and it seems clients don't care
1504 // if you request pieces that you already claim to have. Pruning bad
1505 // connections might just remove any connections that aren't treating us
1506 // favourably anyway.
1508 // for c := range t.conns {
1509 // if c.sentHave(piece) {
1513 for conn := range t.conns {
1514 if conn.PeerHasPiece(piece) {
1515 conn.updateRequests()
1520 func (t *Torrent) verifyPiece(piece int) {
1523 defer cl.mu.Unlock()
1524 p := &t.pieces[piece]
1527 cl.event.Broadcast()
1529 for p.hashing || t.storage == nil {
1532 if !p.t.piecesQueuedForHash.Remove(piece) {
1533 panic("piece was not queued")
1535 if t.closed.IsSet() || t.pieceComplete(piece) {
1536 t.updatePiecePriority(piece)
1540 t.publishPieceChange(piece)
1542 sum := t.hashPiece(piece)
1545 t.pieceHashed(piece, sum == p.hash)
1548 // Return the connections that touched a piece, and clear the entry while
1550 func (t *Torrent) reapPieceTouchers(piece int) (ret []*connection) {
1551 for c := range t.conns {
1552 if _, ok := c.peerTouchedPieces[piece]; ok {
1553 ret = append(ret, c)
1554 delete(c.peerTouchedPieces, piece)
1560 func (t *Torrent) connsAsSlice() (ret []*connection) {
1561 for c := range t.conns {
1562 ret = append(ret, c)
1567 // Currently doesn't really queue, but should in the future.
1568 func (t *Torrent) queuePieceCheck(pieceIndex int) {
1569 piece := &t.pieces[pieceIndex]
1570 if piece.queuedForHash() {
1573 t.piecesQueuedForHash.Add(pieceIndex)
1574 t.publishPieceChange(pieceIndex)
1575 go t.verifyPiece(pieceIndex)
1578 func (t *Torrent) VerifyData() {
1579 for i := range iter.N(t.NumPieces()) {
1580 t.Piece(i).VerifyData()