{-# LANGUAGE CPP #-}{-# LANGUAGE ExistentialQuantification #-}{-# LANGUAGE LambdaCase #-}{-# LANGUAGE ScopedTypeVariables #-}-- | The Nix store: content-addressed, immutable package storage.---- == What the store actually does---- When Nix builds a package, the output goes into the store:---- 1. Builder runs in a build directory under the store's state directory-- and writes the output at its store path, or for a Linux sandboxed-- build at that path beneath its chroot ("Nix.Builder")-- 2. Output is scanned for references to other store paths-- 3. A Linux sandboxed build's output is moved to-- @\/nix\/store\/\<hash\>-\<name\>@; any other build's is there-- already-- 4. Its files' modes and times are made canonical: read-only, and one-- modification time ("Nix.Store.Metadata")-- 5. Path is registered in the SQLite DB with its references---- When Nix SUBSTITUTES (downloads from a binary cache):---- 1. Fetch @\<hash\>.narinfo@ from cache - contains NAR hash, size, refs-- 2. Fetch the NAR file the narinfo's @URL@ names, compressed with xz,-- zstd or bzip2, or not at all-- 3. Decompress and unpack NAR into store path, checking its NAR hash-- and size against the narinfo as it streams-- 4. Make its files' modes and times canonical, as a build's-- 5. Verify NAR hash matches narinfo, on disk-- 6. Register path in DB with references from narinfo---- Both paths end the same way: a registered, immutable store path.---- == Garbage collection---- A GC root is an explicit "keep this" marker: the out-link @build@-- makes to its output, or a file the operator drops under the-- store's @gcroots@ directory. The collector walks every root, follows-- references transitively, and deletes everything not reachable; a-- delete of named paths refuses a path that walk reaches.-- "Nix.Store.GC" holds the roots model, the walk, the sweep, the delete-- of named paths, and the lock that keeps a collection and a concurrent-- writer apart; "Nix.Store.Handle" holds the open handle and its lease-- on that lock.module Nix.Store ( -- * Queries isValid, pathExists, -- * Deletion resolveDeleteTarget, -- * The process useStoreFileMask, -- * Store operations addToStore, addSourceTree, copyPathInto, placeInStore, moveOutput, registrationFor, materializeEvalSources, materializeEvalStoreWrites, replaceWithCopy, freshCopyPath, rewriteBytes, rewriteStoreHashes, scanReferences, canonicalizeMetadata, unpackNarEntry, writeDrv, writeDrvAterm, writeDrvClosure, drvReferences, -- * Streaming NAR unpacking NarUnpackSink, newNarUnpackSink, sinkNarEvent, finishNarUnpack, NarLinks, closeNarUnpack, moveNarUnpack, abortNarUnpack, NarStreamFailure (..), ArchiveEnd (..), NarFeed, NarFed (..), startNarFeed, feedNar, endNar, sinkNarStream, checkNarClaim, narHashMismatch, narSizeMismatch, -- * Paths copied in SignatureRequirement (..), AddressedPath (..), addressMakesPath, addressRegistrable, fixedReferencesRefusal, notContentAddressed, -- * Link ordering (exposed for testing) orderLinks, -- * Rewriting a file in place (exposed for testing) rewriteRegularFile, -- * Case-hack naming (exposed for testing) onDiskNameKey, caseHackDiskNames, -- * Re-exports module Nix.Store.Path, module Nix.Store.DB, module Nix.Store.Lock, module Nix.Store.CaseSensitive, module Nix.Store.Handle, module Nix.Store.GC, module Nix.Store.Upstream, )whereimport Control.Exception (IOException, bracket, catch, finally, onException, throwIO, try, tryJust)import Control.Monad (guard, unless, when)import Data.Bool (bool)import qualified Data.ByteString as BSimport qualified Data.ByteString.Char8 as BS8import Data.Char (toUpper)import Data.Foldable (fold, traverse_)import Data.IORef (IORef, newIORef, readIORef, writeIORef)import Data.List (inits, stripPrefix)import Data.Map.Strict (Map)import qualified Data.Map.Strict as Mapimport Data.Maybe (catMaybes)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 Nix.Daemon.Protocol (ContentAddress, ContentAddressMethod (..), caAlgo, caDigest, caMethod, contentAddressFromParts)import Nix.Derivation (Derivation (..), fromATerm, toATerm)import Nix.Hash (FileIngestionMethod (..), makeFixedOutputPath, makeSourcePath, makeStorePath, makeTextPath, sha256Digest)import Nix.Logger (Level (..), Logger (..))import Nix.Store.CaseSensitive (CaseSensitivity (..), pathCaseHack, trySetCaseSensitiveDir, volumeCaseHack)import Nix.Store.DBimport Nix.Store.EntryName (checkEntryName, entryNamePath, hostNameRules, linkTargetPath, shownBytes)import Nix.Store.Exclusive (Occupant (..), directoryTakenMessage, fileTakenMessage, openNewBinaryFile, symlinkTakenMessage)import qualified Nix.Store.ExecBit as ExecBitimport Nix.Store.GCimport Nix.Store.Handleimport Nix.Store.Lockimport Nix.Store.Metadata (canonicalizeMetadata)import Nix.Store.Pathimport Nix.Store.Symlink (WalkNode (..), classifyWalkNode, createSymlinkOfKind)import Nix.Store.Upstreamimport qualified NovaCache.Base64 as B64import qualified NovaCache.Hash as Hashimport qualified NovaCache.NAR as NARimport qualified NovaCache.NAR.Stream as Streamimport qualified NovaCache.Signing as Signingimport System.Directory ( doesDirectoryExist, doesPathExist, listDirectory, renamePath, setPermissions, )import qualified System.Directory as Dirimport qualified System.Directory.OsPath as OsDirimport System.FilePath ((</>))import qualified System.FilePath.Windows as Windowsimport System.IO (Handle, IOMode (ReadMode), hClose, withBinaryFile)import System.IO.Error (isAlreadyExistsError)import System.OsPath (OsPath)import qualified System.OsPath as OP#if !defined(mingw32_HOST_OS)import Data.Bits ((.&.), (.|.))import Data.Functor (void)import Foreign.C.Error (Errno (..), eXDEV)import GHC.IO.Exception (IOException (ioe_errno))import System.Posix.Files (FileStatus, deviceID, fileID, fileMode, fileSize, getFdStatus, getSymbolicLinkStatus, groupWriteMode, isDirectory, isRegularFile, otherWriteMode, ownerWriteMode, setFdMode, setFdSize, setFileCreationMask, setFileMode)import System.Posix.IO (OpenFileFlags (..), OpenMode (..), closeFd, defaultFileFlags, openFd)import qualified System.Posix.IO.ByteString as PosixBytesimport System.Posix.Types (Fd)#endif-- | Give the process upstream's file-creation mask, 0022, as every-- upstream command does (@initNix@ in shared.cc): what it writes, and what a-- builder it starts writes, is then readable by everybody and writable by its-- owner alone, so no build's output is refused as one others could have-- changed (@registerOutputs@). Windows has no such mask.useStoreFileMask :: IO ()#if defined(mingw32_HOST_OS)useStoreFileMask = pure ()#elseuseStoreFileMask = void (setFileCreationMask (groupWriteMode .|. otherWriteMode))#endif-- | Check if a store path is registered as valid in the database.isValid :: Store -> StorePath -> IO BoolisValid = isValidPath . stDB-- | Check if a store path exists on disk (file or directory, regardless of DB).pathExists :: Store -> StorePath -> IO BoolpathExists store sp = doesPathExist (storePathToFilePath (stDir store) sp)-- ----------------------------------------------------------------------------- Deletion-- ----------------------------------------------------------------------------- | Resolve a @store delete@ argument to the store entry it names: a bare-- @hash-name@ basename, or a full path spelled under the opened store's-- directory, the platform store, or the canonical store, with either-- separator. The name after the last separator is refused as-- 'storeEntryName' refuses a library caller's, in its words, so the-- command and the library delete refuse the same names; like it, this-- does not check the name as a store path name. Lock files are refused-- too, but not here: names like @flake.lock@ are legal store-path names,-- so telling a lock file from a store object needs the registration-- rows, and that decision lives in 'deleteStorePathRaw'.resolveDeleteTarget :: StoreDir -> Text -> Either Text StoreEntryNameresolveDeleteTarget storeDir raw = storeEntryName basename >>= underThisStore where underThisStore name | dirOk = Right name | otherwise = Left (raw <> ": not a path under this store") basename = T.takeWhileEnd (not . Windows.isPathSeparator) raw dirPart = normalizeSeps (T.dropWhileEnd Windows.isPathSeparator (T.dropEnd (T.length basename) raw)) dirOk = T.null dirPart || dirPart `elem` [ normalizeSeps (T.pack (unStoreDir storeDir)), normalizeSeps (T.pack (unStoreDir platformStoreDir)), normalizeSeps (T.pack (unStoreDir defaultStoreDir)) ] normalizeSeps = T.map (\c -> if c == '\\' then '/' else c)-- ----------------------------------------------------------------------------- Store operations-- ----------------------------------------------------------------------------- | Move a build output (file or directory) to the store path, make its-- metadata canonical ('canonicalizeMetadata'), and register.---- If @renamePath@ fails across volumes (on Windows, for any reason), falls-- back to copy + remove.addToStore :: Store -> FilePath -> StorePath -> Maybe Text -> [StorePath] -> IO ()addToStore store srcPath sp deriver refs = do reg <- placeInStore store srcPath sp deriver refs registerPath (stDB store) reg-- | Move a build output into the store, make its metadata canonical-- ('canonicalizeMetadata'), and compute its registration (NAR hash, size,-- references) WITHOUT writing to the database.---- Splitting placement from registration lets a multi-output build place every-- output first and then register them together, so intra-derivation-- cross-output references are preserved (see 'registerPaths').placeInStore :: Store -> FilePath -> StorePath -> Maybe Text -> [StorePath] -> IO PathRegistrationplaceInStore store srcPath sp deriver refs = do let destPath = storePathToFilePath (stDir store) sp moveOutput srcPath destPath canonicalizeMetadata destPath registrationFor store sp deriver refs-- | Compute the registration metadata for a store path already present on-- disk, without moving anything. Used by 'placeInStore' after its move,-- and by 'materializeEvalSources' to register a verified adopted tree.-- The path is not ultimately trusted and has no signatures or content-- address; a caller that knows better says so in the registration.registrationFor :: Store -> StorePath -> Maybe Text -> [StorePath] -> IO PathRegistrationregistrationFor store sp deriver refs = do let destPath = storePathToFilePath (stDir store) sp -- Compute the NAR hash and size of the final store contents. The NAR -- serialization is canonical (entries sorted, 8-byte padding), so this is -- exactly the NarHash/NarSize a binary cache reports for the path. narEntry <- ExecBit.serialiseFromPath (volumeCaseHack (stCaseSensitivity store)) destPath let narBytes = NAR.serialise narEntry pure PathRegistration { prPath = sp, prNarHash = Hash.formatNixHash (Hash.hashBytes narBytes), prNarSize = BS.length narBytes, prDeriver = deriver, prReferences = refs, prUltimate = NotUltimate, prSignatures = Set.empty, prContentAddress = Nothing, prRegistrationTime = RegisteredNow }-- | Move a file or directory, by a rename, as upstream's @movePath@-- does (local-derivation-goal.cc at 2.24.9, unix\/file-system.cc at 2.36.0):-- a directory its owner may not write, as a canonical one is, is given owner-- write for the rename, which needs it to change the directory's @..@, and-- its mode back after. A rename that fails fails the move, so a tree keeps-- its inodes and hard links, except across volumes, where the move copies and-- removes ('copyPathInto', which keeps symlinks as symlinks: a dereferencing-- copy would make the stored bytes, and the NAR hash a cache signs, depend on-- where the source was). On Windows every failure copies.moveOutput :: FilePath -> FilePath -> IO ()moveOutput src dest -- A build writes into its own output path, so the usual case is a move -- onto itself. POSIX rename(a,a) is a benign no-op, but MoveFileEx is -- documented as unusable when either name is a directory, and the -- IOException fallback below would then copy a tree into itself and -- delete the result. Answering here settles both platforms. | src == dest = pure ()#if defined(mingw32_HOST_OS) | otherwise = renamePath src dest `catch` \(_ :: IOException) -> do copyPathInto src dest Dir.removePathForcibly src#else | otherwise = do status <- getSymbolicLinkStatus src let mode = fileMode status if isDirectory status && mode .&. ownerWriteMode == 0 then do setFileMode src (mode .|. ownerWriteMode) rename `onException` setFileMode src mode setFileMode dest mode else rename where rename = renamePath src dest `catch` \(failure :: IOException) -> if ioe_errno failure == Just (case eXDEV of Errno number -> number) then copyPathInto src dest *> Dir.removePathForcibly src else throwIO failure#endif-- | Byte-scan a tree for store path references.---- Searches each scan unit ('collectScanUnits': regular file bytes,-- symlink target strings and entry names) for each candidate's bare-- 32-character hash - the same needle upstream Nix scans for. Matching-- the hash rather than a store-dir-prefixed path keeps the scan-- independent of the spelling the builder embedded (canonical-- @\/nix\/store\/...@, @C:\\nix\\store\\...@, @C:\/nix\/store\/...@):-- a builder is handed its store paths under the store's real directory-- (the derivation's canonical spelling is rewritten at the spawn, in-- "Nix.Builder"), and what it writes from them may spell that directory-- any of these ways.scanReferences :: [StorePath] -> FilePath -> IO [StorePath]scanReferences candidates dir = do let candidateSet = Set.fromList [(spHash sp, sp) | sp <- candidates] needles = [(TE.encodeUtf8 h, h) | (h, _) <- Set.toList candidateSet] units <- collectScanUnits dir foundHashes <- foldlIO Set.empty units $ \acc unit -> do contents <- scanUnitBytes unit pure (Set.union acc (Set.fromList [h | (needle, h) <- needles, needle `BS.isInfixOf` contents])) pure [sp | (h, sp) <- Set.toList candidateSet, Set.member h foundHashes]-- | Replace store path hashes across a tree: file bytes, symlink targets and-- entry names, every place a NAR carries one. Upstream rewrites the serialized-- NAR and so reaches all three (@rewriteOutput@ in-- @local-derivation-goal.cc@ at 2.24.9). A store path hash has one length, so-- no offset inside a file moves.rewriteStoreHashes :: [(Text, Text)] -> FilePath -> IO ()rewriteStoreHashes [] _ = pure ()rewriteStoreHashes rewrites root = rewriteAt id root where byteRewrites = [(TE.encodeUtf8 from, TE.encodeUtf8 to) | (from, to) <- rewrites] nameRewrites = [(T.unpack from, T.unpack to) | (from, to) <- rewrites] rewriteName name = foldl' (\acc (from, to) -> replaceInName from to acc) name nameRewrites -- Replacing a link edits its parent, so the guard for a read-only parent -- comes from the caller: the root's parent is the store, not the output. rewriteAt parentGuard path = do node <- classifyWalkNode path case node of WalkSymlink -> do target <- Dir.getSymbolicLinkTarget path let updated = rewriteName target unless (updated == target) (parentGuard (replaceLink path updated)) WalkDirectory -> do entries <- listDirectory path mapM_ (rewriteEntry path) entries WalkRegular -> rewriteRegularFile (rewriteBytes byteRewrites) path WalkAbsent -> pure () rewriteEntry dir entry = do rewriteAt (whileWritable dir) (dir </> entry) let renamed = rewriteName entry unless (renamed == entry) $ do taken <- doesPathExist (dir </> renamed) when taken (ioError (userError ("rewriting a store hash would overwrite " <> (dir </> renamed)))) whileWritable dir (renamePath (dir </> entry) (dir </> renamed))-- | Change a regular file's bytes in place. On POSIX it never follows a-- link: the file is opened without following one, read and written-- through descriptors that name the inode the first open found, a second-- open that finds another refused, and made writable for the write-- through its own descriptor, its mode put back after: a link put at the-- name after the walk's @lstat@ fails the rewrite, where a path-based read-- and write would follow it out of the tree.rewriteRegularFile :: (BS.ByteString -> BS.ByteString) -> FilePath -> IO ()#if defined(mingw32_HOST_OS)rewriteRegularFile change path = do bytes <- BS.readFile path let updated = change bytes unless (updated == bytes) (whileWritable path (BS.writeFile path updated))#elserewriteRegularFile change path = bracket (openFd path ReadOnly noFollow) closeFd $ \reader -> do status <- getFdStatus reader unless (isRegularFile status) (ioError (userError ("'" <> path <> "' is not a regular file"))) -- The file is canonical by now, so only its owner may write it, and -- what its size says is the bytes there are to read. bytes <- readSize reader (fromIntegral (fileSize status)) let updated = change bytes unless (updated == bytes) $ bracket (setFdMode reader (fileMode status .|. ownerWriteMode)) (\() -> setFdMode reader (fileMode status)) $ \() -> bracket (openFd path WriteOnly noFollow) closeFd $ \writer -> do reopened <- getFdStatus writer unless (sameNode status reopened) (ioError (userError ("'" <> path <> "' was replaced while it was rewritten"))) writeWhole writer updated setFdSize writer (fromIntegral (BS.length updated)) where noFollow = defaultFileFlags {nofollow = True, cloexec = True}-- | Whether two statuses are of one inode.sameNode :: FileStatus -> FileStatus -> BoolsameNode one other = deviceID one == deviceID other && fileID one == fileID other-- | The bytes a read makes at most at once from a descriptor.readChunkBytes :: IntreadChunkBytes = 65536-- | Read a number of bytes from a descriptor, failing at an end before-- them.readSize :: Fd -> Int -> IO BS.ByteStringreadSize fd = go [] where go chunks 0 = pure (BS.concat (reverse chunks)) go chunks remaining = do chunk <- PosixBytes.fdRead fd (fromIntegral (min remaining readChunkBytes)) go (chunk : chunks) (remaining - BS.length chunk)-- | Write all of some bytes to a descriptor, from where it is.writeWhole :: Fd -> BS.ByteString -> IO ()writeWhole fd bytes | BS.null bytes = pure () | otherwise = do written <- PosixBytes.fdWrite fd bytes writeWhole fd (BS.drop (fromIntegral written) bytes)#endif-- | Replace a node with a fresh copy of itself, as upstream replaces a-- fixed-output output before it hashes one: a-- descriptor the builder passed out of its build names the old inode, which-- the copy leaves behind, so nothing written through it reaches what is-- registered. The copy is made beside the node ('freshCopyPath'), the-- node is removed and the copy renamed to its name, and the copy is-- removed should the replacement fail.replaceWithCopy :: FilePath -> IO ()replaceWithCopy path = do let copy = freshCopyPath path Dir.removePathForcibly copy ( do copyPathInto path copy Dir.removePathForcibly path renamePath copy path ) `onException` Dir.removePathForcibly copy-- | Where 'replaceWithCopy' copies a node, upstream's name beside it.freshCopyPath :: FilePath -> FilePathfreshCopyPath path = path <> ".tmp"-- | Point a symlink somewhere else. 'Dir.removePathForcibly' removes a file-- link or a directory link alike, which differ on Windows.replaceLink :: FilePath -> FilePath -> IO ()replaceLink path target = do linkOs <- OP.encodeFS path targetOs <- OP.encodeFS target Dir.removePathForcibly path created <- createSymlinkOfKind linkOs targetOs either (ioError . userError . T.unpack) pure created-- | Run an action on a path with write permission, then put its permissions-- back. A builder may mark its output read-only before registration does.whileWritable :: FilePath -> IO a -> IO awhileWritable path action = do permissions <- Dir.getPermissions path setPermissions path (Dir.setOwnerWritable True permissions) action `finally` setPermissions path permissions-- | Apply each replacement to bytes, in order. An empty needle matches-- nothing.rewriteBytes :: [(BS.ByteString, BS.ByteString)] -> BS.ByteString -> BS.ByteStringrewriteBytes rewrites bytes = foldl' (\acc (from, to) -> replaceInBytes from to acc) bytes rewritesreplaceInBytes :: BS.ByteString -> BS.ByteString -> BS.ByteString -> BS.ByteStringreplaceInBytes from to bytes | BS.null from = bytes | otherwise = BS.concat (pieces bytes) where pieces remaining = case BS.breakSubstring from remaining of (before, rest) | BS.null rest -> [before] | otherwise -> before : to : pieces (BS.drop (BS.length from) rest)-- | 'replaceInBytes' on a path component. The rest of the name is left as-- the operating system spelled it, so no decoding step can damage it.replaceInName :: String -> String -> String -> StringreplaceInName from to name = case name of _ | null from -> name [] -> [] c : rest -> case stripPrefix from name of Just after -> to ++ replaceInName from to after Nothing -> c : replaceInName from to rest-- | One scannable unit of a walked tree: a regular file's bytes read-- from disk, a symlink's target string, or an entry's name. The NAR-- serialization carries all three and upstream scans that serialization,-- so reference scanning covers all three - a link into a dependency-- (@bin\/tool -> \/nix\/store\/\<hash\>-dep\/tool@) references the-- dependency even when no file byte does.data ScanUnit = ScanFile !FilePath | ScanText !BS.ByteString-- | Collect the scannable units under a path: regular files, symlink-- targets and the names of a directory's entries, links never followed.-- A path that is itself a regular file or link is its own single unit.collectScanUnits :: FilePath -> IO [ScanUnit]collectScanUnits path = do node <- classifyWalkNode path case node of WalkSymlink -> do target <- Dir.getSymbolicLinkTarget path pure [ScanText (TE.encodeUtf8 (T.pack target))] WalkDirectory -> do entries <- listDirectory path nested <- concat <$> mapM (collectScanUnits . (path </>)) entries pure (map (ScanText . TE.encodeUtf8 . T.pack) entries ++ nested) WalkRegular -> pure [ScanFile path] WalkAbsent -> pure []-- | The bytes a 'ScanUnit' contributes to the scan.scanUnitBytes :: ScanUnit -> IO BS.ByteStringscanUnitBytes (ScanFile path) = BS.readFile pathscanUnitBytes (ScanText text) = pure text-- | Strict left fold over a list in IO. The accumulator is forced to-- WHNF each step - without it, the scan retains every scanned file's-- bytes in Set.union thunks until the end (peak memory ~ total tree-- size). Set's spine-strict nodes make WHNF force the whole union.foldlIO :: a -> [b] -> (a -> b -> IO a) -> IO afoldlIO z [] _ = pure zfoldlIO z (x : xs) f = do !acc <- f z x foldlIO acc xs f-- | Write an already-serialized derivation ATerm to its store path and make-- its metadata canonical ('canonicalizeMetadata'), as upstream Nix adds a-- @.drv@. Used to materialize the input @.drv@-- closure (root plus every transitive input) before a dependency-aware build:-- evaluation computes these ATerms and records them without writing them,-- so the build driver writes them here. A file that already holds exactly-- these bytes is kept as it is, read-only from the write that made it; one-- holding anything else, which an interrupted write can leave, is replaced.writeDrvAterm :: Store -> StorePath -> BS.ByteString -> IO ()writeDrvAterm store sp aterm = do let destPath = storePathToFilePath (stDir store) sp existing <- try (BS.readFile destPath) unless (either (\(_ :: IOException) -> False) (== aterm) existing) $ do Dir.removePathForcibly destPath -- Raw bytes, not text-mode IO: the path was computed from exactly these -- bytes, and a locale-dependent or newline-translating write would store -- bytes that no longer match their content address. BS.writeFile destPath aterm canonicalizeMetadata destPath-- | Serialize a derivation to ATerm, write it to the store, and register-- it: a @.drv@ is a store object like any other, so it gets a ValidPaths-- row with its NAR hash, its references and the text address its path is-- made from ('textAddress'). Reference scans may name a @.drv@ (one in a-- build's input closure, where a @drvPath@'s context puts it), and an-- unregistered referent fails the whole registration batch.writeDrv :: Store -> Derivation -> StorePath -> IO ()writeDrv store drv sp = do let aterm = toATerm drv writeDrvAterm store sp aterm reg <- registrationFor store sp Nothing (drvReferences drv) registerPath (stDB store) reg {prContentAddress = textAddress aterm}-- | The content address of a store object made from a text, as a @.drv@-- is: the SHA-256 of its bytes under the text method.textAddress :: BS.ByteString -> Maybe ContentAddresstextAddress = contentAddressFromParts TextMethod sha256Algo . sha256Digest-- | The algorithm every content address nova-nix makes a path from hashes-- with.sha256Algo :: Textsha256Algo = "sha256"-- | A @.drv@'s references: its input sources and input @.drv@ paths --- the same set upstream records when writing a derivation to the store.drvReferences :: Derivation -> [StorePath]drvReferences drv = drvInputSrcs drv ++ Map.keys (drvInputDrvs drv)-- | Write every recorded @.drv@ ATerm (keyed by its store-path text) to-- the store and register the whole closure in one batch: rows all land-- before edges ('registerPaths'), so references between the closure's-- own @.drv@ files resolve regardless of map order. Input SOURCES must-- already be registered - the build driver runs 'materializeEvalSources'-- first.---- Keys come from evaluation via 'storePathToText' so they always parse;-- an unparseable key is skipped defensively. The ATerm bytes were-- rendered by evaluation, so a re-parse failure is an invariant break-- and throws rather than registering a recipe with dropped references.writeDrvClosure :: Store -> Map Text BS.ByteString -> IO ()writeDrvClosure store closure = do regs <- mapM writeOne (Map.toList closure) registerPaths (stDB store) (catMaybes regs) where writeOne (pathText, aterm) = case parseStorePath defaultStoreDir pathText of Nothing -> pure Nothing Just sp -> do writeDrvAterm store sp aterm case fromATerm aterm of Right drv -> (\reg -> Just reg {prContentAddress = textAddress aterm}) <$> registrationFor store sp Nothing (drvReferences drv) Left err -> throwIO ( userError ( "writeDrvClosure: recorded ATerm for " <> T.unpack pathText <> " does not re-parse: " <> T.unpack err ) )-- ----------------------------------------------------------------------------- Exclusive creation-- ----------------------------------------------------------------------------- Every regular file and directory a tree materializes is created-- exclusively: a name already taken refuses the write instead of-- landing on the earlier entry. 'onDiskNameKey' predicts which-- siblings a folding volume merges, but only the volume knows its own-- fold table, so the create is what catches a pair the key misses.-- Upstream's restore creates the same way (@RestoreSink@ in-- fs-sink.cc at 2.24.9: @O_CREAT | O_EXCL@ for a regular file, a-- refused @create_directory@ for a directory), and the refusals carry-- its words ("Nix.Store.Exclusive"). Symlinks need nothing extra:-- @symlink(2)@ and CreateSymbolicLinkW never replace an existing name,-- and 'createSymlinkOfKind' words that refusal as upstream does.-- | Run a create that must find its name free, its refusal becoming the-- failure the given action describes. Only the refusal becomes a-- value: it is a property of the tree being written, where any other-- I\/O failure (permissions, a full disk) is one of the machine and-- stays an exception.refuseTaken :: IO Text -> IO a -> IO (Either Text a)refuseTaken describe create = do attempt <- tryJust (guard . isAlreadyExistsError) create either (const (Left <$> describe)) (pure . Right) attempt-- | Create a regular file of a materialized tree exclusively and write-- it through the handle, closed on the way out.withNewTreeFile :: OsPath -> (Handle -> IO a) -> IO (Either Text a)withNewTreeFile path write = bracket (openNewTreeFile path) (traverse_ hClose) (traverse write)-- | Open a regular file of a materialized tree, created exclusively.openNewTreeFile :: OsPath -> IO (Either Text Handle)openNewTreeFile path = refuseTaken (fileTakenMessage <$> OP.decodeFS path) (openNewBinaryFile path)-- | Create a directory of a materialized tree exclusively. Its parent-- is created first if missing, which only the root can need. A-- refusal asks what holds the name, as @create_directory@ does before-- it chooses between returning false and throwing.createTreeDirectory :: OsPath -> IO (Either Text ())createTreeDirectory path = do OsDir.createDirectoryIfMissing True (OP.takeDirectory path) refuseTaken describe (OsDir.createDirectory path) where describe = do occupant <- bool OccupiedByOther OccupiedByDirectory <$> OsDir.doesDirectoryExist path directoryTakenMessage occupant <$> OP.decodeFS path-- ----------------------------------------------------------------------------- NAR unpacking-- ----------------------------------------------------------------------------- | Unpack a NarEntry tree to a filesystem destination. Returns @Left@-- on an entry name or link target the host cannot hold-- ("Nix.Store.EntryName"); these can come from untrusted cache data, so-- a typed failure is used instead of a partial 'error'.---- Names and targets reach the filesystem as the bytes the NAR carries,-- as upstream's restore writes them on POSIX: the tree is walked in-- 'OsPath's, a POSIX path being bytes. Only the destination enters as-- a 'FilePath', spelled as every 'FilePath' API spells it.---- The sensitivity is the destination volume's ('stCaseSensitivity' for-- a store path) and decides whether case-variant siblings need the-- case-hack ('onDiskNameKey').---- Regular files and directories are written in one pass; symlinks are-- created in a second pass, after their targets are materialized. Windows-- symlinks are typed (file vs directory) and the NAR format does not record-- the target's kind, so the only reliable way to pick the flavor is to look-- at the target on disk - which may sort after the link within the tree.unpackNarEntry :: CaseSensitivity -> FilePath -> NAR.NarEntry -> IO (Either Text ())unpackNarEntry sensitivity path entry = do root <- OP.encodeFS path walked <- unpackTree sensitivity root entry case walked of Left err -> pure (Left err) Right links -> createSymlinks links-- | First unpack pass: write regular files and directories, recording-- symlinks as (link path, target) for the second pass.unpackTree :: CaseSensitivity -> OsPath -> NAR.NarEntry -> IO (Either Text [(OsPath, OsPath)])unpackTree sensitivity path entry = case entry of NAR.NarRegular isExec contents -> do OsDir.createDirectoryIfMissing True (OP.takeDirectory path) written <- withNewTreeFile path (`BS.hPut` contents) case written of Left err -> pure (Left err) Right () -> do when isExec (ExecBit.markExecutableOsPath path) pure (Right []) NAR.NarSymlink target -> fmap (\targetPath -> [(path, targetPath)]) <$> linkTargetPath target NAR.NarDirectory entries -> do created <- createTreeDirectory path case created of Left err -> pure (Left err) Right () -> unpackChildren sensitivity path entries-- | The on-disk identity a NAR entry name occupies on a volume of the-- given case sensitivity. Two sibling entries sharing a key name ONE-- file on that volume, so the unpack keeps them apart-- (@unpackNamedChildren@). A folding volume (the default APFS format,-- NTFS through Win32) keys a name by its uppercase; a sensitive one-- (Linux, a case-sensitive APFS volume) keys it byte-for-byte. The-- fold is per-character uppercase, which keeps apart the collisions-- real trees carry (@Makefile@\/@makefile@) but not every pair the-- volume folds: APFS reads U+00DF and U+1E9E as one name while-- 'toUpper' leaves U+00DF unchanged, so that pair takes two keys and-- the exclusive create refuses the second at the write, as-- upstream's restore does. The reverse miss (U+0131 uppercases to-- @I@, which APFS keeps distinct) only spells a name with a suffix it-- did not need. A name that is not UTF-8 has no characters to fold-- and keys as its bytes; no host whose volumes fold admits one-- ("Nix.Store.EntryName"), and the create would catch what the key-- missed. Win32 strips a trailing dot or space on create, which would-- merge names this key keeps apart, but Windows refuses such names-- before any is keyed.---- Upstream decides this per process, not per volume: its-- @use-case-hack@ setting defaults to on for Darwin and off elsewhere-- (archive.cc at 2.24.9), so a case-sensitive macOS volume still has-- @makefile@ restored as @makefile~nix~case~hack~1@ (observed from-- @nix-store --restore@ 2.33.2). The hack exists to work around-- folding, and a volume that does not fold needs none, so nova-nix-- keys by the probed answer and materializes true names there. The-- divergence is in on-disk spelling only: either tree re-serialises-- to the same NAR.onDiskNameKey :: CaseSensitivity -> BS.ByteString -> BS.ByteStringonDiskNameKey sensitivity name = case sensitivity of CaseSensitive -> name CaseInsensitive -> either (const name) (TE.encodeUtf8 . T.map toUpper) (TE.decodeUtf8' name)-- | The first pair of sibling names folding to the same on-disk file,-- if any: (earlier entry, colliding later entry).firstNameCollision :: CaseSensitivity -> [BS.ByteString] -> Maybe (BS.ByteString, BS.ByteString)firstNameCollision sensitivity = go Map.empty where go !_ [] = Nothing go !seen (name : rest) = let key = onDiskNameKey sensitivity name in case Map.lookup key seen of Just earlier -> Just (earlier, name) Nothing -> go (Map.insert key name seen) rest-- | Whether a tree on a volume of the given case sensitivity is read-- back with the case-hack suffix stripped ('volumeCaseHack'). Where-- it is, an INCOMING entry name carrying the suffix must be rejected:-- materialized verbatim it would re-serialise under a different name-- and fail its own hash recheck. Upstream's restore accepts such a-- name and its dump then strips the suffix (archive.cc at 2.24.9), so-- the tree fails there as well, only later; refusing at the write-- boundary surfaces the same failure before anything is materialized.-- A volume that keeps names apart reads every name as spelled, so the-- name materializes and round-trips there.volumeStripsCaseHack :: CaseSensitivity -> BoolvolumeStripsCaseHack sensitivity = volumeCaseHack sensitivity == NAR.CaseHackEnabled-- | Refuse an entry name before any sibling is written: one the host-- cannot hold ('checkEntryName'), or one carrying the case-hack suffix-- where the destination volume's serialiser would strip it.admitEntryName :: CaseSensitivity -> BS.ByteString -> Either Text ()admitEntryName sensitivity name = do checkEntryName hostNameRules name when (volumeStripsCaseHack sensitivity && NAR.caseHackSuffix `BS.isInfixOf` name) $ Left ("NAR entry name contains the case-hack suffix: " <> shownBytes name)-- | The case-hacked disk name for the given occurrence of a key.caseHackName :: BS.ByteString -> Int -> BS.ByteStringcaseHackName name occurrence = name <> NAR.caseHackSuffix <> BS8.pack (show occurrence)-- | Disk names for a sibling list on a volume of the given case-- sensitivity, WITHOUT per-directory case sensitivity: upstream's-- case-hack where names fold, every name as spelled where they do not.-- The first occurrence of each key keeps its spelling; every later-- name with the same key gains the reversible suffix and a per-name-- counter, which the serialiser strips on the way back out-- ('volumeCaseHack'). Order is preserved; result pairs are (NAR-- name, on-disk name).caseHackDiskNames :: CaseSensitivity -> [BS.ByteString] -> [(BS.ByteString, BS.ByteString)]caseHackDiskNames sensitivity = reverse . snd . foldl' step (Map.empty, []) where step (!seen, !acc) name = let key = onDiskNameKey sensitivity name in case Map.lookup key seen of Nothing -> (Map.insert key (0 :: Int) seen, (name, name) : acc) Just occurrences -> let next = occurrences + 1 in (Map.insert key next seen, (name, caseHackName name next) : acc)-- | Unpack directory children. Entry names arrive as the raw bytes-- the NAR carries, and every sibling's name is admitted-- ('admitEntryName') before the first is written, so a name the host-- cannot hold leaves no partial directory behind it.unpackChildren :: CaseSensitivity -> OsPath -> [(BS.ByteString, NAR.NarEntry)] -> IO (Either Text [(OsPath, OsPath)])unpackChildren sensitivity path entries = case traverse_ (admitEntryName sensitivity . fst) entries of Left err -> pure (Left err) Right () -> unpackNamedChildren sensitivity path entries-- | Unpack admitted directory children.---- On a volume the probe reports sensitive (Linux, case-sensitive APFS)-- no two sibling names share an on-disk identity and every entry-- materializes as spelled. Sibling names folding to one on-disk name-- (NTFS, default APFS) take the TRUE-NAME path when the platform-- provides one: the just-created empty directory gains NTFS-- per-directory case sensitivity and the tree materializes under its-- real names. Where the flag is unavailable (a non-NTFS store volume,-- a folding APFS volume) the collision falls back to upstream's-- case-hack renaming, which the volume's serialiser reverses. Either-- way a registered path re-serialises to its NAR byte-for-byte - the-- substituter's on-disk recheck verifies it. The name spelled on disk-- is the one the host is asked to hold, suffix included.unpackNamedChildren :: CaseSensitivity -> OsPath -> [(BS.ByteString, NAR.NarEntry)] -> IO (Either Text [(OsPath, OsPath)])unpackNamedChildren sensitivity path entries = do diskNames <- resolveDiskNames walkChildren (zip diskNames (map snd entries)) where names = map fst entries resolveDiskNames = case firstNameCollision sensitivity names of Nothing -> pure names Just _ -> do trueNames <- trySetCaseSensitiveDir =<< OP.decodeFS path pure ( if trueNames then names else map snd (caseHackDiskNames sensitivity names) ) walkChildren [] = pure (Right []) walkChildren ((diskName, child) : rest) = do spelled <- entryNamePath diskName case spelled of Left err -> pure (Left err) Right component -> do result <- unpackTree sensitivity (path OP.</> component) child case result of Left err -> pure (Left err) Right links -> do restResult <- walkChildren rest case restResult of Left err -> pure (Left err) Right moreLinks -> pure (Right (links <> moreLinks))-- | Second unpack pass: create the recorded symlinks in dependency-- order - each link is created after every pending link its target-- resolves at or through - so the Windows link flavor (file vs-- directory) is read off the real target with one probe per link.-- Links on a dependency cycle have no knowable kind and default to file-- links, as dangling links do.createSymlinks :: [(OsPath, OsPath)] -> IO (Either Text ())createSymlinks pending = createAll (orderLinks pending) where createAll [] = pure (Right ()) createAll (link : rest) = do made <- uncurry createSymlink link case made of Left err -> pure (Left err) Right () -> createAll rest-- | Order pending links so each follows every pending link its target-- path resolves at or through: the target itself, or a link standing on-- one of the target's ancestor directories. Purely textual over the-- same @takeDirectory linkPath \</\> target@ resolution 'createSymlink'-- probes - no filesystem access. Kahn's ordering, deterministic:-- ready links leave in input order, and cycle members keep input order-- at the end. Exported for testing (the ordering property is pure).orderLinks :: [(OsPath, OsPath)] -> [(OsPath, OsPath)]orderLinks pending = let indexed = zip [0 :: Int ..] pending linkByIndex = Map.fromList indexed indexByKey = Map.fromList [(normalisedComponents linkPath, i) | (i, (linkPath, _)) <- indexed] -- The pending links this link's resolved target lands on or -- passes through (every nonempty component prefix). depsOf (linkPath, target) = let resolved = normalisedComponents (OP.takeDirectory linkPath OP.</> target) in Set.fromList [j | prefix <- drop 1 (inits resolved), Just j <- [Map.lookup prefix indexByKey]] dependsOn = Map.fromList [(i, depsOf link) | (i, link) <- indexed] dependents = Map.fromListWith (flip (++)) [(dep, [i]) | (i, deps) <- Map.toList dependsOn, dep <- Set.toList deps] initialCounts = Map.map Set.size dependsOn initialReady = [i | (i, count) <- Map.toList initialCounts, count == 0] -- Kahn's ordering with a two-list queue (amortized O(1) pops). run !emittedRev !counts front back = case front of [] -> case back of [] -> reverse emittedRev _ -> run emittedRev counts (reverse back) [] (i : rest) -> let (updatedCounts, readied) = release counts (Map.findWithDefault [] i dependents) in run (i : emittedRev) updatedCounts rest (readied ++ back) release !counts deps = case deps of [] -> (counts, []) (d : more) -> let updated = Map.adjust (subtract 1) d counts (finalCounts, readied) = release updated more in (finalCounts, [d | Map.lookup d updated == Just 0] ++ readied) emittedOrder = run [] initialCounts initialReady [] emittedSet = Set.fromList emittedOrder cycleRemainder = [link | (i, link) <- indexed, not (Set.member i emittedSet)] in [link | i <- emittedOrder, Just link <- [Map.lookup i linkByIndex]] ++ cycleRemainder-- | Path components with @.@ dropped and @..@ collapsed textually - the-- spelling-insensitive key that matches a link target against pending-- link paths ('OP.splitDirectories' accepts both separator spellings-- on Windows). A @..@ with nothing left to pop stays, matching no real-- path.normalisedComponents :: OsPath -> [OsPath]normalisedComponents path = reverse (foldl' step [] (OP.splitDirectories path)) where step stack comp | comp == currentDirectory = stack | comp == parentDirectory = case stack of (top : rest) | top /= parentDirectory -> rest _ -> comp : stack | otherwise = comp : stack currentDirectory = OP.pack [dot] parentDirectory = OP.pack [dot, dot] dot = OP.unsafeFromChar '.'-- | Create one unpacked symlink, parents first, with the Windows flavor-- read off the target ('createSymlinkOfKind'). A creation failure is-- loud, and failing lets the caller fall back to a local build.createSymlink :: OsPath -> OsPath -> IO (Either Text ())createSymlink linkPath target = do OsDir.createDirectoryIfMissing True (OP.takeDirectory linkPath) createSymlinkOfKind linkPath target-- ----------------------------------------------------------------------------- Streaming NAR unpacking-- ----------------------------------------------------------------------------- | Where a node of an archive lies under the destination it unpacks at.data UnpackPlace = -- | The destination itself. UnpackRoot | -- | A path below the destination, relative to it. BelowRoot !OsPath-- | A place as a path under a destination.placedUnder :: OsPath -> UnpackPlace -> OsPathplacedUnder root = \case UnpackRoot -> root BelowRoot relative -> root OP.</> relative-- | The place of an entry of the directory at a place.entryPlace :: UnpackPlace -> OsPath -> UnpackPlaceentryPlace place component = BelowRoot $ case place of UnpackRoot -> component BelowRoot relative -> relative OP.</> component-- | One open directory in the streaming unpack: its place and the-- sibling names materialized so far, keyed by their on-disk identity-- ('onDiskNameKey') for collision handling.data UnpackFrame = UnpackFrame { ufPlace :: !UnpackPlace, ufSeen :: !(Map BS.ByteString Int) }-- | Mutable state behind a t'NarUnpackSink' - the same deliberate IO-- boundary as the store's other materializers. 'nusTargets' is the-- stack of places the NEXT node materializes at: the destination at the-- root, plus one pushed per open directory entry. A symlink is recorded-- by its place, so it can be made under the destination or wherever the-- tree is moved ('moveNarUnpack').data NarUnpackState = NarUnpackState { -- | The destination volume's case sensitivity, keying sibling -- names exactly as the strict path does. nusCaseSensitivity :: !CaseSensitivity, nusRoot :: !OsPath, nusFrames :: ![UnpackFrame], nusTargets :: ![UnpackPlace], nusOpen :: !(Maybe (Handle, OsPath, Bool)), nusLinks :: ![(UnpackPlace, OsPath)] }-- | A push sink materializing 'Stream.NarEvent's under a destination-- path as they arrive, so a substituted NAR unpacks in the same pass-- that downloads it. Semantics mirror 'unpackNarEntry' - the same-- name bytes and host checks, executable bit, and second-pass-- symlink creation - with one divergence: sibling names colliding on-- a folding volume always take upstream's case-hack renaming, never-- the NTFS true-name path, because per-directory case sensitivity can-- only be enabled on an EMPTY directory and a stream cannot know a-- directory's siblings before materializing the first. On a volume-- the probe reports sensitive nothing collides, as in the strict path.-- Upstream's own streaming restore behaves identically, and the-- substituter's on-disk recheck proves the tree re-serialises to its-- NAR either way.newtype NarUnpackSink = NarUnpackSink (IORef NarUnpackState)-- | A sink for one NAR unpack under the given destination path, on a-- volume of the given case sensitivity.newNarUnpackSink :: CaseSensitivity -> FilePath -> IO NarUnpackSinknewNarUnpackSink sensitivity destPath = do root <- OP.encodeFS destPath NarUnpackSink <$> newIORef (NarUnpackState sensitivity root [] [UnpackRoot] Nothing [])-- | Feed one event. On 'Left' the partial tree stays for the caller-- to remove - 'abortNarUnpack' first, so no handle stays open on it.sinkNarEvent :: NarUnpackSink -> Stream.NarEvent -> IO (Either Text ())sinkNarEvent (NarUnpackSink ref) event = do narState <- readIORef ref outcome <- applyNarEvent narState event case outcome of Left err -> pure (Left err) Right updated -> do writeIORef ref updated pure (Right ())-- | One event's filesystem effects plus the state that follows it.-- The stream machine already proved grammar well-formedness, so the-- mismatch arms guard sink-state desync, not archive syntax.applyNarEvent :: NarUnpackState -> Stream.NarEvent -> IO (Either Text NarUnpackState)applyNarEvent narState event = case event of Stream.EventRegularBegin isExec _declaredSize -> withNodeTarget narState $ \_ path -> do OsDir.createDirectoryIfMissing True (OP.takeDirectory path) opened <- openNewTreeFile path pure (fmap (\fileHandle -> narState {nusOpen = Just (fileHandle, path, isExec)}) opened) Stream.EventRegularChunk slice -> case nusOpen narState of Nothing -> pure (Left "NAR stream sink: file contents outside an open file") Just (fileHandle, _, _) -> do BS.hPut fileHandle slice pure (Right narState) Stream.EventRegularEnd -> case nusOpen narState of Nothing -> pure (Left "NAR stream sink: file close without an open file") Just (fileHandle, path, isExec) -> do hClose fileHandle when isExec (ExecBit.markExecutableOsPath path) pure (Right narState {nusOpen = Nothing}) Stream.EventSymlink targetBytes -> withNodeTarget narState $ \place _ -> fmap (\target -> narState {nusLinks = (place, target) : nusLinks narState}) <$> linkTargetPath targetBytes Stream.EventDirectoryBegin -> withNodeTarget narState $ \place path -> do created <- createTreeDirectory path pure (narState {nusFrames = UnpackFrame place Map.empty : nusFrames narState} <$ created) Stream.EventEntryBegin name -> case nusFrames narState of [] -> pure (Left "NAR stream sink: entry outside a directory") (frame : outer) -> case admitEntryName (nusCaseSensitivity narState) name of Left err -> pure (Left err) Right () -> do -- Sequential case-hack: the disk name of entry N depends only -- on the siblings before it, the same sequence -- 'caseHackDiskNames' folds over a whole list. let key = onDiskNameKey (nusCaseSensitivity narState) name (diskName, occurrences) = case Map.lookup key (ufSeen frame) of Nothing -> (name, 0) Just seen -> (caseHackName name (seen + 1), seen + 1) updatedFrame = frame {ufSeen = Map.insert key occurrences (ufSeen frame)} spelled <- entryNamePath diskName pure $ fmap ( \component -> let !place = entryPlace (ufPlace frame) component in narState { nusFrames = updatedFrame : outer, nusTargets = place : nusTargets narState } ) spelled Stream.EventEntryEnd -> case nusTargets narState of -- The root destination never pops; only entry-pushed paths do. (_ : rest@(_ : _)) -> pure (Right narState {nusTargets = rest}) _ -> pure (Left "NAR stream sink: entry close without an open entry") Stream.EventDirectoryEnd -> case nusFrames narState of [] -> pure (Left "NAR stream sink: directory close without an open directory") (_ : outer) -> pure (Right narState {nusFrames = outer})-- | Run an action on the place the next node materializes at, and its-- path under the destination.withNodeTarget :: NarUnpackState -> (UnpackPlace -> OsPath -> IO (Either Text NarUnpackState)) -> IO (Either Text NarUnpackState)withNodeTarget narState act = case nusTargets narState of (place : _) -> act place (placedUnder (nusRoot narState) place) [] -> pure (Left "NAR stream sink: node with no destination")-- | The symlinks an unpack recorded, in archive order: where each lies-- under the destination the archive unpacked at, and its target. A-- link's Windows flavour is read off what its target reaches from where-- the link is made, so they are made once the tree lies where it stays-- ('moveNarUnpack').newtype NarLinks = NarLinks [(UnpackPlace, OsPath)]-- | Close an unpack after 'Stream.NarDone': every node must be closed.-- The symlinks it recorded are answered, not made.closeNarUnpack :: NarUnpackSink -> IO (Either Text NarLinks)closeNarUnpack (NarUnpackSink ref) = do narState <- readIORef ref pure $ case (nusOpen narState, nusFrames narState) of (Just _, _) -> Left "NAR stream sink: stream ended inside a file" (Nothing, _ : _) -> Left "NAR stream sink: stream ended inside a directory" (Nothing, []) -> Right (NarLinks (reverse (nusLinks narState)))-- | Move a tree an archive unpacked from the destination it unpacked at-- to the path given ('moveOutput'), and make the symlinks it records-- there, each where it lies in the tree, in the dependency order and with-- the flavour probing of the strict path's second pass-- ('createSymlinks'). An archive that is a symlink leaves nothing at its-- destination to move, and its link is made at the path.moveNarUnpack :: FilePath -> FilePath -> NarLinks -> IO (Either Text ())moveNarUnpack from to links@(NarLinks recorded) = do case [target | (UnpackRoot, target) <- recorded] of [] -> moveOutput from to _ : _ -> pure () OP.encodeFS to >>= \root -> createLinksUnder root links-- | Make an unpack's symlinks under a destination.createLinksUnder :: OsPath -> NarLinks -> IO (Either Text ())createLinksUnder root (NarLinks links) = createSymlinks [(placedUnder root place, target) | (place, target) <- links]-- | Finish after 'Stream.NarDone' where the archive unpacked: every node-- must be closed ('closeNarUnpack'), then the recorded symlinks are made-- at the sink's own destination.finishNarUnpack :: NarUnpackSink -> IO (Either Text ())finishNarUnpack sink@(NarUnpackSink ref) = do root <- nusRoot <$> readIORef ref closeNarUnpack sink >>= either (pure . Left) (createLinksUnder root)-- | Close any open handle so the caller can remove the partial tree;-- Windows will not delete a file a handle still holds open.abortNarUnpack :: NarUnpackSink -> IO ()abortNarUnpack (NarUnpackSink ref) = do narState <- readIORef ref case nusOpen narState of Nothing -> pure () Just (fileHandle, _, _) -> hClose fileHandle `catch` \(_ :: IOException) -> pure () writeIORef ref narState {nusOpen = Nothing}-- | Why a streamed archive stopped short of its end.data NarStreamFailure = -- | The store refused what the archive holds (a name, a taken -- path): a property of the archive, not of how it arrived. NarStreamRefused !Text | -- | The bytes do not parse as a NAR. A truncated or torn transfer -- reads the same as a malformed archive. NarStreamMalformed !Text deriving (Eq, Show)-- | Where a NAR fed to 'sinkNarStream' ends.data ArchiveEnd = -- | At the end of its input: a byte after the root node's close fails -- the archive as malformed. AtEndOfInput | -- | At the root node's close: the input after it is left unread, as -- upstream's restore leaves the rest of the source it reads a NAR -- from. AtRootClose deriving (Eq, Show)-- | An archive being unpacked into a sink as its chunks arrive, ending-- where an 'ArchiveEnd' says: the parser's state, and the SHA-256 and-- size of the bytes it has consumed. The last chunk fed is held back-- from the digest until the parser asks for another or finishes, since-- the input after the root node's close is a suffix of that chunk and-- not the archive's. The result type is the parser's, which only says-- what input follows the archive's end.data NarFeed = forall r. NarFeed !(r -> BS.ByteString) !Hash.HashContext !Int !BS.ByteString !(Stream.NarStep r)-- | What feeding an archive a chunk comes to.data NarFed = -- | The archive goes on past what has been fed, and is fed next here. NarGoesOn !NarFeed | -- | The archive ended: its SHA-256, its size, and the bytes of the -- last chunk fed that follow its end. NarEnded !Hash.NixHash !Int !BS.ByteString-- | An archive's parser before its first byte, ending where the-- 'ArchiveEnd' says.startNarFeed :: ArchiveEnd -> NarFeedstartNarFeed = \case AtEndOfInput -> NarFeed (const BS.empty) Hash.hashInit 0 BS.empty Stream.narStream AtRootClose -> NarFeed id Hash.hashInit 0 BS.empty Stream.narPrefix-- | Feed an archive its next chunk, the empty chunk for the end of its-- input, each event that completes going to the sink. The recorded-- symlinks are not created yet ('finishNarUnpack'), so a caller checks-- the digest before any link exists. On a failure the sink is already-- aborted.feedNar :: NarUnpackSink -> NarFeed -> BS.ByteString -> IO (Either NarStreamFailure NarFed)feedNar sink (NarFeed unconsumed context count held step) chunk = advance (Just chunk) context count held step `onException` abortNarUnpack sink where -- The chunk given is pending until the parser first asks for input; -- once it has it, the parser is run up to its next request. advance pending !hashing !consumed kept current = case current of Stream.NarAwait continue -> case pending of Just next -> advance Nothing (Hash.hashUpdate hashing kept) (consumed + BS.length kept) next (continue next) Nothing -> pure (Right (NarGoesOn (NarFeed unconsumed hashing consumed kept current))) Stream.NarYield event next -> do sunk <- sinkNarEvent sink event either (stopWith . NarStreamRefused) (const (advance pending hashing consumed kept next)) sunk Stream.NarFail msg -> stopWith (NarStreamMalformed (T.pack msg)) Stream.NarDone result -> let after = unconsumed result archived = BS.take (BS.length kept - BS.length after) kept in pure (Right (NarEnded (Hash.hashFinalize (Hash.hashUpdate hashing archived)) (consumed + BS.length archived) (after <> fold pending))) stopWith failure = Left failure <$ abortNarUnpack sink-- | Tell an archive its input has ended, and take its SHA-256 and size-- where it ends there. A parser that still asks for input is refused as-- one that does not end does; nova-cache's never asks after the end. On-- a failure the sink is already aborted.endNar :: NarUnpackSink -> NarFeed -> IO (Either NarStreamFailure (Hash.NixHash, Int))endNar sink feed = feedNar sink feed BS.empty >>= \case Left failure -> pure (Left failure) Right (NarEnded digest size _) -> pure (Right (digest, size)) Right (NarGoesOn _) -> Left (NarStreamMalformed "the archive goes on past the end of its input") <$ abortNarUnpack sink-- | Feed a chunk source through the streaming NAR parser into a sink-- ('feedNar'), hashing and counting exactly the bytes the parser-- consumes, and return the archive's SHA-256 and size once it ends where-- the 'ArchiveEnd' says it does. No chunk is pulled after the archive-- ends. On a failure the sink is already aborted.sinkNarStream :: ArchiveEnd -> NarUnpackSink -> IO BS.ByteString -> IO (Either NarStreamFailure (Hash.NixHash, Int))sinkNarStream end sink source = pull (startNarFeed end) `onException` abortNarUnpack sink where pull feed = source >>= feedNar sink feed >>= \case Left failure -> pure (Left failure) Right (NarGoesOn next) -> pull next Right (NarEnded digest size _) -> pure (Right (digest, size))-- | Hold an archive's hash and size, as read, to what its path's info-- claims: the hash first, then the size, as upstream's import of a NAR-- checks them, each refused in upstream's words ('narHashMismatch',-- 'narSizeMismatch') naming the path as given.checkNarClaim :: Text -> Hash.NixHash -> Integer -> Hash.NixHash -> Integer -> Either Text ()checkNarClaim path claimedHash claimedSize gotHash gotSize | gotHash /= claimedHash = Left (narHashMismatch path claimedHash gotHash) | gotSize /= claimedSize = Left (narSizeMismatch path claimedSize gotSize) | otherwise = Right ()-- | Upstream's refusal of an archive whose hash is not the one its-- path's info claims, both in SRI form.narHashMismatch :: Text -> Hash.NixHash -> Hash.NixHash -> TextnarHashMismatch path (Hash.NixHash specified) (Hash.NixHash got) = importMismatch "hash" path (sri specified) (sri got) where sri digest = narHashAlgorithm <> "-" <> B64.encode digest-- | Upstream's refusal of an archive whose size is not the one its-- path's info claims.narSizeMismatch :: Text -> Integer -> Integer -> TextnarSizeMismatch path specified got = importMismatch "size" path (T.pack (show specified)) (T.pack (show got))-- | The shape upstream gives both refusals: what mismatched, the path,-- and what was specified above what was got.importMismatch :: Text -> Text -> Text -> Text -> TextimportMismatch what path specified got = what <> " mismatch importing path '" <> path <> "';\n specified: " <> specified <> "\n got: " <> got-- | The algorithm a NAR hash is taken with, as SRI names it.narHashAlgorithm :: TextnarHashAlgorithm = "sha256"-- ----------------------------------------------------------------------------- Paths copied in-- ----------------------------------------------------------------------------- | Whether a path copied into the store must be signed, as upstream's-- store asks under @require-sigs@.data SignatureRequirement = -- | One of these keys must have signed the path's info, unless its -- content address makes its path ('addressMakesPath'). RequireSignature ![Signing.PublicKey] | -- | It is taken unsigned: @require-sigs@ is off, or the path comes -- from a client the daemon trusts that asks it not to check. SignaturesNotRequired-- | What a content address and the references it is stated with make of-- the path they are stated for ('addressMakesPath').data AddressedPath = -- | Exactly the path. MakesItsPath | -- | Another path. MakesAnotherPath | -- | No path: a fixed address other than a NAR's SHA-256 with -- references, its own path among them or not, refused in upstream's -- words as upstream refuses to make a path from it. MakesNoPath !Text deriving (Eq, Show)-- | What a content address and the references it is stated with make of-- a path, as upstream makes a path from a content address: a text by its-- SHA-256 with its references; a NAR by its SHA-256 as a @source@ path-- with its references, and @self@ when it references itself; any other-- fixed address only with no references at all.addressMakesPath :: StorePath -> [StorePath] -> ContentAddress -> AddressedPathaddressMakesPath sp refs address = case caMethod address of TextMethod -> madeIf (caAlgo address == sha256Algo && makeTextPath name digest refs == Right sp) FixedMethod NarIngestion | caAlgo address == sha256Algo -> madeIf (makeStorePath defaultStoreDir sourceType digest name == Right sp) FixedMethod method | not (null refs) -> MakesNoPath (fixedReferencesRefusal name) | otherwise -> madeIf (makeFixedOutputPath name (caAlgo address) method digest == Right sp) where madeIf made | made = MakesItsPath | otherwise = MakesAnotherPath name = spName sp digest = caDigest address self = sp `elem` refs others = Set.toAscList (Set.delete sp (Set.fromList refs)) sourceType = "source" <> T.concat [":" <> storePathToText defaultStoreDir r | r <- others] <> (if self then ":self" else "")-- | Upstream's refusal to make a path, of the name given, from a fixed-- content address other than a NAR's SHA-256 that comes with references.fixedReferencesRefusal :: Text -> TextfixedReferencesRefusal name = "fixed output derivation '" <> name <> "' is not allowed to refer to other store paths.\nYou may need to use the 'unsafeDiscardReferences' derivation attribute, see the manual for more details."-- | Upstream's warning of a stated content address that does not make its-- path. Upstream prints it, @warning:@ and all, at its error level, each-- time it tests the address: when it counts a path's signatures, and when-- it registers the path.notContentAddressed :: StorePath -> TextnotContentAddressed sp = "warning: path '" <> storePathToText defaultStoreDir sp <> "' claims to be content-addressed but isn't"-- | Whether a path may be registered with the content address it is stated-- with, as upstream's store decides as it registers one: an address that-- makes no path is refused as 'MakesNoPath' says, and one that makes-- another path is warned of at the error level ('notContentAddressed') and-- refused as claiming to be what it is not.addressRegistrable :: Logger -> StorePath -> [StorePath] -> ContentAddress -> IO (Either Text ())addressRegistrable logger sp refs address = case addressMakesPath sp refs address of MakesItsPath -> pure (Right ()) MakesNoPath refusal -> pure (Left refusal) MakesAnotherPath -> do logAt logger LevelError (notContentAddressed sp) pure (Left ("cannot add path '" <> storePathToText defaultStoreDir sp <> "' to the Nix store because it claims to be content-addressed but isn't"))-- ----------------------------------------------------------------------------- Eval source materialization-- ----------------------------------------------------------------------------- | Restore the copies of eval-coerced paths into the store and register-- them. Each entry is a copy's fixed-output store path with the-- path-value text of the tree evaluation hashed for it, the path with its-- symlinks resolved (text only: evaluation writes no copy of a coerced-- path). Each entry not already valid is adopted when the tree already at-- its path reproduces its address, and otherwise restored from a dump of-- that tree ('restoreSource'); its metadata is made canonical-- ('canonicalizeMetadata'), and it is registered. A source carries no-- references. A store upstream Nix's database may also manage is-- refused before any entry is looked at, by an-- 'IOException' carrying the reason ("Nix.Store.Upstream"): a tree on-- disk with no row here is cleared unless it reproduces its address.materializeEvalSources :: Store -> Map StorePath Text -> IO ()materializeEvalSources store sourceCache = do refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (stDir store) maybe (mapM_ adopt (Map.toList sourceCache)) (throwIO . userError . T.unpack) refusal where -- Each source registers IMMEDIATELY after its restore (sources carry -- no cross-references, so there is nothing to batch). A tree already -- on disk is adopted only after verification: its NAR digest must -- reproduce the store path being registered - an interrupted earlier -- restore leaves a partial tree, and registering it as-is validates -- content that does not match its address. A verified adoption keeps -- the files' bytes (rewriting a read-only tree fails on Windows and -- would wedge the store permanently) and has only their metadata made -- canonical, since the tree may be one a restore left before it got -- that far, or one an evaluation wrote; a failed one clears and -- restores. -- The whole check-then-act runs under the path's cross-process -- lock, validity re-checked once held, so of two processes -- materializing the same source the second finds the path valid -- rather than clearing the tree the first registered. Same protocol -- as the builder's withOutputLocks. adopt (sp, srcText) = withPathLock (stLogger store) (stDir store) sp $ \_ -> do valid <- isValid store sp unless valid $ do let dest = storePathToFilePath (stDir store) sp onDisk <- doesPathExist dest adopted <- if onDisk then adoptedTreeAddress (stCaseSensitivity store) dest sp else pure Nothing reg <- case adopted of Just address -> do canonicalizeMetadata dest (\reg -> reg {prContentAddress = Just address}) <$> registrationFor store sp Nothing [] Nothing -> do when onDisk (Dir.removePathForcibly dest) restoreSource store srcText sp >>= either (refuse (storePathToText defaultStoreDir sp)) pure registerPath (stDB store) reg refuse spText reason = throwIO (userError (T.unpack ("refusing to register " <> spText <> ": " <> reason)))-- | Restore a source tree at the store path evaluation named it by,-- from a dump of the source, as upstream's @addToStoreFromDump@-- restores the dump it hashed (@restorePath@, local-store.cc at-- 2.24.9) rather than copying files: the source's NAR streams out of-- the walk, through the hash and into an unpack sink in one pass, so a-- sibling pair the store's volume folds takes the case-hack on the way-- in, and no file's contents are ever held whole. The source is read-- as evaluation read it to name the path: the tree its resolved text-- names, store text in this store's directory ('storeTextToFilePath'),-- under the case-hack that text calls for ('pathCaseHack'); the restored-- tree is read as a store path, under its volume's.---- Evaluation hashed the source earlier, so the dump is held to that-- address before any link is created: a source that changed in between-- is refused, never registered under a hash its bytes no longer have.-- The restored tree is then rechecked on disk, as the substituter-- rechecks an unpacked one, since the volume decides the final-- spelling of every name. Any failure removes the tree.restoreSource :: Store -> Text -> StorePath -> IO (Either Text PathRegistration)restoreSource store srcText sp = do outcome <- restore `onException` Dir.removePathForcibly dest either (\reason -> Left reason <$ Dir.removePathForcibly dest) (pure . Right) outcome where dest = storePathToFilePath (stDir store) sp src = storeTextToFilePath (stDir store) srcText caseHack = pathCaseHack (stCaseSensitivity store) srcText restore = do sink <- newNarUnpackSink (stCaseSensitivity store) dest streamed <- ExecBit.withNarSource caseHack src (sinkNarStream AtEndOfInput sink) case streamed of Left (NarStreamRefused reason) -> pure (Left reason) Left (NarStreamMalformed reason) -> pure (Left ("the dump of " <> srcText <> " does not parse: " <> reason)) Right (digest, size) -> case sourceAddress sp digest of Nothing -> do abortNarUnpack sink pure (Left (srcText <> " changed after evaluation hashed it, so it no longer reproduces its store path; re-evaluate")) Just address -> do finished <- finishNarUnpack sink either (pure . Left) (const (sealAndRecheck digest size address)) finished sealAndRecheck digest size address = do canonicalizeMetadata dest onDisk <- ExecBit.narHashOfPath (volumeCaseHack (stCaseSensitivity store)) dest pure $ if onDisk /= digest then Left "the restored tree does not reproduce its store path on disk" else Right PathRegistration { prPath = sp, prNarHash = Hash.formatNixHash digest, prNarSize = size, prDeriver = Nothing, prReferences = [], prUltimate = NotUltimate, prSignatures = Set.empty, prContentAddress = Just address, prRegistrationTime = RegisteredNow }-- | The content address a recursive NAR digest gives a store path, when-- the digest and the path's own name derive exactly that path, as a-- @source@ path's address is derived.sourceAddress :: StorePath -> Hash.NixHash -> Maybe ContentAddresssourceAddress sp (Hash.NixHash digest) | makeFixedOutputPath (spName sp) sha256Algo NarIngestion digest == Right sp = contentAddressFromParts (FixedMethod NarIngestion) sha256Algo digest | otherwise = Nothing-- | Register the store objects evaluation wrote: makes each one's-- metadata canonical ('canonicalizeMetadata') and records it in the DB.-- Batched so a write referring to another resolves. Covers every-- eval-time writer, not only @builtins.toFile@:-- an unregistered write reaches @drvInputSrcs@ and fails the build.materializeEvalStoreWrites :: Store -> Map Text ([StorePath], StoreWriteMode) -> IO ()materializeEvalStoreWrites store storeWrites = do regs <- catMaybes <$> mapM prepare (Map.toList storeWrites) unless (null regs) (registerPaths (stDB store) regs) where -- Checked and sealed under the path's lock, validity re-checked -- once held, so a peer mid-producing the same path is waited out -- rather than torn-read (and refused). The lock releases before -- the batched registration: registration is an upsert over content -- both holders verified reproduces the same path, so the winner -- and loser record the same row. prepare (spText, (refs, mode)) = case parseStorePath defaultStoreDir spText of Nothing -> pure Nothing Just sp -> withPathLock (stLogger store) (stDir store) sp $ \_ -> do valid <- isValid store sp if valid then pure Nothing else do let dest = storePathToFilePath (stDir store) sp onDisk <- doesPathExist dest -- Absent means removed since eval; nothing to register. if not onDisk then pure Nothing else do -- The writers verified (or rewrote) this content at -- write time; a mismatch here means the tree changed -- between evaluation and registration, and registering -- it would record a hash its bytes do not have, then -- seal the lie. Refuse loudly instead. address <- writtenAddress (stCaseSensitivity store) dest sp refs mode case address of Nothing -> throwIO ( userError ( "refusing to register " <> T.unpack spText <> ": the on-disk content does not reproduce its store path; " <> "delete the path and re-evaluate" ) ) Just reproduced -> do canonicalizeMetadata dest (\reg -> Just reg {prContentAddress = Just reproduced}) <$> registrationFor store sp Nothing refs-- | Add a tree, given as its NAR, as the path the SHA-256 of the NAR, a-- name and the store paths it references make ('makeSourcePath'), and-- answer the path: upstream's @addToStore@ of a dump under @NixArchive@-- and SHA-256 with those references, which @nix profile@ adds each-- generation by (@ProfileManifest::build@ in profile.cc). A valid path is-- passed over. Otherwise, under the path's lock, what is at the path is-- cleared, the NAR is unpacked there as a substituted one is-- ('unpackNarEntry') and its metadata made canonical, and it is registered-- only once it serialises back to the NAR it came from, since the volume-- decides the final spelling of every name; a tree that does not is removed-- and refused. The references must be valid. A store upstream Nix's-- database may also manage is refused before anything is looked at-- ("Nix.Store.Upstream").addSourceTree :: Store -> Text -> Set StorePath -> NAR.NarEntry -> IO (Either Text StorePath)addSourceTree store name refs entry = case makeSourcePath name (sha256Digest nar) refs of Left bad -> pure (Left (badStorePathText bad)) Right sp -> do refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (stDir store) case refusal of Just reason -> pure (Left reason) Nothing -> withPathLock (stLogger store) (stDir store) sp $ \_ -> do valid <- isValid store sp if valid then pure (Right sp) else place sp where nar = NAR.serialise entry place sp = do let dest = storePathToFilePath (stDir store) sp Dir.removePathForcibly dest placed <- (unpackNarEntry (stCaseSensitivity store) dest entry >>= traverse (const (sealed sp dest))) `onException` Dir.removePathForcibly dest case placed of Right (Just reg) -> Right sp <$ registerPath (stDB store) reg Right Nothing -> Left (storePathToText defaultStoreDir sp <> ": the unpacked tree does not serialise to the NAR it was unpacked from") <$ Dir.removePathForcibly dest Left reason -> Left reason <$ Dir.removePathForcibly dest sealed sp dest = do canonicalizeMetadata dest reg <- registrationFor store sp Nothing (Set.toAscList refs) pure (if prNarHash reg == Hash.formatNixHash (Hash.hashBytes nar) then Just reg {prContentAddress = contentAddressFromParts (FixedMethod NarIngestion) sha256Algo (sha256Digest nar)} else Nothing)-- | The content address under which on-disk content re-derives exactly-- the store path it is about to be registered under, by the scheme that-- named the write, or 'Nothing' when it does not. An unreadable-- destination counts as a mismatch.writtenAddress :: CaseSensitivity -> FilePath -> StorePath -> [StorePath] -> StoreWriteMode -> IO (Maybe ContentAddress)writtenAddress sensitivity dest sp refs mode = case mode of WriteRecursive -> adoptedTreeAddress sensitivity dest sp WriteFlat -> withFileDigest (\digest -> makeFixedOutputPath (spName sp) sha256Algo FlatIngestion digest == Right sp) (FixedMethod FlatIngestion) WriteText -> withFileDigest (\digest -> makeTextPath (spName sp) digest refs == Right sp) TextMethod where withFileDigest derives method = do result <- try (BS.readFile dest) :: IO (Either IOException BS.ByteString) pure $ case sha256Digest <$> result of Right digest | derives digest -> contentAddressFromParts method sha256Algo digest _ -> Nothing-- | The content address under which an on-disk tree reproduces the source-- store path it is about to be registered under ('sourceAddress'), or-- 'Nothing' when its recursive NAR digest and the path's own name do not-- derive exactly this path. An unreadable tree counts as a mismatch.-- The sensitivity is the store volume's, which decides the case-hack mode-- the tree is read back under.adoptedTreeAddress :: CaseSensitivity -> FilePath -> StorePath -> IO (Maybe ContentAddress)adoptedTreeAddress sensitivity dest sp = (>>= sourceAddress sp . NAR.narHash) <$> ExecBit.serialiseIfReadable (volumeCaseHack sensitivity) dest-- | Recursively copy a file or directory tree to a destination path.-- A symlink is replicated as a symlink: the store path's name came from a-- NAR hash that ENCODES the link entry, so dereferencing it here would-- store content that no longer matches its own address (and a-- self-referential link would recurse forever). On Windows without-- symlink privilege the link creation fails loudly rather than silently-- corrupting the content address.---- Every entry is created exclusively, like an unpacked tree's:-- siblings distinct on the source volume can fold together on the-- destination's, and the copy refuses the second rather than landing-- it on the first, raising the refusal in upstream's wording.copyPathInto :: FilePath -> FilePath -> IO ()copyPathInto src dest = do isLink <- Dir.pathIsSymbolicLink src if isLink then do target <- Dir.getSymbolicLinkTarget src linkedDir <- doesDirectoryExist src let createLink = if linkedDir then Dir.createDirectoryLink else Dir.createFileLink refuseTaken (pure (symlinkTakenMessage dest target)) (createLink target dest) >>= raiseRefusal else do isDir <- doesDirectoryExist src destPath <- OP.encodeFS dest if isDir then do createTreeDirectory destPath >>= raiseRefusal names <- listDirectory src mapM_ (\name -> copyPathInto (src </> name) (dest </> name)) names else do copied <- withNewTreeFile destPath (\to -> withBinaryFile src ReadMode (`copyHandleBytes` to)) raiseRefusal copied -- Best effort: of the permissions, the NAR records only the -- exec mark, which is carried on its own below (the unnamed -- stream alone does not hold it on Windows). Dir.copyPermissions src dest `catch` \(_ :: IOException) -> pure () ExecBit.copyExecMark src dest where raiseRefusal = either (throwIO . userError . T.unpack) pure-- | Copy a readable handle's remaining bytes into a writable one, a-- bounded chunk at a time.copyHandleBytes :: Handle -> Handle -> IO ()copyHandleBytes from to = go where go = do chunk <- BS.hGetSome from copyChunkBytes unless (BS.null chunk) $ do BS.hPut to chunk go-- | The read size of 'copyHandleBytes': the block @directory@'s own-- file copy reads, which is coreutils' @cp@ size.copyChunkBytes :: IntcopyChunkBytes = 128 * 1024