Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/walk-opens-without-following.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **`serialiseFromPath` and `withNarSource` open a regular file without following a symlink in its own place on POSIX, as upstream's dump opens one, so an entry replaced by a symlink after the walk classified it is refused at the open with a `NarWalkError` for `WalkReadFile`.** Both walks opened the file by name, following a symlink, so a regular file swapped for a symlink to another regular file between its `lstat` and its open was archived as a regular file holding the target's bytes, where upstream refuses it. The open does not block, so a FIFO swapped in is still refused by the size read rather than waiting for a writer.
65 changes: 41 additions & 24 deletions src/NovaCache/NAR.hs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ module NovaCache.NAR
)
where

import Control.Exception (Exception (displayException), IOException, SomeException, bracketOnError, catch, finally, mask, throwIO, try)
import Control.Exception (Exception (displayException), IOException, SomeException, bracket, bracketOnError, catch, finally, mask, throwIO, try)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as B
Expand Down Expand Up @@ -85,12 +85,13 @@ import qualified System.OsPath as OP
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import System.Directory.OsPath (doesDirectoryExist, executable, getPermissions, pathIsSymbolicLink)
import System.IO (Handle, IOMode (ReadMode), hClose, hFileSize, openBinaryFile, withBinaryFile)
import System.IO (Handle, IOMode (ReadMode), hClose, hFileSize, openBinaryFile)
#else
import qualified Data.ByteString.Char8 as BS8
import System.IO (Handle, IOMode (ReadMode), hClose, hFileSize, latin1, openBinaryFile, withBinaryFile)
import System.IO (Handle, hClose, hFileSize, latin1)
import qualified System.Posix.Files as Posix
import qualified System.Posix.Files.ByteString as PosixBytes
import qualified System.Posix.IO.ByteString as PosixIO
#endif

-- ---------------------------------------------------------------------------
Expand Down Expand Up @@ -575,29 +576,46 @@ buildRegularFile resolver path = do
contents <- readFileBytes path
pure (NarRegular isExec contents)

-- | Open a regular file the walk classified, for reading. On POSIX the
-- open does not follow a symlink in the file's own place, as upstream's
-- dump's does not (@O_NOFOLLOW@ at 2.24.9, @openFileEnsureBeneathNoSymlinks@
-- at 2.36.0, in posix-source-accessor.cc), so an entry replaced by a
-- symlink after its @lstat@ is refused here, and one replaced by another
-- type that is not a regular file is refused by the size read after it,
-- which 'hFileSize' refuses on such a handle. Upstream also refuses a
-- symlink among the file's ancestors; this open follows one, so a
-- directory swapped for a symlink after the walk listed it is still
-- followed. The open does not block, so a FIFO swapped in does not wait
-- for a writer. On Windows the file is opened as named.
openWalkedFile :: OsPath -> IO Handle
#ifdef mingw32_HOST_OS
openWalkedFile path = decodeFS path >>= \shownPath -> openBinaryFile shownPath ReadMode
#else
openWalkedFile path = do
pathBytes <- osPathBytes path
bracketOnError (PosixIO.openFd pathBytes PosixIO.ReadOnly noFollow) PosixIO.closeFd PosixIO.fdToHandle
where
noFollow = PosixIO.defaultFileFlags {PosixIO.nofollow = True, PosixIO.nonBlock = True, PosixIO.cloexec = True}
#endif

-- | Run the resolver on a platform-native path. The resolver contract
-- is 'FilePath', so the path bridges through 'decodeFS' - the same
-- interop seam as 'readFileBytes'.
-- is 'FilePath', so the path bridges through 'decodeFS', whose contract
-- is the exact round-trip.
resolveExecBit :: ExecBitResolver -> OsPath -> IO Bool
resolveExecBit resolver path = resolver =<< decodeFS path

