net

May 6, 2026 ยท View on GitHub

{#netmodule}

net

TCP/SSL/UDP networking, socket adapters, DNS resolution.

Namespaces

NameDescription
netSocket transports, adapters, and address helpers.
dnsDNS utilities.

{#net}

net

Socket transports, adapters, and address helpers.

Classes

NameDescription
AddressRepresents an IPv4 or IPv6 socket address with host and port.
PacketSocketEmitterSocket adapter that emits received data as packets.
SocketBase socket implementation from which all sockets derive.
SocketAdapterAbstract adapter interface for socket send/receive chains.
SocketEmitterSocketAdapter that exposes socket events as signals.
SocketPacketDefault packet type emitted by sockets.
SSLAdapterManages the OpenSSL context and BIO buffers for an SSL socket connection.
SSLContextOpenSSL SSL_CTX wrapper for client and server TLS configuration.
SSLManagerSingleton that owns the default client/server TLS contexts and related callbacks.
SSLSessionCached SSL/TLS session wrapper used for client-side resumption.
SSLSocketSSL socket implementation.
TCPSocketTCP socket implementation.
TransactionRequest/response helper for packet types emitted from a socket.
UDPSocketUDP socket implementation.
VerificationErrorDetailsA utility class for certificate error handling.
PacketInfoProvides information about packets emitted from a socket. See SocketPacket.

Enumerations

NameDescription
TransportTypeTransport protocol identifier used to distinguish socket types at runtime.
SocketModeTransport mode for socket adapters and accepted connections.

{#transporttype}

TransportType

enum TransportType

Transport protocol identifier used to distinguish socket types at runtime.

ValueDescription
UDPUnreliable datagram protocol.
TCPReliable stream protocol.
SSLTCPTLS-encrypted TCP stream.

{#socketmode}

SocketMode

enum SocketMode

Transport mode for socket adapters and accepted connections.

ValueDescription
ServerSideServer-side adapter.
ClientSideClient-side adapter.

Functions

ReturnNameDescription
std::shared_ptr< SocketT >makeSocket inlineCreates a socket of type SocketT wrapped in a shared_ptr.
SSLContext::VerificationModeconvertVerificationMode inlineNon-case sensitive conversion of a string to a VerificationMode enum. If verMode is illegal an ArgumentException is thrown.
std::stringconvertCertificateError inlineConverts an SSL certificate handling error code into an error message.
std::stringgetLastError inlineReturns the last error from the error stack.
voidclearErrorStack inlineClears the error stack.
voidgetNetworkInterfaces inlinePopulates hosts with all local network interface addresses.
intgetServerSocketSendBufSizeReturns the current send buffer size for a socket handle, in bytes. Passes val=0 to uv_send_buffer_size, which queries rather than sets the value.
intgetServerSocketRecvBufSizeReturns the current receive buffer size for a socket handle, in bytes. Passes val=0 to uv_recv_buffer_size, which queries rather than sets the value.
intsetServerSocketSendBufSizeSets the send buffer size for a socket handle.
intsetServerSocketRecvBufSizeSets the receive buffer size for a socket handle.

{#makesocket}

makeSocket

inline

template<class SocketT> inline std::shared_ptr< SocketT > makeSocket(uv::Loop * loop)

Creates a socket of type SocketT wrapped in a shared_ptr.

The socket is automatically destroyed when the last shared_ptr owner releases it.

Parameters

Parameters

  • loop Event loop to associate with the socket; defaults to the default loop.

Returns

A shared_ptr owning the newly created socket.


{#convertverificationmode}

convertVerificationMode

inline

inline SSLContext::VerificationMode convertVerificationMode(const std::string & vMode)

Non-case sensitive conversion of a string to a VerificationMode enum. If verMode is illegal an ArgumentException is thrown.


{#convertcertificateerror}

convertCertificateError

inline

inline std::string convertCertificateError(long errCode)

Converts an SSL certificate handling error code into an error message.


{#getlasterror}

getLastError

inline

inline std::string getLastError()

Returns the last error from the error stack.


{#clearerrorstack}

clearErrorStack

inline

inline void clearErrorStack()

Clears the error stack.


{#getnetworkinterfaces}

getNetworkInterfaces

inline

inline void getNetworkInterfaces(std::vector< net::Address > & hosts)

Populates hosts with all local network interface addresses.

Each entry is an IPv4 address constructed from the interface's address4 field. The results include loopback and any other active interfaces reported by libuv.

Parameters

  • hosts Vector to append the discovered addresses to.

{#getserversocketsendbufsize}

getServerSocketSendBufSize

template<typename T> int getServerSocketSendBufSize(uv::Handle< T > & handle)

Returns the current send buffer size for a socket handle, in bytes. Passes val=0 to uv_send_buffer_size, which queries rather than sets the value.

Parameters

  • T The libuv handle type (e.g. uv_tcp_t, uv_udp_t).

Parameters

  • handle The socket handle to query.

Returns

The send buffer size, or a libuv error code on failure.


{#getserversocketrecvbufsize}

getServerSocketRecvBufSize

template<typename T> int getServerSocketRecvBufSize(uv::Handle< T > & handle)

Returns the current receive buffer size for a socket handle, in bytes. Passes val=0 to uv_recv_buffer_size, which queries rather than sets the value.

Parameters

  • T The libuv handle type (e.g. uv_tcp_t, uv_udp_t).

Parameters

  • handle The socket handle to query.

Returns

The receive buffer size, or a libuv error code on failure.


{#setserversocketsendbufsize}

setServerSocketSendBufSize

template<typename T> int setServerSocketSendBufSize(uv::Handle< T > & handle, int size)

Sets the send buffer size for a socket handle.

Parameters

  • T The libuv handle type (e.g. uv_tcp_t, uv_udp_t).

Parameters

  • handle The socket handle to configure.

  • size The desired send buffer size in bytes.

Returns

0 on success, or a libuv error code on failure.


{#setserversocketrecvbufsize}

setServerSocketRecvBufSize

template<typename T> int setServerSocketRecvBufSize(uv::Handle< T > & handle, int size)

Sets the receive buffer size for a socket handle.

Parameters

  • T The libuv handle type (e.g. uv_tcp_t, uv_udp_t).

Parameters

  • handle The socket handle to configure.

  • size The desired receive buffer size in bytes.

Returns

0 on success, or a libuv error code on failure.

Variables

ReturnNameDescription
constexpr intMAX_TCP_PACKET_SIZEMaximum size of a single TCP receive buffer, in bytes.
constexpr intMAX_UDP_PACKET_SIZEMaximum size of a single UDP datagram payload, in bytes.

{#max_tcp_packet_size}

MAX_TCP_PACKET_SIZE

constexpr int MAX_TCP_PACKET_SIZE = 64 * 1024

Maximum size of a single TCP receive buffer, in bytes.


{#max_udp_packet_size}

MAX_UDP_PACKET_SIZE

constexpr int MAX_UDP_PACKET_SIZE = 1500

Maximum size of a single UDP datagram payload, in bytes.

{#address}

Address

#include <icy/net/address.h>

Represents an IPv4 or IPv6 socket address with host and port.

Public Methods

ReturnNameDescription
AddressCreates a wildcard (all zero) IPv4 Address.
AddressCreates an Address from an IP address and a port number.
AddressCreates an Address by copying another one.
AddressCreates an Address from a native socket address.
AddressCreates an Address from an IP address and a service name or port number.
Address explicitCreates an Address from an IP address or host name and a port number/service name. Host name/address and port number must be separated by a colon. In case of an IPv6 address, the address part must be enclosed in brackets.
~AddressDestroys the Address.
Address &operator=Assigns another Address.
voidswapSwaps the Address with another one.
std::stringhost constReturns the host IP address.
uint16_tport constReturns the port number.
socklen_tlength constReturns the length of the internal native socket address.
const struct sockaddr *addr constReturns a pointer to the internal native socket address.
intaf constReturns the address family (AF_INET or AF_INET6) of the address.
std::stringtoString constReturns a string representation of the address.
Address::Familyfamily constReturns the address family of the host's address.
boolvalid constReturns true when the port is set and the address is valid ie. not wildcard.
booloperator< constCompares two addresses for ordering (by family then port).
booloperator== constReturns true if the host and port of both addresses are equal.
booloperator!= constReturns true if the host or port of the addresses differ.

{#address-1}

Address

Address()

Creates a wildcard (all zero) IPv4 Address.


{#address-2}

Address

Address(const std::string & host, uint16_t port)

Creates an Address from an IP address and a port number.

The IP address must either be a domain name, or it must be in dotted decimal (IPv4) or hex string (IPv6) format.


{#address-3}

Address

Address(const Address & addr)

Creates an Address by copying another one.


{#address-4}

Address

Address(const struct sockaddr * addr, socklen_t length)

Creates an Address from a native socket address.


{#address-5}

Address

Address(const std::string & host, const std::string & port)

Creates an Address from an IP address and a service name or port number.

The IP address must either be a domain name, or it must be in dotted decimal (IPv4) or hex string (IPv6) format.

The given port must either be a decimal port number, or a service name.


{#address-6}

Address

explicit

explicit Address(const std::string & hostAndPort)

Creates an Address from an IP address or host name and a port number/service name. Host name/address and port number must be separated by a colon. In case of an IPv6 address, the address part must be enclosed in brackets.

Examples: 192.168.1.10:80

0state.com:8080


{#address-7}

~Address

~Address() noexcept

Destroys the Address.


{#operator-4}

operator=

Address & operator=(const Address & addr)

Assigns another Address.


{#swap}

swap

void swap(Address & addr)

Swaps the Address with another one.


{#host}

host

const

std::string host() const

Returns the host IP address.


{#port}

port

const

uint16_t port() const

Returns the port number.


{#length}

length

const

socklen_t length() const

Returns the length of the internal native socket address.


{#addr-1}

addr

const

const struct sockaddr * addr() const

Returns a pointer to the internal native socket address.


{#af}

af

const

int af() const

Returns the address family (AF_INET or AF_INET6) of the address.


{#tostring-4}

toString

const

std::string toString() const

Returns a string representation of the address.


{#family}

family

const

Address::Family family() const

Returns the address family of the host's address.


{#valid}

valid

const

bool valid() const

Returns true when the port is set and the address is valid ie. not wildcard.


{#operator-5}

operator<

const

bool operator<(const Address & addr) const

Compares two addresses for ordering (by family then port).

Parameters

  • addr The address to compare against.

Returns

true if this address is less than addr.


{#operator-6}

operator==

const

bool operator==(const Address & addr) const

Returns true if the host and port of both addresses are equal.

Parameters

  • addr The address to compare against.

{#operator-7}

operator!=

const

bool operator!=(const Address & addr) const

Returns true if the host or port of the addresses differ.

Parameters

  • addr The address to compare against.

Public Static Methods

ReturnNameDescription
uint16_tresolveService staticResolves a service name or decimal port string to a port number.
boolvalidateIP staticReturns true if the given string is a valid IPv4 or IPv6 address.

{#resolveservice}

resolveService

static

static uint16_t resolveService(const std::string & service)

Resolves a service name or decimal port string to a port number.

Parameters

  • service Service name (e.g. "http") or decimal port string (e.g. "80").

Returns

The resolved port number in host byte order.


{#validateip}

validateIP

static

static bool validateIP(std::string_view address)

Returns true if the given string is a valid IPv4 or IPv6 address.

Parameters

  • address The string to validate.

Returns

true if the address parses as a valid IP address, false otherwise.

Protected Methods

ReturnNameDescription
voidinit

{#init-3}

init

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

Public Types

NameDescription
FamilyPossible address families for IP addresses.

{#family-1}

Family

enum Family

Possible address families for IP addresses.

ValueDescription
IPv4
IPv6

Private Attributes

ReturnNameDescription
std::shared_ptr< AddressBase >_base

{#_base}

_base

std::shared_ptr< AddressBase > _base

{#packetsocketemitter}

PacketSocketEmitter

#include <icy/net/packetsocket.h>

Inherits: SocketEmitter, Signal< void(IPacket &)> Subclassed by: Transaction< Message >, Transaction< PacketT >

Socket adapter that emits received data as packets.

Public Attributes

ReturnNameDescription
PacketFactoryfactoryThe packet factory.

{#factory}

factory

PacketFactory factory

The packet factory.

Public Methods

ReturnNameDescription
PacketSocketEmitterCreates the PacketSocketEmitter and attaches it to the given socket.
boolonSocketRecv virtualParses raw received data into packets via the factory and forwards each parsed packet to onPacket(). Returns true if propagation should stop.
boolonPacket virtualProcess a parsed packet. Returns true to stop propagation.

{#packetsocketemitter-1}

PacketSocketEmitter

PacketSocketEmitter(const Socket::Ptr & socket)

Creates the PacketSocketEmitter and attaches it to the given socket.

The emitter should be assigned a higher priority than plain socket adapters so that packet parsing occurs before generic data callbacks. Packets are created and dispatched using the registered factory strategies; strategies with the highest priority are tried first.

Parameters

  • socket Optional socket to attach to immediately.

{#onsocketrecv}

onSocketRecv

virtual

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

Parses raw received data into packets via the factory and forwards each parsed packet to onPacket(). Returns true if propagation should stop.

Parameters

  • socket The socket that received the data.

  • buffer The raw received data buffer.

  • peerAddress The sender's address.

Returns

true if the event was consumed and should not propagate further.


{#onpacket}

onPacket

virtual

virtual bool onPacket(IPacket & pkt)

Process a parsed packet. Returns true to stop propagation.

{#socket-1}

Socket

#include <icy/net/socket.h>

Inherits: SocketAdapter Subclassed by: TCPSocket, UDPSocket

Base socket implementation from which all sockets derive.

Public Attributes

ReturnNameDescription
std::anyopaqueOptional client data.

{#opaque}

opaque

std::any opaque

Optional client data.

The value is empty on initialization.

Public Methods

ReturnNameDescription
SocketDefaulted constructor.
SocketDeleted constructor.
SocketDeleted constructor.
voidconnectConnects to the given peer IP address.
voidconnectResolves and connects to the given host address.
voidbindBind a local address to the socket. The address may be IPv4 or IPv6 (if supported).
voidlisten virtual inlineListens the socket on the given address.
boolshutdown virtual inlineSends the shutdown packet which should result is socket closure via callback.
ssize_tsendOwnedSends an owned payload buffer to the connected peer.
ssize_tsendOwned
voidcloseCloses the underlying socket.
Addressaddress constThe locally bound address.
AddresspeerAddress constThe connected peer address.
net::TransportTypetransport constThe transport protocol: TCP, UDP or SSLTCP.
voidsetErrorSets the socket error.
const icy::Error &error constReturn the socket error if any.
boolclosed constReturns true if the native socket handle is closed.
uv::Loop *loop constReturns the socket event loop.

{#socket-2}

Socket

Socket() = default

Defaulted constructor.


{#socket-3}

Socket

Socket(const Socket &) = delete

Deleted constructor.


{#socket-4}

Socket

Socket(Socket &&) = delete

Deleted constructor.


{#connect-2}

connect

void connect(const Address & address)

Connects to the given peer IP address.

Throws an exception if the address is malformed. Connection errors can be handled via the Error signal.


{#connect-3}

connect

void connect(std::string_view host, uint16_t port)

Resolves and connects to the given host address.

Throws an Exception if the host is malformed. Since the DNS callback is asynchronous implementations need to listen for the Error signal for handling connection errors.


{#bind}

bind

void bind(const Address & address, unsigned flags)

Bind a local address to the socket. The address may be IPv4 or IPv6 (if supported).

Throws an Exception on error.


{#listen}

listen

virtual inline

virtual inline void listen(int backlog)

Listens the socket on the given address.

Throws an Exception on error.


{#shutdown-1}

shutdown

virtual inline

virtual inline bool shutdown()

Sends the shutdown packet which should result is socket closure via callback.


{#sendowned}

sendOwned

ssize_t sendOwned(Buffer && buffer, int flags)

Sends an owned payload buffer to the connected peer.


{#sendowned-1}

sendOwned

ssize_t sendOwned(Buffer && buffer, const Address & peerAddress, int flags)

{#close-12}

close

void close()

Closes the underlying socket.


{#address-8}

address

const

Address address() const

The locally bound address.

This function will not throw. A Wildcard 0.0.0.0:0 address is returned if the socket is closed or invalid.


{#peeraddress-1}

peerAddress

const

Address peerAddress() const

The connected peer address.

This function will not throw. A Wildcard 0.0.0.0:0 address is returned if the socket is closed or invalid.


{#transport}

transport

const

net::TransportType transport() const

The transport protocol: TCP, UDP or SSLTCP.


{#seterror-1}

setError

void setError(const icy::Error & err)

Sets the socket error.

Setting the error will result in socket closure.


{#error-5}

error

const

const icy::Error & error() const

Return the socket error if any.


{#closed-1}

closed

const

bool closed() const

Returns true if the native socket handle is closed.


{#loop-3}

loop

const

uv::Loop * loop() const

Returns the socket event loop.

Protected Attributes

ReturnNameDescription
int_af

{#_af}

_af

int _af {AF_UNSPEC}

Protected Methods

ReturnNameDescription
voidinitInitializes the underlying socket context.
voidresetResets the socket context for reuse.

{#init-4}

init

void init()

Initializes the underlying socket context.


{#reset-4}

reset

void reset()

Resets the socket context for reuse.

Public Types

NameDescription
Ptr
Vec

{#ptr-4}

Ptr

std::shared_ptr< Socket > Ptr()

{#vec}

Vec

std::vector< Ptr > Vec()

{#socketadapter}

SocketAdapter

#include <icy/net/socketadapter.h>

Subclassed by: Connection, ConnectionAdapter, ConnectionStream, Server, Socket, SocketEmitter

Abstract adapter interface for socket send/receive chains.

SocketAdapter is the abstract interface for all socket classes. A SocketAdapter can also be attached to a Socket in order to override default Socket callbacks and behaviour, while still maintaining the default Socket interface (see Socket::setAdapter).

This class can also be extended to implement custom processing for received socket data before it is dispatched to the application (see PacketSocketEmitter and Transaction classes).

Public Attributes

ReturnNameDescription
intpriorityThe priority of this adapter for STL sort operations.

{#priority-1}

priority

int priority = 0

The priority of this adapter for STL sort operations.

Public Methods

ReturnNameDescription
SocketAdapterCreates the SocketAdapter.
~SocketAdapter virtualDestroys the SocketAdapter.
ssize_tsend virtualSends the given data buffer to the connected peer. Returns the number of bytes sent or -1 on error. No exception will be thrown. For TCP sockets the given peer address must match the connected peer address.
ssize_tsend virtual
ssize_tsendOwned virtualSends an owned payload buffer to the connected peer.
ssize_tsendOwned virtual
ssize_tsendPacket virtualSends the given packet to the connected peer. Returns the number of bytes sent or -1 on error. No exception will be thrown. For TCP sockets the given peer address must match the connected peer address.
ssize_tsendPacket virtual
voidsendPacket virtualSends the given packet to the connected peer. This method provides delegate compatibility, and unlike other send methods throws an exception if the underlying socket is closed.
voidsetSender virtualSets the pointer to the outgoing data adapter. Send methods proxy data to this adapter by default.
SocketAdapter *senderReturns the output SocketAdapter pointer.
voidaddReceiver virtualSets the pointer to the incoming data adapter. Events proxy data to this adapter by default.
voidremoveReceiver virtualRemove the given receiver.
boolhasReceiver virtualReturns true if the given receiver is connected.
std::vector< SocketAdapter * >receiversReturns all currently registered input SocketAdapter pointers. Dead (removed) entries are excluded from the returned list.
boolonSocketConnect virtualCalled when the socket establishes a connection. Forwards the event to all registered receivers in priority order. Override to intercept before the application sees the event.
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.

{#socketadapter-1}

SocketAdapter

SocketAdapter(SocketAdapter * sender)

Creates the SocketAdapter.


{#socketadapter-2}

~SocketAdapter

virtual

virtual ~SocketAdapter() noexcept

Destroys the SocketAdapter.


{#send}

send

virtual

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

Sends the given data buffer to the connected peer. Returns the number of bytes sent or -1 on error. No exception will be thrown. For TCP sockets the given peer address must match the connected peer address.


{#send-1}

send

virtual

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

{#sendowned-2}

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-3}

sendOwned

virtual

virtual ssize_t sendOwned(Buffer && buffer, const Address & peerAddress, int flags)

{#sendpacket}

sendPacket

virtual

virtual ssize_t sendPacket(const IPacket & packet, int flags)

Sends the given packet to the connected peer. Returns the number of bytes sent or -1 on error. No exception will be thrown. For TCP sockets the given peer address must match the connected peer address.


{#sendpacket-1}

sendPacket

virtual

virtual ssize_t sendPacket(const IPacket & packet, const Address & peerAddress, int flags)

{#sendpacket-2}

sendPacket

virtual

virtual void sendPacket(IPacket & packet)

Sends the given packet to the connected peer. This method provides delegate compatibility, and unlike other send methods throws an exception if the underlying socket is closed.


{#setsender}

setSender

virtual

virtual void setSender(SocketAdapter * adapter)

Sets the pointer to the outgoing data adapter. Send methods proxy data to this adapter by default.


{#sender}

sender

SocketAdapter * sender()

Returns the output SocketAdapter pointer.


{#addreceiver}

addReceiver

virtual

virtual void addReceiver(SocketAdapter * adapter)

Sets the pointer to the incoming data adapter. Events proxy data to this adapter by default.


{#removereceiver}

removeReceiver

virtual

virtual void removeReceiver(SocketAdapter * adapter)

Remove the given receiver.

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


{#hasreceiver}

hasReceiver

virtual

virtual bool hasReceiver(SocketAdapter * adapter)

Returns true if the given receiver is connected.


{#receivers}

receivers

std::vector< SocketAdapter * > receivers()

Returns all currently registered input SocketAdapter pointers. Dead (removed) entries are excluded from the returned list.


{#onsocketconnect}

onSocketConnect

virtual

virtual bool onSocketConnect(Socket & socket)

Called when the socket establishes a connection. Forwards the event to all registered receivers in priority order. Override to intercept before the application sees the event.

Parameters

  • socket The connected socket.

Returns

true to stop propagation to subsequent receivers.


{#onsocketrecv-1}

onSocketRecv

virtual

virtual bool onSocketRecv(Socket & socket, const MutableBuffer & buffer, const 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}

onSocketError

virtual

virtual bool onSocketError(Socket & socket, const 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}

onSocketClose

virtual

virtual bool onSocketClose(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.

Protected Attributes

ReturnNameDescription
SocketAdapter *_sender
std::vector< Ref >_receivers
bool_dirty

{#_sender}

_sender

SocketAdapter * _sender

{#_receivers}

_receivers

std::vector< Ref > _receivers

{#_dirty}

_dirty

bool _dirty = false

Protected Methods

ReturnNameDescription
voidcleanupReceivers virtual

{#cleanupreceivers}

cleanupReceivers

virtual

virtual void cleanupReceivers()

{#ref-1}

Ref

#include <icy/net/socketadapter.h>

Reference-counted handle to a SocketAdapter.

Public Attributes

ReturnNameDescription
SocketAdapter *ptr
boolalive

{#ptr-5}

ptr

SocketAdapter * ptr

{#alive}

alive

bool alive

{#socketemitter}

SocketEmitter

#include <icy/net/socketemitter.h>

Inherits: SocketAdapter Subclassed by: WebSocketAdapter, PacketSocketEmitter

SocketAdapter that exposes socket events as signals.

Aside from adding a signal interface, the class wraps the underlying socket instance and is designed to be used much like a std::unique_ptr by overriding the -> operator.

Public Attributes

ReturnNameDescription
LocalSignal< bool(Socket &)>ConnectSignals that the socket is connected.
LocalSignal< bool(Socket &, const MutableBuffer &, const Address &)>RecvSignals when data is received by the socket.
LocalSignal< bool(Socket &, const icy::Error &)>ErrorSignals that the socket is closed in error. This signal will be sent just before the Closed signal.
LocalSignal< bool(Socket &)>CloseSignals that the underlying socket is closed.
Socket::PtrimplPointer to the underlying socket. Sent data will be proxied to this socket.

{#connect-4}

Connect

LocalSignal< bool(Socket &)> Connect

Signals that the socket is connected.


{#recv}

Recv

LocalSignal< bool(Socket &, const MutableBuffer &, const Address &)> Recv

Signals when data is received by the socket.


{#error-6}

Error

LocalSignal< bool(Socket &, const icy::Error &)> Error

Signals that the socket is closed in error. This signal will be sent just before the Closed signal.


{#close-13}

Close

LocalSignal< bool(Socket &)> Close

Signals that the underlying socket is closed.


{#impl}

impl

Socket::Ptr impl

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

Public Methods

ReturnNameDescription
SocketEmitterCreates the SocketEmitter and optionally attaches it to a socket. If socket is provided, this emitter registers itself as a receiver.
SocketEmitterCopy constructor; copies all signal connections and attaches to the same socket.
~SocketEmitter virtualDestroys the SocketAdapter.
voidaddReceiver virtualAttaches a SocketAdapter as a receiver; wires it to all four socket signals.
voidremoveReceiver virtualDetaches a SocketAdapter from all four socket signals.
voidswap virtualReplaces the underlying socket with socket.
T *as inlineReturns the underlying socket cast to type T, or nullptr if the cast fails.
Socket *operator-> const inlineReturns a raw pointer to the underlying socket for direct method access. Follows shared_ptr semantics; the caller must not delete the returned pointer.

{#socketemitter-1}

SocketEmitter

SocketEmitter(const Socket::Ptr & socket)

Creates the SocketEmitter and optionally attaches it to a socket. If socket is provided, this emitter registers itself as a receiver.

Parameters

  • socket Optional socket to attach to; pass nullptr to attach later via swap().

{#socketemitter-2}

SocketEmitter

SocketEmitter(const SocketEmitter & that)

Copy constructor; copies all signal connections and attaches to the same socket.

Parameters


{#socketemitter-3}

~SocketEmitter

virtual

virtual ~SocketEmitter() noexcept

Destroys the SocketAdapter.


{#addreceiver-1}

addReceiver

virtual

virtual void addReceiver(SocketAdapter * adapter)

Attaches a SocketAdapter as a receiver; wires it to all four socket signals.

Parameters

  • adapter The adapter to attach; its priority determines signal ordering.

{#removereceiver-1}

removeReceiver

virtual

virtual void removeReceiver(SocketAdapter * adapter)

Detaches a SocketAdapter from all four socket signals.

Parameters

  • adapter The adapter to detach.

{#swap-1}

swap

virtual

virtual void swap(const Socket::Ptr & socket)

Replaces the underlying socket with socket.

Throws std::logic_error if the emitter already has an attached socket.

Parameters

  • socket The new socket to attach.

{#as}

as

inline

template<class T> inline T * as()

Returns the underlying socket cast to type T, or nullptr if the cast fails.

Parameters

  • T Derived socket type to cast to.

Returns

Pointer to the socket as T, or nullptr on type mismatch.


{#operator-8}

operator->

const inline

inline Socket * operator->() const

Returns a raw pointer to the underlying socket for direct method access. Follows shared_ptr semantics; the caller must not delete the returned pointer.

Returns

Raw pointer to the socket (never null if a socket was attached).

Protected Methods

ReturnNameDescription
boolonSocketConnect virtualForwards the connect event to chained adapters, then fires the Connect signal.
boolonSocketRecv virtualForwards the recv event to chained adapters, then fires the Recv signal.
boolonSocketError virtualForwards the error event to chained adapters, then fires the Error signal.
boolonSocketClose virtualForwards the close event to chained adapters, then fires the Close signal.

{#onsocketconnect-1}

onSocketConnect

virtual

virtual bool onSocketConnect(Socket & socket)

Forwards the connect event to chained adapters, then fires the Connect signal.


{#onsocketrecv-2}

onSocketRecv

virtual

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

Forwards the recv event to chained adapters, then fires the Recv signal.


{#onsocketerror-1}

onSocketError

virtual

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

Forwards the error event to chained adapters, then fires the Error signal.


{#onsocketclose-1}

onSocketClose

virtual

virtual bool onSocketClose(Socket & socket)

Forwards the close event to chained adapters, then fires the Close signal.

{#socketpacket}

SocketPacket

#include <icy/net/socket.h>

Inherits: RawPacket

Default packet type emitted by sockets.

SocketPacket carries the remote peer address plus a borrowed view of the received byte buffer for zero-copy processing inside the receive callback.

The referenced packet buffer lifetime is only guaranteed for the duration of the receiver callback.

Public Methods

ReturnNameDescription
SocketPacket inlineConstructs a SocketPacket wrapping the received buffer.
SocketPacket inlineCopy constructor; shares the underlying buffer reference.
PacketInfo *packetInfo const inlineReturns the PacketInfo for this socket packet.
voidprint virtual const inlinePrints a one-line description of the packet to os.
std::unique_ptr< IPacket >clone virtual const inlineReturns a heap-allocated copy of this SocketPacket.
ssize_tread virtual inlineNot supported; always throws std::logic_error.
voidwrite virtual const inlineAppends the packet payload to buf.
const char *className virtual const inline#### Returns

{#socketpacket-1}

SocketPacket

inline

inline SocketPacket(const Socket::Ptr & socket, const MutableBuffer & buffer, const Address & peerAddress)

Constructs a SocketPacket wrapping the received buffer.

The buffer data pointer remains valid only for the duration of the enclosing receive callback; do not retain references beyond that scope.

Parameters

  • socket Shared pointer to the receiving socket.

  • buffer View of the raw received bytes.

  • peerAddress Address of the remote sender.


{#socketpacket-2}

SocketPacket

inline

inline SocketPacket(const SocketPacket & that)

Copy constructor; shares the underlying buffer reference.

Parameters


{#packetinfo-3}

packetInfo

const inline

inline PacketInfo * packetInfo() const

Returns the PacketInfo for this socket packet.

Returns

Pointer to the associated PacketInfo (never null for a valid packet).


{#print-6}

print

virtual const inline

virtual inline void print(std::ostream & os) const

Prints a one-line description of the packet to os.

Parameters

  • os Output stream to write to.

{#clone-6}

clone

virtual const inline

virtual inline std::unique_ptr< IPacket > clone() const

Returns a heap-allocated copy of this SocketPacket.


{#read-1}

read

virtual inline

virtual inline ssize_t read(const ConstBuffer &)

Not supported; always throws std::logic_error.


{#write-1}

write

virtual const inline

virtual inline void write(Buffer & buf) const

Appends the packet payload to buf.

Parameters

  • buf Destination buffer to append raw bytes to.

{#classname-5}

className

virtual const inline

virtual inline const char * className() const

Returns

The string "SocketPacket".

{#ssladapter}

SSLAdapter

#include <icy/net/ssladapter.h>

Manages the OpenSSL context and BIO buffers for an SSL socket connection.

Public Methods

ReturnNameDescription
SSLAdapterConstructs the SSLAdapter and associates it with the given socket. The socket pointer must remain valid for the lifetime of this adapter.
SSLAdapterDeleted constructor.
SSLAdapterDeleted constructor.
voidinitClientInitializes the SSL context as a client.
voidinitServerInitializes the SSL context as a server.
boolinitialized constReturns true when SSL context has been initialized.
boolready constReturns true when the handshake is complete.
voidhandshakeStart/continue the SSL handshake process.
intavailable constReturns the number of bytes available in the SSL buffer for immediate reading.
voidshutdownIssues an orderly SSL shutdown.
voidflushFlushes the SSL read/write buffers.
voidsetHostnameSet the expected peer hostname for certificate verification. Must be called before initClient() to enable hostname verification.
voidaddIncomingDataFeeds encrypted data received from the network into the SSL read BIO. Triggers a flush, which drives the handshake or decrypts and delivers plaintext to the socket via onRecv().
voidaddOutgoingDataQueues plaintext data for encryption and transmission.
voidaddOutgoingDataQueues plaintext data for encryption and transmission.
voidaddOutgoingDataMoves plaintext data into the pending write buffer when possible.

{#ssladapter-1}

SSLAdapter

SSLAdapter(net::SSLSocket * socket)

Constructs the SSLAdapter and associates it with the given socket. The socket pointer must remain valid for the lifetime of this adapter.

Parameters

  • socket The owning SSLSocket that sends and receives raw data.

{#ssladapter-2}

SSLAdapter

SSLAdapter(const SSLAdapter &) = delete

Deleted constructor.


{#ssladapter-3}

SSLAdapter

SSLAdapter(SSLAdapter &&) = delete

Deleted constructor.


{#initclient}

initClient

void initClient()

Initializes the SSL context as a client.


{#initserver}

initServer

void initServer()

Initializes the SSL context as a server.


{#initialized-2}

initialized

const

bool initialized() const

Returns true when SSL context has been initialized.


{#ready}

ready

const

bool ready() const

Returns true when the handshake is complete.


{#handshake}

handshake

void handshake()

Start/continue the SSL handshake process.


{#available-1}

available

const

int available() const

Returns the number of bytes available in the SSL buffer for immediate reading.


{#shutdown-2}

shutdown

void shutdown()

Issues an orderly SSL shutdown.


{#flush-8}

flush

void flush()

Flushes the SSL read/write buffers.


{#sethostname}

setHostname

void setHostname(std::string_view hostname)

Set the expected peer hostname for certificate verification. Must be called before initClient() to enable hostname verification.


{#addincomingdata}

addIncomingData

void addIncomingData(const char * data, size_t len)

Feeds encrypted data received from the network into the SSL read BIO. Triggers a flush, which drives the handshake or decrypts and delivers plaintext to the socket via onRecv().

Parameters

  • data Pointer to the encrypted bytes.

  • len Number of bytes to feed.


{#addoutgoingdata}

addOutgoingData

void addOutgoingData(std::string_view data)

Queues plaintext data for encryption and transmission.

Parameters

  • data String view of the plaintext payload.

{#addoutgoingdata-1}

addOutgoingData

void addOutgoingData(const char * data, size_t len)

Queues plaintext data for encryption and transmission.

Parameters

  • data Pointer to the plaintext bytes.

  • len Number of bytes to queue.


{#addoutgoingdata-2}

addOutgoingData

void addOutgoingData(Buffer && data)

Moves plaintext data into the pending write buffer when possible.

Protected Attributes

ReturnNameDescription
net::SSLSocket *_socket
SSL *_ssl
BIO *_readBIOThe incoming buffer we write encrypted SSL data into.
BIO *_writeBIOThe outgoing buffer we write to the socket.
std::vector< char >_bufferOutThe outgoing payload to be encrypted and sent.
std::string_hostnameExpected peer hostname for verification.

{#_socket}

_socket

net::SSLSocket * _socket

{#_ssl}

_ssl

SSL * _ssl

{#_readbio}

_readBIO

BIO * _readBIO

The incoming buffer we write encrypted SSL data into.


{#_writebio}

_writeBIO

BIO * _writeBIO

The outgoing buffer we write to the socket.


{#_bufferout}

_bufferOut

std::vector< char > _bufferOut

The outgoing payload to be encrypted and sent.


{#_hostname}

_hostname

std::string _hostname

Expected peer hostname for verification.

Protected Methods

ReturnNameDescription
voidhandleError
voidflushReadBIO
voidflushWriteBIO

{#handleerror}

handleError

void handleError(int rc)

{#flushreadbio}

flushReadBIO

void flushReadBIO()

{#flushwritebio}

flushWriteBIO

void flushWriteBIO()

{#sslcontext}

SSLContext

#include <icy/net/sslcontext.h>

OpenSSL SSL_CTX wrapper for client and server TLS configuration.

This class encapsulates context information for an SSL server or client, such as the certificate verification mode and the location of certificates and private key files, as well as the list of supported ciphers.

The Context class is also used to control SSL session caching on the server and client side.

Public Methods

ReturnNameDescription
SSLContextCreates a Context.
SSLContextCreates a Context.
~SSLContextDestroys the Context.
voiduseCertificateSets the certificate to be used by the Context.
voidaddChainCertificateAdds a certificate for certificate chain validation.
voidaddVerificationCertificateSets the private key to be used by the Context.
SSL_CTX *sslContext const inlineReturns the underlying OpenSSL SSL Context object.
Usageusage const inlineReturns whether the context is for use by a client or by a server and whether TLSv1 is required.
boolisForServerUse const inlineReturns true if the context is for use by a server.
SSLContext::VerificationModeverificationMode const inlineReturns the verification mode.
voidenableSessionCacheEnable or disable SSL/TLS session caching. For session caching to work, it must be enabled on the server, as well as on the client side.
voidenableSessionCacheEnables or disables SSL/TLS session caching on the server. For session caching to work, it must be enabled on the server, as well as on the client side.
boolsessionCacheEnabled constReturns true if the session cache is enabled.
voidsetSessionCacheSizeSets the maximum size of the server session cache, in number of sessions. The default size (according to OpenSSL documentation) is 1024*20, which may be too large for many applications, especially on embedded platforms with limited memory.
size_tgetSessionCacheSize constReturns the current maximum size of the server session cache.
voidsetSessionTimeoutSets the timeout (in seconds) of cached sessions on the server. A cached session will be removed from the cache if it has not been used for the given number of seconds.
longgetSessionTimeout constReturns the timeout (in seconds) of cached sessions on the server.
voidflushSessionCacheFlushes the SSL session cache on the server.
voiddisableStatelessSessionResumptionNewer versions of OpenSSL support RFC 4507 tickets for stateless session resumption.
voidsetALPNProtocolsSet the ALPN protocols for negotiation. Protocols should be in preference order. Example: {"h2", "http/1.1"}
SSLContextDeleted constructor.
SSLContextDeleted constructor.

{#sslcontext-1}

SSLContext

SSLContext(Usage usage, const std::string & privateKeyFile, const std::string & certificateFile, const std::string & caLocation, VerificationMode verificationMode, int verificationDepth, bool loadDefaultCAs, const std::string & cipherList)

Creates a Context.

  • usage specifies whether the context is used by a client or server.

  • privateKeyFile contains the path to the private key file used for encryption. Can be empty if no private key file is used.

  • certificateFile contains the path to the certificate file (in PEM format). If the private key and the certificate are stored in the same file, this can be empty if privateKeyFile is given.

  • caLocation contains the path to the file or directory containing the CA/root certificates. Can be empty if the OpenSSL builtin CA certificates are used (see loadDefaultCAs).

  • verificationMode specifies whether and how peer certificates are validated.

  • verificationDepth sets the upper limit for verification chain sizes. Verification will fail if a certificate chain larger than this is encountered.

  • loadDefaultCAs specifies whether the builtin CA certificates from OpenSSL are used.

  • cipherList specifies the supported ciphers in OpenSSL notation.

Note: If the private key is protected by a passphrase, a PrivateKeyPassphraseHandler must have been setup with the SSLManager, or the SSLManager's PrivateKeyPassphraseRequired event must be handled.


{#sslcontext-2}

SSLContext

SSLContext(Usage usage, const std::string & caLocation, VerificationMode verificationMode, int verificationDepth, bool loadDefaultCAs, const std::string & cipherList)

Creates a Context.

  • usage specifies whether the context is used by a client or server.

  • caLocation contains the path to the file or directory containing the CA/root certificates. Can be empty if the OpenSSL builtin CA certificates are used (see loadDefaultCAs).

  • verificationMode specifies whether and how peer certificates are validated.

  • verificationDepth sets the upper limit for verification chain sizes. Verification will fail if a certificate chain larger than this is encountered.

  • loadDefaultCAs specifies whether the builtin CA certificates from OpenSSL are used.

  • cipherList specifies the supported ciphers in OpenSSL notation.

Note that a private key and/or certificate must be specified with usePrivateKey()/useCertificate() before the Context can be used.


{#sslcontext-3}

~SSLContext

~SSLContext() noexcept

Destroys the Context.


{#usecertificate}

useCertificate

void useCertificate(crypto::X509Certificate & certificate)

Sets the certificate to be used by the Context.

To set-up a complete certificate chain, it might be necessary to call addChainCertificate() to specify additional certificates.

Note that useCertificate() must always be called before usePrivateKey().


{#addchaincertificate}

addChainCertificate

void addChainCertificate(crypto::X509Certificate & certificate)

Adds a certificate for certificate chain validation.


{#addverificationcertificate}

addVerificationCertificate

void addVerificationCertificate(crypto::X509Certificate & certificate)

Sets the private key to be used by the Context.

Note that useCertificate() must always be called before usePrivateKey().

Note: If the private key is protected by a passphrase, a PrivateKeyPassphraseHandler must have been setup with the SSLManager, or the SSLManager's PrivateKeyPassphraseRequired event must be handled. Adds the given certificate to the list of trusted certificates that will be used for verification.


{#sslcontext-4}

sslContext

const inline

inline SSL_CTX * sslContext() const

Returns the underlying OpenSSL SSL Context object.


{#usage}

usage

const inline

inline Usage usage() const

Returns whether the context is for use by a client or by a server and whether TLSv1 is required.


{#isforserveruse}

isForServerUse

const inline

inline bool isForServerUse() const

Returns true if the context is for use by a server.


{#verificationmode}

verificationMode

const inline

inline SSLContext::VerificationMode verificationMode() const

Returns the verification mode.


{#enablesessioncache}

enableSessionCache

void enableSessionCache(bool flag)

Enable or disable SSL/TLS session caching. For session caching to work, it must be enabled on the server, as well as on the client side.

The default is disabled session caching.

To enable session caching on the server side, use the two-argument version of this method to specify a session ID context.


{#enablesessioncache-1}

enableSessionCache

void enableSessionCache(bool flag, std::string_view sessionIdContext)

Enables or disables SSL/TLS session caching on the server. For session caching to work, it must be enabled on the server, as well as on the client side.

SessionIdContext contains the application's unique session ID context, which becomes part of each session identifier generated by the server within this context. SessionIdContext can be an arbitrary sequence of bytes with a maximum length of SSL_MAX_SSL_SESSION_ID_LENGTH.

A non-empty sessionIdContext should be specified even if session caching is disabled to avoid problems with clients requesting to reuse a session (e.g. Firefox 3.6).

This method may only be called on SERVER_USE Context objects.


{#sessioncacheenabled}

sessionCacheEnabled

const

bool sessionCacheEnabled() const

Returns true if the session cache is enabled.


{#setsessioncachesize}

setSessionCacheSize

void setSessionCacheSize(size_t size)

Sets the maximum size of the server session cache, in number of sessions. The default size (according to OpenSSL documentation) is 1024*20, which may be too large for many applications, especially on embedded platforms with limited memory.

Specifying a size of 0 will set an unlimited cache size.

This method may only be called on SERVER_USE Context objects.


{#getsessioncachesize}

getSessionCacheSize

const

size_t getSessionCacheSize() const

Returns the current maximum size of the server session cache.

This method may only be called on SERVER_USE Context objects.


{#setsessiontimeout}

setSessionTimeout

void setSessionTimeout(long seconds)

Sets the timeout (in seconds) of cached sessions on the server. A cached session will be removed from the cache if it has not been used for the given number of seconds.

This method may only be called on SERVER_USE Context objects.


{#getsessiontimeout}

getSessionTimeout

const

long getSessionTimeout() const

Returns the timeout (in seconds) of cached sessions on the server.

This method may only be called on SERVER_USE Context objects.


{#flushsessioncache}

flushSessionCache

void flushSessionCache()

Flushes the SSL session cache on the server.

This method may only be called on SERVER_USE Context objects.


{#disablestatelesssessionresumption}

disableStatelessSessionResumption

void disableStatelessSessionResumption()

Newer versions of OpenSSL support RFC 4507 tickets for stateless session resumption.

The feature can be disabled by calling this method.


{#setalpnprotocols}

setALPNProtocols

void setALPNProtocols(const std::vector< std::string > & protocols)

Set the ALPN protocols for negotiation. Protocols should be in preference order. Example: {"h2", "http/1.1"}


{#sslcontext-5}

SSLContext

SSLContext(const SSLContext &) = delete

Deleted constructor.


{#sslcontext-6}

SSLContext

SSLContext(SSLContext &&) = delete

Deleted constructor.

Public Static Methods

ReturnNameDescription
voidenableSNI staticEnable SNI (Server Name Indication) for a specific SSL connection. The hostname is sent during the TLS handshake to allow the server to select the appropriate certificate.

{#enablesni}

enableSNI

static

static void enableSNI(SSL * ssl, const std::string & hostname)

Enable SNI (Server Name Indication) for a specific SSL connection. The hostname is sent during the TLS handshake to allow the server to select the appropriate certificate.

Public Types

NameDescription
Usage
VerificationMode
Ptr

{#usage-1}

Usage

enum Usage
ValueDescription
CLIENT_USEContext is used by a client.
SERVER_USEContext is used by a server.
TLSV1_CLIENT_USEContext is used by a client requiring TLSv1.
TLSV1_SERVER_USEContext is used by a server requiring TLSv2.

{#verificationmode-1}

VerificationMode

enum VerificationMode
ValueDescription
VERIFY_NONEServer: The server will not send a client certificate request to the client, so the client will not send a certificate.
VERIFY_RELAXEDServer: The server sends a client certificate request to the client. The certificate returned (if any) is checked. If the verification process fails, the TLS/SSL handshake is immediately terminated with an alert message containing the reason for the verification failure.
VERIFY_STRICTServer: If the client did not return a certificate, the TLS/SSL handshake is immediately terminated with a handshake failure alert.
VERIFY_ONCEServer: Only request a client certificate on the initial TLS/SSL handshake. Do not ask for a client certificate again in case of a renegotiation.

{#ptr-6}

Ptr

std::shared_ptr< SSLContext > Ptr()

Private Attributes

ReturnNameDescription
Usage_usage
VerificationMode_mode
SSL_CTX *_sslContext
std::vector< unsigned char >_alpnWireWire-format ALPN protocols for server selection.

{#_usage}

_usage

Usage _usage

{#_mode}

_mode

VerificationMode _mode

{#_sslcontext}

_sslContext

SSL_CTX * _sslContext

{#_alpnwire}

_alpnWire

std::vector< unsigned char > _alpnWire

Wire-format ALPN protocols for server selection.

Private Methods

ReturnNameDescription
voidcreateSSLContextCreate a SSL_CTX object according to Context configuration.

{#createsslcontext}

createSSLContext

void createSSLContext()

Create a SSL_CTX object according to Context configuration.

{#sslmanager}

SSLManager

#include <icy/net/sslmanager.h>

Singleton that owns the default client/server TLS contexts and related callbacks.

Public Attributes

ReturnNameDescription
ThreadSignal< void(VerificationErrorDetails &)>ServerVerificationErrorFired whenever a certificate verification error is detected by the server during a handshake.
ThreadSignal< void(VerificationErrorDetails &)>ClientVerificationErrorFired whenever a certificate verification error is detected by the client during a handshake.
ThreadSignal< void(std::string &)>PrivateKeyPassphraseRequiredFired when an encrypted certificate or private key is loaded. Not setting the password in the event parameter will result in a failure to load the certificate.

{#serververificationerror}

ServerVerificationError

ThreadSignal< void(VerificationErrorDetails &)> ServerVerificationError

Fired whenever a certificate verification error is detected by the server during a handshake.


{#clientverificationerror}

ClientVerificationError

ThreadSignal< void(VerificationErrorDetails &)> ClientVerificationError

Fired whenever a certificate verification error is detected by the client during a handshake.


{#privatekeypassphraserequired}

PrivateKeyPassphraseRequired

ThreadSignal< void(std::string &)> PrivateKeyPassphraseRequired

Fired when an encrypted certificate or private key is loaded. Not setting the password in the event parameter will result in a failure to load the certificate.

Public Methods

ReturnNameDescription
voidinitializeServerInitializes the server side of the SSLManager server-side SSLContext.
voidinitializeClientInitializes the client side of the SSLManager with a default client-side SSLContext.
SSLContext::PtrdefaultServerContextReturns the default context used by the server if initialized.
SSLContext::PtrdefaultClientContextReturns the default context used by the client if initialized.
voidshutdownShuts down the SSLManager and releases the default context objects. After a call to shutdown(), the SSLManager can no longer be used.

{#initializeserver}

initializeServer

void initializeServer(SSLContext::Ptr ptrContext)

Initializes the server side of the SSLManager server-side SSLContext.


{#initializeclient}

initializeClient

void initializeClient(SSLContext::Ptr ptrContext)

Initializes the client side of the SSLManager with a default client-side SSLContext.


{#defaultservercontext}

defaultServerContext

SSLContext::Ptr defaultServerContext()

Returns the default context used by the server if initialized.


{#defaultclientcontext}

defaultClientContext

SSLContext::Ptr defaultClientContext()

Returns the default context used by the client if initialized.


{#shutdown-3}

shutdown

void shutdown()

Shuts down the SSLManager and releases the default context objects. After a call to shutdown(), the SSLManager can no longer be used.

Normally, it's not necessary to call this method directly, as this will be called either by uninitializeSSL(), or when the SSLManager instance is destroyed.

Public Static Methods

ReturnNameDescription
SSLManager &instance staticReturns the instance of the SSLManager singleton.
voiddestroy staticShuts down and destroys the SSLManager singleton instance.
voidinitNoVerifyClient staticInitializes a default no-verify client context that's useful for testing.
voidinitNoVerifyServer staticInitializes a default no-verify server context that's useful for testing. Optionally accepts private key and certificate file paths for server identity; if omitted, no certificate is loaded.

{#instance-2}

instance

static

static SSLManager & instance()

Returns the instance of the SSLManager singleton.


{#destroy}

destroy

static

static void destroy()

Shuts down and destroys the SSLManager singleton instance.


{#initnoverifyclient}

initNoVerifyClient

static

static void initNoVerifyClient()

Initializes a default no-verify client context that's useful for testing.


{#initnoverifyserver}

initNoVerifyServer

static

static void initNoVerifyServer(const std::string & privateKeyFile, const std::string & certificateFile)

Initializes a default no-verify server context that's useful for testing. Optionally accepts private key and certificate file paths for server identity; if omitted, no certificate is loaded.

Private Attributes

ReturnNameDescription
SSLContext::Ptr_defaultServerContext
SSLContext::Ptr_defaultClientContext
std::mutex_mutex

{#_defaultservercontext}

_defaultServerContext

SSLContext::Ptr _defaultServerContext

{#_defaultclientcontext}

_defaultClientContext

SSLContext::Ptr _defaultClientContext

{#_mutex-6}

_mutex

std::mutex _mutex

Private Methods

ReturnNameDescription
SSLManagerCreates the SSLManager.
~SSLManagerDestroys the SSLManager.
SSLManagerDeleted constructor.
SSLManagerDeleted constructor.

{#sslmanager-1}

SSLManager

SSLManager()

Creates the SSLManager.


{#sslmanager-2}

~SSLManager

~SSLManager() noexcept

Destroys the SSLManager.


{#sslmanager-3}

SSLManager

SSLManager(const SSLManager &) = delete

Deleted constructor.


{#sslmanager-4}

SSLManager

SSLManager(SSLManager &&) = delete

Deleted constructor.

Private Static Methods

ReturnNameDescription
intverifyCallback staticThe return value of this method defines how errors in verification are handled. Return 0 to terminate the handshake, or 1 to continue despite the error.

{#verifycallback}

verifyCallback

static

static int verifyCallback(bool server, int ok, X509_STORE_CTX * pStore)

The return value of this method defines how errors in verification are handled. Return 0 to terminate the handshake, or 1 to continue despite the error.

{#sslsession}

SSLSession

#include <icy/net/sslsession.h>

Cached SSL/TLS session wrapper used for client-side resumption.

For session caching to work, a client must save the session object from an existing connection, if it wants to reuse it with a future connection.

Public Methods

ReturnNameDescription
SSL_SESSION *sslSession constReturns the stored OpenSSL SSL_SESSION object.
SSLSessionCreates a new SSLSession wrapping the given OpenSSL session object.
~SSLSessionDestroys the Session.
SSLSessionConstructs an empty SSLSession with a null session pointer.
SSLSessionDeleted constructor.
SSLSessionDeleted constructor.

{#sslsession-1}

sslSession

const

SSL_SESSION * sslSession() const

Returns the stored OpenSSL SSL_SESSION object.


{#sslsession-2}

SSLSession

SSLSession(SSL_SESSION * ptr)

Creates a new SSLSession wrapping the given OpenSSL session object.

The SSL_SESSION's reference count is not incremented; the SSLSession takes ownership and will call SSL_SESSION_free() on destruction.

Parameters

  • ptr The OpenSSL session object to wrap.

{#sslsession-3}

~SSLSession

~SSLSession() noexcept

Destroys the Session.

Calls SSL_SESSION_free() on the stored SSL_SESSION object.


{#sslsession-4}

SSLSession

SSLSession()

Constructs an empty SSLSession with a null session pointer.


{#sslsession-5}

SSLSession

SSLSession(const SSLSession &) = delete

Deleted constructor.


{#sslsession-6}

SSLSession

SSLSession(SSLSession &&) = delete

Deleted constructor.

Protected Attributes

ReturnNameDescription
SSL_SESSION *_ptr

{#_ptr}

_ptr

SSL_SESSION * _ptr

Public Types

NameDescription
Ptr

{#ptr-7}

Ptr

std::shared_ptr< SSLSession > Ptr()

{#sslsocket}

SSLSocket

#include <icy/net/sslsocket.h>

Inherits: TCPSocket

SSL socket implementation.

Public Methods

ReturnNameDescription
SSLSocketConstructs an SSLSocket that acquires its context from SSLManager on first use.
SSLSocketConstructs an SSLSocket with an explicit SSL context.
SSLSocketConstructs an SSLSocket with an explicit context and a prior session for resumption.
voidconnect virtualInitialize the SSLSocket with the given SSLContext.
voidconnect virtualResolves host and initiates a secure connection.
voidbind virtualBinds the socket to address for server-side use. Throws std::logic_error if the context is not a server context.
voidlisten virtualStarts listening for incoming connections. Throws std::logic_error if the context is not a server context.
boolshutdown virtualShuts down the connection by attempting an orderly SSL shutdown, then actually shutting down the TCP connection.
voidclose virtualCloses the socket forcefully.
ssize_tsend virtualEncrypts and sends len bytes to the connected peer.
ssize_tsendOwned virtualSends an owned payload buffer to the connected peer.
ssize_tsend virtualEncrypts and sends len bytes, ignoring peerAddress (TCP is connected).
ssize_tsendOwned virtual
voidsetHostnameSet the expected peer hostname for certificate verification and SNI. Must be called before connect() to enable hostname verification.
voiduseContextUse the given SSL context for this socket.
SSLContext::Ptrcontext constReturns the SSL context used for this socket.
voiduseSessionSets the SSL session to use for the next connection. Setting a previously saved Session object is necessary to enable session caching.
SSLSession::PtrcurrentSessionReturns the SSL session of the current connection, for reuse in a future connection (if session caching is enabled).
boolsessionWasReusedReturns true if a reused session was negotiated during the handshake.
intavailable constReturns the number of bytes available from the SSL buffer for immediate reading.
X509 *peerCertificate constReturns the peer's X.509 certificate, or nullptr if no certificate was presented.
net::TransportTypetransport virtual constReturns the SSLTCP transport protocol identifier.
voidacceptConnection virtualAccepts a pending client connection, initializes the server-side SSL context on the new socket, and fires the AcceptConnection signal.
voidonConnect virtualCalled when the TCP connection is established; starts reading and initiates the client-side SSL handshake.
voidonRead virtualFeeds raw encrypted bytes from the network into the SSL adapter. Called by the stream layer when ciphertext arrives from the peer.

{#sslsocket-1}

SSLSocket

SSLSocket(uv::Loop * loop)

Constructs an SSLSocket that acquires its context from SSLManager on first use.

Parameters

  • loop Event loop to use; defaults to the default loop.

{#sslsocket-2}

SSLSocket

SSLSocket(SSLContext::Ptr sslContext, uv::Loop * loop)

Constructs an SSLSocket with an explicit SSL context.

Parameters

  • sslContext The SSL context to use for this connection.

  • loop Event loop to use; defaults to the default loop.


{#sslsocket-3}

SSLSocket

SSLSocket(SSLContext::Ptr sslContext, SSLSession::Ptr session, uv::Loop * loop)

Constructs an SSLSocket with an explicit context and a prior session for resumption.

Parameters

  • sslContext The SSL context to use for this connection.

  • session A previously saved session to attempt resumption with.

  • loop Event loop to use; defaults to the default loop.


{#connect-5}

connect

virtual

virtual void connect(const Address & peerAddress)

Initialize the SSLSocket with the given SSLContext.

Initiates a secure connection to the peer at the given address.

The SSL handshake begins automatically once the TCP connection is established.

Parameters

  • peerAddress The remote address to connect to.

{#connect-6}

connect

virtual

virtual void connect(std::string_view host, uint16_t port)

Resolves host and initiates a secure connection.

Sets the hostname on the SSL adapter for SNI and certificate verification before resolving and connecting.

Parameters

  • host Hostname or IP address string.

  • port Destination port.


{#bind-1}

bind

virtual

virtual void bind(const net::Address & address, unsigned flags)

Binds the socket to address for server-side use. Throws std::logic_error if the context is not a server context.

Parameters

  • address Local address to bind to.

  • flags Optional bind flags (passed to uv_tcp_bind).


{#listen-1}

listen

virtual

virtual void listen(int backlog)

Starts listening for incoming connections. Throws std::logic_error if the context is not a server context.

Parameters

  • backlog Maximum number of pending connections.

{#shutdown-4}

shutdown

virtual

virtual bool shutdown()

Shuts down the connection by attempting an orderly SSL shutdown, then actually shutting down the TCP connection.


{#close-14}

close

virtual

virtual void close()

Closes the socket forcefully.


{#send-2}

send

virtual

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

Encrypts and sends len bytes to the connected peer.

Parameters

  • data Pointer to the plaintext payload.

  • len Number of bytes to send.

  • flags Reserved; currently unused.

Returns

Number of plaintext bytes accepted, or -1 on error.


{#sendowned-4}

sendOwned

virtual

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

Sends an owned payload buffer to the connected peer.


{#send-3}

send

virtual

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

Encrypts and sends len bytes, ignoring peerAddress (TCP is connected).

Parameters

  • data Pointer to the plaintext payload.

  • len Number of bytes to send.

  • peerAddress Ignored for SSL/TCP; present for interface conformance.

  • flags Reserved; currently unused.

Returns

Number of plaintext bytes accepted, or -1 on error.


{#sendowned-5}

sendOwned

virtual

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

{#sethostname-1}

setHostname

void setHostname(std::string_view hostname)

Set the expected peer hostname for certificate verification and SNI. Must be called before connect() to enable hostname verification.


{#usecontext}

useContext

void useContext(SSLContext::Ptr context)

Use the given SSL context for this socket.


{#context-4}

context

const

SSLContext::Ptr context() const

Returns the SSL context used for this socket.


{#usesession}

useSession

void useSession(SSLSession::Ptr session)

Sets the SSL session to use for the next connection. Setting a previously saved Session object is necessary to enable session caching.

To remove the currently set session, a nullptr pointer can be given.

Must be called before connect() to be effective.


{#currentsession}

currentSession

SSLSession::Ptr currentSession()

Returns the SSL session of the current connection, for reuse in a future connection (if session caching is enabled).

If no connection is established, returns nullptr.


{#sessionwasreused}

sessionWasReused

bool sessionWasReused()

Returns true if a reused session was negotiated during the handshake.


{#available-2}

available

const

int available() const

Returns the number of bytes available from the SSL buffer for immediate reading.


{#peercertificate}

peerCertificate

const

X509 * peerCertificate() const

Returns the peer's X.509 certificate, or nullptr if no certificate was presented.


{#transport-1}

transport

virtual const

virtual net::TransportType transport() const

Returns the SSLTCP transport protocol identifier.


{#acceptconnection}

acceptConnection

virtual

virtual void acceptConnection()

Accepts a pending client connection, initializes the server-side SSL context on the new socket, and fires the AcceptConnection signal.


{#onconnect}

onConnect

virtual

virtual void onConnect()

Called when the TCP connection is established; starts reading and initiates the client-side SSL handshake.


{#onread}

onRead

virtual

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

Feeds raw encrypted bytes from the network into the SSL adapter. Called by the stream layer when ciphertext arrives from the peer.

Parameters

  • data Pointer to the encrypted bytes.

  • len Number of bytes received.

Protected Attributes

ReturnNameDescription
net::SSLContext::Ptr_sslContext
net::SSLSession::Ptr_sslSession
net::SSLAdapter_sslAdapter

{#_sslcontext-1}

_sslContext

net::SSLContext::Ptr _sslContext

{#_sslsession}

_sslSession

net::SSLSession::Ptr _sslSession

{#_ssladapter}

_sslAdapter

net::SSLAdapter _sslAdapter

Public Types

NameDescription
Ptr
Vec

{#ptr-8}

Ptr

std::shared_ptr< SSLSocket > Ptr()

{#vec-1}

Vec

std::vector< Ptr > Vec()

{#tcpsocket}

TCPSocket

#include <icy/net/tcpsocket.h>

Inherits: Stream< uv_tcp_t >, Socket Subclassed by: SSLSocket

TCP socket implementation.

Public Attributes

ReturnNameDescription
LocalSignal< void(const net::TCPSocket::Ptr &)>AcceptConnectionFired when a new client connection is accepted; carries a shared_ptr to the new socket.

{#acceptconnection-1}

AcceptConnection

LocalSignal< void(const net::TCPSocket::Ptr &)> AcceptConnection

Fired when a new client connection is accepted; carries a shared_ptr to the new socket.

Public Methods

ReturnNameDescription
TCPSocketConstructs the TCPSocket and initializes the underlying libuv handle.
TCPSocketDeleted constructor.
TCPSocketDeleted constructor.
boolshutdown virtualSends a TCP shutdown request; the socket closes after the peer acknowledges.
voidclose virtualCloses the socket immediately, releasing all associated resources.
voidconnect virtualConnects to peerAddress using a libuv connect request. On success, calls onConnect(); on failure, calls setUVError().
voidconnect virtualResolves host via DNS (or maps "localhost"), then connects.
ssize_tsend virtualWrites len bytes to the connected peer.
ssize_tsendOwned virtualSends an owned payload buffer to the connected peer.
ssize_tsend virtualWrites len bytes; peerAddress is ignored for TCP (connected stream).
ssize_tsendOwned virtual
voidbind virtualBinds the socket to address. Resets and reinitializes the handle if the address family changes.
voidlisten virtualStarts listening for incoming connections with the given backlog.
voidacceptConnection virtualAccepts the next pending client connection and fires AcceptConnection.
boolsetReusePortEnables SO_REUSEPORT on Linux kernel >= 3.9 for multi-thread load balancing. Must be called after bind(). No-op and returns false on unsupported platforms.
boolsetNoDelayEnables or disables TCP_NODELAY (Nagle's algorithm).
boolsetKeepAliveEnables or disables TCP keep-alive probes.
boolsetSimultaneousAcceptsEnables or disables simultaneous accepts on Windows. No-op and returns false on non-Windows platforms.
voidsetModeSets the socket mode (ServerSide or ClientSide).
SocketModemode constReturns the current socket mode.
voidsetError virtualSets the socket error; ignores the call if an error is already recorded. Setting an error causes the socket to close.
const icy::Error &error virtual constReturns the current socket error, if any.
boolclosed virtual constReturns true if the native socket handle is closed.
net::Addressaddress virtual constReturns the IP address and port number of the socket. A wildcard address is returned if the socket is not connected.
net::AddresspeerAddress virtual constReturns the IP address and port number of the peer socket. A wildcard address is returned if the socket is not connected.
net::TransportTypetransport virtual constReturns the TCP transport protocol.
uv::Loop *loop virtual constReturns the event loop associated with this socket.
voidonConnect virtualCalled by the stream layer when the TCP connection is established.
voidonRead virtualCalled by the stream layer with raw received bytes; wraps them in a MutableBuffer.
voidonRecv virtualDispatches a received buffer to all socket adapters via onSocketRecv.
voidonError virtualDispatches the error to adapters and closes the socket.
voidonClose virtualDispatches the close event to all socket adapters.

{#tcpsocket-1}

TCPSocket

TCPSocket(uv::Loop * loop)

Constructs the TCPSocket and initializes the underlying libuv handle.

Parameters

  • loop Event loop to use; defaults to the default loop.

{#tcpsocket-2}

TCPSocket

TCPSocket(const TCPSocket &) = delete

Deleted constructor.


{#tcpsocket-3}

TCPSocket

TCPSocket(TCPSocket &&) = delete

Deleted constructor.


{#shutdown-5}

shutdown

virtual

virtual bool shutdown()

Sends a TCP shutdown request; the socket closes after the peer acknowledges.

Returns

true if the shutdown request was queued successfully.


{#close-15}

close

virtual

virtual void close()

Closes the socket immediately, releasing all associated resources.


{#connect-7}

connect

virtual

virtual void connect(const net::Address & peerAddress)

Connects to peerAddress using a libuv connect request. On success, calls onConnect(); on failure, calls setUVError().

Parameters

  • peerAddress The remote address to connect to.

{#connect-8}

connect

virtual

virtual void connect(std::string_view host, uint16_t port)

Resolves host via DNS (or maps "localhost"), then connects.

Parameters

  • host Hostname or IP address string.

  • port Destination port.


{#send-4}

send

virtual

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

Writes len bytes to the connected peer.

Parameters

  • data Pointer to the data to send.

  • len Number of bytes to send.

  • flags Reserved; currently unused.

Returns

Number of bytes sent, or -1 on error.


{#sendowned-6}

sendOwned

virtual

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

Sends an owned payload buffer to the connected peer.


{#send-5}

send

virtual

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

Writes len bytes; peerAddress is ignored for TCP (connected stream).

Parameters

  • data Pointer to the data to send.

  • len Number of bytes to send.

  • peerAddress Ignored; present for interface conformance.

  • flags Reserved; currently unused.

Returns

Number of bytes sent, or -1 on error.


{#sendowned-7}

sendOwned

virtual

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

{#bind-2}

bind

virtual

virtual void bind(const net::Address & address, unsigned flags)

Binds the socket to address. Resets and reinitializes the handle if the address family changes.

Parameters

  • address Local address to bind to.

  • flags Optional bind flags (e.g. UV_TCP_IPV6ONLY is added automatically for IPv6).


{#listen-2}

listen

virtual

virtual void listen(int backlog)

Starts listening for incoming connections with the given backlog.

Parameters

  • backlog Maximum length of the pending connection queue.

{#acceptconnection-2}

acceptConnection

virtual

virtual void acceptConnection()

Accepts the next pending client connection and fires AcceptConnection.


{#setreuseport}

setReusePort

bool setReusePort()

Enables SO_REUSEPORT on Linux kernel >= 3.9 for multi-thread load balancing. Must be called after bind(). No-op and returns false on unsupported platforms.

Returns

true if the socket option was set successfully.


{#setnodelay}

setNoDelay

bool setNoDelay(bool enable)

Enables or disables TCP_NODELAY (Nagle's algorithm).

Parameters

  • enable true to disable Nagle's algorithm (lower latency).

Returns

true if the option was set successfully.


{#setkeepalive}

setKeepAlive

bool setKeepAlive(bool enable, int delay)

Enables or disables TCP keep-alive probes.

Parameters

  • enable true to enable keep-alive.

  • delay Initial delay in seconds before the first keep-alive probe.

Returns

true if the option was set successfully.


{#setsimultaneousaccepts}

setSimultaneousAccepts

bool setSimultaneousAccepts(bool enable)

Enables or disables simultaneous accepts on Windows. No-op and returns false on non-Windows platforms.

Parameters

  • enable true to enable simultaneous accepts.

Returns

true if the option was set successfully.


{#setmode}

setMode

void setMode(SocketMode mode)

Sets the socket mode (ServerSide or ClientSide).

Parameters

  • mode The mode to assign.

{#mode}

mode

const

SocketMode mode() const

Returns the current socket mode.


{#seterror-2}

setError

virtual

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

Sets the socket error; ignores the call if an error is already recorded. Setting an error causes the socket to close.

Parameters

  • err The error to record.

{#error-7}

error

virtual const

virtual const icy::Error & error() const

Returns the current socket error, if any.


{#closed-2}

closed

virtual const

virtual bool closed() const

Returns true if the native socket handle is closed.


{#address-9}

address

virtual const

virtual net::Address address() const

Returns the IP address and port number of the socket. A wildcard address is returned if the socket is not connected.


{#peeraddress-2}

peerAddress

virtual const

virtual net::Address peerAddress() const

Returns the IP address and port number of the peer socket. A wildcard address is returned if the socket is not connected.


{#transport-2}

transport

virtual const

virtual net::TransportType transport() const

Returns the TCP transport protocol.


{#loop-4}

loop

virtual const

virtual uv::Loop * loop() const

Returns the event loop associated with this socket.


{#onconnect-1}

onConnect

virtual

virtual void onConnect()

Called by the stream layer when the TCP connection is established.


{#onread-1}

onRead

virtual

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

Called by the stream layer with raw received bytes; wraps them in a MutableBuffer.

Parameters

  • data Pointer to received bytes.

  • len Number of bytes received.


{#onrecv}

onRecv

virtual

virtual void onRecv(const MutableBuffer & buf)

Dispatches a received buffer to all socket adapters via onSocketRecv.

Parameters

  • buf The buffer containing the received data.

{#onerror-1}

onError

virtual

virtual void onError(const icy::Error & error)

Dispatches the error to adapters and closes the socket.

Parameters

  • error The error that occurred.

{#onclose-1}

onClose

virtual

virtual void onClose()

Dispatches the close event to all socket adapters.

Protected Attributes

ReturnNameDescription
SocketMode_mode
net::Address_peerAddressCached peer address (avoids syscall per recv)

{#_mode-1}

_mode

SocketMode _mode

{#_peeraddress}

_peerAddress

net::Address _peerAddress

Cached peer address (avoids syscall per recv)

Protected Methods

ReturnNameDescription
voidinit virtualInitializes the underlying socket context.
voidreset virtualResets the socket context for reuse.

{#init-5}

init

virtual

virtual void init()

Initializes the underlying socket context.


{#reset-5}

reset

virtual

virtual void reset()

Resets the socket context for reuse.

Public Types

NameDescription
Ptr
Vec

{#ptr-9}

Ptr

std::shared_ptr< TCPSocket > Ptr()

{#vec-2}

Vec

std::vector< Ptr > Vec()

{#transaction}

Transaction

#include <icy/net/transaction.h>

Inherits: PacketTransaction< PacketT >, PacketSocketEmitter

Request/response helper for packet types emitted from a socket.

Public Methods

ReturnNameDescription
Transaction inlineConstructs a Transaction on the given socket targeting peerAddress.
boolsend virtual inlineSends the request packet to the peer address and starts the timeout timer. Sets state to Failed and returns false if the packet could not be sent.
voidcancel virtual inlineCancels the transaction and stops the timeout timer.
voiddispose virtual inlineStops the timer and unregisters callbacks.
AddresspeerAddress const inlineReturns the remote peer address used for this transaction.

{#transaction-1}

Transaction

inline

inline Transaction(const net::Socket::Ptr & socket, const Address & peerAddress, int timeout, int retries)

Constructs a Transaction on the given socket targeting peerAddress.

Parameters

  • socket The socket to send/receive packets on.

  • peerAddress The remote address for the request and response matching.

  • timeout Milliseconds to wait for a response before failing.

  • retries Number of additional send attempts on timeout.


{#send-6}

send

virtual inline

virtual inline bool send()

Sends the request packet to the peer address and starts the timeout timer. Sets state to Failed and returns false if the packet could not be sent.

Returns

true if the packet was sent and the timer started successfully.


{#cancel}

cancel

virtual inline

virtual inline void cancel()

Cancels the transaction and stops the timeout timer.


{#dispose}

dispose

virtual inline

virtual inline void dispose()

Stops the timer and unregisters callbacks.


{#peeraddress-3}

peerAddress

const inline

inline Address peerAddress() const

Returns the remote peer address used for this transaction.

Protected Attributes

ReturnNameDescription
Address_peerAddress

{#_peeraddress-1}

_peerAddress

Address _peerAddress

Protected Methods

ReturnNameDescription
boolonPacket virtual inlineChecks whether packet is a matching response for the pending request. If it matches, the transaction completes; socket data propagation stops.
voidonResponse virtual inlineCalled when a confirmed response is received; emits the response via PacketSignal.
boolcheckResponse virtual inlineReturns true if packet is a valid response for this transaction.

{#onpacket-1}

onPacket

virtual inline

virtual inline bool onPacket(IPacket & packet)

Checks whether packet is a matching response for the pending request. If it matches, the transaction completes; socket data propagation stops.

Parameters

  • packet The received packet to test.

Returns

true to stop further propagation of the socket data event.


{#onresponse}

onResponse

virtual inline

virtual inline void onResponse()

Called when a confirmed response is received; emits the response via PacketSignal.


{#checkresponse}

checkResponse

virtual inline

virtual inline bool checkResponse(const PacketT & packet)

Returns true if packet is a valid response for this transaction.

The base implementation matches the local socket address against the PacketInfo socket address and the stored peer address against the PacketInfo peer address. Subclasses may override for stricter matching.

Parameters

  • packet The candidate response packet.

Returns

true if the packet satisfies the response criteria.

Public Types

NameDescription
BaseT

{#baset}

BaseT

PacketTransaction< PacketT > BaseT()

{#udpsocket}

UDPSocket

#include <icy/net/udpsocket.h>

Inherits: Handle< uv_udp_t >, Socket

UDP socket implementation.

Public Methods

ReturnNameDescription
UDPSocketConstructs the UDPSocket and initializes the underlying libuv handle.
UDPSocketDeleted constructor.
UDPSocketDeleted constructor.
voidconnect virtualRecords the peer address and fires the Connect signal to mimic TCP socket behaviour. UDP is connectionless; this call does not send any data.
voidconnect virtualResolves host via DNS (or maps "localhost"), then calls connect(Address).
voidclose virtualStops receiving and closes the underlying UDP handle.
voidbind virtualBinds the socket to address and starts the receive loop.
ssize_tsend virtualSends len bytes to the previously connected peer address. Returns -1 if no peer address has been set.
ssize_tsendOwned virtualSends an owned payload buffer to the connected peer.
ssize_tsend virtualSends len bytes to peerAddress. Returns -1 if the socket is uninitialized or the address is not authorized.
ssize_tsendOwned virtual
boolsetBroadcastEnables or disables UDP broadcast.
boolsetMulticastLoopEnables or disables IP multicast loopback.
boolsetMulticastTTLSets the IP multicast time-to-live (hop limit).
net::Addressaddress virtual constReturns the locally bound address, or a wildcard address if unbound.
net::AddresspeerAddress virtual constReturns the connected peer address set by connect(), or a wildcard address if unconnected.
net::TransportTypetransport virtual constReturns the UDP transport protocol.
voidsetError virtualSets the socket error and triggers close.
const icy::Error &error virtual constReturns the current socket error, if any.
boolclosed virtual constReturns true if the native socket handle is closed.
uv::Loop *loop virtual constReturns the event loop associated with this socket.
voidonRecv virtualDispatches a received datagram to all socket adapters via onSocketRecv.

{#udpsocket-1}

UDPSocket

UDPSocket(uv::Loop * loop)

Constructs the UDPSocket and initializes the underlying libuv handle.

Parameters

  • loop Event loop to use; defaults to the default loop.

{#udpsocket-2}

UDPSocket

UDPSocket(const UDPSocket &) = delete

Deleted constructor.


{#udpsocket-3}

UDPSocket

UDPSocket(UDPSocket &&) = delete

Deleted constructor.


{#connect-9}

connect

virtual

virtual void connect(const net::Address & peerAddress)

Records the peer address and fires the Connect signal to mimic TCP socket behaviour. UDP is connectionless; this call does not send any data.

Parameters

  • peerAddress The remote address to associate with this socket.

{#connect-10}

connect

virtual

virtual void connect(std::string_view host, uint16_t port)

Resolves host via DNS (or maps "localhost"), then calls connect(Address).

Parameters

  • host Hostname or IP address string.

  • port Destination port.


{#close-16}

close

virtual

virtual void close()

Stops receiving and closes the underlying UDP handle.


{#bind-3}

bind

virtual

virtual void bind(const net::Address & address, unsigned flags)

Binds the socket to address and starts the receive loop.

Parameters

  • address Local address to bind to.

  • flags Optional bind flags (UV_UDP_IPV6ONLY is added automatically for IPv6).


{#send-7}

send

virtual

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

Sends len bytes to the previously connected peer address. Returns -1 if no peer address has been set.

Parameters

  • data Pointer to the data to send.

  • len Number of bytes to send.

  • flags Reserved; currently unused.

Returns

Number of bytes accepted for sending, or -1 on error.


{#sendowned-8}

sendOwned

virtual

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

Sends an owned payload buffer to the connected peer.


{#send-8}

send

virtual

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

Sends len bytes to peerAddress. Returns -1 if the socket is uninitialized or the address is not authorized.

Parameters

  • data Pointer to the data to send.

  • len Number of bytes to send.

  • peerAddress Destination address; must match the connected peer if one is set.

  • flags Reserved; currently unused.

Returns

Number of bytes accepted for sending, or -1 on error.


{#sendowned-9}

sendOwned

virtual

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

{#setbroadcast}

setBroadcast

bool setBroadcast(bool flag)

Enables or disables UDP broadcast.

Parameters

  • flag true to enable broadcast.

Returns

true if the option was set successfully.


{#setmulticastloop}

setMulticastLoop

bool setMulticastLoop(bool flag)

Enables or disables IP multicast loopback.

Parameters

  • flag true to enable multicast loopback.

Returns

true if the option was set successfully.


{#setmulticastttl}

setMulticastTTL

bool setMulticastTTL(int ttl)

Sets the IP multicast time-to-live (hop limit).

Parameters

  • ttl Value in the range [1, 255].

Returns

true if the option was set successfully.

Exceptions

  • std::invalid_argument if ttl is out of range.

{#address-10}

address

virtual const

virtual net::Address address() const

Returns the locally bound address, or a wildcard address if unbound.


{#peeraddress-4}

peerAddress

virtual const

virtual net::Address peerAddress() const

Returns the connected peer address set by connect(), or a wildcard address if unconnected.


{#transport-3}

transport

virtual const

virtual net::TransportType transport() const

Returns the UDP transport protocol.


{#seterror-3}

setError

virtual

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

Sets the socket error and triggers close.

Parameters

  • err The error to record.

{#error-8}

error

virtual const

virtual const icy::Error & error() const

Returns the current socket error, if any.


{#closed-3}

closed

virtual const

virtual bool closed() const

Returns true if the native socket handle is closed.


{#loop-5}

loop

virtual const

virtual uv::Loop * loop() const

Returns the event loop associated with this socket.


{#onrecv-1}

onRecv

virtual

virtual void onRecv(const MutableBuffer & buf, const net::Address & address)

Dispatches a received datagram to all socket adapters via onSocketRecv.

Parameters

  • buf Buffer containing the received datagram payload.

  • address Address of the sender.

Protected Attributes

ReturnNameDescription
net::Address_peer
Buffer_buffer

{#_peer}

_peer

net::Address _peer

{#_buffer}

_buffer

Buffer _buffer

Protected Methods

ReturnNameDescription
voidinit virtualInitializes the underlying socket context.
voidreset virtualResets the socket context for reuse.
voidonError virtualCalled by [setError()](#seterror-3) after the error state has been updated.
voidonClose virtualCalled by [close()](#close-16) after the context has been released.
boolrecvStart virtual
boolrecvStop virtual

{#init-6}

init

virtual

virtual void init()

Initializes the underlying socket context.


{#reset-6}

reset

virtual

virtual void reset()

Resets the socket context for reuse.


{#onerror-2}

onError

virtual

virtual void onError(const icy::Error & error)

Called by [setError()](#seterror-3) after the error state has been updated.

Override to react to errors. The default implementation is a no-op.

Parameters

  • error The error that was set.

{#onclose-2}

onClose

virtual

virtual void onClose()

Called by [close()](#close-16) after the context has been released.

Override to perform cleanup on handle closure. The default implementation is a no-op.


{#recvstart}

recvStart

virtual

virtual bool recvStart()

{#recvstop}

recvStop

virtual

virtual bool recvStop()

Public Types

NameDescription
Ptr
Vec

{#ptr-10}

Ptr

std::shared_ptr< UDPSocket > Ptr()

{#vec-3}

Vec

std::vector< Ptr > Vec()

{#verificationerrordetails}

VerificationErrorDetails

#include <icy/net/sslmanager.h>

A utility class for certificate error handling.

Public Methods

ReturnNameDescription
VerificationErrorDetailsCreates the VerificationErrorDetails. _ignoreError is per default set to false.
~VerificationErrorDetailsDestroys the VerificationErrorDetails.
const crypto::X509Certificate &certificate const inlineReturns the certificate that caused the error.
interrorDepth const inlineReturns the position of the certificate in the certificate chain.
interrorNumber const inlineReturns the id of the error.
const std::string &errorMessage const inlineReturns the textual presentation of the errorNumber.
voidsetIgnoreError inlinesetIgnoreError to true, if a verification error is judged non-fatal by the user.
boolgetIgnoreError const inlinereturns the value of _ignoreError

{#verificationerrordetails-1}

VerificationErrorDetails

VerificationErrorDetails(const crypto::X509Certificate & cert, int errDepth, int errNum, const std::string & errMsg)

Creates the VerificationErrorDetails. _ignoreError is per default set to false.


{#verificationerrordetails-2}

~VerificationErrorDetails

~VerificationErrorDetails() noexcept

Destroys the VerificationErrorDetails.


{#certificate}

certificate

const inline

inline const crypto::X509Certificate & certificate() const

Returns the certificate that caused the error.


{#errordepth}

errorDepth

const inline

inline int errorDepth() const

Returns the position of the certificate in the certificate chain.


{#errornumber}

errorNumber

const inline

inline int errorNumber() const

Returns the id of the error.


{#errormessage}

errorMessage

const inline

inline const std::string & errorMessage() const

Returns the textual presentation of the errorNumber.


{#setignoreerror}

setIgnoreError

inline

inline void setIgnoreError(bool ignoreError)

setIgnoreError to true, if a verification error is judged non-fatal by the user.


{#getignoreerror}

getIgnoreError

const inline

inline bool getIgnoreError() const

returns the value of _ignoreError

Private Attributes

ReturnNameDescription
crypto::X509Certificate_cert
int_errorDepth
int_errorNumber
std::string_errorMessage
bool_ignoreError

{#_cert}

_cert

crypto::X509Certificate _cert

{#_errordepth}

_errorDepth

int _errorDepth

{#_errornumber}

_errorNumber

int _errorNumber

{#_errormessage}

_errorMessage

std::string _errorMessage

{#_ignoreerror}

_ignoreError

bool _ignoreError

{#packetinfo}

PacketInfo

#include <icy/net/socket.h>

Inherits: IPacketInfo

Provides information about packets emitted from a socket. See SocketPacket.

Public Attributes

ReturnNameDescription
Socket::PtrsocketThe source socket.
AddresspeerAddressThe originating peer address. For TCP this will always be connected address.

{#socket}

socket

Socket::Ptr socket

The source socket.


{#peeraddress}

peerAddress

Address peerAddress

The originating peer address. For TCP this will always be connected address.

Public Methods

ReturnNameDescription
PacketInfo inlineConstructs PacketInfo with the originating socket and peer address.
PacketInfo inlineCopy constructor.
std::unique_ptr< IPacketInfo >clone virtual const inlineReturns a heap-allocated copy of this PacketInfo.

{#packetinfo-1}

PacketInfo

inline

inline PacketInfo(const Socket::Ptr & socket, const Address & peerAddress)

Constructs PacketInfo with the originating socket and peer address.

Parameters

  • socket Shared pointer to the socket that received the packet.

  • peerAddress Address of the remote peer that sent the packet.


{#packetinfo-2}

PacketInfo

inline

inline PacketInfo(const PacketInfo & r)

Copy constructor.

Parameters


{#clone-5}

clone

virtual const inline

virtual inline std::unique_ptr< IPacketInfo > clone() const

Returns a heap-allocated copy of this PacketInfo.

{#dns}

dns

DNS utilities.

Functions

ReturnNameDescription
autoresolve inlineResolves a hostname to a network address asynchronously.

{#resolve-1}

resolve

inline

inline auto resolve(const std::string & host, int port, std::function< void(int, const net::Address &)> callback, uv::Loop * loop)

Resolves a hostname to a network address asynchronously.

The callback is invoked on the event loop thread when resolution completes. On failure, the callback receives a non-zero status and an empty Address.

Parameters

  • host Hostname or IP address string to resolve.

  • port Port number to associate with the resolved address.

  • callback Invoked with (status, resolved Address); status is 0 on success.

  • loop Event loop to use; defaults to the default loop.

Returns

A request handle whose lifetime controls the in-flight DNS query.