packages feed

streamly-http (empty) → 0.1.0.0

raw patch · 8 files changed

+2007/−0 lines, 8 filesdep +asyncdep +basedep +bytestring

Dependencies added: async, base, bytestring, containers, flatparse, network, streamly-bytestring, streamly-core, streamly-flatparse, streamly-http, streamly-network-tcp, tasty, tasty-hunit, tasty-quickcheck

Files

+ CHANGELOG.md view
@@ -0,0 +1,19 @@+# Revision history for streamly-http++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* An HTTP/1.1 client over TCP: `get`, `fetch`, `withResponse`. Bodies+  delimited by `Content-Length`, by the chunked transfer coding or by the+  end of the connection; heads read with flatparse parsers.+* Limits of time and of size (`Limits`), on every wait, on the head of a+  response and, when asked, on its body.+* Sessions (`withSession`) and clients (`withClient`), which keep+  connections from one request to the next.+* Requests over a connection of the caller (`Transport`,+  `withResponseOver`, `fetchOver`), for HTTPS among others.+* The message format alone, on streams of byte arrays+  (`Streamly.External.Network.HTTP.Wire`), which also reads the head of a+  request.+* `http` and `https` URLs: `parseUrl`, `renderUrl`, `resolve`,+  `urlRequest`.
+ LICENSE view
@@ -0,0 +1,30 @@+Copyright (c) 2025, Xavier Dectot++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++    * Neither the name of GuillaumedeVolpiano nor the names of other+      contributors may be used to endorse or promote products derived+      from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,99 @@+# streamly-http++A small HTTP/1.1 client written with [Streamly](https://streamly.composewell.com/).+The response head is read with+[flatparse](https://hackage.haskell.org/package/flatparse) parsers; the body+is a stream of+byte arrays, whether it is delimited by `Content-Length`, by the chunked+transfer coding or by the end of the connection.++```haskell+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}++import Streamly.Data.Fold qualified as F (length)+import Streamly.Data.Stream (fold)+import Streamly.External.Network.HTTP (Response (..), fetch, get, header,+                                       withResponse)++main :: IO ()+main = do+  -- The whole response in memory.+  response <- fetch (get "example.org" 80 "/")+  print (response.status, header "content-type" response)++  -- The body as a stream, read while the connection is open.+  arrays <- withResponse (get "example.org" 80 "/") $ \streamed ->+    fold F.length streamed.body+  print arrays+```++## Several requests to one server++```haskell+import Streamly.External.Network.HTTP (Response (..), defaultLimits, fetchIn,+                                       get, withSession)++main :: IO ()+main = withSession defaultLimits "example.org" 80 $ \session -> do+  first <- fetchIn session (get "example.org" 80 "/a")+  second <- fetchIn session (get "example.org" 80 "/b")+  print (first.status, second.status)+```++The connection is kept when the body was read to its end, its length was+announced or it was chunked, and the server did not ask to close. A+connection that the server has closed while idle is replaced without a+word: the request is sent again once, unless its body is a stream.++For several servers, `withClient` keeps a session for each, and more than+one for a server whose requests overlap:++```haskell+main :: IO ()+main = withClient defaultLimits $ \client -> do+  first <- fetchFrom client Http (get "example.org" 80 "/a")+  second <- fetchFrom client Http (get "example.net" 80 "/b")+  print (first.status, second.status)+```++## Modules++- `Streamly.External.Network.HTTP`: the client over TCP (`get`, `fetch`,+  `withResponse`).+- `Streamly.External.Network.HTTP.Wire`: the message format alone+  (`renderRequest`, `readResponse`), to run it over another transport. It+  also reads the head of a request, for the servers of protocols that+  start with an HTTP exchange.+- `Streamly.External.Network.HTTP.URL`: `http` and `https` URLs, read,+  written back and resolved against one another.++## Limits of this version++- TLS is not built in. `withResponseOver` and `fetchOver` take a connection+  opened by other means, as a `Transport`: one of+  [streamly-network-tls](https://github.com/GuillaumedeVolpiano/streamly-network-tls)+  gives HTTPS.+- One connection per request (`Connection: close`), unless the requests go+  through a session: `withSession` keeps the connection to a server for+  the next request when the response allows it.+- Redirects are not followed and content codings are not decoded.+- A request names its host, its port and its target. URLs are read by+  `Streamly.External.Network.HTTP.URL`; fetching by URL, with the scheme+  choosing between TCP and TLS, is what+  [streamly-http-tls](https://github.com/GuillaumedeVolpiano/streamly-http-tls)+  adds.+- `Limits` bounds each wait (thirty seconds to connect, thirty seconds of+  silence by default) and the head of a response (64 KiB by default). The+  whole exchange is not bounded: use `System.Timeout.timeout`. The body is+  not either by default: set `maxBodySize` when the server is not trusted.+- A status is never an error: look at `status`.++## Building++To build against copies of+[streamly-network-tcp](https://hackage.haskell.org/package/streamly-network-tcp)+and+[streamly-flatparse](https://hackage.haskell.org/package/streamly-flatparse)+checked out next to this repository, pass+`--project-file=cabal.project.siblings`.
+ src/Streamly/External/Network/HTTP.hs view
@@ -0,0 +1,413 @@+-- |+-- Module      : Streamly.External.Network.HTTP+-- Description : A small HTTP/1.1 client over TCP+-- License     : BSD-3-Clause+--+-- An HTTP/1.1 client over plain TCP, written with Streamly: the response+-- head is read with flatparse parsers and the body is a stream of byte+-- arrays.+--+-- > {-# LANGUAGE OverloadedRecordDot #-}+-- > {-# LANGUAGE OverloadedStrings #-}+-- > import Streamly.External.Network.HTTP (Response (..), fetch, get, header)+-- >+-- > main :: IO ()+-- > main = do+-- >   response <- fetch (get "example.org" 80 "/")+-- >   print (response.status, header "content-type" response)+--+-- Each request opens a connection and closes it afterwards, unless it+-- goes through a t'Session', which keeps its connection for the next. TLS is not+-- built in: 'withResponseOver' takes a connection opened by other means,+-- such as one of @streamly-network-tls@. No redirect is followed and no+-- content coding is decoded. Each wait is limited, and so is the head of a+-- response (see t'Limits'); the body is bounded only when asked+-- (@maxBodySize@), and the whole time taken never is: wrap the calls in+-- 'System.Timeout.timeout' as needed.+-- A status is never an error: look at 'status'.+module Streamly.External.Network.HTTP+  ( -- * Requests+    Request (..)+  , RequestBody (..)+  , Header+  , get+  , withHeaders+  , withBody++    -- * Responses+  , Response (..)+  , header+  , withResponse+  , fetch++    -- * Limits+  , Limits (..)+  , defaultLimits+  , noLimits+  , withResponseWithin+  , fetchWithin++    -- * Several requests over one connection+  , Session+  , withSession+  , withSessionOver+  , withResponseIn+  , fetchIn++    -- * Several servers, their connections kept+  , Client+  , withClient+  , withClientOver+  , withResponseFrom+  , fetchFrom++    -- * Other transports+  , Transport (..)+  , socketTransport+  , opened+  , limitTransport+  , withResponseOver+  , fetchOver+  , connect+  , connectWithin++    -- * Errors+  , HttpError (..)+  ) where++import Control.Concurrent.MVar (MVar, modifyMVar, newMVar, putMVar, readMVar,+                                takeMVar)+import Control.Exception (IOException, SomeException, bracket, finally,+                          fromException, mask, mask_, onException, throwIO, try)+import Control.Monad (void)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as BS8 (map)+import Data.Char (toLower)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.Map.Strict (Map, elems, empty, findWithDefault, insert, insertWith)+import Data.Map.Strict qualified as M (lookup)+import Data.Maybe (isJust)+import Data.Word (Word8)+import Network.Socket (Socket, close)+import Streamly.Data.Array (Array, create, reader)+import Streamly.Data.Array qualified as A (length)+import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (Stream, fold, unfoldEach, unfoldrM)+import Streamly.Data.Stream qualified as S (mapM)+import Streamly.Data.StreamK (StreamK, fromStream, uncons)+import Streamly.External.Network.HTTP.URL (Scheme (..))+import Streamly.External.Network.HTTP.Wire (Header, HttpError (..),+                                            Request (..), RequestBody (..),+                                            Response (..), header,+                                            readResponseReusable,+                                            readResponseWithin, renderRequest,+                                            validateRequest, withBody,+                                            withHeaders)+import Streamly.External.Network.TCP (Transport (..), connect, opened,+                                      socketTransport)+import Streamly.External.Network.TCP qualified as NT (connectWithin)+import System.Timeout (timeout)++-- | A @GET@ request for a target on a host and a port, without headers.+-- 'withHeaders' and 'withBody' change the fields that t'Request' shares+-- with t'Response'.+get :: String -> Int -> ByteString -> Request+get host port target = Request {method = "GET", host, port, target, headers = [], body = NoBody}++-- | Send a request and use the response while the connection is open.+--+-- The body is read from the connection as its stream is consumed: consume+-- it inside the function, and only once. The connection is closed when the+-- function returns, whether the body was read to its end or not.+--+-- The request is sent with @Connection: close@, in place of any+-- @Connection@ header of its own.+--+-- Throws 'HttpError' for a request that cannot be written and for a+-- response that cannot be read, and 'IOError' when the connection fails.+withResponse :: Request -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a+withResponse = withResponseWithin defaultLimits++-- | Send a request and read the whole response into memory.+fetch :: Request -> IO (Response (Array Word8))+fetch = fetchWithin defaultLimits++-- | How long to wait, in microseconds, and how much to accept, in bytes.+-- 'Nothing' sets no limit.+data Limits = Limits+  { connectTimeout :: Maybe Int+  -- ^ For the connection to open.+  , idleTimeout :: Maybe Int+  -- ^ For the server to send its next bytes, whether the response has+  -- started or not, and to take the next bytes of the request. It bounds+  -- each wait, not the whole exchange: a response that keeps coming can+  -- take any time. Bound the whole with 'System.Timeout.timeout'.+  , maxHeadSize :: Maybe Int+  -- ^ For the status line and the headers of the response, interim+  -- responses included. 'HeadTooLarge' beyond.+  , maxBodySize :: Maybe Int+  -- ^ For the body of the response, as received. 'BodyTooLarge' beyond:+  -- at once when the response announces its length, from the stream+  -- otherwise.+  }+  deriving stock (Eq, Show)++-- | Thirty seconds to connect, thirty seconds of silence, a head of at+-- most 64 KiB, and a body of any size: set 'maxBodySize' before reading a+-- whole response into memory from a server that is not trusted.+defaultLimits :: Limits+defaultLimits = Limits {connectTimeout = Just 30_000_000, idleTimeout = Just 30_000_000, maxHeadSize = Just 65536, maxBodySize = Nothing}++-- | No limit at all.+noLimits :: Limits+noLimits = Limits {connectTimeout = Nothing, idleTimeout = Nothing, maxHeadSize = Nothing, maxBodySize = Nothing}++-- | Like 'withResponse', within other limits than 'defaultLimits'.+-- Throws 'ConnectTimedOut', 'ResponseTimedOut', 'HeadTooLarge' and+-- 'BodyTooLarge' when they are exceeded.+withResponseWithin :: Limits -> Request -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a+withResponseWithin limits request use = do+  either throwIO pure (validateRequest request)+  -- The connection is opened unmasked, so that its time limit can stop+  -- it; connectWithin closes what it opened when it is stopped.+  mask $ \restore -> do+    socket <- restore (connectWithin limits.connectTimeout request.host request.port)+    restore (withResponseOver limits (socketTransport socket) request use) `finally` close socket++-- | Like 'fetch', within other limits than 'defaultLimits'.+fetchWithin :: Limits -> Request -> IO (Response (Array Word8))+fetchWithin limits request = withResponseWithin limits request collect++-- | The same transport, with a limit in microseconds on each wait: for+-- the next bytes received, and for bytes to be sent. Exceeding it throws+-- 'ResponseTimedOut'. 'Nothing' changes nothing.+limitTransport :: Maybe Int -> Transport -> Transport+limitTransport Nothing transport = transport+limitTransport (Just microseconds) transport =+  Transport+    { send = within . transport.send+    , receive = unfoldrM (within . uncons) (fromStream transport.receive)+    }+  where+    within :: IO a -> IO a+    within action = timeout microseconds action >>= maybe (throwIO ResponseTimedOut) pure++-- | Like 'withResponseWithin', over a connection that is already open:+-- the limits apply, except the time to connect. The host and the port of+-- the request only serve its @Host@ header. The request asks the server+-- to close the connection after the response: one exchange for each+-- transport. Opening and closing it are up to the caller.+withResponseOver :: Limits -> Transport -> Request -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a+withResponseOver limits transport request use = do+  either throwIO pure (validateRequest request)+  fold (drainMapM limited.send) (renderRequest closing)+  response <- readResponseWithin limits.maxHeadSize limits.maxBodySize request.method (fromStream limited.receive)+  use response+  where+    limited = limitTransport limits.idleTimeout transport+    closing = withHeaders (filter (\(name, _) -> BS8.map toLower name /= "connection") request.headers <> [("Connection", "close")]) request++-- | Like 'fetchWithin', over a connection that is already open.+fetchOver :: Limits -> Transport -> Request -> IO (Response (Array Word8))+fetchOver limits transport request = withResponseOver limits transport request collect++-- | A server, and the connection to it that is kept from one request to+-- the next.+data Session = Session+  { opener :: IO (Transport, IO ())+  , limits :: Limits+  , live :: MVar (Maybe Live)+  -- ^ The connection kept, if any. Held during an exchange: the requests+  -- of a session go one at a time.+  }++-- | An open connection of a session.+data Live = Live+  { transport :: Transport+  , shut :: IO ()+  , input :: StreamK IO (Array Word8)+  -- ^ What is still to read from the connection.+  , received :: IORef Int+  -- ^ How many bytes came from the connection so far.+  }++-- | Use a session with a host and a port, over plain TCP. Its requests+-- reuse one connection when they can, instead of opening one each: see+-- 'withResponseIn'. The connection kept is closed at the end.+withSession :: Limits -> String -> Int -> (Session -> IO a) -> IO a+withSession limits host port = withSessionOver limits (connectWithin limits.connectTimeout host port >>= opened)++-- | Like 'withSession', with the way to open a connection to the server+-- left to an action, which gives a transport and what closes it: for TLS,+-- among others. The time to connect is up to that action; the other+-- limits apply.+withSessionOver :: Limits -> IO (Transport, IO ()) -> (Session -> IO a) -> IO a+withSessionOver limits opener = bracket (newSession limits opener) closeSession++newSession :: Limits -> IO (Transport, IO ()) -> IO Session+newSession limits opener = Session opener limits <$> newMVar Nothing++-- | Close the connection a session keeps. The session can still be used:+-- its next request opens another.+closeSession :: Session -> IO ()+closeSession session = mask_ $ do+  kept <- takeMVar session.live+  mapM_ (quietly . (.shut)) kept+  putMVar session.live Nothing++-- | Connections to any number of servers, kept from one request to the+-- next: a session for each server asked, and more than one when requests+-- to the same server overlap.+data Client = Client+  { connectTo :: Scheme -> String -> Int -> IO (Transport, IO ())+  , limits :: Limits+  , idle :: MVar (Maybe (Map (Scheme, String, Int) [Session]))+  -- ^ The sessions not in use, by server; 'Nothing' once the client is+  -- closed.+  }++-- | How many sessions not in use are kept for one server.+maxIdleSessions :: Int+maxIdleSessions = 4++-- | Use a client over plain TCP. Its requests ('withResponseFrom',+-- 'fetchFrom') reuse the connections it keeps, as those of a session do,+-- for every server they go to. A request over TLS is refused with+-- 'InvalidRequest': see @streamly-http-tls@ for a client that does both.+-- The connections kept are closed at the end.+withClient :: Limits -> (Client -> IO a) -> IO a+withClient limits = withClientOver limits $ \scheme host port -> case scheme of+  Https -> throwIO (InvalidRequest "this client only speaks in clear")+  Http -> connectWithin limits.connectTimeout host port >>= opened++-- | Like 'withClient', with the way to open a connection to a server left+-- to a function of the scheme, the host and the port, which gives a+-- transport and what closes it.+withClientOver :: Limits -> (Scheme -> String -> Int -> IO (Transport, IO ())) -> (Client -> IO a) -> IO a+withClientOver limits connectTo = bracket (Client connectTo limits <$> newMVar (Just empty)) finish+  where+    finish client = mask_ $ do+      kept <- takeMVar client.idle+      putMVar client.idle Nothing+      mapM_ closeSession (concat (maybe [] elems kept))++-- | Send a request to the host and the port it names, in clear or over+-- TLS, and use the response, as 'withResponseIn' does, over a connection+-- the client keeps for that server when one is free.+withResponseFrom :: Client -> Scheme -> Request -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a+withResponseFrom client scheme request use = do+  either throwIO pure (validateRequest request)+  bracket acquire release (\session -> withResponseIn session request use)+  where+    server = (scheme, request.host, request.port)+    acquire = modifyMVar client.idle $ \kept -> case kept >>= M.lookup server of+      Just (session : others) -> pure (insert server others <$> kept, session)+      _ -> (kept,) <$> newSession client.limits (client.connectTo scheme request.host request.port)+    release session = do+      -- A session that has lost its connection is not worth keeping: it+      -- would only stand before one that still has its own.+      connected <- isJust <$> readMVar session.live+      keep <- modifyMVar client.idle $ \kept -> pure $ case kept of+        Just sessions | connected, length (findWithDefault [] server sessions) < maxIdleSessions -> (Just (insertWith (<>) server [session] sessions), True)+        _ -> (kept, False)+      if keep then pure () else closeSession session++-- | Send a request through a client and read the whole response into+-- memory. See 'withResponseFrom'.+fetchFrom :: Client -> Scheme -> Request -> IO (Response (Array Word8))+fetchFrom client scheme request = withResponseFrom client scheme request collect++-- | Send a request in a session and use the response, as 'withResponse'+-- does, over the connection of the session when there is one.+--+-- The connection is kept for the next request when the response allows+-- it: its body was consumed to its end inside the function, its length+-- was announced or it was chunked, and the server did not ask to close.+-- Otherwise it is closed, and the next request opens another.+--+-- A server may close a connection it finds idle. When a request on a+-- connection already used gets no answer at all, it is sent again once on+-- a new connection, unless its body is a stream, which cannot be read+-- twice. A server that had acted on the request before losing the+-- connection then acts twice.+--+-- The host and the port of the request only serve its @Host@ header: the+-- server is that of the session. Requests go one at a time; a second+-- thread waits for the first.+withResponseIn :: Session -> Request -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a+withResponseIn session request use = do+  either throwIO pure (validateRequest request)+  -- The connection in hand, to close if the exchange fails.+  inHand <- newIORef Nothing+  mask $ \restore -> do+    current <- takeMVar session.live+    writeIORef inHand current+    (value, kept) <-+      restore (exchange inHand current) `onException` do+        readIORef inHand >>= mapM_ (quietly . (.shut))+        putMVar session.live Nothing+    putMVar session.live kept+    pure value+  where+    persistent = withHeaders (filter (\(name, _) -> BS8.map toLower name /= "connection") request.headers) request+    replayable = case request.body of+      BodyStream _ -> False+      _ -> True+    open inHand = do+      (transport, shut) <- session.opener+      received <- newIORef 0+      let limited = limitTransport session.limits.idleTimeout transport+          counted = S.mapM (\array -> array <$ modifyIORef' received (+ A.length array)) limited.receive+          connection = Live {transport = limited, shut, input = fromStream counted, received}+      connection <$ writeIORef inHand (Just connection)+    -- Send the request and read the head of the response.+    start connection = do+      fold (drainMapM connection.transport.send) (renderRequest persistent)+      readResponseReusable session.limits.maxHeadSize session.limits.maxBodySize request.method connection.input+    exchange inHand = \case+      Nothing -> open inHand >>= \connection -> start connection >>= complete inHand connection+      Just connection -> do+        before <- readIORef connection.received+        try (start connection) >>= \case+          Right started -> complete inHand connection started+          Left (problem :: SomeException) -> do+            after <- readIORef connection.received+            -- No answer at all on a connection already used: the server+            -- had closed it.+            if replayable && after == before && stale problem+              then do+                quietly connection.shut+                writeIORef inHand Nothing+                fresh <- open inHand+                start fresh >>= complete inHand fresh+              else throwIO problem+    stale problem = case (fromException problem, fromException problem) of+      (Just (_ :: IOException), _) -> True+      (_, Just (MalformedResponse _)) -> True+      _ -> False+    complete inHand connection (response, following) = do+      value <- use response+      following >>= \case+        Just rest -> pure (value, Just connection {input = rest})+        Nothing -> do+          writeIORef inHand Nothing+          quietly connection.shut+          pure (value, Nothing)++-- | Send a request in a session and read the whole response into memory.+-- See 'withResponseIn'.+fetchIn :: Session -> Request -> IO (Response (Array Word8))+fetchIn session request = withResponseIn session request collect++quietly :: IO () -> IO ()+quietly action = void (try @SomeException action)++collect :: Response (Stream IO (Array Word8)) -> IO (Response (Array Word8))+collect response = do+  bytes <- fold create (unfoldEach reader response.body)+  pure (bytes <$ response)++-- | Like 'connect', within a number of microseconds for the whole of it,+-- name resolution included. Throws 'ConnectTimedOut' beyond.+connectWithin :: Maybe Int -> String -> Int -> IO Socket+connectWithin limit host port = NT.connectWithin limit host port >>= maybe (throwIO ConnectTimedOut) pure
+ src/Streamly/External/Network/HTTP/URL.hs view
@@ -0,0 +1,169 @@+-- |+-- Module      : Streamly.External.Network.HTTP.URL+-- Description : The URLs of HTTP, read and resolved+-- License     : BSD-3-Clause+--+-- URLs with the schemes @http@ and @https@ (RFC 3986, RFC 9110 section+-- 4.2): reading one, writing it back, resolving the reference of a+-- redirect against it, and making a request for it.+--+-- A URL is taken as it is written: nothing is percent-encoded or decoded.+module Streamly.External.Network.HTTP.URL+  ( Url (..)+  , Scheme (..)+  , defaultPort+  , parseUrl+  , renderUrl+  , resolve+  , urlRequest++    -- * Parser+  , url+  ) where++import Control.Applicative ((<|>))+import Control.Monad (unless, void, when)+import Data.ByteString (ByteString, dropWhileEnd, intercalate, isPrefixOf,+                        singleton, split)+import Data.ByteString qualified as BS (any, break, concat, drop, elem, foldl',+                                        head, length, null, span, takeWhile,+                                        unpack)+import Data.ByteString.Char8 (pack)+import Data.ByteString.Char8 qualified as BS8 (unpack)+import Data.Char (toLower)+import Data.List qualified as L (foldl')+import Data.Word (Word8)+import FlatParse.Basic (Parser, Result (Err, Fail, OK), anyWord8, byteStringOf,+                        err, failed, runParser, skipMany, skipSome, takeRest,+                        word8)+import Streamly.External.Network.HTTP.Wire (Request (..), RequestBody (..))++-- | Whether the connection is in clear or over TLS.+data Scheme+  = Http+  | Https+  deriving stock (Eq, Ord, Show)++-- | The port of a scheme when the URL names none: 80 and 443.+defaultPort :: Scheme -> Int+defaultPort = \case+  Http -> 80+  Https -> 443++-- | A URL, without its fragment.+data Url = Url+  { scheme :: Scheme+  , host :: String+  -- ^ In lower case; an IPv6 address without its brackets.+  , port :: Int+  , target :: ByteString+  -- ^ The path and the query, @\/@ at least.+  }+  deriving stock (Eq, Show)++-- | Read a URL such as @https:\/\/example.org:8443\/a\/b?c=d#e@. The+-- fragment is dropped. A URL with a user name is refused, and so is one+-- that holds a space or a control character.+parseUrl :: ByteString -> Either String Url+parseUrl bytes = case runParser url bytes of+  OK found _ -> Right found+  Fail -> Left "not an http or https URL"+  Err problem -> Left ("not an http or https URL: " <> problem)++-- | The parser behind 'parseUrl'. It reads the input to its end.+url :: Parser String Url+url = do+  scheme <- (Https <$ keyword "https://") <|> (Http <$ keyword "http://")+  host <- bracketed <|> named+  port <- (word8 colon *> number) <|> pure (defaultPort scheme)+  path <- byteStringOf (skipMany (satisfyByte (\byte -> byte /= question && byte /= hash)))+  query <- byteStringOf (skipMany (satisfyByte (/= hash)))+  void takeRest+  when (BS.any (\byte -> byte <= 32 || byte == 127) (path <> query)) (err "a space or a control character")+  unless (BS.null path || BS.head path == slash) (err "something between the host and the path")+  pure Url {scheme, host, port, target = (if BS.null path then singleton slash else path) <> query}+  where+    keyword = mapM_ (\expected -> satisfyByte ((== expected) . lowerByte)) . BS.unpack+    -- An IPv6 address between brackets.+    bracketed = do+      word8 91+      address <- byteStringOf (skipSome (satisfyByte (\byte -> isHexDigit byte || byte == colon || byte == 46)))+      word8 93+      pure (map toLower (BS8.unpack address))+    named = map toLower . BS8.unpack <$> byteStringOf (skipSome (satisfyByte hostByte))+    -- Letters, digits and what else a name or an IPv4 address may hold.+    -- An at sign, which would end a user name, is not among them.+    hostByte byte = isAlphaNum byte || BS.elem byte "-._~%!$&'()*+,;="+    number = do+      digits <- byteStringOf (skipSome (satisfyByte isDigit))+      let value = BS.foldl' (\total byte -> total * 10 + fromIntegral (byte - 48)) 0 digits :: Int+      if BS.length digits > 5 || value < 1 || value > 65535 then failed else pure value+    satisfyByte accepted = anyWord8 >>= \byte -> if accepted byte then pure () else failed++-- | Write a URL, the port left out when it is the one of the scheme.+renderUrl :: Url -> ByteString+renderUrl found =+  BS.concat+    [ case found.scheme of Http -> "http://"; Https -> "https://"+    , if ':' `elem` found.host then "[" <> pack found.host <> "]" else pack found.host+    , if found.port == defaultPort found.scheme then "" else ":" <> pack (show found.port)+    , found.target+    ]++-- | Resolve a reference, such as the @Location@ of a redirect, against the+-- URL it was found at: a whole URL, @\/\/host\/path@, @\/path@, @?query@+-- or a path relative to the one of the URL.+resolve :: Url -> ByteString -> Either String Url+resolve base reference+  | BS.null trimmed = Right base+  | "//" `isPrefixOf` trimmed = parseUrl (schemeName <> ":" <> trimmed)+  | "/" `isPrefixOf` trimmed = at (removeDots path <> query)+  | "?" `isPrefixOf` trimmed = at (basePath <> trimmed)+  | hasScheme = parseUrl trimmed+  | otherwise = at (removeDots (directory <> path) <> query)+  where+    -- The reference, without its fragment.+    trimmed = BS.takeWhile (/= hash) reference+    (path, query) = BS.break (== question) trimmed+    basePath = BS.takeWhile (/= question) base.target+    directory = dropWhileEnd (/= slash) basePath+    schemeName = case base.scheme of Http -> "http"; Https -> "https"+    hasScheme =+      let (name, rest) = BS.span (\byte -> isAlphaNum byte || BS.elem byte "+-.") trimmed+       in not (BS.null name) && ":" `isPrefixOf` rest+    at target+      | BS.any (\byte -> byte <= 32 || byte == 127) target = Left "a space or a control character in a reference"+      | otherwise = Right (Url base.scheme base.host base.port target)++-- | Remove the @.@ and @..@ segments of an absolute path (RFC 3986,+-- section 5.2.4).+removeDots :: ByteString -> ByteString+removeDots path = "/" <> intercalate "/" (reverse kept) <> (if trailing then "/" else "")+  where+    segments = split slash (BS.drop 1 path)+    trailing = case reverse segments of+      final : _ -> final `elem` ["", ".", ".."] && path /= "/"+      [] -> False+    kept = L.foldl' step [] segments+    step done segment+      | segment == "." || segment == "" = done+      | segment == ".." = drop 1 done+      | otherwise = segment : done++-- | A @GET@ request for a URL, without headers.+urlRequest :: Url -> Request+urlRequest found = Request {method = "GET", host = found.host, port = found.port, target = found.target, headers = [], body = NoBody}++isDigit, isHexDigit, isAlphaNum :: Word8 -> Bool+isDigit byte = byte >= 48 && byte <= 57+isHexDigit byte = isDigit byte || (lowerByte byte >= 97 && lowerByte byte <= 102)+isAlphaNum byte = isDigit byte || (lowerByte byte >= 97 && lowerByte byte <= 122)++lowerByte :: Word8 -> Word8+lowerByte byte = if byte >= 65 && byte <= 90 then byte + 32 else byte++colon, slash, question, hash :: Word8+colon = 58+slash = 47+question = 63+hash = 35
+ src/Streamly/External/Network/HTTP/Wire.hs view
@@ -0,0 +1,542 @@+-- |+-- Module      : Streamly.External.Network.HTTP.Wire+-- Description : HTTP/1.1 messages as streams of byte arrays+-- License     : BSD-3-Clause+--+-- The HTTP/1.1 message format (RFC 9112), independent of any transport: a+-- request becomes a stream of byte arrays, and a response is read from one.+-- "Streamly.External.Network.HTTP" runs these over a TCP connection; use+-- this module directly to run them over another transport.+module Streamly.External.Network.HTTP.Wire+  ( -- * Requests+    Request (..)+  , RequestBody (..)+  , Header+  , withHeaders+  , withBody+  , validateRequest+  , renderRequest++    -- * Responses+  , Response (..)+  , header+  , readResponse+  , readResponseWithin+  , readResponseReusable+  , readResponseHead+  , readResponseHeadWithin++    -- * Requests, as a server reads them+  , RequestHead (..)+  , requestMethod+  , requestTarget+  , requestHeader+  , readRequestHeadWithin++    -- * Errors+  , HttpError (..)++    -- * Parsers+  , responseHead+  , requestHead+  , chunkSizeLine+  ) where++import Control.Applicative ((<|>))+import Control.Exception (Exception, throwIO, try)+import Control.Monad (unless, void, when)+import Data.ByteString (ByteString, dropWhileEnd, isPrefixOf, split)+import Data.ByteString qualified as BS (all, concat, dropWhile, elem, foldl',+                                        length, map, null)+import Data.ByteString.Char8 (pack, readInt, strip)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Maybe (fromMaybe)+import Data.Word (Word8)+import FlatParse.Basic (Parser, anyWord8, byteString, byteStringOf, cut, err,+                        failed, fails, isolate, lookahead, many, skipMany,+                        skipSome, takeRest, withByteString, word8)+import Numeric (showHex)+import Streamly.Data.Array (Array, createOf)+import Streamly.Data.Array qualified as A (length, read)+import Streamly.Data.Stream (Stream, append, concatEffect, fold, fromList,+                             fromPure, nil, unfoldrM)+import Streamly.Data.Stream qualified as S (concatMap, cons, drop, filter, mapM,+                                            take)+import Streamly.Data.StreamK (StreamK, toStream, uncons)+import Streamly.Data.StreamK qualified as K (cons)+import Streamly.External.ByteString (toArray)+import Streamly.External.FlatParse (ParseError (Mismatch, ParserError, TooLong),+                                    parseBreak)++-- | A header name and its value.+type Header = (ByteString, ByteString)++-- | A request to one server.+--+-- 'renderRequest' adds @Host@ (unless given here) and the header that+-- delimits the body; @Content-Length@ and @Transfer-Encoding@ given here+-- are dropped.+data Request = Request+  { method :: ByteString+  -- ^ For example @GET@.+  , host :: String+  -- ^ A host name or an address, without brackets around an IPv6 address.+  , port :: Int+  , target :: ByteString+  -- ^ The path and the query, already percent-encoded: @\/a\/b?c=d@.+  , headers :: [Header]+  , body :: RequestBody+  }++-- | The body of a request.+data RequestBody+  = NoBody+  | -- | Sent with a @Content-Length@.+    BodyBytes ByteString+  | -- | Sent with the chunked transfer coding, one chunk per array.+    BodyStream (Stream IO (Array Word8))++-- | The request with these headers instead of its own.+withHeaders :: [Header] -> Request -> Request+withHeaders headers (Request method host port target _ body) = Request {method, host, port, target, headers, body}++-- | The request with this body instead of its own.+withBody :: RequestBody -> Request -> Request+withBody body (Request method host port target headers _) = Request {method, host, port, target, headers, body}++-- | A response. 'readResponse' gives the names of the headers in lower+-- case, in the order received.+data Response body = Response+  { status :: Int+  , reason :: ByteString+  , headers :: [Header]+  , body :: body+  }+  deriving stock (Eq, Show, Functor)++-- | The first header of that name, whatever the case of the name.+header :: ByteString -> Response body -> Maybe ByteString+header name response = lookup (lowerAscii name) response.headers++-- | What can go wrong with a message. Failures of the connection itself+-- stay the 'IOError's of the transport.+data HttpError+  = -- | The request cannot be written safely: what is wrong with it.+    InvalidRequest String+  | -- | The response head or a chunk size could not be parsed: the reason+    -- given by the parser.+    MalformedResponse String+  | -- | A @Content-Length@ that is not a number.+    InvalidContentLength ByteString+  | -- | A @Transfer-Encoding@ other than @chunked@.+    UnsupportedTransferEncoding ByteString+  | -- | The input ended inside the body: the number of bytes still expected+    -- (of the current chunk, for a chunked body).+    TruncatedBody Int+  | -- | The head of a request could not be parsed, on the side of a+    -- server: the reason given by the parser.+    MalformedRequest String+  | -- | The head of the response, or of the request on the side of a+    -- server, is longer than allowed: the limit, in bytes.+    HeadTooLarge Int+  | -- | The body of the response is longer than allowed: the limit, in+    -- bytes.+    BodyTooLarge Int+  | -- | The connection could not be opened within the time allowed.+    ConnectTimedOut+  | -- | The server went silent for longer than allowed, before or inside+    -- its response, or stopped reading the request.+    ResponseTimedOut+  deriving stock (Eq, Show)++instance Exception HttpError++-- | Check that a request can be written: a method, a target starting with+-- a slash, a port, and no control character or space that would let a+-- field run into the next one.+validateRequest :: Request -> Either HttpError ()+validateRequest request = do+  check (not (BS.null request.method) && BS.all isTokenByte request.method) "the method is not a token"+  check ("/" `isPrefixOf` request.target || request.target == "*") "the target does not start with a slash"+  check (BS.all (\byte -> byte > space && byte /= 127) request.target) "the target holds a space or a control character"+  check (not (null request.host) && all hostChar request.host) "the host is empty or holds a space or a control character"+  check (request.port > 0 && request.port < 65536) "the port is out of range"+  mapM_ checkHeader request.headers+  where+    check ok problem = unless ok (Left (InvalidRequest problem))+    hostChar char = char > ' ' && char < '\DEL' && char `notElem` ("/[]" :: String)+    checkHeader (name, value) = do+      check (not (BS.null name) && BS.all isTokenByte name) ("the header name " <> show name <> " is not a token")+      check (BS.all (\byte -> byte >= space && byte /= 127 || byte == tab) value) ("the value of the header " <> show name <> " holds a control character")++-- | The bytes of a request: the head in one array, then the body.+-- The request is not checked: see 'validateRequest'.+renderRequest :: Request -> Stream IO (Array Word8)+renderRequest request = case request.body of+  NoBody -> fromPure (headWith [])+  BodyBytes bytes ->+    fromList+      (headWith [("Content-Length", pack (show (BS.length bytes)))] : [toArray bytes | not (BS.null bytes)])+  BodyStream chunks ->+    S.cons (headWith [("Transfer-Encoding", "chunked")]) $+      S.concatMap chunk (S.filter ((> 0) . A.length) chunks)+        `append` fromPure (toArray "0\r\n\r\n")+  where+    headWith framing =+      toArray . BS.concat $+        [request.method, " ", request.target, " HTTP/1.1\r\n"]+          <> concatMap written (hostHeader <> kept <> framing)+          <> ["\r\n"]+    written (name, value) = [name, ": ", value, "\r\n"]+    kept = filter (\(name, _) -> lowerAscii name `notElem` owned) request.headers+    owned = ["content-length", "transfer-encoding"]+    hostHeader+      | any (\(name, _) -> lowerAscii name == "host") request.headers = []+      | otherwise = [("Host", authority)]+    authority =+      (if ':' `elem` request.host then "[" <> pack request.host <> "]" else pack request.host)+        <> (if request.port == 80 then "" else ":" <> pack (show request.port))+    chunk array =+      fromList+        [ toArray (pack (showHex (A.length array) "\r\n"))+        , array+        , toArray "\r\n"+        ]++-- | Read a response from the bytes received, given the method of the+-- request (a response to @HEAD@ has no body).+--+-- Interim responses (status 1xx, except 101) are skipped. The body is read+-- from the input as the stream is consumed, so the stream must be consumed+-- while the input is still open, and only once. It ends where the response+-- says it ends; what follows in the input is not read. The trailer fields+-- of a chunked body are not read either.+--+-- Throws 'HttpError': here for the head, from the stream for the body.+readResponse :: ByteString -> StreamK IO (Array Word8) -> IO (Response (Stream IO (Array Word8)))+readResponse = readResponseWithin Nothing Nothing++-- | Like 'readResponse', with the largest head and the largest body+-- accepted, in bytes; 'Nothing' accepts any. The head counts the interim+-- responses skipped; the body is counted as received, after the chunked+-- coding is undone.+--+-- Throws 'HeadTooLarge' here. 'BodyTooLarge' is thrown here when the+-- response announces too long a body, and from the stream otherwise.+readResponseWithin :: Maybe Int -> Maybe Int -> ByteString -> StreamK IO (Array Word8) -> IO (Response (Stream IO (Array Word8)))+readResponseWithin maxHead maxBody method input = do+  ((_, found), rest) <- versionedHeadWithin maxHead input+  framing <- either throwIO pure (bodyFraming method found)+  case (framing, maxBody) of+    (Fixed announced, Just limit) | announced > limit -> throwIO (BodyTooLarge limit)+    _ -> pure ()+  pure (maybe id limitBody maxBody (bodyStream Nothing framing rest) <$ found)++-- | Like 'readResponseWithin', for a connection that may carry another+-- exchange afterwards. The action given with the response tells, once the+-- body has been consumed, whether the connection can go on, and gives the+-- input that follows the response if it can. It cannot when the body was+-- not read to its end, when only the end of the connection ends the body,+-- when the server speaks HTTP\/1.0 without asking to keep the connection,+-- or when it says @Connection: close@.+--+-- Unlike 'readResponseWithin', this reads the trailer fields of a chunked+-- body, to find where the next response starts.+readResponseReusable+  :: Maybe Int+  -> Maybe Int+  -> ByteString+  -> StreamK IO (Array Word8)+  -> IO (Response (Stream IO (Array Word8)), IO (Maybe (StreamK IO (Array Word8))))+readResponseReusable maxHead maxBody method input = do+  ((minor, found), rest) <- versionedHeadWithin maxHead input+  framing <- either throwIO pure (bodyFraming method found)+  case (framing, maxBody) of+    (Fixed announced, Just limit) | announced > limit -> throwIO (BodyTooLarge limit)+    _ -> pure ()+  after <- newIORef Nothing+  let wishes = maybe [] (map (lowerAscii . strip) . split 44) (header "connection" found)+      persistent = "close" `notElem` wishes && (minor >= 1 || "keep-alive" `elem` wishes)+      following = if persistent then readIORef after else pure Nothing+  pure (maybe id limitBody maxBody (bodyStream (Just after) framing rest) <$ found, following)++-- | Read the head of a response, and give what follows it in the input:+-- the body, or after a status 101 the bytes of the protocol switched to.+-- Interim responses (status 1xx, except 101) are skipped.+--+-- Throws 'MalformedResponse'.+readResponseHead :: StreamK IO (Array Word8) -> IO (Response (), StreamK IO (Array Word8))+readResponseHead = readResponseHeadWithin Nothing++-- | Like 'readResponseHead', with the largest head accepted, in bytes,+-- interim responses included; 'Nothing' accepts any. Throws 'HeadTooLarge'+-- beyond.+readResponseHeadWithin :: Maybe Int -> StreamK IO (Array Word8) -> IO (Response (), StreamK IO (Array Word8))+readResponseHeadWithin limit input = do+  ((_, found), rest) <- versionedHeadWithin limit input+  pure (found, rest)++-- | The head of a request, as a server receives it: the method, the+-- target, and the headers with their names in lower case. (Without field+-- names, which would make updates of a t'Request' ambiguous.)+data RequestHead = RequestHead ByteString ByteString [Header]+  deriving stock (Eq, Show)++-- | The method of a request received, such as @GET@.+requestMethod :: RequestHead -> ByteString+requestMethod (RequestHead method _ _) = method++-- | The target of a request received: its path and its query.+requestTarget :: RequestHead -> ByteString+requestTarget (RequestHead _ target _) = target++-- | The first header of that name in the head of a request, whatever the+-- case of the name.+requestHeader :: ByteString -> RequestHead -> Maybe ByteString+requestHeader name (RequestHead _ _ headers) = lookup (lowerAscii name) headers++-- | Read the head of a request, with the largest head accepted, in bytes+-- ('Nothing' accepts any), and give what follows it in the input: the+-- body, or after an upgrade the bytes of the protocol switched to.+--+-- Throws 'MalformedRequest', and 'HeadTooLarge' beyond the limit.+readRequestHeadWithin :: Maybe Int -> StreamK IO (Array Word8) -> IO (RequestHead, StreamK IO (Array Word8))+readRequestHeadWithin limit = parsed MalformedRequest (HeadTooLarge allowed) allowed requestHead+  where+    allowed = fromMaybe maxBound limit++-- | The head of a response with the minor version of its protocol: 0 for+-- HTTP\/1.0, 1 for HTTP\/1.1. Interim responses are skipped; the bytes+-- allowed are for all the heads read.+versionedHeadWithin :: Maybe Int -> StreamK IO (Array Word8) -> IO ((Int, Response ()), StreamK IO (Array Word8))+versionedHeadWithin limit = go allowed+  where+    allowed = fromMaybe maxBound limit+    go budget input = do+      ((size, versioned@(_, found)), rest) <- parsed MalformedResponse (HeadTooLarge allowed) budget (sized versionedHead) input+      if found.status >= 100 && found.status < 200 && found.status /= 101+        then go (budget - size) rest+        else pure (versioned, rest)+    sized parser = withByteString parser (\found bytes -> pure (BS.length bytes, found))++-- | Run a parser on the start of the input, which it may read no further+-- than a number of bytes, and give what follows. Throws the error made of+-- the reason when the input does not parse, and the other error when it+-- would need more bytes than allowed.+parsed :: (String -> HttpError) -> HttpError -> Int -> Parser String a -> StreamK IO (Array Word8) -> IO (a, StreamK IO (Array Word8))+parsed malformed tooLong limit parser input =+  parseBreak limit parser input >>= \case+    (Right found, rest) -> pure (found, rest)+    (Left Mismatch, _) -> throwIO (malformed "the input ended too early")+    (Left (ParserError problem), _) -> throwIO (malformed problem)+    (Left (TooLong _), _) -> throwIO tooLong++-- | Stop a body that grows beyond a number of bytes.+limitBody :: Int -> Stream IO (Array Word8) -> Stream IO (Array Word8)+limitBody limit body = concatEffect $ do+  total <- newIORef 0+  pure $+    S.mapM+      ( \array -> do+          size <- (+ A.length array) <$> readIORef total+          when (size > limit) (throwIO (BodyTooLarge limit))+          array <$ writeIORef total size+      )+      body++-- | How the end of a body is found (RFC 9112, section 6.3).+data Framing+  = Empty+  | Fixed Int+  | Chunked+  | UntilClose++bodyFraming :: ByteString -> Response () -> Either HttpError Framing+bodyFraming method response+  | method == "HEAD" || response.status < 200 || response.status == 204 || response.status == 304 = Right Empty+  | Just coding <- header "transfer-encoding" response =+      if lowerAscii (strip coding) == "chunked"+        then Right Chunked+        else Left (UnsupportedTransferEncoding coding)+  | Just raw <- header "content-length" response =+      case readInt raw of+        Just (n, "") | BS.all isDigit raw -> Right (Fixed n)+        _ -> Left (InvalidContentLength raw)+  | otherwise = Right UntilClose++data BodyState+  = -- | Before the size line of a chunk.+    AtChunkSize (StreamK IO (Array Word8))+  | -- | Inside the data: the bytes still expected, the input, and whether+    -- this is a chunk (then a line end and another chunk follow).+    InData Int (StreamK IO (Array Word8)) Bool++-- | The body, read from the input as the stream is consumed. With a+-- place to leave it, the input that follows the body is left there once+-- the body has been read to its end, when the body says where it ends.+bodyStream :: Maybe (IORef (Maybe (StreamK IO (Array Word8)))) -> Framing -> StreamK IO (Array Word8) -> Stream IO (Array Word8)+bodyStream after framing input = case framing of+  Empty -> concatEffect (nil <$ leave input)+  UntilClose -> toStream input+  Fixed n -> unfoldrM step (InData n input False)+  Chunked -> unfoldrM step (AtChunkSize input)+  where+    leave rest = mapM_ (\place -> writeIORef place (Just rest)) after+    -- The lines between the chunks are short.+    short = parsed MalformedResponse (MalformedResponse "a line between chunks that is too long") 4096+    step (AtChunkSize from) = do+      (size, rest) <- short chunkSizeLine from+      if size /= 0+        then step (InData size rest True)+        else do+          -- The trailer fields are only read to find what follows them;+          -- a trailer that cannot be read ends the use of the connection,+          -- not the body.+          case after of+            Nothing -> pure ()+            Just _ -> do+              trailer <- try (parsed MalformedResponse (MalformedResponse "a trailer that is too long") 65536 (skipMany headerLine *> lineEnd) rest)+              either (\(_ :: HttpError) -> pure ()) (leave . snd) trailer+          pure Nothing+    step (InData 0 from chunked)+      | chunked = do+          ((), rest) <- short chunkEnd from+          step (AtChunkSize rest)+      | otherwise = Nothing <$ leave from+    step (InData remaining from chunked) = do+      next <- uncons from+      case next of+        Nothing -> throwIO (TruncatedBody remaining)+        Just (array, rest)+          | size == 0 -> step (InData remaining rest chunked)+          | size <= remaining -> pure (Just (array, InData (remaining - size) rest chunked))+          | otherwise -> do+              front <- fold (createOf remaining) (S.take remaining (A.read array))+              back <- fold (createOf (size - remaining)) (S.drop remaining (A.read array))+              pure (Just (front, InData 0 (K.cons back rest) chunked))+          where+            size = A.length array++-- | The status line, the header lines and the empty line that ends them.+-- The names of the headers are given in lower case, the values without the+-- spaces around them. Lines end with a line feed, after an optional+-- carriage return. Header lines folded over several lines are refused.+--+-- Like the other parsers here, it fails while a line is not all there, so+-- that it can be run with @parseBreak@ of @streamly-flatparse@ as the+-- bytes come, and it stops on an error as soon as a whole line is wrong.+responseHead :: Parser String (Response ())+responseHead = snd <$> versionedHead++-- | 'responseHead', with the minor version of the protocol of the server.+versionedHead :: Parser String (Int, Response ())+versionedHead = do+  (minor, status, reason) <- line "the first line is not the status line of HTTP/1" $ do+    byteString "HTTP/1."+    minor <- digit+    word8 space+    digits <- byteStringOf (skipSome (satisfyByte isDigit))+    when (BS.length digits /= 3) failed+    reason <- trimmed <$> takeRest+    pure (minor, BS.foldl' (\total byte -> total * 10 + fromIntegral (byte - 48)) 0 digits, reason)+  found <- many headerLine+  lineEnd+  pure (minor, Response {status, reason, headers = found, body = ()})++-- | The request line, the header lines and the empty line that ends them,+-- read as 'responseHead' reads those of a response.+requestHead :: Parser String RequestHead+requestHead = do+  (method, target) <- line "the first line is not the request line of HTTP/1" $ do+    method <- byteStringOf (skipSome (satisfyByte isTokenByte))+    word8 space+    target <- byteStringOf (skipSome (satisfyByte (\byte -> byte > space && byte /= 127)))+    word8 space+    byteString "HTTP/1."+    void digit+    skipMany (word8 carriageReturn)+    pure (method, target)+  found <- many headerLine+  lineEnd+  pure (RequestHead method target found)++-- | A header line: its name in lower case, and its value without the+-- spaces around it. Fails, without an error, on the empty line that ends+-- the headers.+headerLine :: Parser String Header+headerLine = do+  fails lineEnd+  line "a header line is not a name, a colon and a value" $ do+    name <- byteStringOf (skipSome (satisfyByte isTokenByte))+    word8 colon+    value <- trimmed <$> takeRest+    pure (lowerAscii name, value)++-- | The line that starts a chunk: its size in hexadecimal, then extensions+-- that are ignored.+chunkSizeLine :: Parser String Int+chunkSizeLine = line "a chunk does not start with its size in hexadecimal" $ do+  digits <- byteStringOf (skipSome (satisfyByte isHexDigit))+  -- Fifteen digits always fit in an Int.+  when (BS.length digits > 15) failed+  void takeRest+  pure (BS.foldl' (\total byte -> total * 16 + hexValue byte) 0 digits)+  where+    isHexDigit byte = isDigit byte || (byte >= 65 && byte <= 70) || (byte >= 97 && byte <= 102)+    hexValue byte+      | isDigit byte = fromIntegral (byte - 48)+      | byte >= 97 = fromIntegral (byte - 87)+      | otherwise = fromIntegral (byte - 55)++-- | A whole line, read by a parser that must read all of it, the line+-- feed left out. It fails while the line feed has not come, and stops on+-- an error, with a reason, when the line is there and is not what the+-- parser reads.+line :: String -> Parser String a -> Parser String a+line problem content = do+  size <- lookahead (BS.length <$> byteStringOf (skipMany (satisfyByte (/= lineFeed))) <* word8 lineFeed)+  found <- isolate size content `cut` problem+  word8 lineFeed+  pure found++-- | The end of a line: a line feed, after carriage returns if any.+lineEnd :: Parser String ()+lineEnd = skipMany (word8 carriageReturn) *> word8 lineFeed++-- | The end of the line that follows the data of a chunk: an error if+-- something else is there.+chunkEnd :: Parser String ()+chunkEnd = skipMany (word8 carriageReturn) *> (word8 lineFeed <|> (lookahead anyWord8 *> err "the data of a chunk is not followed by a line end"))++satisfyByte :: (Word8 -> Bool) -> Parser String ()+satisfyByte accepted = anyWord8 >>= \byte -> if accepted byte then pure () else failed++digit :: Parser String Int+digit = anyWord8 >>= \byte -> if isDigit byte then pure (fromIntegral (byte - 48)) else failed++-- | Without the spaces, the tabs and the carriage returns around.+trimmed :: ByteString -> ByteString+trimmed = BS.dropWhile blank . dropWhileEnd blank+  where+    blank byte = byte == space || byte == tab || byte == carriageReturn++-- | The bytes allowed in a method or a header name (RFC 9110, tchar).+isTokenByte :: Word8 -> Bool+isTokenByte byte =+  isDigit byte+    || (byte >= 65 && byte <= 90)+    || (byte >= 97 && byte <= 122)+    || BS.elem byte "!#$%&'*+-.^_`|~"++isDigit :: Word8 -> Bool+isDigit byte = byte >= 48 && byte <= 57++lowerAscii :: ByteString -> ByteString+lowerAscii = BS.map (\byte -> if byte >= 65 && byte <= 90 then byte + 32 else byte)++space, tab, colon, lineFeed, carriageReturn :: Word8+space = 32+tab = 9+colon = 58+lineFeed = 10+carriageReturn = 13
+ streamly-http.cabal view
@@ -0,0 +1,85 @@+cabal-version:   3.12+name:            streamly-http+version:         0.1.0.0+synopsis:        A small HTTP/1.1 client written with Streamly+description:+  An HTTP/1.1 client over plain TCP. The response head is read with+  flatparse parsers and the body is a stream of byte arrays, whether it is+  delimited by @Content-Length@, by the chunked transfer coding or by the+  end of the connection. Waits and sizes are limited; sessions and clients+  keep connections from one request to the next. No TLS and no redirects+  here: requests also go over a transport of the caller, which is how+  streamly-http-tls adds both.++homepage:        https://github.com/GuillaumedeVolpiano/streamly-http+license:         BSD-3-Clause+license-file:    LICENSE+author:          Xavier Dectot+maintainer:      Xavier Dectot <xavier@wheredoibegin.fr>+category:        Network, Web, Streamly+build-type:      Simple+tested-with:     GHC ==9.8.4 || ==9.10.3 || ==9.12.4+extra-doc-files:+  CHANGELOG.md+  README.md++source-repository head+  type:     git+  location: https://github.com/GuillaumedeVolpiano/streamly-http.git++common shared+  default-language:   GHC2021+  default-extensions:+    DataKinds+    DerivingStrategies+    DisambiguateRecordFields+    DuplicateRecordFields+    ExplicitNamespaces+    GADTs+    LambdaCase+    MonoLocalBinds+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    RoleAnnotations++  ghc-options:+    -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+    -Wunused-packages++library+  import:          shared+  hs-source-dirs:  src+  exposed-modules:+    Streamly.External.Network.HTTP+    Streamly.External.Network.HTTP.URL+    Streamly.External.Network.HTTP.Wire++  build-depends:+    , base                 >=4.19 && <4.22+    , bytestring           ^>=0.12+    , containers           >=0.6.7 && <0.8+    , flatparse            ^>=0.5+    , network              ^>=3.2+    , streamly-bytestring  ^>=0.2.3+    , streamly-core        ^>=0.3.3+    , streamly-flatparse   ^>=0.1+    , streamly-network-tcp ^>=0.1++test-suite streamly-http-test+  import:         shared+  type:           exitcode-stdio-1.0+  hs-source-dirs: test+  main-is:        Main.hs+  ghc-options:    -threaded+  build-depends:+    , async                ^>=2.2+    , base+    , bytestring+    , network+    , streamly-bytestring+    , streamly-core+    , streamly-http+    , tasty                ^>=1.5+    , tasty-hunit          ^>=0.10+    , tasty-quickcheck     ^>=0.11
+ test/Main.hs view
@@ -0,0 +1,650 @@+-- | The message format on byte arrays cut anywhere, then the client against+-- a server on the loopback interface.+module Main (main) where++import Control.Concurrent (forkIOWithUnmask, threadDelay)+import Control.Concurrent.Async (wait, withAsync)+import Control.Exception (SomeException, bracket, finally, mask_, try)+import Control.Monad (void)+import Data.ByteString (ByteString, breakSubstring, isInfixOf, singleton,+                        unpack)+import Data.ByteString qualified as BS (concat, drop, length, null, pack,+                                        splitAt)+import Data.ByteString.Char8 qualified as BS8 (dropWhile, pack, takeWhile)+import Data.IORef (modifyIORef, newIORef, readIORef)+import Data.List (sort)+import Data.Word (Word8)+import GHC.Clock (getMonotonicTime)+import Network.Socket (Family (AF_INET), SockAddr (SockAddrInet),+                       SocketOption (ReuseAddr), SocketType (Stream), accept,+                       bind, close, defaultProtocol, listen, setSocketOption,+                       socketPort, tupleToHostAddress)+import Network.Socket qualified as N (socket)+import Network.Socket.ByteString (recv, sendAll)+import Streamly.Data.Array (Array)+import Streamly.Data.Stream (Stream, fromList, nil, repeatM, toList)+import Streamly.Data.Stream qualified as S (take)+import Streamly.Data.StreamK (fromStream, toStream)+import Streamly.External.ByteString (fromArray, toArray)+import Streamly.External.Network.HTTP (HttpError (..),+                                       Limits (connectTimeout, idleTimeout, maxBodySize, maxHeadSize),+                                       Request (method),+                                       RequestBody (BodyBytes, BodyStream),+                                       Response (..),+                                       Transport (Transport, receive, send),+                                       connectWithin, defaultLimits, fetch,+                                       fetchFrom, fetchIn, fetchOver,+                                       fetchWithin, get, header, limitTransport,+                                       noLimits, withBody, withClient,+                                       withHeaders, withResponse,+                                       withResponseFrom, withResponseIn,+                                       withSession, withSessionOver)+import Streamly.External.Network.HTTP.URL (Scheme (Http, Https), Url (Url),+                                           parseUrl, renderUrl, resolve,+                                           urlRequest)+import Streamly.External.Network.HTTP.Wire (RequestHead (..),+                                            readRequestHeadWithin,+                                            readResponseHead,+                                            readResponseWithin, renderRequest,+                                            requestHeader, validateRequest)+import System.Timeout (timeout)+import Test.Tasty (TestTree, defaultMain, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.QuickCheck (Positive (..), ioProperty, testProperty, (===))++main :: IO ()+main = defaultMain tests++tests :: TestTree+tests =+  localOption (mkTimeout 20_000_000) $+    testGroup+      "streamly-http"+      [ testGroup "reading a response" reading+      , testGroup "writing a request" writing+      , testGroup "URLs" urls+      , testGroup "over TCP" overTcp+      , testGroup "sessions" sessions+      ]++-- | Read a response to a GET from the bytes, cut into pieces of a size.+readWhole :: Int -> ByteString -> IO (Response ByteString)+readWhole = readWholeFor "GET"++readWholeFor :: ByteString -> Int -> ByteString -> IO (Response ByteString)+readWholeFor = readWholeLimited Nothing Nothing++-- | Like 'readWhole', with the largest head and the largest body accepted.+readWholeWithin :: Maybe Int -> Maybe Int -> Int -> ByteString -> IO (Response ByteString)+readWholeWithin maxHead maxBody = readWholeLimited maxHead maxBody "GET"++readWholeLimited :: Maybe Int -> Maybe Int -> ByteString -> Int -> ByteString -> IO (Response ByteString)+readWholeLimited maxHead maxBody method size bytes = do+  response <- readResponseWithin maxHead maxBody method (fromStream (fromList (map toArray (pieces size bytes))))+  content <- collect response.body+  pure (content <$ response)++collect :: Stream IO (Array Word8) -> IO ByteString+collect = fmap (BS.concat . map fromArray) . toList++pieces :: Int -> ByteString -> [ByteString]+pieces size bytes+  | BS.null bytes = []+  | otherwise = let (front, back) = BS.splitAt size bytes in front : pieces size back++failsWith :: HttpError -> IO a -> IO ()+failsWith expected action = do+  outcome <- try action+  case outcome of+    Left problem -> problem @?= expected+    Right _ -> assertFailure ("no error, expected " <> show expected)++isMalformed :: IO a -> IO ()+isMalformed action = do+  outcome <- try action+  case outcome of+    Left (MalformedResponse _) -> pure ()+    Left other -> assertFailure ("expected MalformedResponse, got " <> show other)+    Right _ -> assertFailure "no error, expected MalformedResponse"++fixed :: ByteString+fixed = fixedHead <> "hello world"++fixedHead :: ByteString+fixedHead = "HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\nContent-Length: 11\r\n\r\n"++chunked :: ByteString+chunked =+  "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"+    <> "5\r\nhello\r\n1;name=value\r\n \r\nA\r\nworld12345\r\n0\r\nTrailer: ignored\r\n\r\n"++reading :: [TestTree]+reading =+  [ testCase "a body delimited by Content-Length" $ do+      response <- readWhole 4096 fixed+      response @?= Response {status = 200, reason = "OK", headers = [("content-type", "image/jpeg"), ("content-length", "11")], body = "hello world"}+  , testCase "a header is found whatever its case" $ do+      response <- readWhole 4096 fixed+      header "Content-TYPE" response @?= Just "image/jpeg"+      header "etag" response @?= Nothing+  , testProperty "a Content-Length body does not depend on how the bytes are cut" $ \(Positive size) ->+      ioProperty $ do+        response <- readWhole size fixed+        pure (response.body === "hello world")+  , testCase "a chunked body, with a chunk extension and a trailer" $ do+      response <- readWhole 4096 chunked+      response.body @?= "hello world12345"+  , testProperty "a chunked body does not depend on how the bytes are cut" $ \(Positive size) ->+      ioProperty $ do+        response <- readWhole size chunked+        pure (response.body === "hello world12345")+  , testCase "a body that runs until the connection closes" $ do+      response <- readWhole 7 "HTTP/1.0 200 OK\r\nServer: old\r\n\r\nuntil the end"+      response.body @?= "until the end"+  , testCase "bytes beyond Content-Length are not part of the body" $ do+      response <- readWhole 5 (fixed <> "HTTP/1.1 500 Next\r\n\r\n")+      response.body @?= "hello world"+  , testCase "line feeds alone end the lines, and the reason may be missing" $ do+      response <- readWhole 3 "HTTP/1.1 404\nContent-Length:2\n\nno"+      (response.status, response.reason, response.body) @?= (404, "", "no")+  , testCase "no body after HEAD, 204 and 304, whatever the headers say" $ do+      afterHead <- readWholeFor "HEAD" 4096 fixed+      afterHead.body @?= ""+      noContent <- readWhole 4096 "HTTP/1.1 204 No Content\r\nContent-Length: 5\r\n\r\nhello"+      noContent.body @?= ""+      notModified <- readWhole 4096 "HTTP/1.1 304 Not Modified\r\nTransfer-Encoding: chunked\r\n\r\n"+      notModified.body @?= ""+  , testCase "interim responses are skipped" $ do+      response <- readWhole 6 ("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 103 Early Hints\r\nLink: </a>\r\n\r\n" <> fixed)+      (response.status, response.body) @?= (200, "hello world")+  , testCase "the head alone, with what follows a switch of protocols" $ do+      let input = fromStream (fromList (map toArray (pieces 9 "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n\r\n\129\5hello")))+      (found, rest) <- readResponseHead input+      (found.status, header "upgrade" found) @?= (101, Just "websocket")+      following <- collect (toStream rest)+      following @?= "\129\5hello"+  , testProperty "a head of exactly the size allowed is read, with its body, however the bytes are cut" $ \(Positive size) ->+      ioProperty $ do+        response <- readWholeWithin (Just (BS.length fixedHead)) Nothing size fixed+        pure (response.body === "hello world")+  , testProperty "a head one byte longer than allowed is refused, however the bytes are cut" $ \(Positive size) ->+      ioProperty $ do+        outcome <- try (readWholeWithin (Just (BS.length fixedHead - 1)) Nothing size fixed)+        pure (fmap (.status) outcome === Left (HeadTooLarge (BS.length fixedHead - 1)))+  , testCase "headers without end are refused" $ do+      let endless = "HTTP/1.1 200 OK\r\n" <> BS.concat (replicate 10_000 "X-Padding: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n")+      failsWith (HeadTooLarge 65536) (readWholeWithin (Just 65536) Nothing 4096 endless)+  , testCase "the size allowed to the head counts the interim responses" $ do+      let interim = "HTTP/1.1 100 Continue\r\n\r\n"+      response <- readWholeWithin (Just (BS.length interim + BS.length fixedHead)) Nothing 5 (interim <> fixed)+      response.body @?= "hello world"+      failsWith (HeadTooLarge (BS.length fixedHead)) (readWholeWithin (Just (BS.length fixedHead)) Nothing 5 (interim <> fixed))+  , testCase "a body of the size allowed is read, a longer one refused: announced, chunked, until the end" $ do+      let untilEnd = "HTTP/1.0 200 OK\r\n\r\nhello world"+      announced <- readWholeWithin Nothing (Just 11) 4 fixed+      announced.body @?= "hello world"+      failsWith (BodyTooLarge 10) (readWholeWithin Nothing (Just 10) 4 fixed)+      inChunks <- readWholeWithin Nothing (Just 16) 4 chunked+      inChunks.body @?= "hello world12345"+      failsWith (BodyTooLarge 15) (readWholeWithin Nothing (Just 15) 4 chunked)+      toTheEnd <- readWholeWithin Nothing (Just 11) 4 untilEnd+      toTheEnd.body @?= "hello world"+      failsWith (BodyTooLarge 10) (readWholeWithin Nothing (Just 10) 4 untilEnd)+  , testCase "too long a body that is announced is refused before it is read" $ do+      -- Only the head is given: reading a body would fail otherwise.+      outcome <- try (readResponseWithin Nothing (Just 10) "GET" (fromStream (fromList [toArray fixedHead])))+      fmap (.status) outcome @?= Left (BodyTooLarge 10)+  , testProperty "the head of a request is read, with what follows it, however the bytes are cut" $ \(Positive size) ->+      ioProperty $ do+        let bytes = "GET /chat?room=1 HTTP/1.1\r\nHost: example.org\r\nUpgrade:  websocket \r\nX-Empty:\r\n\r\n\129\5hello"+        (found, rest) <- readRequestHeadWithin (Just 1000) (fromStream (fromList (map toArray (pieces size bytes))))+        following <- collect (toStream rest)+        pure+          ( (found, requestHeader "UPGRADE" found, following)+              === (RequestHead "GET" "/chat?room=1" [("host", "example.org"), ("upgrade", "websocket"), ("x-empty", "")], Just "websocket", "\129\5hello")+          )+  , testCase "what is not the head of a request, and one that is too long" $ do+      let headOf limit bytes = readRequestHeadWithin limit (fromStream (fromList (map toArray (pieces 7 bytes))))+          malformed bytes =+            try (headOf Nothing bytes) >>= \case+              Left (MalformedRequest _) -> pure ()+              Left other -> assertFailure ("expected MalformedRequest, got " <> show other)+              Right (found, _) -> assertFailure ("accepted " <> show found)+      mapM_ malformed ["", "GET / HTTP/1.1\r\nHost: x\r\n", "GET /a b HTTP/1.1\r\n\r\n", "GET / HTTP/2\r\n\r\n", "HTTP/1.1 200 OK\r\n\r\n", "GET /\r\n\r\n", "GET / HTTP/1.1\r\nno colon\r\n\r\n"]+      outcome <- try (headOf (Just 20) "GET / HTTP/1.1\r\nHost: example.org\r\n\r\n")+      fmap fst outcome @?= Left (HeadTooLarge 20)+  , testCase "a body cut short" $+      failsWith (TruncatedBody 5) (readWhole 4 "HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhello ")+  , testCase "a chunk cut short" $+      failsWith (TruncatedBody 2) (readWhole 4 "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhel")+  , testCase "a chunked body without its last chunk" $+      isMalformed (readWhole 4 "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n")+  , testCase "a chunk size that is not hexadecimal" $+      isMalformed (readWhole 4096 "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nxyz\r\nhello\r\n")+  , -- With streamly-core 0.3.3 a parser repeated by 'many' gives back what+    -- it read when the input ends inside an element, and a following 'eof'+    -- would succeed: the head must end with its empty line instead.+    testCase "a head cut inside a header line" $+      isMalformed (readWhole 4096 "HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\nContent-Le")+  , testCase "a head cut before its empty line" $+      isMalformed (readWhole 4096 "HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\n")+  , testCase "no input at all" $+      isMalformed (readWhole 4096 "")+  , testCase "a header line without a colon" $+      isMalformed (readWhole 4096 "HTTP/1.1 200 OK\r\nnot a header\r\n\r\n")+  , testCase "a folded header line" $+      isMalformed (readWhole 4096 "HTTP/1.1 200 OK\r\nA: b\r\n c\r\n\r\n")+  , testCase "something that is not HTTP" $+      isMalformed (readWhole 4096 "SSH-2.0-OpenSSH\r\n")+  , testCase "a status code of two digits" $+      isMalformed (readWhole 4096 "HTTP/1.1 20 OK\r\n\r\n")+  , testCase "a Content-Length that is not a number" $ do+      failsWith (InvalidContentLength "12a") (readWhole 4096 "HTTP/1.1 200 OK\r\nContent-Length: 12a\r\n\r\n")+      failsWith (InvalidContentLength "-1") (readWhole 4096 "HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\n")+  , testCase "a transfer coding other than chunked" $+      failsWith (UnsupportedTransferEncoding "gzip, chunked") (readWhole 4096 "HTTP/1.1 200 OK\r\nTransfer-Encoding: gzip, chunked\r\n\r\n")+  ]++rendered :: Request -> IO ByteString+rendered = collect . renderRequest++writing :: [TestTree]+writing =+  [ testCase "a GET" $ do+      bytes <- rendered (withHeaders [("Accept", "image/jpeg")] (get "example.org" 8080 "/a?b=c"))+      bytes @?= "GET /a?b=c HTTP/1.1\r\nHost: example.org:8080\r\nAccept: image/jpeg\r\n\r\n"+  , testCase "the Host header leaves out port 80 and brackets an IPv6 address" $ do+      plain <- rendered (get "example.org" 80 "/")+      plain @?= "GET / HTTP/1.1\r\nHost: example.org\r\n\r\n"+      v6 <- rendered (get "::1" 9330 "/")+      v6 @?= "GET / HTTP/1.1\r\nHost: [::1]:9330\r\n\r\n"+  , testCase "a Host given by the caller is kept, the framing headers are not" $ do+      bytes <- rendered (withHeaders [("host", "virtual"), ("Content-Length", "99"), ("connection", "Upgrade")] (get "127.0.0.1" 80 "/"))+      bytes @?= "GET / HTTP/1.1\r\nhost: virtual\r\nconnection: Upgrade\r\n\r\n"+  , testCase "a body in bytes" $ do+      bytes <- rendered (withBody (BodyBytes "hello") (get "h" 80 "/") {method = "POST"})+      bytes @?= "POST / HTTP/1.1\r\nHost: h\r\nContent-Length: 5\r\n\r\nhello"+  , testCase "an empty body in bytes still announces its length" $ do+      bytes <- rendered (withBody (BodyBytes "") (get "h" 80 "/") {method = "POST"})+      bytes @?= "POST / HTTP/1.1\r\nHost: h\r\nContent-Length: 0\r\n\r\n"+  , testCase "a body in a stream is chunked, empty arrays left out" $ do+      let chunks = fromList (map toArray ["hello", "", "0123456789abcdef"])+      bytes <- rendered (withBody (BodyStream chunks) (get "h" 80 "/") {method = "PUT"})+      bytes @?= "PUT / HTTP/1.1\r\nHost: h\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n10\r\n0123456789abcdef\r\n0\r\n\r\n"+  , testCase "requests that would run a field into the next are refused" $ do+      let refused request = case validateRequest request of+            Left (InvalidRequest _) -> pure ()+            other -> assertFailure ("expected InvalidRequest, got " <> show other)+      validateRequest (withHeaders [("Accept", "a, b")] (get "example.org" 80 "/a?b=c")) @?= Right ()+      refused (get "example.org" 80 "/a b")+      refused (get "example.org" 80 "/a\r\nX: y")+      refused (get "example.org" 80 "a")+      refused (get "exa mple.org" 80 "/")+      refused (get "" 80 "/")+      refused (get "example.org" 0 "/")+      refused (get "example.org" 80 "/") {method = "GE T"}+      refused (withHeaders [("A", "b\r\nC: d")] (get "example.org" 80 "/"))+      refused (withHeaders [("A B", "c")] (get "example.org" 80 "/"))+  ]++urls :: [TestTree]+urls =+  [ testCase "a URL with everything" $+      parseUrl "https://Example.ORG:8443/a/b?c=d#e" @?= Right (Url Https "example.org" 8443 "/a/b?c=d")+  , testCase "the port of the scheme, and the root as the path" $ do+      parseUrl "http://example.org" @?= Right (Url Http "example.org" 80 "/")+      parseUrl "HTTPS://example.org" @?= Right (Url Https "example.org" 443 "/")+      parseUrl "http://example.org?q=1" @?= Right (Url Http "example.org" 80 "/?q=1")+      parseUrl "http://example.org/#top" @?= Right (Url Http "example.org" 80 "/")+  , testCase "addresses as hosts" $ do+      parseUrl "http://127.0.0.1:9330/api/image/k" @?= Right (Url Http "127.0.0.1" 9330 "/api/image/k")+      parseUrl "http://[::1]:9330/" @?= Right (Url Http "::1" 9330 "/")+      parseUrl "https://[2001:DB8::1]/x" @?= Right (Url Https "2001:db8::1" 443 "/x")+  , testCase "what is refused" $ do+      let refusedUrl text = either (const (pure ())) (\found -> assertFailure ("accepted " <> show text <> " as " <> show found)) (parseUrl text)+      mapM_+        refusedUrl+        [ ""+        , "example.org"+        , "ftp://example.org/"+        , "http:/example.org"+        , "http://"+        , "http://user@example.org/"+        , "http://user:secret@example.org/"+        , "http://example.org:/"+        , "http://example.org:0/"+        , "http://example.org:65536/"+        , "http://example.org:80x/"+        , "http://example.org/a b"+        , "http://example.org/a\r\nX: y"+        , "http://[::1/"+        ]+  , testCase "a URL is written back, the port of the scheme left out" $ do+      map (fmap renderUrl . parseUrl) ["https://example.org:443/a?b", "http://example.org:8080", "http://[::1]:80/x"]+        @?= [Right "https://example.org/a?b", Right "http://example.org:8080/", Right "http://[::1]/x"]+  , testCase "references are resolved against a URL" $ do+      let base = Url Http "example.org" 8080 "/a/b/c?q=1"+          to reference = fmap renderUrl (resolve base reference)+      to "https://other.example/x" @?= Right "https://other.example/x"+      to "//other.example/x" @?= Right "http://other.example/x"+      to "/x/y?z" @?= Right "http://example.org:8080/x/y?z"+      to "d" @?= Right "http://example.org:8080/a/b/d"+      to "../d/./e?f#g" @?= Right "http://example.org:8080/a/d/e?f"+      to "../../../d" @?= Right "http://example.org:8080/d"+      to "./" @?= Right "http://example.org:8080/a/b/"+      to ".." @?= Right "http://example.org:8080/a/"+      to "?other" @?= Right "http://example.org:8080/a/b/c?other"+      to "" @?= Right "http://example.org:8080/a/b/c?q=1"+      to "#frag" @?= Right "http://example.org:8080/a/b/c?q=1"+      to "/a b" @?= Left "a space or a control character in a reference"+      either (const (pure ())) (assertFailure . show) (to "ftp://example.org/")+  , testCase "the request for a URL" $ do+      bytes <- either fail (rendered . urlRequest) (parseUrl "https://example.org:8443/a?b")+      bytes @?= "GET /a?b HTTP/1.1\r\nHost: example.org:8443\r\n\r\n"+  ]++-- | Run a server that answers one connection: it reads the request head+-- (and what came with it), sends the answer in pieces and closes. Gives the+-- port to the action, and returns the request read with its result.+withServer :: [ByteString] -> (Int -> IO a) -> IO (ByteString, a)+withServer answer action =+  bracket open close $ \listener -> do+    port <- socketPort listener+    withAsync (serve listener) $ \server -> do+      result <- action (fromIntegral port)+      request <- wait server+      pure (request, result)+  where+    open = do+      listener <- N.socket AF_INET Stream defaultProtocol+      setSocketOption listener ReuseAddr 1+      bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+      listen listener 1+      pure listener+    serve listener =+      bracket (fst <$> accept listener) close $ \peer -> do+        request <- readHead peer ""+        mapM_ (sendAll peer) answer+        pure request+    readHead peer seen+      | "\r\n\r\n" `isInfixOf` seen = pure seen+      | otherwise = do+          more <- recv peer 4096+          if BS.null more then pure seen else readHead peer (seen <> more)++-- | Limits short enough for the tests.+quick :: Limits+quick = defaultLimits {connectTimeout = Just 2_000_000, idleTimeout = Just 150_000}++-- | A server that reads the request, sends the pieces of an answer with a+-- pause in microseconds before each, then holds the connection open.+withSlowServer :: Int -> [ByteString] -> (Int -> IO a) -> IO a+withSlowServer pause answer action =+  bracket open close $ \listener -> do+    port <- socketPort listener+    withAsync (serve listener) $ \_ -> action (fromIntegral port)+  where+    open = do+      listener <- N.socket AF_INET Stream defaultProtocol+      setSocketOption listener ReuseAddr 1+      bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+      listen listener 1+      pure listener+    serve listener =+      bracket (fst <$> accept listener) close $ \peer -> do+        _ <- recv peer 4096+        mapM_ (\piece -> threadDelay pause >> sendAll peer piece) answer+        threadDelay 10_000_000++-- | A server that sends the pieces of an answer at once, then holds the+-- connection open without a word.+withHeldServer :: [ByteString] -> (Int -> IO a) -> IO a+withHeldServer = withSlowServer 0++overTcp :: [TestTree]+overTcp =+  [ testCase "fetch sends the request and reads the whole body" $ do+      let image = BS.pack (take 100_000 (cycle [0 .. 255]))+          answer = ["HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\nContent-Le", "ngth: 100000\r\n\r\n"] <> pieces 30_000 image+      (request, (port, response)) <- withServer answer $ \port ->+        (,) port <$> fetch (withHeaders [("Accept", "image/jpeg")] (get "127.0.0.1" port "/api/image/key?width=300"))+      request @?= "GET /api/image/key?width=300 HTTP/1.1\r\nHost: 127.0.0.1:" <> BS8.pack (show port) <> "\r\nAccept: image/jpeg\r\nConnection: close\r\n\r\n"+      (response.status, header "content-type" response) @?= (200, Just "image/jpeg")+      fromArray response.body @?= image+  , testCase "withResponse gives the body as a stream, here chunked" $ do+      let answer = ["HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n", "2\r\nde\r\n0\r\n\r\n"]+      (_, arrays) <- withServer answer $ \port ->+        withResponse (get "localhost" port "/") $ \response -> map fromArray <$> toList response.body+      BS.concat arrays @?= "abcde"+  , testCase "the client closes the connection, whatever the request says" $ do+      (request, _) <- withServer ["HTTP/1.1 204 No Content\r\n\r\n"] $ \port ->+        fetch (withHeaders [("connection", "keep-alive")] (get "127.0.0.1" port "/"))+      BS.drop (BS.length request - 23) request @?= "\r\nConnection: close\r\n\r\n"+      isInfixOf "keep-alive" request @?= False+  , testCase "over a transport of the caller: what is sent, and the response read" $ do+      sent <- newIORef []+      let answer = map toArray ["HTTP/1.1 200 OK\r\nContent-Le", "ngth: 5\r\n\r\nhel", "lo"]+          transport = Transport {send = \array -> modifyIORef sent (fromArray array :), receive = fromList answer}+      response <- fetchOver defaultLimits transport (get "example.org" 443 "/secure")+      (response.status, fromArray response.body) @?= (200, "hello")+      request <- BS.concat . reverse <$> readIORef sent+      request @?= "GET /secure HTTP/1.1\r\nHost: example.org:443\r\nConnection: close\r\n\r\n"+  , testCase "a status is not an error" $ do+      (_, response) <- withServer ["HTTP/1.1 400 Bad Request\r\nContent-Length: 20\r\n\r\nInvalid Scale: bogus"] $ \port ->+        fetch (get "127.0.0.1" port "/")+      (response.status, response.reason, fromArray response.body) @?= (400, "Bad Request", "Invalid Scale: bogus")+  , testCase "a connection closed inside the body" $ do+      outcome <- try (withServer ["HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc"] $ \port -> fetch (get "127.0.0.1" port "/"))+      case outcome of+        Left problem -> problem @?= TruncatedBody 7+        Right _ -> assertFailure "no error, expected TruncatedBody"+  , testCase "a server that accepts and says nothing" $ do+      outcome <- withHeldServer [] $ \port -> try (fetchWithin quick (get "127.0.0.1" port "/"))+      outcome @?= Left ResponseTimedOut+  , testCase "a server that stops in the middle of the body" $ do+      outcome <- withHeldServer ["HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc"] $ \port ->+        try (fetchWithin quick (get "127.0.0.1" port "/"))+      outcome @?= Left ResponseTimedOut+  , testCase "a slow response is not a silent one: each wait is bounded, not the whole" $ do+      let answer = "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\n" : map singleton (unpack "slowly")+      response <- withSlowServer 60_000 answer $ \port -> fetchWithin quick (get "127.0.0.1" port "/")+      fromArray response.body @?= "slowly"+  , testCase "without limits a held connection is waited for" $ do+      outcome <- withHeldServer [] $ \port -> timeout 300_000 (fetchWithin noLimits (get "127.0.0.1" port "/"))+      fmap (.status) outcome @?= Nothing+  , testCase "a limited transport bounds receiving and sending" $ do+      let silent = Transport {send = \_ -> pure (), receive = repeatM (threadDelay 5_000_000 >> pure (toArray ""))}+          deaf = Transport {send = \_ -> threadDelay 5_000_000, receive = nil}+      failsWith ResponseTimedOut (fetchOver noLimits (limitTransport (Just 50_000) silent) (get "example.org" 80 "/"))+      failsWith ResponseTimedOut (fetchOver noLimits (limitTransport (Just 50_000) deaf) (get "example.org" 80 "/"))+      failsWith ResponseTimedOut (fetchOver noLimits {idleTimeout = Just 50_000} silent (get "example.org" 80 "/"))+  , testCase "connecting gives up in time" $ do+      -- An address that answers nothing where it is routed, and is refused+      -- at once where it is not: either way the wait is bounded.+      before <- getMonotonicTime+      outcome <- try (try (connectWithin (Just 200_000) "10.255.255.1" 81))+      after <- getMonotonicTime+      case outcome of+        Left (_ :: IOError) -> pure ()+        Right (Left ConnectTimedOut) -> pure ()+        Right (Left other) -> assertFailure ("expected ConnectTimedOut, got " <> show other)+        Right (Right socket) -> close socket+      assertBool ("waited " <> show (after - before) <> " s") (after - before < 2)+  , testCase "the sizes allowed apply over TCP" $ do+      let answer = ["HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\n", "01234567890123456789"]+      (_, tooLong) <- withServer answer $ \port -> try (fetchWithin defaultLimits {maxBodySize = Just 19} (get "127.0.0.1" port "/"))+      fmap (.status) tooLong @?= Left (BodyTooLarge 19)+      (_, fits) <- withServer answer $ \port -> fetchWithin defaultLimits {maxBodySize = Just 20} (get "127.0.0.1" port "/")+      fromArray fits.body @?= "01234567890123456789"+      (_, longHead) <- withServer answer $ \port -> try (fetchWithin defaultLimits {maxHeadSize = Just 20} (get "127.0.0.1" port "/"))+      fmap (.status) longHead @?= Left (HeadTooLarge 20)+  , testCase "an invalid request is refused before any connection" $+      failsWithInvalid (fetch (get "127.0.0.1" 1 "/a b"))+  , testCase "nothing listening is an IOError" $ do+      port <- bracket closedPort pure pure+      outcome <- try (fetch (get "127.0.0.1" port "/"))+      case outcome of+        Left (_ :: IOError) -> pure ()+        Right _ -> assertFailure "no error, expected an IOError"+  ]+  where+    failsWithInvalid action = do+      outcome <- try action+      case outcome of+        Left (InvalidRequest _) -> pure ()+        Left other -> assertFailure ("expected InvalidRequest, got " <> show other)+        Right _ -> assertFailure "no error, expected InvalidRequest"+    -- A port that was free a moment ago: bound, then closed.+    closedPort = bracket (N.socket AF_INET Stream defaultProtocol) close $ \socket -> do+      bind socket (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+      fromIntegral <$> socketPort socket++-- | Run a server that serves each connection in a thread of its own and,+-- on each, answers request after request with a function of the number of the+-- connection, the number of the request on it and its target. An answer+-- of 'Nothing' closes the connection without a word; 'True' with the+-- bytes closes it after them. Gives the port, and returns the result with+-- the requests seen: connection, request, target.+withKeepingServer :: (Int -> Int -> ByteString -> Maybe (ByteString, Bool)) -> (Int -> IO a) -> IO (a, [(Int, Int, ByteString)])+withKeepingServer answer action = do+  seen <- newIORef []+  bracket open close $ \listener -> do+    port <- socketPort listener+    result <- withAsync (mapM_ (accepting seen listener) [1 ..]) $ \_ -> action (fromIntegral port)+    (result,) . reverse <$> readIORef seen+  where+    open = do+      listener <- N.socket AF_INET Stream defaultProtocol+      setSocketOption listener ReuseAddr 1+      bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+      listen listener 5+      pure listener+    accepting seen listener number = mask_ $ do+      (peer, _) <- accept listener+      void (forkIOWithUnmask (\unmask -> void (try @SomeException (unmask (requests seen peer number (1 :: Int) ""))) `finally` close peer))+    requests seen peer number index buffered = do+      (requestHead', rest) <- readHead peer buffered+      if BS.null requestHead'+        then pure ()+        else do+          let target = BS8.takeWhile (/= ' ') (BS.drop 1 (BS8.dropWhile (/= ' ') requestHead'))+          modifyIORef seen ((number, index, target) :)+          case answer number index target of+            Nothing -> pure ()+            Just (bytes, closing) -> do+              sendAll peer bytes+              if closing then pure () else requests seen peer number (index + 1) rest+    -- A request head, and what came after it; an empty head at the end of+    -- the connection.+    readHead peer buffered = case breakSubstring "\r\n\r\n" buffered of+      (found, rest) | not (BS.null rest) -> pure (found, BS.drop 4 rest)+      _ -> do+        more <- recv peer 4096+        if BS.null more then pure ("", "") else readHead peer (buffered <> more)++lengthAnswer :: ByteString -> ByteString+lengthAnswer content = "HTTP/1.1 200 OK\r\nContent-Length: " <> BS8.pack (show (BS.length content)) <> "\r\n\r\n" <> content++-- | The targets asked, with the connection and the request each went on.+bodies :: [Response (Array Word8)] -> [ByteString]+bodies = map (\response -> fromArray response.body)++sessions :: [TestTree]+sessions =+  [ testCase "a client keeps a connection for each server" $ do+      let answer _ _ target = Just (lengthAnswer target, False)+      ((responses, seenByOther), seen) <- withKeepingServer answer $ \port ->+        withKeepingServer answer $ \other ->+          withClient defaultLimits $ \client ->+            mapM (\(to, target) -> fetchFrom client Http (get "127.0.0.1" to target)) [(port, "/a"), (other, "/b"), (port, "/c"), (other, "/d"), (port, "/e")]+      bodies responses @?= ["/a", "/b", "/c", "/d", "/e"]+      seen @?= [(1, 1, "/a"), (1, 2, "/c"), (1, 3, "/e")]+      seenByOther @?= [(1, 1, "/b"), (1, 2, "/d")]+  , testCase "requests to one server that overlap have a connection each, both kept afterwards" $ do+      (inner, seen) <- withKeepingServer (\_ _ target -> Just (lengthAnswer target, False)) $ \port ->+        withClient defaultLimits $ \client -> do+          inner <- withResponseFrom client Http (get "127.0.0.1" port "/outer") $ \_ ->+            fetchFrom client Http (get "127.0.0.1" port "/inner")+          -- The outer body was not read: its connection is gone, the+          -- other one is kept and serves again.+          again <- fetchFrom client Http (get "127.0.0.1" port "/again")+          pure (bodies [inner, again])+      inner @?= ["/inner", "/again"]+      sort seen @?= [(1, 1, "/outer"), (2, 1, "/inner"), (2, 2, "/again")]+  , testCase "a client in clear refuses a request over TLS" $ do+      outcome <- try (withClient defaultLimits (\client -> fetchFrom client Https (get "example.org" 443 "/")))+      fmap (.status) outcome @?= Left (InvalidRequest "this client only speaks in clear")+  , testCase "requests share one connection, whether the bodies are announced or chunked" $ do+      let answer _ _ = \case+            "/chunked" -> Just ("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\nTrailer: x\r\n\r\n", False)+            "/empty" -> Just ("HTTP/1.1 204 No Content\r\n\r\n", False)+            target -> Just (lengthAnswer ("at " <> target), False)+      (responses, seen) <- withKeepingServer answer $ \port ->+        withSession defaultLimits "127.0.0.1" port $ \session ->+          mapM (\target -> fetchIn session (get "127.0.0.1" port target)) ["/a", "/chunked", "/empty", "/b"]+      bodies responses @?= ["at /a", "abcde", "", "at /b"]+      seen @?= [(1, 1, "/a"), (1, 2, "/chunked"), (1, 3, "/empty"), (1, 4, "/b")]+  , testCase "the request does not ask to close, and a Connection header of the caller is left out" $ do+      requestSeen <- newIORef ""+      let transport = Transport {send = \array -> modifyIORef requestSeen (<> fromArray array), receive = fromList [toArray (lengthAnswer "ok")]}+      response <- withSessionOver defaultLimits (pure (transport, pure ())) $ \session ->+        fetchIn session (withHeaders [("Connection", "close"), ("Accept", "*/*")] (get "example.org" 80 "/"))+      fromArray response.body @?= "ok"+      readIORef requestSeen >>= (@?= "GET / HTTP/1.1\r\nHost: example.org\r\nAccept: */*\r\n\r\n")+  , testCase "a server that asks to close, or speaks HTTP/1.0, gets a new connection for the next request" $ do+      let answer _ _ = \case+            "/close" -> Just ("HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 2\r\n\r\nok", True)+            "/old" -> Just ("HTTP/1.0 200 OK\r\nContent-Length: 2\r\n\r\nok", True)+            "/old-kept" -> Just ("HTTP/1.0 200 OK\r\nConnection: Keep-Alive\r\nContent-Length: 2\r\n\r\nok", False)+            "/until-end" -> Just ("HTTP/1.1 200 OK\r\n\r\nok", True)+            _ -> Just (lengthAnswer "ok", False)+      (responses, seen) <- withKeepingServer answer $ \port ->+        withSession defaultLimits "127.0.0.1" port $ \session ->+          mapM (\target -> fetchIn session (get "127.0.0.1" port target)) ["/close", "/old", "/old-kept", "/kept", "/until-end", "/last"]+      bodies responses @?= replicate 6 "ok"+      map (\(connection, request, _) -> (connection, request)) seen @?= [(1, 1), (2, 1), (3, 1), (3, 2), (3, 3), (4, 1)]+  , testCase "a body that is not read to its end costs the connection" $ do+      (firstBytes, seen) <- withKeepingServer (\_ _ target -> Just (lengthAnswer ("0123456789 " <> target), False)) $ \port ->+        withSession defaultLimits "127.0.0.1" port $ \session -> do+          firstBytes <- withResponseIn session (get "127.0.0.1" port "/a") (\response -> toList (S.take 0 response.body) >> pure response.status)+          second <- fetchIn session (get "127.0.0.1" port "/b")+          pure (firstBytes, fromArray second.body)+      firstBytes @?= (200, "0123456789 /b")+      map (\(connection, request, _) -> (connection, request)) seen @?= [(1, 1), (2, 1)]+  , testCase "a connection the server has closed while idle is replaced without a word" $ do+      -- The server closes after each answer, without saying so.+      (responses, seen) <- withKeepingServer (\_ _ target -> Just (lengthAnswer ("at " <> target), True)) $ \port ->+        withSession defaultLimits "127.0.0.1" port $ \session ->+          mapM (\target -> fetchIn session (get "127.0.0.1" port target) <* threadDelay 50_000) ["/a", "/b", "/c"]+      bodies responses @?= ["at /a", "at /b", "at /c"]+      map (\(connection, _, target) -> (connection, target)) seen @?= [(1, "/a"), (2, "/b"), (3, "/c")]+  , testCase "a request with a body that is a stream is not sent twice" $ do+      (outcome, _) <- withKeepingServer (\_ _ _ -> Just (lengthAnswer "ok", True)) $ \port ->+        withSession defaultLimits "127.0.0.1" port $ \session -> do+          _ <- fetchIn session (get "127.0.0.1" port "/first")+          threadDelay 50_000+          let streamed = withBody (BodyStream (fromList [toArray "once"])) (get "127.0.0.1" port "/second") {method = "POST"}+          lost <- try @SomeException (fetchIn session streamed)+          after <- fetchIn session (get "127.0.0.1" port "/third")+          pure (either (const True) (const False) lost, fromArray after.body)+      outcome @?= (True, "ok")+  , testCase "a failure inside an exchange leaves the session usable" $ do+      let answer _ _ = \case+            "/cut" -> Just ("HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc", True)+            target -> Just (lengthAnswer ("at " <> target), False)+      (outcome, seen) <- withKeepingServer answer $ \port ->+        withSession defaultLimits "127.0.0.1" port $ \session -> do+          cut <- try (fetchIn session (get "127.0.0.1" port "/cut"))+          thrown <- try @IOError (withResponseIn session (get "127.0.0.1" port "/a") (\_ -> ioError (userError "inside")))+          after <- fetchIn session (get "127.0.0.1" port "/b")+          pure (fmap (.status) cut, either (const True) (const False) thrown, fromArray after.body)+      outcome @?= (Left (TruncatedBody 7), True, "at /b")+      map (\(connection, _, target) -> (connection, target)) seen @?= [(1, "/cut"), (2, "/a"), (3, "/b")]+  , testCase "the limits of the session apply to each exchange" $ do+      (outcome, _) <- withKeepingServer (\_ _ target -> Just (lengthAnswer target, False)) $ \port ->+        withSession defaultLimits {maxBodySize = Just 5} "127.0.0.1" port $ \session -> do+          small <- fetchIn session (get "127.0.0.1" port "/ok")+          large <- try (fetchIn session (get "127.0.0.1" port "/too-long"))+          pure (fromArray small.body, fmap (.status) large)+      outcome @?= ("/ok", Left (BodyTooLarge 5))+  ]