4 "bitbucket.org/anacrolix/go.torrent/mmap_span"
5 pp "bitbucket.org/anacrolix/go.torrent/peer_protocol"
6 "bitbucket.org/anacrolix/go.torrent/tracker"
9 "github.com/anacrolix/libtorgo/bencode"
10 "github.com/anacrolix/libtorgo/metainfo"
17 func (t *torrent) PieceNumPendingBytes(index pp.Integer) (count pp.Integer) {
18 pendingChunks := t.Pieces[index].PendingChunkSpecs
19 count = pp.Integer(len(pendingChunks)) * chunkSize
20 _lastChunkSpec := lastChunkSpec(t.PieceLength(index))
21 if _lastChunkSpec.Length != chunkSize {
22 if _, ok := pendingChunks[_lastChunkSpec]; ok {
23 count += _lastChunkSpec.Length - chunkSize
29 type pieceBytesLeft struct {
33 type torrentPiece struct {
35 bytesLeftElement *list.Element
41 Pieces []*torrentPiece
42 PiecesByBytesLeft *OrderedList
43 Data mmap_span.MMapSpan
44 // Prevent mutations to Data memory maps while in use as they're not safe.
49 // BEP 12 Multitracker Metadata Extension. The tracker.Client instances
50 // mirror their respective URLs from the announce-list key.
51 Trackers [][]tracker.Client
57 func (t *torrent) InvalidateMetadata() {
63 func (t *torrent) SaveMetadataPiece(index int, data []byte) {
67 if index >= len(t.metadataHave) {
68 log.Printf("%s: ignoring metadata piece %d", t, index)
71 copy(t.MetaData[(1<<14)*index:], data)
72 t.metadataHave[index] = true
75 func (t *torrent) MetadataPieceCount() int {
76 return (len(t.MetaData) + (1 << 14) - 1) / (1 << 14)
79 func (t *torrent) HaveMetadataPiece(piece int) bool {
80 return t.haveInfo() || t.metadataHave[piece]
83 func (t *torrent) metadataSizeKnown() bool {
84 return t.MetaData != nil
87 func (t *torrent) metadataSize() int {
88 return len(t.MetaData)
91 func infoPieceHashes(info *metainfo.Info) (ret []string) {
92 for i := 0; i < len(info.Pieces); i += 20 {
93 ret = append(ret, string(info.Pieces[i:i+20]))
98 // Called when metadata for a torrent becomes available.
99 func (t *torrent) setMetadata(md metainfo.Info, dataDir string, infoBytes []byte) (err error) {
101 t.MetaData = infoBytes
103 t.Data, err = mmapTorrentData(&md, dataDir)
107 t.PiecesByBytesLeft = NewList(func(a, b interface{}) bool {
108 apb := t.PieceNumPendingBytes(pp.Integer(a.(int)))
109 bpb := t.PieceNumPendingBytes(pp.Integer(b.(int)))
116 return a.(int) < b.(int)
118 for index, hash := range infoPieceHashes(&md) {
119 piece := &torrentPiece{}
120 copyHashSum(piece.Hash[:], []byte(hash))
121 t.Pieces = append(t.Pieces, piece)
122 piece.bytesLeftElement = t.PiecesByBytesLeft.Insert(index)
123 t.pendAllChunkSpecs(pp.Integer(index))
125 for _, conn := range t.Conns {
126 if err := conn.setNumPieces(t.NumPieces()); err != nil {
127 log.Printf("closing connection: %s", err)
134 func (t *torrent) HaveAllMetadataPieces() bool {
138 if t.metadataHave == nil {
141 for _, have := range t.metadataHave {
149 func (t *torrent) SetMetadataSize(bytes int64) {
150 if t.MetaData != nil {
153 t.MetaData = make([]byte, bytes)
154 t.metadataHave = make([]bool, (bytes+(1<<14)-1)/(1<<14))
157 func (t *torrent) Name() string {
164 func (t *torrent) pieceStatusChar(index int) byte {
169 case p.QueuedForHash:
173 case t.PiecePartiallyDownloaded(index):
180 func (t *torrent) metadataPieceSize(piece int) int {
181 return metadataPieceSize(len(t.MetaData), piece)
184 func (t *torrent) NewMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
190 d["total_size"] = len(t.MetaData)
192 p, err := bencode.Marshal(d)
198 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
199 ExtendedPayload: append(p, data...),
204 func (t *torrent) WriteStatus(w io.Writer) {
205 fmt.Fprintf(w, "Infohash: %x\n", t.InfoHash)
206 fmt.Fprint(w, "Pieces: ")
207 for index := range t.Pieces {
208 fmt.Fprintf(w, "%c", t.pieceStatusChar(index))
211 // fmt.Fprintln(w, "Priorities: ")
212 // if t.Priorities != nil {
213 // for e := t.Priorities.Front(); e != nil; e = e.Next() {
214 // fmt.Fprintf(w, "\t%v\n", e.Value)
217 fmt.Fprintf(w, "Pending peers: %d\n", len(t.Peers))
218 for _, c := range t.Conns {
223 func (t *torrent) String() string {
227 func (t *torrent) haveInfo() bool {
231 func (t *torrent) BytesLeft() (left int64) {
235 for i := pp.Integer(0); i < pp.Integer(t.NumPieces()); i++ {
236 left += int64(t.PieceNumPendingBytes(i))
241 func (t *torrent) PiecePartiallyDownloaded(index int) bool {
242 return t.PieceNumPendingBytes(pp.Integer(index)) != t.PieceLength(pp.Integer(index))
245 func NumChunksForPiece(chunkSize int, pieceSize int) int {
246 return (pieceSize + chunkSize - 1) / chunkSize
249 func (t *torrent) ChunkCount() (num int) {
250 num += (t.NumPieces() - 1) * NumChunksForPiece(chunkSize, int(t.PieceLength(0)))
251 num += NumChunksForPiece(chunkSize, int(t.PieceLength(pp.Integer(t.NumPieces()-1))))
255 func (t *torrent) UsualPieceSize() int {
256 return int(t.Info.PieceLength)
259 func (t *torrent) LastPieceSize() int {
260 return int(t.PieceLength(pp.Integer(t.NumPieces() - 1)))
263 func (t *torrent) NumPieces() int {
264 return len(t.Info.Pieces) / 20
267 func (t *torrent) NumPiecesCompleted() (num int) {
268 for _, p := range t.Pieces {
276 func (t *torrent) Length() int64 {
277 return int64(t.LastPieceSize()) + int64(len(t.Pieces)-1)*int64(t.UsualPieceSize())
280 func (t *torrent) isClosed() bool {
284 func (t *torrent) Close() (err error) {
290 for _, conn := range t.Conns {
296 // Return the request that would include the given offset into the torrent data.
297 func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
298 r request, ok bool) {
299 if offset < 0 || offset >= torrentLength {
302 r.Index = pp.Integer(offset / pieceSize)
303 r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
304 left := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
305 if chunkSize < left {
306 r.Length = pp.Integer(chunkSize)
308 r.Length = pp.Integer(left)
314 func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
315 off = int64(r.Index)*pieceSize + int64(r.Begin)
316 if off < 0 || off >= torrentLength {
317 panic("invalid request")
322 func (t *torrent) requestOffset(r request) int64 {
323 return torrentRequestOffset(t.Length(), int64(t.UsualPieceSize()), r)
326 // Return the request that would include the given offset into the torrent data.
327 func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
328 return torrentOffsetRequest(t.Length(), t.Info.PieceLength, chunkSize, off)
331 func (t *torrent) WriteChunk(piece int, begin int64, data []byte) (err error) {
332 _, err = t.Data.WriteAt(data, int64(piece)*t.Info.PieceLength+begin)
336 func (t *torrent) bitfield() (bf []bool) {
337 for _, p := range t.Pieces {
338 bf = append(bf, p.EverHashed && len(p.PendingChunkSpecs) == 0)
343 func (t *torrent) pendAllChunkSpecs(index pp.Integer) {
344 piece := t.Pieces[index]
345 if piece.PendingChunkSpecs == nil {
346 piece.PendingChunkSpecs = make(
347 map[chunkSpec]struct{},
348 (t.Info.PieceLength+chunkSize-1)/chunkSize)
353 cs := piece.PendingChunkSpecs
354 for left := pp.Integer(t.PieceLength(index)); left != 0; left -= c.Length {
356 if c.Length > chunkSize {
362 t.PiecesByBytesLeft.ValueChanged(piece.bytesLeftElement)
373 func (t *torrent) PieceLength(piece pp.Integer) (len_ pp.Integer) {
374 if int(piece) == t.NumPieces()-1 {
375 len_ = pp.Integer(t.Data.Size() % t.Info.PieceLength)
378 len_ = pp.Integer(t.Info.PieceLength)
383 func (t *torrent) HashPiece(piece pp.Integer) (ps pieceSum) {
384 hash := pieceHash.New()
386 n, err := t.Data.WriteSectionTo(hash, int64(piece)*t.Info.PieceLength, t.Info.PieceLength)
391 if pp.Integer(n) != t.PieceLength(piece) {
393 panic(fmt.Sprintf("hashed wrong number of bytes: expected %d; did %d; piece %d", t.PieceLength(piece), n, piece))
395 copyHashSum(ps[:], hash.Sum(nil))
398 func (t *torrent) haveAllPieces() bool {
402 for _, piece := range t.Pieces {
403 if !piece.Complete() {
410 func (me *torrent) haveAnyPieces() bool {
411 for _, piece := range me.Pieces {
412 if piece.Complete() {
419 func (t *torrent) wantChunk(r request) bool {
420 if !t.wantPiece(int(r.Index)) {
423 _, ok := t.Pieces[r.Index].PendingChunkSpecs[r.chunkSpec]
427 func (t *torrent) wantPiece(index int) bool {
432 return p.EverHashed && len(p.PendingChunkSpecs) != 0