]> Sergey Matveev's repositories - btrtrc.git/blob - config.go
Update and expose default client identifiers
[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/expect"
13         "github.com/anacrolix/missinggo/v2"
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
122         // The IP addresses as our peers should see them. May differ from the
123         // local interfaces due to NAT or other network configurations.
124         PublicIp4 net.IP
125         PublicIp6 net.IP
126
127         // Accept rate limiting affects excessive connection attempts from IPs that fail during
128         // handshakes or request torrents that we don't have.
129         DisableAcceptRateLimiting bool
130         // Don't add connections that have the same peer ID as an existing
131         // connection for a given Torrent.
132         DropDuplicatePeerIds bool
133         // Drop peers that are complete if we are also complete and have no use for the peer. This is a
134         // bit of a special case, since a peer could also be useless if they're just not interested, or
135         // we don't intend to obtain all of a torrent's data.
136         DropMutuallyCompletePeers bool
137         // Whether to accept peer connections at all.
138         AcceptPeerConnections bool
139
140         // OnQuery hook func
141         DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
142
143         Extensions PeerExtensionBits
144
145         DisableWebtorrent bool
146         DisableWebseeds   bool
147
148         Callbacks Callbacks
149 }
150
151 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
152         host, port, err := missinggo.ParseHostPort(addr)
153         expect.Nil(err)
154         cfg.ListenHost = func(string) string { return host }
155         cfg.ListenPort = port
156         return cfg
157 }
158
159 func NewDefaultClientConfig() *ClientConfig {
160         cc := &ClientConfig{
161                 HTTPUserAgent:                  version.DefaultHttpUserAgent,
162                 ExtendedHandshakeClientVersion: version.DefaultExtendedHandshakeClientVersion,
163                 Bep20:                          version.DefaultBep20Prefix,
164                 UpnpID:                         version.DefaultUpnpId,
165                 NominalDialTimeout:             20 * time.Second,
166                 MinDialTimeout:                 3 * time.Second,
167                 EstablishedConnsPerTorrent:     50,
168                 HalfOpenConnsPerTorrent:        25,
169                 TotalHalfOpenConns:             100,
170                 TorrentPeersHighWater:          500,
171                 TorrentPeersLowWater:           50,
172                 HandshakesTimeout:              4 * time.Second,
173                 DhtStartingNodes: func(network string) dht.StartingNodesGetter {
174                         return func() ([]dht.Addr, error) { return dht.GlobalBootstrapAddrs(network) }
175                 },
176                 PeriodicallyAnnounceTorrentsToDht: true,
177                 ListenHost:                        func(string) string { return "" },
178                 UploadRateLimiter:                 unlimited,
179                 DownloadRateLimiter:               unlimited,
180                 DisableAcceptRateLimiting:         true,
181                 DropMutuallyCompletePeers:         true,
182                 HeaderObfuscationPolicy: HeaderObfuscationPolicy{
183                         Preferred:        true,
184                         RequirePreferred: false,
185                 },
186                 CryptoSelector:        mse.DefaultCryptoSelector,
187                 CryptoProvides:        mse.AllSupportedCrypto,
188                 ListenPort:            42069,
189                 Extensions:            defaultPeerExtensionBytes(),
190                 AcceptPeerConnections: true,
191         }
192         //cc.ConnTracker.SetNoMaxEntries()
193         //cc.ConnTracker.Timeout = func(conntrack.Entry) time.Duration { return 0 }
194         return cc
195 }
196
197 type HeaderObfuscationPolicy struct {
198         RequirePreferred bool // Whether the value of Preferred is a strict requirement.
199         Preferred        bool // Whether header obfuscation is preferred.
200 }