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{}
74 // Active peer connections.
76 // Set of addrs to which we're attempting to connect.
77 HalfOpen map[string]struct{}
79 // Reserve of peers to connect to. A peer can be both here and in the
80 // active connections if were told about the peer after connecting with
81 // them. That encourages us to reconnect to peers that are well known.
82 Peers map[peersKey]Peer
85 // BEP 12 Multitracker Metadata Extension. The tracker.Client instances
86 // mirror their respective URLs from the announce-list metainfo key.
87 Trackers [][]tracker.Client
92 gotMetainfo chan struct{}
93 GotMetainfo <-chan struct{}
95 pruneTimer *time.Timer
98 func (t *torrent) pieceComplete(piece int) bool {
99 // TODO: This is called when setting metadata, and before storage is
100 // assigned, which doesn't seem right.
101 return t.data != nil && t.data.PieceComplete(piece)
104 // A file-like handle to torrent data that implements SectionOpener. Opened
105 // sections will be reused so long as Reads and ReadAt's are contiguous.
115 func (h *handle) Close() error {
122 func (h *handle) ReadAt(b []byte, off int64) (n int, err error) {
123 return h.readAt(b, off)
126 func (h *handle) readAt(b []byte, off int64) (n int, err error) {
127 avail := h.t.prepareRead(off)
128 if int64(len(b)) > avail {
131 if int64(len(b)) > h.size-off {
134 if h.rcOff != off && h.rc != nil {
139 h.rc, err = h.so.OpenSection(off, h.size-off)
145 n, err = h.rc.Read(b)
150 func (h *handle) Read(b []byte) (n int, err error) {
151 n, err = h.readAt(b, h.curOff)
156 func (h *handle) Seek(off int64, whence int) (newOff int64, err error) {
163 h.curOff = h.size + off
165 err = errors.New("bad whence")
171 // Implements Handle on top of an io.SectionReader.
172 type sectionReaderHandle struct {
176 func (sectionReaderHandle) Close() error { return nil }
178 func (T Torrent) NewReadHandle() Handle {
179 if so, ok := T.data.(SectionOpener); ok {
186 return sectionReaderHandle{io.NewSectionReader(T, 0, T.Length())}
189 func (t *torrent) numConnsUnchoked() (num int) {
190 for _, c := range t.Conns {
198 func (t *torrent) addrActive(addr string) bool {
199 if _, ok := t.HalfOpen[addr]; ok {
202 for _, c := range t.Conns {
203 if c.Socket.RemoteAddr().String() == addr {
210 func (t *torrent) worstConnsHeap() (wcs *worstConns) {
212 c: append([]*connection{}, t.Conns...),
219 func (t *torrent) ceaseNetworking() {
221 defer t.stateMu.Unlock()
223 case <-t.ceasingNetworking:
227 close(t.ceasingNetworking)
228 for _, c := range t.Conns {
234 func (t *torrent) addPeer(p Peer) {
235 t.Peers[peersKey{string(p.IP), p.Port}] = p
238 func (t *torrent) invalidateMetadata() {
244 func (t *torrent) SaveMetadataPiece(index int, data []byte) {
248 if index >= len(t.metadataHave) {
249 log.Printf("%s: ignoring metadata piece %d", t, index)
252 copy(t.MetaData[(1<<14)*index:], data)
253 t.metadataHave[index] = true
256 func (t *torrent) metadataPieceCount() int {
257 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
260 func (t *torrent) haveMetadataPiece(piece int) bool {
262 return (1<<14)*piece < len(t.MetaData)
264 return piece < len(t.metadataHave) && t.metadataHave[piece]
268 func (t *torrent) metadataSizeKnown() bool {
269 return t.MetaData != nil
272 func (t *torrent) metadataSize() int {
273 return len(t.MetaData)
276 func infoPieceHashes(info *metainfo.Info) (ret []string) {
277 for i := 0; i < len(info.Pieces); i += 20 {
278 ret = append(ret, string(info.Pieces[i:i+20]))
283 // Called when metadata for a torrent becomes available.
284 func (t *torrent) setMetadata(md metainfo.Info, infoBytes []byte, eventLocker sync.Locker) (err error) {
287 for _, f := range t.Info.UpvertedFiles() {
290 t.MetaData = infoBytes
292 for _, hash := range infoPieceHashes(&md) {
294 piece.Event.L = eventLocker
295 util.CopyExact(piece.Hash[:], hash)
296 t.Pieces = append(t.Pieces, piece)
298 for _, conn := range t.Conns {
299 t.initRequestOrdering(conn)
300 if err := conn.setNumPieces(t.numPieces()); err != nil {
301 log.Printf("closing connection: %s", err)
308 func (t *torrent) setStorage(td data.Data) (err error) {
309 if c, ok := t.data.(io.Closer); ok {
312 if sd, ok := td.(StatefulData); ok {
315 t.data = &statelessDataWrapper{td, make([]bool, t.Info.NumPieces())}
320 func (t *torrent) haveAllMetadataPieces() bool {
324 if t.metadataHave == nil {
327 for _, have := range t.metadataHave {
335 func (t *torrent) SetMetadataSize(bytes int64) {
336 if t.MetaData != nil {
339 if bytes > 10000000 { // 10MB, pulled from my ass.
342 t.MetaData = make([]byte, bytes)
343 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
346 // The current working name for the torrent. Either the name in the info dict,
347 // or a display name given such as by the dn value in a magnet link, or "".
348 func (t *torrent) Name() string {
352 if t.DisplayName != "" {
358 func (t *torrent) pieceStatusChar(index int) byte {
361 case t.pieceComplete(index):
363 case p.QueuedForHash:
369 case t.piecePartiallyDownloaded(index):
371 case piecePriorityNone:
372 return 'F' // Forgotten
378 case piecePriorityNone:
380 case piecePriorityNow:
382 case piecePriorityReadahead:
384 case piecePriorityNext:
392 func (t *torrent) metadataPieceSize(piece int) int {
393 return metadataPieceSize(len(t.MetaData), piece)
396 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
402 d["total_size"] = len(t.MetaData)
404 p, err := bencode.Marshal(d)
410 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
411 ExtendedPayload: append(p, data...),
415 type PieceStatusCharSequence struct {
420 func (t *torrent) PieceStatusCharSequences() []PieceStatusCharSequence {
422 defer t.stateMu.Unlock()
423 return t.pieceStatusCharSequences()
426 // Returns the length of sequences of identical piece status chars.
427 func (t *torrent) pieceStatusCharSequences() (ret []PieceStatusCharSequence) {
432 writeSequence := func() {
433 ret = append(ret, PieceStatusCharSequence{char, count})
435 if len(t.Pieces) != 0 {
436 char = t.pieceStatusChar(0)
438 for index := range t.Pieces {
439 char1 := t.pieceStatusChar(index)
454 func (t *torrent) WriteStatus(w io.Writer) {
455 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
456 fmt.Fprintf(w, "Piece length: %s\n", func() string {
458 return fmt.Sprint(t.usualPieceSize())
464 fmt.Fprint(w, "Pieces: ")
465 for _, seq := range t.pieceStatusCharSequences() {
466 fmt.Fprintf(w, "%d%c ", seq.Count, seq.Char)
470 fmt.Fprintf(w, "Trackers: ")
471 for _, tier := range t.Trackers {
472 for _, tr := range tier {
473 fmt.Fprintf(w, "%q ", tr.String())
477 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
478 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
479 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
480 sort.Sort(&worstConns{
484 for _, c := range t.Conns {
489 func (t *torrent) String() string {
492 s = fmt.Sprintf("%x", t.InfoHash)
497 func (t *torrent) haveInfo() bool {
501 // TODO: Include URIs that weren't converted to tracker clients.
502 func (t *torrent) announceList() (al [][]string) {
503 for _, tier := range t.Trackers {
505 for _, tr := range tier {
506 l = append(l, tr.URL())
513 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
514 if t.MetaData == nil {
515 panic("info bytes not set")
517 return &metainfo.MetaInfo{
518 Info: metainfo.InfoEx{
522 CreationDate: time.Now().Unix(),
523 Comment: "dynamic metainfo from client",
524 CreatedBy: "go.torrent",
525 AnnounceList: t.announceList(),
529 func (t *torrent) bytesLeft() (left int64) {
533 for i := 0; i < t.numPieces(); i++ {
534 left += int64(t.PieceNumPendingBytes(i))
539 func (t *torrent) piecePartiallyDownloaded(index int) bool {
540 return t.PieceNumPendingBytes(index) != t.PieceLength(index)
543 func numChunksForPiece(chunkSize int, pieceSize int) int {
544 return (pieceSize + chunkSize - 1) / chunkSize
547 func (t *torrent) usualPieceSize() int {
548 return int(t.Info.PieceLength)
551 func (t *torrent) lastPieceSize() int {
552 return int(t.PieceLength(t.numPieces() - 1))
555 func (t *torrent) numPieces() int {
556 return t.Info.NumPieces()
559 func (t *torrent) numPiecesCompleted() (num int) {
560 for i := range iter.N(t.Info.NumPieces()) {
561 if t.pieceComplete(i) {
568 func (t *torrent) Length() int64 {
572 func (t *torrent) isClosed() bool {
581 func (t *torrent) close() (err error) {
587 if c, ok := t.data.(io.Closer); ok {
590 for _, conn := range t.Conns {
596 // Return the request that would include the given offset into the torrent data.
597 func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
598 r request, ok bool) {
599 if offset < 0 || offset >= torrentLength {
602 r.Index = pp.Integer(offset / pieceSize)
603 r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
604 left := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
605 if chunkSize < left {
606 r.Length = pp.Integer(chunkSize)
608 r.Length = pp.Integer(left)
614 func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
615 off = int64(r.Index)*pieceSize + int64(r.Begin)
616 if off < 0 || off >= torrentLength {
617 panic("invalid request")
622 func (t *torrent) requestOffset(r request) int64 {
623 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
626 // Return the request that would include the given offset into the torrent data.
627 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
628 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, chunkSize, off)
631 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
632 _, err = t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
636 func (t *torrent) bitfield() (bf []bool) {
637 for _, p := range t.Pieces {
638 bf = append(bf, p.EverHashed && len(p.PendingChunkSpecs) == 0)
643 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
644 css = make([]chunkSpec, 0, (t.PieceLength(piece)+chunkSize-1)/chunkSize)
646 for left := t.PieceLength(piece); left != 0; left -= cs.Length {
648 if cs.Length > chunkSize {
649 cs.Length = chunkSize
651 css = append(css, cs)
652 cs.Begin += cs.Length
657 func (t *torrent) pendAllChunkSpecs(index int) {
658 piece := t.Pieces[index]
659 if piece.PendingChunkSpecs == nil {
660 piece.PendingChunkSpecs = make(
661 map[chunkSpec]struct{},
662 (t.PieceLength(index)+chunkSize-1)/chunkSize)
664 pcss := piece.PendingChunkSpecs
665 for _, cs := range t.pieceChunks(int(index)) {
666 pcss[cs] = struct{}{}
678 func (t *torrent) PieceLength(piece int) (len_ pp.Integer) {
679 if int(piece) == t.numPieces()-1 {
680 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
683 len_ = pp.Integer(t.Info.PieceLength)
688 func (t *torrent) hashPiece(piece pp.Integer) (ps pieceSum) {
689 hash := pieceHash.New()
690 t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, t.Info.PieceLength)
691 util.CopyExact(ps[:], hash.Sum(nil))
695 func (t *torrent) haveAllPieces() bool {
699 for i := range t.Pieces {
700 if !t.pieceComplete(i) {
707 func (me *torrent) haveAnyPieces() bool {
708 for i := range me.Pieces {
709 if me.pieceComplete(i) {
716 func (t *torrent) havePiece(index int) bool {
717 return t.haveInfo() && t.pieceComplete(index)
720 func (t *torrent) haveChunk(r request) bool {
721 p := t.Pieces[r.Index]
725 _, ok := p.PendingChunkSpecs[r.chunkSpec]
729 func (t *torrent) wantChunk(r request) bool {
730 if !t.wantPiece(int(r.Index)) {
733 _, ok := t.Pieces[r.Index].PendingChunkSpecs[r.chunkSpec]
737 func (t *torrent) wantPiece(index int) bool {
742 return !t.pieceComplete(index) && p.Priority != piecePriorityNone && !p.QueuedForHash && !p.Hashing
745 func (t *torrent) connHasWantedPieces(c *connection) bool {
746 for p := range t.Pieces {
747 if t.wantPiece(p) && c.PeerHasPiece(p) {
754 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
755 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
756 pieces = append(pieces, int(i))