forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtracker_scraper.go
250 lines (224 loc) · 5.87 KB
/
tracker_scraper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package torrent
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"net/url"
"time"
"github.com/anacrolix/dht/v2/krpc"
"github.com/anacrolix/log"
"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
}
type torrentTrackerAnnouncer interface {
statusLine() string
URL() *url.URL
}
func (me trackerScraper) URL() *url.URL {
return &me.u
}
func (ts *trackerScraper) statusLine() string {
var w bytes.Buffer
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)
}(),
)
return w.String()
}
type trackerAnnounceResult struct {
Err error
NumPeers int
Interval time.Duration
Completed time.Time
}
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
}
err = errors.New("no acceptable ips")
return
}
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()
}
// 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.
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")
}
}()
ip, err := me.getIp()
if err != nil {
ret.Err = fmt.Errorf("error getting ip: %s", err)
return
}
me.t.cl.rLock()
req := me.t.announceRequest(event)
me.t.cl.rUnlock()
// The default timeout works well as backpressure on concurrent access to the tracker. Since
// we're passing our own Context now, we will include that timeout ourselves to maintain similar
// behavior to previously, albeit with this context now being cancelled when the Torrent is
// closed.
ctx, cancel := context.WithTimeout(ctx, tracker.DefaultTrackerAnnounceTimeout)
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),
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},
}.Do()
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():
}
}()
// make sure first announce is a "started"
e := tracker.Started
for {
ar := me.announce(ctx, e)
// after first announce, get back to regular "none"
e = tracker.None
me.t.cl.lock()
me.lastAnnounce = ar
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()
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 <-me.t.closed.Done():
return
case <-reconsider:
// Recalculate the interval.
goto recalculate
case <-time.After(time.Until(ar.Completed.Add(interval))):
}
}
}
func (me *trackerScraper) announceStopped() {
ctx, cancel := context.WithTimeout(context.Background(), tracker.DefaultTrackerAnnounceTimeout)
defer cancel()
me.announce(ctx, tracker.Stopped)
}