{-# LANGUAGE OverloadedStrings #-}

{- | libp2p WebTransport over HTTP/3 and QUIC v1.

The first WebTransport stream performs a Noise XX handshake to authenticate
peer identities and bind the advertised TLS certificate hashes. Subsequent
WebTransport streams are exposed directly as the native libp2p muxer.
-}
module LibP2P.Transport.WebTransport (
  newWebTransportTransport,
  canDialWebTransport,
  verifyBoundHashes,
) where

import Control.Applicative ((<|>))
import Control.Concurrent (modifyMVar_, newMVar)
import Control.Concurrent.Async (Async, async, cancel, race, waitCatch)
import Control.Concurrent.STM (
  TMVar,
  TQueue,
  atomically,
  newEmptyTMVarIO,
  newTQueueIO,
  putTMVar,
  readTMVar,
  readTQueue,
  tryPutTMVar,
  writeTQueue,
 )
import Control.Exception (SomeException, displayException, finally, onException, try)
import Control.Monad (unless, void, when)
import Data.Bits (shiftL, shiftR, (.&.), (.|.))
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.IP (IPv6, fromHostAddress6, toHostAddress6)
import Data.Maybe (listToMaybe, mapMaybe)
import Data.Text qualified as Text
import Data.Word (Word16, Word32, Word8)
import Data.X509 (CertificateChain)
import Data.X509.Validation (FailedReason (..), SignatureFailure (..))
import LibP2P.Crypto.Key (KeyPair)
import LibP2P.Crypto.PeerId (PeerId (..))
import LibP2P.Multiaddr (Multiaddr (..))
import LibP2P.Multiaddr.Protocol (Protocol (..))
import LibP2P.MultistreamSelect.Negotiation (StreamIO (..))
import LibP2P.Noise.Handshake (HandshakeResult (..))
import LibP2P.Noise.WebTransport (
  performWebTransportInitiator,
  performWebTransportResponder,
 )
import LibP2P.Transport (
  ConnectionEndpoint (..),
  Listener (..),
  NativeMuxer (..),
  RawConnection (..),
  Transport (..),
 )
import LibP2P.Transport.WebTransport.Certificate (
  newWebTransportCredential,
  verifyWebTransportCertificate,
 )
import LibP2P.Transport.WebTransport.HTTP3 (
  WebTransportSession,
  acceptWebTransport,
  acceptWebTransportStream,
  closeWebTransportSession,
  connectWebTransport,
  openWebTransportStream,
 )
import Network.QUIC qualified as QUIC
import Network.QUIC.Client qualified as Client
import Network.QUIC.Internal (
  ClientConfig (..),
  Hooks (..),
  ServerConfig (..),
  Version (..),
  defaultClientConfig,
  defaultHooks,
  defaultServerConfig,
 )
import Network.QUIC.Server qualified as Server
import Network.Socket qualified as Socket
import Network.TLS (Credential, Credentials (..))

webTransportALPN :: ByteString
webTransportALPN :: ByteString
webTransportALPN = ByteString
"h3"

webTransportMaxDatagramFrameSize :: Int
webTransportMaxDatagramFrameSize :: Int
webTransportMaxDatagramFrameSize = Int
65535

{- | Construct a WebTransport transport with one short-lived self-signed TLS
certificate. The listener address includes its SHA-256 @/certhash@.
-}
newWebTransportTransport :: KeyPair -> IO Transport
newWebTransportTransport :: KeyPair -> IO Transport
newWebTransportTransport KeyPair
identity = do
  (credential, certificateHash) <- IO (Credential, ByteString)
newWebTransportCredential
  pure
    Transport
      { transportDial = dialWebTransport identity
      , transportDialFrom = \Maybe Multiaddr
local Multiaddr
remote -> case Maybe Multiaddr
local of
          Maybe Multiaddr
Nothing -> KeyPair -> Multiaddr -> IO RawConnection
dialWebTransport KeyPair
identity Multiaddr
remote
          Just Multiaddr
_ -> [Char] -> IO RawConnection
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail [Char]
"WebTransport does not support binding an existing listen address"
      , transportListen = listenWebTransport identity credential certificateHash
      , transportCanDial = canDialWebTransport
      }

{- | Match dialable WebTransport multiaddrs containing at least one certificate
hash. A trailing peer ID is optional.
-}
canDialWebTransport :: Multiaddr -> Bool
canDialWebTransport :: Multiaddr -> Bool
canDialWebTransport Multiaddr
address = case Multiaddr -> Either [Char] ParsedAddress
parseWebTransportAddress Multiaddr
address of
  Right ParsedAddress
_ -> Bool
True
  Left [Char]
_ -> Bool
False

data ParsedAddress = ParsedAddress
  { ParsedAddress -> [Char]
parsedHost :: !String
  , ParsedAddress -> [Char]
parsedPort :: !String
  , ParsedAddress -> ByteString
parsedAuthority :: !ByteString
  , ParsedAddress -> Maybe Family
parsedResolutionFamily :: !(Maybe Socket.Family)
  , ParsedAddress -> [ByteString]
parsedCertificateHashes :: ![ByteString]
  , ParsedAddress -> Maybe PeerId
parsedExpectedPeer :: !(Maybe PeerId)
  }

dialWebTransport :: KeyPair -> Multiaddr -> IO RawConnection
dialWebTransport :: KeyPair -> Multiaddr -> IO RawConnection
dialWebTransport KeyPair
identity Multiaddr
remoteAddress = do
  parsedAddress <- ([Char] -> IO ParsedAddress)
-> (ParsedAddress -> IO ParsedAddress)
-> Either [Char] ParsedAddress
-> IO ParsedAddress
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either [Char] -> IO ParsedAddress
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail ParsedAddress -> IO ParsedAddress
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Multiaddr -> Either [Char] ParsedAddress
parseWebTransportAddress Multiaddr
remoteAddress)
  when (null (parsedCertificateHashes parsedAddress)) $
    fail "WebTransport address requires at least one /certhash"
  parsed <- resolveDialHost parsedAddress
  validation <- newEmptyTMVarIO
  established <- newEmptyTMVarIO
  let config = ParsedAddress -> TMVar (Either [Char] ()) -> ClientConfig
