Something went wrong. Try again.
The WebSocket Protocol (RFC 6455) for Zig: framing, a client, and a server handshake on zig-http
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The opening handshake from the other end: RFC 6455 §4.1, as the client.//!//! `handshake.accept` is the server's half and is written against zig-http,//! because a server has a request in hand and an HTTP version to worry about.//! A client has neither. It is sending the first bytes on a fresh connection,//! it knows it is speaking HTTP/1.1 because that is the only version §4.1//! describes, and what comes back is a single response it either accepts or//! gives up on. So this reads and writes the wire directly and needs no HTTP//! library at all -- which is the point, since it lets a client use this//! without taking a dependency on an HTTP server.//!//! What the handshake is actually for is worth keeping in mind while reading//! the checks below. It is not authentication. It is a proof that the thing//! which answered understood the request: a server that merely echoes headers,//! or a cache that replayed an old response, cannot produce the digest, so a//! client that checks it cannot be talked into framing WebSocket messages at//! something that is not a WebSocket endpoint. Every check here is refused//! rather than warned about for that reason.
const std = @import("std");const Io = std.Io;
const Connection = @import("Connection.zig");const handshake = @import("handshake_common.zig");
pub const guid = handshake.guid;pub const version = handshake.version;pub const protocol_name = handshake.protocol_name;pub const accept_token_len = handshake.accept_token_len;pub const acceptToken = handshake.acceptToken;
/// The number of random octets §4.1 requires behind `Sec-WebSocket-Key`.pub const key_len = 16;
/// How long the base64 of those octets is.pub const encoded_key_len = 24;
pub const Header = struct { name: []const u8, value: []const u8,};
pub const Options = struct { /// The resource name: §4.1's request-URI, everything after the authority. /// `/mqtt` for a broker that follows the MQTT specification's advice. resource: []const u8 = "/", /// What goes in `Host`. The authority, so `broker.example:8083` when the /// port is not the scheme's default. host: []const u8, /// Subprotocols to offer, most preferred first. /// /// The server picks at most one, and §4.2.2 forbids it picking one that /// was not offered; `Result.subprotocol` says which, by index, so that a /// caller never has to compare strings that live in a reused buffer. subprotocols: []const []const u8 = &.{}, /// Anything else the request should carry -- `Authorization`, a cookie, a /// broker's own header. Sent verbatim, in order, after the handshake's /// own fields. headers: []const Header = &.{}, /// Where messages are assembled, and therefore the largest message this /// connection will accept. buffer: []u8, /// Masking keys come from here. §5.3 requires that a client's keys be /// unpredictable, so this wants a real source and not a fixed seed. random: std.Random, /// Filled in with the status line's code when the server answers /// something other than 101, which is the difference between "this is not /// a WebSocket endpoint" and "you are not allowed in". status: ?*u16 = null, config: Connection.Config = .{},};
pub const Error = error{ /// The status line was not `HTTP/1.1 101`. The code is in `Options.status` /// if one was asked for; a 401 or 403 is a perfectly ordinary answer and /// means the request needed credentials it did not have. NotSwitchingProtocols, /// The status line was not a status line at all. BadStatusLine, /// §4.2.2: no `Upgrade: websocket`, or no `upgrade` token in `Connection`. NotWebSocket, /// §4.2.2 step 5.4: `Sec-WebSocket-Accept` was missing or was not the /// digest of the key that was sent. Whatever answered had not read the /// request, so nothing after this point can be trusted to be framing. BadAccept, /// The server chose a subprotocol that was not offered, which §4.2.2 /// forbids, or chose one when none was offered. BadSubprotocol, /// The server accepted an extension. None was offered, and agreeing to /// framing that is not implemented would corrupt every message after the /// handshake -- so this is refused rather than ignored. UnexpectedExtension, /// A header line longer than the reader's buffer. HeaderTooLong, /// More header lines than `max_response_headers`. TooManyHeaders,} || Io.Reader.Error || Io.Writer.Error;
/// How many header lines a response may have before this gives up.////// A bound rather than a buffer: the lines are read and discarded as they go,/// so the only thing this protects against is a server that never stops/// sending them.pub const max_response_headers = 64;
pub const Result = struct { connection: Connection, /// Which of `Options.subprotocols` the server chose, or null if it chose /// none. An index rather than the string, because the string lives in the /// reader's buffer and does not survive the first message. subprotocol: ?usize,};
/// Perform the opening handshake and hand back the connection.////// `input` needs a buffer big enough for the longest header line the server/// will send; a few hundred octets is generous for the handshake itself, and/// the buffer is usually sized for the frames that follow anyway.pub fn connect(input: *Io.Reader, output: *Io.Writer, options: Options) Error!Result { var key_bytes: [key_len]u8 = undefined; options.random.bytes(&key_bytes); var key: [encoded_key_len]u8 = undefined; _ = std.base64.standard.Encoder.encode(&key, &key_bytes);
try writeRequest(output, &key, options); try output.flush();
try readStatusLine(input, options.status); return readResponseHeaders(input, output, &key, options);}
fn writeRequest(output: *Io.Writer, key: []const u8, options: Options) Io.Writer.Error!void { try output.print("GET {s} HTTP/1.1\r\n", .{options.resource}); try output.print("Host: {s}\r\n", .{options.host}); try output.print("Upgrade: {s}\r\n", .{protocol_name}); try output.writeAll("Connection: Upgrade\r\n"); try output.print("Sec-WebSocket-Key: {s}\r\n", .{key}); try output.print("Sec-WebSocket-Version: {s}\r\n", .{version}); if (options.subprotocols.len != 0) { try output.writeAll("Sec-WebSocket-Protocol: "); for (options.subprotocols, 0..) |name, i| { if (i != 0) try output.writeAll(", "); try output.writeAll(name); } try output.writeAll("\r\n"); } for (options.headers) |header| { try output.print("{s}: {s}\r\n", .{ header.name, header.value }); } // No `Sec-WebSocket-Extensions`: nothing here implements one, and the // only way to be sure a server does not answer with one is never to ask. try output.writeAll("\r\n");}
fn readStatusLine(input: *Io.Reader, status_out: ?*u16) Error!void { const line = try takeLine(input); // `HTTP/1.1 101 Switching Protocols`, of which only the code matters. var parts = std.mem.splitScalar(u8, line, ' '); const proto = parts.next() orelse return error.BadStatusLine; if (!std.mem.startsWith(u8, proto, "HTTP/")) return error.BadStatusLine; const code_text = parts.next() orelse return error.BadStatusLine; const code = std.fmt.parseInt(u16, code_text, 10) catch return error.BadStatusLine; if (status_out) |out| out.* = code; if (code != 101) return error.NotSwitchingProtocols;}
fn readResponseHeaders( input: *Io.Reader, output: *Io.Writer, key: []const u8, options: Options,) Error!Result { var expected: [accept_token_len]u8 = undefined; const want = acceptToken(key, &expected);
var saw_upgrade = false; var saw_connection = false; var saw_accept = false; var subprotocol: ?usize = null;
for (0..max_response_headers) |_| { const line = try takeLine(input); // The blank line ends the headers and everything after it is frames. if (line.len == 0) { if (!saw_upgrade or !saw_connection) return error.NotWebSocket; if (!saw_accept) return error.BadAccept; return .{ .connection = .init(.{ .input = input, .output = output, .buffer = options.buffer, .role = .client, .random = options.random, .config = options.config, }), .subprotocol = subprotocol, }; }
const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue; const name = std.mem.trim(u8, line[0..colon], " \t"); const value = std.mem.trim(u8, line[colon + 1 ..], " \t");
if (std.ascii.eqlIgnoreCase(name, "upgrade")) { if (!std.ascii.eqlIgnoreCase(value, protocol_name)) return error.NotWebSocket; saw_upgrade = true; } else if (std.ascii.eqlIgnoreCase(name, "connection")) { // A comma-separated list, and `upgrade` need not be alone in it. if (!listContains(value, "upgrade")) return error.NotWebSocket; saw_connection = true; } else if (std.ascii.eqlIgnoreCase(name, "sec-websocket-accept")) { // Constant time is not the point -- the digest is public and // proves comprehension, not identity -- but equality is. if (!std.mem.eql(u8, value, want)) return error.BadAccept; saw_accept = true; } else if (std.ascii.eqlIgnoreCase(name, "sec-websocket-protocol")) { subprotocol = indexOfName(options.subprotocols, value) orelse return error.BadSubprotocol; } else if (std.ascii.eqlIgnoreCase(name, "sec-websocket-extensions")) { if (value.len != 0) return error.UnexpectedExtension; } } return error.TooManyHeaders;}
/// One CRLF-terminated line, with the terminator stripped.////// `takeDelimiterInclusive` rather than the exclusive form on purpose: the/// exclusive one treats the end of the stream as a delimiter, so a response/// that stopped in the middle of a header would come back as a complete line.fn takeLine(input: *Io.Reader) Error![]const u8 { const raw = input.takeDelimiterInclusive('\n') catch |err| switch (err) { error.StreamTooLong => return error.HeaderTooLong, error.EndOfStream => return error.EndOfStream, error.ReadFailed => return error.ReadFailed, }; // The LF is always there; the CR before it is, on anything well formed. var line = raw[0 .. raw.len - 1]; if (line.len != 0 and line[line.len - 1] == '\r') line = line[0 .. line.len - 1]; return line;}
/// Whether a comma-separated field contains `token`, ignoring case and/// surrounding whitespace.fn listContains(field: []const u8, token: []const u8) bool { var it = std.mem.splitScalar(u8, field, ','); while (it.next()) |part| { if (std.ascii.eqlIgnoreCase(std.mem.trim(u8, part, " \t"), token)) return true; } return false;}
fn indexOfName(names: []const []const u8, want: []const u8) ?usize { for (names, 0..) |name, i| { // §4.2.2 leaves the token's case as it was offered, but a server that // changes it has not chosen a different protocol. if (std.ascii.eqlIgnoreCase(name, want)) return i; } return null;}
const testing = std.testing;
/// A fixed PRNG, so that the key in a test is the same every run. A real/// client must not do this -- §5.3 wants unpredictable masking keys -- which/// is why `Options.random` is required rather than defaulted.fn fixedRandom(prng: *std.Random.DefaultPrng) std.Random { prng.* = .init(0x5eed); return prng.random();}
/// Run a handshake against a canned response and hand back what was sent and/// what came of it.fn attempt(response: []const u8, options: struct { subprotocols: []const []const u8 = &.{}, resource: []const u8 = "/", host: []const u8 = "broker.example:8083", headers: []const Header = &.{},}) !struct { result: Error!Result, request: []const u8, status: u16 } { const state = struct { var out_buf: [2048]u8 = undefined; var msg_buf: [256]u8 = undefined; var prng: std.Random.DefaultPrng = undefined; var reader: Io.Reader = undefined; var writer: Io.Writer = undefined; var status: u16 = 0; }; state.reader = .fixed(response); state.writer = .fixed(&state.out_buf); const result = connect(&state.reader, &state.writer, .{ .resource = options.resource, .host = options.host, .subprotocols = options.subprotocols, .headers = options.headers, .buffer = &state.msg_buf, .random = fixedRandom(&state.prng), .status = &state.status, }); return .{ .result = result, .request = state.writer.buffered(), .status = state.status };}
/// The key this fixed seed produces, and the answer a server owes it.fn expectedAccept(request: []const u8, out: *[accept_token_len]u8) []const u8 { const marker = "Sec-WebSocket-Key: "; const at = std.mem.indexOf(u8, request, marker).? + marker.len; return acceptToken(request[at..][0..encoded_key_len], out);}
test "the request is the one RFC 6455 4.1 describes" { const got = try attempt("", .{ .resource = "/mqtt", .subprotocols = &.{ "mqtt", "mqttv3.1" } }); const req = got.request;
try testing.expect(std.mem.startsWith(u8, req, "GET /mqtt HTTP/1.1\r\n")); try testing.expect(std.mem.indexOf(u8, req, "\r\nHost: broker.example:8083\r\n") != null); try testing.expect(std.mem.indexOf(u8, req, "\r\nUpgrade: websocket\r\n") != null); try testing.expect(std.mem.indexOf(u8, req, "\r\nConnection: Upgrade\r\n") != null); try testing.expect(std.mem.indexOf(u8, req, "\r\nSec-WebSocket-Version: 13\r\n") != null); // Offered in order, comma separated. try testing.expect(std.mem.indexOf(u8, req, "\r\nSec-WebSocket-Protocol: mqtt, mqttv3.1\r\n") != null); // No extensions are offered, because none is implemented; a server cannot // answer with one it was never shown. try testing.expect(std.mem.indexOf(u8, req, "Sec-WebSocket-Extensions") == null); // Ends with the blank line that separates the handshake from the frames. try testing.expect(std.mem.endsWith(u8, req, "\r\n\r\n"));
// The key is sixteen octets of base64, which is twenty-four characters. const marker = "Sec-WebSocket-Key: "; const at = std.mem.indexOf(u8, req, marker).? + marker.len; const key = req[at..][0..encoded_key_len]; var decoded: [key_len]u8 = undefined; try std.base64.standard.Decoder.decode(&decoded, key);}
test "extra headers are sent verbatim" { const got = try attempt("", .{ .headers = &.{ .{ .name = "Authorization", .value = "Bearer xyzzy" }, } }); try testing.expect(std.mem.indexOf(u8, got.request, "\r\nAuthorization: Bearer xyzzy\r\n") != null);}
test "a well formed response opens the connection" { // Two passes: the first to learn the key this seed produces, the second to // answer it correctly. A test that hard-coded the digest would be testing // the test. const first = try attempt("", .{}); var token: [accept_token_len]u8 = undefined; const accept = expectedAccept(first.request, &token);
var response: [256]u8 = undefined; const text = try std.fmt.bufPrint(&response, "HTTP/1.1 101 Switching Protocols\r\n" ++ "Upgrade: websocket\r\n" ++ "Connection: Upgrade\r\n" ++ "Sec-WebSocket-Accept: {s}\r\n\r\n", .{accept});
const got = try attempt(text, .{}); const result = try got.result; try testing.expectEqual(@as(?usize, null), result.subprotocol); try testing.expectEqual(@as(u16, 101), got.status);}
test "the subprotocol comes back as an index into what was offered" { const first = try attempt("", .{ .subprotocols = &.{ "mqtt", "other" } }); var token: [accept_token_len]u8 = undefined; const accept = expectedAccept(first.request, &token);
var response: [256]u8 = undefined; const text = try std.fmt.bufPrint(&response, "HTTP/1.1 101 Switching Protocols\r\n" ++ "Upgrade: websocket\r\n" ++ "Connection: Upgrade\r\n" ++ "Sec-WebSocket-Accept: {s}\r\n" ++ "Sec-WebSocket-Protocol: other\r\n\r\n", .{accept});
const got = try attempt(text, .{ .subprotocols = &.{ "mqtt", "other" } }); const result = try got.result; // An index, not a slice: the name lives in the reader's buffer and does // not survive the first message read through it. try testing.expectEqual(@as(?usize, 1), result.subprotocol);}
test "a server that answers wrongly is refused" { const first = try attempt("", .{ .subprotocols = &.{"mqtt"} }); var token: [accept_token_len]u8 = undefined; const accept = expectedAccept(first.request, &token);
var buf: [512]u8 = undefined; const ok_head = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n";
const cases = [_]struct { name: []const u8, text: []const u8, want: anyerror }{ .{ .name = "a status that is not 101", .text = "HTTP/1.1 401 Unauthorized\r\n\r\n", .want = error.NotSwitchingProtocols, }, .{ .name = "not a status line", .text = "quack\r\n\r\n", .want = error.BadStatusLine, }, .{ .name = "no Upgrade field", .text = "HTTP/1.1 101 x\r\nConnection: Upgrade\r\n\r\n", .want = error.NotWebSocket, }, .{ .name = "an Upgrade that is not websocket", .text = "HTTP/1.1 101 x\r\nUpgrade: h2c\r\nConnection: Upgrade\r\n\r\n", .want = error.NotWebSocket, }, .{ .name = "no upgrade token in Connection", .text = "HTTP/1.1 101 x\r\nUpgrade: websocket\r\nConnection: keep-alive\r\n\r\n", .want = error.NotWebSocket, }, .{ .name = "no digest at all", .text = ok_head ++ "\r\n", .want = error.BadAccept, }, .{ .name = "somebody else's digest", .text = ok_head ++ "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n", .want = error.BadAccept, }, }; for (cases) |case| { const got = try attempt(case.text, .{ .subprotocols = &.{"mqtt"} }); testing.expectError(case.want, got.result) catch |err| { std.debug.print("case '{s}' did not fail as expected\n", .{case.name}); return err; }; }
// A subprotocol that was never offered, which §4.2.2 forbids the server // from choosing -- and which would leave both ends framing for different // applications. const smuggled = try std.fmt.bufPrint(&buf, "{s}Sec-WebSocket-Accept: {s}\r\n" ++ "Sec-WebSocket-Protocol: something-else\r\n\r\n", .{ ok_head, accept }); var got = try attempt(smuggled, .{ .subprotocols = &.{"mqtt"} }); try testing.expectError(error.BadSubprotocol, got.result);
// An extension nobody asked for. Agreeing would corrupt every message // after the handshake, so it is refused rather than ignored. var buf2: [512]u8 = undefined; const extended = try std.fmt.bufPrint(&buf2, "{s}Sec-WebSocket-Accept: {s}\r\n" ++ "Sec-WebSocket-Extensions: permessage-deflate\r\n\r\n", .{ ok_head, accept }); got = try attempt(extended, .{ .subprotocols = &.{"mqtt"} }); try testing.expectError(error.UnexpectedExtension, got.result);}
test "header matching ignores case and tolerates lists" { const first = try attempt("", .{}); var token: [accept_token_len]u8 = undefined; const accept = expectedAccept(first.request, &token);
var response: [256]u8 = undefined; const text = try std.fmt.bufPrint(&response, "HTTP/1.1 101 Switching Protocols\r\n" ++ "UPGRADE: WebSocket\r\n" ++ "connection: keep-alive, Upgrade\r\n" ++ "sec-websocket-accept: {s}\r\n\r\n", .{accept});
const got = try attempt(text, .{}); _ = try got.result;}
test "a response that stops in the middle of a header is not a response" { // `takeDelimiterInclusive`, not the exclusive form: the exclusive one // treats the end of the stream as a delimiter, so a truncated header would // read as a complete line and the handshake would judge half a field. const got = try attempt("HTTP/1.1 101 x\r\nUpgrade: websoc", .{}); try testing.expectError(error.EndOfStream, got.result);}
test "a server that never stops sending headers is given up on" { var buf: [8192]u8 = undefined; var w: Io.Writer = .fixed(&buf); try w.writeAll("HTTP/1.1 101 x\r\n"); for (0..max_response_headers + 2) |i| try w.print("X-Pad-{d}: y\r\n", .{i}); try w.writeAll("\r\n");
const got = try attempt(w.buffered(), .{}); try testing.expectError(error.TooManyHeaders, got.result);}