Feature notes: HTTPS application layer notes (HTTP/1.1, h2, h3)
iHttpSessionProvider is declared below the two it takes as arguments would otherwise allow, because it belongs with iHttpSession rather than at the far end of the unit.
(no public members)
(no public members)
WHETHER AN HTTP/3 ENDPOINT IS READY, as the TCP components ask it before advertising it (HTTP.txt section 16.3). TsmHTTPSv1dot1 and TsmHTTPSv2 call TryGetPort for each response they may add Alt-Svc to: True, with the UDP port, while the endpoint accepts HTTP/3 connections - they send h3=":port"; False, with aPort 0, otherwise - they send Alt-Svc: clear. An exception counts as False. TsmHTTPSv3 implements it and an application never calls it; implement it only for an alternative-service source of your own. It is called on the TCP connections' I/O threads, several at once, and the TCP components keep it after the source component is gone: make it thread-safe and quick, answer False once the source has stopped or been freed, and never call into a component from it.
function TryGetPort(out aPort: Word): Boolean;
IMPLEMENTED BY A COMPONENT THAT CAN BE ASSIGNED TO AltSvc.Source on TsmHTTPSv1dot1 / TsmHTTPSv2; TsmHTTPSv3 is the one this library provides. Assigning Source (with the TCP listener inactive) calls AltSvcEndpoint once and keeps the endpoint it returns; after that the TCP components ask only the endpoint, never the component. A component without this interface, or one that answers nil, makes the assignment raise.
function AltSvcEndpoint: iHttpAltSvcEndpoint;
THE TRAILER FIELDS THE CLIENT SENT AFTER THE REQUEST BODY, kept apart from Headers (HTTP.txt section 2.2). Reach them from a handler with Supports(aRequest, iHttpRequestTrailers, lTrailers); this library's requests support it on all three wires, and Trailers is empty when none arrived. A request that does not support it has none to offer. By the time the handler runs the section is complete and has passed the trailer policy, so it never holds framing, routing or authentication fields. Like the request, Trailers is valid only during the handler call: read-only, owned by the request, never free it. A streaming handler reads iHttpServerExchange.Trailers instead.
function GetTrailers: tHttpHeaders;
property Trailers: tHttpHeaders read GetTrailers;
THE ORIGIN THE REQUEST WAS ADDRESSED TO, as the wire carried it rather than as the Host field reads. The TCP components use it to decide on Alt-Svc; a handler reaches it with Supports(aRequest, iHttpRequestOrigin, lOrigin), and a streaming handler the same way on its iHttpRequestHead. Scheme is 'https' on HTTP/1.1, and on HTTP/2 and HTTP/3 the :scheme as sent. Authority is the one Host field on HTTP/1.1, and on HTTP/2 and HTTP/3 the :authority (or Host, when there is no :authority). Both are as received: compare an authority with HttpCanonicalOriginAuthority, not with =. On HTTP/1.1 and HTTP/2 Authority is '' when the request was ambiguous - two Host fields, Host and :authority disagreeing - and both are '' for an HTTP/1.1 absolute-form target. HTTP/3 refuses a request with an empty :authority or Host, or with copies that disagree, before any handler sees it, and reports the one value of copies that agree. Treat '' as unknown, never as the default host. Like Host it is client-supplied: route on it, do not authenticate on it.
function GetScheme: string;
function GetAuthority: string;
property Scheme: string read GetScheme;
property Authority: string read GetAuthority;
THE COOKIES THE CLIENT SENT, parsed out of the Cookie request field(s) per RFC 6265 section 4.2.1. Read-only: these are what arrived. Setting a cookie is a response concern - emit a Set-Cookie field with Response.Headers.Add, which APPENDS, rather than SetHeader, which would replace the previous one.
NAMES ARE CASE-SENSITIVE, unlike header names. That is not an oversight and not a house choice: RFC 6265 gives cookie names no case-insensitive comparison, browsers treat 'SID' and 'sid' as two different cookies, and folding them here would silently merge two cookies a client deliberately kept apart. If you look up 'sessionid' you will not find 'SessionID'.
VALUES ARE RAW. No percent-decoding, no base64, no unquoting: a value the client wrapped in DQUOTEs keeps them. Cookie values carry whatever encoding the application that set them chose, and guessing is how a value gets corrupted. Decode what you wrote, the way you wrote it.
NOTHING HERE IS TRUSTWORTHY. A cookie is client-supplied input that the client can set to any value at all. Validate it exactly as you would a query parameter, and never let one carry an authorization decision on its own - a session identifier is only as good as the check you do against your own store.
Repeats are preserved in arrival order, so a client that sent the same name twice yields two entries; ByName answers the FIRST. On HTTP/2 the several cookie fields RFC 9113 section 8.2.3 permits have already been joined, so both wires look the same here.
function GetCount: Integer;
function GetName(aIndex: Integer): string;
function GetValue(aIndex: Integer): string;
function GetByName(const aName: string): string;
function IndexOf(const aName: string): Integer;
function Exists(const aName: string): Boolean;
property Count: Integer read GetCount;
property Names[aIndex: Integer]: string read GetName;
property Values[aIndex: Integer]: string read GetValue;
property ByName[const aName: string]: string read GetByName; default;
PER-SESSION STATE AN APPLICATION OWNS: somewhere to put what was established earlier in a session and should not have to be re-established per request - the identity a client proved, a decoded authorization, a shopping basket.
THE SESSION SUPPLIED BY DEFAULT LASTS EXACTLY AS LONG AS THE CONNECTION. It is created when the connection is, seen by every request that arrives on it, and destroyed with it. Read that as the guarantee it is: state stored here cannot leak to another client, because another client is on another connection and gets another session. Read it also as the limit it is - it is NOT a browser session:
* An HTTP/2 client uses one connection per origin, so in practice one session per client for as long as it stays connected.
* An HTTP/1.1 browser opens SEVERAL connections to the same origin and replaces them as they time out, so it will see several sessions and lose them without warning.
* Nothing survives a reconnect, and nothing is shared between two servers.
So: cache per-connection work here freely; do not put anything here that has to persist, and do not treat "the session already says the user is logged in" as a substitute for a check you would otherwise do. If you need continuity across connections, implement iHttpSessionProvider (below) over your own store, which is exactly what that seam exists for.
THREADING. One connection is never dispatched twice at once, so the default per-connection session needs no locking of its own and none is taken. That guarantee belongs to the DEFAULT implementation, not to the interface: a provider that returns one session to several connections has made it shared state, and making it thread-safe is then that provider's job.
Values are Variants, so anything a Variant holds goes in. Storing an interface or object reference is allowed and keeps it alive for the session's lifetime; what a Variant cannot do is tell you it holds the type you expect, so read back with VarType or with the typed accessor you wrote yourself.
function GetValue(const aName: string): Variant;
procedure SetValue(const aName: string; const aValue: Variant);
function GetID: string;
function Exists(const aName: string): Boolean;
procedure Remove(const aName: string);
procedure Clear;
property Values[const aName: string]: Variant read GetValue write SetValue; default;
property ID: string read GetID;
THE SEAM. Assign one to TsmHTTPSv1dot1 / TsmHTTPSv2.SessionProvider and it, not the connection, decides which iHttpSession a request sees. That is how a cookie-keyed store, a shared cache, or anything else with a lifetime of its own gets in without iHttpSession changing shape - the interface a handler writes against stays the one above whichever way the state is kept.
AcquireSession is called ONCE PER REQUEST, before the handler, on the I/O thread that will run it. Whatever it returns is what Request.Session answers for that request. It may return the connection session it was handed (including for requests it does not care about), a session of its own, or nil to leave the request with no session at all.
IT RUNS INLINE ON AN I/O THREAD, and every connection has its own. So it must be safe to call from several threads at once, and it must be quick: a provider that goes to a database on each request has put a database round-trip in front of every request the server answers.
WRITING ONE THAT KEYS ON A COOKIE MEANS OWNING WHAT THAT IMPLIES: generating identifiers from a cryptographic RNG and not a counter; expiring them on idle AND absolutely; issuing a fresh identifier when the principal changes, so a fixated one cannot be inherited; setting the cookie HttpOnly, Secure and SameSite; and sweeping what expires, or the store is a memory leak an anonymous client can drive. None of that is done for you here.
function AcquireSession(const aRequest : iHttpRequest; const aResponse: iHttpResponse; const aConnectionSession: iHttpSession): iHttpSession;
WHAT THE TLS HANDSHAKE DECIDED, as a handler sees it: who the peer turned out to be when mTLS was used, which name it asked for, and which algorithms are carrying the request.
Everything is text, deliberately. This unit is the transport-agnostic core and stays free of the TLS and PKIX units; what a handler almost always wants is a string to compare, log or put in a header, and the small number of cases that need the certificate OBJECT can reach it through TransportInfo below.
IT DESCRIBES THE CONNECTION, NOT THE REQUEST. On HTTP/2 many requests share one connection and every one of them sees the same answers here.
THE PEER CERTIFICATE HAS ALREADY BEEN VERIFIED. A certificate that failed the server's trust configuration would have failed the handshake, so there would be no request to handle. What is left for a handler is AUTHORIZATION - deciding whether this particular verified peer may do this particular thing.
ServerName is the exception to all of that: it is a string the client chose, and no part of the handshake ties it to the client's identity.
function GetSecure: Boolean;
function GetTLSVersion: string;
function GetCipherSuite: string;
function GetServerName: string;
function GetKeyExchangeGroup: string;
function GetIsResumed: Boolean;
function GetPeerCertificatePresent: Boolean;
function GetPeerSubject: string;
function GetPeerSubjectCN: string;
function GetPeerIssuer: string;
function GetPeerSerialNumber: string;
function GetTransportInfo: IInterface;
property Secure: Boolean read GetSecure;
property TLSVersion: string read GetTLSVersion;
property CipherSuite: string read GetCipherSuite;
property ServerName: string read GetServerName;
property KeyExchangeGroup: string read GetKeyExchangeGroup;
property IsResumed: Boolean read GetIsResumed;
property PeerCertificatePresent: Boolean read GetPeerCertificatePresent;
property PeerSubject: string read GetPeerSubject;
property PeerSubjectCN: string read GetPeerSubjectCN;
property PeerIssuer: string read GetPeerIssuer;
property PeerSerialNumber: string read GetPeerSerialNumber;
property TransportInfo: IInterface read GetTransportInfo;
ONE REQUEST, ALREADY COMPLETE, handed to a handler for the duration of one HandleRequest call. Everything an application writes against this layer sees the request through this interface, so read the three rules first - they are the ones that cause trouble.
1. IT IS FULLY BUFFERED BEFORE YOU SEE IT. The wire session assembles the head AND the whole body before dispatching, so nothing here ever blocks, returns partial data, or has to be polled. What that costs is bounded by Limits.BodyBytes and the budgets around it; what it buys is that a handler is ordinary straight-line code.
2. IT IS VALID ONLY DURING THE CALL. The request object dies when the handler returns. Do not store the interface, the Headers object or the Body stream anywhere that outlives HandleRequest - copy what you need.
3. YOUR HANDLER RUNS ON AN I/O THREAD, INLINE. There is no worker pool between the socket and this call, so a handler that blocks holds a reactor thread for as long as it blocks, and enough simultaneous slow handlers stop the server answering anybody. Do slow work elsewhere and answer quickly. Different connections are dispatched on different threads at the same time, so anything shared between handlers needs its own locking; one connection is never dispatched twice at once.
NOTHING HERE IS DECODED OR NORMALISED. Path and Query are exactly the octets the peer sent: no percent-decoding, no "." / ".." collapsing, no case folding. That is deliberate - decoding before a security decision is how path traversal gets in - but it means an application that maps a request to anything outside itself must do that validation itself, after decoding, and must not assume two different-looking paths address different things.
Raising from a handler is caught by the wire session and turned into 500, so an exception is a blunt but valid way to fail.
function GetMethod: string;
function GetPath: string;
function GetQuery: string;
function GetVersion: string;
function GetHeaders: tHttpHeaders;
function GetBody: TStream;
function GetRemoteAddress: string;
function GetSecure: Boolean;
function GetNegotiatedProtocol: string;
function GetCookies: iHttpCookies;
function GetSession: iHttpSession;
function GetConnection: iHttpConnectionInfo;
function GetEarlyData: Boolean;
function GetEarlyDataStraddled: Boolean;
function Instance: tObject;
property Method: string read GetMethod;
property Path: string read GetPath;
property Query: string read GetQuery;
property Version: string read GetVersion;
property Headers: tHttpHeaders read GetHeaders;
property Body: TStream read GetBody;
property RemoteAddress: string read GetRemoteAddress;
property Secure: Boolean read GetSecure;
property NegotiatedProtocol: string read GetNegotiatedProtocol;
property Cookies: iHttpCookies read GetCookies;
property Session: iHttpSession read GetSession;
property Connection: iHttpConnectionInfo read GetConnection;
property EarlyData: Boolean read GetEarlyData;
property EarlyDataStraddled: Boolean read GetEarlyDataStraddled;
HTTP/3 SERVER PUSH from an inline TsmHTTPSv3 handler (HTTP.txt section 23.6). Reach it with Supports(aResponse, iHttpResponsePush, lPush) during HandleRequest; HTTP/1.1, HTTP/2 and streaming exchanges do not offer it. TryPush promises the client a GET for aPath on this GET request's https origin, with aHeaders (or nil) as the promised request's fields, and returns in aResponse a fresh response to fill in like any other before the handler returns. Nothing else is copied from this request - no cookies, no credentials - and nothing is routed, so authorize it for this client yourself first. A bad path, or a field such a request may not carry - authorization, cookie, a Content- field - raises eHttpArgumentError. False, with aResponse nil: no push now (Limits.MaxPushes is 0 by default, the client granted none, the request is not GET or arrived as 0-RTT, a limit is reached); just answer normally. True is not delivery: the push can still be cancelled, and is if the handler raises. Once the handler has returned, TryPush answers False.
function TryPush(const aPath: string; const aHeaders: tHttpHeaders; out aResponse: iHttpResponse): Boolean;
THE ANSWER, which a handler fills in and the wire session serialises after HandleRequest returns. Nothing is sent while the handler runs, so the response can be built in any order and changed as often as you like.
IT STARTS AS 404 WITH NO BODY. That is deliberate: a handler that is called and does nothing has, in effect, not found anything, and answering 404 is more honest than answering 200 with an empty body. Setting any content promotes 404 to 200 automatically - see SetContent - so the common case needs no SetStatus at all. Any status you set explicitly is left alone.
THE SESSION OWNS Content-Length and Date, and on HTTP/1.1 Connection; and it frames the body itself, so Transfer-Encoding and Trailer are its own too. Every session drops each copy of Content-Length, Date, Connection and Transfer-Encoding you set, by SetHeader or Headers.Add, and writes its own: one of each it uses, and never a Transfer-Encoding beside a Content-Length. Content-Length in particular is computed from the body you supplied, and a value you set is dropped rather than believed. HTTP/1.1 drops a Trailer you set as well; HTTP/2 and HTTP/3 drop it when they declare trailers of their own or send no body. No session adds a Server field; one you set goes out. On HTTP/2 and HTTP/3 the session also drops the other connection-specific fields (Keep-Alive, Proxy-Connection, Upgrade, TE) and anything beginning with ':' - the pseudo-header space is the wire's, not the application's.
A FIELD THAT CANNOT BE GENERATED FAILS THE RESPONSE: a name that is not a token, or a value with a control character other than HTAB, with DEL, or with SP or HTAB at either end - on HTTP/2 also a character above #255, as that wire carries one octet per character. HTTP/1.1 then sends a 500 whose body is 'Internal Server Error', HTTP/2 a bare 500 with only its own content-length and date; nothing you set goes out. HTTP/1.1 checks every field you set, HTTP/2 the ones it would send; HTTP/3 resets the request. On HTTP/1.1 and HTTP/2 a status outside 100..599 goes out as 500 with your fields and body, and a 1xx as a 500 without a body - a handler's answer is final. On HTTP/1.1 a reason phrase with a control character other than HTAB, or with DEL, gives way to the standard phrase: it shares the status line, where a CR or LF would start a field.
A FILE IS SENT FROM THE FILE, NOT FROM A COPY. SendFile, SendFileRange, HttpSendFile and SetContentStream with aOwns=True keep the stream they were given and the wire session reads it in bounded chunks as the peer takes them, so a large download costs a file handle and a few hundred kilobytes rather than its own size. The file stays open - and, opened the way SendFile opens it, closed to writers - until the response has been sent or the connection is gone. What IS held whole in memory is content set with SetContent / SetContentText, and a stream handed over with aOwns=False, which has to be copied because the caller keeps it. The length is always known up front: HTTP/1.1 sends it as Content-Length, and frames the body chunked only when the response carries trailers.
Same lifetime and threading rules as iHttpRequest: valid only during the call, and the call is on an I/O thread.
function GetStatusCode: Integer;
function GetHeaders: tHttpHeaders;
procedure SetStatus(aCode: Integer; const aReason: string = '');
procedure SetHeader(const aName, aValue: string);
procedure SetContentType(const aValue: string);
procedure SetContent(aData: Pointer; aLen: Integer);
procedure SetContentText(const aText: string);
procedure SetContentStream(const aStream: TStream; aOwns: Boolean);
procedure SendFile(const aPhysicalFile: string);
function SendFileRange(const aPhysicalFile: string; const aRangeHeader: string): Integer;
property StatusCode: Integer read GetStatusCode;
property Headers: tHttpHeaders read GetHeaders;
TRAILER FIELDS SENT AFTER THE RESPONSE BODY, for values known before the handler returns (for values computed while the body is sent, use iHttpResponseDeferredTrailers). Reach it with Supports(aResponse, iHttpResponseTrailers, lTrailers); this library's responses support it on all three wires (HTTP.txt section 2.3). SetTrailers checks and copies aTrailers - the collection stays yours to free - and replaces any earlier trailers or deferred producer. A name the trailer policy forbids or a Connection field names, a value with a control character, a character above #255 or outer SP/HTAB, or more than 16384 bytes in all (32 counted per field) raises eHttpArgumentError and changes nothing. nil or an empty collection removes them. Trailers is the response's read-only copy: never free it. Nothing is sent for HEAD and 1xx/204/205/304; on HTTP/1.1 the body goes chunked, and a body answer to an HTTP/1.0 request becomes 500. On a streaming exchange, set them before TryComplete or TryReject.
function GetTrailers: tHttpHeaders;
procedure SetTrailers(const aTrailers: tHttpHeaders);
property Trailers: tHttpHeaders read GetTrailers;
YOUR CALLBACK FOR TRAILER FIELDS COMPUTED WHILE THE BODY IS SENT - a digest of it, say (HTTP.txt section 2.3.1). Register it with iHttpResponseDeferredTrailers. ProduceTrailers is called once, when the body has been read from its source to the end, on the thread that drives the connection: be quick, never block, never call back into the server or a component. It is not called when the body is not read to the end (short read, source error, cancellation, lost connection), nor for HEAD and 1xx/204/205/304. Return a NEW tHttpHeaders, or nil for no fields, and set Result := nil first: a class-typed result is not initialised. The library checks and copies the fields, then frees what you returned, so never return one you keep. Each name must be one you declared. A raise or an invalid field aborts the response without a successful end; free what you created before raising. To share state with the body stream (a running hash), keep it in a reference-counted object both hold, not a pointer to the stream, which the library may free first.
function ProduceTrailers: tHttpHeaders;
REGISTERS AN iHttpResponseTrailerProducer for the body already set (HTTP.txt section 2.3.1). Reach it with Supports(aResponse, iHttpResponseDeferredTrailers, lDeferred) and call it AFTER setting the body: setting a body again removes the producer. aTrailerNames declares every field the producer may return; it is copied, lowercased and deduplicated, and an invalid or forbidden name raises eHttpArgumentError, leaving the previous registration in place. An empty declaration permits only an empty result. The response holds aProducer until it is called or the response is freed. A nil aProducer removes the registration; registering one removes trailers set with SetTrailers, and SetTrailers removes the producer. On HTTP/1.1 the body goes chunked, and a body answer to an HTTP/1.0 request becomes 500. On a streaming exchange, register before TryComplete or TryReject.
procedure SetTrailerProducer(const aTrailerNames: array of string; const aProducer: iHttpResponseTrailerProducer);
For wire sessions only - a handler never sees it. The deferred-trailer registration tHttpServerResponse.TakeTrailerProducer hands over, frozen against the final response head; the wire session owns it from then on. Once the body has been read from its source to the end, Finish calls the producer once and returns the checked fields, which the caller frees (an empty collection when there are none). Freeing it without Finish never calls the producer.
constructor Create(const aNames: array of string; const aProducer: iHttpResponseTrailerProducer);
destructor Destroy; override;
procedure Freeze(const aInitial: tHttpHeaders);
function Finish: tHttpHeaders;
property Names: tHttpTrailerNames read fNames;
property RetainedBytes: Integer read fRetainedBytes;
WHAT AN APPLICATION IMPLEMENTS. Register an instance for a path with TsmHTTPSv1dot1 / TsmHTTPSv2.AddHandler, and it is called for requests to exactly that path, on either wire, with no per-protocol code. Implement it on a TInterfacedObject and let the router hold the reference; a handler registered for a path lives as long as the router does, so a single instance serves every connection - which is precisely why it must be safe to call from several threads at once (see iHttpRequest).
procedure HandleRequest(const aRequest: iHttpRequest; const aResponse: iHttpResponse);
THE BOUNDS OF ONE STREAMING ROUTE, given to NewHttpStreamingHandler. Fill the record with InitHttpStreamingLimits, then change what you need:
MaxBodyBytes 8 MiB one request body; a larger one is refused (413) or fails the request
BufferBytes 64 KiB the per-request buffer the wire fills and Read drains; while it is full the peer is held back. Keep it at least the stream flow-control window (64 KiB by default) or HTTP/2 and HTTP/3 answer 503
TimeoutMSec 30000 the time a request may take from admission, worker included; progress does not extend it, and the request fails when it runs out
MaxActiveJobs 64 the requests one adapter holds at once, each until the last reference to its exchange is gone; one more is answered 503 Each must be positive, or NewHttpStreamingHandler raises eHttpArgumentError. The adapter keeps a copy of the record.
MaxBodyBytes: Int64;
BufferBytes: Integer;
TimeoutMSec: Cardinal;
MaxActiveJobs: Integer;
THE REQUEST AS IT STOOD WHEN ITS HEADERS ARRIVED, for a streaming handler and its worker: the same facts as iHttpRequest, copied, so any thread may read them for as long as it holds the interface. Headers and Cookies belong to it: read-only, never free them. There is no Body - read that through iHttpServerExchange - and no Session or Connection: take what you need from those in BeginStreaming (iHttpRequestAdmission). Supports iHttpRequestOrigin too. Holding it keeps the whole exchange, and its MaxActiveJobs slot, alive: let go of it when the request is done.
function GetMethod: string;
function GetPath: string;
function GetQuery: string;
function GetVersion: string;
function GetHeaders: tHttpHeaders;
function GetCookies: iHttpCookies;
function GetRemoteAddress: string;
function GetNegotiatedProtocol: string;
function GetSecure: Boolean;
property Method: string read GetMethod;
property Path: string read GetPath;
property Query: string read GetQuery;
property Version: string read GetVersion;
property Headers: tHttpHeaders read GetHeaders;
property Cookies: iHttpCookies read GetCookies;
property RemoteAddress: string read GetRemoteAddress;
property NegotiatedProtocol: string read GetNegotiatedProtocol;
property Secure: Boolean read GetSecure;
WHAT IS AVAILABLE ONLY WHILE BeginStreaming RUNS: the session chosen for this request (nil if a SessionProvider chose none), the connection's TLS facts, and the prepared response - set its status before returning False to refuse. Copy whatever the worker will need, an identity or a permission, into your job before returning: afterwards every property raises eHttpStateError.
function GetSession: iHttpSession;
function GetConnection: iHttpConnectionInfo;
function GetResponse: iHttpResponse;
property Session: iHttpSession read GetSession;
property Connection: iHttpConnectionInfo read GetConnection;
property Response: iHttpResponse read GetResponse;
ONE STREAMING REQUEST, handed to BeginStreaming and then to your worker (HTTP.txt section 24.2). The worker reads the body as it arrives with Read and WaitForBody, builds the answer in Response, and submits it with TryComplete once the whole body is read, or with TryReject before that. Only one thread at a time may read the body and change Response; Cancel and the status properties are safe from any thread. Head, its Headers and Trailers belong to the exchange: read-only, never free them. It lives as long as a reference to it does, and so does its MaxActiveJobs slot: release it when the job is done. If the peer resets, the deadline passes or the server stops first, the request fails: Read answers hsrrFailed and Failed is True.
function GetHead: iHttpRequestHead;
function Read(var aBuffer: TBytes; aOffset, aCount: Integer; out aRead: Integer): tHttpServerReadResult;
function WaitForBody(aMSec: Cardinal): Boolean;
function GetTrailers: tHttpHeaders;
function GetResponse: iHttpResponse;
function GetBodyComplete: Boolean;
function GetFailed: Boolean;
function GetFailText: string;
function TryComplete: Boolean;
function TryReject: Boolean;
procedure Cancel;
property Head: iHttpRequestHead read GetHead;
property Trailers: tHttpHeaders read GetTrailers;
property Response: iHttpResponse read GetResponse;
property BodyComplete: Boolean read GetBodyComplete;
property Failed: Boolean read GetFailed;
property FailText: string read GetFailText;
WHAT A STREAMING APPLICATION IMPLEMENTS, for a route that must act before the body has arrived - a large upload, or authorization that must come before the body is taken in (HTTP.txt section 24). Wrap it with NewHttpStreamingHandler (StreamSec.Http.Streaming) and register the result with AddHandler or AddPrefix. BeginStreaming is called once per request, after its headers, on the connection's I/O thread: decide quickly and never wait for the body there. To accept, put aExchange in your own bounded worker queue and return True once the queue holds it - the library supplies no worker threads. To refuse, set aAdmission.Response's status and return False (503 when you set none); raising answers 500. Early-data requests and a bad Expect are answered 425 and 417 before it is called.
function BeginStreaming(const aHead: iHttpRequestHead; const aAdmission: iHttpRequestAdmission; const aExchange: iHttpServerExchange): Boolean;
IMPLEMENT THIS ON YOUR iHttpSessionProvider TOO when its server has streaming routes: with a provider that lacks it, those routes answer 503 rather than run without your session check. AcquireStreamingSession does AcquireSession's job for a streaming request - once, before BeginStreaming, on the I/O thread - given the request head and the prepared response, so it can still set cookies. What it returns is aAdmission.Session.
function AcquireStreamingSession(const aHead: iHttpRequestHead; const aResponse: iHttpResponse; const aConnectionSession: iHttpSession): iHttpSession;
For wire sessions only: how a wire runs a streaming route; the handler NewHttpStreamingHandler returns supports it. TryReserveJob takes one of the adapter's MaxActiveJobs slots (False: none free - answer 503), and the slot is freed when the last reference to aJob goes.
function GetLimits: tHttpStreamingLimits;
function TryReserveJob(out aJob: IInterface): Boolean;
function BeginStreaming(const aHead: iHttpRequestHead; const aAdmission: iHttpRequestAdmission; const aExchange: iHttpServerExchange): Boolean;
property Limits: tHttpStreamingLimits read GetLimits;
For wire sessions only: Wake asks the wire session to process an exchange's reads and submissions on its own thread. It only posts that work and returns, whichever thread calls it.
procedure Wake;
For wire sessions only: the wire's side of an exchange, from NewHttpServerExchange. Feed takes body bytes in and answers how many fit; Finish ends the body with the validated trailers (copied, so they stay the caller's), Fail ends it with a reason. DrainCommands hands over, once each, the bytes the worker has read (to return as flow-control credit) and a complete, reject or cancel request with the response to send. Detach when the request is gone.
function Feed(aData: Pointer; aCount: Integer): Integer;
procedure Finish(const aValidatedTrailers: tHttpHeaders);
procedure Fail(const aReason: string);
procedure DrainCommands(out aCredit: Int64; out aAction: tHttpServerAction; out aResponse: iHttpResponse);
procedure Detach;
function GetStorageBytes: Integer;
function GetRoom: Integer;
function GetReceivedBytes: Int64;
function GetDeadline: UInt64;
property StorageBytes: Integer read GetStorageBytes;
property Room: Integer read GetRoom;
property ReceivedBytes: Int64 read GetReceivedBytes;
property Deadline: UInt64 read GetDeadline;
ONE REQUEST BODY A BOUND REFUSED, as OnBodyRefused reports it. Every field is what the server knew when it refused, which is why some can be empty.
RemoteAddress: string;
Protocol : string;
Method : string;
Path : string;
StreamID : Cardinal;
Limit : tHttpBodyLimit;
LimitBytes : Int64;
Declared : Int64;
Received : Int64;
Status : Integer;
ReqPath : string;
PhysFile: string;
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);
procedure RemoveRoute(const aPath: string);
function Resolve(const aMethod, aPath: string): iHttpRequestHandler;
PREFIX MOUNTS - the additive companion to iHttpRouter, for a handler that owns a SUBTREE rather than a path: a REST dispatcher mounted at '/api' receives '/api/orders/123' and everything else under '/api', while exact routes keep winning for the paths they name.
A SEPARATE interface rather than new members on iHttpRouter, deliberately: iHttpRouter is a shipped contract, and adding a method to a published interface breaks every implementation outside this unit at once. Reach it with Supports:
var lPfx: iHttpPrefixRouter; if Supports(aRouter, iHttpPrefixRouter, lPfx) then lPfx.AddPrefix('/api', lDispatcher);
and treat a router that does not support it as one that cannot host a mount - which is what it is. The router this unit builds (NewHttpRouter) supports it.
MATCHING. A prefix matches at '/' boundaries only: '/api' receives '/api' itself and '/api/anything', never '/apix'. Matching is on the RAW path, like every other match in this layer - no percent-decoding, no normalisation - so '/%61pi/x' does not reach a mount at '/api'. When several prefixes match, the LONGEST wins; an exact route beats every prefix; the component OnRequest fallback still runs only when neither answered. '/' (or '') mounts at the root and matches every path.
A trailing '/' on the prefix is stripped at registration, so '/api' and '/api/' register the same mount, and RemovePrefix accepts either form.
THE SAME RULES AS THE ROUTES APPLY: registering an existing prefix REPLACES its handler silently, there is no lock, and mounts are expected to be in place before the server goes Active.
procedure AddPrefix(const aPrefix: string; const aHandler: iHttpRequestHandler);
procedure RemovePrefix(const aPrefix: string);
A BODY THAT IS SENT FROM WHERE IT IS - the additive companion to iHttpResponse for a source too large to copy, reached with Supports:
var lSrc: iHttpResponseSource; if Supports(aResponse, iHttpResponseSource, lSrc) then lSrc.SetContentSource(lStream, lOffset, lLength) else ... copy, as SetContentStream(lStream, False) does
A separate interface for the same reason as iHttpPrefixRouter: iHttpResponse is a shipped contract. The response this unit builds supports it, which covers both wire sessions; a response that does not is one that can only hold a copy.
SetContentSource makes the body aLength octets of aStream starting at aOffset, WITHOUT reading any of them: the wire session reads them as it sends, in bounded chunks, paced by the transport. IT TAKES THE STREAM - the response frees it once the body has been sent, the connection has gone, or another body replaced it - so the caller must neither use nor free it afterwards. Promotes an untouched 404 to 200 exactly as SetContent does. HttpSendStreamRange and everything built on it use this when the caller passed ownership.
procedure SetContentSource(aStream: TStream; aOffset, aLength: Int64);
inherits from TInterfacedObject
implements iHttpCookies
The default iHttpCookies: parses one already-joined Cookie field value at construction and answers from the result. Construction is the parse, so the request only builds one when a handler asks.
constructor Create(const aCookieHeader: string);
function IndexOf(const aName: string): Integer;
function Exists(const aName: string): Boolean;
inherits from TInterfacedObject
implements iHttpSession
The default iHttpSession: a name/value map with no lifetime of its own, owned by whatever created it. The wire sessions create one per connection and hold it for the connection's life, which is where the per-connection lifetime documented on iHttpSession comes from - the class itself makes no such promise, so a provider is free to hold one for longer.
constructor Create(const aID: string = '');
destructor Destroy; override;
function Exists(const aName: string): Boolean;
procedure Remove(const aName: string);
procedure Clear;
constructor Create;
destructor Destroy; override;
function Instance: tObject;
procedure LoadBody(aData: Pointer; aLen: Integer);
procedure TakeTrailers(var aTrailers: tHttpHeaders);
property OriginScheme: string read fOriginScheme write fOriginScheme;
property OriginAuthority: string read fOriginAuthority write fOriginAuthority;
property Method: string read fMethod write fMethod;
property Path: string read fPath write fPath;
property Query: string read fQuery write fQuery;
property Version: string read fVersion write fVersion;
property Headers: tHttpHeaders read fHeaders;
property Trailers: tHttpHeaders read fTrailers;
property RemoteAddress: string read fRemoteAddress write fRemoteAddress;
property NegotiatedProtocol: string read fNegotiatedProtocol write fNegotiatedProtocol;
property Secure: Boolean read fSecure write fSecure;
property Session: iHttpSession read fSession write fSession;
property Connection: iHttpConnectionInfo read fConnection write fConnection;
property EarlyData: Boolean read fEarlyData write fEarlyData;
property EarlyDataStraddled: Boolean read fEarlyDataStraddled write fEarlyDataStraddled;
constructor Create;
destructor Destroy; override;
procedure SetStatus(aCode: Integer; const aReason: string = '');
procedure SetHeader(const aName, aValue: string);
procedure SetContentType(const aValue: string);
procedure SetContent(aData: Pointer; aLen: Integer);
procedure SetContentText(const aText: string);
procedure SetContentStream(const aStream: TStream; aOwns: Boolean);
procedure SendFile(const aPhysicalFile: string);
function SendFileRange(const aPhysicalFile: string; const aRangeHeader: string): Integer;
procedure SetContentSource(aStream: TStream; aOffset, aLength: Int64);
procedure SetTrailers(const aTrailers: tHttpHeaders);
procedure SetTrailerProducer(const aTrailerNames: array of string; const aProducer: iHttpResponseTrailerProducer);
function TakeTrailerProducer: tHttpResponseTrailerState;
function HasTrailerProducer: Boolean;
function BodyLength: Int64;
procedure TakeBody(out aStream: TStream; out aOffset, aLength: Int64; out aInMemory: Boolean);
property StatusExplicit: Boolean read fStatusExplicit;
property StatusCode: Integer read fStatusCode;
property Reason: string read fReason;
property Headers: tHttpHeaders read fHeaders;
property Trailers: tHttpHeaders read GetTrailers;
property BodyStream: TMemoryStream read GetBodyStream;
What identifies ONE representation to a cache and to a resuming client - RFC 9110 section 8.8. Both optional; '' / 0 = not known, and a validator that is not known is simply not sent and takes part in no comparison.
ETag: string;
LastModified: TDateTime;
WHAT TO DO WITH A REQUEST THAT ARRIVED AS 0-RTT (RFC 8470). 0-RTT saves a round trip and costs replayability: an attacker who captured the flight can send it again, and no layer below this one can tell the copy from the original. Single-use resumption tickets stop the same TICKET being redeemed twice, which is most of the problem - but within one accepted flight the decision of what to ACT on is the application's, because only the application knows whether doing it twice matters.
What iHttpServerExchange.Read reports; see there.
For wire sessions: what a worker asked for, as iHttpServerExchangeControl.DrainCommands reports it.
WHICH BOUND REFUSED A REQUEST BODY, named after the Limits property of the HTTPS protocol components that holds it.
What a Range header turned out to ask for.