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