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{}
104 func (t *torrent) pieceComplete(piece int) bool {
105 // TODO: This is called when setting metadata, and before storage is
106 // assigned, which doesn't seem right.
107 return t.data != nil && t.data.PieceComplete(piece)
110 func (t *torrent) numConnsUnchoked() (num int) {
111 for _, c := range t.Conns {
119 // There's a connection to that address already.
120 func (t *torrent) addrActive(addr string) bool {
121 if _, ok := t.HalfOpen[addr]; ok {
124 for _, c := range t.Conns {
125 if c.remoteAddr().String() == addr {
132 func (t *torrent) worstConns(cl *Client) (wcs *worstConns) {
134 c: make([]*connection, 0, len(t.Conns)),
138 for _, c := range t.Conns {
142 wcs.c = append(wcs.c, c)
148 func (t *torrent) ceaseNetworking() {
150 defer t.stateMu.Unlock()
152 case <-t.ceasingNetworking:
156 close(t.ceasingNetworking)
157 for _, c := range t.Conns {
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) {
213 err = validateInfo(md)
215 err = fmt.Errorf("bad info: %s", err)
220 for _, f := range t.Info.UpvertedFiles() {
223 t.MetaData = infoBytes
225 for _, hash := range infoPieceHashes(md) {
227 piece.Event.L = eventLocker
228 util.CopyExact(piece.Hash[:], hash)
229 t.Pieces = append(t.Pieces, piece)
231 for _, conn := range t.Conns {
232 t.initRequestOrdering(conn)
233 if err := conn.setNumPieces(t.numPieces()); err != nil {
234 log.Printf("closing connection: %s", err)
241 func (t *torrent) setStorage(td data.Data) (err error) {
242 if c, ok := t.data.(io.Closer); ok {
245 if sd, ok := td.(StatefulData); ok {
248 t.data = &statelessDataWrapper{td, make([]bool, t.Info.NumPieces())}
253 func (t *torrent) haveAllMetadataPieces() bool {
257 if t.metadataHave == nil {
260 for _, have := range t.metadataHave {
268 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
270 // We already know the correct metadata size.
273 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
274 log.Printf("received bad metadata size: %d", bytes)
277 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
280 t.MetaData = make([]byte, bytes)
281 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
282 for _, c := range t.Conns {
283 cl.requestPendingMetadata(t, c)
288 // The current working name for the torrent. Either the name in the info dict,
289 // or a display name given such as by the dn value in a magnet link, or "".
290 func (t *torrent) Name() string {
294 if t.DisplayName != "" {
300 func (t *torrent) pieceState(index int) (ret PieceState) {
302 ret.Priority = p.Priority
303 if t.pieceComplete(index) {
306 if p.QueuedForHash || p.Hashing {
309 if t.piecePartiallyDownloaded(index) {
315 func (t *torrent) metadataPieceSize(piece int) int {
316 return metadataPieceSize(len(t.MetaData), piece)
319 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
325 d["total_size"] = len(t.MetaData)
327 p, err := bencode.Marshal(d)
333 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
334 ExtendedPayload: append(p, data...),
338 func (t *torrent) pieceStateRuns() (ret []PieceStateRun) {
339 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
340 ret = append(ret, PieceStateRun{
341 PieceState: el.(PieceState),
345 for index := range t.Pieces {
346 rle.Append(t.pieceState(index), 1)
352 // Produces a small string representing a PieceStateRun.
353 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
354 ret = fmt.Sprintf("%d", psr.Length)
355 ret += func() string {
356 switch psr.Priority {
357 case PiecePriorityNext:
359 case PiecePriorityNormal:
361 case PiecePriorityReadahead:
363 case PiecePriorityNow:
381 func (t *torrent) writeStatus(w io.Writer, cl *Client) {
382 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
383 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
385 fmt.Fprintf(w, "Metadata have: ")
386 for _, h := range t.metadataHave {
387 fmt.Fprintf(w, "%c", func() rune {
397 fmt.Fprintf(w, "Piece length: %s\n", func() string {
399 return fmt.Sprint(t.usualPieceSize())
405 fmt.Fprint(w, "Pieces:")
406 for _, psr := range t.pieceStateRuns() {
408 w.Write([]byte(pieceStateRunStatusChars(psr)))
412 fmt.Fprintf(w, "Urgent:")
413 for req := range t.urgent {
414 fmt.Fprintf(w, " %v", req)
417 fmt.Fprintf(w, "Trackers: ")
418 for _, tier := range t.Trackers {
419 for _, tr := range tier {
420 fmt.Fprintf(w, "%q ", tr.String())
424 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
425 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
426 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
427 sort.Sort(&worstConns{
432 for i, c := range t.Conns {
433 fmt.Fprintf(w, "%2d. ", i+1)
438 func (t *torrent) String() string {
441 s = fmt.Sprintf("%x", t.InfoHash)
446 func (t *torrent) haveInfo() bool {
447 return t != nil && t.Info != nil
450 // TODO: Include URIs that weren't converted to tracker clients.
451 func (t *torrent) announceList() (al [][]string) {
452 for _, tier := range t.Trackers {
454 for _, tr := range tier {
455 l = append(l, tr.URL())
462 // Returns a run-time generated MetaInfo that includes the info bytes and
463 // announce-list as currently known to the client.
464 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
465 if t.MetaData == nil {
466 panic("info bytes not set")
468 return &metainfo.MetaInfo{
469 Info: metainfo.InfoEx{
473 CreationDate: time.Now().Unix(),
474 Comment: "dynamic metainfo from client",
475 CreatedBy: "go.torrent",
476 AnnounceList: t.announceList(),
480 func (t *torrent) bytesLeft() (left int64) {
484 for i := 0; i < t.numPieces(); i++ {
485 left += int64(t.pieceNumPendingBytes(i))
490 func (t *torrent) piecePartiallyDownloaded(index int) bool {
491 pendingBytes := t.pieceNumPendingBytes(index)
492 return pendingBytes != 0 && pendingBytes != t.pieceLength(index)
495 func numChunksForPiece(chunkSize int, pieceSize int) int {
496 return (pieceSize + chunkSize - 1) / chunkSize
499 func (t *torrent) usualPieceSize() int {
500 return int(t.Info.PieceLength)
503 func (t *torrent) lastPieceSize() int {
504 return int(t.pieceLength(t.numPieces() - 1))
507 func (t *torrent) numPieces() int {
508 return t.Info.NumPieces()
511 func (t *torrent) numPiecesCompleted() (num int) {
512 for i := range iter.N(t.Info.NumPieces()) {
513 if t.pieceComplete(i) {
520 func (t *torrent) Length() int64 {
524 func (t *torrent) isClosed() bool {
533 func (t *torrent) close() (err error) {
539 if c, ok := t.data.(io.Closer); ok {
542 for _, conn := range t.Conns {
548 func (t *torrent) requestOffset(r request) int64 {
549 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
552 // Return the request that would include the given offset into the torrent
553 // data. Returns !ok if there is no such request.
554 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
555 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, chunkSize, off)
558 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
559 n, err := t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
560 if err == nil && n != len(data) {
561 err = io.ErrShortWrite
566 func (t *torrent) bitfield() (bf []bool) {
567 for _, p := range t.Pieces {
568 // TODO: Check this logic.
569 bf = append(bf, p.EverHashed && p.numPendingChunks() == 0)
574 func (t *torrent) validOutgoingRequest(r request) bool {
575 if r.Index >= pp.Integer(t.Info.NumPieces()) {
578 if r.Begin%chunkSize != 0 {
581 if r.Length > chunkSize {
584 pieceLength := t.pieceLength(int(r.Index))
585 if r.Begin+r.Length > pieceLength {
588 return r.Length == chunkSize || r.Begin+r.Length == pieceLength
591 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
592 css = make([]chunkSpec, 0, (t.pieceLength(piece)+chunkSize-1)/chunkSize)
594 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
596 if cs.Length > chunkSize {
597 cs.Length = chunkSize
599 css = append(css, cs)
600 cs.Begin += cs.Length
605 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
606 piece := t.Pieces[pieceIndex]
607 if piece.PendingChunkSpecs == nil {
608 // Allocate to exact size.
609 piece.PendingChunkSpecs = make([]bool, (t.pieceLength(pieceIndex)+chunkSize-1)/chunkSize)
611 // Pend all the chunks.
612 pcss := piece.PendingChunkSpecs
613 for i := range pcss {
624 // Peer is known to support encryption.
625 SupportsEncryption bool
628 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
629 if int(piece) == t.numPieces()-1 {
630 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
633 len_ = pp.Integer(t.Info.PieceLength)
638 func (t *torrent) hashPiece(piece pp.Integer) (ps pieceSum) {
639 hash := pieceHash.New()
640 t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, t.Info.PieceLength)
641 util.CopyExact(ps[:], hash.Sum(nil))
645 func (t *torrent) haveAllPieces() bool {
649 for i := range t.Pieces {
650 if !t.pieceComplete(i) {
657 func (me *torrent) haveAnyPieces() bool {
658 for i := range me.Pieces {
659 if me.pieceComplete(i) {
666 func (t *torrent) havePiece(index int) bool {
667 return t.haveInfo() && t.pieceComplete(index)
670 func (t *torrent) haveChunk(r request) bool {
674 return !t.Pieces[r.Index].pendingChunk(r.chunkSpec)
677 func chunkIndex(cs chunkSpec) int {
678 return int(cs.Begin / chunkSize)
681 // TODO: This should probably be called wantPiece.
682 func (t *torrent) wantChunk(r request) bool {
683 if !t.wantPiece(int(r.Index)) {
686 if t.Pieces[r.Index].pendingChunk(r.chunkSpec) {
693 func (t *torrent) urgentChunkInPiece(piece int) bool {
694 p := pp.Integer(piece)
695 for req := range t.urgent {
703 // TODO: This should be called wantPieceIndex.
704 func (t *torrent) wantPiece(index int) bool {
715 if p.Priority == PiecePriorityNone {
716 if !t.urgentChunkInPiece(index) {
720 // Put piece complete check last, since it's the slowest as it can involve
721 // calling out into external data stores.
722 return !t.pieceComplete(index)
725 func (t *torrent) connHasWantedPieces(c *connection) bool {
726 return c.pieceRequestOrder != nil && c.pieceRequestOrder.First() != nil
729 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
730 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
731 pieces = append(pieces, int(i))
736 func (t *torrent) worstBadConn(cl *Client) *connection {
737 wcs := t.worstConns(cl)
739 // A connection can only be bad if it's in the worst half, rounded down.
740 for wcs.Len() > (socketsPerTorrent+1)/2 {
741 c := heap.Pop(wcs).(*connection)
742 // Give connections 1 minute to prove themselves.
743 if time.Since(c.completedHandshake) < time.Minute {