{-# LANGUAGE OverloadedStrings #-}

{- | Minimal HTTP/3 WebTransport session layer for libp2p.

This implements only the protocol surface required by the libp2p
WebTransport specification: HTTP/3 SETTINGS, one Extended CONNECT request,
and bidirectional WebTransport streams. QPACK is restricted to a zero-sized
dynamic table, keeping all header blocks self-contained.
-}
module LibP2P.Transport.WebTransport.HTTP3 (
  WebTransportSession,
  connectWebTransport,
  acceptWebTransport,
  openWebTransportStream,
  acceptWebTransportStream,
  closeWebTransportSession,
) where

import Control.Concurrent.Async (Async, async, cancel)
import Control.Concurrent.STM (
  TMVar,
  TQueue,
  atomically,
  newEmptyTMVarIO,
  newTQueueIO,
  putTMVar,
  readTMVar,
  readTQueue,
  tryPutTMVar,
  writeTQueue,
 )
import Control.Exception (SomeException, displayException, try)
import Control.Monad (forever, unless, void, when)
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.Int (Int64)
import Data.List (find)
import Network.QPACK (
  Header,
  QDecoderS,
  QEncoderS,
  dcBlockedSterams,
  dcMaxTableCapacity,
  defaultQDecoderConfig,
  defaultQEncoderConfig,
  ecMaxTableCapacity,
  mk,
  newQDecoderS,
  newQEncoderS,
  original,
 )
import Network.QUIC qualified as QUIC
import Network.QUIC.Internal (encodeInt)

webTransportPath :: ByteString
webTransportPath :: ByteString
webTransportPath = ByteString
"/.well-known/libp2p-webtransport?type=noise"

controlStreamType, qpackEncoderStreamType, qpackDecoderStreamType :: Int64
controlStreamType :: Int64
controlStreamType = Int64
0x00
qpackEncoderStreamType :: Int64
qpackEncoderStreamType = Int64
0x02
qpackDecoderStreamType :: Int64
qpackDecoderStreamType = Int64
0x03

headersFrameType, settingsFrameType, webTransportFrameType :: Int64
headersFrameType :: Int64
headersFrameType = Int64
0x01
settingsFrameType :: Int64
settingsFrameType = Int64
0x04
webTransportFrameType :: Int64
webTransportFrameType = Int64
0x41

settingsEnableConnect, settingsH3Datagram, settingsWebTransport :: Int64
settingsEnableConnect :: Int64
settingsEnableConnect = Int64
0x08
settingsH3Datagram :: Int64
settingsH3Datagram = Int64
0x33
settingsWebTransport :: Int64
settingsWebTransport = Int64
0x2b603742

maximumFrameSize :: Int
maximumFrameSize :: Int
maximumFrameSize = Int
64 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
1024

data Role = ClientRole | ServerRole
  deriving (Role -> Role -> Bool
(Role -> Role -> Bool) -> (Role -> Role -> Bool) -> Eq Role
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Role -> Role -> Bool
== :: Role -> Role -> Bool
$c/= :: Role -> Role -> Bool
/= :: Role -> Role -> Bool
Eq)

data PeerSettings = PeerSettings
  { PeerSettings -> Bool
peerExtendedConnect :: !Bool
  , PeerSettings -> Bool
peerH3Datagram :: !Bool
  , PeerSettings -> Bool
peerWebTransport :: !Bool
  }

data SessionBase = SessionBase
  { SessionBase -> Connection
baseConnection :: !QUIC.Connection
  , SessionBase -> TMVar (Either String PeerSettings)
baseSettings :: !(TMVar (Either String PeerSettings))
  , SessionBase -> TMVar (Either String Stream)
baseRequest :: !(TMVar (Either String QUIC.Stream))
  , SessionBase -> TMVar Int
baseSessionId :: !(TMVar QUIC.StreamId)
  , SessionBase -> TQueue (Either String Stream)
baseIncoming :: !(TQueue (Either String QUIC.Stream))
  , SessionBase -> QEncoderS
baseEncoder :: !QEncoderS
  , SessionBase -> QDecoderS
baseDecoder :: !QDecoderS
  , SessionBase -> Async ()
baseDispatcher :: !(Async ())
  , SessionBase -> [Stream]
baseLocalStreams :: ![QUIC.Stream]
  }

data WebTransportSession = WebTransportSession
  { WebTransportSession -> SessionBase
sessionBase :: !SessionBase
  , WebTransportSession -> Stream
sessionConnectStream :: !QUIC.Stream
  }

{- | Establish a client WebTransport session over an authenticated QUIC
connection using the standardized libp2p endpoint.
-}
connectWebTransport ::
  QUIC.Connection -> ByteString -> IO WebTransportSession
connectWebTransport :: Connection -> ByteString -> IO WebTransportSession
connectWebTransport Connection
connection ByteString
authority = do
  base <- Role -> Connection -> IO SessionBase
initializeSession Role
ClientRole Connection
connection
  settings <- awaitPeerSettings base
  validatePeerSettings ClientRole settings
  connectStream <- QUIC.stream connection
  let sessionId = Stream -> Int
QUIC.streamId Stream
connectStream
  atomically $ putTMVar (baseSessionId base) sessionId
  sendConnectRequest base connectStream authority
  receiveConnectResponse base connectStream
  pure
    WebTransportSession
      { sessionBase = base
      , sessionConnectStream = connectStream
      }

{- | Accept the single libp2p WebTransport Extended CONNECT request on a QUIC
connection and send a successful response.
-}
acceptWebTransport :: QUIC.Connection -> IO WebTransportSession
acceptWebTransport :: Connection -> IO WebTransportSession
acceptWebTransport Connection
connection = do
  base <- Role -> Connection -> IO SessionBase
initializeSession Role
ServerRole Connection
connection
  settings <- awaitPeerSettings base
  validatePeerSettings ServerRole settings
  connectStream <- awaitConnectRequest base
  validateConnectRequest base connectStream
  let sessionId = Stream -> Int
QUIC.streamId Stream
connectStream
  atomically $ putTMVar (baseSessionId base) sessionId
  sendConnectResponse base connectStream
  pure
    WebTransportSession
      { sessionBase = base
      , sessionConnectStream = connectStream
      }

-- | Open a bidirectional stream in this WebTransport session.
openWebTransportStream :: WebTransportSession -> IO QUIC.Stream
openWebTransportStream :: WebTransportSession -> IO Stream
openWebTransportStream WebTransportSession
session = do
  let base :: SessionBase
base = WebTransportSession -> SessionBase
sessionBase WebTransportSession
session
  stream <- Connection -> IO Stream
QUIC.stream (SessionBase -> Connection
baseConnection SessionBase
base)
  sessionId <- atomically $ readTMVar (baseSessionId base)
  QUIC.sendStream stream $
    encodeInt webTransportFrameType <> encodeInt (fromIntegral sessionId)
  pure stream

-- | Accept the next bidirectional stream belonging to this session.
acceptWebTransportStream :: WebTransportSession -> IO QUIC.Stream
acceptWebTransportStream :: WebTransportSession -> IO Stream
acceptWebTransportStream WebTransportSession
session = do
  result <- STM (Either String Stream) -> IO (Either String Stream)
forall a. STM a -> IO a
atomically (STM (Either String Stream) -> IO (Either String Stream))
-> STM (Either String Stream) -> IO (Either String Stream)
forall a b. (a -> b) -> a -> b
$ TQueue (Either String Stream) -> STM (Either String Stream)
forall a. TQueue a -> STM a
readTQueue (SessionBase -> TQueue (Either String Stream)
baseIncoming (WebTransportSession -> SessionBase
sessionBase WebTransportSession
session))
  either fail pure result

-- | Close the HTTP/3 control request and stop dispatching streams.
closeWebTransportSession :: WebTransportSession -> IO ()
closeWebTransportSession :: WebTransportSession -> IO ()
closeWebTransportSession WebTransportSession
session =
  Async () -> IO ()
forall a. Async a -> IO ()
cancel (SessionBase -> Async ()
baseDispatcher (WebTransportSession -> SessionBase
sessionBase WebTransportSession
session))

initializeSession :: Role -> QUIC.Connection -> IO SessionBase
initializeSession :: Role -> Connection -> IO SessionBase
initializeSession Role
role Connection
connection = do
  settings <- IO (TMVar (Either String PeerSettings))
forall a. IO (TMVar a)
newEmptyTMVarIO
  request <- newEmptyTMVarIO
  sessionId <- newEmptyTMVarIO
  incoming <- newTQueueIO
  encoder <- makeEncoder
  decoder <- makeDecoder
  localStreams <- openLocalControlStreams connection
  let create Async ()
dispatcher =
        SessionBase
          { baseConnection :: Connection
baseConnection = Connection
connection
          , baseSettings :: TMVar (Either String PeerSettings)
baseSettings = TMVar (Either String PeerSettings)
settings
          , baseRequest :: TMVar (Either String Stream)
baseRequest = TMVar (Either String Stream)
request
          , baseSessionId :: TMVar Int
baseSessionId = TMVar Int
sessionId
          , baseIncoming :: TQueue (Either String Stream)
baseIncoming = TQueue (Either String Stream)
incoming
          , baseEncoder :: QEncoderS
baseEncoder = QEncoderS
encoder
          , baseDecoder :: QDecoderS
baseDecoder = QDecoderS
decoder
          , baseDispatcher :: Async ()
baseDispatcher = Async ()
dispatcher
          , baseLocalStreams :: [Stream]
baseLocalStreams = [Stream]
localStreams
          }
  dispatcher <- async $ dispatchIncoming role connection settings request sessionId incoming
  pure (create dispatcher)

makeEncoder :: IO QEncoderS
makeEncoder :: IO QEncoderS
makeEncoder =
  QEncoderConfig
-> (ByteString -> IO ()) -> Int -> Bool -> Bool -> IO QEncoderS
newQEncoderS
    QEncoderConfig
defaultQEncoderConfig{ecMaxTableCapacity = 0}
    ByteString -> IO ()
forall {f :: * -> *}. MonadFail f => ByteString -> f ()
rejectDynamicInstruction
    Int
0
    Bool
True
    Bool
False
 where
  rejectDynamicInstruction :: ByteString -> f ()
rejectDynamicInstruction ByteString
bytes =
    Bool -> f () -> f ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (ByteString -> Bool
BS.null ByteString
bytes) (f () -> f ()) -> f () -> f ()
forall a b. (a -> b) -> a -> b
$ String -> f ()
forall a. String -> f a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"unexpected QPACK encoder instruction"

makeDecoder :: IO QDecoderS
makeDecoder :: IO QDecoderS
makeDecoder = (QDecoderS, EncoderInstructionHandlerS) -> QDecoderS
forall a b. (a, b) -> a
fst ((QDecoderS, EncoderInstructionHandlerS) -> QDecoderS)
-> IO (QDecoderS, EncoderInstructionHandlerS) -> IO QDecoderS
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> QDecoderConfig
-> (ByteString -> IO ())
-> Bool
-> IO (QDecoderS, EncoderInstructionHandlerS)
newQDecoderS QDecoderConfig
config (IO () -> ByteString -> IO ()
forall a b. a -> b -> a
const (() -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())) Bool
False
 where
  config :: QDecoderConfig
config =
    QDecoderConfig
defaultQDecoderConfig
      { dcMaxTableCapacity = 0
      , dcBlockedSterams = 0
      }

openLocalControlStreams :: QUIC.Connection -> IO [QUIC.Stream]
openLocalControlStreams :: Connection -> IO [Stream]
openLocalControlStreams Connection
connection = do
  control <- Connection -> IO Stream
QUIC.unidirectionalStream Connection
connection
  encoder <- QUIC.unidirectionalStream connection
  decoder <- QUIC.unidirectionalStream connection
  QUIC.sendStream control $ encodeInt controlStreamType <> encodeSettingsFrame
  QUIC.sendStream encoder (encodeInt qpackEncoderStreamType)
  QUIC.sendStream decoder (encodeInt qpackDecoderStreamType)
  pure [control, encoder, decoder]

encodeSettingsFrame :: ByteString
encodeSettingsFrame :: ByteString
encodeSettingsFrame = Int64 -> ByteString -> ByteString
encodeFrame Int64
settingsFrameType ByteString
payload
 where
  payload :: ByteString
payload =
    [ByteString] -> ByteString
BS.concat
      [ Int64 -> ByteString
setting Int64
settingsEnableConnect
      , Int64 -> ByteString
setting Int64
settingsH3Datagram
      , Int64 -> ByteString
setting Int64
settingsWebTransport
      ]
  setting :: Int64 -> ByteString
setting Int64
key = Int64 -> ByteString
encodeInt Int64
key ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Int64 -> ByteString
encodeInt Int64
1

dispatchIncoming ::
  Role ->
  QUIC.Connection ->
  TMVar (Either String PeerSettings) ->
  TMVar (Either String QUIC.Stream) ->
  TMVar QUIC.StreamId ->
  TQueue (Either String QUIC.Stream) ->
  IO ()
dispatchIncoming :: Role
-> Connection
-> TMVar (Either String PeerSettings)
-> TMVar (Either String Stream)
-> TMVar Int
-> TQueue (Either String Stream)
-> IO ()
dispatchIncoming Role
role Connection
connection TMVar (Either String PeerSettings)
settings TMVar (Either String Stream)
request TMVar Int
sessionId TQueue (Either String Stream)
incoming = do
  outcome <- IO () -> IO (Either SomeException ())
forall e a. Exception e => IO a -> IO (Either e a)
try (IO () -> IO (Either SomeException ()))
-> IO () -> IO (Either SomeException ())
forall a b. (a -> b) -> a -> b
$ IO () -> IO ()
forall (f :: * -> *) a b. Applicative f => f a -> f b
forever (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
    stream <- Connection -> IO Stream
QUIC.acceptStream Connection
connection
    if isUnidirectional (QUIC.streamId stream)
      then handleUnidirectional stream settings
      else handleBidirectional role stream request sessionId incoming
  case outcome of
    Left (SomeException
err :: SomeException) ->
      String
-> TMVar (Either String PeerSettings)
-> TMVar (Either String Stream)
-> TQueue (Either String Stream)
-> IO ()
publishDispatchError (SomeException -> String
forall e. Exception e => e -> String
displayException SomeException
err) TMVar (Either String PeerSettings)
settings TMVar (Either String Stream)
request TQueue (Either String Stream)
incoming
    Right () -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

isUnidirectional :: QUIC.StreamId -> Bool
isUnidirectional :: Int -> Bool
isUnidirectional Int
streamId = Int
streamId Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int
4 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
2

handleUnidirectional ::
  QUIC.Stream -> TMVar (Either String PeerSettings) -> IO ()
handleUnidirectional :: Stream -> TMVar (Either String PeerSettings) -> IO ()
handleUnidirectional Stream
stream TMVar (Either String PeerSettings)
settings = do
  streamType <- Stream -> IO Int64
readVarint Stream
stream
  case streamType of
    Int64
0x00 -> Stream -> IO PeerSettings
readSettings Stream
stream IO PeerSettings -> (PeerSettings -> 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
>>= STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ())
-> (PeerSettings -> STM ()) -> PeerSettings -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. STM Bool -> STM ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (STM Bool -> STM ())
-> (PeerSettings -> STM Bool) -> PeerSettings -> STM ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TMVar (Either String PeerSettings)
-> Either String PeerSettings -> STM Bool
forall a. TMVar a -> a -> STM Bool
tryPutTMVar TMVar (Either String PeerSettings)
settings (Either String PeerSettings -> STM Bool)
-> (PeerSettings -> Either String PeerSettings)
-> PeerSettings
-> STM Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PeerSettings -> Either String PeerSettings
forall a b. b -> Either a b
Right
    Int64
0x02 -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    Int64
0x03 -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    Int64
_ -> Stream -> IO ()
QUIC.closeStream Stream
stream

handleBidirectional ::
  Role ->
  QUIC.Stream ->
  TMVar (Either String QUIC.Stream) ->
  TMVar QUIC.StreamId ->
  TQueue (Either String QUIC.Stream) ->
  IO ()
handleBidirectional :: Role
-> Stream
-> TMVar (Either String Stream)
-> TMVar Int
-> TQueue (Either String Stream)
-> IO ()
handleBidirectional Role
role Stream
stream TMVar (Either String Stream)
request TMVar Int
sessionId TQueue (Either String Stream)
incoming = do
  firstType <- Stream -> IO Int64
readVarint Stream
stream
  case firstType of
    Int64
0x01
      | Role
role Role -> Role -> Bool
forall a. Eq a => a -> a -> Bool
== Role
ServerRole ->
          STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ STM Bool -> STM ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (TMVar (Either String Stream) -> Either String Stream -> STM Bool
forall a. TMVar a -> a -> STM Bool
tryPutTMVar TMVar (Either String Stream)
request (Stream -> Either String Stream
forall a b. b -> Either a b
Right Stream
stream))
    Int64
0x41 -> do
      receivedId <- Stream -> IO Int64
readVarint Stream
stream
      expectedId <- atomically $ readTMVar sessionId
      if receivedId == fromIntegral expectedId
        then atomically $ writeTQueue incoming (Right stream)
        else QUIC.closeStream stream
    Int64
_ -> String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
"unexpected HTTP/3 bidirectional stream type " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int64 -> String
forall a. Show a => a -> String
show Int64
firstType

publishDispatchError ::
  String ->
  TMVar (Either String PeerSettings) ->
  TMVar (Either String QUIC.Stream) ->
  TQueue (Either String QUIC.Stream) ->
  IO ()
publishDispatchError :: String
-> TMVar (Either String PeerSettings)
-> TMVar (Either String Stream)
-> TQueue (Either String Stream)
-> IO ()
publishDispatchError String
message TMVar (Either String PeerSettings)
settings TMVar (Either String Stream)
request TQueue (Either String Stream)
incoming = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
  STM Bool -> STM ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (STM Bool -> STM ()) -> STM Bool -> STM ()
forall a b. (a -> b) -> a -> b
$ TMVar (Either String PeerSettings)
-> Either String PeerSettings -> STM Bool
forall a. TMVar a -> a -> STM Bool
tryPutTMVar TMVar (Either String PeerSettings)
settings (String -> Either String PeerSettings
forall a b. a -> Either a b
Left String
message)
  STM Bool -> STM ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (STM Bool -> STM ()) -> STM Bool -> STM ()
forall a b. (a -> b) -> a -> b
$ TMVar (Either String Stream) -> Either String Stream -> STM Bool
forall a. TMVar a -> a -> STM Bool
tryPutTMVar TMVar (Either String Stream)
request (String -> Either String Stream
forall a b. a -> Either a b
Left String
message)
  TQueue (Either String Stream) -> Either String Stream -> STM ()
forall a. TQueue a -> a -> STM ()
writeTQueue TQueue (Either String Stream)
incoming (String -> Either String Stream
forall a b. a -> Either a b
Left String
message)

readSettings :: QUIC.Stream -> IO PeerSettings
readSettings :: Stream -> IO PeerSettings
readSettings Stream
stream = do
  frameType <- Stream -> IO Int64
readVarint Stream
stream
  when (frameType /= settingsFrameType) $
    fail "HTTP/3 control stream did not begin with SETTINGS"
  payload <- readFramePayload stream
  pairs <- either fail pure (decodeSettings payload)
  pure
    PeerSettings
      { peerExtendedConnect = enabled settingsEnableConnect pairs
      , peerH3Datagram = enabled settingsH3Datagram pairs
      , peerWebTransport = enabled settingsWebTransport pairs
      }
 where
  enabled :: a -> [(a, b)] -> Bool
enabled a
key [(a, b)]
pairs = a -> [(a, b)] -> Maybe b
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup a
key [(a, b)]
pairs Maybe b -> Maybe b -> Bool
forall a. Eq a => a -> a -> Bool
== b -> Maybe b
forall a. a -> Maybe a
Just b
1

decodeSettings :: ByteString -> Either String [(Int64, Int64)]
decodeSettings :: ByteString -> Either String [(Int64, Int64)]
decodeSettings ByteString
bytes
  | ByteString -> Bool
BS.null ByteString
bytes = [(Int64, Int64)] -> Either String [(Int64, Int64)]
forall a b. b -> Either a b
Right []
  | Bool
otherwise = do
      (key, rest1) <- ByteString -> Either String (Int64, ByteString)
decodeVarint ByteString
bytes
      (value, rest2) <- decodeVarint rest1
      remaining <- decodeSettings rest2
      if any ((== key) . fst) remaining
        then Left $ "duplicate HTTP/3 setting " <> show key
        else Right ((key, value) : remaining)

awaitPeerSettings :: SessionBase -> IO PeerSettings
awaitPeerSettings :: SessionBase -> IO PeerSettings
awaitPeerSettings SessionBase
base =
  STM (Either String PeerSettings) -> IO (Either String PeerSettings)
forall a. STM a -> IO a
atomically (TMVar (Either String PeerSettings)
-> STM (Either String PeerSettings)
forall a. TMVar a -> STM a
readTMVar (SessionBase -> TMVar (Either String PeerSettings)
baseSettings SessionBase
base)) IO (Either String PeerSettings)
-> (Either String PeerSettings -> IO PeerSettings)
-> IO PeerSettings
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (String -> IO PeerSettings)
-> (PeerSettings -> IO PeerSettings)
-> Either String PeerSettings
-> IO PeerSettings
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> IO PeerSettings
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail PeerSettings -> IO PeerSettings
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure

validatePeerSettings :: Role -> PeerSettings -> IO ()
validatePeerSettings :: Role -> PeerSettings -> IO ()
validatePeerSettings Role
role PeerSettings
settings = do
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Role
role Role -> Role -> Bool
forall a. Eq a => a -> a -> Bool
== Role
ClientRole Bool -> Bool -> Bool
&& Bool -> Bool
not (PeerSettings -> Bool
peerExtendedConnect PeerSettings
settings)) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
    String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"server did not enable HTTP/3 Extended CONNECT"
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (PeerSettings -> Bool
peerH3Datagram PeerSettings
settings) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
    String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"peer did not enable HTTP/3 datagrams"
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Role
role Role -> Role -> Bool
forall a. Eq a => a -> a -> Bool
== Role
ClientRole Bool -> Bool -> Bool
&& Bool -> Bool
not (PeerSettings -> Bool
peerWebTransport PeerSettings
settings)) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
    String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"server did not enable WebTransport"

