FedP2P/tracker_scraper.go

250 lines
5.7 KiB
Go
Raw Normal View History

package torrent
import (
"bytes"
"context"
"errors"
"fmt"
2018-02-19 13:19:18 +08:00
"net"
"net/url"
"time"
2019-08-10 16:46:07 +08:00
"github.com/anacrolix/dht/v2/krpc"
2020-04-16 10:17:18 +08:00
"github.com/anacrolix/log"
2019-08-21 18:58:40 +08:00
"github.com/anacrolix/torrent/tracker"
)
// Announces a torrent to a tracker at regular intervals, when peers are
// required.
type trackerScraper struct {
u url.URL
t *Torrent
lastAnnounce trackerAnnounceResult
}
2020-04-06 13:38:01 +08:00
type torrentTrackerAnnouncer interface {
statusLine() string
2020-04-28 07:13:44 +08:00
URL() *url.URL
2020-04-06 13:38:01 +08:00
}
2020-04-28 07:13:44 +08:00
func (me trackerScraper) URL() *url.URL {
return &me.u
2020-04-06 13:38:01 +08:00
}
func (ts *trackerScraper) statusLine() string {
var w bytes.Buffer
2020-04-28 07:13:44 +08:00
fmt.Fprintf(&w, "next ann: %v, last ann: %v",
func() string {
na := time.Until(ts.lastAnnounce.Completed.Add(ts.lastAnnounce.Interval))
if na > 0 {
na /= time.Second
na *= time.Second
return na.String()
} else {
return "anytime"
}
}(),
func() string {
if ts.lastAnnounce.Err != nil {
return ts.lastAnnounce.Err.Error()
}
if ts.lastAnnounce.Completed.IsZero() {
return "never"
}
return fmt.Sprintf("%d peers", ts.lastAnnounce.NumPeers)
2018-02-19 13:19:18 +08:00
}(),
)
return w.String()
}
type trackerAnnounceResult struct {
Err error
NumPeers int
Interval time.Duration
Completed time.Time
}
2018-02-19 13:19:18 +08:00
func (me *trackerScraper) getIp() (ip net.IP, err error) {
ips, err := net.LookupIP(me.u.Hostname())
if err != nil {
return
}
if len(ips) == 0 {
err = errors.New("no ips")
return
}
for _, ip = range ips {
if me.t.cl.ipIsBlocked(ip) {
continue
}
switch me.u.Scheme {
case "udp4":
if ip.To4() == nil {
continue
}
case "udp6":
if ip.To4() != nil {
continue
}
}
return
}
2018-02-19 13:19:18 +08:00
err = errors.New("no acceptable ips")
return
}
2018-02-19 13:19:18 +08:00
func (me *trackerScraper) trackerUrl(ip net.IP) string {
u := me.u
if u.Port() != "" {
u.Host = net.JoinHostPort(ip.String(), u.Port())
}
return u.String()
}
2016-05-23 09:00:49 +08:00
// Return how long to wait before trying again. For most errors, we return 5
// minutes, a relatively quick turn around for DNS changes.
func (me *trackerScraper) announce(ctx context.Context, event tracker.AnnounceEvent) (ret trackerAnnounceResult) {
defer func() {
ret.Completed = time.Now()
}()
ret.Interval = time.Minute
// Limit concurrent use of the same tracker URL by the Client.
2020-12-17 09:22:02 +08:00
ref := me.t.cl.activeAnnounceLimiter.GetRef(me.u.String())
defer ref.Drop()
select {
case <-ctx.Done():
ret.Err = ctx.Err()
return
case ref.C() <- struct{}{}:
}
defer func() {
select {
case <-ref.C():
default:
panic("should return immediately")
}
}()
2018-02-19 13:19:18 +08:00
ip, err := me.getIp()
2016-05-23 09:00:49 +08:00
if err != nil {
2018-02-19 13:19:18 +08:00
ret.Err = fmt.Errorf("error getting ip: %s", err)
return
}
me.t.cl.rLock()
2019-06-01 00:11:01 +08:00
req := me.t.announceRequest(event)
me.t.cl.rUnlock()
// The default timeout is currently 15s, and that works well as backpressure on concurrent
// access to the tracker.
//ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
//defer cancel()
2020-04-16 15:20:58 +08:00
me.t.logger.WithDefaultLevel(log.Debug).Printf("announcing to %q: %#v", me.u.String(), req)
2018-02-19 13:19:18 +08:00
res, err := tracker.Announce{
//Context: ctx,
HTTPProxy: me.t.cl.config.HTTPProxy,
2018-02-19 13:19:18 +08:00
UserAgent: me.t.cl.config.HTTPUserAgent,
TrackerUrl: me.trackerUrl(ip),
Request: req,
HostHeader: me.u.Host,
ServerName: me.u.Hostname(),
UdpNetwork: me.u.Scheme,
ClientIp4: krpc.NodeAddr{IP: me.t.cl.config.PublicIp4},
ClientIp6: krpc.NodeAddr{IP: me.t.cl.config.PublicIp6},
2018-02-19 13:19:18 +08:00
}.Do()
2020-12-09 17:01:05 +08:00
me.t.logger.WithDefaultLevel(log.Debug).Printf("announce to %q returned %#v: %v", me.u.String(), res, err)
if err != nil {
ret.Err = fmt.Errorf("announcing: %w", err)
return
}
me.t.AddPeers(peerInfos(nil).AppendFromTracker(res.Peers))
ret.NumPeers = len(res.Peers)
ret.Interval = time.Duration(res.Interval) * time.Second
return
}
// Returns whether we can shorten the interval, and sets notify to a channel that receives when we
// might change our mind, or leaves it if we won't.
func (me *trackerScraper) canIgnoreInterval(notify *<-chan struct{}) bool {
gotInfo := me.t.GotInfo()
select {
case <-gotInfo:
// Private trackers really don't like us announcing more than they specify. They're also
// tracking us very carefully, so it's best to comply.
private := me.t.info.Private
return private == nil || !*private
default:
*notify = gotInfo
return false
}
}
func (me *trackerScraper) Run() {
defer me.announceStopped()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
defer cancel()
select {
case <-ctx.Done():
case <-me.t.Closed():
}
}()
2019-06-01 00:11:01 +08:00
// make sure first announce is a "started"
e := tracker.Started
for {
ar := me.announce(ctx, e)
2019-06-01 00:11:01 +08:00
// after first announce, get back to regular "none"
e = tracker.None
2018-07-25 11:41:50 +08:00
me.t.cl.lock()
me.lastAnnounce = ar
2018-07-25 11:41:50 +08:00
me.t.cl.unlock()
recalculate:
// Make sure we don't announce for at least a minute since the last one.
interval := ar.Interval
if interval < time.Minute {
interval = time.Minute
}
me.t.cl.lock()
wantPeers := me.t.wantPeersEvent.C()
closed := me.t.closed.C()
me.t.cl.unlock()
// If we want peers, reduce the interval to the minimum if it's appropriate.
// A channel that receives when we should reconsider our interval. Starts as nil since that
// never receives.
var reconsider <-chan struct{}
select {
case <-wantPeers:
if interval > time.Minute && me.canIgnoreInterval(&reconsider) {
interval = time.Minute
}
default:
reconsider = wantPeers
}
select {
case <-closed:
return
case <-reconsider:
// Recalculate the interval.
goto recalculate
case <-time.After(time.Until(ar.Completed.Add(interval))):
}
}
}
2019-06-01 00:11:01 +08:00
func (me *trackerScraper) announceStopped() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
me.announce(ctx, tracker.Stopped)
2019-06-01 00:11:01 +08:00
}