Targets.hs 9.2 KB

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