{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Network.Wai.Handler.Warp.Response (
    sendResponse,
    sanitizeHeaderValue, -- for testing
    containsRecoverableWhitespace, -- for benchmarking
    --  Provided here for backwards compatibility.
    warpVersion,
    hasBody,
    replaceHeader,
    addServer, -- testing
    addAltSvc,
) where

import qualified Control.Exception as E
import qualified Data.ByteString as S
import Data.ByteString.Internal (toForeignPtr, unsafeCreate)
import Data.ByteString.Builder (Builder, byteString)
import Data.ByteString.Builder.Extra (flush)
import Data.ByteString.Builder.HTTP.Chunked (
    chunkedTransferEncoding,
    chunkedTransferTerminator,
 )
import qualified Data.CaseInsensitive as CI
import Data.Foldable (for_)
import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)
import Data.Streaming.ByteString.Builder (
    newByteStringBuilderRecv,
    reuseBufferStrategy,
 )
import Data.Word8 (_cr, _lf, _nul, _space)
import Foreign (copyBytes, plusForeignPtr, pokeByteOff, withForeignPtr)
import qualified Network.HTTP.Types as H
import qualified Network.HTTP.Types.Header as Header
import Network.Wai
import Network.Wai.Internal
import qualified System.TimeManager as T

import Network.Wai.Handler.Warp.Buffer (toBuilderBuffer)
import qualified Network.Wai.Handler.Warp.Date as D
import Network.Wai.Handler.Warp.File
import Network.Wai.Handler.Warp.Header
import Network.Wai.Handler.Warp.IO (toBufIOWith, unsafeToBufIOWithOffset)
import Network.Wai.Handler.Warp.Imports
import Network.Wai.Handler.Warp.ResponseHeader
import Network.Wai.Handler.Warp.Settings
import Network.Wai.Handler.Warp.Types

-- $setup
-- >>> :set -XOverloadedStrings

----------------------------------------------------------------

-- | Sending a HTTP response to 'Connection' according to 'Response'.
--
--   Applications/middlewares MUST provide a proper 'H.ResponseHeaders'.
--   so that inconsistency does not happen.
--   No header is deleted by this function.
--
--   Especially, Applications/middlewares MUST provide a proper
--   Content-Type. They MUST NOT provide
--   Content-Length, Content-Range, and Transfer-Encoding
--   because they are inserted, when necessary,
--   regardless they already exist.
--   This function does not insert Content-Encoding. It's middleware's
--   responsibility.
--
--   The Date and Server header is added if not exist
--   in HTTP response header.
--
--   There are three basic APIs to create 'Response':
--
--   ['responseBuilder' :: 'H.Status' -> 'H.ResponseHeaders' -> 'Builder' -> 'Response']
--     HTTP response body is created from 'Builder'.
--     Transfer-Encoding: chunked is used in HTTP/1.1.
--
--   ['responseStream' :: 'H.Status' -> 'H.ResponseHeaders' -> 'StreamingBody' -> 'Response']
--     HTTP response body is created from 'Builder'.
--     Transfer-Encoding: chunked is used in HTTP/1.1.
--
--   ['responseRaw' :: ('IO' 'ByteString' -> ('ByteString' -> 'IO' ()) -> 'IO' ()) -> 'Response' -> 'Response']
--     No header is added and no Transfer-Encoding: is applied.
--
--   ['responseFile' :: 'H.Status' -> 'H.ResponseHeaders' -> 'FilePath' -> 'Maybe' 'FilePart' -> 'Response']
--     HTTP response body is sent (by sendfile(), if possible) for GET method.
--     HTTP response body is not sent by HEAD method.
--     Content-Length and Content-Range are automatically
--     added into the HTTP response header if necessary.
--     If Content-Length and Content-Range exist in the HTTP response header,
--     they would cause inconsistency.
--     \"Accept-Ranges: bytes\" is also inserted.
--
--     Applications are categorized into simple and sophisticated.
--     Sophisticated applications should specify 'Just' to
--     'Maybe' 'FilePart'. They should treat the conditional request
--     by themselves. A proper 'Status' (200 or 206) must be provided.
--
--     Simple applications should specify 'Nothing' to
--     'Maybe' 'FilePart'. The size of the specified file is obtained
--     by disk access or from the file info cache.
--     If-Modified-Since, If-Unmodified-Since, If-Range and Range
--     are processed. Since a proper status is chosen, 'Status' is
--     ignored. Last-Modified is inserted.
sendResponse
    :: Settings
    -> Connection
    -> InternalInfo
    -> T.Handle
    -> Request
    -- ^ HTTP request.
    -> IndexedRequestHeader
    -- ^ Indexed header of HTTP request.
    -> IO ByteString
    -- ^ source from client, for raw response
    -> Response
    -- ^ HTTP response including status code and response header.
    -> IO Bool
    -- ^ Returing True if the connection is persistent.
sendResponse :: Settings
-> Connection
-> InternalInfo
-> Handle
-> Request
-> IndexedRequestHeader
-> IO ByteString
-> Response
-> IO Bool
sendResponse Settings
settings Connection
conn InternalInfo
ii Handle
th Request
req IndexedRequestHeader
reqidxhdr IO ByteString
src Response
response = do
    -- Decide connection persistence
    isShuttingDown <-
        case Settings -> Maybe ServerState
settingsServerState Settings
settings of
            Just ServerState