clientConfig ParsedAddress
parsed TMVar (Either [Char] ())
validation
  worker <-
    async $
      runClient identity parsed config remoteAddress validation established
  outcome <- atomically $ readTMVar established
  case outcome of
    Left [Char]
message -> Async () -> IO (Either SomeException ())
forall a. Async a -> IO (Either SomeException a)
waitCatch Async ()
worker IO (Either SomeException ())
-> IO RawConnection -> IO RawConnection
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> [Char] -> IO RawConnection
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail [Char]
message
    Right RawConnection
connection -> RawConnection -> IO RawConnection
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure RawConnection
connection

runClient ::
  KeyPair ->
  ParsedAddress ->
  ClientConfig ->
  Multiaddr ->
  TMVar (Either String ()) ->
  TMVar (Either String RawConnection) ->
  IO ()
runClient :: KeyPair
-> ParsedAddress
-> ClientConfig
-> Multiaddr
-> TMVar (Either [Char] ())
-> TMVar (Either [Char] RawConnection)
-> IO ()
runClient KeyPair
identity ParsedAddress
parsed ClientConfig
config Multiaddr
remoteAddress TMVar (Either [Char] ())
validation TMVar (Either [Char] RawConnection)
established = 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
$ ClientConfig -> (Connection -> IO ()) -> IO ()
forall a. ClientConfig -> (Connection -> IO a) -> IO a
Client.run ClientConfig
config ((Connection -> IO ()) -> IO ()) -> (Connection -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Connection
connection -> do
    certificateResult <- STM (Either [Char] ()) -> IO (Either [Char] ())
forall a. STM a -> IO a
atomically (STM (Either [Char] ()) -> IO (Either [Char] ()))
-> STM (Either [Char] ()) -> IO (Either [Char] ())
forall a b. (a -> b) -> a -> b
$ TMVar (Either [Char] ()) -> STM (Either [Char] ())
forall a. TMVar a -> STM a
readTMVar TMVar (Either [Char] ())
validation
    either fail pure certificateResult
    session <- connectWebTransport connection (parsedAuthority parsed)
    noiseStream <- openWebTransportStream session >>= streamToStreamIO
    (handshake, boundHashes) <-
      performWebTransportInitiator identity noiseStream `finally` streamClose noiseStream
    verifyBoundHashes (parsedCertificateHashes parsed) boundHashes
    verifyExpectedPeer (parsedExpectedPeer parsed) (hrRemotePeerId handshake)
    info <- QUIC.getConnectionInfo connection
    localAddress <- socketAddressToWebTransport (QUIC.localSockAddr info)
    closed <- newEmptyTMVarIO
    raw <- makeRawConnection session handshake localAddress remoteAddress closed
    atomically $ putTMVar established (Right raw)
    atomically $ readTMVar closed
  case outcome of
    Left (SomeException
err :: SomeException) ->
      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 (STM Bool -> STM ()) -> STM Bool -> STM ()
forall a b. (a -> b) -> a -> b
$
          TMVar (Either [Char] RawConnection)
-> Either [Char] RawConnection -> STM Bool
forall a. TMVar a -> a -> STM Bool
tryPutTMVar TMVar (Either [Char] RawConnection)
established ([Char] -> Either [Char] RawConnection
forall a b. a -> Either a b
Left (SomeException -> [Char]
forall e. Exception e => e -> [Char]
displayException SomeException
err))
    Right () -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

clientConfig ::
  ParsedAddress -> TMVar (Either String ()) -> ClientConfig
clientConfig :: ParsedAddress -> TMVar (Either [Char] ()) -> ClientConfig
clientConfig ParsedAddress
parsed TMVar (Either [Char] ())
validation =
  ClientConfig
defaultClientConfig
    { ccVersion = Version 1
    , ccVersions = [Version 1]
    , ccServerName = parsedHost parsed
    , ccPortName = parsedPort parsed
    , ccALPN = const (pure (Just [webTransportALPN]))
    , ccValidate = False
    , ccUseServerNameIndication = True
    , ccOnServerCertificate = validateCertificate validation hashes
    , ccMaxDatagramFrameSize = webTransportMaxDatagramFrameSize
    }
 where
  hashes :: [ByteString]
hashes = ParsedAddress -> [ByteString]
parsedCertificateHashes ParsedAddress
parsed

validateCertificate ::
  TMVar (Either String ()) ->
  [ByteString] ->
  certificateStore ->
  validationCache ->
  serviceId ->
  CertificateChain ->
  IO [FailedReason]
validateCertificate :: forall certificateStore validationCache serviceId.
TMVar (Either [Char] ())
-> [ByteString]
-> certificateStore
-> validationCache
-> serviceId
-> CertificateChain
-> IO [FailedReason]
validateCertificate TMVar (Either [Char] ())
result [ByteString]
expected certificateStore
_ validationCache
_ serviceId
_ CertificateChain
chain = do
  verified <- [ByteString] -> CertificateChain -> IO (Either [Char] ())
verifyWebTransportCertificate [ByteString]
expected CertificateChain
chain
  atomically $ void (tryPutTMVar result verified)
  pure $ case verified of
    Right () -> []
    Left [Char]
_ -> [SignatureFailure -> FailedReason
InvalidSignature SignatureFailure
SignatureInvalid]

verifyBoundHashes :: [ByteString] -> [ByteString] -> IO ()
verifyBoundHashes :: [ByteString] -> [ByteString] -> IO ()
verifyBoundHashes [ByteString]
expected [ByteString]
received =
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((ByteString -> Bool) -> [ByteString] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (ByteString -> [ByteString] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [ByteString]
received) [ByteString]
expected) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
    [Char] -> IO ()
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail [Char]
"Noise payload did not bind every dialed WebTransport certhash"

verifyExpectedPeer :: Maybe PeerId -> PeerId -> IO ()
verifyExpectedPeer :: Maybe PeerId -> PeerId -> IO ()
verifyExpectedPeer Maybe PeerId
Nothing PeerId
_ = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
verifyExpectedPeer (Just PeerId
expected) PeerId
actual =
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (PeerId
expected PeerId -> PeerId -> Bool
forall a. Eq a => a -> a -> Bool
== PeerId
actual) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
    [Char] -> IO ()
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail [Char]
"WebTransport Noise peer ID does not match the /p2p address"

listenWebTransport ::
  KeyPair -> Credential -> ByteString -> Multiaddr -> IO Listener
listenWebTransport :: KeyPair -> Credential -> ByteString -> Multiaddr -> IO Listener
listenWebTransport KeyPair
identity Credential
credential ByteString
certificateHash Multiaddr
requestedAddress = do
  socketAddress <- ([Char] -> IO SockAddr)
-> (SockAddr -> IO SockAddr)
-> Either [Char] SockAddr
-> IO SockAddr
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either [Char] -> IO SockAddr
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail SockAddr -> IO SockAddr
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Multiaddr -> Either [Char] SockAddr
listenSocketAddress Multiaddr
requestedAddress)
  socket <- openServerSocket socketAddress
  boundBase <- Socket.getSocketName socket >>= socketAddressToWebTransport
  let advertised = Multiaddr -> ByteString -> Multiaddr
