Network Connections

Network Facade

Availability

Network is accessed through Events::get<Network>(). The built-in backend resolves numeric addresses and host names asynchronously and provides native TCP and UDP sockets on macOS, Linux, and Windows. TCP uses kqueue, epoll, or IOCP through the event loop that owns each source.

See Resolving Hosts Asynchronously for the complete host-lookup workflow, lifecycle, cancellation, and diagnostics.

Buffering and Errors

SocketBufferLimits bounds accepted TCP output and buffered TCP input. ConnectionQuota bounds concurrent accepted resources with move-only leases. Listener options create a private bounded quota by default, while an explicitly shared quota combines capacity across listeners and event loops. UdpSocketOptions controls the maximum datagram size and accepted UDP output independently. A send accepts or rejects a complete block or datagram immediately; Accepted means the source retained the complete operation, while WouldBlock leaves ownership with the caller. Operational failures carry NetworkErrorContext and a machine-readable NetworkErrorReason through source event editors; invalid API use continues to throw synchronously. TLS failures additionally report the NetworkErrorPhase and, when available, the exact public TlsAlertDescription wire value. NetworkError remains available when a handler wants to transfer a context to an exception-reporting boundary.

Accepted TLS

TlsServerAcceptOptions resolves a required default tls/server identity and up to 64 exact canonical SNI mappings before it consumes a TCP request. A required shared handshake quota independently bounds unauthenticated work and releases its lease when client Finished is verified. ALPN protocols are configured and reported as text::String values. TLS preserves their exact raw bytes and only converts between string storage and protocol bytes at the wire boundary. See Using TLS Server Connections for identity registration, shared quotas, ClientHello policy, back-pressure, and graceful closure.

Network Event Sources

Lifecycle and Affinity

Every factory returns an inactive source. Use a typed event editor on the owner loop to configure handlers before calling start(). The source owns one stable editor and all handlers configured through it. Calling an on...() method again replaces that handler; an empty callback clears it. Regular operations are owner-loop-only; cancellation and abort are thread-safe, and other cross-thread work uses Events::invoke().

HostLookup is reusable: each start(host, options) call captures one host and one HostLookupOptions value. Its result or error handler observes the terminal state, then onFinal() runs after the source returns to Inactive and can start another host immediately.

The built-in HostLookup implementation is described in Resolving Hosts Asynchronously. One-shot transport sources cannot be restarted after reaching Closed or Failed.

Common Connection Interface

Connection is the common application byte-stream interface implemented by TcpConnection, TlsClientConnection, and TlsServerConnection. Protocol-specific connection and handshake checkpoints remain on the concrete interfaces. Once ConnectionState::Active is reached, generic consumers use the same endpoints, buffer limits, atomic send, receive flow control, graceful close, abort, and common event handlers.

ConnectionCloseContext identifies the first orderly-close initiator. A remote TCP close is peer EOF, while a remote TLS close is an authenticated close_notify. Bare TCP EOF below TLS remains a truncation failure.

TLS Client Sources

TlsClientConnection composes one TcpConnection and becomes Active only after server authentication and the TLS 1.3 Finished exchange. Its default configuration label is tls/client. The application configuration is resolved synchronously before TCP startup and retained as an immutable snapshot.

The ordered checkpoints are host resolution, transport connection, peer hello, peer authentication, and handshake completion. Each checkpoint automatically continues after its callback returns. Calling abort() in a checkpoint prevents the next protocol transition or transport flight and emits only onFinal().

TLS Server Sources

TlsServerConnection composes one accepted TcpConnection and remains in Accepting or Handshaking until the client Finished authenticator is verified. Before consuming the request, accept() validates all options, resolves the default and exact-SNI configuration labels into immutable snapshots, and acquires a separate shared handshake-quota lease. The ClientHello checkpoint exposes the bounded SNI and ALPN offer plus the selected cipher, signature scheme, and configuration labels before secrets or the server flight are created.

Application flow, back-pressure, receive pause propagation, deadlines, truncation handling, close_notify, and terminal ordering match the client source. See Using TLS Server Connections for a complete listener example.

Application sends and data delivery occur only in Active. TLS records are transferred atomically to TCP, one TCP-rejected record is retained for writable retry, and receiving pause propagates to the transport. DNS/TCP, handshake, application idle, and graceful-close deadlines are independent. Only accepted non-empty application sends and delivered non-empty application blocks move the idle deadline.

Orderly closure requires authenticated close_notify in both directions. Bare TCP EOF is reported as TLS truncation. Successful closure emits onClosed() followed by onFinal(); failures emit onError() followed by onFinal().

TCP Sources

TcpConnection spans both establishment and active stream use. An outgoing connection resolves a named target, delivers the complete ordered endpoint list through onHostResolved(), and tries endpoints in that order within one overall deadline. Calling abort() in onHostResolved() prevents creation of a native connection socket.

TcpListener applies its optional admission filter immediately after native accept. The filter runs synchronously on the listener owner loop, before a TcpConnectionRequest is allocated or posted, and therefore must be fast and non-blocking. It limits sockets retained by the application but cannot prevent the operating system’s SYN or listen backlog from filling.

After the filter accepts a socket, the listener acquires its connection quota before allocating a request. A full quota silently drops that socket and suspends native acceptance until capacity returns. The move-only lease follows the socket through TcpConnectionRequest into TcpConnection and is released by rejection, abandonment, failure, finalization, or destruction. Sharing one quota pointer combines the limit across listeners and owner loops; default listener options instead create one private quota.

Each emitted TcpConnectionRequest is a transferable, one-shot capability. A prepared TcpConnection consumes it with accept(request, options) on the connection’s destination loop. Rejection is idempotent and thread-safe, and destroying an undecided request rejects it. Closing the listener does not invalidate requests already emitted.

TCP data callbacks contain owned chunks of one byte stream and do not represent messages. Graceful local closure drains accepted output; remote EOF delivers buffered input and drains accepted output. ConnectionCloseContext reports which side initiated the first normal close. Aborting posts only onFinal(), while normal close and failure post onFinal() after onClosed() or onError().

UDP Sources

UdpSocket preserves datagram boundaries and remote addresses with UdpDatagram. It binds once, sends and receives any number of datagrams for multiple remote endpoints, and remains active until it is closed or aborted. UdpSocketOptions independently bounds datagram size and accepted output. See Sending and Receiving UDP Packets for binding, back-pressure, drops, and shutdown.

Interface

class HostLookup : public erbsland::event::EventSource

A reusable asynchronous host lookup.

Subclassed by erbsland::network::impl::HostLookup

Public Functions

virtual std::optional<Host> host() const = 0

Get the host of the current operation.

This method is thread-safe.

Returns:

The active host, or std::nullopt if no operation is active.

virtual NetworkSourceState state() const noexcept = 0

Get the source lifecycle state.

Returns:

The current state.

virtual void start(Host host, HostLookupOptions options = {}) = 0

Start an inactive lookup operation.

Completion is always delivered asynchronously on the owner event loop.

Parameters:
  • host – The address or unresolved name to resolve.

  • options – The options for this operation.

Throws:
  • err::LogicError – If called outside the owner event loop or while an operation is active.

  • err::ParameterError – If the timeout or attempt count is not positive, or the retry delay is negative.

virtual void cancel() noexcept = 0

Cancel the lookup immediately.

This method is thread-safe and suppresses completion that has not started dispatching.

virtual HostLookupEventEditor &events() override = 0

Access the editor for the lookup-owned event handlers.

Throws:

err::LogicError – If called outside the owner event loop.

Returns:

The stable source-owned editor.

using erbsland::network::HostLookupPtr = std::shared_ptr<HostLookup>

A shared host lookup.

class HostLookupEventEditor : public erbsland::event::impl::CommonEventEditor

