]> Sergey Matveev's repositories - btrtrc.git/blob - torrent.go
d6279f2dda626c226e29b26e1b3c9c713b2c0b48
[btrtrc.git] / torrent.go
1 package torrent
2
3 import (
4         "container/list"
5         "fmt"
6         "net"
7         "sort"
8
9         "bitbucket.org/anacrolix/go.torrent/peer_protocol"
10         "bitbucket.org/anacrolix/go.torrent/tracker"
11         metainfo "github.com/nsf/libtorgo/torrent"
12 )
13
14 func (t *Torrent) PieceNumPendingBytes(index peer_protocol.Integer) (count peer_protocol.Integer) {
15         pendingChunks := t.Pieces[index].PendingChunkSpecs
16         count = peer_protocol.Integer(len(pendingChunks)) * chunkSize
17         _lastChunkSpec := lastChunkSpec(t.PieceLength(index))
18         if _lastChunkSpec.Length != chunkSize {
19                 if _, ok := pendingChunks[_lastChunkSpec]; ok {
20                         count += _lastChunkSpec.Length - chunkSize
21                 }
22         }
23         return
24 }
25
26 type Torrent struct {
27         InfoHash   InfoHash
28         Pieces     []*piece
29         Data       MMapSpan
30         MetaInfo   *metainfo.MetaInfo
31         Conns      []*Connection
32         Peers      []Peer
33         Priorities *list.List
34         // BEP 12 Multitracker Metadata Extension. The tracker.Client instances
35         // mirror their respective URLs from the announce-list key.
36         Trackers [][]tracker.Client
37 }
38
39 func (t *Torrent) NumPieces() int {
40         return len(t.MetaInfo.Pieces) / PieceHash.Size()
41 }
42
43 func (t *Torrent) NumPiecesCompleted() (num int) {
44         for _, p := range t.Pieces {
45                 if p.Complete() {
46                         num++
47                 }
48         }
49         return
50 }
51
52 func (t *Torrent) Length() int64 {
53         return int64(t.PieceLength(peer_protocol.Integer(len(t.Pieces)-1))) + int64(len(t.Pieces)-1)*int64(t.PieceLength(0))
54 }
55
56 func (t *Torrent) Close() (err error) {
57         t.Data.Close()
58         for _, conn := range t.Conns {
59                 conn.Close()
60         }
61         return
62 }
63
64 func (t *Torrent) piecesByPendingBytesDesc() (indices []peer_protocol.Integer) {
65         slice := pieceByBytesPendingSlice{
66                 Pending: make([]peer_protocol.Integer, 0, len(t.Pieces)),
67                 Indices: make([]peer_protocol.Integer, 0, len(t.Pieces)),
68         }
69         for i := range t.Pieces {
70                 slice.Pending = append(slice.Pending, t.PieceNumPendingBytes(peer_protocol.Integer(i)))
71                 slice.Indices = append(slice.Indices, peer_protocol.Integer(i))
72         }
73         sort.Sort(sort.Reverse(slice))
74         return slice.Indices
75 }
76
77 // Return the request that would include the given offset into the torrent data.
78 func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
79         r Request, ok bool) {
80         if offset < 0 || offset >= torrentLength {
81                 return
82         }
83         r.Index = peer_protocol.Integer(offset / pieceSize)
84         r.Begin = peer_protocol.Integer(offset % pieceSize / chunkSize * chunkSize)
85         left := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
86         if chunkSize < left {
87                 r.Length = peer_protocol.Integer(chunkSize)
88         } else {
89                 r.Length = peer_protocol.Integer(left)
90         }
91         ok = true
92         return
93 }
94
95 func torrentRequestOffset(torrentLength, pieceSize int64, r Request) (off int64) {
96         off = int64(r.Index)*pieceSize + int64(r.Begin)
97         if off < 0 || off >= torrentLength {
98                 panic("invalid request")
99         }
100         return
101 }
102
103 func (t *Torrent) requestOffset(r Request) int64 {
104         return torrentRequestOffset(t.Length(), t.MetaInfo.PieceLength, r)
105 }
106
107 // Return the request that would include the given offset into the torrent data.
108 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
109         return torrentOffsetRequest(t.Length(), t.MetaInfo.PieceLength, chunkSize, off)
110 }
111
112 func (t *Torrent) WriteChunk(piece int, begin int64, data []byte) (err error) {
113         _, err = t.Data.WriteAt(data, int64(piece)*t.MetaInfo.PieceLength+begin)
114         return
115 }
116
117 func (t *Torrent) bitfield() (bf []bool) {
118         for _, p := range t.Pieces {
119                 bf = append(bf, p.EverHashed && len(p.PendingChunkSpecs) == 0)
120         }
121         return
122 }
123
124 func (t *Torrent) pendAllChunkSpecs(index peer_protocol.Integer) {
125         piece := t.Pieces[index]
126         if piece.PendingChunkSpecs == nil {
127                 piece.PendingChunkSpecs = make(
128                         map[ChunkSpec]struct{},
129                         (t.MetaInfo.PieceLength+chunkSize-1)/chunkSize)
130         }
131         c := ChunkSpec{
132                 Begin: 0,
133         }
134         cs := piece.PendingChunkSpecs
135         for left := peer_protocol.Integer(t.PieceLength(index)); left != 0; left -= c.Length {
136                 c.Length = left
137                 if c.Length > chunkSize {
138                         c.Length = chunkSize
139                 }
140                 cs[c] = struct{}{}
141                 c.Begin += c.Length
142         }
143         return
144 }
145
146 func (t *Torrent) requestHeat() (ret map[Request]int) {
147         ret = make(map[Request]int)
148         for _, conn := range t.Conns {
149                 for req, _ := range conn.Requests {
150                         ret[req]++
151                 }
152         }
153         return
154 }
155
156 type Peer struct {
157         Id   [20]byte
158         IP   net.IP
159         Port int
160 }
161
162 func (t *Torrent) PieceLength(piece peer_protocol.Integer) (len_ peer_protocol.Integer) {
163         if int(piece) == t.NumPieces()-1 {
164                 len_ = peer_protocol.Integer(t.Data.Size() % t.MetaInfo.PieceLength)
165         }
166         if len_ == 0 {
167                 len_ = peer_protocol.Integer(t.MetaInfo.PieceLength)
168         }
169         return
170 }
171
172 func (t *Torrent) HashPiece(piece peer_protocol.Integer) (ps pieceSum) {
173         hash := PieceHash.New()
174         n, err := t.Data.WriteSectionTo(hash, int64(piece)*t.MetaInfo.PieceLength, t.MetaInfo.PieceLength)
175         if err != nil {
176                 panic(err)
177         }
178         if peer_protocol.Integer(n) != t.PieceLength(piece) {
179                 panic(fmt.Sprintf("hashed wrong number of bytes: expected %d; did %d; piece %d", t.PieceLength(piece), n, piece))
180         }
181         copyHashSum(ps[:], hash.Sum(nil))
182         return
183 }
184 func (t *Torrent) haveAllPieces() bool {
185         for _, piece := range t.Pieces {
186                 if !piece.Complete() {
187                         return false
188                 }
189         }
190         return true
191 }
192
193 func (me *Torrent) haveAnyPieces() bool {
194         for _, piece := range me.Pieces {
195                 if piece.Complete() {
196                         return true
197                 }
198         }
199         return false
200 }
201
202 func (t *Torrent) wantPiece(index int) bool {
203         p := t.Pieces[index]
204         return p.EverHashed && len(p.PendingChunkSpecs) != 0
205 }