{-# LANGUAGE CPP #-}

module Data.X509.ReadFile (
    readFileCloexec,
) where

#ifndef MIN_VERSION_unix
#define MIN_VERSION_unix(x, y, z) 0
#endif

import qualified Data.ByteString as B
#if defined(MIN_VERSION_unix) && MIN_VERSION_unix(2,8,0)
import qualified Control.Exception as E
import System.IO (hClose)
import System.Posix.IO
#endif

-- | Read a whole file strictly.  The file descriptor is not inherited
-- by child processes (when unix >= 2.8 is available).
readFileCloexec :: FilePath -> IO B.ByteString
#if defined(MIN_VERSION_unix) && MIN_VERSION_unix(2,8,0)
readFileCloexec :: FilePath -> IO ByteString
readFileCloexec FilePath
path =
    IO Handle
-> (Handle -> IO ()) -> (Handle -> IO ByteString) -> IO ByteString
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
E.bracket
        (FilePath -> OpenMode -> OpenFileFlags -> IO Fd
openFd FilePath
path OpenMode
ReadOnly OpenFileFlags
defaultFileFlags{cloexec = True} IO Fd -> (Fd -> IO Handle) -> IO Handle
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Fd -> IO Handle
fdToHandle)
        Handle -> IO ()
hClose
        Handle -> IO ByteString
B.hGetContents
#else
readFileCloexec = B.readFile
#endif