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