{-# LANGUAGE LambdaCase #-}-- | The build configuration a store's settings give: the caches its-- substituters and trusted keys name, what a failed substitute leads to,-- whether a derivation's @allowSubstitutes@ is heeded, how many times a-- download is tried, the cores a builder is told of, how builds are-- sandboxed, whom they run as and what a failed build keeps, each with-- upstream's default where no setting gives it.---- The defaults that take the machine to find ('machineDefaults') are-- found once, and what settings give is then pure-- ('settingsBuildConfig'), so a daemon gives each operation the-- configuration its connection's settings give without looking again.-- The command line applies its flags to the settings first, as-- upstream's flags set settings.module Nix.Builder.Settings ( MachineDefaults (..), machineDefaults, settingsBuildConfig, configToCaches, settingsFallback, settingsSubstitutes, settingsFetchRetry, )whereimport Control.Applicative ((<|>))import Control.Monad (filterM)import qualified Data.ByteString as BSimport Data.Containers.ListUtils (nubOrd)import Data.Maybe (fromMaybe, listToMaybe)import Data.Set (Set)import qualified Data.Set as Setimport Data.Word (Word32)import Nix.Builder (BuildConfig (..), defaultBuildConfig)import Nix.Builder.BuildDir (FailedBuilds (..))import Nix.Builder.BuildUser (ProcessPrivilege (..), buildUsersFor, defaultBuildUsersGroup, processPrivilege, userPoolDir)import qualified Nix.Builder.Cores as Coresimport Nix.Builder.Sandbox (DropGroups (..), SandboxConfig (..), SandboxFallback (..), SandboxMode (..), ViolationLog (..), darwinImpureHostPrefixes, darwinSandboxPaths, parseSandboxPaths)import Nix.Builder.Sandbox.Spawn (bytesFilePath, filePathBytes)import Nix.Config (DefaultUse (..), NixConfig (..), PathSetValue (..))import Nix.Environment (EnvLookup (..), lookupEnvBytes)import Nix.Http (FetchRetryPolicy (..), defaultFetchRetryPolicy)import Nix.Realise (Fallback (..), SubstitutesSetting (..))import Nix.Store.Path (StoreDir)import Nix.Substituter (CacheConfig (..), RequireSigs (..))import Paths_nova_nix (getBinDir)import System.Directory (doesFileExist)import System.Environment (getExecutablePath)import System.FilePath (takeDirectory, (</>))import qualified System.Info-- ----------------------------------------------------------------------------- The configuration-- ----------------------------------------------------------------------------- | The defaults a build's settings fall back on that only the machine-- can tell.data MachineDefaults = MachineDefaults { -- | Upstream's default for @cores@, which a @cores@ of 0 gives as -- well: the limit of the process's cgroup, which upstream reads on -- Linux alone, else the hardware thread count. mdCores :: !Word32, -- | The sandbox helper: beside the executable, as a release archive -- and a @cabal install@ put it, or in Cabal's install directory. mdSandboxHelper :: !(Maybe FilePath), -- | The @sandbox-paths@ a release archive's bundled shell gives: the -- shell as @\/bin\/sh@ on Linux, where the archive carries one. mdSandboxShell :: !(Set BS.ByteString), -- | Whether the process runs as root, which builds as -- @build-users-group@'s members and turns -- @require-drop-supplementary-groups@ on by default. mdPrivilege :: !ProcessPrivilege, -- | The user pool's directory ('userPoolDir'), in @NIX_STATE_DIR@ -- where that is set and not empty. mdUserPool :: !FilePath, -- | Upstream's @ssl-cert-file@ default: @NIX_SSL_CERT_FILE@, else -- @SSL_CERT_FILE@, when not empty, else the first of upstream's -- bundle paths that exists. mdCaFile :: !(Maybe BS.ByteString) } deriving (Eq, Show)-- | Find the machine's defaults, its cgroup read through the reader-- given.machineDefaults :: Cores.ReadKernelFile IO -> IO MachineDefaultsmachineDefaults readKernelFile = do exeDir <- takeDirectory <$> getExecutablePath binDir <- getBinDir MachineDefaults <$> (Cores.defaultCores <$> cgroupLimit <*> Cores.hardwareConcurrency) <*> (listToMaybe <$> filterM doesFileExist [exeDir </> sandboxHelperName, binDir </> sandboxHelperName]) <*> bundledSandboxShell exeDir <*> processPrivilege <*> userPool <*> defaultSslCertFile where userPool = lookupEnvBytes "NIX_STATE_DIR" >>= \case EnvValue bytes | not (BS.null bytes) -> userPoolDir . Just <$> bytesFilePath bytes _ -> pure (userPoolDir Nothing) cgroupLimit | System.Info.os == "linux" = Cores.cgroupCoreLimit readKernelFile | otherwise = pure Nothing-- | The build configuration settings give a store's builds on a machine.settingsBuildConfig :: MachineDefaults -> NixConfig -> StoreDir -> BuildConfigsettingsBuildConfig defaults config storeDir = (defaultBuildConfig storeDir) { bcCaches = configToCaches config, bcFallback = settingsFallback config, bcSubstitutes = settingsSubstitutes config, bcFetchRetry = settingsFetchRetry config, bcCores = settingsCores defaults config, bcSandbox = sandboxConfig defaults config, bcBuildUsers = buildUsersFor privilege (mdUserPool defaults) (fromMaybe (defaultBuildUsersGroup privilege) (ncBuildUsersGroup config)), bcFailedBuilds = if ncKeepFailed config then KeepFailed else RemoveFailed } where privilege = mdPrivilege defaults-- | The cores a builder is told of: the configured @cores@, or the-- machine's default where it is 0 or nothing sets it, as upstream's-- builder reads a 0 when it builds.settingsCores :: MachineDefaults -> NixConfig -> Word32settingsCores defaults config | Just count <- ncCores config, count > 0 = count | otherwise = mdCores defaults-- | What a failed substitute leads to: a build from source under-- @fallback@.settingsFallback :: NixConfig -> FallbacksettingsFallback config | ncFallback config = BuildFromSource | otherwise = NoFallback-- | Whether a derivation's @allowSubstitutes@ attribute is heeded: not-- under @always-allow-substitutes@.settingsSubstitutes :: NixConfig -> SubstitutesSettingsettingsSubstitutes config | ncAlwaysAllowSubstitutes config = AlwaysAllowSubstitutes | otherwise = HeedAllowSubstitutes-- | How each download and upload is tried: the default policy with the-- attempts @download-attempts@ gives, as upstream's one setting governs-- every transfer.settingsFetchRetry :: NixConfig -> FetchRetryPolicysettingsFetchRetry config = defaultFetchRetryPolicy {frpAttempts = ncDownloadAttempts config}-- ----------------------------------------------------------------------------- Caches-- ----------------------------------------------------------------------------- | The priority a configured HTTP substituter is asked at-- (cache.nixos.org is 40). A @file:\/\/@ one is asked at the priority its-- @nix-cache-info@ states ("Nix.Substituter").substituterPriority :: IntsubstituterPriority = 50-- | The caches the settings name. One t'CacheConfig' per substituter,-- by its URL as configured, each carrying the whole trusted-key set, the-- secret key files whose public keys are trusted too, and-- @require-sigs@: upstream's keys are not bound to a substituter, so a-- narinfo from any cache is accepted by any trusted key. A substituter-- with no trusted key anywhere is not refused here (it accepts nothing at-- the signature gate), as upstream's @substituters@ and-- @trusted-public-keys@ are independent.---- A substituter listed again is dropped and the first listing keeps its-- place, as upstream drops one it already has before it opens them, so a-- cache is not asked a second time for a path it failed to deliver. Two-- listings are one when they are spelled alike. Upstream compares them-- once parsed, so spellings that differ only in percent-escapes, the-- order of a query's parameters, a fragment or a port's leading zeros are-- one substituter there and two here; one with a trailing slash and one-- without are two in both.configToCaches :: NixConfig -> [CacheConfig]configToCaches config = [ CacheConfig { ccUrl = url, ccPublicKeys = ncTrustedPublicKeys config, ccSecretKeyFiles = ncSecretKeyFiles config, ccRequireSigs = if ncRequireSigs config then RequireSigs else AcceptUnsigned, ccPriority = substituterPriority } | url <- nubOrd (ncSubstituters config) ]-- ----------------------------------------------------------------------------- The sandbox-- ----------------------------------------------------------------------------- | How builds are sandboxed: the settings, with upstream's defaults-- where one is unset. @sandbox@ is on by default on Linux alone.-- @sandbox-paths@ keeps a release archive's bundled shell, and macOS's-- system paths ('darwinSandboxPaths'), unless a plain assignment replaces-- it, as upstream's default names the shell a package was built with and-- those paths; @allowed-impure-host-deps@ keeps upstream's macOS prefixes-- the same way. @require-drop-supplementary-groups@ is on for root.sandboxConfig :: MachineDefaults -> NixConfig -> SandboxConfigsandboxConfig defaults config = SandboxConfig { scMode = fromMaybe platformSandboxMode (ncSandbox config), scFallback = if ncSandboxFallback config then FallBackUnsandboxed else RefuseUnsandboxed, scPaths = parseSandboxPaths (withDefault (Set.union (mdSandboxShell defaults) platformSandboxPaths) (ncSandboxPaths config)), scBuildDir = ncSandboxBuildDir config, scDevShmSize = ncSandboxDevShmSize config, scDropGroups = if fromMaybe (mdPrivilege defaults == RunsAsRoot) (ncRequireDropSupplementaryGroups config) then RequireDropGroups else TolerateKeptGroups, scAllowedImpureHostDeps = withDefault platformImpureHostPrefixes (ncAllowedImpureHostDeps config), scViolationLog = if ncDarwinLogSandboxViolations config then ViolationsLogged else ViolationsUnlogged, scCaFile = ncSslCertFile config <|> mdCaFile defaults, scHelper = mdSandboxHelper defaults } where withDefault fallback setting = case psvDefault setting of KeepsDefault -> Set.union fallback (psvPaths setting) ReplacesDefault -> psvPaths setting-- | Upstream's default for @sandbox@ on this platform.platformSandboxMode :: SandboxModeplatformSandboxMode | System.Info.os == "linux" = SandboxEnabled | otherwise = SandboxDisabled-- | The @sandbox-paths@ default beside a sandbox shell: on macOS the-- system paths a build reads ('darwinSandboxPaths'), and elsewhere-- nothing.platformSandboxPaths :: Set BS.ByteStringplatformSandboxPaths | System.Info.os == "darwin" = darwinSandboxPaths | otherwise = Set.empty-- | Upstream's @allowed-impure-host-deps@ default: on macOS, the prefixes-- a derivation's @__impureHostDeps@ may name a path beneath-- ('darwinImpureHostPrefixes'), and elsewhere none.platformImpureHostPrefixes :: Set BS.ByteStringplatformImpureHostPrefixes | System.Info.os == "darwin" = darwinImpureHostPrefixes | otherwise = Set.empty-- | The sandbox helper's file name.sandboxHelperName :: FilePathsandboxHelperName = "nova-nix-sandbox"-- | Where a release archive keeps the shell a sandboxed build sees as-- @\/bin\/sh@, relative to the directory holding @bin@.bundledShellSubpath :: FilePathbundledShellSubpath = "libexec" </> "nova-nix" </> "sh"-- | The @sandbox-paths@ default: a release archive's bundled shell as-- @\/bin\/sh@ on Linux, where the archive carries one, and otherwise-- nothing, upstream's default for a Nix built without a sandbox shell.bundledSandboxShell :: FilePath -> IO (Set BS.ByteString)bundledSandboxShell exeDir | System.Info.os /= "linux" = pure Set.empty | otherwise = do let shell = takeDirectory exeDir </> bundledShellSubpath present <- doesFileExist shell Set.fromList <$> traverse (fmap ("/bin/sh=" <>) . filePathBytes) [shell | present]-- | Upstream's @ssl-cert-file@ default: @NIX_SSL_CERT_FILE@ when it is-- set, else @SSL_CERT_FILE@, when the value is not empty; else the first-- of upstream's bundle paths that exists.defaultSslCertFile :: IO (Maybe BS.ByteString)defaultSslCertFile = do nixVariable <- lookupEnvBytes "NIX_SSL_CERT_FILE" plainVariable <- lookupEnvBytes "SSL_CERT_FILE" case (variableValue nixVariable, variableValue plainVariable) of (Just named, _) | not (BS.null named) -> pure (Just named) (Just _, _) -> firstBundle (Nothing, Just named) | not (BS.null named) -> pure (Just named) _ -> firstBundle where variableValue found = case found of EnvValue value -> Just value _ -> Nothing firstBundle = do present <- filterM doesFileExist sslCertFileDefaults traverse filePathBytes (listToMaybe present)-- | Upstream's bundle paths, in the order it tries them.sslCertFileDefaults :: [FilePath]sslCertFileDefaults = ["/etc/ssl/certs/ca-certificates.crt", "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"]