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 {
21 shortInfohash [20]byte
24 lastAnnounce trackerAnnounceResult
25 lookupTrackerIp func(*url.URL) ([]net.IP, error)
28 type torrentTrackerAnnouncer interface {
33 func (me trackerScraper) URL() *url.URL {
37 func (ts *trackerScraper) statusLine() string {
39 fmt.Fprintf(&w, "next ann: %v, last ann: %v",
41 na := time.Until(ts.lastAnnounce.Completed.Add(ts.lastAnnounce.Interval))
51 if ts.lastAnnounce.Err != nil {
52 return ts.lastAnnounce.Err.Error()
54 if ts.lastAnnounce.Completed.IsZero() {
57 return fmt.Sprintf("%d peers", ts.lastAnnounce.NumPeers)
63 type trackerAnnounceResult struct {
66 Interval time.Duration
70 func (me *trackerScraper) getIp() (ip net.IP, err error) {
72 if me.lookupTrackerIp != nil {
73 ips, err = me.lookupTrackerIp(&me.u)
75 // Do a regular dns lookup
76 ips, err = net.LookupIP(me.u.Hostname())
82 err = errors.New("no ips")
86 defer me.t.cl.rUnlock()
87 if me.t.cl.closed.IsSet() {
88 err = errors.New("client is closed")
91 for _, ip = range ips {
92 if me.t.cl.ipIsBlocked(ip) {
107 err = errors.New("no acceptable ips")
111 func (me *trackerScraper) trackerUrl(ip net.IP) string {
114 u.Host = net.JoinHostPort(ip.String(), u.Port())
119 // Return how long to wait before trying again. For most errors, we return 5
120 // minutes, a relatively quick turn around for DNS changes.
121 func (me *trackerScraper) announce(
123 event tracker.AnnounceEvent,
124 ) (ret trackerAnnounceResult) {
126 ret.Completed = time.Now()
128 ret.Interval = time.Minute
130 // Limit concurrent use of the same tracker URL by the Client.
131 ref := me.t.cl.activeAnnounceLimiter.GetRef(me.u.String())
137 case ref.C() <- struct{}{}:
143 panic("should return immediately")
147 ip, err := me.getIp()
149 ret.Err = fmt.Errorf("error getting ip: %s", err)
153 req := me.t.announceRequest(event, me.shortInfohash)
155 // The default timeout works well as backpressure on concurrent access to the tracker. Since
156 // we're passing our own Context now, we will include that timeout ourselves to maintain similar
157 // behavior to previously, albeit with this context now being cancelled when the Torrent is
159 ctx, cancel := context.WithTimeout(ctx, tracker.DefaultTrackerAnnounceTimeout)
161 me.t.logger.WithDefaultLevel(log.Debug).Printf("announcing to %q: %#v", me.u.String(), req)
162 res, err := tracker.Announce{
164 HttpProxy: me.t.cl.config.HTTPProxy,
165 HttpRequestDirector: me.t.cl.config.HttpRequestDirector,
166 DialContext: me.t.cl.config.TrackerDialContext,
167 ListenPacket: me.t.cl.config.TrackerListenPacket,
168 UserAgent: me.t.cl.config.HTTPUserAgent,
169 TrackerUrl: me.trackerUrl(ip),
171 HostHeader: me.u.Host,
172 ServerName: me.u.Hostname(),
173 UdpNetwork: me.u.Scheme,
174 ClientIp4: krpc.NodeAddr{IP: me.t.cl.config.PublicIp4},
175 ClientIp6: krpc.NodeAddr{IP: me.t.cl.config.PublicIp6},
178 me.t.logger.WithDefaultLevel(log.Debug).Printf("announce to %q returned %#v: %v", me.u.String(), res, err)
180 ret.Err = fmt.Errorf("announcing: %w", err)
183 me.t.AddPeers(peerInfos(nil).AppendFromTracker(res.Peers))
184 ret.NumPeers = len(res.Peers)
185 ret.Interval = time.Duration(res.Interval) * time.Second
189 // Returns whether we can shorten the interval, and sets notify to a channel that receives when we
190 // might change our mind, or leaves it if we won't.
191 func (me *trackerScraper) canIgnoreInterval(notify *<-chan struct{}) bool {
192 gotInfo := me.t.GotInfo()
195 // Private trackers really don't like us announcing more than they specify. They're also
196 // tracking us very carefully, so it's best to comply.
197 private := me.t.info.Private
198 return private == nil || !*private
205 func (me *trackerScraper) Run() {
206 defer me.announceStopped()
208 ctx, cancel := context.WithCancel(context.Background())
214 case <-me.t.Closed():
218 // make sure first announce is a "started"
222 ar := me.announce(ctx, e)
223 // after first announce, get back to regular "none"
230 // Make sure we don't announce for at least a minute since the last one.
231 interval := ar.Interval
232 if interval < time.Minute {
233 interval = time.Minute
237 wantPeers := me.t.wantPeersEvent.C()
240 // If we want peers, reduce the interval to the minimum if it's appropriate.
242 // A channel that receives when we should reconsider our interval. Starts as nil since that
244 var reconsider <-chan struct{}
247 if interval > time.Minute && me.canIgnoreInterval(&reconsider) {
248 interval = time.Minute
251 reconsider = wantPeers
255 case <-me.t.closed.Done():
258 // Recalculate the interval.
260 case <-time.After(time.Until(ar.Completed.Add(interval))):
265 func (me *trackerScraper) announceStopped() {
266 ctx, cancel := context.WithTimeout(context.Background(), tracker.DefaultTrackerAnnounceTimeout)
268 me.announce(ctx, tracker.Stopped)