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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! RFC 6455 §5: the base framing protocol.//!//! Pure, and deliberately so. Nothing here reads a socket or allocates//! anything — a header goes in as octets and comes out as a struct, and a//! struct goes in and comes out as octets. That is what lets the whole of it//! be fuzzed on a string, and it is where every rule that can be decided from//! the header alone is decided.//!//! A WebSocket frame header is two to fourteen octets://!//! ```text//! 0 1 2 3//! 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1//! +-+-+-+-+-------+-+-------------+-------------------------------+//! |F|R|R|R| opcode|M| Payload len | Extended payload length |//! |I|S|S|S| (4) |A| (7) | (16/64) |//! |N|V|V|V| |S| | (if payload len==126/127) |//! | |1|2|3| |K| | |//! +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +//! | Extended payload length continued, if payload len == 127 |//! + - - - - - - - - - - - - - - - +-------------------------------+//! | |Masking-key, if MASK set to 1 |//! +-------------------------------+-------------------------------+//! ```
const std = @import("std");const assert = std.debug.assert;
/// §5.2. The four data opcodes and the three control ones, and the ranges/// reserved for extensions that nobody here has negotiated.pub const Opcode = enum(u4) { continuation = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xa, /// §5.2 reserves 0x3-0x7 for further data frames and 0xb-0xf for further /// control frames. An extension may define one; none has been negotiated, /// so receiving one is a protocol error rather than something to discard /// — unlike HTTP/2, WebSocket has no rule that unknown frames are /// ignorable, because there is no length-prefixed envelope that would let /// a reader skip one safely in every case. _,
/// §5.5: "Control frames are identified by opcodes where the most /// significant bit of the opcode is 1." pub fn isControl(o: Opcode) bool { return @intFromEnum(o) & 0x8 != 0; }
/// Whether this is one of the six the protocol actually defines. pub fn isDefined(o: Opcode) bool { return switch (o) { .continuation, .text, .binary, .close, .ping, .pong => true, _ => false, }; }};
/// §5.5: "All control frames MUST have a payload length of 125 bytes or less/// and MUST NOT be fragmented."pub const max_control_payload_len = 125;
/// The longest header there is: two octets, eight of extended length, four of/// masking key.pub const max_header_len = 14;
pub const Header = struct { fin: bool, /// §5.2: "MUST be 0 unless an extension is negotiated that defines /// meanings for non-zero values." rsv1: bool = false, rsv2: bool = false, rsv3: bool = false, opcode: Opcode, /// §5.3. Present on every client-to-server frame and on no /// server-to-client one. mask: ?[4]u8 = null, payload_len: u64,
/// How many octets this header occupies on the wire. pub fn len(h: Header) usize { var n: usize = 2; if (h.payload_len > 65535) { n += 8; } else if (h.payload_len > 125) { n += 2; } if (h.mask != null) n += 4; return n; }
/// Writes the header into `out`, which must be at least `len()` octets, /// and returns the part of it that was written. pub fn write(h: Header, out: []u8) []u8 { assert(out.len >= h.len()); out[0] = (@as(u8, @intFromBool(h.fin)) << 7) | (@as(u8, @intFromBool(h.rsv1)) << 6) | (@as(u8, @intFromBool(h.rsv2)) << 5) | (@as(u8, @intFromBool(h.rsv3)) << 4) | @intFromEnum(h.opcode);
const mask_bit: u8 = if (h.mask != null) 0x80 else 0; var at: usize = 2; if (h.payload_len > 65535) { out[1] = mask_bit | 127; std.mem.writeInt(u64, out[2..10], h.payload_len, .big); at = 10; } else if (h.payload_len > 125) { out[1] = mask_bit | 126; std.mem.writeInt(u16, out[2..4], @intCast(h.payload_len), .big); at = 4; } else { out[1] = mask_bit | @as(u8, @intCast(h.payload_len)); } if (h.mask) |key| { @memcpy(out[at..][0..4], &key); at += 4; } return out[0..at]; }};
pub const ParseError = error{ /// §5.2: "the minimal number of bytes MUST be used to encode the length". /// /// Refused rather than accepted, and it is worth saying why, because it /// is the one rule here a lenient reader would let through. Two encodings /// of one length is the same shape as the two framing fields that make /// HTTP request smuggling work: it lets two implementations that both /// believe they are conformant disagree about where a frame ends. There /// is nothing to be gained by accepting it and a class of bug to be had. NonMinimalLength, /// §5.2: "the most significant bit MUST be 0" in a 64-bit length. LengthHighBitSet,};
pub const Parsed = struct { header: Header, /// How many octets of the input the header occupied. len: usize,};
/// Reads a header out of the front of `bytes`.////// Returns null when `bytes` does not yet hold a whole one, which is the/// ordinary case on a stream: a caller reads more and asks again. It is not/// an error, and telling the two apart is the whole reason this returns an/// optional rather than erroring on a short buffer.pub fn parse(bytes: []const u8) ParseError!?Parsed { if (bytes.len < 2) return null;
const masked = bytes[1] & 0x80 != 0; const short_len = bytes[1] & 0x7f;
var at: usize = 2; var payload_len: u64 = short_len; switch (short_len) { 126 => { if (bytes.len < 4) return null; payload_len = std.mem.readInt(u16, bytes[2..4], .big); // A length that would have fitted in the seven-bit field. if (payload_len <= 125) return error.NonMinimalLength; at = 4; }, 127 => { if (bytes.len < 10) return null; payload_len = std.mem.readInt(u64, bytes[2..10], .big); if (payload_len >> 63 != 0) return error.LengthHighBitSet; if (payload_len <= 65535) return error.NonMinimalLength; at = 10; }, else => {}, }
var mask: ?[4]u8 = null; if (masked) { if (bytes.len < at + 4) return null; mask = bytes[at..][0..4].*; at += 4; }
return .{ .header = .{ .fin = bytes[0] & 0x80 != 0, .rsv1 = bytes[0] & 0x40 != 0, .rsv2 = bytes[0] & 0x20 != 0, .rsv3 = bytes[0] & 0x10 != 0, .opcode = @enumFromInt(@as(u4, @truncate(bytes[0]))), .mask = mask, .payload_len = payload_len, }, .len = at, };}
/// §5.3's transformation, which is its own inverse: `payload[i] ^= key[i%4]`.////// `offset` is how many octets of this frame's payload have already been/// through it, so that a payload arriving in pieces is unmasked piece by/// piece without buffering the whole of it.pub fn applyMask(key: [4]u8, offset: u64, data: []u8) void { var i: usize = 0; // The tail of a `u64`-at-a-time loop is not worth the alignment argument // here: the payloads that matter are either tiny control frames or large // ones where this is not the bottleneck. while (i < data.len) : (i += 1) { data[i] ^= key[@intCast((offset +% i) % 4)]; }}
const testing = std.testing;
test "RFC 6455 5.7: a single-frame unmasked text message" { const bytes = [_]u8{ 0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f }; const got = (try parse(&bytes)).?; try testing.expectEqual(@as(usize, 2), got.len); try testing.expect(got.header.fin); try testing.expectEqual(Opcode.text, got.header.opcode); try testing.expectEqual(@as(?[4]u8, null), got.header.mask); try testing.expectEqual(@as(u64, 5), got.header.payload_len); try testing.expectEqualStrings("Hello", bytes[got.len..]);
var out: [max_header_len]u8 = undefined; try testing.expectEqualSlices(u8, bytes[0..2], got.header.write(&out));}
test "RFC 6455 5.7: a single-frame masked text message" { const bytes = [_]u8{ 0x81, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58, }; const got = (try parse(&bytes)).?; try testing.expectEqual(@as(usize, 6), got.len); try testing.expectEqual(Opcode.text, got.header.opcode); try testing.expectEqual([4]u8{ 0x37, 0xfa, 0x21, 0x3d }, got.header.mask.?);
var payload: [5]u8 = undefined; @memcpy(&payload, bytes[got.len..]); applyMask(got.header.mask.?, 0, &payload); try testing.expectEqualStrings("Hello", &payload);
var out: [max_header_len]u8 = undefined; try testing.expectEqualSlices(u8, bytes[0..6], got.header.write(&out));}
test "RFC 6455 5.7: a fragmented unmasked text message" { const first = [_]u8{ 0x01, 0x03, 0x48, 0x65, 0x6c }; const last = [_]u8{ 0x80, 0x02, 0x6c, 0x6f };
const a = (try parse(&first)).?; try testing.expect(!a.header.fin); try testing.expectEqual(Opcode.text, a.header.opcode); try testing.expectEqualStrings("Hel", first[a.len..]);
const b = (try parse(&last)).?; try testing.expect(b.header.fin); try testing.expectEqual(Opcode.continuation, b.header.opcode); try testing.expectEqualStrings("lo", last[b.len..]);}
test "RFC 6455 5.7: an unmasked ping and a masked pong" { const ping = [_]u8{ 0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f }; const pong = [_]u8{ 0x8a, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58, };
const a = (try parse(&ping)).?; try testing.expectEqual(Opcode.ping, a.header.opcode); try testing.expect(a.header.opcode.isControl()); try testing.expectEqualStrings("Hello", ping[a.len..]);
const b = (try parse(&pong)).?; try testing.expectEqual(Opcode.pong, b.header.opcode); var payload: [5]u8 = undefined; @memcpy(&payload, pong[b.len..]); applyMask(b.header.mask.?, 0, &payload); try testing.expectEqualStrings("Hello", &payload);}
test "RFC 6455 5.7: the two extended length forms" { // "256 bytes binary message in a single unmasked frame: // 0x82 0x7E 0x0100 [256 bytes of binary data]" const two_byte = [_]u8{ 0x82, 0x7e, 0x01, 0x00 }; const a = (try parse(&two_byte)).?; try testing.expectEqual(@as(u64, 256), a.header.payload_len); try testing.expectEqual(@as(usize, 4), a.len); try testing.expectEqual(Opcode.binary, a.header.opcode);
// "64KiB binary message in a single unmasked frame: // 0x82 0x7F 0x0000000000010000 [65536 bytes of binary data]" const eight_byte = [_]u8{ 0x82, 0x7f, 0, 0, 0, 0, 0, 1, 0, 0 }; const b = (try parse(&eight_byte)).?; try testing.expectEqual(@as(u64, 65536), b.header.payload_len); try testing.expectEqual(@as(usize, 10), b.len);
var out: [max_header_len]u8 = undefined; try testing.expectEqualSlices(u8, &two_byte, a.header.write(&out)); try testing.expectEqualSlices(u8, &eight_byte, b.header.write(&out));}
test "a header that has not all arrived yet is not an error" { try testing.expectEqual(@as(?Parsed, null), try parse(&.{})); try testing.expectEqual(@as(?Parsed, null), try parse(&.{0x81})); // 126 says two more octets of length follow. try testing.expectEqual(@as(?Parsed, null), try parse(&.{ 0x81, 0x7e, 0x01 })); // The mask is four octets and only three are here. try testing.expectEqual(@as(?Parsed, null), try parse(&.{ 0x81, 0x85, 1, 2, 3 }));}
test "a length encoded in more octets than it needed is refused" { // 124 fits in the seven-bit field, so saying it in three is a second way // to say one thing. try testing.expectError(error.NonMinimalLength, parse(&.{ 0x81, 0x7e, 0x00, 0x7c })); try testing.expectError(error.NonMinimalLength, parse(&.{ 0x81, 0x7e, 0x00, 0x00 })); // And 65535 fits in the two-octet field. try testing.expectError(error.NonMinimalLength, parse(&.{ 0x81, 0x7f, 0, 0, 0, 0, 0, 0, 0xff, 0xff, })); // 126 and 127 themselves are the shortest they can be said in. try testing.expectEqual(@as(u64, 126), (try parse(&.{ 0x81, 0x7e, 0x00, 0x7e })).?.header.payload_len); try testing.expectEqual(@as(u64, 65536), (try parse(&.{ 0x81, 0x7f, 0, 0, 0, 0, 0, 1, 0, 0, })).?.header.payload_len);}
test "a 64-bit length with the high bit set is refused" { try testing.expectError(error.LengthHighBitSet, parse(&.{ 0x81, 0x7f, 0x80, 0, 0, 0, 0, 0, 0, 0, }));}
test "masking is its own inverse, in one piece or several" { const key = [4]u8{ 0xde, 0xad, 0xbe, 0xef }; const original = "the quick brown fox jumps over the lazy dog";
var whole: [original.len]u8 = undefined; @memcpy(&whole, original); applyMask(key, 0, &whole); try testing.expect(!std.mem.eql(u8, original, &whole));
// The same thing in pieces, with the offset carrying the position across // each boundary -- which is the only part of this that can be got wrong, // and which a single-chunk test would never reach. var pieces: [original.len]u8 = undefined; @memcpy(&pieces, original); var at: usize = 0; while (at < pieces.len) { const take = @min(7, pieces.len - at); applyMask(key, at, pieces[at..][0..take]); at += take; } try testing.expectEqualSlices(u8, &whole, &pieces);
// And it is its own inverse. applyMask(key, 0, &whole); try testing.expectEqualStrings(original, &whole);}
test "every opcode knows whether it is a control frame" { try testing.expect(!Opcode.continuation.isControl()); try testing.expect(!Opcode.text.isControl()); try testing.expect(!Opcode.binary.isControl()); try testing.expect(Opcode.close.isControl()); try testing.expect(Opcode.ping.isControl()); try testing.expect(Opcode.pong.isControl()); // The reserved ranges, which an extension might one day define. try testing.expect(!@as(Opcode, @enumFromInt(0x3)).isControl()); try testing.expect(@as(Opcode, @enumFromInt(0xb)).isControl()); try testing.expect(!@as(Opcode, @enumFromInt(0x3)).isDefined()); try testing.expect(!@as(Opcode, @enumFromInt(0xf)).isDefined());}
test "a header survives being written and read back" { const cases = [_]Header{ .{ .fin = true, .opcode = .text, .payload_len = 0 }, .{ .fin = false, .opcode = .binary, .payload_len = 125 }, .{ .fin = true, .opcode = .continuation, .payload_len = 126 }, .{ .fin = true, .opcode = .text, .payload_len = 65535 }, .{ .fin = true, .opcode = .binary, .payload_len = 65536 }, .{ .fin = true, .opcode = .ping, .payload_len = 4, .mask = .{ 1, 2, 3, 4 } }, .{ .fin = true, .opcode = .close, .payload_len = 2, .rsv1 = true }, .{ .fin = true, .opcode = .pong, .payload_len = 0, .rsv2 = true, .rsv3 = true }, }; for (cases) |want| { var out: [max_header_len]u8 = undefined; const written = want.write(&out); try testing.expectEqual(want.len(), written.len); const got = (try parse(written)).?; try testing.expectEqual(want, got.header); try testing.expectEqual(written.len, got.len); }}