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