JFLib

netio/ws.rs#

Source: lib/netio/ws.rs

ws -- WebSocket (RFC 6455): the frame codec, the server side in netio's HTTP server, a client (G7d)

  Acceptor::new(Limits) [.origins(..)] [.protocols(..)]   shared by a Server's handler
  acceptor.accept(&req, |ws| ..) -> Response    101 with the upgrade (on_open runs on a thread
                                    of its own until it returns), or 400 / 403 / 426 / 503
  connect(url, &ClientConfig) -> WebSocket       ws://host[:port]/path (wss:// with a connector)
  WebSocket: recv() / recv_timeout(ms) -> Message; send_text / send_binary / ping / close(code,
             reason); &self everywhere: one thread reads while others send (Arc<WebSocket>)
  Decoder: untrusted bytes -> Frame events, no I/O (the fuzzing in apps/nettest drives it)
  encode_frame(out, opcode, fin, payload, mask)

Limits: a frame's and a message's size, frames per message, messages and bytes a second
(token buckets with a burst of two seconds), idle and handshake timeouts, connections per
Acceptor.  A malformed or excessive peer gets the close code RFC 6455 gives it (1002 protocol,
1007 bad UTF-8 in text, 1008 rate, 1009 too big) and the connection ends; nothing panics, no
allocation goes past the limits.  No extensions (permessage-deflate) are offered or accepted.
/// a continuation frame
OP_CONT: u8 = 0x0
/// a text frame (UTF-8)
OP_TEXT: u8 = 0x1
/// a binary frame
OP_BINARY: u8 = 0x2
/// a close frame
OP_CLOSE: u8 = 0x8
/// a ping
OP_PING: u8 = 0x9
/// a pong
OP_PONG: u8 = 0xA
/// close code: normal end
CLOSE_NORMAL: u16 = 1000
/// close code: the endpoint goes away (server stop, idle)
CLOSE_GOING_AWAY: u16 = 1001
/// close code: a protocol error
CLOSE_PROTOCOL: u16 = 1002
/// close code: a kind of data the endpoint does not take
CLOSE_UNSUPPORTED: u16 = 1003
/// (never sent) a close frame without a code
CLOSE_NO_STATUS: u16 = 1005
/// (never sent) the connection ended without a close frame
CLOSE_ABNORMAL: u16 = 1006
/// close code: a text message that is not UTF-8
CLOSE_BAD_DATA: u16 = 1007
/// close code: a policy was violated (rate limits)
CLOSE_POLICY: u16 = 1008
/// close code: a frame or message over the limits
CLOSE_TOO_BIG: u16 = 1009
/// close code: the server failed
CLOSE_INTERNAL: u16 = 1011
  • struct Limits the limits of one connection

    • max_message: usize -- the largest message (all its frames together)
    • max_frame: usize -- the largest frame
    • max_fragments: usize -- frames per message
    • send_frame: usize -- outgoing messages longer than this go as several frames
    • messages_per_s: u32 -- messages (and control frames) a second from the peer, on average; bursts of two seconds
    • bytes_per_s: u32 -- bytes a second from the peer, on average; bursts of two seconds
    • idle_ms: u32 -- nothing received for this long ends the connection (1001)
    • ping_ms: u32 -- a ping goes out after this long without anything received (0: none)
    • handshake_ms: u32 -- (client) the connection and the server's answer within this long
    • write_ms: u32 -- the longest a send waits for the peer to take bytes
    • max_connections: usize -- (Acceptor) connections at once
  • enum WsError why a WebSocket call failed

    • Url(String) -- not a ws:// or wss:// URL, or wss:// without a connector
    • Net(NetError) -- the network (connect, read, write)
    • Tls(String) -- the TLS layer refused (certificate, handshake)
    • Handshake(String) -- the server's answer was not the upgrade (its status, a missing or wrong header)
    • Closed(u16, String) -- the connection ended: the peer's close code and reason (1005: its close frame had no code, 1006: no close frame came)
    • Protocol(u16) -- this side ended it: the peer broke the protocol or a limit (the close code sent)
    • TooLarge -- a message to send over max_message, or a control payload over 125 bytes
    • TimedOut -- nothing came within idle_ms (the connection is closed), or the handshake took too long
  • enum Message a whole message

    • Text(String) -- a text message (UTF-8, checked)
    • Binary(Vec<u8>) -- a binary message

