15 "github.com/anacrolix/missinggo"
16 "github.com/anacrolix/missinggo/pubsub"
17 "github.com/bradfitz/iter"
19 "github.com/anacrolix/torrent/bencode"
20 "github.com/anacrolix/torrent/metainfo"
21 pp "github.com/anacrolix/torrent/peer_protocol"
22 "github.com/anacrolix/torrent/tracker"
25 func (t *torrent) pieceNumPendingBytes(index int) (count pp.Integer) {
26 if t.pieceComplete(index) {
29 piece := &t.Pieces[index]
30 pieceLength := t.pieceLength(index)
31 if !piece.EverHashed {
34 for i, pending := range piece.PendingChunkSpecs {
36 count += chunkIndexSpec(i, pieceLength, t.chunkSize).Length
42 type peersKey struct {
47 // Is not aware of Client. Maintains state of torrent for with-in a Client.
52 // Closed when no more network activity is desired. This includes
53 // announcing, and communicating with peers.
54 ceasingNetworking chan struct{}
58 // Values are the piece indices that changed.
59 pieceStateChanges *pubsub.PubSub
61 // Chunks that are wanted before all others. This is for
62 // responsive/streaming readers that want to unblock ASAP.
63 urgent map[request]struct{}
64 // Total length of the torrent in bytes. Stored because it's not O(1) to
65 // get this from the info dict.
70 // The info dict. Nil if we don't have it (yet).
72 // Active peer connections, running message stream loops.
74 // Set of addrs to which we're attempting to connect. Connections are
75 // half-open until all handshakes are completed.
76 HalfOpen map[string]struct{}
78 // Reserve of peers to connect to. A peer can be both here and in the
79 // active connections if were told about the peer after connecting with
80 // them. That encourages us to reconnect to peers that are well known.
81 Peers map[peersKey]Peer
84 // BEP 12 Multitracker Metadata Extension. The tracker.Client instances
85 // mirror their respective URLs from the announce-list metainfo key.
86 Trackers [][]tracker.Client
87 // Name used if the info name isn't available.
89 // The bencoded bytes of the info dict.
91 // Each element corresponds to the 16KiB metadata pieces. If true, we have
92 // received that piece.
95 // Closed when .Info is set.
96 gotMetainfo chan struct{}
98 connPiecePriorites sync.Pool
102 piecePrioritiesReused = expvar.NewInt("piecePrioritiesReused")
103 piecePrioritiesNew = expvar.NewInt("piecePrioritiesNew")
106 func (t *torrent) newConnPiecePriorities() []int {
107 _ret := t.connPiecePriorites.Get()
109 piecePrioritiesReused.Add(1)
112 piecePrioritiesNew.Add(1)
113 return rand.Perm(t.numPieces())
116 func (t *torrent) pieceComplete(piece int) bool {
117 // TODO: This is called when setting metadata, and before storage is
118 // assigned, which doesn't seem right.
119 return t.data != nil && t.data.PieceComplete(piece)
122 func (t *torrent) numConnsUnchoked() (num int) {
123 for _, c := range t.Conns {
131 // There's a connection to that address already.
132 func (t *torrent) addrActive(addr string) bool {
133 if _, ok := t.HalfOpen[addr]; ok {
136 for _, c := range t.Conns {
137 if c.remoteAddr().String() == addr {
144 func (t *torrent) worstConns(cl *Client) (wcs *worstConns) {
146 c: make([]*connection, 0, len(t.Conns)),
150 for _, c := range t.Conns {
154 wcs.c = append(wcs.c, c)
160 func (t *torrent) ceaseNetworking() {
162 defer t.stateMu.Unlock()
164 case <-t.ceasingNetworking:
168 close(t.ceasingNetworking)
169 for _, c := range t.Conns {
174 func (t *torrent) addPeer(p Peer, cl *Client) {
176 if len(t.Peers) >= torrentPeersHighWater {
179 key := peersKey{string(p.IP), p.Port}
180 if _, ok := t.Peers[key]; ok {
184 peersAddedBySource.Add(string(p.Source), 1)
189 func (t *torrent) invalidateMetadata() {
195 func (t *torrent) saveMetadataPiece(index int, data []byte) {
199 if index >= len(t.metadataHave) {
200 log.Printf("%s: ignoring metadata piece %d", t, index)
203 copy(t.MetaData[(1<<14)*index:], data)
204 t.metadataHave[index] = true
207 func (t *torrent) metadataPieceCount() int {
208 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
211 func (t *torrent) haveMetadataPiece(piece int) bool {
213 return (1<<14)*piece < len(t.MetaData)
215 return piece < len(t.metadataHave) && t.metadataHave[piece]
219 func (t *torrent) metadataSizeKnown() bool {
220 return t.MetaData != nil
223 func (t *torrent) metadataSize() int {
224 return len(t.MetaData)
227 func infoPieceHashes(info *metainfo.Info) (ret []string) {
228 for i := 0; i < len(info.Pieces); i += 20 {
229 ret = append(ret, string(info.Pieces[i:i+20]))
234 // Called when metadata for a torrent becomes available.
235 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte) (err error) {
236 err = validateInfo(md)
238 err = fmt.Errorf("bad info: %s", err)
243 for _, f := range t.Info.UpvertedFiles() {
246 t.MetaData = infoBytes
248 hashes := infoPieceHashes(md)
249 t.Pieces = make([]piece, len(hashes))
250 for i, hash := range hashes {
251 piece := &t.Pieces[i]
252 piece.noPendingWrites.L = &piece.pendingWritesMutex
253 missinggo.CopyExact(piece.Hash[:], hash)
255 for _, conn := range t.Conns {
256 t.initRequestOrdering(conn)
257 if err := conn.setNumPieces(t.numPieces()); err != nil {
258 log.Printf("closing connection: %s", err)
265 func (t *torrent) setStorage(td Data) (err error) {
273 func (t *torrent) haveAllMetadataPieces() bool {
277 if t.metadataHave == nil {
280 for _, have := range t.metadataHave {
288 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
290 // We already know the correct metadata size.
293 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
294 log.Printf("received bad metadata size: %d", bytes)
297 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
300 t.MetaData = make([]byte, bytes)
301 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
302 for _, c := range t.Conns {
303 cl.requestPendingMetadata(t, c)
308 // The current working name for the torrent. Either the name in the info dict,
309 // or a display name given such as by the dn value in a magnet link, or "".
310 func (t *torrent) Name() string {
317 func (t *torrent) pieceState(index int) (ret PieceState) {
318 p := &t.Pieces[index]
319 ret.Priority = p.Priority
320 if t.pieceComplete(index) {
323 if p.QueuedForHash || p.Hashing {
326 if !ret.Complete && t.piecePartiallyDownloaded(index) {
332 func (t *torrent) metadataPieceSize(piece int) int {
333 return metadataPieceSize(len(t.MetaData), piece)
336 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
342 d["total_size"] = len(t.MetaData)
344 p, err := bencode.Marshal(d)
350 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
351 ExtendedPayload: append(p, data...),
355 func (t *torrent) pieceStateRuns() (ret []PieceStateRun) {
356 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
357 ret = append(ret, PieceStateRun{
358 PieceState: el.(PieceState),
362 for index := range t.Pieces {
363 rle.Append(t.pieceState(index), 1)
369 // Produces a small string representing a PieceStateRun.
370 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
371 ret = fmt.Sprintf("%d", psr.Length)
372 ret += func() string {
373 switch psr.Priority {
374 case PiecePriorityNext:
376 case PiecePriorityNormal:
378 case PiecePriorityReadahead:
380 case PiecePriorityNow:
398 func (t *torrent) writeStatus(w io.Writer, cl *Client) {
399 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
400 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
402 fmt.Fprintf(w, "Metadata have: ")
403 for _, h := range t.metadataHave {
404 fmt.Fprintf(w, "%c", func() rune {
414 fmt.Fprintf(w, "Piece length: %s\n", func() string {
416 return fmt.Sprint(t.usualPieceSize())
422 fmt.Fprintf(w, "Num Pieces: %d\n", t.numPieces())
423 fmt.Fprint(w, "Piece States:")
424 for _, psr := range t.pieceStateRuns() {
426 w.Write([]byte(pieceStateRunStatusChars(psr)))
430 fmt.Fprintf(w, "Urgent:")
431 for req := range t.urgent {
432 fmt.Fprintf(w, " %v", req)
435 fmt.Fprintf(w, "Trackers: ")
436 for _, tier := range t.Trackers {
437 for _, tr := range tier {
438 fmt.Fprintf(w, "%q ", tr.String())
442 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
443 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
444 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
445 sort.Sort(&worstConns{
450 for i, c := range t.Conns {
451 fmt.Fprintf(w, "%2d. ", i+1)
456 func (t *torrent) String() string {
459 s = fmt.Sprintf("%x", t.InfoHash)
464 func (t *torrent) haveInfo() bool {
465 return t != nil && t.Info != nil
468 // TODO: Include URIs that weren't converted to tracker clients.
469 func (t *torrent) announceList() (al [][]string) {
470 for _, tier := range t.Trackers {
472 for _, tr := range tier {
473 l = append(l, tr.URL())
480 // Returns a run-time generated MetaInfo that includes the info bytes and
481 // announce-list as currently known to the client.
482 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
483 if t.MetaData == nil {
484 panic("info bytes not set")
486 return &metainfo.MetaInfo{
487 Info: metainfo.InfoEx{
491 CreationDate: time.Now().Unix(),
492 Comment: "dynamic metainfo from client",
493 CreatedBy: "go.torrent",
494 AnnounceList: t.announceList(),
498 func (t *torrent) bytesLeft() (left int64) {
502 for i := 0; i < t.numPieces(); i++ {
503 left += int64(t.pieceNumPendingBytes(i))
508 func (t *torrent) piecePartiallyDownloaded(index int) bool {
509 pendingBytes := t.pieceNumPendingBytes(index)
510 return pendingBytes != 0 && pendingBytes != t.pieceLength(index)
513 func numChunksForPiece(chunkSize int, pieceSize int) int {
514 return (pieceSize + chunkSize - 1) / chunkSize
517 func (t *torrent) usualPieceSize() int {
518 return int(t.Info.PieceLength)
521 func (t *torrent) lastPieceSize() int {
522 return int(t.pieceLength(t.numPieces() - 1))
525 func (t *torrent) numPieces() int {
526 return t.Info.NumPieces()
529 func (t *torrent) numPiecesCompleted() (num int) {
530 for i := range iter.N(t.Info.NumPieces()) {
531 if t.pieceComplete(i) {
538 func (t *torrent) Length() int64 {
542 func (t *torrent) isClosed() bool {
551 func (t *torrent) close() (err error) {
557 if c, ok := t.data.(io.Closer); ok {
560 for _, conn := range t.Conns {
563 t.pieceStateChanges.Close()
567 func (t *torrent) requestOffset(r request) int64 {
568 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
571 // Return the request that would include the given offset into the torrent
572 // data. Returns !ok if there is no such request.
573 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
574 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, int64(t.chunkSize), off)
577 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
578 n, err := t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
579 if err == nil && n != len(data) {
580 err = io.ErrShortWrite
585 func (t *torrent) bitfield() (bf []bool) {
586 for i := range t.Pieces {
588 // TODO: Check this logic.
589 bf = append(bf, p.EverHashed && p.numPendingChunks() == 0)
594 func (t *torrent) validOutgoingRequest(r request) bool {
595 if r.Index >= pp.Integer(t.Info.NumPieces()) {
598 if r.Begin%t.chunkSize != 0 {
601 if r.Length > t.chunkSize {
604 pieceLength := t.pieceLength(int(r.Index))
605 if r.Begin+r.Length > pieceLength {
608 return r.Length == t.chunkSize || r.Begin+r.Length == pieceLength
611 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
612 css = make([]chunkSpec, 0, (t.pieceLength(piece)+t.chunkSize-1)/t.chunkSize)
614 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
616 if cs.Length > t.chunkSize {
617 cs.Length = t.chunkSize
619 css = append(css, cs)
620 cs.Begin += cs.Length
625 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
626 piece := &t.Pieces[pieceIndex]
627 if piece.PendingChunkSpecs == nil {
628 // Allocate to exact size.
629 piece.PendingChunkSpecs = make([]bool, (t.pieceLength(pieceIndex)+t.chunkSize-1)/t.chunkSize)
631 // Pend all the chunks.
632 pcss := piece.PendingChunkSpecs
633 for i := range pcss {
644 // Peer is known to support encryption.
645 SupportsEncryption bool
648 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
649 if int(piece) == t.numPieces()-1 {
650 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
653 len_ = pp.Integer(t.Info.PieceLength)
658 func (t *torrent) hashPiece(piece pp.Integer) (ps pieceSum) {
659 hash := pieceHash.New()
660 p := &t.Pieces[piece]
661 p.pendingWritesMutex.Lock()
662 for p.pendingWrites != 0 {
663 p.noPendingWrites.Wait()
665 p.pendingWritesMutex.Unlock()
666 pl := t.Info.Piece(int(piece)).Length()
667 n, err := t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, pl)
669 if err != io.ErrUnexpectedEOF {
670 log.Printf("error hashing piece with %T: %s", t.data, err)
675 panic(fmt.Sprintf("%T: %d != %d", t.data, n, pl))
677 missinggo.CopyExact(ps[:], hash.Sum(nil))
681 func (t *torrent) haveAllPieces() bool {
685 for i := range t.Pieces {
686 if !t.pieceComplete(i) {
693 func (me *torrent) haveAnyPieces() bool {
694 for i := range me.Pieces {
695 if me.pieceComplete(i) {
702 func (t *torrent) havePiece(index int) bool {
703 return t.haveInfo() && t.pieceComplete(index)
706 func (t *torrent) haveChunk(r request) bool {
710 if t.pieceComplete(int(r.Index)) {
713 p := &t.Pieces[r.Index]
714 if p.PendingChunkSpecs == nil {
717 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
720 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
721 return int(cs.Begin / chunkSize)
724 // TODO: This should probably be called wantPiece.
725 func (t *torrent) wantChunk(r request) bool {
726 if !t.wantPiece(int(r.Index)) {
729 if t.Pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
736 func (t *torrent) urgentChunkInPiece(piece int) bool {
737 p := pp.Integer(piece)
738 for req := range t.urgent {
746 // TODO: This should be called wantPieceIndex.
747 func (t *torrent) wantPiece(index int) bool {
751 p := &t.Pieces[index]
758 if p.Priority == PiecePriorityNone {
759 if !t.urgentChunkInPiece(index) {
763 // Put piece complete check last, since it's the slowest as it can involve
764 // calling out into external data stores.
765 return !t.pieceComplete(index)
768 func (t *torrent) connHasWantedPieces(c *connection) bool {
769 return c.pieceRequestOrder != nil && !c.pieceRequestOrder.Empty()
772 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
773 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
774 pieces = append(pieces, int(i))
779 func (t *torrent) worstBadConn(cl *Client) *connection {
780 wcs := t.worstConns(cl)
783 c := heap.Pop(wcs).(*connection)
784 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
787 if wcs.Len() >= (socketsPerTorrent+1)/2 {
788 // Give connections 1 minute to prove themselves.
789 if time.Since(c.completedHandshake) > time.Minute {
797 func (t *torrent) publishPieceChange(piece int) {
798 cur := t.pieceState(piece)
799 p := &t.Pieces[piece]
800 if cur != p.PublicPieceState {
801 t.pieceStateChanges.Publish(piece)
803 p.PublicPieceState = cur