awaitConnectRequest :: SessionBase -> IO QUIC.Stream
awaitConnectRequest :: SessionBase -> IO Stream
awaitConnectRequest SessionBase
base =
  STM (Either String Stream) -> IO (Either String Stream)
forall a. STM a -> IO a
atomically (TMVar (Either String Stream) -> STM (Either String Stream)
forall a. TMVar a -> STM a
readTMVar (SessionBase -> TMVar (Either String Stream)
baseRequest SessionBase
base)) IO (Either String Stream)
-> (Either String Stream -> IO Stream) -> IO Stream
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (String -> IO Stream)
-> (Stream -> IO Stream) -> Either String Stream -> IO Stream
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> IO Stream
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail Stream -> IO Stream
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure

sendConnectRequest :: SessionBase -> QUIC.Stream -> ByteString -> IO ()
sendConnectRequest :: SessionBase -> Stream -> ByteString -> IO ()
sendConnectRequest SessionBase
base Stream
stream ByteString
authority = do
  payload <-
    SessionBase -> QEncoderS
baseEncoder
      SessionBase
base
      (Stream -> Int
QUIC.streamId Stream
stream)
      [ ByteString -> ByteString -> Header
header ByteString
":method" ByteString
"CONNECT"
      , ByteString -> ByteString -> Header
header ByteString
":scheme" ByteString
"https"
      , ByteString -> ByteString -> Header
header ByteString
":authority" ByteString
authority
      , ByteString -> ByteString -> Header
header ByteString
":path" ByteString
webTransportPath
      , ByteString -> ByteString -> Header
header ByteString
":protocol" ByteString
"webtransport"
      ]
  QUIC.sendStream stream (encodeFrame headersFrameType payload)