Editor for the event handlers owned by a host lookup.

The lookup owns this editor and its handlers. The common editor base exposes the lookup and callback target to generic event-editor code without introducing a strong ownership cycle.

Subclassed by erbsland::network::impl::HostLookupEventEditor

Public Functions

virtual HostLookupEventEditor &onResolved(HostResolvedFn callback) = 0

Set the successful-resolution handler.

Parameters:

callback – The callback receiving the resolved addresses, or an empty callback to clear the handler.

Returns:

This editor for chaining.

virtual HostLookupEventEditor &onError(NetworkErrorFn callback) = 0

Set the operational-error handler.

Parameters:

callback – The callback receiving the error, or an empty callback to clear the handler.

Returns:

This editor for chaining.

virtual HostLookupEventEditor &onFinal(NetworkEventFn callback) = 0

Set the final handler.

This handler runs after a successful, failed, or cancelled operation returns the lookup to its inactive state.

Parameters:

callback – The final callback, or an empty callback to clear the handler.

Returns:

This editor for chaining.

class HostLookupOptions

Options for one asynchronous host lookup operation.

Public Functions

inline time::TimeDelta timeout() const noexcept

Get the deadline for the complete lookup operation.

inline HostLookupOptions &setTimeout(const time::TimeDelta value) noexcept

Set the deadline for the complete lookup operation.

inline unit::ItemCount maximumAttempts() const noexcept

Get the maximum number of native resolver attempts.

inline HostLookupOptions &setMaximumAttempts(const unit::ItemCount value) noexcept

Set the maximum number of native resolver attempts.

inline time::TimeDelta retryDelay() const noexcept

Get the delay between native resolver attempts.

inline HostLookupOptions &setRetryDelay(const time::TimeDelta value) noexcept

Set the delay between native resolver attempts.

Public Static Attributes

static const auto cDefaultTimeout = time::TimeDelta::seconds(10)

The default deadline for the complete lookup operation.

static const auto cDefaultMaximumAttempts = unit::ItemCount{2U}

The default maximum number of native resolver attempts.

static const auto cDefaultRetryDelay = time::TimeDelta::milliseconds(100)

The default delay between native resolver attempts.

using erbsland::network::HostResolvedFn = std::function<void(const util::List<IpAddress>&)>

A callback receiving the resolved addresses for a host lookup.

class Network

The event-loop frontend for asynchronous DNS and socket operations.

Subclassed by erbsland::network::impl::NetworkBackend

Public Functions

virtual HostLookupPtr createHostLookup() = 0

Create an inactive reusable host lookup.

Throws:

err::LogicError – If called outside the owner event loop.

Returns:

The new lookup source.

virtual HttpClientSessionPtr createHttpClientSession() = 0

Create an active session-first HTTP/1.1 and HTTPS client.

Throws:

err::LogicError – If called outside the owner event loop.

Returns:

The new client session.

virtual HttpServerPtr createHttpServer() = 0

Create an inactive HTTP/1.1 or HTTPS server.

Throws:

err::LogicError – If called outside the owner event loop.

Returns:

The new server source.

virtual TcpListenerPtr createTcpListener() = 0

Create an inactive TCP listener.

Returns:

The new listener source.

virtual TcpConnectionPtr createTcpConnection() = 0

Create an inactive TCP connection.

Returns:

The new connection source.

virtual TlsClientConnectionPtr createTlsClientConnection() = 0

Create an inactive TLS client connection.

Throws:

err::LogicError – If called outside the owner event loop.

Returns:

The new one-shot authenticated connection source.

virtual TlsServerConnectionPtr createTlsServerConnection() = 0

Create an inactive accepted TLS server connection.

Throws:

err::LogicError – If called outside the owner event loop.

Returns:

The new one-shot authenticated server connection source.

virtual UdpSocketPtr createUdpSocket() = 0

Create an inactive UDP socket.

Throws:

err::RuntimeError – If the backend does not implement UDP sockets.

Returns:

The new UDP socket source.

Public Static Functions

static inline constexpr event::EventBackendId backendId() noexcept

Get the event-backend identifier for the network frontend.

Returns:

The network backend identifier.

class Connection : public erbsland::event::EventSource

A one-shot event-driven application byte-stream connection.

Protocol-specific subclasses perform their own setup before entering ConnectionState::Active.

Subclassed by erbsland::network::TcpConnection, erbsland::network::TlsClientConnection, erbsland::network::TlsServerConnection

Public Functions

virtual std::optional<IpEndpoint> localEndpoint() const = 0

Get the resolved local endpoint.

virtual std::optional<IpEndpoint> remoteEndpoint() const = 0

Get the resolved remote endpoint.

virtual SocketBufferLimits bufferLimits() const noexcept = 0

Get the configured application-stream buffer limits.

virtual ConnectionState state() const noexcept = 0

Get the connection lifecycle state.

virtual NetworkSendStatus send(const mem::ByteBlock &data) = 0

Atomically submit one complete application byte block.

Parameters:

data – The owned stream data to queue.

Returns:

Whether the block was accepted, back-pressured, or rejected because the stream is closed.

virtual void pauseReceiving() = 0

Suspend application-data delivery.

virtual void resumeReceiving() = 0

Resume application-data delivery.

virtual void close() = 0

Start protocol-specific graceful closure after accepted output drains.

virtual void abort() noexcept = 0

Abort the connection immediately.

virtual ConnectionEventEditor &events() override = 0

Access the stable source-owned connection event editor.

using erbsland::network::ConnectionPtr = std::shared_ptr<Connection>

A shared event-driven byte-stream connection.

class ConnectionCloseContext

Context for one orderly byte-stream connection closure.

A remote TCP close represents peer EOF; a remote TLS close represents an authenticated close_notify.

Public Functions

inline explicit constexpr ConnectionCloseContext(const ConnectionCloseOrigin origin) noexcept

Create a close context.

Parameters:

origin – The side that initiated orderly closure first.

inline constexpr ConnectionCloseOrigin origin() const noexcept

Get the side that initiated orderly closure first.

using erbsland::network::ConnectionCloseFn = std::function<void(const ConnectionCloseContext&)>

A callback for an orderly connection closure.

enum class erbsland::network::ConnectionCloseOrigin : std::uint8_t

The side that first initiated an orderly connection closure.

Values:

enumerator Local

The local application requested closure first.

enumerator Remote

The remote peer completed its protocol-specific orderly close first.

class ConnectionEventEditor : public erbsland::event::impl::CommonEventEditor

Callback editor for the active data phase of a byte-stream connection.

Subclassed by erbsland::network::TcpConnectionEventEditor, erbsland::network::TlsClientConnectionEventEditor, erbsland::network::TlsServerConnectionEventEditor

Public Functions

virtual ConnectionEventEditor &onData(NetworkDataFn callback) = 0

Set the received application-data callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual ConnectionEventEditor &onWritable(NetworkEventFn callback) = 0

Set the writable-transition callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual ConnectionEventEditor &onClosed(ConnectionCloseFn callback) = 0

Set the orderly-closure callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual ConnectionEventEditor &onError(NetworkErrorFn callback) = 0

Set the operational-error callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual ConnectionEventEditor &onFinal(NetworkEventFn callback) = 0

Set the exactly-once terminal callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

class ConnectionQuota : public std::enable_shared_from_this<ConnectionQuota>

A thread-safe shared limit for concurrent connection-related work.

A quota can be shared by listeners on different event loops. Acquisition retains optional remote-endpoint context so future keyed policies can be added without changing connection APIs.

Public Functions

std::optional<ConnectionQuotaLease> tryAcquire(std::optional<IpEndpoint> remoteEndpoint = {})

Try to reserve one slot without blocking.

Parameters:

remoteEndpoint – Optional remote endpoint associated with the work.

Returns:

An acquired lease, or no value when the quota is full.

inline unit::ItemCount maximum() const noexcept

Get the configured maximum.

unit::ItemCount current() const noexcept

Get the current number of acquired leases.

unit::ItemCount available() const noexcept

Get the currently available capacity.

Public Static Functions

static ConnectionQuotaPtr create(unit::ItemCount maximum)

Create a quota with a positive finite maximum.

Parameters:

maximum – The maximum number of simultaneous leases.

Throws:

err::ParameterError – If maximum is zero or infinite.

Returns:

The new shared quota.

class ConnectionQuotaLease

One move-only reservation from a shared connection quota.

The reservation is released exactly once, either explicitly or when this object is destroyed.

Public Functions

ConnectionQuotaLease() = default

Create an empty lease.

~ConnectionQuotaLease()

Release an acquired reservation.

ConnectionQuotaLease(ConnectionQuotaLease &&other) noexcept

Move an acquired reservation.

ConnectionQuotaLease &operator=(ConnectionQuotaLease &&other) noexcept

Replace this lease with another reservation.

inline bool isAcquired() const noexcept

Test whether this object owns a quota reservation.

void release() noexcept

Release the reservation immediately.

enum class erbsland::network::ConnectionState : std::uint8_t

The lifecycle state of a connected byte-stream source.

Values:

enumerator Inactive

Configurable and not yet started.

enumerator Connecting

Resolving or establishing an outgoing transport.

enumerator Accepting

Adopting an accepted transport.

enumerator Handshaking

Negotiating and authenticating a secure protocol.

enumerator Active

Application byte-stream traffic is permitted.

enumerator Closing

Graceful protocol or transport closure is in progress.

enumerator Closed

Terminal orderly closure or explicit abort.

enumerator Failed

Terminal state after an operational failure.

using erbsland::network::NetworkDataFn = std::function<void(mem::ByteBlock)>

A callback receiving an owned block of stream data.

class NetworkError : public erbsland::err::RuntimeError

An asynchronous network operation error.

Public Functions

explicit NetworkError(NetworkErrorContext context, std::exception_ptr cause = {}) noexcept

Create an asynchronous network error.

Parameters:
  • context – The structured operation context.

  • cause – The optional platform or lower-level cause.

virtual err::DiagnosticConstPtr diagnostic() const override

Convert the error with all its details into a structured diagnostic.

inline const NetworkErrorContext &context() const noexcept

Get the structured network context.

Returns:

The retained error context.

class NetworkErrorContext

Structured and machine-readable context for an asynchronous network failure.

Public Functions

inline NetworkErrorContext(text::String title, text::String description) noexcept

Create a network error context.

Parameters:
  • title – The short error title.

  • description – The user-facing error description.

inline const text::String &title() const noexcept

Get the short error title.

Returns:

The title.

inline const text::String &description() const noexcept

Get the user-facing error description.

Returns:

The description.

inline NetworkErrorReason reason() const noexcept

Get the machine-readable error reason.

inline NetworkErrorPhase phase() const noexcept

Get the operation phase in which the failure occurred.

inline const std::optional<TlsAlertDescription> &tlsAlert() const noexcept

Get the public TLS alert associated with the failure.

inline const std::optional<Host> &host() const noexcept

Get the optional host involved in the operation.

Returns:

The host, or std::nullopt if it is unavailable.

inline const std::optional<IpEndpoint> &localEndpoint() const noexcept

Get the optional local endpoint.

Returns:

The local endpoint, or std::nullopt if it is unavailable.

inline const std::optional<HostEndpoint> &remoteEndpoint() const noexcept

Get the optional remote endpoint.

Returns:

The remote endpoint, or std::nullopt if it is unavailable.

inline const system::PlatformErrorContextConstPtr &platformContext() const noexcept

Get the optional platform error context.

Returns:

The platform context, or a null pointer if it is unavailable.

inline NetworkErrorContext &setLocalEndpoint(IpEndpoint endpoint) noexcept

Set the local endpoint.

Parameters:

endpoint – The local endpoint involved in the operation.

Returns:

This context for chaining.

inline NetworkErrorContext &setReason(const NetworkErrorReason reason) noexcept

Set the machine-readable error reason.

Parameters:

reason – The portable error reason.

Returns:

This context for chaining.

inline NetworkErrorContext &setPhase(const NetworkErrorPhase phase) noexcept

Set the operation phase.

Parameters:

phase – The phase in which the failure occurred.

Returns:

This context for chaining.

inline NetworkErrorContext &setTlsAlert(const TlsAlertDescription alert) noexcept

Set the associated TLS alert.

Parameters:

alert – The exact public TLS alert description.

Returns:

This context for chaining.

inline NetworkErrorContext &setHost(Host host) noexcept

Set the host involved in the operation.

Parameters:

host – The host involved in the operation.

Returns:

This context for chaining.

inline NetworkErrorContext &setRemoteEndpoint(HostEndpoint endpoint) noexcept

Set the remote endpoint.

Parameters:

endpoint – The remote endpoint involved in the operation.

Returns:

This context for chaining.

inline NetworkErrorContext &setPlatformContext(system::PlatformErrorContextConstPtr context) noexcept

Set the platform error context.

Parameters:

context – The platform-specific error details.

Returns:

This context for chaining.

using erbsland::network::NetworkErrorFn = std::function<void(const NetworkErrorContext&)>

A callback receiving structured context for an asynchronous network error.

enum class erbsland::network::NetworkErrorPhase : uint8_t

The operation phase in which a network failure occurred.

Values:

enumerator None

No more specific phase is available.

enumerator Configuration

Synchronous connection configuration.

enumerator Accepting

Incoming connection admission or transport adoption.

enumerator Resolving

Host-name resolution.

enumerator Connecting

Transport connection establishment.

enumerator Handshaking

TLS protocol negotiation and peer authentication.

enumerator Active

Authenticated application traffic.

enumerator HttpRequest

HTTP request queueing, serialization, or overall lifetime.

enumerator HttpResponseHeaders

HTTP response status line and main fields.

enumerator HttpResponseBody

HTTP response body, trailers, or local conversion.

enumerator Closing

Graceful protocol or transport closure.

enum class erbsland::network::NetworkErrorReason : std::uint8_t

A machine-readable reason for an asynchronous network failure.

Values:

enumerator Unknown

The failure has no more specific portable reason.

enumerator Timeout

The operation exceeded its configured deadline.

enumerator HostNotFound

The resolver reported that the requested host does not exist.

enumerator NoAddresses

The resolver returned no supported IP addresses.

enumerator HostResolutionFailed

The native host resolver failed for another reason.

enumerator AddressInUse

The requested local address or port is already in use.

enumerator PermissionDenied

The platform denied the requested socket operation.

enumerator NetworkUnreachable

No route to the requested network or host is available.

enumerator ConnectionRefused

The remote endpoint refused the operation.

enumerator ConnectionReset

The established connection was reset by its peer or the network.

enumerator MessageTooLarge

A datagram exceeded a native transport limit.

enumerator SocketOperationFailed

Another native socket operation failed.

enumerator ResourceLimitExceeded

A configured finite resource quota is full.

enumerator ConfigurationFailed

Required application connection configuration is unavailable.

enumerator TlsProtocolFailure

The peer violated the TLS protocol.

enumerator TlsAuthenticationFailure

Peer certificate or proof-of-possession authentication failed.

enumerator TlsPolicyFailure

A TLS policy rejected the peer or negotiated parameters.

enumerator TlsPeerAlert

The peer sent a fatal TLS alert.

enumerator TlsTruncation

The transport ended without authenticated TLS close notification.

enumerator TlsInternalFailure

A local TLS implementation operation failed.

enumerator ContentSourceFailed

A static file or resource provider failed unexpectedly.

enumerator ContentSinkFailed

