]> Sergey Matveev's repositories - btrtrc.git/blob - tracker_scraper.go
fixup! [trackerscraper] Add custom DNS lookup function
[btrtrc.git] / tracker_scraper.go
1 package torrent
2
3 import (
4         "bytes"
5         "context"
6         "errors"
7         "fmt"
8         "net"
9         "net/url"
10         "time"
11
12         "github.com/anacrolix/dht/v2/krpc"
13         "github.com/anacrolix/log"
14
15         "github.com/anacrolix/torrent/tracker"
16 )
17
18 // Announces a torrent to a tracker at regular intervals, when peers are
19 // required.
20 type trackerScraper struct {
21         u               url.URL
22         t               *Torrent
23         lastAnnounce    trackerAnnounceResult
24         lookupTrackerIp func(*url.URL) ([]net.IP, error)
25 }
26
27 type torrentTrackerAnnouncer interface {
28         statusLine() string
29         URL() *url.URL
30 }
31
32 func (me trackerScraper) URL() *url.URL {
33         return &me.u
34 }
35
36 func (ts *trackerScraper) statusLine() string {
37         var w bytes.Buffer
38         fmt.Fprintf(&w, "next ann: %v, last ann: %v",
39                 func() string {
40                         na := time.Until(ts.lastAnnounce.Completed.Add(ts.lastAnnounce.Interval))
41                         if na > 0 {
42                                 na /= time.Second
43                                 na *= time.Second
44                                 return na.String()
45                         } else {
46                                 return "anytime"
47                         }
48                 }(),
49                 func() string {
50                         if ts.lastAnnounce.Err != nil {
51                                 return ts.lastAnnounce.Err.Error()
52                         }
53                         if ts.lastAnnounce.Completed.IsZero() {
54                                 return "never"
55                         }
56                         return fmt.Sprintf("%d peers", ts.lastAnnounce.NumPeers)
57                 }(),
58         )
59         return w.String()
60 }
61
62 type trackerAnnounceResult struct {
63         Err       error
64         NumPeers  int
65         Interval  time.Duration
66         Completed time.Time
67 }
68
69 func (me *trackerScraper) getIp() (ip net.IP, err error) {
70         var ips []net.IP
71         if me.lookupTrackerIp != nil {
72                 ips, err = me.lookupTrackerIp(&me.u)
73         } else {
74                 // Do a regular dns lookup
75                 ips, err = net.LookupIP(me.u.Hostname())
76         }
77         if err != nil {
78                 return
79         }
80         if len(ips) == 0 {
81                 err = errors.New("no ips")
82                 return
83         }
84         for _, ip = range ips {
85                 if me.t.cl.ipIsBlocked(ip) {
86                         continue
87                 }
88                 switch me.u.Scheme {
89                 case "udp4":
90                         if ip.To4() == nil {
91                                 continue
92                         }
93                 case "udp6":
94                         if ip.To4() != nil {
95                                 continue
96                         }
97                 }
98                 return
99         }
100         err = errors.New("no acceptable ips")
101         return
102 }
103
104 func (me *trackerScraper) trackerUrl(ip net.IP) string {
105         u := me.u
106         if u.Port() != "" {
107                 u.Host = net.JoinHostPort(ip.String(), u.Port())
108         }
109         return u.String()
110 }
111
112 // Return how long to wait before trying again. For most errors, we return 5
113 // minutes, a relatively quick turn around for DNS changes.
114 func (me *trackerScraper) announce(ctx context.Context, event tracker.AnnounceEvent) (ret trackerAnnounceResult) {
115
116         defer func() {
117                 ret.Completed = time.Now()
118         }()
119         ret.Interval = time.Minute
120
121         // Limit concurrent use of the same tracker URL by the Client.
122         ref := me.t.cl.activeAnnounceLimiter.GetRef(me.u.String())
123         defer ref.Drop()
124         select {
125         case <-ctx.Done():
126                 ret.Err = ctx.Err()
127                 return
128         case ref.C() <- struct{}{}:
129         }
130         defer func() {
131                 select {
132                 case <-ref.C():
133                 default:
134                         panic("should return immediately")
135                 }
136         }()
137
138         ip, err := me.getIp()
139         if err != nil {
140                 ret.Err = fmt.Errorf("error getting ip: %s", err)
141                 return
142         }
143         me.t.cl.rLock()
144         req := me.t.announceRequest(event)
145         me.t.cl.rUnlock()
146         // The default timeout works well as backpressure on concurrent access to the tracker. Since
147         // we're passing our own Context now, we will include that timeout ourselves to maintain similar
148         // behavior to previously, albeit with this context now being cancelled when the Torrent is
149         // closed.
150         ctx, cancel := context.WithTimeout(ctx, tracker.DefaultTrackerAnnounceTimeout)
151         defer cancel()
152         me.t.logger.WithDefaultLevel(log.Debug).Printf("announcing to %q: %#v", me.u.String(), req)
153         res, err := tracker.Announce{
154                 Context:    ctx,
155                 HTTPProxy:  me.t.cl.config.HTTPProxy,
156                 UserAgent:  me.t.cl.config.HTTPUserAgent,
157                 TrackerUrl: me.trackerUrl(ip),
158                 Request:    req,
159                 HostHeader: me.u.Host,
160                 ServerName: me.u.Hostname(),
161                 UdpNetwork: me.u.Scheme,
162                 ClientIp4:  krpc.NodeAddr{IP: me.t.cl.config.PublicIp4},
163                 ClientIp6:  krpc.NodeAddr{IP: me.t.cl.config.PublicIp6},
164         }.Do()
165         me.t.logger.WithDefaultLevel(log.Debug).Printf("announce to %q returned %#v: %v", me.u.String(), res, err)
166         if err != nil {
167                 ret.Err = fmt.Errorf("announcing: %w", err)
168                 return
169         }
170         me.t.AddPeers(peerInfos(nil).AppendFromTracker(res.Peers))
171         ret.NumPeers = len(res.Peers)
172         ret.Interval = time.Duration(res.Interval) * time.Second
173         return
174 }
175
176 // Returns whether we can shorten the interval, and sets notify to a channel that receives when we
177 // might change our mind, or leaves it if we won't.
178 func (me *trackerScraper) canIgnoreInterval(notify *<-chan struct{}) bool {
179         gotInfo := me.t.GotInfo()
180         select {
181         case <-gotInfo:
182                 // Private trackers really don't like us announcing more than they specify. They're also
183                 // tracking us very carefully, so it's best to comply.
184                 private := me.t.info.Private
185                 return private == nil || !*private
186         default:
187                 *notify = gotInfo
188                 return false
189         }
190 }
191
192 func (me *trackerScraper) Run() {
193
194         defer me.announceStopped()
195
196         ctx, cancel := context.WithCancel(context.Background())
197         defer cancel()
198         go func() {
199                 defer cancel()
200                 select {
201                 case <-ctx.Done():
202                 case <-me.t.Closed():
203                 }
204         }()
205
206         // make sure first announce is a "started"
207         e := tracker.Started
208
209         for {
210                 ar := me.announce(ctx, e)
211                 // after first announce, get back to regular "none"
212                 e = tracker.None
213                 me.t.cl.lock()
214                 me.lastAnnounce = ar
215                 me.t.cl.unlock()
216
217         recalculate:
218                 // Make sure we don't announce for at least a minute since the last one.
219                 interval := ar.Interval
220                 if interval < time.Minute {
221                         interval = time.Minute
222                 }
223
224                 me.t.cl.lock()
225                 wantPeers := me.t.wantPeersEvent.C()
226                 me.t.cl.unlock()
227
228                 // If we want peers, reduce the interval to the minimum if it's appropriate.
229
230                 // A channel that receives when we should reconsider our interval. Starts as nil since that
231                 // never receives.
232                 var reconsider <-chan struct{}
233                 select {
234                 case <-wantPeers:
235                         if interval > time.Minute && me.canIgnoreInterval(&reconsider) {
236                                 interval = time.Minute
237                         }
238                 default:
239                         reconsider = wantPeers
240                 }
241
242                 select {
243                 case <-me.t.closed.Done():
244                         return
245                 case <-reconsider:
246                         // Recalculate the interval.
247                         goto recalculate
248                 case <-time.After(time.Until(ar.Completed.Add(interval))):
249                 }
250         }
251 }
252
253 func (me *trackerScraper) announceStopped() {
254         ctx, cancel := context.WithTimeout(context.Background(), tracker.DefaultTrackerAnnounceTimeout)
255         defer cancel()
256         me.announce(ctx, tracker.Stopped)
257 }