validateConnectRequest :: SessionBase -> QUIC.Stream -> IO ()
validateConnectRequest :: SessionBase -> Stream -> IO ()
validateConnectRequest SessionBase
base Stream
stream = do
  headers <- SessionBase -> Stream -> Int64 -> IO [Header]
receiveHeaders SessionBase
base Stream
stream Int64
headersFrameType
  requireHeader headers ":method" "CONNECT"
  requireHeader headers ":scheme" "https"
  requireHeader headers ":protocol" "webtransport"
  requireHeader headers ":path" webTransportPath

sendConnectResponse :: SessionBase -> QUIC.Stream -> IO ()
sendConnectResponse :: SessionBase -> Stream -> IO ()
sendConnectResponse SessionBase
base Stream
stream = do
  payload <- SessionBase -> QEncoderS
baseEncoder SessionBase
base (Stream -> Int
QUIC.streamId Stream
stream) [ByteString -> ByteString -> Header
header ByteString
":status" ByteString
"200"]
  QUIC.sendStream stream (encodeFrame headersFrameType payload)

receiveConnectResponse :: SessionBase -> QUIC.Stream -> IO ()
receiveConnectResponse :: SessionBase -> Stream -> IO ()
receiveConnectResponse SessionBase
base Stream
stream = do
  frameType <- Stream -> IO Int64
