CL-HTTP Chapter 6: WebSockets


Reference Manual | Prev: Chapter 5. HTTP Server | Next: Chapter 7. HTML Generation


Contents

  1. 6.1 Overview
  2. 6.2 Exporting an Endpoint
  3. 6.3 The Session API
  4. 6.4 Subprotocols
  5. 6.5 Authentication, Access Control, and Origins
  6. 6.6 Keepalive, Idle Timeouts, and Shutdown
  7. 6.7 The WebSocket Client
  8. 6.8 WebSockets over HTTP/2
  9. 6.9 The ws: and wss: URL Schemes
  10. 6.10 Conditions and Close Codes
  11. 6.11 Configuration Variables
  12. 6.12 Platforms and Deployment
  13. 6.13 Conformance and Limits

6.1 Overview

A WebSocket, defined by RFC 6455, is a bidirectional message channel that starts life as an ordinary HTTP GET. The client asks to upgrade, the server answers 101 Switching Protocols, and from that moment both ends exchange discrete messages over the same TCP connection until either says goodbye. Unlike server-sent events (Chapter 5), which push in one direction over a response body, a WebSocket carries traffic both ways and carries binary as readily as text.

CL-HTTP implements the protocol for both the server and the client, over plain TCP and over TLS, and by either of the two handshakes the standards define: the RFC 6455 upgrade on HTTP/1.1, and RFC 8441's Extended CONNECT on HTTP/2 (section 6.8). An endpoint is written once and serves both. The whole of it is portable code: the same server/websockets.lisp and client/websockets.lisp run on every port, and a session on one Lisp talks to a session on another. What varies by port is the transport beneath: LispWorks and SBCL offer both handshakes and terminate their own TLS, while Genera offers the RFC 6455 handshake and takes its TLS from a proxy in front (section 6.12).

Three properties shape the interface, and knowing them in advance explains most of what follows.

6.2 Exporting an Endpoint

A WebSocket endpoint is an exported URL with translation :websocket and a response function of one argument, the connection:

(defun respond-to-websocket-echo (connection)
  "Echoes every message back to the peer, unchanged, until the session ends."
  (http:with-websocket-messages (message length type connection)
    (http:ws-send-message connection type message :end length)))

(http:export-url #u"/cl-http/echo"
                 :websocket
                 :response-function #'respond-to-websocket-echo
                 :subprotocols '("echo")
                 :documentation "An RFC 6455 echo endpoint: every message comes back unchanged.")

That is the complete endpoint. There is no loop to write, no UTF-8 to encode, no close to remember, and no distinction to draw between a peer that says goodbye and one that simply disappears.

The response function runs on the worker thread that handled the upgrade, and that worker stays with the session for its whole life rather than returning to the pool after a request. When the function returns, or signals, or is thrown out of, the closing handshake runs and the connection is torn down.

Export parameters

ParameterDefaultMeaning
:response-functionrequired A function of one argument, the connection. Checked at export time, so an undefined handler is reported when the site is exported rather than when a client first connects.
:subprotocolsnil The subprotocol names this endpoint will agree to speak, most preferred first. See 6.4.
:timeout*websocket-idle-timeout* Idle seconds before the session gives up on a silent peer. This is the ordinary URL :timeout, not a second knob beside it; the :websocket export merely defaults it to the WebSocket value rather than letting a session inherit *server-timeout*, which is measured in hours.
:max-message-size*websocket-max-message-size* Largest message accepted, summed across the frames of a fragmented message. Exceeding it closes the session with 1009.
:max-frame-size*websocket-max-frame-size* Largest single frame payload accepted. A policy check applied while the payload is pumped, not an allocation.
:send-frame-size*websocket-send-frame-size* Largest payload this end puts in one outbound frame; longer messages are fragmented across continuation frames.
:ping-interval*websocket-ping-interval* Seconds of silence before a keepalive PING.
:pong-timeout*websocket-pong-timeout* Seconds to wait for the PONG before declaring the peer gone.

All the ordinary export keywords apply as well — :authentication-realm, :capabilities, :documentation, :keywords, and the rest — because this is an ordinary URL export.

A plain GET to a WebSocket endpoint, from a browser following a link or from a probe, is answered 426 Upgrade Required rather than treated as an error. The address exists; it simply has no document at it.

