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())
384 fmt.Fprintf(w, "Metadata have: ")
385 for _, h := range t.metadataHave {
386 fmt.Fprintf(w, "%c", func() rune {
395 fmt.Fprintf(w, "Piece length: %s\n", func() string {
397 return fmt.Sprint(t.usualPieceSize())
403 fmt.Fprint(w, "Pieces:")
404 for _, psr := range t.pieceStateRuns() {
406 w.Write([]byte(pieceStateRunStatusChars(psr)))
410 fmt.Fprintf(w, "Urgent:")
411 for req := range t.urgent {
412 fmt.Fprintf(w, " %v", req)
415 fmt.Fprintf(w, "Trackers: ")
416 for _, tier := range t.Trackers {
417 for _, tr := range tier {
418 fmt.Fprintf(w, "%q ", tr.String())
422 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
423 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
424 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
425 sort.Sort(&worstConns{
430 for _, c := range t.Conns {
435 func (t *torrent) String() string {
438 s = fmt.Sprintf("%x", t.InfoHash)
443 func (t *torrent) haveInfo() bool {
447 // TODO: Include URIs that weren't converted to tracker clients.
448 func (t *torrent) announceList() (al [][]string) {
449 for _, tier := range t.Trackers {
451 for _, tr := range tier {
452 l = append(l, tr.URL())
459 // Returns a run-time generated MetaInfo that includes the info bytes and
460 // announce-list as currently known to the client.
461 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
462 if t.MetaData == nil {
463 panic("info bytes not set")
465 return &metainfo.MetaInfo{
466 Info: metainfo.InfoEx{
470 CreationDate: time.Now().Unix(),
471 Comment: "dynamic metainfo from client",
472 CreatedBy: "go.torrent",
473 AnnounceList: t.announceList(),
477 func (t *torrent) bytesLeft() (left int64) {
481 for i := 0; i < t.numPieces(); i++ {
482 left += int64(t.pieceNumPendingBytes(i))
487 func (t *torrent) piecePartiallyDownloaded(index int) bool {
488 pendingBytes := t.pieceNumPendingBytes(index)
489 return pendingBytes != 0 && pendingBytes != t.pieceLength(index)
492 func numChunksForPiece(chunkSize int, pieceSize int) int {
493 return (pieceSize + chunkSize - 1) / chunkSize
496 func (t *torrent) usualPieceSize() int {
497 return int(t.Info.PieceLength)
500 func (t *torrent) lastPieceSize() int {
501 return int(t.pieceLength(t.numPieces() - 1))
504 func (t *torrent) numPieces() int {
505 return t.Info.NumPieces()
508 func (t *torrent) numPiecesCompleted() (num int) {
509 for i := range iter.N(t.Info.NumPieces()) {
510 if t.pieceComplete(i) {
517 func (t *torrent) Length() int64 {
521 func (t *torrent) isClosed() bool {
530 func (t *torrent) close() (err error) {
536 if c, ok := t.data.(io.Closer); ok {
539 for _, conn := range t.Conns {
545 func (t *torrent) requestOffset(r request) int64 {
546 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
549 // Return the request that would include the given offset into the torrent
550 // data. Returns !ok if there is no such request.
551 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
552 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, chunkSize, off)
555 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
556 n, err := t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
557 if err == nil && n != len(data) {
558 err = io.ErrShortWrite
563 func (t *torrent) bitfield() (bf []bool) {
564 for _, p := range t.Pieces {
565 // TODO: Check this logic.
566 bf = append(bf, p.EverHashed && p.numPendingChunks() == 0)
571 func (t *torrent) validOutgoingRequest(r request) bool {
572 if r.Index >= pp.Integer(t.Info.NumPieces()) {
575 if r.Begin%chunkSize != 0 {
578 if r.Length > chunkSize {
581 pieceLength := t.pieceLength(int(r.Index))
582 if r.Begin+r.Length > pieceLength {
585 return r.Length == chunkSize || r.Begin+r.Length == pieceLength
588 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
589 css = make([]chunkSpec, 0, (t.pieceLength(piece)+chunkSize-1)/chunkSize)
591 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
593 if cs.Length > chunkSize {
594 cs.Length = chunkSize
596 css = append(css, cs)
597 cs.Begin += cs.Length
602 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
603 piece := t.Pieces[pieceIndex]
604 if piece.PendingChunkSpecs == nil {
605 // Allocate to exact size.
606 piece.PendingChunkSpecs = make([]bool, (t.pieceLength(pieceIndex)+chunkSize-1)/chunkSize)
608 // Pend all the chunks.
609 pcss := piece.PendingChunkSpecs
610 for i := range pcss {
621 // Peer is known to support encryption.
622 SupportsEncryption bool
625 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
626 if int(piece) == t.numPieces()-1 {
627 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
630 len_ = pp.Integer(t.Info.PieceLength)
635 func (t *torrent) hashPiece(piece pp.Integer) (ps pieceSum) {
636 hash := pieceHash.New()
637 t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, t.Info.PieceLength)
638 util.CopyExact(ps[:], hash.Sum(nil))
642 func (t *torrent) haveAllPieces() bool {
646 for i := range t.Pieces {
647 if !t.pieceComplete(i) {
654 func (me *torrent) haveAnyPieces() bool {
655 for i := range me.Pieces {
656 if me.pieceComplete(i) {
663 func (t *torrent) havePiece(index int) bool {
664 return t.haveInfo() && t.pieceComplete(index)
667 func (t *torrent) haveChunk(r request) bool {
671 return !t.Pieces[r.Index].pendingChunk(r.chunkSpec)
674 func chunkIndex(cs chunkSpec) int {
675 return int(cs.Begin / chunkSize)
678 // TODO: This should probably be called wantPiece.
679 func (t *torrent) wantChunk(r request) bool {
680 if !t.wantPiece(int(r.Index)) {
683 if t.Pieces[r.Index].pendingChunk(r.chunkSpec) {
690 func (t *torrent) urgentChunkInPiece(piece int) bool {
691 p := pp.Integer(piece)
692 for req := range t.urgent {
700 // TODO: This should be called wantPieceIndex.
701 func (t *torrent) wantPiece(index int) bool {
712 if p.Priority == PiecePriorityNone {
713 if !t.urgentChunkInPiece(index) {
717 // Put piece complete check last, since it's the slowest as it can involve
718 // calling out into external data stores.
719 return !t.pieceComplete(index)
722 func (t *torrent) connHasWantedPieces(c *connection) bool {
723 return c.pieceRequestOrder != nil && c.pieceRequestOrder.First() != nil
726 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
727 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
728 pieces = append(pieces, int(i))
733 func (t *torrent) worstBadConn(cl *Client) *connection {
734 wcs := t.worstConns(cl)
736 // A connection can only be bad if it's in the worst half, rounded down.
737 for wcs.Len() > (socketsPerTorrent+1)/2 {
738 c := heap.Pop(wcs).(*connection)
739 // Give connections 1 minute to prove themselves.
740 if time.Since(c.completedHandshake) < time.Minute {