Overview / Networking

http

HTTP/1.1 client over the TLS 1.3 of the <code>tls</code> module: a synchronous client with a connection pool, an asynchronous one on the event loop and Server-Sent Events. If your code never calls it, none of it enters the binary.

Always compiled: part of the core build.Include #include <ethereal/cpp/http/http_inc.hpp>C layer

http_inc.hpp

#include <ethereal/cpp/http/http_inc.hpp>

Umbrella header of the Http module (the HTTP/1.1 client of the core). Not to be confused with web-inc.hpp, the umbrella of Web::CWeb.

http_async.hpp

#include <ethereal/cpp/http/http_async.hpp>

The asynchronous HTTP/1.1 client: many requests at once on one thread, over Network::CEventLoop.

The same requests, results, time limits, pool and Happy Eyeballs as the synchronous CClient, without a thread per request: Start returns at once, and the response arrives through callbacks.

The client owns its event loop and runs it on one thread: its own (the default), or the caller's through Run. Every callback runs on that thread, one at a time, so the state of the requests needs no lock. Start, Cancel and the counters are safe from any thread: Start hands the request to the loop, and the loop takes it on its next round.

A name is resolved on a thread of the client (getaddrinfo blocks), never on the loop thread. An IP literal needs no lookup.

struct

SAsyncHandler

Ethereal::Http#
C++
struct   SAsyncHandler   final
{
    /// @brief  Passed to the callbacks.
    void *    pUser = nullptr;

    /// @brief  The head of the final response arrived. Can be null.
    bool ( *pfnHead )( void * pUser, const CResponseReader & Reader ) = nullptr;

    /// @brief  A piece of the body, decoded. Can be null.
    bool ( *pfnData )( void * pUser, std::string_view Data ) = nullptr;

    /// @brief  The request ended: complete, failed, timed out or cancelled. Called exactly
    ///             once for every request Start accepted, and never for one it refused. After
    ///             it, the id of the request is no longer valid. Can be null.
    void ( *pfnDone )( void * pUser, const SResult & Result ) = nullptr;
};

Where an asynchronous response goes. Every callback runs on the loop thread.

pfnHead and pfnData are those of SResponseHandler: the views are valid during the call only, and returning false stops the request (EStatus::eCancelled). The callbacks must not block: the loop serves every other request while they run. They may call Start and Cancel.

alias

void

Ethereal::Http#
using PFN_Scheduled = void ( * )( void * pUser );

A function the loop of an asynchronous client runs (see CAsyncClient::Schedule).

class

CAsyncClient

Ethereal::Http#

An asynchronous HTTP/1.1 client with a keep-alive pool.

class CAsyncClient
C++
Http::CAsyncClient Client;
Http::SAsyncHandler Handler;
Handler.pUser   = &Context;
Handler.pfnData = &OnData;
Handler.pfnDone = &OnDone;
std::uint64_t Id = 0;
Client.Start( Request, Handler, Timeouts, &Id );
// ... later, from any thread:
Client.Cancel( Id );

Start copies what it needs (the head is written at once, and the body is copied), so the request and its views can go away when it returns. A body source (SRequest::pfnBodySource) is called on the loop thread instead. Nothing is allocated per request once the pool holds the connections: the requests, the connections and the timers keep their memory.

Thread safe: Start, Cancel, CloseIdle and the counters can be called from any thread, the callbacks included. Run is for one thread at a time, and only for a client built without its own thread. The client must not be destroyed from inside a callback.
constructor

CAsyncClient

#
explicit CAsyncClient( const SClientOptions & Options = SClientOptions(), bool bOwnThread = true );

A client with the given options. Nothing connects until a request.

CAsyncClient

Options
The options, as those of the synchronous client.
bOwnThread
true runs the loop on a thread of the client. false leaves it to the caller, who calls Run.
function

Start

#
EStatus Start( const SRequest & Request, const SAsyncHandler & Handler, const STimeouts & Timeouts = STimeouts(), std::uint64_t * pId = nullptr );

Starts a request and returns at once.

Start

Request
The request. Copied: it can go away when Start returns.
Handler
Where the response goes.
Timeouts
The time limits.
pId
Receives the id of the request, for Cancel. Can be null.
eOk when the request was accepted, and then Handler.pfnDone comes once. Otherwise the reason (a bad URL, a header that would inject, a body and a body source together, eOutOfMemory, eInvalidState when the client is closing), and no callback comes.
function

Cancel

#
bool Cancel( std::uint64_t Id ) noexcept;

Stops a request. Safe from any thread.

Cancel The request ends with EStatus::eCancelled on the loop thread, unless it ended first: then the id no longer matches and nothing happens.

false when the id was never valid or the client is closing.
function

Schedule

#
EStatus Schedule( ETL_UINT32 uDelayMs, PFN_Scheduled pfn, void * pUser, std::uint64_t * pId = nullptr ) noexcept;

Runs a function on the loop thread after uDelayMs. Safe from any thread, the callbacks included.

Schedule For work that must wait without blocking the loop: the retry of a request, a pause asked by a rate limit. When the client closes, the functions still scheduled run at once, on the loop thread, so their owners can clean up (a Start from there returns eInvalidState).

uDelayMs
The delay. Zero runs it at the next round of the loop.
pfn
The function.
pUser
Passed to it.
pId
Receives the id, for Unschedule. Can be null.
eOk, eInvalidArgument (no function), eOutOfMemory, or eInvalidState when the client is closing.
function

Unschedule

#
bool Unschedule( std::uint64_t Id ) noexcept;

Removes a scheduled function. true when it had not run and now never will. Safe from any thread.

function

Run

#
std::size_t Run( ETL_UINT32 uTimeoutMs );

Runs the loop for at most uTimeoutMs, for a client without its own thread.

Run

How many completions were handled. Zero for a client with its own thread.
function

CloseIdle

#
void CloseIdle( void ) noexcept;

Closes the idle connections of the pool, on the next round of the loop.

function

Stats

#
SClientStats Stats( void ) const noexcept;

The counters.

function

ActiveCount

#
std::size_t ActiveCount( void ) const noexcept;

Requests started and not yet done.

function

IdleCount

#
std::size_t IdleCount( void ) const noexcept;

Connections in the pool, waiting for a request.

function

OpenCount

#
std::size_t OpenCount( void ) const noexcept;

Connections open (or opening), idle or in use.

function

Options

#
const SClientOptions & Options( void ) const noexcept

The options.

http_client.hpp

#include <ethereal/cpp/http/http_client.hpp>

The synchronous HTTP/1.1 client: TCP and TLS connections, the four time limits, cancellation and the keep-alive pool.

The client writes the request with WriteRequestHead, reads the response with CResponseReader, and hands the head and the body pieces to the caller as they arrive.

A request blocks the calling thread until the response ends, fails, times out or is cancelled. Several threads can send on the same CClient at once: each request takes a connection of its own from the pool, and the pool is shared.

The connection to a name with IPv6 and IPv4 addresses races them (Happy Eyeballs, RFC 8305, decision H-C): the first attempt starts at once, the next one 250 ms later if the first has not connected, and the first to connect wins. A machine whose IPv6 has no route connects over IPv4 without waiting for the IPv6 attempt to time out.