appendCerthash Multiaddr
boundBase ByteString
certificateHash
  accepted <- newTQueueIO
  ready <- newEmptyTMVarIO
  worker <-
    async $
      Server.runWithSockets
        [socket]
        (serverConfig credential ready)
        (acceptConnection identity certificateHash advertised accepted)
  waitForServer worker ready `onException` closeServer worker socket
  pure
    Listener
      { listenerAccept = atomically (readTQueue accepted)
      , listenerClose = closeServer worker socket
      , listenerAddr = advertised
      }

serverConfig :: Credential -> TMVar () -> ServerConfig
serverConfig :: Credential -> TMVar () -> ServerConfig
serverConfig Credential
credential TMVar ()
ready =
  ServerConfig
defaultServerConfig
    { scVersions = [Version 1]
    , scCredentials = Credentials [credential]
    , scRequireClientCert = False
    , scMaxDatagramFrameSize = webTransportMaxDatagramFrameSize
    , scALPN = Just selectALPN
    , scHooks = defaultHooks{onServerReady = atomically (putTMVar ready ())}
    }

selectALPN :: Version -> [ByteString] -> IO ByteString
selectALPN :: Version -> [ByteString] -> IO ByteString
selectALPN Version
_ [ByteString]
protocols
  | ByteString
webTransportALPN ByteString -> [ByteString] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [ByteString]
protocols = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
webTransportALPN
  | Bool
otherwise = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty

acceptConnection ::
  KeyPair ->
  ByteString ->
  Multiaddr ->
  TQueue RawConnection ->
  QUIC.Connection ->
  IO ()
acceptConnection :: KeyPair
-> ByteString
-> Multiaddr
-> TQueue RawConnection
-> Connection
-> IO ()
acceptConnection KeyPair
identity ByteString
certificateHash Multiaddr
localAddress TQueue RawConnection
accepted Connection
connection = do
  session <- Connection -> IO WebTransportSession
acceptWebTransport Connection
connection
  noiseStream <- acceptWebTransportStream session >>= streamToStreamIO
  handshake <-
    performWebTransportResponder identity [certificateHash] noiseStream
      `finally` streamClose noiseStream
  info <- QUIC.getConnectionInfo connection
  remoteAddress <- socketAddressToWebTransport (QUIC.remoteSockAddr info)
  closed <- newEmptyTMVarIO
  raw <- makeRawConnection session handshake localAddress remoteAddress closed
  atomically $ writeTQueue accepted raw
  atomically $ readTMVar closed

makeRawConnection ::
  WebTransportSession ->
  HandshakeResult ->
  Multiaddr ->
  Multiaddr ->
  TMVar () ->
  IO RawConnection
makeRawConnection :: WebTransportSession
-> HandshakeResult
-> Multiaddr
-> Multiaddr
-> TMVar ()
-> IO RawConnection
makeRawConnection WebTransportSession
session HandshakeResult
handshake Multiaddr
localAddress Multiaddr
remoteAddress TMVar ()
closed = do
  close <- IO () -> IO (IO ())
