{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Network.Wai.Handler.Warp.HTTP2 (
http2,
http2server,
) where
import qualified Control.Exception as E
import qualified Data.ByteString as BS
import Data.IORef (readIORef)
import qualified Data.IORef as I
import GHC.Conc.Sync (labelThread, myThreadId)
import qualified Network.HTTP2.Client as H2C
import qualified Network.HTTP2.Frame as H2
import qualified Network.HTTP2.Server as H2
import Network.Socket (SockAddr)
import Network.Socket.BufferPool
import Network.Wai
import Network.Wai.Internal (ResponseReceived (..))
import qualified System.TimeManager as T
import Network.Wai.Handler.Warp.HTTP2.File
import Network.Wai.Handler.Warp.HTTP2.PushPromise
import Network.Wai.Handler.Warp.HTTP2.Request
import Network.Wai.Handler.Warp.HTTP2.Response
import Network.Wai.Handler.Warp.Imports
import qualified Network.Wai.Handler.Warp.Settings as S
import Network.Wai.Handler.Warp.Types
#define HAS_EARLY_HINTS_SUPPORT (MIN_VERSION_http_semantics(0,4,1) && MIN_VERSION_http2(5,4,2))
#if HAS_EARLY_HINTS_SUPPORT
import qualified Network.HTTP.Types as H
#endif
http2
:: S.Settings
-> InternalInfo
-> Connection
-> Transport
-> Application
-> SockAddr
-> T.Handle
-> ByteString
-> IO ()
http2 :: Settings
-> InternalInfo
-> Connection
-> Transport
-> Application
-> SockAddr
-> Handle
-> ByteString
-> IO ()
http2 Settings
settings InternalInfo
ii Connection
conn Transport
transport Application
app SockAddr
peersa Handle
th ByteString
bs = do
RecvN
rawRecvN <- ByteString -> Recv -> IO RecvN
makeRecvN ByteString
bs (Recv -> IO RecvN) -> Recv -> IO RecvN
forall a b. (a -> b) -> a -> b
$ Connection -> Recv
connRecv Connection
conn
WriteBuffer
writeBuffer <- IORef WriteBuffer -> IO WriteBuffer
forall a. IORef a -> IO a
readIORef (IORef WriteBuffer -> IO WriteBuffer)
-> IORef WriteBuffer -> IO WriteBuffer
forall a b. (a -> b) -> a -> b
$ Connection -> IORef WriteBuffer
connWriteBuffer Connection
conn
let recvN :: RecvN
recvN = Handle -> Int -> RecvN -> RecvN
wrappedRecvN Handle
th (Settings -> Int
S.settingsSlowlorisSize Settings
settings) RecvN
rawRecvN
sendBS :: ByteString -> IO ()
sendBS ByteString
x = Connection -> ByteString -> IO ()
connSendAll Connection
conn ByteString
x 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
conf :: Config
conf =
Config
H2.defaultConfig
{ H2.confWriteBuffer = bufBuffer writeBuffer
, H2.confBufferSize = bufSize writeBuffer
, H2.confSendAll = sendBS
, H2.confReadN = recvN
, H2.confPositionReadMaker = pReadMaker ii
, H2.confTimeoutManager = timeoutManager ii
, H2.confMySockAddr = connMySockAddr conn
, H2.confPeerSockAddr = peersa
, H2.confReadNTimeout = True
}
Bool
ok <- IO Bool
checkTLS
Connection -> Bool -> IO ()
setConnHTTP2 Connection
conn Bool
True
Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
ok (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
IO () -> IO ()
endedNormally (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
ServerConfig -> Config -> Server -> IO ()
H2.run ServerConfig
H2.defaultServerConfig Config
conf (Server -> IO ()) -> Server -> IO ()
forall a b. (a -> b) -> a -> b
$
[Char]
-> Settings
-> InternalInfo
-> Transport
-> SockAddr
-> Application
-> Server
http2server [Char]
"Warp HTTP/2" Settings
settings InternalInfo
ii Transport
transport SockAddr
peersa Application
app
where
endedNormally :: IO () -> IO ()
endedNormally = (HTTP2Error -> IO ()) -> IO () -> IO ()
forall e a. Exception e => (e -> IO a) -> IO a -> IO a
E.handle ((HTTP2Error -> IO ()) -> IO () -> IO ())
-> (HTTP2Error -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ \HTTP2Error
e -> case HTTP2Error
e of
HTTP2Error
H2C.ConnectionIsClosed -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
HTTP2Error
_ -> HTTP2Error -> IO ()
forall e a. Exception e => e -> IO a
E.throwIO HTTP2Error
e
checkTLS :: IO Bool
checkTLS = case Transport
transport of
Transport
TCP -> Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
TLS{tlsMajorVersion :: Transport -> Int
tlsMajorVersion = Int
major, tlsMinorVersion :: Transport -> Int
tlsMinorVersion = Int
minor}
| Int
major Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
3 Bool -> Bool -> Bool
&& Int
minor Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
3 -> Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
| Bool
otherwise -> do
Connection -> ErrorCode -> ByteString -> IO ()
goaway Connection
conn ErrorCode
H2.InadequateSecurity ByteString
"Weak TLS"
Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
QUIC{} -> Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
http2server
:: String
-> S.Settings
-> InternalInfo
-> Transport
-> SockAddr
-> Application
-> H2.Server
http2server :: [Char]
-> Settings
-> InternalInfo
-> Transport
-> SockAddr
-> Application
-> Server
http2server [Char]
label Settings
settings InternalInfo
ii Transport
transport SockAddr
addr Application
app Request
h2req0 Aux
aux0 Response -> [PushPromise] -> IO ()
response = do
ThreadId
tid <- IO ThreadId
myThreadId
ThreadId -> [Char] -> IO ()
labelThread ThreadId
tid ([Char]
label [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" http2server " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ SockAddr -> [Char]
forall a. Show a => a -> [Char]
show SockAddr
addr)
Request
req0 <- Request -> Aux -> IO Request
toWAIRequest Request
h2req0 Aux
aux0
#if HAS_EARLY_HINTS_SUPPORT
let req :: Request
req = Request
req0{requestSendEarlyHints = H2.auxSendInformational aux0 (H.mkStatus 103 "Early Hints")}
#else
let req = req0
#endif
IORef (Maybe (Response, [PushPromise], Status))
ref <- Maybe (Response, [PushPromise], Status)
-> IO (IORef (Maybe (Response, [PushPromise], Status)))
forall a. a -> IO (IORef a)
I.newIORef Maybe (Response, [PushPromise], Status)
forall a. Maybe a
Nothing
Either SomeException ResponseReceived
eResponseReceived <- IO ResponseReceived -> IO (Either SomeException ResponseReceived)
forall e a. Exception e => IO a -> IO (Either e a)
E.try (IO ResponseReceived -> IO (Either SomeException ResponseReceived))
-> IO ResponseReceived
-> IO (Either SomeException ResponseReceived)
forall a b. (a -> b) -> a -> b
$ Application
app Request
req ((Response -> IO ResponseReceived) -> IO ResponseReceived)
-> (Response -> IO ResponseReceived) -> IO ResponseReceived
forall a b. (a -> b) -> a -> b
$ \Response
rsp -> do
(Response
h2rsp, Status
st, Bool
hasBody) <- Settings
-> InternalInfo
-> Request
-> Response
-> IO (Response, Status, Bool)
fromResponse Settings
settings InternalInfo
ii Request
req Response
rsp
[PushPromise]
pps <- if Bool
hasBody then InternalInfo -> Request -> IO [PushPromise]
fromPushPromises InternalInfo
ii Request
req else [PushPromise] -> IO [PushPromise]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return []
IORef (Maybe (Response, [PushPromise], Status))
-> Maybe (Response, [PushPromise], Status) -> IO ()
forall a. IORef a -> a -> IO ()
I.writeIORef IORef (Maybe (Response, [PushPromise], Status))
ref (Maybe (Response, [PushPromise], Status) -> IO ())
-> Maybe (Response, [PushPromise], Status) -> IO ()
forall a b. (a -> b) -> a -> b
$ (Response, [PushPromise], Status)
-> Maybe (Response, [PushPromise], Status)
forall a. a -> Maybe a
Just (Response
h2rsp, [PushPromise]
pps, Status
st)
()
_ <- Response -> [PushPromise] -> IO ()
response Response
h2rsp [PushPromise]
pps
ResponseReceived -> IO ResponseReceived
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ResponseReceived
ResponseReceived
Maybe (Response, [PushPromise], Status)
msent <- IORef (Maybe (Response, [PushPromise], Status))
-> IO (Maybe (Response, [PushPromise], Status))
forall a. IORef a -> IO a
I.readIORef IORef (Maybe (Response, [PushPromise], Status))
ref
let logSent :: (Response, t PushPromise, Status) -> IO ()
logSent (Response
h2rsp, t PushPromise
pps, Status
st) = do
let msiz :: Maybe Integer
msiz = Int -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Integer) -> Maybe Int -> Maybe Integer
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Response -> Maybe Int
H2.responseBodySize Response
h2rsp
Request -> Status -> Maybe Integer -> IO ()
logResponse Request
req Status
st Maybe Integer
msiz
(PushPromise -> IO ()) -> t PushPromise -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Request -> PushPromise -> IO ()
logPushPromise Request
req) t PushPromise
pps
case Either SomeException ResponseReceived
eResponseReceived of
Right ResponseReceived
ResponseReceived -> case Maybe (Response, [PushPromise], Status)
msent of
Just (Response, [PushPromise], Status)
sent -> (Response, [PushPromise], Status) -> IO ()
forall {t :: * -> *}.
Foldable t =>
(Response, t PushPromise, Status) -> IO ()
logSent (Response, [PushPromise], Status)
sent
Maybe (Response, [PushPromise], Status)
Nothing -> IOError -> IO ()
forall e a. Exception e => e -> IO a
E.throwIO (IOError -> IO ()) -> IOError -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char] -> IOError
userError [Char]
"no response from the application"
Left SomeException
e
| SomeException -> Bool
forall e. Exception e => e -> Bool
isAsyncException SomeException
e -> SomeException -> IO ()
forall e a. Exception e => e -> IO a
E.throwIO SomeException
e
| Bool
otherwise -> do
Settings -> Maybe Request -> SomeException -> IO ()
S.settingsOnException Settings
settings (Request -> Maybe Request
forall a. a -> Maybe a
Just Request
req) SomeException
e
case Maybe (Response, [PushPromise], Status)
msent of
Just (Response, [PushPromise], Status)
sent -> (Response, [PushPromise], Status) -> IO ()
forall {t :: * -> *}.
Foldable t =>
(Response, t PushPromise, Status) -> IO ()
logSent (Response, [PushPromise], Status)
sent
Maybe (Response, [PushPromise], Status)
Nothing -> do
let ersp :: Response
ersp = Settings -> SomeException -> Response
S.settingsOnExceptionResponse Settings
settings SomeException
e
(Response
h2rsp, Status
_, Bool
_) <- Settings
-> InternalInfo
-> Request
-> Response
-> IO (Response, Status, Bool)
fromResponse Settings
settings InternalInfo
ii Request
req Response
ersp
()
_ <- Response -> [PushPromise] -> IO ()
response Response
h2rsp []
(Response, [PushPromise], Status) -> IO ()
forall {t :: * -> *}.
Foldable t =>
(Response, t PushPromise, Status) -> IO ()
logSent (Response
h2rsp, [], Response -> Status
responseStatus Response
ersp)
() -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
where
toWAIRequest :: Request -> Aux -> IO Request
toWAIRequest Request
h2req Aux
aux = InternalInfo -> Settings -> SockAddr -> ToReq
toRequest InternalInfo
ii Settings
settings SockAddr
addr TokenHeaderTable
hdr Maybe Int
bdylen Recv
bdy Handle
th Transport
transport
where
!hdr :: TokenHeaderTable
hdr = Request -> TokenHeaderTable
H2.requestHeaders Request
h2req
!bdy :: Recv
bdy = Request -> Recv
H2.getRequestBodyChunk Request
h2req
!bdylen :: Maybe Int
bdylen = Request -> Maybe Int
H2.requestBodySize Request
h2req
!th :: Handle
th = Aux -> Handle
H2.auxTimeHandle Aux
aux
logResponse :: Request -> Status -> Maybe Integer -> IO ()
logResponse = Settings -> Request -> Status -> Maybe Integer -> IO ()
S.settingsLogger Settings
settings
logPushPromise :: Request -> PushPromise -> IO ()
logPushPromise Request
req PushPromise
pp = Request -> ByteString -> Integer -> IO ()
logger Request
req ByteString
path Integer
siz
where
!logger :: Request -> ByteString -> Integer -> IO ()
logger = Settings -> Request -> ByteString -> Integer -> IO ()
S.settingsServerPushLogger Settings
settings
!path :: ByteString
path = PushPromise -> ByteString
H2.promiseRequestPath PushPromise
pp
!siz :: Integer
siz = case Response -> Maybe Int
H2.responseBodySize (Response -> Maybe Int) -> Response -> Maybe Int
forall a b. (a -> b) -> a -> b
$ PushPromise -> Response
H2.promiseResponse PushPromise
pp of
Maybe Int
Nothing -> Integer
0
Just Int
s -> Int -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
s
wrappedRecvN
:: T.Handle -> Int -> (BufSize -> IO ByteString) -> (BufSize -> IO ByteString)
wrappedRecvN :: Handle -> Int -> RecvN -> RecvN
wrappedRecvN Handle
th Int
slowlorisSize RecvN
readN Int
bufsize = do
ByteString
bs <- (SomeException -> Recv) -> Recv -> Recv
forall e a. Exception e => (e -> IO a) -> IO a -> IO a
E.handle SomeException -> Recv
handler (Recv -> Recv) -> Recv -> Recv
forall a b. (a -> b) -> a -> b
$ RecvN
readN Int
bufsize
Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when
(ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 Bool -> Bool -> Bool
&& ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
slowlorisSize Bool -> Bool -> Bool
|| Int
bufsize Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
slowlorisSize)
(IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ Handle -> IO ()
T.tickle Handle
th
ByteString -> Recv
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ByteString
bs
where
handler :: E.SomeException -> IO ByteString
handler :: SomeException -> Recv
handler = Recv -> SomeException -> Recv
forall a. IO a -> SomeException -> IO a
throughAsync (ByteString -> Recv
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ByteString
"")
goaway :: Connection -> H2.ErrorCode -> ByteString -> IO ()
goaway :: Connection -> ErrorCode -> ByteString -> IO ()
goaway Connection{IO ()
Recv
TVar Int
IORef Bool
IORef WriteBuffer
SockAddr
[ByteString] -> IO ()
RecvBuf
ByteString -> IO ()
SendFile
connRecv :: Connection -> Recv
connWriteBuffer :: Connection -> IORef WriteBuffer
connSendAll :: Connection -> ByteString -> IO ()
connMySockAddr :: Connection -> SockAddr
connSendMany :: [ByteString] -> IO ()
connSendAll :: ByteString -> IO ()
connSendFile :: SendFile
connClose :: IO ()
connRecv :: Recv
connRecvBuf :: RecvBuf
connWriteBuffer :: IORef WriteBuffer
connHTTP2 :: IORef Bool
connMySockAddr :: SockAddr
connAppsInProgress :: TVar Int
connAppsInProgress :: Connection -> TVar Int
connHTTP2 :: Connection -> IORef Bool
connRecvBuf :: Connection -> RecvBuf
connClose :: Connection -> IO ()
connSendFile :: Connection -> SendFile
connSendMany :: Connection -> [ByteString] -> IO ()
..} ErrorCode
etype ByteString
debugmsg = ByteString -> IO ()
connSendAll (ByteString -> IO ()) -> ByteString -> IO ()
forall a b. (a -> b) -> a -> b
$ ByteString
preface ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
bytestream
where
einfo :: EncodeInfo
einfo = (FrameFlags -> FrameFlags) -> Int -> EncodeInfo
H2.encodeInfo FrameFlags -> FrameFlags
forall a. a -> a
id Int
0
preface :: ByteString
preface = EncodeInfo -> FramePayload -> ByteString
H2.encodeFrame EncodeInfo
einfo (FramePayload -> ByteString) -> FramePayload -> ByteString
forall a b. (a -> b) -> a -> b
$ SettingsList -> FramePayload
H2.SettingsFrame []
frame :: FramePayload
frame = Int -> ErrorCode -> ByteString -> FramePayload
H2.GoAwayFrame Int
0 ErrorCode
etype ByteString
debugmsg
bytestream :: ByteString
bytestream = EncodeInfo -> FramePayload -> ByteString
H2.encodeFrame EncodeInfo
einfo FramePayload
frame