]> Sergey Matveev's repositories - btrtrc.git/blob - tracker/http.go
Move tracker test server code to test file
[btrtrc.git] / tracker / http.go
1 package tracker
2
3 import (
4         "bytes"
5         "crypto/tls"
6         "fmt"
7         "io"
8         "math"
9         "net"
10         "net/http"
11         "net/url"
12         "strconv"
13
14         "github.com/anacrolix/dht/v2/krpc"
15         "github.com/anacrolix/missinggo/httptoo"
16
17         "github.com/anacrolix/torrent/bencode"
18 )
19
20 type HttpResponse struct {
21         FailureReason string `bencode:"failure reason"`
22         Interval      int32  `bencode:"interval"`
23         TrackerId     string `bencode:"tracker id"`
24         Complete      int32  `bencode:"complete"`
25         Incomplete    int32  `bencode:"incomplete"`
26         Peers         Peers  `bencode:"peers"`
27         // BEP 7
28         Peers6 krpc.CompactIPv6NodeAddrs `bencode:"peers6"`
29 }
30
31 type Peers []Peer
32
33 func (me *Peers) UnmarshalBencode(b []byte) (err error) {
34         var _v interface{}
35         err = bencode.Unmarshal(b, &_v)
36         if err != nil {
37                 return
38         }
39         switch v := _v.(type) {
40         case string:
41                 vars.Add("http responses with string peers", 1)
42                 var cnas krpc.CompactIPv4NodeAddrs
43                 err = cnas.UnmarshalBinary([]byte(v))
44                 if err != nil {
45                         return
46                 }
47                 for _, cp := range cnas {
48                         *me = append(*me, Peer{
49                                 IP:   cp.IP[:],
50                                 Port: int(cp.Port),
51                         })
52                 }
53                 return
54         case []interface{}:
55                 vars.Add("http responses with list peers", 1)
56                 for _, i := range v {
57                         var p Peer
58                         p.FromDictInterface(i.(map[string]interface{}))
59                         *me = append(*me, p)
60                 }
61                 return
62         default:
63                 vars.Add("http responses with unhandled peers type", 1)
64                 err = fmt.Errorf("unsupported type: %T", _v)
65                 return
66         }
67 }
68
69 func setAnnounceParams(_url *url.URL, ar *AnnounceRequest, opts Announce) {
70         q := _url.Query()
71
72         q.Set("key", strconv.FormatInt(int64(ar.Key), 10))
73         q.Set("info_hash", string(ar.InfoHash[:]))
74         q.Set("peer_id", string(ar.PeerId[:]))
75         // AFAICT, port is mandatory, and there's no implied port key.
76         q.Set("port", fmt.Sprintf("%d", ar.Port))
77         q.Set("uploaded", strconv.FormatInt(ar.Uploaded, 10))
78         q.Set("downloaded", strconv.FormatInt(ar.Downloaded, 10))
79
80         // The AWS S3 tracker returns "400 Bad Request: left(-1) was not in the valid range 0 -
81         // 9223372036854775807" if left is out of range, or "500 Internal Server Error: Internal Server
82         // Error" if omitted entirely.
83         left := ar.Left
84         if left < 0 {
85                 left = math.MaxInt64
86         }
87         q.Set("left", strconv.FormatInt(left, 10))
88
89         if ar.Event != None {
90                 q.Set("event", ar.Event.String())
91         }
92         // http://stackoverflow.com/questions/17418004/why-does-tracker-server-not-understand-my-request-bittorrent-protocol
93         q.Set("compact", "1")
94         // According to https://wiki.vuze.com/w/Message_Stream_Encryption. TODO:
95         // Take EncryptionPolicy or something like it as a parameter.
96         q.Set("supportcrypto", "1")
97         doIp := func(versionKey string, ip net.IP) {
98                 if ip == nil {
99                         return
100                 }
101                 ipString := ip.String()
102                 q.Set(versionKey, ipString)
103                 // Let's try listing them. BEP 3 mentions having an "ip" param, and BEP 7 says we can list
104                 // addresses for other address-families, although it's not encouraged.
105                 q.Add("ip", ipString)
106         }
107         doIp("ipv4", opts.ClientIp4.IP)
108         doIp("ipv6", opts.ClientIp6.IP)
109         _url.RawQuery = q.Encode()
110 }
111
112 func announceHTTP(opt Announce, _url *url.URL) (ret AnnounceResponse, err error) {
113         _url = httptoo.CopyURL(_url)
114         setAnnounceParams(_url, &opt.Request, opt)
115         req, err := http.NewRequest("GET", _url.String(), nil)
116         req.Header.Set("User-Agent", opt.UserAgent)
117         req.Host = opt.HostHeader
118         if opt.Context != nil {
119                 req = req.WithContext(opt.Context)
120         }
121         resp, err := (&http.Client{
122                 //Timeout: time.Second * 15,
123                 Transport: &http.Transport{
124                         //Dial: (&net.Dialer{
125                         //      Timeout: 15 * time.Second,
126                         //}).Dial,
127                         Proxy: opt.HTTPProxy,
128                         //TLSHandshakeTimeout: 15 * time.Second,
129                         TLSClientConfig: &tls.Config{
130                                 InsecureSkipVerify: true,
131                                 ServerName:         opt.ServerName,
132                         },
133                         // This is for S3 trackers that hold connections open.
134                         DisableKeepAlives: true,
135                 },
136         }).Do(req)
137         if err != nil {
138                 return
139         }
140         defer resp.Body.Close()
141         var buf bytes.Buffer
142         io.Copy(&buf, resp.Body)
143         if resp.StatusCode != 200 {
144                 err = fmt.Errorf("response from tracker: %s: %s", resp.Status, buf.String())
145                 return
146         }
147         var trackerResponse HttpResponse
148         err = bencode.Unmarshal(buf.Bytes(), &trackerResponse)
149         if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
150                 err = nil
151         } else if err != nil {
152                 err = fmt.Errorf("error decoding %q: %s", buf.Bytes(), err)
153                 return
154         }
155         if trackerResponse.FailureReason != "" {
156                 err = fmt.Errorf("tracker gave failure reason: %q", trackerResponse.FailureReason)
157                 return
158         }
159         vars.Add("successful http announces", 1)
160         ret.Interval = trackerResponse.Interval
161         ret.Leechers = trackerResponse.Incomplete
162         ret.Seeders = trackerResponse.Complete
163         if len(trackerResponse.Peers) != 0 {
164                 vars.Add("http responses with nonempty peers key", 1)
165         }
166         ret.Peers = trackerResponse.Peers
167         if len(trackerResponse.Peers6) != 0 {
168                 vars.Add("http responses with nonempty peers6 key", 1)
169         }
170         for _, na := range trackerResponse.Peers6 {
171                 ret.Peers = append(ret.Peers, Peer{
172                         IP:   na.IP,
173                         Port: na.Port,
174                 })
175         }
176         return
177 }