]> Sergey Matveev's repositories - btrtrc.git/blob - config.go
Add ClientConfig.AlwaysWantConns
[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/missinggo/v2/expect"
14         "github.com/anacrolix/torrent/version"
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 )
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         // HTTPUserAgent changes default UserAgent for HTTP requests
95         HTTPUserAgent string
96         // Updated occasionally to when there's been some changes to client
97         // behaviour in case other clients are assuming anything of us. See also
98         // `bep20`.
99         ExtendedHandshakeClientVersion string
100         // Peer ID client identifier prefix. We'll update this occasionally to
101         // reflect changes to client behaviour that other clients may depend on.
102         // Also see `extendedHandshakeClientVersion`.
103         Bep20 string
104
105         // Peer dial timeout to use when there are limited peers.
106         NominalDialTimeout time.Duration
107         // Minimum peer dial timeout to use (even if we have lots of peers).
108         MinDialTimeout             time.Duration
109         EstablishedConnsPerTorrent int
110         HalfOpenConnsPerTorrent    int
111         TotalHalfOpenConns         int
112         // Maximum number of peer addresses in reserve.
113         TorrentPeersHighWater int
114         // Minumum number of peers before effort is made to obtain more peers.
115         TorrentPeersLowWater int
116
117         // Limit how long handshake can take. This is to reduce the lingering
118         // impact of a few bad apples. 4s loses 1% of successful handshakes that
119         // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
120         HandshakesTimeout time.Duration
121         // How long between writes before sending a keep alive message on a peer connection that we want
122         // to maintain.
123         KeepAliveTimeout time.Duration
124
125         // The IP addresses as our peers should see them. May differ from the
126         // local interfaces due to NAT or other network configurations.
127         PublicIp4 net.IP
128         PublicIp6 net.IP
129
130         // Accept rate limiting affects excessive connection attempts from IPs that fail during
131         // handshakes or request torrents that we don't have.
132         DisableAcceptRateLimiting bool
133         // Don't add connections that have the same peer ID as an existing
134         // connection for a given Torrent.
135         DropDuplicatePeerIds bool
136         // Drop peers that are complete if we are also complete and have no use for the peer. This is a
137         // bit of a special case, since a peer could also be useless if they're just not interested, or
138         // we don't intend to obtain all of a torrent's data.
139         DropMutuallyCompletePeers bool
140         // Whether to accept peer connections at all.
141         AcceptPeerConnections bool
142         // Whether a Client should want conns without delegating to any attached Torrents. This is
143         // useful when torrents might be added dynmically in callbacks for example.
144         AlwaysWantConns bool
145
146         // OnQuery hook func
147         DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
148
149         Extensions PeerExtensionBits
150
151         DisableWebtorrent bool
152         DisableWebseeds   bool
153
154         Callbacks Callbacks
155 }
156
157 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
158         host, port, err := missinggo.ParseHostPort(addr)
159         expect.Nil(err)
160         cfg.ListenHost = func(string) string { return host }
161         cfg.ListenPort = port
162         return cfg
163 }
164
165 func NewDefaultClientConfig() *ClientConfig {
166         cc := &ClientConfig{
167                 HTTPUserAgent:                  version.DefaultHttpUserAgent,
168                 ExtendedHandshakeClientVersion: version.DefaultExtendedHandshakeClientVersion,
169                 Bep20:                          version.DefaultBep20Prefix,
170                 UpnpID:                         version.DefaultUpnpId,
171                 NominalDialTimeout:             20 * time.Second,
172                 MinDialTimeout:                 3 * time.Second,
173                 EstablishedConnsPerTorrent:     50,
174                 HalfOpenConnsPerTorrent:        25,
175                 TotalHalfOpenConns:             100,
176                 TorrentPeersHighWater:          500,
177                 TorrentPeersLowWater:           50,
178                 HandshakesTimeout:              4 * time.Second,
179                 KeepAliveTimeout:               time.Minute,
180                 DhtStartingNodes: func(network string) dht.StartingNodesGetter {
181                         return func() ([]dht.Addr, error) { return dht.GlobalBootstrapAddrs(network) }
182                 },
183                 PeriodicallyAnnounceTorrentsToDht: true,
184                 ListenHost:                        func(string) string { return "" },
185                 UploadRateLimiter:                 unlimited,
186                 DownloadRateLimiter:               unlimited,
187                 DisableAcceptRateLimiting:         true,
188                 DropMutuallyCompletePeers:         true,
189                 HeaderObfuscationPolicy: HeaderObfuscationPolicy{
190                         Preferred:        true,
191                         RequirePreferred: false,
192                 },
193                 CryptoSelector:        mse.DefaultCryptoSelector,
194                 CryptoProvides:        mse.AllSupportedCrypto,
195                 ListenPort:            42069,
196                 Extensions:            defaultPeerExtensionBytes(),
197                 AcceptPeerConnections: true,
198         }
199         //cc.ConnTracker.SetNoMaxEntries()
200         //cc.ConnTracker.Timeout = func(conntrack.Entry) time.Duration { return 0 }
201         return cc
202 }
203
204 type HeaderObfuscationPolicy struct {
205         RequirePreferred bool // Whether the value of Preferred is a strict requirement.
206         Preferred        bool // Whether header obfuscation is preferred.
207 }