impl Message

  • fn bytes(&self) -> &[u8] the payload's bytes

  • fn close_code_valid(code: u16) -> bool whether a close code may appear in a close frame (RFC 6455 7.4: 1000-1003, 1007-1014 and the ranges 3000-4999 for libraries and applications)

  • enum Role which side a decoder reads for: a server reads masked frames from clients, a client unmasked frames from servers

    • Server -- reads a client's frames: masked
    • Client -- reads a server's frames: unmasked
  • enum Frame one event of the incoming frames

    • Message(Message) -- a whole message (its fragments put together)
    • Ping(Vec<u8>) -- a ping with its payload (at most 125 bytes)
    • Pong(Vec<u8>) -- a pong with its payload
    • Close(Option<(u16, String)>) -- a close frame: its code and reason (None: it had no code)
  • fn apply_mask(data: &mut [u8], mask: [u8; 4], offset: usize) xor data with the mask, starting at byte offset of the payload

  • fn encode_frame(out: &mut Vec<u8>, op: u8, fin: bool, payload: &[u8], mask: Option<[u8; 4]>) append one frame to out: header, the mask key (a client's frames), the payload (masked)

  • struct Decoder the frames of untrusted bytes: feed what arrives, take events until next() says it needs more. Memory stays below one frame (max_frame) plus one feed (64 KiB) plus one message (max_message); a feed beyond that, or anything malformed, is an error with the close code

impl Decoder

  • fn new(role: Role, lim: Limits) -> Decoder a decoder for frames a role reads, within lim

  • fn feed(&mut self, data: &[u8]) -> Result<(), u16> bytes from the peer; Err(1009) when that would buffer more than one frame and a feed (the caller fed again before next() asked for more)

  • fn buffered(&self) -> usize bytes fed but not decoded yet

  • fn closed(&self) -> bool whether a close frame came (nothing is decoded after it)

  • fn next(&mut self) -> Result<Option<Frame>, u16> the next event: Ok(None) when more bytes are needed, Err(close code) for a malformed or excessive stream (the decoder takes nothing more then)

  • struct WebSocket one end of a WebSocket connection. &self everywhere: one thread may block in recv while others send (Arc<WebSocket>). Dropping it closes the connection (1000) if it is open

impl WebSocket

  • fn peer(&self) -> Option<SocketAddr> the peer's address (server side)

  • fn protocol(&self) -> Option<&str> the subprotocol both sides agreed on (Sec-WebSocket-Protocol)

  • fn limits(&self) -> &Limits the limits of this connection

  • fn is_open(&self) -> bool whether the connection is open (no close sent or received)

  • fn recv(&self) -> Result<Message, WsError> the next message, waiting as long as it takes (pings are answered, the peer's close is returned as Err(Closed))

  • fn recv_timeout(&self, ms: Option<u32>) -> Result<Option<Message>, WsError> the next message within ms (None: wait as long as it takes) -> Ok(None) when none came

  • fn send_text(&self, s: &str) -> Result<(), WsError> send a text message

  • fn send_binary(&self, b: &[u8]) -> Result<(), WsError> send a binary message

  • fn ping(&self, payload: &[u8]) -> Result<(), WsError> send a ping (at most 125 bytes); the peer's pong is taken by recv

  • fn send_fragmented(&self, op: u8, payload: &[u8], frame: usize) -> Result<(), WsError> send a message as frames of exactly frame bytes (tests of the peer's reassembly)

  • fn close(&self, code: u16, reason: &str) close the connection: our close frame with code (1000, 3000-4999 ...) and a reason of at most 123 bytes, then (when no other thread reads) wait up to a second for the peer's close

  • struct Acceptor the server side's check of upgrade requests, shared by a Server's handler: limits for its connections, the origins and subprotocols it takes, the count of open connections

impl Acceptor

  • fn new(lim: Limits) -> Acceptor connections with these limits (max_connections at once)

  • fn origins(mut self, list: &[&str]) -> Acceptor take only requests with one of these Origin headers ("https://game.example.org"; a page on another site cannot open a connection with its visitor's cookies then). Empty: any

  • fn protocols(mut self, list: &[&str]) -> Acceptor the subprotocols this side speaks, preferred first; the first the client offers is chosen

  • fn connections(&self) -> usize connections open now

  • fn accept(&self, req: &Request, on_open: impl FnOnce(WebSocket) + Send + 'static) -> Response answer an upgrade request: 101 with on_open running on a thread of the server's own once the answer is out (the connection ends when it returns), or 400 (not a WebSocket request), 403 (an origin not on the list), 426 (another version) or 503 (max_connections)

  • fn accept_key(key: &str) -> String Sec-WebSocket-Accept for a key: base64 of SHA-1 over the key and the GUID

  • struct ClientConfig how a client connects

    • limits: Limits -- the connection's limits (handshake_ms for the whole handshake)
    • connect_ms: u32 -- the TCP connection within this long (the handshake has limits.handshake_ms in all)
    • protocols: Vec<String> -- subprotocols to offer (Sec-WebSocket-Protocol)
    • origin: Option<String> -- an Origin header (a browser always sends one; servers with an origin list check it)
    • headers: Headers -- further headers of the upgrade request (Authorization, cookies)
    • connector: Option<Connector> -- the TLS layer for wss:// (the same as Client::with_connector's)
  • fn parse_url(url: &str) -> Option<Url> a ws:// or wss:// URL as netio's Url (scheme http / https)

  • fn connect(url: &str, cfg: &ClientConfig) -> Result<WebSocket, WsError> connect to a WebSocket server: TCP (and TLS for wss:// through cfg.connector), the upgrade request, the server's 101 with the right Sec-WebSocket-Accept, all within handshake_ms

Source: docs/API.md in the JFLib repository.