streamly-http-tls-0.1.0.0: src/Streamly/External/Network/HTTP/TLS.hs
-- |
-- Module : Streamly.External.Network.HTTP.TLS
-- Description : Fetching http and https URLs
-- License : BSD-3-Clause
--
-- Give a URL, get the response: the scheme chooses between plain TCP and
-- TLS, and redirects are followed.
--
-- > {-# LANGUAGE OverloadedRecordDot #-}
-- > {-# LANGUAGE OverloadedStrings #-}
-- > import Streamly.External.Network.HTTP (Response (..), header)
-- > import Streamly.External.Network.HTTP.TLS (fetchUrl)
-- >
-- > main :: IO ()
-- > main = do
-- > response <- fetchUrl "https://example.org/"
-- > print (response.status, header "content-type" response)
--
-- As with @streamly-http@, a status is never an error. Each call opens
-- its connections and closes them; to keep them from one URL to the next,
-- see 'withSecureClient'. Each wait is limited, and so is the size of
-- the head of a response (see 'limits'); the whole time taken is not, nor
-- the size of a body unless a limit is set.
module Streamly.External.Network.HTTP.TLS
( -- * Fetching a URL
fetchUrl
, withUrl
-- * Options
, Options (..)
, defaultOptions
, fetchUrlWith
, withUrlWith
-- * One exchange
, withResponseAt
-- * Several requests over one connection
, withSessionAt
-- * Several URLs, their connections kept
, withSecureClient
, fetchUrlIn
, withUrlIn
-- * Errors
, UrlError (..)
) where
import Control.Exception (Exception, throwIO, try)
import Data.ByteString (ByteString)
import Data.ByteString.Char8 qualified as BS8 (map)
import Data.Char (toLower)
import Data.Word (Word8)
import Streamly.Data.Array (Array, create, reader)
import Streamly.Data.Fold (drain)
import Streamly.Data.Stream (Stream, fold, unfoldEach)
import Streamly.Data.Stream qualified as S (take)
import Streamly.External.Network.HTTP (Client, Header,
HttpError (ConnectTimedOut),
Limits (connectTimeout),
Request (host, port),
Response (body, status), Session,
connectWithin, defaultLimits, header,
opened, withClientOver, withHeaders,
withResponseFrom, withResponseOver,
withResponseWithin, withSession,
withSessionOver)
import Streamly.External.Network.HTTP.URL (Scheme (..),
Url (host, port, scheme), parseUrl,
renderUrl, resolve, urlRequest)
import Streamly.External.Network.HTTP.Wire (validateRequest)
import Streamly.External.Network.TLS (Certificates (SystemCertificates),
Config (certificates, connectTimeout),
close, config, open, transport,
withConnection)
import Streamly.External.Network.TLS qualified as NT (ConnectTimedOut (ConnectTimedOut))
-- | How URLs are fetched.
data Options = Options
{ certificates :: Certificates
-- ^ The authorities trusted to sign the certificates of @https@
-- servers. Not looked at by 'fetchUrlIn' and 'withUrlIn', which have
-- those of their client.
, limits :: Limits
-- ^ How long to wait for each connection and for each server to go on
-- once connected, and how large a head and a body to accept. For
-- @https@ the time to connect includes the TLS handshake.
, maxRedirects :: Int
-- ^ How many redirects are followed before giving up.
, requestHeaders :: [Header]
-- ^ Headers for every request. When a redirect leads to another host,
-- @Authorization@, @Proxy-Authorization@ and @Cookie@ are left out.
}
deriving stock (Eq, Show)
-- | The certificates of the system, 'defaultLimits' (thirty seconds to
-- connect, thirty seconds of silence, a head of at most 64 KiB, a body of
-- any size), ten redirects, no header.
defaultOptions :: Options
defaultOptions = Options {certificates = SystemCertificates, limits = defaultLimits, maxRedirects = 10, requestHeaders = []}
-- | What can go wrong with a URL, besides what @streamly-http@ and
-- @streamly-network-tls@ throw.
data UrlError
= -- | Not an @http@ or @https@ URL: the text, and why.
InvalidUrl ByteString String
| -- | More redirects than allowed: the limit, and the URL that was not
-- fetched.
TooManyRedirects Int ByteString
| -- | A redirect to something that cannot be followed: the URL that
-- redirected, and its @Location@.
InvalidLocation ByteString ByteString
deriving stock (Eq, Show)
instance Exception UrlError
-- | Fetch a URL with a @GET@ request, following redirects, and read the
-- whole response into memory.
--
-- Throws 'UrlError'; 'HttpError' for a response that cannot be read, and
-- for a server that takes too long to connect to (@ConnectTimedOut@) or
-- goes silent (@ResponseTimedOut@), or sends more than allowed
-- (@HeadTooLarge@, @BodyTooLarge@);
-- @TLSException@ (of the @tls@ package) when a TLS connection fails, among
-- others for a certificate that is not accepted; and 'IOError' when a
-- connection fails.
fetchUrl :: ByteString -> IO (Response (Array Word8))
fetchUrl = fetchUrlWith defaultOptions
-- | Like 'fetchUrl', with options.
fetchUrlWith :: Options -> ByteString -> IO (Response (Array Word8))
fetchUrlWith options text = withUrlWith options text whole
-- | Fetch a URL with a @GET@ request, following redirects, and use the
-- response while its connection is open: consume the body inside the
-- function, and only once. Throws like 'fetchUrl'.
withUrl :: ByteString -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a
withUrl = withUrlWith defaultOptions
-- | Like 'withUrl', with options.
--
-- Responses with the status 301, 302, 303, 307 or 308 and a @Location@
-- are redirects; one without a @Location@ is given as it is. Redirects to
-- the same server go over the same connection.
withUrlWith :: Options -> ByteString -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a
withUrlWith options text use =
withSecureClient options.certificates options.limits (\client -> withUrlIn client options text use)
-- | Use a client that speaks in clear and over TLS: the requests sent
-- through it ('fetchUrlIn', 'withUrlIn', and @fetchFrom@ and
-- 'withResponseFrom' of @streamly-http@) reuse the connections it keeps
-- for each server, which over TLS spares a handshake each time. The
-- servers reached over TLS must present a certificate signed by one of
-- the authorities trusted. The connections kept are closed at the end.
withSecureClient :: Certificates -> Limits -> (Client -> IO a) -> IO a
withSecureClient trusted within = withClientOver within $ \scheme host port -> case scheme of
Http -> connectWithin within.connectTimeout host port >>= opened
Https -> do
let settings = (config host port) {certificates = trusted, connectTimeout = within.connectTimeout}
-- One error for a connection that is not ready in time, whatever the
-- scheme.
connection <- try (open settings) >>= either (\NT.ConnectTimedOut -> throwIO ConnectTimedOut) pure
pure (transport connection, close connection)
-- | Like 'fetchUrlWith', through a client: several URLs fetched this way
-- share its connections. The certificates and the limits are those of the
-- client; those of the options are not looked at.
fetchUrlIn :: Client -> Options -> ByteString -> IO (Response (Array Word8))
fetchUrlIn client options text = withUrlIn client options text whole
-- | Like 'withUrlWith', through a client. See 'fetchUrlIn'.
withUrlIn :: Client -> Options -> ByteString -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a
withUrlIn client options text use = do
start <- either (throwIO . InvalidUrl text) pure (parseUrl text)
follow start start 0
where
follow start current followed = do
let request = withHeaders (headersFor start current) (urlRequest current)
outcome <- withResponseFrom client current.scheme request $ \response ->
case redirection response of
Nothing -> Right <$> use response
Just location -> do
-- Read the body of the redirect, so that its connection can
-- serve the next request; a long one is not worth it.
fold drain (S.take 16 response.body)
pure (Left location)
case outcome of
Right value -> pure value
Left location -> do
next <- either (const (throwIO (InvalidLocation (renderUrl current) location))) pure (resolve current location)
if followed >= options.maxRedirects
then throwIO (TooManyRedirects options.maxRedirects (renderUrl next))
else follow start next (followed + 1 :: Int)
redirection response
| response.status `elem` [301, 302, 303, 307, 308] = header "location" response
| otherwise = Nothing
-- What identifies the caller stays with the server it was meant for.
headersFor start current
| (current.scheme, current.host, current.port) == (start.scheme, start.host, start.port) = options.requestHeaders
| otherwise = filter (\(name, _) -> BS8.map toLower name `notElem` ["authorization", "proxy-authorization", "cookie"]) options.requestHeaders
whole :: Response (Stream IO (Array Word8)) -> IO (Response (Array Word8))
whole response = do
bytes <- fold create (unfoldEach reader response.body)
pure (bytes <$ response)
-- | Send one request to its host and port, in clear or over TLS, and use
-- the response while the connection is open. No redirect is followed.
-- This is @withResponse@ with the scheme as one more argument: it takes
-- any method and any body.
withResponseAt :: Certificates -> Limits -> Scheme -> Request -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a
withResponseAt trusted within scheme request use = case scheme of
Http -> withResponseWithin within request use
Https -> do
either throwIO pure (validateRequest request)
let settings = (config request.host request.port) {certificates = trusted, connectTimeout = within.connectTimeout}
connected <- try (withConnection settings (\connection -> withResponseOver within (transport connection) request use))
-- One error for a connection that is not ready in time, whatever the
-- scheme.
either (\NT.ConnectTimedOut -> throwIO ConnectTimedOut) pure connected
-- | Use a session with a host and a port, in clear or over TLS: its
-- requests (@withResponseIn@, @fetchIn@) reuse one connection when they
-- can. No redirect is followed. For TLS, the time to connect covers the
-- handshake, done again each time the connection has to be opened anew.
withSessionAt :: Certificates -> Limits -> Scheme -> String -> Int -> (Session -> IO a) -> IO a
withSessionAt trusted within scheme host port use = case scheme of
Http -> withSession within host port use
Https -> withSessionOver within secure use
where
settings = (config host port) {certificates = trusted, connectTimeout = within.connectTimeout}
secure = do
-- One error for a connection that is not ready in time, whatever
-- the scheme.
connection <- try (open settings) >>= either (\NT.ConnectTimedOut -> throwIO ConnectTimedOut) pure
pure (transport connection, close connection)