{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}

module Network.HTTP2.H2.Types where

import Control.Concurrent
import Control.Concurrent.STM
import qualified Control.Exception as E
import qualified System.TimeManager as TM
import Data.IORef
import Foreign.Ptr (nullPtr)
import Network.Control
import Network.HTTP.Semantics.Client
import Network.HTTP.Semantics.IO
import Network.Socket hiding (Stream)
import System.IO.Error (catchIOError)
import System.IO.Unsafe
import qualified System.TimeManager as T

import Imports
import Network.HPACK
import Network.HTTP2.Frame

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

{-

== Stream state

The stream state is stored in the 'streamState' field (an @IORef@) of a
'Stream'. The main place where the stream state is updated is in
'controlOrStream', which does something like this:

> state0 <- readStreamState strm
> state1 <- stream .. state0 ..
> processState .. state1 ..

where 'processState' updates the @IORef@, based on 'state1' (the state computed
by 'stream') and the /current/ state of the stream; for simplicity, we will
assume here that this must equal 'state0' (it might not, if a concurrent thread
changed the stream state).

The diagram below summarizes the stream state transitions on the client side,
omitting error cases (which result in exceptions being thrown). Each transition
is labelled with the relevant case in either the function 'stream' or the
function 'processState'.

>               [Open JustOpened]
>                      |
>                      |
>              HEADERS CONTINUATION*
>                      |
>                      | (stream1)
>                      |
>                 END_STREAM?
>                      |
>            _________/ \_________
>           /      yes   no       \
>           |                     |
>      [Open NoBody]        [Open HasBody]
>           |                     |
>           | (process1)          | (process2)
>           |                     |
>  [HalfClosedRemote] <--\   [Open Body] <----------------------\
>           |             |        |                             |
>           |             |        +---------------\             |
>       RST_STREAM        |        |               |             |
>           |             |     HEADERS CONT*     DATA           |
>           | (stream6)   |        |               |             |
>           |             |        | (stream2)     | (stream4)   |
>           | (process5)  |        |               |             |
>           |             |   END_STREAM?      END_STREAM?       |
>        [Closed]         |        |               |             |
>                         |        | yes      yes / \ no         |
>                         \--------+-------------/   \-----------/
>                          (process4)                 (process6)

Notes:

- The 'HalfClosedLocal' state is not used on the client side.
- Indeed, unless an exception is thrown, even the 'Closed' stream state is not
  used in the client; when the @IORef@ is collected, it is typically in
  'HalfClosedRemote' state.

-}

data OpenState
    = JustOpened
    | NoBody TokenHeaderTable
    | HasBody TokenHeaderTable
    | Body
        (TQueue (Either E.SomeException (ByteString, Bool)))
        (Maybe Int) -- received Content-Length
        -- compared the body length for error checking
        (IORef Int) -- actual body length
        (IORef (Maybe TokenHeaderTable)) -- trailers

-- | Header block fragments accumulated so far.
--
-- Fragments are stored in reverse order (newest first).
data PartialHeaderBlock = PartialHeaderBlock
    { PartialHeaderBlock -> [ByteString]
phbFragments :: [HeaderBlockFragment]
    , PartialHeaderBlock -> Int
phbTotalSize :: Int
    , PartialHeaderBlock -> Int
phbNumFrames :: Int
    }

data ClosedCode
    = Finished
    | Killed
    | Reset ErrorCode
    | ResetByMe E.SomeException
    deriving (Int -> ClosedCode -> ShowS
[ClosedCode] -> ShowS
ClosedCode -> String
(Int -> ClosedCode -> ShowS)
-> (ClosedCode -> String)
-> ([ClosedCode] -> ShowS)
-> Show ClosedCode
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ClosedCode -> ShowS
showsPrec :: Int -> ClosedCode -> ShowS
$cshow :: ClosedCode -> String
show :: ClosedCode -> String
$cshowList :: [ClosedCode] -> ShowS
showList :: [ClosedCode] -> ShowS
Show)

