Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
filetransfer.hh
Go to the documentation of this file.
1#pragma once
3
4#include <optional>
5#include <cstdint>
6#include <string>
7#include <future>
8
9#include "nix/util/logging.hh"
10#include "nix/util/types.hh"
11#include "nix/util/ref.hh"
13#include "nix/util/serialise.hh"
14#include "nix/util/url.hh"
15
16#include "nix/store/config.hh"
17#if NIX_WITH_AWS_AUTH
18# include "nix/store/aws-creds.hh"
19#endif
20#include "nix/store/s3-url.hh"
21
22namespace nix {
23
24const std::filesystem::path & nixConfDir();
25
26class FileTransferSettings : public Config
27{
28 static std::optional<std::filesystem::path> getDefaultSSLCertFile();
29
30 void anchor() override;
31
32public:
33 FileTransferSettings();
34
35 Setting<bool> enableHttp2{this, true, "http2", "Whether to enable HTTP/2 support."};
36
37 Setting<bool> enableHttp3{
38 this,
39 false,
40 "http3",
41 R"(
42 Whether to try enabling HTTP/3 (QUIC).
43 When enabled, Nix requests HTTP/3 and transparently falls back
44 to HTTP/2 or HTTP/1.1 for servers that do not support it.
45 This option has no effect unless the `nix` binary is linked
46 against a libcurl built with HTTP/3 (QUIC) support.
47 )"};
48
49 Setting<std::string> userAgentSuffix{
50 this, "", "user-agent-suffix", "String appended to the user agent in HTTP requests."};
51
52 Setting<size_t> httpConnections{
53 this,
54 25,
55 "http-connections",
56 R"(
57 The maximum number of parallel TCP connections used to fetch
58 files from binary caches and by other downloads. It defaults
59 to 25. 0 means no limit.
60 )",
61 {"binary-caches-parallel-connections"}};
62
63 /* Do not set this too low. On glibc, getaddrinfo() contains fallback code
64 paths that deal with ill-behaved DNS servers. Setting this too low
65 prevents some fallbacks from occurring.
66
67 See description of options timeout, single-request, single-request-reopen
68 in resolv.conf(5). Also see https://github.com/NixOS/nix/pull/13985 for
69 details on the interaction between getaddrinfo(3) behavior and libcurl
70 CURLOPT_CONNECTTIMEOUT. */
71 Setting<unsigned long> connectTimeout{
72 this,
73 15,
74 "connect-timeout",
75 R"(
76 The timeout (in seconds) for establishing connections in the
77 binary cache substituter. It corresponds to `curl`’s
78 `--connect-timeout` option. A value of 0 means no limit.
79 )"};
80
81 Setting<unsigned long> stalledDownloadTimeout{
82 this,
83 300,
84 "stalled-download-timeout",
85 R"(
86 The timeout (in seconds) for receiving data from servers
87 during download. Nix cancels idle downloads after this
88 timeout's duration.
89 )"};
90
92 this,
93 5,
94 "filetransfer-retry-attempts",
95 R"(
96 The number of times Nix attempts a file transfer (download
97 or upload) before giving up. Retries apply to transient
98 failures: connection-level errors, HTTP 408, 429, and most
99 5xx responses. Authentication failures (401/403/407),
100 404/410, and other 4xx responses are not retried.
101 )",
102 {"download-attempts"}};
103
104 Setting<uint32_t> retryDelayMs{
105 this,
106 100,
107 "filetransfer-retry-delay",
108 R"(
109 Initial delay in milliseconds before retrying a failed file transfer
110 (download or upload). The delay doubles with each subsequent attempt
111 (exponential backoff) and is subject to random jitter (see
112 `filetransfer-retry-jitter`).
113 )"};
114
115 Setting<uint32_t> retryDelayRateLimitedMs{
116 this,
117 5000,
118 "filetransfer-retry-delay-rate-limited",
119 R"(
120 Initial delay in milliseconds before retrying a file transfer that
121 failed with a rate-limit response (HTTP 429 or 503). The delay doubles
122 with each subsequent attempt.
123
124 Servers may send a `Retry-After` header specifying a longer delay;
125 when present, Nix respects the larger of the two values.
126 )"};
127
128 Setting<uint32_t> retryMaxDelayMs{
129 this,
130 60000,
131 "filetransfer-retry-max-delay",
132 R"(
133 Ceiling on the exponential backoff delay in milliseconds. This does not
134 cap server-provided `Retry-After` values, which are honored as-is.
135 )"};
136
137 Setting<bool> retryJitter{
138 this,
139 true,
140 "filetransfer-retry-jitter",
141 R"(
142 Whether to apply random jitter to retry delays. When enabled, each
143 retry waits for a random duration between 0 and the computed delay
144 ("full jitter"), which spreads out retry storms from many clients.
145
146 Disable for deterministic retry timing (primarily useful for tests).
147 )"};
148
149 Setting<size_t> downloadBufferSize{
150 this,
151 1 * 1024 * 1024,
152 "download-buffer-size",
153 R"(
154 The size of Nix's internal download buffer in bytes during `curl` transfers. If data is
155 not processed quickly enough to exceed the size of this buffer, downloads may stall.
156 The default is 1048576 (1 MiB).
157 )"};
158
159 Setting<unsigned int> downloadSpeed{
160 this,
161 0,
162 "download-speed",
163 R"(
164 Specify the maximum transfer rate in kilobytes per second you want
165 Nix to use for downloads.
166 )"};
167
168 Setting<AbsolutePath> netrcFile{
169 this,
170 nixConfDir() / "netrc",
171 "netrc-file",
172 R"(
173 If set to an absolute path to a `netrc` file, Nix uses the HTTP
174 authentication credentials in this file when trying to download from
175 a remote host through HTTP or HTTPS. Defaults to
176 `$NIX_CONF_DIR/netrc`.
177
178 The `netrc` file consists of a list of accounts in the following
179 format:
180
181 machine my-machine
182 login my-username
183 password my-password
184
185 For the exact syntax, see [the `curl`
186 documentation](https://ec.haxx.se/usingcurl-netrc.html).
187
188 > **Note**
189 >
190 > This must be an absolute path, and `~` is not resolved. For
191 > example, `~/.netrc` won't resolve to your home directory's
192 > `.netrc`.
193 )"};
194
196 this,
197 getDefaultSSLCertFile(),
198 "ssl-cert-file",
199 R"(
200 The path of a file containing CA certificates used to
201 authenticate `https://` downloads. Nix by default uses
202 the first of the following files that exists:
203
204 1. `/etc/ssl/certs/ca-certificates.crt`
205 2. `/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt`
206
207 The path can be overridden by the following environment
208 variables, in order of precedence:
209
210 1. `NIX_SSL_CERT_FILE`
211 2. `SSL_CERT_FILE`
212 )",
213 {},
214 // Don't document the machine-specific default value
215 false};
216};
217
218extern FileTransferSettings fileTransferSettings;
219
223enum struct HttpMethod {
224 Get,
225 Put,
226 Head,
227 Post,
228 Delete,
229};
230
237{
238 std::string username;
239 std::optional<std::string> password;
240};
241
242enum class PauseTransfer : bool {
243 No = false,
244 Yes = true,
245};
246
247struct FileTransferRequest
248{
249 VerbatimURL uri;
250 Headers headers;
251 std::string expectedETag;
252 HttpMethod method = HttpMethod::Get;
253 ActivityId parentAct;
254 bool decompress = true;
255
261 std::optional<uint32_t> retryDelayMs;
262 std::optional<uint32_t> retryDelayRateLimitedMs;
263 std::optional<uint32_t> retryMaxDelayMs;
264 std::optional<uint32_t> retryAttempts;
265
269 std::optional<std::filesystem::path> tlsCert;
270
274 std::optional<std::filesystem::path> tlsKey;
275
276 struct UploadData
277 {
278 UploadData(StringSource & s)
279 : sizeHint(s.s.length())
280 , source(&s)
281 {
282 }
283
284 UploadData(std::size_t sizeHint, RestartableSource & source)
285 : sizeHint(sizeHint)
286 , source(&source)
287 {
288 }
289
290 std::size_t sizeHint = 0;
291 RestartableSource * source = nullptr;
292 };
293
294 std::optional<UploadData> data;
295 std::string mimeType;
296
302 std::function<PauseTransfer(std::string_view data)> dataCallback;
303
308 std::optional<UsernameAuth> usernameAuth;
309#if NIX_WITH_AWS_AUTH
314 std::optional<std::string> preResolvedAwsSessionToken;
315#endif
316
317 FileTransferRequest(VerbatimURL uri)
318 : uri(std::move(uri))
319 , parentAct(getCurActivity())
320 {
321 }
322
329 std::string displayUri() const;
330
334 std::string verb(bool continuous = false) const
335 {
336 switch (method) {
337 case HttpMethod::Head:
338 case HttpMethod::Get:
339 return continuous ? "downloading" : "download";
340 case HttpMethod::Put:
341 case HttpMethod::Post:
342 assert(data);
343 return continuous ? "uploading" : "upload";
344 case HttpMethod::Delete:
345 return continuous ? "deleting" : "delete";
346 }
347 unreachable();
348 }
349
350 std::string noun() const
351 {
352 switch (method) {
353 case HttpMethod::Head:
354 case HttpMethod::Get:
355 return "download";
356 case HttpMethod::Put:
357 case HttpMethod::Post:
358 assert(data);
359 return "upload";
360 case HttpMethod::Delete:
361 return "deletion";
362 }
363 unreachable();
364 }
365
366 void setupForS3();
367
368private:
369 friend struct curlFileTransfer;
370#if NIX_WITH_AWS_AUTH
371 std::optional<std::string> awsSigV4Provider;
372#endif
373};
374
376{
381 bool cached = false;
382
386 std::string etag;
387
394 std::vector<std::string> urls;
395
399 std::string data;
400
401 uint64_t bodySize = 0;
402
408 std::optional<std::string> immutableUrl;
409};
410
411class Store;
412
414{
415protected:
416 class Item
417 {};
418
419public:
423 struct ItemHandle
424 {
425 std::weak_ptr<Item> item;
426 friend struct FileTransfer;
427
428 explicit ItemHandle(std::weak_ptr<Item> item)
429 : item(item)
430 {
431 }
432 };
433
434 virtual ~FileTransfer();
435
441 virtual ItemHandle
443
447 virtual void unpauseTransfer(ItemHandle handle) = 0;
448
449 std::future<FileTransferResult> enqueueFileTransfer(const FileTransferRequest & request);
450
455
460
465
470 void
471 download(FileTransferRequest && request, Sink & sink, std::function<void(FileTransferResult)> resultCallback = {});
472
473 enum Error { NotFound, Unauthorized, Forbidden, Misc, Transient };
474};
475
482ref<FileTransfer> getFileTransfer();
483
489ref<FileTransfer> makeFileTransfer(const FileTransferSettings & settings = fileTransferSettings);
490
491class FileTransferError final : public CloneableError<FileTransferError, Error>
492{
493private:
494 void anchor() override;
495
496public:
497 FileTransfer::Error error;
499 std::optional<std::string> response;
500
501 template<typename... Args>
502 FileTransferError(FileTransfer::Error error, std::optional<std::string> response, Args &&... args);
503};
504
505} // namespace nix
Definition args.hh:29
Definition callback.hh:19
Definition error.hh:310
std::optional< std::string > response
intentionally optional
Definition filetransfer.hh:499
Definition filetransfer.hh:27
Definition filetransfer.hh:417
Definition serialise.hh:183
Definition configuration.hh:476
Definition store-api.hh:397
Definition serialise.hh:315
Definition ref.hh:58
HttpMethod
Definition filetransfer.hh:223
Definition filetransfer.hh:248
std::function< PauseTransfer(std::string_view data)> dataCallback
Definition filetransfer.hh:302
std::string displayUri() const
Definition filetransfer.cc:1335
std::optional< std::filesystem::path > tlsKey
Definition filetransfer.hh:274
std::optional< uint32_t > retryDelayMs
Definition filetransfer.hh:261
std::optional< UsernameAuth > usernameAuth
Definition filetransfer.hh:308
std::string verb(bool continuous=false) const
Definition filetransfer.hh:334
std::optional< std::filesystem::path > tlsCert
Definition filetransfer.hh:269
Definition filetransfer.hh:376
std::string data
Definition filetransfer.hh:399
std::vector< std::string > urls
Definition filetransfer.hh:394
bool cached
Definition filetransfer.hh:381
std::optional< std::string > immutableUrl
Definition filetransfer.hh:408
std::string etag
Definition filetransfer.hh:386
Definition filetransfer.hh:424
Definition filetransfer.hh:414
FileTransferResult download(const FileTransferRequest &request)
Definition filetransfer.cc:1392
FileTransferResult upload(const FileTransferRequest &request)
Definition filetransfer.cc:1397
virtual ItemHandle enqueueFileTransfer(const FileTransferRequest &request, Callback< FileTransferResult > callback)=0
FileTransferResult deleteResource(const FileTransferRequest &request)
Definition filetransfer.cc:1403
virtual void unpauseTransfer(ItemHandle handle)=0
Definition serialise.hh:18
Definition filetransfer.hh:237
Definition url.hh:353