closeOnce (IO () -> IO (IO ())) -> IO () -> IO (IO ())
forall a b. (a -> b) -> a -> b
$ do
    WebTransportSession -> IO ()
closeWebTransportSession WebTransportSession
session
    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 () -> () -> STM Bool
forall a. TMVar a -> a -> STM Bool
tryPutTMVar TMVar ()
closed ())
  let native =
        NativeMuxer
          { nativePeerId :: PeerId
nativePeerId = HandshakeResult -> PeerId
hrRemotePeerId HandshakeResult
handshake
          , nativeSecurity :: ProtocolId
nativeSecurity = ProtocolId
"/noise"
          , nativeMuxerProtocol :: ProtocolId
nativeMuxerProtocol = ProtocolId
"/webtransport"
          , nativeOpenStream :: IO StreamIO
nativeOpenStream = WebTransportSession -> IO Stream
openWebTransportStream WebTransportSession
session IO Stream -> (Stream -> IO StreamIO) -> IO StreamIO
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Stream -> IO StreamIO
streamToStreamIO
          , nativeAcceptStream :: IO StreamIO
nativeAcceptStream = WebTransportSession -> IO Stream
acceptWebTransportStream WebTransportSession
session IO Stream -> (Stream -> IO StreamIO) -> IO StreamIO
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Stream -> IO StreamIO
streamToStreamIO
          , nativeClose :: IO ()
nativeClose = IO ()
close
          }
  pure
    RawConnection
      { rcEndpoint = NativeMuxerEndpoint native
      , rcLocalAddr = localAddress
      , rcRemoteAddr = remoteAddress
      , rcClose = close
      , rcRelayLimit = Nothing
      }

closeOnce :: IO () -> IO (IO ())
closeOnce :: IO () -> IO (IO ())
closeOnce IO ()
action = do
  closed <- Bool -> IO (MVar Bool)
forall a. a -> IO (MVar a)
newMVar Bool
False
  pure $ modifyMVar_ closed $ \Bool
alreadyClosed ->
    if Bool
alreadyClosed
      then Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
      else IO ()
action IO () -> IO Bool -> IO Bool
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True

streamToStreamIO :: QUIC.Stream -> IO StreamIO
streamToStreamIO :: Stream -> IO StreamIO
streamToStreamIO Stream
stream =
  StreamIO -> IO StreamIO
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
    StreamIO
      { streamWrite :: ByteString -> IO ()
streamWrite = Stream -> ByteString -> IO ()
QUIC.sendStream Stream
stream
      , streamReadByte :: IO Word8
streamReadByte = HasCallStack => ByteString -> Word8
ByteString -> Word8
BS.head (ByteString -> Word8) -> IO ByteString -> IO Word8
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Int -> IO ByteString
receive Int
1
      , streamReadChunk :: Int -> IO ByteString
streamReadChunk = Int -> IO ByteString
receive
      , streamClose :: IO ()
streamClose = Stream -> IO ()
QUIC.closeStream Stream
stream
      }
 where
  receive :: Int -> IO ByteString
receive Int
size = do
    bytes <- Stream -> Int -> IO ByteString
QUIC.recvStream Stream
stream Int
size
    if BS.null bytes
      then fail "WebTransport stream closed"
      else pure bytes

parseWebTransportAddress :: Multiaddr -> Either String ParsedAddress
parseWebTransportAddress :: Multiaddr -> Either [Char] ParsedAddress
parseWebTransportAddress Multiaddr
address = do
  let (Multiaddr
withoutPeer, Maybe PeerId
expectedPeer) = Multiaddr -> (Multiaddr, Maybe PeerId)
stripP2P Multiaddr
address
  (host, port, authority, rest) <- Multiaddr -> Either [Char] ([Char], [Char], ByteString, [Protocol])
parseHostPort Multiaddr
withoutPeer
  hashes <- parseSuffix rest
  pure
    ParsedAddress
      { parsedHost = host
      , parsedPort = port
      , parsedAuthority = authority
      , parsedResolutionFamily = addressResolutionFamily withoutPeer
      , parsedCertificateHashes = hashes
      , parsedExpectedPeer = expectedPeer
      }

parseHostPort ::
  Multiaddr -> Either String (String, String, ByteString, [Protocol])
parseHostPort :: Multiaddr -> Either [Char] ([Char], [Char], ByteString, [Protocol])
parseHostPort (Multiaddr [Protocol]
protocols) = case [Protocol]
protocols of
  IP4 Word32
word : UDP Word16
port : Protocol
QuicV1 : Protocol
WebTransport : [Protocol]
rest ->
    [Char]
-> Word16
-> [Protocol]
-> Either [Char] ([Char], [Char], ByteString, [Protocol])
forall {d} {a}.
[Char] -> Word16 -> d -> Either a ([Char], [Char], ByteString, d)
endpoint (Word32 -> [Char]
renderIPv4 Word32
word) Word16
port [Protocol]
rest
  IP6 ByteString
bytes : UDP Word16
port : Protocol
QuicV1 : Protocol
WebTransport : [Protocol]
rest
    | ByteString -> Int
BS.length ByteString
bytes Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
16 ->
        let host :: [Char]
host = IPv6 -> [Char]
forall a. Show a => a -> [Char]
show (ByteString -> IPv6
bytesToIPv6 ByteString
bytes)
         in ([Char], [Char], ByteString, [Protocol])
