15 "github.com/anacrolix/missinggo"
16 "github.com/anacrolix/missinggo/bitmap"
17 "github.com/anacrolix/missinggo/itertools"
18 "github.com/anacrolix/missinggo/perf"
19 "github.com/anacrolix/missinggo/pubsub"
20 "github.com/bradfitz/iter"
22 "github.com/anacrolix/torrent/bencode"
23 "github.com/anacrolix/torrent/metainfo"
24 pp "github.com/anacrolix/torrent/peer_protocol"
25 "github.com/anacrolix/torrent/tracker"
28 func (t *torrent) chunkIndexSpec(chunkIndex, piece int) chunkSpec {
29 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
32 func (t *torrent) pieceNumPendingBytes(index int) (count pp.Integer) {
33 if t.pieceComplete(index) {
36 piece := &t.Pieces[index]
37 count = t.pieceLength(index)
38 if !piece.EverHashed {
41 regularDirty := piece.numDirtyChunks()
42 lastChunkIndex := t.pieceNumChunks(index) - 1
43 if piece.pendingChunkIndex(lastChunkIndex) {
45 count -= t.chunkIndexSpec(lastChunkIndex, index).Length
47 count -= pp.Integer(regularDirty) * t.chunkSize
51 type peersKey struct {
56 // Is not aware of Client. Maintains state of torrent for with-in a Client.
63 // Closed when no more network activity is desired. This includes
64 // announcing, and communicating with peers.
65 ceasingNetworking chan struct{}
69 // Values are the piece indices that changed.
70 pieceStateChanges *pubsub.PubSub
72 // Total length of the torrent in bytes. Stored because it's not O(1) to
73 // get this from the info dict.
78 // The info dict. Nil if we don't have it (yet).
80 // Active peer connections, running message stream loops.
82 // Set of addrs to which we're attempting to connect. Connections are
83 // half-open until all handshakes are completed.
84 HalfOpen map[string]struct{}
86 // Reserve of peers to connect to. A peer can be both here and in the
87 // active connections if were told about the peer after connecting with
88 // them. That encourages us to reconnect to peers that are well known.
89 Peers map[peersKey]Peer
92 // BEP 12 Multitracker Metadata Extension. The tracker.Client instances
93 // mirror their respective URLs from the announce-list metainfo key.
94 Trackers [][]tracker.Client
95 // Name used if the info name isn't available.
97 // The bencoded bytes of the info dict.
99 // Each element corresponds to the 16KiB metadata pieces. If true, we have
100 // received that piece.
103 // Closed when .Info is set.
104 gotMetainfo chan struct{}
106 readers map[*Reader]struct{}
108 pendingPieces bitmap.Bitmap
110 connPieceInclinationPool sync.Pool
114 pieceInclinationsReused = expvar.NewInt("pieceInclinationsReused")
115 pieceInclinationsNew = expvar.NewInt("pieceInclinationsNew")
116 pieceInclinationsPut = expvar.NewInt("pieceInclinationsPut")
119 func (t *torrent) setDisplayName(dn string) {
123 func (t *torrent) pieceComplete(piece int) bool {
124 // TODO: This is called when setting metadata, and before storage is
125 // assigned, which doesn't seem right.
126 return t.data != nil && t.data.PieceComplete(piece)
129 func (t *torrent) numConnsUnchoked() (num int) {
130 for _, c := range t.Conns {
138 // There's a connection to that address already.
139 func (t *torrent) addrActive(addr string) bool {
140 if _, ok := t.HalfOpen[addr]; ok {
143 for _, c := range t.Conns {
144 if c.remoteAddr().String() == addr {
151 func (t *torrent) worstConns(cl *Client) (wcs *worstConns) {
153 c: make([]*connection, 0, len(t.Conns)),
157 for _, c := range t.Conns {
158 if !c.closed.IsSet() {
159 wcs.c = append(wcs.c, c)
165 func (t *torrent) ceaseNetworking() {
167 defer t.stateMu.Unlock()
169 case <-t.ceasingNetworking:
173 close(t.ceasingNetworking)
174 for _, c := range t.Conns {
179 func (t *torrent) addPeer(p Peer, cl *Client) {
181 if len(t.Peers) >= torrentPeersHighWater {
184 key := peersKey{string(p.IP), p.Port}
185 if _, ok := t.Peers[key]; ok {
189 peersAddedBySource.Add(string(p.Source), 1)
194 func (t *torrent) invalidateMetadata() {
200 func (t *torrent) saveMetadataPiece(index int, data []byte) {
204 if index >= len(t.metadataHave) {
205 log.Printf("%s: ignoring metadata piece %d", t, index)
208 copy(t.MetaData[(1<<14)*index:], data)
209 t.metadataHave[index] = true
212 func (t *torrent) metadataPieceCount() int {
213 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
216 func (t *torrent) haveMetadataPiece(piece int) bool {
218 return (1<<14)*piece < len(t.MetaData)
220 return piece < len(t.metadataHave) && t.metadataHave[piece]
224 func (t *torrent) metadataSizeKnown() bool {
225 return t.MetaData != nil
228 func (t *torrent) metadataSize() int {
229 return len(t.MetaData)
232 func infoPieceHashes(info *metainfo.Info) (ret []string) {
233 for i := 0; i < len(info.Pieces); i += 20 {
234 ret = append(ret, string(info.Pieces[i:i+20]))
239 // Called when metadata for a torrent becomes available.
240 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte) (err error) {
241 err = validateInfo(md)
243 err = fmt.Errorf("bad info: %s", err)
248 for _, f := range t.Info.UpvertedFiles() {
251 t.MetaData = infoBytes
253 hashes := infoPieceHashes(md)
254 t.Pieces = make([]piece, len(hashes))
255 for i, hash := range hashes {
256 piece := &t.Pieces[i]
257 piece.noPendingWrites.L = &piece.pendingWritesMutex
258 missinggo.CopyExact(piece.Hash[:], hash)
260 for _, conn := range t.Conns {
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 = t.piecePriority(index)
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, "Reader Pieces:")
435 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
436 fmt.Fprintf(w, " %d:%d", begin, end)
440 fmt.Fprintf(w, "Trackers: ")
441 for _, tier := range t.Trackers {
442 for _, tr := range tier {
443 fmt.Fprintf(w, "%q ", tr.String())
447 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
448 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
449 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
450 sort.Sort(&worstConns{
455 for i, c := range t.Conns {
456 fmt.Fprintf(w, "%2d. ", i+1)
461 func (t *torrent) String() string {
464 s = fmt.Sprintf("%x", t.InfoHash)
469 func (t *torrent) haveInfo() bool {
473 // TODO: Include URIs that weren't converted to tracker clients.
474 func (t *torrent) announceList() (al [][]string) {
475 for _, tier := range t.Trackers {
477 for _, tr := range tier {
478 l = append(l, tr.URL())
485 // Returns a run-time generated MetaInfo that includes the info bytes and
486 // announce-list as currently known to the client.
487 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
488 if t.MetaData == nil {
489 panic("info bytes not set")
491 return &metainfo.MetaInfo{
492 Info: metainfo.InfoEx{
496 CreationDate: time.Now().Unix(),
497 Comment: "dynamic metainfo from client",
498 CreatedBy: "go.torrent",
499 AnnounceList: t.announceList(),
503 func (t *torrent) bytesLeft() (left int64) {
507 for i := 0; i < t.numPieces(); i++ {
508 left += int64(t.pieceNumPendingBytes(i))
513 func (t *torrent) piecePartiallyDownloaded(piece int) bool {
514 if t.pieceComplete(piece) {
517 if t.pieceAllDirty(piece) {
520 return t.Pieces[piece].hasDirtyChunks()
523 func numChunksForPiece(chunkSize int, pieceSize int) int {
524 return (pieceSize + chunkSize - 1) / chunkSize
527 func (t *torrent) usualPieceSize() int {
528 return int(t.Info.PieceLength)
531 func (t *torrent) lastPieceSize() int {
532 return int(t.pieceLength(t.numPieces() - 1))
535 func (t *torrent) numPieces() int {
536 return t.Info.NumPieces()
539 func (t *torrent) numPiecesCompleted() (num int) {
540 for i := range iter.N(t.Info.NumPieces()) {
541 if t.pieceComplete(i) {
548 func (t *torrent) isClosed() bool {
557 func (t *torrent) close() (err error) {
563 if c, ok := t.data.(io.Closer); ok {
566 for _, conn := range t.Conns {
569 t.pieceStateChanges.Close()
573 func (t *torrent) requestOffset(r request) int64 {
574 return torrentRequestOffset(t.length, int64(t.usualPieceSize()), r)
577 // Return the request that would include the given offset into the torrent
578 // data. Returns !ok if there is no such request.
579 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
580 return torrentOffsetRequest(t.length, t.Info.PieceLength, int64(t.chunkSize), off)
583 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
584 tr := perf.NewTimer()
585 n, err := t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
586 if err == nil && n != len(data) {
587 err = io.ErrShortWrite
590 tr.Stop("write chunk")
595 func (t *torrent) bitfield() (bf []bool) {
596 for i := range t.Pieces {
597 bf = append(bf, t.havePiece(i))
602 func (t *torrent) validOutgoingRequest(r request) bool {
603 if r.Index >= pp.Integer(t.Info.NumPieces()) {
606 if r.Begin%t.chunkSize != 0 {
609 if r.Length > t.chunkSize {
612 pieceLength := t.pieceLength(int(r.Index))
613 if r.Begin+r.Length > pieceLength {
616 return r.Length == t.chunkSize || r.Begin+r.Length == pieceLength
619 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
620 css = make([]chunkSpec, 0, (t.pieceLength(piece)+t.chunkSize-1)/t.chunkSize)
622 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
624 if cs.Length > t.chunkSize {
625 cs.Length = t.chunkSize
627 css = append(css, cs)
628 cs.Begin += cs.Length
633 func (t *torrent) pieceNumChunks(piece int) int {
634 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
637 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
638 t.Pieces[pieceIndex].DirtyChunks.Clear()
646 // Peer is known to support encryption.
647 SupportsEncryption bool
650 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
651 if piece < 0 || piece > t.Info.NumPieces() {
654 if int(piece) == t.numPieces()-1 {
655 len_ = pp.Integer(t.length % t.Info.PieceLength)
658 len_ = pp.Integer(t.Info.PieceLength)
663 func (t *torrent) hashPiece(piece int) (ps pieceSum) {
664 hash := pieceHash.New()
665 p := &t.Pieces[piece]
666 p.waitNoPendingWrites()
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) (ret bool) {
709 // log.Println("have chunk", r, ret)
714 if t.pieceComplete(int(r.Index)) {
717 p := &t.Pieces[r.Index]
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) {
733 // TODO: What about pieces that were wanted, but aren't now, and aren't
734 // completed either? That used to be done here.
738 // TODO: This should be called wantPieceIndex.
739 func (t *torrent) wantPiece(index int) bool {
743 p := &t.Pieces[index]
750 if t.pieceComplete(index) {
753 if t.pendingPieces.Contains(index) {
756 return !t.forReaderOffsetPieces(func(begin, end int) bool {
757 return index < begin || index >= end
761 func (t *torrent) forNeededPieces(f func(piece int) (more bool)) (all bool) {
762 return t.forReaderOffsetPieces(func(begin, end int) (more bool) {
763 for i := begin; begin < end; i++ {
772 func (t *torrent) connHasWantedPieces(c *connection) bool {
773 for it := t.pendingPieces.IterTyped(); it.Next(); {
774 if c.PeerHasPiece(it.ValueInt()) {
779 return !t.forReaderOffsetPieces(func(begin, end int) (again bool) {
780 for i := begin; i < end; i++ {
781 if c.PeerHasPiece(i) {
789 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
790 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
791 pieces = append(pieces, int(i))
796 func (t *torrent) worstBadConn(cl *Client) *connection {
797 wcs := t.worstConns(cl)
800 c := heap.Pop(wcs).(*connection)
801 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
804 if wcs.Len() >= (socketsPerTorrent+1)/2 {
805 // Give connections 1 minute to prove themselves.
806 if time.Since(c.completedHandshake) > time.Minute {
814 func (t *torrent) publishPieceChange(piece int) {
815 cur := t.pieceState(piece)
816 p := &t.Pieces[piece]
817 if cur != p.PublicPieceState {
818 t.pieceStateChanges.Publish(piece)
820 p.PublicPieceState = cur
823 func (t *torrent) pieceNumPendingChunks(piece int) int {
824 if t.pieceComplete(piece) {
827 return t.pieceNumChunks(piece) - t.Pieces[piece].numDirtyChunks()
830 func (t *torrent) pieceAllDirty(piece int) bool {
831 return t.Pieces[piece].DirtyChunks.Len() == t.pieceNumChunks(piece)
834 func (t *torrent) forUrgentPieces(f func(piece int) (again bool)) (all bool) {
835 return t.forReaderOffsetPieces(func(begin, end int) (again bool) {
845 func (t *torrent) readersChanged() {
846 t.updatePiecePriorities()
849 func (t *torrent) maybeNewConns() {
850 // Tickle the accept routine.
851 t.cl.event.Broadcast()
855 func (t *torrent) piecePriorityChanged(piece int) {
856 for _, c := range t.Conns {
857 c.updatePiecePriority(piece)
860 t.publishPieceChange(piece)
863 func (t *torrent) updatePiecePriority(piece int) bool {
864 p := &t.Pieces[piece]
865 newPrio := t.piecePriorityUncached(piece)
866 if newPrio == p.priority {
873 func (t *torrent) updatePiecePriorities() {
874 newPrios := make([]piecePriority, t.numPieces())
875 itertools.ForIterable(&t.pendingPieces, func(value interface{}) (next bool) {
876 newPrios[value.(int)] = PiecePriorityNormal
879 t.forReaderOffsetPieces(func(begin, end int) (next bool) {
881 newPrios[begin].Raise(PiecePriorityNow)
883 for i := begin + 1; i < end; i++ {
884 newPrios[i].Raise(PiecePriorityReadahead)
888 // TODO: Do I need a pass suppressing stuff that we already have?
889 for i, prio := range newPrios {
890 if prio != t.Pieces[i].priority {
891 t.Pieces[i].priority = prio
892 t.piecePriorityChanged(i)
897 func (t *torrent) byteRegionPieces(off, size int64) (begin, end int) {
908 begin = int(off / t.Info.PieceLength)
909 end = int((off + size + t.Info.PieceLength - 1) / t.Info.PieceLength)
910 if end > t.Info.NumPieces() {
911 end = t.Info.NumPieces()
916 // Returns true if all iterations complete without breaking.
917 func (t *torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
918 for r := range t.readers {
920 pos, readahead := r.pos, r.readahead
925 begin, end := t.byteRegionPieces(pos, readahead)
936 func (t *torrent) piecePriority(piece int) piecePriority {
938 return PiecePriorityNone
940 return t.Pieces[piece].priority
943 func (t *torrent) piecePriorityUncached(piece int) (ret piecePriority) {
944 ret = PiecePriorityNone
945 if t.pieceComplete(piece) {
948 if t.pendingPieces.Contains(piece) {
949 ret = PiecePriorityNormal
951 raiseRet := ret.Raise
952 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
954 raiseRet(PiecePriorityNow)
956 if begin <= piece && piece < end {
957 raiseRet(PiecePriorityReadahead)
964 func (t *torrent) pendPiece(piece int, cl *Client) {
965 if t.pendingPieces.Contains(piece) {
968 if t.havePiece(piece) {
971 t.pendingPieces.Add(piece)
972 if !t.updatePiecePriority(piece) {
975 t.piecePriorityChanged(piece)
978 func (t *torrent) getCompletedPieces() (ret bitmap.Bitmap) {
979 for i := range iter.N(t.numPieces()) {
980 if t.pieceComplete(i) {
987 func (t *torrent) pendPieces(pend *bitmap.Bitmap) {
988 t.pendingPieces.Union(pend)
989 t.updatePiecePriorities()
992 func (t *torrent) unpendPieces(unpend *bitmap.Bitmap) {
993 t.pendingPieces.Sub(unpend)
994 t.updatePiecePriorities()
997 func (t *torrent) pendPieceRange(begin, end int) {
999 bm.AddRange(begin, end)
1003 func (t *torrent) unpendPieceRange(begin, end int) {
1004 var bm bitmap.Bitmap
1005 bm.AddRange(begin, end)
1009 func (t *torrent) connRequestPiecePendingChunks(c *connection, piece int) (more bool) {
1010 if !c.PeerHasPiece(piece) {
1013 for _, cs := range t.Pieces[piece].shuffledPendingChunkSpecs(t, piece) {
1014 req := request{pp.Integer(piece), cs}
1015 if !c.Request(req) {
1022 func (t *torrent) pendRequest(req request) {
1023 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1024 t.Pieces[req.Index].pendChunkIndex(ci)
1027 func (t *torrent) pieceChanged(piece int) {
1028 t.cl.pieceChanged(t, piece)
1031 func (t *torrent) openNewConns() {
1032 t.cl.openNewConns(t)
1035 func (t *torrent) getConnPieceInclination() []int {
1036 _ret := t.connPieceInclinationPool.Get()
1038 pieceInclinationsNew.Add(1)
1039 return rand.Perm(t.numPieces())
1041 pieceInclinationsReused.Add(1)
1045 func (t *torrent) putPieceInclination(pi []int) {
1046 t.connPieceInclinationPool.Put(pi)
1047 pieceInclinationsPut.Add(1)