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) setDisplayName(dn string) {
110 func (t *torrent) newConnPiecePriorities() []int {
111 _ret := t.connPiecePriorites.Get()
113 piecePrioritiesReused.Add(1)
116 piecePrioritiesNew.Add(1)
117 return rand.Perm(t.numPieces())
120 func (t *torrent) pieceComplete(piece int) bool {
121 // TODO: This is called when setting metadata, and before storage is
122 // assigned, which doesn't seem right.
123 return t.data != nil && t.data.PieceComplete(piece)
126 func (t *torrent) numConnsUnchoked() (num int) {
127 for _, c := range t.Conns {
135 // There's a connection to that address already.
136 func (t *torrent) addrActive(addr string) bool {
137 if _, ok := t.HalfOpen[addr]; ok {
140 for _, c := range t.Conns {
141 if c.remoteAddr().String() == addr {
148 func (t *torrent) worstConns(cl *Client) (wcs *worstConns) {
150 c: make([]*connection, 0, len(t.Conns)),
154 for _, c := range t.Conns {
158 wcs.c = append(wcs.c, c)
164 func (t *torrent) ceaseNetworking() {
166 defer t.stateMu.Unlock()
168 case <-t.ceasingNetworking:
172 close(t.ceasingNetworking)
173 for _, c := range t.Conns {
178 func (t *torrent) addPeer(p Peer, cl *Client) {
180 if len(t.Peers) >= torrentPeersHighWater {
183 key := PeersKey{string(p.IP), p.Port}
184 if _, ok := t.Peers[key]; ok {
188 peersAddedBySource.Add(string(p.Source), 1)
193 func (t *torrent) invalidateMetadata() {
199 func (t *torrent) saveMetadataPiece(index int, data []byte) {
203 if index >= len(t.metadataHave) {
204 log.Printf("%s: ignoring metadata piece %d", t, index)
207 copy(t.MetaData[(1<<14)*index:], data)
208 t.metadataHave[index] = true
211 func (t *torrent) metadataPieceCount() int {
212 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
215 func (t *torrent) haveMetadataPiece(piece int) bool {
217 return (1<<14)*piece < len(t.MetaData)
219 return piece < len(t.metadataHave) && t.metadataHave[piece]
223 func (t *torrent) metadataSizeKnown() bool {
224 return t.MetaData != nil
227 func (t *torrent) metadataSize() int {
228 return len(t.MetaData)
231 func infoPieceHashes(info *metainfo.Info) (ret []string) {
232 for i := 0; i < len(info.Pieces); i += 20 {
233 ret = append(ret, string(info.Pieces[i:i+20]))
238 // Called when metadata for a torrent becomes available.
239 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte) (err error) {
240 err = validateInfo(md)
242 err = fmt.Errorf("bad info: %s", err)
247 for _, f := range t.Info.UpvertedFiles() {
250 t.MetaData = infoBytes
252 hashes := infoPieceHashes(md)
253 t.Pieces = make([]piece, len(hashes))
254 for i, hash := range hashes {
255 piece := &t.Pieces[i]
256 piece.noPendingWrites.L = &piece.pendingWritesMutex
257 missinggo.CopyExact(piece.Hash[:], hash)
259 for _, conn := range t.Conns {
260 t.initRequestOrdering(conn)
261 if err := conn.setNumPieces(t.numPieces()); err != nil {
262 log.Printf("closing connection: %s", err)
269 func (t *torrent) setStorage(td Data) (err error) {
277 func (t *torrent) haveAllMetadataPieces() bool {
281 if t.metadataHave == nil {
284 for _, have := range t.metadataHave {
292 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
294 // We already know the correct metadata size.
297 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
298 log.Printf("received bad metadata size: %d", bytes)
301 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
304 t.MetaData = make([]byte, bytes)
305 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
306 for _, c := range t.Conns {
307 cl.requestPendingMetadata(t, c)
312 // The current working name for the torrent. Either the name in the info dict,
313 // or a display name given such as by the dn value in a magnet link, or "".
314 func (t *torrent) Name() string {
321 func (t *torrent) pieceState(index int) (ret PieceState) {
322 p := &t.Pieces[index]
323 ret.Priority = p.Priority
324 if t.pieceComplete(index) {
327 if p.QueuedForHash || p.Hashing {
330 if !ret.Complete && t.piecePartiallyDownloaded(index) {
336 func (t *torrent) metadataPieceSize(piece int) int {
337 return metadataPieceSize(len(t.MetaData), piece)
340 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
346 d["total_size"] = len(t.MetaData)
348 p, err := bencode.Marshal(d)
354 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
355 ExtendedPayload: append(p, data...),
359 func (t *torrent) pieceStateRuns() (ret []PieceStateRun) {
360 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
361 ret = append(ret, PieceStateRun{
362 PieceState: el.(PieceState),
366 for index := range t.Pieces {
367 rle.Append(t.pieceState(index), 1)
373 // Produces a small string representing a PieceStateRun.
374 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
375 ret = fmt.Sprintf("%d", psr.Length)
376 ret += func() string {
377 switch psr.Priority {
378 case PiecePriorityNext:
380 case PiecePriorityNormal:
382 case PiecePriorityReadahead:
384 case PiecePriorityNow:
402 func (t *torrent) writeStatus(w io.Writer, cl *Client) {
403 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
404 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
406 fmt.Fprintf(w, "Metadata have: ")
407 for _, h := range t.metadataHave {
408 fmt.Fprintf(w, "%c", func() rune {
418 fmt.Fprintf(w, "Piece length: %s\n", func() string {
420 return fmt.Sprint(t.usualPieceSize())
426 fmt.Fprintf(w, "Num Pieces: %d\n", t.numPieces())
427 fmt.Fprint(w, "Piece States:")
428 for _, psr := range t.pieceStateRuns() {
430 w.Write([]byte(pieceStateRunStatusChars(psr)))
434 fmt.Fprintf(w, "Urgent:")
435 for req := range t.urgent {
436 fmt.Fprintf(w, " %v", req)
439 fmt.Fprintf(w, "Trackers: ")
440 for _, tier := range t.Trackers {
441 for _, tr := range tier {
442 fmt.Fprintf(w, "%q ", tr.String())
446 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
447 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
448 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
449 sort.Sort(&worstConns{
454 for i, c := range t.Conns {
455 fmt.Fprintf(w, "%2d. ", i+1)
460 func (t *torrent) String() string {
463 s = fmt.Sprintf("%x", t.InfoHash)
468 func (t *torrent) haveInfo() bool {
469 return t != nil && t.Info != nil
472 // TODO: Include URIs that weren't converted to tracker clients.
473 func (t *torrent) announceList() (al [][]string) {
474 for _, tier := range t.Trackers {
476 for _, tr := range tier {
477 l = append(l, tr.URL())
484 // Returns a run-time generated MetaInfo that includes the info bytes and
485 // announce-list as currently known to the client.
486 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
487 if t.MetaData == nil {
488 panic("info bytes not set")
490 return &metainfo.MetaInfo{
491 Info: metainfo.InfoEx{
495 CreationDate: time.Now().Unix(),
496 Comment: "dynamic metainfo from client",
497 CreatedBy: "go.torrent",
498 AnnounceList: t.announceList(),
502 func (t *torrent) bytesLeft() (left int64) {
506 for i := 0; i < t.numPieces(); i++ {
507 left += int64(t.pieceNumPendingBytes(i))
512 func (t *torrent) piecePartiallyDownloaded(index int) bool {
513 pendingBytes := t.pieceNumPendingBytes(index)
514 return pendingBytes != 0 && pendingBytes != t.pieceLength(index)
517 func numChunksForPiece(chunkSize int, pieceSize int) int {
518 return (pieceSize + chunkSize - 1) / chunkSize
521 func (t *torrent) usualPieceSize() int {
522 return int(t.Info.PieceLength)
525 func (t *torrent) lastPieceSize() int {
526 return int(t.pieceLength(t.numPieces() - 1))
529 func (t *torrent) numPieces() int {
530 return t.Info.NumPieces()
533 func (t *torrent) numPiecesCompleted() (num int) {
534 for i := range iter.N(t.Info.NumPieces()) {
535 if t.pieceComplete(i) {
542 func (t *torrent) Length() int64 {
546 func (t *torrent) isClosed() bool {
555 func (t *torrent) close() (err error) {
561 if c, ok := t.data.(io.Closer); ok {
564 for _, conn := range t.Conns {
567 t.pieceStateChanges.Close()
571 func (t *torrent) requestOffset(r request) int64 {
572 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
575 // Return the request that would include the given offset into the torrent
576 // data. Returns !ok if there is no such request.
577 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
578 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, int64(t.chunkSize), off)
581 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
582 n, err := t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
583 if err == nil && n != len(data) {
584 err = io.ErrShortWrite
589 func (t *torrent) bitfield() (bf []bool) {
590 for i := range t.Pieces {
592 // TODO: Check this logic.
593 bf = append(bf, p.EverHashed && p.numPendingChunks() == 0)
598 func (t *torrent) validOutgoingRequest(r request) bool {
599 if r.Index >= pp.Integer(t.Info.NumPieces()) {
602 if r.Begin%t.chunkSize != 0 {
605 if r.Length > t.chunkSize {
608 pieceLength := t.pieceLength(int(r.Index))
609 if r.Begin+r.Length > pieceLength {
612 return r.Length == t.chunkSize || r.Begin+r.Length == pieceLength
615 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
616 css = make([]chunkSpec, 0, (t.pieceLength(piece)+t.chunkSize-1)/t.chunkSize)
618 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
620 if cs.Length > t.chunkSize {
621 cs.Length = t.chunkSize
623 css = append(css, cs)
624 cs.Begin += cs.Length
629 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
630 piece := &t.Pieces[pieceIndex]
631 if piece.PendingChunkSpecs == nil {
632 // Allocate to exact size.
633 piece.PendingChunkSpecs = make([]bool, (t.pieceLength(pieceIndex)+t.chunkSize-1)/t.chunkSize)
635 // Pend all the chunks.
636 pcss := piece.PendingChunkSpecs
637 for i := range pcss {
648 // Peer is known to support encryption.
649 SupportsEncryption bool
652 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
653 if int(piece) == t.numPieces()-1 {
654 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
657 len_ = pp.Integer(t.Info.PieceLength)
662 func (t *torrent) hashPiece(piece int) (ps pieceSum) {
663 hash := pieceHash.New()
664 p := &t.Pieces[piece]
665 p.pendingWritesMutex.Lock()
666 for p.pendingWrites != 0 {
667 p.noPendingWrites.Wait()
669 p.pendingWritesMutex.Unlock()
670 pl := t.Info.Piece(int(piece)).Length()
671 n, err := t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, pl)
673 if err != io.ErrUnexpectedEOF {
674 log.Printf("error hashing piece with %T: %s", t.data, err)
679 panic(fmt.Sprintf("%T: %d != %d", t.data, n, pl))
681 missinggo.CopyExact(ps[:], hash.Sum(nil))
685 func (t *torrent) haveAllPieces() bool {
689 for i := range t.Pieces {
690 if !t.pieceComplete(i) {
697 func (me *torrent) haveAnyPieces() bool {
698 for i := range me.Pieces {
699 if me.pieceComplete(i) {
706 func (t *torrent) havePiece(index int) bool {
707 return t.haveInfo() && t.pieceComplete(index)
710 func (t *torrent) haveChunk(r request) bool {
714 if t.pieceComplete(int(r.Index)) {
717 p := &t.Pieces[r.Index]
718 if p.PendingChunkSpecs == nil {
721 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
724 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
725 return int(cs.Begin / chunkSize)
728 // TODO: This should probably be called wantPiece.
729 func (t *torrent) wantChunk(r request) bool {
730 if !t.wantPiece(int(r.Index)) {
733 if t.Pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
740 func (t *torrent) urgentChunkInPiece(piece int) bool {
741 p := pp.Integer(piece)
742 for req := range t.urgent {
750 // TODO: This should be called wantPieceIndex.
751 func (t *torrent) wantPiece(index int) bool {
755 p := &t.Pieces[index]
762 if p.Priority == PiecePriorityNone {
763 if !t.urgentChunkInPiece(index) {
767 // Put piece complete check last, since it's the slowest as it can involve
768 // calling out into external data stores.
769 return !t.pieceComplete(index)
772 func (t *torrent) connHasWantedPieces(c *connection) bool {
773 return c.pieceRequestOrder != nil && !c.pieceRequestOrder.Empty()
776 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
777 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
778 pieces = append(pieces, int(i))
783 func (t *torrent) worstBadConn(cl *Client) *connection {
784 wcs := t.worstConns(cl)
787 c := heap.Pop(wcs).(*connection)
788 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
791 if wcs.Len() >= (socketsPerTorrent+1)/2 {
792 // Give connections 1 minute to prove themselves.
793 if time.Since(c.completedHandshake) > time.Minute {
801 func (t *torrent) publishPieceChange(piece int) {
802 cur := t.pieceState(piece)
803 p := &t.Pieces[piece]
804 if cur != p.PublicPieceState {
805 t.pieceStateChanges.Publish(piece)
807 p.PublicPieceState = cur