16 "github.com/anacrolix/missinggo"
17 "github.com/anacrolix/missinggo/bitmap"
18 "github.com/anacrolix/missinggo/itertools"
19 "github.com/anacrolix/missinggo/perf"
20 "github.com/anacrolix/missinggo/pubsub"
21 "github.com/bradfitz/iter"
23 "github.com/anacrolix/torrent/bencode"
24 "github.com/anacrolix/torrent/metainfo"
25 pp "github.com/anacrolix/torrent/peer_protocol"
26 "github.com/anacrolix/torrent/storage"
29 func (t *torrent) chunkIndexSpec(chunkIndex, piece int) chunkSpec {
30 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
33 type peersKey struct {
38 // Maintains state of torrent within a Client.
44 // Closed when no more network activity is desired. This includes
45 // announcing, and communicating with peers.
46 ceasingNetworking chan struct{}
50 // Values are the piece indices that changed.
51 pieceStateChanges *pubsub.PubSub
53 // Total length of the torrent in bytes. Stored because it's not O(1) to
54 // get this from the info dict.
59 // The info dict. Nil if we don't have it (yet).
61 // Active peer connections, running message stream loops.
63 // Set of addrs to which we're attempting to connect. Connections are
64 // half-open until all handshakes are completed.
65 HalfOpen map[string]struct{}
67 // Reserve of peers to connect to. A peer can be both here and in the
68 // active connections if were told about the peer after connecting with
69 // them. That encourages us to reconnect to peers that are well known.
70 Peers map[peersKey]Peer
73 // BEP 12 Multitracker Metadata Extension. The tracker.Client instances
74 // mirror their respective URLs from the announce-list metainfo key.
75 Trackers []trackerTier
76 // Name used if the info name isn't available.
78 // The bencoded bytes of the info dict.
80 // Each element corresponds to the 16KiB metadata pieces. If true, we have
81 // received that piece.
84 // Closed when .Info is set.
85 gotMetainfo chan struct{}
87 readers map[*Reader]struct{}
89 pendingPieces bitmap.Bitmap
90 completedPieces bitmap.Bitmap
92 connPieceInclinationPool sync.Pool
96 pieceInclinationsReused = expvar.NewInt("pieceInclinationsReused")
97 pieceInclinationsNew = expvar.NewInt("pieceInclinationsNew")
98 pieceInclinationsPut = expvar.NewInt("pieceInclinationsPut")
101 func (t *torrent) setDisplayName(dn string) {
105 func (t *torrent) pieceComplete(piece int) bool {
106 return t.completedPieces.Get(piece)
109 func (t *torrent) pieceCompleteUncached(piece int) bool {
110 return t.Pieces[piece].Storage().GetIsComplete()
113 func (t *torrent) numConnsUnchoked() (num int) {
114 for _, c := range t.Conns {
122 // There's a connection to that address already.
123 func (t *torrent) addrActive(addr string) bool {
124 if _, ok := t.HalfOpen[addr]; ok {
127 for _, c := range t.Conns {
128 if c.remoteAddr().String() == addr {
135 func (t *torrent) worstConns(cl *Client) (wcs *worstConns) {
137 c: make([]*connection, 0, len(t.Conns)),
141 for _, c := range t.Conns {
142 if !c.closed.IsSet() {
143 wcs.c = append(wcs.c, c)
149 func (t *torrent) ceaseNetworking() {
151 case <-t.ceasingNetworking:
155 close(t.ceasingNetworking)
156 for _, c := range t.Conns {
161 func (t *torrent) addPeer(p Peer, cl *Client) {
163 if len(t.Peers) >= torrentPeersHighWater {
166 key := peersKey{string(p.IP), p.Port}
167 if _, ok := t.Peers[key]; ok {
171 peersAddedBySource.Add(string(p.Source), 1)
176 func (t *torrent) invalidateMetadata() {
182 func (t *torrent) saveMetadataPiece(index int, data []byte) {
186 if index >= len(t.metadataHave) {
187 log.Printf("%s: ignoring metadata piece %d", t, index)
190 copy(t.MetaData[(1<<14)*index:], data)
191 t.metadataHave[index] = true
194 func (t *torrent) metadataPieceCount() int {
195 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
198 func (t *torrent) haveMetadataPiece(piece int) bool {
200 return (1<<14)*piece < len(t.MetaData)
202 return piece < len(t.metadataHave) && t.metadataHave[piece]
206 func (t *torrent) metadataSizeKnown() bool {
207 return t.MetaData != nil
210 func (t *torrent) metadataSize() int {
211 return len(t.MetaData)
214 func infoPieceHashes(info *metainfo.Info) (ret []string) {
215 for i := 0; i < len(info.Pieces); i += 20 {
216 ret = append(ret, string(info.Pieces[i:i+20]))
221 // Called when metadata for a torrent becomes available.
222 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte) (err error) {
223 err = validateInfo(md)
225 err = fmt.Errorf("bad info: %s", err)
230 for _, f := range t.Info.UpvertedFiles() {
233 t.MetaData = infoBytes
235 hashes := infoPieceHashes(md)
236 t.Pieces = make([]piece, len(hashes))
237 for i, hash := range hashes {
238 piece := &t.Pieces[i]
241 piece.noPendingWrites.L = &piece.pendingWritesMutex
242 missinggo.CopyExact(piece.Hash[:], hash)
244 for _, conn := range t.Conns {
245 if err := conn.setNumPieces(t.numPieces()); err != nil {
246 log.Printf("closing connection: %s", err)
250 for i := range t.Pieces {
251 t.updatePieceCompletion(i)
252 t.Pieces[i].QueuedForHash = true
255 for i := range t.Pieces {
262 func (t *torrent) verifyPiece(piece int) {
263 t.cl.verifyPiece(t, piece)
266 func (t *torrent) haveAllMetadataPieces() bool {
270 if t.metadataHave == nil {
273 for _, have := range t.metadataHave {
281 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
283 // We already know the correct metadata size.
286 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
287 log.Printf("received bad metadata size: %d", bytes)
290 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
293 t.MetaData = make([]byte, bytes)
294 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
295 for _, c := range t.Conns {
296 cl.requestPendingMetadata(t, c)
301 // The current working name for the torrent. Either the name in the info dict,
302 // or a display name given such as by the dn value in a magnet link, or "".
303 func (t *torrent) Name() string {
310 func (t *torrent) pieceState(index int) (ret PieceState) {
311 p := &t.Pieces[index]
312 ret.Priority = t.piecePriority(index)
313 if t.pieceComplete(index) {
316 if p.QueuedForHash || p.Hashing {
319 if !ret.Complete && t.piecePartiallyDownloaded(index) {
325 func (t *torrent) metadataPieceSize(piece int) int {
326 return metadataPieceSize(len(t.MetaData), piece)
329 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
335 d["total_size"] = len(t.MetaData)
337 p, err := bencode.Marshal(d)
343 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
344 ExtendedPayload: append(p, data...),
348 func (t *torrent) pieceStateRuns() (ret []PieceStateRun) {
349 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
350 ret = append(ret, PieceStateRun{
351 PieceState: el.(PieceState),
355 for index := range t.Pieces {
356 rle.Append(t.pieceState(index), 1)
362 // Produces a small string representing a PieceStateRun.
363 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
364 ret = fmt.Sprintf("%d", psr.Length)
365 ret += func() string {
366 switch psr.Priority {
367 case PiecePriorityNext:
369 case PiecePriorityNormal:
371 case PiecePriorityReadahead:
373 case PiecePriorityNow:
391 func (t *torrent) writeStatus(w io.Writer, cl *Client) {
392 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
393 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
395 fmt.Fprintf(w, "Metadata have: ")
396 for _, h := range t.metadataHave {
397 fmt.Fprintf(w, "%c", func() rune {
407 fmt.Fprintf(w, "Piece length: %s\n", func() string {
409 return fmt.Sprint(t.usualPieceSize())
415 fmt.Fprintf(w, "Num Pieces: %d\n", t.numPieces())
416 fmt.Fprint(w, "Piece States:")
417 for _, psr := range t.pieceStateRuns() {
419 w.Write([]byte(pieceStateRunStatusChars(psr)))
423 fmt.Fprintf(w, "Reader Pieces:")
424 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
425 fmt.Fprintf(w, " %d:%d", begin, end)
429 fmt.Fprintf(w, "Trackers: ")
430 for _, tier := range t.Trackers {
431 for _, tr := range tier {
432 fmt.Fprintf(w, "%q ", tr)
436 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
437 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
438 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
439 sort.Sort(&worstConns{
444 for i, c := range t.Conns {
445 fmt.Fprintf(w, "%2d. ", i+1)
450 func (t *torrent) String() string {
453 s = fmt.Sprintf("%x", t.InfoHash)
458 func (t *torrent) haveInfo() bool {
462 // TODO: Include URIs that weren't converted to tracker clients.
463 func (t *torrent) announceList() (al [][]string) {
464 missinggo.CastSlice(&al, t.Trackers)
468 // Returns a run-time generated MetaInfo that includes the info bytes and
469 // announce-list as currently known to the client.
470 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
471 if t.MetaData == nil {
472 panic("info bytes not set")
474 return &metainfo.MetaInfo{
475 Info: metainfo.InfoEx{
479 CreationDate: time.Now().Unix(),
480 Comment: "dynamic metainfo from client",
481 CreatedBy: "go.torrent",
482 AnnounceList: t.announceList(),
486 func (t *torrent) bytesLeft() (left int64) {
487 for i := 0; i < t.numPieces(); i++ {
488 left += int64(t.Pieces[i].bytesLeft())
493 // Bytes left to give in tracker announces.
494 func (t *torrent) bytesLeftAnnounce() uint64 {
496 return uint64(t.bytesLeft())
498 return math.MaxUint64
502 func (t *torrent) piecePartiallyDownloaded(piece int) bool {
503 if t.pieceComplete(piece) {
506 if t.pieceAllDirty(piece) {
509 return t.Pieces[piece].hasDirtyChunks()
512 func numChunksForPiece(chunkSize int, pieceSize int) int {
513 return (pieceSize + chunkSize - 1) / chunkSize
516 func (t *torrent) usualPieceSize() int {
517 return int(t.Info.PieceLength)
520 func (t *torrent) lastPieceSize() int {
521 return int(t.pieceLength(t.numPieces() - 1))
524 func (t *torrent) numPieces() int {
525 return t.Info.NumPieces()
528 func (t *torrent) numPiecesCompleted() (num int) {
529 return t.completedPieces.Len()
532 // Safe to call with or without client lock.
533 func (t *torrent) isClosed() bool {
542 func (t *torrent) close() (err error) {
548 if c, ok := t.storage.(io.Closer); ok {
551 for _, conn := range t.Conns {
554 t.pieceStateChanges.Close()
558 func (t *torrent) requestOffset(r request) int64 {
559 return torrentRequestOffset(t.length, int64(t.usualPieceSize()), r)
562 // Return the request that would include the given offset into the torrent
563 // data. Returns !ok if there is no such request.
564 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
565 return torrentOffsetRequest(t.length, t.Info.PieceLength, int64(t.chunkSize), off)
568 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
569 tr := perf.NewTimer()
571 n, err := t.Pieces[piece].Storage().WriteAt(data, begin)
572 if err == nil && n != len(data) {
573 err = io.ErrShortWrite
576 tr.Stop("write chunk")
581 func (t *torrent) bitfield() (bf []bool) {
582 bf = make([]bool, t.numPieces())
583 t.completedPieces.IterTyped(func(piece int) (again bool) {
590 func (t *torrent) validOutgoingRequest(r request) bool {
591 if r.Index >= pp.Integer(t.Info.NumPieces()) {
594 if r.Begin%t.chunkSize != 0 {
597 if r.Length > t.chunkSize {
600 pieceLength := t.pieceLength(int(r.Index))
601 if r.Begin+r.Length > pieceLength {
604 return r.Length == t.chunkSize || r.Begin+r.Length == pieceLength
607 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
608 css = make([]chunkSpec, 0, (t.pieceLength(piece)+t.chunkSize-1)/t.chunkSize)
610 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
612 if cs.Length > t.chunkSize {
613 cs.Length = t.chunkSize
615 css = append(css, cs)
616 cs.Begin += cs.Length
621 func (t *torrent) pieceNumChunks(piece int) int {
622 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
625 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
626 t.Pieces[pieceIndex].DirtyChunks.Clear()
634 // Peer is known to support encryption.
635 SupportsEncryption bool
638 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
639 if piece < 0 || piece >= t.Info.NumPieces() {
642 if int(piece) == t.numPieces()-1 {
643 len_ = pp.Integer(t.length % t.Info.PieceLength)
646 len_ = pp.Integer(t.Info.PieceLength)
651 func (t *torrent) hashPiece(piece int) (ret pieceSum) {
652 hash := pieceHash.New()
653 p := &t.Pieces[piece]
654 p.waitNoPendingWrites()
655 ip := t.Info.Piece(piece)
657 n, err := io.Copy(hash, io.NewSectionReader(t.Pieces[piece].Storage(), 0, pl))
659 missinggo.CopyExact(&ret, hash.Sum(nil))
662 if err != io.ErrUnexpectedEOF {
663 log.Printf("unexpected error hashing piece with %T: %s", t.storage, err)
668 func (t *torrent) haveAllPieces() bool {
672 return t.completedPieces.Len() == t.numPieces()
675 func (me *torrent) haveAnyPieces() bool {
676 for i := range me.Pieces {
677 if me.pieceComplete(i) {
684 func (t *torrent) havePiece(index int) bool {
685 return t.haveInfo() && t.pieceComplete(index)
688 func (t *torrent) haveChunk(r request) (ret bool) {
690 // log.Println("have chunk", r, ret)
695 if t.pieceComplete(int(r.Index)) {
698 p := &t.Pieces[r.Index]
699 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
702 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
703 return int(cs.Begin / chunkSize)
706 // TODO: This should probably be called wantPiece.
707 func (t *torrent) wantChunk(r request) bool {
708 if !t.wantPiece(int(r.Index)) {
711 if t.Pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
714 // TODO: What about pieces that were wanted, but aren't now, and aren't
715 // completed either? That used to be done here.
719 // TODO: This should be called wantPieceIndex.
720 func (t *torrent) wantPiece(index int) bool {
724 p := &t.Pieces[index]
731 if t.pieceComplete(index) {
734 if t.pendingPieces.Contains(index) {
737 return !t.forReaderOffsetPieces(func(begin, end int) bool {
738 return index < begin || index >= end
742 func (t *torrent) forNeededPieces(f func(piece int) (more bool)) (all bool) {
743 return t.forReaderOffsetPieces(func(begin, end int) (more bool) {
744 for i := begin; begin < end; i++ {
753 func (t *torrent) connHasWantedPieces(c *connection) bool {
754 return !c.pieceRequestOrder.IsEmpty()
757 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
758 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
759 pieces = append(pieces, int(i))
764 func (t *torrent) worstBadConn(cl *Client) *connection {
765 wcs := t.worstConns(cl)
768 c := heap.Pop(wcs).(*connection)
769 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
772 if wcs.Len() >= (socketsPerTorrent+1)/2 {
773 // Give connections 1 minute to prove themselves.
774 if time.Since(c.completedHandshake) > time.Minute {
782 type PieceStateChange struct {
787 func (t *torrent) publishPieceChange(piece int) {
788 cur := t.pieceState(piece)
789 p := &t.Pieces[piece]
790 if cur != p.PublicPieceState {
791 p.PublicPieceState = cur
792 t.pieceStateChanges.Publish(PieceStateChange{
799 func (t *torrent) pieceNumPendingChunks(piece int) int {
800 if t.pieceComplete(piece) {
803 return t.pieceNumChunks(piece) - t.Pieces[piece].numDirtyChunks()
806 func (t *torrent) pieceAllDirty(piece int) bool {
807 return t.Pieces[piece].DirtyChunks.Len() == t.pieceNumChunks(piece)
810 func (t *torrent) forUrgentPieces(f func(piece int) (again bool)) (all bool) {
811 return t.forReaderOffsetPieces(func(begin, end int) (again bool) {
821 func (t *torrent) readersChanged() {
822 t.updatePiecePriorities()
825 func (t *torrent) maybeNewConns() {
826 // Tickle the accept routine.
827 t.cl.event.Broadcast()
831 func (t *torrent) piecePriorityChanged(piece int) {
832 for _, c := range t.Conns {
833 c.updatePiecePriority(piece)
836 t.publishPieceChange(piece)
839 func (t *torrent) updatePiecePriority(piece int) bool {
840 p := &t.Pieces[piece]
841 newPrio := t.piecePriorityUncached(piece)
842 if newPrio == p.priority {
849 // Update all piece priorities in one hit. This function should have the same
850 // output as updatePiecePriority, but across all pieces.
851 func (t *torrent) updatePiecePriorities() {
852 newPrios := make([]piecePriority, t.numPieces())
853 t.pendingPieces.IterTyped(func(piece int) (more bool) {
854 newPrios[piece] = PiecePriorityNormal
857 t.forReaderOffsetPieces(func(begin, end int) (next bool) {
859 newPrios[begin].Raise(PiecePriorityNow)
861 for i := begin + 1; i < end; i++ {
862 newPrios[i].Raise(PiecePriorityReadahead)
866 t.completedPieces.IterTyped(func(piece int) (more bool) {
867 newPrios[piece] = PiecePriorityNone
870 for i, prio := range newPrios {
871 if prio != t.Pieces[i].priority {
872 t.Pieces[i].priority = prio
873 t.piecePriorityChanged(i)
878 func (t *torrent) byteRegionPieces(off, size int64) (begin, end int) {
889 begin = int(off / t.Info.PieceLength)
890 end = int((off + size + t.Info.PieceLength - 1) / t.Info.PieceLength)
891 if end > t.Info.NumPieces() {
892 end = t.Info.NumPieces()
897 // Returns true if all iterations complete without breaking.
898 func (t *torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
899 // There's an oppurtunity here to build a map of beginning pieces, and a
900 // bitmap of the rest. I wonder if it's worth the allocation overhead.
901 for r := range t.readers {
903 pos, readahead := r.pos, r.readahead
908 begin, end := t.byteRegionPieces(pos, readahead)
919 func (t *torrent) piecePriority(piece int) piecePriority {
921 return PiecePriorityNone
923 return t.Pieces[piece].priority
926 func (t *torrent) piecePriorityUncached(piece int) (ret piecePriority) {
927 ret = PiecePriorityNone
928 if t.pieceComplete(piece) {
931 if t.pendingPieces.Contains(piece) {
932 ret = PiecePriorityNormal
934 raiseRet := ret.Raise
935 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
937 raiseRet(PiecePriorityNow)
939 if begin <= piece && piece < end {
940 raiseRet(PiecePriorityReadahead)
947 func (t *torrent) pendPiece(piece int) {
948 if t.pendingPieces.Contains(piece) {
951 if t.havePiece(piece) {
954 t.pendingPieces.Add(piece)
955 if !t.updatePiecePriority(piece) {
958 t.piecePriorityChanged(piece)
961 func (t *torrent) getCompletedPieces() (ret bitmap.Bitmap) {
962 return t.completedPieces.Copy()
965 func (t *torrent) unpendPieces(unpend *bitmap.Bitmap) {
966 t.pendingPieces.Sub(unpend)
967 t.updatePiecePriorities()
970 func (t *torrent) pendPieceRange(begin, end int) {
971 for i := begin; i < end; i++ {
976 func (t *torrent) unpendPieceRange(begin, end int) {
978 bm.AddRange(begin, end)
982 func (t *torrent) connRequestPiecePendingChunks(c *connection, piece int) (more bool) {
983 if !c.PeerHasPiece(piece) {
986 chunkIndices := t.Pieces[piece].undirtiedChunkIndices().ToSortedSlice()
987 return itertools.ForPerm(len(chunkIndices), func(i int) bool {
988 req := request{pp.Integer(piece), t.chunkIndexSpec(chunkIndices[i], piece)}
989 return c.Request(req)
993 func (t *torrent) pendRequest(req request) {
994 ci := chunkIndex(req.chunkSpec, t.chunkSize)
995 t.Pieces[req.Index].pendChunkIndex(ci)
998 func (t *torrent) pieceChanged(piece int) {
999 t.cl.pieceChanged(t, piece)
1002 func (t *torrent) openNewConns() {
1003 t.cl.openNewConns(t)
1006 func (t *torrent) getConnPieceInclination() []int {
1007 _ret := t.connPieceInclinationPool.Get()
1009 pieceInclinationsNew.Add(1)
1010 return rand.Perm(t.numPieces())
1012 pieceInclinationsReused.Add(1)
1016 func (t *torrent) putPieceInclination(pi []int) {
1017 t.connPieceInclinationPool.Put(pi)
1018 pieceInclinationsPut.Add(1)
1021 func (t *torrent) updatePieceCompletion(piece int) {
1022 t.completedPieces.Set(piece, t.pieceCompleteUncached(piece))
1025 // Non-blocking read. Client lock is not required.
1026 func (t *torrent) readAt(b []byte, off int64) (n int, err error) {
1027 p := &t.Pieces[off/t.Info.PieceLength]
1028 p.waitNoPendingWrites()
1029 return p.Storage().ReadAt(b, off-p.Info().Offset())
1032 func (t *torrent) updateAllPieceCompletions() {
1033 for i := range iter.N(t.numPieces()) {
1034 t.updatePieceCompletion(i)