{-  -*- Mode: haskell; -*-
Haskell magic Interface
Copyright (C) 2005 John Goerzen <jgoerzen@complete.org>

This code is under a 3-clause BSD license; see COPYING for details.
-}

{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}

{- |
   Module     : Magic.Internal
   Copyright  : Copyright (C) 2005 John Goerzen
   License    : BSD-3-Clause

   Maintainer : Philippe <philippedev101\@gmail.com>
   Stability  : provisional
   Portability: portable

Internal representation of the t'Magic' handle, the t'MagicException' error type,
and the helpers shared by the other modules. Not part of the public API: it is
exposed only so the rest of the package can build, and may change without a
major-version bump.
-}

module Magic.Internal
  ( CMagic
  , Magic(..)
  , MagicException(..)
  , fromMagicPtr
  , withMagicPtr
  , checkIntError
  , throwErrorIfNull
  , peekCStringText
  , withOsPathCString
  , withSearchPathCString
  , peekSearchPath
  ) where

import Control.Concurrent.MVar (MVar, newMVar, withMVar)
import Control.DeepSeq (NFData(rnf))
import Control.Exception (Exception, displayException, throwIO)
import GHC.Generics (Generic)
import qualified Data.ByteString as BS
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Foreign
import Foreign.C.Error (throwErrnoIfNull)
import Foreign.C.String (CString)
import Foreign.C.Types (CInt)
import System.OsPath (OsPath)

#if defined(mingw32_HOST_OS)
import Data.List (intercalate)
import Foreign.C.String (peekCString, withCString)
import System.OsPath (decodeFS, encodeFS)
#else
import qualified Data.ByteString.Short as SBS
import System.OsString.Internal.Types (OsString(OsString, getOsString), PosixString(PosixString, getPosixString))
#endif

-- | Phantom type standing in for the C @magic_t@ cookie. It appears only as the
-- argument of a 'ForeignPtr' inside the t'Magic' handle and has no values of its
-- own.
data CMagic

{- | The magic handle: an opaque cookie obtained from @magicOpen@ and passed to
the loading and querying functions.

Handles are closed (and their memory freed) automatically when they are
garbage-collected; there is no need to close them explicitly.

__Thread safety.__ Operations on a single handle are serialised by an internal
lock, so it is safe to share one handle across threads (concurrent calls simply
take turns). For genuine parallelism, use one handle per thread; distinct
handles are independent. Programs doing blocking work (loading databases,
examining files) should use the threaded runtime (@-threaded@).
-}
data Magic = Magic !(ForeignPtr CMagic) !(MVar [BS.ByteString])
-- The MVar is both the per-handle lock and the store that keeps any buffers
-- passed to magicLoadBuffers alive for the lifetime of the handle (libmagic
-- retains, rather than copies, those buffers).

-- | The handle is opaque; it shows as a fixed placeholder.
instance Show Magic where
  show :: Magic -> String
show Magic
_ = String
"<magic handle>"

-- | The exception raised when a @libmagic@ operation fails. Carries the name of
-- the operation that failed and the message reported by @libmagic@.
--
-- @since 2.0.0
data MagicException = MagicException
  { MagicException -> Text
magicErrorContext :: !Text  -- ^ the operation that failed, e.g. @\"magicFile\"@
  , MagicException -> Text
magicErrorMessage :: !Text  -- ^ @libmagic@'s error message
  } deriving (Int -> MagicException -> ShowS
[MagicException] -> ShowS
MagicException -> String
(Int -> MagicException -> ShowS)
-> (MagicException -> String)
-> ([MagicException] -> ShowS)
-> Show MagicException
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> MagicException -> ShowS
showsPrec :: Int -> MagicException -> ShowS
$cshow :: MagicException -> String
show :: MagicException -> String
$cshowList :: [MagicException] -> ShowS
showList :: [MagicException] -> ShowS
Show, MagicException -> MagicException -> Bool
(MagicException -> MagicException -> Bool)
-> (MagicException -> MagicException -> Bool) -> Eq MagicException
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: MagicException -> MagicException -> Bool
== :: MagicException -> MagicException -> Bool
$c/= :: MagicException -> MagicException -> Bool
/= :: MagicException -> MagicException -> Bool
Eq, (forall x. MagicException -> Rep MagicException x)
-> (forall x. Rep MagicException x -> MagicException)
-> Generic MagicException
forall x. Rep MagicException x -> MagicException
forall x. MagicException -> Rep MagicException x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. MagicException -> Rep MagicException x
from :: forall x. MagicException -> Rep MagicException x
$cto :: forall x. Rep MagicException x -> MagicException
to :: forall x. Rep MagicException x -> MagicException
Generic)