-- | Used for streams which are cancelled by calling
-- 'Network.HTTP.Semantics.outBodyCancel'.
data CancelledStream = CancelledStream
    deriving (Int -> CancelledStream -> ShowS
[CancelledStream] -> ShowS
CancelledStream -> String
(Int -> CancelledStream -> ShowS)
-> (CancelledStream -> String)
-> ([CancelledStream] -> ShowS)
-> Show CancelledStream
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CancelledStream -> ShowS
showsPrec :: Int -> CancelledStream -> ShowS
$cshow :: CancelledStream -> String
show :: CancelledStream -> String
$cshowList :: [CancelledStream] -> ShowS
showList :: [CancelledStream] -> ShowS
Show, Show CancelledStream
Typeable CancelledStream
(Typeable CancelledStream, Show CancelledStream) =>
(CancelledStream -> SomeException)
-> (SomeException -> Maybe CancelledStream)
-> (CancelledStream -> String)
-> (CancelledStream -> Bool)
-> Exception CancelledStream
SomeException -> Maybe CancelledStream
CancelledStream -> Bool
CancelledStream -> String
CancelledStream -> SomeException
forall e.
(Typeable e, Show e) =>
(e -> SomeException)
-> (SomeException -> Maybe e)
-> (e -> String)
-> (e -> Bool)
-> Exception e
$ctoException :: CancelledStream -> SomeException
toException :: CancelledStream -> SomeException
$cfromException :: SomeException -> Maybe CancelledStream
fromException :: SomeException -> Maybe CancelledStream
$cdisplayException :: CancelledStream -> String
displayException :: CancelledStream -> String
$cbacktraceDesired :: CancelledStream -> Bool
backtraceDesired :: CancelledStream -> Bool
E.Exception)

closedCodeToError :: StreamId -> ClosedCode -> HTTP2Error
closedCodeToError :: Int -> ClosedCode -> HTTP2Error
closedCodeToError Int
sid ClosedCode
cc =
    case ClosedCode
cc of
        ClosedCode
Finished -> HTTP2Error
ConnectionIsClosed
        ClosedCode
Killed -> HTTP2Error
ConnectionIsTimeout
        Reset ErrorCode
err -> ErrorCode -> Int -> HTTP2Error
StreamResetIsReceived ErrorCode
err Int
sid
        ResetByMe SomeException
err -> SomeException -> HTTP2Error
BadThingHappen SomeException
err

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

data StreamState
    = Idle
    | Open (Maybe ClosedCode) OpenState -- HalfClosedLocal if Just
    | HalfClosedRemote
    | Closed ClosedCode
    | Reserved

instance Show StreamState where
    show :: StreamState -> String
show StreamState
Idle = String
"Idle"
    show (Open Maybe ClosedCode
Nothing OpenState
_) = String
"Open"
    show (Open (Just ClosedCode
e) OpenState
_) = String
"HalfClosedLocal: " String -> ShowS
forall a. [a] -> [a] -> [a]
++ ClosedCode -> String
forall a. Show a => a -> String
show ClosedCode
e
    show StreamState
HalfClosedRemote = String
"HalfClosedRemote"
    show (Closed ClosedCode
e) = String
"Closed: " String -> ShowS
forall a. [a] -> [a] -> [a]
++ ClosedCode -> String
forall a. Show a => a -> String
show ClosedCode
e
    show StreamState
Reserved = String
"Reserved"

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

type RxQ = TQueue (Either E.SomeException (ByteString, Bool))

data Stream = Stream
    { Stream -> Int
streamNumber :: StreamId
    , Stream -> TVar StreamState
streamState :: TVar StreamState
    , Stream -> MVar (Either SomeException InpObj)
streamInput :: MVar (Either E.SomeException InpObj) -- Client only
    , Stream -> TVar TxFlow
streamTxFlow :: TVar TxFlow
    , Stream -> IORef RxFlow
streamRxFlow :: IORef RxFlow
    , Stream -> IORef (Maybe RxQ)
streamRxQ :: IORef (Maybe RxQ)
    , Stream -> IORef (Maybe ByteString)
streamRequestMethod :: IORef (Maybe ByteString)
    -- ^ Client only: the method of the request, which decides whether the
    --   response may have content at all (RFC 9110, section 6.4.1)
    , Stream -> TVar Bool
streamDiscardBody :: TVar Bool
    -- ^ Server only: the handler has returned, and nobody will read the
    --   rest of the request body.  It is taken in and thrown away, both
    --   windows given back as it comes, until the peer ends it.
    }

