Targets.hs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. {-# LANGUAGE OverloadedStrings #-}
  2. {-# LANGUAGE ExistentialQuantification #-}
  3. {-# LANGUAGE ForeignFunctionInterface #-}
  4. {-# LANGUAGE InterruptibleFFI #-}
  5. {-# LANGUAGE EmptyDataDecls #-}
  6. module System.IO.Uniform.Targets (TlsSettings(..), UniformIO(..), SocketIO, FileIO, TlsStream, BoundedPort, SomeIO(..), connectTo, connectToHost, bindPort, accept, openFile, getPeer, closePort) where
  7. import Foreign
  8. import Foreign.C.Types
  9. import Foreign.C.String
  10. import Foreign.C.Error
  11. import qualified Data.IP as IP
  12. import Data.ByteString (ByteString)
  13. import qualified Data.ByteString as BS
  14. import qualified Data.List as L
  15. import Control.Exception
  16. import Control.Applicative ((<$>))
  17. import qualified Network.Socket as Soc
  18. import System.IO.Error
  19. import Data.Default.Class
  20. import System.Posix.Types (Fd(..))
  21. -- | Settings for starttls functions.
  22. data TlsSettings = TlsSettings {tlsPrivateKeyFile :: String, tlsCertificateChainFile :: String, tlsDHParametersFile :: String} deriving (Read, Show)
  23. instance Default TlsSettings where
  24. def = TlsSettings "" "" ""
  25. -- |
  26. -- Typeclass for uniform IO targets.
  27. class UniformIO a where
  28. -- | uRead fd n
  29. --
  30. -- Reads a block of at most n bytes of data from the IO target.
  31. -- Reading will block if there's no data available, but will return immediately
  32. -- if any amount of data is availble.
  33. uRead :: a -> Int -> IO ByteString
  34. -- | uPut fd text
  35. --
  36. -- Writes all the bytes of text into the IO target. Takes care of retrying if needed.
  37. uPut :: a -> ByteString -> IO ()
  38. -- | fClose fd
  39. --
  40. -- Closes the IO target, releasing any allocated resource. Resources may leak if not called
  41. -- for every oppened fd.
  42. uClose :: a -> IO ()
  43. -- | startTLS fd
  44. --
  45. -- Starts a TLS connection over the IO target.
  46. startTls :: TlsSettings -> a -> IO TlsStream
  47. -- | isSecure fd
  48. --
  49. -- Indicates whether the data written or read from fd is secure at transport.
  50. isSecure :: a -> Bool
  51. -- | A type that wraps any type in the UniformIO class.
  52. data SomeIO = forall a. (UniformIO a) => SomeIO a
  53. instance UniformIO SomeIO where
  54. uRead (SomeIO s) n = uRead s n
  55. uPut (SomeIO s) t = uPut s t
  56. uClose (SomeIO s) = uClose s
  57. startTls set (SomeIO s) = startTls set s
  58. isSecure (SomeIO s) = isSecure s
  59. data Nethandler
  60. -- | A bounded IP port from where to accept SocketIO connections.
  61. newtype BoundedPort = BoundedPort {lis :: (Ptr Nethandler)}
  62. data Ds
  63. newtype SocketIO = SocketIO {sock :: (Ptr Ds)}
  64. newtype FileIO = FileIO {fd :: (Ptr Ds)}
  65. data TlsDs
  66. newtype TlsStream = TlsStream {tls :: (Ptr TlsDs)}
  67. -- | UniformIO IP connections.
  68. instance UniformIO SocketIO where
  69. uRead s n = do
  70. allocaArray n (
  71. \b -> do
  72. count <- c_recv (sock s) b (fromIntegral n)
  73. if count < 0
  74. then throwErrno "could not read"
  75. else BS.packCStringLen (b, fromIntegral count)
  76. )
  77. uPut s t = do
  78. BS.useAsCStringLen t (
  79. \(str, n) -> do
  80. count <- c_send (sock s) str $ fromIntegral n
  81. if count < 0
  82. then throwErrno "could not write"
  83. else return ()
  84. )
  85. uClose s = do
  86. f <- Fd <$> c_prepareToClose (sock s)
  87. closeFd f
  88. startTls st s = withCString (tlsCertificateChainFile st) (
  89. \cert -> withCString (tlsPrivateKeyFile st) (
  90. \key -> withCString (tlsDHParametersFile st) (
  91. \para -> do
  92. r <- c_startSockTls (sock s) cert key para
  93. if r == nullPtr
  94. then throwErrno "could not start TLS"
  95. else return . TlsStream $ r
  96. )
  97. )
  98. )
  99. isSecure _ = False
  100. -- | UniformIO type for file IO.
  101. instance UniformIO FileIO where
  102. uRead s n = do
  103. allocaArray n (
  104. \b -> do
  105. count <- c_recv (fd s) b $ fromIntegral n
  106. if count < 0
  107. then throwErrno "could not read"
  108. else BS.packCStringLen (b, fromIntegral count)
  109. )
  110. uPut s t = do
  111. BS.useAsCStringLen t (
  112. \(str, n) -> do
  113. count <- c_send (fd s) str $ fromIntegral n
  114. if count < 0
  115. then throwErrno "could not write"
  116. else return ()
  117. )
  118. uClose s = do
  119. f <- Fd <$> c_prepareToClose (fd s)
  120. closeFd f
  121. -- Not implemented yet.
  122. startTls _ _ = return . TlsStream $ nullPtr
  123. isSecure _ = False
  124. -- | UniformIO wrapper that applies TLS to communication on IO target.
  125. -- This type is constructed by calling startTls on other targets.
  126. instance UniformIO TlsStream where
  127. uRead s n = do
  128. allocaArray n (
  129. \b -> do
  130. count <- c_recvTls (tls s) b $ fromIntegral n
  131. if count < 0
  132. then throwErrno "could not read"
  133. else BS.packCStringLen (b, fromIntegral count)
  134. )
  135. uPut s t = do
  136. BS.useAsCStringLen t (
  137. \(str, n) -> do
  138. count <- c_sendTls (tls s) str $ fromIntegral n
  139. if count < 0
  140. then throwErrno "could not write"
  141. else return ()
  142. )
  143. uClose s = do
  144. d <- c_closeTls (tls s)
  145. f <- Fd <$> c_prepareToClose d
  146. closeFd f
  147. startTls _ s = return s
  148. isSecure _ = True
  149. -- | connectToHost hostName port
  150. --
  151. -- Connects to the given host and port.
  152. connectToHost :: String -> Int -> IO SocketIO
  153. connectToHost host port = do
  154. ip <- getAddr
  155. connectTo ip port
  156. where
  157. getAddr :: IO IP.IP
  158. getAddr = do
  159. add <- Soc.getAddrInfo Nothing (Just host) Nothing
  160. case add of
  161. [] -> throwIO $ mkIOError doesNotExistErrorType "host not found" Nothing Nothing
  162. (a:_) -> case Soc.addrAddress a of
  163. Soc.SockAddrInet _ a' -> return . IP.IPv4 . IP.fromHostAddress $ a'
  164. Soc.SockAddrInet6 _ _ a' _ -> return . IP.IPv6 . IP.fromHostAddress6 $ a'
  165. _ -> throwIO $ mkIOError doesNotExistErrorType "host not found" Nothing Nothing
  166. -- | ConnecctTo ipAddress port
  167. --
  168. -- Connects to the given port of the host at the given IP address.
  169. connectTo :: IP.IP -> Int -> IO SocketIO
  170. connectTo host port = do
  171. r <- case host of
  172. IP.IPv4 host' -> fmap SocketIO $ c_connect4 (fromIntegral . IP.toHostAddress $ host') (fromIntegral port)
  173. IP.IPv6 host' -> fmap SocketIO $ withArray (ipToArray host') (
  174. \add -> c_connect6 add (fromIntegral port)
  175. )
  176. if sock r == nullPtr
  177. then throwErrno "could not connect to host"
  178. else return r
  179. where
  180. ipToArray :: IP.IPv6 -> [CUChar]
  181. ipToArray ip = let
  182. (w0, w1, w2, w3) = IP.toHostAddress6 ip
  183. in L.concat [wtoc w0, wtoc w1, wtoc w2, wtoc w3]
  184. wtoc :: Word32 -> [CUChar]
  185. wtoc w = let
  186. c0 = fromIntegral $ mod w 256
  187. w1 = div w 256
  188. c1 = fromIntegral $ mod w1 256
  189. w2 = div w1 256
  190. c2 = fromIntegral $ mod w2 256
  191. c3 = fromIntegral $ div w2 256
  192. in [c3, c2, c1, c0]
  193. -- | bindPort port
  194. -- Binds to the given IP port, becoming ready to accept connections on it.
  195. -- Binding to port numbers under 1024 will fail unless performed by the superuser,
  196. -- once bounded, a process can reduce its privileges and still accept clients on that port.
  197. bindPort :: Int -> IO BoundedPort
  198. bindPort port = do
  199. r <- fmap BoundedPort $ c_getPort $ fromIntegral port
  200. if lis r == nullPtr
  201. then throwErrno "could not bind to port"
  202. else return r
  203. -- | accept port
  204. --
  205. -- Accept clients on a port previously bound with bindPort.
  206. accept :: BoundedPort -> IO SocketIO
  207. accept port = do
  208. r <- fmap SocketIO $ c_accept (lis port)
  209. if sock r == nullPtr
  210. then throwErrno "could not accept connection"
  211. else return r
  212. -- | Open a file for bidirectional IO.
  213. openFile :: String -> IO FileIO
  214. openFile fileName = do
  215. r <- withCString fileName (
  216. \f -> fmap FileIO $ c_createFile f
  217. )
  218. if fd r == nullPtr
  219. then throwErrno "could not open file"
  220. else return r
  221. -- | Gets the address of the peer socket of a internet connection.
  222. getPeer :: SocketIO -> IO (IP.IP, Int)
  223. getPeer s = allocaArray 16 (
  224. \p6 -> alloca (
  225. \p4 -> alloca (
  226. \iptype -> do
  227. p <- c_getPeer (sock s) p4 p6 iptype
  228. if p == -1
  229. then throwErrno "could not get peer address"
  230. else do
  231. iptp <- peek iptype
  232. if iptp == 1
  233. then do --IPv6
  234. add <- peekArray 16 p6
  235. return (IP.IPv6 . IP.toIPv6b $ map fromIntegral add, fromIntegral p)
  236. else do --IPv4
  237. add <- peek p4
  238. return (IP.IPv4 . IP.fromHostAddress . fromIntegral $ add, fromIntegral p)
  239. )
  240. )
  241. )
  242. closeFd :: Fd -> IO ()
  243. closeFd (Fd f) = c_closeFd f
  244. -- | Closes a BoundedPort, and releases any resource used by it.
  245. closePort :: BoundedPort -> IO ()
  246. closePort p = c_closePort (lis p)
  247. foreign import ccall interruptible "getPort" c_getPort :: CInt -> IO (Ptr Nethandler)
  248. foreign import ccall interruptible "createFromHandler" c_accept :: Ptr Nethandler -> IO (Ptr Ds)
  249. foreign import ccall safe "createFromFileName" c_createFile :: CString -> IO (Ptr Ds)
  250. foreign import ccall interruptible "createToIPv4Host" c_connect4 :: CUInt -> CInt -> IO (Ptr Ds)
  251. foreign import ccall interruptible "createToIPv6Host" c_connect6 :: Ptr CUChar -> CInt -> IO (Ptr Ds)
  252. foreign import ccall interruptible "startSockTls" c_startSockTls :: Ptr Ds -> CString -> CString -> CString -> IO (Ptr TlsDs)
  253. foreign import ccall safe "getPeer" c_getPeer :: Ptr Ds -> Ptr CUInt -> Ptr CUChar -> Ptr CInt -> IO (CInt)
  254. --foreign import ccall safe "getFd" c_getFd :: Ptr Ds -> IO CInt
  255. --foreign import ccall safe "getTlsFd" c_getTlsFd :: Ptr TlsDs -> IO CInt
  256. foreign import ccall safe "closeFd" c_closeFd :: CInt -> IO ()
  257. foreign import ccall safe "prepareToClose" c_prepareToClose :: Ptr Ds -> IO CInt
  258. foreign import ccall safe "closeHandler" c_closePort :: Ptr Nethandler -> IO ()
  259. foreign import ccall safe "closeTls" c_closeTls :: Ptr TlsDs -> IO (Ptr Ds)
  260. foreign import ccall interruptible "sendDs" c_send :: Ptr Ds -> Ptr CChar -> CInt -> IO CInt
  261. --foreign import ccall interruptible "stdDsSend" c_sendStd :: Ptr CChar -> CInt -> IO CInt
  262. foreign import ccall interruptible "tlsDsSend" c_sendTls :: Ptr TlsDs -> Ptr CChar -> CInt -> IO CInt
  263. foreign import ccall interruptible "recvDs" c_recv :: Ptr Ds -> Ptr CChar -> CInt -> IO CInt
  264. --foreign import ccall interruptible "stdDsRecv" c_recvStd :: Ptr CChar -> CInt -> IO CInt
  265. foreign import ccall interruptible "tlsDsRecv" c_recvTls :: Ptr TlsDs -> Ptr CChar -> CInt -> IO CInt