A response output sink failed unexpectedly.

enumerator HttpProtocolFailure

The peer violated HTTP syntax or framing.

enumerator HttpResponseValidationFailure

A response failed selected media, text, or JSON validation.

enumerator HttpRedirectFailure

A redirect was rejected or could not satisfy a hard follow guard.

using erbsland::network::NetworkEventFn = std::function<void()>

A callback for a network state transition without associated data.

class NetworkSendStatus : public erbsland::util::Result

The immediate result of an atomic non-blocking network send.

Public Functions

inline constexpr NetworkSendStatus(const Value value) noexcept

Create a send status from a result value.

Parameters:

value – The internal result value.

inline bool isAccepted() const noexcept

Test if the complete message was accepted.

Returns:

true for Accepted.

inline bool wouldBlock() const noexcept

Test if capacity must become writable before retrying.

Returns:

true for WouldBlock.

inline bool isClosed() const noexcept

Test if the source no longer accepts output.

Returns:

true for Closed.

Public Static Attributes

static const NetworkSendStatus Accepted = NetworkSendStatus::Value::success<0>()

The complete message was accepted atomically.

static const NetworkSendStatus WouldBlock = NetworkSendStatus::Value::failure<0>()

The send queue currently has insufficient capacity.

static const NetworkSendStatus Closed = NetworkSendStatus::Value::failure<1>()

The source no longer accepts output.

enum class erbsland::network::NetworkSourceState : uint8_t

The lifecycle state of a network event source.

Values:

enumerator Inactive

Configurable and not yet started.

enumerator Starting

Started but not yet ready for regular operation.

enumerator Active

Ready for regular operation.

enumerator Closing

Graceful closure is draining accepted output.

enumerator Closed

Terminal successful or cancelled state.

enumerator Failed

Terminal state after an operational error.

class SocketBufferLimits

Finite send and receive buffer limits for network sources.

Public Functions

constexpr SocketBufferLimits() noexcept = default

Create limits of one MiB in each direction.

inline constexpr SocketBufferLimits(unit::ByteLength send, unit::ByteLength receive) noexcept

Create explicit send and receive queue limits.

Parameters:
  • send – The maximum queued output size.

  • receive – The maximum buffered input size.

inline constexpr unit::ByteLength send() const noexcept

Get the send queue limit.

Returns:

The maximum queued output size.

inline constexpr unit::ByteLength receive() const noexcept

Get the receive buffer limit.

Returns:

The maximum buffered input size.

class TcpAcceptOptions

Options captured when a pending TCP connection is accepted.

Public Functions

inline constexpr SocketBufferLimits bufferLimits() const noexcept

Get the connected stream buffer limits.

inline TcpAcceptOptions &setBufferLimits(const SocketBufferLimits value) noexcept

Set the connected stream buffer limits.

class TcpConnection : public erbsland::network::Connection

A one-shot TCP connection spanning establishment and active byte-stream use.

Subclassed by erbsland::network::impl::TcpConnection

Public Functions

virtual void connect(HostEndpoint remoteEndpoint, TcpConnectOptions options) = 0

Resolve and connect to a remote endpoint.

Parameters:
  • remoteEndpoint – The numeric address or host name and port.

  • options – The connection policy and stream limits.

void connect(HostEndpoint remoteEndpoint)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

virtual void accept(TcpConnectionRequestPtr request, TcpAcceptOptions options) = 0

Adopt a pending incoming connection.

Parameters:
  • request – The transferable pending request.

  • options – The accepted stream options.

void accept(TcpConnectionRequestPtr request)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

virtual std::optional<IpEndpoint> localEndpoint() const override = 0

Get the resolved local endpoint.

virtual std::optional<IpEndpoint> remoteEndpoint() const override = 0

Get the resolved remote endpoint.

virtual SocketBufferLimits bufferLimits() const noexcept override = 0

Get the configured application-stream buffer limits.

virtual ConnectionState state() const noexcept override = 0

Get the connection lifecycle state.

virtual NetworkSendStatus send(const mem::ByteBlock &data) override = 0

Atomically submit one complete application byte block.

Parameters:

data – The owned stream data to queue.

Returns:

Whether the block was accepted, back-pressured, or rejected because the stream is closed.

virtual void pauseReceiving() override = 0

Suspend application-data delivery.

virtual void resumeReceiving() override = 0

Resume application-data delivery.

virtual void close() override = 0

Start protocol-specific graceful closure after accepted output drains.

virtual void abort() noexcept override = 0

Abort the connection immediately.

virtual TcpConnectionEventEditor &events() override = 0

Access the stable source-owned connection event editor.

using erbsland::network::TcpConnectionPtr = std::shared_ptr<TcpConnection>

A shared connected TCP stream.

class TcpConnectionEventEditor : public erbsland::network::ConnectionEventEditor

Callback editor for a connected TCP byte stream.

The connection owns this stable editor; its common base exposes the source and callback target to generic code.

Subclassed by erbsland::network::impl::TcpConnectionEventEditor

Public Functions

virtual TcpConnectionEventEditor &onHostResolved(TcpHostResolvedFn callback) = 0

Set the host-resolution callback.

This callback runs before any native connection begins and may call abort() on the connection.

Parameters:

callback – The callback receiving ordered resolved endpoints.

Returns:

This editor for chaining.

virtual TcpConnectionEventEditor &onConnected(NetworkEventFn callback) = 0

Set the connected callback.

Parameters:

callback – The callback invoked after an outgoing or accepted stream becomes active.

Returns:

This editor for chaining.

virtual TcpConnectionEventEditor &onData(NetworkDataFn callback) override = 0

Set the received application-data callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TcpConnectionEventEditor &onWritable(NetworkEventFn callback) override = 0

Set the writable-transition callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TcpConnectionEventEditor &onClosed(ConnectionCloseFn callback) override = 0

Set the orderly-closure callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TcpConnectionEventEditor &onError(NetworkErrorFn callback) override = 0

Set the operational-error callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TcpConnectionEventEditor &onFinal(NetworkEventFn callback) override = 0

Set the exactly-once terminal callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

using erbsland::network::TcpConnectionFilterFn = std::function<TcpConnectionFilterResult(const IpEndpoint&)>

A synchronous callback deciding whether an incoming TCP endpoint is admitted.

enum class erbsland::network::TcpConnectionFilterResult : std::uint8_t

The synchronous admission decision for an incoming TCP connection.

Values:

enumerator Accept

Create and emit a pending connection request.

enumerator Reject

Close the incoming connection immediately.

using erbsland::network::TcpConnectionFn = std::function<void(TcpConnectionPtr)>

A callback receiving a newly connected TCP stream.

class TcpConnectionRequest

A pending incoming TCP connection decision.

A request does not emit callbacks and is therefore not an EventSource. Listener implementations enforce its owner-loop affinity while this object only represents the accept-or-reject decision. Concrete implementations reject an undecided request when it is destroyed.

Subclassed by erbsland::network::impl::TcpConnectionRequest

Public Functions

virtual const IpEndpoint &remoteEndpoint() const noexcept = 0

Get the resolved remote endpoint.

Returns:

The connecting peer endpoint.

virtual TcpConnectionRequestState state() const noexcept = 0

Get the request lifecycle state.

Returns:

The current state.

virtual void reject() noexcept = 0

Reject the pending request immediately.

This method is thread-safe and idempotent.

using erbsland::network::TcpConnectionRequestPtr = std::shared_ptr<TcpConnectionRequest>

A shared pending incoming TCP connection request.

using erbsland::network::TcpConnectionRequestFn = std::function<void(TcpConnectionRequestPtr)>

A callback receiving a pending incoming TCP connection request.

enum class erbsland::network::TcpConnectionRequestState : std::uint8_t

The decision state of a pending incoming TCP connection.

Values:

enumerator Pending

No accept-or-reject decision was made yet.

enumerator Accepted

A prepared connection claimed the request.

enumerator Rejected

The request was rejected or abandoned.

class TcpConnectOptions

Options captured when an outgoing TCP connection is started.

Public Functions

inline time::TimeDelta timeout() const noexcept

Get the overall resolution-and-connection timeout.

inline TcpConnectOptions &setTimeout(const time::TimeDelta value) noexcept

Set the overall resolution-and-connection timeout.

inline HostLookupOptions hostLookupOptions() const noexcept

Get the host-lookup options.

inline TcpConnectOptions &setHostLookupOptions(const HostLookupOptions value) noexcept

Set the host-lookup options.

inline constexpr SocketBufferLimits bufferLimits() const noexcept

Get the connected stream buffer limits.

inline TcpConnectOptions &setBufferLimits(const SocketBufferLimits value) noexcept

Set the connected stream buffer limits.

Public Static Attributes

static const auto cDefaultTimeout = time::TimeDelta::seconds(30)

The default deadline for resolution and all connection attempts.

using erbsland::network::TcpHostResolvedFn = std::function<void(const util::List<IpEndpoint>&)>

A callback receiving ordered resolved endpoints before an outgoing TCP connection begins.

class TcpListener : public erbsland::event::EventSource

An inactive TCP listening socket.

Subclassed by erbsland::network::impl::TcpListener

Public Functions

virtual std::optional<IpEndpoint> localEndpoint() const = 0

Get the resolved local endpoint.

Returns:

The configured or bound local endpoint.

virtual NetworkSourceState state() const noexcept = 0

Get the source lifecycle state.

Returns:

The current state.

virtual void start(IpEndpoint localEndpoint, TcpListenerOptions options) = 0

Start binding and listening.

Parameters:
  • localEndpoint – The local address and port to bind.

  • options – The listener backlog, pending-request limit, and admission filter.

void start(IpEndpoint localEndpoint)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

virtual void pauseAccepting() = 0

Suspend delivery of incoming connection requests.

virtual void resumeAccepting() = 0

Resume delivery of incoming connection requests.

virtual void close() = 0

Close the listener gracefully.

virtual void abort() noexcept = 0

Abort the listener immediately.

virtual TcpListenerEventEditor &events() override = 0

Access the editor for the listener-owned event handlers.

Returns:

The stable source-owned editor.

using erbsland::network::TcpListenerPtr = std::shared_ptr<TcpListener>

A shared TCP listener.

class TcpListenerEventEditor : public erbsland::event::impl::CommonEventEditor

Callback editor for a TCP listener.

The listener owns this stable editor; its common base exposes the source and callback target to generic code.

Subclassed by erbsland::network::impl::TcpListenerEventEditor

Public Functions

virtual TcpListenerEventEditor &onListening(NetworkEventFn callback) = 0

Set the listening-ready callback.

Parameters:

callback – The callback invoked after binding and listening succeeds.

Returns:

This editor for chaining.

virtual TcpListenerEventEditor &onConnection(TcpConnectionRequestFn callback) = 0

Set the incoming-connection callback.

Parameters:

callback – The callback receiving pending requests.

Returns:

This editor for chaining.

virtual TcpListenerEventEditor &onClosed(NetworkEventFn callback) = 0

Set the closure callback.

Parameters:

callback – The callback invoked after the listener closes.

Returns:

This editor for chaining.

virtual TcpListenerEventEditor &onError(NetworkErrorFn callback) = 0

Set the operational-error callback.

Parameters:

callback – The callback receiving the error.

Returns:

This editor for chaining.

virtual TcpListenerEventEditor &onFinal(NetworkEventFn callback) = 0

Set the final callback.

Parameters:

callback – The callback invoked after closure, failure, or explicit abort.

Returns:

This editor for chaining.

class TcpListenerOptions

Options captured when a TCP listener is started.

The connection filter runs synchronously on the listener event loop and must remain fast and non-blocking.

Public Functions

TcpListenerOptions()

Create options with one private bounded connection quota.

inline constexpr unit::ItemCount backlog() const noexcept

Get the requested native pending-connection backlog.

inline TcpListenerOptions &setBacklog(const unit::ItemCount value) noexcept

Set the requested native pending-connection backlog.

inline constexpr unit::ItemCount maximumPendingRequests() const noexcept

Get the maximum number of emitted requests awaiting a decision.

inline TcpListenerOptions &setMaximumPendingRequests(const unit::ItemCount value) noexcept

Set the maximum number of emitted requests awaiting a decision.

inline const TcpConnectionFilterFn &connectionFilter() const noexcept

Get the synchronous incoming-connection filter.

inline TcpListenerOptions &setConnectionFilter(TcpConnectionFilterFn value)

Set the synchronous incoming-connection filter.

inline const ConnectionQuotaPtr &connectionQuota() const noexcept

Get the shared accepted-connection quota.

inline TcpListenerOptions &setConnectionQuota(ConnectionQuotaPtr value) noexcept

Set the quota shared by accepted connections and optionally multiple listeners.

Parameters:

value – The non-null shared quota.

Returns:

This options object for chaining.

Public Static Attributes

static constexpr auto cDefaultBacklog = unit::ItemCount{128U}

The default native pending-connection backlog.

static constexpr auto cDefaultMaximumPendingRequests = unit::ItemCount{128U}

The default maximum number of emitted requests awaiting a decision.

static constexpr auto cDefaultMaximumConnections = unit::ItemCount{1024U}

The default maximum number of accepted sockets retained by one listener quota.

enum class erbsland::network::TlsAlertDescription : uint8_t

A TLS alert description preserved as its public RFC wire value.

Unknown peer values can be represented by casting their received byte to this type.

Values:

enumerator CloseNotify

Orderly TLS closure.

enumerator UnexpectedMessage

Message was inappropriate for the current state.

enumerator BadRecordMac

Record authentication failed.

enumerator RecordOverflow

Record exceeded the protocol limit.

enumerator HandshakeFailure

No acceptable security parameters were negotiated.

enumerator BadCertificate

Certificate processing failed generically.

enumerator UnsupportedCertificate

Certificate type or algorithm is unsupported.

enumerator CertificateRevoked

Certificate was revoked.

enumerator CertificateExpired

Certificate is outside its validity period.

enumerator CertificateUnknown

Another certificate failure occurred.

enumerator IllegalParameter

A field was inconsistent with negotiated parameters.

enumerator UnknownCa

No trusted certification path was found.

enumerator AccessDenied

Access was denied after authentication.

enumerator DecodeError

A field could not be decoded completely.

enumerator DecryptError

A handshake signature or Finished value failed.

enumerator ProtocolVersion

The peer did not negotiate a supported protocol version.

enumerator InsufficientSecurity

Negotiated parameters did not meet security policy.

enumerator InternalError

A local internal operation failed.

enumerator InappropriateFallback

A protocol fallback was inappropriate.

enumerator UserCanceled

An operation was cancelled by its initiator.

enumerator MissingExtension

A mandatory extension was absent.

enumerator UnsupportedExtension

A forbidden or unsolicited extension was received.

enumerator UnrecognizedName

The requested server name was not recognized.

enumerator BadCertificateStatusResponse

Certificate status response validation failed.

enumerator UnknownPskIdentity

A pre-shared key identity was unknown.

enumerator CertificateRequired

A required certificate was not supplied.

enumerator NoApplicationProtocol

No acceptable ALPN protocol was negotiated.

class TlsClientConnection : public erbsland::network::Connection

A one-shot authenticated TLS 1.3 client connection over TCP.

Subclassed by erbsland::network::impl::TlsClientConnection

Public Functions

virtual text::String requestedConfigurationLabel() const = 0

Get the label requested when the connection started.

virtual text::String matchedConfigurationLabel() const = 0