instance Show Stream where
    show :: Stream -> String
show Stream{Int
TVar Bool
TVar TxFlow
TVar StreamState
IORef (Maybe ByteString)
IORef (Maybe RxQ)
IORef RxFlow
MVar (Either SomeException InpObj)
streamNumber :: Stream -> Int
streamState :: Stream -> TVar StreamState
streamInput :: Stream -> MVar (Either SomeException InpObj)
streamTxFlow :: Stream -> TVar TxFlow
streamRxFlow :: Stream -> IORef RxFlow
streamRxQ :: Stream -> IORef (Maybe RxQ)
streamRequestMethod :: Stream -> IORef (Maybe ByteString)
streamDiscardBody :: Stream -> TVar Bool
streamNumber :: Int
streamState :: TVar StreamState
streamInput :: MVar (Either SomeException InpObj)
streamTxFlow :: TVar TxFlow
streamRxFlow :: IORef RxFlow
streamRxQ :: IORef (Maybe RxQ)
streamRequestMethod :: IORef (Maybe ByteString)
streamDiscardBody :: TVar Bool
..} =
        String
"Stream{id="
            String -> ShowS
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
streamNumber
            String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
",state="
            String -> ShowS
forall a. [a] -> [a] -> [a]
++ StreamState -> String
forall a. Show a => a -> String
show (IO StreamState -> StreamState
forall a. IO a -> a
unsafePerformIO (TVar StreamState -> IO StreamState
forall a. TVar a -> IO a
readTVarIO TVar StreamState
streamState))
            String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
"}"

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

data Output = Output
    { Output -> Stream
outputStream :: Stream
    , Output -> OutputType
outputType :: OutputType
    , Output -> Maybe Output -> IO ()
outputSync :: Maybe Output -> IO ()
    }

data OutputType
    = OHeader [Header] (Maybe DynaNext) TrailersMaker
    | OPush TokenHeaderList StreamId -- associated stream id from client
    | ONext DynaNext TrailersMaker
    | OInformational [Header]
    | OReset (Maybe E.SomeException)

data Sync = Done | Cont Output

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

data Control = CFrames (Maybe SettingsList) [ByteString]

-- | Control frames waiting for the sender, and how many there are: see
-- 'Network.HTTP2.H2.Queue.waitControlQ'.
data ControlQ = ControlQ (TQueue Control) (TVar Int)

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

type ReasonPhrase = ShortByteString

-- | The connection error or the stream error.
--   A stream error resets that stream and the connection carries on, as
--   RFC 9113 section 5.4.2 asks. One kind of trouble is a connection error
--   even though the spec calls it a stream error, because this
--   implementation cannot carry on through it: a field block abandoned
--   part-way leaves the HPACK tables disagreeing with the peer's, and
--   nothing sent afterwards would decode.
--   `ErrorCode` in connection errors should be the highest stream identifier
--   but in this implementation it identifies the stream that
--   caused this error.
data HTTP2Error
    = ConnectionIsClosed -- NoError
    | ConnectionIsTimeout
    | ConnectionIsReset -- The peer reset the connection.
    | ConnectionErrorIsReceived ErrorCode StreamId ReasonPhrase
    | ConnectionErrorIsSent ErrorCode StreamId ReasonPhrase
    | StreamErrorIsReceived ErrorCode StreamId
    | StreamResetIsReceived ErrorCode StreamId
    | StreamErrorIsSent ErrorCode StreamId ReasonPhrase
    | BadThingHappen E.SomeException
    deriving (Int -> HTTP2Error -> ShowS
[HTTP2Error] -> ShowS
HTTP2Error -> String
(Int -> HTTP2Error -> ShowS)
-> (HTTP2Error -> String)
-> ([HTTP2Error] -> ShowS)
-> Show HTTP2Error
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> HTTP2Error -> ShowS
showsPrec :: Int -> HTTP2Error -> ShowS
$cshow :: HTTP2Error -> String
show :: HTTP2Error -> String
$cshowList :: [HTTP2Error] -> ShowS
showList :: [HTTP2Error] -> ShowS
Show)

