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"
21 "github.com/anacrolix/torrent/bencode"
22 "github.com/anacrolix/torrent/metainfo"
23 pp "github.com/anacrolix/torrent/peer_protocol"
26 func (t *torrent) chunkIndexSpec(chunkIndex, piece int) chunkSpec {
27 return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
30 func (t *torrent) pieceNumPendingBytes(index int) (count pp.Integer) {
31 if t.pieceComplete(index) {
34 piece := &t.Pieces[index]
35 count = t.pieceLength(index)
36 if !piece.EverHashed {
39 regularDirty := piece.numDirtyChunks()
40 lastChunkIndex := t.pieceNumChunks(index) - 1
41 if piece.pendingChunkIndex(lastChunkIndex) {
43 count -= t.chunkIndexSpec(lastChunkIndex, index).Length
45 count -= pp.Integer(regularDirty) * t.chunkSize
49 type peersKey struct {
54 // Is not aware of Client. Maintains state of torrent for with-in a Client.
61 // Closed when no more network activity is desired. This includes
62 // announcing, and communicating with peers.
63 ceasingNetworking chan struct{}
67 // Values are the piece indices that changed.
68 pieceStateChanges *pubsub.PubSub
70 // Total length of the torrent in bytes. Stored because it's not O(1) to
71 // get this from the info dict.
76 // The info dict. Nil if we don't have it (yet).
78 // Active peer connections, running message stream loops.
80 // Set of addrs to which we're attempting to connect. Connections are
81 // half-open until all handshakes are completed.
82 HalfOpen map[string]struct{}
84 // Reserve of peers to connect to. A peer can be both here and in the
85 // active connections if were told about the peer after connecting with
86 // them. That encourages us to reconnect to peers that are well known.
87 Peers map[peersKey]Peer
90 // BEP 12 Multitracker Metadata Extension. The tracker.Client instances
91 // mirror their respective URLs from the announce-list metainfo key.
92 Trackers []trackerTier
93 // Name used if the info name isn't available.
95 // The bencoded bytes of the info dict.
97 // Each element corresponds to the 16KiB metadata pieces. If true, we have
98 // received that piece.
101 // Closed when .Info is set.
102 gotMetainfo chan struct{}
104 readers map[*Reader]struct{}
106 pendingPieces bitmap.Bitmap
107 completedPieces bitmap.Bitmap
109 connPieceInclinationPool sync.Pool
113 pieceInclinationsReused = expvar.NewInt("pieceInclinationsReused")
114 pieceInclinationsNew = expvar.NewInt("pieceInclinationsNew")
115 pieceInclinationsPut = expvar.NewInt("pieceInclinationsPut")
118 func (t *torrent) setDisplayName(dn string) {
122 func (t *torrent) pieceComplete(piece int) bool {
123 return t.completedPieces.Get(piece)
126 func (t *torrent) pieceCompleteUncached(piece int) bool {
127 // TODO: This is called when setting metadata, and before storage is
128 // assigned, which doesn't seem right.
129 return t.data != nil && t.data.PieceComplete(piece)
132 func (t *torrent) numConnsUnchoked() (num int) {
133 for _, c := range t.Conns {
141 // There's a connection to that address already.
142 func (t *torrent) addrActive(addr string) bool {
143 if _, ok := t.HalfOpen[addr]; ok {
146 for _, c := range t.Conns {
147 if c.remoteAddr().String() == addr {
154 func (t *torrent) worstConns(cl *Client) (wcs *worstConns) {
156 c: make([]*connection, 0, len(t.Conns)),
160 for _, c := range t.Conns {
161 if !c.closed.IsSet() {
162 wcs.c = append(wcs.c, c)
168 func (t *torrent) ceaseNetworking() {
170 defer t.stateMu.Unlock()
172 case <-t.ceasingNetworking:
176 close(t.ceasingNetworking)
177 for _, c := range t.Conns {
182 func (t *torrent) addPeer(p Peer, cl *Client) {
184 if len(t.Peers) >= torrentPeersHighWater {
187 key := peersKey{string(p.IP), p.Port}
188 if _, ok := t.Peers[key]; ok {
192 peersAddedBySource.Add(string(p.Source), 1)
197 func (t *torrent) invalidateMetadata() {
203 func (t *torrent) saveMetadataPiece(index int, data []byte) {
207 if index >= len(t.metadataHave) {
208 log.Printf("%s: ignoring metadata piece %d", t, index)
211 copy(t.MetaData[(1<<14)*index:], data)
212 t.metadataHave[index] = true
215 func (t *torrent) metadataPieceCount() int {
216 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
219 func (t *torrent) haveMetadataPiece(piece int) bool {
221 return (1<<14)*piece < len(t.MetaData)
223 return piece < len(t.metadataHave) && t.metadataHave[piece]
227 func (t *torrent) metadataSizeKnown() bool {
228 return t.MetaData != nil
231 func (t *torrent) metadataSize() int {
232 return len(t.MetaData)
235 func infoPieceHashes(info *metainfo.Info) (ret []string) {
236 for i := 0; i < len(info.Pieces); i += 20 {
237 ret = append(ret, string(info.Pieces[i:i+20]))
242 // Called when metadata for a torrent becomes available.
243 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte) (err error) {
244 err = validateInfo(md)
246 err = fmt.Errorf("bad info: %s", err)
251 for _, f := range t.Info.UpvertedFiles() {
254 t.MetaData = infoBytes
256 hashes := infoPieceHashes(md)
257 t.Pieces = make([]piece, len(hashes))
258 for i, hash := range hashes {
259 piece := &t.Pieces[i]
262 piece.noPendingWrites.L = &piece.pendingWritesMutex
263 missinggo.CopyExact(piece.Hash[:], hash)
265 for _, conn := range t.Conns {
266 if err := conn.setNumPieces(t.numPieces()); err != nil {
267 log.Printf("closing connection: %s", err)
274 func (t *torrent) setStorage(td Data) {
279 for i := range t.Pieces {
280 t.updatePieceCompletion(i)
281 t.Pieces[i].QueuedForHash = true
284 for i := range t.Pieces {
290 func (t *torrent) verifyPiece(piece int) {
291 t.cl.verifyPiece(t, piece)
294 func (t *torrent) haveAllMetadataPieces() bool {
298 if t.metadataHave == nil {
301 for _, have := range t.metadataHave {
309 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
311 // We already know the correct metadata size.
314 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
315 log.Printf("received bad metadata size: %d", bytes)
318 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
321 t.MetaData = make([]byte, bytes)
322 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
323 for _, c := range t.Conns {
324 cl.requestPendingMetadata(t, c)
329 // The current working name for the torrent. Either the name in the info dict,
330 // or a display name given such as by the dn value in a magnet link, or "".
331 func (t *torrent) Name() string {
338 func (t *torrent) pieceState(index int) (ret PieceState) {
339 p := &t.Pieces[index]
340 ret.Priority = t.piecePriority(index)
341 if t.pieceComplete(index) {
344 if p.QueuedForHash || p.Hashing {
347 if !ret.Complete && t.piecePartiallyDownloaded(index) {
353 func (t *torrent) metadataPieceSize(piece int) int {
354 return metadataPieceSize(len(t.MetaData), piece)
357 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
363 d["total_size"] = len(t.MetaData)
365 p, err := bencode.Marshal(d)
371 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
372 ExtendedPayload: append(p, data...),
376 func (t *torrent) pieceStateRuns() (ret []PieceStateRun) {
377 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
378 ret = append(ret, PieceStateRun{
379 PieceState: el.(PieceState),
383 for index := range t.Pieces {
384 rle.Append(t.pieceState(index), 1)
390 // Produces a small string representing a PieceStateRun.
391 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
392 ret = fmt.Sprintf("%d", psr.Length)
393 ret += func() string {
394 switch psr.Priority {
395 case PiecePriorityNext:
397 case PiecePriorityNormal:
399 case PiecePriorityReadahead:
401 case PiecePriorityNow:
419 func (t *torrent) writeStatus(w io.Writer, cl *Client) {
420 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
421 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
423 fmt.Fprintf(w, "Metadata have: ")
424 for _, h := range t.metadataHave {
425 fmt.Fprintf(w, "%c", func() rune {
435 fmt.Fprintf(w, "Piece length: %s\n", func() string {
437 return fmt.Sprint(t.usualPieceSize())
443 fmt.Fprintf(w, "Num Pieces: %d\n", t.numPieces())
444 fmt.Fprint(w, "Piece States:")
445 for _, psr := range t.pieceStateRuns() {
447 w.Write([]byte(pieceStateRunStatusChars(psr)))
451 fmt.Fprintf(w, "Reader Pieces:")
452 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
453 fmt.Fprintf(w, " %d:%d", begin, end)
457 fmt.Fprintf(w, "Trackers: ")
458 for _, tier := range t.Trackers {
459 for _, tr := range tier {
460 fmt.Fprintf(w, "%q ", tr)
464 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
465 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
466 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
467 sort.Sort(&worstConns{
472 for i, c := range t.Conns {
473 fmt.Fprintf(w, "%2d. ", i+1)
478 func (t *torrent) String() string {
481 s = fmt.Sprintf("%x", t.InfoHash)
486 func (t *torrent) haveInfo() bool {
490 // TODO: Include URIs that weren't converted to tracker clients.
491 func (t *torrent) announceList() (al [][]string) {
492 missinggo.CastSlice(&al, t.Trackers)
496 // Returns a run-time generated MetaInfo that includes the info bytes and
497 // announce-list as currently known to the client.
498 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
499 if t.MetaData == nil {
500 panic("info bytes not set")
502 return &metainfo.MetaInfo{
503 Info: metainfo.InfoEx{
507 CreationDate: time.Now().Unix(),
508 Comment: "dynamic metainfo from client",
509 CreatedBy: "go.torrent",
510 AnnounceList: t.announceList(),
514 func (t *torrent) bytesLeft() (left int64) {
518 for i := 0; i < t.numPieces(); i++ {
519 left += int64(t.pieceNumPendingBytes(i))
524 func (t *torrent) piecePartiallyDownloaded(piece int) bool {
525 if t.pieceComplete(piece) {
528 if t.pieceAllDirty(piece) {
531 return t.Pieces[piece].hasDirtyChunks()
534 func numChunksForPiece(chunkSize int, pieceSize int) int {
535 return (pieceSize + chunkSize - 1) / chunkSize
538 func (t *torrent) usualPieceSize() int {
539 return int(t.Info.PieceLength)
542 func (t *torrent) lastPieceSize() int {
543 return int(t.pieceLength(t.numPieces() - 1))
546 func (t *torrent) numPieces() int {
547 return t.Info.NumPieces()
550 func (t *torrent) numPiecesCompleted() (num int) {
551 return t.completedPieces.Len()
554 // Safe to call with or without client lock.
555 func (t *torrent) isClosed() bool {
564 func (t *torrent) close() (err error) {
570 if c, ok := t.data.(io.Closer); ok {
573 for _, conn := range t.Conns {
576 t.pieceStateChanges.Close()
580 func (t *torrent) requestOffset(r request) int64 {
581 return torrentRequestOffset(t.length, int64(t.usualPieceSize()), r)
584 // Return the request that would include the given offset into the torrent
585 // data. Returns !ok if there is no such request.
586 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
587 return torrentOffsetRequest(t.length, t.Info.PieceLength, int64(t.chunkSize), off)
590 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
591 tr := perf.NewTimer()
592 n, err := t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
593 if err == nil && n != len(data) {
594 err = io.ErrShortWrite
597 tr.Stop("write chunk")
602 func (t *torrent) bitfield() (bf []bool) {
603 bf = make([]bool, t.numPieces())
604 t.completedPieces.IterTyped(func(piece int) (again bool) {
611 func (t *torrent) validOutgoingRequest(r request) bool {
612 if r.Index >= pp.Integer(t.Info.NumPieces()) {
615 if r.Begin%t.chunkSize != 0 {
618 if r.Length > t.chunkSize {
621 pieceLength := t.pieceLength(int(r.Index))
622 if r.Begin+r.Length > pieceLength {
625 return r.Length == t.chunkSize || r.Begin+r.Length == pieceLength
628 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
629 css = make([]chunkSpec, 0, (t.pieceLength(piece)+t.chunkSize-1)/t.chunkSize)
631 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
633 if cs.Length > t.chunkSize {
634 cs.Length = t.chunkSize
636 css = append(css, cs)
637 cs.Begin += cs.Length
642 func (t *torrent) pieceNumChunks(piece int) int {
643 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
646 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
647 t.Pieces[pieceIndex].DirtyChunks.Clear()
655 // Peer is known to support encryption.
656 SupportsEncryption bool
659 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
660 if piece < 0 || piece > t.Info.NumPieces() {
663 if int(piece) == t.numPieces()-1 {
664 len_ = pp.Integer(t.length % t.Info.PieceLength)
667 len_ = pp.Integer(t.Info.PieceLength)
672 func (t *torrent) hashPiece(piece int) (ret pieceSum) {
673 hash := pieceHash.New()
674 p := &t.Pieces[piece]
675 p.waitNoPendingWrites()
676 ip := t.Info.Piece(piece)
678 n, err := io.Copy(hash, io.NewSectionReader(t.data, ip.Offset(), pl))
680 missinggo.CopyExact(&ret, hash.Sum(nil))
683 if err != io.ErrUnexpectedEOF {
684 log.Printf("unexpected error hashing piece with %T: %s", t.data, err)
689 func (t *torrent) haveAllPieces() bool {
693 return t.completedPieces.Len() == t.numPieces()
696 func (me *torrent) haveAnyPieces() bool {
697 for i := range me.Pieces {
698 if me.pieceComplete(i) {
705 func (t *torrent) havePiece(index int) bool {
706 return t.haveInfo() && t.pieceComplete(index)
709 func (t *torrent) haveChunk(r request) (ret bool) {
711 // log.Println("have chunk", r, ret)
716 if t.pieceComplete(int(r.Index)) {
719 p := &t.Pieces[r.Index]
720 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
723 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
724 return int(cs.Begin / chunkSize)
727 // TODO: This should probably be called wantPiece.
728 func (t *torrent) wantChunk(r request) bool {
729 if !t.wantPiece(int(r.Index)) {
732 if t.Pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
735 // TODO: What about pieces that were wanted, but aren't now, and aren't
736 // completed either? That used to be done here.
740 // TODO: This should be called wantPieceIndex.
741 func (t *torrent) wantPiece(index int) bool {
745 p := &t.Pieces[index]
752 if t.pieceComplete(index) {
755 if t.pendingPieces.Contains(index) {
758 return !t.forReaderOffsetPieces(func(begin, end int) bool {
759 return index < begin || index >= end
763 func (t *torrent) forNeededPieces(f func(piece int) (more bool)) (all bool) {
764 return t.forReaderOffsetPieces(func(begin, end int) (more bool) {
765 for i := begin; begin < end; i++ {
774 func (t *torrent) connHasWantedPieces(c *connection) bool {
775 return !c.pieceRequestOrder.IsEmpty()
778 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
779 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
780 pieces = append(pieces, int(i))
785 func (t *torrent) worstBadConn(cl *Client) *connection {
786 wcs := t.worstConns(cl)
789 c := heap.Pop(wcs).(*connection)
790 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
793 if wcs.Len() >= (socketsPerTorrent+1)/2 {
794 // Give connections 1 minute to prove themselves.
795 if time.Since(c.completedHandshake) > time.Minute {
803 type PieceStateChange struct {
808 func (t *torrent) publishPieceChange(piece int) {
809 cur := t.pieceState(piece)
810 p := &t.Pieces[piece]
811 if cur != p.PublicPieceState {
812 p.PublicPieceState = cur
813 t.pieceStateChanges.Publish(PieceStateChange{
820 func (t *torrent) pieceNumPendingChunks(piece int) int {
821 if t.pieceComplete(piece) {
824 return t.pieceNumChunks(piece) - t.Pieces[piece].numDirtyChunks()
827 func (t *torrent) pieceAllDirty(piece int) bool {
828 return t.Pieces[piece].DirtyChunks.Len() == t.pieceNumChunks(piece)
831 func (t *torrent) forUrgentPieces(f func(piece int) (again bool)) (all bool) {
832 return t.forReaderOffsetPieces(func(begin, end int) (again bool) {
842 func (t *torrent) readersChanged() {
843 t.updatePiecePriorities()
846 func (t *torrent) maybeNewConns() {
847 // Tickle the accept routine.
848 t.cl.event.Broadcast()
852 func (t *torrent) piecePriorityChanged(piece int) {
853 for _, c := range t.Conns {
854 c.updatePiecePriority(piece)
857 t.publishPieceChange(piece)
860 func (t *torrent) updatePiecePriority(piece int) bool {
861 p := &t.Pieces[piece]
862 newPrio := t.piecePriorityUncached(piece)
863 if newPrio == p.priority {
870 // Update all piece priorities in one hit. This function should have the same
871 // output as updatePiecePriority, but across all pieces.
872 func (t *torrent) updatePiecePriorities() {
873 newPrios := make([]piecePriority, t.numPieces())
874 t.pendingPieces.IterTyped(func(piece int) (more bool) {
875 newPrios[piece] = PiecePriorityNormal
878 t.forReaderOffsetPieces(func(begin, end int) (next bool) {
880 newPrios[begin].Raise(PiecePriorityNow)
882 for i := begin + 1; i < end; i++ {
883 newPrios[i].Raise(PiecePriorityReadahead)
887 t.completedPieces.IterTyped(func(piece int) (more bool) {
888 newPrios[piece] = PiecePriorityNone
891 for i, prio := range newPrios {
892 if prio != t.Pieces[i].priority {
893 t.Pieces[i].priority = prio
894 t.piecePriorityChanged(i)
899 func (t *torrent) byteRegionPieces(off, size int64) (begin, end int) {
910 begin = int(off / t.Info.PieceLength)
911 end = int((off + size + t.Info.PieceLength - 1) / t.Info.PieceLength)
912 if end > t.Info.NumPieces() {
913 end = t.Info.NumPieces()
918 // Returns true if all iterations complete without breaking.
919 func (t *torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
920 for r := range t.readers {
922 pos, readahead := r.pos, r.readahead
927 begin, end := t.byteRegionPieces(pos, readahead)
938 func (t *torrent) piecePriority(piece int) piecePriority {
940 return PiecePriorityNone
942 return t.Pieces[piece].priority
945 func (t *torrent) piecePriorityUncached(piece int) (ret piecePriority) {
946 ret = PiecePriorityNone
947 if t.pieceComplete(piece) {
950 if t.pendingPieces.Contains(piece) {
951 ret = PiecePriorityNormal
953 raiseRet := ret.Raise
954 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
956 raiseRet(PiecePriorityNow)
958 if begin <= piece && piece < end {
959 raiseRet(PiecePriorityReadahead)
966 func (t *torrent) pendPiece(piece int) {
967 if t.pendingPieces.Contains(piece) {
970 if t.havePiece(piece) {
973 t.pendingPieces.Add(piece)
974 if !t.updatePiecePriority(piece) {
977 t.piecePriorityChanged(piece)
980 func (t *torrent) getCompletedPieces() (ret bitmap.Bitmap) {
981 return t.completedPieces.Copy()
984 func (t *torrent) unpendPieces(unpend *bitmap.Bitmap) {
985 t.pendingPieces.Sub(unpend)
986 t.updatePiecePriorities()
989 func (t *torrent) pendPieceRange(begin, end int) {
990 for i := begin; i < end; i++ {
995 func (t *torrent) unpendPieceRange(begin, end int) {
997 bm.AddRange(begin, end)
1001 func (t *torrent) connRequestPiecePendingChunks(c *connection, piece int) (more bool) {
1002 if !c.PeerHasPiece(piece) {
1005 chunkIndices := t.Pieces[piece].undirtiedChunkIndices().ToSortedSlice()
1006 return itertools.ForPerm(len(chunkIndices), func(i int) bool {
1007 req := request{pp.Integer(piece), t.chunkIndexSpec(chunkIndices[i], piece)}
1008 return c.Request(req)
1012 func (t *torrent) pendRequest(req request) {
1013 ci := chunkIndex(req.chunkSpec, t.chunkSize)
1014 t.Pieces[req.Index].pendChunkIndex(ci)
1017 func (t *torrent) pieceChanged(piece int) {
1018 t.cl.pieceChanged(t, piece)
1021 func (t *torrent) openNewConns() {
1022 t.cl.openNewConns(t)
1025 func (t *torrent) getConnPieceInclination() []int {
1026 _ret := t.connPieceInclinationPool.Get()
1028 pieceInclinationsNew.Add(1)
1029 return rand.Perm(t.numPieces())
1031 pieceInclinationsReused.Add(1)
1035 func (t *torrent) putPieceInclination(pi []int) {
1036 t.connPieceInclinationPool.Put(pi)
1037 pieceInclinationsPut.Add(1)
1040 func (t *torrent) updatePieceCompletion(piece int) {
1041 t.completedPieces.Set(piece, t.pieceCompleteUncached(piece))