]> Sergey Matveev's repositories - btrtrc.git/blob - config.go
Group Client DHT and tracker config
[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         "golang.org/x/time/rate"
15
16         "github.com/anacrolix/torrent/iplist"
17         "github.com/anacrolix/torrent/mse"
18         "github.com/anacrolix/torrent/storage"
19         "github.com/anacrolix/torrent/version"
20 )
21
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)
34 }
35
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
43         // OnQuery hook func
44         DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
45 }
46
47 // Probably not safe to modify this after it's given to a Client.
48 type ClientConfig struct {
49         ClientTrackerConfig
50         ClientDhtConfig
51
52         // Store torrent file data in this directory unless .DefaultStorage is
53         // specified.
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
58         ListenPort              int
59         NoDefaultPortForwarding bool
60         UpnpID                  string
61         DisablePEX              bool `long:"disable-pex"`
62
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
84
85         // User-provided Client peer ID. If not present, one is generated automatically.
86         PeerID string
87         // For the bittorrent protocol.
88         DisableUTP bool
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
95
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
101
102         IPBlocklist      iplist.Ranger
103         DisableIPv6      bool `long:"disable-ipv6"`
104         DisableIPv4      bool
105         DisableIPv4Peers bool
106         // Perform logging and any other behaviour that will help debug.
107         Debug  bool `help:"enable debugging"`
108         Logger log.Logger
109
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
116         HTTPUserAgent string
117         // HttpRequestDirector modifies the request before it's sent.
118         // Useful for adding authentication headers, for example
119         HttpRequestDirector func(*http.Request) error
120         // Updated occasionally to when there's been some changes to client
121         // behaviour in case other clients are assuming anything of us. See also
122         // `bep20`.
123         ExtendedHandshakeClientVersion string
124         // Peer ID client identifier prefix. We'll update this occasionally to
125         // reflect changes to client behaviour that other clients may depend on.
126         // Also see `extendedHandshakeClientVersion`.
127         Bep20 string
128
129         // Peer dial timeout to use when there are limited peers.
130         NominalDialTimeout time.Duration
131         // Minimum peer dial timeout to use (even if we have lots of peers).
132         MinDialTimeout             time.Duration
133         EstablishedConnsPerTorrent int
134         HalfOpenConnsPerTorrent    int
135         TotalHalfOpenConns         int
136         // Maximum number of peer addresses in reserve.
137         TorrentPeersHighWater int
138         // Minumum number of peers before effort is made to obtain more peers.
139         TorrentPeersLowWater int
140
141         // Limit how long handshake can take. This is to reduce the lingering
142         // impact of a few bad apples. 4s loses 1% of successful handshakes that
143         // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
144         HandshakesTimeout time.Duration
145         // How long between writes before sending a keep alive message on a peer connection that we want
146         // to maintain.
147         KeepAliveTimeout time.Duration
148
149         // The IP addresses as our peers should see them. May differ from the
150         // local interfaces due to NAT or other network configurations.
151         PublicIp4 net.IP
152         PublicIp6 net.IP
153
154         // Accept rate limiting affects excessive connection attempts from IPs that fail during
155         // handshakes or request torrents that we don't have.
156         DisableAcceptRateLimiting bool
157         // Don't add connections that have the same peer ID as an existing
158         // connection for a given Torrent.
159         DropDuplicatePeerIds bool
160         // Drop peers that are complete if we are also complete and have no use for the peer. This is a
161         // bit of a special case, since a peer could also be useless if they're just not interested, or
162         // we don't intend to obtain all of a torrent's data.
163         DropMutuallyCompletePeers bool
164         // Whether to accept peer connections at all.
165         AcceptPeerConnections bool
166         // Whether a Client should want conns without delegating to any attached Torrents. This is
167         // useful when torrents might be added dynamically in callbacks for example.
168         AlwaysWantConns bool
169
170         Extensions PeerExtensionBits
171         // Bits that peers must have set to proceed past handshakes.
172         MinPeerExtensions PeerExtensionBits
173
174         DisableWebtorrent bool
175         DisableWebseeds   bool
176
177         Callbacks Callbacks
178 }
179
180 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
181         host, port, err := missinggo.ParseHostPort(addr)
182         if err != nil {
183                 panic(err)
184         }
185         cfg.ListenHost = func(string) string { return host }
186         cfg.ListenPort = port
187         return cfg
188 }
189
190 func NewDefaultClientConfig() *ClientConfig {
191         cc := &ClientConfig{
192                 HTTPUserAgent:                  version.DefaultHttpUserAgent,
193                 ExtendedHandshakeClientVersion: version.DefaultExtendedHandshakeClientVersion,
194                 Bep20:                          version.DefaultBep20Prefix,
195                 UpnpID:                         version.DefaultUpnpId,
196                 NominalDialTimeout:             20 * time.Second,
197                 MinDialTimeout:                 3 * time.Second,
198                 EstablishedConnsPerTorrent:     50,
199                 HalfOpenConnsPerTorrent:        25,
200                 TotalHalfOpenConns:             100,
201                 TorrentPeersHighWater:          500,
202                 TorrentPeersLowWater:           50,
203                 HandshakesTimeout:              4 * time.Second,
204                 KeepAliveTimeout:               time.Minute,
205                 ListenHost:                     func(string) string { return "" },
206                 UploadRateLimiter:              unlimited,
207                 DownloadRateLimiter:            unlimited,
208                 DisableAcceptRateLimiting:      true,
209                 DropMutuallyCompletePeers:      true,
210                 HeaderObfuscationPolicy: HeaderObfuscationPolicy{
211                         Preferred:        true,
212                         RequirePreferred: false,
213                 },
214                 CryptoSelector:        mse.DefaultCryptoSelector,
215                 CryptoProvides:        mse.AllSupportedCrypto,
216                 ListenPort:            42069,
217                 Extensions:            defaultPeerExtensionBytes(),
218                 AcceptPeerConnections: true,
219                 MaxUnverifiedBytes:    64 << 20,
220         }
221         cc.DhtStartingNodes = func(network string) dht.StartingNodesGetter {
222                 return func() ([]dht.Addr, error) { return dht.GlobalBootstrapAddrs(network) }
223         }
224         cc.PeriodicallyAnnounceTorrentsToDht = true
225         return cc
226 }
227
228 type HeaderObfuscationPolicy struct {
229         RequirePreferred bool // Whether the value of Preferred is a strict requirement.
230         Preferred        bool // Whether header obfuscation is preferred.
231 }