instance E.Exception HTTP2Error

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

-- | Checking 'SettingsList' and reporting an error if any.
--
-- >>> checkSettingsList [(SettingsEnablePush,2)]
-- Just (ConnectionErrorIsSent ProtocolError 0 "enable push must be 0 or 1")
checkSettingsList :: SettingsList -> Maybe HTTP2Error
checkSettingsList :: SettingsList -> Maybe HTTP2Error
checkSettingsList SettingsList
settings = case ((SettingsKey, Int) -> Maybe HTTP2Error)
-> SettingsList -> [HTTP2Error]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (SettingsKey, Int) -> Maybe HTTP2Error
checkSettingsValue SettingsList
settings of
    [] -> Maybe HTTP2Error
forall a. Maybe a
Nothing
    (HTTP2Error
x : [HTTP2Error]
_) -> HTTP2Error -> Maybe HTTP2Error
forall a. a -> Maybe a
Just HTTP2Error
x

checkSettingsValue :: (SettingsKey, SettingsValue) -> Maybe HTTP2Error
checkSettingsValue :: (SettingsKey, Int) -> Maybe HTTP2Error
checkSettingsValue (SettingsKey
SettingsEnablePush, Int
v)
    | Int
v Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
0 Bool -> Bool -> Bool
&& Int
v Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
1 =
        HTTP2Error -> Maybe HTTP2Error
forall a. a -> Maybe a
Just (HTTP2Error -> Maybe HTTP2Error) -> HTTP2Error -> Maybe HTTP2Error
forall a b. (a -> b) -> a -> b
$ ErrorCode -> Int -> ShortByteString -> HTTP2Error
ConnectionErrorIsSent ErrorCode
ProtocolError Int
0 ShortByteString
"enable push must be 0 or 1"
checkSettingsValue (SettingsKey
SettingsInitialWindowSize, Int
v)
    | Int
v Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
maxWindowSize =
        HTTP2Error -> Maybe HTTP2Error
forall a. a -> Maybe a
Just (HTTP2Error -> Maybe HTTP2Error) -> HTTP2Error -> Maybe HTTP2Error
forall a b. (a -> b) -> a -> b
$
            ErrorCode -> Int -> ShortByteString -> HTTP2Error
ConnectionErrorIsSent
                ErrorCode
FlowControlError
                Int
0
                ShortByteString
"Window size must be less than or equal to 65535"
checkSettingsValue (SettingsKey
SettingsMaxFrameSize, Int
v)
    | Int
v Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
defaultPayloadLength Bool -> Bool -> Bool
|| Int
v Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
maxPayloadLength =
        HTTP2Error -> Maybe HTTP2Error
forall a. a -> Maybe a
Just (HTTP2Error -> Maybe HTTP2Error) -> HTTP2Error -> Maybe HTTP2Error
forall a b. (a -> b) -> a -> b
$
            ErrorCode -> Int -> ShortByteString -> HTTP2Error
ConnectionErrorIsSent
                ErrorCode
ProtocolError
                Int
0
                ShortByteString
"Max frame size must be in between 16384 and 16777215"
checkSettingsValue (SettingsKey, Int)
_ = Maybe HTTP2Error
forall a. Maybe a
Nothing

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

