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 Limitsthe limits of one connectionmax_message: usize-- the largest message (all its frames together)max_frame: usize-- the largest framemax_fragments: usize-- frames per messagesend_frame: usize-- outgoing messages longer than this go as several framesmessages_per_s: u32-- messages (and control frames) a second from the peer, on average; bursts of two secondsbytes_per_s: u32-- bytes a second from the peer, on average; bursts of two secondsidle_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 longwrite_ms: u32-- the longest a send waits for the peer to take bytesmax_connections: usize-- (Acceptor) connections at once
enum WsErrorwhy a WebSocket call failedUrl(String)-- not a ws:// or wss:// URL, or wss:// without a connectorNet(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 bytesTimedOut-- nothing came within idle_ms (the connection is closed), or the handshake took too long
enum Messagea whole messageText(String)-- a text message (UTF-8, checked)Binary(Vec<u8>)-- a binary message
impl Message
fn bytes(&self) -> &[u8]the payload's bytesfn close_code_valid(code: u16) -> boolwhether 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 Rolewhich side a decoder reads for: a server reads masked frames from clients, a client unmasked frames from serversServer-- reads a client's frames: maskedClient-- reads a server's frames: unmasked
enum Frameone event of the incoming framesMessage(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 payloadClose(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)xordatawith the mask, starting at byteoffsetof the payloadfn encode_frame(out: &mut Vec<u8>, op: u8, fin: bool, payload: &[u8], mask: Option<[u8; 4]>)append one frame toout: header, the mask key (a client's frames), the payload (masked)struct Decoderthe 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) -> Decodera decoder for frames arolereads, withinlimfn 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) -> usizebytes fed but not decoded yetfn closed(&self) -> boolwhether 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 WebSocketone end of a WebSocket connection.&selfeverywhere: 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) -> &Limitsthe limits of this connectionfn is_open(&self) -> boolwhether 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 withinms(None: wait as long as it takes) -> Ok(None) when none camefn send_text(&self, s: &str) -> Result<(), WsError>send a text messagefn send_binary(&self, b: &[u8]) -> Result<(), WsError>send a binary messagefn ping(&self, payload: &[u8]) -> Result<(), WsError>send a ping (at most 125 bytes); the peer's pong is taken by recvfn send_fragmented(&self, op: u8, payload: &[u8], frame: usize) -> Result<(), WsError>send a message as frames of exactlyframebytes (tests of the peer's reassembly)fn close(&self, code: u16, reason: &str)close the connection: our close frame withcode(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 closestruct Acceptorthe 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) -> Acceptorconnections with these limits (max_connections at once)fn origins(mut self, list: &[&str]) -> Acceptortake 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: anyfn protocols(mut self, list: &[&str]) -> Acceptorthe subprotocols this side speaks, preferred first; the first the client offers is chosenfn connections(&self) -> usizeconnections open nowfn accept(&self, req: &Request, on_open: impl FnOnce(WebSocket) + Send + 'static) -> Responseanswer an upgrade request: 101 withon_openrunning 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) -> StringSec-WebSocket-Accept for a key: base64 of SHA-1 over the key and the GUIDstruct ClientConfighow a client connectslimits: 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:// throughcfg.connector), the upgrade request, the server's 101 with the right Sec-WebSocket-Accept, all within handshake_ms