@@ -1,76 +0,0 @@
1−{-# LANGUAGE CPP, ForeignFunctionInterface, BangPatterns, ScopedTypeVariables #-}
2−{-|
3− Maintainer: Thomas.DuBuisson@gmail.com
4− Stability: beta
5− Portability: portable
6−
7− Obtain entropy from RDRAND when available.
8−
9−-}
10−
11−module System.EntropyXen
12− ( CryptHandle
13− , openHandle
14− , hGetEntropy
15− , closeHandle
16− , hardwareRandom
17− ) where
18−
19−import Control.Monad (liftM, when)
20−import Data.ByteString as B
21−import System.IO.Error (mkIOError, eofErrorType, ioeSetErrorString)
22−
23−import Foreign (allocaBytes)
24−import Foreign.Ptr
25−import Foreign.C.Types
26−import Data.ByteString.Internal as B
27−
28−#ifdef arch_i386
29−-- See .cabal wrt GCC 4.8.2 asm compilation bug
30−#undef HAVE_RDRAND
31−#endif
32−
33−#ifndef HAVE_RDRAND
34−#error "The entropy package requires RDRAND support when using the halvm/Xen"
35−#endif
36−data CryptHandle = UseRdRand -- or die trying
37−
38−-- |Open a `CryptHandle`
39−openHandle :: IO CryptHandle
40−openHandle = do
41− b <- cpuHasRdRand
42− if b then return UseRdRand
43− else nonRDRandHandle
44− where
45− nonRDRandHandle :: IO CryptHandle
46− nonRDRandHandle = error "entropy: On halvm there is no entropy other than RDRAND."
47−
48−-- |Close the `CryptHandle`
49−closeHandle :: CryptHandle -> IO ()
50−closeHandle UseRdRand = return ()
51−
52−-- | Get random values from the hardware RNG or return Nothing if no
53−-- supported hardware RNG is available.
54−--
55−-- Supported hardware:
56−-- * RDRAND
57−-- * Patches welcome
58−hardwareRandom :: Int -> IO (Maybe B.ByteString)
59−hardwareRandom sz = Just <$> hGetEntropy UseRdRand sz
60−
61−-- |Read random data from a `CryptHandle`, which uses RDRAND (when on Xen)
62−hGetEntropy :: CryptHandle -> Int -> IO B.ByteString
63−hGetEntropy UseRdRand = \n -> do
64− B.create n $ \ptr -> do
65− r <- c_get_rand_bytes (castPtr ptr) (fromIntegral n)
66− when (r /= 0)
67− (fail "RDRand failed to gather entropy")
68−
69−foreign import ccall unsafe "cpu_has_rdrand"
70− c_cpu_has_rdrand :: IO CInt
71−
72−foreign import ccall unsafe "get_rand_bytes"
73− c_get_rand_bytes :: Ptr CUChar -> CSize -> IO CInt
74−
75−cpuHasRdRand :: IO Bool
76−cpuHasRdRand = (/= 0) `fmap` c_cpu_has_rdrand