-> Either [Char] ([Char], [Char], ByteString, [Protocol])
forall a b. b -> Either a b
Right ([Char]
host, Word16 -> [Char]
forall a. Show a => a -> [Char]
show Word16
port, [Char] -> Word16 -> ByteString
bracketAuthority [Char]
host Word16
port, [Protocol]
rest)
  DNS ProtocolId
name : UDP Word16
port : Protocol
QuicV1 : Protocol
WebTransport : [Protocol]
rest ->
    [Char]
-> Word16
-> [Protocol]
-> Either [Char] ([Char], [Char], ByteString, [Protocol])
forall {d} {a}.
[Char] -> Word16 -> d -> Either a ([Char], [Char], ByteString, d)
endpoint (ProtocolId -> [Char]
Text.unpack ProtocolId
name) Word16
port [Protocol]
rest
  DNS4 ProtocolId
name : UDP Word16
port : Protocol
QuicV1 : Protocol
WebTransport : [Protocol]
rest ->
    [Char]
-> Word16
-> [Protocol]
-> Either [Char] ([Char], [Char], ByteString, [Protocol])
forall {d} {a}.
[Char] -> Word16 -> d -> Either a ([Char], [Char], ByteString, d)
endpoint (ProtocolId -> [Char]
Text.unpack ProtocolId
name) Word16
port [Protocol]
rest
  DNS6 ProtocolId
name : UDP Word16
port : Protocol
QuicV1 : Protocol
WebTransport : [Protocol]
rest ->
    [Char]
-> Word16
-> [Protocol]
-> Either [Char] ([Char], [Char], ByteString, [Protocol])
forall {d} {a}.
[Char] -> Word16 -> d -> Either a ([Char], [Char], ByteString, d)
endpoint (ProtocolId -> [Char]
Text.unpack ProtocolId
name) Word16
port [Protocol]
rest
  [Protocol]
_ -> [Char] -> Either [Char] ([Char], [Char], ByteString, [Protocol])
forall a b. a -> Either a b
Left [Char]
"expected /ip4|ip6|dns|dns4|dns6/.../udp/.../quic-v1/webtransport"
 where
  endpoint :: [Char] -> Word16 -> d -> Either a ([Char], [Char], ByteString, d)
endpoint [Char]
host Word16
port d
rest =
    ([Char], [Char], ByteString, d)
-> Either a ([Char], [Char], ByteString, d)
forall a b. b -> Either a b
Right ([Char]
host, Word16 -> [Char]
forall a. Show a => a -> [Char]
show Word16
port, [Char] -> Word16 -> ByteString
plainAuthority [Char]
host Word16
port, d
rest)

addressResolutionFamily :: Multiaddr -> Maybe Socket.Family
addressResolutionFamily :: Multiaddr -> Maybe Family
addressResolutionFamily (Multiaddr (DNS ProtocolId
_ : [Protocol]
_)) = Family -> Maybe Family
forall a. a -> Maybe a
Just Family
Socket.AF_UNSPEC
addressResolutionFamily (Multiaddr (DNS4 ProtocolId
_ : [Protocol]
_)) = Family -> Maybe Family
forall a. a -> Maybe a
Just Family
Socket.AF_INET
addressResolutionFamily (Multiaddr (DNS6 ProtocolId
_ : [Protocol]
_)) = Family -> Maybe Family
forall a. a -> Maybe a
Just Family
Socket.AF_INET6
addressResolutionFamily Multiaddr
_ = Maybe Family
forall a. Maybe a
Nothing

resolveDialHost :: ParsedAddress -> IO ParsedAddress
resolveDialHost :: ParsedAddress -> IO ParsedAddress
resolveDialHost ParsedAddress
parsed = case ParsedAddress -> Maybe Family
parsedResolutionFamily ParsedAddress
parsed of
  Maybe Family
Nothing -> ParsedAddress -> IO ParsedAddress
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ParsedAddress
parsed
  Just Family
family -> do
    let hints :: AddrInfo
hints =
          AddrInfo
Socket.defaultHints
            { Socket.addrFamily = family
            , Socket.addrSocketType = Socket.Datagram
            }
    addresses <-
      Maybe AddrInfo -> Maybe [Char] -> Maybe [Char] -> IO [AddrInfo]
forall (t :: * -> *).
GetAddrInfo t =>
Maybe AddrInfo -> Maybe [Char] -> Maybe [Char] -> IO (t AddrInfo)
Socket.getAddrInfo
        (AddrInfo -> Maybe AddrInfo
forall a. a -> Maybe a
Just AddrInfo
hints)
        ([Char] -> Maybe [Char]
forall a. a -> Maybe a
Just (ParsedAddress -> [Char]
parsedHost ParsedAddress
parsed))
        ([Char] -> Maybe [Char]
forall a. a -> Maybe a
Just (ParsedAddress -> [Char]
parsedPort ParsedAddress
parsed))
    host <-
      maybe (fail "WebTransport DNS lookup returned no usable address") pure $
        preferredHost (mapMaybe (numericHost . Socket.addrAddress) addresses)
    pure parsed{parsedHost = host, parsedResolutionFamily = Nothing}

numericHost :: Socket.SockAddr -> Maybe (Socket.Family, String)
numericHost :: SockAddr -> Maybe (Family, [Char])
numericHost (Socket.SockAddrInet PortNumber
_ Word32
host) =
  (Family, [Char]) -> Maybe (Family, [Char])
