13 "github.com/RoaringBitmap/roaring"
15 "github.com/anacrolix/torrent/common"
16 "github.com/anacrolix/torrent/metainfo"
17 "github.com/anacrolix/torrent/segments"
20 type RequestSpec = segments.Extent
22 type requestPartResult struct {
27 type requestPart struct {
30 result chan requestPartResult
32 // Wrap http response bodies for such things as download rate limiting.
33 responseBodyWrapper ResponseBodyWrapper
38 Result chan RequestResult
41 func (r Request) Cancel() {
46 HttpClient *http.Client
48 fileIndex segments.Index
50 // The pieces we can request with the Url. We're more likely to ban/block at the file-level
51 // given that's how requests are mapped to webseeds, but the torrent.Client works at the piece
52 // level. We can map our file-level adjustments to the pieces here. This probably need to be
53 // private in the future, if Client ever starts removing pieces.
55 ResponseBodyWrapper ResponseBodyWrapper
56 PathEscaper PathEscaper
59 type ResponseBodyWrapper func(io.Reader) io.Reader
61 func (me *Client) SetInfo(info *metainfo.Info) {
62 if !strings.HasSuffix(me.Url, "/") && info.IsDir() {
63 // In my experience, this is a non-conforming webseed. For example the
64 // http://ia600500.us.archive.org/1/items URLs in archive.org torrents.
67 me.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
69 me.Pieces.AddRange(0, uint64(info.NumPieces()))
72 type RequestResult struct {
77 func (ws *Client) NewRequest(r RequestSpec) Request {
78 ctx, cancel := context.WithCancel(context.Background())
79 var requestParts []requestPart
80 if !ws.fileIndex.Locate(r, func(i int, e segments.Extent) bool {
81 req, err := newRequest(
82 ws.Url, i, ws.info, e.Start, e.Length,
88 req = req.WithContext(ctx)
91 result: make(chan requestPartResult, 1),
93 responseBodyWrapper: ws.ResponseBodyWrapper,
97 resp, err := ws.HttpClient.Do(req)
98 part.result <- requestPartResult{
104 requestParts = append(requestParts, part)
107 panic("request out of file bounds")
111 Result: make(chan RequestResult, 1),
114 b, err := readRequestPartResponses(ctx, requestParts)
115 req.Result <- RequestResult{
123 type ErrBadResponse struct {
125 Response *http.Response
128 func (me ErrBadResponse) Error() string {
132 func recvPartResult(ctx context.Context, buf io.Writer, part requestPart) error {
133 result := <-part.result
134 // Make sure there's no further results coming, it should be a one-shot channel.
136 if result.err != nil {
139 defer result.resp.Body.Close()
140 var body io.Reader = result.resp.Body
141 if part.responseBodyWrapper != nil {
142 body = part.responseBodyWrapper(body)
144 // Prevent further accidental use
145 result.resp.Body = nil
146 if ctx.Err() != nil {
149 switch result.resp.StatusCode {
150 case http.StatusPartialContent:
151 copied, err := io.Copy(buf, body)
155 if copied != part.e.Length {
156 return fmt.Errorf("got %v bytes, expected %v", copied, part.e.Length)
160 // This number is based on
161 // https://archive.org/download/BloodyPitOfHorror/BloodyPitOfHorror.asr.srt. It seems that
162 // archive.org might be using a webserver implementation that refuses to do partial
163 // responses to small files.
164 if part.e.Start < 48<<10 {
165 if part.e.Start != 0 {
166 log.Printf("resp status ok but requested range [url=%q, range=%q]",
168 part.req.Header.Get("Range"))
170 // Instead of discarding, we could try receiving all the chunks present in the response
171 // body. I don't know how one would handle multiple chunk requests resulting in an OK
172 // response for the same file. The request algorithm might be need to be smarter for
174 discarded, _ := io.CopyN(io.Discard, body, part.e.Start)
176 log.Printf("discarded %v bytes in webseed request response part", discarded)
178 _, err := io.CopyN(buf, body, part.e.Length)
181 return ErrBadResponse{"resp status ok but requested range", result.resp}
183 case http.StatusServiceUnavailable:
186 return ErrBadResponse{
187 fmt.Sprintf("unhandled response status code (%v)", result.resp.StatusCode),
193 var ErrTooFast = errors.New("making requests too fast")
195 func readRequestPartResponses(ctx context.Context, parts []requestPart) (_ []byte, err error) {
197 for _, part := range parts {
199 err = recvPartResult(ctx, &buf, part)
201 err = fmt.Errorf("reading %q at %q: %w", part.req.URL, part.req.Header.Get("Range"), err)
205 return buf.Bytes(), err