CL-HTTP Chapter 5: HTTP Server


Manual Index | Prev: URL System | Next: WebSockets

Contents


5.1 Request/Response Pipeline

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.

5.1.1 The Server Object

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:

AccessorTypeDescription
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.

5.1.2 Pipeline Steps

When a client connects to a CL-HTTP port, the following sequence executes:

  1. Accept Connection. The platform-specific listener thread (running in %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*.
  2. Provide Service. The method 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)))))))
    
  3. Parse Request Line. The function %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.
  4. Parse Headers. Request headers are read and stored in a 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.
  5. Apply Reverse-Proxy Override. Immediately after headers are parsed, %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.
  6. URL Dispatch. The URL string is interned to find a matching URL object. If the URL has a parent exported with a directory export type and *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).
  7. Call Response Function. For URLs exported with :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.
  8. Write Response. The response function writes its output using response macros (see Section 5.2), which handle the HTTP status line, response headers, content encoding, chunked transfer for HTTP/1.1, and character set encoding.
  9. Log Access. After the response completes, log-access records the transaction to all active access logs.
  10. Persistent Connection. For HTTP/1.1 clients, the server checks whether data is available within *persistent-connection-timeout* seconds. If so, it resets transaction state and processes the next request. Otherwise, it closes the connection.

5.1.3 Error Handling in the Pipeline

The function %process-request establishes a handler-bind environment that catches errors at several levels:

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.

5.2 Response Macros

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.

5.2.1 with-successful-response

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
The HTTP stream to write to. In a response function, this is the stream argument passed by the server.
content-type
A keyword denoting the MIME 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)
The response status. Keywords: :success (200), :created (201), :accepted (202), :non-authoritative (203), :no-content (204), :reset-content (205), :partial-content (206), :not-modified (304).
:bytes
The exact content length in bytes, when known in advance. When supplied, the server sends a Content-Length header and does not use chunked transfer encoding. When nil, HTTP/1.1 clients receive chunked encoding.
:last-modification
Universal time when the resource was last modified. Enables conditional GET support via If-Modified-Since.
:character-set
Character set for text content types. Valid values include :us-ascii, :iso-8859-1, :utf-8, and other IANA character set names. Should normally be (url:character-set url).
:entity-tag
An entity tag for cache validation. Obtained from (url:entity-tag url), or a universal time may be supplied.
:expires
Universal time when the response expires. Normally computed by (url:expiration-universal-time url).
:content-language
A list of language keywords (e.g., (:en) or (:en-us :fr)) conforming to RFC 1766. Normally (url:languages url).
:cache-control
A property list of cache-control directives. Normally provided by (url:response-cache-control-directives url).
:additional-headers
A property list of extra headers: (:header-keyword header-value ...). Used for cookies and application-specific headers.
:location
A URI for a resource created by POST or PUT.
:content-location
A URI describing the content being transferred.
:chunk-function
A function called on each output chunk with arguments (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))))

5.2.2 with-conditional-get-response

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.

5.2.3 Content Types

Content type keywords map to MIME types via CL-HTTP's MIME type registry. The commonly used keywords include:

KeywordMIME Type
:htmltext/html
:texttext/plain
:xmltext/xml
:csstext/css
:jsonapplication/json
:javascriptapplication/javascript
:pdfapplication/pdf
:gifimage/gif
:jpegimage/jpeg
:pngimage/png
:svgimage/svg+xml
:mp3audio/mpeg
:mp4video/mp4
:zipapplication/zip

5.3 Server Configuration

CL-HTTP's server behavior is controlled by special variables defined in http:server;variables.lisp. The most important ones are described here.

5.3.1 Port and Protocol Variables

*standard-http-port* (default 80)
The standard port number for HTTP service. Set this before calling enable-http-service. Type: fixnum.
*standard-protocol* (default :http)
The standard protocol: :http or :https.

5.3.2 Timeout Variables

