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 for i, dirty := range piece.DirtyChunks {
43 count -= t.chunkIndexSpec(i, index).Length
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 [][]tracker.Client
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
108 connPieceInclinationPool sync.Pool
112 pieceInclinationsReused = expvar.NewInt("pieceInclinationsReused")
113 pieceInclinationsNew = expvar.NewInt("pieceInclinationsNew")
114 pieceInclinationsPut = expvar.NewInt("pieceInclinationsPut")
117 func (t *torrent) setDisplayName(dn string) {
121 func (t *torrent) pieceComplete(piece int) bool {
122 // TODO: This is called when setting metadata, and before storage is
123 // assigned, which doesn't seem right.
124 return t.data != nil && t.data.PieceComplete(piece)
127 func (t *torrent) numConnsUnchoked() (num int) {
128 for _, c := range t.Conns {
136 // There's a connection to that address already.
137 func (t *torrent) addrActive(addr string) bool {
138 if _, ok := t.HalfOpen[addr]; ok {
141 for _, c := range t.Conns {
142 if c.remoteAddr().String() == addr {
149 func (t *torrent) worstConns(cl *Client) (wcs *worstConns) {
151 c: make([]*connection, 0, len(t.Conns)),
155 for _, c := range t.Conns {
156 if !c.closed.IsSet() {
157 wcs.c = append(wcs.c, c)
163 func (t *torrent) ceaseNetworking() {
165 defer t.stateMu.Unlock()
167 case <-t.ceasingNetworking:
171 close(t.ceasingNetworking)
172 for _, c := range t.Conns {
177 func (t *torrent) addPeer(p Peer, cl *Client) {
179 if len(t.Peers) >= torrentPeersHighWater {
182 key := peersKey{string(p.IP), p.Port}
183 if _, ok := t.Peers[key]; ok {
187 peersAddedBySource.Add(string(p.Source), 1)
192 func (t *torrent) invalidateMetadata() {
198 func (t *torrent) saveMetadataPiece(index int, data []byte) {
202 if index >= len(t.metadataHave) {
203 log.Printf("%s: ignoring metadata piece %d", t, index)
206 copy(t.MetaData[(1<<14)*index:], data)
207 t.metadataHave[index] = true
210 func (t *torrent) metadataPieceCount() int {
211 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
214 func (t *torrent) haveMetadataPiece(piece int) bool {
216 return (1<<14)*piece < len(t.MetaData)
218 return piece < len(t.metadataHave) && t.metadataHave[piece]
222 func (t *torrent) metadataSizeKnown() bool {
223 return t.MetaData != nil
226 func (t *torrent) metadataSize() int {
227 return len(t.MetaData)
230 func infoPieceHashes(info *metainfo.Info) (ret []string) {
231 for i := 0; i < len(info.Pieces); i += 20 {
232 ret = append(ret, string(info.Pieces[i:i+20]))
237 // Called when metadata for a torrent becomes available.
238 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte) (err error) {
239 err = validateInfo(md)
241 err = fmt.Errorf("bad info: %s", err)
246 for _, f := range t.Info.UpvertedFiles() {
249 t.MetaData = infoBytes
251 hashes := infoPieceHashes(md)
252 t.Pieces = make([]piece, len(hashes))
253 for i, hash := range hashes {
254 piece := &t.Pieces[i]
255 piece.noPendingWrites.L = &piece.pendingWritesMutex
256 missinggo.CopyExact(piece.Hash[:], hash)
258 for _, conn := range t.Conns {
259 if err := conn.setNumPieces(t.numPieces()); err != nil {
260 log.Printf("closing connection: %s", err)
267 func (t *torrent) setStorage(td Data) (err error) {
275 func (t *torrent) haveAllMetadataPieces() bool {
279 if t.metadataHave == nil {
282 for _, have := range t.metadataHave {
290 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
292 // We already know the correct metadata size.
295 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
296 log.Printf("received bad metadata size: %d", bytes)
299 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
302 t.MetaData = make([]byte, bytes)
303 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
304 for _, c := range t.Conns {
305 cl.requestPendingMetadata(t, c)
310 // The current working name for the torrent. Either the name in the info dict,
311 // or a display name given such as by the dn value in a magnet link, or "".
312 func (t *torrent) Name() string {
319 func (t *torrent) pieceState(index int) (ret PieceState) {
320 p := &t.Pieces[index]
321 ret.Priority = t.piecePriority(index)
322 if t.pieceComplete(index) {
325 if p.QueuedForHash || p.Hashing {
328 if !ret.Complete && t.piecePartiallyDownloaded(index) {
334 func (t *torrent) metadataPieceSize(piece int) int {
335 return metadataPieceSize(len(t.MetaData), piece)
338 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
344 d["total_size"] = len(t.MetaData)
346 p, err := bencode.Marshal(d)
352 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
353 ExtendedPayload: append(p, data...),
357 func (t *torrent) pieceStateRuns() (ret []PieceStateRun) {
358 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
359 ret = append(ret, PieceStateRun{
360 PieceState: el.(PieceState),
364 for index := range t.Pieces {
365 rle.Append(t.pieceState(index), 1)
371 // Produces a small string representing a PieceStateRun.
372 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
373 ret = fmt.Sprintf("%d", psr.Length)
374 ret += func() string {
375 switch psr.Priority {
376 case PiecePriorityNext:
378 case PiecePriorityNormal:
380 case PiecePriorityReadahead:
382 case PiecePriorityNow:
400 func (t *torrent) writeStatus(w io.Writer, cl *Client) {
401 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
402 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
404 fmt.Fprintf(w, "Metadata have: ")
405 for _, h := range t.metadataHave {
406 fmt.Fprintf(w, "%c", func() rune {
416 fmt.Fprintf(w, "Piece length: %s\n", func() string {
418 return fmt.Sprint(t.usualPieceSize())
424 fmt.Fprintf(w, "Num Pieces: %d\n", t.numPieces())
425 fmt.Fprint(w, "Piece States:")
426 for _, psr := range t.pieceStateRuns() {
428 w.Write([]byte(pieceStateRunStatusChars(psr)))
432 fmt.Fprintf(w, "Reader Pieces:")
433 t.forReaderOffsetPieces(func(begin, end int) (again bool) {
434 fmt.Fprintf(w, " %d:%d", begin, end)
438 fmt.Fprintf(w, "Trackers: ")
439 for _, tier := range t.Trackers {
440 for _, tr := range tier {
441 fmt.Fprintf(w, "%q ", tr.String())
445 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
446 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
447 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
448 sort.Sort(&worstConns{
453 for i, c := range t.Conns {
454 fmt.Fprintf(w, "%2d. ", i+1)
459 func (t *torrent) String() string {
462 s = fmt.Sprintf("%x", t.InfoHash)
467 func (t *torrent) haveInfo() bool {
471 // TODO: Include URIs that weren't converted to tracker clients.
472 func (t *torrent) announceList() (al [][]string) {
473 for _, tier := range t.Trackers {
475 for _, tr := range tier {
476 l = append(l, tr.URL())
483 // Returns a run-time generated MetaInfo that includes the info bytes and
484 // announce-list as currently known to the client.
485 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
486 if t.MetaData == nil {
487 panic("info bytes not set")
489 return &metainfo.MetaInfo{
490 Info: metainfo.InfoEx{
494 CreationDate: time.Now().Unix(),
495 Comment: "dynamic metainfo from client",
496 CreatedBy: "go.torrent",
497 AnnounceList: t.announceList(),
501 func (t *torrent) bytesLeft() (left int64) {
505 for i := 0; i < t.numPieces(); i++ {
506 left += int64(t.pieceNumPendingBytes(i))
511 func (t *torrent) piecePartiallyDownloaded(index int) bool {
512 pendingBytes := t.pieceNumPendingBytes(index)
513 return pendingBytes != 0 && pendingBytes != t.pieceLength(index)
516 func numChunksForPiece(chunkSize int, pieceSize int) int {
517 return (pieceSize + chunkSize - 1) / chunkSize
520 func (t *torrent) usualPieceSize() int {
521 return int(t.Info.PieceLength)
524 func (t *torrent) lastPieceSize() int {
525 return int(t.pieceLength(t.numPieces() - 1))
528 func (t *torrent) numPieces() int {
529 return t.Info.NumPieces()
532 func (t *torrent) numPiecesCompleted() (num int) {
533 for i := range iter.N(t.Info.NumPieces()) {
534 if t.pieceComplete(i) {
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 for i := range t.Pieces {
590 bf = append(bf, t.havePiece(i))
595 func (t *torrent) validOutgoingRequest(r request) bool {
596 if r.Index >= pp.Integer(t.Info.NumPieces()) {
599 if r.Begin%t.chunkSize != 0 {
602 if r.Length > t.chunkSize {
605 pieceLength := t.pieceLength(int(r.Index))
606 if r.Begin+r.Length > pieceLength {
609 return r.Length == t.chunkSize || r.Begin+r.Length == pieceLength
612 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
613 css = make([]chunkSpec, 0, (t.pieceLength(piece)+t.chunkSize-1)/t.chunkSize)
615 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
617 if cs.Length > t.chunkSize {
618 cs.Length = t.chunkSize
620 css = append(css, cs)
621 cs.Begin += cs.Length
626 func (t *torrent) pieceNumChunks(piece int) int {
627 return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
630 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
631 t.Pieces[pieceIndex].DirtyChunks = nil
639 // Peer is known to support encryption.
640 SupportsEncryption bool
643 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
644 if piece < 0 || piece > t.Info.NumPieces() {
647 if int(piece) == t.numPieces()-1 {
648 len_ = pp.Integer(t.length % t.Info.PieceLength)
651 len_ = pp.Integer(t.Info.PieceLength)
656 func (t *torrent) hashPiece(piece int) (ps pieceSum) {
657 hash := pieceHash.New()
658 p := &t.Pieces[piece]
659 p.waitNoPendingWrites()
660 pl := t.Info.Piece(int(piece)).Length()
661 n, err := t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, pl)
663 if err != io.ErrUnexpectedEOF {
664 log.Printf("error hashing piece with %T: %s", t.data, err)
669 panic(fmt.Sprintf("%T: %d != %d", t.data, n, pl))
671 missinggo.CopyExact(ps[:], hash.Sum(nil))
675 func (t *torrent) haveAllPieces() bool {
679 for i := range t.Pieces {
680 if !t.pieceComplete(i) {
687 func (me *torrent) haveAnyPieces() bool {
688 for i := range me.Pieces {
689 if me.pieceComplete(i) {
696 func (t *torrent) havePiece(index int) bool {
697 return t.haveInfo() && t.pieceComplete(index)
700 func (t *torrent) haveChunk(r request) (ret bool) {
702 // log.Println("have chunk", r, ret)
707 if t.pieceComplete(int(r.Index)) {
710 p := &t.Pieces[r.Index]
711 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
714 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
715 return int(cs.Begin / chunkSize)
718 // TODO: This should probably be called wantPiece.
719 func (t *torrent) wantChunk(r request) bool {
720 if !t.wantPiece(int(r.Index)) {
723 if t.Pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
726 // TODO: What about pieces that were wanted, but aren't now, and aren't
727 // completed either? That used to be done here.
731 // TODO: This should be called wantPieceIndex.
732 func (t *torrent) wantPiece(index int) bool {
736 p := &t.Pieces[index]
743 if t.pieceComplete(index) {
746 if t.pendingPieces.Contains(index) {
749 return !t.forReaderOffsetPieces(func(begin, end int) bool {
750 return index < begin || index >= end
754 func (t *torrent) forNeededPieces(f func(piece int) (more bool)) (all bool) {
755 return t.forReaderOffsetPieces(func(begin, end int) (more bool) {
756 for i := begin; begin < end; i++ {
765 func (t *torrent) connHasWantedPieces(c *connection) bool {
766 for it := t.pendingPieces.IterTyped(); it.Next(); {
767 if c.PeerHasPiece(it.ValueInt()) {
772 return !t.forReaderOffsetPieces(func(begin, end int) (again bool) {
773 for i := begin; i < end; i++ {
774 if c.PeerHasPiece(i) {
782 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
783 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
784 pieces = append(pieces, int(i))
789 func (t *torrent) worstBadConn(cl *Client) *connection {
790 wcs := t.worstConns(cl)
793 c := heap.Pop(wcs).(*connection)
794 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
797 if wcs.Len() >= (socketsPerTorrent+1)/2 {
798 // Give connections 1 minute to prove themselves.
799 if time.Since(c.completedHandshake) > time.Minute {
807 func (t *torrent) publishPieceChange(piece int) {
808 cur := t.pieceState(piece)
809 p := &t.Pieces[piece]
810 if cur != p.PublicPieceState {
811 t.pieceStateChanges.Publish(piece)
813 p.PublicPieceState = cur
816 func (t *torrent) pieceNumPendingChunks(piece int) int {
817 if t.pieceComplete(piece) {
820 return t.pieceNumChunks(piece) - t.Pieces[piece].numDirtyChunks()
823 func (t *torrent) pieceAllDirty(piece int) bool {
824 p := &t.Pieces[piece]
825 if len(p.DirtyChunks) != t.pieceNumChunks(piece) {
828 for _, dirty := range p.DirtyChunks {
836 func (t *torrent) forUrgentPieces(f func(piece int) (again bool)) (all bool) {
837 return t.forReaderOffsetPieces(func(begin, end int) (again bool) {
847 func (t *torrent) readersChanged() {
848 t.updatePiecePriorities()
851 func (t *torrent) maybeNewConns() {
852 // Tickle the accept routine.
853 t.cl.event.Broadcast()
857 func (t *torrent) piecePriorityChanged(piece int) {
858 for _, c := range t.Conns {
859 c.updatePiecePriority(piece)
864 func (t *torrent) updatePiecePriority(piece int) bool {
865 p := &t.Pieces[piece]
866 newPrio := t.piecePriorityUncached(piece)
867 if newPrio == p.priority {
874 func (t *torrent) updatePiecePriorities() {
875 newPrios := make([]piecePriority, t.numPieces())
876 itertools.ForIterable(&t.pendingPieces, func(value interface{}) (next bool) {
877 newPrios[value.(int)] = PiecePriorityNormal
880 t.forReaderOffsetPieces(func(begin, end int) (next bool) {
882 newPrios[begin].Raise(PiecePriorityNow)
884 for i := begin + 1; i < end; i++ {
885 newPrios[begin].Raise(PiecePriorityReadahead)
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) connRequestPiecePendingChunks(c *connection, piece int) (more bool) {
979 if !c.PeerHasPiece(piece) {
982 for _, cs := range t.Pieces[piece].shuffledPendingChunkSpecs(t, piece) {
983 req := request{pp.Integer(piece), cs}
991 func (t *torrent) pendRequest(req request) {
992 ci := chunkIndex(req.chunkSpec, t.chunkSize)
993 t.Pieces[req.Index].pendChunkIndex(ci)
996 func (t *torrent) pieceChanged(piece int) {
997 t.cl.pieceChanged(t, piece)
1000 func (t *torrent) openNewConns() {
1001 t.cl.openNewConns(t)
1004 func (t *torrent) getConnPieceInclination() []int {
1005 _ret := t.connPieceInclinationPool.Get()
1007 pieceInclinationsNew.Add(1)
1008 return rand.Perm(t.numPieces())
1010 pieceInclinationsReused.Add(1)
1014 func (t *torrent) putPieceInclination(pi []int) {
1015 t.connPieceInclinationPool.Put(pi)
1016 pieceInclinationsPut.Add(1)