The name is resolved with getaddrinfo, which blocks and has no time limit of its own (decision L6 of AI-03). The connect time limit is checked when it returns, and a cancellation raised during the lookup is seen when it returns.

struct

SUrl

Ethereal::Http#
C++
struct   SUrl   final
{
    /// @brief  true for https.
    bool                bSecure = false;

    /// @brief  The host to connect to: a name, an IPv4 literal, or an IPv6 literal
    ///             without the brackets ('::1').
    std::string_view    sHost;

    /// @brief  The port, 80 or 443 when the URL has none.
    ETL_UINT16            uPort = 0;

    /// @brief  The value of the Host header: the authority as written, brackets and
    ///             port included ('[::1]:8080', 'api.anthropic.com').
    std::string_view    sAuthority;

    /// @brief  The request target: the path and the query, without the fragment. '/'
    ///             when the URL has no path.
    std::string_view    sTarget;
};

The parts of an http or https URL, as views into the text parsed.

function

ParseUrl

Ethereal::Http#
EStatus ParseUrl( std::string_view sUrl, SUrl & Out ) noexcept;

Splits an absolute http or https URL.

ParseUrl The scheme and the host are compared without case. A URL with user information ('user@host') is refused: the credentials belong in a header, and in a URL they end up in logs. So is a URL whose query comes with no path ('http://host?x'), which has no origin form to send. The target is not checked here: the writer refuses the bytes HTTP does not allow.

sUrl
The URL.
Out
Receives the parts, as views into sUrl.
eOk, eUnsupported for another scheme, or eInvalidArgument.
enum

ETimeout

Ethereal::Http#
C++
enum class   ETimeout : ETL_UINT8
{
    /// @brief  None.
    eNone = 0,

    /// @brief  The connection: waiting for a free connection of the pool, the name
    ///             lookup (checked when it returns), TCP and the TLS handshake.
    eConnect,

    /// @brief  From the end of the request to the first byte of the response.
    eFirstByte,

    /// @brief  Between two pieces of the response, after the first byte.
    eIdle,

    /// @brief  The whole request, from the call to the end of the response.
    eTotal
};

Which time limit ran out.

function

TimeoutName

Ethereal::Http#
const char * TimeoutName( ETimeout eTimeout ) noexcept;

Name of a time limit, for messages. Never returns null.

struct

STimeouts

Ethereal::Http#
C++
struct   STimeouts   final
{
    /// @brief  See ETimeout::eConnect.
    ETL_UINT32        uConnectMs = 30000u;

    /// @brief  See ETimeout::eFirstByte.
    ETL_UINT32        uFirstByteMs = 0u;

    /// @brief  See ETimeout::eIdle.
    ETL_UINT32        uIdleMs = 0u;

    /// @brief  See ETimeout::eTotal.
    ETL_UINT32        uTotalMs = 0u;
};

The four time limits of a request, in milliseconds. Zero is no limit.

A model can think for minutes before the first byte, so only the connection has a limit by default. The caller sets the others for what it calls.

class

CCancelToken

Ethereal::Http#

A flag any thread can raise to stop a request.

class CCancelToken

The request sees it within SClientOptions::uWakeMs, in any phase (the name lookup excepted, see the file header), closes its connection and returns EStatus::eCancelled. The token can serve several requests at once, and Reset makes it usable again.

constructor

CCancelToken

#
CCancelToken() noexcept = default;
function

Cancel

#
void Cancel( void ) noexcept

Raises the flag. Safe from any thread.

function

Reset

#
void Reset( void ) noexcept

Lowers the flag.

function

IsCancelled

#
bool IsCancelled( void ) const noexcept

The flag is raised.

alias

EStatus

Ethereal::Http#
using PFN_BodySource = EStatus ( * )( void * pUser, std::span< char > Out, std::size_t & uWritten, bool & bEnd );

Fills the next piece of a chunked request body.

pUser
SRequest::pBodyUser.
Out
Where to write.
uWritten
Receives how many bytes were written.
bEnd
Receives true when the body is over (with or without bytes in this piece).
eOk to go on. Anything else stops the request with that status.
struct

SRequest

Ethereal::Http#
C++
struct   SRequest   final
{
    /// @brief  The method, a token.
    std::string_view            sMethod = "GET";

    /// @brief  The absolute URL (see ParseUrl).
    std::string_view            sUrl;

    /// @brief  The headers. Host, Content-Length and Transfer-Encoding are written by
    ///             the client and refused here.
    std::span< const SHeader >    Headers;

    /// @brief  The body, sent with Content-Length. POST, PUT and PATCH send
    ///             'Content-Length: 0' when it is empty, the other methods send no body.
    std::span< const char >        Body;

    /// @brief  A chunked body instead of Body. Called until it says the body is over.
    ///             A request with it is never sent twice (see
    ///             SClientOptions::bRetryNonIdempotent).
    PFN_BodySource                pfnBodySource = nullptr;

    /// @brief  Passed to pfnBodySource.
    void *                        pBodyUser = nullptr;

    /// @brief  Sends 'Accept-Encoding: gzip, deflate' unless Headers has one.
    bool                        bAcceptCompressed = true;

    /// @brief  Decodes gzip and deflate (see CResponseReader::SetDecode).
    bool                        bDecode = true;
};

What CClient::Send sends.

The views are read during the call only.

struct

SResponseHandler

Ethereal::Http#
C++
struct   SResponseHandler   final
{
    /// @brief  Passed to the callbacks.
    void *    pUser = nullptr;

    /// @brief  The head of the final response arrived: the status and the headers are
    ///             in the reader. Can be null.
    bool ( *pfnHead )( void * pUser, const CResponseReader & Reader ) = nullptr;

    /// @brief  A piece of the body, decoded. Can be null.
    bool ( *pfnData )( void * pUser, std::string_view Data ) = nullptr;
};

Where the response goes, as it arrives.

The views given to the callbacks are valid during the call only. A callback that returns false stops the request: the connection is closed and the result is EStatus::eCancelled.

struct

SResult

Ethereal::Http#
C++
struct   SResult   final
{
    /// @brief  The status, the same CClient::Send returns.
    EStatus                    eStatus = EStatus::eOk;

    /// @brief  Which limit ran out, with EStatus::eTimedOut.
    ETimeout                eTimeout = ETimeout::eNone;

    /// @brief  The status code of the response, or zero when no head arrived.
    ETL_UINT32                uHttpStatus = 0u;

    /// @brief  The system error, with eResolveFailed, eConnectFailed and eIoError.
    Network::SNetStatus        Net;

    /// @brief  The TLS error, with eTlsFailed.
    Tls::STlsStatus            Tls;

    /// @brief  Body bytes handed to the handler, after decoding.
    std::uint64_t            uBodyBytes = 0u;

    /// @brief  The response came over a connection taken from the pool.
    bool                    bReused = false;

    /// @brief  A pooled connection turned out closed before answering, and the
    ///             request was sent again on a new one.
    bool                    bRetried = false;

    /// @brief  What went wrong, in English, for a log. Never null.
    const char *            pErrorText = "";