6.3 The Session API

The message loop

with-websocket-messages (message length type connection) &body body — runs BODY for each message until the session ends, and returns the peer's close code. For a :text message, MESSAGE is the connection's text buffer, decoded under the session's negotiated charset, and LENGTH the count of valid characters; for :binary, MESSAGE is the assembly buffer and LENGTH the count of valid bytes. The text buffer carries a fill pointer, so the string is the message: length, string= and printing all report what the peer sent, and LENGTH is passed only so that both types hand a handler the same two values.

The loop ends on either of the two ways a session can end: the peer's CLOSE, which the framework has already answered, and an orderly disconnect between messages. Handling both is why this exists. A loop written by hand that tests only for :close spins forever on a peer that simply went away — the classic mistake, and one no handler using this macro can make.

map-websocket-messages connection function is the functional form, calling FUNCTION with (MESSAGE LENGTH TYPE). Every timer the session has — the ping interval, the pong timeout, the idle budget, and the shutdown flag — is consulted here, between messages, which is the only place they can safely run: abandoning a partly-read frame would desynchronise the stream.

Borrowed messages, and how to keep one

Both message buffers are reused for the life of the session, growing to the largest message the connection has carried and staying there. That is what lets a steady session receive without allocating at all, and it is why a buffer allocated per message would be the wrong default in code that sits under every message a server handles. The rule it buys is one sentence:

A received message is valid only until the next one.

For the ordinary handler this costs nothing and can go wrong in no way. map-websocket-messages is synchronous: the next receive cannot begin until your function returns, and CL-HTTP runs one worker per connection, so nothing can overwrite a message while it is being read.

It starts to matter when a handler wants the message to outlive the call — storing it, closing over it, or handing it to another thread. Then:

Deferring a message without doing either is the one way to corrupt a WebSocket session in this design: the next message overwrites bytes the other thread has not read yet, silently and only under load.

It is fair to ask why the framework does not simply hand out a queue of buffers instead. A queue does not fix it. A consumer slower than the producer is overwritten N messages later rather than one message later, so the window widens and the bug survives testing; closing it properly requires back-pressure, which stalls the reader — and with it the PING, PONG and CLOSE frames that have to keep moving while the application thinks. Transferring ownership of the one buffer costs nothing until a handler asks for it, and is exact when it does.

Sending

OperatorDescription
ws-send-text connection string &key start end Sends STRING as one :text message. START and END are character indices. Returns the number of bytes sent, which equals the character count only for an all-ASCII message.
ws-send-message connection type payload &key start end Sends PAYLOAD as one message of TYPE, :text or :binary. Accepts a string and delegates to ws-send-text. A message longer than the connection's send frame size is fragmented automatically.
ws-ping connection &optional payload start end Sends a PING. RFC 6455 section 5.5.2 limits the payload to 125 bytes.
ws-pong connection &optional payload start end Sends a PONG. Answering PINGs is automatic; this is for the unsolicited PONG section 5.5.3 permits as a one-way heartbeat.
ws-close connection &optional code reason Sends CLOSE, advancing the closing handshake, and returns the new state. Defaults to 1000, Normal Closure. Sending a second CLOSE is a no-op, as section 5.5.1 requires.

One thread writes one connection. CL-HTTP runs one worker per connection, so there is exactly one sender per session by construction. An application that broadcasts from another thread introduces a second writer and must order the writes itself.

Receiving by hand

Most handlers never call these, but a protocol that interleaves sending and receiving in its own pattern can:

Text messages are validated as UTF-8 while they accumulate rather than at the end, so an ill-formed message is refused as its bytes arrive instead of after a megabyte has been buffered, and a code point straddling a fragment boundary validates correctly.

The connection

The session object passed to a response function is a websocket-connection. Its readable properties are websocket-connection-subprotocol, websocket-connection-state (:open, :closing-local, :closing-remote, :closed), websocket-connection-role (:server or :client), websocket-connection-close-code and websocket-connection-close-reason, and the three timers websocket-connection-idle-timeout, -ping-interval and -pong-timeout.

During a session the connection is also reachable from the server object as (http:server-websocket-connection http:*server*), which is how a condition reporter finds the session it must close.

6.4 Subprotocols

