packages feed

nova-nix-0.11.0.0 / src / Nix / Daemon / StoreChoice.hs

{-# LANGUAGE LambdaCase #-}-- | Which store a command uses, and whether it reaches the store itself-- or through a daemon ("Nix.Daemon.ClientStore").---- == What names a store---- The value comes from @--store@, else nix.conf's @store@ setting, else-- @NIX_REMOTE@, else @auto@ ('storeReference'), and 'parseStoreTarget'-- reads it as upstream reads a store reference: the empty string and-- @auto@ choose by what the machine allows, @daemon@ is the daemon at its-- default address, @unix:\/\/PATH@ the daemon at another, @local@ the-- platform store, opened directly, and a path a store directory.  A-- @unix:\/\/@ path is percent-decoded, split at @\/@ and folded lexically,-- as upstream folds it, and must be absolute.  On Windows it is the named-- pipe's path, as written.  A word with no path separator that is none of-- the above, such as a misspelt @daemon@, is refused as a store that-- cannot be parsed, as upstream refuses it, and is never a directory.---- nova-nix reads three things differently.  It refuses a value with a query-- (@?@) or with a scheme it does not open, where upstream opens many more-- kinds of store; it reads a path as the store itself, as it has always-- read @--store@, where upstream reads it as the root of a store beneath-- it, and on Windows a drive path too, which upstream reads as a URL-- whose scheme is the drive's letter when it has a @\/@; and it makes no-- store of its own under the user's data directory-- where a Linux system has no @\/nix@ and no daemon, which upstream does-- for a user who is not root, but opens the platform store directly, where-- the opening fails as it would have.---- == What a daemon is sent---- A daemon is told the @store@ setting when the setting was set, as-- upstream's client tells it, and is told the reference as the setting-- renders it ('storeOverride').---- == Choosing---- @auto@ opens the store directly when this process can keep its state-- directory ('Nix.Store.Access.probeStoreWriting'), goes through the-- daemon when it cannot and something is at the daemon's address-- ('Nix.Daemon.Dial.addressPresence'), and otherwise opens the store-- directly, where the opening fails as it would have.  It never connects:-- a daemon that is not answering is a failure of the first operation-- that needs it, as upstream's connection is made when its store is first-- used.  A store that is named asks nothing of the machine.module Nix.Daemon.StoreChoice  ( -- * What names a store    StoreTarget (..),    parseStoreTarget,    parseStoreTargetOn,    storeReference,    -- * What a daemon is sent    StoreFlag (..),    storeOverride,    -- * Choosing    StoreProbe (..),    StoreChoice (..),    chooseStore,  )whereimport Control.Applicative ((<|>))import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport qualified Data.ByteString.Char8 as BCimport Data.Map.Strict (Map)import qualified Data.Map.Strict as Mapimport Data.Maybe (fromMaybe, isJust)import Data.Text (Text)import qualified Data.Text.Encoding as TEimport Data.Word (Word8)import Nix.Daemon.ClientStore (DaemonAddress (..))import Nix.Daemon.Dial (AddressPresence (..))import Nix.Eval.Policy (PathRules (..), hostPathRules)import Nix.Fetch.Url (Leniency (..), ParsedUrl (..), encodeUrlPath, isAbsoluteHostPath, parseUrl, percentDecode, renderAuthority, runChecked, urlPathToPath)import Nix.Store.Access (StoreWriting (..))-- ----------------------------------------------------------------------------- What names a store-- ----------------------------------------------------------------------------- | What a store reference names.data StoreTarget  = -- | @auto@, or nothing: the store directly when this process can keep    -- it, the daemon when it cannot and one is there, the store directly    -- otherwise.    AutoStore  | -- | @daemon@, the daemon at its default address, or @unix:\/\/PATH@,    -- the daemon at that address, as the bytes of a socket's path or on    -- Windows a named pipe's.    DaemonSocket !(Maybe ByteString)  | -- | @local@, the platform store, or a directory, the store there,    -- each opened directly.  The directory is as the reference spells it.    LocalStore !(Maybe ByteString)  deriving (Eq, Show)-- | A store reference as the host reads it ('parseStoreTargetOn').parseStoreTarget :: ByteString -> Either Text StoreTargetparseStoreTarget = parseStoreTargetOn hostPathRules-- | What a store reference names, or why nova-nix does not take it, under-- the path rules given, which a path separator and a @unix:\/\/@ address-- depend on.---- The reference is read in the order upstream reads one: a value that is a-- URL, one with a scheme, is the daemon at its address when the scheme is-- @unix@ and is refused with any other, since nova-nix opens no other kind-- of store; a value that is not a URL is @auto@ or nothing, @daemon@ or-- @local@, or, when it has a path separator and no @:\/\/@, a store-- directory, which nova-nix has always read @--store@ as and which-- upstream reads as the root of a store beneath it; any other value, a-- single word that is none of the first three included, is refused as a-- store that cannot be parsed.  A value with a query (@?@) is refused-- before any of this, as nova-nix opens no store that takes settings.---- Windows adds three readings, each made before the URL is read, since the-- URL grammar takes the value another way or not at all.  A value that-- starts with the extended-length prefix (@\\\\?\\@) is a store directory,-- and is read before the query refusal, since the prefix holds the @?@-- that starts a query.  A drive path is a store directory, where a drive-- path with a @\/@ is a URL whose scheme is the drive's letter.  A-- @unix:\/\/@ address is a named pipe's path as written, which holds the-- backslashes no URL holds.parseStoreTargetOn :: PathRules -> ByteString -> Either Text StoreTargetparseStoreTargetOn rules value =  readReference rules value >>= \case    ReferenceAuto -> Right AutoStore    ReferenceDaemon -> Right (DaemonSocket Nothing)    ReferenceLocal -> Right (LocalStore Nothing)    ReferenceSocket _ address -> Right (DaemonSocket address)    ReferenceDirectory directory -> Right (LocalStore (Just directory))-- | A store reference read, before it is taken as a target: each kind of-- reference nova-nix opens, with what rendering it needs.data Reference  = ReferenceAuto  | ReferenceDaemon  | ReferenceLocal  | -- | A @unix:\/\/@ reference: what follows the scheme when upstream    -- renders it, which is the authority and the path with its segments    -- percent-encoded and none folded, and the address it names    -- ('socketAddress').    ReferenceSocket !ByteString !(Maybe ByteString)  | -- | A directory, as the reference spells it.    ReferenceDirectory !ByteString-- | Read a reference in the order 'parseStoreTargetOn' describes.readReference :: PathRules -> ByteString -> Either Text ReferencereadReference rules value  | WindowsPaths <- rules, extendedLengthPrefix `BS.isPrefixOf` value = Right (ReferenceDirectory value)  | BC.elem queryMark value = Left ("store settings in a store's URL are not supported by nova-nix: '" <> shown value <> "'")  | WindowsPaths <- rules, isAbsoluteHostPath rules value = Right (ReferenceDirectory value)  | WindowsPaths <- rules, Just pipe <- BS.stripPrefix unixScheme value = socketReference rules pipe  | (Right url, _) <- runChecked (parseUrl Lenient value) = urlReference rules value url  | otherwise = spelledReference rules value-- | The reference a URL is: the daemon at the address it renders as when-- its scheme is @unix@, and otherwise one nova-nix does not open.urlReference :: PathRules -> ByteString -> ParsedUrl -> Either Text ReferenceurlReference rules value url  | urlScheme url == unixSchemeName = socketReference rules (maybe BS.empty renderAuthority (urlAuthority url) <> encodeUrlPath (urlPath url))  | otherwise = Left ("store '" <> shown value <> "' is not one nova-nix opens: it takes auto, daemon, local, unix://PATH or a store directory")-- | The reference a value is that no URL grammar takes: @auto@ or-- nothing, @daemon@, @local@, a path, or a value that cannot be parsed.spelledReference :: PathRules -> ByteString -> Either Text ReferencespelledReference rules value  | value `elem` [BS.empty, autoSpelling] = Right ReferenceAuto  | value == daemonSpelling = Right ReferenceDaemon  | value == localSpelling = Right ReferenceLocal  | isNonUriPath rules value = Right (ReferenceDirectory value)  | otherwise = Left ("Cannot parse Nix store '" <> shown value <> "'")-- | Whether a value is a path and not a URL: it has no scheme separator,-- and a path separator, so that a single word that might be special, as-- @auto@ is, is not one.isNonUriPath :: PathRules -> ByteString -> BoolisNonUriPath rules value = not (schemeSeparator `BS.isInfixOf` value) && hasPathSeparator rules value-- | Whether a value holds a path separator under the rules: @\/@, and on-- Windows @\\@ too.hasPathSeparator :: PathRules -> ByteString -> BoolhasPathSeparator rules value = BS.elem slash value || (rules == WindowsPaths && BC.elem '\\' value)-- | The spellings of the references that name no path.autoSpelling, daemonSpelling, localSpelling :: ByteStringautoSpelling = "auto"daemonSpelling = "daemon"localSpelling = "local"-- | The scheme of a daemon's address, what ends any scheme, and the two-- together.unixSchemeName, schemeSeparator, unixScheme :: ByteStringunixSchemeName = "unix"schemeSeparator = "://"unixScheme = unixSchemeName <> schemeSeparator-- | What starts the settings of a store's URL.queryMark :: CharqueryMark = '?'-- | What starts a Windows path in the extended-length form.extendedLengthPrefix :: ByteStringextendedLengthPrefix = "\\\\?\\"-- | The byte that separates the components of a POSIX path.slash :: Word8slash = 0x2f-- | The @unix:\/\/@ reference an address is, given the address as the-- reference renders it.socketReference :: PathRules -> ByteString -> Either Text ReferencesocketReference rules rendered = ReferenceSocket rendered <$> socketAddress rules rendered-- | The address a @unix:\/\/@ reference names: none for the daemon's-- default, a named pipe's path as written on Windows, and on a POSIX-- system a socket's path, absolute, percent-decoded and folded.socketAddress :: PathRules -> ByteString -> Either Text (Maybe ByteString)socketAddress rules address  | BS.null address = Right Nothing  | otherwise = case rules of      WindowsPaths -> Right (Just address)      PosixPaths -> Just <$> posixSocketPath address-- | A socket's path from the address of a @unix:\/\/@ reference: the-- address percent-decoded, split at @\/@ and put back together as a-- path, which must be absolute, then folded.posixSocketPath :: ByteString -> Either Text ByteStringposixSocketPath address = do  decoded <- checked (percentDecode address)  path <- checked (urlPathToPath PosixPaths (BS.split slash decoded))  if BS.isPrefixOf rootPath path    then Right (foldPath path)    else Left ("not an absolute path: \"" <> shown path <> "\"")  where    checked = fst . runChecked    rootPath = "/"-- | An absolute path with its repeated separators, @.@ components and-- @..@ components folded, as upstream folds a path it is given: lexically,-- no link followed, a @..@ at the root dropped.foldPath :: ByteString -> ByteStringfoldPath path = BS.cons slash (BS.intercalate (BS.singleton slash) (reverse (foldl' step [] (BS.split slash path))))  where    step kept component      | BS.null component || component == currentDirectory = kept      | component == parentDirectory = drop 1 kept      | otherwise = component : kept    currentDirectory = "."    parentDirectory = ".."-- | Bytes shown in a message, any that are not UTF-8 replaced.shown :: ByteString -> Textshown = TE.decodeUtf8Lenient-- | The reference a command uses, given what @--store@ says, what the-- @store@ setting says where a source set it and what @NIX_REMOTE@ says,-- the first of them that says anything and @auto@ when none does.  The-- setting's default is @NIX_REMOTE@, so a setting a source set overrides-- it, and the flag overrides both.  A setting or variable that is set to-- nothing says the empty reference, which is @auto@, and so overrides-- what is weaker than it.storeReference :: Maybe ByteString -> Maybe ByteString -> Maybe ByteString -> ByteStringstoreReference flag setting environment = fromMaybe autoSpelling (flag <|> setting <|> environment)-- ----------------------------------------------------------------------------- What a daemon is sent-- ----------------------------------------------------------------------------- | How a command's @--store@ flag sets the @store@ setting.data StoreFlag  = -- | The flag gives the setting a value and leaves the record of whether    -- a source set it as it was, as the flag of upstream's @nix-build@ and    -- its other legacy commands does: it changes what a setting that is    -- already set holds, and a setting nothing set is not made one.    ValueFlag  | -- | The flag also marks the setting as set, as the flag every setting    -- has in upstream's @nix@ command does.    SettingFlag  deriving (Eq, Show)-- | The override a command tells its daemon for the @store@ setting, as-- the map of the one setting it sends or no setting at all, given the-- rules, how the command's flag sets the setting, and what @--store@, the-- setting and @NIX_REMOTE@ say ('storeReference'); or why the reference-- they name is not one nova-nix opens, as 'parseStoreTargetOn' says.---- Upstream's client sends the settings that were set, each as the setting-- renders its value.  The setting is set when a source set it, or when-- the flag marks it ('SettingFlag'); @NIX_REMOTE@ only gives its default.-- What is sent is the value the setting holds, which the flag has-- replaced, rendered as upstream's setting renders it: @auto@ for the-- empty reference and for @auto@, @daemon@, @local@, and @unix:\/\/@ and-- the address as the reference spells it, a @unix:\/\/PATH@ with its-- authority and path as they render and no path folded, and with a path-- of one slash, such as @unix:\/PATH@, in the form of three.---- A directory is not sent: its rendering names it by its absolute path,-- which only IO can tell, and a command whose reference is a directory-- opens the store directly and sends no daemon anything.storeOverride :: PathRules -> StoreFlag -> Maybe ByteString -> Maybe ByteString -> Maybe ByteString -> Either Text (Map ByteString ByteString)storeOverride rules how flag setting environment  | not marked = Right Map.empty  | otherwise = maybe Map.empty (Map.singleton storeSettingName) . renderReference <$> readReference rules (storeReference flag setting environment)  where    marked = isJust setting || (how == SettingFlag && isJust flag)-- | A reference as upstream's @store@ setting renders it, or 'Nothing'-- for a directory.renderReference :: Reference -> Maybe ByteStringrenderReference = \case  ReferenceAuto -> Just autoSpelling  ReferenceDaemon -> Just daemonSpelling  ReferenceLocal -> Just localSpelling  ReferenceSocket rendered _ -> Just (unixScheme <> rendered)  ReferenceDirectory _ -> Nothing-- | The name of the setting that says which store commands use.storeSettingName :: ByteStringstoreSettingName = "store"-- ----------------------------------------------------------------------------- Choosing-- ----------------------------------------------------------------------------- | What the machine is asked to choose by under @auto@, over the monad-- the questions are asked in.data StoreProbe m = StoreProbe  { -- | Whether this process can keep the store directly    -- ('Nix.Store.Access.probeStoreWriting').    probeWriting :: !(m StoreWriting),    -- | Whether anything is at the address given, the daemon's default    -- ('Nix.Daemon.Dial.addressPresence').    probePresence :: !(ByteString -> m AddressPresence)  }-- | Where a command's store is.data StoreChoice  = -- | Opened directly: the platform store for none, otherwise the    -- directory the reference spelled.    DirectStore !(Maybe ByteString)  | -- | Through the daemon at an address.    ThroughDaemon !DaemonAddress  deriving (Eq, Show)-- | Where the store a reference names is, given how to look at the machine-- and the daemon's default address.  Only @auto@ looks: it asks whether-- the store can be kept and, when it cannot, whether anything is at the-- default address, and asks nothing further.  A daemon at the default-- address, named or not, is a 'DefaultSocket'.chooseStore :: (Monad m) => StoreProbe m -> ByteString -> StoreTarget -> m StoreChoicechooseStore probe defaultAddress = \case  AutoStore ->    probeWriting probe >>= \case      StoreWritable -> pure (DirectStore Nothing)      StoreNotWritable ->        probePresence probe defaultAddress >>= \case          AddressPresent -> pure (ThroughDaemon (DefaultSocket defaultAddress))          AddressAbsent -> pure (DirectStore Nothing)  DaemonSocket Nothing -> pure (ThroughDaemon (DefaultSocket defaultAddress))  DaemonSocket (Just address)    | address == defaultAddress -> pure (ThroughDaemon (DefaultSocket address))    | otherwise -> pure (ThroughDaemon (NamedSocket address))  LocalStore directory -> pure (DirectStore directory)