    /// @brief  Nanoseconds from the call until the connection was ready (TCP and TLS).
    ///             Zero when a pooled connection was used.
    std::uint64_t            uConnectNs = 0u;

    /// @brief  Nanoseconds from the call until the first byte of the response. Zero when
    ///             nothing arrived.
    std::uint64_t            uFirstByteNs = 0u;

    /// @brief  Nanoseconds from the call until the end, also on failure.
    std::uint64_t            uTotalNs = 0u;
};

What happened to a request.

struct

SClientOptions

Ethereal::Http#
C++
struct   SClientOptions   final
{
    /// @brief  The limits of the response reader.
    SLimits                    Limits;

    /// @brief  Most connections open to one host (scheme, name, port) at once, idle
    ///             or in use. A request that finds them all busy waits for one, within its
    ///             connection time limit.
    std::size_t                uMaxConnectionsPerHost = 6u;

    /// @brief  How long an idle connection stays in the pool. Below the idle limit
    ///             of the servers (often 60 s or more), so a connection is rarely taken
    ///             just as the server closes it. Zero keeps no connection.
    ETL_UINT32                uMaxIdleMs = 30000u;

    /// @brief  Delay between two connection attempts to the addresses of a name
    ///             (Happy Eyeballs). RFC 8305 recommends 250 ms and at least 100 ms.
    ETL_UINT32                uAttemptDelayMs = 250u;

    /// @brief  How often a waiting request wakes to check its cancellation token,
    ///             in milliseconds. Only when a token was given.
    ETL_UINT32                uWakeMs = 20u;

    /// @brief  The roots that authenticate https servers. Null: the roots of the
    ///             operating system, loaded on the first https request. Not owned: it must
    ///             outlive the client.
    const Tls::CTrustStore *    pTrustStore = nullptr;

    /// @brief  How https servers are authenticated.
    Tls::ETlsVerifyMode        eVerify = Tls::eVerifyChain;

    /// @brief  true checks aPinSha256 against the leaf of every https server.
    bool                    bUsePin = false;

    /// @brief  SHA-256 of the DER SubjectPublicKeyInfo of the leaf.
    std::array< std::uint8_t, 32 >    aPinSha256{};

    /// @brief  Send a POST or PATCH again when the pooled connection it went over
    ///             closed before any byte of the response. Off by default: RFC 9110,
    ///             section 9.2.2, forbids retrying a request that is not idempotent
    ///             unless the caller knows it is safe. The idempotent methods (GET, HEAD,
    ///             PUT, DELETE, OPTIONS, TRACE) are retried once either way.
    bool                    bRetryNonIdempotent = false;
};

The options of a client, fixed at construction.

struct

SClientStats

Ethereal::Http#
C++
struct   SClientStats   final
{
    /// @brief  Requests sent (each try of a retried request counts).
    std::uint64_t    uRequests = 0u;

    /// @brief  TCP connections established.
    std::uint64_t    uConnects = 0u;

    /// @brief  TCP connection attempts started (one per address tried).
    std::uint64_t    uConnectAttempts = 0u;

    /// @brief  TLS handshakes completed.
    std::uint64_t    uTlsHandshakes = 0u;

    /// @brief  Requests sent over a pooled connection.
    std::uint64_t    uReused = 0u;

    /// @brief  Requests sent again after a pooled connection turned out closed.
    std::uint64_t    uStaleRetries = 0u;
};

Counters of a client, since its construction.

class

CClient

Ethereal::Http#

A synchronous HTTP/1.1 client with a keep-alive pool.

class CClient
C++
Http::CClient Client;
Http::SRequest Request;
Request.sMethod = "POST";
Request.sUrl    = "https://api.example.com/v1/messages";
Request.Headers = Headers;
Request.Body    = Json;
Http::SResult Result;
Client.Send( Request, Handler, Result, Timeouts, &Token );

A connection goes back to the pool when its response ended and both sides allow another request on it. An idle connection that the server closed is noticed before it is used, and a request whose pooled connection closed before answering is sent again once on a new one (see SClientOptions::bRetryNonIdempotent). Nothing is allocated per request once the pool holds the connections: each connection keeps its buffers and its reader.

Thread safe: Send, Fetch, CloseIdle, Stats and the counts can be called from several threads at once. The client must not be destroyed while a request runs.
constructor

CClient

#
explicit CClient( const SClientOptions & Options = SClientOptions() );

A client with the given options. Nothing connects until a request.

function

Send

#
EStatus Send( const SRequest & Request, const SResponseHandler & Handler, SResult & Result, const STimeouts & Timeouts = STimeouts(), const CCancelToken * pCancel = nullptr );

Sends a request and hands the response to the handler as it arrives.

Send

Request
The request.
Handler
Where the head and the body go.
Result
Receives what happened, also on success.
Timeouts
The time limits.
pCancel
A token that stops the request, or null.
The same as Result.eStatus. eOk means a complete response arrived, whatever its status code: a 404 or a 500 is eOk with Result.uHttpStatus.
function

Fetch

#
EStatus Fetch( const SRequest & Request, std::span< char > Body, std::size_t & uBodySize, SResult & Result, const STimeouts & Timeouts = STimeouts(), const CCancelToken * pCancel = nullptr );

Sends a request and writes the body into the caller's buffer.

Fetch

Request
The request.
Body
Where the body goes.
uBodySize
Receives the size of the body written.
Result
Receives what happened. The status code is in Result.uHttpStatus.
Timeouts
The time limits.
pCancel
A token that stops the request, or null.
As Send, and eBufferTooSmall when the body did not fit (the connection is closed, and uBodySize is what fit).
function

CloseIdle

#
void CloseIdle( void ) noexcept;

Closes the idle connections of the pool. The ones in use are not touched.

function

Stats

#
SClientStats Stats( void ) const noexcept;

The counters.

function

IdleCount

#
std::size_t IdleCount( void ) const noexcept;

Connections in the pool, waiting for a request.

function

OpenCount

#
std::size_t OpenCount( void ) const noexcept;

Connections open, idle or in use.

function

Options

#
const SClientOptions & Options( void ) const noexcept

The options.

http_message.hpp

#include <ethereal/cpp/http/http_message.hpp>

The HTTP/1.1 messages without the network: the request head writer and the incremental response reader.

Nothing here touches a socket. The writer fills the caller's buffer, and the reader eats whatever bytes the transport received, in slices of any size, and says what it found. CClient and CAsyncClient sit on top of the two.

The reader gives the same result for any slicing of the same bytes: the whole response at once, byte by byte, or anything in between. The tests check this, and the fuzz target checks it on every input.

RFC 9110 (semantics) and RFC 9112 (HTTP/1.1 syntax).

enum

EBodyFraming

Ethereal::Http#
C++
enum class   EBodyFraming : ETL_UINT8
{
    /// @brief  No body, and no framing header. For GET, HEAD, DELETE without body.
    ///             A POST without body should say eContentLength with zero.
    eNone = 0,

    /// @brief  'Content-Length: uContentLength'. The caller sends exactly that many
    ///             bytes after the head.
    eContentLength,