-- | Read a regular file's contents by platform-native path: exactly the
-- size the open handle reports, as upstream's dump reads exactly the size
-- it recorded (archive.cc), so the size an archive records and the
-- contents it holds agree. A file that ends before that size is
-- refused, and so is an open that finds no regular file, such as a FIFO
-- swapped in after the walk classified the entry, whose size 'hFileSize'
-- refuses to read, as the streaming walk refuses both. The byte-string file API still takes 'FilePath', so the
-- path bridges through 'decodeFS' - interop with unmigrated APIs is that
-- function's documented purpose, and its contract is the exact
-- round-trip: the reopened path names the same file even when the name
-- has no text decoding.
-- | Read a regular file's contents by platform-native path: the first
-- bytes, as many as the open reports, as upstream's dump reads the size
-- it recorded (@PosixSourceAccessor::readFile@ in
-- posix-source-accessor.cc). A file that ends before that size is
-- refused, and so is an open that finds no regular file
-- ('openWalkedFile'), as the streaming walk refuses both.
readFileBytes :: OsPath -> IO ByteString
readFileBytes path = do
shownPath <- decodeFS path
(size, contents) <-
accessing WalkReadFile path $
withBinaryFile shownPath ReadMode $ \handle -> do
bracket (openWalkedFile path) hClose $ \handle -> do
size <- hFileSize handle
contents <- BS.hGet handle (fromIntegral size)
pure (size, contents)
Expand Down Expand Up @@ -758,14 +776,13 @@ pullChunk stateRef = dispatch =<< readIORef stateRef
writeIORef stateRef (SourceSegments rest)
pure bytes
fromSegments (SegmentFile path : rest) = do
shownPath <- decodeFS path
-- hFileSize throws after a successful open when the entry is no
-- longer a regular file (replaced by a FIFO or a device after the
-- plan read its type); until the state ref records the handle,
-- the latch and the continuation's exit cannot see it, so
-- ownership transfers under bracketOnError.
-- The open refuses an entry replaced by a symlink after the plan
-- read its type, and hFileSize one replaced by a FIFO or a device
-- ('openWalkedFile'); until the state ref records the handle, the
-- latch and the continuation's exit cannot see it, so ownership
-- transfers under bracketOnError.
accessing WalkReadFile path $
bracketOnError (openBinaryFile shownPath ReadMode) hClose $ \handle -> do
bracketOnError (openWalkedFile path) hClose $ \handle -> do
size <- hFileSize handle
let owed = fromIntegral size :: Word64
writeIORef stateRef (SourceFile handle path owed (narPadOf owed) rest)
Expand Down
57 changes: 47 additions & 10 deletions test/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -1342,16 +1342,28 @@ testWalkFailures =
let file = root ++ "/file"
BS.writeFile file "contents"
withFifoAtResolve file $ \resolver -> do
outcome <- try (NAR.serialiseFromPathOpts walkOptions {NAR.soExecBit = resolver} root)
case outcome of
Left failure ->
assertEqual
"the access refused, and the entry"
(Just (NAR.WalkReadFile, file))
((\refusal -> (NAR.nweAccess refusal, NAR.nwePath refusal)) <$> fromException failure)
Right entry -> do
putStrLn (" archived " ++ show entry)
pure False,
outcome <- try (void (NAR.serialiseFromPathOpts walkOptions {NAR.soExecBit = resolver} root))
assertEqual "the access refused, and the entry" (Just (NAR.WalkReadFile, file)) (refusedAccess outcome),
-- The walks open a regular file without following a symlink, as
-- upstream's dump opens one, so a file replaced by a symlink after
-- the walk classified it is refused at the open rather than read
-- through the link.
test "the eager walk refuses a file replaced by a symlink after it classified it" $
withWalkTree $ \root -> do
let file = root ++ "/file"
BS.writeFile file "contents"
BS.writeFile (root ++ "/target") "other"
withSymlinkAtResolve file (root ++ "/target") $ \resolver -> do
outcome <- try (void (NAR.serialiseFromPathOpts walkOptions {NAR.soExecBit = resolver} root))
assertEqual "the access refused, and the entry" (Just (NAR.WalkReadFile, file)) (refusedAccess outcome),
test "the streaming walk refuses a file replaced by a symlink after it planned it" $
withWalkTree $ \root -> do
let file = root ++ "/file"
BS.writeFile file "contents"
BS.writeFile (root ++ "/target") "other"
withSymlinkAtResolve file (root ++ "/target") $ \resolver -> do
outcome <- try (void (NAR.withNarSourceOpts walkOptions {NAR.soExecBit = resolver} root drainSource))
assertEqual "the access refused, and the entry" (Just (NAR.WalkReadFile, file)) (refusedAccess outcome),
test "a Unix socket in a tree is refused as an unsupported type" $
withWalkTree $ \root -> do
let socketPath = root ++ "/sub/socket"
Expand Down Expand Up @@ -1538,6 +1550,31 @@ withFifoAtResolve file check = check resolve
| otherwise = pure False
#endif

-- | Run a check with an executable-bit resolver that replaces a file by a
-- symlink to another file when the walk asks it about that file, which
-- is after the walk classified the file and before it opens it. Windows
-- opens a file as named, so the check is skipped there.
withSymlinkAtResolve :: FilePath -> FilePath -> (NAR.ExecBitResolver -> IO Bool) -> IO Bool
#if defined(mingw32_HOST_OS)
withSymlinkAtResolve _ _ _ = pure True
#else
withSymlinkAtResolve file target check = check resolve
where
resolve path
| path == file = do
removeFile file
createFileLink target file
pure False
| otherwise = pure False
#endif

-- | The access and the entry a walk's failure names, when it is a
-- 'NAR.NarWalkError'.
refusedAccess :: Either SomeException () -> Maybe (NAR.WalkAccess, FilePath)
refusedAccess outcome = case outcome of
Left failure -> (\refusal -> (NAR.nweAccess refusal, NAR.nwePath refusal)) <$> fromException failure
Right () -> Nothing

-- | Bind a Unix socket at a path and run a check on the file the bind
-- leaves, which outlives the socket. The walk on Windows reads no
-- file mode, so the check is skipped there.
Expand Down
Loading