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