13 "github.com/anacrolix/torrent/bencode"
14 "github.com/anacrolix/torrent/metainfo"
15 "github.com/bradfitz/iter"
17 "github.com/anacrolix/torrent/data"
18 pp "github.com/anacrolix/torrent/peer_protocol"
19 "github.com/anacrolix/torrent/tracker"
20 "github.com/anacrolix/torrent/util"
23 func (t *torrent) pieceNumPendingBytes(index int) (count pp.Integer) {
24 if t.pieceComplete(index) {
27 piece := t.Pieces[index]
28 if !piece.EverHashed {
29 return t.pieceLength(index)
31 pendingChunks := t.Pieces[index].PendingChunkSpecs
32 count = pp.Integer(len(pendingChunks)) * chunkSize
33 _lastChunkSpec := lastChunkSpec(t.pieceLength(index))
34 if _lastChunkSpec.Length != chunkSize {
35 if _, ok := pendingChunks[_lastChunkSpec]; ok {
36 count += _lastChunkSpec.Length - chunkSize
42 type peersKey struct {
47 // Data maintains per-piece persistent state.
48 type StatefulData interface {
50 // We believe the piece data will pass a hash check.
51 PieceCompleted(index int) error
52 // Returns true if the piece is complete.
53 PieceComplete(index int) bool
56 // Is not aware of Client. Maintains state of torrent for with-in a Client.
61 // Closed when no more network activity is desired. This includes
62 // announcing, and communicating with peers.
63 ceasingNetworking chan struct{}
67 // Chunks that are wanted before all others. This is for
68 // responsive/streaming readers that want to unblock ASAP.
69 urgent map[request]struct{}
70 // Total length of the torrent in bytes. Stored because it's not O(1) to
71 // get this from the info dict.
76 // The info dict. Nil if we don't have it.
78 // Active peer connections, running message stream loops.
80 // Set of addrs to which we're attempting to connect. Connections are
81 // half-open until all handshakes are completed.
82 HalfOpen map[string]struct{}
84 // Reserve of peers to connect to. A peer can be both here and in the
85 // active connections if were told about the peer after connecting with
86 // them. That encourages us to reconnect to peers that are well known.
87 Peers map[peersKey]Peer
90 // BEP 12 Multitracker Metadata Extension. The tracker.Client instances
91 // mirror their respective URLs from the announce-list metainfo key.
92 Trackers [][]tracker.Client
93 // Name used if the info name isn't available.
95 // The bencoded bytes of the info dict.
97 // Each element corresponds to the 16KiB metadata pieces. If true, we have
98 // received that piece.
101 // Closed when .Info is set.
102 gotMetainfo chan struct{}
103 GotMetainfo <-chan struct{}
105 pruneTimer *time.Timer
108 func (t *torrent) pieceComplete(piece int) bool {
109 // TODO: This is called when setting metadata, and before storage is
110 // assigned, which doesn't seem right.
111 return t.data != nil && t.data.PieceComplete(piece)
114 func (t *torrent) numConnsUnchoked() (num int) {
115 for _, c := range t.Conns {
123 // There's a connection to that address already.
124 func (t *torrent) addrActive(addr string) bool {
125 if _, ok := t.HalfOpen[addr]; ok {
128 for _, c := range t.Conns {
129 if c.remoteAddr().String() == addr {
136 func (t *torrent) worstConnsHeap() (wcs *worstConns) {
138 c: append([]*connection{}, t.Conns...),
145 func (t *torrent) ceaseNetworking() {
147 defer t.stateMu.Unlock()
149 case <-t.ceasingNetworking:
153 close(t.ceasingNetworking)
154 for _, c := range t.Conns {
157 if t.pruneTimer != nil {
162 func (t *torrent) addPeer(p Peer) {
163 t.Peers[peersKey{string(p.IP), p.Port}] = p
166 func (t *torrent) invalidateMetadata() {
172 func (t *torrent) saveMetadataPiece(index int, data []byte) {
176 if index >= len(t.metadataHave) {
177 log.Printf("%s: ignoring metadata piece %d", t, index)
180 copy(t.MetaData[(1<<14)*index:], data)
181 t.metadataHave[index] = true
184 func (t *torrent) metadataPieceCount() int {
185 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
188 func (t *torrent) haveMetadataPiece(piece int) bool {
190 return (1<<14)*piece < len(t.MetaData)
192 return piece < len(t.metadataHave) && t.metadataHave[piece]
196 func (t *torrent) metadataSizeKnown() bool {
197 return t.MetaData != nil
200 func (t *torrent) metadataSize() int {
201 return len(t.MetaData)
204 func infoPieceHashes(info *metainfo.Info) (ret []string) {
205 for i := 0; i < len(info.Pieces); i += 20 {
206 ret = append(ret, string(info.Pieces[i:i+20]))
211 // Called when metadata for a torrent becomes available.
212 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte, eventLocker sync.Locker) (err error) {
215 for _, f := range t.Info.UpvertedFiles() {
218 t.MetaData = infoBytes
220 for _, hash := range infoPieceHashes(md) {
222 piece.Event.L = eventLocker
223 util.CopyExact(piece.Hash[:], hash)
224 t.Pieces = append(t.Pieces, piece)
226 for _, conn := range t.Conns {
227 t.initRequestOrdering(conn)
228 if err := conn.setNumPieces(t.numPieces()); err != nil {
229 log.Printf("closing connection: %s", err)
236 func (t *torrent) setStorage(td data.Data) (err error) {
237 if c, ok := t.data.(io.Closer); ok {
240 if sd, ok := td.(StatefulData); ok {
243 t.data = &statelessDataWrapper{td, make([]bool, t.Info.NumPieces())}
248 func (t *torrent) haveAllMetadataPieces() bool {
252 if t.metadataHave == nil {
255 for _, have := range t.metadataHave {
263 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
265 // We already know the correct metadata size.
268 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
269 log.Printf("received bad metadata size: %d", bytes)
272 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
275 t.MetaData = make([]byte, bytes)
276 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
277 for _, c := range t.Conns {
278 cl.requestPendingMetadata(t, c)
283 // The current working name for the torrent. Either the name in the info dict,
284 // or a display name given such as by the dn value in a magnet link, or "".
285 func (t *torrent) Name() string {
289 if t.DisplayName != "" {
295 func (t *torrent) pieceStatusChar(index int) byte {
298 case t.pieceComplete(index):
300 case p.QueuedForHash:
306 case t.piecePartiallyDownloaded(index):
308 case piecePriorityNone:
309 return 'F' // Forgotten
315 case piecePriorityNone:
317 case piecePriorityNow:
319 case piecePriorityReadahead:
321 case piecePriorityNext:
329 func (t *torrent) metadataPieceSize(piece int) int {
330 return metadataPieceSize(len(t.MetaData), piece)
333 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
339 d["total_size"] = len(t.MetaData)
341 p, err := bencode.Marshal(d)
347 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
348 ExtendedPayload: append(p, data...),
352 type PieceStatusCharSequence struct {
353 Char byte // The state of this sequence of pieces.
354 Count int // How many consecutive pieces have this state.
357 // Returns the state of pieces of the torrent. They are grouped into runs of
358 // same state. The sum of the Counts of the sequences is the number of pieces
359 // in the torrent. See the function torrent.pieceStatusChar for the possible
361 func (t *torrent) PieceStatusCharSequences() []PieceStatusCharSequence {
363 defer t.stateMu.Unlock()
364 return t.pieceStatusCharSequences()
367 // Returns the length of sequences of identical piece status chars.
368 func (t *torrent) pieceStatusCharSequences() (ret []PieceStatusCharSequence) {
373 writeSequence := func() {
374 ret = append(ret, PieceStatusCharSequence{char, count})
376 if len(t.Pieces) != 0 {
377 char = t.pieceStatusChar(0)
379 for index := range t.Pieces {
380 char1 := t.pieceStatusChar(index)
395 func (t *torrent) writeStatus(w io.Writer) {
396 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
397 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
398 fmt.Fprintf(w, "Metadata have: ")
399 for _, h := range t.metadataHave {
400 fmt.Fprintf(w, "%c", func() rune {
409 fmt.Fprintf(w, "Piece length: %s\n", func() string {
411 return fmt.Sprint(t.usualPieceSize())
417 fmt.Fprint(w, "Pieces: ")
418 for _, seq := range t.pieceStatusCharSequences() {
419 fmt.Fprintf(w, "%d%c ", seq.Count, seq.Char)
423 fmt.Fprintf(w, "Urgent:")
424 for req := range t.urgent {
425 fmt.Fprintf(w, " %s", req)
428 fmt.Fprintf(w, "Trackers: ")
429 for _, tier := range t.Trackers {
430 for _, tr := range tier {
431 fmt.Fprintf(w, "%q ", tr.String())
435 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
436 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
437 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
438 sort.Sort(&worstConns{
442 for _, c := range t.Conns {
447 func (t *torrent) String() string {
450 s = fmt.Sprintf("%x", t.InfoHash)
455 func (t *torrent) haveInfo() bool {
459 // TODO: Include URIs that weren't converted to tracker clients.
460 func (t *torrent) announceList() (al [][]string) {
461 for _, tier := range t.Trackers {
463 for _, tr := range tier {
464 l = append(l, tr.URL())
471 // Returns a run-time generated MetaInfo that includes the info bytes and
472 // announce-list as currently known to the client.
473 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
474 if t.MetaData == nil {
475 panic("info bytes not set")
477 return &metainfo.MetaInfo{
478 Info: metainfo.InfoEx{
482 CreationDate: time.Now().Unix(),
483 Comment: "dynamic metainfo from client",
484 CreatedBy: "go.torrent",
485 AnnounceList: t.announceList(),
489 func (t *torrent) bytesLeft() (left int64) {
493 for i := 0; i < t.numPieces(); i++ {
494 left += int64(t.pieceNumPendingBytes(i))
499 func (t *torrent) piecePartiallyDownloaded(index int) bool {
500 return t.pieceNumPendingBytes(index) != t.pieceLength(index)
503 func numChunksForPiece(chunkSize int, pieceSize int) int {
504 return (pieceSize + chunkSize - 1) / chunkSize
507 func (t *torrent) usualPieceSize() int {
508 return int(t.Info.PieceLength)
511 func (t *torrent) lastPieceSize() int {
512 return int(t.pieceLength(t.numPieces() - 1))
515 func (t *torrent) numPieces() int {
516 return t.Info.NumPieces()
519 func (t *torrent) numPiecesCompleted() (num int) {
520 for i := range iter.N(t.Info.NumPieces()) {
521 if t.pieceComplete(i) {
528 func (t *torrent) Length() int64 {
532 func (t *torrent) isClosed() bool {
541 func (t *torrent) close() (err error) {
547 if c, ok := t.data.(io.Closer); ok {
550 for _, conn := range t.Conns {
556 func (t *torrent) requestOffset(r request) int64 {
557 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
560 // Return the request that would include the given offset into the torrent
561 // data. Returns !ok if there is no such request.
562 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
563 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, chunkSize, off)
566 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
567 _, err = t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
571 func (t *torrent) bitfield() (bf []bool) {
572 for _, p := range t.Pieces {
573 // TODO: Check this logic.
574 bf = append(bf, p.EverHashed && len(p.PendingChunkSpecs) == 0)
579 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
580 css = make([]chunkSpec, 0, (t.pieceLength(piece)+chunkSize-1)/chunkSize)
582 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
584 if cs.Length > chunkSize {
585 cs.Length = chunkSize
587 css = append(css, cs)
588 cs.Begin += cs.Length
593 func (t *torrent) pendAllChunkSpecs(index int) {
594 piece := t.Pieces[index]
595 if piece.PendingChunkSpecs == nil {
596 piece.PendingChunkSpecs = make(
597 map[chunkSpec]struct{},
598 (t.pieceLength(index)+chunkSize-1)/chunkSize)
600 pcss := piece.PendingChunkSpecs
601 for _, cs := range t.pieceChunks(int(index)) {
602 pcss[cs] = struct{}{}
612 // Peer is known to support encryption.
613 SupportsEncryption bool
616 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
617 if int(piece) == t.numPieces()-1 {
618 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
621 len_ = pp.Integer(t.Info.PieceLength)
626 func (t *torrent) hashPiece(piece pp.Integer) (ps pieceSum) {
627 hash := pieceHash.New()
628 t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, t.Info.PieceLength)
629 util.CopyExact(ps[:], hash.Sum(nil))
633 func (t *torrent) haveAllPieces() bool {
637 for i := range t.Pieces {
638 if !t.pieceComplete(i) {
645 func (me *torrent) haveAnyPieces() bool {
646 for i := range me.Pieces {
647 if me.pieceComplete(i) {
654 func (t *torrent) havePiece(index int) bool {
655 return t.haveInfo() && t.pieceComplete(index)
658 func (t *torrent) haveChunk(r request) bool {
662 piece := t.Pieces[r.Index]
663 _, ok := piece.PendingChunkSpecs[r.chunkSpec]
664 // log.Println("have chunk", r, !ok)
668 func (t *torrent) wantChunk(r request) bool {
669 if !t.wantPiece(int(r.Index)) {
672 _, ok := t.Pieces[r.Index].PendingChunkSpecs[r.chunkSpec]
680 func (t *torrent) urgentChunkInPiece(piece int) bool {
681 for req := range t.urgent {
682 if int(req.Index) == piece {
689 func (t *torrent) wantPiece(index int) bool {
700 if p.Priority == piecePriorityNone {
701 if !t.urgentChunkInPiece(index) {
705 // Put piece complete check last, since it's the slowest as it can involve
706 // calling out into external data stores.
707 return !t.pieceComplete(index)
710 func (t *torrent) connHasWantedPieces(c *connection) bool {
711 return c.pieceRequestOrder != nil && c.pieceRequestOrder.First() != nil
714 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
715 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
716 pieces = append(pieces, int(i))