]> Sergey Matveev's repositories - btrtrc.git/blob - tracker/udp.go
f7afc9ea5906aa8eb898eab2ce849796216fd653
[btrtrc.git] / tracker / udp.go
1 package tracker
2
3 import (
4         "encoding/binary"
5         "net/url"
6
7         trHttp "github.com/anacrolix/torrent/tracker/http"
8         "github.com/anacrolix/torrent/tracker/udp"
9 )
10
11 type udpAnnounce struct {
12         url url.URL
13         a   *Announce
14 }
15
16 func (c *udpAnnounce) Do(req AnnounceRequest) (res AnnounceResponse, err error) {
17         cl, err := udp.NewConnClient(udp.NewConnClientOpts{
18                 Network: c.dialNetwork(),
19                 Host:    c.url.Host,
20                 Ipv6:    nil,
21         })
22         if err != nil {
23                 return
24         }
25         defer cl.Close()
26         if req.IPAddress == 0 && c.a.ClientIp4.IP != nil {
27                 // I think we're taking bytes in big-endian order (all IPs), and writing it to a natively
28                 // ordered uint32. This will be correctly ordered when written back out by the UDP client
29                 // later. I'm ignoring the fact that IPv6 announces shouldn't have an IP address, we have a
30                 // perfectly good IPv4 address.
31                 req.IPAddress = binary.BigEndian.Uint32(c.a.ClientIp4.IP.To4())
32         }
33         h, nas, err := cl.Announce(c.a.Context, req, udp.Options{RequestUri: c.url.RequestURI()})
34         if err != nil {
35                 return
36         }
37         res.Interval = h.Interval
38         res.Leechers = h.Leechers
39         res.Seeders = h.Seeders
40         for _, cp := range nas.NodeAddrs() {
41                 res.Peers = append(res.Peers, trHttp.Peer{}.FromNodeAddr(cp))
42         }
43         return
44 }
45
46 func (c *udpAnnounce) dialNetwork() string {
47         if c.a.UdpNetwork != "" {
48                 return c.a.UdpNetwork
49         }
50         return "udp"
51 }
52
53 // TODO: Split on IPv6, as BEP 15 says response peer decoding depends on network in use.
54 func announceUDP(opt Announce, _url *url.URL) (AnnounceResponse, error) {
55         ua := udpAnnounce{
56                 url: *_url,
57                 a:   &opt,
58         }
59         return ua.Do(opt.Request)
60 }