readVarint Stream
stream
  headers <- receiveHeaders base stream frameType
  requireHeader headers ":status" "200"

receiveHeaders :: SessionBase -> QUIC.Stream -> Int64 -> IO [Header]
receiveHeaders :: SessionBase -> Stream -> Int64 -> IO [Header]
receiveHeaders SessionBase
base Stream
stream Int64
frameType = do
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int64
frameType Int64 -> Int64 -> Bool
forall a. Eq a => a -> a -> Bool
/= Int64
headersFrameType) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
    String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$
      String
"expected HTTP/3 HEADERS frame, got " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int64 -> String
forall a. Show a => a -> String
show Int64
frameType
  payload <- Stream -> IO ByteString
readFramePayload Stream
stream
  decoded <- baseDecoder base (QUIC.streamId stream) payload
  maybe (fail "failed to decode QPACK header block") pure decoded

header :: ByteString -> ByteString -> Header
header :: ByteString -> ByteString -> Header
header ByteString
name ByteString
value = (ByteString -> CI ByteString
forall s. FoldCase s => s -> CI s
mk ByteString
name, ByteString
value)

requireHeader :: [Header] -> ByteString -> ByteString -> IO ()
requireHeader :: [Header] -> ByteString -> ByteString -> IO ()
requireHeader [Header]
headers ByteString
name ByteString
expected =
  case (Header -> Bool) -> [Header] -> Maybe Header
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
name) (ByteString -> Bool) -> (Header -> ByteString) -> Header -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CI ByteString -> ByteString
forall s. CI s -> s
original (CI ByteString -> ByteString)
-> (Header -> CI ByteString) -> Header -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Header -> CI ByteString
forall a b. (a, b) -> a
fst) [Header]
headers of
    Just (CI ByteString
_, ByteString
actual) | ByteString
actual ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
expected -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    Maybe Header
_ -> String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
"invalid or missing HTTP/3 header " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> ByteString -> String
forall a. Show a => a -> String
show ByteString
name

