18 "github.com/anacrolix/log"
20 "github.com/davecgh/go-spew/spew"
22 "github.com/anacrolix/dht"
23 "github.com/anacrolix/missinggo"
24 "github.com/anacrolix/missinggo/bitmap"
25 "github.com/anacrolix/missinggo/perf"
26 "github.com/anacrolix/missinggo/prioritybitmap"
27 "github.com/anacrolix/missinggo/pubsub"
28 "github.com/anacrolix/missinggo/slices"
29 "github.com/bradfitz/iter"
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 metainfo metainfo.MetaInfo
81 // The info dict. nil if we don't have it (yet).
85 // Active peer connections, running message stream loops.
86 conns map[*connection]struct{}
87 maxEstablishedConns int
88 // Set of addrs to which we're attempting to connect. Connections are
89 // half-open until all handshakes are completed.
90 halfOpen map[string]Peer
91 fastestConn *connection
93 // Reserve of peers to connect to. A peer can be both here and in the
94 // active connections if were told about the peer after connecting with
95 // them. That encourages us to reconnect to peers that are well known in
97 peers map[peersKey]Peer
98 wantPeersEvent missinggo.Event
99 // An announcer for each tracker URL.
100 trackerAnnouncers map[string]*trackerScraper
101 // How many times we've initiated a DHT announce. TODO: Move into stats.
104 // Name used if the info name isn't available. Should be cleared when the
105 // Info does become available.
108 // The bencoded bytes of the info dict. This is actively manipulated if
109 // the info bytes aren't initially available, and we try to fetch them
112 // Each element corresponds to the 16KiB metadata pieces. If true, we have
113 // received that piece.
114 metadataCompletedChunks []bool
115 metadataChanged sync.Cond
117 // Set when .Info is obtained.
118 gotMetainfo missinggo.Event
120 readers map[*reader]struct{}
121 readerNowPieces bitmap.Bitmap
122 readerReadaheadPieces bitmap.Bitmap
124 // A cache of pieces we need to get. Calculated from various piece and
125 // file priorities and completion states elsewhere.
126 pendingPieces prioritybitmap.PriorityBitmap
127 // A cache of completed piece indices.
128 completedPieces bitmap.Bitmap
129 // Pieces that need to be hashed.
130 piecesQueuedForHash bitmap.Bitmap
132 // A pool of piece priorities []int for assignment to new connections.
133 // These "inclinations" are used to give connections preference for
135 connPieceInclinationPool sync.Pool
136 // Torrent-level statistics.
140 // Returns a channel that is closed when the Torrent is closed.
141 func (t *Torrent) Closed() <-chan struct{} {
142 return t.closed.LockedChan(&t.cl.mu)
145 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
146 // pending, and half-open peers.
147 func (t *Torrent) KnownSwarm() (ks []Peer) {
148 // Add pending peers to the list
149 for _, peer := range t.peers {
150 ks = append(ks, peer)
153 // Add half-open peers to the list
154 for _, peer := range t.halfOpen {
155 ks = append(ks, peer)
158 // Add active peers to the list
159 for conn := range t.conns {
160 host, portString, err := net.SplitHostPort(conn.remoteAddr().String())
165 ip := net.ParseIP(host)
166 port, err := strconv.Atoi(portString)
171 ks = append(ks, Peer{
175 Source: conn.Discovery,
176 // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
177 // > But if we're not connected to them with an encrypted connection, I couldn't say
178 // > what's appropriate. We can carry forward the SupportsEncryption value as we
179 // > received it from trackers/DHT/PEX, or just use the encryption state for the
180 // > connection. It's probably easiest to do the latter for now.
181 // https://github.com/anacrolix/torrent/pull/188
182 SupportsEncryption: conn.headerEncrypted,
189 func (t *Torrent) setChunkSize(size pp.Integer) {
191 t.chunkPool = &sync.Pool{
192 New: func() interface{} {
193 b := make([]byte, size)
199 func (t *Torrent) setDisplayName(dn string) {
206 func (t *Torrent) pieceComplete(piece int) bool {
207 return t.completedPieces.Get(piece)
210 func (t *Torrent) pieceCompleteUncached(piece int) storage.Completion {
211 return t.pieces[piece].Storage().Completion()
214 // There's a connection to that address already.
215 func (t *Torrent) addrActive(addr string) bool {
216 if _, ok := t.halfOpen[addr]; ok {
219 for c := range t.conns {
224 if ra.String() == addr {
231 func (t *Torrent) unclosedConnsAsSlice() (ret []*connection) {
232 ret = make([]*connection, 0, len(t.conns))
233 for c := range t.conns {
234 if !c.closed.IsSet() {
241 func (t *Torrent) addPeer(p Peer) {
244 if len(t.peers) >= cl.config.TorrentPeersHighWater {
247 key := peersKey{string(p.IP), p.Port}
248 if _, ok := t.peers[key]; ok {
252 peersAddedBySource.Add(string(p.Source), 1)
257 func (t *Torrent) invalidateMetadata() {
258 for i := range t.metadataCompletedChunks {
259 t.metadataCompletedChunks[i] = false
264 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
268 if index >= len(t.metadataCompletedChunks) {
269 log.Printf("%s: ignoring metadata piece %d", t, index)
272 copy(t.metadataBytes[(1<<14)*index:], data)
273 t.metadataCompletedChunks[index] = true
276 func (t *Torrent) metadataPieceCount() int {
277 return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
280 func (t *Torrent) haveMetadataPiece(piece int) bool {
282 return (1<<14)*piece < len(t.metadataBytes)
284 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
288 func (t *Torrent) metadataSizeKnown() bool {
289 return t.metadataBytes != nil
292 func (t *Torrent) metadataSize() int {
293 return len(t.metadataBytes)
296 func infoPieceHashes(info *metainfo.Info) (ret []string) {
297 for i := 0; i < len(info.Pieces); i += sha1.Size {
298 ret = append(ret, string(info.Pieces[i:i+sha1.Size]))
303 func (t *Torrent) makePieces() {
304 hashes := infoPieceHashes(t.info)
305 t.pieces = make([]Piece, len(hashes))
306 for i, hash := range hashes {
307 piece := &t.pieces[i]
310 piece.noPendingWrites.L = &piece.pendingWritesMutex
311 missinggo.CopyExact(piece.hash[:], hash)
313 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
314 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
315 piece.files = files[beginFile:endFile]
319 // Returns the index of the first file containing the piece. files must be
320 // ordered by offset.
321 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
322 for i, f := range files {
323 if f.offset+f.length > pieceOffset {
330 // Returns the index after the last file containing the piece. files must be
331 // ordered by offset.
332 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
333 for i, f := range files {
334 if f.offset+f.length >= pieceEndOffset {
341 func (t *Torrent) cacheLength() {
343 for _, f := range t.info.UpvertedFiles() {
349 func (t *Torrent) setInfo(info *metainfo.Info) error {
350 if err := validateInfo(info); err != nil {
351 return fmt.Errorf("bad info: %s", err)
353 if t.storageOpener != nil {
355 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
357 return fmt.Errorf("error opening torrent storage: %s", err)
361 t.displayName = "" // Save a few bytes lol.
368 func (t *Torrent) onSetInfo() {
369 for conn := range t.conns {
370 if err := conn.setNumPieces(t.numPieces()); err != nil {
371 log.Printf("closing connection: %s", err)
375 for i := range t.pieces {
376 t.updatePieceCompletion(i)
378 if !p.storageCompletionOk {
379 // log.Printf("piece %s completion unknown, queueing check", p)
383 t.cl.event.Broadcast()
385 t.updateWantPeersEvent()
388 // Called when metadata for a torrent becomes available.
389 func (t *Torrent) setInfoBytes(b []byte) error {
390 if metainfo.HashBytes(b) != t.infoHash {
391 return errors.New("info bytes have wrong hash")
393 var info metainfo.Info
394 if err := bencode.Unmarshal(b, &info); err != nil {
395 return fmt.Errorf("error unmarshalling info bytes: %s", err)
397 if err := t.setInfo(&info); err != nil {
401 t.metadataCompletedChunks = nil
406 func (t *Torrent) haveAllMetadataPieces() bool {
410 if t.metadataCompletedChunks == nil {
413 for _, have := range t.metadataCompletedChunks {
421 // TODO: Propagate errors to disconnect peer.
422 func (t *Torrent) setMetadataSize(bytes int64) (err error) {
424 // We already know the correct metadata size.
427 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
428 return errors.New("bad size")
430 if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
433 t.metadataBytes = make([]byte, bytes)
434 t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
435 t.metadataChanged.Broadcast()
436 for c := range t.conns {
437 c.requestPendingMetadata()
442 // The current working name for the torrent. Either the name in the info dict,
443 // or a display name given such as by the dn value in a magnet link, or "".
444 func (t *Torrent) name() string {
451 func (t *Torrent) pieceState(index int) (ret PieceState) {
452 p := &t.pieces[index]
453 ret.Priority = t.piecePriority(index)
454 ret.Completion = p.completion()
455 if p.queuedForHash() || p.hashing {
458 if !ret.Complete && t.piecePartiallyDownloaded(index) {
464 func (t *Torrent) metadataPieceSize(piece int) int {
465 return metadataPieceSize(len(t.metadataBytes), piece)
468 func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
474 d["total_size"] = len(t.metadataBytes)
476 p, err := bencode.Marshal(d)
482 ExtendedID: c.PeerExtensionIDs["ut_metadata"],
483 ExtendedPayload: append(p, data...),
487 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
488 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
489 ret = append(ret, PieceStateRun{
490 PieceState: el.(PieceState),
494 for index := range t.pieces {
495 rle.Append(t.pieceState(index), 1)
501 // Produces a small string representing a PieceStateRun.
502 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
503 ret = fmt.Sprintf("%d", psr.Length)
504 ret += func() string {
505 switch psr.Priority {
506 case PiecePriorityNext:
508 case PiecePriorityNormal:
510 case PiecePriorityReadahead:
512 case PiecePriorityNow:
514 case PiecePriorityHigh:
535 func (t *Torrent) writeStatus(w io.Writer) {
536 fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
537 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
539 fmt.Fprintf(w, "Metadata have: ")
540 for _, h := range t.metadataCompletedChunks {
541 fmt.Fprintf(w, "%c", func() rune {
551 fmt.Fprintf(w, "Piece length: %s\n", func() string {
553 return fmt.Sprint(t.usualPieceSize())
559 fmt.Fprintf(w, "Num Pieces: %d\n", t.numPieces())
560 fmt.Fprint(w, "Piece States:")
561 for _, psr := range t.pieceStateRuns() {
563 w.Write([]byte(pieceStateRunStatusChars(psr)))
567 fmt.Fprintf(w, "Reader Pieces:")
568 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
569 fmt.Fprintf(w, " %d:%d", begin, end)
574 fmt.Fprintf(w, "Trackers:\n")
576 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
577 fmt.Fprintf(tw, " URL\tNext announce\tLast announce\n")
578 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
580 }).([]*trackerScraper) {
581 fmt.Fprintf(tw, " %s\n", ta.statusLine())
586 fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
588 spew.NewDefaultConfig()
589 spew.Fdump(w, t.statsLocked())
591 conns := t.connsAsSlice()
592 slices.Sort(conns, worseConn)
593 for i, c := range conns {
594 fmt.Fprintf(w, "%2d. ", i+1)
599 func (t *Torrent) haveInfo() bool {
603 // Returns a run-time generated MetaInfo that includes the info bytes and
604 // announce-list as currently known to the client.
605 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
606 return metainfo.MetaInfo{
607 CreationDate: time.Now().Unix(),
608 Comment: "dynamic metainfo from client",
609 CreatedBy: "go.torrent",
610 AnnounceList: t.metainfo.UpvertedAnnounceList(),
611 InfoBytes: func() []byte {
613 return t.metadataBytes
621 func (t *Torrent) BytesMissing() int64 {
623 defer t.mu().RUnlock()
624 return t.bytesMissingLocked()
627 func (t *Torrent) bytesMissingLocked() int64 {
631 func (t *Torrent) bytesLeft() (left int64) {
632 bitmap.Flip(t.completedPieces, 0, t.numPieces()).IterTyped(func(piece int) bool {
633 p := &t.pieces[piece]
634 left += int64(p.length() - p.numDirtyBytes())
640 // Bytes left to give in tracker announces.
641 func (t *Torrent) bytesLeftAnnounce() uint64 {
643 return uint64(t.bytesLeft())
645 return math.MaxUint64
649 func (t *Torrent) piecePartiallyDownloaded(piece int) bool {
650 if t.pieceComplete(piece) {
653 if t.pieceAllDirty(piece) {
656 return t.pieces[piece].hasDirtyChunks()
659 func (t *Torrent) usualPieceSize() int {
660 return int(t.info.PieceLength)
663 func (t *Torrent) numPieces() int {
664 return t.info.NumPieces()
667 func (t *Torrent) numPiecesCompleted() (num int) {
668 return t.completedPieces.Len()
671 func (t *Torrent) close() (err error) {
673 if t.storage != nil {
676 t.storageLock.Unlock()
678 for conn := range t.conns {
681 t.cl.event.Broadcast()
682 t.pieceStateChanges.Close()
683 t.updateWantPeersEvent()
687 func (t *Torrent) requestOffset(r request) int64 {
688 return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
691 // Return the request that would include the given offset into the torrent
692 // data. Returns !ok if there is no such request.
693 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
694 return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
697 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
698 tr := perf.NewTimer()
700 n, err := t.pieces[piece].Storage().WriteAt(data, begin)
701 if err == nil && n != len(data) {
702 err = io.ErrShortWrite
705 tr.Mark("write chunk")
710 func (t *Torrent) bitfield() (bf []bool) {
711 bf = make([]bool, t.numPieces())
712 t.completedPieces.IterTyped(func(piece int) (again bool) {
719 func (t *Torrent) pieceNumChunks(piece int) int {
720 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
723 func (t *Torrent) pendAllChunkSpecs(pieceIndex int) {
724 t.pieces[pieceIndex].dirtyChunks.Clear()
732 // Peer is known to support encryption.
733 SupportsEncryption bool
736 func (t *Torrent) pieceLength(piece int) pp.Integer {
737 if piece == t.numPieces()-1 {
738 ret := pp.Integer(*t.length % t.info.PieceLength)
743 return pp.Integer(t.info.PieceLength)
746 func (t *Torrent) hashPiece(piece int) (ret metainfo.Hash) {
747 hash := pieceHash.New()
748 p := &t.pieces[piece]
749 p.waitNoPendingWrites()
750 ip := t.info.Piece(piece)
752 n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
754 missinggo.CopyExact(&ret, hash.Sum(nil))
757 if err != io.ErrUnexpectedEOF && !os.IsNotExist(err) {
758 log.Printf("unexpected error hashing piece with %T: %s", t.storage.TorrentImpl, err)
763 func (t *Torrent) haveAnyPieces() bool {
764 for i := range t.pieces {
765 if t.pieceComplete(i) {
772 func (t *Torrent) havePiece(index int) bool {
773 return t.haveInfo() && t.pieceComplete(index)
776 func (t *Torrent) haveChunk(r request) (ret bool) {
778 // log.Println("have chunk", r, ret)
783 if t.pieceComplete(int(r.Index)) {
786 p := &t.pieces[r.Index]
787 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
790 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
791 return int(cs.Begin / chunkSize)
794 func (t *Torrent) wantPiece(r request) bool {
795 if !t.wantPieceIndex(int(r.Index)) {
798 if t.pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
801 // TODO: What about pieces that were wanted, but aren't now, and aren't
802 // completed either? That used to be done here.
806 func (t *Torrent) wantPieceIndex(index int) bool {
810 if index < 0 || index >= t.numPieces() {
813 p := &t.pieces[index]
814 if p.queuedForHash() {
820 if t.pieceComplete(index) {
823 if t.pendingPieces.Contains(index) {
826 // log.Printf("piece %d not pending", index)
827 return !t.forReaderOffsetPieces(func(begin, end int) bool {
828 return index < begin || index >= end
832 // The worst connection is one that hasn't been sent, or sent anything useful
833 // for the longest. A bad connection is one that usually sends us unwanted
834 // pieces, or has been in worser half of the established connections for more
836 func (t *Torrent) worstBadConn() *connection {
837 wcs := worseConnSlice{t.unclosedConnsAsSlice()}
840 c := heap.Pop(&wcs).(*connection)
841 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
844 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
845 // Give connections 1 minute to prove themselves.
846 if time.Since(c.completedHandshake) > time.Minute {
854 type PieceStateChange struct {
859 func (t *Torrent) publishPieceChange(piece int) {
860 cur := t.pieceState(piece)
861 p := &t.pieces[piece]
862 if cur != p.publicPieceState {
863 p.publicPieceState = cur
864 t.pieceStateChanges.Publish(PieceStateChange{
871 func (t *Torrent) pieceNumPendingChunks(piece int) int {
872 if t.pieceComplete(piece) {
875 return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
878 func (t *Torrent) pieceAllDirty(piece int) bool {
879 return t.pieces[piece].dirtyChunks.Len() == t.pieceNumChunks(piece)
882 func (t *Torrent) readersChanged() {
883 t.updateReaderPieces()
884 t.updateAllPiecePriorities()
887 func (t *Torrent) updateReaderPieces() {
888 t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
891 func (t *Torrent) readerPosChanged(from, to pieceRange) {
895 t.updateReaderPieces()
896 // Order the ranges, high and low.
898 if l.begin > h.begin {
902 // Two distinct ranges.
903 t.updatePiecePriorities(l.begin, l.end)
904 t.updatePiecePriorities(h.begin, h.end)
911 t.updatePiecePriorities(l.begin, end)
915 func (t *Torrent) maybeNewConns() {
916 // Tickle the accept routine.
917 t.cl.event.Broadcast()
921 func (t *Torrent) piecePriorityChanged(piece int) {
922 // log.Printf("piece %d priority changed", piece)
923 for c := range t.conns {
924 if c.updatePiecePriority(piece) {
925 // log.Print("conn piece priority changed")
930 t.publishPieceChange(piece)
933 func (t *Torrent) updatePiecePriority(piece int) {
934 p := &t.pieces[piece]
935 newPrio := p.uncachedPriority()
936 // log.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
937 if newPrio == PiecePriorityNone {
938 if !t.pendingPieces.Remove(piece) {
942 if !t.pendingPieces.Set(piece, newPrio.BitmapPriority()) {
946 t.piecePriorityChanged(piece)
949 func (t *Torrent) updateAllPiecePriorities() {
950 t.updatePiecePriorities(0, len(t.pieces))
953 // Update all piece priorities in one hit. This function should have the same
954 // output as updatePiecePriority, but across all pieces.
955 func (t *Torrent) updatePiecePriorities(begin, end int) {
956 for i := begin; i < end; i++ {
957 t.updatePiecePriority(i)
961 // Returns the range of pieces [begin, end) that contains the extent of bytes.
962 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end int) {
963 if off >= *t.length {
973 begin = int(off / t.info.PieceLength)
974 end = int((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
975 if end > t.info.NumPieces() {
976 end = t.info.NumPieces()
981 // Returns true if all iterations complete without breaking. Returns the read
982 // regions for all readers. The reader regions should not be merged as some
983 // callers depend on this method to enumerate readers.
984 func (t *Torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
985 for r := range t.readers {
987 if p.begin >= p.end {
990 if !f(p.begin, p.end) {
997 func (t *Torrent) piecePriority(piece int) piecePriority {
998 prio, ok := t.pendingPieces.GetPriority(piece)
1000 return PiecePriorityNone
1002 return piecePriority(-prio)
1005 func (t *Torrent) pendRequest(req request) {
1006 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1007 t.pieces[req.Index].pendChunkIndex(ci)
1010 func (t *Torrent) pieceCompletionChanged(piece int) {
1011 log.Call().Add("piece", piece).AddValue(debugLogValue).Log(t.logger)
1012 t.cl.event.Broadcast()
1013 if t.pieceComplete(piece) {
1014 t.onPieceCompleted(piece)
1016 t.onIncompletePiece(piece)
1018 t.updatePiecePriority(piece)
1021 func (t *Torrent) openNewConns() {
1022 t.cl.openNewConns(t)
1025 func (t *Torrent) getConnPieceInclination() []int {
1026 _ret := t.connPieceInclinationPool.Get()
1028 pieceInclinationsNew.Add(1)
1029 return rand.Perm(t.numPieces())
1031 pieceInclinationsReused.Add(1)
1032 return *_ret.(*[]int)
1035 func (t *Torrent) putPieceInclination(pi []int) {
1036 t.connPieceInclinationPool.Put(&pi)
1037 pieceInclinationsPut.Add(1)
1040 func (t *Torrent) updatePieceCompletion(piece int) {
1041 pcu := t.pieceCompleteUncached(piece)
1042 p := &t.pieces[piece]
1043 changed := t.completedPieces.Get(piece) != pcu.Complete || p.storageCompletionOk != pcu.Ok
1044 log.Fmsg("piece %d completion: %v", piece, pcu.Ok).AddValue(debugLogValue).Log(t.logger)
1045 p.storageCompletionOk = pcu.Ok
1046 t.completedPieces.Set(piece, pcu.Complete)
1047 // log.Printf("piece %d uncached completion: %v", piece, pcu.Complete)
1048 // log.Printf("piece %d changed: %v", piece, changed)
1050 t.pieceCompletionChanged(piece)
1054 // Non-blocking read. Client lock is not required.
1055 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1056 p := &t.pieces[off/t.info.PieceLength]
1057 p.waitNoPendingWrites()
1058 return p.Storage().ReadAt(b, off-p.Info().Offset())
1061 func (t *Torrent) updateAllPieceCompletions() {
1062 for i := range iter.N(t.numPieces()) {
1063 t.updatePieceCompletion(i)
1067 // Returns an error if the metadata was completed, but couldn't be set for
1068 // some reason. Blame it on the last peer to contribute.
1069 func (t *Torrent) maybeCompleteMetadata() error {
1074 if !t.haveAllMetadataPieces() {
1075 // Don't have enough metadata pieces.
1078 err := t.setInfoBytes(t.metadataBytes)
1080 t.invalidateMetadata()
1081 return fmt.Errorf("error setting info bytes: %s", err)
1083 if t.cl.config.Debug {
1084 log.Printf("%s: got metadata from peers", t)
1089 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1090 t.forReaderOffsetPieces(func(begin, end int) bool {
1091 ret.AddRange(begin, end)
1097 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1098 t.forReaderOffsetPieces(func(begin, end int) bool {
1101 readahead.AddRange(begin+1, end)
1108 func (t *Torrent) needData() bool {
1109 if t.closed.IsSet() {
1115 return t.pendingPieces.Len() != 0
1118 func appendMissingStrings(old, new []string) (ret []string) {
1121 for _, n := range new {
1122 for _, o := range old {
1127 ret = append(ret, n)
1132 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1134 for minNumTiers > len(ret) {
1135 ret = append(ret, nil)
1140 func (t *Torrent) addTrackers(announceList [][]string) {
1141 fullAnnounceList := &t.metainfo.AnnounceList
1142 t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1143 for tierIndex, trackerURLs := range announceList {
1144 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1146 t.startMissingTrackerScrapers()
1147 t.updateWantPeersEvent()
1150 // Don't call this before the info is available.
1151 func (t *Torrent) bytesCompleted() int64 {
1155 return t.info.TotalLength() - t.bytesLeft()
1158 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1160 defer t.cl.mu.Unlock()
1161 return t.setInfoBytes(b)
1164 // Returns true if connection is removed from torrent.Conns.
1165 func (t *Torrent) deleteConnection(c *connection) (ret bool) {
1171 func (t *Torrent) dropConnection(c *connection) {
1172 t.cl.event.Broadcast()
1174 if t.deleteConnection(c) {
1179 func (t *Torrent) wantPeers() bool {
1180 if t.closed.IsSet() {
1183 if len(t.peers) > t.cl.config.TorrentPeersLowWater {
1186 return t.needData() || t.seeding()
1189 func (t *Torrent) updateWantPeersEvent() {
1191 t.wantPeersEvent.Set()
1193 t.wantPeersEvent.Clear()
1197 // Returns whether the client should make effort to seed the torrent.
1198 func (t *Torrent) seeding() bool {
1200 if t.closed.IsSet() {
1203 if cl.config.NoUpload {
1206 if !cl.config.Seed {
1209 if cl.config.DisableAggressiveUpload && t.needData() {
1215 func (t *Torrent) startScrapingTracker(url string) {
1219 if _, ok := t.trackerAnnouncers[url]; ok {
1222 newAnnouncer := &trackerScraper{
1226 if t.trackerAnnouncers == nil {
1227 t.trackerAnnouncers = make(map[string]*trackerScraper)
1229 t.trackerAnnouncers[url] = newAnnouncer
1230 go newAnnouncer.Run()
1233 // Adds and starts tracker scrapers for tracker URLs that aren't already
1235 func (t *Torrent) startMissingTrackerScrapers() {
1236 if t.cl.config.DisableTrackers {
1239 t.startScrapingTracker(t.metainfo.Announce)
1240 for _, tier := range t.metainfo.AnnounceList {
1241 for _, url := range tier {
1242 t.startScrapingTracker(url)
1247 // Returns an AnnounceRequest with fields filled out to defaults and current
1249 func (t *Torrent) announceRequest() tracker.AnnounceRequest {
1250 return tracker.AnnounceRequest{
1251 Event: tracker.None,
1253 Port: uint16(t.cl.incomingPeerPort()),
1254 PeerId: t.cl.peerID,
1255 InfoHash: t.infoHash,
1256 Left: t.bytesLeftAnnounce(),
1260 // Adds peers revealed in an announce until the announce ends, or we have
1262 func (t *Torrent) consumeDHTAnnounce(pvs <-chan dht.PeersValues) {
1264 // Count all the unique addresses we got during this announce.
1265 allAddrs := make(map[string]struct{})
1268 case v, ok := <-pvs:
1272 addPeers := make([]Peer, 0, len(v.Peers))
1273 for _, cp := range v.Peers {
1275 // Can't do anything with this.
1278 addPeers = append(addPeers, Peer{
1281 Source: peerSourceDHTGetPeers,
1283 key := (&net.UDPAddr{
1287 allAddrs[key] = struct{}{}
1290 t.addPeers(addPeers)
1291 numPeers := len(t.peers)
1293 if numPeers >= cl.config.TorrentPeersHighWater {
1296 case <-t.closed.LockedChan(&cl.mu):
1302 func (t *Torrent) announceDHT(impliedPort bool) (err error) {
1304 ps, err := cl.dHT.Announce(t.infoHash, cl.incomingPeerPort(), impliedPort)
1308 t.consumeDHTAnnounce(ps.Peers)
1313 func (t *Torrent) dhtAnnouncer() {
1317 case <-t.wantPeersEvent.LockedChan(&cl.mu):
1318 case <-t.closed.LockedChan(&cl.mu):
1321 err := t.announceDHT(true)
1324 defer cl.mu.Unlock()
1328 log.Printf("error announcing %q to DHT: %s", t, err)
1332 case <-t.closed.LockedChan(&cl.mu):
1334 case <-time.After(5 * time.Minute):
1339 func (t *Torrent) addPeers(peers []Peer) {
1340 for _, p := range peers {
1341 if t.cl.badPeerIPPort(p.IP, p.Port) {
1348 func (t *Torrent) Stats() TorrentStats {
1350 defer t.cl.mu.Unlock()
1351 return t.statsLocked()
1354 func (t *Torrent) statsLocked() TorrentStats {
1355 t.stats.ActivePeers = len(t.conns)
1356 t.stats.HalfOpenPeers = len(t.halfOpen)
1357 t.stats.PendingPeers = len(t.peers)
1358 t.stats.TotalPeers = t.numTotalPeers()
1359 t.stats.ConnectedSeeders = 0
1360 for c := range t.conns {
1361 if all, ok := c.peerHasAllPieces(); all && ok {
1362 t.stats.ConnectedSeeders++
1368 // The total number of peers in the torrent.
1369 func (t *Torrent) numTotalPeers() int {
1370 peers := make(map[string]struct{})
1371 for conn := range t.conns {
1372 ra := conn.conn.RemoteAddr()
1374 // It's been closed and doesn't support RemoteAddr.
1377 peers[ra.String()] = struct{}{}
1379 for addr := range t.halfOpen {
1380 peers[addr] = struct{}{}
1382 for _, peer := range t.peers {
1383 peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{}
1388 // Returns true if the connection is added.
1389 func (t *Torrent) addConnection(c *connection, outgoing bool) bool {
1390 if t.cl.closed.IsSet() {
1396 for c0 := range t.conns {
1397 if c.PeerID == c0.PeerID {
1398 // Already connected to a client with that ID.
1399 duplicateClientConns.Add(1)
1400 lower := string(t.cl.peerID[:]) < string(c.PeerID[:])
1401 // Retain the connection from initiated from lower peer ID to
1403 if outgoing == lower {
1404 // Close the other one.
1406 // TODO: Is it safe to delete from the map while we're
1407 // iterating over it?
1408 t.deleteConnection(c0)
1410 // Abandon this one.
1415 if len(t.conns) >= t.maxEstablishedConns {
1416 c := t.worstBadConn()
1420 if t.cl.config.Debug && missinggo.CryHeard() {
1421 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1424 t.deleteConnection(c)
1426 if len(t.conns) >= t.maxEstablishedConns {
1430 panic("connection already associated with a torrent")
1432 // Reconcile bytes transferred before connection was associated with a
1434 t.stats.wroteBytes(c.stats.BytesWritten)
1435 t.stats.readBytes(c.stats.BytesRead)
1437 t.conns[c] = struct{}{}
1441 func (t *Torrent) wantConns() bool {
1442 if !t.networkingEnabled {
1445 if t.closed.IsSet() {
1448 if !t.seeding() && !t.needData() {
1451 if len(t.conns) < t.maxEstablishedConns {
1454 return t.worstBadConn() != nil
1457 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1459 defer t.cl.mu.Unlock()
1460 oldMax = t.maxEstablishedConns
1461 t.maxEstablishedConns = max
1462 wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1463 for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1464 t.dropConnection(wcs.Pop().(*connection))
1470 func (t *Torrent) mu() missinggo.RWLocker {
1474 func (t *Torrent) pieceHashed(piece int, correct bool) {
1475 log.Fmsg("hashed piece %d", piece).Add("piece", piece).Add("passed", correct).AddValue(debugLogValue).Log(t.logger)
1476 if t.closed.IsSet() {
1479 p := &t.pieces[piece]
1480 touchers := t.reapPieceTouchers(piece)
1482 // Don't score the first time a piece is hashed, it could be an
1485 pieceHashedCorrect.Add(1)
1487 log.Printf("%s: piece %d (%s) failed hash: %d connections contributed", t, piece, p.hash, len(touchers))
1488 pieceHashedNotCorrect.Add(1)
1493 for _, c := range touchers {
1494 c.goodPiecesDirtied++
1496 err := p.Storage().MarkComplete()
1498 log.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1501 if len(touchers) != 0 {
1502 for _, c := range touchers {
1503 // Y u do dis peer?!
1504 c.badPiecesDirtied++
1506 slices.Sort(touchers, connLessTrusted)
1507 if t.cl.config.Debug {
1508 log.Printf("dropping first corresponding conn from trust: %v", func() (ret []int) {
1509 for _, c := range touchers {
1510 ret = append(ret, c.netGoodPiecesDirtied())
1516 t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1519 t.onIncompletePiece(piece)
1520 p.Storage().MarkNotComplete()
1522 t.updatePieceCompletion(piece)
1525 func (t *Torrent) cancelRequestsForPiece(piece int) {
1526 // TODO: Make faster
1527 for cn := range t.conns {
1532 func (t *Torrent) onPieceCompleted(piece int) {
1533 t.pendAllChunkSpecs(piece)
1534 t.cancelRequestsForPiece(piece)
1535 for conn := range t.conns {
1540 // Called when a piece is found to be not complete.
1541 func (t *Torrent) onIncompletePiece(piece int) {
1542 if t.pieceAllDirty(piece) {
1543 t.pendAllChunkSpecs(piece)
1545 if !t.wantPieceIndex(piece) {
1546 // log.Printf("piece %d incomplete and unwanted", piece)
1549 // We could drop any connections that we told we have a piece that we
1550 // don't here. But there's a test failure, and it seems clients don't care
1551 // if you request pieces that you already claim to have. Pruning bad
1552 // connections might just remove any connections that aren't treating us
1553 // favourably anyway.
1555 // for c := range t.conns {
1556 // if c.sentHave(piece) {
1560 for conn := range t.conns {
1561 if conn.PeerHasPiece(piece) {
1562 conn.updateRequests()
1567 func (t *Torrent) verifyPiece(piece int) {
1570 defer cl.mu.Unlock()
1571 p := &t.pieces[piece]
1574 cl.event.Broadcast()
1576 for p.hashing || t.storage == nil {
1579 if !p.t.piecesQueuedForHash.Remove(piece) {
1580 panic("piece was not queued")
1582 if t.closed.IsSet() || t.pieceComplete(piece) {
1583 t.updatePiecePriority(piece)
1587 t.publishPieceChange(piece)
1588 t.storageLock.RLock()
1590 sum := t.hashPiece(piece)
1591 t.storageLock.RUnlock()
1594 t.pieceHashed(piece, sum == p.hash)
1595 t.publishPieceChange(piece)
1598 // Return the connections that touched a piece, and clear the entry while
1600 func (t *Torrent) reapPieceTouchers(piece int) (ret []*connection) {
1601 for c := range t.conns {
1602 if _, ok := c.peerTouchedPieces[piece]; ok {
1603 ret = append(ret, c)
1604 delete(c.peerTouchedPieces, piece)
1610 func (t *Torrent) connsAsSlice() (ret []*connection) {
1611 for c := range t.conns {
1612 ret = append(ret, c)
1617 // Currently doesn't really queue, but should in the future.
1618 func (t *Torrent) queuePieceCheck(pieceIndex int) {
1619 piece := &t.pieces[pieceIndex]
1620 if piece.queuedForHash() {
1623 t.piecesQueuedForHash.Add(pieceIndex)
1624 t.publishPieceChange(pieceIndex)
1625 go t.verifyPiece(pieceIndex)
1628 func (t *Torrent) VerifyData() {
1629 for i := range iter.N(t.NumPieces()) {
1630 t.Piece(i).VerifyData()