    /// @brief  'Transfer-Encoding: chunked'. The caller sends each chunk as
    ///             WriteChunkHeader, the data and kChunkEnd, and ends with kLastChunk.
    eChunked
};

How the body of a request is framed.

struct

SRequestHead

Ethereal::Http#
C++
struct   SRequestHead   final
{
    /// @brief  The method, a token ('GET', 'POST').
    std::string_view            sMethod;

    /// @brief  The request target, usually in origin form ('/v1/messages?beta=true').
    ///             Visible ASCII only: anything else goes percent encoded.
    std::string_view            sTarget;

    /// @brief  The value of the Host header ('api.anthropic.com', 'localhost:8080').
    std::string_view            sHost;

    /// @brief  The other headers, in order. Host, Content-Length and
    ///             Transfer-Encoding are refused here: the writer owns the framing.
    std::span< const SHeader >    Headers;

    /// @brief  How the body is framed.
    EBodyFraming                eBody = EBodyFraming::eNone;

    /// @brief  The body size, with EBodyFraming::eContentLength.
    std::uint64_t                uContentLength = 0;

    /// @brief  Writes 'Accept-Encoding: gzip, deflate', unless Headers already has an
    ///             Accept-Encoding.
    bool                        bAcceptCompressed = true;
};

What WriteRequestHead writes.

The views point to the caller's memory and are read during the call only. The body does not pass through the writer: the transport sends it from where it is, after the head.

function

WriteRequestHead

Ethereal::Http#
EStatus WriteRequestHead( const SRequestHead & Head, std::span< char > Out, std::size_t & uSize ) noexcept;

Writes the request line, the headers and the empty line that ends the head.

Order: the request line, Host, the caller's headers, Accept-Encoding, the framing header. Every byte is checked first, so a value with a CR or LF (header injection) is refused and nothing is written.

Head
What to write.
Out
Where to write. Empty only measures.
uSize
The bytes written, or the bytes needed when Out is empty or short.
eOk, eInvalidArgument, eBufferTooSmall or eNotLicensed.
function

WriteChunkHeader

Ethereal::Http#
EStatus WriteChunkHeader( std::uint64_t uChunkBytes, std::span< char > Out, std::size_t & uSize ) noexcept;

Writes the size line of a chunk ('1a2b' and CRLF).

uChunkBytes
The chunk size. Zero is refused: the last chunk is kLastChunk.
Out
Where to write. Empty only measures.
uSize
The bytes written, or the bytes needed when Out is empty or short.
eOk, eInvalidArgument or eBufferTooSmall.
const

kChunkEnd

Ethereal::Http#
inline constexpr std::string_view kChunkEnd = "\r\n";

What follows the data of each chunk.

const

kLastChunk

Ethereal::Http#
inline constexpr std::string_view kLastChunk = "0\r\n\r\n";

The last chunk, without trailers.

const

kMaxChunkHeaderBytes

Ethereal::Http#
inline constexpr std::size_t kMaxChunkHeaderBytes = 18u;

The longest size line WriteChunkHeader writes (16 hex digits and CRLF).

enum

EEvent

Ethereal::Http#
C++
enum class   EEvent : ETL_UINT8
{
    /// @brief  The input was all consumed and the message is not over: feed more.
    eNeedMore = 0,

    /// @brief  The head of the final response was read. The accessors of the status
    ///             and the headers are valid from here until the next Begin. Interim
    ///             (1xx) responses are skipped and never reported.
    eHeaders,

    /// @brief  A piece of the body, in SEvent::Data, already decoded.
    eData,

    /// @brief  The message ended. The bytes after it belong to the next response.
    eDone
};

What a call to CResponseReader::Next found.

struct

SEvent

Ethereal::Http#
C++
struct   SEvent   final
{
    /// @brief  What was found.
    EEvent                eKind = EEvent::eNeedMore;

    /// @brief  The body piece of EEvent::eData, empty otherwise.
    ///
    /// @details  Without a content coding it points into the input the caller gave,
    ///               with no copy. With gzip or deflate it points into the reader's
    ///               buffer. Either way it is valid until the next call to Next.
    std::string_view    Data;
};

The result of CResponseReader::Next.

class

CResponseReader

Ethereal::Http#

Reads an HTTP/1.1 response from bytes that arrive in slices.

class CResponseReader

The loop of a transport:

C++
Reader.Begin();
for( ;; )
{
    std::size_t uUsed = 0;
    EStatus e = Reader.Next( In, uUsed, Event, bClosed );
    In.remove_prefix( uUsed );
    // e != eOk: fail. eNeedMore: receive into In. eData: use Event.Data.
    // eDone: the response is over, and In holds the start of the next.
}

The reader copies the head into its own buffer, because the headers must outlive the transport's receive buffer. The body is not copied unless it is compressed.

The buffers are taken from the allocator once and kept by Begin, so a reader reused across responses does not allocate again unless a response is larger than every one before it. Release gives them back.

For the exclusive use of one thread.
constructor

CResponseReader

#
explicit CResponseReader( Memory::IAllocator * pAllocator = nullptr ) noexcept;

A reader with the default limits. Nothing is allocated until a response needs it.

pAllocator
Source of the buffers. Null is Memory::DefaultAllocator.
function

SetLimits

#
EStatus SetLimits( const SLimits & Limits ) noexcept;

Changes the limits. They apply from the next Begin.

eInvalidArgument when a limit that must be above zero is zero.
function

Limits

#
const SLimits & Limits( void ) const noexcept

The limits.

function

SetDecode

#
void SetDecode( bool bDecode ) noexcept

Decode gzip and deflate (the default). Off, eData gives the bytes as they came and Coding says what they are. Applies from the next Begin.

function

Begin

#
EStatus Begin( bool bHeadRequest = false ) noexcept;

Prepares for a new response. Forgets the previous one and keeps the buffers.

bHeadRequest
The request was HEAD: the response has no body, whatever its headers say.
eOk or eNotLicensed.
function

Next

#
EStatus Next( std::string_view In, std::size_t & uConsumed, SEvent & Out, bool bEof = false ) noexcept;

Eats input until it has something to say.

In
The bytes received and not consumed yet. May be empty.
uConsumed
The bytes of In eaten by this call.
Out
What was found.
bEof
Nothing comes after In: the connection closed. A body delimited by the close ends here. Any other message not over is eTruncated.
eOk, or the cause of the failure. A failure is sticky: every later call returns it until Begin. After eDone, Next returns eInvalidState until Begin.
function

Release

#
void Release( void ) noexcept;

Gives every buffer back. The reader stays usable, and allocates again when needed.

function

StatusCode

#
ETL_UINT32 StatusCode( void ) const noexcept

The status code (200, 429).

function

Reason

#
std::string_view Reason( void ) const noexcept

The reason phrase, possibly empty.

function

VersionMinor

#
ETL_UINT32 VersionMinor( void ) const noexcept

The minor version of the response: 1 for HTTP/1.1, 0 for HTTP/1.0.

function

HeaderCount

#
std::size_t HeaderCount( void ) const noexcept

How many header fields.

function

HeaderAt

#
const SHeader & HeaderAt( std::size_t uIndex ) const noexcept