forall a. a -> Maybe a
Just (Family
Socket.AF_INET, Word32 -> [Char]
renderIPv4 (Word32 -> Word32
hostAddressToWord Word32
host))
numericHost (Socket.SockAddrInet6 PortNumber
_ Word32
_ HostAddress6
host Word32
_) =
  (Family, [Char]) -> Maybe (Family, [Char])
forall a. a -> Maybe a
Just (Family
Socket.AF_INET6, IPv6 -> [Char]
forall a. Show a => a -> [Char]
show (HostAddress6 -> IPv6
fromHostAddress6 HostAddress6
host))
numericHost SockAddr
_ = Maybe (Family, [Char])
forall a. Maybe a
Nothing

preferredHost :: [(Socket.Family, String)] -> Maybe String
preferredHost :: [(Family, [Char])] -> Maybe [Char]
preferredHost [(Family, [Char])]
hosts = (Family, [Char]) -> [Char]
forall a b. (a, b) -> b
snd ((Family, [Char]) -> [Char])
-> Maybe (Family, [Char]) -> Maybe [Char]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ([(Family, [Char])] -> Maybe (Family, [Char])
forall {b}. [(Family, b)] -> Maybe (Family, b)
findIPv4 [(Family, [Char])]
hosts Maybe (Family, [Char])
-> Maybe (Family, [Char]) -> Maybe (Family, [Char])
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> [(Family, [Char])] -> Maybe (Family, [Char])
forall a. [a] -> Maybe a
listToMaybe [(Family, [Char])]
hosts)
 where
  findIPv4 :: [(Family, b)] -> Maybe (Family, b)
findIPv4 = [(Family, b)] -> Maybe (Family, b)
forall a. [a] -> Maybe a
listToMaybe ([(Family, b)] -> Maybe (Family, b))
-> ([(Family, b)] -> [(Family, b)])
-> [(Family, b)]
-> Maybe (Family, b)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Family, b) -> Bool) -> [(Family, b)] -> [(Family, b)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Family -> Family -> Bool
forall a. Eq a => a -> a -> Bool
== Family
Socket.AF_INET) (Family -> Bool) -> ((Family, b) -> Family) -> (Family, b) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Family, b) -> Family
forall a b. (a, b) -> a
fst)

parseSuffix :: [Protocol] -> Either String [ByteString]
parseSuffix :: [Protocol] -> Either [Char] [ByteString]
parseSuffix [] = [ByteString] -> Either [Char] [ByteString]
forall a b. b -> Either a b
Right []
parseSuffix (Certhash ByteString
hashBytes : [Protocol]
rest) =
  (ByteString
hashBytes ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
:) ([ByteString] -> [ByteString])
-> Either [Char] [ByteString] -> Either [Char] [ByteString]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Protocol] -> Either [Char] [ByteString]
parseSuffix [Protocol]
rest
parseSuffix [Protocol]
_ = [Char] -> Either [Char] [ByteString]
forall a b. a -> Either a b
Left [Char]
"only /certhash components may follow /webtransport"

stripP2P :: Multiaddr -> (Multiaddr, Maybe PeerId)
stripP2P :: Multiaddr -> (Multiaddr, Maybe PeerId)
stripP2P (Multiaddr [Protocol]
protocols) = case [Protocol] -> [Protocol]
forall a. [a] -> [a]
reverse [Protocol]
protocols of
  P2P ByteString
bytes : [Protocol]
rest -> ([Protocol] -> Multiaddr
Multiaddr ([Protocol] -> [Protocol]
forall a. [a] -> [a]
reverse [Protocol]
rest), PeerId -> Maybe PeerId
forall a. a -> Maybe a
Just (ByteString -> PeerId
PeerId ByteString
bytes))
  [Protocol]
_ -> ([Protocol] -> Multiaddr
Multiaddr [Protocol]
protocols, Maybe PeerId
forall a. Maybe a
Nothing)

listenSocketAddress :: Multiaddr -> Either String Socket.SockAddr
listenSocketAddress :: Multiaddr -> Either [Char] SockAddr
listenSocketAddress Multiaddr
address = case (Multiaddr, Maybe PeerId) -> Multiaddr
forall a b. (a, b) -> a
fst (Multiaddr -> (Multiaddr, Maybe PeerId)
stripP2P Multiaddr
address) of
  Multiaddr [IP4 Word32
word, UDP Word16
port, Protocol
QuicV1, Protocol
WebTransport] ->
    SockAddr -> Either [Char] SockAddr
forall a b. b -> Either a b
Right (SockAddr -> Either [Char] SockAddr)
-> SockAddr -> Either [Char] SockAddr
forall a b. (a -> b) -> a -> b
$ PortNumber -> Word32 -> SockAddr
Socket.SockAddrInet (Word16 -> PortNumber
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
port) (Word32 -> Word32
wordToHostAddress Word32
word)
  Multiaddr [IP6 ByteString
bytes, UDP Word16
port, Protocol
QuicV1, Protocol
WebTransport]
    | ByteString -> Int
BS.length ByteString
bytes Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
16 ->
        SockAddr -> Either [Char] SockAddr
forall a b. b -> Either a b
Right (SockAddr -> Either [Char] SockAddr)
-> SockAddr -> Either [Char] SockAddr
forall a b. (a -> b) -> a -> b
$
          PortNumber -> Word32 -> HostAddress6 -> Word32 -> SockAddr
