Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

HTTPS client notes (HTTP/1.1, HTTP/2, HTTP/3)

HTTPS CLIENT: HTTP/1.1, HTTP/2 AND HTTP/3
========================================

TsmHTTPSClient owns its TLS configuration component. TsmAdvancedHTTPSClient
uses an application-selected TLSServer; nil selects the existing GlobalServer.
Both expose the same request, response and asynchronous exchange API. Configure
trust and client identity using the existing TLS engine and callbacks.

HTTP/3 DISCOVERY
----------------

HTTP/1.1 and HTTP/2 remain the default. Enable discovery before connecting:

    Client.Protocols := [hcpHttp11, hcpHttp2, hcpHttp3];
    Client.TLSServer.LoadRootCertsFromFile('trusted-ca.der');
    Response := Client.Get('https://www.example.com/api/status');
    try
      // Response.StatusCode, Response.Headers and Response.Body
    finally
      Response.Free;
    end;

A new client bootstraps over TCP/TLS. Authenticated final response heads can
advertise a same-host h3 alternative through Alt-Svc. The next eligible request
tries that alternative when existing exchanges and body-credit obligations are
quiescent. Requests keep the same URL, certificate identity, SNI and logical
Host/:authority, including a nondefault origin port. The advertised UDP port
changes only routing. QUIC uses the library's existing record-free TLS 1.3 and
cryptographic providers, with ALPN h3. TCP continues to offer only its existing
ALPN protocols. A protocol set containing h3 alone is refused; the legacy empty
set keeps its no-ALPN TCP behavior.

    Response := Client.Get('https://www.example.com/api/next');
    try
      // Client.Wire is hcwHttp11, hcwHttp2 or hcwHttp3.
      // Client.NegotiatedProtocol and Secure describe the selected connection.
    finally
      Response.Free;
    end;

No request is resent just to discover HTTP/3. A failed QUIC setup can fall back
to authenticated TCP before request submission. Http3AttemptTimeout defaults
to 1000 milliseconds; ConnectTimeout and DeadlineTick can shorten this budget.
Once HTTP/3 accepts a request, connection loss, timeout, reset or GOAWAY is
reported through the exchange; the client does not automatically replay it.
Retryable remains advice to the application, not permission to repeat an
operation. HTTP statuses, including 421, remain responses. A 421 retires the
selected alternative for later connection selection without retrying the request.

HTTP/3 SERVER PUSH
-----------------

The common high-level client continues to refuse server push and grants no push
IDs. Push responses do not enter ordinary exchanges, the Alt-Svc cache, a cookie
store or an implicit HTTP cache. Push support in the low-level HTTP/3
client/QUIC adapter (finite initialized push limits and an explicit
iHttp3PushObserver) is deprecated: widely used HTTP/3 servers do not send push,
so do not build new designs on it. HTTP.txt section 23.6 documents its
acceptance callbacks, separate body credit, cancellation, expiry and combined
wakeup API.

HTTP/3 QPACK LIMITS
------------------

Limits.Http3QpackTableCapacity defaults to 0 and accepts 0..1048576 bytes.
Limits.Http3QpackBlockedStreams defaults to 0 and accepts 0..100 streams.
Limits.Http3MaxQpackBlockedBytes defaults to 262144 and must be positive.
These are captured when the next HTTP/3 connection is created; changing them
does not reconfigure an existing connection. Assigning the Limits object copies
them too. Zero capacity/blocked allowance preserves static-only defaults.

For example, set capacity to 4096 and blocked streams to 16 before connecting.
The blocked-byte budget bounds encoded HEADERS and deferred stream input;
decoded header/body budgets and operation deadlines remain separate. Requests
waiting for QPACK inserts do not expose partial headers. Other streams and
critical compression feedback can progress. Cancellation releases the blocked
request state. Outbound compression obeys fresh peer SETTINGS, avoids inserting
credential/cookie fields, and keeps different origins out of the dynamic context.
Received trailers remain in Response.Trailers, separate from Response.Headers.
The high-level client still admits authenticated requests only.

CACHE AND ORIGIN RULES
----------------------

Each component starts with a private cache for at most 64 origins. Discovery
supports same-host h3 routes and the omitted-host form h3=":443". Unsupported
protocols/cross-host routes are ignored. Complete advertised field sets are
bounded and validated before caching. A valid new field set replaces the old
origin entry; clear invalidates it. Missing fields preserve it. Informational
heads, trailers, plaintext and 421 responses cannot install alternatives.

Freshness uses ma (default one day, capped at one day), Age, response Date and
request/response delay, followed by a monotone expiry clock. ma=0 cannot create
a fresh route. A failed route has a bounded 30-second suppression period that
identical advertisements do not reset. Stale failures/rejections cannot remove
a newer cache generation. Expiry/clear prevent fresh connections from using the
old entry; they do not abort existing authenticated connections.