-- | HTTP/2 configuration.
data Config = Config
    { Config -> Buffer
confWriteBuffer :: Buffer
    -- ^ This is used only by frameSender.
    -- This MUST be freed after frameSender is terminated.
    , Config -> Int
confBufferSize :: BufferSize
    -- ^ The size of the write buffer.
    --   We assume that the read buffer is the same size.
    --   So, this value is announced via SETTINGS_MAX_FRAME_SIZE
    --   to the peer.
    , Config -> ByteString -> IO ()
confSendAll :: ByteString -> IO ()
    -- ^ Not used when 'confSendAllWith' is 'Just'.  When replacing it in
    --   a config which has one, e.g. from 'allocSimpleConfig', set
    --   'confSendAllWith' to 'Nothing' or to a send of the same kind.
    , Config -> Maybe (STM () -> ByteString -> IO (Either () ()))
confSendAllWith :: Maybe (STM () -> ByteString -> IO (Either () ()))
    -- ^ 'confSendAll' which the library can give up on: 'Left' when the
    --   'STM' action fires first.  With it, a write which the peer does
    --   not read is ended by the timeout rather than by killing a thread.
    --   Part of the data may have gone, so the connection is closed after.
    --
    --   @since 5.4.13
    , Config -> Int -> IO ByteString
confReadN :: Int -> IO ByteString
    -- ^ When 'confReadNWith' is 'Just', frames are read with it and only
    --   the connection preface with this.  When replacing it in a config
    --   which has one, e.g. from 'allocSimpleConfig', set 'confReadNWith'
    --   to 'Nothing' or to a read of the same kind sharing its buffer.
    , Config -> Maybe (STM () -> Int -> IO ByteString)
confReadNWith :: Maybe (STM () -> Int -> IO ByteString)
    -- ^ 'confReadN' which the library can give up on: it answers with an
    --   empty string, as at end of input, when the 'STM' action fires
    --   first.  With it, the reader is stopped without being interrupted.
    --   It must share its buffer with 'confReadN'.
    --
    --   @since 5.4.13
    , Config -> PositionReadMaker
confPositionReadMaker :: PositionReadMaker
    , Config -> Manager
confTimeoutManager :: TM.Manager
    , Config -> SockAddr
confMySockAddr :: SockAddr
    -- ^ This is copied into 'Aux', if exist, on server.
    , Config -> SockAddr
confPeerSockAddr :: SockAddr
    -- ^ This is copied into 'Aux', if exist, on server.
    , Config -> Bool
confReadNTimeout :: Bool
    , Config -> Int -> TokenHeaderTable -> IO ()
confOnInformational :: StreamId -> TokenHeaderTable -> IO ()
    -- ^ Client only: called when a 1xx informational response (e.g. 103 Early
    --   Hints) is received on the given stream, ahead of the final response.
    --   No-op by default.
    --
    --   @since 5.4.2
    }

-- | Default config. This is just a template to modify via
--   field names. Don't use this without modifications.
defaultConfig :: Config
defaultConfig :: Config
defaultConfig =
    Config
        { confWriteBuffer :: Buffer
confWriteBuffer = Buffer
forall a. Ptr a
nullPtr
        , confBufferSize :: Int
confBufferSize = Int
0
        , confSendAll :: ByteString -> IO ()
confSendAll = \ByteString
_ -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        , confSendAllWith :: Maybe (STM () -> ByteString -> IO (Either () ()))
confSendAllWith = Maybe (STM () -> ByteString -> IO (Either () ()))
forall a. Maybe a
Nothing
        , confReadN :: Int -> IO ByteString
confReadN = \Int
_ -> ByteString -> IO ByteString
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ByteString
""
        , confReadNWith :: Maybe (STM () -> Int -> IO ByteString)
confReadNWith = Maybe (STM () -> Int -> IO ByteString)
forall a. Maybe a
Nothing
        , confPositionReadMaker :: PositionReadMaker
confPositionReadMaker = PositionReadMaker
defaultPositionReadMaker
        , confTimeoutManager :: Manager
confTimeoutManager = Manager
T.defaultManager
        , confMySockAddr :: SockAddr
confMySockAddr = PortNumber -> Word32 -> SockAddr
SockAddrInet PortNumber
0 Word32
0
        , confPeerSockAddr :: SockAddr
confPeerSockAddr = PortNumber -> Word32 -> SockAddr
SockAddrInet PortNumber
0 Word32
0
        , confReadNTimeout :: Bool
confReadNTimeout = Bool
False
        , confOnInformational :: Int -> TokenHeaderTable -> IO ()
confOnInformational = \Int
_ TokenHeaderTable
_ -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        }

