module LibP2P.Transport.WebSocket
( WebSocketConfig (..)
, defaultWebSocketConfig
, webSocketServerParams
, newWebSocketTransport
, newWebSocketTransportWithConfig
, canDialWebSocket
) where
import Control.Concurrent.MVar
( MVar
, modifyMVar
, modifyMVar_
, newMVar
, withMVar
)
import Control.Exception
( IOException
, SomeException
, catch
, displayException
, onException
, try
)
import Control.Monad (unless)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Maybe (isJust)
import qualified Data.Text as Text
import Data.Word (Word16)
import LibP2P.Multiaddr (Multiaddr (..))
import LibP2P.Multiaddr.Protocol (Protocol (..))
import LibP2P.MultistreamSelect.Negotiation (StreamIO (..))
import LibP2P.Transport
( ConnectionEndpoint (..)
, Listener (..)
, RawConnection (..)
, Transport (..)
)
import LibP2P.Transport.TCP
( multiaddrToHostPort
, newTCPTransport
, sockAddrToMultiaddr
)
import qualified Network.Socket as Socket
import Network.TLS
( Backend (..)
, ClientParams (..)
, Context
, Credential
, Credentials (..)
, ServerParams (..)
, Shared (..)
, bye
, contextNew
, defaultParamsClient
, defaultParamsServer
, handshake
, recvData
, sendData
)
import qualified Network.WebSockets as WebSocket
import qualified Network.WebSockets.Stream as WebSocketStream
import System.X509 (getSystemCertificateStore)
data WebSocketConfig = WebSocketConfig
{ WebSocketConfig -> [Char] -> ClientParams
webSocketClientTLSParams :: !(String -> ClientParams)
, WebSocketConfig -> Maybe ServerParams
webSocketServerTLSParams :: !(Maybe ServerParams)
}
defaultWebSocketConfig :: IO WebSocketConfig
defaultWebSocketConfig :: IO WebSocketConfig
defaultWebSocketConfig = do
certificateStore <- IO CertificateStore
getSystemCertificateStore
pure WebSocketConfig
{ webSocketClientTLSParams = \[Char]
host ->
let base :: ClientParams
base = [Char] -> ByteString -> ClientParams
defaultParamsClient [Char]
host ByteString
BS.empty
in ClientParams
base
{ clientShared = (clientShared base)
{ sharedCAStore = certificateStore
}
}
, webSocketServerTLSParams = Nothing
}
webSocketServerParams :: Credential -> ServerParams
webSocketServerParams :: Credential -> ServerParams
webSocketServerParams Credential
credential = ServerParams
base
{ serverShared = (serverShared base)
{ sharedCredentials = Credentials [credential]
}
}
where
base :: ServerParams
base = ServerParams
defaultParamsServer
newWebSocketTransport :: IO Transport
newWebSocketTransport :: IO Transport
newWebSocketTransport = IO WebSocketConfig
defaultWebSocketConfig IO WebSocketConfig
-> (WebSocketConfig -> IO Transport) -> IO Transport
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= WebSocketConfig -> IO Transport
newWebSocketTransportWithConfig
newWebSocketTransportWithConfig :: WebSocketConfig -> IO Transport
newWebSocketTransportWithConfig :: WebSocketConfig -> IO Transport
newWebSocketTransportWithConfig WebSocketConfig
config = do
tcp <- IO Transport
newTCPTransport
pure Transport
{ transportDial = dialWebSocket tcp config
, transportDialFrom = \Maybe Multiaddr
local Multiaddr
remote -> case Maybe Multiaddr
local of
Maybe Multiaddr
Nothing -> Transport -> WebSocketConfig -> Multiaddr -> IO RawConnection
dialWebSocket Transport
tcp WebSocketConfig
config Multiaddr
remote
Just Multiaddr
_ -> [Char] -> IO RawConnection
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail [Char]
"WebSocket transport does not support binding a dial to a listener address"
, transportListen = listenWebSocket tcp config
, transportCanDial = canDialWebSocket
}
canDialWebSocket :: Multiaddr -> Bool
canDialWebSocket :: Multiaddr -> Bool
canDialWebSocket Multiaddr
address = case Multiaddr -> Either [Char] WebSocketAddress
parseWebSocketAddress Multiaddr
address of
Right WebSocketAddress
_ -> Bool
True
Left [Char]
_ -> Bool
False
data WebSocketAddress = WebSocketAddress
{ WebSocketAddress -> [Char]
websocketHost :: !String
, WebSocketAddress -> Word16
websocketPort :: !Word16
, WebSocketAddress -> Bool
websocketSecure :: !Bool
, WebSocketAddress -> Family
websocketFamily :: !Socket.Family
, WebSocketAddress -> Maybe Multiaddr
websocketTCPAddress :: !(Maybe Multiaddr)
}
parseWebSocketAddress :: Multiaddr -> Either String WebSocketAddress
parseWebSocketAddress :: Multiaddr -> Either [Char] WebSocketAddress
parseWebSocketAddress Multiaddr
address = case Multiaddr -> Multiaddr
stripP2P Multiaddr
address of
Multiaddr [IP4 Word32
word, TCP Word16
port, Protocol
protocol] -> do
secure <- Protocol -> Either [Char] Bool
parseWebSocketProtocol Protocol
protocol
(host, _) <- multiaddrToHostPort (Multiaddr [IP4 word, TCP port])
pure (WebSocketAddress host port secure Socket.AF_INET (Just (Multiaddr [IP4 word, TCP port])))
Multiaddr [IP6 ByteString
bytes, TCP Word16
port, Protocol
protocol]
| ByteString -> Int
BS.length ByteString
bytes Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
16 -> do
secure <- Protocol -> Either [Char] Bool
parseWebSocketProtocol Protocol
protocol
(host, _) <- multiaddrToHostPort (Multiaddr [IP6 bytes, TCP port])
pure (WebSocketAddress host port secure Socket.AF_INET6 (Just (Multiaddr [IP6 bytes, TCP port])))
Multiaddr [DNS Text
host, TCP Word16
port, Protocol
protocol] ->
Family
-> Text -> Word16 -> Protocol -> Either [Char] WebSocketAddress
dnsAddress Family
Socket.AF_UNSPEC Text
host Word16
port Protocol
protocol
Multiaddr [DNS4 Text
host, TCP Word16
port, Protocol
protocol] ->
Family
-> Text -> Word16 -> Protocol -> Either [Char] WebSocketAddress
dnsAddress Family
Socket.AF_INET Text
host Word16
port Protocol
protocol
Multiaddr [DNS6 Text
host, TCP Word16
port, Protocol
protocol] ->
Family
-> Text -> Word16 -> Protocol -> Either [Char] WebSocketAddress
dnsAddress Family
Socket.AF_INET6 Text
host Word16
port Protocol
protocol
Multiaddr
_ -> [Char] -> Either [Char] WebSocketAddress
forall a b. a -> Either a b
Left [Char]
"expected /ip4|ip6|dns|dns4|dns6/.../tcp/.../ws|wss"
dnsAddress
:: Socket.Family -> Text.Text -> Word16 -> Protocol -> Either String WebSocketAddress
dnsAddress :: Family
-> Text -> Word16 -> Protocol -> Either [Char] WebSocketAddress
dnsAddress Family
family Text
host Word16
port Protocol
protocol = do
secure <- Protocol -> Either [Char] Bool
parseWebSocketProtocol Protocol
protocol
pure WebSocketAddress
{ websocketHost = Text.unpack host
, websocketPort = port
, websocketSecure = secure
, websocketFamily = family
, websocketTCPAddress = Nothing
}
parseWebSocketProtocol :: Protocol -> Either String Bool
parseWebSocketProtocol :: Protocol -> Either [Char] Bool
parseWebSocketProtocol Protocol
WS = Bool -> Either [Char] Bool
forall a b. b -> Either a b
Right Bool
False
parseWebSocketProtocol Protocol
WSS = Bool -> Either [Char] Bool
forall a b. b -> Either a b
Right Bool
True
parseWebSocketProtocol Protocol
_ = [Char] -> Either [Char] Bool
forall a b. a -> Either a b
Left [Char]
"address does not end in /ws or /wss"
stripP2P :: Multiaddr -> Multiaddr
stripP2P :: Multiaddr -> Multiaddr
stripP2P (Multiaddr [Protocol]
protocols) = case [Protocol] -> [Protocol]
forall a. [a] -> [a]
reverse [Protocol]
protocols of
P2P ByteString
_ : [Protocol]
rest -> [Protocol] -> Multiaddr
Multiaddr ([Protocol] -> [Protocol]
forall a. [a] -> [a]
reverse [Protocol]
rest)
[Protocol]
_ -> [Protocol] -> Multiaddr
Multiaddr [Protocol]
protocols
dialWebSocket :: Transport -> WebSocketConfig -> Multiaddr -> IO RawConnection
dialWebSocket :: Transport -> WebSocketConfig -> Multiaddr -> IO RawConnection
dialWebSocket Transport
tcp WebSocketConfig
config Multiaddr
remoteAddress = do
parsed <- ([Char] -> IO WebSocketAddress)
-> (WebSocketAddress -> IO WebSocketAddress)
-> Either [Char] WebSocketAddress
-> IO WebSocketAddress
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either [Char] -> IO WebSocketAddress
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail WebSocketAddress -> IO WebSocketAddress
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Multiaddr -> Either [Char] WebSocketAddress
parseWebSocketAddress Multiaddr
remoteAddress)
rawTCP <- connectTCP tcp parsed
buildClientConnection config parsed rawTCP remoteAddress
`onException` rcClose rawTCP
connectTCP :: Transport -> WebSocketAddress -> IO RawConnection
connectTCP :: Transport -> WebSocketAddress -> IO RawConnection
connectTCP Transport
tcp WebSocketAddress
parsed = case WebSocketAddress -> Maybe Multiaddr
websocketTCPAddress WebSocketAddress
parsed of
Just Multiaddr
address -> Transport -> Multiaddr -> IO RawConnection
transportDial Transport
tcp Multiaddr
address
Maybe Multiaddr
Nothing -> do
addresses <- WebSocketAddress -> IO [Multiaddr]
resolveTCPAddresses WebSocketAddress
parsed
tryAddresses addresses []
where
tryAddresses :: [Multiaddr] -> [[Char]] -> IO RawConnection
tryAddresses [] [[Char]]
errors =
[Char] -> IO RawConnection
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail ([Char] -> IO RawConnection) -> [Char] -> IO RawConnection
forall a b. (a -> b) -> a -> b
$ [Char]
"WebSocket DNS dial failed: " [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [[Char]] -> [Char]
unwords ([[Char]] -> [[Char]]
forall a. [a] -> [a]
reverse [[Char]]
errors)
tryAddresses (Multiaddr
address : [Multiaddr]
rest) [[Char]]
errors = do
result <- IO RawConnection -> IO (Either IOException RawConnection)
forall e a. Exception e => IO a -> IO (Either e a)
try (Transport -> Multiaddr -> IO RawConnection
transportDial Transport
tcp Multiaddr
address) :: IO (Either IOException RawConnection)
case result of
Right RawConnection
connection -> RawConnection -> IO RawConnection
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure RawConnection
connection
Left IOException
err -> [Multiaddr] -> [[Char]] -> IO RawConnection
tryAddresses [Multiaddr]
rest (IOException -> [Char]
forall e. Exception e => e -> [Char]
displayException IOException
err [Char] -> [[Char]] -> [[Char]]
forall a. a -> [a] -> [a]
: [[Char]]
errors)
resolveTCPAddresses :: WebSocketAddress -> IO [Multiaddr]
resolveTCPAddresses :: WebSocketAddress -> IO [Multiaddr]
resolveTCPAddresses WebSocketAddress
parsed = do
let hints :: AddrInfo
hints = AddrInfo
Socket.defaultHints
{ Socket.addrFamily = websocketFamily parsed
, Socket.addrSocketType = Socket.Stream
}
infos <- 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 (WebSocketAddress -> [Char]
websocketHost WebSocketAddress
parsed))
([Char] -> Maybe [Char]
forall a. a -> Maybe a
Just (Word16 -> [Char]
forall a. Show a => a -> [Char]
show (WebSocketAddress -> Word16
websocketPort WebSocketAddress
parsed)))
mapM (sockAddrToMultiaddr . Socket.addrAddress) infos
buildClientConnection
:: WebSocketConfig -> WebSocketAddress -> RawConnection -> Multiaddr -> IO RawConnection
buildClientConnection :: WebSocketConfig
-> WebSocketAddress
-> RawConnection
-> Multiaddr
-> IO RawConnection
buildClientConnection WebSocketConfig
config WebSocketAddress
parsed RawConnection
rawTCP Multiaddr
remoteAddress = do
rawStream <- RawConnection -> IO StreamIO
expectByteStream RawConnection
rawTCP
(networkStream, closeTLS) <- prepareClientStream config parsed rawStream
socketStream <- streamIOToWebSocketStream networkStream
connection <- WebSocket.newClientConnection
socketStream
(webSocketAuthority parsed)
"/"
WebSocket.defaultConnectionOptions
[]
wrapConnection parsed rawTCP remoteAddress closeTLS connection
prepareClientStream
:: WebSocketConfig -> WebSocketAddress -> StreamIO -> IO (StreamIO, IO ())
prepareClientStream :: WebSocketConfig
-> WebSocketAddress -> StreamIO -> IO (StreamIO, IO ())
prepareClientStream WebSocketConfig
config WebSocketAddress
parsed StreamIO
rawStream
| Bool -> Bool
not (WebSocketAddress -> Bool
websocketSecure WebSocketAddress
parsed) = (StreamIO, IO ()) -> IO (StreamIO, IO ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (StreamIO
rawStream, () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())
| Bool
otherwise = do
context <- Backend -> ClientParams -> IO Context
forall (m :: * -> *) backend params.
(MonadIO m, HasBackend backend, TLSParams params) =>
backend -> params -> m Context
contextNew (StreamIO -> Backend
streamBackend StreamIO
rawStream) (ClientParams -> IO Context) -> ClientParams -> IO Context
forall a b. (a -> b) -> a -> b
$
WebSocketConfig -> [Char] -> ClientParams
webSocketClientTLSParams WebSocketConfig
config (WebSocketAddress -> [Char]
websocketHost WebSocketAddress
parsed)
handshake context
stream <- tlsContextToStreamIO context
pure (stream, closeTLSContext context)
webSocketAuthority :: WebSocketAddress -> String
webSocketAuthority :: WebSocketAddress -> [Char]
webSocketAuthority WebSocketAddress
parsed
| WebSocketAddress -> Word16
websocketPort WebSocketAddress
parsed Word16 -> Word16 -> Bool
forall a. Eq a => a -> a -> Bool
== Word16
defaultPort = [Char] -> [Char]
forall {t :: * -> *}.
(Foldable t, Semigroup (t Char), IsString (t Char)) =>
t Char -> t Char
formatHost (WebSocketAddress -> [Char]
websocketHost WebSocketAddress
parsed)
| Bool
otherwise = [Char] -> [Char]
forall {t :: * -> *}.
(Foldable t, Semigroup (t Char), IsString (t Char)) =>
t Char -> t Char
formatHost (WebSocketAddress -> [Char]
websocketHost WebSocketAddress
parsed) [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 (WebSocketAddress -> Word16
websocketPort WebSocketAddress
parsed)
where
defaultPort :: Word16
defaultPort = if WebSocketAddress -> Bool
websocketSecure WebSocketAddress
parsed then Word16
443 else Word16
80
formatHost :: t Char -> t Char
formatHost t Char
host
| Char
':' Char -> t Char -> Bool
forall a. Eq a => a -> t a -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` t Char
host = t Char
"[" t Char -> t Char -> t Char
forall a. Semigroup a => a -> a -> a
<> t Char
host t Char -> t Char -> t Char
forall a. Semigroup a => a -> a -> a
<> t Char
"]"
| Bool
otherwise = t Char
host
listenWebSocket :: Transport -> WebSocketConfig -> Multiaddr -> IO Listener
listenWebSocket :: Transport -> WebSocketConfig -> Multiaddr -> IO Listener
listenWebSocket Transport
tcp WebSocketConfig
config Multiaddr
requestedAddress = do
parsed <- ([Char] -> IO WebSocketAddress)
-> (WebSocketAddress -> IO WebSocketAddress)
-> Either [Char] WebSocketAddress
-> IO WebSocketAddress
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either [Char] -> IO WebSocketAddress
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail WebSocketAddress -> IO WebSocketAddress
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Multiaddr -> Either [Char] WebSocketAddress
parseWebSocketAddress Multiaddr
requestedAddress)
tcpAddress <- maybe
(fail "WebSocket listeners require an IP4 or IP6 multiaddr")
pure
(websocketTCPAddress parsed)
unless (not (websocketSecure parsed) || hasServerTLS config) $
fail "WSS listener requires webSocketServerTLSParams"
tcpListener <- transportListen tcp tcpAddress
pure Listener
{ listenerAccept = acceptWebSocket config parsed tcpListener
, listenerClose = listenerClose tcpListener
, listenerAddr = appendWebSocketProtocol parsed (listenerAddr tcpListener)
}
hasServerTLS :: WebSocketConfig -> Bool
hasServerTLS :: WebSocketConfig -> Bool
hasServerTLS = Maybe ServerParams -> Bool
forall a. Maybe a -> Bool
isJust (Maybe ServerParams -> Bool)
-> (WebSocketConfig -> Maybe ServerParams)
-> WebSocketConfig
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. WebSocketConfig -> Maybe ServerParams
webSocketServerTLSParams
acceptWebSocket
:: WebSocketConfig -> WebSocketAddress -> Listener -> IO RawConnection
acceptWebSocket :: WebSocketConfig -> WebSocketAddress -> Listener -> IO RawConnection
acceptWebSocket WebSocketConfig
config WebSocketAddress
parsed Listener
tcpListener = do
rawTCP <- Listener -> IO RawConnection
listenerAccept Listener
tcpListener
buildServerConnection config parsed rawTCP `onException` rcClose rawTCP
buildServerConnection
:: WebSocketConfig -> WebSocketAddress -> RawConnection -> IO RawConnection
buildServerConnection :: WebSocketConfig
-> WebSocketAddress -> RawConnection -> IO RawConnection
buildServerConnection WebSocketConfig
config WebSocketAddress
parsed RawConnection
rawTCP = do
rawStream <- RawConnection -> IO StreamIO
expectByteStream RawConnection
rawTCP
(networkStream, closeTLS) <- prepareServerStream config parsed rawStream
socketStream <- streamIOToWebSocketStream networkStream
pending <- WebSocket.makePendingConnectionFromStream
socketStream
WebSocket.defaultConnectionOptions
if WebSocket.requestPath (WebSocket.pendingRequest pending) /= "/"
then WebSocket.rejectRequest pending "websocket path must be /" >> fail "invalid websocket path"
else do
connection <- WebSocket.acceptRequest pending
let remoteAddress = WebSocketAddress -> Multiaddr -> Multiaddr
appendWebSocketProtocol WebSocketAddress
parsed (RawConnection -> Multiaddr
rcRemoteAddr RawConnection
rawTCP)
wrapConnection parsed rawTCP remoteAddress closeTLS connection
prepareServerStream
:: WebSocketConfig -> WebSocketAddress -> StreamIO -> IO (StreamIO, IO ())
prepareServerStream :: WebSocketConfig
-> WebSocketAddress -> StreamIO -> IO (StreamIO, IO ())
prepareServerStream WebSocketConfig
config WebSocketAddress
parsed StreamIO
rawStream
| Bool -> Bool
not (WebSocketAddress -> Bool
websocketSecure WebSocketAddress
parsed) = (StreamIO, IO ()) -> IO (StreamIO, IO ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (StreamIO
rawStream, () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())
| Bool
otherwise = do
params <- IO ServerParams
-> (ServerParams -> IO ServerParams)
-> Maybe ServerParams
-> IO ServerParams
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
([Char] -> IO ServerParams
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail [Char]
"WSS listener requires webSocketServerTLSParams")
ServerParams -> IO ServerParams
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
(WebSocketConfig -> Maybe ServerParams
webSocketServerTLSParams WebSocketConfig
config)
context <- contextNew (streamBackend rawStream) params
handshake context
stream <- tlsContextToStreamIO context
pure (stream, closeTLSContext context)
wrapConnection
:: WebSocketAddress
-> RawConnection
-> Multiaddr
-> IO ()
-> WebSocket.Connection
-> IO RawConnection
wrapConnection :: WebSocketAddress
-> RawConnection
-> Multiaddr
-> IO ()
-> Connection
-> IO RawConnection
wrapConnection WebSocketAddress
parsed RawConnection
rawTCP Multiaddr
remoteAddress IO ()
closeTLS Connection
connection = do
close <- IO () -> IO (IO ())
closeOnce (IO () -> IO (IO ())) -> IO () -> IO (IO ())
forall a b. (a -> b) -> a -> b
$ do
Connection -> ByteString -> IO ()
forall a. WebSocketsData a => Connection -> a -> IO ()
WebSocket.sendClose Connection
connection (ByteString
BS.empty :: BS.ByteString)
IO () -> (SomeException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` \(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
IO ()
closeTLS
RawConnection -> IO ()
rcClose RawConnection
rawTCP
stream <- webSocketToStreamIO connection close
pure RawConnection
{ rcEndpoint = ByteStreamEndpoint stream
, rcLocalAddr = appendWebSocketProtocol parsed (rcLocalAddr rawTCP)
, rcRemoteAddr = remoteAddress
, rcClose = close
, rcRelayLimit = Nothing
}
appendWebSocketProtocol :: WebSocketAddress -> Multiaddr -> Multiaddr
appendWebSocketProtocol :: WebSocketAddress -> Multiaddr -> Multiaddr
appendWebSocketProtocol WebSocketAddress
parsed (Multiaddr [Protocol]
protocols) =
[Protocol] -> Multiaddr
Multiaddr ([Protocol]
protocols [Protocol] -> [Protocol] -> [Protocol]
forall a. Semigroup a => a -> a -> a
<> [if WebSocketAddress -> Bool
websocketSecure WebSocketAddress
parsed then Protocol
WSS else Protocol
WS])
expectByteStream :: RawConnection -> IO StreamIO
expectByteStream :: RawConnection -> IO StreamIO
expectByteStream RawConnection
raw = case RawConnection -> ConnectionEndpoint
rcEndpoint RawConnection
raw of
ByteStreamEndpoint StreamIO
stream -> StreamIO -> IO StreamIO
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure StreamIO
stream
NativeMuxerEndpoint NativeMuxer
_ -> [Char] -> IO StreamIO
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail [Char]
"WebSocket requires a byte-stream TCP endpoint"
streamIOToWebSocketStream :: StreamIO -> IO WebSocketStream.Stream
streamIOToWebSocketStream :: StreamIO -> IO Stream
streamIOToWebSocketStream StreamIO
stream = IO (Maybe ByteString) -> (Maybe ByteString -> IO ()) -> IO Stream
WebSocketStream.makeStream IO (Maybe ByteString)
receive Maybe ByteString -> IO ()
send
where
receive :: IO (Maybe ByteString)
receive =
(ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just (ByteString -> Maybe ByteString)
-> IO ByteString -> IO (Maybe ByteString)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StreamIO -> Int -> IO ByteString
streamReadChunk StreamIO
stream Int
8192)
IO (Maybe ByteString)
-> (IOException -> IO (Maybe ByteString)) -> IO (Maybe ByteString)
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` \(IOException
_ :: IOException) -> 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
send :: Maybe ByteString -> IO ()
send Maybe ByteString
Nothing = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
send (Just ByteString
bytes) = (ByteString -> IO ()) -> [ByteString] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (StreamIO -> ByteString -> IO ()
streamWrite StreamIO
stream) (ByteString -> [ByteString]
LBS.toChunks ByteString
bytes)
webSocketToStreamIO :: WebSocket.Connection -> IO () -> IO StreamIO
webSocketToStreamIO :: Connection -> IO () -> IO StreamIO
webSocketToStreamIO Connection
connection IO ()
close = do
readBuffer <- ByteString -> IO (MVar ByteString)
forall a. a -> IO (MVar a)
newMVar ByteString
BS.empty
writeLock <- newMVar ()
pure StreamIO
{ streamWrite = \ByteString
bytes -> Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (ByteString -> Bool
BS.null ByteString
bytes) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
MVar () -> (() -> IO ()) -> IO ()
forall a b. MVar a -> (a -> IO b) -> IO b
withMVar MVar ()
writeLock (\()
_ -> Connection -> ByteString -> IO ()
forall a. WebSocketsData a => Connection -> a -> IO ()
WebSocket.sendBinaryData Connection
connection ByteString
bytes)
, streamReadByte = BS.head <$> readWebSocketChunk connection readBuffer 1
, streamReadChunk = readWebSocketChunk connection readBuffer
, streamClose = close
}
readWebSocketChunk
:: WebSocket.Connection -> MVar BS.ByteString -> Int -> IO BS.ByteString
readWebSocketChunk :: Connection -> MVar ByteString -> Int -> IO ByteString
readWebSocketChunk Connection
_ MVar ByteString
_ Int
requested | Int
requested Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty
readWebSocketChunk Connection
connection MVar ByteString
readBuffer Int
requested =
MVar ByteString
-> (ByteString -> IO (ByteString, ByteString)) -> IO ByteString
forall a b. MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar MVar ByteString
readBuffer ((ByteString -> IO (ByteString, ByteString)) -> IO ByteString)
-> (ByteString -> IO (ByteString, ByteString)) -> IO ByteString
forall a b. (a -> b) -> a -> b
$ \ByteString
buffer -> do
available <- if ByteString -> Bool
BS.null ByteString
buffer then Connection -> IO ByteString
receiveBinary Connection
connection else ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
buffer
let (front, rest) = BS.splitAt requested available
pure (rest, front)
receiveBinary :: WebSocket.Connection -> IO BS.ByteString
receiveBinary :: Connection -> IO ByteString
receiveBinary Connection
connection = do
message <- Connection -> IO DataMessage
WebSocket.receiveDataMessage Connection
connection
case message of
WebSocket.Binary ByteString
bytes
| ByteString -> Bool
LBS.null ByteString
bytes -> Connection -> IO ByteString
receiveBinary Connection
connection
| Bool
otherwise -> ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> ByteString
LBS.toStrict ByteString
bytes)
WebSocket.Text ByteString
_ Maybe Text
_ -> [Char] -> IO ByteString
forall a. [Char] -> IO a
forall (m :: * -> *) a. MonadFail m => [Char] -> m a
fail [Char]
"WebSocket transport received a text message"
streamBackend :: StreamIO -> Backend
streamBackend :: StreamIO -> Backend
streamBackend StreamIO
stream = Backend
{ backendFlush :: IO ()
backendFlush = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
, backendClose :: IO ()
backendClose = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
, backendSend :: ByteString -> IO ()
backendSend = StreamIO -> ByteString -> IO ()
streamWrite StreamIO
stream
, backendRecv :: Int -> IO ByteString
backendRecv = StreamIO -> Int -> IO ByteString
recvExact StreamIO
stream
}
recvExact :: StreamIO -> Int -> IO BS.ByteString
recvExact :: StreamIO -> Int -> IO ByteString
recvExact StreamIO
stream Int
requested
| Int
requested Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty
| Bool
otherwise = [ByteString] -> Int -> IO ByteString
collect [] Int
requested
where
collect :: [ByteString] -> Int -> IO ByteString
collect [ByteString]
chunks Int
remaining = do
bytes <- StreamIO -> Int -> IO ByteString
streamReadChunk StreamIO
stream Int
remaining
IO ByteString -> (IOException -> IO ByteString) -> IO ByteString
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` \(IOException
_ :: IOException) -> ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty
if BS.null bytes
then pure (BS.concat (reverse chunks))
else do
let unread = Int
remaining Int -> Int -> Int
forall a. Num a => a -> a -> a
- ByteString -> Int
BS.length ByteString
bytes
if unread <= 0
then pure (BS.concat (reverse (bytes : chunks)))
else collect (bytes : chunks) unread
tlsContextToStreamIO :: Context -> IO StreamIO
tlsContextToStreamIO :: Context -> IO StreamIO
tlsContextToStreamIO Context
context = do
readBuffer <- ByteString -> IO (MVar ByteString)
forall a. a -> IO (MVar a)
newMVar ByteString
BS.empty
pure StreamIO
{ streamWrite = sendData context . LBS.fromStrict
, streamReadByte = BS.head <$> readTLSChunk context readBuffer 1
, streamReadChunk = readTLSChunk context readBuffer
, streamClose = closeTLSContext context
}
readTLSChunk :: Context -> MVar BS.ByteString -> Int -> IO BS.ByteString
readTLSChunk :: Context -> MVar ByteString -> Int -> IO ByteString
readTLSChunk Context
_ MVar ByteString
_ Int
requested | Int
requested Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty
readTLSChunk Context
context MVar ByteString
readBuffer Int
requested =
MVar ByteString
-> (ByteString -> IO (ByteString, ByteString)) -> IO ByteString
forall a b. MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar MVar ByteString
readBuffer ((ByteString -> IO (ByteString, ByteString)) -> IO ByteString)
-> (ByteString -> IO (ByteString, ByteString)) -> IO ByteString
forall a b. (a -> b) -> a -> b
$ \ByteString
buffer -> do
available <- if ByteString -> Bool
BS.null ByteString
buffer then Context -> IO ByteString
forall (m :: * -> *). MonadIO m => Context -> m ByteString
recvData Context
context else ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
buffer
if BS.null available
then fail "WSS TLS connection closed"
else do
let (front, rest) = BS.splitAt requested available
pure (rest, front)
closeTLSContext :: Context -> IO ()
closeTLSContext :: Context -> IO ()
closeTLSContext Context
context = Context -> IO ()
forall (m :: * -> *). MonadIO m => Context -> m ()
bye Context
context IO () -> (SomeException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` \(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
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
let close = MVar Bool -> (Bool -> IO Bool) -> IO ()
forall a. MVar a -> (a -> IO a) -> IO ()
modifyMVar_ MVar Bool
closed ((Bool -> IO Bool) -> IO ()) -> (Bool -> IO Bool) -> IO ()
forall a b. (a -> b) -> a -> b
$ \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
pure close