]> Sergey Matveev's repositories - btrtrc.git/blob - webseed/client.go
[webseed] Add a custom URL encoder for webseeds
[btrtrc.git] / webseed / client.go
1 package webseed
2
3 import (
4         "bytes"
5         "context"
6         "errors"
7         "fmt"
8         "io"
9         "log"
10         "net/http"
11         "strings"
12
13         "github.com/RoaringBitmap/roaring"
14         "github.com/anacrolix/torrent/common"
15         "github.com/anacrolix/torrent/metainfo"
16         "github.com/anacrolix/torrent/segments"
17 )
18
19 type RequestSpec = segments.Extent
20
21 type requestPartResult struct {
22         resp *http.Response
23         err  error
24 }
25
26 type requestPart struct {
27         req    *http.Request
28         e      segments.Extent
29         result chan requestPartResult
30         start  func()
31         // Wrap http response bodies for such things as download rate limiting.
32         responseBodyWrapper ResponseBodyWrapper
33 }
34
35 type Request struct {
36         cancel func()
37         Result chan RequestResult
38 }
39
40 func (r Request) Cancel() {
41         r.cancel()
42 }
43
44 type Spec struct {
45         Urls      []string
46         EncodeUrl func(string) string
47 }
48
49 type Client struct {
50         HttpClient *http.Client
51         Url        string
52         fileIndex  segments.Index
53         info       *metainfo.Info
54         // The pieces we can request with the Url. We're more likely to ban/block at the file-level
55         // given that's how requests are mapped to webseeds, but the torrent.Client works at the piece
56         // level. We can map our file-level adjustments to the pieces here. This probably need to be
57         // private in the future, if Client ever starts removing pieces.
58         Pieces              roaring.Bitmap
59         ResponseBodyWrapper ResponseBodyWrapper
60         EncodeUrl           func(string) string
61 }
62
63 type ResponseBodyWrapper func(io.Reader) io.Reader
64
65 func (me *Client) SetInfo(info *metainfo.Info) {
66         if !strings.HasSuffix(me.Url, "/") && info.IsDir() {
67                 // In my experience, this is a non-conforming webseed. For example the
68                 // http://ia600500.us.archive.org/1/items URLs in archive.org torrents.
69                 return
70         }
71         me.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
72         me.info = info
73         me.Pieces.AddRange(0, uint64(info.NumPieces()))
74 }
75
76 type RequestResult struct {
77         Bytes []byte
78         Err   error
79 }
80
81 func (ws *Client) NewRequest(r RequestSpec) Request {
82         ctx, cancel := context.WithCancel(context.Background())
83         var requestParts []requestPart
84         if !ws.fileIndex.Locate(r, func(i int, e segments.Extent) bool {
85                 req, err := NewRequestWithCustomUrlEncoding(
86                         ws.Url, i, ws.info, e.Start, e.Length,
87                         ws.EncodeUrl,
88                 )
89                 if err != nil {
90                         panic(err)
91                 }
92                 req = req.WithContext(ctx)
93                 part := requestPart{
94                         req:                 req,
95                         result:              make(chan requestPartResult, 1),
96                         e:                   e,
97                         responseBodyWrapper: ws.ResponseBodyWrapper,
98                 }
99                 part.start = func() {
100                         go func() {
101                                 resp, err := ws.HttpClient.Do(req)
102                                 part.result <- requestPartResult{
103                                         resp: resp,
104                                         err:  err,
105                                 }
106                         }()
107                 }
108                 requestParts = append(requestParts, part)
109                 return true
110         }) {
111                 panic("request out of file bounds")
112         }
113         req := Request{
114                 cancel: cancel,
115                 Result: make(chan RequestResult, 1),
116         }
117         go func() {
118                 b, err := readRequestPartResponses(ctx, requestParts)
119                 req.Result <- RequestResult{
120                         Bytes: b,
121                         Err:   err,
122                 }
123         }()
124         return req
125 }
126
127 type ErrBadResponse struct {
128         Msg      string
129         Response *http.Response
130 }
131
132 func (me ErrBadResponse) Error() string {
133         return me.Msg
134 }
135
136 func recvPartResult(ctx context.Context, buf io.Writer, part requestPart) error {
137         result := <-part.result
138         // Make sure there's no further results coming, it should be a one-shot channel.
139         close(part.result)
140         if result.err != nil {
141                 return result.err
142         }
143         defer result.resp.Body.Close()
144         var body io.Reader = result.resp.Body
145         if part.responseBodyWrapper != nil {
146                 body = part.responseBodyWrapper(body)
147         }
148         // Prevent further accidental use
149         result.resp.Body = nil
150         if ctx.Err() != nil {
151                 return ctx.Err()
152         }
153         switch result.resp.StatusCode {
154         case http.StatusPartialContent:
155                 copied, err := io.Copy(buf, body)
156                 if err != nil {
157                         return err
158                 }
159                 if copied != part.e.Length {
160                         return fmt.Errorf("got %v bytes, expected %v", copied, part.e.Length)
161                 }
162                 return nil
163         case http.StatusOK:
164                 // This number is based on
165                 // https://archive.org/download/BloodyPitOfHorror/BloodyPitOfHorror.asr.srt. It seems that
166                 // archive.org might be using a webserver implementation that refuses to do partial
167                 // responses to small files.
168                 if part.e.Start < 48<<10 {
169                         if part.e.Start != 0 {
170                                 log.Printf("resp status ok but requested range [url=%q, range=%q]",
171                                         part.req.URL,
172                                         part.req.Header.Get("Range"))
173                         }
174                         // Instead of discarding, we could try receiving all the chunks present in the response
175                         // body. I don't know how one would handle multiple chunk requests resulting in an OK
176                         // response for the same file. The request algorithm might be need to be smarter for
177                         // that.
178                         discarded, _ := io.CopyN(io.Discard, body, part.e.Start)
179                         if discarded != 0 {
180                                 log.Printf("discarded %v bytes in webseed request response part", discarded)
181                         }
182                         _, err := io.CopyN(buf, body, part.e.Length)
183                         return err
184                 } else {
185                         return ErrBadResponse{"resp status ok but requested range", result.resp}
186                 }
187         case http.StatusServiceUnavailable:
188                 return ErrTooFast
189         default:
190                 return ErrBadResponse{
191                         fmt.Sprintf("unhandled response status code (%v)", result.resp.StatusCode),
192                         result.resp,
193                 }
194         }
195 }
196
197 var ErrTooFast = errors.New("making requests too fast")
198
199 func readRequestPartResponses(ctx context.Context, parts []requestPart) (_ []byte, err error) {
200         var buf bytes.Buffer
201         for _, part := range parts {
202                 part.start()
203                 err = recvPartResult(ctx, &buf, part)
204                 if err != nil {
205                         err = fmt.Errorf("reading %q at %q: %w", part.req.URL, part.req.Header.Get("Range"), err)
206                         break
207                 }
208         }
209         return buf.Bytes(), err
210 }