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, eventLocker sync.Locker) (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.Event.L = eventLocker
253 piece.noPendingWrites.L = &piece.pendingWritesMutex
254 missinggo.CopyExact(piece.Hash[:], hash)
256 for _, conn := range t.Conns {
257 t.initRequestOrdering(conn)
258 if err := conn.setNumPieces(t.numPieces()); err != nil {
259 log.Printf("closing connection: %s", err)
266 func (t *torrent) setStorage(td Data) (err error) {
274 func (t *torrent) haveAllMetadataPieces() bool {
278 if t.metadataHave == nil {
281 for _, have := range t.metadataHave {
289 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
291 // We already know the correct metadata size.
294 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
295 log.Printf("received bad metadata size: %d", bytes)
298 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
301 t.MetaData = make([]byte, bytes)
302 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
303 for _, c := range t.Conns {
304 cl.requestPendingMetadata(t, c)
309 // The current working name for the torrent. Either the name in the info dict,
310 // or a display name given such as by the dn value in a magnet link, or "".
311 func (t *torrent) Name() string {
318 func (t *torrent) pieceState(index int) (ret PieceState) {
319 p := &t.Pieces[index]
320 ret.Priority = p.Priority
321 if t.pieceComplete(index) {
324 if p.QueuedForHash || p.Hashing {
327 if !ret.Complete && t.piecePartiallyDownloaded(index) {
333 func (t *torrent) metadataPieceSize(piece int) int {
334 return metadataPieceSize(len(t.MetaData), piece)
337 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
343 d["total_size"] = len(t.MetaData)
345 p, err := bencode.Marshal(d)
351 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
352 ExtendedPayload: append(p, data...),
356 func (t *torrent) pieceStateRuns() (ret []PieceStateRun) {
357 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
358 ret = append(ret, PieceStateRun{
359 PieceState: el.(PieceState),
363 for index := range t.Pieces {
364 rle.Append(t.pieceState(index), 1)
370 // Produces a small string representing a PieceStateRun.
371 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
372 ret = fmt.Sprintf("%d", psr.Length)
373 ret += func() string {
374 switch psr.Priority {
375 case PiecePriorityNext:
377 case PiecePriorityNormal:
379 case PiecePriorityReadahead:
381 case PiecePriorityNow:
399 func (t *torrent) writeStatus(w io.Writer, cl *Client) {
400 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
401 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
403 fmt.Fprintf(w, "Metadata have: ")
404 for _, h := range t.metadataHave {
405 fmt.Fprintf(w, "%c", func() rune {
415 fmt.Fprintf(w, "Piece length: %s\n", func() string {
417 return fmt.Sprint(t.usualPieceSize())
423 fmt.Fprintf(w, "Num Pieces: %d\n", t.numPieces())
424 fmt.Fprint(w, "Piece States:")
425 for _, psr := range t.pieceStateRuns() {
427 w.Write([]byte(pieceStateRunStatusChars(psr)))
431 fmt.Fprintf(w, "Urgent:")
432 for req := range t.urgent {
433 fmt.Fprintf(w, " %v", req)
436 fmt.Fprintf(w, "Trackers: ")
437 for _, tier := range t.Trackers {
438 for _, tr := range tier {
439 fmt.Fprintf(w, "%q ", tr.String())
443 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
444 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
445 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
446 sort.Sort(&worstConns{
451 for i, c := range t.Conns {
452 fmt.Fprintf(w, "%2d. ", i+1)
457 func (t *torrent) String() string {
460 s = fmt.Sprintf("%x", t.InfoHash)
465 func (t *torrent) haveInfo() bool {
466 return t != nil && t.Info != nil
469 // TODO: Include URIs that weren't converted to tracker clients.
470 func (t *torrent) announceList() (al [][]string) {
471 for _, tier := range t.Trackers {
473 for _, tr := range tier {
474 l = append(l, tr.URL())
481 // Returns a run-time generated MetaInfo that includes the info bytes and
482 // announce-list as currently known to the client.
483 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
484 if t.MetaData == nil {
485 panic("info bytes not set")
487 return &metainfo.MetaInfo{
488 Info: metainfo.InfoEx{
492 CreationDate: time.Now().Unix(),
493 Comment: "dynamic metainfo from client",
494 CreatedBy: "go.torrent",
495 AnnounceList: t.announceList(),
499 func (t *torrent) bytesLeft() (left int64) {
503 for i := 0; i < t.numPieces(); i++ {
504 left += int64(t.pieceNumPendingBytes(i))
509 func (t *torrent) piecePartiallyDownloaded(index int) bool {
510 pendingBytes := t.pieceNumPendingBytes(index)
511 return pendingBytes != 0 && pendingBytes != t.pieceLength(index)
514 func numChunksForPiece(chunkSize int, pieceSize int) int {
515 return (pieceSize + chunkSize - 1) / chunkSize
518 func (t *torrent) usualPieceSize() int {
519 return int(t.Info.PieceLength)
522 func (t *torrent) lastPieceSize() int {
523 return int(t.pieceLength(t.numPieces() - 1))
526 func (t *torrent) numPieces() int {
527 return t.Info.NumPieces()
530 func (t *torrent) numPiecesCompleted() (num int) {
531 for i := range iter.N(t.Info.NumPieces()) {
532 if t.pieceComplete(i) {
539 func (t *torrent) Length() int64 {
543 func (t *torrent) isClosed() bool {
552 func (t *torrent) close() (err error) {
558 if c, ok := t.data.(io.Closer); ok {
561 for _, conn := range t.Conns {
564 t.pieceStateChanges.Close()
568 func (t *torrent) requestOffset(r request) int64 {
569 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
572 // Return the request that would include the given offset into the torrent
573 // data. Returns !ok if there is no such request.
574 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
575 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, int64(t.chunkSize), off)
578 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
579 n, err := t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
580 if err == nil && n != len(data) {
581 err = io.ErrShortWrite
586 func (t *torrent) bitfield() (bf []bool) {
587 for i := range t.Pieces {
589 // TODO: Check this logic.
590 bf = append(bf, p.EverHashed && p.numPendingChunks() == 0)
595 func (t *torrent) validOutgoingRequest(r request) bool {
596 if r.Index >= pp.Integer(t.Info.NumPieces()) {
599 if r.Begin%t.chunkSize != 0 {
602 if r.Length > t.chunkSize {
605 pieceLength := t.pieceLength(int(r.Index))
606 if r.Begin+r.Length > pieceLength {
609 return r.Length == t.chunkSize || r.Begin+r.Length == pieceLength
612 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
613 css = make([]chunkSpec, 0, (t.pieceLength(piece)+t.chunkSize-1)/t.chunkSize)
615 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
617 if cs.Length > t.chunkSize {
618 cs.Length = t.chunkSize
620 css = append(css, cs)
621 cs.Begin += cs.Length
626 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
627 piece := &t.Pieces[pieceIndex]
628 if piece.PendingChunkSpecs == nil {
629 // Allocate to exact size.
630 piece.PendingChunkSpecs = make([]bool, (t.pieceLength(pieceIndex)+t.chunkSize-1)/t.chunkSize)
632 // Pend all the chunks.
633 pcss := piece.PendingChunkSpecs
634 for i := range pcss {
645 // Peer is known to support encryption.
646 SupportsEncryption bool
649 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
650 if int(piece) == t.numPieces()-1 {
651 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
654 len_ = pp.Integer(t.Info.PieceLength)
659 func (t *torrent) hashPiece(piece pp.Integer) (ps pieceSum) {
660 hash := pieceHash.New()
661 p := &t.Pieces[piece]
662 p.pendingWritesMutex.Lock()
663 for p.pendingWrites != 0 {
664 p.noPendingWrites.Wait()
666 p.pendingWritesMutex.Unlock()
667 pl := t.Info.Piece(int(piece)).Length()
668 n, err := t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, pl)
670 if err != io.ErrUnexpectedEOF {
671 log.Printf("error hashing piece with %T: %s", t.data, err)
676 panic(fmt.Sprintf("%T: %d != %d", t.data, n, pl))
678 missinggo.CopyExact(ps[:], hash.Sum(nil))
682 func (t *torrent) haveAllPieces() bool {
686 for i := range t.Pieces {
687 if !t.pieceComplete(i) {
694 func (me *torrent) haveAnyPieces() bool {
695 for i := range me.Pieces {
696 if me.pieceComplete(i) {
703 func (t *torrent) havePiece(index int) bool {
704 return t.haveInfo() && t.pieceComplete(index)
707 func (t *torrent) haveChunk(r request) bool {
711 if t.pieceComplete(int(r.Index)) {
714 p := &t.Pieces[r.Index]
715 if p.PendingChunkSpecs == nil {
718 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
721 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
722 return int(cs.Begin / chunkSize)
725 // TODO: This should probably be called wantPiece.
726 func (t *torrent) wantChunk(r request) bool {
727 if !t.wantPiece(int(r.Index)) {
730 if t.Pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
737 func (t *torrent) urgentChunkInPiece(piece int) bool {
738 p := pp.Integer(piece)
739 for req := range t.urgent {
747 // TODO: This should be called wantPieceIndex.
748 func (t *torrent) wantPiece(index int) bool {
752 p := &t.Pieces[index]
759 if p.Priority == PiecePriorityNone {
760 if !t.urgentChunkInPiece(index) {
764 // Put piece complete check last, since it's the slowest as it can involve
765 // calling out into external data stores.
766 return !t.pieceComplete(index)
769 func (t *torrent) connHasWantedPieces(c *connection) bool {
770 return c.pieceRequestOrder != nil && !c.pieceRequestOrder.Empty()
773 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
774 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
775 pieces = append(pieces, int(i))
780 func (t *torrent) worstBadConn(cl *Client) *connection {
781 wcs := t.worstConns(cl)
784 c := heap.Pop(wcs).(*connection)
785 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
788 if wcs.Len() >= (socketsPerTorrent+1)/2 {
789 // Give connections 1 minute to prove themselves.
790 if time.Since(c.completedHandshake) > time.Minute {
798 func (t *torrent) publishPieceChange(piece int) {
799 cur := t.pieceState(piece)
800 p := &t.Pieces[piece]
801 if cur != p.PublicPieceState {
802 t.pieceStateChanges.Publish(piece)
804 p.PublicPieceState = cur