*server-timeout* (default 18000, i.e., 5 minutes in 60ths of a second)
Maximum idle time before the server drops a connection. This is the read timeout on the initial request. Measured in 60ths of a second.
*persistent-connection-timeout* (default 10)
Seconds before an idle persistent connection times out. Controls idle connection reaping for both HTTP/1.1 keep-alive and HTTP/2. Changes take effect immediately for HTTP/1.1 and on new connections for HTTP/2.
*server-life-time* (default 300000, i.e., 5 minutes in milliseconds)
Maximum total life time of an HTTP server instance in milliseconds.

5.3.3 Debug and Behavior Variables

*debug-server* (default nil)
Controls error handling. Values: 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)
Controls automatic export of URLs in exported directories. :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)
Security policy for PUT and DELETE methods. Values in order of increasing permissiveness: :none, :local-host, :authenticated-users-on-write-subnets, :write-subnets, :access-controlled, :authenticated-users, :remote-host.

5.3.4 Service Management Functions

(enable-http-service &key (on-ports *standard-http-port*) (address :all))
Top-level function for starting HTTP servers. 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))
Shuts down HTTP servers. 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*))
Ensures that an HTTP service object exists for 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)
Returns a list of port numbers on which HTTP service is currently active.
(http-service-enabled-p &optional (port *standard-http-port*))
Returns true if HTTP service is enabled on the given port.

5.4 HTTP/2 Support

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.

5.4.1 Protocol Version Control

*http-protocol-version* (default :http/1.1)
The maximum HTTP protocol version the server will negotiate. Valid values: :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")
The HTTP/1.x version string written into status lines. This is never set higher than "HTTP/1.1" because HTTP/2 uses binary framing, not version strings in status lines.
(http2-protocol-enabled-p)
Returns t when the server is configured to accept HTTP/2 connections. Checks whether *http-protocol-version* is :http/2.
(set-http-version version)
Set the HTTP protocol level for a running server. 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)

5.4.2 HTTP/2 Architecture

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.

5.5 Condition Handling

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.

5.5.1 Network Condition Hierarchy

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:

ConditionWhen 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.

5.5.2 HTTP Status Conditions

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:

ConditionStatusMeaning
bad-syntax-provided400Malformed request.
recoverable-unauthorized-client-access401Authentication required.
access-forbidden403Access denied.
document-not-found404URL not interned or file missing.
method-not-allowed405HTTP method not supported for URL.
request-timeout408Client timed out.
server-internal-error500Unhandled server error.
server-not-implemented501Method not implemented.
bad-gateway502Upstream server error (proxy).
service-unavailable503Server temporarily overloaded.
gateway-timeout504Upstream server timeout (proxy).
http-version-not-supported505Client requested unsupported version.

5.5.3 Error Handling in Response Functions

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)))))

5.6 Content Negotiation

CL-HTTP supports server-driven content negotiation through request headers. The client declares its preferences; the server selects the best representation.

5.6.1 Language Negotiation

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))
  ...)

5.6.2 Character Set Negotiation

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).

5.6.3 Content Encoding

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.

5.6.4 UTF-8 Encoding and Decoding

CL-HTTP provides platform-specific UTF-8 support for transmitting Unicode content over HTTP. The implementation differs by platform:

LispWorks
LispWorks uses 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.
SBCL
SBCL handles Unicode natively in character streams, so the LispWorks "malformed string" decoder is unnecessary. The 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.
Genera
Genera uses a modal buffered input stream with explicit :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.

Encoding Macros

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))

Utility Functions (WWW-UTILS package)

(utf-8-encoding-length character)
Returns the number of bytes (1-4) needed to UTF-8 encode a character.
(utf-8-encode-unicode-character character)
Returns an array of bytes (no more than 4 elements) encoding the character as UTF-8. Used by URL percent-encoding in escape-character-as-utf-8.
(utf-8-number-of-bytes first-byte)
Returns the length (1-4) of a UTF-8 sequence from its first byte.
(utf-8-decode byte-sequence &optional start end)
Decodes a sequence of UTF-8 bytes into a string.