Get the exact registry label selected by fallback.

virtual std::optional<HostEndpoint> requestedEndpoint() const = 0

Get the originally requested endpoint.

virtual std::optional<cryptology::TlsCipherSuite> cipherSuite() const = 0

Get the negotiated cipher suite.

virtual text::String negotiatedAlpn() const = 0

Get the selected ALPN identifier, or an empty string when none was selected.

virtual util::List<cryptology::X509Certificate> peerCertificatePath() const = 0

Get the authenticated target-to-anchor peer certificate path.

void connect(HostEndpoint endpoint)

Resolve configuration and connect using default options.

virtual void connect(HostEndpoint endpoint, TlsClientConnectOptions options) = 0

Resolve configuration synchronously and start the one-shot connection.

Throws:
  • err::ParameterError – If options or the endpoint are invalid.

  • err::RuntimeError – If no complete client TLS configuration resolves.

virtual std::optional<IpEndpoint> localEndpoint() const override = 0

Get the resolved local endpoint.

virtual std::optional<IpEndpoint> remoteEndpoint() const override = 0

Get the resolved remote endpoint.

virtual SocketBufferLimits bufferLimits() const noexcept override = 0

Get the configured application-stream buffer limits.

virtual ConnectionState state() const noexcept override = 0

Get the connection lifecycle state.

virtual NetworkSendStatus send(const mem::ByteBlock &data) override = 0

Atomically submit one complete application byte block.

Parameters:

data – The owned stream data to queue.

Returns:

Whether the block was accepted, back-pressured, or rejected because the stream is closed.

virtual void pauseReceiving() override = 0

Suspend application-data delivery.

virtual void resumeReceiving() override = 0

Resume application-data delivery.

virtual void close() override = 0

Start protocol-specific graceful closure after accepted output drains.

virtual void abort() noexcept override = 0

Abort the connection immediately.

virtual TlsClientConnectionEventEditor &events() override = 0

Access the stable source-owned connection event editor.

class TlsClientConnectionEventEditor : public erbsland::network::ConnectionEventEditor

Callback editor for an authenticated TLS client connection.

Subclassed by erbsland::network::impl::TlsClientConnectionEventEditor

Public Functions

virtual TlsClientConnectionEventEditor &onHostResolved(TcpHostResolvedFn callback) = 0

Set the checkpoint invoked after DNS resolution produced transport candidates.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsClientConnectionEventEditor &onTransportConnected(NetworkEventFn callback) = 0

Set the checkpoint invoked after TCP establishment and before TLS startup.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsClientConnectionEventEditor &onPeerHello(NetworkEventFn callback) = 0

Set the checkpoint invoked after authenticated parsing of EncryptedExtensions.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsClientConnectionEventEditor &onPeerAuthenticated(NetworkEventFn callback) = 0

Set the checkpoint invoked after certificate validation and CertificateVerify.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsClientConnectionEventEditor &onHandshakeCompleted(NetworkEventFn callback) = 0

Set the checkpoint invoked after verified server Finished and queued client Finished.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsClientConnectionEventEditor &onData(NetworkDataFn callback) override = 0

Set the received application-data callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsClientConnectionEventEditor &onWritable(NetworkEventFn callback) override = 0

Set the writable-transition callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsClientConnectionEventEditor &onClosed(ConnectionCloseFn callback) override = 0

Set the orderly-closure callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsClientConnectionEventEditor &onError(NetworkErrorFn callback) override = 0

Set the operational-error callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsClientConnectionEventEditor &onFinal(NetworkEventFn callback) override = 0

Set the exactly-once terminal callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

class TlsClientConnectOptions

Options captured when an outgoing TLS client connection is started.

Public Functions

inline const text::String &configurationLabel() const noexcept

Get the application TLS configuration label.

inline TlsClientConnectOptions &setConfigurationLabel(text::String value) noexcept

Set the application TLS configuration label.

Parameters:

value – The exact or descendant registry label to resolve.

Returns:

This options object for chaining.

inline const TcpConnectOptions &tcpOptions() const noexcept

Get the nested DNS/TCP connection options.

inline TlsClientConnectOptions &setTcpOptions(TcpConnectOptions value) noexcept

Set the nested DNS/TCP connection options.

Parameters:

value – The DNS and TCP options.

Returns:

This options object for chaining.

inline SocketBufferLimits bufferLimits() const noexcept

Get the TLS protocol queue limits.

inline TlsClientConnectOptions &setBufferLimits(const SocketBufferLimits value) noexcept

Set the TLS protocol queue limits.

Parameters:

value – The TLS-owned send and aggregate receive bounds.

Returns:

This options object for chaining.

inline const std::vector<text::String> &alpnProtocols() const noexcept

Get the ordered ALPN offers.

inline TlsClientConnectOptions &setAlpnProtocols(std::vector<text::String> value) noexcept

Set the ordered ALPN offers.

Parameters:

value – The protocols in client preference order.

Returns:

This options object for chaining.

inline time::TimeDelta handshakeTimeout() const noexcept

Get the TLS handshake timeout.

inline TlsClientConnectOptions &setHandshakeTimeout(const time::TimeDelta value) noexcept

Set the TLS handshake timeout.

Parameters:

value – The positive timeout after TCP establishment.

Returns:

This options object for chaining.

inline time::TimeDelta idleTimeout() const noexcept

Get the authenticated application idle timeout.

inline TlsClientConnectOptions &setIdleTimeout(const time::TimeDelta value) noexcept

Set the authenticated application idle timeout.

Parameters:

value – The positive timeout between application activities.

Returns:

This options object for chaining.

inline time::TimeDelta closeTimeout() const noexcept

Get the graceful TLS closure timeout.

inline TlsClientConnectOptions &setCloseTimeout(const time::TimeDelta value) noexcept

Set the graceful TLS closure timeout.

Parameters:

value – The positive bidirectional close-notify timeout.

Returns:

This options object for chaining.

Public Static Attributes

static const auto cDefaultConfigurationLabel = text::String{"tls/client"}

Reserved framework label for regular TLS clients.

static const auto cDefaultHandshakeTimeout = time::TimeDelta::seconds(30)

Default handshake deadline after TCP connection establishment.

static const auto cDefaultIdleTimeout = time::TimeDelta::minutes(5)

Default authenticated application idle deadline.

static const auto cDefaultCloseTimeout = time::TimeDelta::seconds(10)

Default bidirectional close-notify deadline.

static constexpr auto cMaximumBufferLength = unit::ByteLength{16U * 1024U * 1024U}

Maximum accepted TLS-owned queue limit in either direction.

static constexpr auto cMaximumApplicationSendLength = unit::ByteLength{16U * 1024U}

Maximum one-shot application send size.

class TlsServerAcceptOptions

Options captured when an incoming TLS server connection is accepted.

Public Functions

inline explicit TlsServerAcceptOptions(ConnectionQuotaPtr handshakeQuota)

Create options using a required shared handshake quota.

Parameters:

handshakeQuota – The quota held until peer Finished is authenticated.

inline const ConnectionQuotaPtr &handshakeQuota() const noexcept

Get the shared incomplete-handshake quota.

inline const text::String &configurationLabel() const noexcept

Get the required default identity configuration label.

inline TlsServerAcceptOptions &setConfigurationLabel(text::String value) noexcept

Set the required default identity configuration label.

Parameters:

value – The exact or descendant registry label to resolve.

Returns:

This options object for chaining.

inline const std::vector<TlsServerIdentityMapping> &identityMappings() const noexcept

Get the exact canonical SNI identity mappings.

inline TlsServerAcceptOptions &setIdentityMappings(std::vector<TlsServerIdentityMapping> value) noexcept

Replace all exact canonical SNI identity mappings.

Parameters:

value – At most 64 mappings with unique server names.

