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"
28 func (t *torrent) chunkIndexSpec(chunkIndex, piece int) chunkSpec {
29 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
32 type peersKey struct {
37 // Maintains state of torrent within a Client.
43 // Closed when no more network activity is desired. This includes
44 // announcing, and communicating with peers.
45 ceasingNetworking chan struct{}
49 // Values are the piece indices that changed.
50 pieceStateChanges *pubsub.PubSub
52 // Total length of the torrent in bytes. Stored because it's not O(1) to
53 // get this from the info dict.
58 // The info dict. Nil if we don't have it (yet).
60 // Active peer connections, running message stream loops.
62 // Set of addrs to which we're attempting to connect. Connections are
63 // half-open until all handshakes are completed.
64 HalfOpen map[string]struct{}
66 // Reserve of peers to connect to. A peer can be both here and in the
67 // active connections if were told about the peer after connecting with
68 // them. That encourages us to reconnect to peers that are well known.
69 Peers map[peersKey]Peer
72 // BEP 12 Multitracker Metadata Extension. The tracker.Client instances
73 // mirror their respective URLs from the announce-list metainfo key.
74 Trackers []trackerTier
75 // Name used if the info name isn't available.
77 // The bencoded bytes of the info dict.
79 // Each element corresponds to the 16KiB metadata pieces. If true, we have
80 // received that piece.
83 // Closed when .Info is set.
84 gotMetainfo chan struct{}
86 readers map[*Reader]struct{}
88 pendingPieces bitmap.Bitmap
89 completedPieces bitmap.Bitmap
91 connPieceInclinationPool sync.Pool
95 pieceInclinationsReused = expvar.NewInt("pieceInclinationsReused")
96 pieceInclinationsNew = expvar.NewInt("pieceInclinationsNew")
97 pieceInclinationsPut = expvar.NewInt("pieceInclinationsPut")
100 func (t *torrent) setDisplayName(dn string) {
104 func (t *torrent) pieceComplete(piece int) bool {
105 return t.completedPieces.Get(piece)
108 func (t *torrent) pieceCompleteUncached(piece int) bool {
109 // TODO: This is called when setting metadata, and before storage is
110 // assigned, which doesn't seem right.
111 return t.data != nil && t.data.PieceComplete(piece)
114 func (t *torrent) numConnsUnchoked() (num int) {
115 for _, c := range t.Conns {
123 // There's a connection to that address already.
124 func (t *torrent) addrActive(addr string) bool {
125 if _, ok := t.HalfOpen[addr]; ok {
128 for _, c := range t.Conns {
129 if c.remoteAddr().String() == addr {
136 func (t *torrent) worstConns(cl *Client) (wcs *worstConns) {
138 c: make([]*connection, 0, len(t.Conns)),
142 for _, c := range t.Conns {
143 if !c.closed.IsSet() {
144 wcs.c = append(wcs.c, c)
150 func (t *torrent) ceaseNetworking() {
152 case <-t.ceasingNetworking:
156 close(t.ceasingNetworking)
157 for _, c := range t.Conns {
162 func (t *torrent) addPeer(p Peer, cl *Client) {
164 if len(t.Peers) >= torrentPeersHighWater {
167 key := peersKey{string(p.IP), p.Port}
168 if _, ok := t.Peers[key]; ok {
172 peersAddedBySource.Add(string(p.Source), 1)
177 func (t *torrent) invalidateMetadata() {
183 func (t *torrent) saveMetadataPiece(index int, data []byte) {
187 if index >= len(t.metadataHave) {
188 log.Printf("%s: ignoring metadata piece %d", t, index)
191 copy(t.MetaData[(1<<14)*index:], data)
192 t.metadataHave[index] = true
195 func (t *torrent) metadataPieceCount() int {
196 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
199 func (t *torrent) haveMetadataPiece(piece int) bool {
201 return (1<<14)*piece < len(t.MetaData)
203 return piece < len(t.metadataHave) && t.metadataHave[piece]
207 func (t *torrent) metadataSizeKnown() bool {
208 return t.MetaData != nil
211 func (t *torrent) metadataSize() int {
212 return len(t.MetaData)
215 func infoPieceHashes(info *metainfo.Info) (ret []string) {
216 for i := 0; i < len(info.Pieces); i += 20 {
217 ret = append(ret, string(info.Pieces[i:i+20]))
222 // Called when metadata for a torrent becomes available.
223 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte) (err error) {
224 err = validateInfo(md)
226 err = fmt.Errorf("bad info: %s", err)
231 for _, f := range t.Info.UpvertedFiles() {
234 t.MetaData = infoBytes
236 hashes := infoPieceHashes(md)
237 t.Pieces = make([]piece, len(hashes))
238 for i, hash := range hashes {
239 piece := &t.Pieces[i]
242 piece.noPendingWrites.L = &piece.pendingWritesMutex
243 missinggo.CopyExact(piece.Hash[:], hash)
245 for _, conn := range t.Conns {
246 if err := conn.setNumPieces(t.numPieces()); err != nil {
247 log.Printf("closing connection: %s", err)
254 func (t *torrent) setStorage(td Data) {
259 for i := range t.Pieces {
260 t.updatePieceCompletion(i)
261 t.Pieces[i].QueuedForHash = true
264 for i := range t.Pieces {
270 func (t *torrent) verifyPiece(piece int) {
271 t.cl.verifyPiece(t, piece)
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 = t.piecePriority(index)
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, "Reader Pieces:")
432 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
433 fmt.Fprintf(w, " %d:%d", begin, end)
437 fmt.Fprintf(w, "Trackers: ")
438 for _, tier := range t.Trackers {
439 for _, tr := range tier {
440 fmt.Fprintf(w, "%q ", tr)
444 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
445 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
446 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
447 sort.Sort(&worstConns{
452 for i, c := range t.Conns {
453 fmt.Fprintf(w, "%2d. ", i+1)
458 func (t *torrent) String() string {
461 s = fmt.Sprintf("%x", t.InfoHash)
466 func (t *torrent) haveInfo() bool {
470 // TODO: Include URIs that weren't converted to tracker clients.
471 func (t *torrent) announceList() (al [][]string) {
472 missinggo.CastSlice(&al, t.Trackers)
476 // Returns a run-time generated MetaInfo that includes the info bytes and
477 // announce-list as currently known to the client.
478 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
479 if t.MetaData == nil {
480 panic("info bytes not set")
482 return &metainfo.MetaInfo{
483 Info: metainfo.InfoEx{
487 CreationDate: time.Now().Unix(),
488 Comment: "dynamic metainfo from client",
489 CreatedBy: "go.torrent",
490 AnnounceList: t.announceList(),
494 func (t *torrent) bytesLeft() (left int64) {
495 for i := 0; i < t.numPieces(); i++ {
496 left += int64(t.Pieces[i].bytesLeft())
501 // Bytes left to give in tracker announces.
502 func (t *torrent) bytesLeftAnnounce() uint64 {
504 return uint64(t.bytesLeft())
506 return math.MaxUint64
510 func (t *torrent) piecePartiallyDownloaded(piece int) bool {
511 if t.pieceComplete(piece) {
514 if t.pieceAllDirty(piece) {
517 return t.Pieces[piece].hasDirtyChunks()
520 func numChunksForPiece(chunkSize int, pieceSize int) int {
521 return (pieceSize + chunkSize - 1) / chunkSize
524 func (t *torrent) usualPieceSize() int {
525 return int(t.Info.PieceLength)
528 func (t *torrent) lastPieceSize() int {
529 return int(t.pieceLength(t.numPieces() - 1))
532 func (t *torrent) numPieces() int {
533 return t.Info.NumPieces()
536 func (t *torrent) numPiecesCompleted() (num int) {
537 return t.completedPieces.Len()
540 // Safe to call with or without client lock.
541 func (t *torrent) isClosed() bool {
550 func (t *torrent) close() (err error) {
556 if c, ok := t.data.(io.Closer); ok {
559 for _, conn := range t.Conns {
562 t.pieceStateChanges.Close()
566 func (t *torrent) requestOffset(r request) int64 {
567 return torrentRequestOffset(t.length, int64(t.usualPieceSize()), r)
570 // Return the request that would include the given offset into the torrent
571 // data. Returns !ok if there is no such request.
572 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
573 return torrentOffsetRequest(t.length, t.Info.PieceLength, int64(t.chunkSize), off)
576 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
577 tr := perf.NewTimer()
578 n, err := t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
579 if err == nil && n != len(data) {
580 err = io.ErrShortWrite
583 tr.Stop("write chunk")
588 func (t *torrent) bitfield() (bf []bool) {
589 bf = make([]bool, t.numPieces())
590 t.completedPieces.IterTyped(func(piece int) (again bool) {
597 func (t *torrent) validOutgoingRequest(r request) bool {
598 if r.Index >= pp.Integer(t.Info.NumPieces()) {
601 if r.Begin%t.chunkSize != 0 {
604 if r.Length > t.chunkSize {
607 pieceLength := t.pieceLength(int(r.Index))
608 if r.Begin+r.Length > pieceLength {
611 return r.Length == t.chunkSize || r.Begin+r.Length == pieceLength
614 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
615 css = make([]chunkSpec, 0, (t.pieceLength(piece)+t.chunkSize-1)/t.chunkSize)
617 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
619 if cs.Length > t.chunkSize {
620 cs.Length = t.chunkSize
622 css = append(css, cs)
623 cs.Begin += cs.Length
628 func (t *torrent) pieceNumChunks(piece int) int {
629 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
632 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
633 t.Pieces[pieceIndex].DirtyChunks.Clear()
641 // Peer is known to support encryption.
642 SupportsEncryption bool
645 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
646 if piece < 0 || piece >= t.Info.NumPieces() {
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 int) (ret pieceSum) {
659 hash := pieceHash.New()
660 p := &t.Pieces[piece]
661 p.waitNoPendingWrites()
662 ip := t.Info.Piece(piece)
664 n, err := io.Copy(hash, io.NewSectionReader(t.data, ip.Offset(), pl))
666 missinggo.CopyExact(&ret, hash.Sum(nil))
669 if err != io.ErrUnexpectedEOF {
670 log.Printf("unexpected error hashing piece with %T: %s", t.data, err)
675 func (t *torrent) haveAllPieces() bool {
679 return t.completedPieces.Len() == t.numPieces()
682 func (me *torrent) haveAnyPieces() bool {
683 for i := range me.Pieces {
684 if me.pieceComplete(i) {
691 func (t *torrent) havePiece(index int) bool {
692 return t.haveInfo() && t.pieceComplete(index)
695 func (t *torrent) haveChunk(r request) (ret bool) {
697 // log.Println("have chunk", r, ret)
702 if t.pieceComplete(int(r.Index)) {
705 p := &t.Pieces[r.Index]
706 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
709 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
710 return int(cs.Begin / chunkSize)
713 // TODO: This should probably be called wantPiece.
714 func (t *torrent) wantChunk(r request) bool {
715 if !t.wantPiece(int(r.Index)) {
718 if t.Pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
721 // TODO: What about pieces that were wanted, but aren't now, and aren't
722 // completed either? That used to be done here.
726 // TODO: This should be called wantPieceIndex.
727 func (t *torrent) wantPiece(index int) bool {
731 p := &t.Pieces[index]
738 if t.pieceComplete(index) {
741 if t.pendingPieces.Contains(index) {
744 return !t.forReaderOffsetPieces(func(begin, end int) bool {
745 return index < begin || index >= end
749 func (t *torrent) forNeededPieces(f func(piece int) (more bool)) (all bool) {
750 return t.forReaderOffsetPieces(func(begin, end int) (more bool) {
751 for i := begin; begin < end; i++ {
760 func (t *torrent) connHasWantedPieces(c *connection) bool {
761 return !c.pieceRequestOrder.IsEmpty()
764 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
765 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
766 pieces = append(pieces, int(i))
771 func (t *torrent) worstBadConn(cl *Client) *connection {
772 wcs := t.worstConns(cl)
775 c := heap.Pop(wcs).(*connection)
776 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
779 if wcs.Len() >= (socketsPerTorrent+1)/2 {
780 // Give connections 1 minute to prove themselves.
781 if time.Since(c.completedHandshake) > time.Minute {
789 type PieceStateChange struct {
794 func (t *torrent) publishPieceChange(piece int) {
795 cur := t.pieceState(piece)
796 p := &t.Pieces[piece]
797 if cur != p.PublicPieceState {
798 p.PublicPieceState = cur
799 t.pieceStateChanges.Publish(PieceStateChange{
806 func (t *torrent) pieceNumPendingChunks(piece int) int {
807 if t.pieceComplete(piece) {
810 return t.pieceNumChunks(piece) - t.Pieces[piece].numDirtyChunks()
813 func (t *torrent) pieceAllDirty(piece int) bool {
814 return t.Pieces[piece].DirtyChunks.Len() == t.pieceNumChunks(piece)
817 func (t *torrent) forUrgentPieces(f func(piece int) (again bool)) (all bool) {
818 return t.forReaderOffsetPieces(func(begin, end int) (again bool) {
828 func (t *torrent) readersChanged() {
829 t.updatePiecePriorities()
832 func (t *torrent) maybeNewConns() {
833 // Tickle the accept routine.
834 t.cl.event.Broadcast()
838 func (t *torrent) piecePriorityChanged(piece int) {
839 for _, c := range t.Conns {
840 c.updatePiecePriority(piece)
843 t.publishPieceChange(piece)
846 func (t *torrent) updatePiecePriority(piece int) bool {
847 p := &t.Pieces[piece]
848 newPrio := t.piecePriorityUncached(piece)
849 if newPrio == p.priority {
856 // Update all piece priorities in one hit. This function should have the same
857 // output as updatePiecePriority, but across all pieces.
858 func (t *torrent) updatePiecePriorities() {
859 newPrios := make([]piecePriority, t.numPieces())
860 t.pendingPieces.IterTyped(func(piece int) (more bool) {
861 newPrios[piece] = PiecePriorityNormal
864 t.forReaderOffsetPieces(func(begin, end int) (next bool) {
866 newPrios[begin].Raise(PiecePriorityNow)
868 for i := begin + 1; i < end; i++ {
869 newPrios[i].Raise(PiecePriorityReadahead)
873 t.completedPieces.IterTyped(func(piece int) (more bool) {
874 newPrios[piece] = PiecePriorityNone
877 for i, prio := range newPrios {
878 if prio != t.Pieces[i].priority {
879 t.Pieces[i].priority = prio
880 t.piecePriorityChanged(i)
885 func (t *torrent) byteRegionPieces(off, size int64) (begin, end int) {
896 begin = int(off / t.Info.PieceLength)
897 end = int((off + size + t.Info.PieceLength - 1) / t.Info.PieceLength)
898 if end > t.Info.NumPieces() {
899 end = t.Info.NumPieces()
904 // Returns true if all iterations complete without breaking.
905 func (t *torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
906 // There's an oppurtunity here to build a map of beginning pieces, and a
907 // bitmap of the rest. I wonder if it's worth the allocation overhead.
908 for r := range t.readers {
910 pos, readahead := r.pos, r.readahead
915 begin, end := t.byteRegionPieces(pos, readahead)
926 func (t *torrent) piecePriority(piece int) piecePriority {
928 return PiecePriorityNone
930 return t.Pieces[piece].priority
933 func (t *torrent) piecePriorityUncached(piece int) (ret piecePriority) {
934 ret = PiecePriorityNone
935 if t.pieceComplete(piece) {
938 if t.pendingPieces.Contains(piece) {
939 ret = PiecePriorityNormal
941 raiseRet := ret.Raise
942 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
944 raiseRet(PiecePriorityNow)
946 if begin <= piece && piece < end {
947 raiseRet(PiecePriorityReadahead)
954 func (t *torrent) pendPiece(piece int) {
955 if t.pendingPieces.Contains(piece) {
958 if t.havePiece(piece) {
961 t.pendingPieces.Add(piece)
962 if !t.updatePiecePriority(piece) {
965 t.piecePriorityChanged(piece)
968 func (t *torrent) getCompletedPieces() (ret bitmap.Bitmap) {
969 return t.completedPieces.Copy()
972 func (t *torrent) unpendPieces(unpend *bitmap.Bitmap) {
973 t.pendingPieces.Sub(unpend)
974 t.updatePiecePriorities()
977 func (t *torrent) pendPieceRange(begin, end int) {
978 for i := begin; i < end; i++ {
983 func (t *torrent) unpendPieceRange(begin, end int) {
985 bm.AddRange(begin, end)
989 func (t *torrent) connRequestPiecePendingChunks(c *connection, piece int) (more bool) {
990 if !c.PeerHasPiece(piece) {
993 chunkIndices := t.Pieces[piece].undirtiedChunkIndices().ToSortedSlice()
994 return itertools.ForPerm(len(chunkIndices), func(i int) bool {
995 req := request{pp.Integer(piece), t.chunkIndexSpec(chunkIndices[i], piece)}
996 return c.Request(req)
1000 func (t *torrent) pendRequest(req request) {
1001 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1002 t.Pieces[req.Index].pendChunkIndex(ci)
1005 func (t *torrent) pieceChanged(piece int) {
1006 t.cl.pieceChanged(t, piece)
1009 func (t *torrent) openNewConns() {
1010 t.cl.openNewConns(t)
1013 func (t *torrent) getConnPieceInclination() []int {
1014 _ret := t.connPieceInclinationPool.Get()
1016 pieceInclinationsNew.Add(1)
1017 return rand.Perm(t.numPieces())
1019 pieceInclinationsReused.Add(1)
1023 func (t *torrent) putPieceInclination(pi []int) {
1024 t.connPieceInclinationPool.Put(pi)
1025 pieceInclinationsPut.Add(1)
1028 func (t *torrent) updatePieceCompletion(piece int) {
1029 t.completedPieces.Set(piece, t.pieceCompleteUncached(piece))
1032 // Non-blocking read. Client lock is not required.
1033 func (t *torrent) readAt(b []byte, off int64) (n int, err error) {
1034 if off+int64(len(b)) > t.length {
1035 b = b[:t.length-off]
1037 for pi := off / t.Info.PieceLength; pi*t.Info.PieceLength < off+int64(len(b)); pi++ {
1038 t.Pieces[pi].waitNoPendingWrites()
1040 return t.data.ReadAt(b, off)
1043 func (t *torrent) updateAllPieceCompletions() {
1044 for i := range iter.N(t.numPieces()) {
1045 t.updatePieceCompletion(i)