13 "github.com/anacrolix/missinggo"
14 "github.com/anacrolix/missinggo/pubsub"
15 "github.com/bradfitz/iter"
17 "github.com/anacrolix/torrent/bencode"
18 "github.com/anacrolix/torrent/data"
19 "github.com/anacrolix/torrent/metainfo"
20 pp "github.com/anacrolix/torrent/peer_protocol"
21 "github.com/anacrolix/torrent/tracker"
24 func (t *torrent) pieceNumPendingBytes(index int) (count pp.Integer) {
25 if t.pieceComplete(index) {
28 piece := t.Pieces[index]
29 pieceLength := t.pieceLength(index)
30 if !piece.EverHashed {
33 for i, pending := range piece.PendingChunkSpecs {
35 count += chunkIndexSpec(i, pieceLength, t.chunkSize).Length
41 type peersKey struct {
46 // Data maintains per-piece persistent state.
47 type StatefulData interface {
49 // We believe the piece data will pass a hash check.
50 PieceCompleted(index int) error
51 // Returns true if the piece is complete.
52 PieceComplete(index int) bool
55 // Is not aware of Client. Maintains state of torrent for with-in a Client.
60 // Closed when no more network activity is desired. This includes
61 // announcing, and communicating with peers.
62 ceasingNetworking chan struct{}
66 // Values are the piece indices that changed.
67 pieceStateChanges *pubsub.PubSub
69 // Chunks that are wanted before all others. This is for
70 // responsive/streaming readers that want to unblock ASAP.
71 urgent map[request]struct{}
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{}
107 func (t *torrent) pieceComplete(piece int) bool {
108 // TODO: This is called when setting metadata, and before storage is
109 // assigned, which doesn't seem right.
110 return t.data != nil && t.data.PieceComplete(piece)
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 {
145 wcs.c = append(wcs.c, c)
151 func (t *torrent) ceaseNetworking() {
153 defer t.stateMu.Unlock()
155 case <-t.ceasingNetworking:
159 close(t.ceasingNetworking)
160 for _, c := range t.Conns {
165 func (t *torrent) addPeer(p Peer) {
166 t.Peers[peersKey{string(p.IP), p.Port}] = p
169 func (t *torrent) invalidateMetadata() {
175 func (t *torrent) saveMetadataPiece(index int, data []byte) {
179 if index >= len(t.metadataHave) {
180 log.Printf("%s: ignoring metadata piece %d", t, index)
183 copy(t.MetaData[(1<<14)*index:], data)
184 t.metadataHave[index] = true
187 func (t *torrent) metadataPieceCount() int {
188 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
191 func (t *torrent) haveMetadataPiece(piece int) bool {
193 return (1<<14)*piece < len(t.MetaData)
195 return piece < len(t.metadataHave) && t.metadataHave[piece]
199 func (t *torrent) metadataSizeKnown() bool {
200 return t.MetaData != nil
203 func (t *torrent) metadataSize() int {
204 return len(t.MetaData)
207 func infoPieceHashes(info *metainfo.Info) (ret []string) {
208 for i := 0; i < len(info.Pieces); i += 20 {
209 ret = append(ret, string(info.Pieces[i:i+20]))
214 // Called when metadata for a torrent becomes available.
215 func (t *torrent) setMetadata(md *metainfo.Info, infoBytes []byte, eventLocker sync.Locker) (err error) {
216 err = validateInfo(md)
218 err = fmt.Errorf("bad info: %s", err)
223 for _, f := range t.Info.UpvertedFiles() {
226 t.MetaData = infoBytes
228 for _, hash := range infoPieceHashes(md) {
230 piece.Event.L = eventLocker
231 piece.noPendingWrites.L = &piece.pendingWritesMutex
232 missinggo.CopyExact(piece.Hash[:], hash)
233 t.Pieces = append(t.Pieces, piece)
235 for _, conn := range t.Conns {
236 t.initRequestOrdering(conn)
237 if err := conn.setNumPieces(t.numPieces()); err != nil {
238 log.Printf("closing connection: %s", err)
245 func (t *torrent) setStorage(td data.Data) (err error) {
246 if c, ok := t.data.(io.Closer); ok {
249 if sd, ok := td.(StatefulData); ok {
252 t.data = &statelessDataWrapper{td, make([]bool, t.Info.NumPieces())}
257 func (t *torrent) haveAllMetadataPieces() bool {
261 if t.metadataHave == nil {
264 for _, have := range t.metadataHave {
272 func (t *torrent) setMetadataSize(bytes int64, cl *Client) {
274 // We already know the correct metadata size.
277 if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
278 log.Printf("received bad metadata size: %d", bytes)
281 if t.MetaData != nil && len(t.MetaData) == int(bytes) {
284 t.MetaData = make([]byte, bytes)
285 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
286 for _, c := range t.Conns {
287 cl.requestPendingMetadata(t, c)
292 // The current working name for the torrent. Either the name in the info dict,
293 // or a display name given such as by the dn value in a magnet link, or "".
294 func (t *torrent) Name() string {
301 func (t *torrent) pieceState(index int) (ret PieceState) {
303 ret.Priority = p.Priority
304 if t.pieceComplete(index) {
307 if p.QueuedForHash || p.Hashing {
310 if !ret.Complete && t.piecePartiallyDownloaded(index) {
316 func (t *torrent) metadataPieceSize(piece int) int {
317 return metadataPieceSize(len(t.MetaData), piece)
320 func (t *torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
326 d["total_size"] = len(t.MetaData)
328 p, err := bencode.Marshal(d)
334 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
335 ExtendedPayload: append(p, data...),
339 func (t *torrent) pieceStateRuns() (ret []PieceStateRun) {
340 rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
341 ret = append(ret, PieceStateRun{
342 PieceState: el.(PieceState),
346 for index := range t.Pieces {
347 rle.Append(t.pieceState(index), 1)
353 // Produces a small string representing a PieceStateRun.
354 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
355 ret = fmt.Sprintf("%d", psr.Length)
356 ret += func() string {
357 switch psr.Priority {
358 case PiecePriorityNext:
360 case PiecePriorityNormal:
362 case PiecePriorityReadahead:
364 case PiecePriorityNow:
382 func (t *torrent) writeStatus(w io.Writer, cl *Client) {
383 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
384 fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
386 fmt.Fprintf(w, "Metadata have: ")
387 for _, h := range t.metadataHave {
388 fmt.Fprintf(w, "%c", func() rune {
398 fmt.Fprintf(w, "Piece length: %s\n", func() string {
400 return fmt.Sprint(t.usualPieceSize())
406 fmt.Fprint(w, "Pieces:")
407 for _, psr := range t.pieceStateRuns() {
409 w.Write([]byte(pieceStateRunStatusChars(psr)))
413 fmt.Fprintf(w, "Urgent:")
414 for req := range t.urgent {
415 fmt.Fprintf(w, " %v", req)
418 fmt.Fprintf(w, "Trackers: ")
419 for _, tier := range t.Trackers {
420 for _, tr := range tier {
421 fmt.Fprintf(w, "%q ", tr.String())
425 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
426 fmt.Fprintf(w, "Half open: %d\n", len(t.HalfOpen))
427 fmt.Fprintf(w, "Active peers: %d\n", len(t.Conns))
428 sort.Sort(&worstConns{
433 for i, c := range t.Conns {
434 fmt.Fprintf(w, "%2d. ", i+1)
439 func (t *torrent) String() string {
442 s = fmt.Sprintf("%x", t.InfoHash)
447 func (t *torrent) haveInfo() bool {
448 return t != nil && t.Info != nil
451 // TODO: Include URIs that weren't converted to tracker clients.
452 func (t *torrent) announceList() (al [][]string) {
453 for _, tier := range t.Trackers {
455 for _, tr := range tier {
456 l = append(l, tr.URL())
463 // Returns a run-time generated MetaInfo that includes the info bytes and
464 // announce-list as currently known to the client.
465 func (t *torrent) MetaInfo() *metainfo.MetaInfo {
466 if t.MetaData == nil {
467 panic("info bytes not set")
469 return &metainfo.MetaInfo{
470 Info: metainfo.InfoEx{
474 CreationDate: time.Now().Unix(),
475 Comment: "dynamic metainfo from client",
476 CreatedBy: "go.torrent",
477 AnnounceList: t.announceList(),
481 func (t *torrent) bytesLeft() (left int64) {
485 for i := 0; i < t.numPieces(); i++ {
486 left += int64(t.pieceNumPendingBytes(i))
491 func (t *torrent) piecePartiallyDownloaded(index int) bool {
492 pendingBytes := t.pieceNumPendingBytes(index)
493 return pendingBytes != 0 && pendingBytes != t.pieceLength(index)
496 func numChunksForPiece(chunkSize int, pieceSize int) int {
497 return (pieceSize + chunkSize - 1) / chunkSize
500 func (t *torrent) usualPieceSize() int {
501 return int(t.Info.PieceLength)
504 func (t *torrent) lastPieceSize() int {
505 return int(t.pieceLength(t.numPieces() - 1))
508 func (t *torrent) numPieces() int {
509 return t.Info.NumPieces()
512 func (t *torrent) numPiecesCompleted() (num int) {
513 for i := range iter.N(t.Info.NumPieces()) {
514 if t.pieceComplete(i) {
521 func (t *torrent) Length() int64 {
525 func (t *torrent) isClosed() bool {
534 func (t *torrent) close() (err error) {
540 if c, ok := t.data.(io.Closer); ok {
543 for _, conn := range t.Conns {
546 t.pieceStateChanges.Close()
550 func (t *torrent) requestOffset(r request) int64 {
551 return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
554 // Return the request that would include the given offset into the torrent
555 // data. Returns !ok if there is no such request.
556 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
557 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, int64(t.chunkSize), off)
560 func (t *torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
561 n, err := t.data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
562 if err == nil && n != len(data) {
563 err = io.ErrShortWrite
568 func (t *torrent) bitfield() (bf []bool) {
569 for _, p := range t.Pieces {
570 // TODO: Check this logic.
571 bf = append(bf, p.EverHashed && p.numPendingChunks() == 0)
576 func (t *torrent) validOutgoingRequest(r request) bool {
577 if r.Index >= pp.Integer(t.Info.NumPieces()) {
580 if r.Begin%t.chunkSize != 0 {
583 if r.Length > t.chunkSize {
586 pieceLength := t.pieceLength(int(r.Index))
587 if r.Begin+r.Length > pieceLength {
590 return r.Length == t.chunkSize || r.Begin+r.Length == pieceLength
593 func (t *torrent) pieceChunks(piece int) (css []chunkSpec) {
594 css = make([]chunkSpec, 0, (t.pieceLength(piece)+t.chunkSize-1)/t.chunkSize)
596 for left := t.pieceLength(piece); left != 0; left -= cs.Length {
598 if cs.Length > t.chunkSize {
599 cs.Length = t.chunkSize
601 css = append(css, cs)
602 cs.Begin += cs.Length
607 func (t *torrent) pendAllChunkSpecs(pieceIndex int) {
608 piece := t.Pieces[pieceIndex]
609 if piece.PendingChunkSpecs == nil {
610 // Allocate to exact size.
611 piece.PendingChunkSpecs = make([]bool, (t.pieceLength(pieceIndex)+t.chunkSize-1)/t.chunkSize)
613 // Pend all the chunks.
614 pcss := piece.PendingChunkSpecs
615 for i := range pcss {
626 // Peer is known to support encryption.
627 SupportsEncryption bool
630 func (t *torrent) pieceLength(piece int) (len_ pp.Integer) {
631 if int(piece) == t.numPieces()-1 {
632 len_ = pp.Integer(t.Length() % t.Info.PieceLength)
635 len_ = pp.Integer(t.Info.PieceLength)
640 func (t *torrent) hashPiece(piece pp.Integer) (ps pieceSum) {
641 hash := pieceHash.New()
643 p.pendingWritesMutex.Lock()
644 for p.pendingWrites != 0 {
645 p.noPendingWrites.Wait()
647 p.pendingWritesMutex.Unlock()
648 t.data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, t.Info.PieceLength)
649 missinggo.CopyExact(ps[:], hash.Sum(nil))
653 func (t *torrent) haveAllPieces() bool {
657 for i := range t.Pieces {
658 if !t.pieceComplete(i) {
665 func (me *torrent) haveAnyPieces() bool {
666 for i := range me.Pieces {
667 if me.pieceComplete(i) {
674 func (t *torrent) havePiece(index int) bool {
675 return t.haveInfo() && t.pieceComplete(index)
678 func (t *torrent) haveChunk(r request) bool {
682 if t.pieceComplete(int(r.Index)) {
685 p := t.Pieces[r.Index]
686 if p.PendingChunkSpecs == nil {
689 return !p.pendingChunk(r.chunkSpec, t.chunkSize)
692 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
693 return int(cs.Begin / chunkSize)
696 // TODO: This should probably be called wantPiece.
697 func (t *torrent) wantChunk(r request) bool {
698 if !t.wantPiece(int(r.Index)) {
701 if t.Pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
708 func (t *torrent) urgentChunkInPiece(piece int) bool {
709 p := pp.Integer(piece)
710 for req := range t.urgent {
718 // TODO: This should be called wantPieceIndex.
719 func (t *torrent) wantPiece(index int) bool {
730 if p.Priority == PiecePriorityNone {
731 if !t.urgentChunkInPiece(index) {
735 // Put piece complete check last, since it's the slowest as it can involve
736 // calling out into external data stores.
737 return !t.pieceComplete(index)
740 func (t *torrent) connHasWantedPieces(c *connection) bool {
741 return c.pieceRequestOrder != nil && !c.pieceRequestOrder.Empty()
744 func (t *torrent) extentPieces(off, _len int64) (pieces []int) {
745 for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
746 pieces = append(pieces, int(i))
751 func (t *torrent) worstBadConn(cl *Client) *connection {
752 wcs := t.worstConns(cl)
755 c := heap.Pop(wcs).(*connection)
756 if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
759 if wcs.Len() >= (socketsPerTorrent+1)/2 {
760 // Give connections 1 minute to prove themselves.
761 if time.Since(c.completedHandshake) > time.Minute {
769 func (t *torrent) publishPieceChange(piece int) {
770 cur := t.pieceState(piece)
772 if cur != p.PublicPieceState {
773 t.pieceStateChanges.Publish(piece)
775 p.PublicPieceState = cur