The header field at uIndex, in the order received.

function

Header

#
std::string_view Header( std::string_view sName ) const noexcept;

The value of the first header field named sName (without case).

The value, or an empty view when there is none. HasHeader tells an absent field from an empty one.
function

HasHeader

#
bool HasHeader( std::string_view sName ) const noexcept;

There is a header field named sName (without case).

function

KeepAlive

#
bool KeepAlive( void ) const noexcept

The connection can take another request once this response is over.

False for HTTP/1.0 without 'Connection: keep-alive', for 'Connection: close', for a body delimited by the close, and when the response had both Transfer-Encoding and Content-Length.

function

IsChunked

#
bool IsChunked( void ) const noexcept

The body is chunked.

function

IsCloseDelimited

#
bool IsCloseDelimited( void ) const noexcept

The body ends when the connection closes.

function

HasNoBody

#
bool HasNoBody( void ) const noexcept

The response has no body (HEAD, 1xx, 204, 304, or Content-Length zero).

function

ContentLength

#
std::uint64_t ContentLength( void ) const noexcept

The Content-Length, or UINT64_MAX when the body is not framed by it.

function

Coding

#
ECoding Coding( void ) const noexcept

The content coding of the body.

function

InterimCount

#
std::size_t InterimCount( void ) const noexcept

How many interim (1xx) responses were skipped.

function

BodyBytes

#
std::uint64_t BodyBytes( void ) const noexcept

Body bytes handed out so far, after decoding.

function

BytesConsumed

#
std::uint64_t BytesConsumed( void ) const noexcept

Bytes consumed since Begin. Zero after a close means the server closed before answering anything.

function

Status

#
EStatus Status( void ) const noexcept

The sticky failure, or eOk.

function

ErrorText

#
const char * ErrorText( void ) const noexcept

What went wrong, in English, for a log. Never null.

function

ErrorOffset

#
std::uint64_t ErrorOffset( void ) const noexcept

About where it went wrong: bytes since Begin.

http_sse.hpp

#include <ethereal/cpp/http/http_sse.hpp>

CSseParser: the incremental parser of 'text/event-stream' (Server-Sent Events).

The format of the WHATWG HTML standard, section "Server-sent events", parsed from bytes that arrive in slices of any size:

  • lines end with CRLF, LF or a lone CR, also when the CR and the LF come in different slices
  • a UTF-8 BOM at the start of the stream is dropped
  • a line starting with ':' is a comment
  • the fields are 'event', 'data', 'id' and 'retry'. Any other is ignored. One space after the colon is dropped
  • the 'data' lines of an event are joined with LF, and the event goes out at the empty line. An event without data does not go out, and its type is forgotten
  • an 'id' with a NUL is ignored. The last id stays from one event to the next, and is what a reconnection sends as Last-Event-ID
  • an event cut by the end of the stream never goes out.

The bytes are not decoded: the text goes out as it came, and whoever reads it (the JSON reader, in the Llm module) checks the UTF-8.

The data of an event that came whole in one slice, in a single 'data' line, is not copied: it points into the caller's input. The rest goes to buffers taken once from the allocator and kept by Reset.

struct

SSseEvent

Ethereal::Http#
C++
struct   SSseEvent   final
{
    /// @brief  The type: the last 'event' field, or "message" without one.
    std::string_view    sType;

    /// @brief  The 'data' lines joined with LF, without a LF at the end.
    std::string_view    sData;

    /// @brief  The last event id of the stream when this event went out. Possibly
    ///             empty.
    std::string_view    sId;
};

An event of the stream.

The views are valid until the next call to CSseParser::Next.

class

CSseParser

Ethereal::Http#

Parses an event stream from bytes that arrive in slices.

class CSseParser

The same events come out for any slicing of the same bytes.

C++
for( ;; )
{
    std::size_t uUsed = 0;
    bool bEvent = false;
    EStatus e = Parser.Next( In, uUsed, Event, bEvent );
    In.remove_prefix( uUsed );
    // e != eOk: fail. bEvent: use Event. Else In is empty: feed more.
}
For the exclusive use of one thread.
const

kDefaultMaxEventBytes

#
static constexpr std::size_t kDefaultMaxEventBytes = 1024u * 1024u;

Default limit of an event, in bytes.

constructor

CSseParser

#
explicit CSseParser( Memory::IAllocator * pAllocator = nullptr, std::size_t uMaxEventBytes = 0 ) noexcept;

A parser at the start of a stream. Nothing is allocated until an event needs it.

pAllocator
Source of the buffers. Null is Memory::DefaultAllocator.
uMaxEventBytes
The limit of a line, of the data of an event (a LF after each line counted), of a type and of an id. Zero is kDefaultMaxEventBytes.
function

Next

#
EStatus Next( std::string_view In, std::size_t & uConsumed, SSseEvent & Out, bool & bEvent ) noexcept;

Eats input until an event goes out or the input ends.

In
The bytes received and not consumed yet. May be empty.
uConsumed
The bytes of In eaten by this call. All of In when no event went out.
Out
The event, when bEvent.
bEvent
An event went out.
eOk, eLimitExceeded, eOutOfMemory or eNotLicensed. A failure is sticky until Reset.
function

Reset

#
void Reset( bool bKeepLastEventId = true ) noexcept;

Back to the start of a stream (a reconnection). Keeps the buffers.

bKeepLastEventId
Keep the last event id and the retry time, as a reconnection to the same source should.
function

Release

#
void Release( void ) noexcept;

Gives every buffer back. The parser goes back to the start of a stream, without the last event id.

function

LastEventId

#
std::string_view LastEventId( void ) const noexcept;

The last event id: the value to send as Last-Event-ID on a reconnection.

function

RetryMs

#
std::int64_t RetryMs( void ) const noexcept

The reconnection time the stream asked for, in milliseconds, or -1.

function

Status

#
EStatus Status( void ) const noexcept

The sticky failure, or eOk.

function

MaxEventBytes

#
std::size_t MaxEventBytes( void ) const noexcept

The limit of an event.

function

ReservedBytes

#
std::size_t ReservedBytes( void ) const noexcept

Bytes the parser holds in its buffers (their capacity), for the accounting of the memory of a stream.

http_types.hpp

#include <ethereal/cpp/http/http_types.hpp>

Vocabulary of the Http module: status, header, limits and the content codings the response reader decodes.

The Http module is the HTTP/1.1 client of the core (CClient and CAsyncClient). This header and the message and SSE headers are the messages without the network.

Not to be confused with Web::CWeb (web-*.hpp in this same folder), the older HTTPS client behind ETHEREAL_BUILD_HTTP. The Http module is always compiled.

Everything a server sends is untrusted input. Every limit has a safe default, and a hostile response gives an error, never a crash or an unbounded allocation.

enum

EStatus

