]> Sergey Matveev's repositories - btrtrc.git/blob - tracker/http/http.go
Quote http tracker error response body
[btrtrc.git] / tracker / http / http.go
1 package http
2
3 import (
4         "bytes"
5         "context"
6         "expvar"
7         "fmt"
8         "io"
9         "math"
10         "net"
11         "net/http"
12         "net/url"
13         "strconv"
14         "strings"
15
16         "github.com/anacrolix/missinggo/httptoo"
17         "github.com/anacrolix/torrent/bencode"
18         "github.com/anacrolix/torrent/tracker/shared"
19         "github.com/anacrolix/torrent/tracker/udp"
20         "github.com/anacrolix/torrent/version"
21 )
22
23 var vars = expvar.NewMap("tracker/http")
24
25 func setAnnounceParams(_url *url.URL, ar *AnnounceRequest, opts AnnounceOpt) {
26         q := url.Values{}
27
28         q.Set("key", strconv.FormatInt(int64(ar.Key), 10))
29         q.Set("info_hash", string(ar.InfoHash[:]))
30         q.Set("peer_id", string(ar.PeerId[:]))
31         // AFAICT, port is mandatory, and there's no implied port key.
32         q.Set("port", fmt.Sprintf("%d", ar.Port))
33         q.Set("uploaded", strconv.FormatInt(ar.Uploaded, 10))
34         q.Set("downloaded", strconv.FormatInt(ar.Downloaded, 10))
35
36         // The AWS S3 tracker returns "400 Bad Request: left(-1) was not in the valid range 0 -
37         // 9223372036854775807" if left is out of range, or "500 Internal Server Error: Internal Server
38         // Error" if omitted entirely.
39         left := ar.Left
40         if left < 0 {
41                 left = math.MaxInt64
42         }
43         q.Set("left", strconv.FormatInt(left, 10))
44
45         if ar.Event != shared.None {
46                 q.Set("event", ar.Event.String())
47         }
48         // http://stackoverflow.com/questions/17418004/why-does-tracker-server-not-understand-my-request-bittorrent-protocol
49         q.Set("compact", "1")
50         // According to https://wiki.vuze.com/w/Message_Stream_Encryption. TODO:
51         // Take EncryptionPolicy or something like it as a parameter.
52         q.Set("supportcrypto", "1")
53         doIp := func(versionKey string, ip net.IP) {
54                 if ip == nil {
55                         return
56                 }
57                 ipString := ip.String()
58                 q.Set(versionKey, ipString)
59                 // Let's try listing them. BEP 3 mentions having an "ip" param, and BEP 7 says we can list
60                 // addresses for other address-families, although it's not encouraged.
61                 q.Add("ip", ipString)
62         }
63         doIp("ipv4", opts.ClientIp4)
64         doIp("ipv6", opts.ClientIp6)
65         // We're operating purely on query-escaped strings, where + would have already been encoded to
66         // %2B, and + has no other special meaning. See https://github.com/anacrolix/torrent/issues/534.
67         qstr := strings.ReplaceAll(q.Encode(), "+", "%20")
68
69         // Some private trackers require the original query param to be in the first position.
70         if _url.RawQuery != "" {
71                 _url.RawQuery += "&" + qstr
72         } else {
73                 _url.RawQuery = qstr
74         }
75 }
76
77 type AnnounceOpt struct {
78         UserAgent  string
79         HostHeader string
80         ClientIp4  net.IP
81         ClientIp6  net.IP
82 }
83
84 type AnnounceRequest = udp.AnnounceRequest
85
86 func (cl Client) Announce(ctx context.Context, ar AnnounceRequest, opt AnnounceOpt) (ret AnnounceResponse, err error) {
87         _url := httptoo.CopyURL(cl.url_)
88         setAnnounceParams(_url, &ar, opt)
89         req, err := http.NewRequestWithContext(ctx, http.MethodGet, _url.String(), nil)
90         userAgent := opt.UserAgent
91         if userAgent == "" {
92                 userAgent = version.DefaultHttpUserAgent
93         }
94         if userAgent != "" {
95                 req.Header.Set("User-Agent", userAgent)
96         }
97         req.Host = opt.HostHeader
98         resp, err := cl.hc.Do(req)
99         if err != nil {
100                 return
101         }
102         defer resp.Body.Close()
103         var buf bytes.Buffer
104         io.Copy(&buf, resp.Body)
105         if resp.StatusCode != 200 {
106                 err = fmt.Errorf("response from tracker: %s: %q", resp.Status, buf.Bytes())
107                 return
108         }
109         var trackerResponse HttpResponse
110         err = bencode.Unmarshal(buf.Bytes(), &trackerResponse)
111         if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
112                 err = nil
113         } else if err != nil {
114                 err = fmt.Errorf("error decoding %q: %s", buf.Bytes(), err)
115                 return
116         }
117         if trackerResponse.FailureReason != "" {
118                 err = fmt.Errorf("tracker gave failure reason: %q", trackerResponse.FailureReason)
119                 return
120         }
121         vars.Add("successful http announces", 1)
122         ret.Interval = trackerResponse.Interval
123         ret.Leechers = trackerResponse.Incomplete
124         ret.Seeders = trackerResponse.Complete
125         if len(trackerResponse.Peers) != 0 {
126                 vars.Add("http responses with nonempty peers key", 1)
127         }
128         ret.Peers = trackerResponse.Peers
129         if len(trackerResponse.Peers6) != 0 {
130                 vars.Add("http responses with nonempty peers6 key", 1)
131         }
132         for _, na := range trackerResponse.Peers6 {
133                 ret.Peers = append(ret.Peers, Peer{
134                         IP:   na.IP,
135                         Port: na.Port,
136                 })
137         }
138         return
139 }
140
141 type AnnounceResponse struct {
142         Interval int32 // Minimum seconds the local peer should wait before next announce.
143         Leechers int32
144         Seeders  int32
145         Peers    []Peer
146 }