Socket.SockAddrInet6
            (Word16 -> PortNumber
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
port)
            Word32
0
            (IPv6 -> HostAddress6
toHostAddress6 (ByteString -> IPv6
bytesToIPv6 ByteString
bytes))
            Word32
0
  Multiaddr
_ -> [Char] -> Either [Char] SockAddr
forall a b. a -> Either a b
Left [Char]
"expected listen address /ip4|ip6/.../udp/.../quic-v1/webtransport"

socketAddressToWebTransport :: Socket.SockAddr -> IO Multiaddr
socketAddressToWebTransport :: SockAddr -> IO Multiaddr
socketAddressToWebTransport (Socket.SockAddrInet PortNumber
port Word32
host) =
  Multiaddr -> IO Multiaddr
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Multiaddr -> IO Multiaddr) -> Multiaddr -> IO Multiaddr
forall a b. (a -> b) -> a -> b
$
    [Protocol] -> Multiaddr
Multiaddr
      [ Word32 -> Protocol
IP4 (Word32 -> Word32
hostAddressToWord Word32
host)
      , Word16 -> Protocol
UDP (PortNumber -> Word16
forall a b. (Integral a, Num b) => a -> b
fromIntegral PortNumber
port)
      , Protocol
QuicV1
      , Protocol
WebTransport
      ]
socketAddressToWebTransport (Socket.SockAddrInet6 PortNumber
port Word32
_ HostAddress6
host Word32
_) =
  Multiaddr -> IO Multiaddr
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Multiaddr -> IO Multiaddr) -> Multiaddr -> IO Multiaddr
forall a b. (a -> b) -> a -> b
$
    [Protocol] -> Multiaddr
Multiaddr
      [ ByteString -> Protocol
IP6 (IPv6 -> ByteString
ipv6ToBytes (HostAddress6 -> IPv6
fromHostAddress6 HostAddress6
host))
      , Word16 -> Protocol
UDP (PortNumber -> Word16
forall a b. (Integral a, Num b) => a -> b
fromIntegral PortNumber
port)
      , Protocol
QuicV1
      , Protocol
WebTransport
      ]
socketAddressToWebTransport SockAddr
_ =
  [Char] -> IO Multiaddr
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail [Char]
"WebTransport only supports IPv4 and IPv6 sockets"

appendCerthash :: Multiaddr -> ByteString -> Multiaddr
appendCerthash :: Multiaddr -> ByteString -> Multiaddr
appendCerthash (Multiaddr [Protocol]
protocols) ByteString
hashBytes =
  [Protocol] -> Multiaddr
Multiaddr ([Protocol]
protocols [Protocol] -> [Protocol] -> [Protocol]
forall a. Semigroup a => a -> a -> a
<> [ByteString -> Protocol
Certhash ByteString
hashBytes])

waitForServer :: Async () -> TMVar () -> IO ()
waitForServer :: Async () -> TMVar () -> IO ()
waitForServer Async ()
worker TMVar ()
ready = do
  result <- IO (Either SomeException ())