instance NFData MagicException where
  rnf :: MagicException -> ()
rnf (MagicException Text
c Text
m) = Text -> ()
forall a. NFData a => a -> ()
rnf Text
c () -> () -> ()
forall a b. a -> b -> b
`seq` Text -> ()
forall a. NFData a => a -> ()
rnf Text
m

instance Exception MagicException where
  displayException :: MagicException -> String
displayException (MagicException Text
ctx Text
msg) = Text -> String
T.unpack Text
ctx String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
": " String -> ShowS
forall a. [a] -> [a] -> [a]
++ Text -> String
T.unpack Text
msg

-- | Read a NUL-terminated C string into 'Text', decoding UTF-8 leniently
-- (replacing invalid bytes). Avoids the locale round-trip through 'String'.
peekCStringText :: CString -> IO Text
peekCStringText :: CString -> IO Text
peekCStringText CString
cs = OnDecodeError -> ByteString -> Text
decodeUtf8With OnDecodeError
lenientDecode (ByteString -> Text) -> IO ByteString -> IO Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CString -> IO ByteString
BS.packCString CString
cs

-- | Build a handle from a C cookie-returning action, attaching the
-- @magic_close@ finalizer. Raises an 'IOError' (from @errno@) if the action
-- returns @NULL@.
fromMagicPtr :: String -> IO (Ptr CMagic) -> IO Magic
fromMagicPtr :: String -> IO (Ptr CMagic) -> IO Magic
fromMagicPtr String
caller IO (Ptr CMagic)
action =
    do ptr <- String -> IO (Ptr CMagic) -> IO (Ptr CMagic)
forall a. String -> IO (Ptr a) -> IO (Ptr a)
throwErrnoIfNull String
caller IO (Ptr CMagic)
action
       fp  <- newForeignPtr magic_close ptr
       mv  <- newMVar []
       return (Magic fp mv)

-- | Run an action on the raw handle pointer, holding the per-handle lock and
-- keeping the handle alive for the whole action.
withMagicPtr :: Magic -> (Ptr CMagic -> IO a) -> IO a
withMagicPtr :: forall a. Magic -> (Ptr CMagic -> IO a) -> IO a
withMagicPtr (Magic ForeignPtr CMagic
fp MVar [ByteString]
mv) Ptr CMagic -> IO a
act = MVar [ByteString] -> ([ByteString] -> IO a) -> IO a
forall a b. MVar a -> (a -> IO b) -> IO b
withMVar MVar [ByteString]
mv (\[ByteString]
_ -> ForeignPtr CMagic -> (Ptr CMagic -> IO a) -> IO a
forall a b. ForeignPtr a -> (Ptr a -> IO b) -> IO b
withForeignPtr ForeignPtr CMagic
fp Ptr CMagic -> IO a
act)

-- Turn libmagic's last error into a 'MagicException'. Accesses the handle
-- lock-free because it is only ever called from inside an operation that
-- already holds the lock (so re-taking it would deadlock).
throwError :: String -> Magic -> IO a
throwError :: forall a. String -> Magic -> IO a
throwError String
caller (Magic ForeignPtr CMagic
fp MVar [ByteString]
_) =
    ForeignPtr CMagic -> (Ptr CMagic -> IO a) -> IO a
forall a b. ForeignPtr a -> (Ptr a -> IO b) -> IO b
withForeignPtr ForeignPtr CMagic
fp (\Ptr CMagic
cmagic ->
     do errormsg <- Ptr CMagic -> IO CString
magic_error Ptr CMagic
cmagic
        msg <- if errormsg /= nullPtr
                  then peekCStringText errormsg
                  else return (T.pack "got error code but no error message")
        throwIO (MagicException (T.pack caller) msg))

-- | Raise a t'MagicException' if the C action returns a non-zero (failure) code.
checkIntError :: String -> Magic -> IO CInt -> IO ()
checkIntError :: String -> Magic -> IO CInt -> IO ()
checkIntError String
caller Magic
m IO CInt
action =
    do res <- IO CInt
action
       if res == 0 then return () else throwError caller m

-- | Raise a t'MagicException' if the C action returns a @NULL@ pointer.
throwErrorIfNull :: String -> Magic -> IO (Ptr a) -> IO (Ptr a)
throwErrorIfNull :: forall a. String -> Magic -> IO (Ptr a) -> IO (Ptr a)
throwErrorIfNull String
caller Magic
m IO (Ptr a)
action =
    do res <- IO (Ptr a)
