54
vendor/github.com/anacrolix/torrent/tracker/client.go
generated
vendored
Normal file
54
vendor/github.com/anacrolix/torrent/tracker/client.go
generated
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
package tracker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
|
||||
"github.com/anacrolix/log"
|
||||
trHttp "github.com/anacrolix/torrent/tracker/http"
|
||||
"github.com/anacrolix/torrent/tracker/udp"
|
||||
)
|
||||
|
||||
type Client interface {
|
||||
Announce(context.Context, AnnounceRequest, AnnounceOpt) (AnnounceResponse, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
type AnnounceOpt = trHttp.AnnounceOpt
|
||||
|
||||
type NewClientOpts struct {
|
||||
Http trHttp.NewClientOpts
|
||||
// Overrides the network in the scheme. Probably a legacy thing.
|
||||
UdpNetwork string
|
||||
Logger log.Logger
|
||||
}
|
||||
|
||||
func NewClient(urlStr string, opts NewClientOpts) (Client, error) {
|
||||
_url, err := url.Parse(urlStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch _url.Scheme {
|
||||
case "http", "https":
|
||||
return trHttp.NewClient(_url, opts.Http), nil
|
||||
case "udp", "udp4", "udp6":
|
||||
network := _url.Scheme
|
||||
if opts.UdpNetwork != "" {
|
||||
network = opts.UdpNetwork
|
||||
}
|
||||
cc, err := udp.NewConnClient(udp.NewConnClientOpts{
|
||||
Network: network,
|
||||
Host: _url.Host,
|
||||
Logger: opts.Logger,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &udpClient{
|
||||
cl: cc,
|
||||
requestUri: _url.RequestURI(),
|
||||
}, nil
|
||||
default:
|
||||
return nil, ErrBadScheme
|
||||
}
|
||||
}
|
||||
42
vendor/github.com/anacrolix/torrent/tracker/http/client.go
generated
vendored
Normal file
42
vendor/github.com/anacrolix/torrent/tracker/http/client.go
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
hc *http.Client
|
||||
url_ *url.URL
|
||||
}
|
||||
|
||||
type ProxyFunc func(*http.Request) (*url.URL, error)
|
||||
|
||||
type NewClientOpts struct {
|
||||
Proxy ProxyFunc
|
||||
ServerName string
|
||||
AllowKeepAlive bool
|
||||
}
|
||||
|
||||
func NewClient(url_ *url.URL, opts NewClientOpts) Client {
|
||||
return Client{
|
||||
url_: url_,
|
||||
hc: &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: opts.Proxy,
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
ServerName: opts.ServerName,
|
||||
},
|
||||
// This is for S3 trackers that hold connections open.
|
||||
DisableKeepAlives: !opts.AllowKeepAlive,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (cl Client) Close() error {
|
||||
cl.hc.CloseIdleConnections()
|
||||
return nil
|
||||
}
|
||||
146
vendor/github.com/anacrolix/torrent/tracker/http/http.go
generated
vendored
Normal file
146
vendor/github.com/anacrolix/torrent/tracker/http/http.go
generated
vendored
Normal file
@@ -0,0 +1,146 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"expvar"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/anacrolix/missinggo/httptoo"
|
||||
"github.com/anacrolix/torrent/bencode"
|
||||
"github.com/anacrolix/torrent/tracker/shared"
|
||||
"github.com/anacrolix/torrent/tracker/udp"
|
||||
"github.com/anacrolix/torrent/version"
|
||||
)
|
||||
|
||||
var vars = expvar.NewMap("tracker/http")
|
||||
|
||||
func setAnnounceParams(_url *url.URL, ar *AnnounceRequest, opts AnnounceOpt) {
|
||||
q := url.Values{}
|
||||
|
||||
q.Set("key", strconv.FormatInt(int64(ar.Key), 10))
|
||||
q.Set("info_hash", string(ar.InfoHash[:]))
|
||||
q.Set("peer_id", string(ar.PeerId[:]))
|
||||
// AFAICT, port is mandatory, and there's no implied port key.
|
||||
q.Set("port", fmt.Sprintf("%d", ar.Port))
|
||||
q.Set("uploaded", strconv.FormatInt(ar.Uploaded, 10))
|
||||
q.Set("downloaded", strconv.FormatInt(ar.Downloaded, 10))
|
||||
|
||||
// The AWS S3 tracker returns "400 Bad Request: left(-1) was not in the valid range 0 -
|
||||
// 9223372036854775807" if left is out of range, or "500 Internal Server Error: Internal Server
|
||||
// Error" if omitted entirely.
|
||||
left := ar.Left
|
||||
if left < 0 {
|
||||
left = math.MaxInt64
|
||||
}
|
||||
q.Set("left", strconv.FormatInt(left, 10))
|
||||
|
||||
if ar.Event != shared.None {
|
||||
q.Set("event", ar.Event.String())
|
||||
}
|
||||
// http://stackoverflow.com/questions/17418004/why-does-tracker-server-not-understand-my-request-bittorrent-protocol
|
||||
q.Set("compact", "1")
|
||||
// According to https://wiki.vuze.com/w/Message_Stream_Encryption. TODO:
|
||||
// Take EncryptionPolicy or something like it as a parameter.
|
||||
q.Set("supportcrypto", "1")
|
||||
doIp := func(versionKey string, ip net.IP) {
|
||||
if ip == nil {
|
||||
return
|
||||
}
|
||||
ipString := ip.String()
|
||||
q.Set(versionKey, ipString)
|
||||
// Let's try listing them. BEP 3 mentions having an "ip" param, and BEP 7 says we can list
|
||||
// addresses for other address-families, although it's not encouraged.
|
||||
q.Add("ip", ipString)
|
||||
}
|
||||
doIp("ipv4", opts.ClientIp4)
|
||||
doIp("ipv6", opts.ClientIp6)
|
||||
// We're operating purely on query-escaped strings, where + would have already been encoded to
|
||||
// %2B, and + has no other special meaning. See https://github.com/anacrolix/torrent/issues/534.
|
||||
qstr := strings.ReplaceAll(q.Encode(), "+", "%20")
|
||||
|
||||
// Some private trackers require the original query param to be in the first position.
|
||||
if _url.RawQuery != "" {
|
||||
_url.RawQuery += "&" + qstr
|
||||
} else {
|
||||
_url.RawQuery = qstr
|
||||
}
|
||||
}
|
||||
|
||||
type AnnounceOpt struct {
|
||||
UserAgent string
|
||||
HostHeader string
|
||||
ClientIp4 net.IP
|
||||
ClientIp6 net.IP
|
||||
}
|
||||
|
||||
type AnnounceRequest = udp.AnnounceRequest
|
||||
|
||||
func (cl Client) Announce(ctx context.Context, ar AnnounceRequest, opt AnnounceOpt) (ret AnnounceResponse, err error) {
|
||||
_url := httptoo.CopyURL(cl.url_)
|
||||
setAnnounceParams(_url, &ar, opt)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, _url.String(), nil)
|
||||
userAgent := opt.UserAgent
|
||||
if userAgent == "" {
|
||||
userAgent = version.DefaultHttpUserAgent
|
||||
}
|
||||
if userAgent != "" {
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
}
|
||||
req.Host = opt.HostHeader
|
||||
resp, err := cl.hc.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, resp.Body)
|
||||
if resp.StatusCode != 200 {
|
||||
err = fmt.Errorf("response from tracker: %s: %s", resp.Status, buf.String())
|
||||
return
|
||||
}
|
||||
var trackerResponse HttpResponse
|
||||
err = bencode.Unmarshal(buf.Bytes(), &trackerResponse)
|
||||
if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
|
||||
err = nil
|
||||
} else if err != nil {
|
||||
err = fmt.Errorf("error decoding %q: %s", buf.Bytes(), err)
|
||||
return
|
||||
}
|
||||
if trackerResponse.FailureReason != "" {
|
||||
err = fmt.Errorf("tracker gave failure reason: %q", trackerResponse.FailureReason)
|
||||
return
|
||||
}
|
||||
vars.Add("successful http announces", 1)
|
||||
ret.Interval = trackerResponse.Interval
|
||||
ret.Leechers = trackerResponse.Incomplete
|
||||
ret.Seeders = trackerResponse.Complete
|
||||
if len(trackerResponse.Peers) != 0 {
|
||||
vars.Add("http responses with nonempty peers key", 1)
|
||||
}
|
||||
ret.Peers = trackerResponse.Peers
|
||||
if len(trackerResponse.Peers6) != 0 {
|
||||
vars.Add("http responses with nonempty peers6 key", 1)
|
||||
}
|
||||
for _, na := range trackerResponse.Peers6 {
|
||||
ret.Peers = append(ret.Peers, Peer{
|
||||
IP: na.IP,
|
||||
Port: na.Port,
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type AnnounceResponse struct {
|
||||
Interval int32 // Minimum seconds the local peer should wait before next announce.
|
||||
Leechers int32
|
||||
Seeders int32
|
||||
Peers []Peer
|
||||
}
|
||||
38
vendor/github.com/anacrolix/torrent/tracker/http/peer.go
generated
vendored
Normal file
38
vendor/github.com/anacrolix/torrent/tracker/http/peer.go
generated
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"github.com/anacrolix/dht/v2/krpc"
|
||||
)
|
||||
|
||||
type Peer struct {
|
||||
IP net.IP
|
||||
Port int
|
||||
ID []byte
|
||||
}
|
||||
|
||||
func (p Peer) String() string {
|
||||
loc := net.JoinHostPort(p.IP.String(), fmt.Sprintf("%d", p.Port))
|
||||
if len(p.ID) != 0 {
|
||||
return fmt.Sprintf("%x at %s", p.ID, loc)
|
||||
} else {
|
||||
return loc
|
||||
}
|
||||
}
|
||||
|
||||
// Set from the non-compact form in BEP 3.
|
||||
func (p *Peer) FromDictInterface(d map[string]interface{}) {
|
||||
p.IP = net.ParseIP(d["ip"].(string))
|
||||
if _, ok := d["peer id"]; ok {
|
||||
p.ID = []byte(d["peer id"].(string))
|
||||
}
|
||||
p.Port = int(d["port"].(int64))
|
||||
}
|
||||
|
||||
func (p Peer) FromNodeAddr(na krpc.NodeAddr) Peer {
|
||||
p.IP = na.IP
|
||||
p.Port = na.Port
|
||||
return p
|
||||
}
|
||||
57
vendor/github.com/anacrolix/torrent/tracker/http/protocol.go
generated
vendored
Normal file
57
vendor/github.com/anacrolix/torrent/tracker/http/protocol.go
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/anacrolix/dht/v2/krpc"
|
||||
"github.com/anacrolix/torrent/bencode"
|
||||
)
|
||||
|
||||
type HttpResponse struct {
|
||||
FailureReason string `bencode:"failure reason"`
|
||||
Interval int32 `bencode:"interval"`
|
||||
TrackerId string `bencode:"tracker id"`
|
||||
Complete int32 `bencode:"complete"`
|
||||
Incomplete int32 `bencode:"incomplete"`
|
||||
Peers Peers `bencode:"peers"`
|
||||
// BEP 7
|
||||
Peers6 krpc.CompactIPv6NodeAddrs `bencode:"peers6"`
|
||||
}
|
||||
|
||||
type Peers []Peer
|
||||
|
||||
func (me *Peers) UnmarshalBencode(b []byte) (err error) {
|
||||
var _v interface{}
|
||||
err = bencode.Unmarshal(b, &_v)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch v := _v.(type) {
|
||||
case string:
|
||||
vars.Add("http responses with string peers", 1)
|
||||
var cnas krpc.CompactIPv4NodeAddrs
|
||||
err = cnas.UnmarshalBinary([]byte(v))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, cp := range cnas {
|
||||
*me = append(*me, Peer{
|
||||
IP: cp.IP[:],
|
||||
Port: int(cp.Port),
|
||||
})
|
||||
}
|
||||
return
|
||||
case []interface{}:
|
||||
vars.Add("http responses with list peers", 1)
|
||||
for _, i := range v {
|
||||
var p Peer
|
||||
p.FromDictInterface(i.(map[string]interface{}))
|
||||
*me = append(*me, p)
|
||||
}
|
||||
return
|
||||
default:
|
||||
vars.Add("http responses with unhandled peers type", 1)
|
||||
err = fmt.Errorf("unsupported type: %T", _v)
|
||||
return
|
||||
}
|
||||
}
|
||||
10
vendor/github.com/anacrolix/torrent/tracker/shared/shared.go
generated
vendored
Normal file
10
vendor/github.com/anacrolix/torrent/tracker/shared/shared.go
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
package shared
|
||||
|
||||
import "github.com/anacrolix/torrent/tracker/udp"
|
||||
|
||||
const (
|
||||
None udp.AnnounceEvent = iota
|
||||
Completed // The local peer just completed the torrent.
|
||||
Started // The local peer has just resumed this torrent.
|
||||
Stopped // The local peer is leaving the swarm.
|
||||
)
|
||||
81
vendor/github.com/anacrolix/torrent/tracker/tracker.go
generated
vendored
Normal file
81
vendor/github.com/anacrolix/torrent/tracker/tracker.go
generated
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
package tracker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/anacrolix/dht/v2/krpc"
|
||||
"github.com/anacrolix/log"
|
||||
trHttp "github.com/anacrolix/torrent/tracker/http"
|
||||
"github.com/anacrolix/torrent/tracker/shared"
|
||||
"github.com/anacrolix/torrent/tracker/udp"
|
||||
)
|
||||
|
||||
const (
|
||||
None = shared.None
|
||||
Started = shared.Started
|
||||
Stopped = shared.Stopped
|
||||
Completed = shared.Completed
|
||||
)
|
||||
|
||||
type AnnounceRequest = udp.AnnounceRequest
|
||||
|
||||
type AnnounceResponse = trHttp.AnnounceResponse
|
||||
|
||||
type Peer = trHttp.Peer
|
||||
|
||||
type AnnounceEvent = udp.AnnounceEvent
|
||||
|
||||
var ErrBadScheme = errors.New("unknown scheme")
|
||||
|
||||
type Announce struct {
|
||||
TrackerUrl string
|
||||
Request AnnounceRequest
|
||||
HostHeader string
|
||||
HTTPProxy func(*http.Request) (*url.URL, error)
|
||||
ServerName string
|
||||
UserAgent string
|
||||
UdpNetwork string
|
||||
// If the port is zero, it's assumed to be the same as the Request.Port.
|
||||
ClientIp4 krpc.NodeAddr
|
||||
// If the port is zero, it's assumed to be the same as the Request.Port.
|
||||
ClientIp6 krpc.NodeAddr
|
||||
Context context.Context
|
||||
Logger log.Logger
|
||||
}
|
||||
|
||||
// The code *is* the documentation.
|
||||
const DefaultTrackerAnnounceTimeout = 15 * time.Second
|
||||
|
||||
func (me Announce) Do() (res AnnounceResponse, err error) {
|
||||
cl, err := NewClient(me.TrackerUrl, NewClientOpts{
|
||||
Http: trHttp.NewClientOpts{
|
||||
Proxy: me.HTTPProxy,
|
||||
ServerName: me.ServerName,
|
||||
},
|
||||
UdpNetwork: me.UdpNetwork,
|
||||
Logger: me.Logger.WithContextValue(fmt.Sprintf("tracker client for %q", me.TrackerUrl)),
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer cl.Close()
|
||||
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. See comments elsewhere about longer timeouts
|
||||
// acting as rate limiting overloaded trackers.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultTrackerAnnounceTimeout)
|
||||
defer cancel()
|
||||
me.Context = ctx
|
||||
}
|
||||
return cl.Announce(me.Context, me.Request, trHttp.AnnounceOpt{
|
||||
UserAgent: me.UserAgent,
|
||||
HostHeader: me.HostHeader,
|
||||
ClientIp4: me.ClientIp4.IP,
|
||||
ClientIp6: me.ClientIp6.IP,
|
||||
})
|
||||
}
|
||||
39
vendor/github.com/anacrolix/torrent/tracker/udp.go
generated
vendored
Normal file
39
vendor/github.com/anacrolix/torrent/tracker/udp.go
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
package tracker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
|
||||
trHttp "github.com/anacrolix/torrent/tracker/http"
|
||||
"github.com/anacrolix/torrent/tracker/udp"
|
||||
)
|
||||
|
||||
type udpClient struct {
|
||||
cl *udp.ConnClient
|
||||
requestUri string
|
||||
}
|
||||
|
||||
func (c *udpClient) Close() error {
|
||||
return c.cl.Close()
|
||||
}
|
||||
|
||||
func (c *udpClient) Announce(ctx context.Context, req AnnounceRequest, opts trHttp.AnnounceOpt) (res AnnounceResponse, err error) {
|
||||
if req.IPAddress == 0 && opts.ClientIp4 != nil {
|
||||
// I think we're taking bytes in big-endian order (all IPs), and writing it to a natively
|
||||
// ordered uint32. This will be correctly ordered when written back out by the UDP client
|
||||
// later. I'm ignoring the fact that IPv6 announces shouldn't have an IP address, we have a
|
||||
// perfectly good IPv4 address.
|
||||
req.IPAddress = binary.BigEndian.Uint32(opts.ClientIp4.To4())
|
||||
}
|
||||
h, nas, err := c.cl.Announce(ctx, req, udp.Options{RequestUri: c.requestUri})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
res.Interval = h.Interval
|
||||
res.Leechers = h.Leechers
|
||||
res.Seeders = h.Seeders
|
||||
for _, cp := range nas.NodeAddrs() {
|
||||
res.Peers = append(res.Peers, trHttp.Peer{}.FromNodeAddr(cp))
|
||||
}
|
||||
return
|
||||
}
|
||||
35
vendor/github.com/anacrolix/torrent/tracker/udp/announce.go
generated
vendored
Normal file
35
vendor/github.com/anacrolix/torrent/tracker/udp/announce.go
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
package udp
|
||||
|
||||
import (
|
||||
"encoding"
|
||||
|
||||
"github.com/anacrolix/dht/v2/krpc"
|
||||
)
|
||||
|
||||
// Marshalled as binary by the UDP client, so be careful making changes.
|
||||
type AnnounceRequest struct {
|
||||
InfoHash [20]byte
|
||||
PeerId [20]byte
|
||||
Downloaded int64
|
||||
Left int64 // If less than 0, math.MaxInt64 will be used for HTTP trackers instead.
|
||||
Uploaded int64
|
||||
// Apparently this is optional. None can be used for announces done at
|
||||
// regular intervals.
|
||||
Event AnnounceEvent
|
||||
IPAddress uint32
|
||||
Key int32
|
||||
NumWant int32 // How many peer addresses are desired. -1 for default.
|
||||
Port uint16
|
||||
} // 82 bytes
|
||||
|
||||
type AnnounceEvent int32
|
||||
|
||||
func (e AnnounceEvent) String() string {
|
||||
// See BEP 3, "event", and https://github.com/anacrolix/torrent/issues/416#issuecomment-751427001.
|
||||
return []string{"", "completed", "started", "stopped"}[e]
|
||||
}
|
||||
|
||||
type AnnounceResponsePeers interface {
|
||||
encoding.BinaryUnmarshaler
|
||||
NodeAddrs() []krpc.NodeAddr
|
||||
}
|
||||
179
vendor/github.com/anacrolix/torrent/tracker/udp/client.go
generated
vendored
Normal file
179
vendor/github.com/anacrolix/torrent/tracker/udp/client.go
generated
vendored
Normal file
@@ -0,0 +1,179 @@
|
||||
package udp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/anacrolix/dht/v2/krpc"
|
||||
)
|
||||
|
||||
// Client interacts with UDP trackers via its Writer and Dispatcher. It has no knowledge of
|
||||
// connection specifics.
|
||||
type Client struct {
|
||||
mu sync.Mutex
|
||||
connId ConnectionId
|
||||
connIdIssued time.Time
|
||||
Dispatcher *Dispatcher
|
||||
Writer io.Writer
|
||||
}
|
||||
|
||||
func (cl *Client) Announce(
|
||||
ctx context.Context, req AnnounceRequest, opts Options,
|
||||
// Decides whether the response body is IPv6 or IPv4, see BEP 15.
|
||||
ipv6 func(net.Addr) bool,
|
||||
) (
|
||||
respHdr AnnounceResponseHeader,
|
||||
// A slice of krpc.NodeAddr, likely wrapped in an appropriate unmarshalling wrapper.
|
||||
peers AnnounceResponsePeers,
|
||||
err error,
|
||||
) {
|
||||
respBody, addr, err := cl.request(ctx, ActionAnnounce, append(mustMarshal(req), opts.Encode()...))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
r := bytes.NewBuffer(respBody)
|
||||
err = Read(r, &respHdr)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("reading response header: %w", err)
|
||||
return
|
||||
}
|
||||
if ipv6(addr) {
|
||||
peers = &krpc.CompactIPv6NodeAddrs{}
|
||||
} else {
|
||||
peers = &krpc.CompactIPv4NodeAddrs{}
|
||||
}
|
||||
err = peers.UnmarshalBinary(r.Bytes())
|
||||
if err != nil {
|
||||
err = fmt.Errorf("reading response peers: %w", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// There's no way to pass options in a scrape, since we don't when the request body ends.
|
||||
func (cl *Client) Scrape(
|
||||
ctx context.Context, ihs []InfoHash,
|
||||
) (
|
||||
out ScrapeResponse, err error,
|
||||
) {
|
||||
respBody, _, err := cl.request(ctx, ActionScrape, mustMarshal(ScrapeRequest(ihs)))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
r := bytes.NewBuffer(respBody)
|
||||
for r.Len() != 0 {
|
||||
var item ScrapeInfohashResult
|
||||
err = Read(r, &item)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
if len(out) > len(ihs) {
|
||||
err = fmt.Errorf("got %v results but expected %v", len(out), len(ihs))
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (cl *Client) connect(ctx context.Context) (err error) {
|
||||
// We could get fancier here and use RWMutex, and even fire off the connection asynchronously
|
||||
// and provide a grace period while it resolves.
|
||||
cl.mu.Lock()
|
||||
defer cl.mu.Unlock()
|
||||
if !cl.connIdIssued.IsZero() && time.Since(cl.connIdIssued) < time.Minute {
|
||||
return nil
|
||||
}
|
||||
respBody, _, err := cl.request(ctx, ActionConnect, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var connResp ConnectionResponse
|
||||
err = binary.Read(bytes.NewReader(respBody), binary.BigEndian, &connResp)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cl.connId = connResp.ConnectionId
|
||||
cl.connIdIssued = time.Now()
|
||||
return
|
||||
}
|
||||
|
||||
func (cl *Client) connIdForRequest(ctx context.Context, action Action) (id ConnectionId, err error) {
|
||||
if action == ActionConnect {
|
||||
id = ConnectRequestConnectionId
|
||||
return
|
||||
}
|
||||
err = cl.connect(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
id = cl.connId
|
||||
return
|
||||
}
|
||||
|
||||
func (cl *Client) requestWriter(ctx context.Context, action Action, body []byte, tId TransactionId) (err error) {
|
||||
var buf bytes.Buffer
|
||||
for n := 0; ; n++ {
|
||||
var connId ConnectionId
|
||||
connId, err = cl.connIdForRequest(ctx, action)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
buf.Reset()
|
||||
err = binary.Write(&buf, binary.BigEndian, RequestHeader{
|
||||
ConnectionId: connId,
|
||||
Action: action,
|
||||
TransactionId: tId,
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
buf.Write(body)
|
||||
_, err = cl.Writer.Write(buf.Bytes())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(timeout(n)):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (cl *Client) request(ctx context.Context, action Action, body []byte) (respBody []byte, addr net.Addr, err error) {
|
||||
respChan := make(chan DispatchedResponse, 1)
|
||||
t := cl.Dispatcher.NewTransaction(func(dr DispatchedResponse) {
|
||||
respChan <- dr
|
||||
})
|
||||
defer t.End()
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
writeErr := make(chan error, 1)
|
||||
go func() {
|
||||
writeErr <- cl.requestWriter(ctx, action, body, t.Id())
|
||||
}()
|
||||
select {
|
||||
case dr := <-respChan:
|
||||
if dr.Header.Action == action {
|
||||
respBody = dr.Body
|
||||
addr = dr.Addr
|
||||
} else if dr.Header.Action == ActionError {
|
||||
// I've seen "Connection ID mismatch.^@" in less and other tools, I think they're just
|
||||
// not handling a trailing \x00 nicely.
|
||||
err = fmt.Errorf("error response: %#q", dr.Body)
|
||||
} else {
|
||||
err = fmt.Errorf("unexpected response action %v", dr.Header.Action)
|
||||
}
|
||||
case err = <-writeErr:
|
||||
err = fmt.Errorf("write error: %w", err)
|
||||
case <-ctx.Done():
|
||||
err = ctx.Err()
|
||||
}
|
||||
return
|
||||
}
|
||||
123
vendor/github.com/anacrolix/torrent/tracker/udp/conn-client.go
generated
vendored
Normal file
123
vendor/github.com/anacrolix/torrent/tracker/udp/conn-client.go
generated
vendored
Normal file
@@ -0,0 +1,123 @@
|
||||
package udp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/anacrolix/log"
|
||||
|
||||
"github.com/anacrolix/missinggo/v2"
|
||||
)
|
||||
|
||||
type NewConnClientOpts struct {
|
||||
// The network to operate to use, such as "udp4", "udp", "udp6".
|
||||
Network string
|
||||
// Tracker address
|
||||
Host string
|
||||
// If non-nil, forces either IPv4 or IPv6 in the UDP tracker wire protocol.
|
||||
Ipv6 *bool
|
||||
// Logger to use for internal errors.
|
||||
Logger log.Logger
|
||||
}
|
||||
|
||||
// Manages a Client with a specific connection.
|
||||
type ConnClient struct {
|
||||
Client Client
|
||||
conn net.PacketConn
|
||||
d Dispatcher
|
||||
readErr error
|
||||
closed bool
|
||||
newOpts NewConnClientOpts
|
||||
}
|
||||
|
||||
func (cc *ConnClient) reader() {
|
||||
b := make([]byte, 0x800)
|
||||
for {
|
||||
n, addr, err := cc.conn.ReadFrom(b)
|
||||
if err != nil {
|
||||
// TODO: Do bad things to the dispatcher, and incoming calls to the client if we have a
|
||||
// read error.
|
||||
cc.readErr = err
|
||||
if !cc.closed {
|
||||
panic(err)
|
||||
}
|
||||
break
|
||||
}
|
||||
err = cc.d.Dispatch(b[:n], addr)
|
||||
if err != nil {
|
||||
cc.newOpts.Logger.Levelf(log.Debug, "dispatching packet received on %v: %v", cc.conn.LocalAddr(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ipv6(opt *bool, network string, remoteAddr net.Addr) bool {
|
||||
if opt != nil {
|
||||
return *opt
|
||||
}
|
||||
switch network {
|
||||
case "udp4":
|
||||
return false
|
||||
case "udp6":
|
||||
return true
|
||||
}
|
||||
rip := missinggo.AddrIP(remoteAddr)
|
||||
return rip.To16() != nil && rip.To4() == nil
|
||||
}
|
||||
|
||||
// Allows a UDP Client to write packets to an endpoint without knowing about the network specifics.
|
||||
type clientWriter struct {
|
||||
pc net.PacketConn
|
||||
network string
|
||||
address string
|
||||
}
|
||||
|
||||
func (me clientWriter) Write(p []byte) (n int, err error) {
|
||||
addr, err := net.ResolveUDPAddr(me.network, me.address)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return me.pc.WriteTo(p, addr)
|
||||
}
|
||||
|
||||
func NewConnClient(opts NewConnClientOpts) (cc *ConnClient, err error) {
|
||||
conn, err := net.ListenPacket(opts.Network, ":0")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if opts.Logger.IsZero() {
|
||||
opts.Logger = log.Default
|
||||
}
|
||||
cc = &ConnClient{
|
||||
Client: Client{
|
||||
Writer: clientWriter{
|
||||
pc: conn,
|
||||
network: opts.Network,
|
||||
address: opts.Host,
|
||||
},
|
||||
},
|
||||
conn: conn,
|
||||
newOpts: opts,
|
||||
}
|
||||
cc.Client.Dispatcher = &cc.d
|
||||
go cc.reader()
|
||||
return
|
||||
}
|
||||
|
||||
func (cc *ConnClient) Close() error {
|
||||
cc.closed = true
|
||||
return cc.conn.Close()
|
||||
}
|
||||
|
||||
func (cc *ConnClient) Announce(
|
||||
ctx context.Context, req AnnounceRequest, opts Options,
|
||||
) (
|
||||
h AnnounceResponseHeader, nas AnnounceResponsePeers, err error,
|
||||
) {
|
||||
return cc.Client.Announce(ctx, req, opts, func(addr net.Addr) bool {
|
||||
return ipv6(cc.newOpts.Ipv6, cc.newOpts.Network, addr)
|
||||
})
|
||||
}
|
||||
|
||||
func (cc *ConnClient) LocalAddr() net.Addr {
|
||||
return cc.conn.LocalAddr()
|
||||
}
|
||||
71
vendor/github.com/anacrolix/torrent/tracker/udp/dispatcher.go
generated
vendored
Normal file
71
vendor/github.com/anacrolix/torrent/tracker/udp/dispatcher.go
generated
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
package udp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Maintains a mapping of transaction IDs to handlers.
|
||||
type Dispatcher struct {
|
||||
mu sync.RWMutex
|
||||
transactions map[TransactionId]Transaction
|
||||
}
|
||||
|
||||
// The caller owns b.
|
||||
func (me *Dispatcher) Dispatch(b []byte, addr net.Addr) error {
|
||||
buf := bytes.NewBuffer(b)
|
||||
var rh ResponseHeader
|
||||
err := Read(buf, &rh)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
me.mu.RLock()
|
||||
defer me.mu.RUnlock()
|
||||
if t, ok := me.transactions[rh.TransactionId]; ok {
|
||||
t.h(DispatchedResponse{
|
||||
Header: rh,
|
||||
Body: append([]byte(nil), buf.Bytes()...),
|
||||
Addr: addr,
|
||||
})
|
||||
return nil
|
||||
} else {
|
||||
return fmt.Errorf("unknown transaction id %v", rh.TransactionId)
|
||||
}
|
||||
}
|
||||
|
||||
func (me *Dispatcher) forgetTransaction(id TransactionId) {
|
||||
me.mu.Lock()
|
||||
defer me.mu.Unlock()
|
||||
delete(me.transactions, id)
|
||||
}
|
||||
|
||||
func (me *Dispatcher) NewTransaction(h TransactionResponseHandler) Transaction {
|
||||
me.mu.Lock()
|
||||
defer me.mu.Unlock()
|
||||
for {
|
||||
id := RandomTransactionId()
|
||||
if _, ok := me.transactions[id]; ok {
|
||||
continue
|
||||
}
|
||||
t := Transaction{
|
||||
d: me,
|
||||
h: h,
|
||||
id: id,
|
||||
}
|
||||
if me.transactions == nil {
|
||||
me.transactions = make(map[TransactionId]Transaction)
|
||||
}
|
||||
me.transactions[id] = t
|
||||
return t
|
||||
}
|
||||
}
|
||||
|
||||
type DispatchedResponse struct {
|
||||
Header ResponseHeader
|
||||
// Response payload, after the header.
|
||||
Body []byte
|
||||
// Response source address
|
||||
Addr net.Addr
|
||||
}
|
||||
24
vendor/github.com/anacrolix/torrent/tracker/udp/options.go
generated
vendored
Normal file
24
vendor/github.com/anacrolix/torrent/tracker/udp/options.go
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
package udp
|
||||
|
||||
import (
|
||||
"math"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
RequestUri string
|
||||
}
|
||||
|
||||
func (opts Options) Encode() (ret []byte) {
|
||||
for {
|
||||
l := len(opts.RequestUri)
|
||||
if l == 0 {
|
||||
break
|
||||
}
|
||||
if l > math.MaxUint8 {
|
||||
l = math.MaxUint8
|
||||
}
|
||||
ret = append(append(ret, optionTypeURLData, byte(l)), opts.RequestUri[:l]...)
|
||||
opts.RequestUri = opts.RequestUri[l:]
|
||||
}
|
||||
return
|
||||
}
|
||||
79
vendor/github.com/anacrolix/torrent/tracker/udp/protocol.go
generated
vendored
Normal file
79
vendor/github.com/anacrolix/torrent/tracker/udp/protocol.go
generated
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
package udp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
)
|
||||
|
||||
type Action int32
|
||||
|
||||
const (
|
||||
ActionConnect Action = iota
|
||||
ActionAnnounce
|
||||
ActionScrape
|
||||
ActionError
|
||||
|
||||
ConnectRequestConnectionId = 0x41727101980
|
||||
|
||||
// BEP 41
|
||||
optionTypeEndOfOptions = 0
|
||||
optionTypeNOP = 1
|
||||
optionTypeURLData = 2
|
||||
)
|
||||
|
||||
type TransactionId = int32
|
||||
|
||||
type ConnectionId = int64
|
||||
|
||||
type ConnectionRequest struct {
|
||||
ConnectionId ConnectionId
|
||||
Action Action
|
||||
TransactionId TransactionId
|
||||
}
|
||||
|
||||
type ConnectionResponse struct {
|
||||
ConnectionId ConnectionId
|
||||
}
|
||||
|
||||
type ResponseHeader struct {
|
||||
Action Action
|
||||
TransactionId TransactionId
|
||||
}
|
||||
|
||||
type RequestHeader struct {
|
||||
ConnectionId ConnectionId
|
||||
Action Action
|
||||
TransactionId TransactionId
|
||||
} // 16 bytes
|
||||
|
||||
type AnnounceResponseHeader struct {
|
||||
Interval int32
|
||||
Leechers int32
|
||||
Seeders int32
|
||||
}
|
||||
|
||||
type InfoHash = [20]byte
|
||||
|
||||
func marshal(data interface{}) (b []byte, err error) {
|
||||
var buf bytes.Buffer
|
||||
err = binary.Write(&buf, binary.BigEndian, data)
|
||||
b = buf.Bytes()
|
||||
return
|
||||
}
|
||||
|
||||
func mustMarshal(data interface{}) []byte {
|
||||
b, err := marshal(data)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func Write(w io.Writer, data interface{}) error {
|
||||
return binary.Write(w, binary.BigEndian, data)
|
||||
}
|
||||
|
||||
func Read(r io.Reader, data interface{}) error {
|
||||
return binary.Read(r, binary.BigEndian, data)
|
||||
}
|
||||
11
vendor/github.com/anacrolix/torrent/tracker/udp/scrape.go
generated
vendored
Normal file
11
vendor/github.com/anacrolix/torrent/tracker/udp/scrape.go
generated
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
package udp
|
||||
|
||||
type ScrapeRequest []InfoHash
|
||||
|
||||
type ScrapeResponse []ScrapeInfohashResult
|
||||
|
||||
type ScrapeInfohashResult struct {
|
||||
Seeders int32
|
||||
Completed int32
|
||||
Leechers int32
|
||||
}
|
||||
18
vendor/github.com/anacrolix/torrent/tracker/udp/timeout.go
generated
vendored
Normal file
18
vendor/github.com/anacrolix/torrent/tracker/udp/timeout.go
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
package udp
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxTimeout = 3840 * time.Second
|
||||
|
||||
func timeout(contiguousTimeouts int) (d time.Duration) {
|
||||
if contiguousTimeouts > 8 {
|
||||
contiguousTimeouts = 8
|
||||
}
|
||||
d = 15 * time.Second
|
||||
for ; contiguousTimeouts > 0; contiguousTimeouts-- {
|
||||
d *= 2
|
||||
}
|
||||
return
|
||||
}
|
||||
23
vendor/github.com/anacrolix/torrent/tracker/udp/transaction.go
generated
vendored
Normal file
23
vendor/github.com/anacrolix/torrent/tracker/udp/transaction.go
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
package udp
|
||||
|
||||
import "math/rand"
|
||||
|
||||
func RandomTransactionId() TransactionId {
|
||||
return TransactionId(rand.Uint32())
|
||||
}
|
||||
|
||||
type TransactionResponseHandler func(dr DispatchedResponse)
|
||||
|
||||
type Transaction struct {
|
||||
id int32
|
||||
d *Dispatcher
|
||||
h TransactionResponseHandler
|
||||
}
|
||||
|
||||
func (t *Transaction) Id() TransactionId {
|
||||
return t.id
|
||||
}
|
||||
|
||||
func (t *Transaction) End() {
|
||||
t.d.forgetTransaction(t.id)
|
||||
}
|
||||
Reference in New Issue
Block a user