19 "github.com/anacrolix/dht"
20 "github.com/anacrolix/dht/krpc"
21 "github.com/anacrolix/log"
22 "github.com/anacrolix/missinggo"
23 "github.com/anacrolix/missinggo/bitmap"
24 "github.com/anacrolix/missinggo/perf"
25 "github.com/anacrolix/missinggo/prioritybitmap"
26 "github.com/anacrolix/missinggo/pubsub"
27 "github.com/anacrolix/missinggo/slices"
28 "github.com/bradfitz/iter"
29 "github.com/davecgh/go-spew/spew"
31 "github.com/anacrolix/torrent/bencode"
32 "github.com/anacrolix/torrent/metainfo"
33 pp "github.com/anacrolix/torrent/peer_protocol"
34 "github.com/anacrolix/torrent/storage"
35 "github.com/anacrolix/torrent/tracker"
38 func (t *Torrent) chunkIndexSpec(chunkIndex, piece int) chunkSpec {
39 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
42 type peersKey struct {
47 // Maintains state of torrent within a Client.
52 networkingEnabled bool
53 // Determines what chunks to request from peers. 1: Favour higher priority
54 // pieces with some fuzzing to reduce overlaps and wastage across
55 // connections. 2: The fastest connection downloads strictly in order of
56 // priority, while all others adher to their piece inclications.
59 closed missinggo.Event
60 infoHash metainfo.Hash
62 // Values are the piece indices that changed.
63 pieceStateChanges *pubsub.PubSub
64 // The size of chunks to request from peers over the wire. This is
65 // normally 16KiB by convention these days.
68 // Total length of the torrent in bytes. Stored because it's not O(1) to
69 // get this from the info dict.
72 // The storage to open when the info dict becomes available.
73 storageOpener *storage.Client
74 // Storage for torrent data.
75 storage *storage.Torrent
76 // Read-locked for using storage, and write-locked for Closing.
77 storageLock sync.RWMutex
79 // TODO: Only announce stuff is used?
80 metainfo metainfo.MetaInfo
82 // The info dict. nil if we don't have it (yet).
86 // Active peer connections, running message stream loops. TODO: Make this
87 // open (not-closed) connections only.
88 conns map[*connection]struct{}
89 maxEstablishedConns int
90 // Set of addrs to which we're attempting to connect. Connections are
91 // half-open until all handshakes are completed.
92 halfOpen map[string]Peer
93 fastestConn *connection
95 // Reserve of peers to connect to. A peer can be both here and in the
96 // active connections if were told about the peer after connecting with
97 // them. That encourages us to reconnect to peers that are well known in
99 peers map[peersKey]Peer
100 wantPeersEvent missinggo.Event
101 // An announcer for each tracker URL.
102 trackerAnnouncers map[string]*trackerScraper
103 // How many times we've initiated a DHT announce. TODO: Move into stats.
106 // Name used if the info name isn't available. Should be cleared when the
107 // Info does become available.
110 // The bencoded bytes of the info dict. This is actively manipulated if
111 // the info bytes aren't initially available, and we try to fetch them
114 // Each element corresponds to the 16KiB metadata pieces. If true, we have
115 // received that piece.
116 metadataCompletedChunks []bool
117 metadataChanged sync.Cond
119 // Set when .Info is obtained.
120 gotMetainfo missinggo.Event
122 readers map[*reader]struct{}
123 readerNowPieces bitmap.Bitmap
124 readerReadaheadPieces bitmap.Bitmap
126 // A cache of pieces we need to get. Calculated from various piece and
127 // file priorities and completion states elsewhere.
128 pendingPieces prioritybitmap.PriorityBitmap
129 // A cache of completed piece indices.
130 completedPieces bitmap.Bitmap
131 // Pieces that need to be hashed.
132 piecesQueuedForHash bitmap.Bitmap
134 // A pool of piece priorities []int for assignment to new connections.
135 // These "inclinations" are used to give connections preference for
137 connPieceInclinationPool sync.Pool
138 // Torrent-level statistics.
141 // Count of each request across active connections.
142 pendingRequests map[request]int
145 func (t *Torrent) tickleReaders() {
146 t.cl.event.Broadcast()
149 // Returns a channel that is closed when the Torrent is closed.
150 func (t *Torrent) Closed() <-chan struct{} {
151 return t.closed.LockedChan(&t.cl.mu)
154 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
155 // pending, and half-open peers.
156 func (t *Torrent) KnownSwarm() (ks []Peer) {
157 // Add pending peers to the list
158 for _, peer := range t.peers {
159 ks = append(ks, peer)
162 // Add half-open peers to the list
163 for _, peer := range t.halfOpen {
164 ks = append(ks, peer)
167 // Add active peers to the list
168 for conn := range t.conns {
169 host, portString, err := net.SplitHostPort(conn.remoteAddr().String())
174 ip := net.ParseIP(host)
175 port, err := strconv.Atoi(portString)
180 ks = append(ks, Peer{
184 Source: conn.Discovery,
185 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
186 // > But if we're not connected to them with an encrypted connection, I couldn't say
187 // > what's appropriate. We can carry forward the SupportsEncryption value as we
188 // > received it from trackers/DHT/PEX, or just use the encryption state for the
189 // > connection. It's probably easiest to do the latter for now.
190 // https://github.com/anacrolix/torrent/pull/188
191 SupportsEncryption: conn.headerEncrypted,
198 func (t *Torrent) setChunkSize(size pp.Integer) {
200 t.chunkPool = &sync.Pool{
201 New: func() interface{} {
202 b := make([]byte, size)
208 func (t *Torrent) setDisplayName(dn string) {
215 func (t *Torrent) pieceComplete(piece int) bool {
216 return t.completedPieces.Get(piece)
219 func (t *Torrent) pieceCompleteUncached(piece int) storage.Completion {
220 return t.pieces[piece].Storage().Completion()
223 // There's a connection to that address already.
224 func (t *Torrent) addrActive(addr string) bool {
225 if _, ok := t.halfOpen[addr]; ok {
228 for c := range t.conns {
233 if ra.String() == addr {
240 func (t *Torrent) unclosedConnsAsSlice() (ret []*connection) {
241 ret = make([]*connection, 0, len(t.conns))
242 for c := range t.conns {
243 if !c.closed.IsSet() {
250 func (t *Torrent) addPeer(p Peer) {
252 peersAddedBySource.Add(string(p.Source), 1)
253 if cl.badPeerIPPort(p.IP, p.Port) {
254 torrent.Add("peers not added because of bad addr", 1)
258 if len(t.peers) >= cl.config.TorrentPeersHighWater {
261 t.peers[peersKey{string(p.IP), p.Port}] = p
266 func (t *Torrent) invalidateMetadata() {
267 for i := range t.metadataCompletedChunks {
268 t.metadataCompletedChunks[i] = false
273 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
277 if index >= len(t.metadataCompletedChunks) {
278 log.Printf("%s: ignoring metadata piece %d", t, index)
281 copy(t.metadataBytes[(1<<14)*index:], data)
282 t.metadataCompletedChunks[index] = true
285 func (t *Torrent) metadataPieceCount() int {
286 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
289 func (t *Torrent) haveMetadataPiece(piece int) bool {
291 return (1<<14)*piece < len(t.metadataBytes)
293 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
297 func (t *Torrent) metadataSizeKnown() bool {
298 return t.metadataBytes != nil
301 func (t *Torrent) metadataSize() int {
302 return len(t.metadataBytes)
305 func infoPieceHashes(info *metainfo.Info) (ret []string) {
306 for i := 0; i < len(info.Pieces); i += sha1.Size {
307 ret = append(ret, string(info.Pieces[i:i+sha1.Size]))
312 func (t *Torrent) makePieces() {
313 hashes := infoPieceHashes(t.info)
314 t.pieces = make([]Piece, len(hashes))
315 for i, hash := range hashes {
316 piece := &t.pieces[i]
319 piece.noPendingWrites.L = &piece.pendingWritesMutex
320 missinggo.CopyExact(piece.hash[:], hash)
322 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
323 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
324 piece.files = files[beginFile:endFile]
328 // Returns the index of the first file containing the piece. files must be
329 // ordered by offset.
330 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
331 for i, f := range files {
332 if f.offset+f.length > pieceOffset {
339 // Returns the index after the last file containing the piece. files must be
340 // ordered by offset.
341 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
342 for i, f := range files {
343 if f.offset+f.length >= pieceEndOffset {
350 func (t *Torrent) cacheLength() {
352 for _, f := range t.info.UpvertedFiles() {
358 func (t *Torrent) setInfo(info *metainfo.Info) error {
359 if err := validateInfo(info); err != nil {
360 return fmt.Errorf("bad info: %s", err)
362 if t.storageOpener != nil {
364 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
366 return fmt.Errorf("error opening torrent storage: %s", err)
370 t.displayName = "" // Save a few bytes lol.
377 func (t *Torrent) onSetInfo() {
378 for conn := range t.conns {
379 if err := conn.setNumPieces(t.numPieces()); err != nil {
380 log.Printf("closing connection: %s", err)
384 for i := range t.pieces {
385 t.updatePieceCompletion(i)
387 if !p.storageCompletionOk {
388 // log.Printf("piece %s completion unknown, queueing check", p)
392 t.cl.event.Broadcast()
394 t.updateWantPeersEvent()
395 t.pendingRequests = make(map[request]int)
398 // Called when metadata for a torrent becomes available.
399 func (t *Torrent) setInfoBytes(b []byte) error {
400 if metainfo.HashBytes(b) != t.infoHash {
401 return errors.New("info bytes have wrong hash")
403 var info metainfo.Info
404 if err := bencode.Unmarshal(b, &info); err != nil {
405 return fmt.Errorf("error unmarshalling info bytes: %s", err)
407 if err := t.setInfo(&info); err != nil {
411 t.metadataCompletedChunks = nil
416 func (t *Torrent) haveAllMetadataPieces() bool {
420 if t.metadataCompletedChunks == nil {
423 for _, have := range t.metadataCompletedChunks {
431 // TODO: Propagate errors to disconnect peer.
432 func (t *Torrent) setMetadataSize(bytes int64) (err error) {
434 // We already know the correct metadata size.
437 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
438 return errors.New("bad size")
440 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
443 t.metadataBytes = make([]byte, bytes)
444 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
445 t.metadataChanged.Broadcast()
446 for c := range t.conns {
447 c.requestPendingMetadata()
452 // The current working name for the torrent. Either the name in the info dict,
453 // or a display name given such as by the dn value in a magnet link, or "".
454 func (t *Torrent) name() string {
461 func (t *Torrent) pieceState(index int) (ret PieceState) {
462 p := &t.pieces[index]
463 ret.Priority = t.piecePriority(index)
464 ret.Completion = p.completion()
465 if p.queuedForHash() || p.hashing {
468 if !ret.Complete && t.piecePartiallyDownloaded(index) {
474 func (t *Torrent) metadataPieceSize(piece int) int {
475 return metadataPieceSize(len(t.metadataBytes), piece)
478 func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
484 d["total_size"] = len(t.metadataBytes)
486 p, err := bencode.Marshal(d)
492 ExtendedID: c.PeerExtensionIDs["ut_metadata"],
493 ExtendedPayload: append(p, data...),
497 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
498 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
499 ret = append(ret, PieceStateRun{
500 PieceState: el.(PieceState),
504 for index := range t.pieces {
505 rle.Append(t.pieceState(index), 1)
511 // Produces a small string representing a PieceStateRun.
512 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
513 ret = fmt.Sprintf("%d", psr.Length)
514 ret += func() string {
515 switch psr.Priority {
516 case PiecePriorityNext:
518 case PiecePriorityNormal:
520 case PiecePriorityReadahead:
522 case PiecePriorityNow:
524 case PiecePriorityHigh:
545 func (t *Torrent) writeStatus(w io.Writer) {
546 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
547 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
549 fmt.Fprintf(w, "Metadata have: ")
550 for _, h := range t.metadataCompletedChunks {
551 fmt.Fprintf(w, "%c", func() rune {
561 fmt.Fprintf(w, "Piece length: %s\n", func() string {
563 return fmt.Sprint(t.usualPieceSize())
569 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
570 fmt.Fprint(w, "Piece States:")
571 for _, psr := range t.pieceStateRuns() {
573 w.Write([]byte(pieceStateRunStatusChars(psr)))
577 fmt.Fprintf(w, "Reader Pieces:")
578 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
579 fmt.Fprintf(w, " %d:%d", begin, end)
584 fmt.Fprintf(w, "Enabled trackers:\n")
586 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
587 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
588 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
589 return l.u.String() < r.u.String()
590 }).([]*trackerScraper) {
591 fmt.Fprintf(tw, " %s\n", ta.statusLine())
596 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
598 spew.NewDefaultConfig()
599 spew.Fdump(w, t.statsLocked())
601 conns := t.connsAsSlice()
602 slices.Sort(conns, worseConn)
603 for i, c := range conns {
604 fmt.Fprintf(w, "%2d. ", i+1)
609 func (t *Torrent) haveInfo() bool {
613 // Returns a run-time generated MetaInfo that includes the info bytes and
614 // announce-list as currently known to the client.
615 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
616 return metainfo.MetaInfo{
617 CreationDate: time.Now().Unix(),
618 Comment: "dynamic metainfo from client",
619 CreatedBy: "go.torrent",
620 AnnounceList: t.metainfo.UpvertedAnnounceList(),
621 InfoBytes: func() []byte {
623 return t.metadataBytes
631 func (t *Torrent) BytesMissing() int64 {
633 defer t.mu().RUnlock()
634 return t.bytesMissingLocked()
637 func (t *Torrent) bytesMissingLocked() int64 {
641 func (t *Torrent) bytesLeft() (left int64) {
642 bitmap.Flip(t.completedPieces, 0, t.numPieces()).IterTyped(func(piece int) bool {
643 p := &t.pieces[piece]
644 left += int64(p.length() - p.numDirtyBytes())
650 // Bytes left to give in tracker announces.
651 func (t *Torrent) bytesLeftAnnounce() uint64 {
653 return uint64(t.bytesLeft())
655 return math.MaxUint64
659 func (t *Torrent) piecePartiallyDownloaded(piece int) bool {
660 if t.pieceComplete(piece) {
663 if t.pieceAllDirty(piece) {
666 return t.pieces[piece].hasDirtyChunks()
669 func (t *Torrent) usualPieceSize() int {
670 return int(t.info.PieceLength)
673 func (t *Torrent) numPieces() int {
674 return t.info.NumPieces()
677 func (t *Torrent) numPiecesCompleted() (num int) {
678 return t.completedPieces.Len()
681 func (t *Torrent) close() (err error) {
684 if t.storage != nil {
687 t.storageLock.Unlock()
689 for conn := range t.conns {
692 t.cl.event.Broadcast()
693 t.pieceStateChanges.Close()
694 t.updateWantPeersEvent()
698 func (t *Torrent) requestOffset(r request) int64 {
699 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
702 // Return the request that would include the given offset into the torrent
703 // data. Returns !ok if there is no such request.
704 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
705 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
708 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
709 tr := perf.NewTimer()
711 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
712 if err == nil && n != len(data) {
713 err = io.ErrShortWrite
716 tr.Mark("write chunk")
721 func (t *Torrent) bitfield() (bf []bool) {
722 bf = make([]bool, t.numPieces())
723 t.completedPieces.IterTyped(func(piece int) (again bool) {
730 func (t *Torrent) pieceNumChunks(piece int) int {
731 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
734 func (t *Torrent) pendAllChunkSpecs(pieceIndex int) {
735 t.pieces[pieceIndex].dirtyChunks.Clear()
743 // Peer is known to support encryption.
744 SupportsEncryption bool
748 func (me *Peer) FromPex(na krpc.NodeAddr, fs pexPeerFlags) {
749 me.IP = append([]byte(nil), na.IP...)
751 me.Source = peerSourcePEX
752 // If they prefer encryption, they must support it.
753 if fs.Get(pexPrefersEncryption) {
754 me.SupportsEncryption = true
759 func (t *Torrent) pieceLength(piece int) pp.Integer {
760 if t.info.PieceLength == 0 {
761 // There will be no variance amongst pieces. Only pain.
764 if piece == t.numPieces()-1 {
765 ret := pp.Integer(*t.length % t.info.PieceLength)
770 return pp.Integer(t.info.PieceLength)
773 func (t *Torrent) hashPiece(piece int) (ret metainfo.Hash) {
774 hash := pieceHash.New()
775 p := &t.pieces[piece]
776 p.waitNoPendingWrites()
777 ip := t.info.Piece(piece)
779 n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
781 missinggo.CopyExact(&ret, hash.Sum(nil))
784 if err != io.ErrUnexpectedEOF && !os.IsNotExist(err) {
785 log.Printf("unexpected error hashing piece with %T: %s", t.storage.TorrentImpl, err)
790 func (t *Torrent) haveAnyPieces() bool {
791 return t.completedPieces.Len() != 0
794 func (t *Torrent) haveAllPieces() bool {
798 return t.completedPieces.Len() == t.numPieces()
801 func (t *Torrent) havePiece(index int) bool {
802 return t.haveInfo() && t.pieceComplete(index)
805 func (t *Torrent) haveChunk(r request) (ret bool) {
807 // log.Println("have chunk", r, ret)
812 if t.pieceComplete(int(r.Index)) {
815 p := &t.pieces[r.Index]
816 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
819 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
820 return int(cs.Begin / chunkSize)
823 func (t *Torrent) wantPiece(r request) bool {
824 if !t.wantPieceIndex(int(r.Index)) {
827 if t.pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
830 // TODO: What about pieces that were wanted, but aren't now, and aren't
831 // completed either? That used to be done here.
835 func (t *Torrent) wantPieceIndex(index int) bool {
839 if index < 0 || index >= t.numPieces() {
842 p := &t.pieces[index]
843 if p.queuedForHash() {
849 if t.pieceComplete(index) {
852 if t.pendingPieces.Contains(index) {
855 // log.Printf("piece %d not pending", index)
856 return !t.forReaderOffsetPieces(func(begin, end int) bool {
857 return index < begin || index >= end
861 // The worst connection is one that hasn't been sent, or sent anything useful
862 // for the longest. A bad connection is one that usually sends us unwanted
863 // pieces, or has been in worser half of the established connections for more
865 func (t *Torrent) worstBadConn() *connection {
866 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
869 c := heap.Pop(&wcs).(*connection)
870 if c.stats.ChunksReadUnwanted >= 6 && c.stats.ChunksReadUnwanted > c.stats.ChunksReadUseful {
873 // If the connection is in the worst half of the established
874 // connection quota and is older than a minute.
875 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
876 // Give connections 1 minute to prove themselves.
877 if time.Since(c.completedHandshake) > time.Minute {
885 type PieceStateChange struct {
890 func (t *Torrent) publishPieceChange(piece int) {
891 cur := t.pieceState(piece)
892 p := &t.pieces[piece]
893 if cur != p.publicPieceState {
894 p.publicPieceState = cur
895 t.pieceStateChanges.Publish(PieceStateChange{
902 func (t *Torrent) pieceNumPendingChunks(piece int) int {
903 if t.pieceComplete(piece) {
906 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
909 func (t *Torrent) pieceAllDirty(piece int) bool {
910 return t.pieces[piece].dirtyChunks.Len() == t.pieceNumChunks(piece)
913 func (t *Torrent) readersChanged() {
914 t.updateReaderPieces()
915 t.updateAllPiecePriorities()
918 func (t *Torrent) updateReaderPieces() {
919 t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
922 func (t *Torrent) readerPosChanged(from, to pieceRange) {
926 t.updateReaderPieces()
927 // Order the ranges, high and low.
929 if l.begin > h.begin {
933 // Two distinct ranges.
934 t.updatePiecePriorities(l.begin, l.end)
935 t.updatePiecePriorities(h.begin, h.end)
942 t.updatePiecePriorities(l.begin, end)
946 func (t *Torrent) maybeNewConns() {
947 // Tickle the accept routine.
948 t.cl.event.Broadcast()
952 func (t *Torrent) piecePriorityChanged(piece int) {
953 // log.Printf("piece %d priority changed", piece)
954 for c := range t.conns {
955 if c.updatePiecePriority(piece) {
956 // log.Print("conn piece priority changed")
961 t.publishPieceChange(piece)
964 func (t *Torrent) updatePiecePriority(piece int) {
965 p := &t.pieces[piece]
966 newPrio := p.uncachedPriority()
967 // log.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
968 if newPrio == PiecePriorityNone {
969 if !t.pendingPieces.Remove(piece) {
973 if !t.pendingPieces.Set(piece, newPrio.BitmapPriority()) {
977 t.piecePriorityChanged(piece)
980 func (t *Torrent) updateAllPiecePriorities() {
981 t.updatePiecePriorities(0, len(t.pieces))
984 // Update all piece priorities in one hit. This function should have the same
985 // output as updatePiecePriority, but across all pieces.
986 func (t *Torrent) updatePiecePriorities(begin, end int) {
987 for i := begin; i < end; i++ {
988 t.updatePiecePriority(i)
992 // Returns the range of pieces [begin, end) that contains the extent of bytes.
993 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end int) {
994 if off >= *t.length {
1004 begin = int(off / t.info.PieceLength)
1005 end = int((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1006 if end > t.info.NumPieces() {
1007 end = t.info.NumPieces()
1012 // Returns true if all iterations complete without breaking. Returns the read
1013 // regions for all readers. The reader regions should not be merged as some
1014 // callers depend on this method to enumerate readers.
1015 func (t *Torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
1016 for r := range t.readers {
1018 if p.begin >= p.end {
1021 if !f(p.begin, p.end) {
1028 func (t *Torrent) piecePriority(piece int) piecePriority {
1029 prio, ok := t.pendingPieces.GetPriority(piece)
1031 return PiecePriorityNone
1036 ret := piecePriority(-prio)
1037 if ret == PiecePriorityNone {
1043 func (t *Torrent) pendRequest(req request) {
1044 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1045 t.pieces[req.Index].pendChunkIndex(ci)
1048 func (t *Torrent) pieceCompletionChanged(piece int) {
1049 log.Call().Add("piece", piece).AddValue(debugLogValue).Log(t.logger)
1050 t.cl.event.Broadcast()
1051 if t.pieceComplete(piece) {
1052 t.onPieceCompleted(piece)
1054 t.onIncompletePiece(piece)
1056 t.updatePiecePriority(piece)
1059 func (t *Torrent) numReceivedConns() (ret int) {
1060 for c := range t.conns {
1061 if c.Discovery == peerSourceIncoming {
1068 func (t *Torrent) maxHalfOpen() int {
1069 // Note that if we somehow exceed the maximum established conns, we want
1070 // the negative value to have an effect.
1071 establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1072 extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1073 // We want to allow some experimentation with new peers, and to try to
1074 // upset an oversupply of received connections.
1075 return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.halfOpenLimit)))
1078 func (t *Torrent) openNewConns() {
1079 defer t.updateWantPeersEvent()
1080 for len(t.peers) != 0 {
1084 if len(t.halfOpen) >= t.maxHalfOpen() {
1091 for k, p = range t.peers {
1099 func (t *Torrent) getConnPieceInclination() []int {
1100 _ret := t.connPieceInclinationPool.Get()
1102 pieceInclinationsNew.Add(1)
1103 return rand.Perm(t.numPieces())
1105 pieceInclinationsReused.Add(1)
1106 return *_ret.(*[]int)
1109 func (t *Torrent) putPieceInclination(pi []int) {
1110 t.connPieceInclinationPool.Put(&pi)
1111 pieceInclinationsPut.Add(1)
1114 func (t *Torrent) updatePieceCompletion(piece int) {
1115 pcu := t.pieceCompleteUncached(piece)
1116 p := &t.pieces[piece]
1117 changed := t.completedPieces.Get(piece) != pcu.Complete || p.storageCompletionOk != pcu.Ok
1118 log.Fmsg("piece %d completion: %v", piece, pcu.Ok).AddValue(debugLogValue).Log(t.logger)
1119 p.storageCompletionOk = pcu.Ok
1120 t.completedPieces.Set(piece, pcu.Complete)
1122 // log.Printf("piece %d uncached completion: %v", piece, pcu.Complete)
1123 // log.Printf("piece %d changed: %v", piece, changed)
1125 t.pieceCompletionChanged(piece)
1129 // Non-blocking read. Client lock is not required.
1130 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1131 p := &t.pieces[off/t.info.PieceLength]
1132 p.waitNoPendingWrites()
1133 return p.Storage().ReadAt(b, off-p.Info().Offset())
1136 func (t *Torrent) updateAllPieceCompletions() {
1137 for i := range iter.N(t.numPieces()) {
1138 t.updatePieceCompletion(i)
1142 // Returns an error if the metadata was completed, but couldn't be set for
1143 // some reason. Blame it on the last peer to contribute.
1144 func (t *Torrent) maybeCompleteMetadata() error {
1149 if !t.haveAllMetadataPieces() {
1150 // Don't have enough metadata pieces.
1153 err := t.setInfoBytes(t.metadataBytes)
1155 t.invalidateMetadata()
1156 return fmt.Errorf("error setting info bytes: %s", err)
1158 if t.cl.config.Debug {
1159 log.Printf("%s: got metadata from peers", t)
1164 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1165 t.forReaderOffsetPieces(func(begin, end int) bool {
1166 ret.AddRange(begin, end)
1172 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1173 t.forReaderOffsetPieces(func(begin, end int) bool {
1176 readahead.AddRange(begin+1, end)
1183 func (t *Torrent) needData() bool {
1184 if t.closed.IsSet() {
1190 return t.pendingPieces.Len() != 0
1193 func appendMissingStrings(old, new []string) (ret []string) {
1196 for _, n := range new {
1197 for _, o := range old {
1202 ret = append(ret, n)
1207 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1209 for minNumTiers > len(ret) {
1210 ret = append(ret, nil)
1215 func (t *Torrent) addTrackers(announceList [][]string) {
1216 fullAnnounceList := &t.metainfo.AnnounceList
1217 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1218 for tierIndex, trackerURLs := range announceList {
1219 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1221 t.startMissingTrackerScrapers()
1222 t.updateWantPeersEvent()
1225 // Don't call this before the info is available.
1226 func (t *Torrent) bytesCompleted() int64 {
1230 return t.info.TotalLength() - t.bytesLeft()
1233 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1235 defer t.cl.mu.Unlock()
1236 return t.setInfoBytes(b)
1239 // Returns true if connection is removed from torrent.Conns.
1240 func (t *Torrent) deleteConnection(c *connection) (ret bool) {
1241 if !c.closed.IsSet() {
1242 panic("connection is not closed")
1243 // There are behaviours prevented by the closed state that will fail
1244 // if the connection has been deleted.
1248 c.deleteAllRequests()
1249 if len(t.conns) == 0 {
1250 t.assertNoPendingRequests()
1255 func (t *Torrent) assertNoPendingRequests() {
1256 for _, num := range t.pendingRequests {
1263 func (t *Torrent) dropConnection(c *connection) {
1264 t.cl.event.Broadcast()
1266 if t.deleteConnection(c) {
1271 func (t *Torrent) wantPeers() bool {
1272 if t.closed.IsSet() {
1275 if len(t.peers) > t.cl.config.TorrentPeersLowWater {
1278 return t.needData() || t.seeding()
1281 func (t *Torrent) updateWantPeersEvent() {
1283 t.wantPeersEvent.Set()
1285 t.wantPeersEvent.Clear()
1289 // Returns whether the client should make effort to seed the torrent.
1290 func (t *Torrent) seeding() bool {
1292 if t.closed.IsSet() {
1295 if cl.config.NoUpload {
1298 if !cl.config.Seed {
1301 if cl.config.DisableAggressiveUpload && t.needData() {
1307 func (t *Torrent) startScrapingTracker(_url string) {
1311 u, _ := url.Parse(_url)
1312 if u.Scheme == "udp" {
1314 t.startScrapingTracker(u.String())
1316 t.startScrapingTracker(u.String())
1319 if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1322 if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1325 if _, ok := t.trackerAnnouncers[_url]; ok {
1328 newAnnouncer := &trackerScraper{
1332 if t.trackerAnnouncers == nil {
1333 t.trackerAnnouncers = make(map[string]*trackerScraper)
1335 t.trackerAnnouncers[_url] = newAnnouncer
1336 go newAnnouncer.Run()
1339 // Adds and starts tracker scrapers for tracker URLs that aren't already
1341 func (t *Torrent) startMissingTrackerScrapers() {
1342 if t.cl.config.DisableTrackers {
1345 t.startScrapingTracker(t.metainfo.Announce)
1346 for _, tier := range t.metainfo.AnnounceList {
1347 for _, url := range tier {
1348 t.startScrapingTracker(url)
1353 // Returns an AnnounceRequest with fields filled out to defaults and current
1355 func (t *Torrent) announceRequest() tracker.AnnounceRequest {
1356 return tracker.AnnounceRequest{
1357 Event: tracker.None,
1359 Port: uint16(t.cl.incomingPeerPort()),
1360 PeerId: t.cl.peerID,
1361 InfoHash: t.infoHash,
1362 Left: t.bytesLeftAnnounce(),
1363 Key: t.cl.announceKey(),
1367 // Adds peers revealed in an announce until the announce ends, or we have
1369 func (t *Torrent) consumeDHTAnnounce(pvs <-chan dht.PeersValues) {
1371 // Count all the unique addresses we got during this announce.
1372 allAddrs := make(map[string]struct{})
1375 case v, ok := <-pvs:
1379 addPeers := make([]Peer, 0, len(v.Peers))
1380 for _, cp := range v.Peers {
1382 // Can't do anything with this.
1385 addPeers = append(addPeers, Peer{
1388 Source: peerSourceDHTGetPeers,
1390 key := (&net.UDPAddr{
1394 allAddrs[key] = struct{}{}
1397 t.addPeers(addPeers)
1398 numPeers := len(t.peers)
1400 if numPeers >= cl.config.TorrentPeersHighWater {
1403 case <-t.closed.LockedChan(&cl.mu):
1409 func (t *Torrent) announceDHT(impliedPort bool) (err error) {
1411 ps, err := cl.dHT.Announce(t.infoHash, cl.incomingPeerPort(), impliedPort)
1415 t.consumeDHTAnnounce(ps.Peers)
1420 func (t *Torrent) dhtAnnouncer() {
1424 case <-t.wantPeersEvent.LockedChan(&cl.mu):
1425 case <-t.closed.LockedChan(&cl.mu):
1428 err := t.announceDHT(true)
1431 defer cl.mu.Unlock()
1435 log.Printf("error announcing %q to DHT: %s", t, err)
1439 case <-t.closed.LockedChan(&cl.mu):
1441 case <-time.After(5 * time.Minute):
1446 func (t *Torrent) addPeers(peers []Peer) {
1447 for _, p := range peers {
1452 func (t *Torrent) Stats() TorrentStats {
1454 defer t.cl.mu.Unlock()
1455 return t.statsLocked()
1458 func (t *Torrent) statsLocked() TorrentStats {
1459 t.stats.ActivePeers = len(t.conns)
1460 t.stats.HalfOpenPeers = len(t.halfOpen)
1461 t.stats.PendingPeers = len(t.peers)
1462 t.stats.TotalPeers = t.numTotalPeers()
1463 t.stats.ConnectedSeeders = 0
1464 for c := range t.conns {
1465 if all, ok := c.peerHasAllPieces(); all && ok {
1466 t.stats.ConnectedSeeders++
1472 // The total number of peers in the torrent.
1473 func (t *Torrent) numTotalPeers() int {
1474 peers := make(map[string]struct{})
1475 for conn := range t.conns {
1476 ra := conn.conn.RemoteAddr()
1478 // It's been closed and doesn't support RemoteAddr.
1481 peers[ra.String()] = struct{}{}
1483 for addr := range t.halfOpen {
1484 peers[addr] = struct{}{}
1486 for _, peer := range t.peers {
1487 peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{}
1492 // Reconcile bytes transferred before connection was associated with a
1494 func (t *Torrent) reconcileHandshakeStats(c *connection) {
1495 t.stats.wroteBytes(c.stats.BytesWritten)
1496 t.stats.readBytes(c.stats.BytesRead)
1499 // Returns true if the connection is added.
1500 func (t *Torrent) addConnection(c *connection, outgoing bool) bool {
1501 if t.closed.IsSet() {
1507 for c0 := range t.conns {
1508 if c.PeerID == c0.PeerID {
1509 // Already connected to a client with that ID.
1510 duplicateClientConns.Add(1)
1511 lower := string(t.cl.peerID[:]) < string(c.PeerID[:])
1512 // Retain the connection from initiated from lower peer ID to
1514 if outgoing == lower {
1515 // Close the other one.
1517 // TODO: Is it safe to delete from the map while we're
1518 // iterating over it?
1519 t.deleteConnection(c0)
1521 // Abandon this one.
1526 if len(t.conns) >= t.maxEstablishedConns {
1527 c := t.worstBadConn()
1531 if t.cl.config.Debug && missinggo.CryHeard() {
1532 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1535 t.deleteConnection(c)
1537 if len(t.conns) >= t.maxEstablishedConns {
1544 func (t *Torrent) wantConns() bool {
1545 if !t.networkingEnabled {
1548 if t.closed.IsSet() {
1551 if !t.seeding() && !t.needData() {
1554 if len(t.conns) < t.maxEstablishedConns {
1557 return t.worstBadConn() != nil
1560 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1562 defer t.cl.mu.Unlock()
1563 oldMax = t.maxEstablishedConns
1564 t.maxEstablishedConns = max
1565 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1566 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1567 t.dropConnection(wcs.Pop().(*connection))
1573 func (t *Torrent) mu() missinggo.RWLocker {
1577 func (t *Torrent) pieceHashed(piece int, correct bool) {
1578 log.Fmsg("hashed piece %d", piece).Add("piece", piece).Add("passed", correct).AddValue(debugLogValue).Log(t.logger)
1579 if t.closed.IsSet() {
1582 p := &t.pieces[piece]
1583 touchers := t.reapPieceTouchers(piece)
1584 if p.storageCompletionOk {
1585 // Don't score the first time a piece is hashed, it could be an
1588 pieceHashedCorrect.Add(1)
1590 log.Printf("%s: piece %d (%s) failed hash: %d connections contributed", t, piece, p.hash, len(touchers))
1591 pieceHashedNotCorrect.Add(1)
1595 if len(touchers) != 0 {
1596 t.stats.PiecesDirtiedGood++
1598 for _, c := range touchers {
1599 c.stats.PiecesDirtiedGood++
1601 err := p.Storage().MarkComplete()
1603 log.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1606 if len(touchers) != 0 {
1607 t.stats.PiecesDirtiedBad++
1608 for _, c := range touchers {
1609 // Y u do dis peer?!
1610 c.stats.PiecesDirtiedBad++
1612 slices.Sort(touchers, connLessTrusted)
1613 if t.cl.config.Debug {
1614 log.Printf("dropping first corresponding conn from trust: %v", func() (ret []int64) {
1615 for _, c := range touchers {
1616 ret = append(ret, c.netGoodPiecesDirtied())
1622 t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1625 t.onIncompletePiece(piece)
1626 p.Storage().MarkNotComplete()
1628 t.updatePieceCompletion(piece)
1631 func (t *Torrent) cancelRequestsForPiece(piece int) {
1632 // TODO: Make faster
1633 for cn := range t.conns {
1638 func (t *Torrent) onPieceCompleted(piece int) {
1639 t.pendAllChunkSpecs(piece)
1640 t.cancelRequestsForPiece(piece)
1641 for conn := range t.conns {
1646 // Called when a piece is found to be not complete.
1647 func (t *Torrent) onIncompletePiece(piece int) {
1648 if t.pieceAllDirty(piece) {
1649 t.pendAllChunkSpecs(piece)
1651 if !t.wantPieceIndex(piece) {
1652 // log.Printf("piece %d incomplete and unwanted", piece)
1655 // We could drop any connections that we told we have a piece that we
1656 // don't here. But there's a test failure, and it seems clients don't care
1657 // if you request pieces that you already claim to have. Pruning bad
1658 // connections might just remove any connections that aren't treating us
1659 // favourably anyway.
1661 // for c := range t.conns {
1662 // if c.sentHave(piece) {
1666 for conn := range t.conns {
1667 if conn.PeerHasPiece(piece) {
1668 conn.updateRequests()
1673 func (t *Torrent) verifyPiece(piece int) {
1676 defer cl.mu.Unlock()
1677 p := &t.pieces[piece]
1680 cl.event.Broadcast()
1682 for p.hashing || t.storage == nil {
1685 if !p.t.piecesQueuedForHash.Remove(piece) {
1686 panic("piece was not queued")
1688 if t.closed.IsSet() || t.pieceComplete(piece) {
1689 t.updatePiecePriority(piece)
1693 t.publishPieceChange(piece)
1694 t.storageLock.RLock()
1696 sum := t.hashPiece(piece)
1697 t.storageLock.RUnlock()
1700 t.pieceHashed(piece, sum == p.hash)
1701 t.publishPieceChange(piece)
1704 // Return the connections that touched a piece, and clear the entries while
1706 func (t *Torrent) reapPieceTouchers(piece int) (ret []*connection) {
1707 for c := range t.pieces[piece].dirtiers {
1708 delete(c.peerTouchedPieces, piece)
1709 ret = append(ret, c)
1711 t.pieces[piece].dirtiers = nil
1715 func (t *Torrent) connsAsSlice() (ret []*connection) {
1716 for c := range t.conns {
1717 ret = append(ret, c)
1722 // Currently doesn't really queue, but should in the future.
1723 func (t *Torrent) queuePieceCheck(pieceIndex int) {
1724 piece := &t.pieces[pieceIndex]
1725 if piece.queuedForHash() {
1728 t.piecesQueuedForHash.Add(pieceIndex)
1729 t.publishPieceChange(pieceIndex)
1730 go t.verifyPiece(pieceIndex)
1733 func (t *Torrent) VerifyData() {
1734 for i := range iter.N(t.NumPieces()) {
1735 t.Piece(i).VerifyData()
1739 // Start the process of connecting to the given peer for the given torrent if
1741 func (t *Torrent) initiateConn(peer Peer) {
1742 if peer.Id == t.cl.peerID {
1745 if t.cl.badPeerIPPort(peer.IP, peer.Port) {
1748 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
1749 if t.addrActive(addr) {
1752 t.halfOpen[addr] = peer
1753 go t.cl.outgoingConnection(t, addr, peer.Source)