Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
local-settings.hh
Go to the documentation of this file.
1#pragma once
3
4#include "nix/util/types.hh"
7#include "nix/util/users.hh"
9
10#include "nix/store/config.hh"
11
12#include <limits>
13#include <optional>
14#include <string>
15#include <vector>
16
17namespace nix {
18
19typedef enum { smEnabled, smRelaxed, smDisabled } SandboxMode;
20
21template<>
22SandboxMode BaseSetting<SandboxMode>::parse(const std::string & str) const;
23template<>
24std::string BaseSetting<SandboxMode>::to_string() const;
25
26template<>
27PathsInChroot BaseSetting<PathsInChroot>::parse(const std::string & str) const;
28template<>
29std::string BaseSetting<PathsInChroot>::to_string() const;
30
31template<>
32struct BaseSetting<PathsInChroot>::trait
33{
34 static constexpr bool appendable = true;
35};
36
37template<>
38void BaseSetting<PathsInChroot>::appendOrSet(PathsInChroot newValue, bool append);
39
40struct GCSettings : public virtual Config
41{
42private:
43 void anchor() override;
44
45public:
46 Setting<off_t> reservedSize{
47 this,
48 8 * 1024 * 1024,
49 "gc-reserved-space",
50 "Amount of reserved disk space for the garbage collector.",
51 };
52
53 Setting<bool> keepOutputs{
54 this,
55 false,
56 "keep-outputs",
57 R"(
58 If `true`, the garbage collector keeps the outputs of
59 non-garbage derivations. If `false` (default), outputs are
60 deleted unless they are GC roots themselves (or reachable from other
61 roots).
62
63 In general, outputs must be registered as roots separately. However,
64 even if the output of a derivation is registered as a root, the
65 collector still deletes store paths that are used only at build
66 time (e.g., the C compiler, or source tarballs downloaded from the
67 network). To prevent it from doing so, set this option to `true`.
68
69 This option only applies to garbage collection of the whole store
70 and does not affect deleting explicit paths.
71 )",
72 {"gc-keep-outputs"},
73 };
74
75 Setting<bool> keepDerivations{
76 this,
77 true,
78 "keep-derivations",
79 R"(
80 If `true` (default), the garbage collector keeps the derivations
81 from which non-garbage store paths were built. If `false`, they are
82 deleted unless explicitly registered as a root (or reachable from
83 other roots).
84
85 Keeping derivation around is useful for querying and traceability
86 (e.g., it allows you to ask with what dependencies or options a
87 store path was built), so by default this option is on. Turn it off
88 to save a bit of disk space (or a lot if `keep-outputs` is also
89 turned on).
90
91 This option only applies to garbage collection of the whole store
92 and does not affect deleting explicit paths.
93 )",
94 {"gc-keep-derivations"},
95 };
96
97 Setting<uint64_t> minFree{
98 this,
99 0,
100 "min-free",
101 R"(
102 When free disk space in `/nix/store` drops below `min-free` during a
103 build, Nix performs a garbage-collection until `max-free` bytes are
104 available or there is no more garbage. A value of `0` (the default)
105 disables this feature.
106 )",
107 };
108
109 // n.b. this is deliberately int64 max rather than uint64 max because
110 // this goes through the Nix language JSON parser and thus needs to be
111 // representable in Nix language integers.
112 Setting<uint64_t> maxFree{
113 this,
114 std::numeric_limits<int64_t>::max(),
115 "max-free",
116 R"(
117 When a garbage collection is triggered by the `min-free` option, it
118 stops as soon as `max-free` bytes are available. The default is
119 infinity (i.e. delete all garbage).
120 )",
121 };
122
123 Setting<uint64_t> minFreeCheckInterval{
124 this,
125 5,
126 "min-free-check-interval",
127 "Number of seconds between checking free disk space.",
128 };
129};
130
131const uint32_t maxIdsPerBuild =
132#ifdef __linux__
133 1 << 16
134#else
135 1
136#endif
137 ;
138
139struct AutoAllocateUidSettings : public virtual Config
140{
141private:
142 void anchor() override;
143
144public:
145 Setting<uint32_t> startId{
146 this,
147#ifdef __linux__
148 0x34000000,
149#else
150 56930,
151#endif
152 "start-id",
153 "The first UID and GID to use for dynamic ID allocation."};
154
155 Setting<uint32_t> uidCount{
156 this,
157#ifdef __linux__
158 maxIdsPerBuild * 128,
159#else
160 128,
161#endif
162 "id-count",
163 "The number of UIDs/GIDs to use for dynamic ID allocation."};
164};
165
178struct LocalSettings : public virtual Config, public GCSettings, public AutoAllocateUidSettings
179{
180private:
181 void anchor() override;
182
183public:
188 {
189 return *this;
190 }
191
192 const GCSettings & getGCSettings() const
193 {
194 return *this;
195 }
196
202 {
203 return autoAllocateUids ? this : nullptr;
204 }
205
206 Setting<unsigned int> buildCores{
207 this,
208 0,
209 "cores",
210 R"(
211 Sets the value of the `NIX_BUILD_CORES` environment variable in the [invocation of the `builder` executable](@docroot@/store/building.md#env-vars) of a derivation.
212 The `builder` executable can use this variable to control its own maximum amount of parallelism.
213
214 <!--
215 FIXME(@fricklerhandwerk): I don't think this should even be mentioned here.
216 A very generic example using `derivation` and `xargs` may be more appropriate to explain the mechanism.
217 Using `mkDerivation` as an example requires being aware of that there are multiple independent layers that are completely opaque here.
218 -->
219 For instance, in Nixpkgs, if the attribute `enableParallelBuilding` for the `mkDerivation` build helper is set to `true`, it passes the `-j${NIX_BUILD_CORES}` flag to GNU Make.
220
221 If set to `0`, nix will detect the number of CPU cores and pass this number via `NIX_BUILD_CORES`.
222
223 > **Note**
224 >
225 > The number of parallel local Nix build jobs is independently controlled with the [`max-jobs`](#conf-max-jobs) setting.
226 )",
227 {"build-cores"}};
228
229 Setting<bool> fsyncMetadata{
230 this,
231 true,
232 "fsync-metadata",
233 R"(
234 If set to `true`, changes to the Nix store metadata (in
235 `/nix/var/nix/db`) are synchronously flushed to disk. This improves
236 robustness in case of system crashes, but reduces performance. The
237 default is `true`.
238 )"};
239
240 Setting<bool> fsyncStorePaths{
241 this,
242 false,
243 "fsync-store-paths",
244 R"(
245 Whether to call `fsync()` on store paths before registering them, to
246 flush them to disk. This improves robustness in case of system crashes,
247 but reduces performance. The default is `false`.
248 )"};
249
250#ifndef _WIN32
251 // FIXME: remove this option, `fsync-store-paths` is faster.
252 Setting<bool> syncBeforeRegistering{
253 this, false, "sync-before-registering", "Whether to call `sync()` before registering a path as valid."};
254#endif
255
256 Setting<bool> autoOptimiseStore{
257 this,
258 false,
259 "auto-optimise-store",
260 R"(
261 If set to `true`, Nix automatically detects files in the store
262 that have identical contents, and replaces them with hard links to
263 a single copy. This saves disk space. If set to `false` (the
264 default), you can still run `nix-store --optimise` to get rid of
265 duplicate files.
266 )"};
267
268 Setting<size_t> narBufferSize{
269 this, 32 * 1024 * 1024, "nar-buffer-size", "Maximum size of NARs before spilling them to disk."};
270
271 Setting<bool> allowSymlinkedStore{
272 this,
273 false,
274 "allow-symlinked-store",
275 R"(
276 If set to `true`, Nix stops complaining if the store directory
277 (typically `/nix/store`) contains symlink components.
278
279 This risks making some builds "impure" because builders sometimes
280 "canonicalise" paths by resolving all symlink components. Problems
281 occur if those builds are then deployed to machines where /nix/store
282 resolves to a different location from that of the build machine. You
283 can enable this setting if you are sure you're not going to do that.
284 )"};
285
286 Setting<std::string> buildUsersGroup{
287 this,
288 "",
289 "build-users-group",
290 R"(
291 This options specifies the Unix group containing the Nix build user
292 accounts. In multi-user Nix installations, builds should not be
293 performed by the Nix account since that would allow users to
294 arbitrarily modify the Nix store and database by supplying specially
295 crafted builders; and they cannot be performed by the calling user
296 since that would allow him/her to influence the build result.
297
298 Therefore, if this option is non-empty and specifies a valid group,
299 builds are performed under the user accounts that are a member
300 of the group specified here (as listed in `/etc/group`). Those user
301 accounts should not be used for any other purpose\!
302
303 Nix never runs two builds under the same user account at the
304 same time. This is to prevent an obvious security hole: a malicious
305 user writing a Nix expression that modifies the build result of a
306 legitimate Nix expression being built by another user. Therefore it
307 is good to have as many Nix build user accounts as you can spare.
308 (Remember: uids are cheap.)
309
310 The build users should have permission to create files in the Nix
311 store, but not delete them. Therefore, `/nix/store` should be owned
312 by the Nix account, its group should be the group specified here,
313 and its mode should be `1775`.
314
315 If the build users group is empty, builds are performed under
316 the uid of the Nix process (that is, the uid of the caller if
317 `NIX_REMOTE` is empty, the uid under which the Nix daemon runs if
318 `NIX_REMOTE` is `daemon`). Obviously, this should not be used
319 with a nix daemon accessible to untrusted clients.
320
321 Defaults to `nixbld` when running as root, *empty* otherwise.
322 )",
323 {},
324 false};
325
326 Setting<bool> autoAllocateUids{
327 this,
328 false,
329 "auto-allocate-uids",
330 R"(
331 Whether to select UIDs for builds automatically, instead of using the
332 users in `build-users-group`.
333
334 UIDs are allocated starting at 872415232 (0x34000000) on Linux and 56930 on macOS.
335 )",
336 {},
337 true,
338 Xp::AutoAllocateUids};
339
340#ifdef __linux__
341 Setting<bool> useCgroups{
342 this,
343 false,
344 "use-cgroups",
345 R"(
346 Whether to execute builds inside cgroups.
347 This is only supported on Linux.
348
349 Cgroups are required and enabled automatically for derivations
350 that require the `uid-range` system feature.
351 )"};
352#endif
353
354 Setting<SandboxMode> sandboxMode{
355 this,
356#if defined(__linux__) || defined(__FreeBSD__)
357 smEnabled
358#else
359 smDisabled
360#endif
361 ,
362 "sandbox",
363 R"(
364 If set to `true`, builds are performed in a *sandboxed
365 environment*, i.e., they're isolated from the normal file system
366 hierarchy and only see their dependencies in the Nix store,
367 the temporary build directory, private versions of `/proc`,
368 `/dev`, `/dev/shm` and `/dev/pts` (on Linux), and the paths
369 configured with the `sandbox-paths` option. This is useful to
370 prevent undeclared dependencies on files in directories such as
371 `/usr/bin`. In addition, on Linux, builds run in private PID,
372 mount, network, IPC and UTS namespaces to isolate them from other
373 processes in the system (except that fixed-output derivations do
374 not run in private network namespace to ensure they can access the
375 network).
376
377 Currently, sandboxing only work on Linux and macOS. The use of a
378 sandbox requires that Nix is run as root (so you should use the
379 "build users" feature to perform the actual builds under different
380 users than root).
381
382 If this option is set to `relaxed`, then fixed-output derivations
383 and derivations that have the `__noChroot` attribute set to `true`
384 do not run in sandboxes.
385
386 The default is `true` on Linux and `false` on all other platforms.
387 )",
388 {"build-use-chroot", "build-use-sandbox"}};
389
390 Setting<PathsInChroot> sandboxPaths{
391 this,
392 {},
393 "sandbox-paths",
394 R"(
395 A list of paths bind-mounted into Nix sandbox environments. You can
396 use the syntax `target=source` to mount a path in a different
397 location in the sandbox; for instance, `/bin=/nix-bin` mounts
398 the path `/nix-bin` as `/bin` inside the sandbox. If *source* is
399 followed by `?`, then it is not an error if *source* does not exist;
400 for example, `/dev/nvidiactl?` specifies that `/dev/nvidiactl`
401 only be mounted in the sandbox if it exists in the host filesystem.
402
403 If the source is in the Nix store, then its closure is added to
404 the sandbox as well.
405
406 Depending on how Nix was built, the default value for this option
407 may be empty or provide `/bin/sh` as a bind-mount of `bash`.
408 )",
409 {"build-chroot-dirs", "build-sandbox-paths"}};
410
411 Setting<bool> sandboxFallback{
412 this, true, "sandbox-fallback", "Whether to disable sandboxing when the kernel doesn't allow it."};
413
414#ifndef _WIN32
415 Setting<bool> requireDropSupplementaryGroups{
416 this,
417 isRootUser(),
418 "require-drop-supplementary-groups",
419 R"(
420 Following the principle of least privilege,
421 Nix attempts to drop supplementary groups when building with sandboxing.
422
423 However this can fail under some circumstances.
424 For example, if the user lacks the `CAP_SETGID` capability.
425 Search `setgroups(2)` for `EPERM` to find more detailed information on this.
426
427 If you encounter such a failure, setting this option to `false` enables you to ignore it and continue.
428 But before doing so, you should consider the security implications carefully.
429 Not dropping supplementary groups means the build sandbox is less restricted than intended.
430
431 This option defaults to `true` when the user is root
432 (since `root` usually has permissions to call setgroups)
433 and `false` otherwise.
434 )"};
435#endif
436
437#ifdef __linux__
438 Setting<std::string> sandboxShmSize{
439 this,
440 "50%",
441 "sandbox-dev-shm-size",
442 R"(
443 *Linux only*
444
445 This option determines the maximum size of the `tmpfs` filesystem
446 mounted on `/dev/shm` in Linux sandboxes. For the format, see the
447 description of the `size` option of `tmpfs` in mount(8). The default
448 is `50%`.
449 )"};
450#endif
451
452#if defined(__linux__) || defined(__FreeBSD__)
453 Setting<AbsolutePath> sandboxBuildDir{
454 this,
455 "/build",
456 "sandbox-build-dir",
457 R"(
458 *Linux only*
459
460 The build directory inside the sandbox.
461
462 This directory is backed by [`build-dir`](#conf-build-dir) on the host.
463 )"};
464#endif
465
466 Setting<std::optional<AbsolutePath>> buildDir{
467 this,
468 std::nullopt,
469 "build-dir",
470 R"(
471 Override the `build-dir` store setting for all stores that have this setting.
472
473 See also the per-store [`build-dir`](@docroot@/store/types/local-store.md#store-local-store-build-dir) setting.
474 )"};
475
476 Setting<std::set<std::filesystem::path>> allowedImpureHostPrefixes{
477 this,
478 {},
479 "allowed-impure-host-deps",
480 "Which prefixes to allow derivations to ask for access to (primarily for Darwin)."};
481
482#ifdef __APPLE__
483 Setting<bool> darwinLogSandboxViolations{
484 this,
485 false,
486 "darwin-log-sandbox-violations",
487 "Whether to log Darwin sandbox access violations to the system log."};
488#endif
489
490 Setting<bool> runDiffHook{
491 this,
492 false,
493 "run-diff-hook",
494 R"(
495 If true, enable the execution of the `diff-hook` program.
496
497 When using the Nix daemon, `run-diff-hook` must be set in the
498 `nix.conf` configuration file, and cannot be passed at the command
499 line.
500 )"};
501
502private:
503
504 Setting<std::optional<AbsolutePath>> diffHook{
505 this,
506 std::nullopt,
507 "diff-hook",
508 R"(
509 Absolute path to an executable capable of diffing build
510 results. The hook is executed if `run-diff-hook` is true, and the
511 output of a build is known to not be the same. This program is not
512 executed to determine if two results are the same.
513
514 The diff hook is executed by the same user and group who ran the
515 build. However, the diff hook does not have write access to the
516 store path just built.
517
518 The diff hook program receives three parameters:
519
520 1. A path to the previous build's results
521
522 2. A path to the current build's results
523
524 3. The path to the build's derivation
525
526 4. The path to the build's scratch directory. This directory
527 exists only if the build was run with `--keep-failed`.
528
529 The stderr and stdout output from the diff hook isn't displayed
530 to the user. Instead, it prints to the nix-daemon's log.
531
532 When using the Nix daemon, `diff-hook` must be set in the `nix.conf`
533 configuration file, and cannot be passed at the command line.
534 )"};
535
536public:
537
542 const AbsolutePath * getDiffHook() const
543 {
544 if (!runDiffHook.get()) {
545 return nullptr;
546 }
547 return get(diffHook.get());
548 }
549
550 Setting<std::string> preBuildHook{
551 this,
552 "",
553 "pre-build-hook",
554 R"(
555 If set, the path to a program that can set extra derivation-specific
556 settings for this system. This is used for settings that can't be
557 captured by the derivation model itself and are too variable between
558 different versions of the same system to be hard-coded into nix.
559
560 The hook is passed the derivation path and, if sandboxes are
561 enabled, the sandbox directory. It can then modify the sandbox and
562 send a series of commands to modify various settings to stdout. The
563 currently recognized commands are:
564
565 - `extra-sandbox-paths`\
566 Pass a list of files and directories to be included in the
567 sandbox for this build. One entry per line, terminated by an
568 empty line. Entries have the same format as `sandbox-paths`.
569 )"};
570
571#ifdef __linux__
572 Setting<bool> filterSyscalls{
573 this,
574 true,
575 "filter-syscalls",
576 R"(
577 Whether to prevent certain dangerous system calls, such as
578 creation of setuid/setgid files or adding ACLs or extended
579 attributes. Only disable this if you're aware of the
580 security implications.
581 )"};
582
583 Setting<bool> allowNewPrivileges{
584 this,
585 false,
586 "allow-new-privileges",
587 R"(
588 (Linux-specific.) By default, builders on Linux cannot acquire new
589 privileges by calling setuid/setgid programs or programs that have
590 file capabilities. For example, programs such as `sudo` or `ping`
591 should fail. (Note that in sandbox builds, no such programs are
592 available unless you bind-mount them into the sandbox via the
593 `sandbox-paths` option.) You can allow the use of such programs by
594 enabling this option. This is impure and usually undesirable, but
595 may be useful in certain scenarios (e.g. to spin up containers or
596 set up userspace network interfaces in tests).
597 )"};
598#endif
599
600#if NIX_SUPPORT_ACL
601 Setting<StringSet> ignoredAcls{
602 this,
603 {"security.selinux", "system.nfs4_acl", "security.csm"},
604 "ignored-acls",
605 R"(
606 A list of ACLs that should be ignored, normally Nix attempts to
607 remove all ACLs from files and directories in the Nix store, but
608 some ACLs like `security.selinux` or `system.nfs4_acl` can't be
609 removed even by root. Therefore it's best to just ignore them.
610 )"};
611#endif
612
613 Setting<StringMap> impureEnv{
614 this,
615 {},
616 "impure-env",
617 R"(
618 A list of items, each in the format of:
619
620 - `name=value`: Set environment variable `name` to `value`.
621
622 If the user is trusted (see `trusted-users` option), when building
623 a fixed-output derivation, environment variables set in this option
624 is passed to the builder if they are listed in [`impureEnvVars`](@docroot@/language/advanced-attributes.md#adv-attr-impureEnvVars).
625
626 This option is useful for, e.g., setting `https_proxy` for
627 fixed-output derivations and in a multi-user Nix installation, or
628 setting private access tokens when fetching a private repository.
629 )",
630 {}, // aliases
631 true, // document default
632 Xp::ConfigurableImpureEnv};
633
634 Setting<Strings> hashedMirrors{
635 this,
636 {},
637 "hashed-mirrors",
638 R"(
639 A list of web servers used by `builtins.fetchurl` to obtain files by
640 hash. Given a hash algorithm *ha* and a base-16 hash *h*, Nix tries to
641 download the file from *hashed-mirror*/*ha*/*h*. This allows files to
642 be downloaded even if they have disappeared from their original URI.
643 For example, given an example mirror `http://tarballs.nixos.org/`,
644 when building the derivation
645
646 ```nix
647 builtins.fetchurl {
648 url = "https://example.org/foo-1.2.3.tar.xz";
649 sha256 = "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae";
650 }
651 ```
652
653 Nix will attempt to download this file from
654 `http://tarballs.nixos.org/sha256/2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae`
655 first. If it is not available there, it tries the original URI.
656 )"};
657
658 using ExternalBuilders = std::vector<ExternalBuilder>;
659
660 Setting<ExternalBuilders> externalBuilders{
661 this,
662 {},
663 "external-builders",
664 R"(
665 Helper programs for building derivations, specified in JSON format, e.g.
666
667 ```json
668 [ {"systems": ["aarch64-linux"], "program": "/path/to/helper", "args": ["bla"]} ]
669 ```
670
671 Whenever Nix needs to build a derivation for a system contained in *systems*, it will invoke *program* with the command line arguments *args*, and an additional argument containing the path of a JSON document that describes the build environment.
672 The JSON document looks like this:
673
674 ```json
675 {
676 "args": [
677 "-e",
678 "/nix/store/vj1c3wf9…-source-stdenv.sh",
679 "/nix/store/shkw4qm9…-default-builder.sh"
680 ],
681 "builder": "/nix/store/s1qkj0ph…-bash-5.2p37/bin/bash",
682 "env": {
683 "HOME": "/homeless-shelter",
684 "builder": "/nix/store/s1qkj0ph…-bash-5.2p37/bin/bash",
685 "nativeBuildInputs": "/nix/store/l31j72f1…-version-check-hook",
686 "out": "/nix/store/2yx2prgx…-hello-2.12.2"
687 …
688 },
689 "inputPaths": [
690 "/nix/store/14dciax3…-glibc-2.32-54-dev",
691 "/nix/store/1azs5s8z…-gettext-0.21",
692 …
693 ],
694 "outputs": {
695 "out": "/nix/store/2yx2prgx…-hello-2.12.2"
696 },
697 "realStoreDir": "/nix/store",
698 "storeDir": "/nix/store",
699 "system": "aarch64-linux",
700 "tmpDir": "/private/tmp/nix-build-hello-2.12.2.drv-0/build",
701 "tmpDirInSandbox": "/build",
702 "topTmpDir": "/private/tmp/nix-build-hello-2.12.2.drv-0",
703 "version": 1
704 }
705 ```
706 )",
707 {}, // aliases
708 true, // document default
709 // NOTE(cole-h): even though we can make the experimental feature required here, the errors
710 // are not as good (it just becomes a warning if you try to use this setting without the
711 // experimental feature)
712 //
713 // With this commented out:
714 //
715 // error: experimental Nix feature 'external-builders' is disabled; add '--extra-experimental-features
716 // external-builders' to enable it
717 //
718 // With this uncommented:
719 //
720 // warning: Ignoring setting 'external-builders' because experimental feature 'external-builders' is not enabled
721 // error: Cannot build '/nix/store/vwsp4qd8…-opentofu-1.10.2.drv'.
722 // Reason: required system or feature not available
723 // Required system: 'aarch64-linux' with features {}
724 // Current system: 'aarch64-darwin' with features {apple-virt, benchmark, big-parallel, nixos-test}
725 // Xp::ExternalBuilders
726 };
727
732 const ExternalBuilder * findExternalDerivationBuilderIfSupported(const BasicDerivation & drv);
733};
734
735template<>
736LocalSettings::ExternalBuilders BaseSetting<LocalSettings::ExternalBuilders>::parse(const std::string & str) const;
737
738template<>
739std::string BaseSetting<LocalSettings::ExternalBuilders>::to_string() const;
740
741} // namespace nix
Definition configuration.hh:339
virtual T parse(const std::string &str) const
Definition config-impl.hh:139
virtual void appendOrSet(T newValue, bool append)
Definition config-impl.hh:70
Definition configuration.hh:476
Definition configuration.hh:242
Definition local-settings.hh:140
Definition local-settings.hh:41
Definition local-settings.hh:179
const AbsolutePath * getDiffHook() const
Definition local-settings.hh:542
const ExternalBuilder * findExternalDerivationBuilderIfSupported(const BasicDerivation &drv)
Definition globals.cc:283
GCSettings & getGCSettings()
Definition local-settings.hh:187
const AutoAllocateUidSettings * getAutoAllocateUidSettings() const
Definition local-settings.hh:201
bool isRootUser()
Definition users.cc:65
const T * get(const std::optional< T > &opt)
Definition util.hh:286