13 "github.com/anacrolix/missinggo"
14 "github.com/bradfitz/iter"
16 "github.com/anacrolix/torrent/bencode"
17 "github.com/anacrolix/torrent/data"
18 "github.com/anacrolix/torrent/metainfo"
19 pp "github.com/anacrolix/torrent/peer_protocol"
20 "github.com/anacrolix/torrent/tracker"
21 "github.com/anacrolix/torrent/util"
24 func (t *torrent) pieceNumPendingBytes(index int) (count pp.Integer) {
25 if t.pieceComplete(index) {
28 piece := t.Pieces[index]
29 pieceLength := t.pieceLength(index)
30 if !piece.EverHashed {
33 for i, pending := range piece.PendingChunkSpecs {
35 count += chunkIndexSpec(i, pieceLength).Length
41 type peersKey struct {
46 // Data maintains per-piece persistent state.
47 type StatefulData interface {
49 // We believe the piece data will pass a hash check.
50 PieceCompleted(index int) error
51 // Returns true if the piece is complete.
52 PieceComplete(index int) bool
55 // Is not aware of Client. Maintains state of torrent for with-in a Client.
60 // Closed when no more network activity is desired. This includes
61 // announcing, and communicating with peers.
62 ceasingNetworking chan struct{}
66 // Chunks that are wanted before all others. This is for
67 // responsive/streaming readers that want to unblock ASAP.
68 urgent map[request]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 (yet).
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{}
103 pruneTimer *time.Timer
106 func (t *torrent) pieceComplete(piece int) bool {
107 // TODO: This is called when setting metadata, and before storage is
108 // assigned, which doesn't seem right.
109 return t.data != nil && t.data.PieceComplete(piece)
112 func (t *torrent) numConnsUnchoked() (num int) {
113 for _, c := range t.Conns {
121 // There's a connection to that address already.
122 func (t *torrent) addrActive(addr string) bool {
123 if _, ok := t.HalfOpen[addr]; ok {
126 for _, c := range t.Conns {
127 if c.remoteAddr().String() == addr {
134 func (t *torrent) worstConnsHeap() (wcs *worstConns) {
136 c: append([]*connection{}, t.Conns...),
143 func (t *torrent) ceaseNetworking() {
145 defer t.stateMu.Unlock()
147 case <-t.ceasingNetworking:
151 close(t.ceasingNetworking)
152 for _, c := range t.Conns {
155 if t.pruneTimer != nil {
160 func (t *torrent) addPeer(p Peer) {
161 t.Peers[peersKey{string(p.IP), p.Port}] = p
164 func (t *torrent) invalidateMetadata() {
170 func (t *torrent) saveMetadataPiece(index int, data []byte) {
174 if index >= len(t.metadataHave) {
175 log.Printf("%s: ignoring metadata piece %d", t, index)
178 copy(t.MetaData[(1<<14)*index:], data)
179 t.metadataHave[index] = true
182 func (t *torrent) metadataPieceCount() int {
183 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
186 func (t *torrent) haveMetadataPiece(piece int) bool {
188 return (1<<14)*piece < len(t.MetaData)
190 return piece < len(t.metadataHave) && t.metadataHave[piece]
194 func (t *torrent) metadataSizeKnown() bool {
195 return t.MetaData != nil
198 func (t *torrent) metadataSize() int {
199 return len(t.MetaData)
202 func infoPieceHashes(info *metainfo.Info) (ret []string) {
203 for i := 0; i < len(info.Pieces); i += 20 {
204 ret = append(ret, string(info.Pieces[i:i+20]))
209 // Called when metadata for a torrent becomes available.
210 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte, eventLocker sync.Locker) (err error) {
211 err = validateInfo(md)
213 err = fmt.Errorf("bad info: %s", err)
218 for _, f := range t.Info.UpvertedFiles() {
221 t.MetaData = infoBytes
223 for _, hash := range infoPieceHashes(md) {
225 piece.Event.L = eventLocker
226 util.CopyExact(piece.Hash[:], hash)
227 t.Pieces = append(t.Pieces, piece)
229 for _, conn := range t.Conns {
230 t.initRequestOrdering(conn)
231 if err := conn.setNumPieces(t.numPieces()); err != nil {
232 log.Printf("closing connection: %s", err)
239 func (t *torrent) setStorage(td data.Data) (err error) {
240 if c, ok := t.data.(io.Closer); ok {
243 if sd, ok := td.(StatefulData); ok {
246 t.data = &statelessDataWrapper{td, make([]bool, t.Info.NumPieces())}
251 func (t *torrent) haveAllMetadataPieces() bool {
255 if t.metadataHave == nil {
258 for _, have := range t.metadataHave {
266 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
268 // We already know the correct metadata size.
271 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
272 log.Printf("received bad metadata size: %d", bytes)
275 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
278 t.MetaData = make([]byte, bytes)
279 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
280 for _, c := range t.Conns {
281 cl.requestPendingMetadata(t, c)
286 // The current working name for the torrent. Either the name in the info dict,
287 // or a display name given such as by the dn value in a magnet link, or "".
288 func (t *torrent) Name() string {
292 if t.DisplayName != "" {
298 func (t *torrent) pieceState(index int) (ret PieceState) {
300 ret.Priority = p.Priority
301 if t.pieceComplete(index) {
304 if p.QueuedForHash || p.Hashing {
307 if t.piecePartiallyDownloaded(index) {
313 func (t *torrent) metadataPieceSize(piece int) int {
314 return metadataPieceSize(len(t.MetaData), piece)
317 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
323 d["total_size"] = len(t.MetaData)
325 p, err := bencode.Marshal(d)
331 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
332 ExtendedPayload: append(p, data...),
336 func (t *torrent) pieceStateRuns() (ret []PieceStateRun) {
337 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
338 ret = append(ret, PieceStateRun{
339 PieceState: el.(PieceState),
343 for index := range t.Pieces {
344 rle.Append(t.pieceState(index), 1)
350 // Produces a small string representing a PieceStateRun.
351 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
352 ret = fmt.Sprintf("%d", psr.Length)
353 ret += func() string {
354 switch psr.Priority {
355 case PiecePriorityNext:
357 case PiecePriorityNormal:
359 case PiecePriorityReadahead:
361 case PiecePriorityNow:
379 func (t *torrent) writeStatus(w io.Writer) {
380 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
381 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
382 fmt.Fprintf(w, "Metadata have: ")
383 for _, h := range t.metadataHave {
384 fmt.Fprintf(w, "%c", func() rune {
393 fmt.Fprintf(w, "Piece length: %s\n", func() string {
395 return fmt.Sprint(t.usualPieceSize())
401 fmt.Fprint(w, "Pieces:")
402 for _, psr := range t.pieceStateRuns() {
404 w.Write([]byte(pieceStateRunStatusChars(psr)))
408 fmt.Fprintf(w, "Urgent:")
409 for req := range t.urgent {
410 fmt.Fprintf(w, " %v", req)
413 fmt.Fprintf(w, "Trackers: ")
414 for _, tier := range t.Trackers {
415 for _, tr := range tier {
416 fmt.Fprintf(w, "%q ", tr.String())
420 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
421 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
422 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
423 sort.Sort(&worstConns{
427 for _, c := range t.Conns {
432 func (t *torrent) String() string {
435 s = fmt.Sprintf("%x", t.InfoHash)
440 func (t *torrent) haveInfo() bool {
444 // TODO: Include URIs that weren't converted to tracker clients.
445 func (t *torrent) announceList() (al [][]string) {
446 for _, tier := range t.Trackers {
448 for _, tr := range tier {
449 l = append(l, tr.URL())
456 // Returns a run-time generated MetaInfo that includes the info bytes and
457 // announce-list as currently known to the client.
458 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
459 if t.MetaData == nil {
460 panic("info bytes not set")
462 return &metainfo.MetaInfo{
463 Info: metainfo.InfoEx{
467 CreationDate: time.Now().Unix(),
468 Comment: "dynamic metainfo from client",
469 CreatedBy: "go.torrent",
470 AnnounceList: t.announceList(),
474 func (t *torrent) bytesLeft() (left int64) {
478 for i := 0; i < t.numPieces(); i++ {
479 left += int64(t.pieceNumPendingBytes(i))
484 func (t *torrent) piecePartiallyDownloaded(index int) bool {
485 pendingBytes := t.pieceNumPendingBytes(index)
486 return pendingBytes != 0 && pendingBytes != t.pieceLength(index)
489 func numChunksForPiece(chunkSize int, pieceSize int) int {
490 return (pieceSize + chunkSize - 1) / chunkSize
493 func (t *torrent) usualPieceSize() int {
494 return int(t.Info.PieceLength)
497 func (t *torrent) lastPieceSize() int {
498 return int(t.pieceLength(t.numPieces() - 1))
501 func (t *torrent) numPieces() int {
502 return t.Info.NumPieces()
505 func (t *torrent) numPiecesCompleted() (num int) {
506 for i := range iter.N(t.Info.NumPieces()) {
507 if t.pieceComplete(i) {
514 func (t *torrent) Length() int64 {
518 func (t *torrent) isClosed() bool {
527 func (t *torrent) close() (err error) {
533 if c, ok := t.data.(io.Closer); ok {
536 for _, conn := range t.Conns {
542 func (t *torrent) requestOffset(r request) int64 {
543 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
546 // Return the request that would include the given offset into the torrent
547 // data. Returns !ok if there is no such request.
548 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
549 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, chunkSize, off)
552 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
553 n, err := t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
554 if err == nil && n != len(data) {
555 err = io.ErrShortWrite
560 func (t *torrent) bitfield() (bf []bool) {
561 for _, p := range t.Pieces {
562 // TODO: Check this logic.
563 bf = append(bf, p.EverHashed && p.numPendingChunks() == 0)
568 func (t *torrent) validOutgoingRequest(r request) bool {
569 if r.Index >= pp.Integer(t.Info.NumPieces()) {
572 if r.Begin%chunkSize != 0 {
575 if r.Length > chunkSize {
578 pieceLength := t.pieceLength(int(r.Index))
579 if r.Begin+r.Length > pieceLength {
582 return r.Length == chunkSize || r.Begin+r.Length == pieceLength
585 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
586 css = make([]chunkSpec, 0, (t.pieceLength(piece)+chunkSize-1)/chunkSize)
588 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
590 if cs.Length > chunkSize {
591 cs.Length = chunkSize
593 css = append(css, cs)
594 cs.Begin += cs.Length
599 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
600 piece := t.Pieces[pieceIndex]
601 if piece.PendingChunkSpecs == nil {
602 // Allocate to exact size.
603 piece.PendingChunkSpecs = make([]bool, (t.pieceLength(pieceIndex)+chunkSize-1)/chunkSize)
605 // Pend all the chunks.
606 pcss := piece.PendingChunkSpecs
607 for i := range pcss {
618 // Peer is known to support encryption.
619 SupportsEncryption bool
622 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
623 if int(piece) == t.numPieces()-1 {
624 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
627 len_ = pp.Integer(t.Info.PieceLength)
632 func (t *torrent) hashPiece(piece pp.Integer) (ps pieceSum) {
633 hash := pieceHash.New()
634 t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, t.Info.PieceLength)
635 util.CopyExact(ps[:], hash.Sum(nil))
639 func (t *torrent) haveAllPieces() bool {
643 for i := range t.Pieces {
644 if !t.pieceComplete(i) {
651 func (me *torrent) haveAnyPieces() bool {
652 for i := range me.Pieces {
653 if me.pieceComplete(i) {
660 func (t *torrent) havePiece(index int) bool {
661 return t.haveInfo() && t.pieceComplete(index)
664 func (t *torrent) haveChunk(r request) bool {
668 return !t.Pieces[r.Index].pendingChunk(r.chunkSpec)
671 func chunkIndex(cs chunkSpec) int {
672 return int(cs.Begin / chunkSize)
675 // TODO: This should probably be called wantPiece.
676 func (t *torrent) wantChunk(r request) bool {
677 if !t.wantPiece(int(r.Index)) {
680 if t.Pieces[r.Index].pendingChunk(r.chunkSpec) {
687 func (t *torrent) urgentChunkInPiece(piece int) bool {
688 for req := range t.urgent {
689 if int(req.Index) == piece {
696 // TODO: This should be called wantPieceIndex.
697 func (t *torrent) wantPiece(index int) bool {
708 if p.Priority == PiecePriorityNone {
709 if !t.urgentChunkInPiece(index) {
713 // Put piece complete check last, since it's the slowest as it can involve
714 // calling out into external data stores.
715 return !t.pieceComplete(index)
718 func (t *torrent) connHasWantedPieces(c *connection) bool {
719 return c.pieceRequestOrder != nil && c.pieceRequestOrder.First() != nil
722 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
723 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
724 pieces = append(pieces, int(i))