Ethereal::Http#
C++
enum class   EStatus : ETL_UINT32
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  An argument is empty, out of range, or holds a byte the protocol does
    ///             not allow there (a CR or LF in a header value, a space in the method).
    eInvalidArgument,

    /// @brief  The allocator returned null.
    eOutOfMemory,

    /// @brief  Refused: no license was accepted and the evaluation of this machine has
    ///             ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed,

    /// @brief  The caller's buffer is too small. The size needed is returned.
    eBufferTooSmall,

    /// @brief  A line, the header section, the number of headers, the body, an SSE
    ///             event or the decoded output is larger than the limit allows.
    eLimitExceeded,

    /// @brief  The response breaks the protocol: a bad status line, a header without a
    ///             colon, a bad chunk size, two different Content-Length values, a broken
    ///             gzip stream.
    eMalformed,

    /// @brief  The input ended (the connection closed) before the message did.
    eTruncated,

    /// @brief  The response is valid HTTP the module does not handle: a transfer
    ///             coding other than chunked, a content coding other than gzip and
    ///             deflate, a 101 Switching Protocols.
    eUnsupported,

    /// @brief  A call out of order: data fed to a reader that has already failed or
    ///             finished, without Begin.
    eInvalidState,

    /// @brief  The host name did not resolve to any address. SResult::Net has the
    ///             detail (stage H2, the client).
    eResolveFailed,

    /// @brief  No address of the host accepted the TCP connection. SResult::Net has the
    ///             cause of the last attempt.
    eConnectFailed,

    /// @brief  The TLS handshake or the TLS layer failed: certificate, pin, alert,
    ///             protocol. SResult::Tls has the detail.
    eTlsFailed,

    /// @brief  The connection failed after it was established (reset, broken pipe).
    ///             SResult::Net has the cause.
    eIoError,

    /// @brief  A time limit ran out. SResult::eTimeout says which one.
    eTimedOut,

    /// @brief  The cancellation token was raised, or the response handler asked to
    ///             stop.
    eCancelled
};

Result of an operation of the module.

function

StatusName

Ethereal::Http#
const char * StatusName( EStatus eStatus ) noexcept;

Name of a status, for messages. Never returns null.

struct

SHeader

Ethereal::Http#
C++
struct   SHeader   final
{
    std::string_view    sName;
    std::string_view    sValue;
};

A header field: name and value, as views.

In a request they point to the caller's memory. In a response they point to the reader's buffer and stay valid until the next Begin. The value has no leading or trailing whitespace.

function

EqualsNoCase

Ethereal::Http#
bool EqualsNoCase( std::string_view sA, std::string_view sB ) noexcept;

Compares two ASCII strings without case, as HTTP compares header names and tokens.

struct

SLimits

Ethereal::Http#
C++
struct   SLimits   final
{
    /// @brief  Longest line: the status line, a header line, a chunk size line with
    ///             its extensions, a trailer line. The line ending is not counted.
    std::size_t        uMaxLineBytes = 8u * 1024u;

    /// @brief  Largest header section (and, apart, largest trailer section),
    ///             line endings included.
    std::size_t        uMaxHeaderBytes = 64u * 1024u;

    /// @brief  Most header fields in one response (and, apart, trailer fields).
    std::size_t        uMaxHeaders = 100u;

    /// @brief  Largest body, counted after decoding. On the wire, the framing bytes and
    ///             the compressed body are not counted, only what comes out. Zero is no
    ///             limit.
    std::size_t        uMaxBodyBytes = 64u * 1024u * 1024u;

    /// @brief  Largest ratio between the decoded and the compressed body. Zero is no
    ///             limit. See Compression::SDecompressLimits::uMaxExpansionRatio.
    std::uint32_t    uMaxExpansionRatio = 1024u;

    /// @brief  Most interim (1xx) responses before the final one.
    std::size_t        uMaxInterim = 16u;

    /// @brief  Size of the buffer the decoded body comes out of, in bytes.
    std::size_t        uDecodeBufferBytes = 16u * 1024u;
};

The limits of the response reader.

Each one protects against a server that sends without end. Zero in uMaxBodyBytes means no limit, and the others must be above zero.

enum

ECoding

Ethereal::Http#
C++
enum class   ECoding : ETL_UINT8
{
    /// @brief  No coding (or 'identity').
    eIdentity = 0,

    /// @brief  'gzip' or 'x-gzip' (RFC 1952).
    eGzip,

    /// @brief  'deflate'. RFC 9110 says zlib (RFC 1950), and some servers send raw
    ///             deflate (RFC 1951). The reader tells them apart by the first two bytes.
    eDeflate,

    /// @brief  A coding the reader does not decode ('br', 'zstd', or two codings in a
    ///             row). With decoding on, the response is eUnsupported. With it off, the
    ///             bytes come as they are, and the Content-Encoding header says what they are.
    eOther
};

The content coding of a response body.

web-answer.hpp

#include <ethereal/cpp/http/web-answer.hpp>
class

CWebAnswer

Ethereal::Web#

Helper class for answers to http/https/etc requests.

class CWebAnswer final

There is no guarantee that it is thread-safe. Synchronization is the responsibility of its caller. It must not be inherited directly by any structure, class or object.

constructor

CWebAnswer

#
CWebAnswer() noexcept;

Default constructor.

function

Reset

#
void Reset( void );

Clears everything. CWeb::SynchronousRequest calls it first.

function

GetBody

#
const char * GetBody( void ) const;

The body, already without the chunked framing. The pointer form stops at the first zero byte. For binary data use the std::string form with GetBodyLength.

function

GetBody

#
void GetBody( std::string & sOutStatus ) const;
function

GetBody

#
void GetBody( String::CAString & sOutStatus ) const;
function

GetBodyLength

#
std::size_t GetBodyLength( void ) const;
function

GetStatusCode

#
int GetStatusCode( void ) const;

HTTP status code (200, 404...). 0 when no answer was read.

function

GetStatusLine

#
const char * GetStatusLine( void ) const;

The status line without the line break ("HTTP/1.1 200 OK").

function

GetStatusLine

#
void GetStatusLine( std::string & sOutStatus ) const;
function

GetStatusLine

#
void GetStatusLine( String::CAString & sOutStatus ) const;
function

GetStatusText

#
const char * GetStatusText( void ) const;

The reason phrase of the status line ("OK"). May be empty.

function

GetHeaderCount

#
std::size_t GetHeaderCount( void ) const;

Number of header fields received.

function

GetHeaderName

#
const char * GetHeaderName( const std::size_t uIndex ) const;

Name of the field at uIndex, as received. Empty out of range.

function

GetHeaderValue

#
const char * GetHeaderValue( const std::size_t uIndex ) const;

Value of the field at uIndex. Empty out of range.

function

GetHeader

#
const char * GetHeader( const char * sName ) const;

Value of the first field with this name.

sName
Field name, compared without case.
The value, or nullptr when the field is absent.
function

GetErrorDetail

#
const char * GetErrorDetail( void ) const;

Description of the failure of the last request (the TLS status, or what was wrong in the answer). Empty on success. For logs, it never carries the body.

web-backend.hpp

#include <ethereal/cpp/http/web-backend.hpp>
enum

EWebResult

Ethereal::Web#
C++
enum EWebResult : int
{
    /// @brief    The request pointer is null.
    eWebNullRequest = -2,

    /// @brief    The request carries a configuration error. See
    ///            CWebRequest::GetRequestIssuedErrorCode.
    eWebRequestError = -1,