ClearAltSvcCache clears routes and pending older discovery updates. Use it when
network or trust configuration changes. Changing the TLS engine invalidates the
component's discovery context and gives it a fresh private cache. Other users
of an explicitly shared cache retain their entries. Configure the engine before
assigning a shared cache for its trust context. A deliberately different ServerName or a TLS
configuration callback authenticating another name keeps its existing TCP
behavior and disables automatic discovery for that origin.

An application can assign the runtime AltSvcCache interface to several clients
that use the same trust/security context. Assign nil while disconnected to
restore a fresh private cache. Custom implementations synchronize their state,
respect the declared origin/generation contract and do not reenter client
lifecycle methods from cache operations. No process-global or persistent cache
is created. The standalone tHttpClient and ephemeral REST transport factories
retain their existing behavior; this component cache is not implicitly shared
with them. Discovery reads Alt-Svc response fields only: HTTP/2 ALTSVC frames
and DNS HTTPS/SVCB records are not used.

REQUESTS, STREAMING AND LIFETIME
--------------------------------

Execute follows the existing redirect policy. It preserves the logical URL,
refuses HTTPS-to-HTTP downgrade and strips Authorization, Proxy-Authorization
and Cookie when the logical origin changes. BeginRequest returns iHttpExchange
without following redirects; WaitForHead and Read expose progress, timeout,
completion and failure separately. HTTP/2 and HTTP/3 support concurrent exchanges.

Read returns receive credit after consuming bytes. Managed TBytes lifetime is
separate from credit. Bodies and metadata retain their configured limits.
ReadAll assembles a bounded complete body; use Read to consume large responses
gradually.

READ EVERY BODY TO ITS END, OR DISCARD IT. While any octet of its body is
unread, a completed response keeps that body in memory and the client keeps
the exchange, even after the application has dropped its last reference to
it; reading the last octet ends this, without a further Read for the end. On HTTP/2 and HTTP/3 the unread octets also keep their share
of the connection's receive window - 4 MiB for an HTTP/2 connection - so
enough unread bodies stall every later response on that connection until
Disconnect, and with hcpHttp3 the client does not move to HTTP/3 while it
holds such an exchange. Cancel does not change this for a completed
response: it keeps the response readable, body included. Call DiscardBody on
every exchange whose body you do not want:

  if not Exchange.WaitForHead(5000) then
    Exchange.Cancel
  else if Exchange.Response.StatusCode = 200 then
    Body := Exchange.ReadAll(5000)
  else
    Exchange.DiscardBody;   // an error page nobody reads

DiscardBody drops what has not been read, returns its credit and lets the
exchange go; status, headers and trailers stay readable, and Read then
reports the end of the body. On a response that is not complete it cancels
first, as Cancel does, and Read then reports cHttpReadFailed.

Cancel affects its exchange. A synchronous body-read failure also cancels its
exchange. DeadlineTick bounds both connection setup and later HTTP/3 I/O.
A completed unread exchange can outlive the client
and retain its response/body; an incomplete exchange is detached and failed on
shutdown. Credit from an old exchange cannot reach a replacement connection.

Disconnect stops and joins the pump before freeing the selected backend. Owners
of a referenced TLS engine must disconnect/quiesce associated clients before
freeing that engine. A late component-removal notification provides defensive
cleanup; it does not make concurrent destruction during cryptographic operations
safe. Keep callbacks bounded and follow the existing client lifecycle rules.

ConfigureLayer/OnConfigureLayer and handshake/pinning callbacks still run before
HTTP/3 application streams. The owning/reference TLS tiers and intentional
provider imports are preserved. QUIC 0-RTT is disabled and initial connections
use fresh handshakes. Cross-origin connection coalescing, shared QUIC ticket
caches and active-migration APIs are not provided.

HTTP/2 RESPONSE HEADS, TLS VERSION AND CONNECTION ERRORS
--------------------------------------------------------

HTTP/2 response heads are checked before anything of them reaches the
application. Each head, an interim 1xx as well as the final one, must start
with exactly one :status field whose value is three ASCII digits from 100 to
599, so '0200', ' 200' or '2x0' is not a status. 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 the
stream with PROTOCOL_ERROR; none of its fields reaches Response.Headers. The
header block is decoded first in every case, so the connection and its other
exchanges carry on.

HTTP/2 needs TLS 1.2 or later (RFC 9113 s9.2). If a server selects h2 on an
older version - possible only when the process-wide
StreamSec.Mobile.TlsConst.VersionMinorMin has been lowered below its TLS 1.2
default (TLS.txt) - 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. HTTP.txt section 6 describes
the server side.

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

RECEIVED RESPONSE TRAILERS
--------------------------

tHttpResponse.Trailers is a response-owned tHttpHeaders ordered multimap,
separate from initial Headers. Duplicates, empty values and arrival order are
preserved. Before successful response completion it returns a stable empty
view. WaitForHead or reading part of the body does not publish a partial list.
After Read reaches successful EOF, or ReadAll/Execute succeeds, fetch Trailers
again to read the complete validated section. A view retained before completion
stays empty and alive until the response itself is freed.