serverState -> ServerState -> IO Bool
currentShuttingDownState ServerState
serverState
            -- Should never be reached!
            -- (cf. 'makeServerState' in 'runSettingsConnectionMakerSecure')
            Maybe ServerState
Nothing -> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False
    let shouldPersist = Bool -> Bool
not Bool
isShuttingDown Bool -> Bool -> Bool
&& Bool
ret
        addConnection [(HeaderName, b)]
hs =
            if Bool
shouldPersist Bool -> Bool -> Bool
|| Bool
responseWantsToClose
                then [(HeaderName, b)]
hs
                else (HeaderName
Header.hConnection, b
"close") (HeaderName, b) -> [(HeaderName, b)] -> [(HeaderName, b)]
forall a. a -> [a] -> [a]
: [(HeaderName, b)]
hs

    -- Adjust headers
    hs <- addConnection . addAltSvc settings <$> addServerAndDate hs0

    -- Start response logic
    if hasBody s
        then do
            -- The response to HEAD does not have body.
            -- But to handle the conditional requests defined RFC 7232 and
            -- to generate appropriate content-length, content-range,
            -- and status, the response to HEAD is processed here.
            --
            -- See definition of rsp below for proper body stripping.
            (ms, mlen) <- sendRsp conn ii th ver s hs rspidxhdr maxRspBufSize method rsp
            case ms of
                Maybe Status
Nothing -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
                Just Status
realStatus -> Request -> Status -> Maybe Integer -> IO ()
logger Request
req Status
realStatus Maybe Integer
mlen
        else do
            _ <- sendRsp conn ii th ver s hs rspidxhdr maxRspBufSize method RspNoBody
            logger req s Nothing
    T.tickle th
    return shouldPersist
  where
    -- From Settings --
    defServer :: ByteString
defServer = Settings -> ByteString
settingsServerName Settings
settings
    logger :: Request -> Status -> Maybe Integer -> IO ()
logger = Settings -> Request -> Status -> Maybe Integer -> IO ()
settingsLogger Settings
settings
    maxRspBufSize :: Int
maxRspBufSize = Settings -> Int
settingsMaxBuilderResponseBufferSize Settings
settings

    -- From Request --
    method :: ByteString
method = Request -> ByteString
requestMethod Request
req
    isHead :: Bool
isHead = ByteString
method ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
H.methodHead
    ver :: HttpVersion
ver = Request -> HttpVersion
httpVersion Request
req
    isHttp11 :: Bool
isHttp11 = HttpVersion
ver HttpVersion -> HttpVersion -> Bool
forall a. Eq a => a -> a -> Bool
== HttpVersion
H.http11
    reqSaysPersist :: Bool
reqSaysPersist = Bool -> IndexedRequestHeader -> Bool
checkReqConnectionHeader Bool
isHttp11 IndexedRequestHeader
reqidxhdr

    -- From Response --
    s :: Status
s = Response -> Status
responseStatus Response
response
    hs0 :: [(HeaderName, ByteString)]
