]> Sergey Matveev's repositories - btrtrc.git/blob - config.go
[trackerscraper] Add custom DNS lookup function
[btrtrc.git] / config.go
1 package torrent
2
3 import (
4         "net"
5         "net/http"
6         "net/url"
7         "time"
8
9         "github.com/anacrolix/dht/v2"
10         "github.com/anacrolix/dht/v2/krpc"
11         "github.com/anacrolix/log"
12         "github.com/anacrolix/missinggo/v2"
13         "github.com/anacrolix/torrent/version"
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 )
20
21 // Probably not safe to modify this after it's given to a Client.
22 type ClientConfig struct {
23         // Store torrent file data in this directory unless .DefaultStorage is
24         // specified.
25         DataDir string `long:"data-dir" description:"directory to store downloaded torrent data"`
26         // The address to listen for new uTP and TCP BitTorrent protocol connections. DHT shares a UDP
27         // socket with uTP unless configured otherwise.
28         ListenHost              func(network string) string
29         ListenPort              int
30         NoDefaultPortForwarding bool
31         UpnpID                  string
32         // Don't announce to trackers. This only leaves DHT to discover peers.
33         DisableTrackers bool `long:"disable-trackers"`
34         DisablePEX      bool `long:"disable-pex"`
35
36         // Don't create a DHT.
37         NoDHT            bool `long:"disable-dht"`
38         DhtStartingNodes func(network string) dht.StartingNodesGetter
39         // Called for each anacrolix/dht Server created for the Client.
40         ConfigureAnacrolixDhtServer       func(*dht.ServerConfig)
41         PeriodicallyAnnounceTorrentsToDht bool
42
43         // Never send chunks to peers.
44         NoUpload bool `long:"no-upload"`
45         // Disable uploading even when it isn't fair.
46         DisableAggressiveUpload bool `long:"disable-aggressive-upload"`
47         // Upload even after there's nothing in it for us. By default uploading is
48         // not altruistic, we'll only upload to encourage the peer to reciprocate.
49         Seed bool `long:"seed"`
50         // Only applies to chunks uploaded to peers, to maintain responsiveness
51         // communicating local Client state to peers. Each limiter token
52         // represents one byte. The Limiter's burst must be large enough to fit a
53         // whole chunk, which is usually 16 KiB (see TorrentSpec.ChunkSize).
54         UploadRateLimiter *rate.Limiter
55         // Rate limits all reads from connections to peers. Each limiter token
56         // represents one byte. The Limiter's burst must be bigger than the
57         // largest Read performed on a the underlying rate-limiting io.Reader
58         // minus one. This is likely to be the larger of the main read loop buffer
59         // (~4096), and the requested chunk size (~16KiB, see
60         // TorrentSpec.ChunkSize).
61         DownloadRateLimiter *rate.Limiter
62         // Maximum unverified bytes across all torrents. Not used if zero.
63         MaxUnverifiedBytes int64
64
65         // User-provided Client peer ID. If not present, one is generated automatically.
66         PeerID string
67         // For the bittorrent protocol.
68         DisableUTP bool
69         // For the bittorrent protocol.
70         DisableTCP bool `long:"disable-tcp"`
71         // Called to instantiate storage for each added torrent. Builtin backends
72         // are in the storage package. If not set, the "file" implementation is
73         // used (and Closed when the Client is Closed).
74         DefaultStorage storage.ClientImpl
75
76         HeaderObfuscationPolicy HeaderObfuscationPolicy
77         // The crypto methods to offer when initiating connections with header obfuscation.
78         CryptoProvides mse.CryptoMethod
79         // Chooses the crypto method to use when receiving connections with header obfuscation.
80         CryptoSelector mse.CryptoSelector
81
82         IPBlocklist      iplist.Ranger
83         DisableIPv6      bool `long:"disable-ipv6"`
84         DisableIPv4      bool
85         DisableIPv4Peers bool
86         // Perform logging and any other behaviour that will help debug.
87         Debug  bool `help:"enable debugging"`
88         Logger log.Logger
89
90         // Defines proxy for HTTP requests, such as for trackers. It's commonly set from the result of
91         // "net/http".ProxyURL(HTTPProxy).
92         HTTPProxy func(*http.Request) (*url.URL, error)
93         // Takes a tracker's hostname and requests DNS A and AAAA records.
94         // Used in case DNS lookups require a special setup (i.e., dns-over-https)
95         TrackerIpFetcher func(*url.URL) ([]net.IP, error)
96         // HTTPUserAgent changes default UserAgent for HTTP requests
97         HTTPUserAgent string
98         // Updated occasionally to when there's been some changes to client
99         // behaviour in case other clients are assuming anything of us. See also
100         // `bep20`.
101         ExtendedHandshakeClientVersion string
102         // Peer ID client identifier prefix. We'll update this occasionally to
103         // reflect changes to client behaviour that other clients may depend on.
104         // Also see `extendedHandshakeClientVersion`.
105         Bep20 string
106
107         // Peer dial timeout to use when there are limited peers.
108         NominalDialTimeout time.Duration
109         // Minimum peer dial timeout to use (even if we have lots of peers).
110         MinDialTimeout             time.Duration
111         EstablishedConnsPerTorrent int
112         HalfOpenConnsPerTorrent    int
113         TotalHalfOpenConns         int
114         // Maximum number of peer addresses in reserve.
115         TorrentPeersHighWater int
116         // Minumum number of peers before effort is made to obtain more peers.
117         TorrentPeersLowWater int
118
119         // Limit how long handshake can take. This is to reduce the lingering
120         // impact of a few bad apples. 4s loses 1% of successful handshakes that
121         // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
122         HandshakesTimeout time.Duration
123         // How long between writes before sending a keep alive message on a peer connection that we want
124         // to maintain.
125         KeepAliveTimeout time.Duration
126
127         // The IP addresses as our peers should see them. May differ from the
128         // local interfaces due to NAT or other network configurations.
129         PublicIp4 net.IP
130         PublicIp6 net.IP
131
132         // Accept rate limiting affects excessive connection attempts from IPs that fail during
133         // handshakes or request torrents that we don't have.
134         DisableAcceptRateLimiting bool
135         // Don't add connections that have the same peer ID as an existing
136         // connection for a given Torrent.
137         DropDuplicatePeerIds bool
138         // Drop peers that are complete if we are also complete and have no use for the peer. This is a
139         // bit of a special case, since a peer could also be useless if they're just not interested, or
140         // we don't intend to obtain all of a torrent's data.
141         DropMutuallyCompletePeers bool
142         // Whether to accept peer connections at all.
143         AcceptPeerConnections bool
144         // Whether a Client should want conns without delegating to any attached Torrents. This is
145         // useful when torrents might be added dynmically in callbacks for example.
146         AlwaysWantConns bool
147
148         // OnQuery hook func
149         DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
150
151         Extensions PeerExtensionBits
152         // Bits that peers must have set to proceed past handshakes.
153         MinPeerExtensions PeerExtensionBits
154
155         DisableWebtorrent bool
156         DisableWebseeds   bool
157
158         Callbacks Callbacks
159 }
160
161 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
162         host, port, err := missinggo.ParseHostPort(addr)
163         if err != nil {
164                 panic(err)
165         }
166         cfg.ListenHost = func(string) string { return host }
167         cfg.ListenPort = port
168         return cfg
169 }
170
171 func NewDefaultClientConfig() *ClientConfig {
172         cc := &ClientConfig{
173                 HTTPUserAgent:                  version.DefaultHttpUserAgent,
174                 ExtendedHandshakeClientVersion: version.DefaultExtendedHandshakeClientVersion,
175                 Bep20:                          version.DefaultBep20Prefix,
176                 UpnpID:                         version.DefaultUpnpId,
177                 NominalDialTimeout:             20 * time.Second,
178                 MinDialTimeout:                 3 * time.Second,
179                 EstablishedConnsPerTorrent:     50,
180                 HalfOpenConnsPerTorrent:        25,
181                 TotalHalfOpenConns:             100,
182                 TorrentPeersHighWater:          500,
183                 TorrentPeersLowWater:           50,
184                 HandshakesTimeout:              4 * time.Second,
185                 KeepAliveTimeout:               time.Minute,
186                 DhtStartingNodes: func(network string) dht.StartingNodesGetter {
187                         return func() ([]dht.Addr, error) { return dht.GlobalBootstrapAddrs(network) }
188                 },
189                 PeriodicallyAnnounceTorrentsToDht: true,
190                 ListenHost:                        func(string) string { return "" },
191                 UploadRateLimiter:                 unlimited,
192                 DownloadRateLimiter:               unlimited,
193                 DisableAcceptRateLimiting:         true,
194                 DropMutuallyCompletePeers:         true,
195                 HeaderObfuscationPolicy: HeaderObfuscationPolicy{
196                         Preferred:        true,
197                         RequirePreferred: false,
198                 },
199                 CryptoSelector:        mse.DefaultCryptoSelector,
200                 CryptoProvides:        mse.AllSupportedCrypto,
201                 ListenPort:            42069,
202                 Extensions:            defaultPeerExtensionBytes(),
203                 AcceptPeerConnections: true,
204         }
205         //cc.ConnTracker.SetNoMaxEntries()
206         //cc.ConnTracker.Timeout = func(conntrack.Entry) time.Duration { return 0 }
207         return cc
208 }
209
210 type HeaderObfuscationPolicy struct {
211         RequirePreferred bool // Whether the value of Preferred is a strict requirement.
212         Preferred        bool // Whether header obfuscation is preferred.
213 }