]> Sergey Matveev's repositories - btrtrc.git/blob - tracker/tracker.go
Fix tracker test timeouts
[btrtrc.git] / tracker / tracker.go
1 package tracker
2
3 import (
4         "context"
5         "errors"
6         "net/http"
7         "net/url"
8         "time"
9
10         "github.com/anacrolix/dht/v2/krpc"
11         "github.com/anacrolix/torrent/tracker/udp"
12 )
13
14 type AnnounceRequest = udp.AnnounceRequest
15
16 type AnnounceResponse struct {
17         Interval int32 // Minimum seconds the local peer should wait before next announce.
18         Leechers int32
19         Seeders  int32
20         Peers    []Peer
21 }
22
23 type AnnounceEvent = udp.AnnounceEvent
24
25 const (
26         None      AnnounceEvent = iota
27         Completed               // The local peer just completed the torrent.
28         Started                 // The local peer has just resumed this torrent.
29         Stopped                 // The local peer is leaving the swarm.
30 )
31
32 var (
33         ErrBadScheme = errors.New("unknown scheme")
34 )
35
36 type Announce struct {
37         TrackerUrl string
38         Request    AnnounceRequest
39         HostHeader string
40         HTTPProxy  func(*http.Request) (*url.URL, error)
41         ServerName string
42         UserAgent  string
43         UdpNetwork string
44         // If the port is zero, it's assumed to be the same as the Request.Port.
45         ClientIp4 krpc.NodeAddr
46         // If the port is zero, it's assumed to be the same as the Request.Port.
47         ClientIp6 krpc.NodeAddr
48         Context   context.Context
49 }
50
51 // The code *is* the documentation.
52 const DefaultTrackerAnnounceTimeout = 15 * time.Second
53
54 func (me Announce) Do() (res AnnounceResponse, err error) {
55         _url, err := url.Parse(me.TrackerUrl)
56         if err != nil {
57                 return
58         }
59         if me.Context == nil {
60                 // This is just to maintain the old behaviour that should be a timeout of 15s. Users can
61                 // override it by providing their own Context. See comments elsewhere about longer timeouts
62                 // acting as rate limiting overloaded trackers.
63                 ctx, cancel := context.WithTimeout(context.Background(), DefaultTrackerAnnounceTimeout)
64                 defer cancel()
65                 me.Context = ctx
66         }
67         switch _url.Scheme {
68         case "http", "https":
69                 return announceHTTP(me, _url)
70         case "udp", "udp4", "udp6":
71                 return announceUDP(me, _url)
72         default:
73                 err = ErrBadScheme
74                 return
75         }
76 }