15 "github.com/bradfitz/iter"
17 "bitbucket.org/anacrolix/go.torrent/data"
18 pp "bitbucket.org/anacrolix/go.torrent/peer_protocol"
19 "bitbucket.org/anacrolix/go.torrent/tracker"
20 "bitbucket.org/anacrolix/go.torrent/util"
21 "github.com/anacrolix/libtorgo/bencode"
22 "github.com/anacrolix/libtorgo/metainfo"
25 func (t *torrent) PieceNumPendingBytes(index int) (count pp.Integer) {
26 if t.pieceComplete(index) {
29 piece := t.Pieces[index]
30 if !piece.EverHashed {
31 return t.PieceLength(index)
33 pendingChunks := t.Pieces[index].PendingChunkSpecs
34 count = pp.Integer(len(pendingChunks)) * chunkSize
35 _lastChunkSpec := lastChunkSpec(t.PieceLength(index))
36 if _lastChunkSpec.Length != chunkSize {
37 if _, ok := pendingChunks[_lastChunkSpec]; ok {
38 count += _lastChunkSpec.Length - chunkSize
44 type peersKey struct {
49 // Data maintains per-piece persistent state.
50 type StatefulData interface {
52 // We believe the piece data will pass a hash check.
53 PieceCompleted(index int) error
54 // Returns true if the piece is complete.
55 PieceComplete(index int) bool
58 // Is not aware of Client. Maintains state of torrent for with-in a Client.
63 // Closed when no more network activity is desired. This includes
64 // announcing, and communicating with peers.
65 ceasingNetworking chan struct{}
69 // Total length of the torrent in bytes. Stored because it's not O(1) to
70 // get this from the info dict.
75 // The info dict. Nil if we don't have it.
77 // Active peer connections, running message stream loops.
79 // Set of addrs to which we're attempting to connect. Connections are
80 // half-open until all handshakes are completed.
81 HalfOpen map[string]struct{}
83 // Reserve of peers to connect to. A peer can be both here and in the
84 // active connections if were told about the peer after connecting with
85 // them. That encourages us to reconnect to peers that are well known.
86 Peers map[peersKey]Peer
89 // BEP 12 Multitracker Metadata Extension. The tracker.Client instances
90 // mirror their respective URLs from the announce-list metainfo key.
91 Trackers [][]tracker.Client
92 // Name used if the info name isn't available.
94 // The bencoded bytes of the info dict.
96 // Each element corresponds to the 16KiB metadata pieces. If true, we have
97 // received that piece.
100 // Closed when .Info is set.
101 gotMetainfo chan struct{}
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 // A file-like handle to torrent data that implements SectionOpener. Opened
114 // sections will be reused so long as Reads and ReadAt's are contiguous.
124 func (h *handle) Close() error {
131 func (h *handle) ReadAt(b []byte, off int64) (n int, err error) {
132 return h.readAt(b, off)
135 func (h *handle) readAt(b []byte, off int64) (n int, err error) {
136 avail := h.t.prepareRead(off)
137 if int64(len(b)) > avail {
140 if int64(len(b)) > h.size-off {
143 if h.rcOff != off && h.rc != nil {
148 h.rc, err = h.so.OpenSection(off, h.size-off)
154 n, err = h.rc.Read(b)
159 func (h *handle) Read(b []byte) (n int, err error) {
160 n, err = h.readAt(b, h.curOff)
165 func (h *handle) Seek(off int64, whence int) (newOff int64, err error) {
172 h.curOff = h.size + off
174 err = errors.New("bad whence")
180 // Implements Handle on top of an io.SectionReader.
181 type sectionReaderHandle struct {
185 func (sectionReaderHandle) Close() error { return nil }
187 func (T Torrent) NewReadHandle() Handle {
188 if so, ok := T.data.(SectionOpener); ok {
195 return sectionReaderHandle{io.NewSectionReader(T, 0, T.Length())}
198 func (t *torrent) numConnsUnchoked() (num int) {
199 for _, c := range t.Conns {
207 // There's a connection to that address already.
208 func (t *torrent) addrActive(addr string) bool {
209 if _, ok := t.HalfOpen[addr]; ok {
212 for _, c := range t.Conns {
213 if c.remoteAddr().String() == addr {
220 func (t *torrent) worstConnsHeap() (wcs *worstConns) {
222 c: append([]*connection{}, t.Conns...),
229 func (t *torrent) ceaseNetworking() {
231 defer t.stateMu.Unlock()
233 case <-t.ceasingNetworking:
237 close(t.ceasingNetworking)
238 for _, c := range t.Conns {
244 func (t *torrent) addPeer(p Peer) {
245 t.Peers[peersKey{string(p.IP), p.Port}] = p
248 func (t *torrent) invalidateMetadata() {
254 func (t *torrent) SaveMetadataPiece(index int, data []byte) {
258 if index >= len(t.metadataHave) {
259 log.Printf("%s: ignoring metadata piece %d", t, index)
262 copy(t.MetaData[(1<<14)*index:], data)
263 t.metadataHave[index] = true
266 func (t *torrent) metadataPieceCount() int {
267 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
270 func (t *torrent) haveMetadataPiece(piece int) bool {
272 return (1<<14)*piece < len(t.MetaData)
274 return piece < len(t.metadataHave) && t.metadataHave[piece]
278 func (t *torrent) metadataSizeKnown() bool {
279 return t.MetaData != nil
282 func (t *torrent) metadataSize() int {
283 return len(t.MetaData)
286 func infoPieceHashes(info *metainfo.Info) (ret []string) {
287 for i := 0; i < len(info.Pieces); i += 20 {
288 ret = append(ret, string(info.Pieces[i:i+20]))
293 // Called when metadata for a torrent becomes available.
294 func (t *torrent) setMetadata(md metainfo.Info, infoBytes []byte, eventLocker sync.Locker) (err error) {
297 for _, f := range t.Info.UpvertedFiles() {
300 t.MetaData = infoBytes
302 for _, hash := range infoPieceHashes(&md) {
304 piece.Event.L = eventLocker
305 util.CopyExact(piece.Hash[:], hash)
306 t.Pieces = append(t.Pieces, piece)
308 for _, conn := range t.Conns {
309 t.initRequestOrdering(conn)
310 if err := conn.setNumPieces(t.numPieces()); err != nil {
311 log.Printf("closing connection: %s", err)
318 func (t *torrent) setStorage(td data.Data) (err error) {
319 if c, ok := t.data.(io.Closer); ok {
322 if sd, ok := td.(StatefulData); ok {
325 t.data = &statelessDataWrapper{td, make([]bool, t.Info.NumPieces())}
330 func (t *torrent) haveAllMetadataPieces() bool {
334 if t.metadataHave == nil {
337 for _, have := range t.metadataHave {
345 func (t *torrent) SetMetadataSize(bytes int64) {
346 if t.MetaData != nil {
349 if bytes > 10000000 { // 10MB, pulled from my ass.
352 t.MetaData = make([]byte, bytes)
353 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
356 // The current working name for the torrent. Either the name in the info dict,
357 // or a display name given such as by the dn value in a magnet link, or "".
358 func (t *torrent) Name() string {
362 if t.DisplayName != "" {
368 func (t *torrent) pieceStatusChar(index int) byte {
371 case t.pieceComplete(index):
373 case p.QueuedForHash:
379 case t.piecePartiallyDownloaded(index):
381 case piecePriorityNone:
382 return 'F' // Forgotten
388 case piecePriorityNone:
390 case piecePriorityNow:
392 case piecePriorityReadahead:
394 case piecePriorityNext:
402 func (t *torrent) metadataPieceSize(piece int) int {
403 return metadataPieceSize(len(t.MetaData), piece)
406 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
412 d["total_size"] = len(t.MetaData)
414 p, err := bencode.Marshal(d)
420 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
421 ExtendedPayload: append(p, data...),
425 type PieceStatusCharSequence struct {
430 func (t *torrent) PieceStatusCharSequences() []PieceStatusCharSequence {
432 defer t.stateMu.Unlock()
433 return t.pieceStatusCharSequences()
436 // Returns the length of sequences of identical piece status chars.
437 func (t *torrent) pieceStatusCharSequences() (ret []PieceStatusCharSequence) {
442 writeSequence := func() {
443 ret = append(ret, PieceStatusCharSequence{char, count})
445 if len(t.Pieces) != 0 {
446 char = t.pieceStatusChar(0)
448 for index := range t.Pieces {
449 char1 := t.pieceStatusChar(index)
464 func (t *torrent) WriteStatus(w io.Writer) {
465 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
466 fmt.Fprintf(w, "Piece length: %s\n", func() string {
468 return fmt.Sprint(t.usualPieceSize())
474 fmt.Fprint(w, "Pieces: ")
475 for _, seq := range t.pieceStatusCharSequences() {
476 fmt.Fprintf(w, "%d%c ", seq.Count, seq.Char)
480 fmt.Fprintf(w, "Trackers: ")
481 for _, tier := range t.Trackers {
482 for _, tr := range tier {
483 fmt.Fprintf(w, "%q ", tr.String())
487 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
488 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
489 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
490 sort.Sort(&worstConns{
494 for _, c := range t.Conns {
499 func (t *torrent) String() string {
502 s = fmt.Sprintf("%x", t.InfoHash)
507 func (t *torrent) haveInfo() bool {
511 // TODO: Include URIs that weren't converted to tracker clients.
512 func (t *torrent) announceList() (al [][]string) {
513 for _, tier := range t.Trackers {
515 for _, tr := range tier {
516 l = append(l, tr.URL())
523 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
524 if t.MetaData == nil {
525 panic("info bytes not set")
527 return &metainfo.MetaInfo{
528 Info: metainfo.InfoEx{
532 CreationDate: time.Now().Unix(),
533 Comment: "dynamic metainfo from client",
534 CreatedBy: "go.torrent",
535 AnnounceList: t.announceList(),
539 func (t *torrent) bytesLeft() (left int64) {
543 for i := 0; i < t.numPieces(); i++ {
544 left += int64(t.PieceNumPendingBytes(i))
549 func (t *torrent) piecePartiallyDownloaded(index int) bool {
550 return t.PieceNumPendingBytes(index) != t.PieceLength(index)
553 func numChunksForPiece(chunkSize int, pieceSize int) int {
554 return (pieceSize + chunkSize - 1) / chunkSize
557 func (t *torrent) usualPieceSize() int {
558 return int(t.Info.PieceLength)
561 func (t *torrent) lastPieceSize() int {
562 return int(t.PieceLength(t.numPieces() - 1))
565 func (t *torrent) numPieces() int {
566 return t.Info.NumPieces()
569 func (t *torrent) numPiecesCompleted() (num int) {
570 for i := range iter.N(t.Info.NumPieces()) {
571 if t.pieceComplete(i) {
578 func (t *torrent) Length() int64 {
582 func (t *torrent) isClosed() bool {
591 func (t *torrent) close() (err error) {
597 if c, ok := t.data.(io.Closer); ok {
600 for _, conn := range t.Conns {
606 // Return the request that would include the given offset into the torrent data.
607 func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
608 r request, ok bool) {
609 if offset < 0 || offset >= torrentLength {
612 r.Index = pp.Integer(offset / pieceSize)
613 r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
614 left := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
615 if chunkSize < left {
616 r.Length = pp.Integer(chunkSize)
618 r.Length = pp.Integer(left)
624 func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
625 off = int64(r.Index)*pieceSize + int64(r.Begin)
626 if off < 0 || off >= torrentLength {
627 panic("invalid request")
632 func (t *torrent) requestOffset(r request) int64 {
633 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
636 // Return the request that would include the given offset into the torrent data.
637 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
638 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, chunkSize, off)
641 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
642 _, err = t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
646 func (t *torrent) bitfield() (bf []bool) {
647 for _, p := range t.Pieces {
648 bf = append(bf, p.EverHashed && len(p.PendingChunkSpecs) == 0)
653 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
654 css = make([]chunkSpec, 0, (t.PieceLength(piece)+chunkSize-1)/chunkSize)
656 for left := t.PieceLength(piece); left != 0; left -= cs.Length {
658 if cs.Length > chunkSize {
659 cs.Length = chunkSize
661 css = append(css, cs)
662 cs.Begin += cs.Length
667 func (t *torrent) pendAllChunkSpecs(index int) {
668 piece := t.Pieces[index]
669 if piece.PendingChunkSpecs == nil {
670 piece.PendingChunkSpecs = make(
671 map[chunkSpec]struct{},
672 (t.PieceLength(index)+chunkSize-1)/chunkSize)
674 pcss := piece.PendingChunkSpecs
675 for _, cs := range t.pieceChunks(int(index)) {
676 pcss[cs] = struct{}{}
688 func (t *torrent) PieceLength(piece int) (len_ pp.Integer) {
689 if int(piece) == t.numPieces()-1 {
690 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
693 len_ = pp.Integer(t.Info.PieceLength)
698 func (t *torrent) hashPiece(piece pp.Integer) (ps pieceSum) {
699 hash := pieceHash.New()
700 t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, t.Info.PieceLength)
701 util.CopyExact(ps[:], hash.Sum(nil))
705 func (t *torrent) haveAllPieces() bool {
709 for i := range t.Pieces {
710 if !t.pieceComplete(i) {
717 func (me *torrent) haveAnyPieces() bool {
718 for i := range me.Pieces {
719 if me.pieceComplete(i) {
726 func (t *torrent) havePiece(index int) bool {
727 return t.haveInfo() && t.pieceComplete(index)
730 func (t *torrent) haveChunk(r request) bool {
731 p := t.Pieces[r.Index]
735 _, ok := p.PendingChunkSpecs[r.chunkSpec]
739 func (t *torrent) wantChunk(r request) bool {
740 if !t.wantPiece(int(r.Index)) {
743 _, ok := t.Pieces[r.Index].PendingChunkSpecs[r.chunkSpec]
747 func (t *torrent) wantPiece(index int) bool {
752 return !t.pieceComplete(index) && p.Priority != piecePriorityNone && !p.QueuedForHash && !p.Hashing
755 func (t *torrent) connHasWantedPieces(c *connection) bool {
756 for p := range t.Pieces {
757 if t.wantPiece(p) && c.PeerHasPiece(p) {
764 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
765 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
766 pieces = append(pieces, int(i))