13 "github.com/RoaringBitmap/roaring"
14 "github.com/anacrolix/torrent/common"
15 "github.com/anacrolix/torrent/metainfo"
16 "github.com/anacrolix/torrent/segments"
19 type RequestSpec = segments.Extent
21 type requestPartResult struct {
26 type requestPart struct {
29 result chan requestPartResult
35 Result chan RequestResult
38 func (r Request) Cancel() {
43 HttpClient *http.Client
45 fileIndex segments.Index
47 // The pieces we can request with the Url. We're more likely to ban/block at the file-level
48 // given that's how requests are mapped to webseeds, but the torrent.Client works at the piece
49 // level. We can map our file-level adjustments to the pieces here. This probably need to be
50 // private in the future, if Client ever starts removing pieces.
54 func (me *Client) SetInfo(info *metainfo.Info) {
55 if !strings.HasSuffix(me.Url, "/") && info.IsDir() {
56 // In my experience, this is a non-conforming webseed. For example the
57 // http://ia600500.us.archive.org/1/items URLs in archive.org torrents.
60 me.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
62 me.Pieces.AddRange(0, uint64(info.NumPieces()))
65 type RequestResult struct {
70 func (ws *Client) NewRequest(r RequestSpec) Request {
71 ctx, cancel := context.WithCancel(context.Background())
72 var requestParts []requestPart
73 if !ws.fileIndex.Locate(r, func(i int, e segments.Extent) bool {
74 req, err := NewRequest(ws.Url, i, ws.info, e.Start, e.Length)
78 req = req.WithContext(ctx)
81 result: make(chan requestPartResult, 1),
86 resp, err := ws.HttpClient.Do(req)
87 part.result <- requestPartResult{
93 requestParts = append(requestParts, part)
96 panic("request out of file bounds")
100 Result: make(chan RequestResult, 1),
103 b, err := readRequestPartResponses(ctx, requestParts)
104 req.Result <- RequestResult{
112 type ErrBadResponse struct {
114 Response *http.Response
117 func (me ErrBadResponse) Error() string {
121 func recvPartResult(ctx context.Context, buf io.Writer, part requestPart) error {
122 result := <-part.result
123 // Make sure there's no further results coming, it should be a one-shot channel.
125 if result.err != nil {
128 defer result.resp.Body.Close()
129 if ctx.Err() != nil {
132 switch result.resp.StatusCode {
133 case http.StatusPartialContent:
134 copied, err := io.Copy(buf, result.resp.Body)
138 if copied != part.e.Length {
139 return fmt.Errorf("got %v bytes, expected %v", copied, part.e.Length)
143 // This number is based on
144 // https://archive.org/download/BloodyPitOfHorror/BloodyPitOfHorror.asr.srt. It seems that
145 // archive.org might be using a webserver implementation that refuses to do partial
146 // responses to small files.
147 if part.e.Start < 48<<10 {
148 if part.e.Start != 0 {
149 log.Printf("resp status ok but requested range [url=%q, range=%q]",
151 part.req.Header.Get("Range"))
153 // Instead of discarding, we could try receiving all the chunks present in the response
154 // body. I don't know how one would handle multiple chunk requests resulting in an OK
155 // response for the same file. The request algorithm might be need to be smarter for
157 discarded, _ := io.CopyN(io.Discard, result.resp.Body, part.e.Start)
159 log.Printf("discarded %v bytes in webseed request response part", discarded)
161 _, err := io.CopyN(buf, result.resp.Body, part.e.Length)
164 return ErrBadResponse{"resp status ok but requested range", result.resp}
166 case http.StatusServiceUnavailable:
169 return ErrBadResponse{
170 fmt.Sprintf("unhandled response status code (%v)", result.resp.StatusCode),
176 var ErrTooFast = errors.New("making requests too fast")
178 func readRequestPartResponses(ctx context.Context, parts []requestPart) (_ []byte, err error) {
180 for _, part := range parts {
182 err = recvPartResult(ctx, &buf, part)
184 err = fmt.Errorf("reading %q at %q: %w", part.req.URL, part.req.Header.Get("Range"), err)
188 return buf.Bytes(), err