Feature notes
HTTPS application layer notes (HTTP/1.1, h2, h3)
================================================================================
HTTPS APPLICATION LAYER
HTTP/1.1, HTTP/2 (RFC 9113) and HTTP/3 (RFC 9114)
One request-handling core; TLS/TCP and QUIC/UDP application protocol plugins
(StreamSec Security Library for Embarcadero Delphi)
================================================================================
Updated: 2026-10-24b (iHttpRequestOrigin reports the scheme and authority on
HTTP/3 too (section 13.1); section 23.1 says to read or
DiscardBody every response body.)
Updated: 2026-10-24 (sections 2.1, 14 and 17 state the threads: HTTP/3
handlers, session providers and the other QUIC callbacks
run on the QUIC listener's connection worker threads.)
Updated: 2026-10-23d (HTTP/2 refuses a TLS version below 1.2, and both ends
then close the connection (sections 6, 23.1); a received
GOAWAY is checked and charged (sections 6, 12, 20). A
response field that cannot be generated gives a 500 on
HTTP/1.1 and HTTP/2, and so does a status outside
100..599; an HTTP/2 304 carries no content-length, and one
date goes out (sections 4, 13.2). An HTTP/1.1 reason
phrase with a control character gives way to the standard
one (section 4). The HTTP/2 client refuses a malformed
response head (section 23.1).)
Updated: 2026-10-23c (FPC legacy DES exclusion and TLS qualification corrected;
full public endpoint qualification remains scoped.)
Updated: 2026-10-23b (pointers to unshipped test files removed; section 19 now
states what was accepted per area, and section 22.8 what
the REST tests proved.)
Updated: 2026-10-23 (platform qualification notes in sections 19, 23.1, 23.3
and 24.3.)
Updated: 2026-10-21 (opt-in HTTP/3 server push, bounded acceptance and resource
policy (section 23.6).)
Updated: 2026-10-21 (opt-in dynamic QPACK, bounded blocked streams and critical
stream progress (section 23.5).)
Updated: 2026-10-21 (explicit buffered QUIC 0-RTT admission and common
HTTP/1.1, HTTP/2 and HTTP/3 early-data policy parity
(sections 2.1 and 23.4).)
Updated: 2026-10-20 (generated request/response trailers on all three wires
(sections 2.3 and 23.1.1), including deferred response
body-EOF generation for streamed digests (section 2.3.1),
and absolute header/buffered-request deadlines on all
three protocols (section 20.4).)
Updated: 2026-10-19 (QUIC and HTTP/3: TsmAsyncQUICServer with TsmHTTPSv3 as
its first application protocol plugin, sharing the HTTP
router, handlers and optional session provider with
TsmHTTPSv1dot1 and TsmHTTPSv2. Added the HTTP/3 wire and
QPACK layers, availability-aware Alt-Svc advertisement,
high-level HTTPS client discovery, and bounded incremental
uploads in the low-level HTTP/3 client engines and common
high-level HTTPS uploads with known or unknown lengths,
plus strict HTTP/1.1 chunked request decoding and separate
received request/response trailers. Opt-in server request
streaming shares bounded exchanges across all three wires
(section 24). Sections 14, 16 and 23 describe HTTP/3,
shared wiring and clients.)
Updated: 2026-10-09 (large responses: owned body streams are read as the
transport accepts data, rather than copied whole into
memory (section 3.1). HTTP/2 bounds the response memory it
retains with ConnResponseBytes / TotalResponseBytes
(sections 13 and 20).)
Updated: 2026-08-16 (static serving: HttpSendStream supplies validators,
conditional requests, byte ranges and caller-selected
Cache-Control over a stream. HttpStreamValidators reads
validators from an open handle; HttpSendFile is the path
form; HttpSendStreamRange is the bare range primitive.
HTTP-date formatting and parsing are exported. Sections 3
and 15 also document SendFileRange.)
Updated: 2026-08-11 (REST: StreamSec.Http.RestServer adds TsmRESTServer and a
JSON dispatcher mounted on the shared router, using the
separate iHttpPrefixRouter contract. Section 22 describes
it; section 2 includes prefix mounts in route resolution.
HttpReasonPhrase includes the REST status codes and 416.)
Generated: 2026-07-31 (shared request/response model, router and three handler
registration forms; HTTP/1.1 and HTTP/2 wire sessions;
TsmHTTPSv1dot1 and TsmHTTPSv2 as ALPN plugins for
TsmAsyncTLSServer.)
--------------------------------------------------------------------------------
0. SUMMARY - ONE CORE, THREE HTTP PROTOCOLS
================================================================================
HTTP/1.1, HTTP/2 and HTTP/3 use the same request/response contracts and the same
three handler registration forms. Their wire engines supply that shared model:
TLS/TCP: TsmAsyncTLSServer
'http/1.1' -> TsmHTTPSv1dot1 -> tHttp11Session --+
'h2' -> TsmHTTPSv2 -> tHttp2Session ---+-> iHttpRouter
| |
QUIC/UDP: TsmAsyncQUICServer | +-> interface handler
'h3' -> TsmHTTPSv3 -> tHttp3ServerConn -+ +-> event handler
+-> static file map
else OnRequest -> 404
Use one TsmAsyncTLSServer for HTTP/1.1 and HTTP/2, and one TsmAsyncQUICServer
for HTTP/3. Each host negotiates ALPN among its own registered plugins. QUIC is
a separate datagram transport; HTTP/3 is its first plugin, rather than a third
TCP session selected by the TLS server.
Assign the SAME iHttpRouter to all three HTTP components. Register handlers
once, before activation, and requests over any of the three protocols reach
those handlers. Each connection has its own wire engine, transport and default
session lifetime. Share one iHttpSessionProvider too when application session
state must follow a client across connections or protocols (section 2.1).
Existing handlers receive a complete, bounded body. An opt-in streaming adapter
on the same router instead supplies an immutable request head and a detached,
bounded body exchange for application workers (section 24). All three wires
support this contract. Responses can use owned streams sent in bounded pieces
as transport room permits (section 3.1). Client upload APIs are separate
(section 23).
Headers reuse tHttpHeaders from StreamSec.Http.Client: an ordered,
case-insensitive Name=Value multimap shared by clients and servers. Received
trailers use a separate ordered collection: request handlers query the optional
iHttpRequestTrailers interface, and clients read tHttpResponse.Trailers after
successful completion. Initial headers keep their original meaning.
TsmRESTServer mounts a JSON-REST dispatcher on the router (section 22). Its
published Protocol property accepts TsmHTTPSv1dot1 or TsmHTTPSv2 through their
TsmCustomHTTPSProtocol base. Point it at either TCP component whose Router is
also assigned to TsmHTTPSv3, and that one mount serves all three protocols.
Alternatively, MountOn accepts the shared iHttpRouter directly at runtime.
--------------------------------------------------------------------------------
1. UNIT INVENTORY & WHERE EACH LAYER LIVES
================================================================================
The following HTTP units are included in the regular runtime packages
StrSecIV170-370 (Delphi XE3 through Delphi 13), grouped here by role. HTTP/3
reuses the same core as the two TCP protocols.
SHARED APPLICATION CORE:
StreamSec.Http.Server iHttpRequest / iHttpResponse / iHttpRouter /
iHttpRequestHandler, request and response
implementations, sessions, event/static-file
wrappers, NewHttpRouter, HttpMimeType and
HttpReasonPhrase (sections 2, 3). It also defines
detached Alt-Svc endpoint and request-origin
contracts. No socket or TLS dependency.
StreamSec.Http.Trailers Pure received-field validation, connection-token
exclusions and decoded metadata accounting. No
crypto or TLS dependency (section 2.2).
StreamSec.Http.RestServer tRestDispatcher, a transport-free request handler,
and TsmCustomRESTServer / TsmRESTServer, which
mount it on the router. REST request/response,
handler and idempotency-store contracts live here
too (section 22).
StreamSec.Http.BodyQueue Fixed TBytes request ring and readiness primitive;
RTL-only (section 24).
StreamSec.Http.Streaming Opt-in handler adapter, immutable request head,
detached body/response exchange and job admission
(section 24).
HTTP/1.1 AND HTTP/2 OVER THE ASYNC TLS SERVER:
StreamSec.Http.Hpack RFC 7541 HPACK static/dynamic tables and field
encoding/decoding (section 8).
StreamSec.Http.Http2Frames RFC 9113 constants and frame reader/writer;
transport-free (section 7).
StreamSec.Http.Http2Conn tHttp2Conn: preface, SETTINGS, streams, flow
control, request assembly and response output;
transport-free (sections 6, 9-13).
StreamSec.Mobile.HTTPS TsmCustomHTTPSProtocol, TsmHTTPSv1dot1 and
TsmHTTPSv2; tHttp11Session and tHttp2Session bind
the wire engines to iAppTransport on
TsmAsyncTLSServer (sections 4, 15, 16).
HTTP/3 OVER THE ASYNC QUIC SERVER:
StreamSec.Http.Huffman Shared HPACK/QPACK Huffman coding.
StreamSec.Http.Qpack HTTP/3 field-section encoding/decoding and QPACK
instruction parsing; HTTP/3 uses the dynamic
table only when configured (sections 14, 23.5).
StreamSec.Http.Http3Frames Incremental HTTP/3 frame parsing, SETTINGS,
stream types and error codes (section 14).
StreamSec.Http.Http3Server tHttp3ServerConn and iHttp3ServerTransport;
complete/streaming request input, shared-core
dispatch and paced response output (section 14).
StreamSec.Mobile.HTTPSv3 TsmHTTPSv3: binds that engine to iQuicAppSession
on TsmAsyncQUICServer and shares the application
router and session provider (section 14).
StreamSec.Mobile.AsyncQUICServer
General-purpose UDP/QUIC host. QUICServer.txt
describes its plugin registry, reactor, admission,
connection lifecycle and shutdown policy.
CLIENT AND DISCOVERY LAYERS:
StreamSec.Http.Client tHttpHeaders, also used by the server core, and
the HTTP/1.1 client model/parser.
StreamSec.Http.Http2Client tHttp2ClientConn: HTTP/2 client engine, response
credit and bounded request production.
StreamSec.Http.Http3Client tHttp3ClientConn: transport-free request engine,
response observer and bounded incremental upload
API (section 23).
StreamSec.Http.Http3QuicClient
tHttp3QuicClient: attaches the HTTP/3 engine to
the QUIC client and propagates stream/credit
events (section 23).
StreamSec.Http.AltSvc Bounded, origin-scoped HTTP/3 discovery cache and
strict HTTPS origin/authority parsing.
StreamSec.Mobile.HTTPS3ClientTransport
TLS/UDP/QUIC adapter owned by the high-level HTTPS
client. It borrows the selected TLS engine.
StreamSec.Mobile.HTTPSClient
High-level HTTP/1.1, HTTP/2 and optional HTTP/3
client, including authenticated Alt-Svc discovery.
Its common request API still accepts complete
bodies; see HTTPSClient.txt.
DESIGN-TIME REGISTRATION (regular DStrSecIV170-370 packages):
StreamSec.Mobile.AsyncTLSServerReg
Registers TsmAsyncTLSServer, TsmHTTPSv1dot1 and
TsmHTTPSv2 on 'StreamSec Mobile'.
StreamSec.Mobile.AsyncQUICServerReg
Registers TsmAsyncQUICServer and TsmHTTPSv3 on
the same palette page.
StreamSec.Http.RestReg Registers TsmRESTClient and TsmRESTServer there.
The transport-free codecs and connection engines can be exercised without a
socket; the server adapters provide their transport and dispatch seam. Sharing
handlers therefore does not require sharing a parser, wire state or connection.
READ ALSO. AsyncTLSServer.txt describes the TCP/TLS host and its iAppProtocol /
iAppSession seam. QUICServer.txt describes the separate iQuicAppProtocol /
iQuicAppSession host and the shared-listener setup. HTTPSClient.txt owns the
high-level client API.
--------------------------------------------------------------------------------
2. THE SHARED REQUEST-HANDLING MODEL (StreamSec.Http.Server)
================================================================================
iHttpRequest - Method, Path, Query, Version, Headers (tHttpHeaders), Body
(TStream), plus session-populated RemoteAddress, Secure and
NegotiatedProtocol. The wire adapter supplies these facts;
the core has no socket or TLS dependency. HTTP/3 takes the
address of the current validated QUIC path when each request
stream is first observed. That request keeps its address across
later rebinding. It has no port or IPv6 brackets. Also Cookies,
Session and Connection - see section 2.1. All three server
engines dispatch complete bounded request bodies. Incremental
HTTP/3 client uploads do not change that handler contract.
iHttpRequestTrailers
- Optional companion exposing the request-owned, separate
Trailers multimap after complete validation (section 2.2).
iHttpResponse - StatusCode (defaults 404), Headers, SetHeader (replace-or-add),
and a content source set by one of SetContent(ptr,len) /
SetContentText (UTF-8) / SetContentStream / SendFile(physFile).
There is NO ReasonPhrase member: the reason is an optional
argument of SetStatus, and a session that was given none falls
back to HttpReasonPhrase(code). Each of the four content setters
also promotes the status from 404 to 200 - but ONLY from exactly
404, so a deliberate SetStatus(404) plus a body silently becomes
200 while a pre-set 201/302/500 survives. The session serializes
the whole thing after dispatch. A field the wire cannot carry
makes the answer a 500 on HTTP/1.1 and HTTP/2 (sections 4 and
13.2) and resets the request on HTTP/3 (section 14).
iHttpRequestHandler - the single internal abstraction: HandleRequest(aReq,aResp).
Body is the LIVE internal stream, rewound on every read of the
property: two consumers interfere, and a handler must never free
it. tHttpRouter and the event/file handler wrappers are
implementation-only types - an application reaches them through
NewHttpRouter and iHttpRouter, never by name.
THE THREE REGISTRATION WAYS all reduce to an iHttpRequestHandler in the router:
(1) INTERFACE Router.AddHandler('/api/status', myHandler) {myHandler: iHttpRequestHandler}
(2) EVENT Router.AddEvent('/api/time', Form1.OnTime) {wrapped internally}
plus a component-level OnRequest event = the global fallback.
Sender differs between the two: a router-registered AddEvent
handler is called with Sender = nil, the component-level
OnRequest fallback with Sender = the component.
(3) STATIC FILE Router.AddFile('/index.html','C:\www\index.html')
AddFiles([HttpFile('/','...'), HttpFile('/a.css','...')])
Exact request-path -> physical-file matches, NO directories
(a matched entry becomes an internal file-serving handler;
GET/HEAD only, MIME by extension, Content-Length, 404 if gone).
RESOLUTION ORDER (run per request by every session): exact-path route (interface
OR static file) -> else the LONGEST matching prefix mount -> else the component
OnRequest event -> else 404. Because the response starts at 404, an unmatched
request with no event simply returns 404. Routes are path-keyed (any method; the
handler inspects Method); per-method routes and directory serving (AddDirectory)
are the noted extensions.
PREFIX MOUNTS (iHttpPrefixRouter) are how a handler claims a SUBTREE rather than
a path - what a REST API needs, since '/api/orders/17' cannot be an exact
registration. It is a SEPARATE interface reached with Supports, not new members
on iHttpRouter, because iHttpRouter is a shipped contract and adding a method to
it would break every outside implementation at once:
var lPfx: iHttpPrefixRouter;
if Supports(aRouter, iHttpPrefixRouter, lPfx) then
lPfx.AddPrefix('/api', lHandler);
A prefix matches at '/' boundaries ONLY, so '/api' receives '/api' and
'/api/orders' but never '/apix'; matching is on the RAW path like everything
else here, so '/%61pi/x' does not reach a mount at '/api'. A trailing '/' is
stripped at registration, '/' (or '') mounts at the root and matches every path,
and an exact route always beats a mount - which is what lets a static file or a
health endpoint live INSIDE a REST server's subtree. The router NewHttpRouter
builds supports it; a foreign router that does not is simply one that cannot
host a mount, and TsmRESTServer.MountOn says so rather than failing quietly.
TWO ROUTER PROPERTIES WORTH KNOWING BEFORE SHARING ONE. Registration is
replace-not-append: a second AddHandler/AddEvent/AddFile on the same path
silently REPLACES the first, with no exception and no duplicate route (and
RemoveRoute on an absent path is equally quiet). And the route table is a plain
dictionary with NO lock: concurrent Resolve calls from every connection and
every engine shard are fine, but mutating routes after the server is Active
races with those lookups. Register everything before activation, or serialize it
yourself. The core also imposes no size limits of its own - every cap in this
document lives in the wire sessions, never in the router or the response object.
2.1 COOKIES, SESSION STATE, AND CONNECTION SECURITY
--------------------------------------------------------------------------------
Three more properties on iHttpRequest, for the things a handler needs that are
not in the request line.
Cookies : iHttpCookies what the client sent in its Cookie field(s)
Session : iHttpSession the session selected for this request
Connection : iHttpConnectionInfo the connection's security view
COOKIES. Parsed on first access and cached for the request, so a handler that
never asks never pays. Two rules matter:
* NAMES ARE CASE-SENSITIVE, unlike header names. RFC 6265 defines no
case-insensitive comparison for them and browsers keep 'SID' and 'sid' apart,
so folding them would merge two cookies a client deliberately kept distinct.
* EVERY Cookie FIELD IS JOINED before parsing. HTTP/2 and HTTP/3 can
carry several Cookie fields; the shared model combines them so the
handler sees the full collection on every wire.
Values are raw - no percent-decoding, no unquoting - for the same reason Path
and Query are raw: this layer does not know how you encoded them. A pair with no
'=' or an empty name is discarded rather than stored under an invented name.
Exists tells an absent cookie from a present empty one; ByName cannot.
SESSION. By default each connection has one iHttpSession shared by its requests.
Connections have separate default sessions even when their protocol components
share a router:
* requests multiplexed over one HTTP/2 or HTTP/3 connection see that
connection's default session;
* several HTTP/1.1 connections have several default sessions;
* reconnecting, or moving between TCP and QUIC, does not move session state
automatically.
Cache per-connection work there freely - a decoded authorization, an identity
the peer proved, anything expensive to recompute. Do not put anything there that
has to persist, and do not let "the session says they are logged in" replace a
check you would otherwise do.
Names are case-INSENSITIVE, the opposite of the cookie rule and deliberately so:
these names are yours, not the client's. Values are Variants. One connection is
never dispatched twice at once, so the default session needs no locking.
THE PROVIDER SEAM. Assign SessionProvider on TsmHTTPSv1dot1, TsmHTTPSv2 and
TsmHTTPSv3 at runtime. AcquireSession runs once per request before the handler
and receives its per-connection session. It may return that session unchanged or
select application state from a shared store. Assign ONE provider to all three
components to find the same application session across connections and
protocols. This shares the lookup policy, not the default session object.
The callback is synchronous on the thread driving the connection: a reactor I/O
thread for HTTP/1.1 and HTTP/2, one of the QUIC listener's connection worker
threads (TsmAsyncQUICServer.WorkerThreadCount) for HTTP/3. Requests of one
connection can arrive on different threads; do not assume one dedicated thread.
That is the seam a cookie-keyed store goes through, and it exists so
iHttpSession does not have to change shape when one arrives. WRITING ONE MEANS
OWNING WHAT IT IMPLIES: identifiers from a cryptographic RNG, idle AND absolute
expiry, a fresh identifier when the principal changes so a fixated one cannot be
inherited, HttpOnly + Secure + SameSite on the cookie, and a sweeper - or the
store is a memory leak an anonymous client can drive. None of that is done for
you.
EARLY DATA. HTTP/1.1, HTTP/2 and HTTP/3 use the same application policy,
tEarlyDataPolicy in StreamSec.Http.Server. The existing
StreamSec.Mobile.HTTPS-qualified type and constants remain compatible aliases.
edpRefuse is the default and answers 425 (Too Early); edpSafeMethods permits
GET, HEAD, OPTIONS and TRACE, compared case-sensitively; edpDispatch permits
other methods only when the application is prepared for replayable input.
Neither policy makes application side effects replay-safe. Configure TLS/QUIC
ticket acceptance, size limits and replay checks separately before enabling
transport early data.
Request.EarlyData is True if any request octet was received as early data, or
if the request carries Early-Data: 1 from an intermediary. For HTTP/2 the
provenance includes split frame headers, payloads and CONTINUATION fragments;
an early connection preface or SETTINGS frame does not mark a later request.
Output work and internal stream lookups do not change that provenance.
A REQUEST THAT LAY ACROSS THE BOUNDARY IS ALWAYS REFUSED 425, WHATEVER THE
POLICY SAYS. Request.EarlyDataStraddled is True when the request has both early
and ordinary input. Such requests also report EarlyData. The buffered policy
gate runs before SessionProvider.AcquireSession and the request handler, and a
425 includes Cache-Control: no-store so a retry on the completed connection
can receive an ordinary response. Streaming request bodies remain refused
when marked early, before creating the streaming application consumer.
QUIC's transport and HTTP/3 protocol-state restoration on early-data rejection
does not introduce a separate application rollback contract. Any stronger
application guarantee must apply equally to HTTP/2.
CONNECTION INFO. Everything the TLS handshake settled, as strings:
Secure, TLSVersion ('TLS 1.3'), CipherSuite ('TLS_AES_128_GCM_SHA256'),
ServerName (the SNI name), KeyExchangeGroup ('x25519'), IsResumed,
PeerCertificatePresent, PeerSubject, PeerSubjectCN, PeerIssuer,
PeerSerialNumber, TransportInfo
It describes the CONNECTION, not the request: requests on one HTTP/1.1, HTTP/2
or HTTP/3 connection share that context. The HTTP/3 adapter reuses the existing
presentation for QUIC's record-free TLS handshake. Three things to know:
* ServerName IS CLIENT-SUPPLIED AND UNAUTHENTICATED. The client picks the
string and nothing ties it to the client's identity. Route on it; do not
authenticate on it. It is also not the Host header - the two are set
independently, and if your application cares that they agree, compare them.
* KeyExchangeGroup IS EMPTY ON TLS 1.2, which negotiates no such group. Test
TLSVersion before reporting an empty value as an anomaly.
* THE PEER CERTIFICATE HAS ALREADY BEEN VERIFIED. One that failed the trust
configuration would have failed the handshake, so there would be no request.
What is left for a handler is AUTHORIZATION.
PeerSubject and PeerIssuer are RFC 4514 renderings - most specific attribute
first, reserved characters escaped, so 'CN=alice, OU=Ops, O=Corp, C=SE'. They
match `openssl x509 -nameopt RFC2253` except that '=' inside a value is escaped
here, which RFC 4514 permits and openssl does not do. PREFER (PeerIssuer,
PeerSerialNumber) AS AN AUTHORIZATION KEY: that pair identifies exactly one
certificate by RFC 5280, whereas a DN string is a rendering and two renderings
of one name can differ. And a subject is unique only WITHIN an issuer, so a
subject test that ignores the issuer is satisfied by any CA you trust.
TransportInfo is the transport's own fully typed view, for what the strings
cannot answer - extensions, validity dates, re-verifying something yourself:
var lTLS: iTLSConnectionInfo; { StreamSec.Mobile.AsyncTLSServer }
if Supports(aRequest.Connection.TransportInfo,iTLSConnectionInfo,lTLS) then
lCert := lTLS.PeerCertificate; { iCertificate, nil without mTLS }
It is typed IInterface so that StreamSec.Http.Server needs neither the TLS nor
the PKIX units - the core stays transport-agnostic and the one line above is the
price. HTTP/3 also exposes the existing iTLSConnectionInfo view here. See
AsyncTLSServer.txt section 8.2 for that interface and QUICServer.txt for the
QUIC transport itself.
2.2 RECEIVED REQUEST TRAILERS
--------------------------------------------------------------------------------
HTTP/1.1, HTTP/2 and HTTP/3 retain valid received request trailers separately
from the initial Headers. The existing iHttpRequest interface is unchanged;
query its optional iHttpRequestTrailers companion with Supports:
if Supports(aRequest, iHttpRequestTrailers, lReceived) then
for i := 0 to lReceived.Trailers.Count - 1 do
UseMetadata(lReceived.Trailers.Names[i], lReceived.Trailers.Values[i]);
Declare lReceived as iHttpRequestTrailers. The ordered tHttpHeaders multimap
preserves duplicates, empty values and arrival order. The library's request
implementation supplies an empty collection when no trailers arrived; custom
request implementations may omit this optional interface. Treat the collection
as read-only. It belongs to the request, must not be freed, and has the existing
handler-call lifetime. Keeping the companion interface does not authorize
asynchronous access to the request after the handler returns.
A handler sees the complete decoded Body and the complete validated trailer
section together. An incomplete or malformed section never reaches a handler.
Trailers do not alter routing, initial Headers, Cookies, authentication or body
framing. Generated response and request trailers use the separate contracts
in sections 2.3 and 23.1.1.
The shared policy accepts benign metadata and rejects fields that affect
framing, routing, connection handling, authentication, request modifiers or
payload interpretation. It also rejects a name nominated by any initial
Connection field. Names must be tokens; values cannot contain forbidden
controls. HTTP/1.1 validates raw octets before removing only outer SP/HTAB and
requires exact CRLF. HTTP/2 and HTTP/3 also apply their own lowercase-name and
field-value rules. Existing wire-specific errors terminate the invalid request.
Retained names and values are charged at their wire-byte lengths plus 32 bytes
per field. This bounds field count as well as text storage, in addition to
encoded metadata limits. HTTP/1.1 reuses HeaderBytes, HTTP/2 its decoded
header-list bound, and HTTP/3 MaxFieldSectionBytes for each trailer section.
HTTP/3 also bounds its aggregate retained trailer charge by MaxActiveRequests
multiplied by MaxFieldSectionBytes. Metadata is released after dispatch or
failure; BodyBytes and body-memory counters continue to count payload only. Zero retains
its existing unlimited-policy meaning where supported, with checked structural
bounds still enforced. Section 20 describes the wire limits.
2.3 GENERATED RESPONSE TRAILERS
--------------------------------------------------------------------------------
Shared handlers opt in through the additive iHttpResponseTrailers companion:
lFields := tHttpHeaders.Create;
try
lFields.Add('x-result', 'complete');
if Supports(aResponse, iHttpResponseTrailers, lOutgoing) then
lOutgoing.SetTrailers(lFields);
finally
lFields.Free;
end;
Declare lOutgoing as iHttpResponseTrailers. SetTrailers validates and copies
the whole ordered section atomically; an exception leaves the previous section
intact. A nil or empty collection clears it. The builder-owned Trailers view
is read-only to consumers, valid until the next successful setter or builder
destruction. Do not free or mutate it. Initial Headers remain separate.
Response preparation on a streaming worker follows section 24: finish all
builder changes before TryComplete/TryReject, then never mutate the sealed
response. SetTrailers supplies already prepared fields. For fields calculated
while reading the response source, use the companion in section 2.3.1.
All wires send the copied section after the entire body. HTTP/1.1 automatically
uses chunked framing and declares the generated names when the section is
nonempty, replacing conflicting Content-Length, Transfer-Encoding and Trailer
fields. Optional response trailers can be sent without TE: trailers; that field
indicates willingness to receive them, and an intermediary may discard them.
A body-bearing response to an HTTP/1.0 request cannot carry generated trailers
and becomes a local 500 before a response head is emitted. HEAD and statuses
1xx, 204, 205 and 304 suppress the trailer section along with the body.
HTTP/2 sends terminal HEADERS/CONTINUATION with END_STREAM after DATA,
respecting owner send credit through a single bounded encoded terminal block.
If cancellation/reset must abandon this pending stateful block, the connection
is retired to avoid compression desynchronization or a fabricated successful
END_HEADERS. Cancellation before commitment or after full handoff retains
ordinary per-stream behavior. HTTP/3 sends terminal HEADERS before the final
QUIC FIN; an empty generated field list uses ordinary FIN without HEADERS.
Empty static sections preserve ordinary response framing. A source error or
cancellation does not emit a successful terminal section.
Generated names must be tokens and pass the shared forbidden-field policy
(section 2.2), including current initial Connection nominations. Values are
single-octet strings: U+0000..U+00FF represents the corresponding wire byte,
subject to field-value rules. Non-octet Unicode, forbidden controls, DEL and
leading/trailing SP/HTAB are rejected; interior HTAB, high octets, duplicates,
empty values and order are retained. Names are normalized to lowercase.
Each section charges name/value wire bytes plus 32 bytes per field, at most
16384 bytes; its encoded terminal storage is separately bounded at 32768.
Peer field-section limits can be smaller. Trailer metadata is separate from
payload budgets. The application selects fields whose definitions allow trailer
use; optional metadata cannot replace framing, routing or authentication.
2.3.1 DEFERRED FIELDS AT RESPONSE BODY EOF
--------------------------------------------------------------------------------
For fields computed while the outgoing response source is read, query the
additive iHttpResponseDeferredTrailers companion after configuring the body:
if Supports(aResponse, iHttpResponseDeferredTrailers, lDeferred) then
lDeferred.SetTrailerProducer(['x-body-sha256'], lProducer);
lProducer implements iHttpResponseTrailerProducer:
function ProduceTrailers: tHttpHeaders;
The callback explicitly initializes Result and returns a NEW owned collection,
or nil for no fields. The library validates and copies the fields, then frees
that collection. Do not return a borrowed view. If the callback raises, it
must free any partial result it allocated. The declaration is copied,
normalized to lowercase, deduplicated and bounded before registration succeeds.
Returned fields must be a subset of the declaration; duplicates and omitted
names are allowed. An empty declaration permits only an empty result.
ProduceTrailers runs once after successful consumption of exactly the selected
response source offset/length range, before the transferred source is freed.
It does not read beyond the range to probe the underlying file's EOF and does
not wait for remote delivery. An eligible zero-length body finalizes once.
HEAD, 1xx, 204, 205 and 304 suppress it. Short reads, source errors, cancellation
or connection shutdown before range completion release it without a callback.
Application-selected 1xx statuses are normalized to an empty final 500;
protocol-owned informational responses such as 100-continue are unchanged.
No callback runs from a destructor. A producer exception or invalid final field
aborts the unfinished response without a successful end marker: HTTP/1.1 closes
the connection; HTTP/2 and HTTP/3 follow their stream/compression failure rules.
The callback executes synchronously on the connection owner. Keep it short and
nonblocking, and do not reenter server/component operations. A hashing source
and producer can share a reference-counted hash context. Do not keep a raw
pointer to the source: reading BodyStream can materialize and free it before
wire processing. A memory-stream hash observer must cover every Read overload
used by its RTL; a TStream composition wrapper avoids optimized memory-stream
overloads, as shown by the native digest fixture. Materialization preserves the
producer on success and cancels
it on read failure. No digest algorithm is chosen or computed automatically.
Configure the body BEFORE the producer. Replacing the body clears its bound
producer. The last successful static SetTrailers or non-nil SetTrailerProducer
selects that mode and clears the other; nil producer clears deferred generation.
As with other builder changes, finish registration before TryComplete/TryReject.
HTTP/1.1 chooses chunked framing before final values exist, including when the
producer later returns no fields; an empty declaration emits no Trailer header.
HTTP/1.0 refuses this mode before the original response head. HTTP/2 and HTTP/3
withhold successful termination while generation is pending. Parked final
metadata never invokes the callback again. Existing field/wire bounds and late
peer limits apply. Declaration storage and frozen Connection nominations are
each capped at 16 KiB including field overhead; neither is payload storage.
--------------------------------------------------------------------------------
3. STATIC FILE SERVING
================================================================================
AddFile(reqPath, physFile) registers ONE exact match. On a hit the internal file
handler rejects non-GET/HEAD with 405 and otherwise just calls
iHttpResponse.SendFile, which does the rest: a missing file sets 404 and clears
the body (leaving any headers already set), and a readable one is OPENED and
becomes the body - nothing is read yet - with Content-Type overwritten from the
extension (HttpMimeType: .html/.css/.js/.json/.png/.jpg/.svg/.ico/.txt/.wasm/
.woff2/..., textual types carrying '; charset=utf-8', default
application/octet-stream). Note the overwrite: a Content-Type the handler set
before calling SendFile is discarded. Content-Length is NOT set here - the wire
session adds it from the body's length. No path is derived from the request -
only the registered exact matches are served, so there is no traversal surface
by design. Directory/prefix mounting (AddDirectory) with traversal-safe path
resolution is the future extension.
BYTE RANGES, VALIDATORS AND CONDITIONAL REQUESTS. SendFile ignores a Range
header and sends no validator, so nothing it serves can be revalidated or
resumed. Four exported functions do the rest, and one of them is the call to
make for anything static:
HttpSendStream(aRequest, aResponse, aStream, aOwns, aContentType,
aValidators [, aCacheControl]); <- THIS ONE
HttpSendFile(aRequest, aResponse, physFile [, aCacheControl]);
the same, by path
HttpSendStreamRange(aResponse, aStream, rangeHeader, aOwns, aContentType);
aResponse.SendFileRange(physFile, rangeHeader); (iHttpResponse member)
HttpSendStream does RFC 9110 sections 13 and 14 in the order the RFC prescribes,
then hands the body to HttpSendStreamRange:
If-None-Match weak comparison against ETag; '*' matches. False ->
304 for GET/HEAD, 412 for anything else; If-Modified-
Since is then not consulted.
If-Modified-Since GET/HEAD only, only without If-None-Match, only when
Last-Modified is known and the value parses; not
modified since -> 304.
If-Range only with a Range. An entity-tag matches under STRONG
comparison (a weak tag on either side never does); a
date only if it equals Last-Modified to the second.
No match - or nothing of ours to compare against - and
the Range is IGNORED: the whole thing goes as 200.
Range 200 / 206 + Content-Range / 416 with an EMPTY body and
'Content-Range: bytes */total'; Accept-Ranges: bytes on
every outcome. A SINGLE 'bytes' range only - a multi-
range request gets 200 and everything, deliberately (a
206 carrying only the first of several requested ranges
is the trap; the client cannot tell).
ETag and Last-Modified go on every 200, 206 and 304 when known; a 304 carries
them, Accept-Ranges and no body, as the 200 it stands in for would have. It
answers the status it set. aStream is read from Position 0 and freed on every
path when aOwns is True. aContentType is set on 200 and 206 when not '' - a
stream has no extension, so the caller decides.
tHttpValidators = record
ETag: string; '"1f3-5d1a"' or 'W/"..."'; '' = none
LastModified: TDateTime; UTC; 0 = none; whole seconds on the wire
end;
NOTHING CONDITIONAL HAPPENS WITHOUT VALIDATORS. Pass HttpStreamValidators(
aStream) for a file: it reads size and last-write time off the OPEN HANDLE
behind a THandleStream (TFileStream and both stFileJail stream classes) - never
off a path, so a jail-verified stream keeps its proof - and builds a strong ETag
'"<size>-<mtime>"' in hex. A stream that is not a THandleStream yields empty
validators, and then no validator is sent and no precondition is evaluated.
Anything else - a generated body with a version number, say - fills the record
itself.
WHY THE STREAM FORM EXISTS. SendFileRange opens its file by name, and that is
the one thing a caller serving out of a verified stFileJail handle must not do:
the handle IS the containment proof, and re-resolving the name is the
check-then-use the jail was written to remove. Until these functions the choice
was race-free serving (jail stream + SetContentStream) OR ranges (path +
SendFileRange), never both. Now: open through the jail, hand the stream to
HttpSendStream. HttpSendFile is for callers that hold a path they trust (a
registered mapping); it opens the file, reads its validators off the handle,
sets Content-Type from the extension and calls HttpSendStream; 404 for a file
that is not there. Both are standalone functions rather than iHttpResponse
members, for the iHttpPrefixRouter reason: they use only the interface's public
members, plus iHttpResponseSource where the response offers it.
A FILE IS SENT FROM THE FILE. When the stream is handed over (aOwns = True, as
SendFileRange and HttpSendFile do), the response does not copy the window: it
keeps the stream, through iHttpResponseSource, and the wire session reads it in
pieces as the peer takes them (section 3.1). The file stays open - opened by
SendFile, SendFileRange or HttpSendFile, it is closed to writers - until the
response has gone or the connection has. With aOwns = False the stream stays the
caller's and may be gone the moment the handler returns, so the window IS
copied, and a large one is a large allocation. SetContentStream follows the same
rule: aOwns = True keeps the stream, aOwns = False copies it.
iHttpResponseSource = interface { Supports on an iHttpResponse }
procedure SetContentSource(aStream: TStream; aOffset, aLength: Int64);
end;
SetContentSource makes the body aLength octets of aStream from aOffset and TAKES
the stream - the response frees it when it is done with it, or when another body
replaces it. tHttpServerResponse implements it; BodyLength reads the length
without touching the stream, and BodyStream, for code that inspects a response
as one block of memory, materialises it on first use.
HTTP-date is exported too, because a handler setting Expires or reading a date
of its own needs the same two functions: HttpFormatDate emits IMF-fixdate ('Sun,
06 Nov 1994 08:49:37 GMT', always GMT, English names whatever the locale);
HttpTryParseDate accepts the three forms a recipient MUST accept - IMF-fixdate,
RFC 850 ('Sunday, 06-Nov-94 08:49:37 GMT', two-digit year read as the most
recent such year not more than 50 years ahead) and asctime ('Sun Nov 6 08:49:37
1994').
CACHE-CONTROL IS THE CALLER'S POLICY. HttpSendStream and HttpSendFile take an
optional aCacheControl, sent verbatim on 200, 206 and 304 (RFC 9111 section
4.3.4: a 304 must carry what the 200 would have) and not sent at all when ''.
The library has no opinion on how long your content may be cached; four
constants name the usual answers, chosen by HOW THE RESOURCE CHANGES, not by
what it is:
cHttpCacheRevalidate 'no-cache' may be stored, checked
before every reuse; the
safe default for a file
that changes in place
cHttpCacheStatic 'public, max-age=86400' a day without asking,
then revalidate
cHttpCacheImmutable 'public, max-age=31536000, immutable'
ONLY for a URL that
changes when the content
does (hash in the name)
cHttpCacheNoStore 'no-store' one user's data
The validators are what make any of these cheap: a cache whose copy has expired
revalidates with If-None-Match and is answered with a bodiless 304. Without them
'no-cache' would mean a full re-download per use.
3.1 HOW A RESPONSE LEAVES - PACED BY THE TRANSPORT
--------------------------------------------------------------------------------
All three wire engines send large responses in bounded pieces as their transport
accepts data. An owned file/content stream remains a stream; it is not copied
whole into memory. A memory-backed response still occupies memory until its
source has been consumed or the request/connection is terminated.
HTTP/1.1 AND HTTP/2 OVER TCP/TLS. A Send that does not fit beneath
TsmAsyncTLSServer.MaxSendQueueBytes closes the connection (AsyncTLSServer.txt
section 5.05). Other output can already be queued: the TLS 1.3 NewSessionTicket
flight may follow the handshake, and another HTTP/2 stream may be sending when a
WINDOW_UPDATE opens more peer credit.
The two TCP sessions keep at most about 1 MiB (cResponseReadAhead) with the
transport, in Sends of at most 512 KiB on HTTP/1.1 (cResponseChunk) and about
256 KiB on HTTP/2. Neither exceeds iAppTransportFlow.SendCredit. Output resumes
through iAppSessionDrain.Drained as the transport drains. A small response can
leave in one Send, with its headers and body together.
HTTP/1.1 The header block and first body piece go together; the rest follows
as the transport drains. Responses remain ordered, so a pipelined
request waits in the receive buffer until the preceding response
has gone. That raw waiting buffer is bounded by twice HeaderBytes
plus BodyBytes for a head, chunk metadata and payload. Exceeding
that bound drops the connection. A requested
Connection: close takes effect after the whole body is handed over,
followed on the wire by TLS close_notify.
HTTP/2 tHttp2Conn produces DATA while both the peer's flow-control windows
and the transport room reported by OnOutputRoom permit it.
ResumeOutput is driven by Drained and by peer WINDOW_UPDATE.
Streams remain multiplexed; transport queue room and HTTP/2 flow
control are separate permissions to send.
HTTP/3 OVER QUIC/UDP. tHttp3ServerConn obtains per-stream capacity from
iHttp3ServerTransport.SendCapacity before reading a source or sending data. It
reads an owned response stream in pieces of at most 16 KiB, also bounded by
remaining source length and MaxBufferedSendBytes queue room. Its pump rotates
among streams and limits each stream's burst, so a large response does not
consume every send opportunity. The QUIC adapter resumes it when writable; QUIC
owns transport flow control, packet pacing, recovery and retransmission.
HTTP/3's MaxMemoryResponseBytes and the plugin's TotalResponseBytes bound the
memory-backed response sources it retains. Owned file sources do not charge
their full file length to those memory counters. MaxBufferedSendBytes bounds the
engine's queued HTTP/3 output separately (sections 14 and 20).
A body that cannot be delivered after its length was announced is not completed
with an orderly end a client could mistake for success. HTTP/1.1 drops the
connection; HTTP/2 resets its stream with INTERNAL_ERROR; HTTP/3 aborts its
request stream with H3_INTERNAL_ERROR. A file that shrinks or fails to read can
therefore leave a partial response, but is not reported as a complete body.
--------------------------------------------------------------------------------
4. THE HTTP/1.1 WIRE SESSION (tHttp11Session)
================================================================================
Per connection, driven by iAppSession over the async TLS server:
- DataReceived parses the request line and fields, then reads Content-Length
payload or decodes HTTP/1.1 chunks incrementally. Path is the target up to
'?'; Query is the remainder. Handlers receive one complete decoded
Body stream, with no chunk framing or extensions. Received trailers are
available separately through iHttpRequestTrailers (section 2.2).
- A complete request reaches TsmCustomHTTPSProtocol.DispatchRequest through
the shared router/event path. The response uses a status line, Date,
Content-Type, Content-Length and Connection fields as applicable, followed
by its body through iAppTransport.Send. Small responses can leave in one
Send; large owned sources are paced by the transport (section 3.1).
- Keep-alive is the HTTP/1.1 default. Connection: close and HTTP/1.0 policy
are honoured after the response is handed over. Pipelined requests remain in
wire order; bytes after the current request's complete framing belong to
the next request, whose response waits for the preceding one to leave.
- HEAD emits response headers only. Request bodies can use Content-Length or
chunked framing; server response bodies use Content-Length, or chunked
framing when the response carries trailers (section 2.2).
CHUNKED REQUESTS. The accepted transfer coding is one case-insensitive
Transfer-Encoding: chunked field, with legal optional whitespace and no
Content-Length. Chunk sizes are checked hexadecimal numbers. Each size line,
payload and following CRLF can arrive in separate fragments. A zero chunk does
not complete the request until its trailer section's final blank line arrives.
An incomplete request is never dispatched, including when its connection ends.
The decoder consumes framing as it progresses, rather than retaining complete
encoded and decoded copies of the body or rescanning the whole upload.
Valid chunk extensions, including quoted values, are checked and ignored.
Trailer fields are validated and retained in the separate request-owned
collection described in section 2.2, with no merge into request.Headers.
Malformed fields, folding, controls and forbidden or Connection-nominated names
are refused. Existing handlers keep their complete-body API; chunked decoding
does not introduce incremental application consumption.
REQUEST FRAMING IS STRICT. A failed parse closes the connection because the
start of the next request cannot be trusted. The principal refusals are:
Transfer-Encoding plus CL 400 neither framing interpretation is guessed
duplicate Transfer-Encoding 400 even if both values say chunked
repeated/non-final chunked 400 chunked must be applied exactly once, last
malformed transfer coding 400 invalid syntax or a non-chunked final coding
HTTP/1.0 transfer coding 400 transfer coding requires HTTP/1.1
unsupported coding before 501 a valid chain ends in chunked, but another
final chunked coding in it is not implemented
malformed chunk framing 400 checked size, extension and CRLF grammar;
arithmetic overflow is also refused
forbidden/bad trailer 400 no late change to framing or request meaning
duplicate Content-Length 400 even when the values agree
nondecimal/overflowing CL 400 no coercion to an absent or zero-length body
space before field colon 400 field names are tokens, without trailing OWS
obsolete line folding 400 no reinterpretation as an independent field
header line with no colon 400 no silent field removal
non-token field name 400 controls, spaces and non-ASCII in a name
request line not 3 parts 400 no truncation of a target containing a space
non-token method 400
version not 1.0 or 1.1 505
Limits.HeaderBytes defaults to 64 KiB and separately bounds the request head
and aggregate chunk metadata: size lines, extensions, payload CRLFs and
trailers, including the final blank line. HeaderBytes also separately bounds
the retained trailer charge, including 32 bytes per field. Complete heads are
bounded too.
Over either metadata budget gives 431 and closes. Limits.BodyBytes defaults
to 8 MiB and counts decoded payload; exceeding it gives 413 and closes. Each
announced chunk reserves server-wide TotalBodyBytes before its payload is
retained; insufficient room gives 503 and closes. Zero keeps the
configurable unlimited-policy meaning, subject to structural
arithmetic/storage bounds. Section 20 describes accounting and refusal
events.
Every malformed/limit refusal above sends its status and closes, so trailing
bytes cannot be mistaken for a valid pipelined request. Body reservations are
released on dispatch, refusal and teardown. Early-data provenance is retained
across fragmented framing and body data, without leaking into a later ordinary
request. A handler exception becomes 500 on that request.
RESPONSE FIELDS ARE CHECKED BEFORE ANY IS WRITTEN. The writer puts each field on
the wire as 'Name: value' and CRLF, so a CR or LF in a value would end the field
there and turn the rest into another field or the start of the body. Every field
in the response's Headers is therefore checked first: the name must be a token
(RFC 9110 s5.6.2), and the value may hold no control character other than HTAB,
no DEL, and no SP or HTAB at either end. One field that fails replaces the
response with a 500 whose body is 'Internal Server Error'; nothing the handler
set goes out. Non-ASCII characters in a value are not refused: the head is
written as UTF-8. A name stays ASCII tchar.
THE WRITER'S OWN FIELDS. Content-Length, Date and Connection are the writer's,
and Transfer-Encoding and Trailer describe the framing it chooses. Every one of
them the handler set is dropped - each copy, set with SetHeader or added with
Headers.Add - and the writer adds its own: Date and Connection always;
Content-Length when it frames the body by length, 0 on a 205 and none on 204
and 304; Transfer-Encoding: chunked and its own Trailer declaration when it
frames the body chunked, which it does for trailers (section 2.2). So each goes
out once - RFC 9110 s5.3: a sender "MUST NOT generate multiple field lines with
the same name" unless the field is a list - and Transfer-Encoding never beside
Content-Length, which a client would read as a chunked body (RFC 9112 s6.2: "A
sender MUST NOT send a Content-Length header field in any message that contains
a Transfer-Encoding header field."). A value the handler gave one of them is
still checked as above: one that cannot be written fails the response, though
it would not have gone out. HTTP/2 and HTTP/3 drop every Content-Length, Date,
Connection and Transfer-Encoding the handler set as well (section 5).
THE STATUS LINE. The reason phrase is application text on the status line, where
a CR or LF would end the line and start a field. One that holds a control
character other than HTAB, or DEL, is replaced by the standard phrase for the
status; HTAB, SP and characters above U+007F go out as given, the latter as
UTF-8. A status outside 100..599 (RFC 9110 s15: "All valid status codes are
within the range of 100 to 599, inclusive.") goes out as 500 with the handler's
fields and body, and the status line then carries the standard reason phrase.
--------------------------------------------------------------------------------
5. BINARY HTTP - HTTP/2 AND HTTP/3
================================================================================
Both binary protocols multiplex request/response exchanges and map their fields
and bodies into the shared core. Their transport and wire state differ:
Property HTTP/1.1 HTTP/2 HTTP/3
-------------------- ---------------- ----------------- -----------------
Host TLS host same TLS host QUIC host
Transport TLS over TCP TLS over TCP QUIC over UDP
ALPN http/1.1 h2 h3
Exchanges ordered requests HTTP/2 streams QUIC bidi streams
Header encoding text fields HPACK QPACK
Body end length/chunks END_STREAM QUIC FIN
Flow control TCP/queue credit h2 windows + TCP QUIC stream/conn
Shared handler iHttpRequest / iHttpResponse through one iHttpRouter
HTTP/2 uses one ordered TLS byte stream. Its framing, stream state, HPACK table,
SETTINGS acknowledgements, WINDOW_UPDATE and RST_STREAM are described in
sections 6-13. These are HTTP/2 mechanisms, not a second implementation of QUIC.
HTTP/3 assigns each request to a QUIC bidirectional stream. QUIC supplies stream
delivery, flow control, loss recovery and connection security. HTTP/3 supplies
its own HEADERS/DATA/control framing and QPACK rules (section 14). It has no
HTTP/2 preface, CONTINUATION, WINDOW_UPDATE or SETTINGS ACK. QPACK has its own
dynamic table, off unless configured (section 23.5); it does not reuse HPACK's
dynamic table state.
All three server components support complete bounded requests and the opt-in
streaming request exchange (section 24), and can stream an owned response
source. Ordinary handlers remain synchronous; streaming admission stays quick
while application workers consume the detached body. Shared mapping, execution
and limits are covered in sections 13, 17, 20 and 24.
--------------------------------------------------------------------------------
6. HTTP/2 CONNECTION LIFECYCLE
================================================================================
TLS 1.2 OR LATER. RFC 9113 s9.2: "Implementations of HTTP/2 MUST use TLS
version 1.2 [TLS12] or higher for HTTP/2 over TLS." ALPN selects h2 whatever
version the handshake settled on, and the TLS engine's own floor,
StreamSec.Mobile.TlsConst.VersionMinorMin (TLS 1.2 by default; TLS.txt), is
process-wide: lowering it for a legacy HTTP/1.1 peer lowers it for h2 as well.
So both HTTP/2 endpoints check the negotiated version themselves. Below TLS 1.2
the server sends its preface (SETTINGS), then GOAWAY(INADEQUATE_SECURITY),
closes the connection and dispatches nothing. The HTTP/2 client sends its
preface and SETTINGS, then the same GOAWAY, and closes the connection too,
without taking a request on it (section 23.1). RFC 9113 s5.4.1: "After sending
the GOAWAY frame for an error condition, the endpoint MUST close the TCP
connection." INADEQUATE_SECURITY is the error code for a transport that does
not meet the minimum security requirements of s9.2 (s7). A transport that
reports no TLS version at all (zero) is not refused: s9.2 is about HTTP/2 over
TLS.
CLIENT PREFACE (RFC 9113 s3.4). Immediately after the TLS handshake (ALPN 'h2'),
the client sends the 24-octet connection preface followed by a SETTINGS frame:
50 52 49 20 2a 20 48 54 54 50 2f 32 2e 30 0d 0a "PRI * HTTP/2.0\r\n"
0d 0a 53 4d 0d 0a 0d 0a "\r\nSM\r\n\r\n"
SERVER PREFACE. The server answers with its own connection preface, which is a
SETTINGS frame (possibly empty) and MUST be the first frame it sends. The peers
then exchange SETTINGS ACKs (flag 0x1) for each other's SETTINGS.
Sequence on the wire:
server opens -> server SETTINGS (our parameters, section 11)
first client bytes-> the 24-octet magic is required, then a client SETTINGS
frame; a non-SETTINGS first frame is a connection error
PROTOCOL_ERROR. It is ACKed and normal framing begins.
our SETTINGS -> the peer's ACK is awaited but not timed out
each peer SETTINGS -> applied, then ACKed
SHUTDOWN. GOAWAY(last-stream-id, code) is sent on one occasion only: a
connection error. last-stream-id is the highest client stream id seen, so the
peer learns which streams were processed; the frame does not itself close the
transport, the close follows it, and it happens at most once. When the transport
reports the connection gone in the other direction, no frames are emitted at
all.
Two consequences to be honest about, both listed as extensions in section 18:
there is NO graceful GOAWAY(NO_ERROR) path (nothing today refuses new work while
letting live streams drain, so the polite shutdown a load balancer wants is not
implemented), and the MEANING of a RECEIVED GOAWAY is ignored - we record
nothing, so HEADERS arriving after it still open streams normally. The rationale
is that the peer stops sending, and a server that must keep serving in-flight
streams gains nothing by tracking the frame; the cost is that we do not detect a
peer that says GOAWAY and then keeps opening streams.
THE RECEIVED FRAME ITSELF IS CHECKED AND CHARGED. A GOAWAY on a stream other
than 0 is a connection error PROTOCOL_ERROR (s6.8: "An endpoint MUST treat a
GOAWAY frame with a stream identifier other than 0x00 as a connection error
(Section 5.4.1) of type PROTOCOL_ERROR."), and one shorter than its 8 mandatory
octets - the last stream ID and the error code - is FRAME_SIZE_ERROR (s4.2).
A GOAWAY that passes both checks costs one token of MaxUnproductiveFrames
(section 20), so a peer that sends nothing but GOAWAYs runs the budget out and
gets GOAWAY(ENHANCE_YOUR_CALM).
--------------------------------------------------------------------------------
7. HTTP/2 FRAME LAYER
================================================================================
Every frame is a 9-octet header (length, type, flags, stream id) plus a payload,
big-endian, per RFC 9113 s4.1. A frame's declared length must be within the
receiver's SETTINGS_MAX_FRAME_SIZE; we advertise 16384 and hold peers to it.
Oversize is ALWAYS a connection error FRAME_SIZE_ERROR - there is no
per-frame-type leniency - and the length is checked BEFORE the payload is
buffered, which is what stops a hostile 24-bit length from forcing an unbounded
allocation.
FRAME TYPES, and what this server does with each
DATA $00 stream body octets; flags END_STREAM $1, PADDED $8
HEADERS $01 HPACK header block; flags END_STREAM $1, END_HEADERS $4,
PADDED $8, PRIORITY $20
PRIORITY $02 5-octet priority (parse + IGNORE; deprecated by 9113)
RST_STREAM $03 4-octet error code; abrupt stream termination
SETTINGS $04 0..N * 6-octet (id16,value32); flag ACK $1 (payload empty)
PUSH_PROMISE $05 server push (we never send; RECEIPT is a connection error
PROTOCOL_ERROR - we advertise ENABLE_PUSH 0)
PING $06 8-octet opaque; flag ACK $1 (echo back with ACK set)
GOAWAY $07 last-stream-id32 + error32 + optional debug data
WINDOW_UPDATE $08 4-octet window-size increment (conn if stream 0, else stream)
CONTINUATION $09 HPACK header block continuation; flag END_HEADERS $4
FLAGS END_STREAM $01 ACK $01 END_HEADERS $04 PADDED $08 PRIORITY $20
Inbound framing is streaming: whole frames only are acted on, and a partial
trailing frame waits for the rest of its bytes. PADDED frames are accepted and
their padding stripped; we never pad on write.
--------------------------------------------------------------------------------
8. HPACK & HEADER-BLOCK ASSEMBLY
================================================================================
Header compression is per connection and lives as long as it does: the HPACK
dynamic table is connection-scoped, and a decoder that loses sync with the
peer's encoder cannot recover, which is why a decode failure below is fatal to
the whole connection rather than to one stream.
A header block = one HEADERS (or PUSH_PROMISE) frame followed by zero or more
CONTINUATION frames, and it MUST be contiguous: once a HEADERS without
END_HEADERS is seen, the ONLY legal next frame is a CONTINUATION on the SAME
stream. Any other frame (even on another stream) before END_HEADERS is a
connection error PROTOCOL_ERROR (RFC 9113 s4.3). Concatenate the block
fragments, then HPACK-decode the whole thing exactly once. An HPACK decode
failure is a connection error COMPRESSION_ERROR - the dynamic table is now
unrecoverable for the connection.
MEMORY BOUNDS. SETTINGS_MAX_HEADER_LIST_SIZE accounting (uncompressed
name+value+32 per field) IS implemented, bounded at 64 KiB
(cMaxHeaderListBytes), enforced inside the HPACK decoder over every emitted
field - including the ones that come from the static and dynamic tables, which
are exactly the cheap ones an expansion attack is built from - and advertised in
the server's initial SETTINGS.
ADVERTISING IT IS A COURTESY; ENFORCING IT IS THE POINT. The parameter is
advisory on the wire, so a peer is free to ignore what we announce; the local
ceiling is what actually protects us and is deliberately the same number. This
is the one place where a SETTINGS value we send is also a rule we keep, and the
reason is that no OTHER cap can substitute for it: the CONTINUATION guards below
bound the COMPRESSED block, and HPACK's entire job is to make those two numbers
differ. A 256 KiB block of one-octet indexed references against a full 4 KiB
dynamic table decodes to something on the order of a gigabyte.
Breaching it is a CONNECTION error with ENHANCE_YOUR_CALM rather than
COMPRESSION_ERROR: abandoning a block midway desynchronises the dynamic table,
so it cannot be a stream error, but the peer is abusive rather than broken and
the code should say which. Any per-field policy beyond the total an application
wants is still its own to add.
THE DECODER ALSO BOUNDS the integers themselves. Every HPACK integer - index,
string length, table-size update - is accumulated wide and refused above MaxInt,
and string lengths are range-checked in Int64. That is memory safety rather than
policy: against a bare Cardinal accumulator, a 5-octet continuation could
overflow it to $8000007F, whose cast to Integer is NEGATIVE, which would pass
the "does this string fit in the block" test and reach SetLength/Move with a ~2
GB count. Six octets of header block, on any h2 endpoint, for a multi-gigabyte
allocation and an out-of-bounds read. HpackSelfTest carries the vectors for it,
with positive controls.
REQUEST pseudo-headers (RFC 9113 s8.3.1): :method :scheme :path (:authority
optional but expected). All pseudo-headers MUST precede regular fields; any
pseudo-header after a regular field, an unknown pseudo-header, a duplicate, or a
missing required one is a malformed request -> stream error PROTOCOL_ERROR, and
no response (section 13). Connection-specific fields (Connection, Keep-Alive,
Proxy-Connection, Transfer-Encoding, Upgrade) MUST NOT appear -> malformed. "TE"
may appear, but only as "trailers".
RESPONSE: :status is the sole response pseudo-header, emitted FIRST, value = the
decimal status, always in 100..599 (a status outside it goes out as 500).
Regular response fields follow. Names are lowercased by the HPACK encoder
already; there is no status line and no Connection field, and the date field is
the engine's own. Section 13.2 lists what survives of the handler's fields.
THE CONTINUATION-FLOOD GUARD IS TWO CAPS, not one: an assembled header block may
not exceed 256 KiB, and one block may not span more than 128 frames. Tripping
either is a CONNECTION error with code ENHANCE_YOUR_CALM ($0b) rather than
PROTOCOL_ERROR - the peer is not malformed, it is abusive, and the code says so.
--------------------------------------------------------------------------------
9. HTTP/2 STREAM STATE MACHINE (RFC 9113 s5.1)
================================================================================
Client streams are odd, strictly increasing; the server opens none (no push), so
even ids and the reserved states are unused. Per-stream state we track:
idle no frames yet
open HEADERS received (request head complete or in progress)
half-closed(remote) client sent END_STREAM; request fully received; server may
still send its response
half-closed(local) server sent END_STREAM (unusual before the client is done)
closed RST_STREAM either way, or both END_STREAMs, or connection GOAWAY
Transitions we honour (receive side):
idle --HEADERS--> open (new request; id must exceed all prior
client ids, else PROTOCOL_ERROR)
open --END_STREAM (HEADERS/DATA)--> half-closed(remote) (request complete ->
dispatch)
any --RST_STREAM--> closed (drop the stream, free its buffers)
half-closed(remote) --response HEADERS+DATA(END_STREAM)--> closed (send side)
Frame legality by state (reject illegal -> STREAM_CLOSED or PROTOCOL_ERROR):
- DATA/HEADERS on idle with a LOWER-or-equal id than an established stream:
connection error PROTOCOL_ERROR.
- DATA on a stream that is not open: RST_STREAM(STREAM_CLOSED) and the stream
is dropped. In practice most late DATA never reaches that test, because a
stream is forgotten the moment its response is flushed. An unknown id is then
judged against the highest client id seen so far: above it means "idle", a
connection PROTOCOL_ERROR; at or below it means "closed", tolerated silently.
- HEADERS on a stream the server RESET while the client could still be sending
on it - a 413 at HEADERS, a body reset at a cap, REFUSED_STREAM, a malformed
content-length - is decoded through HPACK, so the dynamic table stays in
step, and dropped (s5.1: "An endpoint MUST minimally process and then
discard any frames it receives in this state. This means updating header
compression state for HEADERS and PUSH_PROMISE frames."). Nothing is sent
on the stream, and each such block costs one unproductive-frame token. This
is how trailers that were already on their way are taken.
Such a stream is remembered until the client ends its side of it (END_STREAM
on a DATA or HEADERS that was dropped, or a RST_STREAM of its own) or until
newer resets push it out of a list as long as MaxConcurrentStreams (100 when
that is 0) - no timer (s5.1: "Endpoints SHOULD NOT use timers for this
purpose"). A client counts a stream the server reset as open until it has
read the reset or reset the stream itself, and reads the resets in order.
Take a reset that finds the list full, and the newest stream the client
opened among the listed ones and the one being reset (not always the one
being reset: a stream reset on its DATA may be older). A client that keeps
to the concurrency limit cannot have counted all the others as open when it
opened that newest one, so it had read the oldest reset by then - and
everything it sent on the oldest stream came before that HEADERS, which has
arrived. That does not hold
for a client that ignores the limit, for MaxConcurrentStreams 0 (no limit
is announced, but the list stops at 100), or for the client's first flight,
sent before it has read the server's SETTINGS (s6.5.2: "Initially, there is
no limit to this value."): there a HEADERS on a stream pushed out is the
connection error below.
The list is a set of stream ids linked in the order they were listed, so
listing a stream, finding it, taking it off and pushing out the oldest
each cost the same however long the list is - MaxConcurrentStreams may be
set far above 100.
Any other HEADERS at or below the highest id seen - on an id the client
skipped, on a stream both sides ended, on one the client reset, on one
pushed out of that list - is a connection PROTOCOL_ERROR.
- WINDOW_UPDATE / RST_STREAM / PRIORITY are allowed in more states (incl. shortly
after close) - tolerate a late WINDOW_UPDATE/RST_STREAM on a just-closed stream.
- A STREAM ERROR ENDS THE STREAM. A WINDOW_UPDATE with an increment of 0
(s6.9, PROTOCOL_ERROR) and a PRIORITY that is not 5 octets (s6.3,
FRAME_SIZE_ERROR) are stream errors: a live stream gets RST_STREAM and is
dropped at once, so the rest of a response waiting for window is never
sent, and what the client still sends on it is dropped as above. On a
closed stream nothing is sent; on an idle one, which RST_STREAM may not name
(s6.4), the error is a connection error with the same code (s5.4.1).
- A second HEADERS on a request is its trailer section only if it ends the
request; without END_STREAM it makes the request malformed (s8.1). Trailers
are held to the field rules of the request's own fields - no pseudo-header
field (s8.1), the s8.2.1 name and value rules (section 13), no
connection-specific field, and the shared forbidden-field policy of
section 2.2. A field that breaks these rules makes the request malformed:
RST_STREAM PROTOCOL_ERROR, not dispatched. Valid fields remain separate
from initial Headers and are visible through iHttpRequestTrailers.
- A RESET THE CLIENT PROVOKES COSTS WHAT ONE IT SENDS DOES. Every stream the
server resets for something the client sent - the stream errors above, a
WINDOW_UPDATE that takes a stream's window past 2^31-1, DATA after
END_STREAM, a malformed request, a body refused at a limit - costs one
token of MaxUnproductiveFrames, as the client's own RST_STREAM does
(section 20). So does a stream error on a stream that has closed, where
nothing is sent. A reset the server causes itself - INTERNAL_ERROR on a
response body that cannot be read - costs nothing.
- Exceeding SETTINGS_MAX_CONCURRENT_STREAMS (peer opening too many): refuse the
excess with RST_STREAM(REFUSED_STREAM) - a stream error, connection survives.
A request is DISPATCHED when its header block is complete (END_HEADERS) AND the
request body is complete (END_STREAM on HEADERS, or on the final DATA). Body =
concatenation of DATA payloads, bounded by the same 8 MiB cap as HTTP/1.1
(section 20).
OF THE FIVE RFC STATES, ONLY FOUR ARE REACHABLE HERE and one of those never
occurs. half-closed(local) cannot arise, because it would need the server to
send END_STREAM while the client is still sending, and dispatch happens only
after the request is complete - by then the stream is already
half-closed(remote) and goes straight to closed. The reserved states are unused
for the same reason even stream ids are: there is no push. A stream is forgotten
as soon as it closes, which is what bounds per-connection memory to the LIVE
stream set rather than to every stream the connection has ever carried.
--------------------------------------------------------------------------------
10. HTTP/2 FLOW CONTROL (RFC 9113 s5.2, s6.9)
================================================================================
Two levels of credit, both octet counters, DATA-frame payloads only (headers,
SETTINGS, etc. are NOT flow-controlled):
connection send-window how many DATA octets WE may send across all streams
per-stream send-window how many DATA octets WE may send on that one stream
connection recv-window how many DATA octets we let the peer send us (conn-wide)
per-stream recv-window ditto per stream
Initial value = 65535 for every window (the spec's fixed default), EXCEPT that a
peer SETTINGS_INITIAL_WINDOW_SIZE changes the initial per-stream SEND window for
streams opened AFTER it and RE-BASES all existing stream send-windows by the
delta (RFC 9113 s6.9.2). A negative window after a decrease is legal and must be
honoured (send nothing until it climbs back above zero). The connection window
is NOT changed by SETTINGS_INITIAL_WINDOW_SIZE - only by WINDOW_UPDATE on stream
0.
SENDING our response DATA: for each stream, we may send up to
min(connection-send-window, stream-send-window, peer MAX_FRAME_SIZE)
octets at a time; decrement both windows by what we send. When both windows are
positive again (peer WINDOW_UPDATE increments them), resume any stalled stream.
A stalled peer stops granting credit, so we stop producing DATA and the response
waits where it is - in its file, or in memory counted against the response
budget (section 13).
THE WINDOWS ARE NOT A PACE. They are the peer's permission to send, and say
nothing about how much is already waiting in the transport's send queue: a
browser opens 6-15 MiB at a time, and producing a whole window in one go while
the previous one is still on the wire is what made the transport's backlog
ceiling close the connection. DATA is therefore also limited by the transport's
room (OnOutputRoom, section 3.1) and resumed when the transport drains, as well
as when the peer's WINDOW_UPDATE arrives.
RECEIVING peer DATA: decrement our recv-windows by the payload length as data
arrives and replenish IMMEDIATELY, per DATA frame - not at body completion. The
connection credit is returned before the stream is even looked up, so DATA on an
unknown or already-closed stream still gives its credit back (a peer cannot
bleed the connection window dry by writing to dead streams), and the stream
window is re-credited as the body is appended.
Error SCOPE follows the window that overran, which is the part worth getting
right: the CONNECTION recv-window going negative is a connection error
FLOW_CONTROL_ERROR, a STREAM recv-window going negative is a stream error - the
stream is reset and dropped, the connection survives. Likewise a WINDOW_UPDATE
increment of 0 is a connection PROTOCOL_ERROR on stream 0 but a stream error on
any other stream, and an increment that would push a window past 2^31-1 is
FLOW_CONTROL_ERROR at the same two scopes.
--------------------------------------------------------------------------------
11. HTTP/2 SETTINGS (RFC 9113 s6.5)
================================================================================
Parameters we SEND (server preface) and/or ENFORCE on receipt:
$01 HEADER_TABLE_SIZE HPACK dynamic-table size we permit the peer's
encoder to use for OUR decoder; the 4096 default
is kept. A peer's value bounds OUR encoder.
$02 ENABLE_PUSH we SEND 0 (no push). We must reject a peer value
other than 0/1; a client sending 1 to a server is
harmless but we never push regardless.
$03 MAX_CONCURRENT_STREAMS the cap WE impose on the peer's open streams; excess
-> RST_STREAM(REFUSED_STREAM). We advertise 100.
$04 INITIAL_WINDOW_SIZE initial per-stream flow window; >2^31-1 is a
connection error FLOW_CONTROL_ERROR. Peer's value
re-bases our stream SEND windows (s5).
$05 MAX_FRAME_SIZE largest frame WE accept (16384..16777215); we
advertise 16384 and reject larger inbound frames.
Peer's value caps the frames WE send.
$06 MAX_HEADER_LIST_SIZE advisory cap on uncompressed header size we accept.
Unknown setting ids are IGNORED (forward-compat). A SETTINGS frame whose length
is not a multiple of 6 -> connection error FRAME_SIZE_ERROR. A SETTINGS with ACK
set and non-empty payload -> FRAME_SIZE_ERROR. Every non-ACK SETTINGS we receive
is answered with an empty SETTINGS+ACK.
THE SERVER PREFACE ADVERTISES UP TO FIVE of them, and these are the values a
client will see:
ENABLE_PUSH 0 we never push
INITIAL_WINDOW_SIZE 65535 the spec default
MAX_FRAME_SIZE 16384 the spec floor
MAX_CONCURRENT_STREAMS 100 excess -> REFUSED_STREAM (Limits)
MAX_HEADER_LIST_SIZE 64 KiB decoded-list ceiling (Limits)
"UP TO", because the last two are configurable (section 20) and are OMITTED when
their limit is switched off. That is not cosmetic. RFC 9113 s6.5.2 defines an
ABSENT parameter as "no limit", but a SENT MAX_CONCURRENT_STREAMS of 0 tells the
peer it may not open a stream at all - so advertising the raw value would turn
"unbounded" into a total outage while simultaneously disabling the local guard.
Unbounded is expressed by saying nothing.
MAX_HEADER_LIST_SIZE is advertised as a courtesy so a well-behaved peer can trim
its own request instead of losing the connection; it is advisory on the wire, so
the local ceiling in the HPACK decoder is what actually protects us and is
deliberately the same number (section 8). HEADER_TABLE_SIZE is not advertised -
leaving it at its 4096 default is what we want, and a larger table only raises
the expansion factor an attacker gets. On the receive side a peer's
MAX_CONCURRENT_STREAMS is ignored rather than stored, because it caps streams WE
open and we open none.
--------------------------------------------------------------------------------
12. HTTP/2 ERROR HANDLING (RFC 9113 s5.4, s7)
================================================================================
CONNECTION error: GOAWAY(last-stream-id, code), then the connection closes and
no further frames are processed. STREAM error: RST_STREAM(stream-id, code), and
the connection carries on. The narrowest correct scope is always the one chosen
- section 20 explains why that division is a design decision rather than an
accident.
Error codes:
$00 NO_ERROR $01 PROTOCOL_ERROR $02 INTERNAL_ERROR
$03 FLOW_CONTROL_ERROR $04 SETTINGS_TIMEOUT $05 STREAM_CLOSED
$06 FRAME_SIZE_ERROR $07 REFUSED_STREAM $08 CANCEL
$09 COMPRESSION_ERROR $0a CONNECT_ERROR $0b ENHANCE_YOUR_CALM
$0c INADEQUATE_SECURITY $0d HTTP_1_1_REQUIRED
What a peer gets, case by case:
- bad client preface magic -> GOAWAY PROTOCOL_ERROR
- first frame not SETTINGS -> GOAWAY PROTOCOL_ERROR
- frame on stream 0 that needs a stream, or vice versa (e.g. DATA on 0,
SETTINGS or GOAWAY on non-0) -> GOAWAY PROTOCOL_ERROR
- non-CONTINUATION during an open header block -> GOAWAY PROTOCOL_ERROR
- HPACK decode failure -> GOAWAY COMPRESSION_ERROR
- inbound frame length > our MAX_FRAME_SIZE -> GOAWAY FRAME_SIZE_ERROR, always
(no per-type leniency; rejected
before the payload is buffered)
- recv beyond our CONNECTION flow window -> GOAWAY FLOW_CONTROL_ERROR
- recv beyond a STREAM flow window -> RST_STREAM FLOW_CONTROL_ERROR
- header block over 256 KiB, or spanning
more than 128 frames (CONTINUATION flood) -> GOAWAY ENHANCE_YOUR_CALM
- content-length over the body cap, per
stream or per connection (8 MiB each) -> 413 with END_STREAM, then
RST_STREAM NO_ERROR (s8.1),
before any DATA is taken in
- assembled request body over 8 MiB - no
content-length, or one the body passes
in the frame that reaches the cap -> RST_STREAM ENHANCE_YOUR_CALM
- content-length not the length of the
DATA that came (s8.1.1), or not a run
of digits: when the body passes it, or
at END_STREAM -> RST_STREAM PROTOCOL_ERROR
- HEADERS (trailers) on a stream the
server reset while the client was
still sending on it -> decoded and dropped (s5.1);
see section 9
- PRIORITY whose payload is not 5 octets -> RST_STREAM FRAME_SIZE_ERROR and
the stream dropped; on an idle
stream GOAWAY FRAME_SIZE_ERROR;
on a closed one nothing
- WINDOW_UPDATE of 0 on a stream -> RST_STREAM PROTOCOL_ERROR and
the stream dropped; idle: GOAWAY
PROTOCOL_ERROR; closed: nothing
- WINDOW_UPDATE of 0 on stream 0 -> GOAWAY PROTOCOL_ERROR
- PUSH_PROMISE received -> GOAWAY PROTOCOL_ERROR
- GOAWAY shorter than 8 octets -> GOAWAY FRAME_SIZE_ERROR
- negotiated TLS version below 1.2 -> the server preface, then GOAWAY
INADEQUATE_SECURITY (section 6)
- too many concurrent streams -> RST_STREAM REFUSED_STREAM (stream)
- malformed request (pseudo-header rules,
or the field rules of section 13) -> RST_STREAM PROTOCOL_ERROR (stream)
and no response (section 13)
- a second HEADERS without END_STREAM, or
trailers that break the field rules -> RST_STREAM PROTOCOL_ERROR
- a handler raises -> 500 response on that stream only,
exactly as on HTTP/1.1
- a response field the handler set that
HTTP/2 cannot carry (section 13.2) -> a bare 500 on that stream only
--------------------------------------------------------------------------------
13. REQUEST / RESPONSE MAPPING INTO THE SHARED CORE
================================================================================
13.1 THE COMMON REQUEST AND RESPONSE
--------------------------------------------------------------------------------
Handlers receive the same iHttpRequest/iHttpResponse types on all three wires:
Fact HTTP/1.1 HTTP/2 HTTP/3
-------------------- ---------------- ---------------- ----------------
Version HTTP/1.0 or 1.1 HTTP/2 HTTP/3
NegotiatedProtocol http/1.1 (*) h2 h3
Secure True for these HTTPS plugin paths
Method/Path/Query preserved HTTP octets, split without URI normalization
Headers shared ordered tHttpHeaders; repeated fields retained
Body at dispatch complete bounded TStream, owned by the request
Connection/Session facts and state for this connection (section 2.1)
(*) HTTP/1.1's value is the actual negotiated token. When a configured TCP
fallback serves a client without ALPN, NegotiatedProtocol can be empty. The
HTTP/2 and HTTP/3 paths require their respective negotiated tokens.
HTTP/2 and HTTP/3 pseudo-fields supply method, raw path and authority; their
adapters synthesize the common Host view. iHttpRequestOrigin separately
reports the scheme and authority the wire carried, on all three wires. Host
and SNI remain routing inputs, not client authentication. Binary responses
carry :status, lowercase field names, and no reason phrase or Connection
transfer semantics.
The handler still sets the same status, headers and content source.
HEAD and bodyless status handling are enforced by the wire adapter. Body length
and hop-by-hop filtering are not instructions to handcraft protocol framing.
HTTP/3 validates lowercase token names, forbidden controls and leading/trailing
field whitespace. Like HTTP/2 it refuses leading/trailing SP/HT rather than
applying HTTP/1.1's surrounding-whitespace trimming.
13.2 HTTP/2 MAPPING AND RESPONSE MEMORY
--------------------------------------------------------------------------------
This is what a handler sees, and it is deliberately the same shape a handler
sees on HTTP/1.1 - which is the whole point of the shared core.
THE REQUEST, once the header block and the body are both complete:
Method from :method
Path / Query from :path, split at the first '?'
Version 'HTTP/2'
Secure True
NegotiatedProtocol 'h2'
RemoteAddress the peer address of the TLS connection
Headers the regular fields, with :authority turned into Host.
Pseudo-headers do not appear as ordinary fields.
Body the concatenated DATA payloads
Fields are validated on the way in, and a request that fails is malformed (RFC
9113 s8.2.1) - RST_STREAM PROTOCOL_ERROR, a handler never sees it. Every field,
in the header section or the trailers, pseudo-header fields included, is held to
the "minimal validation" of s8.2.1: a name with no octet 0x00-0x20, 0x41-0x5a
(UPPERCASE) or 0x7f-0xff and no colon but a pseudo-header field's first; a value
with no NUL, CR or LF - the header-splitting guard - and no SP or HTAB at its
start or end. So is an empty name (RFC 9110 s5.1 makes a name a token, of one
character at least), and an empty :path. THE ANSWER IS THE RESET ALONE. s8.1.1
requires it ("MUST be treated as a stream error (Section 5.4.2) of type
PROTOCOL_ERROR") and allows a response before it ("For malformed requests, a
server MAY send an HTTP response prior to closing or resetting the stream.");
s8.2.1 asks for a 400: "When a request message violates one of these
requirements, an implementation SHOULD generate a 400 (Bad Request) status code
(see Section 15.5.1 of [HTTP]), unless a more suitable status code is defined or
the status code cannot be sent (e.g., because the error occurs in a trailer
field)." The engine sends no response to any malformed request - these, the
pseudo-header rules, connection-specific fields, a content-length that is not
the length - so for a field in the request's header section it does not do what
that SHOULD asks (for one in a trailer section the sentence itself excuses it),
and a client sees RST_STREAM(PROTOCOL_ERROR) with no status to say why. THE TWO
WIRES DIFFER on a value with a space or a tab at its start or end: HTTP/1.1
trims it (the field grammar allows the whitespace there), HTTP/2 holds it
malformed. A client that sends such a value as its application set it - Go's
x/net HTTP/2 client does; it refuses only control characters, DEL and octets
below 0x20 but HTAB, so SP and HTAB pass - is served over HTTP/1.1 and reset
over HTTP/2. Apache's mod_http2 turns nghttp2's version of this check off on its
server, to strip the whitespace as its HTTP/1.1 parser does, and curl turns it
off on its client; this engine keeps to the MUSTs of s8.2.1. The full grammar of
RFC 9110 (a name of tchar only, a value of VCHAR, SP, HTAB and obs-text) is a
SHOULD and is not checked beyond that.
THE RESPONSE is built from the same iHttpResponse the handler filled in, in this
order: :status first, then the handler's own headers, then content-length,
trailer (when trailers follow), content-type and date. The engine adds no
Server field; one the handler sets goes out like any other field. These rules
govern what survives:
- :status is the handler's status when it lies in 100..599 (RFC 9110 s15).
One outside that range goes out as 500, with the handler's fields and body.
A 1xx the handler chose goes out as a 500 without a body: an application
response is final.
- Pseudo-headers and connection-specific fields (Connection, Keep-Alive,
Proxy-Connection, Transfer-Encoding, Upgrade, and TE, which RFC 9113 s8.2.2
allows in a request only) are DROPPED - they are illegal in an HTTP/2
response, and a handler that sets one on both wires gets it honoured on 1.1
and removed here.
- content-length is OURS. A handler-supplied one is discarded and the real
body size sent instead, HEAD included, where the length is reported
truthfully while no DATA follows. 204 and 304 carry none, 205 carries 0.
For 304, RFC 9110 s8.6 allows only "the decimal number of octets that
would have been sent in the content of a 200 (OK) response to the same
request", which the engine cannot know.
- date is OURS too. A handler-supplied one is discarded, so exactly one date
field goes out (RFC 9110 s5.3).
- content-type defaults to application/octet-stream only when there is a body
and the handler set none.
- Header names are lowercased by HPACK; do not build a status line or
HTTP/1-style Connection semantics by hand.
A FIELD THE WIRE CANNOT CARRY MAKES THE RESPONSE A BARE 500. HPACK carries one
octet per character and lowercases names, so a field that breaks s8.2.1 would
reach the wire as it is, or changed. Every handler field the engine would send
is therefore checked before anything is encoded: the name must be a token (RFC
9110 s5.6.2; either case), and the value may hold no control character other
than HTAB, no DEL, no SP or HTAB at either end, and no character above U+00FF.
U+0080..U+00FF (obs-text) go out as those octets, unchanged. One field that
fails replaces the response with :status 500, content-length 0 and date: no
field, body or trailer of the handler's goes out. HTTP/1.1 checks every field
the handler set, without the U+00FF limit (section 4); HTTP/3 resets the request
instead (section 14).
The encoded header block goes out as HEADERS, continued into CONTINUATION frames
if it exceeds the peer's maximum frame size, and the body follows as
flow-controlled DATA with END_STREAM on the last frame.
ONE MEMORY CONSEQUENCE WORTH KNOWING: the response object is released when the
handler returns, so its body is TAKEN by the stream - the object holding it
moves, nothing is copied - and sent from there under flow control. A body that
is a file costs a handle and one frame at a time. A body that is memory
(SetContent, SetContentText, or a stream handed over with aOwns = False, which
had to be copied) stays whole until its last frame is out, and a stalled peer
can keep it there for as long as it keeps its window shut. Those memory-held
octets are counted: per connection against Limits.ConnResponseBytes (32 MiB) and
across the server against Limits.TotalResponseBytes (256 MiB). While either is
reached, a NEW stream is refused with REFUSED_STREAM - which RFC 9113 s8.7 lets
a client retry - and the responses already owed carry on. The question is asked
when a stream opens, because that is the last point at which saying no costs
nothing; a response already dispatched has to be held either way.
TsmHTTPSv2.ResponseBytesHeld and ResponseBytesHighWater are the measurements to
size the two from.
--------------------------------------------------------------------------------
14. THE HTTP/3 WIRE SESSION AND SERVER COMPONENT
================================================================================
Each HTTP/3 request occupies one client-initiated QUIC bidirectional stream.
Stream IDs are UInt64 and zero is a valid request ID. HEADERS carries QPACK
fields, DATA carries body bytes, and QUIC FIN ends a direction. Request trailers
are validated and retained through the optional iHttpRequestTrailers companion
interface, separate from initial Headers (section 2.2).
TsmHTTPSv3 is declared in StreamSec.Mobile.HTTPSv3. Assign Server to a
TsmAsyncQUICServer before activation, then assign OnRequest or register routes
with AddHandler, AddEvent, AddFile or AddFiles. Router and SessionProvider use
the existing StreamSec.Http.Server interfaces and may be shared with HTTP/1.1
and HTTP/2 components. The same handler receives Version = HTTP/3,
NegotiatedProtocol = h3 and Secure = True. Connection uses the existing
certificate/security presentation adapter; TransportInfo retains the optional
existing iTLSConnectionInfo view. Association changes and component settings
require an inactive host. DFM forward references and component declaration order
are supported.
Handlers run inline on the QUIC listener's connection worker threads
(TsmAsyncQUICServer.WorkerThreadCount): one at a time for each connection,
concurrently across connections, and a handler occupies its worker until it
returns. Requests and responses have the existing callback lifetime,
complete request bodies and owned-stream response behavior. Request trailers
are published only when a valid FIN completes the request, matching the common
handler contract. Paths and field values
preserve HTTP octets without URI normalization. SNI and :authority/Host remain
application routing/authorization inputs. A handler exception produces an empty
500 response; invalid response fields or a short response source reset that
request. Responses preserve repeated fields, compute Content-Length and Date,
remove hop-by-hop fields and honor HEAD/204/205/304 body rules. Owned
file/stream responses are read in bounded pieces while QUIC permits queueing.
The shared EarlyDataPolicy gate handles early provenance and Early-Data: 1
before a session provider or handler runs. EnableEarlyData defaults to False.
Opt-in QUIC acceptance also requires TLS replay approval and stable protocol
context. Application delivery still follows authenticated handshake completion;
enabling transport early data does not move callbacks before authentication.
Streaming early requests remain refused 425/no-store.
Limits and their different semantics are listed in section 20.2. The shared
request mapping is in section 13.1; TCP and QUIC component setup is in section
16.
The engine opens one local control stream and the two QPACK streams, advertises
zero dynamic capacity/blocked streams unless dynamic QPACK is configured
(section 23.5), and uses the shared QPACK/Huffman codecs. It validates
critical-stream uniqueness/lifetime, SETTINGS ordering,
message fields/content length and request/control frame placement. SETTINGS is
first on the control stream and has no HTTP/2-style acknowledgement. Malformed
messages reset a request; connection-level framing/control/QPACK errors close
with their HTTP/3 application error. Unknown extensions are skipped with bounded
metadata/work. Response pumping uses bounded fair stream turns. Graceful drain
sends GOAWAY, refuses unprocessed requests at/above its boundary, retains
already processed responses, and reports application drain completion only after
response FIN and GOAWAY bytes have entered QUIC. The host separately waits for
pending QUIC ranges/FIN acknowledgement and applies its shutdown deadline.
This component supports opt-in dynamic QPACK and server push (sections 23.5
and 23.6). CONNECT tunnels remain outside its API. Shared request-body
streaming is described in section 24. Explicit
buffered QUIC 0-RTT uses the policy in section 2.1 and the client admission
boundary in section 23.4.
--------------------------------------------------------------------------------
15. DELPHI PUBLIC SURFACE
================================================================================
The unit interfaces are the canonical declarations, including GUIDs, overloads
and defaults. This section lists the application entry points rather than
duplicating private parser, stream-table and compression-state layouts.
15.1 THE SHARED CORE (StreamSec.Http.Server)
--------------------------------------------------------------------------------
iHttpRequest Method, Path, Query, Version, Headers, Body, Cookies,
Session, Connection and transport presentation facts
iHttpRequestTrailers optional companion; request-owned Trailers: tHttpHeaders
iHttpResponse status, repeated headers and one owned content source
iHttpResponseTrailers
optional companion; copied SetTrailers and read-only
response-owned Trailers: tHttpHeaders (section 2.3)
iHttpRouter exact routes; optional iHttpPrefixRouter for mounts
iHttpRequestHandler HandleRequest(const aRequest: iHttpRequest;
const aResponse: iHttpResponse)
tHttpRequestEvent Sender first, followed by those two const interfaces
iHttpSessionProvider.AcquireSession
selects a request's session from its connection session
NewHttpRouter returns iHttpRouter; supports iHttpPrefixRouter
The router and all three protocol components offer these registration methods:
procedure AddHandler(const aPath: string;
const aHandler: iHttpRequestHandler);
procedure AddEvent(const aPath: string; aEvent: tHttpRequestEvent);
procedure AddFile(const aReqPath, aPhysicalFile: string);
procedure AddFiles(const aMap: array of THttpFileMap);
Response operations include SetStatus, SetHeader, SetContentType, SetContent,
SetContentText, SetContentStream, SendFile and SendFileRange. Headers.Add
preserves repeated fields such as Set-Cookie. Owned streams are transferred to
the response; borrowed streams are copied as specified in section 3. Requests
and response interfaces have the handler lifetime described in section 2.
iHttpRequestOrigin is an optional companion for actual Scheme/Authority facts.
iHttpAltSvcSource returns a detached iHttpAltSvcEndpoint; response workers use
the endpoint rather than call through a palette component (section 16.3).
15.2 TCP PROTOCOL COMPONENTS AND HTTP/2 ENGINE
--------------------------------------------------------------------------------
StreamSec.Mobile.HTTPS declares TsmCustomHTTPSProtocol, TsmHTTPSv1dot1 and
TsmHTTPSv2. Their shared application surface includes Router, SessionProvider,
OnRequest and the registration helpers above. Server is TsmAsyncTLSServer;
AppProtocol returns iAppProtocol. The concrete Limits types are tHTTP11Limits
and tHTTP2Limits. AlpnToken, AlpnPriority, IsFallback and AltSvc are TCP
plugin policies; they must not be presumed to exist on TsmHTTPSv3.
EarlyDataPolicy is shared (EARLY DATA in section 2.1): TsmHTTPSv3 publishes it
too, next to EnableEarlyData (sections 14 and 23.4).
OnBodyRefused and the BodyBytesHeld/BodyBytesHighWater observations belong to
these TCP components. TsmHTTPSv2 also exposes response-memory observations. They
are not the QUIC plugin's event/counter contract. See section 20.
StreamSec.Http.Http2Frames supplies the frame reader, frame types, settings and
error constants. StreamSec.Http.Http2Conn supplies tHttp2Conn and its callbacks
for complete requests, output, output room and body accounting. Receive parses
input; ResumeOutput resumes response production after transport room changes.
Their detailed state machine is described in sections 6-13.
The TLS 1.2 floor of section 6 is applied by TsmHTTPSv2's session and by the
high-level client, not inside the engines, which see no TLS layer. An
application that drives tHttp2Conn or tHttp2ClientConn itself asks
Http2TlsBelowMinimum(major, minor) from StreamSec.Http.Http2Frames once the
handshake is done and, when it answers True, calls the engine's
RefuseConnection with cErrInadequateSecurity right after Opened. RFC 9113
s5.4.1 then requires the TCP connection to be closed. tHttp2Conn asks for that
through OnClose, as on any connection error; tHttp2ClientConn only writes the
GOAWAY, so a program that drives it closes its transport itself once
ErrorGoAwaySent is True: after RefuseConnection, and after every connection
error the engine finds in the peer's frames (section 23.1). ErrorGoAwaySent
stays False when the connection ended by the peer's GOAWAY or by Closed.
StreamSec.Http.Hpack supplies iHpackEncoder/iHpackDecoder and their factories.
Reach iHpackDecoderLimits to set the decoded header-list bound; the
implementation enforces the size of the decoded list while decompressing
(section 8). HPACK's dynamic table is per HTTP/2 connection. HTTP/3 uses QPACK,
not these interfaces.
15.3 QUIC SERVER PLUGIN AND HTTP/3 ENGINES
--------------------------------------------------------------------------------
StreamSec.Mobile.HTTPSv3 declares TsmHTTPSv3 and its persistent tHTTP3Limits.
Its application surface is intentionally familiar, but its transport types
differ:
Server TsmAsyncQUICServer
AppProtocol function returning iQuicAppProtocol
Router iHttpRouter, read/write at runtime
SessionProvider iHttpSessionProvider, read/write at runtime
OnRequest tHttpRequestEvent, published fallback event
Limits tHTTP3Limits, published and assignable
EnableEarlyData Boolean, published, default False
EarlyDataPolicy tEarlyDataPolicy, published, default edpRefuse
BodyBytesHeld Int64, read-only aggregate request-memory charge
ResponseBytesHeld Int64, read-only aggregate response-memory charge
AltSvcEndpoint function returning iHttpAltSvcEndpoint
Server, Limits and OnRequest follow component streaming/lifetime conventions.
Configure associations, router, provider and limits while the host is inactive.
Limits.SendWindowBytes sets the retained QUIC send window (section 20.2),
independently of the HTTP framing queue. AppProtocol registers fixed token h3
with the QUIC registry. No TLS registry
fallback or TCP ALPN priority can select this component.
StreamSec.Http.Http3Server declares the transport-free tHttp3ServerConn,
iHttp3ServerTransport, tHttp3ServerLimits and Init/ValidateHttp3ServerLimits.
StreamSec.Http.Http3Client declares tHttp3ClientConn, iHttp3ClientTransport,
iHttp3ClientObserver and tHttp3ClientLimits. StreamSec.Http.Http3QuicClient
declares tHttp3QuicClient, the adapter borrowing a caller-owned tQuicClient. See
sections 14, 20.2 and 23 for their distinct server/client contracts.
HTTP/3 fields are tQpackFields from StreamSec.Http.Qpack. Name and Value are
RawByteString HTTP octets; NeverIndex is a field flag. Managed TBytes buffers
are retained as shared immutable arrays where the API permits. Their lifetime is
separate from explicit receive-credit release and transport acknowledgement.
15.4 THE REST COMPONENTS
--------------------------------------------------------------------------------
StreamSec.Http.RestServer declares TsmCustomRESTServer/TsmRESTServer,
iRestRequest/iRestResponse/iRestHandler, route helpers and idempotency
interfaces. The published Protocol type remains TsmCustomHTTPSProtocol. MountOn
accepts an iHttpRouter directly, including a router shared with HTTP/3 (section
22). The REST client's owned/reference TLS engine is described in section 22.9.
--------------------------------------------------------------------------------
16. WIRING THE TCP AND QUIC LISTENERS
================================================================================
16.1 THE TCP ALPN COMPONENTS
--------------------------------------------------------------------------------
FROM CODE. The two TCP protocols share one TLS server:
lRouter := NewHttpRouter;
lRouter.AddFiles([HttpFile('/','C:\www\index.html'),
HttpFile('/style.css','C:\www\style.css')]);
lRouter.AddHandler('/api/time', myTimeHandler); { interface }
lHttp11 := TsmHTTPSv1dot1.Create(Self);
lHttp11.Router := lRouter; { share across protocols }
lHttp11.OnRequest := Form1.HttpRequest; { fallback }
lHttp2 := TsmHTTPSv2.Create(Self);
lHttp2.Router := lRouter; { the SAME router }
srv.Protocols.AddProtocol(lHttp2.AppProtocol); { prefer h2 on TCP }
srv.Protocols.AddProtocol(lHttp11.AppProtocol); { srv: TsmAsyncTLSServer }
ALPN in the TLS handshake selects the session (the registry's
AdvertisedProtocols advertise 'http/1.1' and 'h2'); each session parses its own
wire and calls the one shared router. Certificate selection can also key on the
negotiated ALPN.
ORDER IS PREFERENCE, AND THE SERVER'S ORDER IS THE ONE THAT COUNTS. Selection
walks OUR list outermost and takes the first token the client also offered
(TCustomTLS_ContentLayer.PickProtocol), so the client's own ordering is ignored
beyond membership - RFC 7301 s3.2. In the code above that order is simply the
order of the AddProtocol calls, and it reads top to bottom: h2 registered first
means h2 wins against a browser offering both. Swap the two lines and every such
client quietly gets HTTP/1.1 - no diagnostic, because both outcomes are valid
negotiations.
FROM THE OBJECT INSPECTOR THAT ORDER IS INVISIBLE: a component registers itself
from Loaded, so it is DFM declaration order. Set AlpnPriority instead. HIGHER IS
PREFERRED, insertion is sorted, and each component therefore lands in its right
slot whenever it happens to load - the reverse declaration order yields the same
advertised list. Typical use is h2 = 10 against http/1.1 = 0. LEAVE EVERY
COMPONENT AT 0 AND NOTHING CHANGES: equal priorities keep insertion order - the
same order the AddProtocol calls produce. AlpnPriority orders the REGISTRY
segment only - engine-seeded tokens such as 'acme-tls/1' are merged ahead of all
of them and cannot be demoted here, which is correct: a challenge that cannot be
negotiated is a challenge that fails.
FROM THE OBJECT INSPECTOR. The two AddProtocol calls are not the only way to
make that association, and at design time they are not the natural one. Both
components publish Server: TsmAsyncTLSServer - assigning it registers the ALPN
token with that server's registry, clearing it unregisters - so dropping a
TsmAsyncTLSServer and the two plugins on a form and setting Server on each is
equivalent to the code above, minus the AddProtocol calls. The declared property
type is what narrows the Object Inspector drop-down to eligible servers, so no
property editor is involved.
EITHER PATH, AND DOING BOTH IS HARMLESS. Server := srv and
Protocols.AddProtocol(x.AppProtocol) do the same thing; registering an instance
that is already registered RE-SEATS it rather than adding a second entry, so the
token is advertised once whichever way (or both ways) you get there. Use the
property when the components live on a form, and the explicit call for protocols
that are not components at all (the Snif plugin in KAPA.txt, for instance). One
difference is worth knowing: the explicit call cannot see the component's
AlpnPriority, so it seats at the default until a later Server := srv re-seats
it.
Two states the setter must NOT act in, and they are the whole reason the binding
is split between SetServer and Loaded:
csLoading the referenced server may not exist yet and DFM restore order is
not ours to rely on, so Loaded does the binding after the whole
form has materialised.
csDesigning registering a live ALPN token on a design surface would give the
designer real runtime state; skipped in both paths.
REGISTRATION IS KEYED BY THE INSTANCE, NOT BY THE TOKEN. Unbinding removes the
entry this component registered, so two plugins sharing a token cannot evict one
another - a token lookup would take the first match, which need not be yours.
That is what makes the teardown paths safe to state plainly:
Destroy unregisters, so a freed plugin never leaves an entry
handing out sessions from a dead component.
Notification opRemove from a server being DESTROYED (csDestroying)
(opRemove) only drops the reference - its registry is already gone.
From a server that is still ALIVE (RemoveComponent,
reparenting) it also unregisters, or the adapter would
be stranded in a live registry that the plugin no longer
believes it is in.
AND WHAT THE COMPONENT CANNOT REACH IS MADE INERT. Server is ONE association.
The iAppProtocol adapter is refcounted, so it also survives in any registry the
component was never told about (a manual AddProtocol with a second server), in a
connection that already resolved it, and in any variable the application kept.
Destroy therefore DETACHES it: the back-pointer is dropped and the last token
snapshotted, so a leftover entry still advertises its token - one that suddenly
answered '' would corrupt the advertised list - but declines to mint sessions,
and the connection is closed exactly as an unresolved ALPN is. A forgotten
second registration then costs a refused connection rather than a call into
freed memory. It is still yours to clean up:
Protocols.RemoveProtocol(x.AppProtocol) before freeing the component, or the
port advertises a token nothing can serve.
TWO PROPERTIES REFUSE RATHER THAN DIVERGE. AlpnPriority raises ETLSAsyncServer
if the server is Active, because the registry is read per connection during
handshakes; storing a value that could not be applied would leave the property
reporting one order and the wire showing another. TsnipTLSServer.AlpnToken
raises once AppProtocol has been handed out, because the adapter reads it live,
which makes it a registry key from that moment. Both are settable at design time
and while streaming - neither has a running server - and re-assigning the
current value is always allowed.
The TLS host and its two HTTP components are registered on the palette page
'StreamSec Mobile' by StreamSec.Mobile.AsyncTLSServerReg. The QUIC host and its
HTTP/3 plugin are registered by StreamSec.Mobile.AsyncQUICServerReg on that same
page. Their Server property types select the appropriate host. Platform metadata
does not by itself establish native backend acceptance; see section 19.
16.2 ONE ROUTER, ONE TCP LISTENER AND ONE QUIC LISTENER
--------------------------------------------------------------------------------
Create/configure both hosts before activation. The example assumes their
existing TLS engines and certificate configuration have already been supplied:
lRouter := NewHttpRouter;
lRouter.AddHandler('/api/time', myTimeHandler);
lHttp11.Router := lRouter;
lHttp2.Router := lRouter;
lHttp3.Router := lRouter;
lHttp2.AlpnPriority := 10; { prefer h2 on the TCP listener }
lHttp11.Server := lTlsServer; { TsmAsyncTLSServer, TCP }
lHttp2.Server := lTlsServer; { the same host }
lHttp3.Server := lQuicServer; { TsmAsyncQUICServer, UDP }
lHttp11.SessionProvider := lProvider;
lHttp2.SessionProvider := lProvider;
lHttp3.SessionProvider := lProvider;
Register routes once. Router resolution runs before each component's own
OnRequest fallback, so sharing a router does not share those event properties.
Assign the same event to each if the fallback behavior should also match. Shared
handlers/providers must allow calls from different connections.
The TCP and UDP listeners may use the same numerical port, normally 443. They
remain independent listeners with separate activation, connection admission,
drain and failure state. TsmHTTPSv3.Server registers its iQuicAppProtocol with
the QUIC host; it never enters TsmAsyncTLSServer.Protocols. ALPN h3 is
negotiated inside QUIC's record-free TLS 1.3 handshake, not through a TCP
fallback.
Configure the QUIC host and plugin while inactive. Loaded/FreeNotification and
activation-time binding handle component declaration order. Removing a live
plugin first shuts down its host so sessions cannot call a freed component.
Explicit interface registration remains available for non-component QUIC
protocols. See QUICServer.txt for TLS engine ownership, host budgets, datagram
backends, admission, timers and graceful shutdown. Existing TLS cryptographic
provider imports and forced linking remain intentional for both transport paths.
The next subsection connects listener availability to discovery. A shared router
alone does not advertise an endpoint or authorize a second origin.
16.3 AVAILABILITY-AWARE ALT-SVC ADVERTISEMENT
--------------------------------------------------------------------------------
One TsmAsyncTLSServer hosts both TsmHTTPSv1dot1 and TsmHTTPSv2. Assign both
Server properties to that same TCP listener. A separate TsmAsyncQUICServer hosts
TsmHTTPSv3 on UDP; the TCP and UDP listeners may use the same port. The three
plugins can share one Router, the same registered handlers and a
SessionProvider. Add routes once, then assign the Router interfaces to the other
plugins. Per-connection sessions and request/response objects retain their
existing lifetimes; shared handlers/providers must support concurrent calls from
different connections.
TsmHTTPSv1dot1 and TsmHTTPSv2 inherit the AltSvc persistent settings:
Http11.AltSvc.Source := Http3;
Http11.AltSvc.Origin := 'https://www.example.com';
Http11.AltSvc.Enabled := True;
Http2.AltSvc.Assign(Http11.AltSvc);
Source is a component implementing iHttpAltSvcSource; TsmHTTPSv3 is the first
implementation. HTTP workers retain its iHttpAltSvcEndpoint rather than call
through the component. Existing TCP components do not import QUIC implementation
units. Configure AltSvc with the TCP listener inactive. Enabled defaults to
False, PublicPort to 0 (actual bound UDP port), and MaxAge to 60 seconds
(0..86400). PublicPort can override a public/NAT mapping explicitly.
Origin is one HTTPS origin, without a path, userinfo, query or fragment. Use
ASCII DNS A-labels for IDNs, strict dotted IPv4 or bracketed IPv6. DNS case and
default port 443 normalize; a trailing DNS root dot remains a distinct origin.
Ambiguous numeric-host forms and scoped IPv6 are refused. Only secure requests
for that origin qualify. Actual HTTP/2 :scheme/:authority are preserved in the
optional iHttpRequestOrigin companion interface; duplicate/conflicting Host,
non-HTTPS schemes, malformed authorities and HTTP/1.1 absolute-form targets
suppress automatic advertisement. Existing request-interface GUIDs and legacy
handler acceptance are unchanged; unknown origin metadata fails closed.
After dispatch, a complete enabled mapping adds h3=":<port>"; ma=<seconds> when
its exact registered h3 plugin is ready, otherwise clear. This includes normal
404/425 and handler-error responses. Readiness starts only after successful QUIC
startup and ends before drain, endpoint closure or component destruction. Manual
Alt-Svc fields always take precedence, including repeated/empty fields. Other
origins, incomplete/disabled settings and plaintext redirect paths add nothing.
No automatic cross-host alternative or HTTP/2 ALTSVC frame is emitted.
Enabling a mapping asserts deployment reachability and origin authorization;
local binding cannot verify public routing or certificate suitability. No state
lock spans application dispatch or network output. An advertisement sampled
before a concurrent stop can already be queued/sent; later responses sample
fresh state. Clients that miss clear retain cached mappings until MaxAge.
Source-removal notification keeps a detached unavailable endpoint for clear;
explicit reassignment/nil while inactive replaces the configuration. See
QUICServer.txt for the shared-listener setup and withdrawal sequence.
--------------------------------------------------------------------------------
17. CONCURRENCY AND HANDLER EXECUTION
================================================================================
Each connection's wire state is serialized. The TCP reactor serializes its
Opened/DataReceived/Closed callbacks and transport operations with the
connection gate; tHttp11Session and tHttp2Conn therefore process one connection
at a time. The QUIC host independently serializes a connection's stream,
writable, timer and lifecycle work. Standalone HTTP/3 engine/adapter calls must
also be serialized and must not be reentered from an observer callback.
Ordinary interface/event/static handlers are synchronous on all three server
paths. A slow callback stalls its connection until it returns. The opt-in
iHttpStreamingRequestHandler has a separate contract: its quick admission
callback enqueues a detached exchange for an application worker, which reads
the body and submits a sealed response (section 24). Different admitted jobs
can run concurrently even on one H2/H3 connection; live session/connection state
remains confined to admission. There is no library worker pool.
Different connections can execute concurrently, including connections on the TCP
and QUIC hosts sharing a router. Shared handlers, event targets and session
providers must support that concurrency. Register/replace routes before listener
activation, or serialize router mutation yourself; the shared router does not
lock its route dictionary. Configure the QUIC component while inactive.
Ordinary request/response objects have the callback lifetime in section 2. Do
not retain them for deferred work or free their internal body stream. Only the
new immutable head/exchange and its prepared response have the extended worker
lifetime in section 24. QUIC callbacks run on the listener's connection worker
threads, never on its reactor or timer thread; consecutive callbacks of one
connection can run on different workers, so no thread identity is promised.
During deactivation the last Closed and OnConnectionClosed calls can run on the
thread setting Active := False. Do not activate/deactivate hosts or destroy
their components from those callbacks. Host teardown waits for callbacks to
return.
Whatever the wire, a request remains untrusted application input. Transport
security authenticates the configured peer context; it does not authorize a
path, Host/SNI value or action. The wire engines enforce their own bounds and
the router maps only registered routes/files (sections 2, 3 and 20).
--------------------------------------------------------------------------------
18. IMPLEMENTED SCOPE AND EXTENSIONS
================================================================================
The common application layer implements complete bounded requests, opt-in
server request streaming, interface/event/static-file handlers, routing and
prefix mounts, per-connection sessions with optional shared providers, and
owned-source response streaming.
The wire-specific server scope is:
Wire Implemented Outside the current API
--------- ---------------------------------- -----------------------------
HTTP/1.1 TLS, keep-alive, ordered pipeline, h2c/Upgrade, CONNECT tunnels,
chunked input/output, HEAD, trailers
HTTP/2 h2 ALPN, frames, HPACK, streams, server push, priority tree,
windows, SETTINGS/ACK, GOAWAY, h2c, CONNECT tunnels,
RST_STREAM, bounded response pump graceful GOAWAY drain,
acting on a received GOAWAY
HTTP/3 QUIC h3, static/dynamic QPACK, CONNECT tunnels
bidi requests, critical uni
streams, SETTINGS, GOAWAY,
FIN/reset/stop, buffered 0-RTT,
opt-in bounded server push
All three wires refuse a streaming request body that arrives as early data
(425 Too Early, sections 2.1 and 24.3).
HTTP/1.1 accepts strict chunked request framing and refuses ambiguous or
unsupported transfer coding before pipeline reuse (section 4). All three server
engines expose validated received request trailers through the optional shared
companion interface (section 2.2). Clients expose separate response trailers
only after successful completion (section 23.1). Shared handlers generate
response trailers (section 2.3), and trailer-enabled uploads generate request
trailers (section 23.1.1); forbidden fields are refused.
Shared response-header policy, traversal-safe directory serving and per-method
routes remain separate extensions. Worker completion uses only the streaming
exchange described in section 24; old handler interfaces are unchanged. A wire
protocol supporting a feature does not mean this component exposes its API.
Applications can already set suitable response security headers themselves.
The high-level HTTPS client supplies opt-in h3 discovery and BeginUpload for
known- or unknown-length bodies across all three wires (section 23.1). The
HTTP/1.1 server decodes chunked requests for the complete-body handler model
or the opt-in bounded server exchange (section 24). The client's HTTP/3
transport configures receive/send/range
admission and late-tail cancellation. The lower-level HTTP/3 engines also
permit incremental production (section 23.3); their owners supply the
transport resource policy. Final admission remains distinct from transport
delivery/acknowledgement.
--------------------------------------------------------------------------------
19. STATUS AND INTEROPERABILITY
================================================================================
The implemented server and client surfaces are described in this manual; future
extensions are explicitly listed in section 18. Acceptance is per target and
scenario, by area as below. Historical test counts or one successful handshake
are not acceptance for every backend.
Area What was accepted
----------------------- -----------------------------------------------------
Shared core/H1/H2 the shared core over HTTP/1.1 and HTTP/2, connection
info and large responses on actual TLS connections,
and the async TLS reactor beneath them
QPACK/H3 frames/client QPACK, the HTTP/3 frames and the HTTP/3 client
QUIC server/H3 plugin TsmAsyncQUICServer with the TsmHTTPSv3 plugin
Shared handlers/Alt-Svc one router and handler set behind H1, H2 and H3,
with availability-aware Alt-Svc advertisement
High-level h3 discovery opt-in h3 discovery in the high-level HTTPS client
Incremental uploads bounded incremental HTTP/3 uploads
Received trailers validated received trailers
Selected regressions re-run as named rows with recorded floors
Transport-free suites cover parsers, framing, QPACK/HPACK bounds, stream state,
memory budgets and positive controls as well as refusals. Native suites exercise
actual TLS/QUIC connections and independent peers: OpenSSL and native HTTP/2
clients for the TCP paths, and aioquic/pylsqpack for QUIC/HTTP/3.
Shared-listener tests prove the same router/handlers can serve H1, H2 and H3.
The upload fixture checks exact large-body patterns/digests, flow-credit
recovery, simultaneous progress and early responses/STOP/cancellation, with
explicit producer headroom.
The current H3 target matrices cover Delphi XE3 through 13 Win32/Win64 and
genuine Delphi 13 Linux64. FPC 3.3.1 qualification includes transport-free
engines, record-free TLS 1.3 and the QUIC packet/TLS bridge on native Linux64
and big-endian MIPS/o32 under QEMU in WSL. Each acceptance holds for the
compiler, profile and backend it executed, within its limits. Full public
FPC endpoint qualification remains incomplete; separate backend and runtime
limitations remain.
The FPC build conditionally excludes legacy DES imports and dependent DES
code paths. DES/3DES is not required by TLS 1.3 or QUIC; FPC stDES support for
legacy encrypted files remains a separate backlog item. Intentional linking
of the remaining TLS providers is preserved. QUIC 0-RTT application acceptance
is explicit and disabled by default (section 23.4).
The HTTP/1.1/HTTP/2 native connection-info and large-response drivers retain
their own scope. Newer live h2/Alt-Svc tests do not retroactively prove every
field of an older TLS fixture. HTTP/3 protocol/limit details are in sections 14
and 20.
--------------------------------------------------------------------------------
20. LIMITS, RESOURCE BUDGETS AND HOSTILE INPUT
================================================================================
20.1 HTTP/1.1 AND HTTP/2 LIMITS
--------------------------------------------------------------------------------
This subsection lists the HTTP/1.1 and HTTP/2 limits and refusal policies. None
of these lives in the shared core: the core buffers whatever it is handed, so a
new wire session inherits NO protection and must bring its own row to this
table.
THE TCP COMPONENT LIMITS are configurable through their published sub-object:
TsmHTTPSv1dot1.Limits : tHTTP11Limits
TsmHTTPSv2.Limits : tHTTP2Limits (both descend tCustomHTTPLimits)
HeaderBytes 64 KiB 1.1 request head; independently,
aggregate chunk metadata
HeaderTimeoutMSec 10000 both absolute header/framing stage
RequestTimeoutMSec 30000 both absolute buffered body/trailers
BodyBytes 8 MiB both one request's assembled body
ConnBodyBytes 8 MiB h2 bodies summed over one connection
TotalBodyBytes 256 MiB both bodies summed over the SERVER
ConnResponseBytes 32 MiB h2 memory-held RESPONSES on one
connection; new streams refused
TotalResponseBytes 256 MiB h2 the same over the SERVER
MaxConcurrentStreams 100 h2 peer-opened streams at once
HeaderBlockBytes 256 KiB h2 assembled COMPRESSED header block
MaxContinuationFrames 128 h2 frames one header block may span
HeaderListBytes 64 KiB h2 DECODED header list
MaxStreamsPerConnection 1000 h2 streams over the connection's LIFE
MaxUnproductiveFrames 1000 h2 frames that advance no request
MaxRequestsPerConnection 1000 1.1 requests over the connection's LIFE
Each value above is the compile-time DEFAULT of the matching property, so a
component nobody configures uses exactly these numbers - the same way the async
TLS server publishes its own capacities.
* 0 MEANS UNBOUNDED on every one of them, in the engine as well as in the
documentation - a bound of 0 that rejected everything would turn "switch this
off" into "refuse all traffic". Switching one off is a decision to take
deliberately; each exists because something without it was a DoS hole.
* WHEN A CHANGE TAKES EFFECT differs by bound, in three ways, and it is worth
being exact because two of them are surprising:
- HTTP/1.1 reads its bounds during parsing: HeaderBytes for the head and
each metadata octet, BodyBytes when checking a declared length or an
announced chunk. A change can affect an incomplete request; configure
before activation rather than relying on a fixed per-request snapshot.
The two timeout durations are captured once when the next header stage
begins; changing them cannot extend an already timed request.
- HTTP/2 bounds are copied into a connection's engine as its session is
created, so a change applies only to connections opened AFTERWARDS. Two of
them (MaxConcurrentStreams, HeaderListBytes) are announced to that peer in
its opening SETTINGS, so enforcing a changed value mid-connection without
re-announcing it would be worse than not changing it at all.
- TotalBodyBytes is read on EVERY charge, by both wires, so a change takes
effect immediately and everywhere - including on connections that are
already open. Lowering it below what is currently held does not reclaim
anything; it refuses the next charge until enough has been released.
* EVERYTHING HERE IS PER PROTOCOL COMPONENT, not per host - the per-request and
per-connection caps as much as the server-wide budget. A host serving both
wires has two tCustomHTTPLimits, configures them independently, and its real
server-wide ceiling is the SUM of the two TotalBodyBytes.
* NEGATIVES NORMALISE TO 0: the property stores 0 so the Object Inspector
reads back the bound that is in effect rather than the number that was
typed.
* CONFIGURE BEFORE Active. Reading a bound while connections are live is safe;
two threads WRITING the same bound is not, and nothing here serialises that.
* Size TotalBodyBytes from evidence, not guesswork: BodyBytesHeld and
BodyBytesHighWater on the component report what is held now and the most ever
held. TotalResponseBytes the same way, from TsmHTTPSv2.ResponseBytesHeld and
ResponseBytesHighWater; like TotalBodyBytes it is read every time a stream
opens, so a change applies at once.
* THE RESPONSE BUDGET REFUSES NEW STREAMS, NOT RESPONSES. A response already
dispatched has to be held until it is sent, so the bound is asked where
saying no costs nothing: when the next stream opens (section 13). A
connection can therefore go over ConnResponseBytes by the responses of the
streams that were already open when it filled. Responses sent from a file
are not counted at all - they hold a handle and one frame at a time.
LIMIT VALUE WIRE WHERE ON BREACH
----- ----- ---- ----- ---------
request header block 64 KiB 1.1 Mobile.HTTPS 431 + close
aggregate chunk metadata 64 KiB 1.1 Mobile.HTTPS 431 + close
request body 8 MiB 1.1 Mobile.HTTPS 413 + close
malformed request line - 1.1 Mobile.HTTPS 400 + close
Content-Length not 1*DIGIT - 1.1 Mobile.HTTPS 400 + close
Content-Length > MaxInt/2 - 1.1 Mobile.HTTPS 400 + close
duplicate Content-Length - 1.1 Mobile.HTTPS 400 + close
TE/CL ambiguity, invalid - 1.1 Mobile.HTTPS 400 + close
coding/chunk/trailer
unsupported coding before - 1.1 Mobile.HTTPS 501 + close
final chunked
obs-fold / bad field name - 1.1 Mobile.HTTPS 400 + close
request line not 3 parts - 1.1 Mobile.HTTPS 400 + close
version not HTTP/1.0 or .1 - 1.1 Mobile.HTTPS 505 + close
requests per connection 1000 1.1 Mobile.HTTPS Connection: close
HPACK integer MaxInt h2 Http.Hpack GOAWAY
(any index/length/size) COMPRESSION_ERROR
non-GET/HEAD on a file
route - both Http.Server 405
frame length 16384 h2 Http2Frames GOAWAY
(declared, pre-buffer) FRAME_SIZE_ERROR
assembled header block 256 KiB h2 Http2Conn GOAWAY
(COMPRESSED) ENHANCE_YOUR_CALM
decoded header list 64 KiB h2 Http.Hpack GOAWAY
(UNCOMPRESSED, name+ ENHANCE_YOUR_CALM
value+32 per field;
also advertised)
CONTINUATION frames per
header block 128 h2 Http2Conn GOAWAY
ENHANCE_YOUR_CALM
assembled request body 8 MiB h2 Http2Conn 413 + RST_STREAM
(PER STREAM) NO_ERROR when the
content-length
says so; else
RST_STREAM
ENHANCE_YOUR_CALM
assembled request bodies 8 MiB h2 Http2Conn the same
(PER CONNECTION, summed
over live streams)
request bodies held 256 MiB both Mobile.HTTPS 503 (1.1) /
(PER SERVER, all conns) RST_STREAM (h2)
concurrent open streams 100 h2 Http2Conn RST_STREAM
REFUSED_STREAM
memory-held responses 32 MiB h2 Http2Conn RST_STREAM on
(PER CONNECTION) NEW streams,
REFUSED_STREAM
memory-held responses 256 MiB h2 Mobile.HTTPS RST_STREAM on
(PER SERVER, all conns) NEW streams,
REFUSED_STREAM
pipelined raw input while 2*HeaderBytes 1.1 Mobile.HTTPS connection
a response is leaving + BodyBytes dropped
streams per connection 1000 h2 Http2Conn GOAWAY
(LIFETIME, not concurrent) NO_ERROR
unproductive frames 1000 h2 Http2Conn GOAWAY
(budget; refunded by work) ENHANCE_YOUR_CALM
connection recv window 65535 + h2 Http2Conn GOAWAY
overrun updates FLOW_CONTROL_ERROR
stream recv window 65535 + h2 Http2Conn RST_STREAM
overrun updates FLOW_CONTROL_ERROR
handler raises - both Mobile.HTTPS / 500 on that
Http2Conn request only
THE LAST TWO ROWS ARE A DIFFERENT KIND OF BOUND. Everything else here limits how
BIG one thing may be; those two limit how MANY. That axis is what the flood CVEs
attack:
* MaxUnproductiveFrames is a per-connection budget spent by frames that make
the server work without advancing any request - PING and SETTINGS (each
obliges an answer), PRIORITY (ignored outright since RFC 9113 deprecated
the tree), GOAWAY (whose meaning the server ignores too, section 6),
RST_STREAM, zero-length DATA on an open stream, unknown frame types, and
refused HEADERS. That is CVE-2019-9512 (PING), -9513 (PRIORITY), -9515
(SETTINGS) and -9518 (empty frames): 9-octet frames sent as fast as the link
allows, every one of which the server answers. A stream the server resets
for something the client sent - a stream error, a malformed request, a
body refused at a limit - is spent from the same budget, as the client's
own RST_STREAM is: the client opened a stream and had it reset with nothing
served, whichever side sent the RST_STREAM (the "MadeYouReset" shape,
CVE-2025-8671, below). Each costs a token; each
request actually served REFUNDS several, capped at the budget. So a connection
doing real work never drifts into the limit however long it lives, and one
doing nothing else runs out. Exhausting it is ENHANCE_YOUR_CALM: every frame
counted was legal, so the peer is not malformed, it is abusive.
* MaxStreamsPerConnection bounds streams over the connection's LIFETIME, which
MaxConcurrentStreams does not and never did - a stream is dropped as soon as
its response is flushed, so the concurrent count returns to near zero after
every request and a peer can open them one after another for ever. Because
dispatch here is synchronous, that is a request-RATE control: thousands of
requests fit in a single TCP segment at roughly 30 octets each and every one
is served inline on an I/O thread. This is the rapid-reset shape
(CVE-2023-44487) approached from the resource side rather than the
cancellation side - cancelling cannot free a concurrency slot for more
concurrent work here, because the work was already done synchronously, so what
needs bounding is the total. Reaching it is GOAWAY(NO_ERROR), not an abuse
code: the peer has used this connection up and should open another, which
makes it pay for TCP and TLS again. Same idea, and same default, as nginx's
keepalive_requests.
The same holds for "MadeYouReset" (CVE-2025-8671): the client makes the
SERVER reset its streams - with a WINDOW_UPDATE of 0, or a malformed frame
or request - and a server that goes on working on a request after it has
reset the stream no longer counts that request against
MaxConcurrentStreams. Here a handler has returned before the next frame is
read, so a reset frees a response that exists or a request never
dispatched, never work in progress. A request served and then reset keeps
the refund its dispatch earned and is bounded by MaxStreamsPerConnection,
as a request the client cancels is; a stream reset with nothing served
costs a token of MaxUnproductiveFrames.
THE THREE BODY ROWS ARE THREE DIFFERENT QUESTIONS. "8 MiB per request" says
nothing about memory on its own: a hundred streams each just under it is 800 MiB
on ONE connection, and MaxLiveSessions of those is tens of gigabytes. Caps
compose by MULTIPLICATION and the product is the number that matters, so each
level has its own:
per stream one exchange cannot be huge
per connection one peer cannot be huge by being numerous (same 8 MiB, so a
connection may hold one maximal body or a hundred small ones)
per server the whole population cannot be huge by being many
(Limits.TotalBodyBytes; 0 = unbounded)
Breaching the server-wide budget gives 503 plus close on HTTP/1.1 and a stream
reset on HTTP/2. The peer has done nothing wrong; the server is full. HTTP/1.1
closes because it has not consumed the refused request's remaining framing.
The budget is per protocol component, so a host serving both wires has two and
its TCP ceiling is their sum. HTTP/3 adds its separate plugin budgets.
A BODY THAT SAYS IT IS TOO LARGE IS ANSWERED BEFORE IT IS SENT. HTTP/1.1
reads Content-Length from the head and answers 413 at once. For a chunked
request it checks the decoded sum plus each announced chunk before retaining
its payload; that rejection also sends 413 and closes. It reserves each
chunk against the server-wide budget first, releasing reservations once on
dispatch or failure. Chunk framing and trailers have a separate HeaderBytes
budget, not BodyBytes. The separately retained trailer list also charges
HeaderBytes, including field overhead (section 2.2). HTTP/2 does the same at the
end of the request's
header block: a content-length over the per-stream or the per-connection cap
gets a complete 413 response (END_STREAM) and then RST_STREAM(NO_ERROR),
which RFC 9113 s8.1 provides for - "a server MAY request that the client
abort transmission of a request without error by sending a RST_STREAM with
an error code of NO_ERROR after sending a complete response" - so the client
has an answer to show, not a dropped upload. What it had already sent is
discarded and credited to the connection window (s5.4.2), and the connection
carries on. Only a body that does not say - no content-length - or a budget
shared with others (the per-connection sum, the server-wide budget) can be
stopped part-way, with RST_STREAM ENHANCE_YOUR_CALM. A body that runs past
the content-length it declared is malformed (RFC 9113 s8.1.1) and is reset
with PROTOCOL_ERROR as soon as it does, unless the frame that passes it also
reaches the cap, which is then the reset above; one shorter than declared is
reset the same way at its END_STREAM. Trailers the client had already sent
on a refused stream are decoded and dropped (section 9).
EVERY BODY REFUSAL IS REPORTED: OnBodyRefused on both protocol components
(and on tHttp2Conn) fires once per refusal - 413, 503 or a stream reset -
with the peer, the request, the content-length, the bound and its value
(tHttpBodyRefusal). A chunked HTTP/1.1 refusal reports Declared = -1;
Received counts decoded payload actually received, excluding all framing.
Metadata/malformed refusals are not body-limit events. Without this event
the server is the one party that never hears of a body-budget refusal; log
it.
For ordinary complete-body handlers, these budgets refuse rather than throttle.
HTTP/2 replenishes their receive windows when DATA arrives, while retaining the
assembled payload against body limits. Opt-in streaming routes instead reserve
bounded storage before admission and withhold payload credit until worker Read
(section 24). Their cumulative body limit is separate from retained storage;
large bodies can progress without being assembled in memory.
Three things this table is deliberately saying:
* THE SCOPE OF A BREACH IS A DESIGN DECISION, not an accident. Anything that
desynchronises shared per-connection state (framing, the HPACK table, the
connection window) has to kill the connection; anything confined to one
exchange (a body cap, too many streams, a stream window) kills only the
stream. Getting that backwards is how one abusive request takes out 99 healthy
ones, or how a corrupt table silently serves garbage.
* NO CAP IS ADVISORY. Every row is enforced locally; nothing here depends on the
peer honouring a SETTINGS value we sent. MAX_HEADER_LIST_SIZE - the one
parameter in RFC 9113 that WOULD be advisory - is BOTH advertised and
enforced locally at the same number (section 8). Advertising it lets a
well-behaved peer trim its own request instead of losing the connection;
the local ceiling is what makes it a cap rather than a request.
* ENHANCE_YOUR_CALM, not PROTOCOL_ERROR, for the flood cases. The peer is not
malformed, it is abusive, and the code should say which.
HeaderTimeoutMSec and RequestTimeoutMSec add absolute input deadlines to
these size budgets (section 20.4). The TLS host's HandshakeTimeout and
IdleTimeout remain separate connection policies (AsyncTLSServer.txt sections
5, 5.1). Inbound progress may refresh an idle timer, but cannot extend either
HTTP input deadline. HTTP work is delivered separately from expiry-nudge
callbacks. Opt-in streaming exchanges retain their own finite TimeoutMSec
covering admission, worker queueing, body consumption and response submission
(section 24), including periods with parked receive.
20.2 HTTP/3 SERVER LIMITS (TsmHTTPSv3.Limits: tHTTP3Limits)
--------------------------------------------------------------------------------
HTTP/3 has its own persistent limit object and validation rules. These are the
default values. Size/count budgets require positive minima. The two input
timeouts additionally accept zero to explicitly disable that stage:
Property Default What it bounds
------------------------- -------- ---------------------------------------
HeaderTimeoutMSec 10000 ms absolute header/control stage
RequestTimeoutMSec 30000 ms absolute buffered body/trailers
MaxHeaderBlockBytes 64 KiB one encoded QPACK field block
MaxFieldSectionBytes 64 KiB decoded name + value + 32 per field
QpackTableCapacity 0 advertised decoder table bytes
QpackBlockedStreams 0 simultaneous blocked request streams
MaxQpackBlockedBytes 256 KiB retained encoded blocked input
MaxPushes 0 lifetime push intentions
MaxActivePushes 8 outstanding pushed responses
MaxPushBufferedBytes 256 KiB retained promised request metadata
PushTimeoutMSec 10000 ms absolute pending push-stream admission
SendWindowBytes 64 KiB physical QUIC send storage until ACK/reset ACK
MaxBufferedSendBytes 256 KiB queued HTTP/3 framing/body output
MaxActiveRequests 100 requests whose response FIN is pending
MaxRequests 1000 requests per cumulative stream-credit block
MinRequestBlockAgeMSec 60000 ms minimum block age for renewal (0 always renews)
MaxPeerUniStreams 64 retained peer uni-stream records
MaxBodyBytes 8 MiB one assembled request body
MaxConnectionBodyBytes 8 MiB assembled body memory on one connection
MaxMemoryResponseBytes 16 MiB memory response sources on one connection
MaxUnproductiveFrames 4096 work without useful request-body progress
TotalBodyBytes 256 MiB request memory across this plugin
TotalResponseBytes 256 MiB response memory across this plugin
Configure these while the QUIC host is inactive. Per-connection limits are
captured when a session opens; aggregate charges are synchronized in the
detached plugin state. Snapshot/activation validates positive minima and
consistency: MaxFieldSectionBytes >= 32, MaxHeaderBlockBytes >= 2,
MaxBufferedSendBytes >= MaxHeaderBlockBytes + 64, MaxRequests >= 1,
MinRequestBlockAgeMSec in 0..86400000, MaxPeerUniStreams >= 3 and MaxConnectionBodyBytes >=
MaxBodyBytes. Invalid configurations raise before activation rather than
silently become unbounded.
SendWindowBytes is 16384..3145728, checked at assignment; Assign, component
streaming and the per-connection snapshot preserve it. The default 65536 is
not stored in DFM. A different window changes the 0-RTT context, refusing old
early data. The minimum is one 16 KiB HTTP/3 source piece; the maximum leaves
the built-in host's initial 1 MiB receive credit inside its 4 MiB pool.
The cap applies to physical allocations shared by all streams and retained
until ACK/reset acknowledgement, independently of MaxBufferedSendBytes. At
most W bytes per RTT can be sent: 65536 at 50 ms is 1.31 MB/s; 262144 at 50 ms
is 5.24 MB/s. Tiny peer credit grants and selective ACKs can create W one-byte
ranges. Each send-range descriptor is 32 bytes on Win32, 40 on Win64; each
pending output stream interval is 32 on both (CRYPTO intervals are 16).
Steady send storage can reach W + W*SizeOf(tSendRange) + max(256,W div 256)*32.
Pending output intervals, including empty FINs, share that cap: 256 at 64 KiB,
1024 at 256 KiB, 4096 at 1 MiB and 12288 at 3 MiB. Copy-on-change arrays can double
descriptor storage temporarily and fragmentation costs quadratic CPU. Add
receive/HTTP/TLS and separate CRYPTO/control budgets, then multiply by the
listener's MaxConnections. The deliberately low default favours visible low
performance over letting any peer pin large per-connection allocations. Raise
it together with a lower MaxConnections and an explicit process memory budget.
No protocol requirement selects 65536 over another modest safe reservation.
BodyBytesHeld and ResponseBytesHeld expose current aggregate charges. Unlike the
TCP HTTP/2 component, this component does not publish the same high-water or
OnBodyRefused event surface. Owned file/stream lengths are not charged as
materialized response memory. The body budgets, memory-response budgets and
framing queue budget are separate; sharing a router does not combine them with
the TCP components' budgets. Add per-component budgets when sizing the process.
The engine validates declared Content-Length and enforces the actual body sum.
Oversized/budget-refused requests are aborted with H3_EXCESSIVE_LOAD; malformed
message fields/lengths use H3_MESSAGE_ERROR. Do not expect the TCP HTTP/2
413/RST_STREAM(NO_ERROR) sequence or a TCP 503 from this path. Local response
resource failures abort the affected stream. Connection/control/QPACK errors
remain connection-scoped as described in section 14.
Accepted body bytes replenish QUIC receive credit so a complete upload can
exceed the initial window, but assembled application bodies stay bounded by the
memory budgets. Ordinary handlers receive complete bodies; opt-in streaming
routes use the bounded exchange and credit rules in section 24. Input deadlines
are described in section 20.4. Terminal request IDs
retire after receive termination and consumption, send FIN/reset acknowledgement
and release of application, streaming and QPACK references. The host compacts
its notices with the QUIC and HTTP records; deadline and service scans walk
live records. Retired floors plus bounded sparse ranges remember closed IDs,
so late frames cannot reopen them or alter final-size accounting. Live records
and sparse retired metadata share the fixed 2048-entry connection ceiling.
MaxRequests is a block size, independently of MaxActiveRequests. Match the
first block to the host's InitialMaxStreamsBidi (both default 1000). At the
LAST stream of the current grant, compare the block age, measured from Opened
for the first block, with MinRequestBlockAgeMSec. Skipped IDs consume the grant
and count too, including streams first seen through STOP_SENDING or RESET.
If the age is strictly greater, grant another MaxRequests streams using the
absolute cumulative MAX_STREAMS limit, then reset the block start and counter.
The client can wait at most about one round trip for the new credit. Zero
always renews if records permit; equality counts as young.
The shared cQuicServerStreamRecordCeiling is 2048. A full 1000-request next
block therefore fits while a browser still has 100 requests active at the
boundary, together with critical streams and outstanding uni-stream credit.
Reservation counts unused and skipped IDs without allocating their records;
QUIC objects, host notices and HTTP records allocate only as streams materialize.
A peer that pins enough records to prevent reserving the whole next block
still gets GOAWAY regardless of block age.
Fixed request-record storage measured with Delphi 13 (Win32 / Win64 bytes):
QUIC stream object 156 / 176
host notice 24 / 24
HTTP/3 stream object 332 / 424
frame reader 60 / 80
empty request-body stream 24 / 48
reader's 8-byte buffer and array header 16 / 24
QUIC and HTTP record-array pointers 8 / 16
QUIC lookup slots at the ceiling 8 / 8
total per materialized request 628 / 800
At the ceiling, worst-case steady fixed record storage is 1286144 / 1638400
bytes per connection (about 1.23 / 1.56 MiB), plus 32 / 64 bytes for the four
shared array headers. Multiply by the listener's MaxConnections: at its default
1024, about 1.23 / 1.56 GiB for these records alone. This is not a total process
memory bound: add allocator overhead, transient array resizing, retired-range
storage and the separate receive, send, HTTP, QPACK and TLS budgets. Configure
MaxConnections against that total. Empty body streams allocate no body buffer;
payload and range allocations are charged to their respective budgets.
Set MinRequestBlockAgeMSec to allow human client users but rule out bots. A
person browsing does not open 1000 requests in 60 seconds; a bot or scraper
does. A young or equally old block gets GOAWAY with the first ID beyond the
current grant, making it reconnect through admission, Retry and the peer
filter. Every already allowed request may finish. An old block also gets
GOAWAY if a full next block cannot fit the fixed record ceiling after
retirement. Reservation includes unused and skipped IDs and outstanding peer
uni-stream credit: granting a block cannot promise more records than memory
can hold. Streams pinned open or QPACK references withheld by the peer cannot
grow memory or scan work with the connection's lifetime.
If peer uni-stream credit delays the control stream, or response framing fills
the queue, GOAWAY stays pending until its prefix and queue room are available.
That delay does not fail admitted requests or report drain complete; the host's
shutdown bound still applies.
20.3 TRANSPORT BUDGETS, TIMERS AND CLIENT PRODUCTION
--------------------------------------------------------------------------------
HTTP memory/queue budgets do not replace transport budgets. The QUIC stream
manager separately retains send data for acknowledgement/retransmission, receive
reassembly and bounded range metadata. Its MaxBufferedBytes pool combines send
and receive retention; MaxRangesPerStream must allow ACK fragmentation as well
as queued output. Filling the shared pool with sends can leave no receive room.
An HTTP queue limit alone provides no reserved receive capacity there.
TsmHTTPSv3 prepares Limits.SendWindowBytes before SETTINGS, atomically with
max(256,W div 256) pending STREAM intervals, including empty FINs. Tiny credit
grants and selective ACKs beyond this cap close only that connection with an
internal error recorded in LastConnectionError. This deliberately favours
visible low performance over giving a peer a CPU lever. Packet-sized loss
within the window stays well within capacity. CRYPTO
and control budgets stay independent. An offered preparation policy that
refuses fails closed with H3_INTERNAL_ERROR and a reason naming the window;
a transport without it retains legacy complete-handler behaviour. The memory
and W/RTT costs are in section 20.2.
A low-level incremental client owner must account for the QUIC stream manager's
BufferedBytes and the HTTP engine's RetainedSendBytes, candidate framing and
receive/header/control headroom before production (section 23.3). The native
fixture demonstrates an explicit bounded producer policy. The high-level
BeginUpload path supplies automatic receive/send/range admission and late-tail
cancellation (section 23.1). Simply increasing a finite pool/range cap is not a
general guarantee against saturation.
Connection timers belong to the corresponding host: the TLS host's reaper for
HTTP/1.1 and HTTP/2; QUIC idle/close, recovery and shutdown timers for HTTP/3.
HTTP/3 graceful drain queues GOAWAY/response FIN before the host waits for
pending QUIC sends/acknowledgements within its deadline (QUICServer.txt). A
request-block decision drains only that connection; the listener and other
connections keep serving. Successful HTTP/3 drain, including listener shutdown,
uses APPLICATION CONNECTION_CLOSE with H3_NO_ERROR (0x100).
A connection idle timeout is not a per-request deadline against a peer that keeps
dribbling data. Client operation deadlines are supplied by the high-level client
or the owner driving the low-level adapter; do not infer them from a buffer
limit.
20.4 ABSOLUTE HEADER AND BUFFERED-REQUEST DEADLINES
--------------------------------------------------------------------------------
All three protocol components publish Limits.HeaderTimeoutMSec (10000 ms) and
Limits.RequestTimeoutMSec (30000 ms). These are absolute stage budgets. A peer
cannot keep an incomplete request alive by dribbling bytes, frames or trailers.
Zero explicitly disables that stage; negative component values store zero.
Configure finite values before activation. HTTP/1.1 captures them when each
header stage begins; HTTP/2 and HTTP/3 capture them for each new connection.
HTTP/1.1 starts its header budget at Opened, so a silent authenticated peer is
bounded too. After a response, the next budget starts when the session can
parse another request. Pipelined bytes intentionally waiting for the preceding
response do not time that response. Valid initial headers end the header stage
and start the buffered-request budget, which covers the entire body and
trailers through validated EOF, including chunk syntax and unknown lengths.
Neither progress nor reparsing restarts a stage. The two stages can consume
their configured sum; RequestTimeoutMSec is not a new full budget per chunk.
HTTP/2 bounds its opening preface and first SETTINGS, every unfinished frame,
and the complete HEADERS/CONTINUATION block. An unfinished compressed block
keeps its original deadline across fragments. Timeout in framing or shared
HPACK state sends GOAWAY(ENHANCE_YOUR_CALM) and closes when possible. Expiry of
a buffered body after valid initial headers resets only that stream with
CANCEL, releases its retained resources and leaves unrelated streams usable.
HTTP/3 bounds initial request headers from first owner observation of an
explicit receive stream, including out-of-order data with a reassembly hole.
It also bounds startup through peer SETTINGS and unfinished uni-stream types,
control frames and decoder instructions. Idle known critical streams between
complete units are not timed as incomplete headers. A request timeout uses
H3_REQUEST_CANCELLED; potentially critical uni/control/QPACK expiry closes the
connection. FIN/reset before a complete uni type is tolerated. Failed request
IDs retain only the bounded tombstone needed to reject late data safely.
HTTP/1.1 sends 408 and closes when no preceding response is in progress. If
response output is still pending, it closes without inserting another status
into that response. Expired requests never reach a complete-body handler.
Cancellation and closure release input parsers, body reservations and receive
credit through each wire's existing accounting rules.
Validated EOF stops buffered input timing before application dispatch. The
budget does not interrupt synchronous handlers or time their response sources,
file downloads or long-lived responses. Accepted streaming routes instead hand
off after valid initial headers to their existing exchange deadline; granting
unknown-length privilege does not disable either initial header protection or
the exchange's finite resource limits (section 24.1).
The built-in owners schedule the earliest outstanding HTTP and exchange
deadline even when no peer input arrives. Expiry is processed before late
completion and at the first serialized owner opportunity, not as hard-real-time
application-thread preemption. Finite deadlines require a working work/timer
transport; an incapable custom backend is refused, rather than silently leaving
the timer unenforced. Standalone tHttp2Conn/tHttp3ServerConn owners must schedule
OnWorkDeadline and call WorkQueued themselves. The millisecond clock is
stTlsUtils.GetTickCount64; HttpServerDeadline safely computes an absolute value.
Transport idle/handshake/shutdown timers remain independent.
--------------------------------------------------------------------------------
21. THE TCP CLEARTEXT REDIRECT PORT
================================================================================
This facility belongs to TsmAsyncTLSServer and its HTTP/1.1 plugin. The QUIC
listener accepts TLS-protected QUIC with h3; it has no cleartext HTTP/3
fallback, TCP Upgrade path or IsFallback setting. HTTP/3 discovery is advertised
through authenticated HTTP responses as described in section 16.3.
A TLS-only server still has to answer the browser that typed the bare host name.
TsmAsyncTLSServer.PlainTextRedirectPort binds a cleartext port for exactly one
purpose - one request in, one redirect out, socket closed - and hands each
exchange to whichever plugin implements iAppPlainTextRedirect. The HTTP/1.1
component implements it; this section is the surface that puts it to work.
HTTP/1.1 IS THE ONE THAT SHOULD ANSWER, and not by accident: a plaintext
redirect is a one-line HTTP/1.1 response, and h2 without prior knowledge cannot
be spoken in cleartext at all. So the natural pairing is AlpnPriority high on
the HTTP/2 component - it wins the ALPN negotiation - and IsFallback on the
HTTP/1.1 one, which answers whatever negotiated nothing.
property IsFallback: Boolean; { default False }
EXACTLY ONE component bound to a given server may set it. Nothing in the type
system can say so, so the binding says it instead: a second component claiming
the same server raises rather than winning by load order, which would be
invisible in a DFM and would change with declaration order.
IT IS HALF A SWITCH. The server's FallbackPolicy decides whether a fallback is
consulted at all and defaults to fbpRefuse, so IsFallback alone does nothing and
the cleartext port looks dead. Set FallbackPolicy := fbpUseFallback too. The two
are deliberately separate settings: WHICH protocol answers, and WHETHER an
un-negotiated connection is answered at all, are different questions.
IsFallback also decides who answers a TLS client that offered no ALPN - the
cleartext port is simply the case where there was no ALPN to offer.
property OnPlainTextRedirect: tPlainTextRedirectEvent;
tPlainTextRedirectEvent = procedure (Sender: TObject;
const aHost, aTarget: string;
var aLocation: string;
var aStatusCode: Integer) of object;
aHost is the Host header and aTarget the request target, both exactly as the
peer sent them. aLocation arrives holding 'https://' + aHost + aTarget and
aStatusCode holding 301, so a handler that does nothing still redirects
correctly, and a server that assigns no handler at all still works.
aLocation := '' REFUSES: the connection closes with no response whatsoever.
THE TRAP THIS EVENT EXISTS TO CLOSE. The default answer echoes an
attacker-chosen Host into a Location header, which is an open redirect in every
respect except that it cannot leave the https scheme. It is a safe DEFAULT and a
poor POLICY. A deployment that knows its own names should answer only for those
and refuse the rest:
procedure TForm1.Redirect(Sender: TObject; const aHost, aTarget: string;
var aLocation: string; var aStatusCode: Integer);
var
I: Integer;
begin
I := FAliases.IndexOfName(aHost); { alias -> canonical }
if I >= 0 then
aLocation := 'https://' + FAliases.ValueFromIndex[I] + aTarget
else if FKnownHosts.IndexOf(aHost) >= 0 then
aLocation := 'https://' + aHost + aTarget
else
aLocation := ''; { not ours - say nothing }
end;
Redirecting an alias to its canonical name matters for more than tidiness: it is
what makes the redirect land on a name the certificate is valid for, so the
browser's next hop succeeds instead of failing to verify.
THE HANDLER RUNS ON A SHORT-LIVED THREAD OF ITS OWN, not an I/O thread, and the
socket is closed the moment it returns. Read only state that outlives the
request - a configuration list built at startup is fine, per-connection state
does not exist here - and do not block: the exchange has a five-second budget
and at most 64 run at once (AsyncTLSServer.txt section 4).
Nothing on the request side is parsed beyond the head, and the request is parsed
by HttpParseRequestHead - the same hardened parser the TLS wire uses, so the
smuggling and framing vectors in section 20 are refused here too, before any of
this is reached.
--------------------------------------------------------------------------------
22. THE REST LAYER AND CLIENT TLS ENGINE
================================================================================
The server-side counterpart of TsmRESTClient (StreamSec.Http.Rest). Everything
below sits ON the core of sections 2-3: it is an iHttpRequestHandler mounted at
a prefix, so it inherits the shared-router property - one mount on a shared
router serves HTTP/1.1, HTTP/2 and HTTP/3 without per-wire REST handlers. The
published Protocol association still accepts only the TCP component base; use
the shared Router or MountOn for HTTP/3.
22.1 THE SHAPE - A TRANSPORT-FREE ENGINE INSIDE A COMPONENT
--------------------------------------------------------------------------------
tRestDispatcher is the engine and implements iHttpRequestHandler and nothing
else, so every routing, auth, validation and idempotency path can be driven by
calling HandleRequest with a hand-built tHttpServerRequest / tHttpServerResponse
- no socket, no TLS, no reactor. That is the same split as tHttp2Conn inside
TsmHTTPSv2 and it exists for the same reason given in section 1: dispatch logic
that needs a live server to exercise is dispatch logic whose hostile cases do
not get tested.
TsmCustomRESTServer / TsmRESTServer is the component around it. Its published
TCP association is:
Protocol: TsmCustomHTTPSProtocol either TCP component fits - the
property is typed at their shared base
BasePath: string the subtree, default '/api'
Assigning Protocol mounts the dispatcher on that component's Router at BasePath;
clearing it unmounts. The association is made in Loaded, not in the setter, for
the reason section 16 gives for the plugins' own Server property: during DFM
streaming the referenced component may not exist yet. Runtime assignment binds
immediately, the designer never mounts, and Notification unmounts if the
protocol component goes away. MountOn(aRouter) is the runtime escape hatch for a
shared router, including one assigned to TsmHTTPSv3; routes are registered from
code, because a route table is not something the Object Inspector can carry.
22.2 WHAT A REQUEST GOES THROUGH, IN ORDER
--------------------------------------------------------------------------------
1 MOUNT the raw path must lie under BasePath (404 otherwise)
2 ROUTE template match on raw segments; 404 for no path, 405 + a
lowercase 'allow' for a known path with the wrong method, and
204 + allow for OPTIONS
3 CAPTURES each capture percent-decoded AFTER the split; 400 on a
malformed escape
4 AUTH the Authenticate seam - deny-by-default once configured
5 BODY a non-empty body must declare a JSON media type (415) and
parse (400)
6 IDEMPOTENCY replay a completed answer, 409 a concurrent duplicate
7 DISPATCH the handler, with an exception answered as a generic 500
Errors are RFC 9457 application/problem+json throughout, and every header this
layer emits is lowercase - HTTP/2 and HTTP/3 reject uppercase field names;
HTTP/1.1 does not care, the same rule the REST client follows.
22.3 ROUTES AND CAPTURES
--------------------------------------------------------------------------------
lRest.AddRoute('GET', '/orders/{id}', lOrdersHandler); {iRestHandler}
lRest.AddRouteEvent('POST', '/orders', Form1.CreateOrder);
lRest.AddRouteEvent('GET', '/health', Form1.Health, True); {AuthExempt}
Literal segments match RAW and case-sensitively; a brace-wrapped segment
captures any ONE non-empty segment. Two registration ways with DISTINCT names
rather than an overload, to avoid Delphi E2250 ambiguity: Delphi cannot resolve
a bare method reference across an interface-vs-method-pointer overload.
Re-registering the same method and shape REPLACES the handler, matching the
router convention.
THE DECODE HAPPENS AFTER THE SPLIT, and that ordering is the security property:
the path is divided on '/' first and each captured segment decoded afterwards,
so an encoded separator can never manufacture a path boundary - '/orders/17%2F3'
is one capture holding '17/3', not two segments. Malformed templates raise at
REGISTRATION, where the mistake is on the screen rather than in a 404 six months
later.
HEAD is served by a GET route when no explicit HEAD route exists; all three wire
sessions already suppress the body of a HEAD answer.
22.4 THE HANDLER SURFACE
--------------------------------------------------------------------------------
iRestRequest Params[name] (decoded captures), Json (the parsed body, nil when
there was none - a handler never sees malformed input, the
dispatcher answered 415 or 400 first), Principal, QueryValue, and
Http: iHttpRequest for everything else - headers, cookies,
session, and Connection with the TLS facts of section 2.1.
iRestResponse SendJson / SendCreated / SendNoContent / SendProblem, each setting
the status EXPLICITLY so the 404-to-200 promotion of section 2
never applies, plus Http: iHttpResponse for the rest.
Lifetime and threading are the core rules, unchanged: both die when the handler
returns, handlers run inline on threads driving their connections, one
connection is never dispatched twice at once and different connections are
concurrent. The route table has NO lock - register before the server is Active,
exactly as for the router itself.
22.5 AUTH
--------------------------------------------------------------------------------
Authenticate / OnAuthenticate is a virtual-method-and-event pair, the same
both-ways contract TsmCustomRESTClient offers: subclass and override, or drop an
instance and assign the event.
aAllow ARRIVES False. With neither an event nor an override the API is open -
answering 401 for want of a handler nobody wrote would be surprising - but the
moment a policy exists, denying is the default and allowing is the explicit act.
A refusal answers 401 with a lowercase www-authenticate carrying AuthChallenge.
AuthExempt on a route skips the seam, for health checks and discovery documents.
It runs BEFORE the body is parsed: an unauthenticated peer's body is not worth
parsing. mTLS needs nothing new - Http.Connection.TransportInfo yields
iTLSConnectionInfo through Supports (section 2.1), and the guidance there
applies unchanged: authorize on (PeerIssuer, PeerSerialNumber), never on a
rendered DN string.
22.6 IDEMPOTENCY - THE SERVER HALF OF THE CLIENT KEY
--------------------------------------------------------------------------------
TsmRESTClient sends an idempotency key under a configurable header; this is the
side that honours it. Both default to 'Idempotency-Key', so an unconfigured pair
already works together. Only UNSAFE methods are considered, and the key is
scoped by method and raw path so one client key cannot collide across endpoints.
The store is a seam (iRestIdempotencyStore) with a bundled in-memory
implementation installed by the constructor: self-locking, TTL-expired (one
hour, measured from COMPLETION), and capped at 10000 entries with the oldest
completed entry evicted first. In-memory means replay protection ends with the
process - the same trade the TLS 1.3 ticket store makes; implement the interface
over a real store when that is not enough, or assign nil to disable.
THE CONTRACT IS A RESERVATION, and the failure mode it exists to prevent is a
reservation that is never resolved:
rivNew reserved - the dispatcher MUST later Complete or Abandon it,
including on the exception path
rivInFlight a duplicate arrived while the first is still running -> 409,
never executed alongside
rivReplay completed -> the stored status, content-type and body are
replayed verbatim
rivOverloaded nothing but in-flight work and the cap is reached -> 503
A 5xx is ABANDONED, never stored: a transient failure must not become the key's
permanent answer. A 4xx IS stored, because it is deterministic - the same
request will earn the same refusal.
22.7 WHAT IS DELIBERATELY NOT HERE
--------------------------------------------------------------------------------
No new security bounds. Request size is already bounded by
tHTTP11Limits/tHTTP2Limits/tHTTP3Limits at the wire (section 20), and the lesson
recorded there - that making a bound configurable reopens what the constant was
accidentally protecting - is the reason this layer adds none of its own.
Also out, and each a separate decision rather than an oversight: CORS (a
TPersistent options block when browser consumers appear), content negotiation
beyond JSON, streamed or asynchronous responses (a handler that produces its
body after it returns: the transport's drain notification such a thing needs
exists - section 3.1 - but no handler API is built on it), and OpenAPI
generation.
22.8 STATUS & TESTS
--------------------------------------------------------------------------------
A test of the engine alone, no socket, covers: the prefix-router seam, routing
and template validation, captures including the encoded separator, the JSON
body, auth, query values, the response helpers, the store, and the whole
pipeline. Controls first, as in every suite here - a dispatcher that answered
404 to everything would satisfy every negative vector otherwise.
The LOOP test runs TsmRESTClient against TsmRESTServer over a real async TLS
server in one process, the whole suite once for each TCP wire, plus a third
section on the client's TLS engine (see 22.9). It exists because the properties
that matter are the ones only a live pair has: that the client default
idempotency header IS the header the server deduplicates on, that the client
single 401 retry lands on the server real 401 path and that the retried
credential is the one accepted, and that lowercase header hygiene survives
HPACK. Its first control is a NON-REST handler on the same server, which is what
separates "the pair cannot talk" from "the REST layer is wrong"; the second
asserts the negotiated ALPN, without which an h2 leg that fell back to HTTP/1.1
would pass the h2 half of the suite. With the two halves split into separate
processes, the server was judged by curl and by a script driving the Node http2
client - a foreign peer is the only thing that can show the pair agrees on HTTP
as everyone else implements it, rather than merely with itself.
A TRAP THE LOOP TEST WALKED INTO, worth knowing when configuring any listener
here: loading a CA into the server engine RootCerts makes the server request a
client certificate, because RootCerts is what a CertificateRequest is built from
(the trust-anchor rule AsyncTLSServer.txt states). No client in the test has
one, so every handshake aborted - and it presented as "connection was aborted"
with nothing said about certificates, on curl as well as on our own client. Set
Options.RequestClientCertificate / RequireClientCertificate explicitly on a
listener that loads anchors for any other purpose.
22.9 THE CLIENT'S TLS ENGINE - TsmRESTClient.TLSEngine
--------------------------------------------------------------------------------
property TLSEngine: TsmSimpleTLSInternalServer;
Assign an engine you create and keep for as long as the client lives, and every
call runs on it. Leave it nil and the client behaves exactly as it always has.
WHY YOU WANT TO. The engine owns the trust store, and the trust store is also
the cache the revocation check consults before it fetches: a CRL fetched while
validating one call is FOUND by the next rather than fetched again. A client
with no engine of its own builds one per exchange and destroys it afterwards, so
every call starts with an empty cache and re-fetches the peer's CRLs. Against a
slow or distant distribution point that is seconds per call - and it lands on
the call a user is waiting for, because this client is synchronous.
This is about not repeating the work, NOT about doing less of it.
RevocationChecking keeps its meaning and its rvcSoft default, and a revoked
certificate is still refused. If slow revocation lookups have ever tempted you
towards rvcOff, this is the fix that does not cost you the check.
var lEngine: TsmSimpleTLSInternalServer; // created once, kept
lRest: TsmRESTClient;
...
lRest.OnConfigureTrust := MyAnchors; // still where anchors come from
lRest.TLSEngine := lEngine; // ...installed on THIS engine, once
WHICH COMPONENT THE CLIENT USES is now decided rather than fixed:
TLSEngine assigned TsmAdvancedHTTPSClient on your engine. Prefer
this wherever calls repeat.
no trust of its own TsmAdvancedHTTPSClient with no engine, which
resolves to GlobalServer. Nothing of this
client's is installed on it - this unit never
widens GlobalServer.
trust but no TLSEngine TsmHTTPSClient, which owns an engine for the one
exchange. The original behaviour.
"Trust of its own" is HasPrivateTrust, a protected virtual answered from
OnConfigureTrust/ExtraAnchorFile. A SUBCLASS THAT OVERRIDES ConfigureTrust
WITHOUT USING THE EVENT MUST OVERRIDE HasPrivateTrust TOO - the base cannot see
an overridden virtual, and a subclass that installs anchors while it answers
False has them installed nowhere while the client quietly runs on GlobalServer.
BuildTransport returns TsmCustomHTTPSClient rather than TsmHTTPSClient, so a
subclass overriding it needs the wider signature. One that reached through
Result.TLSServer to add anchors should add them from ConfigureTrust instead.
*** WITH BOTH TLSEngine AND OnConfigureTrust SET, THE ENGINE HANDED TO THE
HANDLER IS YOURS - NOT A TEMPORARY. *** Anchors it adds persist, and are seen by
everything else sharing that engine. Keep ONE ENGINE PER TRUST DOMAIN: an engine
shared between two destinations makes each one's CA able to vouch for the other,
which is the whole reason this client does not simply use GlobalServer. The
handler runs once per engine rather than once per call, so it need not be
idempotent - but it is not being handed a blank engine to scribble on either.
The client clears TLSEngine if the engine is destroyed first, and re-arms the
configuration if you assign a different one. It never frees your engine.
A NOTE FOR ANY COMPONENT THAT CREATES HTTPS CLIENTS AT RUNTIME, not just this
one: reach for TsmAdvancedHTTPSClient with a long-lived engine rather than
TsmHTTPSClient per call, for exactly the reason above. StreamSec.Mail.SMTPMx
(tMtaStsHttpsFetcher) is the pattern to copy.
--------------------------------------------------------------------------------
23. HTTP CLIENTS AND INCREMENTAL REQUEST PRODUCTION
================================================================================
23.1 THE HIGH-LEVEL HTTPS CLIENT
--------------------------------------------------------------------------------
TsmHTTPSClient owns its TLS engine; TsmAdvancedHTTPSClient accepts an external
engine. Both expose the same origin-bound request/exchange API. HTTPSClient.txt
describes discovery, cache sharing, configuration and lifetime in detail.
READ EVERY RESPONSE BODY TO ITS END, OR DISCARD IT. A completed response whose
body is not read keeps that body in memory and stays with the client; on HTTP/2
and HTTP/3 its unread octets keep their share of the connection's receive
window, so enough of them stall every response on the connection, and the
client does not move to HTTP/3. Cancel keeps a completed response readable,
body included. iHttpExchange.DiscardBody drops the unread body, returns its
credit and lets the exchange go; on an unfinished response it cancels first.
RECEIVED RESPONSE TRAILERS. tHttpResponse.Trailers is an ordered tHttpHeaders
multimap separate from the initial Headers. It preserves duplicate order and
empty values, and remains empty until the entire message completes successfully.
WaitForHead and a partial body read do not publish trailers. Re-fetch Trailers
after Read reaches successful EOF or ReadAll/Execute returns successfully. An
earlier retained empty view stays empty and valid until the response is freed;
publication replaces the response's view with the complete collection.
The response owns both views. Treat them as read-only and never free them. A
complete response retains trailers, headers and unread body through Cancel,
client destruction and an independent pending-upload teardown. Cancellation,
truncation, length mismatch or a protocol error before successful completion
never publishes a partial trailer section.
BEHAVIOUR CHANGE: HTTP/2 and HTTP/3 trailers are no longer appended to Headers.
Read Trailers explicitly, including when the same name appears in both sections.
Header, ContentType, Link and other header conveniences, redirects,
authentication and Alt-Svc discovery consult initial headers only.
All three wires use the shared field policy in section 2.2 and separately bound
retained trailer metadata, including 32 bytes per field. The high-level client
uses its existing metadata limits; the standalone HTTP/1.1 tHttpClient uses
MaxResponseSize. The latter also returns trailers for chunked responses.
Generated trailers use the optional producer companion in section 23.1.1;
the received collection is never used as an outgoing builder.
HTTP/2 RESPONSE HEADS ARE CHECKED before anything of them is published. Each
head, an interim 1xx as well as the final one, must start with exactly one
:status field, and its value must be three ASCII digits from 100 to 599, so
'0200', ' 200' or '2x0' is not a status (RFC 9113 s8.3, s8.3.2; RFC 9110 s15).
Every other field needs a non-empty lowercase name with no space, colon,
control, DEL or non-ASCII octet - so no second pseudo-header - and a value with
no control character other than HTAB, no DEL and no SP or HTAB at either end;
octets 0x80-0xFF are accepted. A connection-specific field is malformed, and so
is TE, which RFC 9113 s8.2.2 allows in a request only. RFC 9113 s8.1.1:
"Clients MUST NOT accept a malformed response." A malformed head fails its
exchange, not retryable, and resets its stream with PROTOCOL_ERROR; none of its
fields reaches Response.Headers. The header block is HPACK-decoded first in
every case, so the connection and its other exchanges carry on.
HTTP/2 NEEDS TLS 1.2 OR LATER (section 6). When a server selects h2 on an older
version - possible only where the process-wide VersionMinorMin has been lowered
below TLS 1.2 - the client sends its preface and SETTINGS, then
GOAWAY(INADEQUATE_SECURITY), and closes the connection (RFC 9113 s5.4.1) without
taking a request on it. The call that opened it - Connect, or the BeginRequest
or BeginUpload that connected - raises eHTTPSClientError whose message ends with
'HTTP/2 requires TLS 1.2 or later (RFC 9113 s9.2)', after the name of the
routine that raised it. An exchange already waiting on the connection fails, not
retryable, with exactly that text as its FailText. The client does not fall back
to HTTP/1.1 by itself. To reach such a server over HTTP/1.1, set Protocols
without hcpHttp2 before the next request; Protocols changes only while the
client is disconnected, as it is after the refusal.
AN HTTP/2 CONNECTION ERROR CLOSES THE CONNECTION. When the server's frames
break the protocol on an established connection - a first frame that is not
SETTINGS, a PING on a stream, a frame longer than the 16384 octets the client
announces, a header block that does not decode, and the other connection
errors of RFC 9113 - the client sends GOAWAY with that error code, fails every
exchange on the connection, not retryable, and closes the connection: TLS
close_notify, then a TCP FIN. RFC 9113 s5.4.1: "After sending the GOAWAY frame
for an error condition, the endpoint MUST close the TCP connection." Wire then
reads hcwNone, and the next request, BeginUpload or Connect opens a new
connection; nothing is resent by itself. A GOAWAY from the server does not
make the client close: the server closes after its own GOAWAY, and after one
with NO_ERROR the streams at or below its Last-Stream-ID complete first.
BeginUpload returns iHttpUploadExchange, which extends iHttpExchange without
changing the existing exchange interface. Choose the overload for the source:
BeginUpload(method, URL, headers, contentLength) known body length
BeginUpload(method, URL, headers) unknown body length
Both use the authenticated HTTP/1.1, HTTP/2 or HTTP/3 backend selected by the
component, including opt-in Alt-Svc discovery. BeginRequest and Execute retain
their complete-body behavior. BeginUpload returns redirects and other statuses
as responses; it does not follow them or replay the producer.
The known-length overload requires a nonnegative Int64 Content-Length, at most
cHttpsMaxUploadLength ($0FFFFFFFFFFFFFFF). Without trailer intent it emits
one canonical length field.
Negative lengths and duplicate/conflicting length fields remain invalid. The
unknown-length overload rejects every caller Content-Length, including zero.
Both reject caller transfer coding, hop-by-hop fields and malformed method, URL
and header input before submission. The cumulative payload cap applies to both.
For unknown HTTP/1.1 bodies, the client emits Transfer-Encoding: chunked and no
Content-Length. Each nonempty chunk has a hexadecimal size and CRLF framing;
the final write ends the body with one zero chunk. HTTP/2 and HTTP/3 omit both
Content-Length and Transfer-Encoding and end through DATA END_STREAM or QUIC
FIN. Optional generated request trailers are described in section 23.1.1;
chunk extensions are not generated.
RequestBodyOpen reports whether further producer writes are valid.
RequestBodyCapacity is an advisory storage snapshot, capped at 16 KiB. Submit
immutable TBytes chunks of at most cHttpsUploadChunkBytes (16 KiB) through
TrySendBody(chunk, endStream). The entire chunk and optional final boundary are
accepted, or False indicates temporary pressure and accepts neither. Retry the
same unchanged chunk after progress. Invalid/terminal writes and cumulative
payload overflow raise without admission. Known-length uploads also reject a
length overrun or short final write, so a corrected write can follow a length
error. Empty nonfinal writes are no-ops. Explicitly finish an empty upload with
an empty final write in either overload.
The compiler manages array lifetime. Accepted const chunks may share their
original storage; do not change their elements through another alias while
retained. Replacing the producer's variable is safe. A stream reader should
allocate a fresh chunk for each accepted block instead of overwriting shared
storage. No complete upload buffer is required. Retained payload is bounded at
64 KiB, with at most 4096 live parts, regardless of declared length. Whole
retained arrays remain charged through partial sends. HTTP/1.1 adds at most
eight transient framing octets per part and, without generated trailers, five
final octets outside that payload budget; framing does not require a copy of the payload. Existing
complete-body calls may retain the complete body supplied by the caller; that
storage reduces streaming capacity.
WaitForBodyCapacity(minBytes, milliseconds) waits without holding the engine
gate or a response-reader lock. minBytes is 1..16384 and zero milliseconds is
an immediate poll. False means timeout or producer closure: inspect
RequestBodyOpen, Failed and the response separately. Capacity is advisory and
can change before the next write. Zero capacity does not itself forbid an
empty final write. Producer admission performs no socket wait; the pump sends
accepted chunks and processes responses. DeadlineTick bounds later work too.
Upload and response completion are independent. A server can return its answer
while the producer remains open. Keep reading the response, or Cancel when the
remaining upload is no longer wanted. A complete response retains its status,
headers and unread body through cancellation or connection loss. An incomplete
response drains buffered bytes before reporting failure. Pending uploads retain
their connection/generation obligation even after response EOF; an old exchange
cannot write into a replacement connection or destroyed component.
Final admission closes the producer; it does not promise transport delivery or
acknowledgement. An unknown-length HTTP/1.1 body still owes its terminating zero
chunk until that is sent, even after response EOF. A known-length HTTP/1.1 body without trailer intent
has no extra final wire octets, so an empty send queue settles immediately.
Trailer-enabled bodies retain the complete final section until sent.
Cancel also aborts a tail/FIN already queued into QUIC, while preserving a
completed response. HTTP/2 and HTTP/3 cancel only that stream; cancelling an
unfinished HTTP/1.1 body or its chunk terminator retires the connection before
reuse. Other multiplexed requests continue to make progress.
Streaming client production does not change the peer's body limits or the
server handler model: existing complete-body handlers still receive complete
bodies, and opt-in streaming handlers use HTTP.txt section 24.
TsmHTTPSv1dot1 decodes chunked HTTP/1.1 requests before dispatch, so both common
upload overloads can use the existing shared handlers. Its body limits count
decoded payload. Valid chunk extensions are ignored and benign trailers are
retained separately through iHttpRequestTrailers; forbidden or malformed
trailers are rejected (section 2.2). Trailer-enabled client uploads generate request trailers as described below;
chunk extensions are not generated.
The high-level HTTP/3 transport automatically reserves outstanding advertised
receive credit and header/control transition space, separately from its 64 KiB
HTTP queue. Its aggregate QUIC send window is 256 KiB; retained-range and output
interval limits derive from that byte window rather than a spare-slot guess.
Low-level QUIC/HTTP engine owners must still configure an equivalent policy
themselves. TLS provider linking is unchanged. FPC qualification and the
remaining public endpoint limitations are described in section 19.
23.1.1 GENERATING REQUEST TRAILERS
--------------------------------------------------------------------------------
Select trailer intent before the initial request head, even for a known-length
body or an empty name list:
Upload := Client.BeginUpload('POST', URL, Headers, ['x-checksum']);
// Or: BeginUpload('POST', URL, Headers, ContentLength, ['x-checksum'])
// Submit immutable body chunks with TrySendBody(Chunk, False).
if Supports(Upload, iHttpUploadTrailersExchange, lFinal) then begin
Fields := tHttpHeaders.Create;
try
Fields.Add('x-checksum', Checksum);
// Retry False within the operation deadline; nothing was accepted.
Accepted := lFinal.TrySendTrailers(Fields);
finally
Fields.Free;
end;
end;
The new overloads still return iHttpUploadExchange. Query the additive
iHttpUploadTrailersExchange companion for TrySendTrailers. Final fields must
be a subset of the copied declared names; unused declared names may be omitted.
Names are normalized/deduplicated in first-seen order and separately bounded
at 16384 bytes including 32 bytes per name. The nonempty declaration is also
charged to the initial header budget. Fields follow section 2.3. Successful
admission copies them, closes the producer and returns True; it does not mean
delivery or acknowledgement. False means temporary pressure and retains
nothing. A dedicated terminal slot does not consume body-queue capacity.
Invalid fields, state or final payload length raise atomically, so an open
producer can correct an invalid section. An ordinary final TrySendBody sends
an empty section; a subsequent TrySendTrailers call is invalid. The old upload
overloads cannot generate trailers. Cancel, deadlines and owner destruction
retain the existing response/producer lifetime rules.
Trailer-enabled HTTP/1.1 uploads always use chunked framing without a wire
Content-Length. A declared body length is still enforced locally. The last
chunk and trailer lines remain pending transport work until fully sent; the
connection cannot be reused earlier. HTTP/2 and HTTP/3 retain their native
framing, HPACK/QPACK and per-stream cancellation. Applications may supply one
TE: trailers field to indicate response-trailer willingness. The common client
rejects other or duplicate TE fields before submission; HTTP/1.1 nominates TE
in Connection, while HTTP/2 and HTTP/3 emit no Connection field for it.
23.2 LOW-LEVEL HTTP/3 CLIENT ENGINE AND QUIC ADAPTER
--------------------------------------------------------------------------------
StreamSec.Http.Http3Client provides the transport-free tHttp3ClientConn.
StreamSec.Http.Http3QuicClient provides tHttp3QuicClient, an adapter over a
caller-owned tQuicClient. These are client connection engines. The server host
and plugin are documented in section 14 and QUICServer.txt.
Configure and start the QUIC client with certificate validation, the intended
server name and ALPN h3. Its transport parameters must permit at least three
peer unidirectional streams with usable receive credit. Budget retained QUIC
stream records for the complete connection lifetime: closed records remain
present, so include requests, the three local critical streams and admitted peer
streams. Configure HTTP/3 request limits consistently with that budget. The
application owns origin selection and certificate authorization for every
requested authority; the adapter does not authorize cross-origin connection
reuse or discover endpoints through Alt-Svc. For a high-level HTTPS client,
TsmHTTPSClient and TsmAdvancedHTTPSClient provide opt-in h3 discovery and the
common request/exchange API; see HTTPSClient.txt. The logical HTTPS origin
remains the authority and certificate identity when the UDP port changes.
Create tHttp3QuicClient with the QUIC client and an iHttp3ClientObserver. The
QUIC client, socket and TLS host must outlive the adapter. Calls are serialized
per connection; neither another thread nor an observer callback may reenter.
Pump takes the caller's monotone microsecond timestamp. It polls QUIC, starts
HTTP/3 only after authenticated h3 negotiation, dispatches stream input and
flushes pending output. Call it for socket readiness and QUIC.NextWakeup instead
of polling QUIC separately. Once Ready is true, StartRequest takes method,
scheme, authority, origin-form path, header fields and a TBytes body, and
returns the actual request stream ID. Each request ends its send direction when
its queued headers/body have been accepted by QUIC.
Requests and observer callbacks use tQpackFields from StreamSec.Http.Qpack. Each
field contains Name and Value as RawByteString HTTP octets and a NeverIndex
flag. Field names must be lowercase HTTP tokens; values must not contain
forbidden control octets or leading/trailing whitespace. Encode a Unicode value
into the appropriate HTTP octets deliberately; no locale or implicit UTF-8
conversion is applied by QPACK. Request control data uses ASCII URI octets,
including an already-encoded path. Connection-specific fields and conflicting
Content-Length values are rejected before opening a request.
The observer receives ResponseHeaders (including an informational flag),
ResponseData, ResponseTrailers, ResponseComplete, RequestFailed and
ConnectionFailed. ResponseTrailers fires only after a valid FIN and the
message's terminal/frame/content-length checks, immediately before
ResponseComplete. Its entire validated field list is retained within the
configured field-section and active-request metadata bounds while awaiting FIN;
failed or truncated messages produce no trailer callback. Initial and trailing
field sections remain distinct. Header arrays and body TBytes are shared
read-only values whose compiler-managed lifetime permits retention. Neither side may mutate their
elements through another alias. A caller needing mutable storage makes an
independent copy.
Array lifetime and flow-control credit are distinct. After processing received
body bytes, call ReleaseBody(stream ID, byte count) outside the callback. It
accepts at most the delivered, unreleased body bytes. Header/framing overhead
and discarded extension bytes are consumed separately by the engine. Slow body
consumption withholds credit and bounds in-flight response data. Limits also
bound queued request bytes, retained response body bytes, header blocks, decoded
field sections, request counts, peer streams and unproductive frames. The
adapter replenishes explicit MAX_DATA/MAX_STREAM_DATA credit; a blocked send
stays queued without borrowing future credit.
Cancel aborts an active request in both directions. The QUIC client exposes
StopReceive separately for general QUIC applications. Cancelling receive work
does not keep extending that stream's window: discarded in-flight data can
return connection credit, and RESET final-size accounting is released once. A
caller may still release body bytes retained before a reset. GOAWAY prevents new
requests, preserves eligible earlier responses and identifies requests the
server refused as retryable. A reset with H3_REQUEST_REJECTED likewise reports
retryability; unrelated transport failure does not grant replay permission
automatically.
QPACK supports static and dynamic field compression, literals and the shared
HTTP Huffman codec. Dynamic compression is opt-in; capacity and blocked-stream
allowance default to zero. Section 23.5 describes configuration and bounds.
Malformed instructions and field sections retain their QPACK errors. Push is
refused by default; section 23.6 describes explicit opt-in and consumer callbacks.
Ungranted push IDs fail with H3_ID_ERROR. Unknown extension frames and streams
are ignored within configured resource bounds. Critical-stream loss, misplaced
frames, malformed SETTINGS and invalid message framing retain their HTTP/3 error
codes.
23.3 INCREMENTAL HTTP/3 REQUEST BODIES
--------------------------------------------------------------------------------
The complete-body StartRequest overload keeps its existing behavior. The
overload with aEndStream = False leaves the request body open. It can include an
initial TBytes chunk. Call RequestBodyOpen(stream ID) to check whether further
writes are valid and RequestBodyCapacity(stream ID) for advisory body admission
space. Queries return False/zero for unknown or terminal uploads; stream ID zero
is valid. Zero payload capacity can still permit an empty final write when a
part slot is free.
TrySendBody(stream ID, chunk, aEndStream) accepts the entire chunk and optional
FIN, or returns False for temporary queue pressure. On False, retry the same
unchanged chunk after Pump makes progress, within the caller's operation
deadline. No part of a rejected chunk has been retained or counted. Invalid
state or length raises before admission. Empty non-final writes are no-ops. An
accepted final write, including an empty chunk, closes body admission exactly
once. Transport FIN emission can follow later as QUIC accepts the queued data.
Accepted const TBytes values remain shared immutable buffers. Replacing the
caller's variable releases its reference; changing shared elements is
prohibited. Create an independent buffer when mutable storage must be reused.
Pump and all writes remain serialized and nonblocking; consumer stream reads are
not invoked inside the engine. Both engine and adapter expose the open-body
StartRequest, RequestBodyOpen/Capacity and TrySendBody methods.
Content-Length, when supplied, must match the total accepted payload at FIN.
Oversized chunks and a short final write raise without accepting either bytes or
FIN, so the caller can correct the write. Open bodies without a declared length
omit Content-Length and use explicit FIN. TrySendTrailers(stream ID, fields)
admits a separately bounded terminal HEADERS section on an open request; it
uses the same field and byte policy as section 2.3 and validates the final
payload length before admission. CONNECT remains a separate capability. The high-level BeginUpload overloads provide known- and
unknown-length production on all three wires (section 23.1); BeginRequest and
Execute keep their complete-body signatures.
MaxBufferedSendBytes limits retained send buffers, including framing. A
partially sent managed array is charged at its full length until that part
drains or is dropped. QueuedBytes reports logical unsent bytes;
RetainedSendBytes reports the retained-buffer charge. QueuedSendParts is bounded
by the connection-wide 4096-part limit. Consumed entries are reclaimed
throughout a long upload. Fair scheduling rotates between streams with a bounded
send quantum; a busy upload cannot occupy every send opportunity indefinitely.
This HTTP queue budget is separate from QUIC's combined retained send/receive
budget. QUIC also retains accepted output for acknowledgement/retransmission.
Configure transport budgets and advertised receive credit together. A saturated
combined budget can reject incoming data even when the HTTP queue fits its own
limit; this API does not reserve a separate receive allowance in that budget.
The transport range budget must also accommodate ACK splitting of retained
sends. These transport resource limits are independent of the HTTP send-part
bound.
For QUIC-backed incremental production, the connection owner must leave receive
and header/control headroom. Before admitting a chunk, account for the
configured transport pool, Streams.BufferedBytes, Engine.RetainedSendBytes and
the candidate's framing, reserving outstanding advertised receive credit and
new-header space. Pause production and keep pumping while that allowance is
exhausted. The native fixture demonstrates this producer policy; automatic
transport admission with reserved receive/range capacity is supplied by the
high-level BeginUpload transport policy (section 23.1).
Response completion and request send completion are independent. A valid early
response is delivered immediately. If the peer stops the upload, no further body
writes are admitted. Cancelling an unfinished upload after the response
completes preserves that response and its receive-credit obligations.
ActiveRequests settles when both halves become terminal. Here, send completion
means data and FIN have been accepted by the supplied transport; QUIC wire
delivery and acknowledgement can follow later. Cancel is a no-op after both
engine halves are terminal and does not retract a tail already accepted into
QUIC at that point. A transport owner needing a later abort controls the QUIC
send half separately. No accepted request is automatically replayed.
Incremental bodies remain unavailable to 0-RTT admission; the explicit early
API accepts complete buffered requests (section 23.4). The standalone framing,
QPACK, Huffman and client state engines do not need TLS and are exercised
under FPC. Record-free TLS 1.3 and the QUIC packet/TLS bridge are also
qualified there; section 19 describes the remaining public endpoint scope.
23.4 EXPLICIT BUFFERED QUIC 0-RTT ADMISSION
--------------------------------------------------------------------------------
The low-level tHttp3QuicClient API can resume with an explicit caller-supplied
ticket. CaptureResumptionTicket captures the TLS credential together with the
authenticated QUIC transport parameters and HTTP/3 SETTINGS. Before QUIC.Start,
ConfigureEarlyData(ticket, now) checks that remembered context and configures
early admission. After QUIC.Start, check EarlyReady and call StartEarlyRequest
before the first adapter Pump or socket poll; flush QUIC output before reading
the server flight. EarlyReady is a query without startup side effects.
Ordinary Ready and StartRequest still require authenticated readiness. An early
request supplies its complete buffered body; incremental producers, request
trailers and streaming bodies do not run through this API. If a TLS ticket
notification precedes authenticated peer SETTINGS, retain a ticket clone until
the complete capture context is available.
On rejection, RequestFailed reports RequestRejected with aRetryable = False.
The adapter drops its old HTTP/3 protocol state and prepares fresh state for
later ordinary operations. It does not replay a request or call a
body producer again. The caller decides whether a new authenticated request
is appropriate. QUIC keeps increasing packet numbers and rejects ACKs covering
discarded early packets, so an old ACK cannot retire a later 1-RTT request.
Server acceptance requires TsmHTTPSv3.EnableEarlyData = True, TLS early-data
acceptance with the configured replay hook and an atomic ticket store, and a
stable application/QUIC context. Every registered protocol must implement the
optional iQuicAppProtocolEarlyData companion and provide a bounded, nonempty
context; missing or invalid context disables early acceptance for the endpoint.
Such a protocol must also create sessions implementing iQuicAppSessionEarlyData;
the host fails closed if accepted early input has no matching session companion.
EarlyDataPolicy remains a separate application decision, shared with HTTP/1.1
and HTTP/2 as described in section 2.1. Plugin Opened and input delivery still
wait for the authenticated handshake and current peer transport parameters.
The high-level HTTPS client and its automatic Alt-Svc path continue to use
fresh authenticated HTTP/3 requests. They do not silently cache tickets or
enable 0-RTT. The common streaming-body refusal applies even during unresolved
early provenance; conservative admission refusal does not falsely label a
wholly ordinary request as early.
23.5 DYNAMIC QPACK AND BLOCKED FIELD SECTIONS
--------------------------------------------------------------------------------
Configure TsmHTTPSv3.Limits.QpackTableCapacity and QpackBlockedStreams while the
host is inactive. Capacity accepts 0..1048576 bytes; blocked streams accepts
0..MaxActiveRequests. MaxQpackBlockedBytes is a positive per-connection budget
(default 262144 bytes) shared by retained encoded blocked headers and deferred
stream input. The unchanged zero defaults advertise static-only decoding.
A useful opt-in configuration is capacity 4096 with 16 blocked streams.
Low-level clients and servers take the same fields in their initialized limits
records. Always call InitHttp3ClientLimits or InitHttp3ServerLimits before
customizing a record. The common HTTPS client exposes corresponding next-
connection settings under Limits, documented in HTTPSClient.txt. These settings
bound reception; outbound compression also obeys the peer's authenticated
SETTINGS and local encoder bounds. A peer advertising zero capacity continues
to receive static/literal sections.
Incomplete encoder instructions are retained within a finite input budget.
Blocked HEADERS, later DATA/frame bytes and FIN remain ordered on that stream;
other streams can progress. The decoder publishes no partial field collection.
When required inserts arrive, ordinary HTTP validation and application admission
run before callbacks. Stream/count/byte exhaustion or malformed compression
fails with the appropriate protocol error. Cancellation, reset, close and
absolute header deadlines release retained blocked state. Trailer blocking has
its own absolute header-stage deadline; arriving fragments do not extend it.
Deferred wire bytes return QUIC receive credit so they cannot prevent encoder
stream progress. Replaying those bytes does not return credit twice. Encoder
and decoder instruction output precedes ordinary body output and has bounded
queue storage. Outbound admission either commits a complete prepared compression
section with its instructions, or uses a static/literal encoding. Referenced
entries stay pinned until acknowledged or cancelled; blocked references cannot
exceed the peer's allowance. No unbounded table or blocked-input mode exists.
Never-index fields remain literal. Authorization, Proxy-Authorization, Cookie
and Set-Cookie are also excluded from dynamic insertion. A connection's outbound
compression context is restricted to its first scheme/authority; fields for
other origins use static/literal encoding. This does not make shared application
credentials safe to disclose. Applications retain their authentication policy.
Each connection starts with empty tables, including resumption. Rejected early
data clears provisional compression and blocked state. Early output stays
static until fresh peer SETTINGS permits dynamic compression. The server ticket
context includes the new limits, so changing them refuses incompatible early
data. Generated informational/trailer output can use static sections; incoming
dynamic informational and trailer sections use the same bounded decoder.
23.6 OPTIONAL HTTP/3 SERVER PUSH
--------------------------------------------------------------------------------
Deprecated. Server push, on both the server and the low-level client, is
provided for completeness of RFC 9114 only. It remains an optional part of
HTTP/3, but no browser accepts it and widely used HTTP/3 servers do not send
it, so do not build new designs on it. To have a browser fetch related
resources early, send Link preload headers on the ordinary response instead.
The rest of this section describes the feature as it stands.
Server push has two independent permissions. Set TsmHTTPSv3.Limits.MaxPushes to
a positive lifetime allowance before activation, and the client must grant push
IDs. MaxPushes defaults to zero and accepts 0..1024. MaxActivePushes defaults to
8 and accepts 1..1024; the smaller effective allowance applies. Push IDs are
sequential, never recycled, and do not increase the ordinary request allowance.
No grant means no push, even if a handler queries the capability.
An inline shared handler can query iHttpResponsePush, declared in
StreamSec.Http.Server, without changing its existing iHttpResponse signature:
if Supports(aResponse, iHttpResponsePush, lPush) then
if lPush.TryPush('/style.css', nil, lPushed) then begin
lPushed.SetContentType('text/css');
lPushed.SendFile(lAuthorizedCssFile);
end;
lPush is an iHttpResponsePush, lPushed an iHttpResponse. Authorize the resource
for aRequest's actual client/session privileges before making this call. The
library does not infer that a resource is public from its path or GET method.
The child can use ordinary response content, owned stream/file sources,
generated trailers and deferred body-EOF trailers. It is not dispatched through
another router/session provider, so no extra application authorization or side
effects happen implicitly. No recursive push capability is offered on a child.
TryPush takes a path, an optional const tHttpHeaders collection and an out child
response. It copies promised fields and accepts only bodyless, credential-free
GET on the parent GET's exact HTTPS scheme/authority. No parent headers,
cookies or authorization are inherited. Invalid fields/paths raise; unavailable
local/peer allowance returns False with an explicit nil child and accepts
nothing. True reserves an intention, not delivery or acknowledgement. Configure
the child before the inline handler returns. Do not mutate retained aliases
later. The capability detaches at dispatch completion: retaining it after that
point, or after connection destruction, safely returns False/nil. HTTP/1.1,
HTTP/2 and worker request-streaming exchanges do not expose this companion.
MaxPushBufferedBytes defaults to 262144 and must be positive. On the server it
bounds retained promised-request metadata. Encoded frames, response memory and
file output additionally use the existing send, per-connection and plugin-wide
response budgets. Parent and child output share those budgets. A file is read
in bounded chunks as QUIC accepts data. Pending uni-stream credit has a positive
absolute PushTimeoutMSec budget (default 10000 ms); more peer grants do not
extend it. Enabling push requires owner work/timer scheduling even if both
ordinary input timeouts are disabled. The stock QUIC host supplies that service.
A source failure resets the affected push without emitting a successful FIN.
The promise is queued on the parent before the corresponding server uni-stream
is sent. A push waits for stream-count credit after the three critical streams
open. CANCEL_PUSH, STOP_SENDING, expiry, GOAWAY and transport loss retire the
appropriate work and sources; ordinary responses remain independent. Generated
push promises/responses currently use static QPACK. Received dynamic push
sections use the connection decoder, including bounded QPACK blocking and
feedback. This does not change dynamic encoding of ordinary response headers.
A low-level client opts in by setting initialized tHttp3ClientLimits.MaxPushes
before constructing tHttp3ClientConn/tHttp3QuicClient and implementing the
optional iHttp3PushObserver on its ordinary observer. The constructor refuses a
positive allowance without that companion. It grants one finite ID range only
after ordinary authenticated Start; early Start does not restore a grant.
Server push is not available from early parent requests. Rejected early state
cannot revive push IDs, and server limits participate in the resumption context.
PushPromised(request ID, push ID, const fields) decides acceptance after complete
validation. False cancels the push. PushHeaders, PushData, PushTrailers,
PushComplete and PushFailed are separate from ordinary response callbacks.
ReleasePushBody(push ID, count) returns consumed body credit outside callbacks;
CancelPush cancels a known push. BeginPushDrain sends a nonincreasing push-ID
GOAWAY boundary. Neither callback arrays nor managed TBytes lifetime return
receive credit automatically. Calls/callbacks are serialized and cannot reenter.
The QUIC adapter forwards those operations and exposes NextWakeup(nowMicros,
out deadline), combining QUIC wakeups with application push expiry. Standalone
engine owners can query NextPushDeadline(out tickMS) and must keep driving Pump.
A push stream can arrive before its promise. Encoded input uses a finite pool,
with geometric growth charged by retained capacity. In the client,
MaxPushBufferedBytes includes that input and promised-field history retained
until connection close. MaxActivePushes bounds unresolved/accepted pushes.
PushTimeoutMSec is an absolute client budget through validated push FIN; no
fragment, body progress or QPACK insert extends it. Replayed buffered input
returns no duplicate transport credit. Received fields, body bytes and trailers
retain their separate existing budgets. Duplicate promises must match ordered
name/value octets exactly; a second stream using the same ID is an error.
Cancellation can precede reordered promises/streams and cannot be undone by them.
A low-level observer owns any reuse or caching decision and the applicable HTTP
cache rules. No push becomes an ordinary exchange, populates a cache, changes
cookies, installs Alt-Svc or triggers a replay automatically. Use suitable cache
directives for personalized responses. The common high-level HTTPS client keeps
refusing push; it does not silently introduce a push cache or new callbacks.
--------------------------------------------------------------------------------
24. SHARED SERVER REQUEST-BODY STREAMING
================================================================================
24.1 OPT IN THROUGH THE EXISTING ROUTER
--------------------------------------------------------------------------------
Implement iHttpStreamingRequestHandler and wrap it with
NewHttpStreamingHandler from StreamSec.Http.Streaming. The result is an
iHttpRequestHandler registered with the existing AddHandler/AddPrefix methods.
Assign that same router and adapter to TsmHTTPSv1dot1, TsmHTTPSv2 and
TsmHTTPSv3; no wire-specific application handler is needed. Ordinary
handlers/events still receive complete rewound Body streams with their
original callback lifetime. Route resolution happens once after valid initial
headers; exact paths and prefix precedence are unchanged.
BeginStreaming(Head, Admission, Exchange) runs under the connection gate and
must return promptly. Return True only after a bounded application queue has
retained Exchange for a worker. Return False without retaining a job to send
the prepared refusal response (503 by default). An exception produces 500. The
library supplies no worker threads. A legacy custom wire lacking the new
capabilities refuses the opt-in adapter rather than presenting a partial Body.
Head is retained immutable metadata: method/path/query/version, initial
ordered Headers, eagerly parsed Cookies, address, security/protocol facts and
optional iHttpRequestOrigin. It has no Body or live session/transport. Header
collections are owned, read-only views; never free or change them. Retaining
Head also pins its job quota. Admission exposes Session, Connection and the
prepared Response only during BeginStreaming. Capture ordinary authorization
values there for the job; do not use live default session/connection objects
from workers.
A configured SessionProvider must also implement
iHttpStreamingSessionProvider. Its AcquireStreamingSession runs once against
Head and the prepared response, before the factory, preserving its
cookies/headers. A legacy-only custom provider makes that streaming route
unavailable (503); authorization is never silently bypassed. Complete handlers
keep the old provider contract.
For an upload route, permission to omit Content-Length can depend on the
client's authenticated privileges. Check the server-selected session during
BeginStreaming, before retaining Exchange or enqueueing a worker. For example:
function tUploadHandler.BeginStreaming(const aHead: iHttpRequestHead;
const aAdmission: iHttpRequestAdmission;
const aExchange: iHttpServerExchange): Boolean;
var
lSession: iHttpSession;
lGrant: Variant;
lAllowed: Boolean;
begin
Result := False;
if not aHead.Headers.Exists('content-length') then
begin
lAllowed := False;
lSession := aAdmission.Session;
if lSession <> nil then
if lSession.Exists('allow-unknown-upload') then
begin
lGrant := lSession.Values['allow-unknown-upload'];
if VarType(lGrant) = varBoolean then
lAllowed := Boolean(lGrant);
end;
if not lAllowed then
begin
aAdmission.Response.SetStatus(403, '');
Exit;
end;
end;
Result := fUploadQueue.TryEnqueue(aExchange);
if not Result then aAdmission.Response.SetStatus(503, '');
end;
Use Variants for VarType/varBoolean. fUploadQueue denotes the application's
bounded nonblocking queue; it retains the exchange only when TryEnqueue
succeeds. The nested checks work with complete Boolean evaluation enabled.
Only a Boolean True grants permission: nil sessions, missing keys, False,
strings such as 'True' and numeric values fail closed. A trusted application
session provider must derive this grant from verified credentials or another
server-owned authorization decision. A client-supplied privilege header does
not grant it. Apply the route's ordinary authorization independently to every
upload; this example governs permission to omit its length.
This conservative upload policy treats every absent Content-Length as unknown,
including an empty HTTP/2 or HTTP/3 request. A client using the known-length
path can send Content-Length: 0. Initial framing fields have already been
validated. Declaring zero never makes later payload part of that request:
HTTP/2 and HTTP/3 reject a length mismatch; HTTP/1.1 parses following bytes as
the next request, whose framing and authorization are checked independently.
A denial returns the prepared 403 without a worker, body Feed or 100 Continue.
The framework releases temporary job/ring reservations; bounded transport
staging may already contain bytes, so this does not promise that no network
bytes arrived. Ordinary complete-body handlers run after buffering: use the
streaming adapter when authorization must precede body consumption.
Permission to omit a length never permits unlimited resources. Keep finite
MaxBodyBytes, BufferBytes, TimeoutMSec and MaxActiveJobs on the adapter. These
limits are per adapter, not automatic dynamic per-client quotas; separate
adapters or an application admission/quota service can impose stricter classes.
24.2 WORKER READS, VALIDATION AND RESPONSE SUBMISSION
--------------------------------------------------------------------------------
Allocate a TBytes destination and call:
lState := lExchange.Read(lBuffer, lOffset, lCount, lRead);
The buffer is var because the method may change the requested elements. It is
never resized or retained. Read validates a positive allocated range before
consuming bytes and explicitly writes lRead on every outcome:
hsrrData lRead > 0 copied bytes; consume them, then read again.
hsrrPending lRead = 0; no bytes available yet, input remains open.
hsrrComplete lRead = 0; validated message EOF and the ring is empty.
hsrrFailed lRead = 0; input failed/rejected/cancelled; never treat as EOF.
Read is nonblocking. WaitForBody(milliseconds) is worker-only; zero polls.
True means another Read can observe data or terminal state, not that the body
succeeded. False means timeout. Failed/FailText and BodyComplete expose state.
The queue copies const wire input into a fixed TBytes ring before callbacks
return. The compiler manages array lifetime; release of receive credit follows
successful Read, independently of array references.
Every byte consumed before hsrrComplete is provisional. Commit application
side effects only after valid EOF; a later length/framing/trailer error may
invalidate an earlier prefix. Trailers is a separate read-only ordered
collection published only after successful terminal checks. An earlier empty
view stays empty/alive with its exchange. Failure/cancellation discards unread
bytes and wakes readers.
One worker owns Response mutation after admission. TryComplete returns True
only after validated EOF and a drained ring, atomically sealing and queuing
that prepared builder. TryReject queues an early final response and stops
input. Its deliberate rejection makes Read return hsrrFailed, while Failed
remains False and FailText records rejection. TryComplete returns False while
input is pending or unread; both submission methods refuse sealed, failed or
detached exchanges. Do not mutate a sealed builder or its owned source through
any alias. These bools
promise submission, not network delivery or output-memory admission: the wire
applies its existing response limits and may refuse before exposing headers.
Cancel aborts unfinished work and is idempotent. During paced response output
the owner still observes cancellation until the entire response and its HTTP/2
or HTTP/3 end-of-stream marker have been accepted by the transport. Later wire
transmission/acknowledgement may follow. A peer reset, timeout or component
shutdown detaches the owner bridge, releases payload storage and wakes
workers; it never joins arbitrary application workers on an I/O thread.
Retained immutable metadata remains owned by the exchange.
24.3 LIMITS, BACKPRESSURE AND WIRE BEHAVIOR
--------------------------------------------------------------------------------
Configure the limits-taking adapter factory with InitHttpStreamingLimits:
MaxBodyBytes 8 MiB cumulative decoded Int64 payload, checked separately
BufferBytes 64 KiB fixed copied ring capacity per admitted request
TimeoutMSec 30000 finite absolute request/job deadline
MaxActiveJobs 64 per adapter across shared protocols/connections
The streaming body cap is independent of the legacy complete-body BodyBytes.
It can exceed a 32-bit buffer index because the entire body is never
assembled; the common structural ceiling is 2^60-1. All four limits must be
positive. The job slot remains charged until the last exchange/head reference
is released, including a terminal job retained by application code. Payload
storage is freed earlier on failure or validated EOF+drain. A bounded
application worker queue is still required; keeping every completed head
indefinitely exhausts job admission.
Existing connection/global body budgets reserve actual ring capacity before
factory invocation. HTTP/1.1 additionally reserves bounded decrypted-output
and HTTP ingress staging. Metadata has separate parser/field-section bounds;
neither payload credit nor the cumulative body count includes
headers/trailers. Held storage counters for opt-in routes count these
reservations, rather than all bytes that have ever passed through a worker. A
large declaration or announced chunk does not reserve the complete payload.
HTTP/1.1 accepts Content-Length or strict chunked input. When the ring fills,
receive drain/rearm parks; bounded already decrypted/pipelined tails are
retained until owner work can proceed. The next request waits for the current
response. Null TLS compression and supported receive-flow/work companions are
required. An early final answer sends its paced body, then closes the
connection, since the unfinished request framing cannot safely be reused.
HTTP/2 promptly returns connection DATA credit while withholding stream
payload credit until Read; padding is credited separately. The TLS host must
confirm supported work/receive-flow companions and null compression. The ring
covers the actual advertised stream allowance (normally 65535). Reserving that
allowance before admission lets another nonempty request/control stream
progress while one consumer is stopped. Early rejection sends the response
through END_STREAM before RST_STREAM(NO_ERROR); it does not discard an answer
still being paced.
HTTP/3 likewise withholds DATA credit until Read and promptly consumes parsed
framing/control bytes. The QUIC host supplies actual receive-window/backing
queries, and H3 prepares bounded send admission before opening critical
streams, preserving legal receive space in the shared pool.
Limits.SendWindowBytes controls that reservation (default 65536);
offered-policy refusal closes before SETTINGS. See section 20.2 for its
memory and throughput costs. The ring must
cover the advertised request-stream allowance (normally 65536). The receive
ledger counts all observed unfinished request-stream allowances, including
refused/stopped requests, and leaves three peer-uni windows for control/QPACK.
STOP_SENDING and response completion do not revoke a grant: its promise
remains charged until the transport and HTTP have both observed input
termination and no held payload remains. Early rejection preserves response
output/FIN. If observed grants exceed the reserved headroom, the connection
fails with H3_EXCESSIVE_LOAD before a new worker factory runs. Other
unsupported/unsafe transport configurations refuse streaming before the
factory.
This headroom protects cooperative observed/admitted requests. Existing QUIC
parameters grant receive credit before HTTP can identify every stream. Unseen
out-of-order input or a peer withholding permitted input still follows the
existing QUIC flow-control, pool and connection-timeout bounds; universal
critical-stream progress is not promised against those cases.
All three wires reject streaming early-data provenance, including the field
Early-Data: 1, with 425/no-store before provider/factory side effects. Valid
100-continue is answered only after admission, while unknown/malformed expectations get
417. A final refusal already queued during admission suppresses 100. Streaming
uses separate owner work and absolute deadlines; slow progress cannot extend
them. TLS provider linking is preserved. FPC qualification and the remaining
public endpoint limitations are described in section 19.