hs0 = [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
sanitizeHeaders ([(HeaderName, ByteString)] -> [(HeaderName, ByteString)])
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
forall a b. (a -> b) -> a -> b
$ Response -> [(HeaderName, ByteString)]
responseHeaders Response
response
    rspidxhdr :: ResponseHeaderPresence
rspidxhdr = [(HeaderName, ByteString)] -> ResponseHeaderPresence
indexResponseHeader [(HeaderName, ByteString)]
hs0
    hasLength :: Bool
hasLength = ResponseHeaderPresence -> Bool
hasContentLength ResponseHeaderPresence
rspidxhdr
    responseWantsToClose :: Bool
responseWantsToClose =
        case ResponseHeaderPresence -> Maybe ByteString
hasConnection ResponseHeaderPresence
rspidxhdr of
            Maybe ByteString
Nothing -> Bool
False
            Just ByteString
v -> ByteString -> ByteString
forall s. FoldCase s => s -> s
CI.foldCase ByteString
v ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
"close"
    isPersist :: Bool
isPersist = Bool
reqSaysPersist Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
responseWantsToClose

    -- Other --
    getdate :: IO ByteString
getdate = InternalInfo -> IO ByteString
getDate InternalInfo
ii
    addServerAndDate :: [(HeaderName, ByteString)] -> IO [(HeaderName, ByteString)]
addServerAndDate = IO ByteString
-> ResponseHeaderPresence
-> [(HeaderName, ByteString)]
-> IO [(HeaderName, ByteString)]
addDate IO ByteString
getdate ResponseHeaderPresence
rspidxhdr ([(HeaderName, ByteString)] -> IO [(HeaderName, ByteString)])
-> ([(HeaderName, ByteString)] -> [(HeaderName, ByteString)])
-> [(HeaderName, ByteString)]
-> IO [(HeaderName, ByteString)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString
-> ResponseHeaderPresence
-> [(HeaderName, ByteString)]
-> [(HeaderName, ByteString)]
addServer ByteString
defServer ResponseHeaderPresence
rspidxhdr
    needsChunked :: Bool
needsChunked = Bool
isHttp11 Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
hasLength
    rsp :: Rsp
rsp = case Response
response of
        ResponseFile Status
_ [(HeaderName, ByteString)]
_ String
path Maybe FilePart
mPart -> String -> Maybe FilePart -> IndexedRequestHeader -> IO () -> Rsp
RspFile String
path Maybe FilePart
mPart IndexedRequestHeader
reqidxhdr (Handle -> IO ()
T.tickle Handle
th)
        ResponseBuilder Status
_ [(HeaderName, ByteString)]
_ Builder
b
            | Bool
isHead -> Rsp
RspNoBody
            | Bool
otherwise -> Builder -> Bool -> Rsp
RspBuilder Builder
b Bool
needsChunked
        ResponseStream Status
_ [(HeaderName, ByteString)]
_ StreamingBody
fb
            | Bool
isHead -> Rsp
RspNoBody
            | Bool
otherwise -> StreamingBody -> Bool -> Rsp
RspStream StreamingBody
fb Bool
needsChunked
        ResponseRaw IO ByteString -> (ByteString -> IO ()) -> IO ()
raw Response
_ -> (IO ByteString -> (ByteString -> IO ()) -> IO ())
-> IO ByteString -> Rsp
RspRaw IO ByteString -> (ByteString -> IO ()) -> IO ()
raw IO ByteString
src
    -- Should be False if (http10 && not hasLength), regardless of what
    -- the 'Connection' header says. (as long as the response should have a body)
    isKeepAlive :: Bool
isKeepAlive =
        Bool
isPersist Bool -> Bool -> Bool
&& (Bool
isHttp11 Bool -> Bool -> Bool
|| Bool
hasLength Bool -> Bool -> Bool
|| Bool
isHead Bool -> Bool -> Bool
|| Bool -> Bool
not (Status -> Bool
hasBody Status
s))
    -- Make sure we don't hang on to 'response' (avoid space leak)
    !ret :: Bool
ret = case Response
response of
        -- Will get 'Content-Length' header later on using the
        -- 'addContentHeaders(ForFilePart)' functions, so if the
        -- 'Connection' header says we persist, we persist.
        ResponseFile{} -> Bool
isPersist
        ResponseBuilder{} -> Bool
isKeepAlive
        ResponseStream{} -> Bool
isKeepAlive
        -- Is already an ongoing open connection, so if it is done,
        -- the connection should be closed.
        ResponseRaw{} -> Bool
False

----------------------------------------------------------------

-- | As per RFC 9110 we replace any newlines (\r\n) or \NUL with spaces
-- Values without CR/LF/NUL (the overwhelmingly common case) leave the
-- header list untouched; only a dirty value triggers a rebuild.
sanitizeHeaders :: H.ResponseHeaders -> H.ResponseHeaders
sanitizeHeaders :: [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
sanitizeHeaders [(HeaderName, ByteString)]
hdrs
      -- slow path
    | ((HeaderName, ByteString) -> Bool)
-> [(HeaderName, ByteString)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (ByteString -> Bool
containsRecoverableWhitespace (ByteString -> Bool)
-> ((HeaderName, ByteString) -> ByteString)
-> (HeaderName, ByteString)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (HeaderName, ByteString) -> ByteString
forall a b. (a, b) -> b
snd) [(HeaderName, ByteString)]
hdrs = ((HeaderName, ByteString) -> (HeaderName, ByteString))
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
forall a b. (a -> b) -> [a] -> [b]
map (ByteString -> ByteString
sanitize (ByteString -> ByteString)
-> (HeaderName, ByteString) -> (HeaderName, ByteString)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>) [(HeaderName, ByteString)]
hdrs
      -- fast path
    | Bool
otherwise = [(HeaderName, ByteString)]
hdrs
  where
    sanitize :: ByteString -> ByteString
sanitize ByteString
bs
        | ByteString -> Bool
containsRecoverableWhitespace ByteString
bs = ByteString -> ByteString
sanitizeHeaderValue ByteString
bs
        | Bool
otherwise = ByteString
bs

-- Yes, this is quicker than @S.any (\w -> w == _lf || w == _cr || w == _nul)@
-- because of `bytestring`'s rewrite rules.
containsRecoverableWhitespace :: ByteString -> Bool
containsRecoverableWhitespace :: ByteString -> Bool
containsRecoverableWhitespace ByteString
bs =
    (Word8 -> Bool) -> ByteString -> Bool
S.any (Word8
_lf Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
==) ByteString
bs Bool -> Bool -> Bool
|| (Word8 -> Bool) -> ByteString -> Bool
S.any (Word8
_cr Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
==) ByteString
bs Bool -> Bool -> Bool
|| (Word8 -> Bool) -> ByteString -> Bool
S.any (Word8
_nul Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
==) ByteString
bs

{-# INLINE isRecoverableWhitespace #-}
-- | CR, LF and NUL can safely be replaced with a SP according to RFC 9110
-- <https://www.rfc-editor.org/rfc/rfc9110.html#section-5.5-5>
isRecoverableWhitespace :: Word8 -> Bool
isRecoverableWhitespace :: Word8 -> Bool
isRecoverableWhitespace Word8
w = Word8
w Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
_cr Bool -> Bool -> Bool
|| Word8
w Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
_lf Bool -> Bool -> Bool
|| Word8
w Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
_nul

sanitizeHeaderValue :: ByteString -> ByteString
sanitizeHeaderValue :: ByteString -> ByteString
sanitizeHeaderValue ByteString
v =
    case (Word8 -> Bool) -> ByteString -> [Int]
S.findIndices Word8 -> Bool
isRecoverableWhitespace ByteString
v of
        -- Nothing to replace
        [] -> ByteString
v
        -- Found CR, LF or NUL.
        [Int]
ixs ->
            Int -> (Ptr Word8 -> IO ()) -> ByteString
unsafeCreate Int
len ((Ptr Word8 -> IO ()) -> ByteString)
-> (Ptr Word8 -> IO ()) -> ByteString
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
dst -> do
                ForeignPtr Word8 -> (Ptr Word8 -> IO ()) -> IO ()
forall a b. ForeignPtr a -> (Ptr a -> IO b) -> IO b
withForeignPtr ForeignPtr Word8
forall {b}. ForeignPtr b
fptr ((Ptr Word8 -> IO ()) -> IO ()) -> (Ptr Word8 -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
src -> do
                    -- copy the bytestring
                    Ptr Word8 -> Ptr Word8 -> Int -> IO ()
forall a. Ptr a -> Ptr a -> Int -> IO ()
copyBytes Ptr Word8
dst Ptr Word8
src Int
len
                    -- and then replace the offending bytes
                    [Int] -> (Int -> IO ()) -> IO ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
t a -> (a -> f b) -> f ()
for_ [Int]
ixs ((Int -> IO ()) -> IO ()) -> (Int -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Int
ix -> Ptr Word8 -> Int -> Word8 -> IO ()
forall b. Ptr b -> Int -> Word8 -> IO ()
forall a b. Storable a => Ptr b -> Int -> a -> IO ()
pokeByteOff Ptr Word8
dst Int
ix Word8
_space
  where
    (ForeignPtr Word8
fptr', Int
offset, Int
len) = ByteString -> (ForeignPtr Word8, Int, Int)
toForeignPtr ByteString
v
    -- We need to use the offset for backwards compatibility with
    -- "bytestring < 0.11"
    fptr :: ForeignPtr b
fptr = ForeignPtr Word8
fptr' ForeignPtr Word8 -> Int -> ForeignPtr b
forall a b. ForeignPtr a -> Int -> ForeignPtr b
`plusForeignPtr` Int
offset

----------------------------------------------------------------

data Rsp
    = RspNoBody
    | RspFile FilePath (Maybe FilePart) IndexedRequestHeader (IO ())
    | RspBuilder Builder Bool
    | RspStream StreamingBody Bool
    | RspRaw (IO ByteString -> (ByteString -> IO ()) -> IO ()) (IO ByteString)

----------------------------------------------------------------

sendRsp
    :: Connection
    -> InternalInfo
    -> T.Handle
    -> H.HttpVersion
    -> H.Status
    -> H.ResponseHeaders
    -> ResponseHeaderPresence
    -> Int -- maxBuilderResponseBufferSize
    -> H.Method
    -> Rsp
    -> IO (Maybe H.Status, Maybe Integer)
----------------------------------------------------------------

sendRsp :: Connection
-> InternalInfo
-> Handle
-> HttpVersion
-> Status
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Int
-> ByteString
-> Rsp
-> IO (Maybe Status, Maybe Integer)
sendRsp Connection
conn InternalInfo
_ Handle
_ HttpVersion
ver Status
s [(HeaderName, ByteString)]
hs ResponseHeaderPresence
_ Int
_ ByteString
_ Rsp
RspNoBody = do
    -- Not adding Content-Length.
    -- User agents treats it as Content-Length: 0.
    HttpVersion
-> Status -> [(HeaderName, ByteString)] -> IO ByteString
composeHeader HttpVersion
ver Status
s [(HeaderName, ByteString)]
hs IO ByteString -> (ByteString -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Connection -> ByteString -> IO ()
connSendAll Connection
conn
    (Maybe Status, Maybe Integer) -> IO (Maybe Status, Maybe Integer)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Status -> Maybe Status
forall a. a -> Maybe a
Just Status
s, Integer -> Maybe Integer
forall a. a -> Maybe a
Just Integer
0)

----------------------------------------------------------------

sendRsp Connection
conn InternalInfo
_ Handle
th HttpVersion
ver Status
s [(HeaderName, ByteString)]
hs ResponseHeaderPresence
rspidxhdr Int
maxRspBufSize ByteString
_ (RspBuilder Builder
body Bool
needsChunked) = do
    writeBuffer <- IORef WriteBuffer -> IO WriteBuffer
forall a. IORef a -> IO a
readIORef IORef WriteBuffer
writeBufferRef
    len <-
        -- SAFETY: this check is what makes the unchecked writes below
        -- memory-safe, do not weaken it. composeHeaderPtr writes hdrLen
        -- bytes into the write buffer with no bounds checking of its own,
        -- and unsafeToBufIOWithOffset requires an offset within the
        -- buffer (it hands the builder buffer + offset with
        -- bufSize - offset bytes of claimed free space). If hdrLen could
        -- reach the buffer size, either write would run past the end of
        -- the allocation and corrupt memory, so oversized headers must
        -- take the composeHeaderBuilder fallback.
        if hdrLen < bufSize writeBuffer
            then do
                -- Compose the header directly into the connection write
                -- buffer and run the body builder right after it, saving
                -- a copy of the header bytes through an intermediate
                -- ByteString.
                _ <- composeHeaderPtr (bufBuffer writeBuffer) ver s hs'
                unsafeToBufIOWithOffset hdrLen maxRspBufSize writeBufferRef send bdy
            else do
                -- Huge headers: fall back to composing a separate header
                -- ByteString and letting the builder machinery copy it.
                (header, _) <- composeHeaderBuilder ver s hs rspidxhdr needsChunked
                toBufIOWith maxRspBufSize writeBufferRef send (header <> bdy)
    --              small adjustment to only count the body
    return (Just s, Just $ len - fromIntegral hdrLen)
  where
    hs' :: [(HeaderName, ByteString)]
hs'
        | Bool
needsChunked = ResponseHeaderPresence
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
addTransferEncoding ResponseHeaderPresence
rspidxhdr [(HeaderName, ByteString)]
hs
        | Bool
otherwise = [(HeaderName, ByteString)]
hs
    hdrLen :: Int
hdrLen = Status -> [(HeaderName, ByteString)] -> Int
composeHeaderLength Status
s [(HeaderName, ByteString)]
hs'
    bdy :: Builder
bdy
        | Bool
needsChunked = Builder -> Builder
chunkedTransferEncoding Builder
body Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
chunkedTransferTerminator
        | Bool
otherwise = Builder
body
    writeBufferRef :: IORef WriteBuffer
writeBufferRef = Connection -> IORef WriteBuffer
connWriteBuffer Connection
conn
    send :: ByteString -> IO ()
send ByteString
bs = Connection -> ByteString -> IO ()
connSendAll Connection
conn ByteString
bs IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Handle -> IO ()
T.tickle Handle
th

----------------------------------------------------------------

sendRsp Connection
conn InternalInfo
_ Handle
th HttpVersion
ver Status
s [(HeaderName, ByteString)]
hs ResponseHeaderPresence
rspidxhdr Int
_ ByteString
_ (RspStream StreamingBody
streamingBody Bool
needsChunked) = do
    (header, hdrLen) <- HttpVersion
-> Status
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Bool
-> IO (Builder, Int)
composeHeaderBuilder HttpVersion
ver Status
s [(HeaderName, ByteString)]
hs ResponseHeaderPresence
rspidxhdr Bool
needsChunked
    (recv, finish) <-
        newByteStringBuilderRecv $
            reuseBufferStrategy $
                toBuilderBuffer $
                    connWriteBuffer conn
    -- We'll be counting how many bytes we send with this 'IORef'
    sizeCounter <- newIORef (0 :: Integer)
    let sendFragmentAndCount ByteString
bs = do
            Connection -> Handle -> ByteString -> IO ()
sendFragment Connection
conn Handle
th ByteString
bs
            -- add amount of bytes to count
            ByteString -> Int
S.length ByteString
bs Int -> IORef Integer -> IO ()
`addToCounter` IORef Integer
sizeCounter
    let send Builder
builder = do
            popper <- BuilderRecv
recv Builder
builder
            let loop = do
                    bs <- IO ByteString
popper
                    unless (S.null bs) $ do
                        sendFragmentAndCount bs
                        loop
            loop
        sendChunk
            | Bool
needsChunked = Builder -> IO ()
send (Builder -> IO ()) -> (Builder -> Builder) -> Builder -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Builder -> Builder
chunkedTransferEncoding
            | Bool
otherwise = Builder -> IO ()
send
    send header
    streamingBody sendChunk (sendChunk flush)
    when needsChunked $ send chunkedTransferTerminator
    -- final flush
    finish >>= mapM_ sendFragmentAndCount
    finalSize <- readIORef sizeCounter
    --              small adjustment to only count the body
    return (Just s, Just $ finalSize - fromIntegral hdrLen)
  where
    addToCounter :: Int -> IORef Integer -> IO ()
    addToCounter :: Int -> IORef Integer -> IO ()
addToCounter Int
bytes IORef Integer
ref =
        IORef Integer -> (Integer -> (Integer, ())) -> IO ()
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' IORef Integer
ref ((Integer -> (Integer, ())) -> IO ())
-> (Integer -> (Integer, ())) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Integer
old ->
            (Integer
old Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Int -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
bytes, ())

----------------------------------------------------------------

sendRsp Connection
conn InternalInfo
_ Handle
th HttpVersion
_ Status
_ [(HeaderName, ByteString)]
_ ResponseHeaderPresence
_ Int
_ ByteString
_ (RspRaw IO ByteString -> (ByteString -> IO ()) -> IO ()
withApp IO ByteString
src) = do
    IO ByteString -> (ByteString -> IO ()) -> IO ()
withApp IO ByteString
recv ByteString -> IO ()
send
    (Maybe Status, Maybe Integer) -> IO (Maybe Status, Maybe Integer)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Status
forall a. Maybe a
Nothing, Maybe Integer
forall a. Maybe a
Nothing)
  where
    recv :: IO ByteString
recv = do
        bs <- IO ByteString
src
        unless (S.null bs) $ T.tickle th
        return bs
    send :: ByteString -> IO ()
send ByteString
bs = Connection -> ByteString -> IO ()
connSendAll Connection
conn ByteString
bs IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Handle -> IO ()
T.tickle Handle
th

----------------------------------------------------------------

-- Sophisticated WAI applications.
-- We respect s0. s0 MUST be a proper value.
sendRsp Connection
conn InternalInfo
ii Handle
th HttpVersion
ver Status
s0 [(HeaderName, ByteString)]
hs0 ResponseHeaderPresence
rspidxhdr Int
maxRspBufSize ByteString
method (RspFile String
path (Just FilePart
part) IndexedRequestHeader
_ IO ()
hook) =
    Connection
-> InternalInfo
-> Handle
-> HttpVersion
-> Status
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Int
-> ByteString
-> String
-> Integer
-> Integer
-> IO ()
-> IO (Maybe Status, Maybe Integer)
sendRspFile2XX
        Connection
conn
        InternalInfo
ii
        Handle
th
        HttpVersion
ver
        Status
s0
        [(HeaderName, ByteString)]
hs
        ResponseHeaderPresence
rspidxhdr
        Int
maxRspBufSize
        ByteString
method
        String
path
        Integer
beg
        Integer
len
        IO ()
hook
  where
    beg :: Integer
beg = FilePart -> Integer
filePartOffset FilePart
part
    len :: Integer
len = FilePart -> Integer
filePartByteCount FilePart
part
    hs :: [(HeaderName, ByteString)]
hs = [(HeaderName, ByteString)]
-> FilePart -> [(HeaderName, ByteString)]
addContentHeadersForFilePart [(HeaderName, ByteString)]
hs0 FilePart
part

----------------------------------------------------------------

-- Simple WAI applications.
-- Status is ignored
sendRsp Connection
conn InternalInfo
ii Handle
th HttpVersion
ver Status
_ [(HeaderName, ByteString)]
hs0 ResponseHeaderPresence
rspidxhdr Int
maxRspBufSize ByteString
method (RspFile String
path Maybe FilePart
Nothing IndexedRequestHeader
reqidxhdr IO ()
hook) = do
    efinfo <- IO FileInfo -> IO (Either IOException FileInfo)
forall e a. Exception e => IO a -> IO (Either e a)
E.try (IO FileInfo -> IO (Either IOException FileInfo))
-> IO FileInfo -> IO (Either IOException FileInfo)
forall a b. (a -> b) -> a -> b
$ InternalInfo -> String -> IO FileInfo
getFileInfo InternalInfo
ii String
path
    case efinfo of
        Left (IOException
_ex :: E.IOException) ->
#ifdef WARP_DEBUG
            print _ex >>
#endif
            Connection
-> InternalInfo
-> Handle
-> HttpVersion
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Int
-> ByteString
-> IO (Maybe Status, Maybe Integer)
sendRspFile404 Connection
conn InternalInfo
ii Handle
th HttpVersion
ver [(HeaderName, ByteString)]
hs0 ResponseHeaderPresence
rspidxhdr Int
maxRspBufSize ByteString
method
        Right FileInfo
finfo -> case FileInfo
-> [(HeaderName, ByteString)]
-> ByteString
-> ResponseHeaderPresence
-> IndexedRequestHeader
-> RspFileInfo
conditionalRequest FileInfo
finfo [(HeaderName, ByteString)]
hs0 ByteString
method ResponseHeaderPresence
rspidxhdr IndexedRequestHeader
reqidxhdr of
            WithoutBody Status
s ->
                Connection
-> InternalInfo
-> Handle
-> HttpVersion
-> Status
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Int
-> ByteString
-> Rsp
-> IO (Maybe Status, Maybe Integer)
sendRsp Connection
conn InternalInfo
ii Handle
th HttpVersion
ver Status
s [(HeaderName, ByteString)]
hs0 ResponseHeaderPresence
rspidxhdr Int
maxRspBufSize ByteString
method Rsp
RspNoBody
            WithBody Status
s [(HeaderName, ByteString)]
hs Integer
beg Integer
len ->
                Connection
-> InternalInfo
-> Handle
-> HttpVersion
-> Status
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Int
-> ByteString
-> String
-> Integer
-> Integer
-> IO ()
-> IO (Maybe Status, Maybe Integer)
sendRspFile2XX
                    Connection
conn
                    InternalInfo
ii
                    Handle
th
                    HttpVersion
ver
                    Status
s
                    [(HeaderName, ByteString)]
hs
                    ResponseHeaderPresence
rspidxhdr
                    Int
maxRspBufSize
                    ByteString
method
                    String
path
                    Integer
beg
                    Integer
len
                    IO ()
hook

----------------------------------------------------------------

sendRspFile2XX
    :: Connection
    -> InternalInfo
    -> T.Handle
    -> H.HttpVersion
    -> H.Status
    -> H.ResponseHeaders
    -> ResponseHeaderPresence
    -> Int
    -> H.Method
    -> FilePath
    -> Integer
    -> Integer
    -> IO ()
    -> IO (Maybe H.Status, Maybe Integer)
sendRspFile2XX :: Connection
-> InternalInfo
-> Handle
-> HttpVersion
-> Status
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Int
-> ByteString
-> String
-> Integer
-> Integer
-> IO ()
-> IO (Maybe Status, Maybe Integer)
sendRspFile2XX Connection
conn InternalInfo
ii Handle
th HttpVersion
ver Status
s [(HeaderName, ByteString)]
hs ResponseHeaderPresence
rspidxhdr Int
maxRspBufSize ByteString
method String
path Integer
beg Integer
len IO ()
hook
    | ByteString
method ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
H.methodHead =
        -- FIXME: We could check the size of the file and add a
        -- 'Content-Length' header to give the requester more information?
        Connection
-> InternalInfo
-> Handle
-> HttpVersion
-> Status
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Int
-> ByteString
-> Rsp
-> IO (Maybe Status, Maybe Integer)
sendRsp Connection
conn InternalInfo
ii Handle
th HttpVersion
ver Status
s [(HeaderName, ByteString)]
hs ResponseHeaderPresence
rspidxhdr Int
maxRspBufSize ByteString
method Rsp
RspNoBody
    | Bool
otherwise = do
        lheader <- HttpVersion
-> Status -> [(HeaderName, ByteString)] -> IO ByteString
composeHeader HttpVersion
ver Status
s [(HeaderName, ByteString)]
hs
        (mfd, fresher) <- getFd ii path
        let fid = String -> Maybe Fd -> FileId
FileId String
path Maybe Fd
mfd
            hook' = IO ()
hook IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> IO ()
fresher
        connSendFile conn fid beg len hook' [lheader]
        return (Just s, Just len)

sendRspFile404
    :: Connection
    -> InternalInfo
    -> T.Handle
    -> H.HttpVersion
    -> H.ResponseHeaders
    -> ResponseHeaderPresence
    -> Int
    -> H.Method
    -> IO (Maybe H.Status, Maybe Integer)
sendRspFile404 :: Connection
-> InternalInfo
-> Handle
-> HttpVersion
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Int
-> ByteString
-> IO (Maybe Status, Maybe Integer)
sendRspFile404 Connection
conn InternalInfo
ii Handle
th HttpVersion
ver [(HeaderName, ByteString)]
hs0 ResponseHeaderPresence
rspidxhdr Int
maxRspBufSize ByteString
method =
    Connection
-> InternalInfo
-> Handle
-> HttpVersion
-> Status
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Int
-> ByteString
-> Rsp
-> IO (Maybe Status, Maybe Integer)
sendRsp
        Connection
conn
        InternalInfo
ii
        Handle
th
        HttpVersion
ver
        Status
s
        [(HeaderName, ByteString)]
hs
        ResponseHeaderPresence
rspidxhdr
        Int
maxRspBufSize
        ByteString
method
        (Builder -> Bool -> Rsp
RspBuilder Builder
body Bool
True)
  where
    s :: Status
s = Status
H.notFound404
    hs :: [(HeaderName, ByteString)]
hs = HeaderName
-> ByteString
-> [(HeaderName, ByteString)]
-> [(HeaderName, ByteString)]
replaceHeader HeaderName
Header.hContentType ByteString
"text/plain; charset=utf-8" [(HeaderName, ByteString)]
hs0
    body :: Builder
body = ByteString -> Builder
byteString ByteString
"File not found"

----------------------------------------------------------------
----------------------------------------------------------------

-- | Use 'connSendAll' to send this data while respecting timeout rules.
sendFragment :: Connection -> T.Handle -> ByteString -> IO ()
sendFragment :: Connection -> Handle -> ByteString -> IO ()
sendFragment Connection{connSendAll :: Connection -> ByteString -> IO ()
connSendAll = ByteString -> IO ()
send} Handle
th ByteString
bs = do
    Handle -> IO ()
T.resume Handle
th
    ByteString -> IO ()
send ByteString
bs
    Handle -> IO ()
T.pause Handle
th

-- We pause timeouts before passing control back to user code. This ensures
-- that a timeout will only ever be executed when Warp is in control. We
-- also make sure to resume the timeout after the completion of user code
-- so that we can kill idle connections.

----------------------------------------------------------------

-- | We infer from the request whether the connection should be persisted.
checkReqConnectionHeader :: Bool -> IndexedRequestHeader -> Bool
checkReqConnectionHeader :: Bool -> IndexedRequestHeader -> Bool
checkReqConnectionHeader Bool
isHttp11 IndexedRequestHeader
reqidxhdr =
    case IndexedRequestHeader -> Maybe ByteString
reqidxConnection IndexedRequestHeader
reqidxhdr of
        -- If no "Connection" header, then default: HTTP/1.1 == persist
        Maybe ByteString
Nothing -> Bool
isHttp11
        Just ByteString
val ->
            let connValue :: ByteString
connValue = ByteString -> ByteString
forall s. FoldCase s => s -> s
CI.foldCase ByteString
val
             in if Bool
isHttp11
                    then ByteString
connValue ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
/= ByteString
"close"
                    else ByteString
connValue ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
"keep-alive"

----------------------------------------------------------------

-- | Only checks for status codes, NOT for methods.
--
-- This is by design and some handling relies on HEAD being a separate check.
hasBody :: H.Status -> Bool
hasBody :: Status -> Bool
hasBody Status
s =
    Int
sc Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
204
        Bool -> Bool -> Bool
&& Int
sc Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
304
        Bool -> Bool -> Bool
&& Int
sc Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
200
  where
    sc :: Int
sc = Status -> Int
H.statusCode Status
s

----------------------------------------------------------------

-- | We ASSUME there's no middleware that will chunk the transfer, so
-- we'll add it to the headers if there's no other encoding, or add it
-- to the end in case it is.
-- (e.g. if a 'Middleware' were to add "Transfer-Encoding: gzip")
addTransferEncoding :: ResponseHeaderPresence -> H.ResponseHeaders -> H.ResponseHeaders
addTransferEncoding :: ResponseHeaderPresence
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
addTransferEncoding ResponseHeaderPresence
rspidxhdr =
    case ResponseHeaderPresence -> Maybe ByteString
hasTransferEncoding ResponseHeaderPresence
rspidxhdr of
        Just ByteString
value -> HeaderName
-> ByteString
-> [(HeaderName, ByteString)]
-> [(HeaderName, ByteString)]
replaceHeader HeaderName
Header.hTransferEncoding (ByteString
value ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
", chunked")
        Maybe ByteString
Nothing -> ((HeaderName
Header.hTransferEncoding, ByteString
"chunked") (HeaderName, ByteString)
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
forall a. a -> [a] -> [a]
:)

addDate
    :: IO D.GMTDate -> ResponseHeaderPresence -> H.ResponseHeaders -> IO H.ResponseHeaders
addDate :: IO ByteString
-> ResponseHeaderPresence
-> [(HeaderName, ByteString)]
-> IO [(HeaderName, ByteString)]
addDate IO ByteString
getdate ResponseHeaderPresence
rspidxhdr [(HeaderName, ByteString)]
hdrs
    | ResponseHeaderPresence -> Bool
hasDate ResponseHeaderPresence
rspidxhdr = [(HeaderName, ByteString)] -> IO [(HeaderName, ByteString)]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return [(HeaderName, ByteString)]
hdrs
    | Bool
otherwise = do
        gmtdate <- IO ByteString
getdate
        return $ (Header.hDate, gmtdate) : hdrs

----------------------------------------------------------------

{-# INLINE addServer #-}
addServer
    :: HeaderValue -> ResponseHeaderPresence -> H.ResponseHeaders -> H.ResponseHeaders
addServer :: ByteString
-> ResponseHeaderPresence
-> [(HeaderName, ByteString)]
-> [(HeaderName, ByteString)]
addServer ByteString
serverName ResponseHeaderPresence
rspidxhdr [(HeaderName, ByteString)]
hdrs =
    case ByteString
serverName of
        -- empty string means there shouldn't be a "Server" header
        ByteString
""
            | Bool
serverPresent -> ((HeaderName, ByteString) -> Bool)
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((HeaderName -> HeaderName -> Bool
forall a. Eq a => a -> a -> Bool
/= HeaderName
Header.hServer) (HeaderName -> Bool)
-> ((HeaderName, ByteString) -> HeaderName)
-> (HeaderName, ByteString)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (HeaderName, ByteString) -> HeaderName
forall a b. (a, b) -> a
fst) [(HeaderName, ByteString)]
hdrs
            | Bool
otherwise -> [(HeaderName, ByteString)]
hdrs
        -- Anything else should set the "Server" header if it isn't already set
        ByteString
_
            | Bool -> Bool
not Bool
serverPresent -> (HeaderName
Header.hServer, ByteString
serverName) (HeaderName, ByteString)
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
forall a. a -> [a] -> [a]
: [(HeaderName, ByteString)]
hdrs
            | Bool
otherwise -> [(HeaderName, ByteString)]
hdrs
  where
    serverPresent :: Bool
serverPresent = ResponseHeaderPresence -> Bool
hasServer ResponseHeaderPresence
rspidxhdr

addAltSvc :: Settings -> H.ResponseHeaders -> H.ResponseHeaders
addAltSvc :: Settings
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
addAltSvc Settings
settings [(HeaderName, ByteString)]
hs = case Settings -> Maybe ByteString
settingsAltSvc Settings
settings of
    Maybe ByteString
Nothing -> [(HeaderName, ByteString)]
hs
    Just ByteString
v -> (HeaderName
"Alt-Svc", ByteString
v) (HeaderName, ByteString)
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
forall a. a -> [a] -> [a]
: [(HeaderName, ByteString)]
hs

----------------------------------------------------------------

-- | Replaces a header, instead of just adding it which might lead to
-- duplicate entries of the same header name.
--
-- >>> replaceHeader "Content-Type" "new" [("content-type","old")]
-- [("Content-Type","new")]
replaceHeader
    :: H.HeaderName -> HeaderValue -> H.ResponseHeaders -> H.ResponseHeaders
replaceHeader :: HeaderName
-> ByteString
-> [(HeaderName, ByteString)]
-> [(HeaderName, ByteString)]
replaceHeader HeaderName
k ByteString
v [(HeaderName, ByteString)]
hdrs = (HeaderName
k, ByteString
v) (HeaderName, ByteString)
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
forall a. a -> [a] -> [a]
: ((HeaderName, ByteString) -> Bool)
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((HeaderName -> HeaderName -> Bool
forall a. Eq a => a -> a -> Bool
/= HeaderName
k) (HeaderName -> Bool)
-> ((HeaderName, ByteString) -> HeaderName)
-> (HeaderName, ByteString)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (HeaderName, ByteString) -> HeaderName
forall a b. (a, b) -> a
fst) [(HeaderName, ByteString)]
hdrs

----------------------------------------------------------------

composeHeaderBuilder
    :: H.HttpVersion -> H.Status -> H.ResponseHeaders -> ResponseHeaderPresence -> Bool -> IO (Builder, Int)
composeHeaderBuilder :: HttpVersion
-> Status
-> [(HeaderName, ByteString)]
-> ResponseHeaderPresence
-> Bool
-> IO (Builder, Int)
composeHeaderBuilder HttpVersion
ver Status
s [(HeaderName, ByteString)]
hs ResponseHeaderPresence
rspidxhdr Bool
shouldChunk = do
    bs <- HttpVersion
-> Status -> [(HeaderName, ByteString)] -> IO ByteString
composeHeader HttpVersion
ver Status
s [(HeaderName, ByteString)]
finalHdrs
    pure (byteString bs, S.length bs)
  where
    finalHdrs :: [(HeaderName, ByteString)]
finalHdrs
        | Bool
shouldChunk = ResponseHeaderPresence
-> [(HeaderName, ByteString)] -> [(HeaderName, ByteString)]
addTransferEncoding ResponseHeaderPresence
rspidxhdr [(HeaderName, ByteString)]
hs
        | Bool
otherwise = [(HeaderName, ByteString)]
hs