13 "github.com/bradfitz/iter"
15 "github.com/anacrolix/torrent/bencode"
16 "github.com/anacrolix/torrent/data"
17 "github.com/anacrolix/torrent/metainfo"
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 (yet).
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{}
104 pruneTimer *time.Timer
107 func (t *torrent) pieceComplete(piece int) bool {
108 // TODO: This is called when setting metadata, and before storage is
109 // assigned, which doesn't seem right.
110 return t.data != nil && t.data.PieceComplete(piece)
113 func (t *torrent) numConnsUnchoked() (num int) {
114 for _, c := range t.Conns {
122 // There's a connection to that address already.
123 func (t *torrent) addrActive(addr string) bool {
124 if _, ok := t.HalfOpen[addr]; ok {
127 for _, c := range t.Conns {
128 if c.remoteAddr().String() == addr {
135 func (t *torrent) worstConnsHeap() (wcs *worstConns) {
137 c: append([]*connection{}, t.Conns...),
144 func (t *torrent) ceaseNetworking() {
146 defer t.stateMu.Unlock()
148 case <-t.ceasingNetworking:
152 close(t.ceasingNetworking)
153 for _, c := range t.Conns {
156 if t.pruneTimer != nil {
161 func (t *torrent) addPeer(p Peer) {
162 t.Peers[peersKey{string(p.IP), p.Port}] = p
165 func (t *torrent) invalidateMetadata() {
171 func (t *torrent) saveMetadataPiece(index int, data []byte) {
175 if index >= len(t.metadataHave) {
176 log.Printf("%s: ignoring metadata piece %d", t, index)
179 copy(t.MetaData[(1<<14)*index:], data)
180 t.metadataHave[index] = true
183 func (t *torrent) metadataPieceCount() int {
184 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
187 func (t *torrent) haveMetadataPiece(piece int) bool {
189 return (1<<14)*piece < len(t.MetaData)
191 return piece < len(t.metadataHave) && t.metadataHave[piece]
195 func (t *torrent) metadataSizeKnown() bool {
196 return t.MetaData != nil
199 func (t *torrent) metadataSize() int {
200 return len(t.MetaData)
203 func infoPieceHashes(info *metainfo.Info) (ret []string) {
204 for i := 0; i < len(info.Pieces); i += 20 {
205 ret = append(ret, string(info.Pieces[i:i+20]))
210 // Called when metadata for a torrent becomes available.
211 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte, eventLocker sync.Locker) (err error) {
214 for _, f := range t.Info.UpvertedFiles() {
217 t.MetaData = infoBytes
219 for _, hash := range infoPieceHashes(md) {
221 piece.Event.L = eventLocker
222 util.CopyExact(piece.Hash[:], hash)
223 t.Pieces = append(t.Pieces, piece)
225 for _, conn := range t.Conns {
226 t.initRequestOrdering(conn)
227 if err := conn.setNumPieces(t.numPieces()); err != nil {
228 log.Printf("closing connection: %s", err)
235 func (t *torrent) setStorage(td data.Data) (err error) {
236 if c, ok := t.data.(io.Closer); ok {
239 if sd, ok := td.(StatefulData); ok {
242 t.data = &statelessDataWrapper{td, make([]bool, t.Info.NumPieces())}
247 func (t *torrent) haveAllMetadataPieces() bool {
251 if t.metadataHave == nil {
254 for _, have := range t.metadataHave {
262 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
264 // We already know the correct metadata size.
267 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
268 log.Printf("received bad metadata size: %d", bytes)
271 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
274 t.MetaData = make([]byte, bytes)
275 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
276 for _, c := range t.Conns {
277 cl.requestPendingMetadata(t, c)
282 // The current working name for the torrent. Either the name in the info dict,
283 // or a display name given such as by the dn value in a magnet link, or "".
284 func (t *torrent) Name() string {
288 if t.DisplayName != "" {
294 func (t *torrent) pieceStatusChar(index int) byte {
297 case t.pieceComplete(index):
299 case p.QueuedForHash:
305 case t.piecePartiallyDownloaded(index):
307 case piecePriorityNone:
308 return 'F' // Forgotten
314 case piecePriorityNone:
316 case piecePriorityNow:
318 case piecePriorityReadahead:
320 case piecePriorityNext:
328 func (t *torrent) metadataPieceSize(piece int) int {
329 return metadataPieceSize(len(t.MetaData), piece)
332 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
338 d["total_size"] = len(t.MetaData)
340 p, err := bencode.Marshal(d)
346 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
347 ExtendedPayload: append(p, data...),
351 type PieceStatusCharSequence struct {
352 Char byte // The state of this sequence of pieces.
353 Count int // How many consecutive pieces have this state.
356 // Returns the state of pieces of the torrent. They are grouped into runs of
357 // same state. The sum of the Counts of the sequences is the number of pieces
358 // in the torrent. See the function torrent.pieceStatusChar for the possible
360 func (t *torrent) PieceStatusCharSequences() []PieceStatusCharSequence {
362 defer t.stateMu.Unlock()
363 return t.pieceStatusCharSequences()
366 // Returns the length of sequences of identical piece status chars.
367 func (t *torrent) pieceStatusCharSequences() (ret []PieceStatusCharSequence) {
372 writeSequence := func() {
373 ret = append(ret, PieceStatusCharSequence{char, count})
375 if len(t.Pieces) != 0 {
376 char = t.pieceStatusChar(0)
378 for index := range t.Pieces {
379 char1 := t.pieceStatusChar(index)
394 func (t *torrent) writeStatus(w io.Writer) {
395 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
396 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
397 fmt.Fprintf(w, "Metadata have: ")
398 for _, h := range t.metadataHave {
399 fmt.Fprintf(w, "%c", func() rune {
408 fmt.Fprintf(w, "Piece length: %s\n", func() string {
410 return fmt.Sprint(t.usualPieceSize())
416 fmt.Fprint(w, "Pieces: ")
417 for _, seq := range t.pieceStatusCharSequences() {
418 fmt.Fprintf(w, "%d%c ", seq.Count, seq.Char)
422 fmt.Fprintf(w, "Urgent:")
423 for req := range t.urgent {
424 fmt.Fprintf(w, " %s", req)
427 fmt.Fprintf(w, "Trackers: ")
428 for _, tier := range t.Trackers {
429 for _, tr := range tier {
430 fmt.Fprintf(w, "%q ", tr.String())
434 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
435 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
436 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
437 sort.Sort(&worstConns{
441 for _, c := range t.Conns {
446 func (t *torrent) String() string {
449 s = fmt.Sprintf("%x", t.InfoHash)
454 func (t *torrent) haveInfo() bool {
458 // TODO: Include URIs that weren't converted to tracker clients.
459 func (t *torrent) announceList() (al [][]string) {
460 for _, tier := range t.Trackers {
462 for _, tr := range tier {
463 l = append(l, tr.URL())
470 // Returns a run-time generated MetaInfo that includes the info bytes and
471 // announce-list as currently known to the client.
472 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
473 if t.MetaData == nil {
474 panic("info bytes not set")
476 return &metainfo.MetaInfo{
477 Info: metainfo.InfoEx{
481 CreationDate: time.Now().Unix(),
482 Comment: "dynamic metainfo from client",
483 CreatedBy: "go.torrent",
484 AnnounceList: t.announceList(),
488 func (t *torrent) bytesLeft() (left int64) {
492 for i := 0; i < t.numPieces(); i++ {
493 left += int64(t.pieceNumPendingBytes(i))
498 func (t *torrent) piecePartiallyDownloaded(index int) bool {
499 return t.pieceNumPendingBytes(index) != t.pieceLength(index)
502 func numChunksForPiece(chunkSize int, pieceSize int) int {
503 return (pieceSize + chunkSize - 1) / chunkSize
506 func (t *torrent) usualPieceSize() int {
507 return int(t.Info.PieceLength)
510 func (t *torrent) lastPieceSize() int {
511 return int(t.pieceLength(t.numPieces() - 1))
514 func (t *torrent) numPieces() int {
515 return t.Info.NumPieces()
518 func (t *torrent) numPiecesCompleted() (num int) {
519 for i := range iter.N(t.Info.NumPieces()) {
520 if t.pieceComplete(i) {
527 func (t *torrent) Length() int64 {
531 func (t *torrent) isClosed() bool {
540 func (t *torrent) close() (err error) {
546 if c, ok := t.data.(io.Closer); ok {
549 for _, conn := range t.Conns {
555 func (t *torrent) requestOffset(r request) int64 {
556 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
559 // Return the request that would include the given offset into the torrent
560 // data. Returns !ok if there is no such request.
561 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
562 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, chunkSize, off)
565 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
566 _, err = t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
570 func (t *torrent) bitfield() (bf []bool) {
571 for _, p := range t.Pieces {
572 // TODO: Check this logic.
573 bf = append(bf, p.EverHashed && len(p.PendingChunkSpecs) == 0)
578 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
579 css = make([]chunkSpec, 0, (t.pieceLength(piece)+chunkSize-1)/chunkSize)
581 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
583 if cs.Length > chunkSize {
584 cs.Length = chunkSize
586 css = append(css, cs)
587 cs.Begin += cs.Length
592 func (t *torrent) pendAllChunkSpecs(index int) {
593 piece := t.Pieces[index]
594 if piece.PendingChunkSpecs == nil {
595 piece.PendingChunkSpecs = make(
596 map[chunkSpec]struct{},
597 (t.pieceLength(index)+chunkSize-1)/chunkSize)
599 pcss := piece.PendingChunkSpecs
600 for _, cs := range t.pieceChunks(int(index)) {
601 pcss[cs] = struct{}{}
611 // Peer is known to support encryption.
612 SupportsEncryption bool
615 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
616 if int(piece) == t.numPieces()-1 {
617 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
620 len_ = pp.Integer(t.Info.PieceLength)
625 func (t *torrent) hashPiece(piece pp.Integer) (ps pieceSum) {
626 hash := pieceHash.New()
627 t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, t.Info.PieceLength)
628 util.CopyExact(ps[:], hash.Sum(nil))
632 func (t *torrent) haveAllPieces() bool {
636 for i := range t.Pieces {
637 if !t.pieceComplete(i) {
644 func (me *torrent) haveAnyPieces() bool {
645 for i := range me.Pieces {
646 if me.pieceComplete(i) {
653 func (t *torrent) havePiece(index int) bool {
654 return t.haveInfo() && t.pieceComplete(index)
657 func (t *torrent) haveChunk(r request) bool {
661 piece := t.Pieces[r.Index]
662 _, ok := piece.PendingChunkSpecs[r.chunkSpec]
663 // log.Println("have chunk", r, !ok)
667 func (t *torrent) wantChunk(r request) bool {
668 if !t.wantPiece(int(r.Index)) {
671 _, ok := t.Pieces[r.Index].PendingChunkSpecs[r.chunkSpec]
679 func (t *torrent) urgentChunkInPiece(piece int) bool {
680 for req := range t.urgent {
681 if int(req.Index) == piece {
688 func (t *torrent) wantPiece(index int) bool {
699 if p.Priority == piecePriorityNone {
700 if !t.urgentChunkInPiece(index) {
704 // Put piece complete check last, since it's the slowest as it can involve
705 // calling out into external data stores.
706 return !t.pieceComplete(index)
709 func (t *torrent) connHasWantedPieces(c *connection) bool {
710 return c.pieceRequestOrder != nil && c.pieceRequestOrder.First() != nil
713 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
714 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
715 pieces = append(pieces, int(i))