Every HTTP request processed by CL-HTTP follows a well-defined pipeline from connection acceptance through response generation. Understanding this pipeline is essential for writing response functions and debugging server behavior.
The central data structure is the server object, an instance
of the class http:server. During request processing, the
current server is bound to the special variable
http:*server*. The server object holds all per-request
state: the client stream, method, URL, parsed headers, form data,
status code, and timing information.
The server class hierarchy uses CLOS mixins to compose functionality:
(defclass server
(uri-resolver-mixin
proxy-server-mixin
server-authentication-mixin
server-logging-mixin
basic-server-mixin)
()
(:documentation "The HTTP server class."))
The base class basic-server-mixin provides the essential
slots:
| Accessor | Type | Description |
|---|---|---|
server-stream |
stream | The TCP connection to the client. |
server-address |
integer | Client IP address as a 32-bit integer. |
server-host |
host | Client host object (resolved lazily). |
server-method |
keyword | HTTP method: :get, :head, :post, :put, :delete, etc. |
server-url |
url | The interned URL object for the request. |
server-url-string |
string | The raw URL string from the request line. |
server-headers |
header-set | Parsed request headers (lazy evaluation). |
server-form-data |
list | Parsed form data from POST bodies. |
server-status |
fixnum | HTTP status code of the response. |
server-requests-completed |
fixnum | Number of requests on this persistent connection. |
server-close-connection-p |
boolean | Whether to close after this response. |
server-persistent-connection-p |
boolean | Whether the client supports persistent connections. |
server-timeout |
integer | Idle timeout for this server instance. |
server-process |
process | The thread handling this request. |
Server objects are pooled via defresource as the resource
http-server. They are allocated when a connection arrives,
initialized for each request, and returned to the pool when the
connection closes. This avoids per-request allocation overhead.
When a client connects to a CL-HTTP port, the following sequence executes:
%listen-for-connections) accepts a TCP
connection and dispatches it to a worker thread from the process pool.
The worker calls %provide-service, which allocates a server
object from the http-server resource pool and binds it to
*server*.provide-service
(specialized on basic-server-mixin) runs the main request
loop. For persistent connections, it processes multiple requests on the
same TCP stream:
(defmethod provide-service ((server basic-server-mixin))
(with-connection-noted
(with-standard-server-io-syntax ()
(let ((stream (server-stream server)))
(with-local-port-context ((local-port stream) (local-protocol stream))
(loop initially (clear-white-space stream)
while (%process-request server stream)
do (log-access server)
(unless (http-input-data-available-p-with-timeout
stream *persistent-connection-timeout*)
(close stream :abort (not (live-connection-p stream)))
(return-from provide-service))
(reset-transaction-state server)
finally (close stream :abort (not (live-connection-p stream)))
(log-access server)))))))
%process-request
reads the HTTP request line (e.g., GET /index.html
HTTP/1.1) from the stream using read-delimited-line,
then calls %execute-request to parse it into method, URL
string, and HTTP version via parse-request.header-set object. Headers use lazy evaluation: the raw
bytes are buffered, and individual header values are parsed on first
access. This avoids parsing headers that the response function never
examines.%apply-reverse-proxy-overrides consults
*trusted-reverse-proxies*: when the immediate TCP peer is a
trusted upstream proxy, the X-Forwarded-For (or RFC 7239 Forwarded)
header is parsed and (server-address) is rewritten to the
real client IP. Fail-closed: with the default empty trust list, this is
a no-op. See Section 11.6.*auto-export* is :on-demand,
inferiors are auto-exported on first access. The server then calls
invoke-server-method, which dispatches to the appropriate
method handler (GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE).:computed, :computed-form, or
:html-computed-form export types, the response function
registered at export time is called with the URL and stream. For static
export types (:html-file, :gif-image, etc.),
built-in handlers serve the file from disk.log-access records the transaction to all active access
logs.*persistent-connection-timeout* seconds. If so, it resets
transaction state and processes the next request. Otherwise, it closes
the connection.The function %process-request establishes a handler-bind
environment that catches errors at several levels:
reportable-condition -- HTTP conditions with
status codes (400, 404, 405, etc.) are caught, the status code is set on
the server, and the condition is reported to the client as an HTML error
page via report-status.url:parsing-error -- Malformed URLs produce a
400 Bad Request response.error -- Unexpected errors are reported via
bug-report-error (logged or mailed depending on
*bug-report-destination*). The behavior is controlled by
*debug-server*:
nil -- Errors are silently logged (production mode).t -- All errors invoke the debugger.:conditions -- Only HTTP conditions invoke the debugger.:errors -- Only non-HTTP errors invoke the debugger.Network errors (connection lost, timeout, reset) during response writing are caught and the connection is aborted without generating an error page, since the client is no longer listening.
CL-HTTP provides macros that handle the HTTP response protocol correctly: writing the status line, emitting response headers (content type, length, caching directives, cookies), selecting chunked transfer encoding for HTTP/1.1, and managing character set encoding. Response functions should always use these macros rather than writing raw HTTP to the stream.
The primary macro for writing HTTP responses. It wraps the body that generates content, emitting the status line and all response headers before the body executes.
(with-successful-response (stream content-type
&key (status :success) bytes last-modification
character-set entity-tag expires
location content-location content-language
allow cache-control
additional-headers additional-mime-headers
(termination-line-p t) chunk-function footer-plist
version)
&body body)
stream
content-type
:html, :text, :gif,
:jpeg, :png, :pdf,
:xml, :json, :css,
:javascript, etc. A full MIME type specification
(e.g., (:text :plain :charset :utf-8)) may also be
supplied.
:status (default :success)
:success (200),
:created (201), :accepted (202),
:non-authoritative (203), :no-content (204),
:reset-content (205), :partial-content (206),
:not-modified (304).
:bytes
Content-Length header and does
not use chunked transfer encoding. When nil, HTTP/1.1
clients receive chunked encoding.
:last-modification
If-Modified-Since.
:character-set
:us-ascii, :iso-8859-1,
:utf-8, and other IANA character set names. Should
normally be (url:character-set url).
:entity-tag
(url:entity-tag url), or a universal time may be supplied.
:expires
(url:expiration-universal-time url).
:content-language
(:en) or
(:en-us :fr)) conforming to RFC 1766. Normally
(url:languages url).
:cache-control
(url:response-cache-control-directives url).
:additional-headers
(:header-keyword header-value ...). Used for cookies and
application-specific headers.
:location
:content-location
:chunk-function
(buffer start end), for computing message digests or other
per-chunk processing.
Example: A simple computed response:
(http:export-url #u"/my-app/hello"
:computed
:response-function #'respond-to-hello)
(defun respond-to-hello (url stream)
(http:with-successful-response (stream :html
:expires (url:expiration-universal-time url)
:cache-control (url:response-cache-control-directives url)
:content-language (url:languages url))
(html:with-html-document (:stream stream)
(html:with-document-preamble (:stream stream)
(html:declare-title "Hello" :stream stream))
(html:with-document-body (:stream stream)
(html:with-paragraph (:stream stream)
(write-string "Hello from CL-HTTP!" stream))))))
Example: Returning JSON data:
(defun respond-with-json (url stream)
(let ((json-string "{\"status\": \"ok\", \"version\": \"1.0\"}"))
(http:with-successful-response (stream :json
:bytes (length json-string)
:cache-control '(:no-cache t))
(write-string json-string stream))))
Wraps a response that supports conditional GET. When the client
supplies an If-Modified-Since or If-None-Match
header and the resource has not changed, only a 304 Not Modified
status is returned -- the body is not executed and no content is
transferred. This macro is used for cacheable resources with known
modification times.
(with-conditional-get-response (stream content-type
&key bytes last-modification character-set entity-tag
expires location cache-control content-location
content-language additional-headers
additional-mime-headers (termination-line-p t) version)
&body body)
The parameters are the same as with-successful-response.
Internally, this macro calls handling-conditional-get to
check the request headers, and only executes the body (wrapped in
with-successful-response) when the client's cache is
stale.
Example: Serving a file with conditional GET:
(defun respond-with-document (url stream)
(let* ((pathname (url:translated-pathname url))
(modification-date (file-write-date pathname)))
(http:with-conditional-get-response (stream :html
:last-modification modification-date
:expires (url:expiration-universal-time url)
:cache-control (url:response-cache-control-directives url))
(with-open-file (file-stream pathname :direction :input)
(http:stream-copy-until-eof file-stream stream :text)))))
Guideline: Use with-conditional-get-response for
resources whose modification time is known (files, database records with
timestamps). Use with-successful-response for dynamically
generated content where the full body must always be computed, as it
provides chunked transfer encoding for HTTP/1.1 clients.
Content type keywords map to MIME types via CL-HTTP's MIME type registry. The commonly used keywords include:
| Keyword | MIME Type |
|---|---|
:html | text/html |
:text | text/plain |
:xml | text/xml |
:css | text/css |
:json | application/json |
:javascript | application/javascript |
:pdf | application/pdf |
:gif | image/gif |
:jpeg | image/jpeg |
:png | image/png |
:svg | image/svg+xml |
:mp3 | audio/mpeg |
:mp4 | video/mp4 |
:zip | application/zip |
CL-HTTP's server behavior is controlled by special variables defined
in http:server;variables.lisp. The most important ones are
described here.
*standard-http-port* (default 80)
enable-http-service. Type: fixnum.
*standard-protocol* (default :http)
:http or :https.
*server-timeout* (default 18000, i.e., 5 minutes in 60ths of a second)
*persistent-connection-timeout* (default 10)
*server-life-time* (default 300000, i.e., 5 minutes in milliseconds)
*debug-server* (default nil)
nil (production -- errors logged),
t (all errors enter debugger),
:conditions (only HTTP conditions enter debugger),
:errors (only non-HTTP errors enter debugger).
*auto-export* (default :on-demand)
:on-demand exports URLs when first accessed.
t exports all URLs at directory export time.
nil disables auto-export.
*accept-write-methods* (default :access-controlled)
:none,
:local-host,
:authenticated-users-on-write-subnets,
:write-subnets,
:access-controlled,
:authenticated-users,
:remote-host.
(enable-http-service &key (on-ports *standard-http-port*) (address :all))
on-ports is a port number or list of port numbers.
address specifies the interface to bind to; :all
binds to all interfaces. If the port already has a service defined, it
is re-enabled; otherwise a new service is created via
ensure-http-protocol-on-port.
;; Start serving on port 8000 (http:enable-http-service :on-ports '(8000)) ;; Start serving on multiple ports (http:enable-http-service :on-ports '(8000 8443))
(disable-http-service &key (on-ports :all))
on-ports can be a port
number, a list of port numbers, or :all to stop all
listeners.
;; Stop all services (http:disable-http-service) ;; Stop only port 8000 (http:disable-http-service :on-ports '(8000))
(ensure-http-protocol-on-port port &key (address :all)
(enable-service-p t) (timeout *server-timeout*)
(process-priority *listener-process-priority*)
(backlog *connection-backlog*))
port.
If one already exists, it is returned. If enable-service-p
is true, the service is started immediately. This is the lower-level
function used by enable-http-service.
(listening-on-http-ports)
(http-service-enabled-p &optional (port *standard-http-port*))
CL-HTTP supports HTTP/2 alongside HTTP/1.1 on the same port. HTTP/2 connections are negotiated via ALPN (Application-Layer Protocol Negotiation) during the TLS handshake on HTTPS ports. The HTTP/2 implementation uses a reactor architecture for multiplexed streams.
*http-protocol-version* (default :http/1.1)
:http/0.9, :http/1.0,
:http/1.1, :http/2. Controls ALPN
negotiation and HTTP/2 dispatch. HTTP/1.x connections always use
*http-version* for the status line string.
*http-version* (default "HTTP/1.1")
"HTTP/1.1" because HTTP/2
uses binary framing, not version strings in status lines.
(http2-protocol-enabled-p)
t when the server is configured to accept
HTTP/2 connections. Checks whether *http-protocol-version*
is :http/2.
(set-http-version version)
version is a keyword: :http/2,
:http/1.1, :http/1.0, or
:http/0.9. For :http/2, only
*http-protocol-version* is changed -- the status line
string stays "HTTP/1.1". For HTTP/1.x versions, both
variables are set. Existing connections are not affected; only new
connections use the updated version.
;; Enable HTTP/2 on a running server (http:set-http-version :http/2) ;; Check if HTTP/2 is active (http:http2-protocol-enabled-p) ; => T ;; Downgrade to HTTP/1.1 only (http:set-http-version :http/1.1)
HTTP/2 uses a reactor architecture for multiplexed streams. A single TCP connection carries multiple concurrent request/response streams, each identified by a stream ID. The server multiplexes frames (HEADERS, DATA, SETTINGS, PING, etc.) across these streams. The portable HTTP/2 code dispatches requests through the same URL resolution and response function infrastructure as HTTP/1.1 -- response functions work identically regardless of protocol version.
HTTP/2 connections share the *persistent-connection-timeout*
variable for idle connection reaping, the same as HTTP/1.1 keep-alive
connections.
CL-HTTP defines a comprehensive condition hierarchy for network
errors and HTTP protocol errors. Network conditions are defined in the
platform-specific tcp-stream.lisp files (in the
www-utils package) and are portable across all CL-HTTP
platforms.
All network conditions inherit from network-error,
which itself inherits from simple-error:
network-error
domain-resolver-error
local-network-error
network-resources-exhausted
network-port-in-use
unknown-address
unknown-host-name
remote-network-error
bad-connection-state
connection-closed
connection-lost
host-stopped-responding
connection-error
connection-refused
host-not-responding
protocol-timeout
connection-timed-out ; inherits protocol-timeout + bad-connection-state
network-error-mixin
Key conditions and when they are signalled:
| Condition | When Signalled |
|---|---|
connection-refused |
Remote host refuses TCP connection (client operations). |
connection-closed |
Remote end closed the connection gracefully. |
connection-lost |
Connection reset or broken pipe during I/O. |
protocol-timeout |
No response within the timeout period. |
host-not-responding |
Remote host unreachable or not responding at TCP level. |
unknown-host-name |
DNS resolution failed for a hostname. |
network-resources-exhausted |
No local resources (file descriptors, ports) available. |
network-port-in-use |
The requested port is already bound. |
HTTP-level conditions are defined in
http:server;http-conditions.lisp. These correspond to HTTP
status codes and are signalled by the server when protocol errors occur.
Major classes include:
| Condition | Status | Meaning |
|---|---|---|
bad-syntax-provided | 400 | Malformed request. |
recoverable-unauthorized-client-access | 401 | Authentication required. |
access-forbidden | 403 | Access denied. |
document-not-found | 404 | URL not interned or file missing. |
method-not-allowed | 405 | HTTP method not supported for URL. |
request-timeout | 408 | Client timed out. |
server-internal-error | 500 | Unhandled server error. |
server-not-implemented | 501 | Method not implemented. |
bad-gateway | 502 | Upstream server error (proxy). |
service-unavailable | 503 | Server temporarily overloaded. |
gateway-timeout | 504 | Upstream server timeout (proxy). |
http-version-not-supported | 505 | Client requested unsupported version. |
Response functions run inside the handler-bind environment established
by %process-request. Most HTTP conditions are handled
automatically -- a 404 is sent when a URL is not found, a 400 when the
request is malformed, etc. Response functions can signal conditions
explicitly:
(defun respond-to-resource (url stream)
(let ((data (find-resource url)))
(unless data
(error 'http:document-not-found :url url))
(http:with-successful-response (stream :json)
(write-string (encode-json data) stream))))
For finer-grained control, response functions can establish their own handlers:
(defun respond-with-error-handling (url stream)
(handler-case
(let ((result (compute-expensive-result url)))
(http:with-successful-response (stream :html)
(write-result result stream)))
(database-error (condition)
(error 'http:service-unavailable
:format-string "Database error: ~A"
:format-args (list condition)))))
CL-HTTP supports server-driven content negotiation through request headers. The client declares its preferences; the server selects the best representation.
URLs can be exported with language metadata using the
:language keyword to export-url. The
:content-language keyword to
with-successful-response emits the
Content-Language response header. Language tags follow RFC
1766 (two-letter ISO 639 code with optional ISO 3166 country subtag):
(http:export-url #u"/docs/readme"
:html-file
:pathname "http:docs;readme.html"
:language :en-us)
;; In a computed response:
(http:with-successful-response (stream :html
:content-language '(:en-us))
...)
The :character-set parameter to
with-successful-response specifies the character encoding
of text responses. The default is :iso-8859-1 per the HTTP
specification. For UTF-8 content:
(http:with-successful-response (stream :html
:character-set :utf-8)
...)
The character set is normally stored as a URL property and retrieved
via (url:character-set url).
CL-HTTP supports content transfer encodings including identity (no encoding) and chunked transfer encoding for HTTP/1.1. The response macros automatically select the appropriate encoding based on the client version and whether the content length is known.
CL-HTTP provides platform-specific UTF-8 support for transmitting Unicode content over HTTP. The implementation differs by platform:
base-char socket streams internally.
UTF-8 encoding and decoding are handled explicitly by the TCP stream
layer in http:lw;server;tcp-stream.lisp. The macros
with-character-output-encoding and
with-character-input-encoding switch the stream between
Latin-1 (the default) and UTF-8 modes. The function
utf-8-decode-unicode-characters-from-malformed-string
handles strings that arrive as raw UTF-8 byte sequences in
base-char arrays.
with-character-output-encoding and
with-character-input-encoding macros still operate but
delegate to SBCL's native encoding support. The core
utf-8-encode-unicode-character and
utf-8-decode functions are retained because they are
used by URL percent-encoding in http:server;utils.lisp.
:ascii, :utf-8, and :binary
modes. The utf-8-input-mode method on the TCP stream
switches from ASCII translation to UTF-8 decoding, managing buffer
state (index, start, end) and cleaning up the ASCII translation
layer (at-cr-flag, untranslate-window) on mode entry.
The key macros for character encoding are defined in
http:server;headers.lisp with platform-specific
implementations in each port's tcp-stream.lisp:
(with-character-output-encoding (stream character-set &optional error-p) &body body) (with-character-input-encoding (stream character-set &optional error-p) &body body)
CHARACTER-SET must be one of
*translated-character-encodings*, typically
:utf-8, :iso-8859-1, or
:us-ascii. If ERROR-P is non-null, an
error is signalled for untranslatable character sets.
These macros are normally called implicitly by
with-successful-response when the
:character-set parameter is supplied. Direct use is
needed only for fine-grained control within a response body:
;; Switch to UTF-8 for a specific section of output (with-character-output-encoding (stream :utf-8) (write-string unicode-content stream))
(utf-8-encoding-length character)
(utf-8-encode-unicode-character character)
escape-character-as-utf-8.
(utf-8-number-of-bytes first-byte)
(utf-8-decode byte-sequence &optional start end)
To serve UTF-8 content, set the character set on the URL at export time. The response macros then handle encoding automatically:
;; Export with UTF-8 character set
(http:export-url #u"/my-app/page"
:computed
:response-function #'my-response
:character-set :utf-8
:language :en)
;; The response function gets UTF-8 encoding automatically
(defmethod my-response ((url http-url) stream)
(http:with-successful-response (stream :html
:character-set (url:character-set url))
;; Output is UTF-8 encoded on the wire
(html:with-html-document (:stream stream)
...)))
When *content-negotiate-directory-views* is non-null,
clients can request specific directory listing formats via the
Accept header. This allows the same directory URL to return
HTML, plain text, or other representations depending on client
preference.
CL-HTTP provides functions for setting and reading HTTP cookies. Cookies are set via response headers and read from request headers.
Use make-set-cookie-header-value to create a cookie
specification, then pass it via the :additional-headers
parameter of with-successful-response:
(make-set-cookie-header-value name value
&key expires max-age version port-list domain path
comment comment-url secure discard http-only)
=> cookie-spec
name (keyword)
value (string)
:expires (universal-time)
:max-age (integer)
:domain (string)
:path (string)
/.
:secure (boolean)
:http-only (boolean)
Example: Setting a session cookie:
(defun respond-with-cookie (url stream)
(let ((cookie-headers
(list :set-cookie
(http:make-set-cookie-header-value
:session-id "abc123"
:path "/"
:http-only t
:secure t))))
(http:with-successful-response (stream :html
:additional-headers cookie-headers)
(html:with-html-document (:stream stream)
(html:with-document-preamble (:stream stream)
(html:declare-title "Cookie Set" :stream stream))
(html:with-document-body (:stream stream)
(html:with-paragraph (:stream stream)
(write-string "Session cookie has been set." stream)))))))
The macro set-cookie-http-headers provides a higher-level
interface for setting multiple cookies at once:
(set-cookie-http-headers (:session-id session-value :path "/" :http-only t) (:preference pref-value :max-age 86400 :path "/")) => (:set-cookie cookie-spec)
The expansion is gated on
(user-agent-capability-p :cookies ...) for the current
request -- the macro returns NIL (no headers emitted) for
user-agents whose profile does not include :cookies. All
modern browsers ride the catchall profile and receive cookies; explicit
non-browser profiles (:curl, :wget,
:python-requests, etc.) do not. See
5.11 User-Agent Capabilities for
how to extend or override the capability profiles.
Use the with-cookie-values macro to bind variables to
cookie values sent by the client:
(with-cookie-values ((variables &key (headers '*headers*)) &body body)
Within the body, cookies is bound to the full cookie
property list, and the macro get-cookie retrieves
individual cookie values by keyword:
(defun respond-with-greeting (url stream)
(http:with-cookie-values ((session-id username))
(http:with-successful-response (stream :html)
(html:with-html-document (:stream stream)
(html:with-document-preamble (:stream stream)
(html:declare-title "Greeting" :stream stream))
(html:with-document-body (:stream stream)
(html:with-paragraph (:stream stream)
(cond (username
(format stream "Welcome back, ~A!" username))
(session-id
(write-string "Welcome back." stream))
(t
(write-string "Welcome, new visitor." stream)))))))))
The get-cookie local macro can also be used directly
within the body:
(http:with-cookie-values (())
(let ((theme (get-cookie :theme)))
...))
CL-HTTP has a flexible logging system based on CLOS log classes. Access logs record HTTP transactions to files and/or dynamic log windows. The logging system supports multiple simultaneous logs, per-port log assignment, and pluggable log formats.
When the server runs behind an external reverse proxy (Caddy, nginx,
HAProxy, etc.), declare the proxy's IP in
*trusted-reverse-proxies* so the access log records the
real client IP rather than the proxy's. See
Section 11.6.
The log class hierarchy provides several predefined formats:
| Class | Description |
|---|---|
common-file-log |
Standard Common Log Format (CLF): host, ident, user, date, request, status, bytes. |
extended-common-file-log |
CLF plus Referer and User-Agent
fields (tab-delimited). |
server-common-file-log |
CLF excluding proxy requests, with compressed file support. |
server-extended-common-file-log |
Extended CLF excluding proxy requests, with compressed file support. |
http-log |
CLF with dynamic logging and window notifications. |
*log-access-log-class*
(setq http:*log-access-log-class* 'http:extended-common-file-log)
(intern-access-log name &key port directory (class *log-access-log-class*) (if-does-not-exist :error))
name
is a string naming the log. port specifies which port's
transactions to record. directory is the pathname for log
files. If if-does-not-exist is :create, a
new log is created when none matches.
(log-file-logging-on log-or-logs &optional on-p)
log-or-logs may be a
single log or a list. When on-p is true, transactions are
written to disk.
(log-dynamic-logging-on log-or-logs &optional on-p)
(current-access-logs)
(standard-access-logs port)
(start-log-queue log)
(ensure-current-log)
The Common Log Format (CLF) produces lines of the form:
192.168.1.100 - - [2026-03-30 14:22:05] "GET /index.html HTTP/1.1" 200 3856
Fields: remote host, RFC 931 identity (always -),
authenticated user (or -), date/time, request line, status
code, response bytes.
The Extended Common Log Format appends the Referer and
User-Agent headers, tab-delimited:
192.168.1.100 - - [2026-03-30 14:22:05] "GET /index.html HTTP/1.1" 200 3856 http://example.com/ Mozilla/5.0
CL-HTTP can parse its own log files for analysis:
(parse-log-file log pathname &key log-format stream)
log-format defaults to *default-log-line-parser*
(normally :common-log-format). Available formats:
:common-log-format,
:extended-common-log-format,
:post-log-format.
;; In your server initialization: (setq http:*log-access-log-class* 'http:extended-common-file-log) ;; After enabling HTTP service: (let ((logs (http:standard-access-logs 8000))) (http:log-file-logging-on logs t) ; enable file logging (http:log-dynamic-logging-on logs nil)) ; disable dynamic logging in production
CL-HTTP provides a portable bug reporting facility that can send
reports to a log window, a file (in Emacs RMAIL BABYL format), or
via SMTP mail. The destination is controlled by
*bug-report-destination*.
*bug-report-destination* — Variable
:log-window — Report in the notification window (default).
:file — Append to *bug-report-pathname* in BABYL format, readable by Emacs RMAIL.
:mail — Send by email via SMTP (requires SMTP system).
:none — Do not report.
*bug-report-pathname* — Variable
*bug-report-destination*
is :file. Default: #p"http:logs;bugs;bug-reports.text".
The file is created automatically on first write with a BABYL header.
*bug-http-server* — Variable
:mail.
Computed from *server-bug-list* and *default-mailer-host*.
(report-bug to subject format-string &rest format-args) — Function
format to FORMAT-STRING and
FORMAT-ARGS. If FORMAT-STRING is a function, it is called
with a stream to produce the bug report body. Dispatches on
*bug-report-destination*.
(log-bug-report-to-file pathname to subject bug-report) — Function
*bug-report-destination*.
;; Log bugs to a file (readable by Emacs M-x rmail)
(setf http:*bug-report-destination* :file)
(setf http:*bug-report-pathname* #p"http:logs;bugs;bug-reports.text")
;; Or send bugs by email
(setf http:*bug-report-destination* :mail)
;; Direct logging from a subsystem
(http:log-bug-report-to-file #p"http:logs;bugs;h2-bugs.text"
"bug-cl-http@cl-http.com" "H2 reactor error"
(lambda (stream)
(format stream "Condition: ~A~%" condition)
(write-stack-backtrace stream)))
CL-HTTP supports two server push mechanisms: Server-Sent Events
(SSE) and legacy Netscape multipart push. SSE is the preferred
approach for new code. The with-server-push macro
abstracts over both, with :push-type :sse (default) or
:push-type :multipart.
Server-Sent Events provide server-to-client push over standard HTTP.
SSE is defined by the WHATWG
HTML Living Standard Section 9.2. It replaces the legacy Netscape
server push (multipart/x-mixed-replace) with a simpler
wire format supported by all modern browsers via the
EventSource JavaScript API.
SSE works over HTTP/1.1 (chunked transfer encoding) and HTTP/2
(long-lived DATA stream). The server responds with Content-Type
text/event-stream, keeps the connection open, and writes
UTF-8 lines in the SSE format. The browser reconnects automatically
if the connection drops.
An SSE event consists of one or more field lines followed by a blank line that dispatches the event:
event: notification id: 42 data: <pre>127.0.0.1 200 GET /index.html</pre>
Fields: data: (event payload, one or more lines),
event: (event type, default "message"),
id: (last-event-id for reconnection),
retry: (reconnection interval in milliseconds).
Lines starting with : are comments (used for keep-alive).
A blank line dispatches the accumulated event to the client.
with-event-stream-response establishes an SSE
connection, setting the Content-Type to text/event-stream
and Cache-Control to no-cache. Connection errors
(bad-connection-state) are handled gracefully:
(with-event-stream-response (stream :timeout *connection-timeout*)
(loop doing
(write-sse-event stream :data "heartbeat" :event "ping")
(process-wait "SSE Wait" #'data-available-p)
(unless (live-connection-p stream) (return))))
Two interfaces for writing SSE events:
write-sse-event -- writes a complete event and flushes.
Handles multi-line data by splitting on #\Newline (the
portable Common Lisp line terminator emitted by HTML generators and
with-output-to-string) into separate data:
lines, as required by the SSE wire format. Each split line is
prefixed with data: and terminated with CRLF; the wire
serializer translates embedded #\Newline characters to
CRLF on output regardless of platform:
(write-sse-event stream :data html-string :event "statistics" :id (log-total-number-of-requests log))
Arguments: :data (string or list of strings),
:event (event type string), :id
(last-event-id), :retry (milliseconds),
:comment (keep-alive or annotation).
with-sse-event / write-sse-data-line -- block macros for
writing events incrementally. Parallel to
with-block for multipart push. Use when the event
payload is generated by multiple write operations:
(with-sse-event (stream :event "notification" :id counter)
(write-sse-data-line stream
(write-string "<pre>" stream)
(write-log-entry entry stream)
(write-string "</pre>" stream)))
with-sse-event writes the event/id/retry headers,
executes the body, then dispatches with a blank line and
force-output. write-sse-data-line writes the
data: prefix, executes the body (which writes the line
content), then writes CRLF.
CL-HTTP's original server push uses Netscape's
multipart/x-mixed-replace content type (NS4.0 package).
This predates SSE and works by sending a multipart response where
each part replaces the previous one in the browser. Support is
limited to older browsers (Netscape, Mozilla, Firefox) and is not
available in Chrome, Safari, or Edge.
For new code, use SSE instead. Legacy push is retained for
backward compatibility with existing applications. The original
log window implementation is preserved in
examples/log-window-netscape.lisp.
;; Legacy multipart push:
(with-server-push-response (stream)
(setf (server-timeout *server*) timeout)
(loop doing
(with-block (stream :content-type :html :content-location url)
(with-html-document (:stream stream)
... write HTML for this frame ...))
(process-wait "Refresh Wait" #'refresh-p ...)
(unless (live-connection-p stream) (return))))
with-server-push abstracts over SSE and legacy
multipart push, selecting the implementation via
:push-type:
;; SSE (default): (with-server-push (stream :push-type :sse :timeout timeout) ...) ;; Legacy Netscape multipart push: (with-server-push (stream :push-type :multipart :timeout timeout) ...)
Use :sse (the default) for all new code.
The event-channel class provides named pub/sub channels
with multiple subscribers. Channels are pooled via
defresource for efficient allocation:
;; Define a static channel: (define-event-channel server-stats :documentation "Server statistics broadcast channel.") ;; In the SSE endpoint -- subscribe: (subscribe-channel *server-stats-channel* stream) ;; From the server -- broadcast to all subscribers: (broadcast-event *server-stats-channel* :data html :event "stats-update") ;; Cleanup -- unsubscribe on disconnect: (unsubscribe-channel *server-stats-channel* stream)
broadcast-event automatically removes disconnected
clients. For dynamic per-session channels, use the
:dynamic t option in define-event-channel
to pool channels via defresource.
The browser's EventSource API cannot negotiate HTTP
authentication challenges -- it treats a 401 response as a fatal
error. When SSE endpoints require authentication (e.g., Digest auth),
use a session cookie set by the authenticated entry page. The SSE
endpoint validates the cookie in its response function and returns
403 Forbidden on failure. JavaScript in the onerror
handler redirects to the entry page for re-authentication.
See examples/log-window.lisp for the complete pattern:
HMAC session cookie, %log-window-mint-cookie,
%log-window-valid-cookie-p, and the
write-log-notification-events response function.
The server log window (examples/log-window.lisp) uses
SSE to stream server statistics and notification log entries to the
browser. The statistics pane pushes an HTML table on each update.
The notification pane uses the task queue: each HTTP request generates
a log entry whose write-log-entry method adds SSE
framing via with-sse-event and
write-sse-data-line, then calls
call-next-method for the actual log text.
Source: server/server-events.lisp (portable SSE
infrastructure), examples/log-window.lisp (SSE log
window with cookie authentication).
CL-HTTP gates a handful of response-shaping decisions on whether the
client's user-agent supports a feature -- for example,
set-cookie-http-headers emits no headers if the UA does
not honor cookies, and the directory listing emits HTML4-style markup
only when the UA supports it. The capability database lives in two
parameters in the HTTP package; the predicate
user-agent-capability-p is the public lookup interface.
*known-user-agent-capabilities* is the master list of
capability names. Adding a new capability requires adding the symbol
here as well as in the relevant entries of
*user-agent-capabilities*. An unknown capability raises
an error from the predicate.
(:html4 :html5 :tables :frames :iframes :client-side-image-maps :cookies :java-script :event-source :web-sockets :http/2)
*user-agent-capabilities* is an alist keyed by
user-agent; each entry lists the capabilities that user-agent
supports. The entry whose key is T is the
catchall profile applied to any user-agent not explicitly
listed -- notably modern browsers (Chrome, Firefox, Safari, Edge),
which all parse to :MOZILLA via the standard
Mozilla/5.0 UA prefix and inherit the catchall. Text-mode
browsers and non-browser HTTP clients have their own, narrower
profiles:
((t :html4 :html5 :tables :frames :iframes :client-side-image-maps
:cookies :java-script :event-source :web-sockets :http/2)
;; Text-mode browsers -- render HTML but no JS, no SSE, no WebSockets.
(:lynx :html4 :html5 :tables :frames :iframes :client-side-image-maps :cookies)
(:w3m :html4 :html5 :tables :frames :iframes :client-side-image-maps :cookies)
;; Non-browser HTTP clients -- no cookies, no JS, no SSE, no WebSockets.
(:curl) (:wget) (:python-requests) (:python-urllib) (:node)
(:libwww-perl) (:|Go-http-client|))
(user-agent-capability-p capability user-agent &optional version)
Returns non-null when user-agent supports
capability. capability is either a single
keyword or a list of keywords (in which case all must hold).
version is accepted for backward compatibility but
ignored -- per-version capability gating was retired since no modern
user-agent needs it.
Lookup is one ASSOC over
*user-agent-capabilities* with fallback to the
T entry, plus one MEMBER over the resulting
capability list -- no consing on the hot path.
;;; Typical use: pair with CURRENT-USER-AGENT in a response function.
(defmethod respond-with-redirect ((url http-url) stream)
(declare (ignore stream))
(multiple-value-bind (user-agent)
(current-user-agent)
(redirect-request *server*
(if (user-agent-capability-p :frames user-agent)
#u"/my-app/framed.html"
#u"/my-app/simple.html"))))
To add a new capability, add its symbol to
*known-user-agent-capabilities* and add the symbol to the
relevant entries in *user-agent-capabilities* -- minimally
the T catchall entry if modern browsers support it
universally.
To add a new user-agent with a non-default capability profile, add
an alist entry keyed by the user-agent keyword (this is the symbol
returned by parse-user-agent on the first token of the
User-Agent request header). User-agents whose first token
is Mozilla ride the catchall regardless; explicit entries
are needed only when the UA's profile differs from the catchall.
Authentication scheme (Basic vs. Digest) is not a capability. CL-HTTP enforces a single authentication scheme per realm by design; offering both schemes invites a client-driven downgrade attack (RFC 7616 §5.3). Modern browsers (Chrome, Firefox, Safari, Edge) all support Digest authentication with MD5; SHA-256 support varies but is broadly available. See Chapter 8 for realm configuration.