Returns:

This options object for chaining.

inline const TcpAcceptOptions &tcpOptions() const noexcept

Get the nested accepted TCP stream options.

inline TlsServerAcceptOptions &setTcpOptions(TcpAcceptOptions value) noexcept

Set the nested accepted TCP stream options.

Parameters:

value – The accepted TCP stream options.

Returns:

This options object for chaining.

inline SocketBufferLimits bufferLimits() const noexcept

Get the TLS protocol queue limits.

inline TlsServerAcceptOptions &setBufferLimits(const SocketBufferLimits value) noexcept

Set the TLS protocol queue limits.

Parameters:

value – The TLS-owned send and aggregate receive bounds.

Returns:

This options object for chaining.

inline const std::vector<text::String> &alpnProtocols() const noexcept

Get supported ALPN identifiers in server-preference order.

inline TlsServerAcceptOptions &setAlpnProtocols(std::vector<text::String> value) noexcept

Set supported ALPN identifiers in server-preference order.

Parameters:

value – The bounded non-empty protocol identifiers.

Returns:

This options object for chaining.

inline const std::vector<cryptology::TlsCipherSuite> &cipherSuites() const noexcept

Get enabled cipher suites in server-preference order.

inline TlsServerAcceptOptions &setCipherSuites(std::vector<cryptology::TlsCipherSuite> value) noexcept

Set enabled cipher suites in server-preference order.

Parameters:

value – The non-empty unique suite list.

Returns:

This options object for chaining.

inline time::TimeDelta handshakeTimeout() const noexcept

Get the TLS handshake timeout.

inline TlsServerAcceptOptions &setHandshakeTimeout(const time::TimeDelta value) noexcept

Set the TLS handshake timeout.

Parameters:

value – The positive timeout after TCP adoption.

Returns:

This options object for chaining.

inline time::TimeDelta idleTimeout() const noexcept

Get the authenticated application idle timeout.

inline TlsServerAcceptOptions &setIdleTimeout(const time::TimeDelta value) noexcept

Set the authenticated application idle timeout.

Parameters:

value – The positive timeout between application activities.

Returns:

This options object for chaining.

inline time::TimeDelta closeTimeout() const noexcept

Get the graceful TLS closure timeout.

inline TlsServerAcceptOptions &setCloseTimeout(const time::TimeDelta value) noexcept

Set the graceful TLS closure timeout.

Parameters:

value – The positive bidirectional close-notify timeout.

Returns:

This options object for chaining.

Public Static Attributes

static const auto cDefaultConfigurationLabel = text::String{"tls/server"}

Reserved framework label for regular TLS servers.

static const auto cDefaultHandshakeTimeout = time::TimeDelta::seconds(30)

Default handshake deadline after TCP adoption.

static const auto cDefaultIdleTimeout = time::TimeDelta::minutes(5)

Default authenticated application idle deadline.

static const auto cDefaultCloseTimeout = time::TimeDelta::seconds(10)

Default bidirectional close-notify deadline.

static constexpr auto cMaximumBufferLength = unit::ByteLength{16U * 1024U * 1024U}

Maximum accepted TLS-owned queue limit in either direction.

static constexpr auto cMaximumApplicationSendLength = unit::ByteLength{16U * 1024U}

Maximum one-shot application send size.

static constexpr auto cMaximumIdentityMappings = unit::ItemCount{64U}

Maximum number of exact SNI identity mappings.

class TlsServerConnection : public erbsland::network::Connection

A one-shot authenticated TLS 1.3 server connection over an accepted TCP request.

Subclassed by erbsland::network::impl::TlsServerConnection

Public Functions

virtual std::optional<text::String> requestedConfigurationLabel() const = 0

Get the selected requested application TLS configuration label.

virtual std::optional<text::String> matchedConfigurationLabel() const = 0

Get the selected exact registry label after fallback.

virtual std::optional<HostName> serverName() const = 0

Get the canonical SNI name, if offered.

virtual std::vector<text::String> offeredAlpn() const = 0

Get the bounded client ALPN offer in wire order.

virtual text::String negotiatedAlpn() const = 0

Get the selected ALPN identifier, or an empty block.

virtual std::optional<cryptology::TlsCipherSuite> cipherSuite() const = 0

Get the negotiated cipher suite.

virtual std::optional<cryptology::TlsSignatureScheme> signatureScheme() const = 0

Get the selected CertificateVerify signature scheme.

virtual void accept(TcpConnectionRequestPtr request, TlsServerAcceptOptions options) = 0

Resolve immutable identity configurations and consume one pending TCP request.

Parameters:
  • request – The transferable pending TCP request.

  • options – The complete accepted TLS policy and required handshake quota.

Throws:
  • err::ParameterError – If the options, mappings, quota, or request are invalid.

  • err::RuntimeError – If a required immutable TLS identity cannot be resolved.

virtual std::optional<IpEndpoint> localEndpoint() const override = 0

Get the resolved local endpoint.

virtual std::optional<IpEndpoint> remoteEndpoint() const override = 0

Get the resolved remote endpoint.

virtual SocketBufferLimits bufferLimits() const noexcept override = 0

Get the configured application-stream buffer limits.

virtual ConnectionState state() const noexcept override = 0

Get the connection lifecycle state.

virtual NetworkSendStatus send(const mem::ByteBlock &data) override = 0

Atomically submit one complete application byte block.

Parameters:

data – The owned stream data to queue.

Returns:

Whether the block was accepted, back-pressured, or rejected because the stream is closed.

virtual void pauseReceiving() override = 0

Suspend application-data delivery.

virtual void resumeReceiving() override = 0

Resume application-data delivery.

virtual void close() override = 0

Start protocol-specific graceful closure after accepted output drains.

virtual void abort() noexcept override = 0

Abort the connection immediately.

virtual TlsServerConnectionEventEditor &events() override = 0

Access the stable source-owned connection event editor.

class TlsServerConnectionEventEditor : public erbsland::network::ConnectionEventEditor

Callback editor for an accepted authenticated TLS server connection.

Subclassed by erbsland::network::impl::TlsServerConnectionEventEditor

Public Functions

virtual TlsServerConnectionEventEditor &onTransportConnected(NetworkEventFn callback) = 0

Set the checkpoint after the accepted TCP transport becomes active.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsServerConnectionEventEditor &onClientHello(NetworkEventFn callback) = 0

Set the checkpoint after bounded ClientHello parsing and policy selection.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsServerConnectionEventEditor &onHandshakeCompleted(NetworkEventFn callback) = 0

Set the checkpoint after authenticated client Finished.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsServerConnectionEventEditor &onData(NetworkDataFn callback) override = 0

Set the received application-data callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsServerConnectionEventEditor &onWritable(NetworkEventFn callback) override = 0

Set the writable-transition callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsServerConnectionEventEditor &onClosed(ConnectionCloseFn callback) override = 0

Set the orderly-closure callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsServerConnectionEventEditor &onError(NetworkErrorFn callback) override = 0

Set the operational-error callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

virtual TlsServerConnectionEventEditor &onFinal(NetworkEventFn callback) override = 0

Set the exactly-once terminal callback.

Parameters:

callback – The replacement callback.

Returns:

This editor for chaining.

class TlsServerIdentityMapping

An exact canonical SNI host name mapped to an application TLS configuration label.

Public Functions

inline TlsServerIdentityMapping(HostName serverName, text::String configurationLabel)

Create one exact SNI mapping.

Parameters:
  • serverName – The exact canonical SNI name.

  • configurationLabel – The application TLS configuration label to resolve.

inline const HostName &serverName() const noexcept

Get the exact canonical SNI host name.

inline const text::String &configurationLabel() const noexcept

Get the TLS configuration label resolved before accepting TCP.

class UdpDatagram

One owned UDP datagram and its remote endpoint.

