{-# LANGUAGE LambdaCase #-}{-# LANGUAGE ScopedTypeVariables #-}{-# LANGUAGE TupleSections #-}-- | Paths a store takes from elsewhere: a NAR with what its path claims of-- itself ('importNar'), a dump made into the path its content address-- makes ('beginDumpAdd'), or a text with the references it names-- ('addTextToStore'), each held to upstream's checks before it becomes-- valid, and refused in upstream's words.---- A NAR is taken when one of the caller's keys signed its path's info, or-- when its content address and references make exactly its path, which-- its bytes then have to reproduce. Its hash and size are held to the-- bytes that arrive. A derivation, by any route, is taken only when each-- of its outputs is the path its inputs make ('checkDerivationOutputs').---- A NAR and a dump arrive a chunk at a time, each step taking the next-- chunk, so a daemon can feed them as its client sends them. What they-- write goes to a staging directory in the store until it has been-- checked, and is moved to its path under the path's lock, so giving-- one up never touches a store path.module Nix.Store.Import ( -- * Importing a NAR AdmittedNar, admitNar, NarImportStart (..), NarImport, beginNarImport, NarImportStep (..), feedNarImport, endNarImport, abandonNarImport, importNar, -- * Adding a dump DumpAdd, beginDumpAdd, feedDumpAdd, EndedDump, endDumpAdd, endedDumpPath, placeDump, abandonDumpAdd, -- * Adding a text addTextToStore, -- * The checks checkDerivationOutputs, -- * Writing a path (exposed for testing) replacePath, )whereimport Control.Exception (IOException, catch, displayException, finally, mask, onException, try, tryJust)import Control.Monad (guard, unless, when)import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, throwError, withExceptT)import Control.Monad.IO.Class (liftIO)import Control.Monad.State.Strict (StateT, evalStateT, gets, modify')import Data.Bifunctor (first)import qualified Data.ByteString as BSimport Data.Foldable (for_, traverse_)import Data.Map.Strict (Map)import qualified Data.Map.Strict as Mapimport Data.Maybe (fromMaybe)import Data.Set (Set)import qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport Data.Word (Word64)import Database.SQLite.Simple (SQLError)import Nix.Daemon.Protocol (ContentAddress, ContentAddressMethod (..), contentAddressFromParts, renderSignature)import Nix.Derivation (Derivation (..), DerivationOutput (..), drvExtension, drvFileDerivation, fixedOutput, fixedOutputModulo, fromATerm, inputAddressed, inputAddressedModulo)import Nix.Hash (FileIngestionMethod (..), IncrementalHash, bytesToHexText, hashFinalizeBytes, hashInitWithAlgo, hashUpdateChunk, hexToBytes, makeFixedOutputPath, makeSourcePath, makeTextPath, sha256Digest, unknownHashAlgo)import Nix.Logger (Level (..), Logger (..))import Nix.Store (AddressedPath (..), ArchiveEnd (..), NarFed (..), NarFeed, NarLinks, NarStreamFailure (..), NarUnpackSink, PathRegistration (..), RegistrationTime (..), SignatureRequirement (..), Store (..), Ultimate (..), UpstreamHazard (..), abortNarUnpack, addressMakesPath, addressRegistrable, canonicalizeMetadata, checkNarClaim, closeNarUnpack, endNar, feedNar, fixedReferencesRefusal, isValid, moveNarUnpack, moveOutput, newNarUnpackSink, notContentAddressed, registerPath, registrationFor, startNarFeed, upstreamManagedRefusal, volumeCaseHack, withPathLock)import Nix.Store.Access (DirAccess (OwnerAccess), createDirectoryWith)import Nix.Store.Exclusive (openNewBinaryFile)import qualified Nix.Store.ExecBit as ExecBitimport Nix.Store.Path (BadStorePath, StoreDir (..), StorePath (spName), badStorePathText, defaultStoreDir, storePathBasename, storePathToFilePath, storePathToText)import Nix.Substituter (checkContentAddress)import qualified NovaCache.Hash as Hashimport qualified NovaCache.NAR as NARimport qualified NovaCache.NarInfo as NarInfoimport qualified NovaCache.Signing as Signingimport Numeric (showHex)import qualified System.Directory as Dirimport System.FilePath ((</>))import System.IO (Handle, hClose)import System.IO.Error (ioeGetErrorString, isAlreadyExistsError, isUserError)import qualified System.OsPath as OPimport System.Random (randomIO)-- ----------------------------------------------------------------------------- Importing a NAR-- ----------------------------------------------------------------------------- | A path admitted to be imported from its NAR: the store, what the path-- claims of itself, and the NAR hash it claims.data AdmittedNar = AdmittedNar !Store !PathRegistration !Hash.NixHash-- | Admit a path to be imported from its NAR, given what it claims of-- itself as a registration: its NAR hash and size, its references and-- deriver, its content address, its signatures and whether it is-- ultimately trusted. Nothing is read yet. Where signatures are-- required, the path's signatures are counted as upstream's store counts-- them for one it is handed a NAR for: a path whose stated address makes-- it needs none; an address that makes another path is warned of, as-- upstream warns each time it tests one ('notContentAddressed'), and the-- path needs a signature; an address that makes no path is refused-- ('MakesNoPath'); and a path neither content-addressed nor signed by one-- of the keys is refused. A store-- upstream Nix's database may also manage is refused-- ("Nix.Store.Upstream").admitNar :: Store -> SignatureRequirement -> PathRegistration -> IO (Either Text AdmittedNar)admitNar store requirement claim = runExceptT $ do narHash <- liftEither (claimedNarHash claim) case requirement of SignaturesNotRequired -> pure () RequireSignature keys -> case addressMakesPath sp (prReferences claim) <$> prContentAddress claim of Just MakesItsPath -> pure () Just (MakesNoPath refusal) -> throwError refusal Just MakesAnotherPath -> liftIO (logAt (stLogger store) LevelError (notContentAddressed sp)) >> signedOrRefused keys narHash Nothing -> signedOrRefused keys narHash refusal <- liftIO (upstreamManagedRefusal ReplacesUpstreamPaths (stDir store)) traverse_ throwError refusal pure (AdmittedNar store claim narHash) where sp = prPath claim signedOrRefused :: [Signing.PublicKey] -> Hash.NixHash -> ExceptT Text IO () signedOrRefused keys narHash = unless (signedByOneOf keys claim narHash) $ throwError ("cannot add path '" <> storePathToText defaultStoreDir sp <> "' because it lacks a signature by a trusted key")-- | How an import begins.data NarImportStart = -- | The path is valid already, so its NAR is not read. NarAlreadyValid | -- | Its NAR is to be read. NarImportBegun !NarImport-- | A NAR being imported: the path admitted, the staging directory its-- tree is unpacked in, and the archive read so far.data NarImport = NarImport !AdmittedNar !Staging !NarUnpackSink !NarFeed-- | Begin importing an admitted path. One already valid is left as it is.-- For another, a staging directory is made in the store, where the NAR is-- unpacked as it arrives ('feedNarImport'), so nothing is written at the-- path until the archive has been held to the claim. The import begun-- holds that directory until it ends or is given up-- ('abandonNarImport'), so a caller begins it with asynchronous-- exceptions masked, as 'importNar' does.beginNarImport :: AdmittedNar -> IO NarImportStartbeginNarImport admitted@(AdmittedNar store claim _) = do valid <- isValid store (prPath claim) if valid then pure NarAlreadyValid else do staging <- createStaging (stDir store) sink <- newNarUnpackSink (stCaseSensitivity store) (stagedTree staging) `onException` removeStaging staging pure (NarImportBegun (NarImport admitted staging sink (startNarFeed AtRootClose)))-- | What feeding an import a chunk comes to.data NarImportStep = -- | Its archive goes on, and is fed next here. NarImportGoesOn !NarImport | -- | The path is valid: registered from the archive, or by another -- writer while the archive was read. NarImported-- | Feed an import the next chunk of its NAR. The archive is unpacked up-- to its root node's close, and the bytes of the chunk past that close-- are not the archive's: upstream's daemon reads an imported NAR the same-- way and leaves what follows it to the stream it came on, which drains-- the rest of a frame or skips to the claimed size. Once the archive-- ends ('settleNar'), or is refused, the staging directory is gone; an-- exception removes it too.feedNarImport :: NarImport -> BS.ByteString -> IO (Either Text NarImportStep)feedNarImport begun@(NarImport admitted staging sink feed) chunk = stepped `onException` abandonNarImport begun where stepped = feedNar sink feed chunk >>= \case Left failure -> Left (streamFailure failure) <$ removeStaging staging Right (NarGoesOn next) -> pure (Right (NarImportGoesOn (NarImport admitted staging sink next))) Right (NarEnded digest size _) -> (NarImported <$) <$> (settleNar admitted staging sink digest size `finally` removeStaging staging)-- | Tell an import that its NAR's bytes ended: an archive that had not-- ended by then is refused as the truncated archive it is. The staging-- directory is gone after, however it ends.endNarImport :: NarImport -> IO (Either Text ())endNarImport begun@(NarImport admitted staging sink feed) = ended `onException` abandonNarImport begun where ended = endNar sink feed >>= \case Left failure -> Left (streamFailure failure) <$ removeStaging staging Right (digest, size) -> settleNar admitted staging sink digest size `finally` removeStaging staging-- | Give up an import, removing what it unpacked. It releases what the-- import held from its beginning, the same at every step, and never-- touches the path itself, so it may be called on the import as it began,-- and after the import has ended.abandonNarImport :: NarImport -> IO ()abandonNarImport (NarImport _ staging sink _) = abortNarUnpack sink >> removeStaging staging-- | Make a path valid from its archive, read and unpacked in a staging-- directory: the archive's hash and size, over the bytes read to its root-- node's close, are held to the claim, and then, under the path's lock-- and with the path still not valid, the tree is moved to the path, the-- links it records made there, its metadata made canonical, and the tree-- as it lies there held to the hash, the tree to the address it states,-- the address to the path, and a derivation to its outputs. A refusal-- removes the tree. What passes is registered as the claim states it.settleNar :: AdmittedNar -> Staging -> NarUnpackSink -> Hash.NixHash -> Int -> IO (Either Text ())settleNar (AdmittedNar store claim narHash) staging sink digest size = runExceptT $ do liftEither (heldToClaim digest) links <- ExceptT (closeNarUnpack sink) ExceptT $ placeStaged store sp staging (Just links) $ \dest -> do liftIO (canonicalizeMetadata dest) onDisk <- liftIO (ExecBit.narHashOfPath caseHack dest) liftEither (heldToClaim onDisk) for_ (prContentAddress claim) (ExceptT . checkContentAddress caseHack defaultStoreDir sp dest) ExceptT (registrable store claim) ExceptT (registered store claim) where sp = prPath claim caseHack = volumeCaseHack (stCaseSensitivity store) heldToClaim got = checkNarClaim (storePathToText defaultStoreDir sp) narHash (toInteger (prNarSize claim)) got (toInteger size)-- | Import a path from its NAR, pulled from a chunk source, as upstream's-- local store adds a path it is handed a NAR for: the path is admitted-- ('admitNar'), a path already valid is left as it is with the source not-- read, and otherwise the NAR is read up to its root node's close-- ('feedNarImport') and the path made valid from it ('settleNar'). No-- chunk is pulled after that close, so a caller that needs the bytes of-- the last chunk past it gives a source that ends where they begin. The-- import is given up on an exception from its beginning on.importNar :: Store -> SignatureRequirement -> PathRegistration -> IO BS.ByteString -> IO (Either Text ())importNar store requirement claim source = runExceptT $ do admitted <- ExceptT (admitNar store requirement claim) ExceptT $ mask $ \restore -> beginNarImport admitted >>= \case NarAlreadyValid -> pure (Right ()) NarImportBegun begun -> restore (pumped begun) `onException` abandonNarImport begun where pumped begun = source >>= feedNarImport begun >>= \case Left reason -> pure (Left reason) Right (NarImportGoesOn next) -> pumped next Right NarImported -> pure (Right ())-- | What a refused archive is refused with.streamFailure :: NarStreamFailure -> TextstreamFailure failure = case failure of NarStreamRefused reason -> reason NarStreamMalformed reason -> reason-- ----------------------------------------------------------------------------- Adding a dump-- ----------------------------------------------------------------------------- | A dump being added as the path its content address makes: what the-- path is made from, the staging directory its contents are written in,-- how its bytes are being taken, and their hash so far under the-- address's algorithm.data DumpAdd = DumpAdd { daStore :: !Store, daName :: !Text, daMethod :: !ContentAddressMethod, daAlgo :: !Text, daReferences :: !(Set StorePath), daStaging :: !Staging, daReading :: !DumpReading, daHash :: !IncrementalHash }-- | How a dump's bytes are being taken.data DumpReading = -- | A NAR, unpacked as it arrives. ReadingArchive !NarUnpackSink !NarFeed | -- | A NAR whose root node has closed, with its SHA-256; no byte may -- follow. ArchiveRead !NarUnpackSink !Hash.NixHash | -- | A file's contents, written as they arrive. ReadingFile !Handle-- | Begin adding a dump, given the name, the method and the algorithm of-- the content address its path is made from, and the paths it refers to,-- as upstream's store adds a dump a client sends: a NAR for the-- recursive method, and a file's contents for the flat and text methods.-- What the address cannot make is refused before anything is read-- ('addressAdmits'). A store upstream Nix's database may also manage is-- refused too ("Nix.Store.Upstream"). Otherwise a staging directory is-- made in the store, where the dump is written as it arrives-- ('feedDumpAdd'). The add begun holds that directory until it ends or-- is given up ('abandonDumpAdd'), so a caller begins it with asynchronous-- exceptions masked.beginDumpAdd :: Store -> Text -> ContentAddressMethod -> Text -> Set StorePath -> IO (Either Text DumpAdd)beginDumpAdd store name method algo refs = runExceptT $ do hashing <- maybe (throwError (unknownHashAlgo algo)) pure (hashInitWithAlgo algo) liftEither (addressAdmits name method algo refs) refusal <- liftIO (upstreamManagedRefusal ReplacesUpstreamPaths (stDir store)) traverse_ throwError refusal liftIO $ do staging <- createStaging (stDir store) reading <- startReading staging `onException` removeStaging staging pure (DumpAdd store name method algo refs staging reading hashing) where startReading staging = case method of FixedMethod NarIngestion -> (\sink -> ReadingArchive sink (startNarFeed AtRootClose)) <$> newNarUnpackSink (stCaseSensitivity store) (stagedTree staging) FixedMethod FlatIngestion -> ReadingFile <$> (OP.encodeFS (stagedTree staging) >>= openNewBinaryFile) TextMethod -> ReadingFile <$> (OP.encodeFS (stagedTree staging) >>= openNewBinaryFile)-- | Whether a content address can make a path with these references, or-- why not. Only a NAR's SHA-256 address may come with references, as-- upstream makes a path from an address, and the others are refused in-- its words. A text's path is made from its SHA-256 alone, and upstream-- has no words for another algorithm: its store stops on an assertion.addressAdmits :: Text -> ContentAddressMethod -> Text -> Set StorePath -> Either Text ()addressAdmits name method algo refs = case method of TextMethod | algo /= sha256Algo -> Left ("cannot add '" <> name <> "' as a text hashed with " <> algo <> ": a text's content address is its " <> sha256Algo <> " hash") FixedMethod ingestion | not (Set.null refs) && not (ingestion == NarIngestion && algo == sha256Algo) -> Left (fixedReferencesRefusal name) _ -> Right ()-- | Write the next chunk of a dump, an empty chunk writing nothing: the-- dump's end is 'endDumpAdd'. A NAR is unpacked up to its root node's-- close, and a byte after that close is refused, as a dump is all-- archive. Once a chunk is refused the staging directory is gone; an-- exception removes it too.feedDumpAdd :: DumpAdd -> BS.ByteString -> IO (Either Text DumpAdd)feedDumpAdd add chunk | BS.null chunk = pure (Right add) | otherwise = (fmap (\reading -> add {daReading = reading, daHash = hashUpdateChunk (daHash add) chunk}) <$> taken) `onException` abandonDumpAdd add where taken = case daReading add of ReadingArchive sink feed -> feedNar sink feed chunk >>= \case Left failure -> Left (streamFailure failure) <$ removeStaging (daStaging add) Right (NarGoesOn next) -> pure (Right (ReadingArchive sink next)) Right (NarEnded digest _ after) | BS.null after -> pure (Right (ArchiveRead sink digest)) | otherwise -> trailing ArchiveRead {} -> trailing ReadingFile handle -> Right (ReadingFile handle) <$ BS.hPut handle chunk trailing = Left trailingBytesRefusal <$ abandonDumpAdd add-- | The refusal of a dump that goes on past its archive's end, in the-- words nova-cache's parser refuses an archive's trailing bytes with.trailingBytesRefusal :: TexttrailingBytesRefusal = "trailing bytes after NAR root node"-- | A dump read to its end: the add, the path its address makes, the-- address, and for a NAR what was read of it.data EndedDump = EndedDump !DumpAdd !StorePath !ContentAddress !(Maybe ReadArchive)-- | A dump's archive as it was read: its SHA-256, and the links it-- records, which are made once its tree lies at its path.data ReadArchive = ReadArchive !Hash.NixHash !NarLinks-- | The path an ended dump's address makes.endedDumpPath :: EndedDump -> StorePathendedDumpPath (EndedDump _ sp _ _) = sp-- | End a dump: a NAR must have ended with its bytes, every node of it-- closed, and a file is closed. The path its address makes is worked-- out from its hash, a name the store cannot hold refused in upstream's-- words. A refusal or an exception removes the staging directory.endDumpAdd :: DumpAdd -> IO (Either Text EndedDump)endDumpAdd add = (runExceptT ending >>= either (\reason -> Left reason <$ abandonDumpAdd add) (pure . Right)) `onException` abandonDumpAdd add where ending = do archive <- case daReading add of ReadingArchive sink feed -> do (digest, _) <- withExceptT streamFailure (ExceptT (endNar sink feed)) Just . ReadArchive digest <$> ExceptT (closeNarUnpack sink) ArchiveRead sink digest -> Just . ReadArchive digest <$> ExceptT (closeNarUnpack sink) ReadingFile handle -> Nothing <$ liftIO (hClose handle) let digest = hashFinalizeBytes (daHash add) sp <- liftEither (first badStorePathText (dumpPath add digest)) address <- maybe (throwError (unknownHashAlgo (daAlgo add))) pure (contentAddressFromParts (daMethod add) (daAlgo add) digest) pure (EndedDump add sp address archive)-- | The path a dump's address makes, given the dump's hash.dumpPath :: DumpAdd -> BS.ByteString -> Either BadStorePath StorePathdumpPath add digest = case daMethod add of TextMethod -> makeTextPath name digest (Set.toAscList (daReferences add)) FixedMethod NarIngestion | daAlgo add == sha256Algo -> makeSourcePath name digest (daReferences add) FixedMethod ingestion -> makeFixedOutputPath name (daAlgo add) ingestion digest where name = daName add-- | Make an ended dump's path valid, under the path's lock, unless it is-- valid by then: the contents are moved to the path, the links a NAR-- records made there, their metadata made canonical, and the path-- registered with its NAR hash and size, the references given and its-- content address, as upstream registers a dump it adds. A NAR is held-- to the hash it was read with once it lies at the path, since the-- volume decides the final spelling of every name, and a derivation to-- its outputs; a refusal removes it. The staging directory is gone-- after, however it ends.placeDump :: EndedDump -> IO (Either Text ())placeDump (EndedDump add sp address archive) = placeStaged store sp (daStaging add) ((\(ReadArchive _ links) -> links) <$> archive) settle `finally` removeStaging (daStaging add) where store = daStore add settle dest = do liftIO (canonicalizeMetadata dest) (narHash, narSize) <- liftIO (narOfPath (volumeCaseHack (stCaseSensitivity store)) dest) for_ archive $ \(ReadArchive digest _) -> unless (narHash == digest) $ throwError (storePathToText defaultStoreDir sp <> ": the unpacked tree does not serialise to the NAR it was unpacked from") let registration = PathRegistration sp (Hash.formatNixHash narHash) narSize Nothing (Set.toAscList (daReferences add)) NotUltimate Set.empty (Just address) RegisteredNow ExceptT (registrable store registration) ExceptT (registered store registration)-- | Give up adding a dump, removing what was written of it. It releases-- what the add held from its beginning, the same at every step, so it may-- be called on the add as it began, and after the add has ended.abandonDumpAdd :: DumpAdd -> IO ()abandonDumpAdd add = closeReading (daReading add) >> removeStaging (daStaging add) where closeReading = \case ReadingArchive sink _ -> abortNarUnpack sink ArchiveRead sink _ -> abortNarUnpack sink -- The file is about to be removed, so a failure to flush what was -- written to it is no failure of the add; closing is what lets -- Windows remove it. ReadingFile handle -> hClose handle `catch` \(_ :: IOException) -> pure ()-- | The SHA-256 and size of a path's NAR, read as it streams.narOfPath :: NAR.CaseHack -> FilePath -> IO (Hash.NixHash, Int)narOfPath caseHack path = ExecBit.withNarSource caseHack path (absorb Hash.hashInit 0) where absorb !hashing !size pull = do chunk <- pull if BS.null chunk then pure (Hash.hashFinalize hashing, size) else absorb (Hash.hashUpdate hashing chunk) (size + BS.length chunk) pull-- ----------------------------------------------------------------------------- Staging-- ----------------------------------------------------------------------------- | A directory in the store that a path's contents are written in before-- they are moved to the path ('stagedTree'), so a path is never seen-- half written and what a refusal leaves is not at a store path. Its-- name, upstream's prefix for its own and a random number, is no store-- path's, so a collection sweeps one a stopped process left.newtype Staging = Staging FilePath-- | The prefix of a staging directory's name: upstream's for the-- directories its store stages a path in.stagingPrefix :: FilePathstagingPrefix = "tmp-"-- | Make a staging directory in the store, open to the user nova-nix-- runs as alone, under a name nothing else has.createStaging :: StoreDir -> IO StagingcreateStaging dir = do number <- randomIO :: IO Word64 let path = unStoreDir dir </> stagingPrefix <> showHex number "" created <- tryJust (guard . isAlreadyExistsError) (createDirectoryWith OwnerAccess path) either (const (createStaging dir)) (const (pure (Staging path))) created-- | Where in a staging directory the contents are written.stagedTree :: Staging -> FilePathstagedTree (Staging dir) = dir </> "x"-- | Remove a staging directory and what is left in it.removeStaging :: Staging -> IO ()removeStaging (Staging dir) = Dir.removePathForcibly dir-- | Move staged contents to their path and register them there, under the-- path's lock: a path valid by then is left as it is, and otherwise the-- contents are moved to the path, with the links an archive they were-- unpacked from records made there ('moveNarUnpack'), and the path given-- to the registration ('replacePath').placeStaged :: Store -> StorePath -> Staging -> Maybe NarLinks -> (FilePath -> ExceptT Text IO ()) -> IO (Either Text ())placeStaged store sp staging archived register = withPathLock (stLogger store) (stDir store) sp $ \_ -> do valid <- isValid store sp if valid then pure (Right ()) else replacePath store sp (moved >> register dest) where dest = storePathToFilePath (stDir store) sp moved = case archived of Nothing -> liftIO (moveOutput (stagedTree staging) dest) Just links -> ExceptT (moveNarUnpack (stagedTree staging) dest links)-- | Run a write of a path that registers it, the caller holding the-- path's lock, leaving what it wrote only where the path ends valid: what-- was at the path is cleared first, and cleared again on a refusal, or on-- an exception unless the path is valid by then. An asynchronous-- exception that arrives while the registration commits is raised once it-- has committed, as the database's transaction masks its commit, so the-- path is valid and its tree stays. Where its validity cannot be read-- the tree stays too: a tree at a path that is not valid is garbage a-- collection removes, and one removed from a valid path is a store that-- no longer holds what its database says.replacePath :: Store -> StorePath -> ExceptT Text IO () -> IO (Either Text ())replacePath store sp write = do Dir.removePathForcibly dest outcome <- runExceptT write `onException` clearUnlessValid either (\reason -> Left reason <$ Dir.removePathForcibly dest) (pure . Right) outcome where dest = storePathToFilePath (stDir store) sp clearUnlessValid = try (isValid store sp) >>= \case Right False -> Dir.removePathForcibly dest Right True -> pure () Left (_ :: SQLError) -> pure ()-- | Register a path, refused in upstream's words where the database-- refuses it: a reference that is not valid, or a derivation that does-- not parse, which it raises as a user error.registered :: Store -> PathRegistration -> IO (Either Text ())registered store registration = tryJust refusal (registerPath (stDB store) registration) where refusal err | isUserError err = Just (T.pack (ioeGetErrorString err)) | otherwise = Nothing-- | The NAR hash a claim states, which must be a SHA-256 hash in the-- store's spelling.claimedNarHash :: PathRegistration -> Either Text Hash.NixHashclaimedNarHash claim = either (const (Left ("cannot add path '" <> storePathToText defaultStoreDir (prPath claim) <> "': its NAR hash '" <> prNarHash claim <> "' is not a SHA-256 hash in nix-base32"))) Right (Hash.parseNixHash (prNarHash claim))-- | Whether one of the keys given verifies one of a claim's signatures-- over its fingerprint, given the NAR hash it claims.signedByOneOf :: [Signing.PublicKey] -> PathRegistration -> Hash.NixHash -> BoolsignedByOneOf keys claim narHash = any (\sig -> any (\key -> either (const False) (Signing.verify key fingerprinted) (TE.decodeUtf8' (renderSignature sig))) keys) (Set.toList (prSignatures claim)) where -- The fields a path's fingerprint is made of, which is what its -- signatures sign; a narinfo's transport fields, which no signature -- covers, are empty. fingerprinted = NarInfo.NarInfo { NarInfo.niStorePath = storePathToText defaultStoreDir (prPath claim), NarInfo.niUrl = "", NarInfo.niCompression = "", NarInfo.niFileHash = Nothing, NarInfo.niFileSize = Nothing, NarInfo.niNarHash = Hash.formatNixHash narHash, NarInfo.niNarSize = toInteger (prNarSize claim), NarInfo.niReferences = map storePathBasename (prReferences claim), NarInfo.niDeriver = Nothing, NarInfo.niSigs = [], NarInfo.niCA = Nothing }-- | Whether a claim may be registered as it lies on disk: its content-- address, if it states one, makes its path ('addressRegistrable'), and a-- derivation's outputs are the paths its inputs make.registrable :: Store -> PathRegistration -> IO (Either Text ())registrable store claim = do addressed <- maybe (pure (Right ())) (addressRegistrable (stLogger store) sp (prReferences claim)) (prContentAddress claim) case addressed of Left refusal -> pure (Left refusal) Right () | isDerivation sp -> either (pure . Left) (checkDerivationOutputs (stDir store) sp) =<< readDerivationAt (stDir store) sp | otherwise -> pure (Right ()) where sp = prPath claim-- ----------------------------------------------------------------------------- Adding a text-- ----------------------------------------------------------------------------- | Add a text, with the store paths it references, as the path its-- SHA-256 and its name make, and answer the path, as upstream adds a-- text, which is how a client writes a @.drv@. A valid path is-- passed over. Otherwise, under the path's lock, the text is written at-- the path, its metadata made canonical, a derivation held to its outputs-- ('checkDerivationOutputs'), and it is registered with its text address; a-- refusal removes it. The references must be valid. A store upstream-- Nix's database may also manage is refused before anything is written-- ("Nix.Store.Upstream").addTextToStore :: Store -> Text -> BS.ByteString -> [StorePath] -> IO (Either Text StorePath)addTextToStore store name contents refs = runExceptT $ do sp <- liftEither (either (Left . badStorePathText) Right (makeTextPath name digest refs)) refusal <- liftIO (upstreamManagedRefusal ReplacesUpstreamPaths (stDir store)) traverse_ throwError refusal let dest = storePathToFilePath (stDir store) sp ExceptT $ withPathLock (stLogger store) (stDir store) sp $ \_ -> do valid <- isValid store sp if valid then pure (Right ()) else replacePath store sp $ do liftIO (BS.writeFile dest contents) liftIO (canonicalizeMetadata dest) when (isDerivation sp) $ do drv <- liftEither (parsedDerivation sp contents) ExceptT (checkDerivationOutputs (stDir store) sp drv) reg <- liftIO (registrationFor store sp Nothing refs) liftIO (registerPath (stDB store) reg {prContentAddress = contentAddressFromParts TextMethod sha256Algo digest}) pure sp where digest = sha256Digest contents-- ----------------------------------------------------------------------------- Derivations-- ----------------------------------------------------------------------------- | Whether a derivation's outputs are the paths its inputs make, as-- upstream checks a derivation it registers: a fixed output's path is the-- one its hash makes, each output of any other the one the derivation's-- masked modulo hash makes, its inputs' modulo hashes read from their-- @.drv@ files in the store, and each output's environment variable-- names its path. The refusals are upstream's. A derivation with-- outputs that are neither, a floating content address or more than one-- fixed output, is refused: nova-nix builds neither.checkDerivationOutputs :: StoreDir -> StorePath -> Derivation -> IO (Either Text ())checkDerivationOutputs dir sp drv = runExceptT $ do expected <- case fixedOutput drv of Just out -> liftEither (fixedOutputPaths out) Nothing | not (all (T.null . doHashAlgo) (drvOutputs drv)) -> throwError ("derivation '" <> storePathToText defaultStoreDir sp <> "' has outputs with content addresses nova-nix does not check") | otherwise -> do inputs <- evalStateT (inputModuloHashes dir drv) Map.empty made <- liftEither (either (Left . badStorePathText) Right (inputAddressed drvName inputs drv)) pure (Map.fromList [(doName out, doPath out) | out <- drvOutputs (drvFileDerivation made)]) for_ (drvOutputs drv) $ \out -> do let stated = doPath out for_ (Map.lookup (doName out) expected) $ \path -> unless (path == stated) $ throwError ("derivation has incorrect output '" <> storePathToText defaultStoreDir stated <> "', should be '" <> storePathToText defaultStoreDir path <> "'") let pathText = storePathToText defaultStoreDir stated case Map.lookup (doName out) (drvEnv drv) of Nothing -> throwError ("derivation has missing environment variable '" <> doName out <> "', should be '" <> pathText <> "' but is not present") Just value | value /= TE.encodeUtf8 pathText -> throwError ("derivation has incorrect environment variable '" <> doName out <> "', should be '" <> pathText <> "' but is actually '" <> TE.decodeUtf8Lenient value <> "'") | otherwise -> pure () where drvName = fromMaybe (spName sp) (T.stripSuffix drvExtension (spName sp)) fixedOutputPaths out = case hexToBytes (doHash out) of Nothing -> Left ("derivation '" <> storePathToText defaultStoreDir sp <> "' has a malformed hash for output '" <> doName out <> "'") Just digest -> let (method, algo) = case T.stripPrefix "r:" (doHashAlgo out) of Just rest -> (NarIngestion, rest) Nothing -> (FlatIngestion, doHashAlgo out) in either (Left . badStorePathText) (Right . Map.singleton (doName out)) (makeFixedOutputPath drvName algo method digest)-- | The modulo hash (hex) of each input derivation with the outputs taken-- from it, in path order, as 'Nix.Derivation.inputAddressed' takes them,-- each read from its @.drv@ file in the store, and each derivation hashed-- once however many paths reach it.inputModuloHashes :: StoreDir -> Derivation -> StateT (Map StorePath Text) (ExceptT Text IO) [(Text, [Text])]inputModuloHashes dir drv = traverse (\(input, outs) -> (,outs) <$> moduloHashOf input) (Map.toList (drvInputDrvs drv)) where moduloHashOf input = do known <- gets (Map.lookup input) case known of Just hex -> pure hex Nothing -> do inputDrv <- liftEither =<< liftIO (readDerivationAt dir input) hex <- case fixedOutputModulo inputDrv of Just modulo -> pure (bytesToHexText modulo) Nothing -> bytesToHexText . (`inputAddressedModulo` inputDrv) <$> inputModuloHashes dir inputDrv modify' (Map.insert input hex) pure hex-- | The derivation a @.drv@ file in the store holds, or why it cannot be-- read.readDerivationAt :: StoreDir -> StorePath -> IO (Either Text Derivation)readDerivationAt dir sp = do contents <- try (BS.readFile (storePathToFilePath dir sp)) pure $ case contents of Left (failure :: IOException) -> Left ("cannot read derivation '" <> storePathToText defaultStoreDir sp <> "': " <> T.pack (displayException failure)) Right bytes -> parsedDerivation sp bytes-- | A derivation parsed from its file, or upstream's refusal.parsedDerivation :: StorePath -> BS.ByteString -> Either Text DerivationparsedDerivation sp bytes = either (\err -> Left ("error parsing derivation '" <> storePathToText defaultStoreDir sp <> "': " <> err)) Right (fromATerm bytes)-- | Whether a store path names a derivation, by its name, as upstream-- tells one.isDerivation :: StorePath -> BoolisDerivation sp = drvExtension `T.isSuffixOf` spName sp-- | The algorithm a text address and a @source@ path hash with.sha256Algo :: Textsha256Algo = "sha256"