]> Sergey Matveev's repositories - btrtrc.git/blob - config.go
cmd/btrtrc client
[btrtrc.git] / config.go
1 package torrent
2
3 import (
4         "context"
5         "net"
6         "net/http"
7         "net/url"
8         "time"
9
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"
16
17         "github.com/anacrolix/torrent/iplist"
18         "github.com/anacrolix/torrent/mse"
19         "github.com/anacrolix/torrent/storage"
20         "github.com/anacrolix/torrent/version"
21 )
22
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)
35 }
36
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
44         // OnQuery hook func
45         DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
46 }
47
48 // Probably not safe to modify this after it's given to a Client.
49 type ClientConfig struct {
50         ClientTrackerConfig
51         ClientDhtConfig
52
53         // Store torrent file data in this directory unless .DefaultStorage is
54         // specified.
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
59         ListenPort              int
60         NoDefaultPortForwarding bool
61         UpnpID                  string
62         DisablePEX              bool `long:"disable-pex"`
63
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
85
86         // User-provided Client peer ID. If not present, one is generated automatically.
87         PeerID string
88         // For the bittorrent protocol.
89         DisableUTP bool
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
96
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
102
103         IPBlocklist      iplist.Ranger
104         DisableIPv6      bool `long:"disable-ipv6"`
105         DisableIPv4      bool
106         DisableIPv4Peers bool
107         // Perform logging and any other behaviour that will help debug.
108         Debug  bool `help:"enable debugging"`
109         Logger log.Logger
110
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
119         HTTPUserAgent string
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
128         // `bep20`.
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`.
133         Bep20 string
134
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
146
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
152         // to maintain.
153         KeepAliveTimeout time.Duration
154         // Maximum bytes to buffer per peer connection for peer request data before it is sent.
155         MaxAllocPeerRequestDataPerConn int64
156
157         // The IP addresses as our peers should see them. May differ from the
158         // local interfaces due to NAT or other network configurations.
159         PublicIp4 net.IP
160         PublicIp6 net.IP
161
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.
176         AlwaysWantConns bool
177
178         Extensions PeerExtensionBits
179         // Bits that peers must have set to proceed past handshakes.
180         MinPeerExtensions PeerExtensionBits
181
182         DisableWebtorrent bool
183         DisableWebseeds   bool
184
185         Callbacks Callbacks
186
187         // ICEServerList defines a slice describing servers available to be used by
188         // ICE, such as STUN and TURN servers.
189         ICEServerList []webrtc.ICEServer
190
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.
194         ICEServers []string
195
196         DialRateLimiter *rate.Limiter
197
198         PieceHashersPerTorrent int // default: 2
199 }
200
201 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
202         host, port, err := missinggo.ParseHostPort(addr)
203         if err != nil {
204                 panic(err)
205         }
206         cfg.ListenHost = func(string) string { return host }
207         cfg.ListenPort = port
208         return cfg
209 }
210
211 func NewDefaultClientConfig() *ClientConfig {
212         cc := &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{
233                         Preferred:        true,
234                         RequirePreferred: false,
235                 },
236                 CryptoSelector:         mse.DefaultCryptoSelector,
237                 CryptoProvides:         mse.AllSupportedCrypto,
238                 ListenPort:             42069,
239                 Extensions:             defaultPeerExtensionBytes(),
240                 AcceptPeerConnections:  true,
241                 MaxUnverifiedBytes:     64 << 20,
242                 DialRateLimiter:        rate.NewLimiter(10, 10),
243                 PieceHashersPerTorrent: 2,
244         }
245         cc.DhtStartingNodes = func(network string) dht.StartingNodesGetter {
246                 return func() ([]dht.Addr, error) { return dht.GlobalBootstrapAddrs(network) }
247         }
248         cc.PeriodicallyAnnounceTorrentsToDht = true
249         return cc
250 }
251
252 type HeaderObfuscationPolicy struct {
253         RequirePreferred bool // Whether the value of Preferred is a strict requirement.
254         Preferred        bool // Whether header obfuscation is preferred.
255 }