packages feed

nova-cache-0.14.0.1 / src / NovaCache / NAR / Stream.hs

-- | Incremental NAR parsing: a pure, chunk-fed event machine.---- "NovaCache.NAR" parses a NAR held whole in memory; consumers realize-- entire archives to walk them, and nova-nix's substituter documents-- the resident-set spike that costs on large paths.  This module parses-- the same grammar incrementally: feed chunks as they arrive - from a-- download, a decompressor - and act on events as they complete.-- Regular-file contents pass through as slices of the fed chunks, so-- memory is bounded by the largest structural wire string, never by-- archive or file size.---- 'narStream' parses an archive that is the whole input.  'narPrefix'-- parses one that more input follows, as a NAR is followed by the rest-- of a stream it is sent in, and finishes with the bytes after it.---- Beyond the grammar, both refuse what upstream's parser refuses: a-- keyword over 32 bytes, an entry name over 255, a symlink target over-- 4095, a nonempty executable marker, an empty symlink target or one-- holding NUL, and a node 'narMaxDepth' levels deep.  A string over its-- limit is refused from its length prefix, before the bytes it declares-- are read, so the largest structural string held is a 4095-byte-- target.---- The grammar lives here once: 'NovaCache.NAR.deserialise' is the-- whole-input instantiation of this machine, and the serialiser draws-- its wire vocabulary from the exports below, so the two directions-- cannot drift apart.module NovaCache.NAR.Stream  ( -- * Events    NarEvent (..),    -- * The machine    NarStep (..),    narStream,    narPrefix,    -- * Limits    narMaxDepth,    -- * Entry-name safety    checkEntryName,    isWindowsHazardName,    -- * Wire vocabulary (shared with the serialiser in "NovaCache.NAR")    tokMagic,    tokLParen,    tokRParen,    tokType,    tokRegular,    tokDirectory,    tokSymlink,    tokContents,    tokTarget,    tokExecutable,    tokEntry,    tokName,    tokNode,    narAlignment,    narPad,    narPadOf,  )whereimport Data.Bits (shiftL, (.&.), (.|.))import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport qualified Data.ByteString.Char8 as BS8import Data.Word (Word64)import NovaCache.SafeName (hasTrailingDotOrSpace, isReservedDeviceName)-- ----------------------------------------------------------------------------- Wire vocabulary-- ----------------------------------------------------------------------------- | Archive framing: the magic header, node delimiters, and the type-- keyword.tokMagic, tokLParen, tokRParen, tokType :: ByteStringtokMagic = "nix-archive-1"tokLParen = "("tokRParen = ")"tokType = "type"-- | The three node kinds.tokRegular, tokDirectory, tokSymlink :: ByteStringtokRegular = "regular"tokDirectory = "directory"tokSymlink = "symlink"-- | Regular-file and symlink field keywords.tokContents, tokTarget, tokExecutable :: ByteStringtokContents = "contents"tokTarget = "target"tokExecutable = "executable"-- | Directory-entry keywords.tokEntry, tokName, tokNode :: ByteStringtokEntry = "entry"tokName = "name"tokNode = "node"-- | Alignment boundary for NAR wire strings.narAlignment :: IntnarAlignment = 8-- | Compute padding to reach the next 8-byte boundary.narPad :: Int -> IntnarPad len =  let remainder = len .&. (narAlignment - 1)   in if remainder == 0 then 0 else narAlignment - remainder-- | 'narPad' over the wire's own length type, for sizes that may not-- fit 'Int'.  The result is a padding count, so it always does.narPadOf :: Word64 -> IntnarPadOf len =  let remainder = len .&. fromIntegral (narAlignment - 1)   in if remainder == 0 then 0 else narAlignment - fromIntegral remainder-- | Size of the length prefix preceding every wire string.lengthPrefixBytes :: IntlengthPrefixBytes = 8-- ----------------------------------------------------------------------------- Events-- ----------------------------------------------------------------------------- | One structural step of an archive.  A node unfolds as either---- @'EventRegularBegin' ('EventRegularChunk'*) 'EventRegularEnd'@,-- an 'EventSymlink', or-- @'EventDirectoryBegin' entry* 'EventDirectoryEnd'@ where each entry-- is @'EventEntryBegin' node 'EventEntryEnd'@.data NarEvent  = -- | A regular file opens: executable flag and its declared    -- contents size, known up front from the wire length prefix.    EventRegularBegin !Bool !Word64  | -- | One slice of regular-file contents, in order.  Slices are    -- substrings of the fed chunks (no copying); their lengths sum to    -- the declared size.    EventRegularChunk !ByteString  | -- | The regular file's contents and padding are fully consumed and    -- its node is closed.    EventRegularEnd  | -- | A complete symlink node: the target, as the raw bytes the    -- archive carries.    EventSymlink !ByteString  | EventDirectoryBegin  | -- | An entry opens under the innermost open directory.  The name    -- has already passed 'checkEntryName', order included.    EventEntryBegin !ByteString  | EventEntryEnd  | EventDirectoryEnd  deriving (Eq, Show)-- | The machine's outward face, finishing with a result of type @r@.-- Drive it by pattern matching: hand 'NarAwait' the next chunk (the-- empty string means end of input, the same convention as-- 'NovaCache.Store.writeNarStreaming' consumes), and read events off-- 'NarYield' as they complete.  'NarDone' ends a parse that succeeded:-- from 'narStream' it confirms the archive ended exactly at the root-- node's close, and from 'narPrefix' it carries the input after that-- close.  Anything else that can go wrong is a 'NarFail'.data NarStep r  = NarAwait !(ByteString -> NarStep r)  | -- | The continuation is deliberately lazy: yielding is what hands    -- control back to the consumer, and a strict field would force    -- each step's successor at construction, materializing the whole    -- fed chunk's event chain before the consumer acts on the first    -- event.  Do not add a bang.    NarYield !NarEvent (NarStep r)  | NarDone !r  | NarFail !String-- | The parser for an archive that is the whole input, positioned at-- its start.  After the root node's close it awaits the end of input,-- and any byte before that end fails the parse.narStream :: NarStep ()narStream = archive archiveEnd  where    archiveEnd leftover      | BS.null leftover = NarAwait confirm      | otherwise = NarFail trailingBytes    confirm chunk      | BS.null chunk = NarDone ()      | otherwise = NarFail trailingBytes    trailingBytes = "trailing bytes after NAR root node"-- | The parser for an archive that more input follows, positioned at-- its start.  It finishes at the root node's close, without awaiting-- more input, with the input after that close: a suffix of the last-- chunk fed, so the archive is every byte fed before that suffix.-- Upstream reads a NAR from a stream the same way, stopping at the root-- node's close and leaving what follows to the stream's next reader.-- The end of input before that close fails the parse, as for-- 'narStream'.narPrefix :: NarStep ByteStringnarPrefix = archive NarDone-- ----------------------------------------------------------------------------- Limits-- ----------------------------------------------------------------------------- | The depth of the first node refused: the root is at depth 0 and an-- entry's node one deeper than its directory, so the deepest node-- accepted sits below a chain of 63 directories, the root included.-- Upstream refuses a node this deep both when it parses an archive and-- when it dumps a tree, to bound the stack its recursive walks run on,-- and the walk in "NovaCache.NAR" refuses one as its dump does.narMaxDepth :: IntnarMaxDepth = 64-- | The longest keyword string read: every keyword is at most 10 bytes,-- and the slack keeps a short wrong string readable in the error.narMaxTag :: Word64narMaxTag = 32-- | The longest entry name, the format's own bound, independent of any-- host's name limit.narMaxName :: Word64narMaxName = 255-- | The longest symlink target, the format's own bound, independent of-- any host's path limit.narMaxTarget :: Word64narMaxTarget = 4095-- | The executable marker's length: its value is always the empty-- string, so a marker declaring any bytes is refused before they are-- read.narMaxExecutableMarker :: Word64narMaxExecutableMarker = 0-- ----------------------------------------------------------------------------- Parser-- ----------------------------------------------------------------------------- | A parse state waiting for its share of the input: apply it to the-- unconsumed bytes to proceed.type Continue r = ByteString -> NarStep r-- | Parse the archive magic and the root node, then continue with the-- input after the root node's close.  The magic is held to its own-- length, so a longer string is refused from its length prefix.archive :: Continue r -> NarStep rarchive k =  expectWire (fromIntegral (BS.length tokMagic)) "archive magic" tokMagic (parseNode 0 k) BS.empty-- | Parse one node at the given depth and continue.parseNode :: Int -> Continue r -> Continue rparseNode depth k =  expectTag "node opening" tokLParen    $ expectTag "type keyword" tokType    $ wireString narMaxTag "node type" dispatch  where    dispatch kind      | kind == tokRegular = parseRegular k      | kind == tokSymlink = parseSymlink k      | kind == tokDirectory = parseDirectory depth k      | otherwise = failWith ("unknown NAR entry type: " ++ show kind)-- | Parse a regular file node: optional executable flag, then contents-- streamed through as chunk events.parseRegular :: Continue r -> Continue rparseRegular k = wireString narMaxTag "regular-node keyword" body  where    body tok      | tok == tokExecutable =          wireString narMaxExecutableMarker "executable marker" $ \_ ->            expectTag "contents keyword" tokContents (contentsOf True)      | tok == tokContents = contentsOf False      | otherwise =          failWith ("expected 'executable' or 'contents' in regular, got: " ++ show tok)    contentsOf isExec = exactly lengthPrefixBytes "length of file contents" (withSize isExec)    withSize isExec lenBytes leftover =      let size = word64LE lenBytes       in NarYield            (EventRegularBegin isExec size)            (streamContents size (afterContents size) leftover)    afterContents size =      exactly (narPadOf size) "file contents padding" $ \padding ->        if BS.any (/= 0) padding          then failWith nonzeroPadding          else expectTag "node closing" tokRParen $ \leftover ->            NarYield EventRegularEnd (k leftover)-- | Yield contents slices until the declared size is consumed.  Slices-- are substrings of the fed chunks; nothing accumulates.streamContents :: Word64 -> Continue r -> Continue rstreamContents remaining k leftover  | remaining == 0 = k leftover  | BS.null leftover = NarAwait feed  | otherwise =      let sliceLen = fromIntegral (min remaining (fromIntegral (BS.length leftover)))          (slice, rest) = BS.splitAt sliceLen leftover       in NarYield            (EventRegularChunk slice)            (streamContents (remaining - fromIntegral sliceLen) k rest)  where    feed chunk      | BS.null chunk = NarFail "unexpected end of NAR: file contents"      | otherwise = streamContents remaining k chunk-- | Parse a symlink node.  The target is carried verbatim: upstream-- imposes no text encoding on it, and refuses only an empty one or one-- holding NUL, before the node's closing.parseSymlink :: Continue r -> Continue rparseSymlink k =  expectTag "target keyword" tokTarget $    wireString narMaxTarget "symlink target" checked  where    checked target      | BS.null target = failWith "empty NAR symlink target"      | BS.elem 0 target = failWith ("NAR symlink target holds NUL: " ++ show target)      | otherwise =          expectTag "node closing" tokRParen $ \leftover ->            NarYield (EventSymlink target) (k leftover)-- | Parse a directory node at the given depth: entries validated name-- by name as they open, so a consumer can act on each entry before the-- next arrives.  An entry's node too deep is refused once its node-- keyword is read, before the node itself, where upstream refuses it.parseDirectory :: Int -> Continue r -> Continue rparseDirectory depth k leftover =  NarYield EventDirectoryBegin (entries Nothing leftover)  where    childDepth = depth + 1    entries prev = wireString narMaxTag "directory token" (branch prev)    branch prev tok      | tok == tokRParen = NarYield EventDirectoryEnd . k      | tok == tokEntry =          expectTag "entry opening" tokLParen            $ expectTag "name keyword" tokName            $ wireString narMaxName "entry name" (named prev)      | otherwise = failWith ("expected 'entry' or ')' in directory, got: " ++ show tok)    named prev entryName = case checkEntryName prev entryName of      Left err -> failWith err      Right () ->        NarYield (EventEntryBegin entryName)          . expectTag "node keyword" tokNode (descend entryName)    descend entryName      | childDepth >= narMaxDepth =          failWith            ( "NAR directory nesting exceeds the maximum depth of "                ++ show narMaxDepth                ++ ": "                ++ show entryName            )      | otherwise = parseNode childDepth (closeEntry entryName)    closeEntry entryName =      expectTag "entry closing" tokRParen $ \leftover2 ->        NarYield EventEntryEnd (entries (Just entryName) leftover2)-- ----------------------------------------------------------------------------- Entry-name safety-- ----------------------------------------------------------------------------- | Reject a NAR directory entry name the grammar itself refuses, or-- one out of order against its predecessor.  The rejections are-- exactly upstream's: no empty name, no @.@ or @..@, no @/@ or NUL,-- and strictly increasing (sorted, unique) byte order - which rejects-- malformed archives, keeps @serialise . deserialise@ an identity,-- and forecloses the POSIX path-traversal surface.  Names hazardous-- only on Windows (device stems like @aux.c@, colons, backslashes,-- trailing dots or spaces) are accepted here, as upstream's restore-- accepts them on Unix and real caches serve them; rejecting them is-- a materialization-boundary decision a store writer takes with-- 'isWindowsHazardName' when the target filesystem needs it.checkEntryName :: Maybe ByteString -> ByteString -> Either String ()checkEntryName prev name  | BS.null name = Left "empty NAR directory entry name"  | name == "." || name == ".." || BS8.any (\c -> c == '/' || c == '\0') name =      Left ("unsafe NAR directory entry name: " ++ show name)  | Just p <- prev,    name <= p =      Left ("NAR directory entries not strictly increasing: " ++ show name)  | otherwise = Right ()-- | Does the name resolve, on a Windows filesystem, to something other-- than an ordinary file of this exact spelling?  Backslash is a-- directory separator there, so @..\\out.exe@ traverses like a name-- with @/@; a colon is a drive prefix (@C:evil@) or an NTFS alternate-- data stream (@a:b@); a reserved device stem (@nul@, @aux.c@) opens-- the device; and NTFS strips a trailing dot or space, silently-- diverging the on-disk name from the NAR name.  The parser accepts-- all of these because upstream does and real cache.nixos.org-- archives carry them (perl man pages named @ExtUtils::MakeMaker.3@,-- kernel trees carrying @aux.c@); a store writer applies this-- predicate at materialization when the target filesystem needs it.-- Every check is ASCII-structural, so it stays exact whether or not-- the name decodes as text (see "NovaCache.SafeName").isWindowsHazardName :: ByteString -> BoolisWindowsHazardName name =  BS8.any (\c -> c == '\\' || c == ':') name    || isReservedDeviceName name    || hasTrailingDotOrSpace name-- ----------------------------------------------------------------------------- Chunk-fed primitives-- ----------------------------------------------------------------------------- | Read one whole wire string - length prefix, payload, zero padding --- refusing a declared length over the limit from the prefix, before-- reading or allocating for the payload, as upstream refuses it.  For-- structural strings only; file contents go through 'streamContents'.wireString :: Word64 -> String -> (ByteString -> Continue r) -> Continue rwireString limit what k = exactly lengthPrefixBytes ("length of " ++ what) withLength  where    withLength lenBytes =      let declared = word64LE lenBytes       in if declared > limit            then              failWith                ( what                    ++ ": declared length "                    ++ show declared                    ++ " exceeds the "                    ++ show limit                    ++ "-byte limit"                )            else              -- Safe narrowing and a safe padded demand: every limit              -- is a few KiB at most.              let len = fromIntegral declared               in exactly (len + narPad len) what $ \whole ->                    case BS.splitAt len whole of                      (payload, padding)                        -- Nix's reader rejects nonzero padding; accepting it                        -- would let archives that upstream tooling refuses                        -- round-trip through this library.                        | BS.any (/= 0) padding -> failWith nonzeroPadding                        | otherwise -> k payload-- | Read a wire string held to the limit and require an exact token.expectWire :: Word64 -> String -> ByteString -> Continue r -> Continue rexpectWire limit what expected k = wireString limit what check  where    check got      | got == expected = k      | otherwise = failWith ("expected " ++ show expected ++ ", got " ++ show got)-- | Read a keyword and require an exact one.expectTag :: String -> ByteString -> Continue r -> Continue rexpectTag = expectWire narMaxTag-- | Demand exactly @n@ bytes, awaiting more chunks as needed, then-- continue with them and the leftover.  Held chunks concatenate once,-- so pathological chunking costs linear work, not quadratic.exactly :: Int -> String -> (ByteString -> Continue r) -> Continue rexactly n what k leftover = go [leftover] (BS.length leftover)  where    go !heldRev !heldLen      | heldLen >= n =          case BS.splitAt n (BS.concat (reverse heldRev)) of            (taken, rest) -> k taken rest      | otherwise = NarAwait $ \chunk ->          if BS.null chunk            then NarFail ("unexpected end of NAR: " ++ what)            else go (chunk : heldRev) (heldLen + BS.length chunk)-- | Fail from any position that still owes the machine a continuation.failWith :: String -> Continue rfailWith err _ = NarFail errnonzeroPadding :: StringnonzeroPadding = "nonzero padding bytes in NAR string"-- | Read a little-endian 'Word64' from an 8-byte string.word64LE :: ByteString -> Word64word64LE = BS.foldr accumulate 0  where    accumulate byte acc = (acc `shiftL` bitsPerByte) .|. fromIntegral byte-- | Bits per byte, for the length-prefix fold.bitsPerByte :: IntbitsPerByte = 8