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
26 type torrentTrackerAnnouncer interface {
31 func (me trackerScraper) URL() *url.URL {
35 func (ts *trackerScraper) statusLine() string {
37 fmt.Fprintf(&w, "next ann: %v, last ann: %v",
39 na := time.Until(ts.lastAnnounce.Completed.Add(ts.lastAnnounce.Interval))
49 if ts.lastAnnounce.Err != nil {
50 return ts.lastAnnounce.Err.Error()
52 if ts.lastAnnounce.Completed.IsZero() {
55 return fmt.Sprintf("%d peers", ts.lastAnnounce.NumPeers)
61 type trackerAnnounceResult struct {
64 Interval time.Duration
68 func (me *trackerScraper) getIp() (ip net.IP, err error) {
69 ips, err := net.LookupIP(me.u.Hostname())
74 err = errors.New("no ips")
77 for _, ip = range ips {
78 if me.t.cl.ipIsBlocked(ip) {
93 err = errors.New("no acceptable ips")
97 func (me *trackerScraper) trackerUrl(ip net.IP) string {
100 u.Host = net.JoinHostPort(ip.String(), u.Port())
105 // Return how long to wait before trying again. For most errors, we return 5
106 // minutes, a relatively quick turn around for DNS changes.
107 func (me *trackerScraper) announce(ctx context.Context, event tracker.AnnounceEvent) (ret trackerAnnounceResult) {
110 ret.Completed = time.Now()
112 ret.Interval = time.Minute
114 // Limit concurrent use of the same tracker URL by the Client.
115 ref := me.t.cl.activeAnnounceLimiter.GetRef(me.u.String())
121 case ref.C() <- struct{}{}:
127 panic("should return immediately")
131 ip, err := me.getIp()
133 ret.Err = fmt.Errorf("error getting ip: %s", err)
137 req := me.t.announceRequest(event)
139 // The default timeout works well as backpressure on concurrent access to the tracker. Since
140 // we're passing our own Context now, we will include that timeout ourselves to maintain similar
141 // behavior to previously, albeit with this context now being cancelled when the Torrent is
143 ctx, cancel := context.WithTimeout(ctx, tracker.DefaultTrackerAnnounceTimeout)
145 me.t.logger.WithDefaultLevel(log.Debug).Printf("announcing to %q: %#v", me.u.String(), req)
146 res, err := tracker.Announce{
148 HTTPProxy: me.t.cl.config.HTTPProxy,
149 UserAgent: me.t.cl.config.HTTPUserAgent,
150 TrackerUrl: me.trackerUrl(ip),
152 HostHeader: me.u.Host,
153 ServerName: me.u.Hostname(),
154 UdpNetwork: me.u.Scheme,
155 ClientIp4: krpc.NodeAddr{IP: me.t.cl.config.PublicIp4},
156 ClientIp6: krpc.NodeAddr{IP: me.t.cl.config.PublicIp6},
158 me.t.logger.WithDefaultLevel(log.Debug).Printf("announce to %q returned %#v: %v", me.u.String(), res, err)
160 ret.Err = fmt.Errorf("announcing: %w", err)
163 me.t.AddPeers(peerInfos(nil).AppendFromTracker(res.Peers))
164 ret.NumPeers = len(res.Peers)
165 ret.Interval = time.Duration(res.Interval) * time.Second
169 // Returns whether we can shorten the interval, and sets notify to a channel that receives when we
170 // might change our mind, or leaves it if we won't.
171 func (me *trackerScraper) canIgnoreInterval(notify *<-chan struct{}) bool {
172 gotInfo := me.t.GotInfo()
175 // Private trackers really don't like us announcing more than they specify. They're also
176 // tracking us very carefully, so it's best to comply.
177 private := me.t.info.Private
178 return private == nil || !*private
185 func (me *trackerScraper) Run() {
187 defer me.announceStopped()
189 ctx, cancel := context.WithCancel(context.Background())
195 case <-me.t.Closed():
199 // make sure first announce is a "started"
203 ar := me.announce(ctx, e)
204 // after first announce, get back to regular "none"
211 // Make sure we don't announce for at least a minute since the last one.
212 interval := ar.Interval
213 if interval < time.Minute {
214 interval = time.Minute
218 wantPeers := me.t.wantPeersEvent.C()
221 // If we want peers, reduce the interval to the minimum if it's appropriate.
223 // A channel that receives when we should reconsider our interval. Starts as nil since that
225 var reconsider <-chan struct{}
228 if interval > time.Minute && me.canIgnoreInterval(&reconsider) {
229 interval = time.Minute
232 reconsider = wantPeers
236 case <-me.t.closed.Done():
239 // Recalculate the interval.
241 case <-time.After(time.Until(ar.Completed.Add(interval))):
246 func (me *trackerScraper) announceStopped() {
247 ctx, cancel := context.WithTimeout(context.Background(), tracker.DefaultTrackerAnnounceTimeout)
249 me.announce(ctx, tracker.Stopped)