Targets.hs 9.9 KB

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