encodeFrame :: Int64 -> ByteString -> ByteString
encodeFrame :: Int64 -> ByteString -> ByteString
encodeFrame Int64
frameType ByteString
payload =
  Int64 -> ByteString
encodeInt Int64
frameType ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Int64 -> ByteString
encodeInt (Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS.length ByteString
payload)) ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
payload

readFramePayload :: QUIC.Stream -> IO ByteString
readFramePayload :: Stream -> IO ByteString
readFramePayload Stream
stream = do
  size <- Stream -> IO Int64
readVarint Stream
stream
  when (size < 0 || size > fromIntegral maximumFrameSize) $
    fail $
      "HTTP/3 frame too large: " <> show size
  readExact stream (fromIntegral size)

readVarint :: QUIC.Stream -> IO Int64
readVarint :: Stream -> IO Int64
readVarint Stream
stream = do
  first <- Stream -> Int -> IO ByteString
readExact Stream
stream Int
1
  let byte = HasCallStack => ByteString -> Word8
ByteString -> Word8
BS.head ByteString
first
      trailingLength = case Word8
byte Word8 -> Word8 -> Word8
forall a. Integral a => a -> a -> a
`div` Word8
64 of
        Word8
0 -> Int
0
        Word8
1 -> Int
1
        Word8
2 -> Int
3
        Word8