A subprotocol names the application-level language the two ends will speak over the WebSocket — "chat", "v1.orders", whatever an application defines. The client offers a list in preference order, the server picks one it knows, and the choice comes back in the handshake response.

RFC 6455 section 4.2.2 makes the header optional in both directions. A client that offers none still connects; a server that recognises none of the offered names still connects, with no subprotocol. The endpoint therefore serves an ordinary wscat as readily as a client that names a protocol. The negotiated name, or nil, is on the connection as websocket-connection-subprotocol, kept there rather than passed as an argument because it is a property of the session that outlives any one message.

6.5 Authentication, Access Control, and Origins

Because the upgrade is an ordinary GET dispatched by URL, everything in Chapter 7 applies unchanged:

(http:export-url #u"/chat/private"
                 :websocket
                 :response-function #'respond-to-chat
                 :subprotocols '("chat")
                 :authentication-realm :my-realm
                 :capabilities :chat-access)

An unauthenticated upgrade attempt is answered 401 with a WWW-Authenticate header exactly as a document request would be, and the response function runs only after credentials check out. Subnet access control, virtual hosts, and the access log behave the same way — the request reached them all before any decision about upgrading was made.

Origins. A browser sends an Origin header on every WebSocket handshake, and unlike a form POST, a WebSocket is not subject to the same-origin policy: any page on the web may open a WebSocket to your server, carrying the user's cookies. Restricting origins is therefore the cross-site request forgery defense for WebSocket endpoints. Set *websocket-allowed-origins* to the list of acceptable origin strings, compared case-insensitively; the default nil accepts any origin, which is convenient for testing and wrong for production. A rejected origin is refused before the session starts.

6.6 Keepalive, Idle Timeouts, and Shutdown

A WebSocket session may be quiet for hours, and TCP will not report a peer that has vanished on an idle connection for a very long time. RFC 6455's control frames are the remedy, and CL-HTTP uses them so that an idle session can be told from a dead one.

The session's read wakes every ping-interval seconds. On a wake with nothing received, in order: a shutdown in progress ends the session with 1001; a PONG that arrived means the peer is alive and the idle clock restarts; a PING left unanswered past pong-timeout means the peer is gone though the socket says otherwise; silence past the idle budget closes with 1001; and otherwise, if the ping interval has elapsed, a PING goes out and starts the clock the third case reads.

Because a session notices a shutdown only on its next wake, the grace period must exceed the ping interval — which is why the default grace period is twice the default interval.

Operating on running sessions

6.7 The WebSocket Client

The client opens a session with the same handshake read from the other side, and hands back a connection that speaks the same session API as the server's:

(http:with-websocket-connection (connection "ws://example.com/echo" :subprotocols '("echo"))
  (http:ws-send-text connection "hello")
  (multiple-value-bind (buffer length type) (http:ws-receive-message connection)
    (declare (ignore type))
    (http:ws-decode-text buffer 0 length)))

The request goes out through the ordinary client substrate, so proxies, authentication and TLS all apply. A wss: session is an HTTPS request that opens a session.

Which handshake it uses is negotiated. The RFC 6455 upgrade is an HTTP/1.1 mechanism — Upgrade is hop-by-hop, HTTP/2 does not carry it, and RFC 9113 section 8.1 forbids it — so when a server offers HTTP/2 and says it accepts Extended CONNECT, the client uses that instead, and otherwise it suppresses HTTP/2 for this one request and upgrades. Both produce the same connection. The :http-version argument decides the matter explicitly when a caller cares; see section 6.8.

Every frame a client sends is masked with an unpredictable key, as RFC 6455 sections 5.1 and 5.3 require. The key stream is derived from CL-HTTP's random seed, salted per connection with the handshake key, and allocated only when a connection first masks something. Nothing about it needs configuring.

6.8 WebSockets over HTTP/2

HTTP/2 has no upgrade mechanism — RFC 9113 section 8.1 removed it, and makes Upgrade and Connection malformed fields. RFC 8441 puts the handshake back together out of an Extended CONNECT: a CONNECT request carrying a :protocol pseudo-header naming websocket, sent on one stream of a connection that goes on multiplexing everything else.

CL-HTTP implements it on both sides, and an endpoint needs no changes at all. The same :websocket export serves both transports, the same response function runs, and nothing in the session API distinguishes them: an Extended CONNECT is dispatched as the GET section 5.1 calls it equivalent to, so it travels the ordinary request path — URL interning, virtual host context, authentication, access control, timeouts and logging — and arrives at write-document like any other request.

What differs is only the handshake and what the session owns afterwards:

HTTP/1.1HTTP/2
Request GET with Upgrade: websocket CONNECT with :protocol websocket
Nonce Sec-WebSocket-Key and its accept value none — section 5.1 drops both
Success 101 Switching Protocols 200 OK, since nothing switches
Session owns the socket one stream of a shared connection

That last row is the practical difference. Over HTTP/1.1 a session takes the connection with it and closing the session closes the socket. Over HTTP/2 the connection stays, carrying whatever other streams it was carrying; ending a session ends its stream and nothing else. Sec-WebSocket-Version is still required and still 13, and Sec-WebSocket-Protocol negotiates subprotocols exactly as before.

Serving

Nothing to configure. A server that speaks HTTP/2 advertises SETTINGS_ENABLE_CONNECT_PROTOCOL automatically, which is how a client learns it may ask; RFC 8441 section 3 forbids a client to send an Extended CONNECT before seeing it. An endpoint exported with :websocket then answers either handshake.

A request that is not a handshake still gets 426, a version other than 13 still gets 426 naming the version, and a :protocol this server does not implement is refused — the same three answers as over HTTP/1.1, because they are the same code.

Connecting

websocket-connect takes :http-version:

Negotiating is what makes this worth having: both handshakes produce the same connection object, so a caller that does not care writes nothing different and gets whichever the server prefers. A plain ws: or http: URL is never offered HTTP/2 — there is no ALPN to negotiate it and no prior knowledge to go on.

;; Whatever the server prefers.
(http:with-websocket-connection (connection "wss://example.com/echo")
  (http:ws-send-text connection "hello"))

;; RFC 8441 or nothing.
(http:with-websocket-connection (connection "wss://example.com/echo" :http-version :http/2)
  (http:ws-send-text connection "hello"))

Extending the handshake

Two generic functions carry the difference, should a third transport ever want one. websocket-session-request-p stream &optional headers answers whether a request is an attempt to open a session, and websocket-accept-handshake stream method http-version headers subprotocols validates it and writes the response, returning the subprotocol agreed and the status sent. Both dispatch on the stream, because the stream is what knows which protocol it is speaking. websocket-handle-upgrade sits above them and builds the connection, and is the same function for every protocol.

Note for code written against earlier releases: websocket-handle-upgrade was named websocket-h1-handle-upgrade when HTTP/1.1 was the only transport. Callers of the old name need renaming; its behaviour is unchanged.

6.9 The ws: and wss: URL Schemes

RFC 6455 section 3 defines ws: and wss:, and CL-HTTP interns them as first-class URLs: url:ws-url, default port 80, and url:wss-url, default port 443, which inherit from the same websocket-url-mixin the exported http-websocket-url and https-websocket-url classes use.

A ws: URL names an endpoint, but a request cannot be written to one — the opening handshake is a GET, so what travels is an http: or https: request line. url:websocket-http-url url &optional recache-p returns the same endpoint written the way a request can reach it, caching the answer on first call:

(url:name-string (url:websocket-http-url (url:intern-url "ws://example.com/chat")))
  => "http://example.com/chat"

On a URL that is already an http: or https: WebSocket endpoint the method is the identity, so a caller need not know which form it was handed. websocket-connect uses this, and so may an application that has to render a ws: URL into a page for a browser's WebSocket constructor.

6.10 Conditions and Close Codes

Every WebSocket condition descends from websocket-condition, and the errors from websocket-error. They carry the close code the protocol assigns to that failure, which is how a session that fails reports itself to the peer: the condition reporter sends the CLOSE.

Close CodeMeaningConditions
1000Normal closureThe default for ws-close.
1001Going awayServer shutting down, session idle, or peer unresponsive to keepalive.
1002Protocol error websocket-protocol-error and its subtypes: websocket-invalid-opcode, websocket-reserved-bit-set, websocket-oversized-control-frame, websocket-fragmented-control-frame, websocket-unmasked-frame, websocket-masked-frame, websocket-truncated-frame.
1003Unsupported data websocket-unsupported-data, and websocket-charset-error for a code point outside the session's negotiated charset.
1007Invalid payload data websocket-invalid-payload — a TEXT message from the peer that is not well-formed UTF-8.
1008Policy violationwebsocket-policy-violation.
1009Message too big websocket-message-too-big, websocket-frame-too-large.
1011Internal error websocket-internal-error, the send-side errors websocket-send-error, websocket-send-after-close and websocket-ill-formed-text — and anything else a response function signals.

That last entry is the one an application author should read. A handler that signals an ordinary Lisp error, or an HTTP condition such as document-not-found, ends its session with 1011: the stream stopped being HTTP at the 101, so an HTTP response on it would reach the peer as frame garbage, and section 7.4.1 provides 1011 for an unexpected condition that prevented the request being fulfilled. The bug report still reaches the operator exactly as it would for a failing page. A websocket-error keeps its own code instead, so a message too large still closes 1009 rather than being flattened into a generic failure.

The practical consequence is that a session needs no error handler of its own to fail politely. One is still worth writing where the application can say something more useful than 1011 — a chat endpoint that rejects a malformed command does better to close 1003, or to answer with an application-level error message and keep the session open.

The pairing of 1007 and 1011 is worth noticing, because it is the same fault seen from two sides. A TEXT message arriving with invalid UTF-8 is the peer's error and closes with 1007; a TEXT message handed to ws-send-text with invalid UTF-8 is this end's error, and signalling it at the call that caused it — with the offending message still in the caller's hands — is far more useful than waiting for the peer to disconnect and having to work out why.

Handshake failures are reported before any session exists and are ordinary HTTP conditions: websocket-handshake-failure and websocket-version-unsupported on the server side, and on the client side websocket-server-handshake-failure for a response that is not a well-formed 101 with a correct Sec-WebSocket-Accept, and websocket-subprotocol-mismatch for a server that selects a subprotocol the client did not offer.

An application handler rarely handles any of these. A condition that escapes the response function closes the session with the right code and returns the worker to the pool.

6.11 Configuration Variables

VariableDefaultMeaning
*websocket-allowed-origins*nil Acceptable Origin header values, or NIL to accept any. Set it in production; see 6.5.
*websocket-idle-timeout*600 Seconds of silence before an open session is given up on. Distinct from *persistent-connection-timeout* so that a quiet WebSocket is not reaped by the HTTP scavenger.
*websocket-ping-interval*30 Seconds between keepalive PINGs on an otherwise idle session. Keep it smaller than the idle timeout.
*websocket-pong-timeout*30 Seconds to wait for the PONG before declaring the peer dead.
*character-code-point-limit*char-code-limit One past the largest code point this Lisp's characters can hold. Not a policy but a fact about the port, and the only entry here a site should not change: Genera sets 256. See 6.12.
*websocket-max-message-size*1048576 Largest message accepted, across all frames of a fragmented message. One megabyte is ample for chat and dashboard traffic while keeping abuse bounded.
*websocket-max-frame-size*16777216 Largest single frame payload accepted. Generous because frame size cannot be negotiated away: RFC 6455 defines no header by which a receiver may advertise a limit, and section 5.4 leaves fragmentation entirely to the sender.
*websocket-send-frame-size*65536 Largest payload this end puts in one outbound frame. A send-side chunk size, unrelated to the receive limit above.
*websocket-read-buffer-size*65536 The fixed, pooled buffer a connection reads the wire into. Not related to frame size: a 16 MiB frame traverses this buffer 256 times and nothing holds it whole.
*websocket-shutdown-grace-period*60 Seconds disable-websocket-sessions waits for sessions to say goodbye. Must exceed the ping interval.

Every size and timer here has a per-endpoint counterpart in export-url, so a site sets policy globally and overrides it where an endpoint needs something different.

6.12 Platforms and Deployment

The session layer is portable code — the same server/websockets.lisp and client/websockets.lisp on every port — so what differs between Lisps is not the protocol but the transports underneath it.

PortServerClientRFC 6455 on HTTP/1.1 RFC 8441 on HTTP/2TLS in this image
LispWorksyesyesyesyes yes
SBCLyesyesyesyes yes (pure-tls)
Generayesyesyes no — this port has no HTTP/2 no — terminate in front
Text on Genera is Latin-1; see what a port can represent. The other two reach the whole of Unicode.

Every pairing has been run against every other: a client on each port against a server on each of the others, in both directions. That is what establishes the ports agree about the wire rather than each agreeing with itself.

What a port can represent, and telling the peer

Section 5.6 fixes the wire encoding of a TEXT message as UTF-8 and that is not negotiable. What varies is what the two ends can hold once the bytes are decoded, and on that the ports differ: LispWorks and SBCL reach the whole of Unicode, while Genera's characters are Latin-1 and stop at U+00FF.

Three parties bound a session's code points, and each answers a question the other two cannot.

BoundAnswersDirection
*character-code-point-limit* what this image can hold both — and the only one that can refuse an inbound message
the endpoint's :charset what this endpoint chooses to carryboth
the peer's Accept-Charset what the peer will readwhat we send

A CL-HTTP client states its own repertoire as Accept-Charset on every handshake, over both transports — iso-8859-1 from Genera, utf-8 elsewhere — and a server narrows its endpoint's charset to the widest charset the peer said it accepts. It only ever narrows: acceptance is not capability, so a peer that accepts UTF-8 cannot widen an endpoint that declared Latin-1. A quality of zero refuses one charset specifically; a wildcard imposes nothing; and a charset CL-HTTP does not model imposes nothing rather than refusing the handshake, which RFC 7231 section 5.3.3 permits.

What Accept-Charset cannot do is bound what arrives, because a request header describes what a peer reads and not what it writes. A message carrying a code point this image cannot represent is refused with websocket-charset-error and a 1003 close. On Genera that is reached by U+0100 and above, and it is the honest answer: the alternative is not a wider repertoire but a silent substitution, because code-char there accepts 955 and returns a character that is not the λ U+03BB names. Such a message would even echo correctly, char-code undoing code-char on the way out, while the application held a character it never received.

So an application that must carry arbitrary Unicode on Genera should carry it as a binary message and decode it itself. Binary payloads are octets and are never interpreted — verified byte-exact there including NUL, CR and LF, which the modal streams leave alone because frames are written in binary mode.

Genera, and terminating TLS in front

Genera's networking predates TLS 1.3, so a Genera image serves clear text and something in front of it does the cryptography. This is a deployment arrangement rather than a WebSocket limitation — the same proxy carries the ordinary web site — and it costs the endpoint nothing: wss: is what the browser speaks to the proxy, and the Genera end sees an ordinary ws: upgrade arriving on an ordinary HTTP port.

  browser  ==== wss://www.example.org (TLS) ====>  proxy
                                                     |
                                        ws://10.0.0.5:8443 (clear text)
                                                     |
                                                     v
                                                  Genera

Three things need configuring on the Genera side, and only the third is particular to running behind a proxy at all.

  1. Serve the proxied port as an ordinary HTTP port, and export the endpoint on that port's context.

      (http:enable-http-service :on-ports '(8443))
    
      (http:export-url (url:merge-url "/chat" (http:local-port-context 8443 :http))
                       :websocket
                       :response-function #'respond-to-chat
                       :subprotocols '("chat.v1"))
    

    There is no wss: port to configure and no certificate to install. The port is plain HTTP; the encryption happened upstream.

  2. Make the Host the proxy forwards resolve to that context. CL-HTTP dispatches on Host, and a name it does not recognize is answered 400 Bad Request — not with a WebSocket error, because the request never reaches the endpoint. If the proxy forwards www.example.org while the image knows itself by another name, give it the nickname:

      (http:add-virtual-host-nick-name "www.example.org" 8443
                                       (http:local-port-context 8443 :http))
    

    This failure looks alarming and is trivial. Read the body of the 400 — CL-HTTP names the host it did not recognize, which turns ten minutes of protocol debugging into one line of configuration.

  3. Trust the proxy, so client addresses survive it. Every connection arrives from the proxy's address. Until the proxy is trusted, that address is what access control tests, what the log records, and what per-client accounting counts — every session in the world appearing to come from one host.

      (setq http:*trusted-reverse-proxies* '("10.0.0.1"))
    

    When a request arrives from a trusted address, CL-HTTP takes the effective client from X-Forwarded-For or Forwarded, installs it as the server's address, keeps the real TCP peer in server-reverse-proxy-host and the parsed chain in server-reverse-proxy-forwarded-chain. The list is fail-closed: while it is NIL nothing is trusted and forwarded headers are ignored, which is the safe default, since a client may send X-Forwarded-For too. Trusting a proxy to state client addresses grants it no other right — the list is consulted independently of *read-subnets*, *write-subnets* and *proxy-subnets*.

Configuring the proxy

Caddy needs nothing said about WebSockets. Version 2's reverse_proxy detects the upgrade, hijacks the connection and pipes it both ways; the explicit websocket directive people remember belonged to version 1 and no longer exists.

  www.example.org {
          reverse_proxy 10.0.0.5:8443
  }

nginx is the opposite: it strips hop-by-hop headers by default, so an upgrade must be restored explicitly, and on HTTP/1.1.

  location /chat {
          proxy_pass http://10.0.0.5:8443;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
          proxy_set_header Host $host;
          proxy_read_timeout 3600s;
  }

That last line is the one setting a WebSocket deployment genuinely needs, whatever the proxy. The proxy's idle timeout must exceed *websocket-ping-interval*, or the proxy will cut sessions the server considers healthy — and the tell is unmistakable, because they will die at the same interval every time, under no load, on both ends at once. nginx defaults proxy_read_timeout to 60 seconds, which is shorter than plenty of real sessions are quiet for.

Testing an endpoint

Use a WebSocket client — wscat -c wss://www.example.org/chat, or CL-HTTP's own (6.7), which has the advantage of running inside a Lisp where the endpoint can be inspected while the session is open.

curl deserves a warning. Against any modern proxy curl negotiates HTTP/2, HTTP/2 has no Upgrade, and so a hand-assembled upgrade request is answered 426 Upgrade Required. That is the server behaving correctly, and it reads exactly like a broken handshake. Pass --http1.1, or draw no conclusion.

Building an application

Beyond the echo of http:examples;websocket-echo, four things decide the shape of a real endpoint.

Then set policy: *websocket-allowed-origins* in production, and whatever sizes and timers the traffic wants, globally in 6.11 or per endpoint in export-url. Behind a proxy, do that with the trusted-proxy list already configured — access control and origin policy are only as meaningful as the client address they are testing.

6.13 Conformance and Limits

The implementation is judged by the Autobahn fuzzingclient, the standard external conformance suite for RFC 6455, against the echo endpoint of http:examples;websocket-echo. Across its 517 cases, LispWorks and SBCL return identical results:

Genera has been judged by the same suite and answers 213 OK, 216 unimplemented, 3 informational, 2 non-strict and 83 failed. Every one of the 83 is a declared limit declining traffic rather than a defect, and they divide in two:

It is worth being precise about what that number bought, because the score went down to earn it. Before the ceiling was declared, those 59 cases passed: char-code undid code-char on the way out, so the right bytes came back while the application held a character it never received. A suite that echoes cannot see the difference between representing a character and appearing to. Refusing is worse arithmetic and better behaviour.

The run that first exposed this is also what found the defect behind it: a Genera server used to fail every non-ASCII TEXT message, accented Latin-1 included, because utf-8-encoding-length looked a code point up in a translation table that covers 25 of the 128 characters in 128-255 rather than computing the width from the code point. Autobahn scored 66 section-6 failures where LispWorks and SBCL had none, which is precisely the kind of thing three hand-run sessions in ASCII will never reveal.

The unit suites add 684 checks over the frame codec, the message layer, the handshake, the session layer and the client, and both ports are additionally tested against each other — an SBCL client against a LispWorks server and the reverse — which is what demonstrates the two agree about the wire rather than each agreeing with itself.

Autobahn speaks only HTTP/1.1, so the RFC 8441 transport is judged separately: by each port's client against both servers, and by a purpose-written client that builds HTTP/2 and RFC 6455 frames by hand, so that a session working proves the server right rather than proving two CL-HTTP implementations wrong together. What that checks is the handshake and the session over it — sessions, subprotocol negotiation, mixed-case protocol tokens, 426 for a missing or wrong version, refusal of an unknown :protocol, and ordinary HTTP/2 requests continuing to work alongside. The frame-level conformance those sessions rely on is what Autobahn establishes, and the codec is the same code on both transports.

Not implemented


Reference Manual | Prev: Chapter 5. HTTP Server | Next: Chapter 7. HTML Generation