-> IO () -> IO (Either (Either SomeException ()) ())
forall a b. IO a -> IO b -> IO (Either a b)
race (Async () -> IO (Either SomeException ())
forall a. Async a -> IO (Either SomeException a)
waitCatch Async ()
worker) (STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TMVar () -> STM ()
forall a. TMVar a -> STM a
readTMVar TMVar ()
ready)
  case result of
    Right () -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    Left (Left SomeException
err) -> [Char] -> IO ()
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail ([Char] -> IO ()) -> [Char] -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char]
"WebTransport listener failed: " [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> SomeException -> [Char]
forall e. Exception e => e -> [Char]
displayException SomeException
err
    Left (Right ()) -> [Char] -> IO ()
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail [Char]
"WebTransport listener stopped before becoming ready"

closeServer :: Async () -> Socket.Socket -> IO ()
closeServer :: Async () -> Socket -> IO ()
closeServer Async ()
worker Socket
socket = do
  Async () -> IO ()
forall a. Async a -> IO ()
cancel Async ()
worker
  Socket -> IO ()
Socket.close Socket
socket

openServerSocket :: Socket.SockAddr -> IO Socket.Socket
openServerSocket :: SockAddr -> IO Socket
openServerSocket SockAddr
address = do
  socket <- Family -> SocketType -> ProtocolNumber -> IO Socket
Socket.socket (SockAddr -> Family
socketFamily SockAddr
address) SocketType
Socket.Datagram ProtocolNumber
Socket.defaultProtocol
  ( do
      Socket.setSocketOption socket Socket.ReuseAddr 1
      Socket.withFdSocket socket Socket.setCloseOnExecIfNeeded
      Socket.bind socket address
      pure socket
    )
    `onException` Socket.close socket

socketFamily :: Socket.SockAddr -> Socket.Family
socketFamily :: SockAddr -> Family
socketFamily Socket.SockAddrInet{} = Family
Socket.AF_INET
socketFamily Socket.SockAddrInet6{} = Family
Socket.AF_INET6
socketFamily SockAddr
_ = Family
Socket.AF_UNSPEC

wordToHostAddress :: Word32 -> Socket.HostAddress
wordToHostAddress :: Word32 -> Word32
wordToHostAddress Word32
word =
  (Word8, Word8, Word8, Word8) -> Word32
Socket.tupleToHostAddress
    ( Int -> Word32 -> Word8
octet Int
3 Word32
word
    , Int -> Word32 -> Word8
octet Int
2 Word32
word
    , Int -> Word32 -> Word8
octet Int
1 Word32
word
    , Int -> Word32 -> Word8
octet Int
0 Word32
word
    )

hostAddressToWord :: Socket.HostAddress -> Word32
hostAddressToWord :: Word32 -> Word32
hostAddressToWord Word32
host =
  let (Word8
a, Word8
b, Word8
c, Word8
d) = Word32 -> (Word8, Word8, Word8, Word8)
Socket.hostAddressToTuple Word32
host
   in (Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
a Word32 -> Int -> Word32
forall a. Bits a => a -> Int -> a
`shiftL` Int
24)
        Word32 -> Word32 -> Word32
forall a. Bits a => a -> a -> a
.|. (Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
b Word32 -> Int -> Word32
forall a. Bits a => a -> Int -> a
`shiftL` Int
16)
        Word32 -> Word32 -> Word32
forall a. Bits a => a -> a -> a
.|. (Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
c Word32 -> Int -> Word32
forall a. Bits a => a -> Int -> a
`shiftL` Int
8)
        Word32 -> Word32 -> Word32
forall a. Bits a => a -> a -> a
.|. Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
d

octet :: Int -> Word32 -> Word8
octet :: Int -> Word32 -> Word8
octet Int
index Word32
word = Word32 -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral ((Word32
word Word32 -> Int -> Word32
forall a. Bits a => a -> Int -> a
`shiftR` (Int
index Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
8)) Word32 -> Word32 -> Word32
forall a. Bits a => a -> a -> a
.&. Word32
0xff)

renderIPv4 :: Word32 -> String
renderIPv4 :: Word32 -> [Char]
renderIPv4 Word32
word =
  Word8 -> [Char]
forall a. Show a => a -> [Char]
show (Int -> Word32 -> Word8
octet Int
3 Word32
word)
    [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
"."
    [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> Word8 -> [Char]
forall a. Show a => a -> [Char]
show (Int -> Word32 -> Word8
octet Int
2 Word32
word)
    [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
"."
    [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> Word8 -> [Char]
forall a. Show a => a -> [Char]
show (Int -> Word32 -> Word8
octet Int
1 Word32
word)
    [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
"."
    [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> Word8 -> [Char]
forall a. Show a => a -> [Char]
show (Int -> Word32 -> Word8
octet Int
0 Word32
word)

plainAuthority :: String -> Word16 -> ByteString
plainAuthority :: [Char] -> Word16 -> ByteString
plainAuthority [Char]
host Word16
port =
  [Word8] -> ByteString
BS.pack ((Char -> Word8) -> [Char] -> [Word8]
forall a b. (a -> b) -> [a] -> [b]
map (Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Word8) -> (Char -> Int) -> Char -> Word8
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Int
forall a. Enum a => a -> Int
fromEnum) ([Char]
host [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
":" [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> Word16 -> [Char]
forall a. Show a => a -> [Char]
show Word16
port))

bracketAuthority :: String -> Word16 -> ByteString
bracketAuthority :: [Char] -> Word16 -> ByteString
bracketAuthority [Char]
host Word16
port = [Char] -> Word16 -> ByteString
plainAuthority ([Char]
"[" [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
host [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
"]") Word16
port

bytesToIPv6 :: ByteString -> IPv6
bytesToIPv6 :: ByteString -> IPv6
bytesToIPv6 ByteString
bytes =
  HostAddress6 -> IPv6
fromHostAddress6
    ( Int -> Word32
forall {a}. (Bits a, Num a) => Int -> a
readWord32 Int
0
    , Int -> Word32
forall {a}. (Bits a, Num a) => Int -> a
readWord32 Int
4
    , Int -> Word32
forall {a}. (Bits a, Num a) => Int -> a
readWord32 Int
8
    , Int -> Word32
forall {a}. (Bits a, Num a) => Int -> a
readWord32 Int
12
    )
 where
  readWord32 :: Int -> a
readWord32 Int
offset =
    (Word8 -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bytes Int
offset) a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftL` Int
24)
      a -> a -> a
forall a. Bits a => a -> a -> a
.|. (Word8 -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bytes (Int
offset Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)) a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftL` Int
16)
      a -> a -> a
forall a. Bits a => a -> a -> a
.|. (Word8 -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bytes (Int
offset Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2)) a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftL` Int
8)
      a -> a -> a
forall a. Bits a => a -> a -> a
.|. Word8 -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bytes (Int
offset Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
3))

ipv6ToBytes :: IPv6 -> ByteString
ipv6ToBytes :: IPv6 -> ByteString
ipv6ToBytes IPv6
ipv6 = [Word8] -> ByteString
BS.pack ((Word32 -> [Word8]) -> [Word32] -> [Word8]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Word32 -> [Word8]
forall {a} {a}. (Integral a, Bits a, Num a) => a -> [a]
word32Bytes [Word32]
words32)
 where
  (Word32
a, Word32
b, Word32
c, Word32
d) = IPv6 -> HostAddress6
toHostAddress6 IPv6
ipv6
  words32 :: [Word32]
words32 = [Word32
a, Word32
b, Word32
c, Word32
d]
  word32Bytes :: a -> [a]
word32Bytes a
word =
    [ a -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral (a
word a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftR` Int
24)
    , a -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral (a
word a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftR` Int
16)
    , a -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral (a
word a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftR` Int
8)
    , a -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral a
word
    ]