streamly-network-tls-0.1.0.0: src/Streamly/External/Network/TLS.hs
-- |
-- Module : Streamly.External.Network.TLS
-- Description : TLS connections to a server, as streams
-- License : BSD-3-Clause
--
-- A TLS client for Streamly, over the @tls@ package. A connection gives
-- the bytes received as a stream of arrays, and takes the bytes to send
-- through a function or a fold. It knows nothing of the protocol carried.
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- > import Streamly.Data.Stream (toList)
-- > import Streamly.External.ByteString (toArray)
-- > import Streamly.External.Network.TLS (config, received, send, withConnection)
-- >
-- > main :: IO ()
-- > main = withConnection (config "example.org" 443) $ \connection -> do
-- > send connection (toArray "GET / HTTP/1.0\r\nHost: example.org\r\n\r\n")
-- > toList (received connection) >>= print . length
--
-- The server must present a certificate that is valid for the name asked
-- and signed by an authority that is trusted: those of the system, or
-- those of a file. There is no way to skip the check.
--
-- For the side of a server, 'acceptConnection' does the handshake on a
-- connection already accepted, with the t'Credentials' of the server.
module Streamly.External.Network.TLS
( -- * Connections
Config (..)
, config
, Certificates (..)
, Connection
, withConnection
, open
, close
, ConnectTimedOut (..)
-- * The side of a server
, Credentials
, loadCredentials
, acceptConnection
-- * Bytes
, send
, write
, received
, transport
) where
import Control.Exception (Exception, IOException, SomeException, bracketOnError,
finally, mask, throwIO, try)
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO (..))
import Data.ByteString qualified as BS (null)
import Data.ByteString.Lazy (fromStrict)
import Data.Word (Word8)
import Data.X509.CertificateStore (CertificateStore, readCertificateStore)
import Network.Socket (Socket)
import Network.Socket qualified as N (close)
import Network.TLS (ClientParams (clientShared), Context, Credential,
ServerParams (serverShared),
Shared (sharedCAStore, sharedCredentials), bye,
contextClose, contextNew, credentialLoadX509,
defaultParamsClient, defaultParamsServer, handshake,
recvData, sendData)
import Network.TLS qualified as TLS (Credentials (Credentials))
import Streamly.Data.Array (Array)
import Streamly.Data.Fold (Fold, drainMapM)
import Streamly.Data.Stream (Stream, unfoldrM)
import Streamly.External.ByteString (fromArray, toArray)
import Streamly.External.Network.TCP (Transport (Transport, receive, send),
connect)
import System.Timeout (timeout)
import System.X509 (getSystemCertificateStore)
-- | The authorities trusted to sign the certificate of the server.
data Certificates
= -- | Those the system trusts.
SystemCertificates
| -- | Those of a file of certificates in PEM, or of a directory of such
-- files, and no other. A server with a certificate of its own making
-- is reached by giving that certificate here.
CertificatesFrom FilePath
deriving stock (Eq, Show)
-- | Where to connect, and whom to expect there.
data Config = Config
{ host :: String
-- ^ A host name or an address, to connect to.
, port :: Int
, serverName :: String
-- ^ The name the certificate of the server must be valid for; also
-- sent to the server, which may hold several (server name indication).
, certificates :: Certificates
, connectTimeout :: Maybe Int
-- ^ Microseconds allowed for the TCP connection and the TLS handshake
-- together. 'Nothing' waits without end.
}
deriving stock (Eq, Show)
-- | A host and a port; the certificate must be valid for the host, and
-- signed by an authority the system trusts; thirty seconds to connect.
config :: String -> Int -> Config
config host port = Config {host, port, serverName = host, certificates = SystemCertificates, connectTimeout = Just 30_000_000}
-- | The connection was not ready within the time allowed: the server did
-- not accept it, or did not finish the TLS handshake.
data ConnectTimedOut = ConnectTimedOut
deriving stock (Eq, Show)
instance Exception ConnectTimedOut
-- | An open connection, past its handshake: the TLS session, and what
-- frees the connection under it when this library opened it.
data Connection = Connection Context (IO ())
-- | Connect, do the TLS handshake and use the connection. When the
-- function returns, the server is told that nothing more comes, and the
-- connection is closed.
--
-- Throws 'TLS.TLSException' when the handshake fails, among others for a
-- certificate that is not accepted; t'ConnectTimedOut' when the connection
-- is not ready in time; and 'IOError' when the TCP connection fails or the
-- certificates cannot be read.
--
-- Once the connection is open nothing limits the waits: a caller that
-- needs it wraps @send@ and 'received' (the @limitTransport@ of
-- @streamly-http@ does, for the transports made of them).
withConnection :: Config -> (Connection -> IO a) -> IO a
withConnection settings use =
-- The connection is opened unmasked, so that its time limit can stop
-- it; open closes what it opened when it is stopped.
mask $ \restore -> do
connection <- restore (open settings)
restore (use connection) `finally` close connection
-- | Connect and do the TLS handshake, for a connection that outlives a
-- function: 'close' it when it is no longer needed. Prefer
-- 'withConnection', which cannot forget to. Throws like 'withConnection'.
open :: Config -> IO Connection
open settings = do
store <- trusted settings.certificates
let defaults = defaultParamsClient settings.serverName ""
parameters = defaults {clientShared = (clientShared defaults) {sharedCAStore = store}}
within (ready parameters)
where
within action = case settings.connectTimeout of
Nothing -> action
Just microseconds -> timeout microseconds action >>= maybe (throwIO ConnectTimedOut) pure
ready parameters =
bracketOnError (connect settings.host settings.port) N.close $ \socket -> do
context <- contextNew socket parameters
handshake context
pure (Connection context (contextClose context `finally` N.close socket))
-- | Tell the other side that nothing more comes, and free a connection
-- got from 'open'. Never throws; closing twice does no harm.
close :: Connection -> IO ()
close (Connection context release) = do
-- The other side may already be gone.
void (try @SomeException (bye context))
void (try @SomeException release)
trusted :: Certificates -> IO CertificateStore
trusted = \case
SystemCertificates -> getSystemCertificateStore
CertificatesFrom path ->
readCertificateStore path >>= maybe (throwIO (userError ("no certificate could be read from " <> path))) pure
-- | What a server proves its name with: a certificate and its private key.
newtype Credentials = Credentials Credential
-- | Read a certificate, with the certificates that sign it if any, and
-- its private key, from two files in PEM. Throws 'IOError' when they
-- cannot be read.
loadCredentials :: FilePath -> FilePath -> IO Credentials
loadCredentials certificateFile keyFile =
credentialLoadX509 certificateFile keyFile
>>= either (\problem -> throwIO (userError ("no credentials could be read from " <> certificateFile <> " and " <> keyFile <> ": " <> problem))) (pure . Credentials)
-- | Do the TLS handshake of a server on a connection it has accepted,
-- within a number of microseconds ('Nothing' waits without end), and use
-- the connection. When the function returns, the client is told that
-- nothing more comes. The socket stays open: closing it is up to the
-- caller.
--
-- Throws 'TLS.TLSException' when the handshake fails, t'ConnectTimedOut'
-- when it is not done in time, and 'IOError' when the connection fails.
acceptConnection :: Credentials -> Maybe Int -> Socket -> (Connection -> IO a) -> IO a
acceptConnection (Credentials credential) limit socket use =
-- The handshake runs unmasked, so that its time limit can stop it.
mask $ \restore -> do
context <- contextNew socket parameters
( do
restore (within (handshake context))
value <- restore (use (Connection context (pure ())))
-- The client may already be gone.
void (try @IOException (bye context))
pure value
)
`finally` contextClose context
where
shared = (serverShared defaultParamsServer) {sharedCredentials = TLS.Credentials [credential]}
parameters = defaultParamsServer {serverShared = shared}
within action = case limit of
Nothing -> action
Just microseconds -> timeout microseconds action >>= maybe (throwIO ConnectTimedOut) pure
-- | Send bytes. Throws 'TLS.TLSException' or 'IOError' when the
-- connection fails.
send :: MonadIO m => Connection -> Array Word8 -> m ()
send (Connection context _) bytes = sendData context (fromStrict (fromArray bytes))
-- | The connection as a transport, for the protocols written against
-- one: @streamly-http@ and @streamly-websockets@ take it as it is.
transport :: Connection -> Transport
transport connection = Transport {send = send connection, receive = received connection}
-- | Send each array.
write :: MonadIO m => Connection -> Fold m (Array Word8) ()
write connection = drainMapM (send connection)
-- | The bytes received, until the server ends the connection. Throws
-- like @send@, from the stream.
received :: MonadIO m => Connection -> Stream m (Array Word8)
received (Connection context _) = unfoldrM next ()
where
next () = do
bytes <- recvData context
pure (if BS.null bytes then Nothing else Just (toArray bytes, ()))