packages feed

nova-nix-0.11.0.0 / src / Nix / Config.hs

{-# LANGUAGE TupleSections #-}-- | Nix configuration: the @nix.conf@ / @NIX_CONFIG@ settings that decide-- which binary caches a machine substitutes from, which public keys it-- trusts, whether a failed substitute builds from source (@fallback@),-- whether a derivation may forbid substitutes-- (@always-allow-substitutes@), how many cores a builder is told it may-- use (@cores@), how deep function calls may nest, how far an evaluation-- may reach (@restrict-eval@, @pure-eval@, @allowed-uris@), whether-- @builtins.traceVerbose@ traces (@trace-verbose@), whether a path-- reader may build what its argument's context names-- (@allow-import-from-derivation@, @trace-import-from-derivation@), how-- builds are sandboxed (@sandbox@ and the settings beside it, macOS's-- @allowed-impure-host-deps@ and @darwin-log-sandbox-violations@ among-- them), whom builds run as when nova-nix runs as root-- (@build-users-group@), what a build that fails leaves (@keep-failed@),-- where the link to the default profile is-- (@use-xdg-base-directories@), the prompt of a @develop@ shell-- (@bash-prompt@ and its prefix and suffix), which experimental features-- are on (@experimental-features@), who may connect to the daemon and-- what it lets them do (@trusted-users@, @allowed-users@,-- @build-users-group@, @trusted-substituters@), and how many times a-- download or upload is tried (@filetransfer-retry-attempts@, also-- named @download-attempts@), and which store a command uses (@store@).---- == The format---- One @name = value@ assignment per line.  A @#@ truncates the rest of the-- line (a comment).  A list value is whitespace separated.  An @include@-- or @!include@ line splices another file in at that position: the path-- is resolved against the directory of the file being parsed, and the two-- forms differ only in that @!include@ goes on without a file that cannot-- be read.  These are the rules upstream's @parseConfigFiles@ applies-- (@config.cc@ at 2.24.9: comment truncation, no line continuation,-- whitespace tokenizing, inline include expansion), matched here.  A-- Boolean value is one of @true@, @yes@, @1@, @false@, @no@, @0@-- (upstream's @BaseSetting\<bool\>::parse@), and any other spelling is-- an error.  An integer value is upstream's too ('parseUnsignedSetting'):-- decimal digits, an optional leading @+@, and an optional binary unit-- suffix (@K@, @M@, @G@, @T@).---- == Bytes---- A source is bytes until a setting takes a value from it, as upstream's-- @std::string@ is.  A line splits into tokens on upstream's separators-- alone (space, tab, CR, LF), not on every Unicode space; a comment, and-- the value of a setting this layer does not model, are never decoded;-- and an include target reaches the open as the bytes the line holds-- ("Nix.HostPath"), so a target with no UTF-8 reading names the file it-- names on disk.  A Boolean or integer setting compares the value's bytes-- with what it accepts, so a byte with no UTF-8 reading there is-- upstream's own invalid-value error.  A list setting's tokens are-- decoded strictly where upstream keeps them as bytes, because everything-- downstream holds them as text (a substituter's URL, a key matched-- against a narinfo's signatures, a URI prefix matched against the-- evaluator's URIs).  A token that is not UTF-8 is refused rather than-- spelled with U+FFFD, which would name a different cache, key or URI.-- The daemon's lists of users stay bytes, as upstream keeps them, since-- they are matched against the names the system gives in bytes.---- == Where the files are---- Upstream's @loadConfFile@ (@globals.cc@) reads, weakest first: the system-- file @$NIX_CONF_DIR\/nix.conf@, by default under the platform's-- machine-wide config directory (@\/etc\/nix@ where upstream runs), the-- directory having to be absolute and being collapsed lexically as the-- @Settings@ constructor runs it through @canonPath@; the user files,-- which are @$NIX_USER_CONF_FILES@ when that is set and otherwise-- @nix\/nix.conf@ under the XDG config home and then under each-- @XDG_CONFIG_DIRS@ entry, applied back to front so the first listed wins;-- then @NIX_CONFIG@.  'configFilePaths' computes that order from the-- environment and the platform's directories, which the caller looks up-- (the one platform choice this module makes is the default of-- @trusted-users@), and 'loadConfig' reads and-- folds it.---- == Precedence---- Sources are folded weakest first, so a later source overrides an earlier-- one.  A plain assignment REPLACES the accumulated value; an @extra-@-- prefixed assignment APPENDS to a list or a set.  An @extra-@ on a Boolean or a-- scalar names no setting (upstream appends only to an appendable-- setting, so @extra-max-call-depth@ is an unknown name) and is ignored-- like any unknown name.  'loadConfig' folds over the built-in default-- the files, in the order the caller lists them, then @NIX_CONFIG@, so-- @NIX_CONFIG@ overrides every file, as upstream Nix orders them.  The-- command line is not a source here: the CLI applies its flags over the-- resolved settings.---- == Settings a source set---- A client of a daemon sends the daemon the store settings a source set-- and none it left at their defaults.  Only the settings this module-- reads can be sent: a store setting it does not read (@builders@ and-- @connect-timeout@, for example) is not sent whatever a source says.-- The fold records which settings an assignment named-- ('assignedSettings', through 'loadConfigAssigned'), each by its own-- name whatever alias or @extra-@ spelling set it, and whether a plain-- assignment replaced the value it started from or only @extra-@-- assignments added to it ('HowAssigned'); 'storeSettingOverrides'-- writes those that belong to the store as @nix.conf@ spells them.  A-- list that only @extra-@ assignments built is sent with the default-- upstream's client would hold before the entries, since the default-- here is empty and a daemon is sent what upstream's client sends.  A-- command-line flag that sets a store setting is recorded as the-- assignment it stands for, each setting's record joined to the sources'-- ('Semigroup'): the flag that adds to a list is an @extra-@ assignment-- and one that sets a mode a plain assignment, so a setting a source-- replaced stays replaced when a flag only adds to it.---- == Security---- @trusted-public-keys@ decides which signatures a substituted path is-- accepted under.  The precedence is therefore load bearing: a source that-- REPLACES the trusted set where it should APPEND, or an @extra-@ that is-- mishandled, silently widens what the machine trusts.  The fold here is-- pure and total so the whole rule set can be tested directly, and the-- include expander is written over a file-reading effect-- ('ReadConfigFile') for the same reason.---- One deliberate divergence: upstream silently drops an @include@ whose-- file exists but cannot be read (its own TODO questions that).  Here a-- required include that cannot be read is an error, because the only-- thing @include@ promises over @!include@ is to fail when the file is-- unusable, and an include is where a site narrows the substituter or-- trusted-key set; dropping it leaves the wider set in force.  The reader-- therefore reports which of the two happened ('ConfigReadFailure'), so a-- missing include is reported in upstream's words and an unreadable one-- in its own.module Nix.Config  ( -- * Resolved settings    NixConfig (..),    defaultNixConfig,    PathSetValue (..),    DefaultUse (..),    -- * Where the files are    ConfigLocations (..),    configFilePaths,    nixConfFileName,    nixConfDirName,    -- * Sources and includes    ConfigSource (..),    nixConfigSourceName,    ConfigReadFailure (..),    ReadConfigFile,    loadConfig,    loadConfigAssigned,    expandConfigSource,    -- * Settings a source set    AssignedSettings (..),    HowAssigned (..),    assignedSettings,    storeSettingOverrides,    -- * Parsing and folding    ConfigLine (..),    IncludeMode (..),    ConfigAssignment (..),    parseConfigLines,    parseUnsignedSetting,    applyAssignment,    resolveConfig,  )whereimport Control.Applicative ((<|>))import Control.Monad (foldM, mfilter, when)import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, throwError)import Control.Monad.Trans (lift)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport qualified Data.ByteString.Char8 as BS8import Data.Char (isDigit, ord, toUpper)import Data.Either (rights)import Data.List (dropWhileEnd, intercalate)import Data.List.NonEmpty (NonEmpty (..))import qualified Data.List.NonEmpty as NEimport Data.Map.Strict (Map)import qualified Data.Map.Strict as Mapimport Data.Maybe (catMaybes, fromMaybe, mapMaybe, maybeToList)import Data.Set (Set)import qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text.Encoding as TEimport Data.Word (Word32)import Nix.Builder.Sandbox (SandboxMode, parseSandboxMode, renderSandboxMode)import Nix.Eval.CallDepth (defaultMaxCallDepth)import Nix.ExperimentalFeature (FeatureSet, addFeatures, noFeatures, parseFeatures, replaceFeatures)import Nix.HostPath (hostPathFromBytes, hostPathText)import Nix.Http (defaultDownloadAttempts)import qualified System.Infoimport System.OsPath (OsChar, OsPath, OsString, (</>))import qualified System.OsPath as OP-- ----------------------------------------------------------------------------- Settings-- ----------------------------------------------------------------------------- | The subset of Nix settings that this layer resolves.  The lists are-- ordered (upstream's @substituters@, @trusted-public-keys@ and-- @allowed-uris@ are each a @Strings@); order is preserved on write, though-- it does not affect key acceptance (any trusted key is enough) or URI-- admission (any prefix is enough).data NixConfig = NixConfig  { ncSubstituters :: ![Text],    ncTrustedPublicKeys :: ![Text],    -- | Upstream's @secret-key-files@: files of secret keys, whose public    -- halves are trusted beside @trusted-public-keys@, as bytes.    ncSecretKeyFiles :: ![ByteString],    -- | Upstream's @require-sigs@: a path copied into the store that is    -- not content-addressed must be signed by a trusted key.    ncRequireSigs :: !Bool,    -- | Upstream @fallback@: build from source when a substitute fails.    ncFallback :: !Bool,    -- | Upstream @always-allow-substitutes@: substitute a derivation    -- whatever its @allowSubstitutes@ attribute says.    ncAlwaysAllowSubstitutes :: !Bool,    -- | Upstream's @cores@, what a builder's @NIX_BUILD_CORES@ says, when    -- a source sets it.  Its default, which a 0 gives as well, is the    -- machine's ("Nix.Builder.Cores"), which only IO can find, so unset    -- is 'Nothing' rather than a number.    ncCores :: !(Maybe Word32),    -- | Upstream's @max-call-depth@: how many function calls may be    -- active around a new one before evaluation refuses it.    ncMaxCallDepth :: !Word32,    -- | URI prefixes a fetch may reach under @restrict-eval@.    ncAllowedUris :: ![Text],    -- | Upstream @restrict-eval@.    ncRestrictEval :: !Bool,    -- | Upstream @pure-eval@.    ncPureEval :: !Bool,    -- | Upstream @trace-verbose@.    ncTraceVerbose :: !Bool,    -- | Upstream @allow-import-from-derivation@.    ncAllowImportFromDerivation :: !Bool,    -- | Upstream @trace-import-from-derivation@.    ncTraceImportFromDerivation :: !Bool,    -- | Upstream's @sandbox@, when a source sets it.  Its default is    -- @true@ on Linux and @false@ elsewhere, the caller's to apply.    ncSandbox :: !(Maybe SandboxMode),    -- | Upstream @sandbox-fallback@.    ncSandboxFallback :: !Bool,    -- | Upstream @sandbox-paths@, as bytes.    ncSandboxPaths :: !PathSetValue,    -- | Upstream @sandbox-build-dir@.    ncSandboxBuildDir :: !ByteString,    -- | Upstream @sandbox-dev-shm-size@.    ncSandboxDevShmSize :: !ByteString,    -- | Upstream's @require-drop-supplementary-groups@, when a source sets    -- it.  Its default is whether the process runs as root, which only IO    -- can find.    ncRequireDropSupplementaryGroups :: !(Maybe Bool),    -- | Upstream's @ssl-cert-file@, when a source sets it.  Its default    -- comes from the environment and the files there are, which only IO    -- can find.    ncSslCertFile :: !(Maybe ByteString),    -- | Upstream's @build-users-group@, when a source sets it: the group    -- whose members builds run as, and whose members may not connect to    -- the daemon.  Its default is @nixbld@ for root and empty otherwise,    -- which only IO can tell apart ("Nix.Builder.BuildUser").    ncBuildUsersGroup :: !(Maybe ByteString),    -- | Upstream's @store@, as @--store@ spells it, when a source sets it:    -- the store commands use.  Its default is @$NIX_REMOTE@ and then    -- @auto@, which only the environment can tell.    ncStore :: !(Maybe ByteString),    -- | Upstream @use-xdg-base-directories@: the link to the default    -- profile is in the state directory, not the home.    ncUseXdgBaseDirectories :: !Bool,    -- | Upstream's @bash-prompt@: a @develop@ shell's prompt in place of    -- the user's, none when empty.    ncBashPrompt :: !ByteString,    -- | Upstream's @bash-prompt-prefix@: text before that prompt.    ncBashPromptPrefix :: !ByteString,    -- | Upstream's @bash-prompt-suffix@: text after it.    ncBashPromptSuffix :: !ByteString,    -- | Upstream's @allowed-impure-host-deps@, as bytes.  Its default is    -- macOS's alone, the caller's to apply.    ncAllowedImpureHostDeps :: !PathSetValue,    -- | Upstream's @darwin-log-sandbox-violations@.    ncDarwinLogSandboxViolations :: !Bool,    -- | Upstream's @keep-failed@: a build that fails keeps its directory,    -- and a check its rebuild of an output that differs.    ncKeepFailed :: !Bool,    -- | Upstream's @experimental-features@, with the warnings its values    -- gave, which the caller reports.    ncExperimentalFeatures :: !FeatureSet,    -- | Upstream's @trusted-users@: the users, and with @\@@ the groups,    -- the daemon trusts, as bytes, as the system names them.  Its default    -- is upstream's @root@, and on Windows, which has no root, the    -- machine's administrators.    ncTrustedUsers :: ![ByteString],    -- | Upstream's @allowed-users@: the users, and with @\@@ the groups,    -- who may connect to the daemon, @*@ for everyone, as bytes.    ncAllowedUsers :: ![ByteString],    -- | Upstream's @trusted-substituters@: substituters a client the    -- daemon does not trust may ask for.    ncTrustedSubstituters :: ![Text],    -- | Upstream's @filetransfer-retry-attempts@: how many times one    -- download or upload is tried before it fails.    ncDownloadAttempts :: !Word32  }  deriving (Eq, Show)-- | A set of paths whose default is the caller's: upstream's-- @sandbox-paths@ defaults to the sandbox shell a binary was built with,-- which is where it was installed, and on macOS to system paths, as its-- @allowed-impure-host-deps@ does.  An @extra-@ assignment adds to the-- default, and a plain one replaces it.data PathSetValue = PathSetValue  { psvDefault :: !DefaultUse,    psvPaths :: !(Set ByteString)  }  deriving (Eq, Show)-- | Whether a t'PathSetValue' keeps its default beside its own paths.data DefaultUse = KeepsDefault | ReplacesDefault  deriving (Eq, Show)-- | The baseline the fold starts from: no substituters, no trusted keys,-- no secret key files, signatures required, no fallback,-- @allowSubstitutes@ heeded, @cores@ unset so that the-- machine's default applies, upstream's call-depth ceiling, no allowed-- URIs, both evaluation modes off, @trace-verbose@ off, an import from-- derivation allowed and not traced, upstream's sandbox settings,-- those whose defaults take the platform or IO unset or kept for the-- caller, the default profile's link in the home, the three prompt-- settings empty, as upstream's are, nothing kept of a build that-- fails, and upstream's number of download attempts.  The empty-- substituter list and the empty trusted-key list diverge from upstream,-- whose defaults name cache.nixos.org and its key: turning a cache on for-- every machine, and trusting what its key signed, is the operator's-- decision to make in a config file, not a built-in.  The other defaults-- are upstream's own.defaultNixConfig :: NixConfigdefaultNixConfig =  NixConfig    { ncSubstituters = [],      ncTrustedPublicKeys = [],      ncSecretKeyFiles = [],      ncRequireSigs = True,      ncFallback = False,      ncAlwaysAllowSubstitutes = False,      ncCores = Nothing,      ncMaxCallDepth = defaultMaxCallDepth,      ncAllowedUris = [],      ncRestrictEval = False,      ncPureEval = False,      ncTraceVerbose = False,      ncAllowImportFromDerivation = True,      ncTraceImportFromDerivation = False,      ncSandbox = Nothing,      ncSandboxFallback = True,      ncSandboxPaths = PathSetValue KeepsDefault Set.empty,      ncSandboxBuildDir = "/build",      ncSandboxDevShmSize = "50%",      ncRequireDropSupplementaryGroups = Nothing,      ncSslCertFile = Nothing,      ncBuildUsersGroup = Nothing,      ncStore = Nothing,      ncUseXdgBaseDirectories = False,      ncBashPrompt = "",      ncBashPromptPrefix = "",      ncBashPromptSuffix = "",      ncAllowedImpureHostDeps = PathSetValue KeepsDefault Set.empty,      ncDarwinLogSandboxViolations = False,      ncKeepFailed = False,      ncExperimentalFeatures = noFeatures,      ncTrustedUsers = defaultTrustedUsers,      ncAllowedUsers = ["*"],      ncTrustedSubstituters = [],      ncDownloadAttempts = defaultDownloadAttempts    }-- | The default of @trusted-users@: upstream's @root@, and on Windows,-- which has no root, the machine's administrators, the group of SID-- @S-1-5-32-544@ that only an elevated administrator's token enables.-- The group is named by its SID, which no name a domain or a user could-- take stands in for.defaultTrustedUsers :: [ByteString]defaultTrustedUsers = case System.Info.os of  "mingw32" -> ["@S-1-5-32-544"]  _ -> ["root"]-- ----------------------------------------------------------------------------- Where the files are-- ----------------------------------------------------------------------------- | The environment that decides which files are read.  The three-- variables are carried raw, as the bytes 'Nix.Environment.lookupEnvBytes'-- returns, because upstream reads them differently: an empty-- @NIX_CONF_DIR@ is unset (@getEnvNonEmpty@), while an empty-- @NIX_USER_CONF_FILES@ is set and names no files at all, and an empty-- @NIX_CONFIG_HOME@ is set and names the working directory.  The directories arrive resolved, since the-- platform defaults behind them (where the machine-wide config directory-- is, what the XDG config home and dirs fall back to) are the caller's to-- look up.data ConfigLocations = ConfigLocations  { -- | @NIX_CONF_DIR@.    clConfDir :: !(Maybe ByteString),    -- | The platform's machine-wide config directory, where the system    -- file is unless @NIX_CONF_DIR@ moves it; 'Nothing' on a platform    -- that names none, and then there is no system file to read.    clSystemConfDir :: !(Maybe OsPath),    -- | @NIX_USER_CONF_FILES@.    clUserConfFiles :: !(Maybe ByteString),    -- | @NIX_CONFIG_HOME@.    clNixConfigHome :: !(Maybe ByteString),    -- | The XDG config home.    clConfigHome :: !OsPath,    -- | The XDG config dirs, first entry strongest.    clConfigDirs :: ![OsPath]  }  deriving (Eq, Show)-- | The config files to read, weakest first: the system file, under-- @NIX_CONF_DIR@ when that is set and non-empty and otherwise under the-- platform's machine-wide directory (no file at all when the platform has-- none); then the user files in reverse of the order upstream lists them,-- since @loadConfFile@ walks @nixUserConfFiles@ back to front-- (globals.cc) so that the first listed, the config home, wins.  The-- config home's file is in @NIX_CONFIG_HOME@ itself when that is set,-- as upstream 2.36.0's @getConfigDir@ reads it (users.cc), and otherwise-- in @nix@ under the XDG config home; an empty @NIX_CONFIG_HOME@ is set,-- since upstream reads it with @getEnvOs@, and names @nix.conf@ in the-- working directory, as @std::filesystem@ joins an empty path.  The system-- directory goes through 'canonicalAbsolutePath', as upstream's @Settings@-- constructor runs it through @canonPath@ (globals.cc): a relative one is-- refused, and @.@ and @..@ in it collapse, so the file is named canonically-- wherever it is reported and its includes resolve against the collapsed-- directory.  The user files are read as named; upstream canonicalizes none-- of them.  @NIX_USER_CONF_FILES@ replaces the XDG list outright, in its own-- order.  It is split on the platform's list separator with empty entries-- dropped as upstream's tokenizer drops them; upstream splits on @:@ on every-- platform, which cannot carry a Windows drive letter, so @;@ is honoured-- there as it is for @PATH@ and @XDG_CONFIG_DIRS@.configFilePaths :: ConfigLocations -> Either Text [OsPath]configFilePaths locations = do  confDir <- traverse variablePath (mfilter (not . BS.null) (clConfDir locations))  systemDir <- traverse canonicalAbsolutePath (confDir <|> clSystemConfDir locations)  userFiles <- case clUserConfFiles locations of    Just listed -> splitListVar <$> variablePath listed    Nothing -> do      home <- maybe (pure (clConfigHome locations </> nixConfDirName)) variablePath (clNixConfigHome locations)      pure (map (</> nixConfFileName) (home : map (</> nixConfDirName) (clConfigDirs locations)))  pure (maybeToList ((</> nixConfFileName) <$> systemDir) ++ reverse userFiles)  where    variablePath bytes = maybe (Left (noHostSpelling bytes)) Right (hostPathFromBytes bytes)-- | Split a path-list variable on the platform's list separator, dropping-- empty entries.splitListVar :: OsString -> [OsPath]splitListVar = map OP.pack . filter (not . null) . splitOn . OP.unpack  where    splitOn units = case break (== OP.searchPathSeparator) units of      (item, []) -> [item]      (item, _ : rest) -> item : splitOn rest-- | The file name every source directory is read under.nixConfFileName :: OsPathnixConfFileName = asciiPath "nix.conf"-- | The directory @nix.conf@ sits in beneath a config directory: @nix@-- under each XDG directory (@getUserConfigFiles@) and under @sysconfdir@-- for the system file (libstore's meson.build at 2.24.9).nixConfDirName :: OsPathnixConfDirName = asciiPath "nix"-- | A path this module spells itself.  'OP.unsafeFromChar' narrows a-- character to the platform's path unit (a byte, or a UTF-16 unit), which-- is exact for ASCII on both.asciiPath :: String -> OsPathasciiPath = OP.pack . map OP.unsafeFromChar-- ----------------------------------------------------------------------------- Sources and includes-- ----------------------------------------------------------------------------- | One source of config text and the name it is reported under: a file's-- path, or 'nixConfigSourceName' for the environment variable.  The name-- also anchors relative includes, so a source that is not a file cannot-- include relatively; upstream passes the literal @NIX_CONFIG@ as the-- path and its @canonPath@ refuses the @.\/x@ that results.data ConfigSource = ConfigSource  { csName :: !OsPath,    csText :: !ByteString  }  deriving (Eq, Show)-- | The name upstream applies the @NIX_CONFIG@ text under.nixConfigSourceName :: OsPathnixConfigSourceName = asciiPath "NIX_CONFIG"-- | Why a file could not be read: there is nothing at the path, or there-- is and it cannot be read (a directory, a permission refusal).  Upstream-- tells the two apart with @pathExists@ before @readFile@; here the-- distinction decides only how a failed @include@ is reported.data ConfigReadFailure = ConfigFileMissing | ConfigFileUnreadable  deriving (Eq, Show)-- | How the expander reads a file: its bytes, or why it could not be-- read.  A function so the expander runs over an in-memory map in tests-- and over the filesystem in the CLI.type ReadConfigFile m = OsPath -> m (Either ConfigReadFailure ByteString)-- | Read, expand and fold the whole configuration: the files at the given-- paths, weakest first (one that cannot be read is simply absent, as-- upstream's @applyConfigFile@ treats a @SystemError@), then the-- @NIX_CONFIG@ bytes when the variable is set.  A file that is read and-- does not expand is an error, never treated as absent.loadConfig :: (Monad m) => ReadConfigFile m -> [OsPath] -> Maybe ByteString -> m (Either Text NixConfig)loadConfig readConfigFile paths nixConfigText = fmap fst <$> loadConfigAssigned readConfigFile paths nixConfigText-- | 'loadConfig', and which settings the sources set.loadConfigAssigned :: (Monad m) => ReadConfigFile m -> [OsPath] -> Maybe ByteString -> m (Either Text (NixConfig, AssignedSettings))loadConfigAssigned readConfigFile paths nixConfigText = runExceptT $ do  fileSources <- lift (rights <$> traverse readSource paths)  let sources = fileSources ++ maybeToList (ConfigSource nixConfigSourceName <$> nixConfigText)  assignments <- concat <$> traverse (ExceptT . expandConfigSource readConfigFile) sources  config <- liftEither (resolveConfig assignments)  pure (config, assignedSettings assignments)  where    readSource path = fmap (ConfigSource path) <$> readConfigFile path-- | Expand one source into its assignments, every include spliced in at-- its line, as upstream's @parseConfigFiles@ pushes an included file's-- pairs into the same list.  An include whose resolved path is already-- being expanded is refused: upstream recurses until the stack overflows,-- and no cycle can mean anything.expandConfigSource :: (Monad m) => ReadConfigFile m -> ConfigSource -> m (Either Text [ConfigAssignment])expandConfigSource readConfigFile = runExceptT . expandWithin readConfigFile []-- | Expand one source beneath the names of the files including it.expandWithin :: (Monad m) => ReadConfigFile m -> [OsPath] -> ConfigSource -> ExceptT Text m [ConfigAssignment]expandWithin readConfigFile ancestors (ConfigSource name text) = do  parsed <- liftEither (parseConfigLines name text)  concat <$> traverse (expandLine readConfigFile (name :| ancestors)) parsed-- | Expand one line of the file at the chain's head: an assignment is-- itself; an include is the included file, expanded beneath the chain.-- A target with no host spelling (bytes that are not UTF-8, on Windows)-- names no file that can exist, so @!include@ goes on without it as it-- does without a missing file.expandLine :: (Monad m) => ReadConfigFile m -> NonEmpty OsPath -> ConfigLine -> ExceptT Text m [ConfigAssignment]expandLine _ _ (LineAssignment assignment) = pure [assignment]expandLine readConfigFile chain@(from :| _) (LineInclude mode target) =  case (hostPathFromBytes target, mode) of    (Nothing, IncludeOptional) -> pure []    (Nothing, IncludeRequired) -> throwError (includeUnspellable target from)    (Just targetPath, _) -> do      path <- liftEither (resolveIncludePath from targetPath)      when (path `elem` chain) (throwError (includeCycle path from))      contents <- lift (readConfigFile path)      case (contents, mode) of        (Right text, _) -> expandWithin readConfigFile (NE.toList chain) (ConfigSource path text)        (Left _, IncludeOptional) -> pure []        (Left failure, IncludeRequired) -> throwError (includeFailed failure path from)-- | Where an include points: the target joined under the including-- file's directory (an absolute target stands alone), then collapsed-- through 'canonicalAbsolutePath', as upstream's @absPath@ then-- @canonPath@ do.  A result that is still relative is refused: the-- including source has no directory, which is the case for @NIX_CONFIG@-- and for a user file named relatively.resolveIncludePath :: OsPath -> OsPath -> Either Text OsPathresolveIncludePath from target = canonicalAbsolutePath (OP.takeDirectory from </> target)-- | An absolute native path collapsed lexically, or upstream's own-- complaint (@canonPath@, file-system.cc at 2.24.9) for a relative one.-- The drive 'OP.splitDrive' finds (the POSIX root, a Windows drive letter-- or UNC server) is kept as spelled, and the path beneath it collapses as-- upstream's @canonPath@ collapses ('collapseUnits'), from the drive's-- last separator on, so a UNC root survives rather than folding to the-- current drive.canonicalAbsolutePath :: OsPath -> Either Text OsPathcanonicalAbsolutePath path  | OP.isAbsolute path = Right (OP.pack (root ++ collapseUnits (lastSeparator ++ OP.unpack below)))  | otherwise = Left (configErrorPrefix <> "not an absolute path: '" <> hostPathText path <> "'")  where    (drive, below) = OP.splitDrive path    driveUnits = OP.unpack drive    root = dropWhileEnd OP.isPathSeparator driveUnits    lastSeparator = take 1 (takeWhile OP.isPathSeparator (reverse driveUnits))-- | Upstream's lexical collapse, over a native path's units: @.@ drops,-- @..@ pops a real predecessor (at a root it drops, in a relative path it-- stays), repeated separators fold to one, and an empty result is @.@.-- The same rule 'Nix.Eval.CanonPath.canonPath' applies to path values,-- which are text; a native path here is bytes, which text cannot hold.-- The separator is the platform's when the path spells one with it and-- @/@ otherwise, as there.collapseUnits :: [OsChar] -> [OsChar]collapseUnits units  | rooted = separator : joined  | null resolved = [dotUnit]  | otherwise = joined  where    rooted = any OP.isPathSeparator (take 1 units)    segments = filter (not . null) (splitOnSeparators units)    resolved = reverse (foldl' (collapseStep rooted) [] segments)    separator = if OP.pathSeparator `elem` units then OP.pathSeparator else slashUnit    joined = intercalate [separator] resolved-- | One segment of the collapse fold; the accumulator holds resolved-- segments in reverse.collapseStep :: Bool -> [[OsChar]] -> [OsChar] -> [[OsChar]]collapseStep rooted acc segment  | segment == [dotUnit] = acc  | segment == parent = case acc of      [] -> [parent | not rooted]      (top : rest)        | top == parent -> parent : acc        | otherwise -> rest  | otherwise = segment : acc  where    parent = [dotUnit, dotUnit]splitOnSeparators :: [OsChar] -> [[OsChar]]splitOnSeparators units = case break OP.isPathSeparator units of  (segment, []) -> [segment]  (segment, _ : rest) -> segment : splitOnSeparators restdotUnit, slashUnit :: OsChardotUnit = OP.unsafeFromChar '.'slashUnit = OP.unsafeFromChar '/'includeFailed :: ConfigReadFailure -> OsPath -> OsPath -> TextincludeFailed failure path from =  configErrorPrefix <> "file '" <> hostPathText path <> "' included from '" <> hostPathText from <> "' " <> reason  where    reason = case failure of      ConfigFileMissing -> "not found"      ConfigFileUnreadable -> "cannot be read"includeCycle :: OsPath -> OsPath -> TextincludeCycle path from =  configErrorPrefix <> "file '" <> hostPathText path <> "' included from '" <> hostPathText from <> "' is already being included (include cycle)"includeUnspellable :: ByteString -> OsPath -> TextincludeUnspellable target from =  configErrorPrefix <> "file '" <> shownBytes target <> "' included from '" <> hostPathText from <> "' " <> noWindowsSpelling-- | The refusal of a path variable with no host spelling.  Unreachable-- while the environment reaches this module as "Nix.Environment" reads-- it, which spells a Windows value as UTF-8.noHostSpelling :: ByteString -> TextnoHostSpelling bytes = configErrorPrefix <> "path '" <> shownBytes bytes <> "' " <> noWindowsSpellingnoWindowsSpelling :: TextnoWindowsSpelling = "is not valid UTF-8, so it names no Windows file"-- ----------------------------------------------------------------------------- Parsing-- ----------------------------------------------------------------------------- | One line of a config source after comment truncation: an assignment,-- or an include directive and the bytes of the path it names.data ConfigLine  = LineAssignment !ConfigAssignment  | LineInclude !IncludeMode !ByteString  deriving (Eq, Show)-- | @include@ fails when its file cannot be read; @!include@ goes on-- without it.  That is the only difference between the two directives.data IncludeMode = IncludeRequired | IncludeOptional  deriving (Eq, Show)-- | One parsed @name = value@ assignment, before its name is resolved-- against the known settings and aliases.  The value is its tokens-- joined by single spaces, as upstream joins them.data ConfigAssignment = ConfigAssignment  { caName :: !ByteString,    caValue :: !ByteString  }  deriving (Eq, Show)-- | Parse one source's bytes into its lines.  Comments and blank lines-- drop out; a malformed line (fewer than @name =@, a missing @=@,-- or an include with other than exactly one path) is a loud error rather-- than a silent skip, as upstream Nix makes it - a typo in a-- security-relevant file must not pass for an empty setting.  The error-- quotes the line as upstream does, comment-truncated and otherwise-- verbatim, leading whitespace included.parseConfigLines :: OsPath -> ByteString -> Either Text [ConfigLine]parseConfigLines name = fmap catMaybes . traverse (parseLine . BS8.takeWhile (/= commentChar)) . BS8.lines  where    parseLine line = case configTokens line of      [] -> Right Nothing      [directive, target]        | directive == includeDirective -> Right (Just (LineInclude IncludeRequired target))        | directive == bangIncludeDirective -> Right (Just (LineInclude IncludeOptional target))      (directive : _)        | directive == includeDirective || directive == bangIncludeDirective -> syntaxError line      (key : eq : valueTokens)        | eq == assignEq -> Right (Just (LineAssignment (ConfigAssignment key (BS.intercalate valueSeparator valueTokens))))      _ -> syntaxError line    syntaxError line =      Left (configErrorPrefix <> "syntax error in configuration line '" <> shownBytes line <> "' in '" <> hostPathText name <> "'")-- | Upstream's @tokenizeString@ under its default separators (util.hh at-- 2.24.9): the maximal runs of bytes other than space, tab, CR and LF.configTokens :: ByteString -> [ByteString]configTokens = filter (not . BS.null) . BS8.splitWith (`BS8.elem` tokenSeparators)-- | Parse an unsigned integer setting the way upstream's-- @BaseSetting\<unsigned int\>@ does (@string2IntWithUnitPrefix@ over-- @boost::lexical_cast@, config-impl.hh and util.hh at 2.24.9): decimal-- digits with an optional leading @+@, then an optional binary unit-- letter, @K@, @M@, @G@ or @T@ in either case, multiplying by 1024 to-- that power.  Anything else (a minus sign, a fraction, hex, a number-- past @unsigned int@) is upstream's @UsageError@, worded as it words it,-- with no source label: upstream names the setting alone, and the value-- may have come from @NIX_CONFIG@ rather than a file.-- One divergence: upstream computes the unit product in 64 bits and-- narrows it silently, so @5G@ is accepted there as 1073741824; here it-- is refused like any other value outside the range, since a ceiling-- that cannot mean what it says must not quietly become another number.parseUnsignedSetting :: ByteString -> ByteString -> Either Text Word32parseUnsignedSetting name value = maybe (Left invalid) Right (unitValue >>= inRange)  where    invalid = "setting '" <> shownBytes name <> "' has invalid value '" <> shownBytes value <> "'"    unsigned = fromMaybe value (BS.stripPrefix plusSign value)    unitValue = case BS8.unsnoc unsigned of      Just (digits, unit) | Just multiplier <- unitMultiplier unit -> (* multiplier) <$> decimalInteger digits      _ -> decimalInteger unsigned    inRange n      | n <= toInteger (maxBound :: Word32) = Just (fromInteger n)      | otherwise = Nothing-- | A whole run of decimal digits as an 'Integer'; anything else, the-- empty run included, is 'Nothing'.decimalInteger :: ByteString -> Maybe IntegerdecimalInteger digits  | not (BS.null digits) && BS8.all isDigit digits = Just (BS8.foldl' step 0 digits)  | otherwise = Nothing  where    step acc digit = acc * 10 + toInteger (ord digit - ord '0')-- | Upstream's binary unit letters.unitMultiplier :: Char -> Maybe IntegerunitMultiplier unit = case toUpper unit of  'K' -> Just (unitBase ^ (1 :: Int))  'M' -> Just (unitBase ^ (2 :: Int))  'G' -> Just (unitBase ^ (3 :: Int))  'T' -> Just (unitBase ^ (4 :: Int))  _ -> NothingunitBase :: IntegerunitBase = 1024-- ----------------------------------------------------------------------------- Applying-- ----------------------------------------------------------------------------- | Apply one assignment to the accumulated config.  The name is resolved-- through the aliases (@binary-caches@ -> @substituters@,-- @binary-cache-public-keys@ -> @trusted-public-keys@,-- @trusted-binary-caches@ -> @trusted-substituters@,-- @build-fallback@ -> @fallback@, @build-cores@ -> @cores@,-- @build-use-chroot@ and @build-use-sandbox@ -> @sandbox@,-- @build-chroot-dirs@ and @build-sandbox-paths@ -> @sandbox-paths@,-- @download-attempts@ -> @filetransfer-retry-attempts@) and the-- @extra-@ prefix (append rather than replace, list and path-set settings-- only).  A name-- outside the known set is ignored, not an error: upstream warns and-- continues, and refusing every unknown key would reject a config that-- also carries settings this layer does not model.  A value that does-- not parse for its setting is an error, as it is in upstream Nix:-- @pure-eval = ture@ must not pass for off.applyAssignment :: NixConfig -> ConfigAssignment -> Either Text NixConfigapplyAssignment config (ConfigAssignment name value) =  case resolveName name of    Nothing -> Right config    Just (ListSetting field, mode) ->      (\items -> setList field (combine mode (getList field config) items) config) <$> listItems field value    Just (WordsSetting field, mode) ->      Right (setWords field (combine mode (getWords field config) (configTokens value)) config)    -- Upstream's Boolean and integer errors name the setting by its own    -- name, not the alias it was set through (@BaseSetting\<T\>::parse@    -- throws with @name@, the setting's, which @Config::set@ reaches    -- through an alias's entry, config.cc at 2.24.9).    Just (BoolSetting field, _) ->      (\flag -> setBool field flag config) <$> parseBool (boolFieldKey field) value    Just (ScalarSetting field, _) ->      (\number -> setScalar field number config) <$> parseUnsignedSetting (scalarFieldKey field) value    Just (ModeSetting, _) ->      (\mode -> config {ncSandbox = Just mode}) <$> parseSandboxMode value    Just (BytesSetting field, _) -> Right (setBytes field value config)    Just (PathSetSetting field, mode) ->      Right (setPathSet field (combinePaths mode (getPathSet field config) (Set.fromList (configTokens value))) config)    Just (FeaturesSetting, mode) ->      Right (config {ncExperimentalFeatures = combineFeatures mode (ncExperimentalFeatures config) (parseFeatures value)})  where    combine ReplaceMode _ new = new    combine AppendMode old new = old ++ new    -- Upstream's @StringSet@ setting: a plain assignment replaces the    -- set, the default included, and @extra-@ adds to it    -- (its @parse@ and @appendOrSet@ in config.cc at 2.24.9,    -- configuration.cc at 2.36.0).    combinePaths ReplaceMode _ new = PathSetValue ReplacesDefault new    combinePaths AppendMode old new = old {psvPaths = Set.union (psvPaths old) new}    -- Upstream's set of features: a plain assignment replaces it and    -- @extra-@ adds to it (@appendOrSet@ in configuration.cc at 2.36.0).    combineFeatures ReplaceMode = replaceFeatures    combineFeatures AppendMode = addFeatures-- | A list value's tokens as text, split as upstream's @Strings@ setting-- splits it, or the refusal of a token that is not UTF-8 (see the module-- header's Bytes section).  The refusal names the setting as upstream's-- value errors do, by its own name rather than an alias or an @extra-@-- spelling.listItems :: ListField -> ByteString -> Either Text [Text]listItems field value = maybe (Left refusal) Right (traverse decoded (configTokens value))  where    decoded = either (const Nothing) Just . TE.decodeUtf8'    refusal = "setting '" <> shownBytes (listFieldKey field) <> "' has invalid value '" <> shownBytes value <> "': not valid UTF-8"-- | Which setting a name targets, once the @extra-@ prefix and the aliases-- are resolved, and whether it replaces or appends.  @extra-@ composes-- with a list or a path set only: upstream looks the base name up and appends-- when the setting is appendable, and a Boolean or a scalar is not.resolveName :: ByteString -> Maybe (Setting, ApplyMode)resolveName name =  case BS.stripPrefix extraPrefix name of    Just base -> case baseSetting base of      Just setting@(ListSetting _) -> Just (setting, AppendMode)      Just setting@(WordsSetting _) -> Just (setting, AppendMode)      Just setting@(PathSetSetting _) -> Just (setting, AppendMode)      Just FeaturesSetting -> Just (FeaturesSetting, AppendMode)      _ -> Nothing    Nothing -> case baseSetting name of      Just setting -> Just (setting, ReplaceMode)      Nothing -> Nothing  where    baseSetting n      | n == substitutersKey || n == substitutersAlias = Just (ListSetting SubstitutersField)      | n == trustedKeysKey || n == trustedKeysAlias = Just (ListSetting TrustedKeysField)      | n == secretKeyFilesKey = Just (WordsSetting SecretKeyFilesField)      | n == requireSigsKey = Just (BoolSetting RequireSigsField)      | n == trustedUsersKey = Just (WordsSetting TrustedUsersField)      | n == allowedUsersKey = Just (WordsSetting AllowedUsersField)      | n == trustedSubstitutersKey || n == trustedSubstitutersAlias = Just (ListSetting TrustedSubstitutersField)      | n == allowedUrisKey = Just (ListSetting AllowedUrisField)      | n == fallbackKey || n == fallbackAlias = Just (BoolSetting FallbackField)      | n == alwaysAllowSubstitutesKey = Just (BoolSetting AlwaysAllowSubstitutesField)      | n == restrictEvalKey = Just (BoolSetting RestrictEvalField)      | n == pureEvalKey = Just (BoolSetting PureEvalField)      | n == traceVerboseKey = Just (BoolSetting TraceVerboseField)      | n == allowImportFromDerivationKey = Just (BoolSetting AllowImportFromDerivationField)      | n == traceImportFromDerivationKey = Just (BoolSetting TraceImportFromDerivationField)      | n == maxCallDepthKey = Just (ScalarSetting MaxCallDepthField)      | n == coresKey || n == coresAlias = Just (ScalarSetting CoresField)      | n == downloadAttemptsKey || n == downloadAttemptsAlias = Just (ScalarSetting DownloadAttemptsField)      | n == sandboxKey || n `elem` sandboxAliases = Just ModeSetting      | n == sandboxFallbackKey = Just (BoolSetting SandboxFallbackField)      | n == sandboxPathsKey || n `elem` sandboxPathsAliases = Just (PathSetSetting SandboxPathsField)      | n == allowedImpureHostDepsKey = Just (PathSetSetting AllowedImpureHostDepsField)      | n == darwinLogSandboxViolationsKey = Just (BoolSetting DarwinLogSandboxViolationsField)      | n == keepFailedKey = Just (BoolSetting KeepFailedField)      | n == sandboxBuildDirKey = Just (BytesSetting SandboxBuildDirField)      | n == sandboxDevShmSizeKey = Just (BytesSetting SandboxDevShmSizeField)      | n == requireDropGroupsKey = Just (BoolSetting RequireDropGroupsField)      | n == sslCertFileKey = Just (BytesSetting SslCertFileField)      | n == buildUsersGroupKey = Just (BytesSetting BuildUsersGroupField)      | n == storeKey = Just (BytesSetting StoreField)      | n == useXdgBaseDirectoriesKey = Just (BoolSetting UseXdgBaseDirectoriesField)      | n == bashPromptKey = Just (BytesSetting BashPromptField)      | n == bashPromptPrefixKey = Just (BytesSetting BashPromptPrefixField)      | n == bashPromptSuffixKey = Just (BytesSetting BashPromptSuffixField)      | n == experimentalFeaturesKey = Just FeaturesSetting      | otherwise = Nothing-- | A setting this layer resolves, by the shape of its value: a list of-- text, a list of tokens kept as bytes, a Boolean, an unsigned integer,-- @sandbox@'s mode, a string kept as bytes, a set of paths, or-- @experimental-features@' set of features.data Setting  = ListSetting !ListField  | WordsSetting !WordsField  | BoolSetting !BoolField  | ScalarSetting !ScalarField  | ModeSetting  | BytesSetting !BytesField  | PathSetSetting !PathSetField  | FeaturesSetting  deriving (Eq, Show)-- | The settings whose value is a set of paths, kept as bytes.data PathSetField = SandboxPathsField | AllowedImpureHostDepsField  deriving (Eq, Show)-- | The list settings.data ListField  = SubstitutersField  | TrustedKeysField  | AllowedUrisField  | TrustedSubstitutersField  deriving (Eq, Show)-- | The settings whose value is a list of tokens kept as bytes: user and-- group names, which the system spells in bytes, and the files of secret-- keys.data WordsField = TrustedUsersField | AllowedUsersField | SecretKeyFilesField  deriving (Eq, Show)-- | The Boolean settings.data BoolField  = FallbackField  | AlwaysAllowSubstitutesField  | RestrictEvalField  | PureEvalField  | TraceVerboseField  | AllowImportFromDerivationField  | TraceImportFromDerivationField  | SandboxFallbackField  | RequireDropGroupsField  | UseXdgBaseDirectoriesField  | DarwinLogSandboxViolationsField  | KeepFailedField  | RequireSigsField  deriving (Eq, Show)-- | The settings whose value is a string, kept as bytes.data BytesField  = SandboxBuildDirField  | SandboxDevShmSizeField  | SslCertFileField  | BuildUsersGroupField  | StoreField  | BashPromptField  | BashPromptPrefixField  | BashPromptSuffixField  deriving (Eq, Show)-- | The scalar settings, which only ever replace.data ScalarField = MaxCallDepthField | CoresField | DownloadAttemptsField  deriving (Eq, Show)-- | Whether an assignment replaces the accumulated value or appends to it.data ApplyMode = ReplaceMode | AppendMode  deriving (Eq, Show)getList :: ListField -> NixConfig -> [Text]getList SubstitutersField = ncSubstitutersgetList TrustedKeysField = ncTrustedPublicKeysgetList AllowedUrisField = ncAllowedUrisgetList TrustedSubstitutersField = ncTrustedSubstituterssetList :: ListField -> [Text] -> NixConfig -> NixConfigsetList SubstitutersField v config = config {ncSubstituters = v}setList TrustedKeysField v config = config {ncTrustedPublicKeys = v}setList AllowedUrisField v config = config {ncAllowedUris = v}setList TrustedSubstitutersField v config = config {ncTrustedSubstituters = v}getWords :: WordsField -> NixConfig -> [ByteString]getWords TrustedUsersField = ncTrustedUsersgetWords AllowedUsersField = ncAllowedUsersgetWords SecretKeyFilesField = ncSecretKeyFilessetWords :: WordsField -> [ByteString] -> NixConfig -> NixConfigsetWords TrustedUsersField v config = config {ncTrustedUsers = v}setWords AllowedUsersField v config = config {ncAllowedUsers = v}setWords SecretKeyFilesField v config = config {ncSecretKeyFiles = v}wordsFieldKey :: WordsField -> ByteStringwordsFieldKey TrustedUsersField = trustedUsersKeywordsFieldKey AllowedUsersField = allowedUsersKeywordsFieldKey SecretKeyFilesField = secretKeyFilesKeybytesFieldKey :: BytesField -> ByteStringbytesFieldKey SandboxBuildDirField = sandboxBuildDirKeybytesFieldKey SandboxDevShmSizeField = sandboxDevShmSizeKeybytesFieldKey SslCertFileField = sslCertFileKeybytesFieldKey BuildUsersGroupField = buildUsersGroupKeybytesFieldKey StoreField = storeKeybytesFieldKey BashPromptField = bashPromptKeybytesFieldKey BashPromptPrefixField = bashPromptPrefixKeybytesFieldKey BashPromptSuffixField = bashPromptSuffixKeypathSetFieldKey :: PathSetField -> ByteStringpathSetFieldKey SandboxPathsField = sandboxPathsKeypathSetFieldKey AllowedImpureHostDepsField = allowedImpureHostDepsKeylistFieldKey :: ListField -> ByteStringlistFieldKey SubstitutersField = substitutersKeylistFieldKey TrustedKeysField = trustedKeysKeylistFieldKey AllowedUrisField = allowedUrisKeylistFieldKey TrustedSubstitutersField = trustedSubstitutersKey-- | What a scalar setting holds, none for one no source has set whose-- default only IO can find.getScalar :: ScalarField -> NixConfig -> Maybe Word32getScalar MaxCallDepthField = Just . ncMaxCallDepthgetScalar CoresField = ncCoresgetScalar DownloadAttemptsField = Just . ncDownloadAttemptssetScalar :: ScalarField -> Word32 -> NixConfig -> NixConfigsetScalar MaxCallDepthField v config = config {ncMaxCallDepth = v}setScalar CoresField v config = config {ncCores = Just v}setScalar DownloadAttemptsField v config = config {ncDownloadAttempts = v}scalarFieldKey :: ScalarField -> ByteStringscalarFieldKey MaxCallDepthField = maxCallDepthKeyscalarFieldKey CoresField = coresKeyscalarFieldKey DownloadAttemptsField = downloadAttemptsKeyboolFieldKey :: BoolField -> ByteStringboolFieldKey FallbackField = fallbackKeyboolFieldKey AlwaysAllowSubstitutesField = alwaysAllowSubstitutesKeyboolFieldKey RestrictEvalField = restrictEvalKeyboolFieldKey PureEvalField = pureEvalKeyboolFieldKey TraceVerboseField = traceVerboseKeyboolFieldKey AllowImportFromDerivationField = allowImportFromDerivationKeyboolFieldKey TraceImportFromDerivationField = traceImportFromDerivationKeyboolFieldKey SandboxFallbackField = sandboxFallbackKeyboolFieldKey RequireDropGroupsField = requireDropGroupsKeyboolFieldKey UseXdgBaseDirectoriesField = useXdgBaseDirectoriesKeyboolFieldKey DarwinLogSandboxViolationsField = darwinLogSandboxViolationsKeyboolFieldKey KeepFailedField = keepFailedKeyboolFieldKey RequireSigsField = requireSigsKey-- | What a Boolean setting holds, none for one whose default only IO can-- find while no source has set it.getBool :: BoolField -> NixConfig -> Maybe BoolgetBool FallbackField = Just . ncFallbackgetBool AlwaysAllowSubstitutesField = Just . ncAlwaysAllowSubstitutesgetBool RestrictEvalField = Just . ncRestrictEvalgetBool PureEvalField = Just . ncPureEvalgetBool TraceVerboseField = Just . ncTraceVerbosegetBool AllowImportFromDerivationField = Just . ncAllowImportFromDerivationgetBool TraceImportFromDerivationField = Just . ncTraceImportFromDerivationgetBool SandboxFallbackField = Just . ncSandboxFallbackgetBool RequireDropGroupsField = ncRequireDropSupplementaryGroupsgetBool UseXdgBaseDirectoriesField = Just . ncUseXdgBaseDirectoriesgetBool DarwinLogSandboxViolationsField = Just . ncDarwinLogSandboxViolationsgetBool KeepFailedField = Just . ncKeepFailedgetBool RequireSigsField = Just . ncRequireSigssetBool :: BoolField -> Bool -> NixConfig -> NixConfigsetBool FallbackField v config = config {ncFallback = v}setBool AlwaysAllowSubstitutesField v config = config {ncAlwaysAllowSubstitutes = v}setBool RestrictEvalField v config = config {ncRestrictEval = v}setBool PureEvalField v config = config {ncPureEval = v}setBool TraceVerboseField v config = config {ncTraceVerbose = v}setBool AllowImportFromDerivationField v config = config {ncAllowImportFromDerivation = v}setBool TraceImportFromDerivationField v config = config {ncTraceImportFromDerivation = v}setBool SandboxFallbackField v config = config {ncSandboxFallback = v}setBool RequireDropGroupsField v config = config {ncRequireDropSupplementaryGroups = Just v}setBool UseXdgBaseDirectoriesField v config = config {ncUseXdgBaseDirectories = v}setBool DarwinLogSandboxViolationsField v config = config {ncDarwinLogSandboxViolations = v}setBool KeepFailedField v config = config {ncKeepFailed = v}setBool RequireSigsField v config = config {ncRequireSigs = v}getPathSet :: PathSetField -> NixConfig -> PathSetValuegetPathSet SandboxPathsField = ncSandboxPathsgetPathSet AllowedImpureHostDepsField = ncAllowedImpureHostDepssetPathSet :: PathSetField -> PathSetValue -> NixConfig -> NixConfigsetPathSet SandboxPathsField v config = config {ncSandboxPaths = v}setPathSet AllowedImpureHostDepsField v config = config {ncAllowedImpureHostDeps = v}-- | What a string setting holds, none for one no source has set whose-- default only IO can find.getBytes :: BytesField -> NixConfig -> Maybe ByteStringgetBytes SandboxBuildDirField = Just . ncSandboxBuildDirgetBytes SandboxDevShmSizeField = Just . ncSandboxDevShmSizegetBytes SslCertFileField = ncSslCertFilegetBytes BuildUsersGroupField = ncBuildUsersGroupgetBytes StoreField = ncStoregetBytes BashPromptField = Just . ncBashPromptgetBytes BashPromptPrefixField = Just . ncBashPromptPrefixgetBytes BashPromptSuffixField = Just . ncBashPromptSuffix-- | Upstream's @Setting\<std::string\>@: the value as it reads, its tokens-- joined by single spaces.setBytes :: BytesField -> ByteString -> NixConfig -> NixConfigsetBytes SandboxBuildDirField v config = config {ncSandboxBuildDir = v}setBytes SandboxDevShmSizeField v config = config {ncSandboxDevShmSize = v}setBytes SslCertFileField v config = config {ncSslCertFile = Just v}setBytes BuildUsersGroupField v config = config {ncBuildUsersGroup = Just v}setBytes StoreField v config = config {ncStore = Just v}setBytes BashPromptField v config = config {ncBashPrompt = v}setBytes BashPromptPrefixField v config = config {ncBashPromptPrefix = v}setBytes BashPromptSuffixField v config = config {ncBashPromptSuffix = v}-- | Upstream's Boolean spellings (@BaseSetting\<bool\>::parse@): anything-- else is an error with upstream's wording, which names the setting alone,-- as 'parseUnsignedSetting' does.parseBool :: ByteString -> ByteString -> Either Text BoolparseBool name value  | value `elem` trueSpellings = Right True  | value `elem` falseSpellings = Right False  | otherwise = Left ("Boolean setting '" <> shownBytes name <> "' has invalid value '" <> shownBytes value <> "'")trueSpellings, falseSpellings :: [ByteString]trueSpellings = [canonicalTrue, "yes", "1"]falseSpellings = [canonicalFalse, "no", "0"]-- | The spellings upstream writes a Boolean setting's value in.canonicalTrue, canonicalFalse :: ByteStringcanonicalTrue = "true"canonicalFalse = "false"-- | Fold expanded assignments onto the default config, weakest first.-- The caller orders them so the strongest source's assignments are last-- (and so win).  A value a setting cannot take aborts the fold, as-- upstream's @UsageError@ does.resolveConfig :: [ConfigAssignment] -> Either Text NixConfigresolveConfig = foldM applyAssignment defaultNixConfig-- ----------------------------------------------------------------------------- Settings a source set-- ----------------------------------------------------------------------------- | How the sources set a setting: by a plain assignment, which replaces-- the value the setting started from (its built-in default, or what an-- earlier source set), or by @extra-@ assignments alone, which add to it.data HowAssigned  = -- | Only @extra-@ assignments named the setting.    ExtendedOnly  | -- | A plain assignment named it, whatever @extra-@ assignments came    -- before or after.    Replaced  deriving (Eq, Show)-- | Two records of how a setting was set, as one: a plain assignment-- anywhere makes the setting replaced, whatever @extra-@ assignments-- came before it or after.instance Semigroup HowAssigned where  Replaced <> _ = Replaced  ExtendedOnly <> how = how-- | The settings any source set, each by its own name (the name an alias-- or an @extra-@ spelling resolves to) with how the sources set it.-- Upstream's client sends a daemon the settings that were set and none-- left at their defaults, so this is what tells them apart.newtype AssignedSettings = AssignedSettings (Map ByteString HowAssigned)  deriving (Eq, Show)-- | The records of two sets of assignments as the record of both, a-- setting both name being replaced when either replaced it.instance Semigroup AssignedSettings where  AssignedSettings earlier <> AssignedSettings later = AssignedSettings (Map.unionWith (<>) earlier later)-- | The settings a list of assignments sets.  An alias or an @extra-@-- spelling counts as the setting itself, and a name this layer does not-- know sets nothing.assignedSettings :: [ConfigAssignment] -> AssignedSettingsassignedSettings assignments =  AssignedSettings (Map.fromListWith (<>) [(settingKey setting, howAssigned mode) | ConfigAssignment name _ <- assignments, Just (setting, mode) <- [resolveName name]])  where    howAssigned ReplaceMode = Replaced    howAssigned AppendMode = ExtendedOnly-- | The overrides a client sends a daemon: each setting a source set that-- upstream's client sends from its store library or its file transfer,-- under its own name and written as @nix.conf@ spells its value, so that-- a daemon reads it back as the assignment it came from.  Only the-- settings this module reads are sent: a store setting it does not read-- (@builders@ and @connect-timeout@, for example) is not, whatever a-- source says.  Left out too are the settings the @SetOptions@ message-- carries as fields of its own, the ones upstream's client does not send-- from its other configuration objects (the evaluator's, a command's, the-- daemon command's), a setting upstream declares only on other systems-- than the one this runs on (@sandbox-dev-shm-size@ on Linux alone, for-- example), and a setting whose value only IO can find that no source-- gave one.---- A list is sent in full under its own name.  The default of-- @substituters@ and of @trusted-public-keys@ is empty here and names-- cache.nixos.org and its key in upstream's client, which sends a daemon-- the default and then the entries added to it, so a list that only-- @extra-@ assignments built is sent with those two defaults before its-- entries, none merged and none dropped, and so is one whose @extra-@-- assignments added nothing.  A list a plain assignment replaced is sent-- as it resolved.  A trusted client of nova-nix's own daemon that only-- extends either list therefore turns on cache.nixos.org and its key-- there, as upstream's client would.---- A set of paths that keeps its default beside its own paths is sent as an-- @extra-@ assignment of those paths alone, and not at all when it holds-- none: its default (the sandbox shell the binary was built with, the-- system paths of macOS) is not held here, so the default is the daemon's-- to apply.storeSettingOverrides :: AssignedSettings -> NixConfig -> Map ByteString ByteStringstoreSettingOverrides (AssignedSettings assigned) config =  Map.fromList (mapMaybe override (Map.toAscList assigned))  where    override (key, how) = do      (setting, _) <- resolveName key      case carriage setting of        Sent declared          | declaredOn System.Info.os declared -> overrideOf config how setting          | otherwise -> Nothing        InOptions -> Nothing        ClientsOwn -> Nothing-- | The name and value of a setting's override, if it has one.overrideOf :: NixConfig -> HowAssigned -> Setting -> Maybe (ByteString, ByteString)overrideOf config how setting = case setting of  ListSetting field -> Just (key, listOverride (upstreamListDefault field) how (map TE.encodeUtf8 (getList field config)))  WordsSetting field -> Just (key, joinTokens (getWords field config))  BoolSetting field -> named (spellBool <$> getBool field config)  ScalarSetting field -> named (spellNumber <$> getScalar field config)  ModeSetting -> named (renderSandboxMode <$> ncSandbox config)  BytesSetting field -> named (getBytes field config)  PathSetSetting field -> pathSetOverride key (getPathSet field config)  FeaturesSetting -> Nothing  where    key = settingKey setting    named = fmap (key,)-- | The entries of a list setting's default in upstream's client that the-- default here lacks, spelled as that client sends them.  The defaults-- here are empty, so a list that only @extra-@ assignments built holds-- just the entries they added; a daemon is sent what upstream's client-- sends, which is the default and then those entries.  A daemon at-- upstream's defaults then keeps cache.nixos.org, and an untrusted-- client's added cache that the daemon trusts passes the daemon's-- filter, which takes the plain @substituters@ name from such a client-- and refuses its @extra-@ spelling.upstreamListDefault :: ListField -> [ByteString]upstreamListDefault SubstitutersField = [upstreamSubstituter]upstreamListDefault TrustedKeysField = [upstreamTrustedKey]upstreamListDefault AllowedUrisField = []upstreamListDefault TrustedSubstitutersField = []-- | The one entry of upstream's default @substituters@, with the trailing-- slash its client renders it with.upstreamSubstituter :: ByteStringupstreamSubstituter = "https://cache.nixos.org/"-- | The one entry of upstream's default @trusted-public-keys@.upstreamTrustedKey :: ByteStringupstreamTrustedKey = "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="-- | A list's value as an override: its tokens, with upstream's default-- before them where only @extra-@ assignments built it, none merged and-- none dropped.listOverride :: [ByteString] -> HowAssigned -> [ByteString] -> ByteStringlistOverride upstreamDefault how items = joinTokens (start ++ items)  where    start = case how of      ExtendedOnly -> upstreamDefault      Replaced -> []-- | A set of paths as an override: replacing the default, under the-- setting's own name, and adding to it, under its @extra-@ name.pathSetOverride :: ByteString -> PathSetValue -> Maybe (ByteString, ByteString)pathSetOverride key (PathSetValue use paths) = case use of  ReplacesDefault -> Just (key, joinTokens (Set.toAscList paths))  KeepsDefault    | Set.null paths -> Nothing    | otherwise -> Just (extraPrefix <> key, joinTokens (Set.toAscList paths))-- | The tokens of a value as upstream's @Strings@ and @StringSet@ settings-- write them.joinTokens :: [ByteString] -> ByteStringjoinTokens = BS.intercalate valueSeparatorspellBool :: Bool -> ByteStringspellBool True = canonicalTruespellBool False = canonicalFalsespellNumber :: Word32 -> ByteStringspellNumber = BS8.pack . show-- | How a setting reaches a daemon from a client.  Every setting this-- module reads has one, so a setting added to it is classified before it-- compiles ('carriage').data Carriage  = -- | As an override, from the systems upstream declares it on: a    -- setting of upstream's store library or its file transfer.    Sent !Declared  | -- | As a field of the @SetOptions@ message, where upstream's client    -- takes it out of its overrides: keep-failed, fallback and cores.    InOptions  | -- | Not at all: the client's own.  These are the settings of    -- upstream's other configuration objects (the evaluator's, which says    -- how deep calls nest, what an evaluation may reach and whether an    -- import from a derivation builds and traces; the @develop@ command's    -- prompt; the daemon command's, who it trusts and who may connect),    -- and the two its client takes out of its overrides because they are    -- its own: @experimental-features@, which a daemon ignores from a    -- client, and @use-xdg-base-directories@, which places the client's    -- default profile.  The @store@ setting is the client's own as well:    -- what a daemon is sent for it depends on the command's flag and on    -- @NIX_REMOTE@, which this module does not see, so the client sends it    -- itself (@storeOverride@ in "Nix.Daemon.StoreChoice").    ClientsOwn-- | The systems upstream declares a setting on, by the names-- 'System.Info.os' gives them.  Its client has the setting, and so sends-- it, on those alone.data Declared  = -- | Every system.    EverySystem  | -- | Only these.    OnlySystems ![String]  | -- | Every system but these.    EverySystemBut ![String]-- | Whether a setting is declared on a system.declaredOn :: String -> Declared -> BooldeclaredOn _ EverySystem = TruedeclaredOn os (OnlySystems systems) = os `elem` systemsdeclaredOn os (EverySystemBut systems) = os `notElem` systems-- | The names 'System.Info.os' gives the systems a setting is declared-- on or off.linuxOs, freeBsdOs, darwinOs, windowsOs :: StringlinuxOs = "linux"freeBsdOs = "freebsd"darwinOs = "darwin"windowsOs = "mingw32"-- | How a setting is carried, by an exhaustive match over each kind of-- setting.carriage :: Setting -> Carriagecarriage setting = case setting of  ListSetting field -> listCarriage field  WordsSetting field -> wordsCarriage field  BoolSetting field -> boolCarriage field  ScalarSetting field -> scalarCarriage field  ModeSetting -> everySystem  BytesSetting field -> bytesCarriage field  PathSetSetting field -> pathSetCarriage field  FeaturesSetting -> ClientsOwn-- | A setting of the store library or the file transfer, declared on every-- system.everySystem :: CarriageeverySystem = Sent EverySystemlistCarriage :: ListField -> CarriagelistCarriage SubstitutersField = everySystemlistCarriage TrustedKeysField = everySystemlistCarriage AllowedUrisField = ClientsOwnlistCarriage TrustedSubstitutersField = everySystemwordsCarriage :: WordsField -> CarriagewordsCarriage TrustedUsersField = ClientsOwnwordsCarriage AllowedUsersField = ClientsOwnwordsCarriage SecretKeyFilesField = everySystem-- | Upstream declares @require-drop-supplementary-groups@ on every system-- but Windows and @darwin-log-sandbox-violations@ on macOS alone.boolCarriage :: BoolField -> CarriageboolCarriage FallbackField = InOptionsboolCarriage AlwaysAllowSubstitutesField = everySystemboolCarriage RestrictEvalField = ClientsOwnboolCarriage PureEvalField = ClientsOwnboolCarriage TraceVerboseField = ClientsOwnboolCarriage AllowImportFromDerivationField = ClientsOwnboolCarriage TraceImportFromDerivationField = ClientsOwnboolCarriage SandboxFallbackField = everySystemboolCarriage RequireDropGroupsField = Sent (EverySystemBut [windowsOs])boolCarriage UseXdgBaseDirectoriesField = ClientsOwnboolCarriage DarwinLogSandboxViolationsField = Sent (OnlySystems [darwinOs])boolCarriage KeepFailedField = InOptionsboolCarriage RequireSigsField = everySystemscalarCarriage :: ScalarField -> CarriagescalarCarriage MaxCallDepthField = ClientsOwnscalarCarriage CoresField = InOptionsscalarCarriage DownloadAttemptsField = everySystem-- | Upstream declares @sandbox-build-dir@ on Linux and FreeBSD and-- @sandbox-dev-shm-size@ on Linux alone.bytesCarriage :: BytesField -> CarriagebytesCarriage SandboxBuildDirField = Sent (OnlySystems [linuxOs, freeBsdOs])bytesCarriage SandboxDevShmSizeField = Sent (OnlySystems [linuxOs])bytesCarriage SslCertFileField = everySystembytesCarriage BuildUsersGroupField = everySystembytesCarriage StoreField = ClientsOwnbytesCarriage BashPromptField = ClientsOwnbytesCarriage BashPromptPrefixField = ClientsOwnbytesCarriage BashPromptSuffixField = ClientsOwnpathSetCarriage :: PathSetField -> CarriagepathSetCarriage SandboxPathsField = everySystempathSetCarriage AllowedImpureHostDepsField = everySystem-- | The name a setting is known by, which an alias and an @extra-@-- spelling both resolve to.settingKey :: Setting -> ByteStringsettingKey setting = case setting of  ListSetting field -> listFieldKey field  WordsSetting field -> wordsFieldKey field  BoolSetting field -> boolFieldKey field  ScalarSetting field -> scalarFieldKey field  ModeSetting -> sandboxKey  BytesSetting field -> bytesFieldKey field  PathSetSetting field -> pathSetFieldKey field  FeaturesSetting -> experimentalFeaturesKey-- ----------------------------------------------------------------------------- Messages-- ----------------------------------------------------------------------------- | Bytes from a source as a message quotes them, for display only: their-- UTF-8 reading, with U+FFFD where it fails.  Upstream writes the bytes-- themselves; a message here is text.shownBytes :: ByteString -> TextshownBytes = TE.decodeUtf8Lenient-- | What every error about the files themselves opens with (a syntax-- error, a failed include, a path that is not absolute): the format's-- name.  A setting's value error carries none, as upstream's does not.configErrorPrefix :: TextconfigErrorPrefix = "nix.conf: "-- ----------------------------------------------------------------------------- Setting names and syntax-- ---------------------------------------------------------------------------substitutersKey, substitutersAlias :: ByteStringsubstitutersKey = "substituters"substitutersAlias = "binary-caches"trustedKeysKey, trustedKeysAlias :: ByteStringtrustedKeysKey = "trusted-public-keys"trustedKeysAlias = "binary-cache-public-keys"-- | The settings that decide what a path copied into the store must be-- signed by, beside @trusted-public-keys@.secretKeyFilesKey, requireSigsKey :: ByteStringsecretKeyFilesKey = "secret-key-files"requireSigsKey = "require-sigs"fallbackKey, fallbackAlias :: ByteStringfallbackKey = "fallback"fallbackAlias = "build-fallback"coresKey, coresAlias :: ByteStringcoresKey = "cores"coresAlias = "build-cores"downloadAttemptsKey, downloadAttemptsAlias :: ByteStringdownloadAttemptsKey = "filetransfer-retry-attempts"downloadAttemptsAlias = "download-attempts"allowImportFromDerivationKey, allowedUrisKey, alwaysAllowSubstitutesKey, maxCallDepthKey, pureEvalKey, restrictEvalKey, traceImportFromDerivationKey, traceVerboseKey :: ByteStringallowImportFromDerivationKey = "allow-import-from-derivation"allowedUrisKey = "allowed-uris"alwaysAllowSubstitutesKey = "always-allow-substitutes"maxCallDepthKey = "max-call-depth"pureEvalKey = "pure-eval"restrictEvalKey = "restrict-eval"traceImportFromDerivationKey = "trace-import-from-derivation"traceVerboseKey = "trace-verbose"sandboxKey, sandboxFallbackKey, sandboxPathsKey, sandboxBuildDirKey, sandboxDevShmSizeKey, requireDropGroupsKey, sslCertFileKey :: ByteStringsandboxKey = "sandbox"sandboxFallbackKey = "sandbox-fallback"sandboxPathsKey = "sandbox-paths"sandboxBuildDirKey = "sandbox-build-dir"sandboxDevShmSizeKey = "sandbox-dev-shm-size"requireDropGroupsKey = "require-drop-supplementary-groups"sslCertFileKey = "ssl-cert-file"useXdgBaseDirectoriesKey :: ByteStringuseXdgBaseDirectoriesKey = "use-xdg-base-directories"-- | Upstream's name for the group whose members builds run as.buildUsersGroupKey :: ByteStringbuildUsersGroupKey = "build-users-group"-- | Upstream's name for the setting that names the store commands use.storeKey :: ByteStringstoreKey = "store"-- | The daemon's settings: who it trusts and who may connect, and the-- substituters an untrusted client may ask for, with that setting's older-- name.trustedUsersKey, allowedUsersKey, trustedSubstitutersKey, trustedSubstitutersAlias :: ByteStringtrustedUsersKey = "trusted-users"allowedUsersKey = "allowed-users"trustedSubstitutersKey = "trusted-substituters"trustedSubstitutersAlias = "trusted-binary-caches"-- | The settings of a @develop@ shell's prompt (@DevelopSettings@ in-- develop.cc).bashPromptKey, bashPromptPrefixKey, bashPromptSuffixKey :: ByteStringbashPromptKey = "bash-prompt"bashPromptPrefixKey = "bash-prompt-prefix"bashPromptSuffixKey = "bash-prompt-suffix"allowedImpureHostDepsKey, darwinLogSandboxViolationsKey :: ByteStringallowedImpureHostDepsKey = "allowed-impure-host-deps"darwinLogSandboxViolationsKey = "darwin-log-sandbox-violations"experimentalFeaturesKey :: ByteStringexperimentalFeaturesKey = "experimental-features"-- | The setting for what a build that fails leaves, which upstream gives no-- other name.keepFailedKey :: ByteStringkeepFailedKey = "keep-failed"-- | Upstream's older names for @sandbox@ and @sandbox-paths@-- (the aliases of @sandboxMode@ and @sandboxPaths@ in globals.hh at-- 2.24.9, local-settings.hh from 2.34.9).sandboxAliases, sandboxPathsAliases :: [ByteString]sandboxAliases = ["build-use-chroot", "build-use-sandbox"]sandboxPathsAliases = ["build-chroot-dirs", "build-sandbox-paths"]extraPrefix :: ByteStringextraPrefix = "extra-"assignEq :: ByteStringassignEq = "="plusSign :: ByteStringplusSign = "+"includeDirective, bangIncludeDirective :: ByteStringincludeDirective = "include"bangIncludeDirective = "!include"commentChar :: CharcommentChar = '#'tokenSeparators :: ByteStringtokenSeparators = " \t\n\r"-- | What a value's tokens are joined with, as upstream's-- @concatStringsSep(" ", ...)@ joins them.valueSeparator :: ByteStringvalueSeparator = " "