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