// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The opening handshake: RFC 6455 §4.2 over HTTP/1.1, RFC 8441 §5 over //! HTTP/2. //! //! These are two quite different documents and `accept` is one function, //! because zig-http's `Request` is HTTP semantics rather than a wire format: //! `offersUpgrade` answers from an `Upgrade` field on one version and from a //! `:protocol` pseudo-header on the other, and `Response.upgrade` sends `101` //! on one and `200` on the other. What is left that genuinely differs is one //! thing, and §5 of RFC 8441 says it outright: over HTTP/2 there is no //! `Sec-WebSocket-Key` exchange, "as that functionality has been superseded //! by the :protocol pseudo-header field". //! //! Which is worth a moment, because it is easy to read as a simplification //! and it is not. The `Sec-` prefix exists to prove the request came from //! something that speaks WebSocket rather than from an `XMLHttpRequest` that //! was talked into sending a POST — a header a browser will not let script //! set. A pseudo-header is a stronger version of the same argument: script //! cannot create one at all, because it is not a header, it is part of the //! frame layer. const std = @import("std"); const Io = std.Io; const http = @import("http"); const Request = http.server.Request; const Response = http.server.Response; const ws = @import("websocket"); const Connection = ws.Connection; // Through the module rather than the file: Zig puts each file in exactly // one module, and this one is compiled into `websocket_server` while the // shared pieces live in `websocket`. const common = ws.handshake; pub const guid = common.guid; pub const version = common.version; pub const protocol_name = common.protocol_name; pub const accept_token_len = common.accept_token_len; pub const acceptToken = common.acceptToken; pub const Error = error{ /// The request did not offer to become a WebSocket. Over HTTP/1.1 that /// means no `Upgrade: websocket` with `Connection: upgrade` beside it; /// over HTTP/2, no `:protocol` of `websocket` on a CONNECT. NotWebSocket, /// §4.2.1: the opening handshake is a `GET`. Not reachable over HTTP/2, /// where the method is `CONNECT` by construction. BadMethod, /// §4.2.1: `Sec-WebSocket-Version` was missing or was not `13`. The /// answer is `426` carrying the version this server does speak, which is /// what `refuse` sends. UnsupportedVersion, /// §4.2.1: `Sec-WebSocket-Key` was missing, or was not the base64 of /// sixteen octets. BadKey, /// The client offered a list of subprotocols and this server speaks none /// of them, having been configured to insist. NoSubprotocol, } || Response.UpgradeError; pub const Options = struct { /// Where messages are assembled, and therefore the largest message this /// connection will accept. buffer: []u8, /// The subprotocols this server speaks, most preferred first. /// /// §4.2.2 step 5.5: the server picks one of the client's, or sends no /// `Sec-WebSocket-Protocol` at all. It may **not** pick one the client /// did not offer, and this will not. subprotocols: []const []const u8 = &.{}, /// Whether a client that offers subprotocols must be given one. /// /// The default is to answer without a subprotocol, which is what the RFC /// describes and what a client is obliged to cope with. A server whose /// application only makes sense under a particular subprotocol sets this /// and refuses instead. require_subprotocol: bool = false, connection: Connection.Config = .{}, }; /// Completes the opening handshake and hands back the connection. /// /// A refusal leaves the response untouched — the same contract /// `Response.upgrade` has — so a handler can answer however it likes, and /// `refuse` answers the way the RFC suggests. pub fn accept(req: *Request, res: *Response, options: Options) Error!Connection { if (!req.offersUpgrade(protocol_name)) return error.NotWebSocket; // RFC 8441 §5 over HTTP/2, RFC 6455 §4.2 over HTTP/1.1. The test is what // the request actually arrived as rather than its version, because that // is the thing that decides whether there is a key to answer. const extended_connect = req.connect_protocol != null; if (!extended_connect) { // §4.2.1 step 1: "An HTTP/1.1 or higher GET request". if (!req.method.eql(http.protocol.Method.get)) return error.BadMethod; // §4.2.1 step 6. A client that asks for a version this server does // not speak gets told which one it does, rather than a flat refusal. const asked = req.header("sec-websocket-version") orelse return error.UnsupportedVersion; if (!std.mem.eql(u8, asked, version)) return error.UnsupportedVersion; const key = req.header("sec-websocket-key") orelse return error.BadKey; try checkKey(key); var token: [accept_token_len]u8 = undefined; try res.setHeader("Sec-WebSocket-Accept", acceptToken(key, &token)); } if (try chooseSubprotocol(req, options)) |chosen| { try res.setHeader("Sec-WebSocket-Protocol", chosen); } // No `Sec-WebSocket-Extensions` goes out, ever. §9.1: a server "MUST NOT" // respond with an extension the client did not offer, and the stronger // rule this library follows is that it responds with none at all — // `permessage-deflate` is not implemented, and silently agreeing to an // extension whose framing is not implemented would corrupt every message // after the handshake. const stream = try res.upgrade(protocol_name); return .init(.{ .input = stream.input, .output = stream.output, .buffer = options.buffer, .role = .server, .config = options.connection, }); } /// §4.2.1 step 7: the key is "a base64-encoded value that, when decoded, is /// 16 bytes in length". /// /// Checked rather than taken on trust, and the reason is that the value is /// hashed and handed straight back: a server that echoes an attacker-chosen /// string into a response header of a protocol another implementation may be /// parsing is the shape of a great many bugs, and sixteen octets of base64 is /// a cheap thing to insist on. fn checkKey(key: []const u8) Error!void { const decoder = std.base64.standard.Decoder; const len = decoder.calcSizeForSlice(key) catch return error.BadKey; if (len != 16) return error.BadKey; var decoded: [16]u8 = undefined; decoder.decode(&decoded, key) catch return error.BadKey; } /// The first subprotocol this server speaks that the client also offered. /// /// The server's order wins, which is the choice worth stating: the client's /// list is in *its* order of preference, but it is the server that knows /// which of them it implements well. fn chooseSubprotocol(req: *Request, options: Options) Error!?[]const u8 { if (options.subprotocols.len == 0) return null; const offered = req.headers.has("sec-websocket-protocol"); if (!offered) { if (options.require_subprotocol) return error.NoSubprotocol; return null; } for (options.subprotocols) |mine| { if (req.headers.containsToken("sec-websocket-protocol", mine)) return mine; } if (options.require_subprotocol) return error.NoSubprotocol; return null; } /// Answers a handshake that `accept` refused, the way RFC 6455 suggests. /// /// A version mismatch gets `426` carrying `Sec-WebSocket-Version`, which /// §4.4 says is how a client learns what to ask for next time. Everything /// else is `400`: the request was not a handshake this server could make /// sense of, and there is nothing for the client to retry differently. pub fn refuse(res: *Response, err: Error) Response.Error!void { switch (err) { error.UnsupportedVersion => { res.status = .upgrade_required; try res.setHeader("Sec-WebSocket-Version", version); return res.sendStatus(.upgrade_required); }, error.NotWebSocket, error.NotOffered, error.UpgradeUnavailable => { return res.sendStatus(.upgrade_required); }, error.BadMethod, error.BadKey, error.NoSubprotocol, error.BodyNotConsumed => { return res.sendStatus(.bad_request); }, error.WriteFailed => return error.WriteFailed, error.OutOfMemory => return error.OutOfMemory, error.InvalidField => return error.InvalidField, error.LengthMismatch => return error.LengthMismatch, } } const testing = std.testing; test "RFC 6455 1.3: the worked example of the opening handshake" { // The key and the accept token printed in §1.3, which is the one place // the document does the arithmetic for you. var out: [accept_token_len]u8 = undefined; try testing.expectEqualStrings( "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", acceptToken("dGhlIHNhbXBsZSBub25jZQ==", &out), ); } test "RFC 6455 4.2.2: the example in the section that defines the rule" { var out: [accept_token_len]u8 = undefined; try testing.expectEqualStrings( "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", acceptToken("dGhlIHNhbXBsZSBub25jZQ==", &out), ); // And the token is always the same length, because the digest is. try testing.expectEqual(@as(usize, accept_token_len), out.len); } test "a key that is not sixteen octets of base64 is refused" { try testing.expectError(error.BadKey, checkKey("")); try testing.expectError(error.BadKey, checkKey("not base64 at all!!")); // Valid base64, wrong length: fifteen octets and seventeen. try testing.expectError(error.BadKey, checkKey("AAAAAAAAAAAAAAAAAAAA")); try testing.expectError(error.BadKey, checkKey("AAAAAAAAAAAAAAAAAAAAAAAA")); // Sixteen, which is the one that passes. try checkKey("dGhlIHNhbXBsZSBub25jZQ=="); try checkKey("AAAAAAAAAAAAAAAAAAAAAA=="); }