    /// @brief    The answer was read whole.
    eWebOk = 0,

    /// @brief    The name did not resolve or the TCP connection was refused or
    ///            unreachable.
    eWebConnectFailed = 1,

    /// @brief    @ref CWeb::Initialize was not called.
    eWebNotInitialized = 2,

    /// @brief    The TLS handshake failed: protocol error, alert from the
    ///            server, server without TLS 1.3, connection lost.
    eWebHandshakeFailed = 3,

    /// @brief    The server key does not match the pin (@ref CWeb::SetSpkiPin).
    eWebPinMismatch = 4,

    /// @brief    Sending the request failed.
    eWebSendFailed = 5,

    /// @brief    Receiving the answer failed (transport or TLS error).
    eWebReceiveFailed = 6,

    /// @brief    The certificate was rejected: unknown root, wrong host name,
    ///            out of its dates, bad signature.
    eWebCertificateRejected = 7,

    /// @brief    A time limit expired (connection, handshake or wait for data).
    eWebTimeout = 8,

    /// @brief    The answer breaks HTTP/1.1 (status line, header field, chunk,
    ///            Content-Length, unsupported transfer coding).
    eWebMalformedAnswer = 9,

    /// @brief    The header or the body goes over the limits
    ///            (@ref CWeb::SetMaxAnswerBodyBytes).
    eWebAnswerTooLarge = 10,

    /// @brief    The connection ended before the end announced by
    ///            Content-Length or by the last chunk.
    eWebAnswerTruncated = 11,

    /// @brief    The domain, path, file name or charset cannot go in a request
    ///            (empty domain, space, line break, control character).
    eWebInvalidTarget = 12,

    /// @brief    Local failure (memory, random source).
    eWebInternal = 13,

    /// @brief    Refused: no license was accepted and the evaluation of this
    ///            machine has ended, or the license passed was refused (see
    ///            Bundle::UnlockBundle). Nothing was sent.
    eNotLicensed = 14
};

Result codes of CWeb::SynchronousRequest. The function returns them as int.

An HTTP error status (404, 500) is not a failure here: the answer was read, the code is eWebOk and the status is in CWebAnswer::GetStatusCode. On a failure, CWebAnswer::GetErrorDetail says more.

function

WebResultName

Ethereal::Web#
const char * WebResultName( const int iResult );

Readable name of a result code, for logs.

iResult
The code returned by CWeb::SynchronousRequest.
A static string ("ok", "timeout"...). "unknown" out of range.
class

CWeb

Ethereal::Web#

Backend class of the http/https/etc requests. Uses the TLS 1.3 stream of the Ethereal 'tls' module.

class CWeb final

Thread safety: several threads can call SynchronousRequest at the same time, each with its own request and answer objects. The configuration calls (roots, pin, limit) can come from any thread at any time and take effect on the next request. A request object or an answer object must not be shared between threads. It must not be inherited directly by any structure, class or object.

The padding of this type is intended (alignment). See 'ETL_BEGIN_INTENDED_PADDING'.

function

Instance

#
static CWeb & Instance() noexcept;

Gets the singleton instance of the web backend.

Reference to the single instance of CWeb.
function

Initialize

#
int Initialize( void );

Starts the network layer and, the first time, loads the root certificates of the system into the trust store.

0 on success, 1 when already initialized, 2 when the network layer did not start, 3 when the library is not licensed (see Bundle::UnlockBundle). A system without roots is not an error (a warning goes to the log): add roots with AddTrustedRootsPem.
function

Deinitialize

#
void Deinitialize( void );

Stops the network layer. The trust store, the pin and the limit stay for a later Initialize.

function

AddTrustedRootsPem

#
std::size_t AddTrustedRootsPem( std::string_view sPem );

Adds every "CERTIFICATE" block of a PEM text to the trust store.

A self-signed server certificate added here is trusted alone (pinned certificate). Allowed before or after Initialize.

sPem
The PEM text.
How many certificates were added.
function

AddTrustedRootDer

#
bool AddTrustedRootDer( std::span< const std::uint8_t > Der );

Adds one certificate in DER to the trust store.

Der
The certificate.
true when it parsed and was added.
function

LoadSystemRoots

#
std::size_t LoadSystemRoots( void );

Loads the system roots now (Initialize does it once). Returns how many were added.

function

ClearTrustedRoots

#
void ClearTrustedRoots( void );

Empties the trust store, system roots included. To trust only a private root, clear and then add it.

function

GetTrustedRootCount

#
std::size_t GetTrustedRootCount( void ) const;

Number of certificates in the trust store.

function

SetSpkiPin

#
void SetSpkiPin( std::span< const std::uint8_t, 32 > Sha256 );

Requires the SHA-256 of the server SubjectPublicKeyInfo (DER) to be this value, on top of the chain check, which stays on.

Sha256
The 32 bytes of the pin.
function

ClearSpkiPin

#
void ClearSpkiPin( void );

Removes the pin. Only the chain and the host name are checked.

function

HasSpkiPin

#
bool HasSpkiPin( void ) const;

true when a pin is set.

function

SetMaxAnswerBodyBytes

#
void SetMaxAnswerBodyBytes( const std::size_t uBytes );

Largest body accepted, in bytes (default 16 MiB). A bigger answer fails with eWebAnswerTooLarge. The header is limited apart, to 64 KiB. 0 restores the default.

function

GetMaxAnswerBodyBytes

#
std::size_t GetMaxAnswerBodyBytes( void ) const;

The current body limit.

function

SynchronousRequest

#
int SynchronousRequest( CWebRequest * pWebRequest, CWebAnswer & OutWebAnswer );

Sends the request over TLS 1.3 and reads the whole answer.

One connection per request, closed at the end even with keep-alive. The chain, the dates and the host name are always checked against the trust store, plus the pin when set. The answer is read by Content-Length, by chunked transfer coding or up to the end of the connection. No exception leaves.

pWebRequest
The request.
OutWebAnswer
Receives the status, the header fields and the body.
A code of EWebResult.

web-body.hpp

#include <ethereal/cpp/http/web-body.hpp>
class

CWebBody

Ethereal::Web#

Body class of the http/https/etc requests.

class CWebBody

There is no guarantee that it is thread-safe. Synchronization is the responsibility of its caller.

constructor

CWebBody

#
CWebBody() noexcept;

Default constructor.

function

ResetBody

#
void ResetBody( void );

Resets the internal state of the HTTP/HTTPS body to default values.

Sets the content type to FormUrl, zeroes the count of key/value pairs, sets the charset to "UTF-8" and fully clears the internal buffer used to build the request body.

Use before building a new request to avoid leftovers from previous uses.
function

StrRaw

#
const char * StrRaw( void );

Gets the final representation of the request body as a string pointer.

Pointer to a string with the body ready for sending according to the configured type. In invalid scenarios, returns an empty string.
function

Str

#
std::string Str( void );

Gets the final representation of the request body as a string.

String with the body ready for sending according to the configured type. In invalid scenarios, returns an empty string.
function

StrA

#
String::CAString StrA( void );

