10 "github.com/anacrolix/dht/v2"
11 "github.com/anacrolix/dht/v2/krpc"
12 "github.com/anacrolix/log"
13 "github.com/anacrolix/missinggo/v2"
14 "golang.org/x/time/rate"
16 "github.com/anacrolix/torrent/iplist"
17 "github.com/anacrolix/torrent/mse"
18 "github.com/anacrolix/torrent/storage"
19 "github.com/anacrolix/torrent/version"
22 // Contains config elements that are exclusive to tracker handling. There may be other fields in
23 // ClientConfig that are also relevant.
24 type ClientTrackerConfig struct {
25 // Don't announce to trackers. This only leaves DHT to discover peers.
26 DisableTrackers bool `long:"disable-trackers"`
27 // Defines DialContext func to use for HTTP tracker announcements
28 TrackerDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
29 // Defines ListenPacket func to use for UDP tracker announcements
30 TrackerListenPacket func(network, addr string) (net.PacketConn, error)
31 // Takes a tracker's hostname and requests DNS A and AAAA records.
32 // Used in case DNS lookups require a special setup (i.e., dns-over-https)
33 LookupTrackerIp func(*url.URL) ([]net.IP, error)
36 type ClientDhtConfig struct {
37 // Don't create a DHT.
38 NoDHT bool `long:"disable-dht"`
39 DhtStartingNodes func(network string) dht.StartingNodesGetter
40 // Called for each anacrolix/dht Server created for the Client.
41 ConfigureAnacrolixDhtServer func(*dht.ServerConfig)
42 PeriodicallyAnnounceTorrentsToDht bool
44 DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
47 // Probably not safe to modify this after it's given to a Client.
48 type ClientConfig struct {
52 // Store torrent file data in this directory unless .DefaultStorage is
54 DataDir string `long:"data-dir" description:"directory to store downloaded torrent data"`
55 // The address to listen for new uTP and TCP BitTorrent protocol connections. DHT shares a UDP
56 // socket with uTP unless configured otherwise.
57 ListenHost func(network string) string
59 NoDefaultPortForwarding bool
61 DisablePEX bool `long:"disable-pex"`
63 // Never send chunks to peers.
64 NoUpload bool `long:"no-upload"`
65 // Disable uploading even when it isn't fair.
66 DisableAggressiveUpload bool `long:"disable-aggressive-upload"`
67 // Upload even after there's nothing in it for us. By default uploading is
68 // not altruistic, we'll only upload to encourage the peer to reciprocate.
69 Seed bool `long:"seed"`
70 // Only applies to chunks uploaded to peers, to maintain responsiveness
71 // communicating local Client state to peers. Each limiter token
72 // represents one byte. The Limiter's burst must be large enough to fit a
73 // whole chunk, which is usually 16 KiB (see TorrentSpec.ChunkSize).
74 UploadRateLimiter *rate.Limiter
75 // Rate limits all reads from connections to peers. Each limiter token
76 // represents one byte. The Limiter's burst must be bigger than the
77 // largest Read performed on a the underlying rate-limiting io.Reader
78 // minus one. This is likely to be the larger of the main read loop buffer
79 // (~4096), and the requested chunk size (~16KiB, see
80 // TorrentSpec.ChunkSize).
81 DownloadRateLimiter *rate.Limiter
82 // Maximum unverified bytes across all torrents. Not used if zero.
83 MaxUnverifiedBytes int64
85 // User-provided Client peer ID. If not present, one is generated automatically.
87 // For the bittorrent protocol.
89 // For the bittorrent protocol.
90 DisableTCP bool `long:"disable-tcp"`
91 // Called to instantiate storage for each added torrent. Builtin backends
92 // are in the storage package. If not set, the "file" implementation is
93 // used (and Closed when the Client is Closed).
94 DefaultStorage storage.ClientImpl
96 HeaderObfuscationPolicy HeaderObfuscationPolicy
97 // The crypto methods to offer when initiating connections with header obfuscation.
98 CryptoProvides mse.CryptoMethod
99 // Chooses the crypto method to use when receiving connections with header obfuscation.
100 CryptoSelector mse.CryptoSelector
102 IPBlocklist iplist.Ranger
103 DisableIPv6 bool `long:"disable-ipv6"`
105 DisableIPv4Peers bool
106 // Perform logging and any other behaviour that will help debug.
107 Debug bool `help:"enable debugging"`
110 // Defines proxy for HTTP requests, such as for trackers. It's commonly set from the result of
111 // "net/http".ProxyURL(HTTPProxy).
112 HTTPProxy func(*http.Request) (*url.URL, error)
113 // Defines DialContext func to use for HTTP requests, such as for fetching metainfo and webtorrent seeds
114 HTTPDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
115 // HTTPUserAgent changes default UserAgent for HTTP requests
117 // HttpRequestDirector modifies the request before it's sent.
118 // Useful for adding authentication headers, for example
119 HttpRequestDirector func(*http.Request) error
120 // WebsocketTrackerHttpHeader returns a custom header to be used when dialing a websocket connection
121 // to the tracker. Useful for adding authentication headers
122 WebsocketTrackerHttpHeader func() http.Header
123 // Updated occasionally to when there's been some changes to client
124 // behaviour in case other clients are assuming anything of us. See also
126 ExtendedHandshakeClientVersion string
127 // Peer ID client identifier prefix. We'll update this occasionally to
128 // reflect changes to client behaviour that other clients may depend on.
129 // Also see `extendedHandshakeClientVersion`.
132 // Peer dial timeout to use when there are limited peers.
133 NominalDialTimeout time.Duration
134 // Minimum peer dial timeout to use (even if we have lots of peers).
135 MinDialTimeout time.Duration
136 EstablishedConnsPerTorrent int
137 HalfOpenConnsPerTorrent int
138 TotalHalfOpenConns int
139 // Maximum number of peer addresses in reserve.
140 TorrentPeersHighWater int
141 // Minumum number of peers before effort is made to obtain more peers.
142 TorrentPeersLowWater int
144 // Limit how long handshake can take. This is to reduce the lingering
145 // impact of a few bad apples. 4s loses 1% of successful handshakes that
146 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
147 HandshakesTimeout time.Duration
148 // How long between writes before sending a keep alive message on a peer connection that we want
150 KeepAliveTimeout time.Duration
151 // Maximum bytes to buffer per peer connection for peer request data before it is sent.
152 MaxAllocPeerRequestDataPerConn int64
154 // The IP addresses as our peers should see them. May differ from the
155 // local interfaces due to NAT or other network configurations.
159 // Accept rate limiting affects excessive connection attempts from IPs that fail during
160 // handshakes or request torrents that we don't have.
161 DisableAcceptRateLimiting bool
162 // Don't add connections that have the same peer ID as an existing
163 // connection for a given Torrent.
164 DropDuplicatePeerIds bool
165 // Drop peers that are complete if we are also complete and have no use for the peer. This is a
166 // bit of a special case, since a peer could also be useless if they're just not interested, or
167 // we don't intend to obtain all of a torrent's data.
168 DropMutuallyCompletePeers bool
169 // Whether to accept peer connections at all.
170 AcceptPeerConnections bool
171 // Whether a Client should want conns without delegating to any attached Torrents. This is
172 // useful when torrents might be added dynamically in callbacks for example.
175 Extensions PeerExtensionBits
176 // Bits that peers must have set to proceed past handshakes.
177 MinPeerExtensions PeerExtensionBits
179 DisableWebtorrent bool
184 // ICEServers defines a slice describing servers available to be used by
185 // ICE, such as STUN and TURN servers.
188 DialRateLimiter *rate.Limiter
191 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
192 host, port, err := missinggo.ParseHostPort(addr)
196 cfg.ListenHost = func(string) string { return host }
197 cfg.ListenPort = port
201 func NewDefaultClientConfig() *ClientConfig {
203 HTTPUserAgent: version.DefaultHttpUserAgent,
204 ExtendedHandshakeClientVersion: version.DefaultExtendedHandshakeClientVersion,
205 Bep20: version.DefaultBep20Prefix,
206 UpnpID: version.DefaultUpnpId,
207 NominalDialTimeout: 20 * time.Second,
208 MinDialTimeout: 3 * time.Second,
209 EstablishedConnsPerTorrent: 50,
210 HalfOpenConnsPerTorrent: 25,
211 TotalHalfOpenConns: 100,
212 TorrentPeersHighWater: 500,
213 TorrentPeersLowWater: 50,
214 HandshakesTimeout: 4 * time.Second,
215 KeepAliveTimeout: time.Minute,
216 MaxAllocPeerRequestDataPerConn: 1 << 20,
217 ListenHost: func(string) string { return "" },
218 UploadRateLimiter: unlimited,
219 DownloadRateLimiter: unlimited,
220 DisableAcceptRateLimiting: true,
221 DropMutuallyCompletePeers: true,
222 HeaderObfuscationPolicy: HeaderObfuscationPolicy{
224 RequirePreferred: false,
226 CryptoSelector: mse.DefaultCryptoSelector,
227 CryptoProvides: mse.AllSupportedCrypto,
229 Extensions: defaultPeerExtensionBytes(),
230 AcceptPeerConnections: true,
231 MaxUnverifiedBytes: 64 << 20,
232 DialRateLimiter: rate.NewLimiter(10, 10),
234 cc.DhtStartingNodes = func(network string) dht.StartingNodesGetter {
235 return func() ([]dht.Addr, error) { return dht.GlobalBootstrapAddrs(network) }
237 cc.PeriodicallyAnnounceTorrentsToDht = true
241 type HeaderObfuscationPolicy struct {
242 RequirePreferred bool // Whether the value of Preferred is a strict requirement.
243 Preferred bool // Whether header obfuscation is preferred.