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