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 // Used for torrent sources and webseeding if set.
111 WebTransport http.RoundTripper
112 // Defines proxy for HTTP requests, such as for trackers. It's commonly set from the result of
113 // "net/http".ProxyURL(HTTPProxy).
114 HTTPProxy func(*http.Request) (*url.URL, error)
115 // Defines DialContext func to use for HTTP requests, such as for fetching metainfo and webtorrent seeds
116 HTTPDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
117 // HTTPUserAgent changes default UserAgent for HTTP requests
119 // HttpRequestDirector modifies the request before it's sent.
120 // Useful for adding authentication headers, for example
121 HttpRequestDirector func(*http.Request) error
122 // WebsocketTrackerHttpHeader returns a custom header to be used when dialing a websocket connection
123 // to the tracker. Useful for adding authentication headers
124 WebsocketTrackerHttpHeader func() http.Header
125 // Updated occasionally to when there's been some changes to client
126 // behaviour in case other clients are assuming anything of us. See also
128 ExtendedHandshakeClientVersion string
129 // Peer ID client identifier prefix. We'll update this occasionally to
130 // reflect changes to client behaviour that other clients may depend on.
131 // Also see `extendedHandshakeClientVersion`.
134 // Peer dial timeout to use when there are limited peers.
135 NominalDialTimeout time.Duration
136 // Minimum peer dial timeout to use (even if we have lots of peers).
137 MinDialTimeout time.Duration
138 EstablishedConnsPerTorrent int
139 HalfOpenConnsPerTorrent int
140 TotalHalfOpenConns int
141 // Maximum number of peer addresses in reserve.
142 TorrentPeersHighWater int
143 // Minumum number of peers before effort is made to obtain more peers.
144 TorrentPeersLowWater int
146 // Limit how long handshake can take. This is to reduce the lingering
147 // impact of a few bad apples. 4s loses 1% of successful handshakes that
148 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
149 HandshakesTimeout time.Duration
150 // How long between writes before sending a keep alive message on a peer connection that we want
152 KeepAliveTimeout time.Duration
153 // Maximum bytes to buffer per peer connection for peer request data before it is sent.
154 MaxAllocPeerRequestDataPerConn int64
156 // The IP addresses as our peers should see them. May differ from the
157 // local interfaces due to NAT or other network configurations.
161 // Accept rate limiting affects excessive connection attempts from IPs that fail during
162 // handshakes or request torrents that we don't have.
163 DisableAcceptRateLimiting bool
164 // Don't add connections that have the same peer ID as an existing
165 // connection for a given Torrent.
166 DropDuplicatePeerIds bool
167 // Drop peers that are complete if we are also complete and have no use for the peer. This is a
168 // bit of a special case, since a peer could also be useless if they're just not interested, or
169 // we don't intend to obtain all of a torrent's data.
170 DropMutuallyCompletePeers bool
171 // Whether to accept peer connections at all.
172 AcceptPeerConnections bool
173 // Whether a Client should want conns without delegating to any attached Torrents. This is
174 // useful when torrents might be added dynamically in callbacks for example.
177 Extensions PeerExtensionBits
178 // Bits that peers must have set to proceed past handshakes.
179 MinPeerExtensions PeerExtensionBits
181 DisableWebtorrent bool
186 // ICEServers defines a slice describing servers available to be used by
187 // ICE, such as STUN and TURN servers.
190 DialRateLimiter *rate.Limiter
192 PieceHashersPerTorrent int // default: 2
195 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
196 host, port, err := missinggo.ParseHostPort(addr)
200 cfg.ListenHost = func(string) string { return host }
201 cfg.ListenPort = port
205 func NewDefaultClientConfig() *ClientConfig {
207 HTTPUserAgent: version.DefaultHttpUserAgent,
208 ExtendedHandshakeClientVersion: version.DefaultExtendedHandshakeClientVersion,
209 Bep20: version.DefaultBep20Prefix,
210 UpnpID: version.DefaultUpnpId,
211 NominalDialTimeout: 20 * time.Second,
212 MinDialTimeout: 3 * time.Second,
213 EstablishedConnsPerTorrent: 50,
214 HalfOpenConnsPerTorrent: 25,
215 TotalHalfOpenConns: 100,
216 TorrentPeersHighWater: 500,
217 TorrentPeersLowWater: 50,
218 HandshakesTimeout: 4 * time.Second,
219 KeepAliveTimeout: time.Minute,
220 MaxAllocPeerRequestDataPerConn: 1 << 20,
221 ListenHost: func(string) string { return "" },
222 UploadRateLimiter: unlimited,
223 DownloadRateLimiter: unlimited,
224 DisableAcceptRateLimiting: true,
225 DropMutuallyCompletePeers: true,
226 HeaderObfuscationPolicy: HeaderObfuscationPolicy{
228 RequirePreferred: false,
230 CryptoSelector: mse.DefaultCryptoSelector,
231 CryptoProvides: mse.AllSupportedCrypto,
233 Extensions: defaultPeerExtensionBytes(),
234 AcceptPeerConnections: true,
235 MaxUnverifiedBytes: 64 << 20,
236 DialRateLimiter: rate.NewLimiter(10, 10),
237 PieceHashersPerTorrent: 2,
239 cc.DhtStartingNodes = func(network string) dht.StartingNodesGetter {
240 return func() ([]dht.Addr, error) { return dht.GlobalBootstrapAddrs(network) }
242 cc.PeriodicallyAnnounceTorrentsToDht = true
246 type HeaderObfuscationPolicy struct {
247 RequirePreferred bool // Whether the value of Preferred is a strict requirement.
248 Preferred bool // Whether header obfuscation is preferred.