11 "github.com/anacrolix/dht/krpc"
12 "github.com/anacrolix/missinggo"
14 "github.com/anacrolix/torrent/tracker"
17 // Announces a torrent to a tracker at regular intervals, when peers are
19 type trackerScraper struct {
21 // Causes the trackerScraper to stop running.
24 lastAnnounce trackerAnnounceResult
27 func (ts *trackerScraper) statusLine() string {
29 fmt.Fprintf(&w, "%q\t%s\t%s",
32 na := time.Until(ts.lastAnnounce.Completed.Add(ts.lastAnnounce.Interval))
42 if ts.lastAnnounce.Err != nil {
43 return ts.lastAnnounce.Err.Error()
45 if ts.lastAnnounce.Completed.IsZero() {
48 return fmt.Sprintf("%d peers", ts.lastAnnounce.NumPeers)
54 type trackerAnnounceResult struct {
57 Interval time.Duration
61 func (me *trackerScraper) getIp() (ip net.IP, err error) {
62 ips, err := net.LookupIP(me.u.Hostname())
67 err = errors.New("no ips")
70 for _, ip = range ips {
71 if me.t.cl.ipIsBlocked(ip) {
86 err = errors.New("no acceptable ips")
90 func (me *trackerScraper) trackerUrl(ip net.IP) string {
93 u.Host = net.JoinHostPort(ip.String(), u.Port())
98 // Return how long to wait before trying again. For most errors, we return 5
99 // minutes, a relatively quick turn around for DNS changes.
100 func (me *trackerScraper) announce() (ret trackerAnnounceResult) {
102 ret.Completed = time.Now()
104 ret.Interval = 5 * time.Minute
105 ip, err := me.getIp()
107 ret.Err = fmt.Errorf("error getting ip: %s", err)
111 req := me.t.announceRequest()
113 res, err := tracker.Announce{
114 HttpClient: me.t.cl.config.TrackerHttpClient,
115 UserAgent: me.t.cl.config.HTTPUserAgent,
116 TrackerUrl: me.trackerUrl(ip),
118 HostHeader: me.u.Host,
119 UdpNetwork: me.u.Scheme,
120 ClientIp4: krpc.NodeAddr{IP: me.t.cl.config.PublicIp4},
121 ClientIp6: krpc.NodeAddr{IP: me.t.cl.config.PublicIp6},
124 ret.Err = fmt.Errorf("error announcing: %s", err)
127 me.t.AddPeers(Peers(nil).AppendFromTracker(res.Peers))
128 ret.NumPeers = len(res.Peers)
129 ret.Interval = time.Duration(res.Interval) * time.Second
133 func (me *trackerScraper) Run() {
141 interval := time.Until(ar.Completed.Add(ar.Interval))
143 case <-me.t.wantPeersEvent.LockedChan(me.t.cl.locker()):
144 if interval > time.Minute {
145 interval = time.Minute
151 case <-me.t.closed.LockedChan(me.t.cl.locker()):
153 case <-me.stop.LockedChan(me.t.cl.locker()):
155 case <-time.After(interval):
156 case <-me.t.wantPeersEvent.LockedChan(me.t.cl.locker()):