-- | Sending with 'confSendAllWith' if there is one, giving up when the
--   'STM' action fires, and with 'confSendAll' otherwise.
sendAllGivingUp :: Config -> STM () -> ByteString -> IO (Either () ())
sendAllGivingUp :: Config -> STM () -> ByteString -> IO (Either () ())
sendAllGivingUp 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 :: Config -> Buffer
confBufferSize :: Config -> Int
confSendAll :: Config -> ByteString -> IO ()
confSendAllWith :: Config -> Maybe (STM () -> ByteString -> IO (Either () ()))
confReadN :: Config -> Int -> IO ByteString
confReadNWith :: Config -> Maybe (STM () -> Int -> IO ByteString)
confPositionReadMaker :: Config -> PositionReadMaker
confTimeoutManager :: Config -> Manager
confMySockAddr :: Config -> SockAddr
confPeerSockAddr :: Config -> SockAddr
confReadNTimeout :: Config -> Bool
confOnInformational :: Config -> Int -> TokenHeaderTable -> 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 ()
..} STM ()
giveUp ByteString
bs = case Maybe (STM () -> ByteString -> IO (Either () ()))
confSendAllWith of
    Just STM () -> ByteString -> IO (Either () ())
sendWith -> STM () -> ByteString -> IO (Either () ())
sendWith STM ()
giveUp ByteString
bs
    Maybe (STM () -> ByteString -> IO (Either () ()))
Nothing -> () -> Either () ()
forall a b. b -> Either a b
Right (() -> Either () ()) -> IO () -> IO (Either () ())
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> IO ()
confSendAll ByteString
bs

-- | Reading with 'confReadNWith' if there is one, giving up when the
--   'STM' action fires, and with 'confReadN' otherwise.
readNGivingUp :: Config -> STM () -> Int -> IO ByteString
readNGivingUp :: Config -> STM () -> Int -> IO ByteString
readNGivingUp 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 :: Config -> Buffer
confBufferSize :: Config -> Int
confSendAll :: Config -> ByteString -> IO ()
confSendAllWith :: Config -> Maybe (STM () -> ByteString -> IO (Either () ()))
confReadN :: Config -> Int -> IO ByteString
confReadNWith :: Config -> Maybe (STM () -> Int -> IO ByteString)
confPositionReadMaker :: Config -> PositionReadMaker
confTimeoutManager :: Config -> Manager
confMySockAddr :: Config -> SockAddr
confPeerSockAddr :: Config -> SockAddr
confReadNTimeout :: Config -> Bool
confOnInformational :: Config -> Int -> TokenHeaderTable -> 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 ()
..} STM ()
giveUp Int
n = case Maybe (STM () -> Int -> IO ByteString)
confReadNWith of
    Just STM () -> Int -> IO ByteString
readWith -> STM () -> Int -> IO ByteString
readWith STM ()
giveUp Int
n
    Maybe (STM () -> Int -> IO ByteString)
Nothing -> Int -> IO ByteString
confReadN Int
n

-- | Sending GOAWAY, as a last word: it waits one second at most, since a
--   peer which does not read would hold the connection open for good.
sendGoaway :: Config -> ByteString -> IO ()
sendGoaway :: Config -> ByteString -> IO ()
sendGoaway Config
conf ByteString
frame = IO ()
send IO () -> (IOError -> IO ()) -> IO ()
forall a. IO a -> (IOError -> IO a) -> IO a
`catchIOError` \IOError
_ -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  where
    send :: IO ()
send = case Config -> Maybe (STM () -> ByteString -> IO (Either () ()))
confSendAllWith Config
conf of
        Maybe (STM () -> ByteString -> IO (Either () ()))
Nothing -> Config -> ByteString -> IO ()
confSendAll Config
conf ByteString
frame
        Just STM () -> ByteString -> IO (Either () ())
_ -> do
            late <- Int -> IO (TVar Bool)
registerDelay Int
1000000
            void $ sendAllGivingUp conf (readTVar late >>= check) frame

isAsyncException :: E.Exception e => e -> Bool
isAsyncException :: forall e. Exception e => e -> Bool
isAsyncException e
e =
    case SomeException -> Maybe SomeAsyncException
forall e. Exception e => SomeException -> Maybe e
E.fromException (e -> SomeException
forall e. Exception e => e -> SomeException
E.toException e
e) of
        Just (E.SomeAsyncException e
_) -> Bool
True
        Maybe SomeAsyncException
Nothing -> Bool
False