_ -> Int
7
      initial = Word8 -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word8
byte Word8 -> Word8 -> Word8
forall a. Integral a => a -> a -> a
`mod` Word8
64)
  trailing <- readExact stream trailingLength
  pure $ BS.foldl' (\Int64
value Word8
next -> Int64
value Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
* Int64
256 Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
+ Word8 -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
next) initial trailing

decodeVarint :: ByteString -> Either String (Int64, ByteString)
decodeVarint :: ByteString -> Either String (Int64, ByteString)
decodeVarint ByteString
bytes
  | ByteString -> Bool
BS.null ByteString
bytes = String -> Either String (Int64, ByteString)
forall a b. a -> Either a b
Left String
"truncated QUIC varint"
  | ByteString -> Int
BS.length ByteString
bytes Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
totalLength = String -> Either String (Int64, ByteString)
forall a b. a -> Either a b
Left String
"truncated QUIC varint"
  | Bool
otherwise = (Int64, ByteString) -> Either String (Int64, ByteString)
forall a b. b -> Either a b
Right (Int64
value, Int -> ByteString -> ByteString
BS.drop Int
totalLength ByteString
bytes)
 where
  first :: Word8
first = HasCallStack => ByteString -> Word8
ByteString -> Word8
BS.head ByteString
bytes
  trailingLength :: Int
