12 "github.com/anacrolix/dht/v2/krpc"
13 "github.com/anacrolix/log"
15 "github.com/anacrolix/torrent/tracker"
18 // Announces a torrent to a tracker at regular intervals, when peers are
20 type trackerScraper struct {
23 lastAnnounce trackerAnnounceResult
24 lookupTrackerIp func(*url.URL) ([]net.IP, error)
27 type torrentTrackerAnnouncer interface {
32 func (me trackerScraper) URL() *url.URL {
36 func (ts *trackerScraper) statusLine() string {
38 fmt.Fprintf(&w, "next ann: %v, last ann: %v",
40 na := time.Until(ts.lastAnnounce.Completed.Add(ts.lastAnnounce.Interval))
50 if ts.lastAnnounce.Err != nil {
51 return ts.lastAnnounce.Err.Error()
53 if ts.lastAnnounce.Completed.IsZero() {
56 return fmt.Sprintf("%d peers", ts.lastAnnounce.NumPeers)
62 type trackerAnnounceResult struct {
65 Interval time.Duration
69 func (me *trackerScraper) getIp() (ip net.IP, err error) {
71 if me.lookupTrackerIp != nil {
72 ips, err = me.lookupTrackerIp(&me.u)
74 // Do a regular dns lookup
75 ips, err = net.LookupIP(me.u.Hostname())
81 err = errors.New("no ips")
84 for _, ip = range ips {
85 if me.t.cl.ipIsBlocked(ip) {
100 err = errors.New("no acceptable ips")
104 func (me *trackerScraper) trackerUrl(ip net.IP) string {
107 u.Host = net.JoinHostPort(ip.String(), u.Port())
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) {
116 ret.Completed = time.Now()
118 ret.Interval = time.Minute
120 // Limit concurrent use of the same tracker URL by the Client.
121 ref := me.t.cl.activeAnnounceLimiter.GetRef(me.u.String())
127 case ref.C() <- struct{}{}:
133 panic("should return immediately")
137 ip, err := me.getIp()
139 ret.Err = fmt.Errorf("error getting ip: %s", err)
143 req := me.t.announceRequest(event)
145 // The default timeout works well as backpressure on concurrent access to the tracker. Since
146 // we're passing our own Context now, we will include that timeout ourselves to maintain similar
147 // behavior to previously, albeit with this context now being cancelled when the Torrent is
149 ctx, cancel := context.WithTimeout(ctx, tracker.DefaultTrackerAnnounceTimeout)
151 me.t.logger.WithDefaultLevel(log.Debug).Printf("announcing to %q: %#v", me.u.String(), req)
152 res, err := tracker.Announce{
154 HTTPProxy: me.t.cl.config.HTTPProxy,
155 UserAgent: me.t.cl.config.HTTPUserAgent,
156 TrackerUrl: me.trackerUrl(ip),
158 HostHeader: me.u.Host,
159 ServerName: me.u.Hostname(),
160 UdpNetwork: me.u.Scheme,
161 ClientIp4: krpc.NodeAddr{IP: me.t.cl.config.PublicIp4},
162 ClientIp6: krpc.NodeAddr{IP: me.t.cl.config.PublicIp6},
164 me.t.logger.WithDefaultLevel(log.Debug).Printf("announce to %q returned %#v: %v", me.u.String(), res, err)
166 ret.Err = fmt.Errorf("announcing: %w", err)
169 me.t.AddPeers(peerInfos(nil).AppendFromTracker(res.Peers))
170 ret.NumPeers = len(res.Peers)
171 ret.Interval = time.Duration(res.Interval) * time.Second
175 // Returns whether we can shorten the interval, and sets notify to a channel that receives when we
176 // might change our mind, or leaves it if we won't.
177 func (me *trackerScraper) canIgnoreInterval(notify *<-chan struct{}) bool {
178 gotInfo := me.t.GotInfo()
181 // Private trackers really don't like us announcing more than they specify. They're also
182 // tracking us very carefully, so it's best to comply.
183 private := me.t.info.Private
184 return private == nil || !*private
191 func (me *trackerScraper) Run() {
192 defer me.announceStopped()
194 ctx, cancel := context.WithCancel(context.Background())
200 case <-me.t.Closed():
204 // make sure first announce is a "started"
208 ar := me.announce(ctx, e)
209 // after first announce, get back to regular "none"
216 // Make sure we don't announce for at least a minute since the last one.
217 interval := ar.Interval
218 if interval < time.Minute {
219 interval = time.Minute
223 wantPeers := me.t.wantPeersEvent.C()
226 // If we want peers, reduce the interval to the minimum if it's appropriate.
228 // A channel that receives when we should reconsider our interval. Starts as nil since that
230 var reconsider <-chan struct{}
233 if interval > time.Minute && me.canIgnoreInterval(&reconsider) {
234 interval = time.Minute
237 reconsider = wantPeers
241 case <-me.t.closed.Done():
244 // Recalculate the interval.
246 case <-time.After(time.Until(ar.Completed.Add(interval))):
251 func (me *trackerScraper) announceStopped() {
252 ctx, cancel := context.WithTimeout(context.Background(), tracker.DefaultTrackerAnnounceTimeout)
254 me.announce(ctx, tracker.Stopped)