http

April 7, 2026 ยท View on GitHub

{#httpmodule}

http

HTTP client/server, WebSocket support, form handling, cookies, URL parsing.

Namespaces

NameDescription
httpHTTP request/response types, parsers, and server/client helpers.
wsWebSocket framing, handshakes, and connection helpers.

{#http}

http

HTTP request/response types, parsers, and server/client helpers.

Classes

NameDescription
AuthenticatorMaintains HTTP Basic or Digest authentication state for outbound requests.
BasicAuthenticatorEncodes and decodes HTTP Basic authentication credentials.
ChunkedAdapterHTTP chunked transfer encoding adapter for streaming responses.
ClientHTTP client for creating and managing outgoing connections.
ClientConnectionHTTP client connection for managing request/response lifecycle.
ConnectionBase HTTP connection managing socket I/O and message lifecycle
ConnectionAdapterDefault HTTP socket adapter for reading and writing HTTP messages
ConnectionPoolLIFO connection pool for reusing ServerConnection objects. Avoids per-request heap allocation by resetting and reusing connections instead of destroying and recreating them.
ConnectionStreamPacket stream wrapper for an HTTP connection.
CookieHTTP cookie value plus its response/header attributes.
FilePartForm part backed by a file on disk.
FormPartAn implementation of FormPart.
FormWriterFormWriter is an HTTP client connection adapter for writing HTML forms.
MessageThe base class for Request and Response.
MultipartAdapterHTTP multipart encoding adapter for multipart/x-mixed-replace streaming.
ParserHTTP request/response parser using the llhttp library.
ParserObserverAbstract observer interface for HTTP parser events.
ProgressSignalHTTP progress signal for upload and download progress notifications.
RequestHTTP request message with method, URI, headers, and optional body.
ResponseHTTP response message with status, reason phrase, headers, and body metadata.
ServerHTTP server implementation.
ServerConnectionHTTP server connection.
ServerConnectionFactoryFactory for creating per-socket [ServerConnection](#serverconnection) and per-request [ServerResponder](#serverresponder) objects.
ServerResponderBase responder interface for handling one HTTP request on a server connection. Derived classes typically override [onRequest()](#onrequest) and optionally the streaming hooks.
StringPartForm part backed by an in-memory string payload.
URLAn RFC 3986 based URL parser. Constructors and assignment operators will throw a SyntaxException if the URL is invalid.
DateCacheCaches the formatted Date header, updated once per second. Avoids per-request time formatting and string allocation.
MethodHTTP request methods.

Enumerations

NameDescription
StatusCodeHTTP Response Status Codes.
ServerConnectionStateHTTP server-side lifecycle phases used by the keep-alive state machine.
ServerConnectionModeTransport mode for server connections before and after protocol upgrade.

{#statuscode}

StatusCode

enum StatusCode

HTTP Response Status Codes.

ValueDescription
Continue
SwitchingProtocols
OK
Created
Accepted
NonAuthoritative
NoContent
ResetContent
PartialContent
MultipleChoices
MovedPermanently
Found
SeeOther
NotModified
UseProxy
TemporaryRedirect
BadRequest
Unauthorized
PaymentRequired
Forbidden
NotFound
MethodNotAllowed
NotAcceptable
ProxyAuthRequired
RequestTimeout
Conflict
Gone
LengthRequired
PreconditionFailed
EntityTooLarge
UriTooLong
UnsupportedMediaType
RangeNotSatisfiable
ExpectationFailed
UnprocessableEntity
UpgradeRequired
InternalServerError
NotImplemented
BadGateway
Unavailable
GatewayTimeout
VersionNotSupported

{#serverconnectionstate}

ServerConnectionState

enum ServerConnectionState

HTTP server-side lifecycle phases used by the keep-alive state machine.

ValueDescription
ReceivingHeadersParsing request headers.
ReceivingBodyReceiving request body bytes.
DispatchingOrSendingDispatching the responder or sending a normal response.
StreamingSending a long-lived streaming response.
UpgradedUpgraded to a non-HTTP protocol such as WebSocket.
ClosingClose has been requested and teardown is in progress.
ClosedConnection has fully closed.

{#serverconnectionmode}

ServerConnectionMode

enum ServerConnectionMode

Transport mode for server connections before and after protocol upgrade.

ValueDescription
HttpStandard HTTP request/response mode.
UpgradedUpgraded transport mode owned by another protocol adapter.

Typedefs

ReturnNameDescription
std::vector< ClientConnection::Ptr >ClientConnectionPtrVecList of owned client connections tracked by an HTTP client.

{#clientconnectionptrvec}

ClientConnectionPtrVec

std::vector< ClientConnection::Ptr > ClientConnectionPtrVec()

List of owned client connections tracked by an HTTP client.

Functions

ReturnNameDescription
boolisBasicCredentialsReturns true if the given Authorization header value uses HTTP Basic authentication.
boolisDigestCredentialsReturns true if the given Authorization header value uses HTTP Digest authentication.
boolhasBasicCredentialsReturns true if the request contains a Basic Authorization header.
boolhasDigestCredentialsReturns true if the request contains a Digest Authorization header.
boolhasProxyBasicCredentialsReturns true if the request contains a Basic Proxy-Authorization header.
boolhasProxyDigestCredentialsReturns true if the request contains a Digest Proxy-Authorization header.
voidextractCredentialsSplits a "user:password" user-info string into separate username and password strings. If no ':' is present, the entire string is treated as the username and password is empty.
voidextractCredentialsExtracts username and password from the user-info component of a URL. Does nothing if the URL has no user-info part.
ClientConnection::PtrcreateConnectionT inlineCreates a ClientConnection (or subtype) for the given URL without registering it with a Client instance. The socket and adapter are chosen based on the URL scheme:
ClientConnection::PtrcreateConnection inlineCreates a ClientConnection for the given URL and optionally registers it with a Client. Equivalent to calling Client::createConnection() when client is non-null.
const char *getStatusCodeReasonReturns the standard reason phrase for the given HTTP status code (e.g. "OK" for StatusCode::OK, "Not Found" for StatusCode::NotFound).
const char *getStatusCodeStringReturns a combined "NNN Reason" string for the given HTTP status code (e.g. "200 OK").
std::stringparseURIExtracts the URI (path and query) from a raw HTTP request line.
boolmatchURLTests whether a URI matches a glob-style expression.
std::stringparseCookieItemExtracts a named attribute from a Cookie header value.
boolsplitURIParametersParses URL query parameters from a URI into key-value pairs. Handles percent-decoding of names and values.
voidsplitParametersSplits a header-style parameter string into a primary value and named attributes. Attributes are separated by ';'. Enclosing quotes are stripped from values.
voidsplitParametersSplits a substring (defined by iterators) into named attributes. Attributes are separated by ';'. Enclosing quotes are stripped from values.

{#isbasiccredentials}

isBasicCredentials

bool isBasicCredentials(std::string_view header)

Returns true if the given Authorization header value uses HTTP Basic authentication.

Parameters

  • header Value of the Authorization or WWW-Authenticate header.

{#isdigestcredentials}

isDigestCredentials

bool isDigestCredentials(std::string_view header)

Returns true if the given Authorization header value uses HTTP Digest authentication.

Parameters

  • header Value of the Authorization or WWW-Authenticate header.

{#hasbasiccredentials}

hasBasicCredentials

bool hasBasicCredentials(const http::Request & request)

Returns true if the request contains a Basic Authorization header.

Parameters

  • request HTTP request to inspect.

{#hasdigestcredentials}

hasDigestCredentials

bool hasDigestCredentials(const http::Request & request)

Returns true if the request contains a Digest Authorization header.

Parameters

  • request HTTP request to inspect.

{#hasproxybasiccredentials}

hasProxyBasicCredentials

bool hasProxyBasicCredentials(const http::Request & request)

Returns true if the request contains a Basic Proxy-Authorization header.

Parameters

  • request HTTP request to inspect.

{#hasproxydigestcredentials}

hasProxyDigestCredentials

bool hasProxyDigestCredentials(const http::Request & request)

Returns true if the request contains a Digest Proxy-Authorization header.

Parameters

  • request HTTP request to inspect.

{#extractcredentials}

extractCredentials

void extractCredentials(std::string_view userInfo, std::string & username, std::string & password)

Splits a "user:password" user-info string into separate username and password strings. If no ':' is present, the entire string is treated as the username and password is empty.

Parameters

  • userInfo Input string in the form "user:password".

  • username Receives the extracted username.

  • password Receives the extracted password.


{#extractcredentials-1}

extractCredentials

void extractCredentials(const http::URL & uri, std::string & username, std::string & password)

Extracts username and password from the user-info component of a URL. Does nothing if the URL has no user-info part.

Parameters

  • uri URL to extract credentials from.

  • username Receives the extracted username.

  • password Receives the extracted password.


{#createconnectiont}

createConnectionT

inline

template<class ConnectionT> inline ClientConnection::Ptr createConnectionT(const URL & url, uv::Loop * loop)

Creates a ClientConnection (or subtype) for the given URL without registering it with a Client instance. The socket and adapter are chosen based on the URL scheme:

  • "http" -> TCPSocket

  • "https" -> SSLSocket

  • "ws" -> TCPSocket + WebSocket adapter

  • "wss" -> SSLSocket + WebSocket adapter

Parameters

Parameters

  • url Target URL. Must have a recognised scheme.

  • loop Event loop to use. Defaults to the default libuv loop.

Returns

Shared pointer to the created connection.

Exceptions

  • std::runtime_error if the URL scheme is not recognised.

{#createconnection}

createConnection

inline

inline ClientConnection::Ptr createConnection(const URL & url, http::Client * client, uv::Loop * loop)

Creates a ClientConnection for the given URL and optionally registers it with a Client. Equivalent to calling Client::createConnection() when client is non-null.

Parameters

  • url Target URL. The scheme determines the socket and adapter type.

  • client Optional Client instance to register the connection with.

  • loop Event loop to use. Defaults to the default libuv loop.

Returns

Shared pointer to the created connection.


{#getstatuscodereason}

getStatusCodeReason

const char * getStatusCodeReason(StatusCode status)

Returns the standard reason phrase for the given HTTP status code (e.g. "OK" for StatusCode::OK, "Not Found" for StatusCode::NotFound).

Parameters

  • status HTTP status code.

Returns

Null-terminated reason phrase string.


{#getstatuscodestring}

getStatusCodeString

const char * getStatusCodeString(StatusCode status)

Returns a combined "NNN Reason" string for the given HTTP status code (e.g. "200 OK").

Parameters

  • status HTTP status code.

Returns

Null-terminated status code string.


{#parseuri}

parseURI

std::string parseURI(std::string_view request)

Extracts the URI (path and query) from a raw HTTP request line.

Parameters

  • request Raw HTTP request line (e.g. "GET /path?q=1 HTTP/1.1").

Returns

The URI portion (e.g. "/path?q=1").


{#matchurl}

matchURL

bool matchURL(std::string_view uri, std::string_view expression)

Tests whether a URI matches a glob-style expression.

Parameters

  • uri The URI to test.

  • expression Pattern to match against. '*' matches any sequence of characters.

Returns

true if the URI matches the expression.


{#parsecookieitem}

parseCookieItem

std::string parseCookieItem(std::string_view cookie, std::string_view item)

Extracts a named attribute from a Cookie header value.

Parameters

  • cookie Full Cookie header value (e.g. "name=value; Path=/; HttpOnly").

  • item Attribute name to find (e.g. "Path").

Returns

The value of the named attribute, or an empty string if not found.


{#splituriparameters}

splitURIParameters

bool splitURIParameters(std::string_view uri, NVCollection & out)

Parses URL query parameters from a URI into key-value pairs. Handles percent-decoding of names and values.

Parameters

  • uri URI string optionally containing a '?' query component.

  • out Collection to populate with parsed parameters.

Returns

true if at least one parameter was parsed; false otherwise.


{#splitparameters}

splitParameters

void splitParameters(const std::string & s, std::string & value, NVCollection & parameters)

Splits a header-style parameter string into a primary value and named attributes. Attributes are separated by ';'. Enclosing quotes are stripped from values.

Example input: "multipart/mixed; boundary="boundary-01234567"" Output value: "multipart/mixed", parameters: { "boundary" -> "boundary-01234567" }

Parameters

  • s Input string to split.

  • value Receives the primary value before the first ';'.

  • parameters Receives the parsed attribute key-value pairs.


{#splitparameters-1}

splitParameters

void splitParameters(const std::string::const_iterator & begin, const std::string::const_iterator & end, NVCollection & parameters)

Splits a substring (defined by iterators) into named attributes. Attributes are separated by ';'. Enclosing quotes are stripped from values.

Parameters

  • begin Iterator to the start of the string to parse.

  • end Iterator past the end of the string to parse.

  • parameters Receives the parsed attribute key-value pairs.

{#authenticator}

Authenticator

#include <icy/http/authenticator.h>

Maintains HTTP Basic or Digest authentication state for outbound requests.

Note: Do not forget to read the entire response stream from the 401 response before sending the authenticated request, otherwise there may be problems if a persistent connection is used.

Public Methods

ReturnNameDescription
AuthenticatorCreates an empty authenticator.
AuthenticatorCreates an authenticator with the given username and password.
~AuthenticatorDestroys the authenticator.
voidfromUserInfoParses username:password std::string and sets username and password of the credentials object. Throws SyntaxException on invalid user information.
voidfromURIExtracts username and password from the given URI and sets username and password of the credentials object. Does nothing if URI has no user info part.
voidsetUsernameSets the username.
const std::string &username constReturns the username.
voidsetPasswordSets the password.
const std::string &password constReturns the password.
voidauthenticateInspects WWW-Authenticate header of the response, initializes the internal state (in case of digest authentication) and adds required information to the given http::Request.
voidupdateAuthInfoUpdates internal state (in case of digest authentication) and replaces authentication information in the request accordingly.
voidproxyAuthenticateInspects Proxy-Authenticate header of the response, initializes the internal state (in case of digest authentication) and adds required information to the given http::Request.
voidupdateProxyAuthInfoUpdates internal state (in case of digest authentication) and replaces proxy authentication information in the request accordingly.

{#authenticator-1}

Authenticator

Authenticator()

Creates an empty authenticator.


{#authenticator-2}

Authenticator

Authenticator(const std::string & username, const std::string & password)

Creates an authenticator with the given username and password.


{#authenticator-3}

~Authenticator

~Authenticator()

Destroys the authenticator.


{#fromuserinfo}

fromUserInfo

void fromUserInfo(std::string_view userInfo)

Parses username:password std::string and sets username and password of the credentials object. Throws SyntaxException on invalid user information.


{#fromuri}

fromURI

void fromURI(const http::URL & uri)

Extracts username and password from the given URI and sets username and password of the credentials object. Does nothing if URI has no user info part.


{#setusername}

setUsername

void setUsername(const std::string & username)

Sets the username.


{#username}

username

const

const std::string & username() const

Returns the username.


{#setpassword}

setPassword

void setPassword(const std::string & password)

Sets the password.


{#password}

password

const

const std::string & password() const

Returns the password.


{#authenticate}

authenticate

void authenticate(http::Request & request, const http::Response & response)

Inspects WWW-Authenticate header of the response, initializes the internal state (in case of digest authentication) and adds required information to the given http::Request.


{#updateauthinfo}

updateAuthInfo

void updateAuthInfo(http::Request & request)

Updates internal state (in case of digest authentication) and replaces authentication information in the request accordingly.


{#proxyauthenticate}

proxyAuthenticate

void proxyAuthenticate(http::Request & request, const http::Response & response)

Inspects Proxy-Authenticate header of the response, initializes the internal state (in case of digest authentication) and adds required information to the given http::Request.


{#updateproxyauthinfo}

updateProxyAuthInfo

void updateProxyAuthInfo(http::Request & request)

Updates internal state (in case of digest authentication) and replaces proxy authentication information in the request accordingly.

Private Attributes

ReturnNameDescription
std::string_username
std::string_password

{#_username}

_username

std::string _username

{#_password}

_password

std::string _password

Private Methods

ReturnNameDescription
AuthenticatorDeleted constructor.

{#authenticator-4}

Authenticator

Authenticator(const Authenticator &) = delete

Deleted constructor.

{#basicauthenticator}

BasicAuthenticator

#include <icy/http/authenticator.h>

Encodes and decodes HTTP Basic authentication credentials.

Public Methods

ReturnNameDescription
BasicAuthenticatorCreates an empty basic authenticator.
BasicAuthenticatorCreates a basic authenticator with the given username and password.
BasicAuthenticator explicitExtracts basic authentication credentials from the given request.
BasicAuthenticator explicitParses a raw Basic authentication payload string. The value can be extracted from a request via [Request::getCredentials()](#getcredentials).
~BasicAuthenticatorDestroys the basic authenticator.
voidsetUsernameSets the username.
const std::string &username constReturns the username.
voidsetPasswordSets the password.
const std::string &password constReturns the password.
voidauthenticate constAdds authentication information to the given http::Request.
voidproxyAuthenticate constAdds proxy authentication information to the given http::Request.

{#basicauthenticator-1}

BasicAuthenticator

BasicAuthenticator()

Creates an empty basic authenticator.


{#basicauthenticator-2}

BasicAuthenticator

BasicAuthenticator(const std::string & username, const std::string & password)

Creates a basic authenticator with the given username and password.


{#basicauthenticator-3}

BasicAuthenticator

explicit

explicit BasicAuthenticator(const http::Request & request)

Extracts basic authentication credentials from the given request.

Throws a NotAuthenticatedException if the request does not contain basic authentication information.


{#basicauthenticator-4}

BasicAuthenticator

explicit

explicit BasicAuthenticator(const std::string & authInfo)

Parses a raw Basic authentication payload string. The value can be extracted from a request via [Request::getCredentials()](#getcredentials).


{#basicauthenticator-5}

~BasicAuthenticator

~BasicAuthenticator()

Destroys the basic authenticator.


{#setusername-1}

setUsername

void setUsername(const std::string & username)

Sets the username.


{#username-1}

username

const

const std::string & username() const

Returns the username.


{#setpassword-1}

setPassword

void setPassword(const std::string & password)

Sets the password.


{#password-1}

password

const

const std::string & password() const

Returns the password.


{#authenticate-1}

authenticate

const

void authenticate(http::Request & request) const

Adds authentication information to the given http::Request.


{#proxyauthenticate-1}

proxyAuthenticate

const

void proxyAuthenticate(http::Request & request) const

Adds proxy authentication information to the given http::Request.

Protected Methods

ReturnNameDescription
voidparseAuthInfoExtracts username and password from Basic authentication info by base64-decoding authInfo and splitting the resulting std::string at the ':' delimiter.

{#parseauthinfo}

parseAuthInfo

void parseAuthInfo(std::string_view authInfo)

Extracts username and password from Basic authentication info by base64-decoding authInfo and splitting the resulting std::string at the ':' delimiter.

Private Attributes

ReturnNameDescription
std::string_username
std::string_password

{#_username-1}

_username

std::string _username

{#_password-1}

_password

std::string _password

Private Methods

ReturnNameDescription
BasicAuthenticatorDeleted constructor.

{#basicauthenticator-6}

BasicAuthenticator

BasicAuthenticator(const BasicAuthenticator &) = delete

Deleted constructor.

{#chunkedadapter}

ChunkedAdapter

#include <icy/http/packetizers.h>

Inherits: PacketProcessor

HTTP chunked transfer encoding adapter for streaming responses.

Public Attributes

ReturnNameDescription
Connection::PtrconnectionHTTP connection to send the initial response header through.
std::stringcontentTypeContent-Type value for the chunked response.
std::stringframeSeparatorOptional separator written before each chunk payload.
boolinitialTrue until the first chunk is processed and the header emitted.
boolnocopyIf true, header/data/footer are emitted as separate packets.
PacketSignalemitter

{#connection}

connection

Connection::Ptr connection

HTTP connection to send the initial response header through.


{#contenttype}

contentType

std::string contentType

Content-Type value for the chunked response.


{#frameseparator}

frameSeparator

std::string frameSeparator

Optional separator written before each chunk payload.


{#initial}

initial

bool initial

True until the first chunk is processed and the header emitted.


{#nocopy}

nocopy

bool nocopy

If true, header/data/footer are emitted as separate packets.


{#emitter-5}

emitter

PacketSignal emitter

Public Methods

ReturnNameDescription
ChunkedAdapter inlineCreates a ChunkedAdapter that sends its initial response header through the given connection. The content type is read from the connection's outgoing header.
ChunkedAdapter inlineCreates a ChunkedAdapter that emits its own raw HTTP/1.1 200 response header. Use this when no Connection object is available.
voidemitHeader virtual inlineEmits the initial HTTP/1.1 200 OK response headers with chunked transfer encoding. If a connection is set, headers are written through it; otherwise a raw response string is emitted via the packet signal.
voidprocess virtual inlineEncodes an incoming packet as a chunked transfer encoding chunk and emits it. Emits the HTTP response headers on the first call.

{#chunkedadapter-1}

ChunkedAdapter

inline

inline ChunkedAdapter(Connection::Ptr connection, const std::string & frameSeparator, bool nocopy)

Creates a ChunkedAdapter that sends its initial response header through the given connection. The content type is read from the connection's outgoing header.

Parameters

  • connection HTTP connection to use. May be nullptr to emit a raw response instead.

  • frameSeparator Optional data prepended to each chunk payload.

  • nocopy If true, header and payload are emitted as separate packets (avoids copies).


{#chunkedadapter-2}

ChunkedAdapter

inline

inline ChunkedAdapter(const std::string & contentType, const std::string & frameSeparator, bool nocopy)

Creates a ChunkedAdapter that emits its own raw HTTP/1.1 200 response header. Use this when no Connection object is available.

Parameters

  • contentType Content-Type value for the response.

  • frameSeparator Optional data prepended to each chunk payload.

  • nocopy If true, header and payload are emitted as separate packets.


{#emitheader}

emitHeader

virtual inline

virtual inline void emitHeader()

Emits the initial HTTP/1.1 200 OK response headers with chunked transfer encoding. If a connection is set, headers are written through it; otherwise a raw response string is emitted via the packet signal.


{#process-5}

process

virtual inline

virtual inline void process(IPacket & packet)

Encodes an incoming packet as a chunked transfer encoding chunk and emits it. Emits the HTTP response headers on the first call.

Parameters

  • packet Packet containing the raw payload data.

Exceptions

  • std::invalid_argument if the packet does not carry data.

{#client}

Client

#include <icy/http/client.h>

HTTP client for creating and managing outgoing connections.

Public Attributes

ReturnNameDescription
NullSignalShutdown

{#shutdown-6}

Shutdown

NullSignal Shutdown

Public Methods

ReturnNameDescription
Client
voidstopStop the Client and close all connections.
ClientConnection::PtrcreateConnectionT inlineCreates and registers a typed client connection for the given URL. The connection type is inferred from the URL scheme (http, https, ws, wss).
ClientConnection::PtrcreateConnection inlineCreates and registers a ClientConnection for the given URL. The socket type is chosen based on the URL scheme (http/https/ws/wss).
voidaddConnection virtualRegisters a connection with this client so it is tracked and cleaned up on stop().
voidremoveConnection virtualRemoves a previously registered connection from the client.

{#client-1}

Client

Client()

{#stop-7}

stop

void stop()

Stop the Client and close all connections.


{#createconnectiont-1}

createConnectionT

inline

template<class ConnectionT> inline ClientConnection::Ptr createConnectionT(const URL & url, uv::Loop * loop)

Creates and registers a typed client connection for the given URL. The connection type is inferred from the URL scheme (http, https, ws, wss).

Parameters

Parameters

  • url Target URL. The scheme determines the socket and adapter type.

  • loop Event loop to use. Defaults to the default libuv loop.

Returns

Shared pointer to the created connection.


{#createconnection-1}

createConnection

inline

inline ClientConnection::Ptr createConnection(const URL & url, uv::Loop * loop)

Creates and registers a ClientConnection for the given URL. The socket type is chosen based on the URL scheme (http/https/ws/wss).

Parameters

  • url Target URL.

  • loop Event loop to use. Defaults to the default libuv loop.

Returns

Shared pointer to the created connection.


{#addconnection}

addConnection

virtual

virtual void addConnection(ClientConnection::Ptr conn)

Registers a connection with this client so it is tracked and cleaned up on stop().

Parameters

  • conn The connection to add.

{#removeconnection}

removeConnection

virtual

virtual void removeConnection(ClientConnection * conn)

Removes a previously registered connection from the client.

Parameters

  • conn Raw pointer to the connection to remove.

Exceptions

  • std::logic_error if the connection is not tracked by this client.

Public Static Methods

ReturnNameDescription
Client &instance staticReturn the default HTTP Client singleton.
voiddestroy staticDestroys the default HTTP Client singleton.

{#instance-3}

instance

static

static Client & instance()

Return the default HTTP Client singleton.


{#destroy-1}

destroy

static

static void destroy()

Destroys the default HTTP Client singleton.

Protected Attributes

ReturnNameDescription
ClientConnectionPtrVec_connections

{#_connections}

_connections

ClientConnectionPtrVec _connections

Protected Methods

ReturnNameDescription
voidonConnectionClose

{#onconnectionclose}

onConnectionClose

void onConnectionClose(Connection & conn)

{#clientconnection}

ClientConnection

#include <icy/http/client.h>

Inherits: Connection

HTTP client connection for managing request/response lifecycle.

Public Attributes

ReturnNameDescription
void *opaqueOptional unmanaged client data pointer. Not used by the connection internally.
NullSignalConnectStatus signals.
Signal< void(Response &)>HeadersSignals when the response HTTP header has been received.
Signal< void(const MutableBuffer &)>PayloadSignals when raw data is received.
Signal< void(const Response &)>CompleteSignals when the HTTP transaction is complete.
Signal< void(const icy::Error &)>ErrorSignals when the underlying transport reports an error.
Signal< void(Connection &)>CloseSignals when the connection is closed.
ProgressSignalIncomingProgressSignals download progress (0-100%)

{#opaque-1}

opaque

void * opaque

Optional unmanaged client data pointer. Not used by the connection internally.


{#connect-11}

Connect

NullSignal Connect

Status signals.

Signals when the client socket is connected and data can flow


{#headers}

Headers

Signal< void(Response &)> Headers

Signals when the response HTTP header has been received.


{#payload}

Payload

Signal< void(const MutableBuffer &)> Payload

Signals when raw data is received.


{#complete}

Complete

Signal< void(const Response &)> Complete

Signals when the HTTP transaction is complete.


{#error-9}

Error

Signal< void(const icy::Error &)> Error

Signals when the underlying transport reports an error.


{#close-19}

Close

Signal< void(Connection &)> Close

Signals when the connection is closed.


{#incomingprogress}

IncomingProgress

ProgressSignal IncomingProgress

Signals download progress (0-100%)

Public Methods

ReturnNameDescription
ClientConnectionCreates a ClientConnection to the given URL, pre-populating the request URI and Host header. The response status is initialised to 502 Bad Gateway until a real response is received.
voidstart virtualStarts the internal HTTP request.
voidstart virtualStarts the given HTTP request, replacing the internal request object.
ssize_tsend virtualSends raw data to the peer, initiating a connection first if needed. Data is buffered internally until the connection is established.
voidsetReadStream virtualSets the output stream to which incoming response body data is written. The stream pointer is owned by the connection and freed with it. Must be called before start().
StreamT &readStream inlineReturns a reference to the read stream cast to the specified type.

{#clientconnection-1}

ClientConnection

ClientConnection(const URL & url, const net::TCPSocket::Ptr & socket)

Creates a ClientConnection to the given URL, pre-populating the request URI and Host header. The response status is initialised to 502 Bad Gateway until a real response is received.

Parameters

  • url Target URL. Scheme, host, port and path are extracted automatically.

  • socket TCP socket to use. Defaults to a plain TCPSocket; pass an SSLSocket for HTTPS.


{#start-8}

start

virtual

virtual void start()

Starts the internal HTTP request.

Calls connect() internally if the socket is not already connecting or connected. The actual request will be sent when the socket is connected.

Exceptions

  • std::runtime_error if already connecting.

{#start-9}

start

virtual

virtual void start(http::Request & req)

Starts the given HTTP request, replacing the internal request object.

Calls connect() internally if the socket is not already connecting or connected. The actual request will be sent when the socket is connected.

Parameters

  • req The HTTP request to send. Replaces the internal request.

Exceptions

  • std::runtime_error if already connecting.

{#send-10}

send

virtual

virtual ssize_t send(const char * data, size_t len, int flags)

Sends raw data to the peer, initiating a connection first if needed. Data is buffered internally until the connection is established.

Parameters

  • data Pointer to the data buffer.

  • len Number of bytes to send.

  • flags Socket send flags (unused for HTTP).

Returns

Number of bytes sent or buffered.


{#setreadstream}

setReadStream

virtual

virtual void setReadStream(std::ostream * os)

Sets the output stream to which incoming response body data is written. The stream pointer is owned by the connection and freed with it. Must be called before start().

Parameters

  • os Pointer to the output stream. Takes ownership.

Exceptions

  • std::runtime_error if already connecting.

{#readstream}

readStream

inline

template<class StreamT> inline StreamT & readStream()

Returns a reference to the read stream cast to the specified type.

Parameters

  • StreamT The concrete stream type to cast to.

Returns

Reference to the stream.

Exceptions

  • std::runtime_error if no read stream has been set.

  • std::bad_cast if the stream is not of type StreamT.

Protected Attributes

ReturnNameDescription
URL_url
bool_connect
bool_active
bool_complete
std::vector< PendingWrite >_outgoingBuffer
std::unique_ptr< std::ostream >_readStream

{#_url}

_url

URL _url

{#_connect}

_connect

bool _connect

{#_active}

_active

bool _active

{#_complete}

_complete

bool _complete

{#_outgoingbuffer}

_outgoingBuffer

std::vector< PendingWrite > _outgoingBuffer

{#_readstream}

_readStream

std::unique_ptr< std::ostream > _readStream

Protected Methods

ReturnNameDescription
voidconnect virtualConnects to the server endpoint. All sent data is buffered until the connection is made.
http::Message *incomingHeader virtualReturns the incoming HTTP message header (request or response depending on role).
http::Message *outgoingHeader virtualReturns the outgoing HTTP message header (request or response depending on role).
boolonSocketConnect virtualnet::SocketAdapter interface

{#connect-12}

connect

virtual

virtual void connect()

Connects to the server endpoint. All sent data is buffered until the connection is made.


{#incomingheader}

incomingHeader

virtual

virtual http::Message * incomingHeader()

Returns the incoming HTTP message header (request or response depending on role).


{#outgoingheader}

outgoingHeader

virtual

virtual http::Message * outgoingHeader()

Returns the outgoing HTTP message header (request or response depending on role).


{#onsocketconnect-2}

onSocketConnect

virtual

virtual bool onSocketConnect(net::Socket & socket)

net::SocketAdapter interface

Public Types

NameDescription
Ptr

{#ptr-11}

Ptr

std::shared_ptr< ClientConnection > Ptr()

Private Methods

ReturnNameDescription
voidonHeaders virtualConnection interface.
voidonPayload virtualCalled for each chunk of incoming response body data.
voidonComplete virtualCalled when the full HTTP response has been received.
voidonClose virtualCalled when the connection is closed.
boolonSocketError virtualCalled when the underlying transport encounters an error.

{#onheaders}

onHeaders

virtual

virtual void onHeaders()

Connection interface.

Called when the response headers have been parsed.


{#onpayload}

onPayload

virtual

virtual void onPayload(const MutableBuffer & buffer)

Called for each chunk of incoming response body data.


{#oncomplete}

onComplete

virtual

virtual void onComplete()

Called when the full HTTP response has been received.


{#onclose-3}

onClose

virtual

virtual void onClose()

Called when the connection is closed.


{#onsocketerror-2}

onSocketError

virtual

virtual bool onSocketError(net::Socket & socket, const icy::Error & error)

Called when the underlying transport encounters an error.

{#pendingwrite}

PendingWrite

#include <icy/http/client.h>

Public Attributes

ReturnNameDescription
Bufferdata
intflags

{#data-1}

data

Buffer data

{#flags}

flags

int flags = 0

{#connection-1}

Connection

#include <icy/http/connection.h>

Inherits: SocketAdapter Subclassed by: ClientConnection, ServerConnection

Base HTTP connection managing socket I/O and message lifecycle

Public Methods

ReturnNameDescription
ConnectionCreates a Connection using the given TCP socket.
voidonHeadersCalled when the incoming HTTP headers have been fully parsed.
voidonPayloadCalled for each chunk of incoming body data after headers are complete.
voidonCompleteCalled when the incoming HTTP message is fully received.
voidonCloseCalled when the connection is closed.
ssize_tsend virtualSend raw data to the peer.
ssize_tsendOwned virtualSend an owned payload buffer to the peer.
ssize_tsendHeader virtualSend the outdoing HTTP header.
voidclose virtualClose the connection and schedule the object for deferred deletion.
voidmarkActive virtual inlineMarks the connection as active. Server connections override this to refresh the idle timer.
voidbeginStreaming virtual inlineExplicitly enter long-lived streaming mode. Base connections ignore this; server connections use it to disable keep-alive idle reaping while a response stream is active.
voidendStreaming virtual inlineExit long-lived streaming mode.
boolclosed constReturn true if the connection is closed.
icy::Errorerror constReturn the error object if any.
boolheaderAutoSendEnabled constReturn true if headers should be automatically sent.
voidsetHeaderAutoSendEnabledEnable or disable automatic header emission for the next outgoing send path.
voidreplaceAdapter virtualAssign the new ConnectionAdapter and setup the chain. The flow is: Connection <-> ConnectionAdapter <-> Socket. Takes ownership of the adapter (deferred deletion via uv loop).
voidreplaceAdapter virtualOverload for nullptr (used in destructor to clear adapter).
boolsecure constReturn true if the connection uses TLS/SSL.
net::TCPSocket::Ptr &socketReturn the underlying socket pointer.
net::SocketAdapter *adapter constReturn the underlying adapter pointer.
Request &requestThe HTTP request headers.
Response &responseThe HTTP response headers.
http::Message *incomingHeaderReturns the incoming HTTP message header (request or response depending on role).
http::Message *outgoingHeaderReturns the outgoing HTTP message header (request or response depending on role).

{#connection-2}

Connection

Connection(const net::TCPSocket::Ptr & socket)

Creates a Connection using the given TCP socket.

Parameters

  • socket The TCP socket to use for I/O. Defaults to a new TCPSocket.

{#onheaders-1}

onHeaders

void onHeaders()

Called when the incoming HTTP headers have been fully parsed.


{#onpayload-1}

onPayload

void onPayload(const MutableBuffer & buffer)

Called for each chunk of incoming body data after headers are complete.

Parameters

  • buffer Buffer containing the received data chunk.

{#oncomplete-1}

onComplete

void onComplete()

Called when the incoming HTTP message is fully received.


{#onclose-4}

onClose

void onClose()

Called when the connection is closed.


{#send-11}

send

virtual

virtual ssize_t send(const char * data, size_t len, int flags)

Send raw data to the peer.

This is the zero-copy fast path. The caller retains ownership of the payload until the underlying async write completes.


{#sendowned-10}

sendOwned

virtual

virtual ssize_t sendOwned(Buffer && buffer, int flags)

Send an owned payload buffer to the peer.

Use this when the payload does not naturally outlive the current scope.


{#sendheader}

sendHeader

virtual

virtual ssize_t sendHeader()

Send the outdoing HTTP header.


{#close-20}

close

virtual

virtual void close()

Close the connection and schedule the object for deferred deletion.


{#markactive}

markActive

virtual inline

virtual inline void markActive()

Marks the connection as active. Server connections override this to refresh the idle timer.


{#beginstreaming}

beginStreaming

virtual inline

virtual inline void beginStreaming()

Explicitly enter long-lived streaming mode. Base connections ignore this; server connections use it to disable keep-alive idle reaping while a response stream is active.


{#endstreaming}

endStreaming

virtual inline

virtual inline void endStreaming()

Exit long-lived streaming mode.


{#closed-4}

closed

const

bool closed() const

Return true if the connection is closed.


{#error-10}

error

const

icy::Error error() const

Return the error object if any.


{#headerautosendenabled}

headerAutoSendEnabled

const

bool headerAutoSendEnabled() const

Return true if headers should be automatically sent.


{#setheaderautosendenabled}

setHeaderAutoSendEnabled

void setHeaderAutoSendEnabled(bool enabled)

Enable or disable automatic header emission for the next outgoing send path.


{#replaceadapter}

replaceAdapter

virtual

virtual void replaceAdapter(std::unique_ptr< net::SocketAdapter > adapter)

Assign the new ConnectionAdapter and setup the chain. The flow is: Connection <-> ConnectionAdapter <-> Socket. Takes ownership of the adapter (deferred deletion via uv loop).


{#replaceadapter-1}

replaceAdapter

virtual

virtual void replaceAdapter(std::nullptr_t)

Overload for nullptr (used in destructor to clear adapter).


{#secure}

secure

const

bool secure() const

Return true if the connection uses TLS/SSL.


{#socket-5}

socket

net::TCPSocket::Ptr & socket()

Return the underlying socket pointer.


{#adapter}

adapter

const

net::SocketAdapter * adapter() const

Return the underlying adapter pointer.


{#request-3}

request

Request & request()

The HTTP request headers.


{#response}

response

Response & response()

The HTTP response headers.


{#incomingheader-1}

incomingHeader

http::Message * incomingHeader()

Returns the incoming HTTP message header (request or response depending on role).


{#outgoingheader-1}

outgoingHeader

http::Message * outgoingHeader()

Returns the outgoing HTTP message header (request or response depending on role).

Protected Attributes

ReturnNameDescription
net::TCPSocket::Ptr_socket
net::SocketAdapter *_adapter
Request_request
Response_response
icy::Error_error
bool_closed
bool_shouldSendHeader

{#_socket-1}

_socket

net::TCPSocket::Ptr _socket

{#_adapter}

_adapter

net::SocketAdapter * _adapter

{#_request}

_request

Request _request

{#_response}

_response

Response _response

{#_error-2}

_error

icy::Error _error

{#_closed}

_closed

bool _closed

{#_shouldsendheader}

_shouldSendHeader

bool _shouldSendHeader

Protected Methods

ReturnNameDescription
voidsetError virtualSet the internal error. Note: Setting the error does not [close()](#close-20) the connection.
boolonSocketConnect virtualnet::SocketAdapter interface
boolonSocketRecv virtualCalled when data is received from the socket. Forwards the event to all registered receivers in priority order.
boolonSocketError virtualCalled when the socket encounters an error. Forwards the event to all registered receivers in priority order.
boolonSocketClose virtualCalled when the socket is closed. Forwards the event to all registered receivers in priority order.

{#seterror-4}

setError

virtual

virtual void setError(const icy::Error & err)

Set the internal error. Note: Setting the error does not [close()](#close-20) the connection.


{#onsocketconnect-3}

onSocketConnect

virtual

virtual bool onSocketConnect(net::Socket & socket)

net::SocketAdapter interface


{#onsocketrecv-3}

onSocketRecv

virtual

virtual bool onSocketRecv(net::Socket & socket, const MutableBuffer & buffer, const net::Address & peerAddress)

Called when data is received from the socket. Forwards the event to all registered receivers in priority order.

Parameters

  • socket The socket that received data.

  • buffer The received data buffer.

  • peerAddress Address of the sender.

Returns

true to stop propagation to subsequent receivers.


{#onsocketerror-3}

onSocketError

virtual

virtual bool onSocketError(net::Socket & socket, const icy::Error & error)

Called when the socket encounters an error. Forwards the event to all registered receivers in priority order.

Parameters

  • socket The socket that encountered the error.

  • error Error details.

Returns

true to stop propagation to subsequent receivers.


{#onsocketclose-2}

onSocketClose

virtual

virtual bool onSocketClose(net::Socket & socket)

Called when the socket is closed. Forwards the event to all registered receivers in priority order.

Parameters

  • socket The socket that was closed.

Returns

true to stop propagation to subsequent receivers.

Public Types

NameDescription
Ptr

{#ptr-12}

Ptr

std::shared_ptr< Connection > Ptr()

{#connectionadapter}

ConnectionAdapter

#include <icy/http/connection.h>

Inherits: ParserObserver, SocketAdapter

Default HTTP socket adapter for reading and writing HTTP messages

Public Methods

ReturnNameDescription
ConnectionAdapterCreates a ConnectionAdapter for the given connection.
ssize_tsend virtualSends data to the peer, flushing the outgoing HTTP header first if needed.
ssize_tsendOwned virtualSends an owned payload buffer to the connected peer.
voidremoveReceiverRemove the given receiver.
Parser &parserReturns the HTTP parser instance.
Connection *connectionReturns the owning Connection pointer, or nullptr if detached.
voidresetResets the adapter for reuse with a new socket and request. Clears the parser state and re-wires the sender without reallocating. Used by the connection pool to avoid destroying/recreating adapters.

{#connectionadapter-1}

ConnectionAdapter

ConnectionAdapter(Connection * connection, llhttp_type_t type)

Creates a ConnectionAdapter for the given connection.

Parameters

  • connection Owning HTTP connection.

  • type Parser type: HTTP_REQUEST for server side, HTTP_RESPONSE for client side.


{#send-12}

send

virtual

virtual ssize_t send(const char * data, size_t len, int flags)

Sends data to the peer, flushing the outgoing HTTP header first if needed.

Parameters

  • data Pointer to the data buffer.

  • len Number of bytes to send.

  • flags Send flags (unused for HTTP, used for WebSocket frame type).

Returns

Number of bytes sent, or -1 on error.


{#sendowned-11}

sendOwned

virtual

virtual ssize_t sendOwned(Buffer && buffer, int flags)

Sends an owned payload buffer to the connected peer.

The buffer is moved through the adapter chain and retained by the transport layer until async write completion.


{#removereceiver-2}

removeReceiver

void removeReceiver(SocketAdapter * adapter)

Remove the given receiver.

By default this function does nothing unless the given receiver matches the current receiver.


{#parser}

parser

Parser & parser()

Returns the HTTP parser instance.


{#connection-3}

connection

Connection * connection()

Returns the owning Connection pointer, or nullptr if detached.


{#reset-7}

reset

void reset(net::SocketAdapter * sender, http::Request * request)

Resets the adapter for reuse with a new socket and request. Clears the parser state and re-wires the sender without reallocating. Used by the connection pool to avoid destroying/recreating adapters.

Parameters

  • sender New socket adapter to send data through.

  • request New HTTP request object for the parser to populate.

Protected Attributes

ReturnNameDescription
Connection *_connection
Parser_parser

{#_connection}

_connection

Connection * _connection

{#_parser}

_parser

Parser _parser

Protected Methods

ReturnNameDescription
boolonSocketRecv virtualSocketAdapter interface.
voidonParserHeader virtualHTTP Parser interface.
voidonParserHeadersEnd virtualCalled when all HTTP headers have been parsed.
voidonParserChunk virtualCalled for each chunk of body data received.
voidonParserError virtualCalled when a parse error occurs.
voidonParserEnd virtualCalled when the HTTP message is fully parsed.

{#onsocketrecv-4}

onSocketRecv

virtual

virtual bool onSocketRecv(net::Socket & socket, const MutableBuffer & buffer, const net::Address & peerAddress)

SocketAdapter interface.


{#onparserheader}

onParserHeader

virtual

virtual void onParserHeader(const std::string & name, const std::string & value)

HTTP Parser interface.


{#onparserheadersend}

onParserHeadersEnd

virtual

virtual void onParserHeadersEnd(bool upgrade)

Called when all HTTP headers have been parsed.

Parameters

  • upgrade True if the connection should be upgraded (e.g. to WebSocket).

{#onparserchunk}

onParserChunk

virtual

virtual void onParserChunk(const char * data, size_t len)

Called for each chunk of body data received.

Parameters

  • data Pointer to the body data chunk.

  • len Length of the chunk in bytes.


{#onparsererror}

onParserError

virtual

virtual void onParserError(const icy::Error & err)

Called when a parse error occurs.

Parameters

  • err Error details from llhttp.

{#onparserend}

onParserEnd

virtual

virtual void onParserEnd()

Called when the HTTP message is fully parsed.

{#connectionpool}

ConnectionPool

#include <icy/http/server.h>

LIFO connection pool for reusing ServerConnection objects. Avoids per-request heap allocation by resetting and reusing connections instead of destroying and recreating them.

Public Methods

ReturnNameDescription
ServerConnection::Ptracquire inlineTakes a connection from the pool for reuse.
boolrelease inlineReturns a connection to the pool after use.
voidsetMaxSize inlineSets the maximum number of connections the pool will hold.
size_tsize const inlineReturns the current number of connections held in the pool.

{#acquire}

acquire

inline

inline ServerConnection::Ptr acquire()

Takes a connection from the pool for reuse.

Returns

A pooled connection, or nullptr if the pool is empty.


{#release}

release

inline

inline bool release(ServerConnection::Ptr & conn)

Returns a connection to the pool after use.

Parameters

  • conn The connection to return.

Returns

true if accepted into the pool; false if the pool is full.


{#setmaxsize}

setMaxSize

inline

inline void setMaxSize(size_t n)

Sets the maximum number of connections the pool will hold.

Parameters

  • n Maximum pool capacity.

{#size}

size

const inline

inline size_t size() const

Returns the current number of connections held in the pool.

Private Attributes

ReturnNameDescription
std::vector< ServerConnection::Ptr >_pool
size_t_maxSize

{#_pool}

_pool

std::vector< ServerConnection::Ptr > _pool

{#_maxsize}

_maxSize

size_t _maxSize = 128

{#connectionstream}

ConnectionStream

#include <icy/http/connection.h>

Inherits: SocketAdapter

Packet stream wrapper for an HTTP connection.

Public Attributes

ReturnNameDescription
PacketStreamOutgoingThe Outgoing stream is responsible for packetizing raw application data into the agreed upon HTTP format and sending it to the peer.
PacketStreamIncomingThe Incoming stream emits incoming HTTP packets for processing by the application.
ProgressSignalIncomingProgressFired on download progress.
ProgressSignalOutgoingProgressFired on upload progress.

{#outgoing}

Outgoing

PacketStream Outgoing

The Outgoing stream is responsible for packetizing raw application data into the agreed upon HTTP format and sending it to the peer.


{#incoming}

Incoming

PacketStream Incoming

The Incoming stream emits incoming HTTP packets for processing by the application.

This is useful for example when writing incoming data to a file.


{#incomingprogress-1}

IncomingProgress

ProgressSignal IncomingProgress

Fired on download progress.


{#outgoingprogress}

OutgoingProgress

ProgressSignal OutgoingProgress

Fired on upload progress.

Public Methods

ReturnNameDescription
ConnectionStreamCreates a ConnectionStream wrapping the given HTTP connection. Wires the Outgoing stream emitter to the connection adapter and registers this stream to receive incoming data from the adapter.
ssize_tsend virtualSend data via the Outgoing stream.
Connection::PtrconnectionReturn a reference to the underlying connection.

{#connectionstream-1}

ConnectionStream

ConnectionStream(Connection::Ptr connection)

Creates a ConnectionStream wrapping the given HTTP connection. Wires the Outgoing stream emitter to the connection adapter and registers this stream to receive incoming data from the adapter.

Parameters

  • connection The HTTP connection to wrap.

{#send-13}

send

virtual

virtual ssize_t send(const char * data, size_t len, int flags)

Send data via the Outgoing stream.


{#connection-4}

connection

Connection::Ptr connection()

Return a reference to the underlying connection.

Protected Attributes

ReturnNameDescription
Connection::Ptr_connection

{#_connection-1}

_connection

Connection::Ptr _connection

Protected Methods

ReturnNameDescription
boolonSocketRecv virtualCalled when data is received from the socket. Forwards the event to all registered receivers in priority order.

{#onsocketrecv-5}

onSocketRecv

virtual

virtual bool onSocketRecv(net::Socket & socket, const MutableBuffer & buffer, const net::Address & peerAddress)

Called when data is received from the socket. Forwards the event to all registered receivers in priority order.

Parameters

  • socket The socket that received data.

  • buffer The received data buffer.

  • peerAddress Address of the sender.

Returns

true to stop propagation to subsequent receivers.

{#cookie}

#include <icy/http/cookie.h>

HTTP cookie value plus its response/header attributes.

A cookie is a small amount of information sent by a Web server to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications. By default, cookies are created using Version 0 to ensure the best interoperability.

Public Methods

ReturnNameDescription
CookieCreates an empty Cookie.
Cookie explicitCreates a cookie with the given name. The cookie never expires.
Cookie explicitCreates a cookie from the given NVCollection.
CookieCreates a cookie with the given name and value. The cookie never expires.
CookieCreates the Cookie by copying another one.
~CookieDestroys the Cookie.
Cookie &operator=Assigns a cookie.
voidsetVersionSets the version of the cookie.
intgetVersion const inlineReturns the version of the cookie, which is either 0 or 1.
voidsetNameSets the name of the cookie.
const std::string &getName const inlineReturns the name of the cookie.
voidsetValueSets the value of the cookie.
const std::string &getValue const inlineReturns the value of the cookie.
voidsetCommentSets the comment for the cookie.
const std::string &getComment const inlineReturns the comment for the cookie.
voidsetDomainSets the domain for the cookie.
const std::string &getDomain const inlineReturns the domain for the cookie.
voidsetPathSets the path for the cookie.
const std::string &getPath const inlineReturns the path for the cookie.
voidsetSecureSets the value of the secure flag for the cookie.
boolgetSecure const inlineReturns the value of the secure flag for the cookie.
voidsetMaxAgeSets the maximum age in seconds for the cookie.
intgetMaxAge const inlineReturns the maximum age in seconds for the cookie.
voidsetHttpOnlySets the HttpOnly flag for the cookie.
boolgetHttpOnly const inlineReturns true if the cookie's HttpOnly flag is set.
std::stringtoString constReturns a std::string representation of the cookie, suitable for use in a Set-Cookie header.

{#cookie-1}

Cookie()

Creates an empty Cookie.


{#cookie-2}

explicit

explicit Cookie(const std::string & name)

Creates a cookie with the given name. The cookie never expires.


{#cookie-3}

explicit

explicit Cookie(const NVCollection & nvc)

Creates a cookie from the given NVCollection.


{#cookie-4}

Cookie(const std::string & name, const std::string & value)

Creates a cookie with the given name and value. The cookie never expires.

Note: If value contains whitespace or non-alphanumeric characters, the value should be escaped by calling escape() before passing it to the constructor.


{#cookie-5}

Cookie(const Cookie & cookie)

Creates the Cookie by copying another one.


{#cookie-6}

~Cookie()

Destroys the Cookie.


{#operator-14}

operator=

Cookie & operator=(const Cookie & cookie)

Assigns a cookie.


{#setversion}

setVersion

void setVersion(int version)

Sets the version of the cookie.

Version must be either 0 (denoting a Netscape cookie) or 1 (denoting a RFC 2109 cookie).


{#getversion}

getVersion

const inline

inline int getVersion() const

Returns the version of the cookie, which is either 0 or 1.


{#setname}

setName

void setName(const std::string & name)

Sets the name of the cookie.


{#getname}

getName

const inline

inline const std::string & getName() const

Returns the name of the cookie.


{#setvalue}

setValue

void setValue(const std::string & value)

Sets the value of the cookie.

According to the cookie specification, the size of the value should not exceed 4 Kbytes.

Note: If value contains whitespace or non-alphanumeric characters, the value should be escaped by calling escape() prior to passing it to setName().


{#getvalue}

getValue

const inline

inline const std::string & getValue() const

Returns the value of the cookie.


{#setcomment}

setComment

void setComment(const std::string & comment)

Sets the comment for the cookie.

Comments are only supported for version 1 cookies.


{#getcomment}

getComment

const inline

inline const std::string & getComment() const

Returns the comment for the cookie.


{#setdomain}

setDomain

void setDomain(const std::string & domain)

Sets the domain for the cookie.


{#getdomain}

getDomain

const inline

inline const std::string & getDomain() const

Returns the domain for the cookie.


{#setpath}

setPath

void setPath(const std::string & path)

Sets the path for the cookie.


{#getpath}

getPath

const inline

inline const std::string & getPath() const

Returns the path for the cookie.


{#setsecure}

setSecure

void setSecure(bool secure)

Sets the value of the secure flag for the cookie.


{#getsecure}

getSecure

const inline

inline bool getSecure() const

Returns the value of the secure flag for the cookie.


{#setmaxage}

setMaxAge

void setMaxAge(int maxAge)

Sets the maximum age in seconds for the cookie.

A value of -1 causes the cookie to never expire on the client.

A value of 0 deletes the cookie on the client.


{#getmaxage}

getMaxAge

const inline

inline int getMaxAge() const

Returns the maximum age in seconds for the cookie.


{#sethttponly}

setHttpOnly

void setHttpOnly(bool flag)

Sets the HttpOnly flag for the cookie.


{#gethttponly}

getHttpOnly

const inline

inline bool getHttpOnly() const

Returns true if the cookie's HttpOnly flag is set.


{#tostring-5}

toString

const

std::string toString() const

Returns a std::string representation of the cookie, suitable for use in a Set-Cookie header.

Public Static Methods

ReturnNameDescription
std::stringescape staticEscapes the given std::string by replacing all non-alphanumeric characters with escape sequences in the form xx, where xx is the hexadecimal character code.
std::stringunescape staticUnescapes the given std::string by replacing all escape sequences in the form xx with the respective characters.

{#escape}

escape

static

static std::string escape(std::string_view str)

Escapes the given std::string by replacing all non-alphanumeric characters with escape sequences in the form xx, where xx is the hexadecimal character code.


{#unescape}

unescape

static

static std::string unescape(std::string_view str)

Unescapes the given std::string by replacing all escape sequences in the form xx with the respective characters.

Private Attributes

ReturnNameDescription
int_version
std::string_name
std::string_value
std::string_comment
std::string_domain
std::string_path
bool_secure
int_maxAge
bool_httpOnly

{#_version}

_version

int _version

{#_name}

_name

std::string _name

{#_value}

_value

std::string _value

{#_comment}

_comment

std::string _comment

{#_domain}

_domain

std::string _domain

{#_path}

_path

std::string _path

{#_secure}

_secure

bool _secure

{#_maxage}

_maxAge

int _maxAge

{#_httponly}

_httpOnly

bool _httpOnly

{#filepart}

FilePart

#include <icy/http/form.h>

Inherits: FormPart

Form part backed by a file on disk.

Public Methods

ReturnNameDescription
FilePartCreates the FilePart for the given path.
FilePartCreates the FilePart for the given path and MIME type.
FilePartCreates the FilePart for the given path and MIME type. The given filename is used as part filename (see filename()) only.
~FilePart virtualDestroys the FilePart.
voidopen virtualOpens the file for reading.
voidreset virtualResets the file stream to the beginning and clears initial-write state.
boolwriteChunk virtualWrites the next chunk of the file to the FormWriter.
voidwrite virtualWrites the entire file content to the FormWriter.
voidwrite virtualWrites the entire file content to an output stream (used for content-length calculation).
const std::string &filename constReturns the filename component of the file path (not the full path).
std::ifstream &streamReturns a reference to the underlying file input stream.
uint64_tlength virtual constReturns the total file size in bytes.

{#filepart-1}

FilePart

FilePart(const std::string & path)

Creates the FilePart for the given path.

The MIME type is set to application/octet-stream.

Throws an FileException if the file cannot be opened.


{#filepart-2}

FilePart

FilePart(const std::string & path, const std::string & contentType)

Creates the FilePart for the given path and MIME type.

Throws an FileException if the file cannot be opened.


{#filepart-3}

FilePart

FilePart(const std::string & path, const std::string & filename, const std::string & contentType)

Creates the FilePart for the given path and MIME type. The given filename is used as part filename (see filename()) only.

Throws an FileException if the file cannot be opened.


{#filepart-4}

~FilePart

virtual

virtual ~FilePart()

Destroys the FilePart.


{#open-4}

open

virtual

virtual void open()

Opens the file for reading.

Exceptions

  • std::runtime_error if the file cannot be opened.

{#reset-8}

reset

virtual

virtual void reset()

Resets the file stream to the beginning and clears initial-write state.


{#writechunk}

writeChunk

virtual

virtual bool writeChunk(FormWriter & writer)

Writes the next chunk of the file to the FormWriter.

Parameters

  • writer The FormWriter to send the chunk through.

Returns

true if more data remains; false when the file is fully sent.


{#write-2}

write

virtual

virtual void write(FormWriter & writer)

Writes the entire file content to the FormWriter.

Parameters


{#write-3}

write

virtual

virtual void write(std::ostream & ostr)

Writes the entire file content to an output stream (used for content-length calculation).

Parameters

  • ostr Output stream to write to.

{#filename-1}

filename

const

const std::string & filename() const

Returns the filename component of the file path (not the full path).


{#stream-3}

stream

std::ifstream & stream()

Returns a reference to the underlying file input stream.


{#length-1}

length

virtual const

virtual uint64_t length() const

Returns the total file size in bytes.

Protected Attributes

ReturnNameDescription
std::string_path
std::string_filename
std::ifstream_istr
uint64_t_fileSize

{#_path-1}

_path

std::string _path

{#_filename-1}

_filename

std::string _filename

{#_istr}

_istr

std::ifstream _istr

{#_filesize}

_fileSize

uint64_t _fileSize

{#formpart}

FormPart

#include <icy/http/form.h>

Subclassed by: FilePart, StringPart

An implementation of FormPart.

Public Methods

ReturnNameDescription
FormPartCreates the FormPart with the given MIME content type.
~FormPart virtualDestroys the FormPart.
voidreset virtualResets the internal state and write position to the beginning. Called by FormWriter when retrying or recalculating content length.
boolwriteChunkWrites the next chunk of data to the FormWriter.
voidwriteWrites the entire part data to the FormWriter in one call.
voidwriteWrites the entire part data to an output stream (used for content-length calculation).
NVCollection &headersReturns the extra MIME headers for this part (e.g. Content-Disposition).
boolinitialWrite virtual constReturns true if this is the first write call since construction or reset().
const std::string &contentType constReturns the MIME content type for this part.
uint64_tlength constReturns the total byte length of the part data.

{#formpart-1}

FormPart

FormPart(const std::string & contentType)

Creates the FormPart with the given MIME content type.

Parameters

  • contentType MIME type for this part (default: "application/octet-stream").

{#formpart-2}

~FormPart

virtual

virtual ~FormPart()

Destroys the FormPart.


{#reset-9}

reset

virtual

virtual void reset()

Resets the internal state and write position to the beginning. Called by FormWriter when retrying or recalculating content length.


{#writechunk-1}

writeChunk

bool writeChunk(FormWriter & writer)

Writes the next chunk of data to the FormWriter.

Parameters

  • writer The FormWriter to send the chunk through.

Returns

true if more data remains to be written; false when complete.


{#write-4}

write

void write(FormWriter & writer)

Writes the entire part data to the FormWriter in one call.

Parameters


{#write-5}

write

void write(std::ostream & ostr)

Writes the entire part data to an output stream (used for content-length calculation).

Parameters

  • ostr Output stream to write to.

{#headers-1}

headers

NVCollection & headers()

Returns the extra MIME headers for this part (e.g. Content-Disposition).


{#initialwrite}

initialWrite

virtual const

virtual bool initialWrite() const

Returns true if this is the first write call since construction or reset().


{#contenttype-1}

contentType

const

const std::string & contentType() const

Returns the MIME content type for this part.


{#length-2}

length

const

uint64_t length() const

Returns the total byte length of the part data.

Protected Attributes

ReturnNameDescription
std::string_contentType
uint64_t_length
NVCollection_headers
bool_initialWrite

{#_contenttype}

_contentType

std::string _contentType

{#_length}

_length

uint64_t _length

{#_headers}

_headers

NVCollection _headers

{#_initialwrite}

_initialWrite

bool _initialWrite

{#formwriter}

FormWriter

#include <icy/http/form.h>

Inherits: NVCollection, PacketStreamAdapter, Startable

FormWriter is an HTTP client connection adapter for writing HTML forms.

This class runs in its own thread so as not to block the event loop while uploading big files. Class members are not synchronized hence they should not be accessed while the form is sending, not that there would be any reason to do so.

Public Attributes

ReturnNameDescription
PacketSignalemitterThe outgoing packet emitter.

{#emitter-6}

emitter

PacketSignal emitter

The outgoing packet emitter.

Public Methods

ReturnNameDescription
~FormWriter virtualDestroys the FormWriter.
voidaddPartAdds a part or file attachment to the multipart form.
voidstart virtualStarts the sending thread.
voidstop virtualStops the sending thread.
boolcomplete constReturns true if the request is complete.
boolcancelled constReturns true if the request is cancelled.
voidprepareSubmitPrepares the outgoing HTTP request object for submitting the form.
uint64_tcalculateMultipartContentLengthProcesses the entire form body and computes its total byte length. Only meaningful for multipart/form-data when not using chunked encoding.
voidwriteUrlWrites the complete "application/x-www-form-urlencoded" encoded body to ostr. All key-value pairs from the NVCollection base are percent-encoded and joined with '&'.
voidwriteMultipartChunkWrites the next pending multipart chunk to the connection. Non-blocking; intended to be called repeatedly from the event loop until all parts have been sent.
voidwriteAsyncWrites the next message chunk from the background runner thread. Called by the Runner; do not call directly.
voidsetEncodingSets the MIME encoding used for submitting the form. Must be set before prepareSubmit() is called.
const std::string &encoding constReturns the encoding used for posting the form.
voidsetBoundarySets the MIME boundary string used to delimit multipart form parts. If not set, a random boundary is generated by prepareSubmit(). Must be set before prepareSubmit() is called.
const std::string &boundary constReturns the MIME boundary used for writing multipart form data.
ConnectionStream &connectionThe associated HTTP client connection.

{#formwriter-1}

~FormWriter

virtual

virtual ~FormWriter()

Destroys the FormWriter.


{#addpart}

addPart

void addPart(const std::string & name, FormPart * part)

Adds a part or file attachment to the multipart form.

The FormWriter takes ownership of part and deletes it when done. Parts are only sent when the encoding is "multipart/form-data".

Parameters

  • name Form field name for this part.

  • part Part to add. Ownership is transferred.


{#start-10}

start

virtual

virtual void start()

Starts the sending thread.


{#stop-8}

stop

virtual

virtual void stop()

Stops the sending thread.


{#complete-1}

complete

const

bool complete() const

Returns true if the request is complete.


{#cancelled-1}

cancelled

const

bool cancelled() const

Returns true if the request is cancelled.


{#preparesubmit}

prepareSubmit

void prepareSubmit()

Prepares the outgoing HTTP request object for submitting the form.


{#calculatemultipartcontentlength}

calculateMultipartContentLength

uint64_t calculateMultipartContentLength()

Processes the entire form body and computes its total byte length. Only meaningful for multipart/form-data when not using chunked encoding.

Returns

Total content length in bytes.


{#writeurl}

writeUrl

void writeUrl(std::ostream & ostr)

Writes the complete "application/x-www-form-urlencoded" encoded body to ostr. All key-value pairs from the NVCollection base are percent-encoded and joined with '&'.

Parameters

  • ostr Output stream to write to.

{#writemultipartchunk}

writeMultipartChunk

void writeMultipartChunk()

Writes the next pending multipart chunk to the connection. Non-blocking; intended to be called repeatedly from the event loop until all parts have been sent.


{#writeasync}

writeAsync

void writeAsync()

Writes the next message chunk from the background runner thread. Called by the Runner; do not call directly.


{#setencoding}

setEncoding

void setEncoding(const std::string & encoding)

Sets the MIME encoding used for submitting the form. Must be set before prepareSubmit() is called.

Parameters

  • encoding MIME type: ENCODING_URL or ENCODING_MULTIPART_FORM.

{#encoding}

encoding

const

const std::string & encoding() const

Returns the encoding used for posting the form.


{#setboundary}

setBoundary

void setBoundary(const std::string & boundary)

Sets the MIME boundary string used to delimit multipart form parts. If not set, a random boundary is generated by prepareSubmit(). Must be set before prepareSubmit() is called.

Parameters

  • boundary Boundary string (without leading "--").

{#boundary}

boundary

const

const std::string & boundary() const

Returns the MIME boundary used for writing multipart form data.


{#connection-5}

connection

ConnectionStream & connection()

The associated HTTP client connection.

Public Static Attributes

ReturnNameDescription
const char *ENCODING_URL static"application/x-www-form-urlencoded"
const char *ENCODING_MULTIPART_FORM static"multipart/form-data"
const char *ENCODING_MULTIPART_RELATED static"multipart/related" http://tools.ietf.org/html/rfc2387

{#encoding_url}

ENCODING_URL

static

const char * ENCODING_URL

"application/x-www-form-urlencoded"


{#encoding_multipart_form}

ENCODING_MULTIPART_FORM

static

const char * ENCODING_MULTIPART_FORM

"multipart/form-data"


{#encoding_multipart_related}

static

const char * ENCODING_MULTIPART_RELATED

"multipart/related" http://tools.ietf.org/html/rfc2387

Public Static Methods

ReturnNameDescription
FormWriter *create staticCreates a FormWriter for the given connection and encoding.

{#create-7}

create

static

static FormWriter * create(ConnectionStream & conn, const std::string & encoding)

Creates a FormWriter for the given connection and encoding.

Encoding must be either "application/x-www-form-urlencoded" (which is the default) or "multipart/form-data".

Parameters

  • conn The HTTP connection stream to write form data to.

  • encoding MIME encoding type.

Returns

Heap-allocated FormWriter. The caller owns the returned pointer.

Protected Attributes

ReturnNameDescription
ConnectionStream &_stream
std::shared_ptr< Runner >_runner
std::string_encoding
std::string_boundary
PartQueue_parts
uint64_t_filesLength
int_writeState
bool_initial
bool_complete

{#_stream}

_stream

ConnectionStream & _stream

{#_runner}

_runner

std::shared_ptr< Runner > _runner

{#_encoding}

_encoding

std::string _encoding

{#_boundary}

_boundary

std::string _boundary

{#_parts}

_parts

PartQueue _parts

{#_fileslength}

_filesLength

uint64_t _filesLength

{#_writestate}

_writeState

int _writeState

{#_initial}

_initial

bool _initial

{#_complete-1}

_complete

bool _complete

Protected Methods

ReturnNameDescription
FormWriterCreates the FormWriter that uses the given encoding.
FormWriterDeleted constructor.
FormWriterDeleted constructor.
voidwritePartHeaderWrites the message boundary std::string, followed by the message header to the output stream.
voidwriteEndWrites the final boundary std::string to the output stream.
voidupdateProgress virtualUpdates the upload progress via the associated ConnectionStream object.

{#formwriter-2}

FormWriter

FormWriter(ConnectionStream & conn, std::shared_ptr< Runner > runner, const std::string & encoding)

Creates the FormWriter that uses the given encoding.


{#formwriter-3}

FormWriter

FormWriter(const FormWriter &) = delete

Deleted constructor.


{#formwriter-4}

FormWriter

FormWriter(FormWriter &&) = delete

Deleted constructor.


{#writepartheader}

writePartHeader

void writePartHeader(const NVCollection & header, std::ostream & ostr)

Writes the message boundary std::string, followed by the message header to the output stream.


{#writeend}

writeEnd

void writeEnd(std::ostream & ostr)

Writes the final boundary std::string to the output stream.


{#updateprogress}

updateProgress

virtual

virtual void updateProgress(int nread)

Updates the upload progress via the associated ConnectionStream object.

{#part}

Part

#include <icy/http/form.h>

Individual part within a multipart form submission.

Public Attributes

ReturnNameDescription
std::stringname
std::unique_ptr< FormPart >part

{#name-5}

name

std::string name

{#part-1}

part

std::unique_ptr< FormPart > part

{#message}

Message

#include <icy/http/message.h>

Inherits: NVCollection Subclassed by: Request, Response

The base class for Request and Response.

Defines the common properties of all HTTP messages. These are version, content length, content type and transfer encoding.

Public Methods

ReturnNameDescription
voidsetVersionSets the HTTP version for this message.
const std::string &getVersion constReturns the HTTP version for this message.
voidsetContentLengthSets the Content-Length header.
uint64_tgetContentLength constReturns the content length for this message, which may be UNKNOWN_CONTENT_LENGTH if no Content-Length header is present.
boolhasContentLength constReturns true if a Content-Length header is present.
voidsetTransferEncodingSets the transfer encoding for this message.
const std::string &getTransferEncoding constReturns the transfer encoding used for this message.
voidsetChunkedTransferEncodingIf flag is true, sets the Transfer-Encoding header to chunked. Otherwise, removes the Transfer-Encoding header.
boolisChunkedTransferEncoding constReturns true if the Transfer-Encoding header is set and its value is chunked.
voidsetContentTypeSets the content type for this message.
const std::string &getContentType constReturns the content type for this message.
voidsetKeepAliveSets the value of the Connection header field.
boolgetKeepAlive constReturns true if
voidwrite virtual constWrites the message header to the given output stream.
voidwrite virtual constWrites the message header to the given output string.
voidwrite virtual constWrites the message header directly into a byte buffer.

{#setversion-1}

setVersion

void setVersion(const std::string & version)

Sets the HTTP version for this message.


{#getversion-1}

getVersion

const

const std::string & getVersion() const

Returns the HTTP version for this message.


{#setcontentlength}

setContentLength

void setContentLength(uint64_t length)

Sets the Content-Length header.

If length is UNKNOWN_CONTENT_LENGTH, removes the Content-Length header.


{#getcontentlength}

getContentLength

const

uint64_t getContentLength() const

Returns the content length for this message, which may be UNKNOWN_CONTENT_LENGTH if no Content-Length header is present.


{#hascontentlength}

hasContentLength

const

bool hasContentLength() const

Returns true if a Content-Length header is present.


{#settransferencoding}

setTransferEncoding

void setTransferEncoding(const std::string & transferEncoding)

Sets the transfer encoding for this message.

The value should be either IDENTITY_TRANSFER_CODING or CHUNKED_TRANSFER_CODING.


{#gettransferencoding}

getTransferEncoding

const

const std::string & getTransferEncoding() const

Returns the transfer encoding used for this message.

Normally, this is the value of the Transfer-Encoding header field. If no such field is present, returns IDENTITY_TRANSFER_CODING.


{#setchunkedtransferencoding}

setChunkedTransferEncoding

void setChunkedTransferEncoding(bool flag)

If flag is true, sets the Transfer-Encoding header to chunked. Otherwise, removes the Transfer-Encoding header.


{#ischunkedtransferencoding}

isChunkedTransferEncoding

const

bool isChunkedTransferEncoding() const

Returns true if the Transfer-Encoding header is set and its value is chunked.


{#setcontenttype}

setContentType

void setContentType(const std::string & contentType)

Sets the content type for this message.

Specify NO_CONTENT_TYPE to remove the Content-Type header.


{#getcontenttype}

getContentType

const

const std::string & getContentType() const

Returns the content type for this message.

If no Content-Type header is present, returns UNKNOWN_CONTENT_TYPE.


{#setkeepalive-1}

setKeepAlive

void setKeepAlive(bool keepAlive)

Sets the value of the Connection header field.

The value is set to "Keep-Alive" if keepAlive is true, or to "Close" otherwise.


{#getkeepalive}

getKeepAlive

const

bool getKeepAlive() const

Returns true if

  • the message has a Connection header field and its value is "Keep-Alive"

  • the message is an HTTP/1.1 message and no Connection header is set Returns false otherwise.


{#write-6}

write

virtual const

virtual void write(std::ostream & ostr) const

Writes the message header to the given output stream.

The format is one name-value pair per line, with name and value separated by a colon and lines delimited by a carriage return and a linefeed character. See RFC 2822 for details.


{#write-7}

write

virtual const

virtual void write(std::string & str) const

Writes the message header to the given output string.


{#write-8}

write

virtual const

virtual void write(Buffer & buf) const

Writes the message header directly into a byte buffer.

Public Static Attributes

ReturnNameDescription
const std::stringHTTP_1_0 static
const std::stringHTTP_1_1 static
const std::stringIDENTITY_TRANSFER_ENCODING static
const std::stringCHUNKED_TRANSFER_ENCODING static
const intUNKNOWN_CONTENT_LENGTH static
const std::stringUNKNOWN_CONTENT_TYPE static
const std::stringCONTENT_LENGTH static
const std::stringCONTENT_TYPE static
const std::stringTRANSFER_ENCODING static
const std::stringCONNECTION static
const std::stringCONNECTION_KEEP_ALIVE static
const std::stringCONNECTION_CLOSE static
const std::stringEMPTY static

{#http_1_0}

HTTP_1_0

static

const std::string HTTP_1_0

{#http_1_1}

HTTP_1_1

static

const std::string HTTP_1_1

{#identity_transfer_encoding}

IDENTITY_TRANSFER_ENCODING

static

const std::string IDENTITY_TRANSFER_ENCODING

{#chunked_transfer_encoding}

CHUNKED_TRANSFER_ENCODING

static

const std::string CHUNKED_TRANSFER_ENCODING

{#unknown_content_length}

UNKNOWN_CONTENT_LENGTH

static

const int UNKNOWN_CONTENT_LENGTH

{#unknown_content_type}

UNKNOWN_CONTENT_TYPE

static

const std::string UNKNOWN_CONTENT_TYPE

{#content_length}

CONTENT_LENGTH

static

const std::string CONTENT_LENGTH

{#content_type}

CONTENT_TYPE

static

const std::string CONTENT_TYPE

{#transfer_encoding}

TRANSFER_ENCODING

static

const std::string TRANSFER_ENCODING

{#connection-6}

CONNECTION

static

const std::string CONNECTION

{#connection_keep_alive}

CONNECTION_KEEP_ALIVE

static

const std::string CONNECTION_KEEP_ALIVE

{#connection_close}

CONNECTION_CLOSE

static

const std::string CONNECTION_CLOSE

{#empty}

EMPTY

static

const std::string EMPTY

Protected Attributes

ReturnNameDescription
std::string_version

{#_version-1}

_version

std::string _version

Protected Methods

ReturnNameDescription
MessageCreates the Message with version HTTP/1.0.
MessageCreates the Message and sets the version.
~Message virtualDestroys the Message.

{#message-1}

Message

Message()

Creates the Message with version HTTP/1.0.


{#message-2}

Message

Message(const std::string & version)

Creates the Message and sets the version.


{#message-3}

~Message

virtual

virtual ~Message()

Destroys the Message.

{#multipartadapter}

MultipartAdapter

#include <icy/http/packetizers.h>

Inherits: PacketProcessor

HTTP multipart encoding adapter for multipart/x-mixed-replace streaming.

Public Attributes

ReturnNameDescription
Connection::PtrconnectionHTTP connection for sending the initial response header.
std::stringcontentTypeContent-Type of each part (e.g. "image/jpeg").
boolisBase64If true, adds "Content-Transfer-Encoding: base64" to each part.
boolinitialTrue until the first chunk is processed and the boundary header emitted.
PacketSignalemitter

{#connection-7}

connection

Connection::Ptr connection

HTTP connection for sending the initial response header.


{#contenttype-2}

contentType

std::string contentType

Content-Type of each part (e.g. "image/jpeg").


{#isbase64}

isBase64

bool isBase64

If true, adds "Content-Transfer-Encoding: base64" to each part.


{#initial-1}

initial

bool initial

True until the first chunk is processed and the boundary header emitted.


{#emitter-7}

emitter

PacketSignal emitter

Public Methods

ReturnNameDescription
MultipartAdapter inlineCreates a MultipartAdapter that sends headers through the given connection. The per-part content type is read from the connection's outgoing header.
MultipartAdapter inlineCreates a MultipartAdapter that emits its own raw HTTP/1.1 200 response header. Use this when no Connection object is available.
voidemitHeader virtual inlineEmits the initial HTTP/1.1 200 OK response with Content-Type multipart/x-mixed-replace. If a connection is set, headers are written through it; otherwise a raw response string is emitted.
voidemitChunkHeader virtual inlineEmits the MIME boundary and per-part headers (Content-Type, optionally Content-Transfer-Encoding) for the next multipart chunk.
voidprocess virtual inlineWraps the incoming packet as a multipart chunk and emits it downstream. Emits the multipart HTTP response headers on the first call.

{#multipartadapter-1}

MultipartAdapter

inline

inline MultipartAdapter(Connection::Ptr connection, bool base64)

Creates a MultipartAdapter that sends headers through the given connection. The per-part content type is read from the connection's outgoing header.

Parameters

  • connection HTTP connection to use for sending the initial multipart header.

  • [base64](base.md#base64) If true, indicates parts are base64-encoded.


{#multipartadapter-2}

MultipartAdapter

inline

inline MultipartAdapter(const std::string & contentType, bool base64)

Creates a MultipartAdapter that emits its own raw HTTP/1.1 200 response header. Use this when no Connection object is available.

Parameters

  • contentType Content-Type for each multipart part.

  • [base64](base.md#base64) If true, indicates parts are base64-encoded.


{#emitheader-1}

emitHeader

virtual inline

virtual inline void emitHeader()

Emits the initial HTTP/1.1 200 OK response with Content-Type multipart/x-mixed-replace. If a connection is set, headers are written through it; otherwise a raw response string is emitted.


{#emitchunkheader}

emitChunkHeader

virtual inline

virtual inline void emitChunkHeader()

Emits the MIME boundary and per-part headers (Content-Type, optionally Content-Transfer-Encoding) for the next multipart chunk.


{#process-6}

process

virtual inline

virtual inline void process(IPacket & packet)

Wraps the incoming packet as a multipart chunk and emits it downstream. Emits the multipart HTTP response headers on the first call.

Parameters

  • packet Packet containing the raw payload data.

{#parser-1}

Parser

#include <icy/http/parser.h>

HTTP request/response parser using the llhttp library.

Public Methods

ReturnNameDescription
ParserCreates a response parser. The response object is populated as data is parsed.
ParserCreates a request parser. The request object is populated as data is parsed.
ParserCreates a parser of the given type without binding a message object.
ParserDeleted constructor.
ParserDeleted constructor.
ParseResultparseFeeds a buffer of raw HTTP data into the parser.
voidresetReset the internal state (reinitialises llhttp). Safe to call externally, NOT from inside llhttp callbacks.
voidresetStateReset internal flags without reinitialising llhttp. Safe to call from inside llhttp callbacks (e.g. on_message_begin).
boolcomplete constReturns true if parsing is complete, either in success or error.
boolupgrade constReturns true if the connection should be upgraded.
llhttp_type_ttype const inlineReturns the parser type (HTTP_REQUEST or HTTP_RESPONSE).
voidsetRequestBinds an HTTP request object to populate during parsing. Must only be called when no message is currently set and type is HTTP_REQUEST.
voidsetResponseBinds an HTTP response object to populate during parsing. Must only be called when no message is currently set and type is HTTP_RESPONSE.
voidsetObserverSets the observer that receives parser events.
voidclearMessageClear request/response pointers so they can be re-set. Used when resetting a pooled connection for reuse.
http::Message *messageReturns the currently bound message (request or response), or nullptr.
ParserObserver *observer constReturns the current parser observer, or nullptr if none is set.

{#parser-2}

Parser

Parser(http::Response * response)

Creates a response parser. The response object is populated as data is parsed.

Parameters

  • response HTTP response object to populate.

{#parser-3}

Parser

Parser(http::Request * request)

Creates a request parser. The request object is populated as data is parsed.

Parameters

  • request HTTP request object to populate.

{#parser-4}

Parser

Parser(llhttp_type_t type)

Creates a parser of the given type without binding a message object.

Parameters

  • type Either HTTP_REQUEST or HTTP_RESPONSE.

{#parser-5}

Parser

Parser(const Parser &) = delete

Deleted constructor.


{#parser-6}

Parser

Parser(Parser &&) = delete

Deleted constructor.


{#parse}

parse

ParseResult parse(const char * data, size_t length)

Feeds a buffer of raw HTTP data into the parser.

May be called multiple times for streaming data. The parser state persists between calls. On completion or error, the observer is notified.

Parameters

  • data Pointer to the input data buffer.

  • length Number of bytes in the buffer.

Returns

Structured parse result including bytes consumed and terminal state.


{#reset-10}

reset

void reset()

Reset the internal state (reinitialises llhttp). Safe to call externally, NOT from inside llhttp callbacks.


{#resetstate}

resetState

void resetState()

Reset internal flags without reinitialising llhttp. Safe to call from inside llhttp callbacks (e.g. on_message_begin).


{#complete-2}

complete

const

bool complete() const

Returns true if parsing is complete, either in success or error.


{#upgrade}

upgrade

const

bool upgrade() const

Returns true if the connection should be upgraded.


{#type-9}

type

const inline

inline llhttp_type_t type() const

Returns the parser type (HTTP_REQUEST or HTTP_RESPONSE).


{#setrequest}

setRequest

void setRequest(http::Request * request)

Binds an HTTP request object to populate during parsing. Must only be called when no message is currently set and type is HTTP_REQUEST.

Parameters

  • request The request object to populate.

{#setresponse}

setResponse

void setResponse(http::Response * response)

Binds an HTTP response object to populate during parsing. Must only be called when no message is currently set and type is HTTP_RESPONSE.

Parameters

  • response The response object to populate.

{#setobserver}

setObserver

void setObserver(ParserObserver * observer)

Sets the observer that receives parser events.

Parameters

  • observer Observer to notify. May be nullptr to clear.

{#clearmessage}

clearMessage

void clearMessage()

Clear request/response pointers so they can be re-set. Used when resetting a pooled connection for reuse.


{#message-4}

message

http::Message * message()

Returns the currently bound message (request or response), or nullptr.


{#observer}

observer

const

ParserObserver * observer() const

Returns the current parser observer, or nullptr if none is set.

Protected Attributes

ReturnNameDescription
ParserObserver *_observer
http::Request *_request
http::Response *_response
http::Message *_message
llhttp_t_parser
llhttp_settings_t_settings
llhttp_type_t_type
bool_wasHeaderValue
std::string_lastHeaderField
std::string_lastHeaderValue
bool_complete
bool_upgrade
Error_error
ParseResult_lastResult
MessageScratch_scratch

{#_observer}

_observer

ParserObserver * _observer

{#_request-1}

_request

http::Request * _request

{#_response-1}

_response

http::Response * _response

{#_message}

_message

http::Message * _message

{#_parser-1}

_parser

llhttp_t _parser

{#_settings}

_settings

llhttp_settings_t _settings

{#_type}

_type

llhttp_type_t _type

{#_washeadervalue}

_wasHeaderValue

bool _wasHeaderValue

{#_lastheaderfield}

_lastHeaderField

std::string _lastHeaderField

{#_lastheadervalue}

_lastHeaderValue

std::string _lastHeaderValue

{#_complete-2}

_complete

bool _complete

{#_upgrade}

_upgrade

bool _upgrade

{#_error-3}

_error

Error _error

{#_lastresult}

_lastResult

ParseResult _lastResult

{#_scratch}

_scratch

MessageScratch _scratch

Protected Methods

ReturnNameDescription
voidinit
voidclearBoundMessage
voidstoreHeader
voidapplyScratchToBoundMessage
voidonHeaderCallbacks.
voidonHeadersEnd
voidonBody
voidonMessageEnd
voidonError

{#init-8}

init

void init()

{#clearboundmessage}

clearBoundMessage

void clearBoundMessage()

{#storeheader}

storeHeader

void storeHeader(std::string name, std::string value)

{#applyscratchtoboundmessage}

applyScratchToBoundMessage

void applyScratchToBoundMessage()

{#onheader}

onHeader

void onHeader(std::string name, std::string value)

Callbacks.


{#onheadersend}

onHeadersEnd

void onHeadersEnd()

{#onbody}

onBody

void onBody(const char * buf, size_t len)

{#onmessageend}

onMessageEnd

void onMessageEnd()

{#onerror-3}

onError

void onError(llhttp_errno_t errnum, const std::string & message)

{#messagescratch}

MessageScratch

#include <icy/http/parser.h>

Public Attributes

ReturnNameDescription
std::stringversion
std::stringmethod
std::stringuri
std::stringreason
http::StatusCodestatus
std::vector< std::pair< std::string, std::string > >headers

{#version-2}

version

std::string version

{#method-1}

method

std::string method

{#uri}

uri

std::string uri

{#reason}

reason

std::string reason

{#status-2}

status

http::StatusCode status = 

{#headers-2}

headers

std::vector< std::pair< std::string, std::string > > headers

Public Methods

ReturnNameDescription
voidreset inline

{#reset-11}

reset

inline

inline void reset()

{#parseresult}

ParseResult

#include <icy/http/parser.h>

Public Attributes

ReturnNameDescription
size_tbytesConsumed
boolmessageComplete
boolupgrade
Errorerror

{#bytesconsumed}

bytesConsumed

size_t bytesConsumed = 0

{#messagecomplete}

messageComplete

bool messageComplete = false

{#upgrade-1}

upgrade

bool upgrade = false

{#error-11}

error

Error error

Public Methods

ReturnNameDescription
boolok const inline

{#ok}

ok

const inline

inline bool ok() const

{#parserobserver}

ParserObserver

#include <icy/http/parser.h>

Subclassed by: ConnectionAdapter

Abstract observer interface for HTTP parser events.

Public Methods

ReturnNameDescription
voidonParserHeaderCalled for each parsed HTTP header name/value pair.
voidonParserHeadersEndCalled when all HTTP headers have been parsed.
voidonParserChunkCalled for each chunk of body data received.
voidonParserEndCalled when the HTTP message is fully parsed.
voidonParserErrorCalled when a parse error occurs.

{#onparserheader-1}

onParserHeader

void onParserHeader(const std::string & name, const std::string & value)

Called for each parsed HTTP header name/value pair.

Parameters

  • name Header field name.

  • value Header field value.


{#onparserheadersend-1}

onParserHeadersEnd

void onParserHeadersEnd(bool upgrade)

Called when all HTTP headers have been parsed.

Parameters

  • upgrade True if the connection should be upgraded (e.g. to WebSocket).

{#onparserchunk-1}

onParserChunk

void onParserChunk(const char * data, size_t len)

Called for each chunk of body data received.

Parameters

  • data Pointer to the body data chunk.

  • len Length of the chunk in bytes.


{#onparserend-1}

onParserEnd

void onParserEnd()

Called when the HTTP message is fully parsed.


{#onparsererror-1}

onParserError

void onParserError(const Error & err)

Called when a parse error occurs.

Parameters

  • err Error details from llhttp.

{#progresssignal}

ProgressSignal

#include <icy/http/connection.h>

Inherits: Signal< void(const double &)>

HTTP progress signal for upload and download progress notifications.

Emits a double in the range [0, 100] as data is transferred. Set total to the expected byte count before calling [update()](#update-1).

Public Attributes

ReturnNameDescription
void *senderOptional context pointer identifying the sender.
uint64_tcurrentBytes transferred so far.
uint64_ttotalTotal expected bytes (from Content-Length).

{#sender-1}

sender

void * sender

Optional context pointer identifying the sender.


{#current-1}

current

uint64_t current

Bytes transferred so far.


{#total-1}

total

uint64_t total

Total expected bytes (from Content-Length).

Public Methods

ReturnNameDescription
ProgressSignal inline
doubleprogress const inlineReturns the current transfer progress as a percentage (0-100).
voidupdate inlineAdvances the progress counter by nread bytes and emits the updated percentage.

{#progresssignal-1}

ProgressSignal

inline

inline ProgressSignal()

{#progress}

progress

const inline

inline double progress() const

Returns the current transfer progress as a percentage (0-100).


{#update-1}

update

inline

inline void update(int nread)

Advances the progress counter by nread bytes and emits the updated percentage.

Parameters

  • nread Number of bytes just transferred.

Exceptions

  • std::runtime_error if current would exceed total.

{#request-4}

Request

#include <icy/http/request.h>

Inherits: Message

HTTP request message with method, URI, headers, and optional body.

In addition to the properties common to all HTTP messages, an HTTP request has a method (e.g. GET, HEAD, POST, etc.) and a request URI.

Public Methods

ReturnNameDescription
RequestCreates a GET / HTTP/1.1 HTTP request.
RequestCreates a GET / HTTP/1.x request with the given version (HTTP/1.0 or HTTP/1.1).
RequestCreates an HTTP/1.0 request with the given method and URI.
RequestCreates an HTTP request with the given method, URI and version.
~Request virtualDestroys the Request.
voidsetMethodSets the method.
const std::string &getMethod constReturns the method.
voidsetURISets the request URI.
voidappendURIAppends a fragment to the request URI. Used by the parser when llhttp splits the URL across callbacks.
const std::string &getURI constReturns the request URI.
voidsetHostSets the value of the Host header field.
voidsetHostSets the value of the Host header field.
const std::string &getHost constReturns the value of the Host header field.
voidsetCookiesAdds a Cookie header with the names and values from cookies.
voidgetCookies constFills cookies with the cookies extracted from the Cookie headers in the request.
voidgetURIParameters constReturns the request URI parameters.
boolhasCredentials constReturns true if the request contains authentication information in the form of an Authorization header.
voidgetCredentials constReturns the authentication scheme and additional authentication information contained in this request.
voidsetCredentialsSets the authentication scheme and information for this request.
boolhasProxyCredentials constReturns true if the request contains proxy authentication information in the form of an Proxy-Authorization header.
voidgetProxyCredentials constReturns the proxy authentication scheme and additional proxy authentication information contained in this request.
voidsetProxyCredentialsSets the proxy authentication scheme and information for this request.
voidwrite virtual constWrites the HTTP request to the given output stream.
voidwrite virtual constWrites the HTTP request to the given output string.
voidwrite virtual constWrites the HTTP request directly into a byte buffer.

{#request-5}

Request

Request()

Creates a GET / HTTP/1.1 HTTP request.


{#request-6}

Request

Request(const std::string & version)

Creates a GET / HTTP/1.x request with the given version (HTTP/1.0 or HTTP/1.1).


{#request-7}

Request

Request(const std::string & method, const std::string & uri)

Creates an HTTP/1.0 request with the given method and URI.


{#request-8}

Request

Request(const std::string & method, const std::string & uri, const std::string & version)

Creates an HTTP request with the given method, URI and version.


{#request-9}

~Request

virtual

virtual ~Request()

Destroys the Request.


{#setmethod}

setMethod

void setMethod(const std::string & method)

Sets the method.


{#getmethod}

getMethod

const

const std::string & getMethod() const

Returns the method.


{#seturi}

setURI

void setURI(std::string uri)

Sets the request URI.


{#appenduri}

appendURI

void appendURI(std::string_view uri)

Appends a fragment to the request URI. Used by the parser when llhttp splits the URL across callbacks.


{#geturi}

getURI

const

const std::string & getURI() const

Returns the request URI.


{#sethost}

setHost

void setHost(const std::string & host)

Sets the value of the Host header field.


{#sethost-1}

setHost

void setHost(const std::string & host, uint16_t port)

Sets the value of the Host header field.

If the given port number is a non-standard port number (other than 80 or 443), it is included in the Host header field.


{#gethost}

getHost

const

const std::string & getHost() const

Returns the value of the Host header field.

Throws a NotFoundException if the request does not have a Host header field.


{#setcookies}

setCookies

void setCookies(const NVCollection & cookies)

Adds a Cookie header with the names and values from cookies.


{#getcookies}

getCookies

const

void getCookies(NVCollection & cookies) const

Fills cookies with the cookies extracted from the Cookie headers in the request.


{#geturiparameters}

getURIParameters

const

void getURIParameters(NVCollection & params) const

Returns the request URI parameters.


{#hascredentials}

hasCredentials

const

bool hasCredentials() const

Returns true if the request contains authentication information in the form of an Authorization header.


{#getcredentials}

getCredentials

const

void getCredentials(std::string & scheme, std::string & authInfo) const

Returns the authentication scheme and additional authentication information contained in this request.

Throws a std::exception if no authentication information is contained in the request.


{#setcredentials}

setCredentials

void setCredentials(std::string_view scheme, std::string_view authInfo)

Sets the authentication scheme and information for this request.


{#hasproxycredentials}

hasProxyCredentials

const

bool hasProxyCredentials() const

Returns true if the request contains proxy authentication information in the form of an Proxy-Authorization header.


{#getproxycredentials}

getProxyCredentials

const

void getProxyCredentials(std::string & scheme, std::string & authInfo) const

Returns the proxy authentication scheme and additional proxy authentication information contained in this request.

Throws a std::exception if no proxy authentication information is contained in the request.


{#setproxycredentials}

setProxyCredentials

void setProxyCredentials(std::string_view scheme, std::string_view authInfo)

Sets the proxy authentication scheme and information for this request.


{#write-9}

write

virtual const

virtual void write(std::ostream & ostr) const

Writes the HTTP request to the given output stream.


{#write-10}

write

virtual const

virtual void write(std::string & str) const

Writes the HTTP request to the given output string.


{#write-11}

write

virtual const

virtual void write(Buffer & buf) const

Writes the HTTP request directly into a byte buffer.

Protected Methods

ReturnNameDescription
voidgetCredentials constReturns the authentication scheme and additional authentication information contained in the given header of request.
voidsetCredentialsWrites the authentication scheme and information for this request to the given header.

{#getcredentials-1}

getCredentials

const

void getCredentials(const std::string & header, std::string & scheme, std::string & authInfo) const

Returns the authentication scheme and additional authentication information contained in the given header of request.

Throws a NotAuthenticatedException if no authentication information is contained in the request.


{#setcredentials-1}

setCredentials

void setCredentials(const std::string & header, std::string_view scheme, std::string_view authInfo)

Writes the authentication scheme and information for this request to the given header.

Private Attributes

ReturnNameDescription
std::string_method
std::string_uri

{#_method}

_method

std::string _method

{#_uri}

_uri

std::string _uri

{#response-1}

Response

#include <icy/http/response.h>

Inherits: Message

HTTP response message with status, reason phrase, headers, and body metadata.

Public Methods

ReturnNameDescription
ResponseCreates the Response with OK status.
ResponseCreates the Response with the given status and reason phrase.
ResponseCreates the Response with the given version, status and reason phrase.
ResponseCreates the Response with the given status and an appropriate reason phrase.
ResponseCreates the Response with the given version, status and an appropriate reason phrase.
~Response virtualDestroys the Response.
voidsetStatusSets the HTTP status code.
StatusCodegetStatus constReturns the HTTP status code.
voidsetReasonSets the HTTP reason phrase.
const std::string &getReason constReturns the HTTP reason phrase.
voidsetStatusAndReasonSets the HTTP status code and reason phrase.
voidsetDateSets the Date header to the given date/time value.
TimestampgetDate constReturns the value of the Date header.
voidaddCookieAdds the cookie to the response by adding a Set-Cookie header.
voidgetCookies constReturns a vector with all the cookies set in the response header.
voidwrite virtual constWrites the HTTP response headers to the given output stream.
voidwrite virtual constWrites the HTTP response headers to the given output string.
voidwrite virtual constWrites the HTTP response headers directly into a byte buffer.
boolsuccess virtual constReturns true if the HTTP response code was successful (< 400).

{#response-2}

Response

Response()

Creates the Response with OK status.


{#response-3}

Response

Response(StatusCode status, const std::string & reason)

Creates the Response with the given status and reason phrase.


{#response-4}

Response

Response(const std::string & version, StatusCode status, const std::string & reason)

Creates the Response with the given version, status and reason phrase.


{#response-5}

Response

Response(StatusCode status)

Creates the Response with the given status and an appropriate reason phrase.


{#response-6}

Response

Response(const std::string & version, StatusCode status)

Creates the Response with the given version, status and an appropriate reason phrase.


{#response-7}

~Response

virtual

virtual ~Response()

Destroys the Response.


{#setstatus}

setStatus

void setStatus(StatusCode status)

Sets the HTTP status code.

The reason phrase is set according to the status code.


{#getstatus}

getStatus

const

StatusCode getStatus() const

Returns the HTTP status code.


{#setreason}

setReason

void setReason(const std::string & reason)

Sets the HTTP reason phrase.


{#getreason}

getReason

const

const std::string & getReason() const

Returns the HTTP reason phrase.


{#setstatusandreason}

setStatusAndReason

void setStatusAndReason(StatusCode status, const std::string & reason)

Sets the HTTP status code and reason phrase.


{#setdate}

setDate

void setDate(const Timestamp & dateTime)

Sets the Date header to the given date/time value.


{#getdate}

getDate

const

Timestamp getDate() const

Returns the value of the Date header.


{#addcookie}

addCookie

void addCookie(const Cookie & cookie)

Adds the cookie to the response by adding a Set-Cookie header.


{#getcookies-1}

getCookies

const

void getCookies(std::vector< Cookie > & cookies) const

Returns a vector with all the cookies set in the response header.

May throw an exception in case of a malformed Set-Cookie header.


{#write-12}

write

virtual const

virtual void write(std::ostream & ostr) const

Writes the HTTP response headers to the given output stream.


{#write-13}

write

virtual const

virtual void write(std::string & str) const

Writes the HTTP response headers to the given output string.


{#write-14}

write

virtual const

virtual void write(Buffer & buf) const

Writes the HTTP response headers directly into a byte buffer.


{#success}

success

virtual const

virtual bool success() const

Returns true if the HTTP response code was successful (< 400).

Private Attributes

ReturnNameDescription
StatusCode_status
std::string_reason

{#_status}

_status

StatusCode _status

{#_reason}

_reason

std::string _reason

{#server}

Server

#include <icy/http/server.h>

Inherits: SocketAdapter

HTTP server implementation.

This HTTP server is not strictly standards compliant. It was created to be a fast (nocopy where possible) solution for streaming media to web browsers.

Public Attributes

ReturnNameDescription
LocalSignal< void(ServerConnection::Ptr)>ConnectionSignals when a new connection has been created. A reference to the new connection object is provided.
LocalSignal< void()>ShutdownSignals when the server is shutting down.

{#connection-8}

Connection

LocalSignal< void(ServerConnection::Ptr)> Connection

Signals when a new connection has been created. A reference to the new connection object is provided.


{#shutdown-7}

Shutdown

LocalSignal< void()> Shutdown

Signals when the server is shutting down.

Public Methods

ReturnNameDescription
ServerConstructs an HTTP server on the given host and port using an internally created TCP socket.
ServerConstructs an HTTP server on the given address using an internally created TCP socket.
ServerConstructs an HTTP server on the given host and port using a caller-supplied socket. Useful for HTTPS by passing an SSLSocket. The event loop is derived from the socket.
ServerConstructs an HTTP server on the given address using a caller-supplied socket. The event loop is derived from the socket.
voidstartStart the HTTP server.
voidstopStop the HTTP server.
voidsetReusePort inlineEnable SO_REUSEPORT for multicore server instances. Must be called before start(). Allows multiple server instances to bind the same address:port with kernel-level load balancing (Linux 3.9+).
voidsetMaxPooledConnections inlineSet the maximum number of pooled connections (default 128). Set to 0 to disable connection pooling entirely.
voidsetKeepAliveTimeout inlineSet the keep-alive idle timeout in seconds (default 30). Connections idle longer than this are closed by the timer. Set to 0 to disable idle timeout.
size_tconnectionCount const inlineReturn the number of active connections (all states).
net::Address &addressReturn the server bind address.
const DateCache &dateCache const inlineReturn the cached Date header for use in responses.

{#server-1}

Server

Server(const std::string & host, short port, uv::Loop * loop, std::unique_ptr< ServerConnectionFactory > factory)

Constructs an HTTP server on the given host and port using an internally created TCP socket.

Parameters

  • host Bind address (e.g. "0.0.0.0" or "127.0.0.1").

  • port TCP port to listen on.

  • loop Event loop to use. Defaults to the default libuv loop.

  • factory Connection and responder factory. Defaults to the base factory.


{#server-2}

Server

Server(const net::Address & address, uv::Loop * loop, std::unique_ptr< ServerConnectionFactory > factory)

Constructs an HTTP server on the given address using an internally created TCP socket.

Parameters

  • address Bind address and port.

  • loop Event loop to use. Defaults to the default libuv loop.

  • factory Connection and responder factory.


{#server-3}

Server

Server(const std::string & host, short port, net::TCPSocket::Ptr socket, std::unique_ptr< ServerConnectionFactory > factory)

Constructs an HTTP server on the given host and port using a caller-supplied socket. Useful for HTTPS by passing an SSLSocket. The event loop is derived from the socket.

Parameters

  • host Bind address.

  • port TCP port to listen on.

  • socket Pre-created socket (e.g. SSLSocket for HTTPS).

  • factory Connection and responder factory.


{#server-4}

Server

Server(const net::Address & address, net::TCPSocket::Ptr socket, std::unique_ptr< ServerConnectionFactory > factory)

Constructs an HTTP server on the given address using a caller-supplied socket. The event loop is derived from the socket.

Parameters

  • address Bind address and port.

  • socket Pre-created socket (e.g. SSLSocket for HTTPS).

  • factory Connection and responder factory.


{#start-11}

start

void start()

Start the HTTP server.


{#stop-9}

stop

void stop()

Stop the HTTP server.


{#setreuseport-1}

setReusePort

inline

inline void setReusePort(bool enable)

Enable SO_REUSEPORT for multicore server instances. Must be called before start(). Allows multiple server instances to bind the same address:port with kernel-level load balancing (Linux 3.9+).


{#setmaxpooledconnections}

setMaxPooledConnections

inline

inline void setMaxPooledConnections(size_t n)

Set the maximum number of pooled connections (default 128). Set to 0 to disable connection pooling entirely.


{#setkeepalivetimeout}

setKeepAliveTimeout

inline

inline void setKeepAliveTimeout(int seconds)

Set the keep-alive idle timeout in seconds (default 30). Connections idle longer than this are closed by the timer. Set to 0 to disable idle timeout.


{#connectioncount}

connectionCount

const inline

inline size_t connectionCount() const

Return the number of active connections (all states).


{#address-11}

address

net::Address & address()

Return the server bind address.


{#datecache-1}

dateCache

const inline

inline const DateCache & dateCache() const

Return the cached Date header for use in responses.

Protected Attributes

ReturnNameDescription
uv::Loop *_loop
net::Address_address
net::TCPSocket::Ptr_socket
Timer_timer
std::unique_ptr< ServerConnectionFactory >_factory
std::unordered_map< ServerConnection *, ServerConnection::Ptr >_connections
ConnectionPool_pool
DateCache_dateCache
int_keepAliveTimeout
bool_reusePort

{#_loop-1}

_loop

uv::Loop * _loop

{#_address}

_address

net::Address _address

{#_socket-2}

_socket

net::TCPSocket::Ptr _socket

{#_timer}

_timer

Timer _timer

{#_factory}

_factory

std::unique_ptr< ServerConnectionFactory > _factory

{#_connections-1}

_connections

std::unordered_map< ServerConnection *, ServerConnection::Ptr > _connections

{#_pool-1}

_pool

ConnectionPool _pool

{#_datecache}

_dateCache

DateCache _dateCache

{#_keepalivetimeout}

_keepAliveTimeout

int _keepAliveTimeout {30}

{#_reuseport}

_reusePort

bool _reusePort {false}

Protected Methods

ReturnNameDescription
std::unique_ptr< ServerResponder >createResponder
voidonClientSocketAccept
voidonConnectionReady
voidonConnectionClose
boolonSocketClose virtualCalled when the socket is closed. Forwards the event to all registered receivers in priority order.
voidonTimer
uv::Loop *loop const inlineReturn the event loop this server runs on.

{#createresponder}

createResponder

std::unique_ptr< ServerResponder > createResponder(ServerConnection & conn)

{#onclientsocketaccept}

onClientSocketAccept

void onClientSocketAccept(const net::TCPSocket::Ptr & socket)

{#onconnectionready}

onConnectionReady

void onConnectionReady(ServerConnection & conn)

{#onconnectionclose-1}

onConnectionClose

void onConnectionClose(ServerConnection & conn)

{#onsocketclose-3}

onSocketClose

virtual

virtual bool onSocketClose(net::Socket & socket)

Called when the socket is closed. Forwards the event to all registered receivers in priority order.

Parameters

  • socket The socket that was closed.

Returns

true to stop propagation to subsequent receivers.


{#ontimer}

onTimer

void onTimer()

{#loop-6}

loop

const inline

inline uv::Loop * loop() const

Return the event loop this server runs on.

{#serverconnection}

ServerConnection

#include <icy/http/server.h>

Inherits: Connection

HTTP server connection.

Public Attributes

ReturnNameDescription
LocalSignal< void(ServerConnection &, const MutableBuffer &)>PayloadSignals when raw data is received.
LocalSignal< void(ServerConnection &)>CloseSignals when the connection is closed.

{#payload-1}

Payload

LocalSignal< void(ServerConnection &, const MutableBuffer &)> Payload

Signals when raw data is received.


{#close-21}

Close

LocalSignal< void(ServerConnection &)> Close

Signals when the connection is closed.

Public Methods

ReturnNameDescription
ServerConnectionCreates a ServerConnection attached to the given server and socket.
Server &serverReturns the owning Server instance.
ServerConnectionStatestate const inlineReturns the current server-side connection state.
ServerConnectionModemode const inlineReturns the current transport mode.
boolupgraded const inlineReturns true if the connection has been upgraded (e.g. to WebSocket).
boolstreaming const inlineReturns true if the connection is in long-lived streaming mode.
boolidleTimeoutEnabled constReturns true if the server idle timer is allowed to reap this connection.
boolreusableForPool constReturns true if the closed connection can be returned to the reuse pool.
voidmarkActive virtual inlineRefresh the idle timer.
voidresetReset this connection for reuse with a new socket. Called by the connection pool to avoid allocating a new ServerConnection.
voidtouch inlineUpdate the last activity timestamp.
doubleidleSeconds const inlineReturn seconds since last activity.
voidbeginStreaming virtualExplicitly mark the response as long-lived streaming. Streaming connections are excluded from the keep-alive idle reaper.
voidendStreaming virtualExit streaming mode and return to the given HTTP state.
voidendStreaming
ssize_tsendHeader virtualSend the outgoing HTTP header.
voidclose virtualClose the connection with an explicit terminal state transition.

{#serverconnection-1}

ServerConnection

ServerConnection(Server & server, net::TCPSocket::Ptr socket)

Creates a ServerConnection attached to the given server and socket.

Parameters

  • server The owning HTTP server instance.

  • socket The accepted TCP socket for this connection.


{#server-5}

server

Server & server()

Returns the owning Server instance.


{#state-1}

state

const inline

inline ServerConnectionState state() const

Returns the current server-side connection state.


{#mode-1}

mode

const inline

inline ServerConnectionMode mode() const

Returns the current transport mode.


{#upgraded}

upgraded

const inline

inline bool upgraded() const

Returns true if the connection has been upgraded (e.g. to WebSocket).


{#streaming}

streaming

const inline

inline bool streaming() const

Returns true if the connection is in long-lived streaming mode.


{#idletimeoutenabled}

idleTimeoutEnabled

const

bool idleTimeoutEnabled() const

Returns true if the server idle timer is allowed to reap this connection.


{#reusableforpool}

reusableForPool

const

bool reusableForPool() const

Returns true if the closed connection can be returned to the reuse pool.


{#markactive-1}

markActive

virtual inline

virtual inline void markActive()

Refresh the idle timer.


{#reset-12}

reset

void reset(net::TCPSocket::Ptr socket)

Reset this connection for reuse with a new socket. Called by the connection pool to avoid allocating a new ServerConnection.


{#touch}

touch

inline

inline void touch()

Update the last activity timestamp.


{#idleseconds}

idleSeconds

const inline

inline double idleSeconds() const

Return seconds since last activity.


{#beginstreaming-1}

beginStreaming

virtual

virtual void beginStreaming()

Explicitly mark the response as long-lived streaming. Streaming connections are excluded from the keep-alive idle reaper.


{#endstreaming-1}

endStreaming

virtual

virtual void endStreaming()

Exit streaming mode and return to the given HTTP state.


{#endstreaming-2}

endStreaming

void endStreaming(ServerConnectionState nextState)

{#sendheader-1}

sendHeader

virtual

virtual ssize_t sendHeader()

Send the outgoing HTTP header.


{#close-22}

close

virtual

virtual void close()

Close the connection with an explicit terminal state transition.

Protected Attributes

ReturnNameDescription
Server &_server
std::unique_ptr< ServerResponder >_responder
std::time_t_lastActivity
ServerConnectionState_state
ServerConnectionMode_mode

{#_server}

_server

Server & _server

{#_responder}

_responder

std::unique_ptr< ServerResponder > _responder

{#_lastactivity}

_lastActivity

std::time_t _lastActivity {0}

{#_state-2}

_state

ServerConnectionState _state {}

{#_mode-2}

_mode

ServerConnectionMode _mode {}

Protected Methods

ReturnNameDescription
voidonHeaders virtualCalled when the incoming HTTP headers have been fully parsed.
voidonPayload virtualCalled for each chunk of incoming body data after headers are complete.
voidonComplete virtualCalled when the incoming HTTP message is fully received.
voidonClose virtualCalled when the connection is closed.
http::Message *incomingHeader virtualReturns the incoming HTTP message header (request or response depending on role).
http::Message *outgoingHeader virtualReturns the outgoing HTTP message header (request or response depending on role).
voidsetState
boolrequestHasBody const
boolresponseLooksStreaming const

{#onheaders-2}

onHeaders

virtual

virtual void onHeaders()

Called when the incoming HTTP headers have been fully parsed.


{#onpayload-2}

onPayload

virtual

virtual void onPayload(const MutableBuffer & buffer)

Called for each chunk of incoming body data after headers are complete.

Parameters

  • buffer Buffer containing the received data chunk.

{#oncomplete-2}

onComplete

virtual

virtual void onComplete()

Called when the incoming HTTP message is fully received.


{#onclose-5}

onClose

virtual

virtual void onClose()

Called when the connection is closed.


{#incomingheader-2}

incomingHeader

virtual

virtual http::Message * incomingHeader()

Returns the incoming HTTP message header (request or response depending on role).


{#outgoingheader-2}

outgoingHeader

virtual

virtual http::Message * outgoingHeader()

Returns the outgoing HTTP message header (request or response depending on role).


{#setstate}

setState

void setState(ServerConnectionState state)

{#requesthasbody}

requestHasBody

const

bool requestHasBody() const

{#responselooksstreaming}

responseLooksStreaming

const

bool responseLooksStreaming() const

Public Types

NameDescription
Ptr

{#ptr-13}

Ptr

std::shared_ptr< ServerConnection > Ptr()

{#serverconnectionfactory}

ServerConnectionFactory

#include <icy/http/server.h>

Factory for creating per-socket [ServerConnection](#serverconnection) and per-request [ServerResponder](#serverresponder) objects.

Public Methods

ReturnNameDescription
ServerConnectionFactoryDefaulted constructor.
ServerConnection::PtrcreateConnection virtual inlineCreates the [ServerConnection](#serverconnection) wrapper for an accepted TCP socket.
std::unique_ptr< ServerResponder >createResponder virtual inlineCreates the responder for the current request on connection.

{#serverconnectionfactory-1}

ServerConnectionFactory

ServerConnectionFactory() = default

Defaulted constructor.


{#createconnection-2}

createConnection

virtual inline

virtual inline ServerConnection::Ptr createConnection(Server & server, const net::TCPSocket::Ptr & socket)

Creates the [ServerConnection](#serverconnection) wrapper for an accepted TCP socket.


{#createresponder-1}

createResponder

virtual inline

virtual inline std::unique_ptr< ServerResponder > createResponder(ServerConnection & connection)

Creates the responder for the current request on connection.

{#serverresponder}

ServerResponder

#include <icy/http/server.h>

Base responder interface for handling one HTTP request on a server connection. Derived classes typically override [onRequest()](#onrequest) and optionally the streaming hooks.

Public Methods

ReturnNameDescription
ServerResponder inlineCreates a ServerResponder for the given connection.
voidonHeaders virtual inlineCalled when the incoming request headers have been parsed.
voidonPayload virtual inlineCalled for each chunk of incoming request body data.
voidonRequest virtual inlineCalled when the complete HTTP request has been received. Derived classes should write their response here.
voidonClose virtual inlineCalled when the connection is closed.
ServerConnection &connection inlineReturns the underlying server connection.
Request &request inlineReturns the current HTTP request from the underlying connection.
Response &response inlineReturns the current HTTP response from the underlying connection.

{#serverresponder-1}

ServerResponder

inline

inline ServerResponder(ServerConnection & connection)

Creates a ServerResponder for the given connection.

Parameters

  • connection The server connection this responder handles.

{#onheaders-3}

onHeaders

virtual inline

virtual inline void onHeaders(Request & request)

Called when the incoming request headers have been parsed.

Parameters

  • request The parsed HTTP request with headers populated.

{#onpayload-3}

onPayload

virtual inline

virtual inline void onPayload(const MutableBuffer & body)

Called for each chunk of incoming request body data.

Parameters

  • body Buffer containing a chunk of the request body.

{#onrequest}

onRequest

virtual inline

virtual inline void onRequest(Request & request, Response & response)

Called when the complete HTTP request has been received. Derived classes should write their response here.

Parameters

  • request The fully received HTTP request.

  • response The HTTP response to populate and send.


{#onclose-6}

onClose

virtual inline

virtual inline void onClose()

Called when the connection is closed.


{#connection-9}

connection

inline

inline ServerConnection & connection()

Returns the underlying server connection.


{#request-10}

request

inline

inline Request & request()

Returns the current HTTP request from the underlying connection.


{#response-8}

response

inline

inline Response & response()

Returns the current HTTP response from the underlying connection.

Protected Attributes

ReturnNameDescription
ServerConnection &_connection

{#_connection-2}

_connection

ServerConnection & _connection

Private Methods

ReturnNameDescription
ServerResponderDeleted constructor.

{#serverresponder-2}

ServerResponder

ServerResponder(const ServerResponder &) = delete

Deleted constructor.

{#stringpart}

StringPart

#include <icy/http/form.h>

Inherits: FormPart

Form part backed by an in-memory string payload.

Public Methods

ReturnNameDescription
StringPartCreates a StringPart with the given data and default content type "application/octet-stream".
StringPartCreates a StringPart with the given data and MIME content type.
~StringPart virtualDestroys the StringPart.
boolwriteChunk virtualWrites the string data as a single chunk to the FormWriter.
voidwrite virtualWrites the string data to the FormWriter.
voidwrite virtualWrites the string data to an output stream.
uint64_tlength virtual constReturns the byte length of the string data.

{#stringpart-1}

StringPart

StringPart(const std::string & data)

Creates a StringPart with the given data and default content type "application/octet-stream".

Parameters

  • data String data to send as this part.

{#stringpart-2}

StringPart

StringPart(const std::string & data, const std::string & contentType)

Creates a StringPart with the given data and MIME content type.

Parameters

  • data String data to send as this part.

  • contentType MIME type for this part.


{#stringpart-3}

~StringPart

virtual

virtual ~StringPart()

Destroys the StringPart.


{#writechunk-2}

writeChunk

virtual

virtual bool writeChunk(FormWriter & writer)

Writes the string data as a single chunk to the FormWriter.

Parameters

Returns

false always (string data is sent in a single chunk).


{#write-15}

write

virtual

virtual void write(FormWriter & writer)

Writes the string data to the FormWriter.

Parameters


{#write-16}

write

virtual

virtual void write(std::ostream & ostr)

Writes the string data to an output stream.

Parameters

  • ostr Output stream to write to.

{#length-3}

length

virtual const

virtual uint64_t length() const

Returns the byte length of the string data.

Protected Attributes

ReturnNameDescription
std::string_data

{#_data}

_data

std::string _data

{#url}

URL

#include <icy/http/url.h>

An RFC 3986 based URL parser. Constructors and assignment operators will throw a SyntaxException if the URL is invalid.

Public Methods

ReturnNameDescription
URLCreates an empty URL.
URLParses the URL from a null-terminated string.
URLParses the URL from a std::string.
URLConstructs a URL from scheme and authority components.
URLConstructs a URL from scheme, authority, and path+query+fragment.
URLConstructs a URL from individual components.
URLDefaulted constructor.
URL &operator=Assigns a URL from another URL instance.
URL &operator=Assigns a URL from a null-terminated string.
URL &operator=Assigns a URL from a std::string.
boolparseParses and assigns a URL from the given string view, resetting all components first.
std::stringscheme constReturns the URL scheme (e.g. "http", "https", "ws"). Always lowercase.
std::stringuserInfo constReturns the user info component (e.g. "user:pass" from "http://user:pass@host/"). Returns an empty string if not present.
std::stringhost constReturns the host component (e.g. "example.com"). Returns an empty string if not present.
uint16_tport constReturns the port number. If no explicit port was in the URL, returns the default port for the scheme (80 for http, 443 for https), or 0 if the scheme is unknown.
std::stringauthority constReturns the authority component (userinfo@host:port). Only includes components that are present.
std::stringpath constReturns the path component (e.g. "/index.html"). Returns an empty string if not present.
std::stringpathEtc constReturns the path, query and fragment combined (e.g. "/path?q=1#frag").
std::stringquery constReturns the query string without the leading '?' (e.g. "key=value&foo=bar"). Returns an empty string if not present.
std::stringfragment constReturns the fragment identifier without the leading '#'. Returns an empty string if not present.
boolhasSchema constReturns true if the URL has a scheme component.
boolhasUserInfo constReturns true if the URL has a user info component.
boolhasHost constReturns true if the URL has a host component.
boolhasPort constReturns true if an explicit port was specified in the URL.
boolhasPath constReturns true if the URL has a path component.
boolhasQuery constReturns true if the URL has a query component.
boolhasFragment constReturns true if the URL has a fragment component.
boolvalid constReturns true if the URL is non-empty and was successfully parsed.
std::stringstr constReturns the original URL string as parsed.

{#url-1}

URL

URL()

Creates an empty URL.


{#url-2}

URL

URL(const char * url)

Parses the URL from a null-terminated string.

Parameters

  • url Null-terminated URL string to parse.

{#url-3}

URL

URL(const std::string & url)

Parses the URL from a std::string.

Parameters

  • url URL string to parse.

{#url-4}

URL

URL(const std::string & scheme, const std::string & authority)

Constructs a URL from scheme and authority components.

Parameters

  • scheme URL scheme (e.g. "http", "https").

  • authority Host and optional port (e.g. "example.com:8080").


{#url-5}

URL

URL(const std::string & scheme, const std::string & authority, const std::string & pathEtc)

Constructs a URL from scheme, authority, and path+query+fragment.

Parameters

  • scheme URL scheme (e.g. "http").

  • authority Host and optional port.

  • pathEtc Path, query and fragment combined (e.g. "/path?q=1#frag").


{#url-6}

URL

URL(const std::string & scheme, const std::string & authority, const std::string & path, const std::string & query, const std::string & fragment)

Constructs a URL from individual components.

Parameters

  • scheme URL scheme (e.g. "http").

  • authority Host and optional port.

  • path URL path (e.g. "/index.html").

  • query Query string without leading '?' (e.g. "key=value").

  • fragment Fragment identifier without leading '#'.


{#url-7}

URL

URL(const URL &) = default

Defaulted constructor.


{#operator-15}

operator=

URL & operator=(const URL & uri)

Assigns a URL from another URL instance.

Parameters

  • uri Source URL to copy from.

Returns

Reference to this URL.


{#operator-16}

operator=

URL & operator=(const char * uri)

Assigns a URL from a null-terminated string.

Parameters

  • uri Null-terminated URL string to parse.

Returns

Reference to this URL.


{#operator-17}

operator=

URL & operator=(const std::string & uri)

Assigns a URL from a std::string.

Parameters

  • uri URL string to parse.

Returns

Reference to this URL.


{#parse-1}

parse

bool parse(std::string_view url, bool whiny)

Parses and assigns a URL from the given string view, resetting all components first.

Parameters

  • url URL string to parse.

  • whiny If true, throws std::runtime_error on an invalid URL; otherwise returns false.

Returns

true if the URL was parsed successfully; false if invalid and whiny is false.


{#scheme}

scheme

const

std::string scheme() const

Returns the URL scheme (e.g. "http", "https", "ws"). Always lowercase.


{#userinfo}

userInfo

const

std::string userInfo() const

Returns the user info component (e.g. "user:pass" from "http://user:pass@host/"). Returns an empty string if not present.


{#host-1}

host

const

std::string host() const

Returns the host component (e.g. "example.com"). Returns an empty string if not present.


{#port-1}

port

const

uint16_t port() const

Returns the port number. If no explicit port was in the URL, returns the default port for the scheme (80 for http, 443 for https), or 0 if the scheme is unknown.


{#authority}

authority

const

std::string authority() const

Returns the authority component (userinfo@host:port). Only includes components that are present.


{#path}

path

const

std::string path() const

Returns the path component (e.g. "/index.html"). Returns an empty string if not present.


{#pathetc}

pathEtc

const

std::string pathEtc() const

Returns the path, query and fragment combined (e.g. "/path?q=1#frag").


{#query}

query

const

std::string query() const

Returns the query string without the leading '?' (e.g. "key=value&foo=bar"). Returns an empty string if not present.


{#fragment}

fragment

const

std::string fragment() const

Returns the fragment identifier without the leading '#'. Returns an empty string if not present.


{#hasschema}

hasSchema

const

bool hasSchema() const

Returns true if the URL has a scheme component.


{#hasuserinfo}

hasUserInfo

const

bool hasUserInfo() const

Returns true if the URL has a user info component.


{#hashost}

hasHost

const

bool hasHost() const

Returns true if the URL has a host component.


{#hasport}

hasPort

const

bool hasPort() const

Returns true if an explicit port was specified in the URL.


{#haspath}

hasPath

const

bool hasPath() const

Returns true if the URL has a path component.


{#hasquery}

hasQuery

const

bool hasQuery() const

Returns true if the URL has a query component.


{#hasfragment}

hasFragment

const

bool hasFragment() const

Returns true if the URL has a fragment component.


{#valid-1}

valid

const

bool valid() const

Returns true if the URL is non-empty and was successfully parsed.


{#str-1}

str

const

std::string str() const

Returns the original URL string as parsed.

Public Static Methods

ReturnNameDescription
std::stringencode staticPercent-encodes a string per RFC 3986, preserving unreserved characters (A-Z, a-z, 0-9, '-', '_', '.', '~'). Equivalent to JavaScript's encodeURIComponent().
std::stringdecode staticDecodes a percent-encoded string per RFC 3986. Equivalent to JavaScript's decodeURIComponent().

{#encode-21}

encode

static

static std::string encode(std::string_view str)

Percent-encodes a string per RFC 3986, preserving unreserved characters (A-Z, a-z, 0-9, '-', '_', '.', '~'). Equivalent to JavaScript's encodeURIComponent().

Parameters

  • str Input string to encode.

Returns

Percent-encoded string.


{#decode-10}

decode

static

static std::string decode(std::string_view str)

Decodes a percent-encoded string per RFC 3986. Equivalent to JavaScript's decodeURIComponent().

Parameters

  • str Percent-encoded input string.

Returns

Decoded string.

Protected Attributes

ReturnNameDescription
std::string_buf
std::string_scheme
std::string_userInfo
std::string_host
uint16_t_port
std::string_path
std::string_query
std::string_fragment
bool_hasPort

{#_buf}

_buf

std::string _buf

{#_scheme}

_scheme

std::string _scheme

{#_userinfo}

_userInfo

std::string _userInfo

{#_host}

_host

std::string _host

{#_port}

_port

uint16_t _port

{#_path-2}

_path

std::string _path

{#_query}

_query

std::string _query

{#_fragment}

_fragment

std::string _fragment

{#_hasport}

_hasPort

bool _hasPort

{#datecache}

DateCache

#include <icy/http/server.h>

Caches the formatted Date header, updated once per second. Avoids per-request time formatting and string allocation.

Public Attributes

ReturnNameDescription
charbuf
size_tlen
std::time_tlastSecond

{#buf}

buf

char buf {}

{#len}

len

size_t len = 0

{#lastsecond}

lastSecond

std::time_t lastSecond = 0

Public Methods

ReturnNameDescription
voidupdate inlineRefreshes the cached Date header string if the current second has changed. No-op if called multiple times within the same second.
const char *data const inlineReturns a pointer to the formatted "Date: ...\r\n" header string.
size_tsize const inlineReturns the byte length of the formatted Date header string.

{#update}

update

inline

inline void update()

Refreshes the cached Date header string if the current second has changed. No-op if called multiple times within the same second.


{#data-2}

data

const inline

inline const char * data() const

Returns a pointer to the formatted "Date: ...\r\n" header string.


{#size-1}

size

const inline

inline size_t size() const

Returns the byte length of the formatted Date header string.

{#method}

Method

#include <icy/http/request.h>

HTTP request methods.

Public Static Attributes

ReturnNameDescription
const std::stringGet static
const std::stringHead static
const std::stringPut static
const std::stringPost static
const std::stringOptions static
const std::stringDelete static
const std::stringTrace static
const std::stringConnect static

{#get-4}

Get

static

const std::string Get

{#head}

static

const std::string Head

{#put}

Put

static

const std::string Put

{#post-2}

Post

static

const std::string Post

{#options-3}

Options

static

const std::string Options

{#delete}

Delete

static

const std::string Delete

{#trace}

Trace

static

const std::string Trace

{#connect-13}

Connect

static

const std::string Connect

{#ws}

ws

WebSocket framing, handshakes, and connection helpers.

Classes

NameDescription
ConnectionAdapterWebSocket class which belongs to an HTTP connection.
WebSocketStandalone WebSocket class.
WebSocketAdapterWebSocket protocol adapter for both client and server endpoints.
WebSocketException
WebSocketFramerWebSocket frame encoder/decoder and handshake validator for RFC 6455.

Enumerations

NameDescription
ModeWebSocket endpoint mode.
FrameFlagsFrame header flags.
OpcodeFrame header opcodes.
SendFlagsCombined header flags and opcodes for identifying the payload type of sent frames.
CloseStatusCodeStatusCodes for CLOSE frames sent with shutdown().
ErrorCodeThese error codes can be obtained from WebSocket exceptions to determine the exact cause of the error.
CloseState

{#mode-2}

Mode

enum Mode

WebSocket endpoint mode.

ValueDescription
ServerSideServer-side WebSocket.
ClientSideClient-side WebSocket.

{#frameflags}

FrameFlags

enum FrameFlags

Frame header flags.

ValueDescription
FinFIN bit: final fragment of a multi-fragment message.
Rsv1Reserved for future use. Must be zero.
Rsv2Reserved for future use. Must be zero.
Rsv3Reserved for future use. Must be zero.

{#opcode}

Opcode

enum Opcode

Frame header opcodes.

ValueDescription
ContinuationContinuation frame.
TextText frame.
BinaryBinary frame.
CloseClose connection.
PingPing frame.
PongPong frame.
BitmaskBit mask for opcodes.

{#sendflags}

SendFlags

enum SendFlags

Combined header flags and opcodes for identifying the payload type of sent frames.

ValueDescription
Text
Binary

{#closestatuscode}

CloseStatusCode

enum CloseStatusCode

StatusCodes for CLOSE frames sent with shutdown().

ValueDescription
NormalClose
EndpointGoingAway
ProtocolError
PayloadNotAcceptable
Reserved
ReservedNoStatusCode
ReservedAbnormalClose
MalformedPayload
PolicyViolation
PayloadTooBig
ExtensionRequired
UnexpectedCondition
ReservedTLSFailure

{#errorcode}

ErrorCode

enum ErrorCode

These error codes can be obtained from WebSocket exceptions to determine the exact cause of the error.

ValueDescription
NoHandshakeNo Connection: Upgrade or Upgrade: websocket header in handshake request.
HandshakeNoVersionNo Sec-WebSocket-Version header in handshake request.
HandshakeUnsupportedVersionUnsupported WebSocket version requested by client.
HandshakeNoKeyNo Sec-WebSocket-Key header in handshake request.
HandshakeAcceptNo Sec-WebSocket-Accept header or wrong value.
UnauthorizedThe server rejected the username or password for authentication.
PayloadTooBigPayload too big for supplied buffer.
IncompleteFrameIncomplete frame received.
InvalidRsvBitsRSV bits set without extension negotiation.
InvalidOpcodeUnknown or reserved opcode received.
UnmaskedClientFrameClient-to-server frame not masked (RFC 6455 violation).
ProtocolViolationGeneral RFC 6455 protocol violation.

{#closestate}

CloseState

enum CloseState
ValueDescription
Open
CloseSent
CloseReceived
Closed

Variables

ReturnNameDescription
constexpr autoServerSide static
constexpr autoClientSide static
constexpr charProtocolGuid
constexpr charProtocolVersionThe WebSocket protocol version supported (13).

{#serverside}

ServerSide

static

constexpr auto ServerSide = Mode::ServerSide

{#clientside}

ClientSide

static

constexpr auto ClientSide = Mode::ClientSide

{#protocolguid}

ProtocolGuid

constexpr char ProtocolGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

{#protocolversion}

ProtocolVersion

constexpr char ProtocolVersion = "13"

The WebSocket protocol version supported (13).

{#connectionadapter-2}

ConnectionAdapter

#include <icy/http/websocket.h>

Inherits: WebSocketAdapter

WebSocket class which belongs to an HTTP connection.

Public Methods

ReturnNameDescription
ConnectionAdapterCreates a ConnectionAdapter for upgrading an existing HTTP connection to WebSocket. Disables automatic header sending on the underlying connection.
voidonHandshakeComplete virtualCalled when the WebSocket handshake completes. Emits the connect event via the socket emitter chain.

{#connectionadapter-3}

ConnectionAdapter

ConnectionAdapter(Connection * connection, ws::Mode mode)

Creates a ConnectionAdapter for upgrading an existing HTTP connection to WebSocket. Disables automatic header sending on the underlying connection.

Parameters

  • connection The HTTP connection to upgrade.

  • mode ServerSide or ClientSide.


{#onhandshakecomplete}

onHandshakeComplete

virtual

virtual void onHandshakeComplete()

Called when the WebSocket handshake completes. Emits the connect event via the socket emitter chain.

Protected Attributes

ReturnNameDescription
Connection *_connection

{#_connection-3}

_connection

Connection * _connection

{#websocket}

WebSocket

#include <icy/http/websocket.h>

Inherits: WebSocketAdapter

Standalone WebSocket class.

Public Methods

ReturnNameDescription
WebSocketCreates the WebSocket with the given Socket. The Socket should be a TCPSocket or a SSLSocket, depending on the protocol used (ws or wss).
http::Request &requestReturns the HTTP request used during the WebSocket handshake.
http::Response &responseReturns the HTTP response received during the WebSocket handshake.

{#websocket-1}

WebSocket

WebSocket(const net::Socket::Ptr & socket)

Creates the WebSocket with the given Socket. The Socket should be a TCPSocket or a SSLSocket, depending on the protocol used (ws or wss).


{#request-11}

request

http::Request & request()

Returns the HTTP request used during the WebSocket handshake.


{#response-9}

response

http::Response & response()

Returns the HTTP response received during the WebSocket handshake.

Protected Attributes

ReturnNameDescription
http::Request_request
http::Response_response

{#_request-2}

_request

http::Request _request

{#_response-2}

_response

http::Response _response

Public Types

NameDescription
Vec

{#vec-4}

Vec

std::vector< WebSocket > Vec()

{#websocketadapter}

WebSocketAdapter

#include <icy/http/websocket.h>

Inherits: SocketEmitter Subclassed by: ConnectionAdapter, WebSocket

WebSocket protocol adapter for both client and server endpoints.

Public Attributes

ReturnNameDescription
net::Socket::PtrsocketPointer to the underlying socket. Sent data will be proxied to this socket.

{#socket-6}

socket

net::Socket::Ptr socket

Pointer to the underlying socket. Sent data will be proxied to this socket.

Public Methods

ReturnNameDescription
WebSocketAdapterCreates a WebSocketAdapter using the given socket, mode and HTTP message objects.
ssize_tsend virtualFrames and sends data to the peer's address.
ssize_tsend virtualFrames and sends data to a specific peer address (for UDP-backed sockets).
ssize_tsendOwned virtualSends an owned payload buffer to the connected peer.
ssize_tsendOwned virtual
boolshutdown virtualSends a WebSocket CLOSE frame with the given status code and message, then closes the underlying socket.
voidsendClientRequest virtualClient side.
voidhandleClientResponse virtualParses the server's HTTP upgrade response and completes the handshake. Any data remaining in the buffer after the HTTP response is re-fed as WebSocket frames.
voidhandleServerRequest virtualServer side.
voidonHandshakeComplete virtualCalled when the WebSocket handshake completes. Emits the connect event to downstream handlers.

{#websocketadapter-1}

WebSocketAdapter

WebSocketAdapter(const net::Socket::Ptr & socket, ws::Mode mode, http::Request & request, http::Response & response)

Creates a WebSocketAdapter using the given socket, mode and HTTP message objects.

Parameters

  • socket The underlying TCP or SSL socket.

  • mode ServerSide or ClientSide.

  • request HTTP request used for the handshake.

  • response HTTP response used for the handshake.


{#send-14}

send

virtual

virtual ssize_t send(const char * data, size_t len, int flags)

Frames and sends data to the peer's address.

Parameters

Returns

Number of bytes sent, or -1 on error.


{#send-15}

send

virtual

virtual ssize_t send(const char * data, size_t len, const net::Address & peerAddr, int flags)

Frames and sends data to a specific peer address (for UDP-backed sockets).

Parameters

Returns

Number of bytes sent, or -1 on error.


{#sendowned-12}

sendOwned

virtual

virtual ssize_t sendOwned(Buffer && buffer, int flags)

Sends an owned payload buffer to the connected peer.

The buffer is moved through the adapter chain and retained by the transport layer until async write completion.


{#sendowned-13}

sendOwned

virtual

virtual ssize_t sendOwned(Buffer && buffer, const net::Address & peerAddr, int flags)

{#shutdown-8}

shutdown

virtual

virtual bool shutdown(uint16_t statusCode, const std::string & statusMessage)

Sends a WebSocket CLOSE frame with the given status code and message, then closes the underlying socket.

Parameters

  • statusCode WebSocket close status code (e.g. 1000 for normal close).

  • statusMessage Human-readable reason for closing.

Returns

true if the close frame was sent successfully.


{#sendclientrequest}

sendClientRequest

virtual

virtual void sendClientRequest()

Client side.

Sends the WebSocket HTTP upgrade request to initiate the handshake. Called automatically on socket connect.


{#handleclientresponse}

handleClientResponse

virtual

virtual void handleClientResponse(const MutableBuffer & buffer, const net::Address & peerAddr)

Parses the server's HTTP upgrade response and completes the handshake. Any data remaining in the buffer after the HTTP response is re-fed as WebSocket frames.

Parameters

  • buffer Buffer containing the server's HTTP response.

  • peerAddr Address of the peer.


{#handleserverrequest}

handleServerRequest

virtual

virtual void handleServerRequest(const MutableBuffer & buffer, const net::Address & peerAddr)

Server side.

Parses the client's HTTP upgrade request and sends the 101 response.

Parameters

  • buffer Buffer containing the client's HTTP upgrade request.

  • peerAddr Address of the peer.


{#onhandshakecomplete-1}

onHandshakeComplete

virtual

virtual void onHandshakeComplete()

Called when the WebSocket handshake completes. Emits the connect event to downstream handlers.

Protected Attributes

ReturnNameDescription
WebSocketFramerframer
http::Request &_request
http::Response &_response
ws::CloseState_closeState

{#framer}

framer

WebSocketFramer framer

{#_request-3}

_request

http::Request & _request

{#_response-3}

_response

http::Response & _response

{#_closestate}

_closeState

ws::CloseState _closeState {}

Protected Methods

ReturnNameDescription
boolsendControlFrame
voidresetFrameState

{#sendcontrolframe}

sendControlFrame

bool sendControlFrame(ws::Opcode opcode, const char * payload, size_t payloadLen, const net::Address & peerAddr)

{#resetframestate}

resetFrameState

void resetFrameState()

Private Methods

ReturnNameDescription
boolonSocketConnect virtualCalled by the socket on connect; initiates the client handshake.
boolonSocketRecv virtualCalled by the socket on each received buffer; handles handshake or frame parsing depending on state.
boolonSocketClose virtualCalled by the socket on close; resets framer state.

{#onsocketconnect-4}

onSocketConnect

virtual

virtual bool onSocketConnect(net::Socket & socket)

Called by the socket on connect; initiates the client handshake.


{#onsocketrecv-6}

onSocketRecv

virtual

virtual bool onSocketRecv(net::Socket & socket, const MutableBuffer & buffer, const net::Address & peerAddress)

Called by the socket on each received buffer; handles handshake or frame parsing depending on state.


{#onsocketclose-4}

onSocketClose

virtual

virtual bool onSocketClose(net::Socket & socket)

Called by the socket on close; resets framer state.

{#websocketexception}

WebSocketException

#include <icy/http/websocket.h>

Inherits: runtime_error

Public Methods

ReturnNameDescription
WebSocketException inline
ErrorCodecode const inline
boolhasCloseStatus const inline
uint16_tcloseStatus const inline

{#websocketexception-1}

WebSocketException

inline

inline WebSocketException(ErrorCode code, std::string message, uint16_t closeStatus)

{#code}

code

const inline

inline ErrorCode code() const

{#hasclosestatus}

hasCloseStatus

const inline

inline bool hasCloseStatus() const

{#closestatus}

closeStatus

const inline

inline uint16_t closeStatus() const

Private Attributes

ReturnNameDescription
ErrorCode_code
uint16_t_closeStatus

{#_code}

_code

ErrorCode _code

{#_closestatus}

_closeStatus

uint16_t _closeStatus

{#websocketframer}

WebSocketFramer

#include <icy/http/websocket.h>

WebSocket frame encoder/decoder and handshake validator for RFC 6455.

Public Methods

ReturnNameDescription
WebSocketFramerCreates a WebSocketFramer operating in the given endpoint mode. Client-side framers mask outgoing payloads; server-side framers do not.
size_twriteFrame virtualEncodes data into a WebSocket frame and writes it to frame.
uint64_treadFrame virtualDecodes a single WebSocket frame from frame.
boolhandshakeComplete constReturns true if the WebSocket handshake has completed successfully.
voidacceptServerRequestServer side.
voidcreateClientHandshakeRequestClient side.
boolcheckClientHandshakeResponseValidates the server's 101 Switching Protocols response.
voidcompleteClientHandshakeCompletes the client-side handshake by verifying Connection, Upgrade and Sec-WebSocket-Accept headers. Advances internal state to "complete".

{#websocketframer-1}

WebSocketFramer

WebSocketFramer(ws::Mode mode)

Creates a WebSocketFramer operating in the given endpoint mode. Client-side framers mask outgoing payloads; server-side framers do not.

Parameters

  • mode ServerSide or ClientSide.

{#writeframe}

writeFrame

virtual

virtual size_t writeFrame(const char * data, size_t len, int flags, BitWriter & frame)

Encodes data into a WebSocket frame and writes it to frame.

Parameters

Returns

Total number of bytes written to the frame buffer (header + payload).


{#readframe}

readFrame

virtual

virtual uint64_t readFrame(BitReader & frame, char *& payload)

Decodes a single WebSocket frame from frame.

The payload is unmasked in-place in the source buffer; no copy is made. payload is set to point at the start of the payload within frame's buffer.

Parameters

  • frame BitReader positioned at the start of a frame.

  • payload Set to point at the start of the decoded payload. Not null-terminated.

Returns

Payload length in bytes.

Exceptions

  • std::runtime_error on protocol violations or if the buffer is too small.

{#handshakecomplete}

handshakeComplete

const

bool handshakeComplete() const

Returns true if the WebSocket handshake has completed successfully.


{#acceptserverrequest}

acceptServerRequest

void acceptServerRequest(http::Request & request, http::Response & response)

Server side.

Validates the client upgrade request and writes a 101 Switching Protocols response. Sets the internal state to mark the handshake as complete.

Parameters

  • request Incoming HTTP upgrade request.

  • response HTTP response to populate with the handshake reply.

Exceptions

  • std::runtime_error if the request is not a valid WebSocket upgrade.

{#createclienthandshakerequest}

createClientHandshakeRequest

void createClientHandshakeRequest(http::Request & request)

Client side.

Populates request with the WebSocket upgrade headers (Connection, Upgrade, Sec-WebSocket-Key, Sec-WebSocket-Version) to initiate the handshake.

Parameters

  • request HTTP request to add upgrade headers to.

{#checkclienthandshakeresponse}

checkClientHandshakeResponse

bool checkClientHandshakeResponse(http::Response & response)

Validates the server's 101 Switching Protocols response.

Parameters

  • response The HTTP response received from the server.

Returns

true if the handshake succeeded and data can flow.

Exceptions

  • std::runtime_error if the server rejected or mishandled the upgrade.

{#completeclienthandshake}

completeClientHandshake

void completeClientHandshake(http::Response & response)

Completes the client-side handshake by verifying Connection, Upgrade and Sec-WebSocket-Accept headers. Advances internal state to "complete".

Parameters

  • response The 101 Switching Protocols response from the server.

Exceptions

  • std::runtime_error if any required header is missing or incorrect.

Protected Methods

ReturnNameDescription
intframeFlags constReturns the frame flags of the most recently received frame. Set by readFrame()
boolmustMaskPayload constReturns true if the payload must be masked. Used by writeFrame()
ws::Modemode const

{#frameflags-1}

frameFlags

const

int frameFlags() const

Returns the frame flags of the most recently received frame. Set by readFrame()


{#mustmaskpayload}

mustMaskPayload

const

bool mustMaskPayload() const

Returns true if the payload must be masked. Used by writeFrame()


{#mode-3}

mode

const

ws::Mode mode() const

Private Attributes

ReturnNameDescription
ws::Mode_mode
int_frameFlags
int_headerState
bool_maskPayload
Random_rnd
std::string_key
bool_fragmentedCurrently receiving a fragmented message.
int_fragmentOpcodeOpcode of the first frame in the fragment sequence.
Buffer_fragmentBufferAccumulated payload from continuation frames.
Buffer_incompleteFrameBuffer for incomplete frame data across TCP segments.

{#_mode-3}

_mode

ws::Mode _mode

{#_frameflags}

_frameFlags

int _frameFlags

{#_headerstate}

_headerState

int _headerState

{#_maskpayload}

_maskPayload

bool _maskPayload

{#_rnd}

_rnd

Random _rnd

{#_key}

_key

std::string _key

{#_fragmented}

_fragmented

bool _fragmented {false}

Currently receiving a fragmented message.


{#_fragmentopcode}

_fragmentOpcode

int _fragmentOpcode {0}

Opcode of the first frame in the fragment sequence.


{#_fragmentbuffer}

_fragmentBuffer

Buffer _fragmentBuffer

Accumulated payload from continuation frames.


{#_incompleteframe}

_incompleteFrame

Buffer _incompleteFrame

Buffer for incomplete frame data across TCP segments.