trailingLength = case Word8
first Word8 -> Word8 -> Word8
forall a. Integral a => a -> a -> a
`div` Word8
64 of
    Word8
0 -> Int
0
    Word8
1 -> Int
1
    Word8
2 -> Int
3
    Word8
_ -> Int
7
  totalLength :: Int
totalLength = Int
trailingLength Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
  initial :: Int64
initial = Word8 -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word8
first Word8 -> Word8 -> Word8
forall a. Integral a => a -> a -> a
`mod` Word8
64)
  value :: Int64
value =
    (Int64 -> Word8 -> Int64) -> Int64 -> ByteString -> Int64
forall a. (a -> Word8 -> a) -> a -> ByteString -> a
BS.foldl'
      (\Int64
acc Word8
next -> Int64
acc Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
* Int64
256 Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
+ Word8 -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
next)
      Int64
initial
      (Int -> ByteString -> ByteString
BS.take Int
trailingLength (HasCallStack => ByteString -> ByteString
ByteString -> ByteString
BS.tail ByteString
bytes))

readExact :: QUIC.Stream -> Int -> IO ByteString
readExact :: Stream -> Int -> IO ByteString
readExact Stream
_ Int
0 = EncoderInstructionHandlerS
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty
readExact Stream
stream Int
wanted = ByteString -> Int -> IO ByteString
go ByteString
BS.empty Int
wanted
 where
  go :: ByteString -> Int -> IO ByteString
go ByteString
acc Int
0 = EncoderInstructionHandlerS
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
acc
  go ByteString
acc Int
remaining = do
    chunk <- Stream -> Int -> IO ByteString
QUIC.recvStream Stream
stream Int
remaining
    if BS.null chunk
      then fail "HTTP/3 stream closed unexpectedly"
      else go (acc <> chunk) (remaining - BS.length chunk)