Treat both collections as read-only and never free them. Completed trailers
have the same response lifetime as Headers and remain available after Cancel,
client destruction or cancellation of an independent pending upload. An
incomplete, truncated, cancelled or invalid response does not expose partial
trailers. A response with no trailers has an empty collection.

BEHAVIOUR CHANGE: the common HTTP/2 and HTTP/3 clients no longer append trailers
to Headers. Use Trailers explicitly, even when an initial field has the same
name. Header conveniences, redirects, authentication and Alt-Svc discovery use
only initial Headers; a trailing Alt-Svc field cannot install an alternative.
The standalone HTTP/1.1 tHttpClient also retains valid chunked response
trailers.

All wires validate fields and reject names affecting framing, routing,
connection handling, authentication or payload interpretation, including names
nominated by any initial Connection field. Retained names and values charge
wire bytes plus 32 bytes per field against the existing metadata bound. These
limits are separate from body bytes. HTTP/1.1 requires exact CRLF and validates
raw values before trimming only outer SP/HTAB. HTTP/2 and HTTP/3 retain their
wire-specific field rules. The low-level HTTP/3 ResponseTrailers observer fires
only at validated FIN, immediately before ResponseComplete.

Generated request trailers use the producer companion below. Shared server
response generation uses iHttpResponseTrailers (HTTP.txt section 2.3). Shared server
handlers can query optional iHttpRequestTrailers for a complete received request
section; HTTP.txt section 2.2 describes that contract.

STREAMING UPLOADS
-----------------

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. Trailer-enabled overloads add a separate final section, as described below.
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, trailers 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 through the separate optional iHttpRequestTrailers interface;
forbidden or malformed trailers are rejected. The client upload API generates
no chunk extensions. Trailer-enabled overloads can generate request trailers.

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.

The lower-level tHttp3ClientConn and tHttp3QuicClient also expose incremental
immutable-chunk writes, including unknown-length HTTP/3 bodies; see HTTP.txt.

The HTTP/3 adapter and public client target Delphi XE3 through 13. Record-free
TLS 1.3 and the QUIC packet/TLS bridge have also been qualified with FPC 3.3.1
on native Linux64 and big-endian MIPS/o32 under QEMU in WSL. Full public FPC
client qualification remains incomplete because of separate backend and
runtime limitations. The FPC build excludes legacy DES imports; FPC stDES
support for legacy encrypted files remains a separate backlog item. TLS 1.3
and QUIC do not require DES/3DES. The remaining TLS providers stay linked.
Discovery and common uploads are acceptance-tested; upload admission over HTTP/2
and over pure QUIC is tested separately.

GENERATED REQUEST TRAILERS
--------------------------

Use the additional BeginUpload overload with an explicit list of trailer names:

  Upload := Client.BeginUpload('POST', URL, Headers, ['x-checksum']);
  // Known length: BeginUpload('POST', URL, Headers, Length, ['x-checksum'])

Send body chunks with TrySendBody(Chunk, False). Compute the final fields as the
producer reads its source, then query iHttpUploadTrailersExchange with Supports
and call TrySendTrailers(Fields). Fields is a tHttpHeaders collection owned by
the application; successful admission copies its entries. Empty sections are
valid, and unused declared names may be omitted. Fields outside the declared
set, forbidden fields, malformed values and final length mismatches raise
without admission. Correct the fields and retry while RequestBodyOpen is True.
An ordinary final body write sends an empty section; trailer writes after any
final admission are invalid. Old BeginUpload overloads do not opt in.

True closes the producer without promising delivery. False is temporary pressure
and accepts nothing; retry under the operation deadline. The bounded terminal
slot is independent of payload-queue capacity. Names are lowercase/deduplicated
in first-seen order. Section/declaration metadata is bounded at 16 KiB including
32 bytes per entry, and encoded terminal storage at 32 KiB. Peer limits may be
smaller. Duplicates, order, empty values, interior HTAB and raw high octets are
preserved. Strings must contain only single-octet characters; non-octet Unicode,
forbidden controls, DEL and leading/trailing SP/HTAB are rejected. Choose fields
whose definitions permit trailer use (HTTP.txt sections 2.3 and 23.1.1).

HTTP/1.1 trailer intent selects chunked framing before the initial head, also
for known-length bodies; the declared payload count remains locally enforced.
The final zero chunk and trailer section remain pending until sent, preventing
premature connection reuse. HTTP/2 uses terminal HEADERS and HTTP/3 uses
terminal HEADERS followed by FIN; an empty field list uses ordinary FIN. Cancellation, response preservation, owner
lifetime and the existing TLS provider linking retain their contracts.

The common client accepts one TE: trailers request field and rejects other or
duplicate TE fields before submission. HTTP/1.1 nominates it in Connection;
HTTP/2 and HTTP/3 never emit that connection-specific field. Optional response
trailers do not require TE and may be discarded by an intermediary.

Generated trailers are qualified by their own acceptance tests.