From 010362ec82fecd1fd1e43978d490c7150cc7117c Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Thu, 1 Oct 2020 10:45:05 +1000 Subject: [PATCH] Rework HTTP announce timeouts Use Request.Context to implement timeouts, set the default to 3s for announces from the Client. --- tracker/http.go | 13 +++++++------ tracker/tracker.go | 8 ++++++++ tracker_scraper.go | 4 ++++ 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/tracker/http.go b/tracker/http.go index 82a23dc1..328c0832 100644 --- a/tracker/http.go +++ b/tracker/http.go @@ -113,17 +113,18 @@ func announceHTTP(opt Announce, _url *url.URL) (ret AnnounceResponse, err error) req = req.WithContext(opt.Context) } resp, err := (&http.Client{ - Timeout: time.Second * 15, + //Timeout: time.Second * 15, Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 15 * time.Second, - }).Dial, - Proxy: opt.HTTPProxy, - TLSHandshakeTimeout: 15 * time.Second, + //Dial: (&net.Dialer{ + // Timeout: 15 * time.Second, + //}).Dial, + Proxy: opt.HTTPProxy, + //TLSHandshakeTimeout: 15 * time.Second, TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: opt.ServerName, }, + // This is for S3 trackers that hold connections open. DisableKeepAlives: true, }, }).Do(req) diff --git a/tracker/tracker.go b/tracker/tracker.go index 93f11ccd..5497037f 100644 --- a/tracker/tracker.go +++ b/tracker/tracker.go @@ -5,6 +5,7 @@ import ( "errors" "net/http" "net/url" + "time" "github.com/anacrolix/dht/v2/krpc" ) @@ -70,6 +71,13 @@ func (me Announce) Do() (res AnnounceResponse, err error) { if err != nil { return } + if me.Context == nil { + // This is just to maintain the old behaviour that should be a timeout of 15s. Users can + // override it by providing their own Context. + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + me.Context = ctx + } switch _url.Scheme { case "http", "https": return announceHTTP(me, _url) diff --git a/tracker_scraper.go b/tracker_scraper.go index b7d38c5a..62ca4261 100644 --- a/tracker_scraper.go +++ b/tracker_scraper.go @@ -2,6 +2,7 @@ package torrent import ( "bytes" + "context" "errors" "fmt" "net" @@ -119,8 +120,11 @@ func (me *trackerScraper) announce(event tracker.AnnounceEvent) (ret trackerAnno me.t.cl.rLock() req := me.t.announceRequest(event) me.t.cl.rUnlock() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() me.t.logger.WithDefaultLevel(log.Debug).Printf("announcing to %q: %#v", me.u.String(), req) res, err := tracker.Announce{ + Context: ctx, HTTPProxy: me.t.cl.config.HTTPProxy, UserAgent: me.t.cl.config.HTTPUserAgent, TrackerUrl: me.trackerUrl(ip), -- 2.44.0