module LibP2P.Switch.Upgrade
(
performStreamHandshake
, performStreamHandshakeWithPrologue
, noiseSessionToStreamIO
, noiseSessionToManagedStreamIO
, yamuxToMuxerSession
, upgradeAs
, upgradeAsWithConfig
, upgradeWithSwitchConfig
, upgradeAsWithSecurityProtocols
, upgradeOutbound
, upgradeInbound
, readExact
, readFramedMessage
, writeFramedMessage
) where
import Control.Concurrent.Async (async, cancel, race, waitCatch)
import Control.Concurrent.STM (STM, atomically, isEmptyTQueue, newTVarIO, retry)
import Control.Exception (SomeException, catch, finally, mask, mask_, onException, throwIO)
import Control.Monad (unless)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.Word (Word8)
import LibP2P.Core.Binary (readWord16BE)
import LibP2P.Crypto.Key (KeyPair (..))
import LibP2P.Crypto.PeerId (PeerId, fromPublicKey)
import LibP2P.Yamux.Frame (maxStreamWindowSize)
import LibP2P.Yamux.Session
( closeSession
, keepaliveLoop
, newManagedSessionWithConfig
, recvLoop
, sendLoop
)
import qualified LibP2P.Yamux.Session as Yamux
import LibP2P.Yamux.Stream (streamReadRetained)
import qualified LibP2P.Yamux.Stream as YS
import LibP2P.Yamux.Types
( SessionRole (..)
, YamuxConfig
, YamuxSession (ysessSendCh)
, YamuxStream (ysMemoryAccount)
, defaultYamuxConfig
)
import LibP2P.MultistreamSelect.Negotiation
( NegotiationResult (..)
, ProtocolId
, StreamIO (..)
, negotiateInitiator
, negotiateResponder
, readExactBounded
)
import LibP2P.Noise.Framing (chunkPlaintext, encodeFrame)
import LibP2P.Noise.Handshake
( HandshakeResult (..)
, buildHandshakePayload
, decodeNoisePayload
, encodeNoisePayload
, getRemoteNoiseStaticKey
, initHandshakeInitiator
, initHandshakeInitiatorWithPrologue
, initHandshakeResponder
, initHandshakeResponderWithPrologue
, readHandshakeMsg
, verifyStaticKey
, writeHandshakeMsg
)
import LibP2P.Noise.Session
( NoiseSession
, decryptMessage
, encryptMessage
, mkNoiseSession
)
import LibP2P.Security.TLS
( TLSHandshakeResult (..)
, TLSRole (..)
, libp2pALPN
, performTLSHandshake
, tlsProtocolId
, yamuxProtocolId
)
import LibP2P.Switch.ResourceManager
( MemoryAccount (..)
, ResourceError
, ResourceManager
, ResourceScope
, releaseConnection
, reserveConnection
, reserveStream
, scopeMemoryAccount
, unlimitedMemoryAccount
)
import LibP2P.Switch.Types
( ConnState (..)
, Connection (..)
, Direction (..)
, MuxerSession (..)
, SwitchConfig (..)
, defaultSwitchConfig
)
import LibP2P.Transport
( ConnectionEndpoint (..)
, NativeMuxer (..)
, RawConnection (..)
)
import System.Timeout (timeout)
import qualified LibP2P.Crypto.Protobuf as Proto
import qualified LibP2P.Noise.Handshake as HS
readExact :: StreamIO -> Int -> IO ByteString
readExact :: StreamIO -> Int -> IO ByteString
readExact StreamIO
stream Int
n =
(String -> IO ByteString)
-> (ByteString -> IO ByteString)
-> Either String ByteString
-> IO ByteString
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> IO ByteString
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
(Either String ByteString -> IO ByteString)
-> IO (Either String ByteString) -> IO ByteString
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< StreamIO -> Int -> Int -> IO (Either String ByteString)
readExactBounded StreamIO
stream (Word32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
maxStreamWindowSize) Int
n
readFramedMessage :: StreamIO -> IO ByteString
readFramedMessage :: StreamIO -> IO ByteString
readFramedMessage StreamIO
stream = do
lenBytes <- StreamIO -> Int -> IO ByteString
readExact StreamIO
stream Int
2
let len = Word16 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Word16
readWord16BE ByteString
lenBytes) :: Int
if len == 0
then pure BS.empty
else readExact stream len
writeFramedMessage :: StreamIO -> ByteString -> IO ()
writeFramedMessage :: StreamIO -> ByteString -> IO ()
writeFramedMessage StreamIO
stream ByteString
msg =
(String -> IO ())
-> (ByteString -> IO ()) -> Either String ByteString -> IO ()
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (StreamIO -> ByteString -> IO ()
streamWrite StreamIO
stream) (ByteString -> Either String ByteString
encodeFrame ByteString
msg)
performStreamHandshake
:: KeyPair -> Direction -> StreamIO -> IO (NoiseSession, HandshakeResult)
performStreamHandshake :: KeyPair
-> Direction -> StreamIO -> IO (NoiseSession, HandshakeResult)
performStreamHandshake KeyPair
identityKP Direction
dir =
KeyPair
-> Direction
-> ByteString
-> StreamIO
-> IO (NoiseSession, HandshakeResult)
performStreamHandshakeWithPrologue KeyPair
identityKP Direction
dir ByteString
BS.empty
performStreamHandshakeWithPrologue
:: KeyPair -> Direction -> ByteString -> StreamIO -> IO (NoiseSession, HandshakeResult)
performStreamHandshakeWithPrologue :: KeyPair
-> Direction
-> ByteString
-> StreamIO
-> IO (NoiseSession, HandshakeResult)
performStreamHandshakeWithPrologue KeyPair
identityKP Direction
dir ByteString
prologue StreamIO
stream = case Direction
dir of
Direction
Outbound -> KeyPair
-> ByteString -> StreamIO -> IO (NoiseSession, HandshakeResult)
performInitiatorHandshake KeyPair
identityKP ByteString
prologue StreamIO
stream
Direction
Inbound -> KeyPair
-> ByteString -> StreamIO -> IO (NoiseSession, HandshakeResult)
performResponderHandshake KeyPair
identityKP ByteString
prologue StreamIO
stream
performInitiatorHandshake :: KeyPair -> ByteString -> StreamIO -> IO (NoiseSession, HandshakeResult)
performInitiatorHandshake :: KeyPair
-> ByteString -> StreamIO -> IO (NoiseSession, HandshakeResult)
performInitiatorHandshake KeyPair
identityKP ByteString
prologue StreamIO
stream = do
(hsState0, noiseStaticPub) <-
if ByteString -> Bool
BS.null ByteString
prologue
then KeyPair -> IO (HandshakeState, ByteString)
initHandshakeInitiator KeyPair
identityKP
else KeyPair -> ByteString -> IO (HandshakeState, ByteString)
initHandshakeInitiatorWithPrologue KeyPair
identityKP ByteString
prologue
(msg1, hsState1) <- either (fail . ("initiator msg1 write: " <>)) pure $
writeHandshakeMsg hsState0 BS.empty
writeFramedMessage stream msg1
msg2 <- readFramedMessage stream
(payload2, hsState2) <- either (fail . ("initiator msg2 read: " <>)) pure $
readHandshakeMsg hsState1 msg2
remoteNP <- either (fail . ("initiator decode payload: " <>)) pure $
decodeNoisePayload payload2
remotePubKey <- either (fail . ("initiator decode pubkey: " <>)) pure $
Proto.decodePublicKey (HS.npIdentityKey remoteNP)
let remotePeerId = PublicKey -> PeerId
fromPublicKey PublicKey
remotePubKey
case getRemoteNoiseStaticKey hsState2 of
Maybe ByteString
Nothing -> String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"performInitiatorHandshake: remote Noise static key unavailable after msg2"
Just ByteString
remoteNoisePub ->
if Bool -> Bool
not (PublicKey -> ByteString -> ByteString -> Bool
verifyStaticKey PublicKey
remotePubKey ByteString
remoteNoisePub (NoisePayload -> ByteString
HS.npIdentitySig NoisePayload
remoteNP))
then String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"performInitiatorHandshake: identity signature verification failed"
else () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
identPayload <- either (fail . ("initiator payload build: " <>)) pure $
encodeNoisePayload <$> buildHandshakePayload identityKP noiseStaticPub
(msg3, hsStateFinal) <- either (fail . ("initiator msg3 write: " <>)) pure $
writeHandshakeMsg hsState2 identPayload
writeFramedMessage stream msg3
let noiseSession = CacophonyState -> NoiseSession
mkNoiseSession (HandshakeState -> CacophonyState
HS.hsNoiseState HandshakeState
hsStateFinal)
pure (noiseSession, HandshakeResult remotePeerId remotePubKey)
performResponderHandshake :: KeyPair -> ByteString -> StreamIO -> IO (NoiseSession, HandshakeResult)
performResponderHandshake :: KeyPair
-> ByteString -> StreamIO -> IO (NoiseSession, HandshakeResult)
performResponderHandshake KeyPair
identityKP ByteString
prologue StreamIO
stream = do
(hsState0, noiseStaticPub) <-
if ByteString -> Bool
BS.null ByteString
prologue
then KeyPair -> IO (HandshakeState, ByteString)
initHandshakeResponder KeyPair
identityKP
else KeyPair -> ByteString -> IO (HandshakeState, ByteString)
initHandshakeResponderWithPrologue KeyPair
identityKP ByteString
prologue
msg1 <- readFramedMessage stream
(_payload1, hsState1) <- either (fail . ("responder msg1 read: " <>)) pure $
readHandshakeMsg hsState0 msg1
identPayload <- either (fail . ("responder payload build: " <>)) pure $
encodeNoisePayload <$> buildHandshakePayload identityKP noiseStaticPub
(msg2, hsState2) <- either (fail . ("responder msg2 write: " <>)) pure $
writeHandshakeMsg hsState1 identPayload
writeFramedMessage stream msg2
msg3 <- readFramedMessage stream
(payload3, hsStateFinal) <- either (fail . ("responder msg3 read: " <>)) pure $
readHandshakeMsg hsState2 msg3
remoteNP <- either (fail . ("responder decode payload: " <>)) pure $
decodeNoisePayload payload3
remotePubKey <- either (fail . ("responder decode pubkey: " <>)) pure $
Proto.decodePublicKey (HS.npIdentityKey remoteNP)
let remotePeerId = PublicKey -> PeerId
fromPublicKey PublicKey
remotePubKey
case getRemoteNoiseStaticKey hsStateFinal of
Maybe ByteString
Nothing -> String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"performResponderHandshake: remote Noise static key unavailable after msg3"
Just ByteString
remoteNoisePub ->
if Bool -> Bool
not (PublicKey -> ByteString -> ByteString -> Bool
verifyStaticKey PublicKey
remotePubKey ByteString
remoteNoisePub (NoisePayload -> ByteString
HS.npIdentitySig NoisePayload
remoteNP))
then String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"performResponderHandshake: identity signature verification failed"
else () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
let noiseSession = CacophonyState -> NoiseSession
mkNoiseSession (HandshakeState -> CacophonyState
HS.hsNoiseState HandshakeState
hsStateFinal)
pure (noiseSession, HandshakeResult remotePeerId remotePubKey)
noiseSessionToStreamIO
:: IORef NoiseSession
-> IORef NoiseSession
-> IORef ByteString
-> StreamIO
-> StreamIO
noiseSessionToStreamIO :: IORef NoiseSession
-> IORef NoiseSession -> IORef ByteString -> StreamIO -> StreamIO
noiseSessionToStreamIO IORef NoiseSession
sendRef IORef NoiseSession
recvRef IORef ByteString
bufRef =
MemoryAccount
-> IORef NoiseSession
-> IORef NoiseSession
-> IORef ByteString
-> StreamIO
-> StreamIO
noiseSessionToManagedStreamIO MemoryAccount
unlimitedMemoryAccount IORef NoiseSession
sendRef IORef NoiseSession
recvRef IORef ByteString
bufRef
noiseSessionToManagedStreamIO
:: MemoryAccount
-> IORef NoiseSession
-> IORef NoiseSession
-> IORef ByteString
-> StreamIO
-> StreamIO
noiseSessionToManagedStreamIO :: MemoryAccount
-> IORef NoiseSession
-> IORef NoiseSession
-> IORef ByteString
-> StreamIO
-> StreamIO
noiseSessionToManagedStreamIO MemoryAccount
account IORef NoiseSession
sendRef IORef NoiseSession
recvRef IORef ByteString
bufRef StreamIO
rawIO = StreamIO
{ streamWrite :: ByteString -> IO ()
streamWrite = MemoryAccount
-> IORef NoiseSession -> StreamIO -> ByteString -> IO ()
encryptAndWrite MemoryAccount
account IORef NoiseSession
sendRef StreamIO
rawIO
, streamReadByte :: IO Word8
streamReadByte = MemoryAccount
-> IORef NoiseSession -> IORef ByteString -> StreamIO -> IO Word8
decryptAndReadByte MemoryAccount
account IORef NoiseSession
recvRef IORef ByteString
bufRef StreamIO
rawIO
, streamReadChunk :: Int -> IO ByteString
streamReadChunk = MemoryAccount
-> IORef NoiseSession
-> IORef ByteString
-> StreamIO
-> Int
-> IO ByteString
decryptAndReadChunk MemoryAccount
account IORef NoiseSession
recvRef IORef ByteString
bufRef StreamIO
rawIO
, streamClose :: IO ()
streamClose = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
}
encryptAndWrite
:: MemoryAccount -> IORef NoiseSession -> StreamIO -> ByteString -> IO ()
encryptAndWrite :: MemoryAccount
-> IORef NoiseSession -> StreamIO -> ByteString -> IO ()
encryptAndWrite MemoryAccount
account IORef NoiseSession
sendRef StreamIO
rawIO ByteString
plaintext =
(ByteString -> IO ()) -> [ByteString] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ ByteString -> IO ()
encryptChunk (ByteString -> [ByteString]
chunkPlaintext ByteString
plaintext)
where
encryptChunk :: ByteString -> IO ()
encryptChunk ByteString
chunk = ((forall a. IO a -> IO a) -> IO ()) -> IO ()
forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
mask (((forall a. IO a -> IO a) -> IO ()) -> IO ())
-> ((forall a. IO a -> IO a) -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restore -> do
let cipherBytes :: Int
cipherBytes = ByteString -> Int
BS.length ByteString
chunk Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
16
MemoryAccount -> Int -> IO ()
reserveMemory MemoryAccount
account Int
cipherBytes
IO () -> IO ()
forall a. IO a -> IO a
restore (ByteString -> IO ()
encryptAndSend ByteString
chunk) IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO a
`finally` MemoryAccount -> Int -> IO ()
releaseMemory MemoryAccount
account Int
cipherBytes
encryptAndSend :: ByteString -> IO ()
encryptAndSend ByteString
chunk = do
sess <- IORef NoiseSession -> IO NoiseSession
forall a. IORef a -> IO a
readIORef IORef NoiseSession
sendRef
case encryptMessage sess chunk of
Left String
err -> 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
"encryptAndWrite: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
err
Right (ByteString
ct, NoiseSession
sess') -> do
IORef NoiseSession -> NoiseSession -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef NoiseSession
sendRef NoiseSession
sess'
StreamIO -> ByteString -> IO ()
writeFramedMessage StreamIO
rawIO ByteString
ct
nextPlaintext
:: MemoryAccount
-> IORef NoiseSession
-> IORef ByteString
-> StreamIO
-> IO ByteString
nextPlaintext :: MemoryAccount
-> IORef NoiseSession
-> IORef ByteString
-> StreamIO
-> IO ByteString
nextPlaintext MemoryAccount
account IORef NoiseSession
recvRef IORef ByteString
bufRef StreamIO
rawIO = do
lenBytes <- StreamIO -> Int -> IO ByteString
readExact StreamIO
rawIO Int
2
let cipherBytes = Word16 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Word16
readWord16BE ByteString
lenBytes)
if cipherBytes == 0
then nextPlaintext account recvRef bufRef rawIO
else readAndDecrypt cipherBytes
where
readAndDecrypt :: Int -> IO ByteString
readAndDecrypt Int
cipherBytes = ((forall a. IO a -> IO a) -> IO ByteString) -> IO ByteString
forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
mask (((forall a. IO a -> IO a) -> IO ByteString) -> IO ByteString)
-> ((forall a. IO a -> IO a) -> IO ByteString) -> IO ByteString
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restore -> do
MemoryAccount -> Int -> IO ()
reserveMemory MemoryAccount
account Int
cipherBytes
ct <- IO ByteString -> IO ByteString
forall a. IO a -> IO a
restore (StreamIO -> Int -> IO ByteString
readExact StreamIO
rawIO Int
cipherBytes)
IO ByteString -> IO () -> IO ByteString
forall a b. IO a -> IO b -> IO a
`onException` MemoryAccount -> Int -> IO ()
releaseMemory MemoryAccount
account Int
cipherBytes
result <- decryptPayload ct
`onException` releaseMemory account cipherBytes
releaseMemory account cipherBytes
case result of
Maybe ByteString
Nothing -> MemoryAccount
-> IORef NoiseSession
-> IORef ByteString
-> StreamIO
-> IO ByteString
nextPlaintext MemoryAccount
account IORef NoiseSession
recvRef IORef ByteString
bufRef StreamIO
rawIO
Just ByteString
pt -> IORef ByteString -> ByteString -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef ByteString
bufRef ByteString
pt IO () -> IO ByteString -> IO ByteString
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
pt
decryptPayload :: ByteString -> IO (Maybe ByteString)
decryptPayload ByteString
ct = do
sess <- IORef NoiseSession -> IO NoiseSession
forall a. IORef a -> IO a
readIORef IORef NoiseSession
recvRef
case decryptMessage sess ct of
Left String
err -> String -> IO (Maybe ByteString)
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO (Maybe ByteString))
-> String -> IO (Maybe ByteString)
forall a b. (a -> b) -> a -> b
$ String
"nextPlaintext: decrypt failed: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
err
Right (ByteString
pt, NoiseSession
sess') -> do
IORef NoiseSession -> NoiseSession -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef NoiseSession
recvRef NoiseSession
sess'
if ByteString -> Bool
BS.null ByteString
pt
then Maybe ByteString -> IO (Maybe ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe ByteString
forall a. Maybe a
Nothing
else MemoryAccount -> Int -> IO ()
reserveMemory MemoryAccount
account (ByteString -> Int
BS.length ByteString
pt) IO () -> IO (Maybe ByteString) -> IO (Maybe ByteString)
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Maybe ByteString -> IO (Maybe ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
pt)
reserveMemory :: MemoryAccount -> Int -> IO ()
reserveMemory :: MemoryAccount -> Int -> IO ()
reserveMemory MemoryAccount
account Int
bytes = do
reserved <- STM (Either ResourceError ()) -> IO (Either ResourceError ())
forall a. STM a -> IO a
atomically (STM (Either ResourceError ()) -> IO (Either ResourceError ()))
-> STM (Either ResourceError ()) -> IO (Either ResourceError ())
forall a b. (a -> b) -> a -> b
$ MemoryAccount -> Int -> STM (Either ResourceError ())
maReserve MemoryAccount
account Int
bytes
either throwIO pure reserved
releaseMemory :: MemoryAccount -> Int -> IO ()
releaseMemory :: MemoryAccount -> Int -> IO ()
releaseMemory MemoryAccount
account Int
bytes = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ MemoryAccount -> Int -> STM ()
maRelease MemoryAccount
account Int
bytes
decryptAndReadByte
:: MemoryAccount -> IORef NoiseSession -> IORef ByteString -> StreamIO
-> IO Word8
decryptAndReadByte :: MemoryAccount
-> IORef NoiseSession -> IORef ByteString -> StreamIO -> IO Word8
decryptAndReadByte MemoryAccount
account IORef NoiseSession
recvRef IORef ByteString
bufRef StreamIO
rawIO = do
buf <- IORef ByteString -> IO ByteString
forall a. IORef a -> IO a
readIORef IORef ByteString
bufRef
bs <- if BS.null buf
then nextPlaintext account recvRef bufRef rawIO
else pure buf
BS.head <$> consumeAccountedBuffer account bufRef 1 bs
decryptAndReadChunk
:: MemoryAccount -> IORef NoiseSession -> IORef ByteString -> StreamIO
-> Int -> IO ByteString
decryptAndReadChunk :: MemoryAccount
-> IORef NoiseSession
-> IORef ByteString
-> StreamIO
-> Int
-> IO ByteString
decryptAndReadChunk MemoryAccount
account IORef NoiseSession
recvRef IORef ByteString
bufRef StreamIO
rawIO Int
n = do
buf <- IORef ByteString -> IO ByteString
forall a. IORef a -> IO a
readIORef IORef ByteString
bufRef
bs <- if BS.null buf
then nextPlaintext account recvRef bufRef rawIO
else pure buf
consumeAccountedBuffer account bufRef n bs
consumeAccountedBuffer
:: MemoryAccount -> IORef ByteString -> Int -> ByteString -> IO ByteString
consumeAccountedBuffer :: MemoryAccount
-> IORef ByteString -> Int -> ByteString -> IO ByteString
consumeAccountedBuffer MemoryAccount
account IORef ByteString
bufRef Int
n ByteString
bs = IO ByteString -> IO ByteString
forall a. IO a -> IO a
mask_ (IO ByteString -> IO ByteString) -> IO ByteString -> IO ByteString
forall a b. (a -> b) -> a -> b
$ do
let (ByteString
front, ByteString
rest) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
n ByteString
bs
IORef ByteString -> ByteString -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef ByteString
bufRef ByteString
rest
MemoryAccount -> Int -> IO ()
releaseMemory MemoryAccount
account (ByteString -> Int
BS.length ByteString
front)
ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
front
goAwayFlushTimeoutUs :: Int
goAwayFlushTimeoutUs :: Int
goAwayFlushTimeoutUs = Int
200000
yamuxToMuxerSession :: YamuxSession -> IO () -> IO MuxerSession
yamuxToMuxerSession :: YamuxSession -> IO () -> IO MuxerSession
yamuxToMuxerSession YamuxSession
yamuxSess IO ()
closeTransport = do
sendLoopA <- IO () -> IO (Async ())
forall a. IO a -> IO (Async a)
async (YamuxSession -> IO ()
sendLoop YamuxSession
yamuxSess)
recvLoopA <- async (recvLoop yamuxSess)
keepaliveA <- async $ do
result <- keepaliveLoop yamuxSess
case result of
Left YamuxError
_ -> Async () -> IO ()
forall a. Async a -> IO ()
cancel Async ()
recvLoopA
Right () -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
pure MuxerSession
{ muxOpenStream = \MemoryAccount
account -> do
result <- YamuxSession -> MemoryAccount -> IO (Either YamuxError YamuxStream)
Yamux.openStreamWithAccount YamuxSession
yamuxSess MemoryAccount
account
case result of
Right YamuxStream
stream -> MemoryAccount -> YamuxStream -> IO StreamIO
yamuxStreamToStreamIO MemoryAccount
account YamuxStream
stream
Left YamuxError
err -> String -> IO StreamIO
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO StreamIO) -> String -> IO StreamIO
forall a b. (a -> b) -> a -> b
$ String
"muxOpenStream: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> YamuxError -> String
forall a. Show a => a -> String
show YamuxError
err
, muxAcceptStream = do
result <- race (waitCatch recvLoopA) (Yamux.acceptStream yamuxSess)
case result of
Left Either SomeException ()
_ -> String -> IO StreamIO
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"muxAcceptStream: session terminated"
Right (Right YamuxStream
stream) ->
MemoryAccount -> YamuxStream -> IO StreamIO
yamuxStreamToStreamIO (YamuxStream -> MemoryAccount
ysMemoryAccount YamuxStream
stream) YamuxStream
stream
Right (Left YamuxError
err) -> String -> IO StreamIO
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO StreamIO) -> String -> IO StreamIO
forall a b. (a -> b) -> a -> b
$ String
"muxAcceptStream: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> YamuxError -> String
forall a. Show a => a -> String
show YamuxError
err
, muxClose = do
closeSession yamuxSess
_ <- timeout goAwayFlushTimeoutUs $ atomically $ do
empty <- isEmptyTQueue (ysessSendCh yamuxSess)
unless empty retry
cancel keepaliveA
cancel sendLoopA
cancel recvLoopA
closeTransport `catch` \(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
}
yamuxStreamToStreamIO :: MemoryAccount -> YamuxStream -> IO StreamIO
yamuxStreamToStreamIO :: MemoryAccount -> YamuxStream -> IO StreamIO
yamuxStreamToStreamIO MemoryAccount
account YamuxStream
yamuxStream = do
readBuf <- ByteString -> IO (IORef ByteString)
forall a. a -> IO (IORef a)
newIORef ByteString
BS.empty
let readChunk Int
n = IO ByteString -> IO ByteString
forall a. IO a -> IO a
mask_ (IO ByteString -> IO ByteString) -> IO ByteString -> IO ByteString
forall a b. (a -> b) -> a -> b
$ do
buffered <- IORef ByteString -> IO ByteString
forall a. IORef a -> IO a
readIORef IORef ByteString
readBuf
chunk <- if BS.null buffered
then nextRetainedChunk
else pure buffered
let (front, rest) = BS.splitAt n chunk
writeIORef readBuf rest
releaseMemory account (BS.length front)
pure front
nextRetainedChunk = do
result <- YamuxStream -> IO (Either YamuxError ByteString)
streamReadRetained YamuxStream
yamuxStream
case result of
Left YamuxError
err -> String -> IO ByteString
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO ByteString) -> String -> IO ByteString
forall a b. (a -> b) -> a -> b
$ String
"yamuxStreamRead: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> YamuxError -> String
forall a. Show a => a -> String
show YamuxError
err
Right ByteString
chunk
| ByteString -> Bool
BS.null ByteString
chunk -> String -> IO ByteString
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"yamuxStreamRead: empty chunk"
| Bool
otherwise -> ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
chunk
releaseBuffered = IO () -> IO ()
forall a. IO a -> IO a
mask_ (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
buffered <- IORef ByteString -> IO ByteString
forall a. IORef a -> IO a
readIORef IORef ByteString
readBuf
writeIORef readBuf BS.empty
releaseMemory account (BS.length buffered)
pure StreamIO
{ streamWrite = \ByteString
bs -> do
result <- YamuxStream -> ByteString -> IO (Either YamuxError ())
YS.streamWrite YamuxStream
yamuxStream ByteString
bs
case result of
Right () -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
Left YamuxError
err -> 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
"yamuxStreamWrite: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> YamuxError -> String
forall a. Show a => a -> String
show YamuxError
err
, streamReadByte = BS.head <$> readChunk 1
, streamReadChunk = readChunk
, streamClose = do
_ <- YS.streamClose yamuxStream
releaseBuffered
}
upgradeAs :: ResourceManager -> Direction -> KeyPair -> RawConnection -> IO Connection
upgradeAs :: ResourceManager
-> Direction -> KeyPair -> RawConnection -> IO Connection
upgradeAs = YamuxConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeAsWithConfig YamuxConfig
defaultYamuxConfig
upgradeAsWithConfig
:: YamuxConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeAsWithConfig :: YamuxConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeAsWithConfig YamuxConfig
yamuxConfig ResourceManager
rm =
YamuxConfig
-> ResourceManager
-> [ProtocolId]
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeAsWithOptions YamuxConfig
yamuxConfig ResourceManager
rm (SwitchConfig -> [ProtocolId]
scSecurityProtocols SwitchConfig
defaultSwitchConfig)
upgradeWithSwitchConfig
:: SwitchConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeWithSwitchConfig :: SwitchConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeWithSwitchConfig SwitchConfig
config ResourceManager
rm =
YamuxConfig
-> ResourceManager
-> [ProtocolId]
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeAsWithOptions
(SwitchConfig -> YamuxConfig
scYamuxConfig SwitchConfig
config)
ResourceManager
rm
(SwitchConfig -> [ProtocolId]
scSecurityProtocols SwitchConfig
config)
upgradeAsWithSecurityProtocols
:: ResourceManager
-> [ProtocolId]
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeAsWithSecurityProtocols :: ResourceManager
-> [ProtocolId]
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeAsWithSecurityProtocols ResourceManager
rm =
YamuxConfig
-> ResourceManager
-> [ProtocolId]
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeAsWithOptions YamuxConfig
defaultYamuxConfig ResourceManager
rm
upgradeAsWithOptions
:: YamuxConfig
-> ResourceManager
-> [ProtocolId]
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeAsWithOptions :: YamuxConfig
-> ResourceManager
-> [ProtocolId]
-> Direction
-> KeyPair
-> RawConnection
-> IO Connection
upgradeAsWithOptions YamuxConfig
yamuxConfig ResourceManager
rm [ProtocolId]
securityProtocols Direction
dir KeyPair
identityKP RawConnection
rawConn =
case RawConnection -> ConnectionEndpoint
rcEndpoint RawConnection
rawConn of
ByteStreamEndpoint StreamIO
rawIO ->
YamuxConfig
-> ResourceManager
-> [ProtocolId]
-> Direction
-> KeyPair
-> RawConnection
-> StreamIO
-> IO Connection
upgradeByteStream YamuxConfig
yamuxConfig ResourceManager
rm [ProtocolId]
securityProtocols Direction
dir KeyPair
identityKP RawConnection
rawConn StreamIO
rawIO
NativeMuxerEndpoint NativeMuxer
native -> ResourceManager
-> Direction -> RawConnection -> NativeMuxer -> IO Connection
nativeToConnection ResourceManager
rm Direction
dir RawConnection
rawConn NativeMuxer
native
data MuxerNegotiation
= NegotiateMuxer
| InlinedMuxer ProtocolId
upgradeByteStream
:: YamuxConfig
-> ResourceManager
-> [ProtocolId]
-> Direction
-> KeyPair
-> RawConnection
-> StreamIO
-> IO Connection
upgradeByteStream :: YamuxConfig
-> ResourceManager
-> [ProtocolId]
-> Direction
-> KeyPair
-> RawConnection
-> StreamIO
-> IO Connection
upgradeByteStream YamuxConfig
yamuxConfig ResourceManager
rm [ProtocolId]
securityProtocols Direction
dir KeyPair
identityKP RawConnection
rawConn StreamIO
rawIO = do
let isServer :: Bool
isServer = Direction
dir Direction -> Direction -> Bool
forall a. Eq a => a -> a -> Bool
== Direction
Inbound
negotiate :: StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiate = if Bool
isServer then StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiateResponder else StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiateInitiator
role :: String
role = if Bool
isServer then String
"upgradeInbound" else String
"upgradeOutbound"
secResult <- StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiate StreamIO
rawIO [ProtocolId]
securityProtocols
case secResult of
Accepted ProtocolId
"/noise" ->
YamuxConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> StreamIO
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO Connection
upgradeNoiseChannel YamuxConfig
yamuxConfig ResourceManager
rm Direction
dir KeyPair
identityKP RawConnection
rawConn StreamIO
rawIO StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiate String
role
Accepted ProtocolId
protocol
| ProtocolId
protocol ProtocolId -> ProtocolId -> Bool
forall a. Eq a => a -> a -> Bool
== ProtocolId
tlsProtocolId ->
YamuxConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> StreamIO
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO Connection
upgradeTLSChannel YamuxConfig
yamuxConfig ResourceManager
rm Direction
dir KeyPair
identityKP RawConnection
rawConn StreamIO
rawIO StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiate String
role
| Bool
otherwise -> String -> IO Connection
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String
role String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
": unsupported security protocol")
NegotiationResult
NoProtocol -> String -> IO Connection
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String
role String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
": security protocol negotiation failed")
upgradeNoiseChannel
:: YamuxConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> StreamIO
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO Connection
upgradeNoiseChannel :: YamuxConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> StreamIO
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO Connection
upgradeNoiseChannel YamuxConfig
yamuxConfig ResourceManager
rm Direction
dir KeyPair
identityKP RawConnection
rawConn StreamIO
rawIO StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiate String
role = do
(noiseSess, HandshakeResult remotePeerId _remotePK) <-
KeyPair
-> Direction -> StreamIO -> IO (NoiseSession, HandshakeResult)
performStreamHandshake KeyPair
identityKP Direction
dir StreamIO
rawIO
connScope <- acquireConnectionScope rm remotePeerId dir
sendRef <- newIORef noiseSess
recvRef <- newIORef noiseSess
bufRef <- newIORef BS.empty
let encryptedIO = MemoryAccount
-> IORef NoiseSession
-> IORef NoiseSession
-> IORef ByteString
-> StreamIO
-> StreamIO
noiseSessionToManagedStreamIO
(ResourceManager -> ResourceScope -> MemoryAccount
scopeMemoryAccount ResourceManager
rm ResourceScope
connScope) IORef NoiseSession
sendRef IORef NoiseSession
recvRef IORef ByteString
bufRef StreamIO
rawIO
finishSecureUpgrade yamuxConfig rm dir rawConn connScope remotePeerId "/noise"
encryptedIO (pure ()) NegotiateMuxer negotiate role
`onException` atomically (releaseConnection rm connScope)
upgradeTLSChannel
:: YamuxConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> StreamIO
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO Connection
upgradeTLSChannel :: YamuxConfig
-> ResourceManager
-> Direction
-> KeyPair
-> RawConnection
-> StreamIO
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO Connection
upgradeTLSChannel YamuxConfig
yamuxConfig ResourceManager
rm Direction
dir KeyPair
identityKP RawConnection
rawConn StreamIO
rawIO StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiate String
role = do
tlsResult <- KeyPair -> TLSRole -> StreamIO -> IO TLSHandshakeResult
performTLSHandshake KeyPair
identityKP TLSRole
tlsRole StreamIO
rawIO
muxerNegotiation <- either fail pure (tlsMuxerNegotiation tlsResult)
let remotePeerId = TLSHandshakeResult -> PeerId
tlsRemotePeerId TLSHandshakeResult
tlsResult
closeTLS = TLSHandshakeResult -> IO ()
tlsClose TLSHandshakeResult
tlsResult
connScope <- acquireConnectionScope rm remotePeerId dir
`onException` closeTLS
finishSecureUpgrade yamuxConfig rm dir rawConn connScope remotePeerId tlsProtocolId
(tlsStream tlsResult) closeTLS muxerNegotiation negotiate role
`onException` (closeTLS `finally` atomically (releaseConnection rm connScope))
where
tlsRole :: TLSRole
tlsRole = if Direction
dir Direction -> Direction -> Bool
forall a. Eq a => a -> a -> Bool
== Direction
Inbound then TLSRole
TLSServer else TLSRole
TLSClient
tlsMuxerNegotiation :: TLSHandshakeResult -> Either String MuxerNegotiation
tlsMuxerNegotiation :: TLSHandshakeResult -> Either String MuxerNegotiation
tlsMuxerNegotiation TLSHandshakeResult
result = case TLSHandshakeResult -> Maybe ByteString
tlsNegotiatedALPN TLSHandshakeResult
result of
Just ByteString
protocol
| ByteString
protocol ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
"/yamux/1.0.0" -> MuxerNegotiation -> Either String MuxerNegotiation
forall a b. b -> Either a b
Right (ProtocolId -> MuxerNegotiation
InlinedMuxer ProtocolId
yamuxProtocolId)
| ByteString
protocol ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
libp2pALPN -> MuxerNegotiation -> Either String MuxerNegotiation
forall a b. b -> Either a b
Right MuxerNegotiation
NegotiateMuxer
| Bool
otherwise -> String -> Either String MuxerNegotiation
forall a b. a -> Either a b
Left String
"TLS handshake selected an unsupported ALPN protocol"
Maybe ByteString
Nothing -> String -> Either String MuxerNegotiation
forall a b. a -> Either a b
Left String
"TLS handshake did not negotiate ALPN"
finishSecureUpgrade
:: YamuxConfig
-> ResourceManager
-> Direction
-> RawConnection
-> ResourceScope
-> PeerId
-> ProtocolId
-> StreamIO
-> IO ()
-> MuxerNegotiation
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO Connection
finishSecureUpgrade :: YamuxConfig
-> ResourceManager
-> Direction
-> RawConnection
-> ResourceScope
-> PeerId
-> ProtocolId
-> StreamIO
-> IO ()
-> MuxerNegotiation
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO Connection
finishSecureUpgrade YamuxConfig
yamuxConfig ResourceManager
rm Direction
dir RawConnection
rawConn ResourceScope
connScope PeerId
remotePeerId ProtocolId
securityProtocol
StreamIO
encryptedIO IO ()
closeSecurity MuxerNegotiation
muxerNegotiation StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiate String
role = do
muxerProtocol <- StreamIO
-> MuxerNegotiation
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO ProtocolId
resolveMuxer StreamIO
encryptedIO MuxerNegotiation
muxerNegotiation StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiate String
role
let connectionMemory = ResourceManager -> ResourceScope -> MemoryAccount
scopeMemoryAccount ResourceManager
rm ResourceScope
connScope
closeOwnedTransport = IO ()
closeSecurity IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO a
`finally`
(RawConnection -> IO ()
rcClose RawConnection
rawConn IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO a
`finally` STM () -> IO ()
forall a. STM a -> IO a
atomically (ResourceManager -> ResourceScope -> STM ()
releaseConnection ResourceManager
rm ResourceScope
connScope))
yamuxSess <- newManagedSessionWithConfig yamuxConfig
(if dir == Inbound then RoleServer else RoleClient)
connectionMemory
(newStreamMemoryAccount rm connScope Inbound)
(newStreamMemoryAccount rm connScope Outbound)
(streamWrite encryptedIO)
(readExact encryptedIO)
muxer <- yamuxToMuxerSession yamuxSess closeOwnedTransport
stateVar <- newTVarIO ConnOpen
pure Connection
{ connPeerId = remotePeerId
, connDirection = dir
, connLocalAddr = rcLocalAddr rawConn
, connRemoteAddr = rcRemoteAddr rawConn
, connSecurity = securityProtocol
, connMuxer = muxerProtocol
, connSession = muxer
, connState = stateVar
, connResourceScope = connScope
, connRelayLimit = rcRelayLimit rawConn
}
resolveMuxer
:: StreamIO
-> MuxerNegotiation
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO ProtocolId
resolveMuxer :: StreamIO
-> MuxerNegotiation
-> (StreamIO -> [ProtocolId] -> IO NegotiationResult)
-> String
-> IO ProtocolId
resolveMuxer StreamIO
_ (InlinedMuxer ProtocolId
protocol) StreamIO -> [ProtocolId] -> IO NegotiationResult
_ String
_ = ProtocolId -> IO ProtocolId
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ProtocolId
protocol
resolveMuxer StreamIO
encryptedIO MuxerNegotiation
NegotiateMuxer StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiate String
role = do
muxResult <- StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiate StreamIO
encryptedIO [ProtocolId
yamuxProtocolId]
case muxResult of
Accepted ProtocolId
protocol -> ProtocolId -> IO ProtocolId
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ProtocolId
protocol
NegotiationResult
NoProtocol -> String -> IO ProtocolId
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String
role String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
": /yamux/1.0.0 negotiation failed")
nativeToConnection
:: ResourceManager -> Direction -> RawConnection -> NativeMuxer
-> IO Connection
nativeToConnection :: ResourceManager
-> Direction -> RawConnection -> NativeMuxer -> IO Connection
nativeToConnection ResourceManager
rm Direction
dir RawConnection
rawConn NativeMuxer
native = do
connScope <- ResourceManager -> PeerId -> Direction -> IO ResourceScope
acquireConnectionScope ResourceManager
rm (NativeMuxer -> PeerId
nativePeerId NativeMuxer
native) Direction
dir
stateVar <- newTVarIO ConnOpen
let closeOwnedMuxer = NativeMuxer -> IO ()
nativeClose NativeMuxer
native
IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO a
`finally` STM () -> IO ()
forall a. STM a -> IO a
atomically (ResourceManager -> ResourceScope -> STM ()
releaseConnection ResourceManager
rm ResourceScope
connScope)
muxer = MuxerSession
{ muxOpenStream :: MemoryAccount -> IO StreamIO
muxOpenStream = \MemoryAccount
account ->
MemoryAccount -> IO StreamIO -> IO StreamIO
openNativeStream MemoryAccount
account (NativeMuxer -> IO StreamIO
nativeOpenStream NativeMuxer
native)
, muxAcceptStream :: IO StreamIO
muxAcceptStream = ResourceManager
-> ResourceScope -> Direction -> IO StreamIO -> IO StreamIO
reserveAndOpenNativeStream
ResourceManager
rm ResourceScope
connScope Direction
Inbound (NativeMuxer -> IO StreamIO
nativeAcceptStream NativeMuxer
native)
, muxClose :: IO ()
muxClose = IO ()
closeOwnedMuxer
}
pure Connection
{ connPeerId = nativePeerId native
, connDirection = dir
, connLocalAddr = rcLocalAddr rawConn
, connRemoteAddr = rcRemoteAddr rawConn
, connSecurity = nativeSecurity native
, connMuxer = nativeMuxerProtocol native
, connSession = muxer
, connState = stateVar
, connResourceScope = connScope
, connRelayLimit = rcRelayLimit rawConn
}
openNativeStream :: MemoryAccount -> IO StreamIO -> IO StreamIO
openNativeStream :: MemoryAccount -> IO StreamIO -> IO StreamIO
openNativeStream MemoryAccount
account IO StreamIO
open = do
stream <- IO StreamIO
open IO StreamIO -> IO () -> IO StreamIO
forall a b. IO a -> IO b -> IO a
`onException` STM () -> IO ()
forall a. STM a -> IO a
atomically (MemoryAccount -> STM ()
maClose MemoryAccount
account)
pure stream
{ streamClose = streamClose stream `finally` atomically (maClose account)
}
reserveAndOpenNativeStream
:: ResourceManager -> ResourceScope -> Direction -> IO StreamIO
-> IO StreamIO
reserveAndOpenNativeStream :: ResourceManager
-> ResourceScope -> Direction -> IO StreamIO -> IO StreamIO
reserveAndOpenNativeStream ResourceManager
rm ResourceScope
connection Direction
direction IO StreamIO
open = do
streamScope <- STM (Either ResourceError ResourceScope)
-> IO (Either ResourceError ResourceScope)
forall a. STM a -> IO a
atomically (ResourceManager
-> ResourceScope
-> Direction
-> STM (Either ResourceError ResourceScope)
reserveStream ResourceManager
rm ResourceScope
connection Direction
direction)
IO (Either ResourceError ResourceScope)
-> (Either ResourceError ResourceScope -> IO ResourceScope)
-> IO ResourceScope
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (ResourceError -> IO ResourceScope)
-> (ResourceScope -> IO ResourceScope)
-> Either ResourceError ResourceScope
-> IO ResourceScope
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ResourceError -> IO ResourceScope
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO ResourceScope -> IO ResourceScope
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
openNativeStream (scopeMemoryAccount rm streamScope) open
newStreamMemoryAccount
:: ResourceManager -> ResourceScope -> Direction
-> STM (Either ResourceError MemoryAccount)
newStreamMemoryAccount :: ResourceManager
-> ResourceScope
-> Direction
-> STM (Either ResourceError MemoryAccount)
newStreamMemoryAccount ResourceManager
rm ResourceScope
connection Direction
direction = do
reserved <- ResourceManager
-> ResourceScope
-> Direction
-> STM (Either ResourceError ResourceScope)
reserveStream ResourceManager
rm ResourceScope
connection Direction
direction
pure $ scopeMemoryAccount rm <$> reserved
acquireConnectionScope
:: ResourceManager -> PeerId -> Direction -> IO ResourceScope
acquireConnectionScope :: ResourceManager -> PeerId -> Direction -> IO ResourceScope
acquireConnectionScope ResourceManager
rm PeerId
pid Direction
direction =
STM (Either ResourceError ResourceScope)
-> IO (Either ResourceError ResourceScope)
forall a. STM a -> IO a
atomically (ResourceManager
-> PeerId -> Direction -> STM (Either ResourceError ResourceScope)
reserveConnection ResourceManager
rm PeerId
pid Direction
direction) IO (Either ResourceError ResourceScope)
-> (Either ResourceError ResourceScope -> IO ResourceScope)
-> IO ResourceScope
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (ResourceError -> IO ResourceScope)
-> (ResourceScope -> IO ResourceScope)
-> Either ResourceError ResourceScope
-> IO ResourceScope
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ResourceError -> IO ResourceScope
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO ResourceScope -> IO ResourceScope
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
upgradeOutbound :: ResourceManager -> KeyPair -> RawConnection -> IO Connection
upgradeOutbound :: ResourceManager -> KeyPair -> RawConnection -> IO Connection
upgradeOutbound ResourceManager
rm = ResourceManager
-> Direction -> KeyPair -> RawConnection -> IO Connection
upgradeAs ResourceManager
rm Direction
Outbound
upgradeInbound :: ResourceManager -> KeyPair -> RawConnection -> IO Connection
upgradeInbound :: ResourceManager -> KeyPair -> RawConnection -> IO Connection
upgradeInbound ResourceManager
rm = ResourceManager
-> Direction -> KeyPair -> RawConnection -> IO Connection
upgradeAs ResourceManager
rm Direction
Inbound