Gets the final representation of the request body as a CAString.

CAString with the body ready for sending according to the configured type. In invalid scenarios, returns an empty string.
function

StrAsPtr

#
std::string * StrAsPtr( void );

Gets the data pointer of the request body.

Pointer to the std::string with the body ready for sending according to the configured type.
function

StrW

#
String::CWString StrW( void );

Gets the final representation of the request body as a CWString.

CWString with the body ready for sending according to the configured type. In invalid scenarios, returns an empty string.
function

Form_KeyEncodeAndPush

#
void Form_KeyEncodeAndPush( const char * sStr, std::string & OutStr ) const;

Encodes and appends a key or value in the application/x-www-form-urlencoded format.

Applies the standard URL encoding: characters [A-Z][a-z][0-9] and "-_.~" are kept, the others are converted to "%XX" in hexadecimal.

sStr
Input string (key or value) to encode and append.
Operation skipped if the current content type is not eFormUrl. Designed for a high call frequency when building forms.
function

Json_KeyEscapeAndPush

#
void Json_KeyEscapeAndPush( const char * sStr, std::string & OutStr ) const;

Escapes and appends text for use as a key or value in JSON.

Escapes the mandatory special characters: '\\', '"', '\n', '\r', '\t', keeping the JSON syntax safe.

sStr
Input text (key or value) to escape and append.
OutStr
Output text (key or value) already escaped and appended.
Operation skipped if the current content type is not eJSON. Meant for direct building of simple and plain JSON structures.
function

Xml_KeyEscapeAndPush

#
void Xml_KeyEscapeAndPush( const char * sStr, std::string & OutStr ) const;

Escapes and appends text for use as the content of XML elements.

Converts special characters to XML entities: '&' -> "&amp;", '<' -> "&lt;", '>' -> "&gt;", '"' -> "&quot;", '\'' -> "&apos;".

sStr
Input text to escape and append.
Operation skipped if the current content type is not eXML. Ensures well-formed XML even with syntax-sensitive data.
function

PushKeyPairToBody

#
int PushKeyPairToBody( const char * sKey, const char * Value );

Adds a key/value pair to the request body according to the configured type.

Behavior per type:

  • eFormUrl: Concatenates "key=value" with URL encoding, separating multiple pairs with '&'.
  • eXML: On the first call, writes the XML header with the current charset and the root tag <root>. For each pair, creates <key>escaped value</key>.
  • eJSON: On the first call, opens with "{". Each pair is added as "key":"value" with the needed escapes, separated by ','.
sKey
Name of the key to add.
Value
Value associated with the key.
0: Success, key/value pair added to the internal buffer.
Increments the internal pair counter. Prepared for intensive use in high throughput HTTP/HTTPS scenarios inside the framework.

web-inc.hpp

#include <ethereal/cpp/http/web-inc.hpp>

web-request.hpp

#include <ethereal/cpp/http/web-request.hpp>
class

CWebRequest

Ethereal::Web#

Class of the http/https/etc requests. Uses the @CWebBody class as a helper.

class CWebRequest : public CWebBody

There is no guarantee that it is thread-safe. Synchronization is the responsibility of its caller.

constructor

CWebRequest

#
CWebRequest() noexcept;

Default constructor.

function

HasRequestIssuedAnyError

#
bool HasRequestIssuedAnyError( void ) const;
function

GetRequestIssuedErrorCode

#
int GetRequestIssuedErrorCode( void ) const;
function

Reset

#
void Reset( void );
function

SetDomain

#
void SetDomain( const char * sWebDomainURL );

Host name or IP literal of the server, without scheme or port ("api.example.com", "127.0.0.1", "::1"). It is the address to connect to, the TLS server name and the Host field.

function

GetDomain

#
const char * GetDomain( void ) const;
function

SetPort

#
void SetPort( const unsigned short uPort );

Port of the server. 0 (not set) means 443. The connection is always TLS, on any port.

function

GetPort

#
unsigned short GetPort( void ) const;
function

SetTargetPath

#
void SetTargetPath( const char * sWebPath );

Path of the request. The target sent is the path followed by the file name, already percent-encoded by the caller. Empty sends "/", and a missing leading '/' is added.

function

GetTargetPath

#
const char * GetTargetPath( void ) const;
function

SetTargetFileName

#
void SetTargetFileName( const char * sWebFileName );
function

GetTargetFileName

#
const char * GetTargetFileName( void ) const;
function

SetKeepAliveStatus

#
void SetKeepAliveStatus( void );
function

GetKeepAliveStatus

#
bool GetKeepAliveStatus( void ) const;
function

SetRequestMethod

#
void SetRequestMethod( const ERequestMethodID eRequestMethod );
function

GetRequestMethod

#
ERequestMethodID GetRequestMethod( void ) const;
function

SetCharset

#
void SetCharset( const char * sCharset );
function

GetCharset

#
const char * GetCharset( void ) const;
function

SetContentType

#
void SetContentType( const EContentTypeID eContentType );
function

GetContentType

#
EContentTypeID GetContentType( void ) const;
function

SetConnectionTimeoutTime

#
void SetConnectionTimeoutTime( const unsigned int iTimeInMs );

Time limit of the TCP connection and, again, of the TLS handshake, in milliseconds. Default 30000. 0 uses the default.

function

GetConnectionTimeoutTime

#
unsigned int GetConnectionTimeoutTime( void ) const;
function

SetReadTimeoutTime

#
void SetReadTimeoutTime( const unsigned int iTimeInMs );

Time limit of each send and of each wait for answer data, in milliseconds. Default 60000. 0 uses the default. It is a limit without data, not a total limit of the request.

function

GetReadTimeoutTime

#
unsigned int GetReadTimeoutTime( void ) const;
function

PushKeyPair

#
int PushKeyPair( const char * sKey, const char * Value );

web-types.hpp

#include <ethereal/cpp/http/web-types.hpp>
const

WEB_CHARSET_MAX_LENGTH

#
static constexpr int WEB_CHARSET_MAX_LENGTH = 32;
const

WEB_URL_MAX_LENGTH

#
static constexpr int WEB_URL_MAX_LENGTH = 256;
const

WEB_PATH_MAX_LENGTH

#
static constexpr int WEB_PATH_MAX_LENGTH = 512;
const

WEB_FILE_NAME_MAX_LENGTH

#
static constexpr int WEB_FILE_NAME_MAX_LENGTH = 64;
enum

ERequestMethodID

Ethereal::Web#
C++
enum class ERequestMethodID : unsigned char
{
    /// @brief    GET method
    ///            Default per request.
    eGET = 0,

    /// @brief    POST method (recommended)
    ePOST
};

Identification of the web request methods.

enum

EContentTypeID

Ethereal::Web#
C++
enum class EContentTypeID : unsigned char
{
    /// @brief    Content in encoded form format (application/x-www-form-urlencoded)
    ///            Default per request.
    eFormUrl = 0,

    /// @brief    Content in XML format (application/xml)
    eXML,

    /// @brief    Content in JSON format (application/json)
    eJSON,

    /// @brief    Content in Stream format (application/octet-stream)
    eStream
};

Identification of the content types of the web request.