{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

module Network.HTTP2.Server.Run where

import Control.Concurrent.Async
import Control.Concurrent.STM
import Imports
import Network.Control (defaultMaxData)
import Network.HTTP.Semantics.IO
import Network.HTTP.Semantics.Server
import Network.HTTP.Semantics.Server.Internal
import Network.Socket (SockAddr)

import Network.HTTP2.Frame
import Network.HTTP2.H2
import Network.HTTP2.Server.Worker

-- | Server configuration
data ServerConfig = ServerConfig
    { ServerConfig -> Int
numberOfWorkers :: Int
    -- ^ Deprecated field.
    , ServerConfig -> Int
connectionWindowSize :: WindowSize
    -- ^ The window size of incoming streams
    , ServerConfig -> Settings
settings :: Settings
    -- ^ Settings
    }
    deriving (ServerConfig -> ServerConfig -> Bool
(ServerConfig -> ServerConfig -> Bool)
-> (ServerConfig -> ServerConfig -> Bool) -> Eq ServerConfig
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ServerConfig -> ServerConfig -> Bool
== :: ServerConfig -> ServerConfig -> Bool
$c/= :: ServerConfig -> ServerConfig -> Bool
/= :: ServerConfig -> ServerConfig -> Bool
Eq, Int -> ServerConfig -> ShowS
[ServerConfig] -> ShowS
ServerConfig -> String
(Int -> ServerConfig -> ShowS)
-> (ServerConfig -> String)
-> ([ServerConfig] -> ShowS)
-> Show ServerConfig
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ServerConfig -> ShowS
showsPrec :: Int -> ServerConfig -> ShowS
$cshow :: ServerConfig -> String
show :: ServerConfig -> String
$cshowList :: [ServerConfig] -> ShowS
showList :: [ServerConfig] -> ShowS
Show)

{-# DEPRECATED numberOfWorkers "No effect anymore" #-}

-- | The default server config.
--
-- >>> defaultServerConfig
-- ServerConfig {numberOfWorkers = 8, connectionWindowSize = 16777216, settings = Settings {headerTableSize = 4096, enablePush = True, maxConcurrentStreams = Just 64, initialWindowSize = 262144, maxFrameSize = 16384, maxHeaderListSize = Just 65536, pingRateLimit = 10, emptyFrameRateLimit = 4, settingsRateLimit = 4, rstRateLimit = 4}}
defaultServerConfig :: ServerConfig
defaultServerConfig :: ServerConfig
defaultServerConfig =
    ServerConfig
        { numberOfWorkers :: Int
numberOfWorkers = Int
8
        , connectionWindowSize :: Int
connectionWindowSize = Int
defaultMaxData
        , settings :: Settings
settings = Settings
defaultSettings
        }

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

-- | Running HTTP/2 server.
run :: ServerConfig -> Config -> Server -> IO ()
run :: ServerConfig -> Config -> Server -> IO ()
run = Maybe (STM ()) -> ServerConfig -> Config -> Server -> IO ()
runMaybe Maybe (STM ())
forall a. Maybe a
Nothing

-- | Like 'run', but the connection goes away once the 'STM' action fires:
--   GOAWAY(NO_ERROR) at once, streams above it refused, and the
--   connection closed when those below it are done.
--
--   @since 5.4.13
runWith :: STM () -> ServerConfig -> Config -> Server -> IO ()
runWith :: STM () -> ServerConfig -> Config -> Server -> IO ()
runWith = Maybe (STM ()) -> ServerConfig -> Config -> Server -> IO ()
runMaybe (Maybe (STM ()) -> ServerConfig -> Config -> Server -> IO ())
-> (STM () -> Maybe (STM ()))
-> STM ()
-> ServerConfig
-> Config
-> Server
-> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. STM () -> Maybe (STM ())
forall a. a -> Maybe a
Just

-- Nothing for 'run': no thread waits on an action which never fires.
runMaybe :: Maybe (STM ()) -> ServerConfig -> Config -> Server -> IO ()
runMaybe :: Maybe (STM ()) -> ServerConfig -> Config -> Server -> IO ()
runMaybe Maybe (STM ())
mGoAway ServerConfig
sconf Config
conf Server
server = do
    ok <- Config -> IO Bool
checkPreface Config
conf
    when ok $ do
        let lnch = Config -> Server -> Launch
runServer Config
conf Server
server
        ctx <- setup sconf conf lnch Nothing
        runH2 conf ctx mGoAway

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

data ServerIO a = ServerIO
    { forall a. ServerIO a -> SockAddr
sioMySockAddr :: SockAddr
    , forall a. ServerIO a -> SockAddr
sioPeerSockAddr :: SockAddr
    , forall a. ServerIO a -> IO (a, Request)
sioReadRequest :: IO (a, Request)
    , forall a. ServerIO a -> a -> Response -> IO ()
sioWriteResponse :: a -> Response -> IO ()
    -- ^ 'Response' MUST be created with 'responseBuilder'.
    -- Others are not supported.
    , forall a. ServerIO a -> IO ()
sioDone :: IO ()
    }

-- | Launching a receiver and a sender without workers.
-- Any frames can be sent with `sioWriteBytes`.
runIO
    :: ServerConfig
    -> Config
    -> (ServerIO Stream -> IO (IO ()))
    -> IO ()
runIO :: ServerConfig -> Config -> (ServerIO Stream -> IO (IO ())) -> IO ()
runIO = Maybe (STM ())
-> ServerConfig
-> Config
-> (ServerIO Stream -> IO (IO ()))
-> IO ()
runIOMaybe Maybe (STM ())
forall a. Maybe a
Nothing

-- | Like 'runIO', but the connection goes away once the 'STM' action
--   fires, as with 'runWith'.
--
--   @since 5.4.13
runIOWith
    :: STM ()
    -> ServerConfig
    -> Config
    -> (ServerIO Stream -> IO (IO ()))
    -> IO ()
runIOWith :: STM ()
-> ServerConfig
-> Config
-> (ServerIO Stream -> IO (IO ()))
-> IO ()
runIOWith = Maybe (STM ())
-> ServerConfig
-> Config
-> (ServerIO Stream -> IO (IO ()))
-> IO ()
runIOMaybe (Maybe (STM ())
 -> ServerConfig
 -> Config
 -> (ServerIO Stream -> IO (IO ()))
 -> IO ())
-> (STM () -> Maybe (STM ()))
-> STM ()
-> ServerConfig
-> Config
-> (ServerIO Stream -> IO (IO ()))
-> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. STM () -> Maybe (STM ())
forall a. a -> Maybe a
Just

runIOMaybe
    :: Maybe (STM ())
    -> ServerConfig
    -> Config
    -> (ServerIO Stream -> IO (IO ()))
    -> IO ()
runIOMaybe :: Maybe (STM ())
-> ServerConfig
-> Config
-> (ServerIO Stream -> IO (IO ()))
-> IO ()
runIOMaybe Maybe (STM ())
mGoAway ServerConfig
sconf conf :: Config
conf@Config{Bool
Int
Maybe (STM () -> Int -> IO ByteString)
Maybe (STM () -> ByteString -> IO (Either () ()))
Buffer
Manager
SockAddr
Int -> IO ByteString
Int -> TokenHeaderTable -> IO ()
PositionReadMaker
ByteString -> IO ()
confWriteBuffer :: Buffer
confBufferSize :: Int
confSendAll :: ByteString -> IO ()
confSendAllWith :: Maybe (STM () -> ByteString -> IO (Either () ()))
confReadN :: Int -> IO ByteString
confReadNWith :: Maybe (STM () -> Int -> IO ByteString)
confPositionReadMaker :: PositionReadMaker
confTimeoutManager :: Manager
confMySockAddr :: SockAddr
confPeerSockAddr :: SockAddr
confReadNTimeout :: Bool
confOnInformational :: Int -> TokenHeaderTable -> IO ()
confBufferSize :: Config -> Int
confMySockAddr :: Config -> SockAddr
confOnInformational :: Config -> Int -> TokenHeaderTable -> IO ()
confPeerSockAddr :: Config -> SockAddr
confPositionReadMaker :: Config -> PositionReadMaker
confReadN :: Config -> Int -> IO ByteString
confReadNTimeout :: Config -> Bool
confReadNWith :: Config -> Maybe (STM () -> Int -> IO ByteString)
confSendAll :: Config -> ByteString -> IO ()
confSendAllWith :: Config -> Maybe (STM () -> ByteString -> IO (Either () ()))
confTimeoutManager :: Config -> Manager
confWriteBuffer :: Config -> Buffer
..} ServerIO Stream -> IO (IO ())
action = do
    ok <- Config -> IO Bool
checkPreface Config
conf
    when ok $ do
        inpQ <- newTQueueIO
        let lnch p
_ Stream
strm InpObj
inpObj = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TQueue (Stream, InpObj) -> (Stream, InpObj) -> STM ()
forall a. TQueue a -> a -> STM ()
writeTQueue TQueue (Stream, InpObj)
inpQ (Stream
strm, InpObj
inpObj)
        done <- newTVarIO False
        ctx <- setup sconf conf lnch $ Just $ readTVar done
        let get = do
                (strm, inpObj) <- STM (Stream, InpObj) -> IO (Stream, InpObj)
forall a. STM a -> IO a
atomically (STM (Stream, InpObj) -> IO (Stream, InpObj))
-> STM (Stream, InpObj) -> IO (Stream, InpObj)
forall a b. (a -> b) -> a -> b
$ TQueue (Stream, InpObj) -> STM (Stream, InpObj)
forall a. TQueue a -> STM a
readTQueue TQueue (Stream, InpObj)
inpQ
                return (strm, Request inpObj)
            putR Stream
strm (Response OutObj{[Header]
OutBody
TrailersMaker
outObjHeaders :: [Header]
outObjBody :: OutBody
outObjTrailers :: TrailersMaker
outObjBody :: OutObj -> OutBody
outObjHeaders :: OutObj -> [Header]
outObjTrailers :: OutObj -> TrailersMaker
..}) = do
                case OutBody
outObjBody of
                    OutBodyBuilder Builder
builder -> do
                        let next :: DynaNext
next = Builder -> DynaNext
fillBuilderBodyGetNext Builder
builder
                            otyp :: OutputType
otyp = [Header] -> Maybe DynaNext -> TrailersMaker -> OutputType
OHeader [Header]
outObjHeaders (DynaNext -> Maybe DynaNext
forall a. a -> Maybe a
Just DynaNext
next) TrailersMaker
outObjTrailers
                        Context -> Stream -> OutputType -> IO ()
enqueueOutputSIO Context
ctx Stream
strm OutputType
otyp
                    OutBody
_ -> String -> IO ()
forall a. HasCallStack => String -> a
error String
"Response other than OutBodyBuilder is not supported"
            serverIO =
                ServerIO
                    { sioMySockAddr :: SockAddr
sioMySockAddr = SockAddr
confMySockAddr
                    , sioPeerSockAddr :: SockAddr
sioPeerSockAddr = SockAddr
confPeerSockAddr
                    , sioReadRequest :: IO (Stream, Request)
sioReadRequest = IO (Stream, Request)
get
                    , sioWriteResponse :: Stream -> Response -> IO ()
sioWriteResponse = Stream -> Response -> IO ()
putR
                    , sioDone :: IO ()
sioDone = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TVar Bool -> Bool -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar TVar Bool
done Bool
True
                    }
        io <- action serverIO
        concurrently_ io $ runH2 conf ctx mGoAway

checkPreface :: Config -> IO Bool
checkPreface :: Config -> IO Bool
checkPreface conf :: Config
conf@Config{Bool
Int
Maybe (STM () -> Int -> IO ByteString)
Maybe (STM () -> ByteString -> IO (Either () ()))
Buffer
Manager
SockAddr
Int -> IO ByteString
Int -> TokenHeaderTable -> IO ()
PositionReadMaker
ByteString -> IO ()
confBufferSize :: Config -> Int
confMySockAddr :: Config -> SockAddr
confOnInformational :: Config -> Int -> TokenHeaderTable -> IO ()
confPeerSockAddr :: Config -> SockAddr
confPositionReadMaker :: Config -> PositionReadMaker
confReadN :: Config -> Int -> IO ByteString
confReadNTimeout :: Config -> Bool
confReadNWith :: Config -> Maybe (STM () -> Int -> IO ByteString)
confSendAll :: Config -> ByteString -> IO ()
confSendAllWith :: Config -> Maybe (STM () -> ByteString -> IO (Either () ()))
confTimeoutManager :: Config -> Manager
confWriteBuffer :: Config -> Buffer
confWriteBuffer :: Buffer
confBufferSize :: Int
confSendAll :: ByteString -> IO ()
confSendAllWith :: Maybe (STM () -> ByteString -> IO (Either () ()))
confReadN :: Int -> IO ByteString
confReadNWith :: Maybe (STM () -> Int -> IO ByteString)
confPositionReadMaker :: PositionReadMaker
confTimeoutManager :: Manager
confMySockAddr :: SockAddr
confPeerSockAddr :: SockAddr
confReadNTimeout :: Bool
confOnInformational :: Int -> TokenHeaderTable -> IO ()
..} = do
    preface <- Int -> IO ByteString
confReadN Int
connectionPrefaceLength
    if connectionPreface /= preface
        then do
            goaway conf ProtocolError "Preface mismatch"
            return False
        else return True

setup :: ServerConfig -> Config -> Launch -> Maybe (STM Bool) -> IO Context
setup :: ServerConfig -> Config -> Launch -> Maybe (STM Bool) -> IO Context
setup ServerConfig{Int
Settings
numberOfWorkers :: ServerConfig -> Int
connectionWindowSize :: ServerConfig -> Int
settings :: ServerConfig -> Settings
numberOfWorkers :: Int
connectionWindowSize :: Int
settings :: Settings
..} conf :: Config
conf@Config{Bool
Int
Maybe (STM () -> Int -> IO ByteString)
Maybe (STM () -> ByteString -> IO (Either () ()))
Buffer
Manager
SockAddr
Int -> IO ByteString
Int -> TokenHeaderTable -> IO ()
PositionReadMaker
ByteString -> IO ()
confBufferSize :: Config -> Int
confMySockAddr :: Config -> SockAddr
confOnInformational :: Config -> Int -> TokenHeaderTable -> IO ()
confPeerSockAddr :: Config -> SockAddr
confPositionReadMaker :: Config -> PositionReadMaker
confReadN :: Config -> Int -> IO ByteString
confReadNTimeout :: Config -> Bool
confReadNWith :: Config -> Maybe (STM () -> Int -> IO ByteString)
confSendAll :: Config -> ByteString -> IO ()
confSendAllWith :: Config -> Maybe (STM () -> ByteString -> IO (Either () ()))
confTimeoutManager :: Config -> Manager
confWriteBuffer :: Config -> Buffer
confWriteBuffer :: Buffer
confBufferSize :: Int
confSendAll :: ByteString -> IO ()
confSendAllWith :: Maybe (STM () -> ByteString -> IO (Either () ()))
confReadN :: Int -> IO ByteString
confReadNWith :: Maybe (STM () -> Int -> IO ByteString)
confPositionReadMaker :: PositionReadMaker
confTimeoutManager :: Manager
confMySockAddr :: SockAddr
confPeerSockAddr :: SockAddr
confReadNTimeout :: Bool
confOnInformational :: Int -> TokenHeaderTable -> IO ()
..} Launch
lnch Maybe (STM Bool)
mIsDone = do
    let serverInfo :: RoleInfo
serverInfo = Launch -> RoleInfo
newServerInfo Launch
lnch
    RoleInfo
-> Config
-> Int
-> Int
-> Settings
-> Manager
-> Maybe (STM Bool)
-> IO Context
newContext
        RoleInfo
serverInfo
        Config
conf
        Int
0
        Int
connectionWindowSize
        Settings
settings
        Manager
confTimeoutManager
        Maybe (STM Bool)
mIsDone

runH2 :: Config -> Context -> Maybe (STM ()) -> IO ()
runH2 :: Config -> Context -> Maybe (STM ()) -> IO ()
runH2 Config
conf Context
ctx Maybe (STM ())
mGoAway = do
    let mgr :: ThreadManager
mgr = Context -> ThreadManager
threadManager Context
ctx
        runReceiver :: IO SomeException
runReceiver = Context -> Config -> IO SomeException
frameReceiver Context
ctx Config
conf
        runSender :: IO SomeException
runSender = Context -> Config -> IO SomeException
frameSender Context
ctx Config
conf
        -- Two GOAWAYs, as RFC 9113 section 6.8 has it: the first, with
        -- the largest identifier, stops the client opening streams; the
        -- second fixes the last one taken once a PING has gone round, so
        -- that the streams it opened meanwhile are not refused.  The
        -- receiver is stopped as it is after the peer's GOAWAY, once the
        -- streams below ours are done; it reads until then.
        sendGoAway :: STM () -> Async a -> IO ()
        sendGoAway :: forall a. STM () -> Async a -> IO ()
sendGoAway STM ()
goAway Async a
ar = do
            STM () -> IO ()
forall a. STM a -> IO a
atomically STM ()
goAway
            ControlQ -> Control -> IO ()
enqueueControl (Context -> ControlQ
controlQ Context
ctx) (Control -> IO ()) -> Control -> IO ()
forall a b. (a -> b) -> a -> b
$
                Maybe SettingsList -> [ByteString] -> Control
CFrames
                    Maybe SettingsList
forall a. Maybe a
Nothing
                    [ Int -> ErrorCode -> ByteString -> ByteString
goawayFrame Int
maxStreamId ErrorCode
NoError ByteString
"going away"
                    , Bool -> ByteString -> ByteString
pingFrame Bool
False ByteString
goAwayPing
                    ]
            roundTrip <- Int -> IO (TVar Bool)
registerDelay Int
1000000
            atomically $
                (readTVar (pingAcked ctx) >>= check . (== goAwayPing))
                    `orElse` (readTVar roundTrip >>= check)
            mlast <- atomically $ goingAwayMine ctx
            forM_ mlast $ \Int
lastSid ->
                ControlQ -> Control -> IO ()
enqueueControl (Context -> ControlQ
controlQ Context
ctx) (Control -> IO ()) -> Control -> IO ()
forall a b. (a -> b) -> a -> b
$
                    Maybe SettingsList -> [ByteString] -> Control
CFrames Maybe SettingsList
forall a. Maybe a
Nothing [Int -> ErrorCode -> ByteString -> ByteString
goawayFrame Int
lastSid ErrorCode
NoError ByteString
"going away"]
            atomically $ drainedMine ctx
            stopReceiver ctx $ asyncThreadId ar
        withGoAway :: Async a -> IO b -> IO b
withGoAway Async a
ar IO b
body = case Maybe (STM ())
mGoAway of
            Maybe (STM ())
Nothing -> IO b
body
            Just STM ()
goAway -> IO () -> (Async () -> IO b) -> IO b
forall a b. IO a -> (Async a -> IO b) -> IO b
withAsync (STM () -> Async a -> IO ()
forall a. STM () -> Async a -> IO ()
sendGoAway STM ()
goAway Async a
ar) ((Async () -> IO b) -> IO b) -> (Async () -> IO b) -> IO b
forall a b. (a -> b) -> a -> b
$ \Async ()
_ -> IO b
body
        runBackgroundThreads :: IO b
runBackgroundThreads =
            IO SomeException -> (Async SomeException -> IO b) -> IO b
forall a b. IO a -> (Async a -> IO b) -> IO b
withAsync IO SomeException
runReceiver ((Async SomeException -> IO b) -> IO b)
-> (Async SomeException -> IO b) -> IO b
forall a b. (a -> b) -> a -> b
$ \Async SomeException
ar ->
                Async SomeException -> IO b -> IO b
forall {a} {b}. Async a -> IO b -> IO b
withGoAway Async SomeException
ar (IO b -> IO b) -> IO b -> IO b
forall a b. (a -> b) -> a -> b
$
                    IO SomeException -> (Async SomeException -> IO b) -> IO b
forall a b. IO a -> (Async a -> IO b) -> IO b
withAsync IO SomeException
runSender ((Async SomeException -> IO b) -> IO b)
-> (Async SomeException -> IO b) -> IO b
forall a b. (a -> b) -> a -> b
$ \Async SomeException
as -> do
                        r <- Async SomeException
-> Async SomeException -> IO (Either SomeException SomeException)
forall a b. Async a -> Async b -> IO (Either a b)
waitEither Async SomeException
ar Async SomeException
as
                        e <- case r of
                            -- The receiver is done; the sender finishes once it
                            -- has flushed what is queued.
                            Left SomeException
_ -> Async SomeException -> IO SomeException
forall a. Async a -> IO a
wait Async SomeException
as
                            -- The sender finished first.  Either the receiver is
                            -- done too and not yet seen to be, and this is its
                            -- error, or the sender failed: nothing more would go
                            -- out, and leaving the receiver to run on left the
                            -- connection open and silent, with no GOAWAY.  Both
                            -- are closed with it: the receiver is stopped
                            -- rather than cancelled when its reads can give up.
                            Right SomeException
e -> do
                                Context -> ThreadId -> IO ()
stopReceiver Context
ctx (ThreadId -> IO ()) -> ThreadId -> IO ()
forall a b. (a -> b) -> a -> b
$ Async SomeException -> ThreadId
forall a. Async a -> ThreadId
asyncThreadId Async SomeException
ar
                                late <- Int -> IO (TVar Bool)
registerDelay Int
1000000
                                atomically $
                                    void (waitCatchSTM ar) `orElse` (readTVar late >>= check)
                                return e
                        closureServer conf ctx e
    ThreadManager -> IO () -> (Maybe SomeException -> IO ()) -> IO ()
forall a.
ThreadManager -> IO a -> (Maybe SomeException -> IO ()) -> IO a
stopAfterAndWait ThreadManager
mgr IO ()
forall {b}. IO b
runBackgroundThreads ((Maybe SomeException -> IO ()) -> IO ())
-> (Maybe SomeException -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Maybe SomeException
res ->
        TVar OddStreamTable
-> TVar EvenStreamTable -> Maybe SomeException -> IO ()
closeAllStreams (Context -> TVar OddStreamTable
oddStreamTable Context
ctx) (Context -> TVar EvenStreamTable
evenStreamTable Context
ctx) Maybe SomeException
res

-- | The payload of the PING sent with the first GOAWAY.
goAwayPing :: ByteString
goAwayPing :: ByteString
goAwayPing = ByteString
"goaway\0\0"

-- | The largest stream identifier.
maxStreamId :: StreamId
maxStreamId :: Int
maxStreamId = Int
2147483647

-- connClose must not be called here since Run:fork calls it
goaway :: Config -> ErrorCode -> ByteString -> IO ()
goaway :: Config -> ErrorCode -> ByteString -> IO ()
goaway Config
conf ErrorCode
etype ByteString
debugmsg = Config -> ByteString -> IO ()
sendGoaway Config
conf ByteString
bytestream
  where
    bytestream :: ByteString
bytestream = Int -> ErrorCode -> ByteString -> ByteString
goawayFrame Int
0 ErrorCode
etype ByteString
debugmsg