Exporting URLs with UTF-8

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)
      ...)))

5.6.5 Directory View Negotiation

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.

5.7 Cookies

CL-HTTP provides functions for setting and reading HTTP cookies. Cookies are set via response headers and read from request headers.

5.7.1 Setting Cookies

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)
The cookie name, as a keyword symbol.
value (string)
The cookie value. The combined size of name and value must not exceed 4000 bytes.
:expires (universal-time)
When the cookie expires. To delete a cookie, set this to a time in the past.
:max-age (integer)
Time in seconds before the cookie should be discarded.
:domain (string)
The server domain for which the cookie is valid. Defaults to the server host name.
:path (string)
The URL path scope for the cookie. Defaults to /.
:secure (boolean)
When true, the cookie is only sent over SSL/TLS connections.
:http-only (boolean)
When true, the cookie is not accessible to client-side scripts.

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.

5.7.2 Reading Cookies

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)))
    ...))

5.8 Logging

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.

5.8.1 Log Classes

The log class hierarchy provides several predefined formats:

ClassDescription
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.

5.8.2 Configuration Variable

*log-access-log-class*
Controls the class of access log used to record HTTP transactions. This variable must be set before logs are created (typically in the configuration file loaded at startup). The predefined classes listed above are all valid values. Example:
(setq http:*log-access-log-class* 'http:extended-common-file-log)

5.8.3 Log Management Functions

(intern-access-log name &key port directory (class *log-access-log-class*) (if-does-not-exist :error))
Interns (finds or creates) a server access log. 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)
Turns file logging on or off. 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)
Turns dynamic (in-memory) logging on or off.
(current-access-logs)
Returns the list of currently active access logs.
(standard-access-logs port)
Returns the access logs assigned to the given port.
(start-log-queue log)
Starts the background log-writing thread for a log.
(ensure-current-log)
Ensures that log objects exist and are active for the standard HTTP port.

5.8.4 Common Log Format

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

5.8.5 Log Parsing

CL-HTTP can parse its own log files for analysis:

(parse-log-file log pathname &key log-format stream)
Parses a log file according to the specified format. log-format defaults to *default-log-line-parser* (normally :common-log-format). Available formats: :common-log-format, :extended-common-log-format, :post-log-format.

5.8.6 Typical Log Setup

;; 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

5.9 Bug Reporting

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*.

5.9.1 Configuration Variables

*bug-report-destination* — Variable
Controls where bug reports go. Values:
*bug-report-pathname* — Variable
Pathname for the bug report log file when *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
Email address for bug reports when destination is :mail. Computed from *server-bug-list* and *default-mailer-host*.

5.9.2 Bug Reporting Functions

(report-bug to subject format-string &rest format-args) — Function
Reports a bug to TO with SUBJECT and message body produced by applying 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
Appends a bug report to PATHNAME in Emacs RMAIL (BABYL) format. BUG-REPORT is a string or a function of one argument (stream) that writes the body. Creates the file with a BABYL header on first write. Can be called directly for subsystem-specific bug logging independent of *bug-report-destination*.

5.9.3 Typical Setup

;; 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)))

5.10 Server Push

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.

5.10.1 Server-Sent Events (SSE)

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.

Wire Format

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.

Response Macro

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))))

Writing Events

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.

5.10.2 Legacy Netscape Multipart Push

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))))

5.10.3 Generalized Push Macro

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.

Pub/Sub Event Channels

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.

SSE with Authentication

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.

Example: SSE Log Window

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).


5.11 User-Agent Capabilities

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.

5.11.1 Capability Database

*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|))

5.11.2 user-agent-capability-p

(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"))))

5.11.3 Adding New Capabilities and User-Agents

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.

5.11.4 What Is Not a Capability

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.


Manual Index | Prev: URL System | Next: WebSockets