action
       if res == nullPtr then throwError caller m else return res

foreign import ccall unsafe "magic.h &magic_close"
  magic_close :: FunPtr (Ptr CMagic -> IO ())

foreign import ccall unsafe "magic.h magic_error"
  magic_error :: Ptr CMagic -> IO CString

-- Marshalling between 'OsPath' and the C @const char*@ that libmagic expects.
-- On POSIX an 'OsPath' is exactly the path bytes the OS uses, which is exactly
-- what libmagic wants, so they pass through untouched (no lossy locale round
-- trip). On Windows we fall back to the locale encoding (a libmagic build for
-- Windows is a rarity).

#if defined(mingw32_HOST_OS)

withOsPathCString :: OsPath -> (CString -> IO a) -> IO a
withOsPathCString p k = decodeFS p >>= \s -> withCString s k

withSearchPathCString :: [OsPath] -> (CString -> IO a) -> IO a
withSearchPathCString ps k =
    do ss <- mapM decodeFS ps
       withCString (intercalate ";" ss) k

peekSearchPath :: CString -> IO [OsPath]
peekSearchPath cs =
    do s <- peekCString cs
       mapM encodeFS (filter (not . null) (splitOn ';' s))
  where
    splitOn :: Char -> String -> [String]
    splitOn c s = case break (== c) s of
        (a, [])     -> [a]
        (a, _:rest) -> a : splitOn c rest

#else

osPathBytes :: OsPath -> BS.ByteString
osPathBytes :: OsPath -> ByteString
osPathBytes = ShortByteString -> ByteString
SBS.fromShort (ShortByteString -> ByteString)
-> (OsPath -> ShortByteString) -> OsPath -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PosixString -> ShortByteString
getPosixString (PosixString -> ShortByteString)
-> (OsPath -> PosixString) -> OsPath -> ShortByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. OsPath -> PosixString
getOsString

bytesOsPath :: BS.ByteString -> OsPath
bytesOsPath :: ByteString -> OsPath
bytesOsPath = PosixString -> OsPath
OsString (PosixString -> OsPath)
-> (ByteString -> PosixString) -> ByteString -> OsPath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ShortByteString -> PosixString
PosixString (ShortByteString -> PosixString)
-> (ByteString -> ShortByteString) -> ByteString -> PosixString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> ShortByteString
SBS.toShort

-- | Run an action with the path marshalled to a NUL-terminated C string.
withOsPathCString :: OsPath -> (CString -> IO a) -> IO a
withOsPathCString :: forall a. OsPath -> (CString -> IO a) -> IO a
withOsPathCString = ByteString -> (CString -> IO a) -> IO a
forall a. ByteString -> (CString -> IO a) -> IO a
BS.useAsCString (ByteString -> (CString -> IO a) -> IO a)
-> (OsPath -> ByteString) -> OsPath -> (CString -> IO a) -> IO a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. OsPath -> ByteString
osPathBytes

-- | Marshal a search path: the paths joined by the @:@ separator.
withSearchPathCString :: [OsPath] -> (CString -> IO a) -> IO a
withSearchPathCString :: forall a. [OsPath] -> (CString -> IO a) -> IO a
withSearchPathCString [OsPath]
ps =
    ByteString -> (CString -> IO a) -> IO a
forall a. ByteString -> (CString -> IO a) -> IO a
BS.useAsCString (ByteString -> [ByteString] -> ByteString
BS.intercalate (Word8 -> ByteString
BS.singleton Word8
0x3a) ((OsPath -> ByteString) -> [OsPath] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map OsPath -> ByteString
osPathBytes [OsPath]
ps))

-- | Read a @:@-separated C search-path string back into a list of paths.
peekSearchPath :: CString -> IO [OsPath]
peekSearchPath :: CString -> IO [OsPath]
peekSearchPath CString
cs =
    ((ByteString -> OsPath) -> [ByteString] -> [OsPath]
forall a b. (a -> b) -> [a] -> [b]
map ByteString -> OsPath
bytesOsPath ([ByteString] -> [OsPath])
-> (ByteString -> [ByteString]) -> ByteString -> [OsPath]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ByteString -> Bool) -> [ByteString] -> [ByteString]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (ByteString -> Bool) -> ByteString -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Bool
BS.null) ([ByteString] -> [ByteString])
-> (ByteString -> [ByteString]) -> ByteString -> [ByteString]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word8 -> ByteString -> [ByteString]
BS.split Word8
0x3a) (ByteString -> [OsPath]) -> IO ByteString -> IO [OsPath]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CString -> IO ByteString
BS.packCString CString
cs

#endif