]> Sergey Matveev's repositories - btrtrc.git/blob - reader.go
Remove unused functions
[btrtrc.git] / reader.go
1 package torrent
2
3 import (
4         "errors"
5         "io"
6         "log"
7         "os"
8         "sync"
9
10         "github.com/anacrolix/missinggo"
11         "golang.org/x/net/context"
12 )
13
14 // Piece range by piece index, [begin, end).
15 type pieceRange struct {
16         begin, end int
17 }
18
19 // Accesses Torrent data via a Client. Reads block until the data is
20 // available. Seeks and readahead also drive Client behaviour.
21 type Reader struct {
22         t          *Torrent
23         responsive bool
24         // Ensure operations that change the position are exclusive, like Read()
25         // and Seek().
26         opMu sync.Mutex
27
28         // Required when modifying pos and readahead, or reading them without
29         // opMu.
30         mu        sync.Locker
31         pos       int64
32         readahead int64
33         // The cached piece range this reader wants downloaded. The zero value
34         // corresponds to nothing. We cache this so that changes can be detected,
35         // and bubbled up to the Torrent only as required.
36         pieces pieceRange
37 }
38
39 var _ io.ReadCloser = &Reader{}
40
41 // Don't wait for pieces to complete and be verified. Read calls return as
42 // soon as they can when the underlying chunks become available.
43 func (r *Reader) SetResponsive() {
44         r.responsive = true
45 }
46
47 // Disable responsive mode.
48 func (r *Reader) SetNonResponsive() {
49         r.responsive = false
50 }
51
52 // Configure the number of bytes ahead of a read that should also be
53 // prioritized in preparation for further reads.
54 func (r *Reader) SetReadahead(readahead int64) {
55         r.mu.Lock()
56         r.readahead = readahead
57         r.mu.Unlock()
58         r.t.cl.mu.Lock()
59         defer r.t.cl.mu.Unlock()
60         r.posChanged()
61 }
62
63 // Return reader's current position.
64 func (r *Reader) CurrentPos() int64 {
65         return r.pos
66 }
67
68 func (r *Reader) readable(off int64) (ret bool) {
69         if r.t.closed.IsSet() {
70                 return true
71         }
72         req, ok := r.t.offsetRequest(off)
73         if !ok {
74                 panic(off)
75         }
76         if r.responsive {
77                 return r.t.haveChunk(req)
78         }
79         return r.t.pieceComplete(int(req.Index))
80 }
81
82 // How many bytes are available to read. Max is the most we could require.
83 func (r *Reader) available(off, max int64) (ret int64) {
84         for max > 0 {
85                 req, ok := r.t.offsetRequest(off)
86                 if !ok {
87                         break
88                 }
89                 if !r.t.haveChunk(req) {
90                         break
91                 }
92                 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
93                 max -= len1
94                 ret += len1
95                 off += len1
96         }
97         // Ensure that ret hasn't exceeded our original max.
98         if max < 0 {
99                 ret += max
100         }
101         return
102 }
103
104 func (r *Reader) waitReadable(off int64) {
105         // We may have been sent back here because we were told we could read but
106         // it failed.
107         r.t.cl.event.Wait()
108 }
109
110 // Calculates the pieces this reader wants downloaded, ignoring the cached
111 // value at r.pieces.
112 func (r *Reader) piecesUncached() (ret pieceRange) {
113         ra := r.readahead
114         if ra < 1 {
115                 ra = 1
116         }
117         ret.begin, ret.end = r.t.byteRegionPieces(r.pos, ra)
118         return
119 }
120
121 func (r *Reader) Read(b []byte) (n int, err error) {
122         return r.ReadContext(b, context.Background())
123 }
124
125 func (r *Reader) ReadContext(b []byte, ctx context.Context) (n int, err error) {
126         // This is set under the Client lock if the Context is canceled.
127         var ctxErr error
128         if ctx.Done() != nil {
129                 ctx, cancel := context.WithCancel(ctx)
130                 // Abort the goroutine when the function returns.
131                 defer cancel()
132                 go func() {
133                         <-ctx.Done()
134                         r.t.cl.mu.Lock()
135                         ctxErr = ctx.Err()
136                         r.t.cl.event.Broadcast()
137                         r.t.cl.mu.Unlock()
138                 }()
139         }
140         // Hmmm, if a Read gets stuck, this means you can't change position for
141         // other purposes. That seems reasonable, but unusual.
142         r.opMu.Lock()
143         defer r.opMu.Unlock()
144         for len(b) != 0 {
145                 var n1 int
146                 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
147                 if n1 == 0 {
148                         if err == nil {
149                                 panic("expected error")
150                         }
151                         break
152                 }
153                 b = b[n1:]
154                 n += n1
155                 r.mu.Lock()
156                 r.pos += int64(n1)
157                 r.posChanged()
158                 r.mu.Unlock()
159         }
160         if r.pos >= r.t.length {
161                 err = io.EOF
162         } else if err == io.EOF {
163                 err = io.ErrUnexpectedEOF
164         }
165         return
166 }
167
168 // Wait until some data should be available to read. Tickles the client if it
169 // isn't. Returns how much should be readable without blocking.
170 func (r *Reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
171         r.t.cl.mu.Lock()
172         defer r.t.cl.mu.Unlock()
173         for !r.readable(pos) && *ctxErr == nil {
174                 r.waitReadable(pos)
175         }
176         return r.available(pos, wanted)
177 }
178
179 // Performs at most one successful read to torrent storage.
180 func (r *Reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
181         if pos >= r.t.length {
182                 err = io.EOF
183                 return
184         }
185         for {
186                 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
187                 if avail == 0 {
188                         if r.t.closed.IsSet() {
189                                 err = errors.New("torrent closed")
190                                 return
191                         }
192                         if *ctxErr != nil {
193                                 err = *ctxErr
194                                 return
195                         }
196                 }
197                 b1 := b[:avail]
198                 pi := int(pos / r.t.Info().PieceLength)
199                 ip := r.t.Info().Piece(pi)
200                 po := pos % r.t.Info().PieceLength
201                 missinggo.LimitLen(&b1, ip.Length()-po)
202                 n, err = r.t.readAt(b1, pos)
203                 if n != 0 {
204                         err = nil
205                         return
206                 }
207                 r.t.cl.mu.Lock()
208                 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
209                 r.t.updateAllPieceCompletions()
210                 r.t.updateAllPiecePriorities()
211                 r.t.cl.mu.Unlock()
212         }
213 }
214
215 func (r *Reader) Close() error {
216         r.t.cl.mu.Lock()
217         defer r.t.cl.mu.Unlock()
218         r.t.deleteReader(r)
219         return nil
220 }
221
222 func (r *Reader) posChanged() {
223         to := r.piecesUncached()
224         from := r.pieces
225         if to == from {
226                 return
227         }
228         r.pieces = to
229         r.t.readerPosChanged(from, to)
230 }
231
232 func (r *Reader) Seek(off int64, whence int) (ret int64, err error) {
233         r.opMu.Lock()
234         defer r.opMu.Unlock()
235
236         r.mu.Lock()
237         defer r.mu.Unlock()
238         switch whence {
239         case os.SEEK_SET:
240                 r.pos = off
241         case os.SEEK_CUR:
242                 r.pos += off
243         case os.SEEK_END:
244                 r.pos = r.t.info.TotalLength() + off
245         default:
246                 err = errors.New("bad whence")
247         }
248         ret = r.pos
249
250         r.posChanged()
251         return
252 }
253
254 func (r *Reader) Torrent() *Torrent {
255         return r.t
256 }