Public Functions

UdpDatagram() = default

Create an empty datagram for the IPv4 any endpoint.

inline UdpDatagram(IpEndpoint remoteEndpoint, mem::ByteBlock data) noexcept

Create an owned datagram.

Parameters:
  • remoteEndpoint – The remote source or destination endpoint.

  • data – The owned datagram payload.

inline const IpEndpoint &remoteEndpoint() const noexcept

Get the remote endpoint.

Returns:

The datagram source or destination endpoint.

inline const mem::ByteBlock &data() const noexcept

Get the owned payload.

Returns:

The datagram bytes.

class UdpDatagramDropContext

Details about one incoming UDP datagram discarded by the socket.

Public Functions

inline UdpDatagramDropContext(UdpDatagramDropReason reason, unit::ByteLength maximumSize, std::optional<IpEndpoint> remoteEndpoint = {}, std::optional<unit::ByteLength> datagramSize = {}) noexcept

Create a datagram drop context.

Parameters:
  • reason – The reason for discarding the datagram.

  • maximumSize – The configured maximum payload size.

  • remoteEndpoint – The sender endpoint, if the platform reported it.

  • datagramSize – The original payload size, if the platform reported it.

inline constexpr UdpDatagramDropReason reason() const noexcept

Get the reason for discarding the datagram.

inline constexpr unit::ByteLength maximumSize() const noexcept

Get the configured maximum payload size.

inline const std::optional<IpEndpoint> &remoteEndpoint() const noexcept

Get the sender endpoint, if the platform reported it.

inline const std::optional<unit::ByteLength> &datagramSize() const noexcept

Get the original payload size, if the platform reported it.

using erbsland::network::UdpDatagramDropFn = std::function<void(const UdpDatagramDropContext&)>

A callback receiving details about one locally discarded UDP datagram.

enum class erbsland::network::UdpDatagramDropReason : std::uint8_t

The reason why an observed incoming UDP datagram was discarded.

Values:

enumerator TooLarge

The payload exceeded the configured maximum datagram size.

using erbsland::network::UdpDatagramFn = std::function<void(UdpDatagram)>

A callback receiving an owned UDP datagram.

class UdpSocket : public erbsland::event::EventSource

An UDP socket.

Subclassed by erbsland::network::impl::UdpSocket

Public Functions

virtual std::optional<IpEndpoint> localEndpoint() const = 0

Get the bound local endpoint.

This method is thread-safe.

Returns:

The bound endpoint, or std::nullopt before binding succeeds.

virtual NetworkSourceState state() const noexcept = 0

Get the source lifecycle state.

Returns:

The current state.

virtual void start(IpEndpoint localEndpoint, UdpSocketOptions options = {}) = 0

Start binding the inactive socket to a complete endpoint.

Parameters:
  • localEndpoint – The local address, port, and optional IPv6 scope.

  • options – The datagram and queue options captured for this socket.

Throws:
  • err::LogicError – If called outside the owner event loop or more than once.

  • err::ParameterError – If the endpoint or options are invalid.

void start(UdpSocketOptions options = {})

Start with an automatic IPv4 address and port.

Parameters:

options – The datagram and queue options captured for this socket.

void start(IpAddress localAddress, UdpSocketOptions options = {})

Start with a local address and automatic port.

Parameters:
  • localAddress – The local IPv4 or IPv6 address.

  • options – The datagram and queue options captured for this socket.

void start(Port localPort, UdpSocketOptions options = {})

Start with an IPv4-any address and a local port.

Parameters:
  • localPort – The local port, or the automatic port.

  • options – The datagram and queue options captured for this socket.

void start(IpAddress localAddress, Port localPort, UdpSocketOptions options = {})

Start with a local address and port.

Parameters:
  • localAddress – The local IPv4 or IPv6 address.

  • localPort – The local port, or the automatic port.

  • options – The datagram and queue options captured for this socket.

virtual NetworkSendStatus send(const UdpDatagram &datagram) = 0

Atomically submit one addressed datagram.

Parameters:

datagram – The owned payload and destination endpoint.

Throws:
  • err::LogicError – If called outside the owner event loop.

  • err::ParameterError – If the destination or payload is invalid for this socket.

Returns:

Whether the datagram was accepted, would block, or was rejected because the socket is closed. Fixed invalid datagrams throw synchronously; operational failures are reported through onError().

NetworkSendStatus send(const IpEndpoint &destination, const mem::ByteBlock &data)

Atomically submit one payload to a destination endpoint.

Parameters:
  • destination – The remote destination endpoint.

  • data – The owned datagram payload retained on acceptance.

Returns:

Whether the datagram was accepted, would block, or the socket is closed.

virtual void pauseReceiving() = 0

Suspend delivery of received datagrams.

virtual void resumeReceiving() = 0

Resume delivery of received datagrams.

virtual void close() = 0

Close gracefully after accepted datagrams drain.

virtual void abort() noexcept = 0

Abort the socket immediately.

virtual UdpSocketEventEditor &events() override = 0

Access the editor for the socket-owned event handlers.

Returns:

The stable source-owned editor.

using erbsland::network::UdpSocketPtr = std::shared_ptr<UdpSocket>

A shared unconnected UDP socket.

class UdpSocketEventEditor : public erbsland::event::impl::CommonEventEditor

Callback editor for a bound UDP socket.

The socket owns this stable editor; its common base exposes the source and callback target to generic code.

Subclassed by erbsland::network::impl::UdpSocketEventEditor

Public Functions

virtual UdpSocketEventEditor &onBound(NetworkEventFn callback) = 0

Set the bound-ready callback.

Parameters:

callback – The callback invoked after binding succeeds.

Returns:

This editor for chaining.

virtual UdpSocketEventEditor &onDatagram(UdpDatagramFn callback) = 0

Set the received-datagram callback.

Parameters:

callback – The callback receiving owned datagrams.

Returns:

This editor for chaining.

virtual UdpSocketEventEditor &onDatagramDropped(UdpDatagramDropFn callback) = 0

Set the discarded-datagram callback.

Parameters:

callback – The callback receiving details about locally discarded datagrams.

Returns:

This editor for chaining.

virtual UdpSocketEventEditor &onWritable(NetworkEventFn callback) = 0

Set the writable-transition callback.

Parameters:

callback – The callback invoked when capacity can satisfy a previously blocked send.

Returns:

This editor for chaining.

virtual UdpSocketEventEditor &onClosed(NetworkEventFn callback) = 0

Set the closure callback.

Parameters:

callback – The callback invoked after the socket closes.

Returns:

This editor for chaining.

virtual UdpSocketEventEditor &onError(NetworkErrorFn callback) = 0

Set the operational-error callback.

Parameters:

callback – The callback receiving the error.

Returns:

This editor for chaining.

class UdpSocketOptions

Options captured when a UDP socket is started.

Public Functions

inline constexpr unit::ByteLength maximumDatagramSize() const noexcept

Get the largest accepted incoming or outgoing datagram payload.

inline UdpSocketOptions &setMaximumDatagramSize(const unit::ByteLength value) noexcept

Set the largest accepted incoming or outgoing datagram payload.

inline constexpr unit::ByteLength sendQueueLimit() const noexcept

Get the maximum amount of queued outgoing payload data.

inline UdpSocketOptions &setSendQueueLimit(const unit::ByteLength value) noexcept

Set the maximum amount of queued outgoing payload data.

Public Static Attributes

static constexpr auto cMaximumPortableDatagramSize = unit::ByteLength{65'507U}

The largest portable UDP payload size.

static constexpr auto cDefaultMaximumDatagramSize = cMaximumPortableDatagramSize

The default maximum accepted datagram size.

static constexpr auto cDefaultSendQueueLimit = unit::ByteLength{1024U * 1024U}

The default queued output limit.