module System.X509.Common (
    maybeSSLCertEnvOr,
    nativeCertificates,
)
where

import Control.Exception (bracket)
import Control.Monad (when)
import Data.Bits (shiftL, (.|.))
import qualified Data.ByteString as B
import Data.Either (rights)
import Data.Maybe (catMaybes, maybeToList)
import Data.Word (Word8)
import Data.X509
import Data.X509.CertificateStore
import Foreign.C.Types (CInt (..), CSize (..))
import Foreign.Marshal.Alloc (alloca, free)
import Foreign.Ptr (Ptr, castPtr)
import Foreign.Storable (peek)
import System.Environment (lookupEnv)
import System.FilePath (searchPathSeparator)

-- | Like OpenSSL, the certificates in @SSL_CERT_FILE@ and in the
-- directories listed in @SSL_CERT_DIR@ replace the default store if
-- either variable is set to a non-empty value.
maybeSSLCertEnvOr :: IO CertificateStore -> IO CertificateStore
maybeSSLCertEnvOr :: IO CertificateStore -> IO CertificateStore
maybeSSLCertEnvOr IO CertificateStore
defaultStore = do
    file <- Maybe [Char] -> Maybe [Char]
forall {t :: * -> *} {a}. Foldable t => Maybe (t a) -> Maybe (t a)
nonEmpty (Maybe [Char] -> Maybe [Char])
-> IO (Maybe [Char]) -> IO (Maybe [Char])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Char] -> IO (Maybe [Char])
lookupEnv [Char]
"SSL_CERT_FILE"
    dirs <- maybe [] splitDirs <$> lookupEnv "SSL_CERT_DIR"
    case maybeToList file ++ dirs of
        [] -> IO CertificateStore
defaultStore
        [[Char]]
paths -> [CertificateStore] -> CertificateStore
forall a. Monoid a => [a] -> a
mconcat ([CertificateStore] -> CertificateStore)
-> ([Maybe CertificateStore] -> [CertificateStore])
-> [Maybe CertificateStore]
-> CertificateStore
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Maybe CertificateStore] -> [CertificateStore]
forall a. [Maybe a] -> [a]
catMaybes ([Maybe CertificateStore] -> CertificateStore)
-> IO [Maybe CertificateStore] -> IO CertificateStore
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ([Char] -> IO (Maybe CertificateStore))
-> [[Char]] -> IO [Maybe CertificateStore]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM [Char] -> IO (Maybe CertificateStore)
readCertificateStore [[Char]]
paths
  where
    nonEmpty :: Maybe (t a) -> Maybe (t a)
nonEmpty (Just t a
s) | Bool -> Bool
not (t a -> Bool
forall a. t a -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null t a
s) = t a -> Maybe (t a)
forall a. a -> Maybe a
Just t a
s
    nonEmpty Maybe (t a)
_ = Maybe (t a)
forall a. Maybe a
Nothing
    splitDirs :: [Char] -> [[Char]]
splitDirs [Char]
s = case (Char -> Bool) -> [Char] -> ([Char], [Char])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
searchPathSeparator) [Char]
s of
        ([Char]
d, []) -> [[Char]
d | Bool -> Bool
not ([Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
d)]
        ([Char]
d, Char
_ : [Char]
rest) -> [[Char]
d | Bool -> Bool
not ([Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
d)] [[Char]] -> [[Char]] -> [[Char]]
forall a. [a] -> [a] -> [a]
++ [Char] -> [[Char]]
splitDirs [Char]
rest

-- | Certificates returned by a C function as a malloc'ed buffer of 4-byte
-- big-endian lengths each followed by DER.  The first argument names the
-- caller in errors.
nativeCertificates
    :: String
    -> (Ptr (Ptr Word8) -> Ptr CSize -> IO CInt)
    -> IO [SignedCertificate]
nativeCertificates :: [Char]
-> (Ptr (Ptr Word8) -> Ptr CSize -> IO CInt)
-> IO [SignedCertificate]
nativeCertificates [Char]
name Ptr (Ptr Word8) -> Ptr CSize -> IO CInt
getCerts =
    (Ptr (Ptr Word8) -> IO [SignedCertificate])
-> IO [SignedCertificate]
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr (Ptr Word8) -> IO [SignedCertificate])
 -> IO [SignedCertificate])
-> (Ptr (Ptr Word8) -> IO [SignedCertificate])
-> IO [SignedCertificate]
forall a b. (a -> b) -> a -> b
$ \Ptr (Ptr Word8)
pbuf -> (Ptr CSize -> IO [SignedCertificate]) -> IO [SignedCertificate]
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr CSize -> IO [SignedCertificate]) -> IO [SignedCertificate])
-> (Ptr CSize -> IO [SignedCertificate]) -> IO [SignedCertificate]
forall a b. (a -> b) -> a -> b
$ \Ptr CSize
plen -> do
        rc <- Ptr (Ptr Word8) -> Ptr CSize -> IO CInt
getCerts Ptr (Ptr Word8)
pbuf Ptr CSize
plen
        when (rc /= 0) $
            ioError $
                userError $
                    name ++ ": cannot get the trusted certificates: " ++ show rc
        bracket (peek pbuf) free $ \Ptr Word8
buf -> do
            len <- Ptr CSize -> IO CSize
forall a. Storable a => Ptr a -> IO a
peek Ptr CSize
plen
            bs <- B.packCStringLen (castPtr buf, fromIntegral len)
            return $ rights $ map decodeSignedCertificate $ split bs
  where
    split :: ByteString -> [ByteString]
split ByteString
bs
        | ByteString -> Int
B.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
4 = []
        | Bool
otherwise =
            let (ByteString
hdr, ByteString
rest) = Int -> ByteString -> (ByteString, ByteString)
B.splitAt Int
4 ByteString
bs
                n :: Int
n = (Int -> Word8 -> Int) -> Int -> [Word8] -> Int
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl (\Int
a Word8
w -> Int
a Int -> Int -> Int
forall a. Bits a => a -> Int -> a
`shiftL` Int
8 Int -> Int -> Int
forall a. Bits a => a -> a -> a
.|. Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
w) Int
0 (ByteString -> [Word8]
B.unpack ByteString
hdr)
                (ByteString
der, ByteString
rest') = Int -> ByteString -> (ByteString, ByteString)
B.splitAt Int
n ByteString
rest
             in ByteString
der ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: ByteString -> [ByteString]
split ByteString
rest'