packages feed

streamly-websockets (empty) → 0.1.0.0

raw patch · 10 files changed

+1564/−0 lines, 10 filesdep +asyncdep +basedep +base64-bytestring

Dependencies added: async, base, base64-bytestring, bytestring, cryptohash-sha1, entropy, flatparse, network, stm, streamly-bytestring, streamly-core, streamly-flatparse, streamly-http, streamly-network-tcp, streamly-websockets, tasty, tasty-hunit, tasty-quickcheck, text, websockets

Files

+ CHANGELOG.md view
@@ -0,0 +1,14 @@+# Revision history for streamly-websockets++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* A WebSocket client over TCP: `withConnection`, `send`, `receive`,+  `messages`, `ping`, `pongCount`, `close`, within a time to open+  (`openTimeout`); `withConnectionOver` for a connection of the caller,+  such as a TLS one.+* The side of a server (`Streamly.External.Network.WebSocket.Server`):+  `serve`, `listen`, `serveSocket`, `serveSocketWith` and `acceptOver`. A+  connection is the same type on both sides.+* Frames written and read (`Frame`), their headers with a flatparse+  parser, and the opening handshake (`Handshake`) over streamly-http.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Xavier Dectot+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++    * Neither the name of the copyright holder nor the names of its+      contributors may be used to endorse or promote products derived+      from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,78 @@+# streamly-websockets++WebSockets (RFC 6455) written with+[Streamly](https://streamly.composewell.com/), over plain TCP, for clients+and for servers. The opening handshake goes through+[streamly-http](https://hackage.haskell.org/package/streamly-http);+frames are read with flatparse parsers from the stream of byte arrays of the+connection; the messages received are a stream.++A client:++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (fold)+import Streamly.Data.Stream qualified as S (take)+import Streamly.External.Network.WebSocket (Message (TextMessage), config,+                                            messages, send, withConnection)++main :: IO ()+main = withConnection (config "127.0.0.1" 9330 "/api") $ \connection -> do+  send connection (TextMessage "hello")+  fold (drainMapM print) (S.take 3 (messages connection))+```++A server that sends back what it receives:++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (fold)+import Streamly.External.Network.WebSocket.Server (defaultServerOptions,+                                                   messages, send, serve)++main :: IO ()+main = serve "127.0.0.1" 8080 defaultServerOptions $ \_ connection ->+  fold (drainMapM (send connection)) (messages connection)+```++## What it does++- Text and binary messages, sent in one frame each, received whole even+  when the other side fragments them. Text is checked to be UTF-8.+- Pings of the other side are answered, the pongs to `ping` counted+  (`pongCount`, in `STM`), and the closing handshake is done, all while+  messages are received.+- Sending is safe from several threads. Receiving is for one thread at a+  time.+- A limit on the size of a message (`maxMessageSize`) and on the time to+  open the connection (`openTimeout`).++## Modules++- `Streamly.External.Network.WebSocket`: the client.+- `Streamly.External.Network.WebSocket.Server`: the server. Each client is+  served in a thread of its own; every upgrade asked properly is accepted.+- `Streamly.External.Network.WebSocket.Frame`: frames, written and read.+- `Streamly.External.Network.WebSocket.Handshake`: the opening handshake.++## Limits of this version++- TLS is not built in: `withConnectionOver` and `acceptOver` take a+  connection opened by other means, as a `Transport` of streamly-http.+  [streamly-websockets-tls](https://github.com/GuillaumedeVolpiano/streamly-websockets-tls)+  does it for both sides: `wss://` URLs for clients, servers over TLS.+- No extension (no compression) and no subprotocol negotiation.+- Messages are sent in one frame; there is no streaming of a message.++## Building++To build against copies of the libraries this package is built on+([streamly-http](https://hackage.haskell.org/package/streamly-http),+[streamly-network-tcp](https://hackage.haskell.org/package/streamly-network-tcp),+[streamly-flatparse](https://hackage.haskell.org/package/streamly-flatparse))+checked out next to this repository, pass+`--project-file=cabal.project.siblings`.
+ src/Streamly/External/Network/WebSocket.hs view
@@ -0,0 +1,146 @@+-- |+-- Module      : Streamly.External.Network.WebSocket+-- Description : A WebSocket client over TCP+-- License     : BSD-3-Clause+--+-- A WebSocket client (RFC 6455) over plain TCP, written with Streamly.+--+-- > {-# LANGUAGE OverloadedStrings #-}+-- > import Streamly.Data.Fold (drainMapM)+-- > import Streamly.Data.Stream (fold)+-- > import Streamly.Data.Stream qualified as S (take)+-- > import Streamly.External.Network.WebSocket (Message (TextMessage), config,+-- >                                             messages, send, withConnection)+-- >+-- > main :: IO ()+-- > main = withConnection (config "127.0.0.1" 9330 "/api") $ \connection -> do+-- >   send connection (TextMessage "hello")+-- >   fold (drainMapM print) (S.take 3 (messages connection))+--+-- Pings are answered, pongs counted and the closing handshake answered+-- while messages are received: a program that stops receiving stops all+-- three. Sending is safe from several threads; receiving is for one thread+-- at a time. TLS is not built in: 'withConnectionOver' takes a connection+-- opened by other means. There is no extension. For the side of a server,+-- see "Streamly.External.Network.WebSocket.Server".+module Streamly.External.Network.WebSocket+  ( -- * Connections+    Config (..)+  , config+  , Connection+  , withConnection+  , withConnectionOver++    -- * Messages+  , Message (..)+  , send+  , receive+  , messages++    -- * Pings and closing+  , ping+  , pongCount+  , close++    -- * Errors+  , WebSocketError (..)+  ) where++import Control.Exception (catch, finally, mask, throwIO)+import Data.ByteString (ByteString)+import Network.Socket (SocketOption (NoDelay), setSocketOption)+import Network.Socket qualified as N (close)+import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (fold)+import Streamly.Data.StreamK (fromStream)+import Streamly.External.Network.HTTP (HttpError (..), Transport (..),+                                       connectWithin, socketTransport)+import Streamly.External.Network.HTTP.Wire (Header, readResponseHeadWithin,+                                            renderRequest, validateRequest)+import Streamly.External.Network.WebSocket.Connection (Connection, Message (..),+                                                       close, established,+                                                       messages, ping,+                                                       pongCount, receive, send)+import Streamly.External.Network.WebSocket.Frame (Side (..),+                                                  WebSocketError (..))+import Streamly.External.Network.WebSocket.Handshake (checkUpgrade, newKey,+                                                      upgradeRequest)+import System.Timeout (timeout)++-- | Where to connect, and within what bounds.+data Config = Config+  { host :: String+  , port :: Int+  , path :: ByteString+  -- ^ The path and the query, such as @\/api@.+  , headers :: [Header]+  -- ^ Extra headers for the opening handshake.+  , maxMessageSize :: Int+  -- ^ The largest message accepted, in bytes. A larger one closes the+  -- connection with 'MessageTooLarge'.+  , openTimeout :: Maybe Int+  -- ^ Microseconds allowed for the connection to open: the TCP connection+  -- and the answer to the upgrade. 'Nothing' waits without end. Once the+  -- connection is open nothing limits the waits: a silent WebSocket is a+  -- normal one, and 'ping' with 'pongCount' tells a dead one.+  , closeTimeout :: Int+  -- ^ Microseconds to wait, once the function given to 'withConnection'+  -- is done, for the server to answer the closing of the connection.+  }+  deriving stock (Eq, Show)++-- | A host, a port and a path, with no extra header, messages of at most+-- 64 MiB, thirty seconds to open and one second to close.+config :: String -> Int -> ByteString -> Config+config host port path = Config {host, port, path, headers = [], maxMessageSize = 64 * 1024 * 1024, openTimeout = Just 30_000_000, closeTimeout = 1_000_000}++-- | Connect, open a WebSocket and use it. When the function returns, the+-- connection is closed in order: a close frame is sent, and the answer of+-- the server awaited for at most 'closeTimeout'. When it throws, the TCP+-- connection is closed at once.+--+-- Throws 'HandshakeFailed' when the server does not accept the upgrade,+-- 'OpenTimedOut' when the connection is not open in time,+-- 'Streamly.External.Network.HTTP.HttpError' (@InvalidRequest@) for a+-- path or a header that cannot be written, and 'IOError' when the TCP+-- connection fails.+withConnection :: Config -> (Connection -> IO a) -> IO a+withConnection settings use = do+  either throwIO pure (validateRequest (upgradeRequest settings.host settings.port settings.path settings.headers ""))+  -- The connection is opened unmasked, so that its time limit can stop+  -- it; connectWithin closes what it opened when it is stopped.+  mask $ \restore -> do+    socket <-+      restore (connectWithin settings.openTimeout settings.host settings.port)+        `catch` \case+          ConnectTimedOut -> throwIO OpenTimedOut+          other -> throwIO other+    ( restore $ do+        -- Frames are small and wait for answers: do not hold them back.+        setSocketOption socket NoDelay 1+        withConnectionOver (socketTransport socket) settings use+      )+      `finally` N.close socket++-- | Like 'withConnection', over a connection that is already open, such+-- as a TLS connection of @streamly-network-tls@ for a secure WebSocket+-- (@wss:\/\/@). The host and the port of the configuration only serve the+-- @Host@ header. Opening and closing the transport are up to the caller.+withConnectionOver :: Transport -> Config -> (Connection -> IO a) -> IO a+withConnectionOver transport settings use = do+  key <- newKey+  let request = upgradeRequest settings.host settings.port settings.path settings.headers key+  either throwIO pure (validateRequest request)+  rest <- opening $ do+    fold (drainMapM transport.send) (renderRequest request)+    (response, rest) <-+      -- No answer to an upgrade needs more than this.+      readResponseHeadWithin (Just 65536) (fromStream transport.receive)+        `catch` \(problem :: HttpError) -> throwIO (HandshakeFailed (show problem))+    either throwIO pure (checkUpgrade key response)+    pure rest+  established Client transport rest settings.maxMessageSize settings.closeTimeout use+  where+    opening action = case settings.openTimeout of+      Nothing -> action+      Just microseconds -> timeout microseconds action >>= maybe (throwIO OpenTimedOut) pure
+ src/Streamly/External/Network/WebSocket/Connection.hs view
@@ -0,0 +1,200 @@+-- |+-- Module      : Streamly.External.Network.WebSocket.Connection+-- Description : An open WebSocket, for a client as for a server+-- License     : BSD-3-Clause+--+-- What both sides do once the opening handshake is over: sending and+-- receiving messages, pings, and the closing handshake. The client and the+-- server modules open connections and export these functions.+module Streamly.External.Network.WebSocket.Connection+  ( Connection+  , established+  , Message (..)+  , send+  , receive+  , messages+  , ping+  , pongCount+  , close+  ) where++import Control.Concurrent.MVar (MVar, modifyMVar, newMVar, withMVar)+import Control.Concurrent.STM (STM, TVar, atomically, modifyTVar', newTVarIO,+                               readTVar)+import Control.Exception (SomeException, catch, onException, throwIO, try)+import Control.Monad (unless, void, when)+import Data.ByteString (ByteString, pack)+import Data.ByteString qualified as BS (concat, length, take)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Text (Text)+import Data.Text.Encoding (decodeUtf8', encodeUtf8)+import Data.Word (Word8)+import Streamly.Data.Array (Array)+import Streamly.Data.Fold (drain)+import Streamly.Data.Stream (Stream, fold, unfoldrM)+import Streamly.Data.StreamK (StreamK, nil)+import Streamly.External.ByteString (toArray)+import Streamly.External.Network.HTTP (Transport (..))+import Streamly.External.Network.WebSocket.Frame (Frame (..),+                                                  Opcode (BinaryFrame, CloseFrame, Continuation, PingFrame, PongFrame, TextFrame),+                                                  Side (..),+                                                  WebSocketError (ConnectionClosed, MessageTooLarge, ProtocolViolation),+                                                  encodeFrame, readFrame)+import System.Entropy (getEntropy)+import System.Timeout (timeout)++-- | A whole message, put together from its frames.+data Message+  = TextMessage Text+  | BinaryMessage ByteString+  deriving stock (Eq, Show)++-- | An open connection.+data Connection = Connection+  { side :: Side+  , transport :: Transport+  , input :: MVar (StreamK IO (Array Word8))+  -- ^ What is still to read. Held while a message is received.+  , sendLock :: MVar ()+  -- ^ Held for each frame sent, and to read or change 'closeSent'.+  , closeSent :: IORef Bool+  , ended :: IORef Bool+  -- ^ Nothing more will be received.+  , pongs :: TVar Int+  , maxMessageSize :: Int+  }++-- | Use a connection whose opening handshake is over: the side this is,+-- the transport, what was received after the handshake, the largest+-- message accepted and the microseconds to wait for the closing. When the+-- function returns, the connection is closed in order: a close frame is+-- sent, and the answer of the other side awaited.+established :: Side -> Transport -> StreamK IO (Array Word8) -> Int -> Int -> (Connection -> IO a) -> IO a+established side transport rest maxMessageSize closeTimeout use = do+  connection <- Connection side transport <$> newMVar rest <*> newMVar () <*> newIORef False <*> newIORef False <*> newTVarIO 0 <*> pure maxMessageSize+  value <- use connection+  -- Wait for the close frame of the other side before the connection+  -- goes: closing it at once can make the system reset it, and the other+  -- side lose what it had not read yet.+  void . try @SomeException . timeout closeTimeout $ do+    close connection+    fold drain (messages connection)+  pure value++-- | Send a message, in one frame.+--+-- Throws 'ConnectionClosed' once a close frame was sent or received, and+-- 'IOError' when the TCP connection fails.+send :: Connection -> Message -> IO ()+send connection = \case+  TextMessage text -> sendFrame connection False (Frame True TextFrame (encodeUtf8 text))+  BinaryMessage bytes -> sendFrame connection False (Frame True BinaryFrame bytes)++-- | Send a ping with a payload of at most 125 bytes. The pong that answers+-- it is counted by 'pongCount' when it is received.+--+-- Throws like @send@, and 'ProtocolViolation' for too long a payload.+ping :: Connection -> ByteString -> IO ()+ping connection payload = do+  when (BS.length payload > 125) (throwIO (ProtocolViolation "a ping payload longer than 125 bytes"))+  sendFrame connection False (Frame True PingFrame payload)++-- | The number of pongs received so far. It only grows while messages are+-- received. In 'STM', to wait for the next one.+pongCount :: Connection -> STM Int+pongCount connection = readTVar connection.pongs++-- | Start closing the connection, with the status 1000 (normal). Nothing+-- can be sent afterwards; messages can still be received until the other+-- side answers. Does nothing when the connection is already closing.+close :: Connection -> IO ()+close connection = sendFrame connection True (Frame True CloseFrame (statusBytes 1000)) `catch` \case+  ConnectionClosed -> pure ()+  other -> throwIO other++-- | Send a frame, under a fresh masking key for a client. A closing frame marks the+-- connection as closing; nothing is sent after one.+sendFrame :: Connection -> Bool -> Frame -> IO ()+sendFrame connection closing frame =+  withMVar connection.sendLock $ \() -> do+    closed <- readIORef connection.closeSent+    when closed (throwIO ConnectionClosed)+    -- A client masks what it sends; a server does not.+    key <- case connection.side of+      Client -> Just <$> getEntropy 4+      Server -> pure Nothing+    when closing (writeIORef connection.closeSent True)+    connection.transport.send (toArray (encodeFrame key frame))++-- | Like 'sendFrame', for answers that no longer matter once the+-- connection is closing or gone.+sendQuietly :: Connection -> Bool -> Frame -> IO ()+sendQuietly connection closing frame = void (try @SomeException (sendFrame connection closing frame))++-- | Receive the next message. 'Nothing' once the connection is closed, by+-- either side or by the loss of the TCP connection.+--+-- Meanwhile pings are answered, pongs counted, and a close frame of the+-- other side answered.+--+-- Throws 'ProtocolViolation' or 'MessageTooLarge' when the other side+-- sends what cannot be accepted (the connection is then closed), and 'IOError'+-- when the TCP connection fails.+receive :: Connection -> IO (Maybe Message)+receive connection = modifyMVar connection.input $ \input -> do+  over <- readIORef connection.ended+  if over+    then pure (input, Nothing)+    else assemble input Nothing `onException` writeIORef connection.ended True+  where+    finish = writeIORef connection.ended True+    -- Tell the other side why, then give up.+    failWith :: Int -> WebSocketError -> IO a+    failWith status problem = do+      sendQuietly connection True (Frame True CloseFrame (statusBytes status))+      throwIO problem+    violation :: String -> IO a+    violation = failWith 1002 . ProtocolViolation+    -- The second argument holds the frames of a fragmented message read+    -- so far: its opcode, its payloads in reverse order and their size.+    assemble input pending = do+      next <-+        readFrame connection.side connection.maxMessageSize input `catch` \case+          problem@(MessageTooLarge _) -> failWith 1009 problem+          problem -> failWith 1002 problem+      case next of+        Nothing -> (nil, Nothing) <$ finish+        Just (frame, rest) -> case frame.opcode of+          PingFrame -> sendQuietly connection False (Frame True PongFrame frame.payload) >> assemble rest pending+          PongFrame -> atomically (modifyTVar' connection.pongs (+ 1)) >> assemble rest pending+          CloseFrame -> do+            when (BS.length frame.payload == 1) (violation "a close frame with half a status")+            -- Answer with the same status, unless the closing is ours.+            sendQuietly connection True (Frame True CloseFrame (BS.take 2 frame.payload))+            (nil, Nothing) <$ finish+          Continuation -> case pending of+            Nothing -> violation "a continuation frame without a message to continue"+            Just (opcode, parts, size) -> do+              let total = size + BS.length frame.payload+              when (total > connection.maxMessageSize) (failWith 1009 (MessageTooLarge connection.maxMessageSize))+              if frame.final+                then deliver rest opcode (BS.concat (reverse (frame.payload : parts)))+                else assemble rest (Just (opcode, frame.payload : parts, total))+          opcode -> do+            unless (pending == Nothing) (violation "a new message inside a fragmented one")+            if frame.final+              then deliver rest opcode frame.payload+              else assemble rest (Just (opcode, [frame.payload], BS.length frame.payload))+    deliver rest opcode bytes = case opcode of+      TextFrame -> case decodeUtf8' bytes of+        Right text -> pure (rest, Just (TextMessage text))+        Left _ -> failWith 1007 (ProtocolViolation "a text message that is not UTF-8")+      _ -> pure (rest, Just (BinaryMessage bytes))++-- | The messages received until the connection is closed. See @receive@.+messages :: Connection -> Stream IO Message+messages connection = unfoldrM (\() -> fmap (,()) <$> receive connection) ()++-- | A close status as the first two bytes of the payload of a close frame.+statusBytes :: Int -> ByteString+statusBytes status = pack [fromIntegral (status `div` 256), fromIntegral (status `mod` 256)]
+ src/Streamly/External/Network/WebSocket/Frame.hs view
@@ -0,0 +1,220 @@+-- |+-- Module      : Streamly.External.Network.WebSocket.Frame+-- Description : WebSocket frames, written and read+-- License     : BSD-3-Clause+--+-- The frames of RFC 6455, section 5: writing them, masked or not, and+-- reading them from a stream of byte arrays, on either side.+module Streamly.External.Network.WebSocket.Frame+  ( -- * Frames+    Frame (..)+  , Opcode (..)+  , isControl+  , encodeFrame+  , applyMask++    -- * Reading+  , Side (..)+  , FrameHeader (..)+  , frameHeader+  , readFrame++    -- * Errors+  , WebSocketError (..)+  ) where++import Control.Exception (Exception, throwIO)+import Control.Monad (when)+import Data.Bits (shiftR, testBit, xor, (.&.), (.|.))+import Data.ByteString (ByteString, mapAccumL, pack)+import Data.ByteString qualified as BS (concat, length, splitAt)+import Data.ByteString.Unsafe (unsafeIndex)+import Data.Word (Word8)+import FlatParse.Basic (Parser, anyWord16be, anyWord64be, anyWord8, err)+import FlatParse.Basic qualified as FB (take)+import Streamly.Data.Array (Array)+import Streamly.Data.Array qualified as A (length)+import Streamly.Data.StreamK (StreamK, cons, uncons)+import Streamly.External.ByteString (fromArray, toArray)+import Streamly.External.FlatParse (ParseError (ParserError), parseBreak)++-- | What a frame carries.+data Opcode+  = -- | The next part of a fragmented message.+    Continuation+  | TextFrame+  | BinaryFrame+  | CloseFrame+  | PingFrame+  | PongFrame+  deriving stock (Eq, Show)++-- | Close, ping and pong: frames about the connection itself.+isControl :: Opcode -> Bool+isControl opcode = opcode `elem` [CloseFrame, PingFrame, PongFrame]++-- | A frame, its payload unmasked.+data Frame = Frame+  { final :: Bool+  -- ^ The last frame of its message.+  , opcode :: Opcode+  , payload :: ByteString+  }+  deriving stock (Eq, Show)++-- | What can go wrong on a WebSocket connection. Failures of the TCP+-- connection itself stay 'IOError's.+data WebSocketError+  = -- | The opening handshake failed: the server did not accept the upgrade+    -- or, for a server, the client did not ask for one properly. Why.+    HandshakeFailed String+  | -- | The other side broke the protocol: how.+    ProtocolViolation String+  | -- | A frame or a message larger than the limit of the connection, in+    -- bytes: the limit.+    MessageTooLarge Int+  | -- | The connection was not open within the time allowed: the server+    -- did not accept it, or did not answer the upgrade.+    OpenTimedOut+  | -- | Sending on a connection that is closed or closing.+    ConnectionClosed+  deriving stock (Eq, Show)++instance Exception WebSocketError++-- | The bytes of a frame. With a masking key of four bytes the payload is+-- masked, as a client must do; without one it is sent as it is, as a+-- server does.+encodeFrame :: Maybe ByteString -> Frame -> ByteString+encodeFrame mask frame =+  BS.concat $+    [pack (first : lengthBytes)]+      <> maybe [frame.payload] (\key -> [key, applyMask key frame.payload]) mask+  where+    first = (if frame.final then 0x80 else 0) .|. opcodeNumber frame.opcode+    maskBit = maybe 0 (const 0x80) mask+    size = BS.length frame.payload+    lengthBytes+      | size < 126 = [maskBit .|. fromIntegral size]+      | size < 65536 = (maskBit .|. 126) : bigEndian 2+      | otherwise = (maskBit .|. 127) : bigEndian 8+    bigEndian :: Int -> [Word8]+    bigEndian count = [fromIntegral (size `shiftR` (8 * index)) | index <- [count - 1, count - 2 .. 0]]++opcodeNumber :: Opcode -> Word8+opcodeNumber = \case+  Continuation -> 0+  TextFrame -> 1+  BinaryFrame -> 2+  CloseFrame -> 8+  PingFrame -> 9+  PongFrame -> 10++-- | Mask or unmask a payload with a key of four bytes: each byte is+-- combined by exclusive or with the byte of the key at its position modulo+-- four.+applyMask :: ByteString -> ByteString -> ByteString+applyMask key+  | BS.length key /= 4 = id+  | otherwise = snd . mapAccumL (\index byte -> (index + 1, byte `xor` unsafeIndex key (index .&. 3))) (0 :: Int)++-- | What precedes the payload of a frame.+data FrameHeader = FrameHeader+  { final :: Bool+  , opcode :: Opcode+  , mask :: Maybe ByteString+  -- ^ The masking key, of four bytes, when the payload is masked.+  , size :: Int+  -- ^ The number of bytes of the payload.+  }+  deriving stock (Eq, Show)++-- | The header of a frame, as a flatparse parser: it fails while the+-- header is not all there, and stops on an error for what no further byte+-- can mend. Refuses reserved bits (no extension is+-- negotiated), unknown opcodes, lengths not written in the shortest form,+-- and control frames that are fragmented or longer than 125 bytes.+frameHeader :: Parser String FrameHeader+frameHeader = do+  first <- anyWord8+  when (first .&. 0x70 /= 0) (err "a reserved bit is set")+  opcode <- case first .&. 0x0F of+    0 -> pure Continuation+    1 -> pure TextFrame+    2 -> pure BinaryFrame+    8 -> pure CloseFrame+    9 -> pure PingFrame+    10 -> pure PongFrame+    other -> err ("unknown opcode " <> show other)+  second <- anyWord8+  let final = testBit first 7+  size <- case second .&. 0x7F of+    126 -> do+      long <- anyWord16be+      when (long < 126) (err "a length not in its shortest form")+      pure (fromIntegral long)+    127 -> do+      long <- anyWord64be+      when (long < 65536) (err "a length not in its shortest form")+      when (long > fromIntegral (maxBound :: Int)) (err "a length beyond what can be held")+      pure (fromIntegral long)+    short -> pure (fromIntegral short)+  when (isControl opcode && not final) (err "a fragmented control frame")+  when (isControl opcode && size > 125) (err "a control frame longer than 125 bytes")+  mask <- if testBit second 7 then Just <$> FB.take 4 else pure Nothing+  pure FrameHeader {final, opcode, mask, size}++-- | The two ends of a connection. A client masks the frames it sends; a+-- server does not.+data Side = Client | Server+  deriving stock (Eq, Show)++-- | Read one frame as the given side receives it, with the largest payload+-- accepted, and give the input that follows it. 'Nothing' when the input+-- has ended before the frame starts. A payload masked by a client is+-- given unmasked.+--+-- Throws 'ProtocolViolation' for a header that cannot be read, for a+-- frame masked when it must not be (those a client receives) or not+-- masked when it must be (those a server receives), and for an input that+-- ends inside the frame; 'MessageTooLarge' for a payload beyond the limit.+readFrame :: Side -> Int -> StreamK IO (Array Word8) -> IO (Maybe (Frame, StreamK IO (Array Word8)))+readFrame side limit input =+  uncons input >>= \case+    Nothing -> pure Nothing+    Just (array, rest)+      | A.length array == 0 -> readFrame side limit rest+      | otherwise -> do+          -- A header is fourteen bytes at most.+          (outcome, afterHeader) <- parseBreak 14 frameHeader (cons array rest)+          found <- case outcome of+            Right found -> pure found+            Left (ParserError problem) -> throwIO (ProtocolViolation problem)+            Left _ -> throwIO (ProtocolViolation "the connection ended inside the header of a frame")+          case (side, found.mask) of+            (Client, Just _) -> throwIO (ProtocolViolation "a masked frame from the server")+            (Server, Nothing) -> throwIO (ProtocolViolation "a frame from the client that is not masked")+            _ -> pure ()+          when (found.size > limit) (throwIO (MessageTooLarge limit))+          takeBytes found.size afterHeader >>= \case+            Nothing -> throwIO (ProtocolViolation "the connection ended inside a frame")+            Just (received, afterFrame) ->+              let payload = maybe received (`applyMask` received) found.mask+               in pure (Just (Frame {final = found.final, opcode = found.opcode, payload}, afterFrame))++-- | Take a number of bytes from the input, without copying the arrays+-- that hold them. 'Nothing' when the input ends first.+takeBytes :: Int -> StreamK IO (Array Word8) -> IO (Maybe (ByteString, StreamK IO (Array Word8)))+takeBytes = go []+  where+    go taken 0 input = pure (Just (BS.concat (reverse taken), input))+    go taken remaining input =+      uncons input >>= \case+        Nothing -> pure Nothing+        Just (array, rest)+          | BS.length bytes <= remaining -> go (bytes : taken) (remaining - BS.length bytes) rest+          | otherwise ->+              let (front, back) = BS.splitAt remaining bytes+               in pure (Just (BS.concat (reverse (front : taken)), cons (toArray back) rest))+          where+            bytes = fromArray array
+ src/Streamly/External/Network/WebSocket/Handshake.hs view
@@ -0,0 +1,107 @@+-- |+-- Module      : Streamly.External.Network.WebSocket.Handshake+-- Description : The HTTP exchange that opens a WebSocket+-- License     : BSD-3-Clause+--+-- The opening handshake of RFC 6455, section 4. From the client: an HTTP+-- request that asks for the upgrade, and the check of the answer. From the+-- server: the check of the request, and the answer.+module Streamly.External.Network.WebSocket.Handshake+  ( newKey+  , acceptFor+  , upgradeRequest+  , checkUpgrade++    -- * The side of a server+  , checkUpgradeRequest+  , upgradeResponse+  , refusal+  ) where++import Control.Monad (unless, when)+import Crypto.Hash.SHA1 (hash)+import Data.ByteString (ByteString, split)+import Data.ByteString qualified as BS (null)+import Data.ByteString.Base64 (encode)+import Data.ByteString.Char8 (strip, unpack)+import Data.ByteString.Char8 qualified as BS8 (map)+import Data.Char (toLower)+import Data.Maybe (isJust)+import Streamly.External.Network.HTTP.Wire (Header, Request (..),+                                            RequestBody (..), RequestHead,+                                            Response (..), header,+                                            requestHeader, requestMethod)+import Streamly.External.Network.WebSocket.Frame (WebSocketError (..))+import System.Entropy (getEntropy)++-- | A key for one handshake: sixteen random bytes in base64.+newKey :: IO ByteString+newKey = encode <$> getEntropy 16++-- | What a server must answer in @Sec-WebSocket-Accept@ to a key.+acceptFor :: ByteString -> ByteString+acceptFor key = encode (hash (key <> "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))++-- | The request that asks a host and a port to open a WebSocket on a+-- path, with extra headers and the key of the handshake.+upgradeRequest :: String -> Int -> ByteString -> [Header] -> ByteString -> Request+upgradeRequest host port path extra key =+  Request+    { method = "GET"+    , host+    , port+    , target = path+    , headers =+        [ ("Upgrade", "websocket")+        , ("Connection", "Upgrade")+        , ("Sec-WebSocket-Key", key)+        , ("Sec-WebSocket-Version", "13")+        ]+          <> extra+    , body = NoBody+    }++-- | Check that the answer accepts the upgrade asked with a key: status+-- 101, the upgrade to @websocket@, the proof that the key was read, and+-- no extension, since none was offered.+checkUpgrade :: ByteString -> Response body -> Either WebSocketError ()+checkUpgrade key response = do+  unless (response.status == 101) $+    refuse ("the server answered " <> show response.status <> " " <> unpack response.reason)+  unless (fmap lower (header "upgrade" response) == Just "websocket") $+    refuse "the answer does not upgrade to websocket"+  unless (maybe False (elem "upgrade" . tokens) (header "connection" response)) $+    refuse "the answer does not say Connection: Upgrade"+  unless (header "sec-websocket-accept" response == Just (acceptFor key)) $+    refuse "the answer does not prove that the key was read"+  when (isJust (header "sec-websocket-extensions" response)) $+    refuse "the server uses an extension that was not offered"+  where+    refuse = Left . HandshakeFailed+    lower = BS8.map toLower+    tokens = map (lower . strip) . split 44++-- | Check that a request asks properly for a WebSocket, and give its key:+-- a @GET@ that upgrades to @websocket@, version 13, with a key.+checkUpgradeRequest :: RequestHead -> Either WebSocketError ByteString+checkUpgradeRequest request = do+  unless (requestMethod request == "GET") (refuse "the request is not a GET")+  unless (fmap lower (requestHeader "upgrade" request) == Just "websocket") (refuse "the request does not ask for websocket")+  unless (maybe False (elem "upgrade" . tokens) (requestHeader "connection" request)) (refuse "the request does not say Connection: Upgrade")+  unless (fmap strip (requestHeader "sec-websocket-version" request) == Just "13") (refuse "the request is not for version 13")+  case requestHeader "sec-websocket-key" request of+    Just key | not (BS.null key) -> Right key+    _ -> refuse "the request has no key"+  where+    refuse = Left . HandshakeFailed+    lower = BS8.map toLower+    tokens = map (lower . strip) . split 44++-- | The answer that accepts the upgrade asked with a key.+upgradeResponse :: ByteString -> ByteString+upgradeResponse key =+  "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " <> acceptFor key <> "\r\n\r\n"++-- | The answer to a request that does not ask properly for a WebSocket.+refusal :: ByteString+refusal = "HTTP/1.1 400 Bad Request\r\nConnection: close\r\nSec-WebSocket-Version: 13\r\nContent-Length: 0\r\n\r\n"
+ src/Streamly/External/Network/WebSocket/Server.hs view
@@ -0,0 +1,145 @@+-- |+-- Module      : Streamly.External.Network.WebSocket.Server+-- Description : A WebSocket server over TCP+-- License     : BSD-3-Clause+--+-- The side of a server: accepting the upgrade a client asks for, then+-- exchanging messages over the same 'Connection' as a client does.+--+-- > {-# LANGUAGE OverloadedStrings #-}+-- > import Streamly.Data.Fold (drainMapM)+-- > import Streamly.Data.Stream (fold)+-- > import Streamly.External.Network.WebSocket.Server (defaultServerOptions,+-- >                                                    messages, send, serve)+-- >+-- > -- Send back what is received.+-- > main :: IO ()+-- > main = serve "127.0.0.1" 8080 defaultServerOptions $ \\_ connection ->+-- >   fold (drainMapM (send connection)) (messages connection)+--+-- Every upgrade asked properly is accepted, whatever its path: a handler+-- that does not want a client closes its connection. There is no TLS+-- ('acceptOver' takes a connection opened by other means) and no+-- extension.+module Streamly.External.Network.WebSocket.Server+  ( -- * Serving+    ServerOptions (..)+  , defaultServerOptions+  , Upgrade (..)+  , serve+  , listen+  , serveSocket+  , serveSocketWith+  , acceptOver++    -- * Connections+  , Connection+  , Message (..)+  , send+  , receive+  , messages+  , ping+  , pongCount+  , close++    -- * Errors+  , WebSocketError (..)+  ) where++import Control.Exception (SomeException, bracket, catch, throwIO, try)+import Control.Monad (void)+import Data.ByteString (ByteString)+import Network.Socket (Socket, SocketOption (NoDelay), setSocketOption)+import Network.Socket qualified as N (close)+import Streamly.Data.StreamK (fromStream)+import Streamly.External.ByteString (toArray)+import Streamly.External.Network.HTTP (HttpError, Transport (..),+                                       socketTransport)+import Streamly.External.Network.HTTP.Wire (Header, RequestHead (..),+                                            readRequestHeadWithin)+import Streamly.External.Network.TCP (listen, serveConnections)+import Streamly.External.Network.WebSocket.Connection (Connection, Message (..),+                                                       close, established,+                                                       messages, ping,+                                                       pongCount, receive, send)+import Streamly.External.Network.WebSocket.Frame (Side (..),+                                                  WebSocketError (..))+import Streamly.External.Network.WebSocket.Handshake (checkUpgradeRequest,+                                                      refusal, upgradeResponse)+import System.Timeout (timeout)++-- | The bounds of the connections of a server.+data ServerOptions = ServerOptions+  { maxMessageSize :: Int+  -- ^ The largest message accepted, in bytes.+  , openTimeout :: Maybe Int+  -- ^ Microseconds allowed for a client to send its request. 'Nothing'+  -- waits without end.+  , closeTimeout :: Int+  -- ^ Microseconds to wait, once the handler is done, for the client to+  -- answer the closing of the connection.+  }+  deriving stock (Eq, Show)++-- | Messages of at most 64 MiB, thirty seconds for the request and one+-- second to close.+defaultServerOptions :: ServerOptions+defaultServerOptions = ServerOptions {maxMessageSize = 64 * 1024 * 1024, openTimeout = Just 30_000_000, closeTimeout = 1_000_000}++-- | What a client asked for.+data Upgrade = Upgrade+  { path :: ByteString+  -- ^ The path and the query, such as @\/chat?room=1@.+  , headers :: [Header]+  -- ^ The headers of the request, their names in lower case.+  }+  deriving stock (Eq, Show)++-- | Listen on an address and a port, and serve every client with a+-- handler, each in a thread of its own, without end. See 'serveSocket'.+serve :: String -> Int -> ServerOptions -> (Upgrade -> Connection -> IO ()) -> IO ()+serve host port options handler = bracket (listen host port) N.close (\listener -> serveSocket listener options handler)++-- | Serve every client that connects to a listening socket, each in a+-- thread of its own, without end. The connection of a client is closed+-- when its handler returns or throws; what a handler throws, and a client+-- whose request is refused, end that client only and are not reported.+serveSocket :: Socket -> ServerOptions -> (Upgrade -> Connection -> IO ()) -> IO ()+serveSocket listener options handler = serveSocketWith listener $ \peer ->+  acceptOver (socketTransport peer) options handler++-- | Like 'serveSocket', leaving to a function what is done with the TCP+-- connection of each client: a server over TLS does its handshake there,+-- then calls 'acceptOver' with the transport it got. The connection is+-- closed when the function returns or throws.+serveSocketWith :: Socket -> (Socket -> IO ()) -> IO ()+serveSocketWith listener client = serveConnections listener $ \peer -> do+  -- Frames are small and wait for answers: do not hold them back.+  setSocketOption peer NoDelay 1+  client peer++-- | Accept the upgrade asked on a connection that is already open, and+-- use the WebSocket. When the function returns, the connection is closed+-- in order. Opening and closing the transport are up to the caller.+--+-- Throws 'HandshakeFailed' when the client does not ask properly for a+-- WebSocket (it is answered 400), and 'OpenTimedOut' when its request does+-- not come in time.+acceptOver :: Transport -> ServerOptions -> (Upgrade -> Connection -> IO a) -> IO a+acceptOver transport options use = do+  (request, rest) <- opening $+    -- No request for an upgrade needs more than this.+    readRequestHeadWithin (Just 65536) (fromStream transport.receive)+      `catch` \(problem :: HttpError) -> refuse (HandshakeFailed (show problem))+  key <- either refuse pure (checkUpgradeRequest request)+  transport.send (toArray (upgradeResponse key))+  let RequestHead _ path headers = request+  established Server transport rest options.maxMessageSize options.closeTimeout (use Upgrade {path, headers})+  where+    refuse :: WebSocketError -> IO b+    refuse problem = do+      void (try @SomeException (transport.send (toArray refusal)))+      throwIO problem+    opening action = case options.openTimeout of+      Nothing -> action+      Just microseconds -> timeout microseconds action >>= maybe (throwIO OpenTimedOut) pure
+ streamly-websockets.cabal view
@@ -0,0 +1,96 @@+cabal-version:   3.12+name:            streamly-websockets+version:         0.1.0.0+synopsis:        WebSocket clients and servers written with Streamly+description:+  WebSockets (RFC 6455) over plain TCP, for clients and for servers. The+  opening handshake goes through streamly-http, frames are read with+  flatparse parsers from the stream of byte arrays of the connection, and+  the messages received are a stream. Pings are answered, fragmented+  messages put together, and the closing handshake done. TLS through a+  transport of the caller; no extension.++homepage:        https://github.com/GuillaumedeVolpiano/streamly-websockets+license:         BSD-3-Clause+license-file:    LICENSE+author:          Xavier Dectot+maintainer:      Xavier Dectot <xavier@wheredoibegin.fr>+category:        Network, Web, Streamly+build-type:      Simple+tested-with:     GHC ==9.8.4 || ==9.10.3 || ==9.12.4+extra-doc-files:+  CHANGELOG.md+  README.md++source-repository head+  type:     git+  location: https://github.com/GuillaumedeVolpiano/streamly-websockets.git++common shared+  default-language:   GHC2021+  default-extensions:+    DataKinds+    DerivingStrategies+    DisambiguateRecordFields+    DuplicateRecordFields+    ExplicitNamespaces+    GADTs+    LambdaCase+    MonoLocalBinds+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    RoleAnnotations++  ghc-options:+    -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+    -Wunused-packages++library+  import:          shared+  hs-source-dirs:  src+  exposed-modules:+    Streamly.External.Network.WebSocket+    Streamly.External.Network.WebSocket.Frame+    Streamly.External.Network.WebSocket.Handshake+    Streamly.External.Network.WebSocket.Server++  other-modules:   Streamly.External.Network.WebSocket.Connection++  build-depends:+    , base                 >=4.19 && <4.22+    , base64-bytestring    ^>=1.2+    , bytestring           ^>=0.12+    , cryptohash-sha1      ^>=0.11+    , entropy              ^>=0.4+    , flatparse            ^>=0.5+    , network              ^>=3.2+    , stm                  ^>=2.5+    , streamly-bytestring  ^>=0.2.3+    , streamly-core        ^>=0.3.3+    , streamly-flatparse   ^>=0.1+    , streamly-http        ^>=0.1+    , streamly-network-tcp ^>=0.1+    , text                 ^>=2.1++test-suite streamly-websockets-test+  import:         shared+  type:           exitcode-stdio-1.0+  hs-source-dirs: test+  main-is:        Main.hs+  ghc-options:    -threaded+  build-depends:+    , async                ^>=2.2+    , base+    , bytestring+    , network+    , stm+    , streamly-bytestring+    , streamly-core+    , streamly-http+    , streamly-websockets+    , tasty                ^>=1.5+    , tasty-hunit          ^>=0.10+    , tasty-quickcheck     ^>=0.11+    , text+    , websockets           ^>=0.13
+ test/Main.hs view
@@ -0,0 +1,529 @@+-- | Frames on byte arrays cut anywhere; the handshake; then the client+-- against a server of the @websockets@ package, and against servers that+-- send chosen bytes.+module Main (main) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (mapConcurrently, wait, withAsync)+import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)+import Control.Concurrent.STM (atomically, check)+import Control.Exception (bracket, try)+import Control.Monad (forever, void)+import Data.ByteString (ByteString, breakSubstring, isInfixOf, isPrefixOf)+import Data.ByteString qualified as BS (concat, drop, length, null, pack,+                                        replicate, splitAt, take, takeWhile)+import Data.ByteString.Char8 (strip)+import Data.ByteString.Char8 qualified as BS8 (filter, lines, pack)+import Data.ByteString.Lazy (fromStrict)+import Data.Text (Text)+import Data.Text qualified as T (length, pack)+import Network.Socket (Family (AF_INET), ShutdownCmd (ShutdownSend),+                       SockAddr (SockAddrInet), Socket,+                       SocketOption (ReuseAddr), SocketType (Stream), accept,+                       bind, defaultProtocol, setSocketOption, shutdown,+                       socketPort, tupleToHostAddress)+import Network.Socket qualified as N (close, listen, socket)+import Network.Socket.ByteString (recv, sendAll)+import Network.WebSockets (ConnectionException (CloseRequest),+                           ControlMessage (Pong), DataMessage (Text),+                           Message (ControlMessage),+                           PendingConnection (pendingRequest),+                           RequestHead (requestHeaders, requestPath),+                           acceptRequest, defaultConnectionOptions,+                           makePendingConnection, receiveData,+                           receiveDataMessage, runClient, runClientWith,+                           sendBinaryData, sendClose, sendDataMessage, sendPing,+                           sendTextData)+import Network.WebSockets qualified as NWS (Connection, receive)+import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (fold, fromList, toList)+import Streamly.Data.Stream qualified as S (take)+import Streamly.Data.StreamK (fromStream)+import Streamly.External.ByteString (toArray)+import Streamly.External.Network.HTTP (HttpError (..), connect, socketTransport)+import Streamly.External.Network.WebSocket (Config (headers, host, maxMessageSize, openTimeout, port),+                                            Connection,+                                            Message (BinaryMessage, TextMessage),+                                            WebSocketError (ConnectionClosed, HandshakeFailed, MessageTooLarge, OpenTimedOut, ProtocolViolation),+                                            close, config, messages, ping,+                                            pongCount, receive, send,+                                            withConnection, withConnectionOver)+import Streamly.External.Network.WebSocket.Frame (Frame (Frame),+                                                  Opcode (BinaryFrame, CloseFrame, Continuation, PingFrame, TextFrame),+                                                  Side (Client, Server),+                                                  applyMask, encodeFrame,+                                                  readFrame)+import Streamly.External.Network.WebSocket.Handshake (acceptFor)+import Streamly.External.Network.WebSocket.Server (acceptOver,+                                                   defaultServerOptions,+                                                   serveSocket)+import Streamly.External.Network.WebSocket.Server qualified as WSS (ServerOptions (openTimeout),+                                                                    Upgrade (headers, path),+                                                                    listen)+import Test.Tasty (TestTree, defaultMain, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))+import Test.Tasty.QuickCheck (Positive (..), ioProperty, testProperty, (===))++main :: IO ()+main = defaultMain tests++tests :: TestTree+tests =+  localOption (mkTimeout 20_000_000) $+    testGroup+      "streamly-websockets"+      [ testGroup "frames" frames+      , testGroup "against the websockets package" interop+      , testGroup "against chosen bytes" chosen+      , testGroup "the server against the websockets package" serving+      , testGroup "the server against the client, and against chosen bytes" serverSide+      ]++pieces :: Int -> ByteString -> [ByteString]+pieces size bytes+  | BS.null bytes = []+  | otherwise = let (front, back) = BS.splitAt size bytes in front : pieces size back++-- | Read every frame from bytes cut into pieces of a size.+readAll :: Int -> Int -> ByteString -> IO [Frame]+readAll limit size bytes = go (fromStream (fromList (map toArray (pieces size bytes))))+  where+    go input =+      readFrame Client limit input >>= \case+        Nothing -> pure []+        Just (frame, rest) -> (frame :) <$> go rest++violates :: IO a -> IO ()+violates action =+  try action >>= \case+    Left (ProtocolViolation _) -> pure ()+    Left other -> assertFailure ("expected ProtocolViolation, got " <> show other)+    Right _ -> assertFailure "no error, expected ProtocolViolation"++frames :: [TestTree]+frames =+  [ testCase "the examples of RFC 6455, section 5.7" $ do+      encodeFrame Nothing (Frame True TextFrame "Hello") @?= BS.pack [0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]+      encodeFrame (Just (BS.pack [0x37, 0xfa, 0x21, 0x3d])) (Frame True TextFrame "Hello")+        @?= BS.pack [0x81, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58]+      encodeFrame Nothing (Frame False TextFrame "Hel") @?= BS.pack [0x01, 0x03, 0x48, 0x65, 0x6c]+      encodeFrame Nothing (Frame True Continuation "lo") @?= BS.pack [0x80, 0x02, 0x6c, 0x6f]+      encodeFrame Nothing (Frame True PingFrame "Hello") @?= BS.pack [0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]+      BS.take 4 (encodeFrame Nothing (Frame True BinaryFrame (BS.replicate 256 0))) @?= BS.pack [0x82, 0x7E, 0x01, 0x00]+      BS.take 10 (encodeFrame Nothing (Frame True BinaryFrame (BS.replicate 65536 0)))+        @?= BS.pack [0x82, 0x7F, 0, 0, 0, 0, 0, 0x01, 0, 0]+  , testProperty "masking twice gives the payload back" $ \bytes ->+      let payload = BS.pack bytes+          key = BS.pack [1, 2, 254, 255]+       in applyMask key (applyMask key payload) === payload+  , testProperty "frames are read back however the bytes are cut" $ \(Positive size) ->+      ioProperty $ do+        let sent =+              [ Frame False TextFrame "Hel"+              , Frame True PingFrame ""+              , Frame True Continuation "lo"+              , Frame True BinaryFrame (BS.replicate 125 1)+              , Frame True BinaryFrame (BS.replicate 126 2)+              , Frame True BinaryFrame (BS.replicate 70_000 3)+              , Frame True CloseFrame "\3\232bye"+              ]+        received <- readAll 100_000 (size * 7) (BS.concat (map (encodeFrame Nothing) sent))+        pure (received === sent)+  , testCase "no frame in no input" $+      readAll 100 4096 "" >>= (@?= [])+  , testCase "a payload beyond the limit" $+      try (readAll 99 4096 (encodeFrame Nothing (Frame True BinaryFrame (BS.replicate 100 0)))) >>= (@?= Left (MessageTooLarge 99))+  , testCase "a masked frame, as a server must not send" $+      violates (readAll 100 4096 (encodeFrame (Just "abcd") (Frame True TextFrame "Hello")))+  , testCase "input that ends inside a header or a payload" $ do+      violates (readAll 100 4096 (BS.pack [0x81]))+      violates (readAll 1000 4096 (BS.pack [0x82, 0x7E, 0x01]))+      violates (readAll 100 4096 (BS.pack [0x81, 0x05, 0x48, 0x65]))+  , testCase "reserved bits, unknown opcodes, lengths not in their shortest form" $ do+      violates (readAll 100 4096 (BS.pack [0xC1, 0x00]))+      violates (readAll 100 4096 (BS.pack [0x83, 0x00]))+      violates (readAll 100 4096 (BS.pack [0x82, 0x7E, 0x00, 0x7D] <> BS.replicate 125 0))+      violates (readAll 100_000 4096 (BS.pack [0x82, 0x7F, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF] <> BS.replicate 65535 0))+      violates (readAll 100 4096 (BS.pack [0x82, 0x7F, 0x80, 0, 0, 0, 0, 0, 0, 0]))+  , testProperty "a server reads the masked frames of a client, however the bytes are cut" $ \(Positive size) ->+      ioProperty $ do+        let sent = [Frame False TextFrame "Hel", Frame True Continuation "lo", Frame True BinaryFrame (BS.replicate 70_000 3), Frame True CloseFrame "\3\232"]+            go input =+              readFrame Server 100_000 input >>= \case+                Nothing -> pure []+                Just (frame, rest) -> (frame :) <$> go rest+        received <- go (fromStream (fromList (map toArray (pieces (size * 7) (BS.concat (map (encodeFrame (Just "\1\2\254\255")) sent))))))+        pure (received === sent)+  , testCase "a server refuses a frame that is not masked" $+      violates (readFrame Server 100 (fromStream (fromList [toArray (encodeFrame Nothing (Frame True TextFrame "Hello"))])))+  , testCase "control frames fragmented or too long" $ do+      violates (readAll 100 4096 (BS.pack [0x09, 0x00]))+      violates (readAll 1000 4096 (BS.pack [0x89, 0x7E, 0x00, 0x7E] <> BS.replicate 126 0))+  ]++-- | A socket listening on a free port of the loopback interface.+listening :: IO Socket+listening = do+  listener <- N.socket AF_INET Stream defaultProtocol+  setSocketOption listener ReuseAddr 1+  bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+  N.listen listener 1+  pure listener++-- | Serve one connection with the @websockets@ package, and run a client+-- against it. Returns what both return.+withPeer :: (NWS.Connection -> IO a) -> (Config -> IO b) -> IO (a, b)+withPeer serve run =+  bracket listening N.close $ \listener -> do+    port <- socketPort listener+    let accepted = bracket (fst <$> accept listener) N.close $ \peer -> do+          pending <- makePendingConnection peer defaultConnectionOptions+          acceptRequest pending >>= serve+    withAsync accepted $ \server -> do+      result <- run (config "127.0.0.1" (fromIntegral port) "/chat?room=1")+      served <- wait server+      pure (served, result)++-- | Echo data messages until the client closes; 'True' when it closed in+-- order.+echo :: NWS.Connection -> IO Bool+echo connection =+  try (forever (receiveDataMessage connection >>= sendDataMessage connection)) >>= \case+    Left (CloseRequest 1000 _) -> pure True+    Left _ -> pure False+    Right () -> pure False++interop :: [TestTree]+interop =+  [ testCase "text and binary messages come back, and the connection closes in order" $ do+      (closedInOrder, received) <- withPeer echo $ \settings -> withConnection settings $ \connection -> do+        send connection (TextMessage "héllo")+        send connection (BinaryMessage (BS.pack [0, 1, 255]))+        send connection (TextMessage "")+        toList (S.take 3 (messages connection))+      received @?= [TextMessage "héllo", BinaryMessage (BS.pack [0, 1, 255]), TextMessage ""]+      closedInOrder @?= True+  , testCase "over a transport of the caller" $ do+      (closedInOrder, received) <- withPeer echo $ \settings ->+        bracket (connect settings.host settings.port) N.close $ \socket ->+          withConnectionOver (socketTransport socket) settings $ \connection -> do+            send connection (TextMessage "over a transport")+            receive connection+      (received, closedInOrder) @?= (Just (TextMessage "over a transport"), True)+  , testCase "messages of every length form" $ do+      let sizes = [125, 126, 65535, 65536, 300_000]+      (_, received) <- withPeer echo $ \settings -> withConnection settings $ \connection -> do+        mapM_ (\size -> send connection (BinaryMessage (BS.replicate size 7))) sizes+        toList (S.take (length sizes) (messages connection))+      map (\case BinaryMessage bytes -> BS.length bytes; TextMessage text -> negate (T.length text)) received @?= sizes+  , testCase "the path and the extra headers reach the server" $ do+      let serve listener = bracket (fst <$> accept listener) N.close $ \peer -> do+            pending <- makePendingConnection peer defaultConnectionOptions+            let request = pendingRequest pending+            void (acceptRequest pending)+            pure (requestPath request, lookup "X-Extra" (requestHeaders request), lookup "Host" (requestHeaders request))+      bracket listening N.close $ \listener -> do+        port <- socketPort listener+        withAsync (serve listener) $ \server -> do+          withConnection (config "127.0.0.1" (fromIntegral port) "/chat?room=1") {headers = [("X-Extra", "yes")]} (\_ -> pure ())+          seen <- wait server+          seen @?= ("/chat?room=1", Just "yes", Just ("127.0.0.1:" <> BS8.pack (show port)))+  , testCase "a ping of the server is answered while receiving" $ do+      let serve connection = do+            sendPing connection ("are you there" :: ByteString)+            answer <- NWS.receive connection+            sendTextData connection ("done" :: ByteString)+            void (try @ConnectionException (forever (receiveDataMessage connection)))+            pure answer+      (answer, received) <- withPeer serve $ \settings -> withConnection settings receive+      received @?= Just (TextMessage "done")+      answer @?= ControlMessage (Pong "are you there")+  , testCase "the pong to a ping is counted" $ do+      (_, counts) <- withPeer echo $ \settings -> withConnection settings $ \connection -> do+        before <- atomically (pongCount connection)+        ping connection "one"+        send connection (TextMessage "after the ping")+        message <- receive connection+        after <- atomically (pongCount connection)+        pure (before, message, after)+      counts @?= (0, Just (TextMessage "after the ping"), 1)+  , testCase "waiting for a pong in STM, with another thread receiving" $ do+      (_, arrived) <- withPeer echo $ \settings -> withConnection settings $ \connection ->+        withAsync (toList (messages connection)) $ \_ -> do+          ping connection ""+          atomically (pongCount connection >>= check . (> 0))+          pure True+      arrived @?= True+  , testCase "a server that closes ends the messages, and gets its close back" $ do+      let serve connection = do+            sendTextData connection ("last" :: ByteString)+            sendClose connection ("bye" :: ByteString)+            try (forever (receiveDataMessage connection)) >>= \case+              Left (CloseRequest status _) -> pure (Just status)+              Left _ -> pure Nothing+              Right () -> pure Nothing+      (echoed, outcome) <- withPeer serve $ \settings -> withConnection settings $ \connection -> do+        received <- toList (messages connection)+        again <- receive connection+        late <- try (send connection (TextMessage "too late"))+        pure (received, again, late)+      outcome @?= ([TextMessage "last"], Nothing, Left ConnectionClosed)+      echoed @?= Just 1000+  , testCase "after close nothing is sent, and messages still arrive" $ do+      let serve connection = do+            first <- receiveDataMessage connection+            sendTextData connection ("still here" :: ByteString)+            closed <- try @ConnectionException (receiveDataMessage connection)+            pure (first, either (const True) (const False) closed)+      ((first, closed), outcome) <- withPeer serve $ \settings -> withConnection settings $ \connection -> do+        send connection (TextMessage "hello")+        close connection+        close connection+        late <- try (send connection (TextMessage "too late"))+        received <- toList (messages connection)+        pure (late, received)+      outcome @?= (Left ConnectionClosed, [TextMessage "still here"])+      first @?= Text (fromStrict "hello") Nothing+      closed @?= True+  ]++-- | A server that reads the opening request, answers it with a function+-- of the key sent, and ends its side of the connection. Returns the request with the result.+withRawServer :: (ByteString -> [ByteString]) -> (Config -> IO a) -> IO (ByteString, a)+withRawServer answer run =+  bracket listening N.close $ \listener -> do+    port <- socketPort listener+    let serve = bracket (fst <$> accept listener) N.close $ \peer -> do+          request <- readHead peer ""+          mapM_ (sendAll peer) (answer (keyOf request))+          -- Say that nothing more comes, then read until the client is+          -- done, so that nothing is reset.+          shutdown peer ShutdownSend+          drainFrom peer+          pure request+    withAsync serve $ \server -> do+      result <- run (config "127.0.0.1" (fromIntegral port) "/")+      request <- wait server+      pure (request, result)+  where+    readHead peer seen+      | "\r\n\r\n" `isInfixOf` seen = pure seen+      | otherwise = do+          more <- recv peer 4096+          if BS.null more then pure seen else readHead peer (seen <> more)+    drainFrom peer = do+      more <- recv peer 4096+      if BS.null more then pure () else drainFrom peer+    keyOf request =+      strip . BS.takeWhile (/= 13) . BS.drop 18 . snd $ breakSubstring "Sec-WebSocket-Key:" request++-- | The answer that accepts the upgrade, then these frames.+accepting :: [Frame] -> ByteString -> [ByteString]+accepting sent key =+  ("HTTP/1.1 101 Switching Protocols\r\nUpgrade: WebSocket\r\nConnection: keep-alive, Upgrade\r\nSec-WebSocket-Accept: " <> acceptFor key <> "\r\n\r\n")+    : map (encodeFrame Nothing) sent++refused :: (ByteString -> [ByteString]) -> IO ()+refused answer =+  try (withRawServer answer (\settings -> withConnection settings (\_ -> pure ()))) >>= \case+    Left (HandshakeFailed _) -> pure ()+    Left other -> assertFailure ("expected HandshakeFailed, got " <> show other)+    Right _ -> assertFailure "no error, expected HandshakeFailed"++chosen :: [TestTree]+chosen =+  [ testCase "the opening request" $ do+      (request, ()) <- withRawServer (accepting []) (\settings -> withConnection settings (\_ -> pure ()))+      let requestLines = BS8.lines (BS8.filter (/= '\r') request)+      take 1 requestLines @?= ["GET / HTTP/1.1"]+      filter (`elem` requestLines) ["Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Version: 13"]+        @?= ["Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Version: 13"]+  , testCase "the accept value of RFC 6455, section 1.3" $+      acceptFor "dGhlIHNhbXBsZSBub25jZQ==" @?= "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="+  , testCase "a fragmented message is put together, pings in the middle answered" $ do+      let sent =+            [ Frame False TextFrame "Hel"+            , Frame True PingFrame "mid"+            , Frame False Continuation "lo, "+            , Frame True Continuation "world"+            , Frame True BinaryFrame "\1\2"+            ]+      (_, received) <- withRawServer (accepting sent) $ \settings ->+        withConnection settings (toList . messages)+      received @?= [TextMessage "Hello, world", BinaryMessage "\1\2"]+  , testCase "a server that goes without closing ends the messages" $ do+      (_, received) <- withRawServer (accepting [Frame True TextFrame "only"]) $ \settings ->+        withConnection settings (toList . messages)+      received @?= [TextMessage "only"]+  , testCase "the server refuses: another status, a wrong proof, no upgrade, an extension, an endless answer" $ do+      refused (const ["HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"])+      refused (const ["HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"])+      refused (\key -> ["HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " <> acceptFor key <> "\r\n\r\n"])+      refused (\key -> ["HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nSec-WebSocket-Accept: " <> acceptFor key <> "\r\n\r\n"])+      refused (\key -> ["HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Extensions: permessage-deflate\r\nSec-WebSocket-Accept: " <> acceptFor key <> "\r\n\r\n"])+      refused (const ["SSH-2.0-OpenSSH\r\n"])+      refused (\key -> ["HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" <> BS.concat (replicate 2000 "X-Padding: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n") <> "Sec-WebSocket-Accept: " <> acceptFor key <> "\r\n\r\n"])+  , testCase "what breaks the protocol is reported, and what came before delivered" $ do+      let breaking sent = do+            (_, outcome) <- withRawServer (accepting (Frame True TextFrame "fine" : sent)) $ \settings ->+              withConnection settings $ \connection -> do+                first <- receive connection+                second <- try (receive connection)+                third <- receive connection+                pure (first, second, third)+            case outcome of+              (Just (TextMessage "fine"), Left (ProtocolViolation _), Nothing) -> pure ()+              other -> assertFailure ("unexpected: " <> show other)+      breaking [Frame True Continuation "nothing to continue"]+      breaking [Frame False TextFrame "a", Frame True TextFrame "b"]+      breaking [Frame True TextFrame "\255\254"]+      breaking [Frame True CloseFrame "\3"]+  , testCase "a message beyond the limit, in one frame or in several" $ do+      let tooLarge sent = do+            (_, outcome) <- withRawServer (accepting sent) $ \settings ->+              try (withConnection settings {maxMessageSize = 10} receive)+            outcome @?= Left (MessageTooLarge 10)+      tooLarge [Frame True BinaryFrame "12345678901"]+      tooLarge [Frame False BinaryFrame "123456", Frame True Continuation "78901"]+  , testCase "a server that accepts and never answers the upgrade" $+      bracket listening N.close $ \listener -> do+        port <- socketPort listener+        let hold = bracket (fst <$> accept listener) N.close (\_ -> threadDelay 10_000_000)+        withAsync hold $ \_ ->+          try (withConnection (config "127.0.0.1" (fromIntegral port) "/") {openTimeout = Just 150_000} (\_ -> pure ())) >>= (@?= Left OpenTimedOut)+  , testCase "a path that cannot be written is refused before any connection" $+      try (withConnection (config "127.0.0.1" 1 "/a b") (\_ -> pure ())) >>= \case+        Left (InvalidRequest _) -> pure ()+        Left other -> assertFailure ("expected InvalidRequest, got " <> show other)+        Right () -> assertFailure "no error, expected InvalidRequest"+  , testCase "nothing listening is an IOError" $ do+      port <- bracket listening N.close socketPort+      try (withConnection (config "127.0.0.1" (fromIntegral port) "/") (\_ -> pure ())) >>= \case+        Left (_ :: IOError) -> pure ()+        Right () -> assertFailure "no error, expected an IOError"+  ]++-- | Serve with a handler on a free port of the loopback interface, and+-- run something against the port.+withOwnServer :: (WSS.Upgrade -> Connection -> IO ()) -> (Int -> IO a) -> IO a+withOwnServer handler run =+  bracket (WSS.listen "127.0.0.1" 0) N.close $ \listener -> do+    port <- socketPort listener+    withAsync (serveSocket listener defaultServerOptions handler) $ \_ -> run (fromIntegral port)++-- | Send back every message received.+echoBack :: WSS.Upgrade -> Connection -> IO ()+echoBack _ connection = fold (drainMapM (send connection)) (messages connection)++serving :: [TestTree]+serving =+  [ testCase "messages of a websockets client come back, of every length form" $ do+      let sizes = [0, 125, 126, 65535, 65536, 300_000]+      received <- withOwnServer echoBack $ \port ->+        runClient "127.0.0.1" port "/" $ \connection -> do+          sendTextData connection ("héllo" :: Text)+          text <- receiveData connection+          sizesBack <- mapM (\size -> sendBinaryData connection (BS.replicate size 7) >> BS.length <$> receiveData connection) sizes+          sendClose connection ("" :: ByteString)+          pure (text :: Text, sizesBack)+      received @?= ("héllo", sizes)+  , testCase "the handler sees the path and the headers asked" $ do+      asked <- newEmptyMVar+      withOwnServer (\upgrade _ -> putMVar asked upgrade) $ \port ->+        runClientWith "127.0.0.1" port "/chat?room=1" defaultConnectionOptions [("X-Extra", "yes")] (\_ -> pure ())+      upgrade <- takeMVar asked+      (upgrade.path, lookup "x-extra" upgrade.headers, lookup "host" upgrade.headers) @?= ("/chat?room=1", Just "yes", lookup "host" upgrade.headers)+      fmap (isPrefixOf "127.0.0.1") (lookup "host" upgrade.headers) @?= Just True+  , testCase "a ping of the client is answered while the server receives" $ do+      answer <- withOwnServer echoBack $ \port ->+        runClient "127.0.0.1" port "/" $ \connection -> do+          sendPing connection ("are you there" :: ByteString)+          NWS.receive connection+      answer @?= ControlMessage (Pong "are you there")+  , testCase "a handler that returns closes the connection in order" $ do+      outcome <- withOwnServer (\_ connection -> send connection (TextMessage "bye")) $ \port ->+        runClient "127.0.0.1" port "/" $ \connection -> do+          first <- receiveData connection+          closed <- try (receiveDataMessage connection)+          pure (first :: Text, either (\case CloseRequest status _ -> Just status; _ -> Nothing) (const Nothing) closed)+      outcome @?= ("bye", Just 1000)+  , testCase "a client that closes ends the messages of the handler" $ do+      seen <- newEmptyMVar+      withOwnServer (\_ connection -> toList (messages connection) >>= putMVar seen) $ \port ->+        runClient "127.0.0.1" port "/" $ \connection -> do+          sendTextData connection ("one" :: Text)+          sendTextData connection ("two" :: Text)+          sendClose connection ("" :: ByteString)+          void (try @ConnectionException (forever (receiveDataMessage connection)))+      takeMVar seen >>= (@?= [TextMessage "one", TextMessage "two"])+  , testCase "several clients are served at once" $ do+      answers <- withOwnServer echoBack $ \port ->+        mapConcurrently+          ( \index -> runClient "127.0.0.1" port "/" $ \connection -> do+              sendTextData connection (T.pack (show index))+              answer <- receiveData connection+              sendClose connection ("" :: ByteString)+              pure (answer :: Text)+          )+          [1 .. 20 :: Int]+      answers @?= map (T.pack . show) [1 .. 20 :: Int]+  ]++serverSide :: [TestTree]+serverSide =+  [ testCase "the client and the server of this library talk to each other" $ do+      outcome <- withOwnServer echoBack $ \port ->+        withConnection (config "127.0.0.1" port "/") $ \connection -> do+          -- The ping first: its pong then comes before the messages, and is+          -- counted while they are received.+          ping connection "x"+          send connection (TextMessage "héllo")+          send connection (BinaryMessage (BS.replicate 70_000 9))+          answers <- toList (S.take 2 (messages connection))+          pongs <- atomically (pongCount connection)+          pure (answers, pongs)+      outcome @?= ([TextMessage "héllo", BinaryMessage (BS.replicate 70_000 9)], 1)+  , testCase "a ping of the server is answered by the client, and counted" $ do+      counted <- newEmptyMVar+      let handler _ connection = do+            ping connection ""+            -- The pong is counted while something receives.+            withAsync (toList (messages connection)) $ \_ ->+              atomically (pongCount connection >>= check . (> 0))+            atomically (pongCount connection) >>= putMVar counted+      received <- withOwnServer handler $ \port ->+        withConnection (config "127.0.0.1" port "/") (toList . messages)+      takeMVar counted >>= (@?= 1)+      received @?= []+  , testCase "what does not ask for a WebSocket is answered 400, and the server goes on" $ do+      (answers, served) <- withOwnServer echoBack $ \port -> do+        let talk request = bracket (connect "127.0.0.1" port) N.close $ \socket -> do+              sendAll socket request+              recv socket 4096+        plain <- talk "GET / HTTP/1.1\r\nHost: x\r\n\r\n"+        notHttp <- talk "SSH-2.0-OpenSSH\r\n\r\n"+        oldVersion <- talk "GET / HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 8\r\n\r\n"+        after <- withConnection (config "127.0.0.1" port "/") (\connection -> send connection (TextMessage "still serving") >> receive connection)+        pure (map (BS.takeWhile (/= 13)) [plain, notHttp, oldVersion], after)+      answers @?= replicate 3 "HTTP/1.1 400 Bad Request"+      served @?= Just (TextMessage "still serving")+  , testCase "the answer to a proper request, and a frame that is not masked" $ do+      outcome <- newEmptyMVar+      answer <- withOwnServer (\_ connection -> try (receive connection) >>= putMVar outcome) $ \port ->+        bracket (connect "127.0.0.1" port) N.close $ \socket -> do+          sendAll socket "GET /x HTTP/1.1\r\nHost: x\r\nUpgrade: WebSocket\r\nConnection: keep-alive, Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"+          answer <- recv socket 4096+          sendAll socket (encodeFrame Nothing (Frame True TextFrame "not masked"))+          takeMVar outcome >>= \case+            Left (ProtocolViolation _) -> pure ()+            other -> assertFailure ("expected ProtocolViolation, got " <> show other)+          pure answer+      answer @?= "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"+  , testCase "a client that never sends its request" $+      bracket (WSS.listen "127.0.0.1" 0) N.close $ \listener -> do+        port <- socketPort listener+        let silent = bracket (connect "127.0.0.1" (fromIntegral port)) N.close (\_ -> threadDelay 10_000_000)+        withAsync silent $ \_ ->+          bracket (fst <$> accept listener) N.close $ \peer ->+            try (acceptOver (socketTransport peer) defaultServerOptions {WSS.openTimeout = Just 150_000} (\_ _ -> pure ())) >>= (@?= Left OpenTimedOut)+  ]