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