Targets.hs 9.7 KB

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