net
May 6, 2026 ยท View on GitHub
{#netmodule}
net
TCP/SSL/UDP networking, socket adapters, DNS resolution.
Namespaces
| Name | Description |
|---|---|
net | Socket transports, adapters, and address helpers. |
dns | DNS utilities. |
{#net}
net
Socket transports, adapters, and address helpers.
Classes
| Name | Description |
|---|---|
Address | Represents an IPv4 or IPv6 socket address with host and port. |
PacketSocketEmitter | Socket adapter that emits received data as packets. |
Socket | Base socket implementation from which all sockets derive. |
SocketAdapter | Abstract adapter interface for socket send/receive chains. |
SocketEmitter | SocketAdapter that exposes socket events as signals. |
SocketPacket | Default packet type emitted by sockets. |
SSLAdapter | Manages the OpenSSL context and BIO buffers for an SSL socket connection. |
SSLContext | OpenSSL SSL_CTX wrapper for client and server TLS configuration. |
SSLManager | Singleton that owns the default client/server TLS contexts and related callbacks. |
SSLSession | Cached SSL/TLS session wrapper used for client-side resumption. |
SSLSocket | SSL socket implementation. |
TCPSocket | TCP socket implementation. |
Transaction | Request/response helper for packet types emitted from a socket. |
UDPSocket | UDP socket implementation. |
VerificationErrorDetails | A utility class for certificate error handling. |
PacketInfo | Provides information about packets emitted from a socket. See SocketPacket. |
Enumerations
| Name | Description |
|---|---|
TransportType | Transport protocol identifier used to distinguish socket types at runtime. |
SocketMode | Transport mode for socket adapters and accepted connections. |
{#transporttype}
TransportType
enum TransportType
Transport protocol identifier used to distinguish socket types at runtime.
| Value | Description |
|---|---|
UDP | Unreliable datagram protocol. |
TCP | Reliable stream protocol. |
SSLTCP | TLS-encrypted TCP stream. |
{#socketmode}
SocketMode
enum SocketMode
Transport mode for socket adapters and accepted connections.
| Value | Description |
|---|---|
ServerSide | Server-side adapter. |
ClientSide | Client-side adapter. |
Functions
| Return | Name | Description |
|---|---|---|
std::shared_ptr< SocketT > | makeSocket inline | Creates a socket of type SocketT wrapped in a shared_ptr. |
SSLContext::VerificationMode | convertVerificationMode inline | Non-case sensitive conversion of a string to a VerificationMode enum. If verMode is illegal an ArgumentException is thrown. |
std::string | convertCertificateError inline | Converts an SSL certificate handling error code into an error message. |
std::string | getLastError inline | Returns the last error from the error stack. |
void | clearErrorStack inline | Clears the error stack. |
void | getNetworkInterfaces inline | Populates hosts with all local network interface addresses. |
int | getServerSocketSendBufSize | 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. |
int | getServerSocketRecvBufSize | 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. |
int | setServerSocketSendBufSize | Sets the send buffer size for a socket handle. |
int | setServerSocketRecvBufSize | Sets 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
loopEvent 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
hostsVector 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
TThe libuv handle type (e.g. uv_tcp_t, uv_udp_t).
Parameters
handleThe 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
TThe libuv handle type (e.g. uv_tcp_t, uv_udp_t).
Parameters
handleThe 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
TThe libuv handle type (e.g. uv_tcp_t, uv_udp_t).
Parameters
-
handleThe socket handle to configure. -
sizeThe 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
TThe libuv handle type (e.g. uv_tcp_t, uv_udp_t).
Parameters
-
handleThe socket handle to configure. -
sizeThe desired receive buffer size in bytes.
Returns
0 on success, or a libuv error code on failure.
Variables
| Return | Name | Description |
|---|---|---|
constexpr int | MAX_TCP_PACKET_SIZE | Maximum size of a single TCP receive buffer, in bytes. |
constexpr int | MAX_UDP_PACKET_SIZE | Maximum 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
| Return | Name | Description |
|---|---|---|
Address | Creates a wildcard (all zero) IPv4 Address. | |
Address | Creates an Address from an IP address and a port number. | |
Address | Creates an Address by copying another one. | |
Address | Creates an Address from a native socket address. | |
Address | Creates an Address from an IP address and a service name or port number. | |
Address explicit | 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. | |
~Address | Destroys the Address. | |
Address & | operator= | Assigns another Address. |
void | swap | Swaps the Address with another one. |
std::string | host const | Returns the host IP address. |
uint16_t | port const | Returns the port number. |
socklen_t | length const | Returns the length of the internal native socket address. |
const struct sockaddr * | addr const | Returns a pointer to the internal native socket address. |
int | af const | Returns the address family (AF_INET or AF_INET6) of the address. |
std::string | toString const | Returns a string representation of the address. |
Address::Family | family const | Returns the address family of the host's address. |
bool | valid const | Returns true when the port is set and the address is valid ie. not wildcard. |
bool | operator< const | Compares two addresses for ordering (by family then port). |
bool | operator== const | Returns true if the host and port of both addresses are equal. |
bool | operator!= const | Returns 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
addrThe 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
addrThe 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
addrThe address to compare against.
Public Static Methods
| Return | Name | Description |
|---|---|---|
uint16_t | resolveService static | Resolves a service name or decimal port string to a port number. |
bool | validateIP static | Returns 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
serviceService 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
addressThe string to validate.
Returns
true if the address parses as a valid IP address, false otherwise.
Protected Methods
| Return | Name | Description |
|---|---|---|
void | init |
{#init-3}
init
void init(const std::string & host, uint16_t port)
Public Types
| Name | Description |
|---|---|
Family | Possible address families for IP addresses. |
{#family-1}
Family
enum Family
Possible address families for IP addresses.
| Value | Description |
|---|---|
IPv4 | |
IPv6 |
Private Attributes
| Return | Name | Description |
|---|---|---|
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
| Return | Name | Description |
|---|---|---|
PacketFactory | factory | The packet factory. |
{#factory}
factory
PacketFactory factory
The packet factory.
Public Methods
| Return | Name | Description |
|---|---|---|
PacketSocketEmitter | Creates the PacketSocketEmitter and attaches it to the given socket. | |
bool | onSocketRecv virtual | Parses raw received data into packets via the factory and forwards each parsed packet to onPacket(). Returns true if propagation should stop. |
bool | onPacket virtual | Process 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
socketOptional 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
-
socketThe socket that received the data. -
bufferThe raw received data buffer. -
peerAddressThe 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:
SocketAdapterSubclassed by:TCPSocket,UDPSocket
Base socket implementation from which all sockets derive.
Public Attributes
| Return | Name | Description |
|---|---|---|
std::any | opaque | Optional client data. |
{#opaque}
opaque
std::any opaque
Optional client data.
The value is empty on initialization.
Public Methods
| Return | Name | Description |
|---|---|---|
Socket | Defaulted constructor. | |
Socket | Deleted constructor. | |
Socket | Deleted constructor. | |
void | connect | Connects to the given peer IP address. |
void | connect | Resolves and connects to the given host address. |
void | bind | Bind a local address to the socket. The address may be IPv4 or IPv6 (if supported). |
void | listen virtual inline | Listens the socket on the given address. |
bool | shutdown virtual inline | Sends the shutdown packet which should result is socket closure via callback. |
ssize_t | sendOwned | Sends an owned payload buffer to the connected peer. |
ssize_t | sendOwned | |
void | close | Closes the underlying socket. |
Address | address const | The locally bound address. |
Address | peerAddress const | The connected peer address. |
net::TransportType | transport const | The transport protocol: TCP, UDP or SSLTCP. |
void | setError | Sets the socket error. |
const icy::Error & | error const | Return the socket error if any. |
bool | closed const | Returns true if the native socket handle is closed. |
uv::Loop * | loop const | Returns 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
| Return | Name | Description |
|---|---|---|
int | _af |
{#_af}
_af
int _af {AF_UNSPEC}
Protected Methods
| Return | Name | Description |
|---|---|---|
void | init | Initializes the underlying socket context. |
void | reset | Resets 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
| Name | Description |
|---|---|
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
| Return | Name | Description |
|---|---|---|
int | priority | The 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
| Return | Name | Description |
|---|---|---|
SocketAdapter | Creates the SocketAdapter. | |
~SocketAdapter virtual | Destroys the SocketAdapter. | |
ssize_t | send virtual | 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. |
ssize_t | send virtual | |
ssize_t | sendOwned virtual | Sends an owned payload buffer to the connected peer. |
ssize_t | sendOwned virtual | |
ssize_t | sendPacket virtual | 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. |
ssize_t | sendPacket virtual | |
void | sendPacket virtual | 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. |
void | setSender virtual | Sets the pointer to the outgoing data adapter. Send methods proxy data to this adapter by default. |
SocketAdapter * | sender | Returns the output SocketAdapter pointer. |
void | addReceiver virtual | Sets the pointer to the incoming data adapter. Events proxy data to this adapter by default. |
void | removeReceiver virtual | Remove the given receiver. |
bool | hasReceiver virtual | Returns true if the given receiver is connected. |
std::vector< SocketAdapter * > | receivers | Returns all currently registered input SocketAdapter pointers. Dead (removed) entries are excluded from the returned list. |
bool | onSocketConnect virtual | 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. |
bool | onSocketRecv virtual | Called when data is received from the socket. Forwards the event to all registered receivers in priority order. |
bool | onSocketError virtual | Called when the socket encounters an error. Forwards the event to all registered receivers in priority order. |
bool | onSocketClose virtual | Called 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
socketThe 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
-
socketThe socket that received data. -
bufferThe received data buffer. -
peerAddressAddress 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
-
socketThe socket that encountered the error. -
errorError 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
socketThe socket that was closed.
Returns
true to stop propagation to subsequent receivers.
Protected Attributes
| Return | Name | Description |
|---|---|---|
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
| Return | Name | Description |
|---|---|---|
void | cleanupReceivers virtual |
{#cleanupreceivers}
cleanupReceivers
virtual
virtual void cleanupReceivers()
{#ref-1}
Ref
#include <icy/net/socketadapter.h>
Reference-counted handle to a SocketAdapter.
Public Attributes
| Return | Name | Description |
|---|---|---|
SocketAdapter * | ptr | |
bool | alive |
{#ptr-5}
ptr
SocketAdapter * ptr
{#alive}
alive
bool alive
{#socketemitter}
SocketEmitter
#include <icy/net/socketemitter.h>
Inherits:
SocketAdapterSubclassed 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
| Return | Name | Description |
|---|---|---|
LocalSignal< bool(Socket &)> | Connect | Signals that the socket is connected. |
LocalSignal< bool(Socket &, const MutableBuffer &, const Address &)> | Recv | Signals when data is received by the socket. |
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. |
LocalSignal< bool(Socket &)> | Close | Signals that the underlying socket is closed. |
Socket::Ptr | impl | Pointer 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
| Return | Name | Description |
|---|---|---|
SocketEmitter | Creates the SocketEmitter and optionally attaches it to a socket. If socket is provided, this emitter registers itself as a receiver. | |
SocketEmitter | Copy constructor; copies all signal connections and attaches to the same socket. | |
~SocketEmitter virtual | Destroys the SocketAdapter. | |
void | addReceiver virtual | Attaches a SocketAdapter as a receiver; wires it to all four socket signals. |
void | removeReceiver virtual | Detaches a SocketAdapter from all four socket signals. |
void | swap virtual | Replaces the underlying socket with socket. |
T * | as inline | Returns the underlying socket cast to type T, or nullptr if the cast fails. |
Socket * | operator-> const inline | Returns 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
socketOptional 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
thatThe SocketEmitter to copy from.
{#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
adapterThe 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
adapterThe 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
socketThe 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
TDerived 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
| Return | Name | Description |
|---|---|---|
bool | onSocketConnect virtual | Forwards the connect event to chained adapters, then fires the Connect signal. |
bool | onSocketRecv virtual | Forwards the recv event to chained adapters, then fires the Recv signal. |
bool | onSocketError virtual | Forwards the error event to chained adapters, then fires the Error signal. |
bool | onSocketClose virtual | Forwards 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
| Return | Name | Description |
|---|---|---|
SocketPacket inline | Constructs a SocketPacket wrapping the received buffer. | |
SocketPacket inline | Copy constructor; shares the underlying buffer reference. | |
PacketInfo * | packetInfo const inline | Returns the PacketInfo for this socket packet. |
void | print virtual const inline | Prints a one-line description of the packet to os. |
std::unique_ptr< IPacket > | clone virtual const inline | Returns a heap-allocated copy of this SocketPacket. |
ssize_t | read virtual inline | Not supported; always throws std::logic_error. |
void | write virtual const inline | Appends 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
-
socketShared pointer to the receiving socket. -
bufferView of the raw received bytes. -
peerAddressAddress of the remote sender.
{#socketpacket-2}
SocketPacket
inline
inline SocketPacket(const SocketPacket & that)
Copy constructor; shares the underlying buffer reference.
Parameters
thatSource SocketPacket to copy.
{#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}
virtual const inline
virtual inline void print(std::ostream & os) const
Prints a one-line description of the packet to os.
Parameters
osOutput 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
bufDestination 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
| Return | Name | Description |
|---|---|---|
SSLAdapter | Constructs the SSLAdapter and associates it with the given socket. The socket pointer must remain valid for the lifetime of this adapter. | |
SSLAdapter | Deleted constructor. | |
SSLAdapter | Deleted constructor. | |
void | initClient | Initializes the SSL context as a client. |
void | initServer | Initializes the SSL context as a server. |
bool | initialized const | Returns true when SSL context has been initialized. |
bool | ready const | Returns true when the handshake is complete. |
void | handshake | Start/continue the SSL handshake process. |
int | available const | Returns the number of bytes available in the SSL buffer for immediate reading. |
void | shutdown | Issues an orderly SSL shutdown. |
void | flush | Flushes the SSL read/write buffers. |
void | setHostname | Set the expected peer hostname for certificate verification. Must be called before initClient() to enable hostname verification. |
void | addIncomingData | 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(). |
void | addOutgoingData | Queues plaintext data for encryption and transmission. |
void | addOutgoingData | Queues plaintext data for encryption and transmission. |
void | addOutgoingData | Moves 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
socketThe 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
-
dataPointer to the encrypted bytes. -
lenNumber of bytes to feed.
{#addoutgoingdata}
addOutgoingData
void addOutgoingData(std::string_view data)
Queues plaintext data for encryption and transmission.
Parameters
dataString view of the plaintext payload.
{#addoutgoingdata-1}
addOutgoingData
void addOutgoingData(const char * data, size_t len)
Queues plaintext data for encryption and transmission.
Parameters
-
dataPointer to the plaintext bytes. -
lenNumber of bytes to queue.
{#addoutgoingdata-2}
addOutgoingData
void addOutgoingData(Buffer && data)
Moves plaintext data into the pending write buffer when possible.
Protected Attributes
| Return | Name | Description |
|---|---|---|
net::SSLSocket * | _socket | |
SSL * | _ssl | |
BIO * | _readBIO | The incoming buffer we write encrypted SSL data into. |
BIO * | _writeBIO | The outgoing buffer we write to the socket. |
std::vector< char > | _bufferOut | The outgoing payload to be encrypted and sent. |
std::string | _hostname | Expected 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
| Return | Name | Description |
|---|---|---|
void | handleError | |
void | flushReadBIO | |
void | flushWriteBIO |
{#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
| Return | Name | Description |
|---|---|---|
SSLContext | Creates a Context. | |
SSLContext | Creates a Context. | |
~SSLContext | Destroys the Context. | |
void | useCertificate | Sets the certificate to be used by the Context. |
void | addChainCertificate | Adds a certificate for certificate chain validation. |
void | addVerificationCertificate | Sets the private key to be used by the Context. |
SSL_CTX * | sslContext const inline | Returns the underlying OpenSSL SSL Context object. |
Usage | usage const inline | Returns whether the context is for use by a client or by a server and whether TLSv1 is required. |
bool | isForServerUse const inline | Returns true if the context is for use by a server. |
SSLContext::VerificationMode | verificationMode const inline | Returns the verification mode. |
void | enableSessionCache | 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. |
void | enableSessionCache | 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. |
bool | sessionCacheEnabled const | Returns true if the session cache is enabled. |
void | setSessionCacheSize | 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. |
size_t | getSessionCacheSize const | Returns the current maximum size of the server session cache. |
void | setSessionTimeout | 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. |
long | getSessionTimeout const | Returns the timeout (in seconds) of cached sessions on the server. |
void | flushSessionCache | Flushes the SSL session cache on the server. |
void | disableStatelessSessionResumption | Newer versions of OpenSSL support RFC 4507 tickets for stateless session resumption. |
void | setALPNProtocols | Set the ALPN protocols for negotiation. Protocols should be in preference order. Example: {"h2", "http/1.1"} |
SSLContext | Deleted constructor. | |
SSLContext | Deleted 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
| Return | Name | Description |
|---|---|---|
void | enableSNI static | 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. |
{#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
| Name | Description |
|---|---|
Usage | |
VerificationMode | |
Ptr |
{#usage-1}
Usage
enum Usage
| Value | Description |
|---|---|
CLIENT_USE | Context is used by a client. |
SERVER_USE | Context is used by a server. |
TLSV1_CLIENT_USE | Context is used by a client requiring TLSv1. |
TLSV1_SERVER_USE | Context is used by a server requiring TLSv2. |
{#verificationmode-1}
VerificationMode
enum VerificationMode
| Value | Description |
|---|---|
VERIFY_NONE | Server: The server will not send a client certificate request to the client, so the client will not send a certificate. |
VERIFY_RELAXED | Server: 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_STRICT | Server: If the client did not return a certificate, the TLS/SSL handshake is immediately terminated with a handshake failure alert. |
VERIFY_ONCE | Server: 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
| Return | Name | Description |
|---|---|---|
Usage | _usage | |
VerificationMode | _mode | |
SSL_CTX * | _sslContext | |
std::vector< unsigned char > | _alpnWire | Wire-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
| Return | Name | Description |
|---|---|---|
void | createSSLContext | Create 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
| Return | Name | Description |
|---|---|---|
ThreadSignal< void(VerificationErrorDetails &)> | ServerVerificationError | Fired whenever a certificate verification error is detected by the server during a handshake. |
ThreadSignal< void(VerificationErrorDetails &)> | ClientVerificationError | Fired whenever a certificate verification error is detected by the client during a handshake. |
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. |
{#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
| Return | Name | Description |
|---|---|---|
void | initializeServer | Initializes the server side of the SSLManager server-side SSLContext. |
void | initializeClient | Initializes the client side of the SSLManager with a default client-side SSLContext. |
SSLContext::Ptr | defaultServerContext | Returns the default context used by the server if initialized. |
SSLContext::Ptr | defaultClientContext | Returns the default context used by the client if initialized. |
void | shutdown | Shuts 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
| Return | Name | Description |
|---|---|---|
SSLManager & | instance static | Returns the instance of the SSLManager singleton. |
void | destroy static | Shuts down and destroys the SSLManager singleton instance. |
void | initNoVerifyClient static | Initializes a default no-verify client context that's useful for testing. |
void | initNoVerifyServer static | 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. |
{#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
| Return | Name | Description |
|---|---|---|
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
| Return | Name | Description |
|---|---|---|
SSLManager | Creates the SSLManager. | |
~SSLManager | Destroys the SSLManager. | |
SSLManager | Deleted constructor. | |
SSLManager | Deleted 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
| Return | Name | Description |
|---|---|---|
int | verifyCallback static | 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. |
{#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
| Return | Name | Description |
|---|---|---|
SSL_SESSION * | sslSession const | Returns the stored OpenSSL SSL_SESSION object. |
SSLSession | Creates a new SSLSession wrapping the given OpenSSL session object. | |
~SSLSession | Destroys the Session. | |
SSLSession | Constructs an empty SSLSession with a null session pointer. | |
SSLSession | Deleted constructor. | |
SSLSession | Deleted 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
ptrThe 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
| Return | Name | Description |
|---|---|---|
SSL_SESSION * | _ptr |
{#_ptr}
_ptr
SSL_SESSION * _ptr
Public Types
| Name | Description |
|---|---|
Ptr |
{#ptr-7}
Ptr
std::shared_ptr< SSLSession > Ptr()
{#sslsocket}
SSLSocket
#include <icy/net/sslsocket.h>
Inherits:
TCPSocket
SSL socket implementation.
Public Methods
| Return | Name | Description |
|---|---|---|
SSLSocket | Constructs an SSLSocket that acquires its context from SSLManager on first use. | |
SSLSocket | Constructs an SSLSocket with an explicit SSL context. | |
SSLSocket | Constructs an SSLSocket with an explicit context and a prior session for resumption. | |
void | connect virtual | Initialize the SSLSocket with the given SSLContext. |
void | connect virtual | Resolves host and initiates a secure connection. |
void | bind virtual | Binds the socket to address for server-side use. Throws std::logic_error if the context is not a server context. |
void | listen virtual | Starts listening for incoming connections. Throws std::logic_error if the context is not a server context. |
bool | shutdown virtual | Shuts down the connection by attempting an orderly SSL shutdown, then actually shutting down the TCP connection. |
void | close virtual | Closes the socket forcefully. |
ssize_t | send virtual | Encrypts and sends len bytes to the connected peer. |
ssize_t | sendOwned virtual | Sends an owned payload buffer to the connected peer. |
ssize_t | send virtual | Encrypts and sends len bytes, ignoring peerAddress (TCP is connected). |
ssize_t | sendOwned virtual | |
void | setHostname | Set the expected peer hostname for certificate verification and SNI. Must be called before connect() to enable hostname verification. |
void | useContext | Use the given SSL context for this socket. |
SSLContext::Ptr | context const | Returns the SSL context used for this socket. |
void | useSession | Sets the SSL session to use for the next connection. Setting a previously saved Session object is necessary to enable session caching. |
SSLSession::Ptr | currentSession | Returns the SSL session of the current connection, for reuse in a future connection (if session caching is enabled). |
bool | sessionWasReused | Returns true if a reused session was negotiated during the handshake. |
int | available const | Returns the number of bytes available from the SSL buffer for immediate reading. |
X509 * | peerCertificate const | Returns the peer's X.509 certificate, or nullptr if no certificate was presented. |
net::TransportType | transport virtual const | Returns the SSLTCP transport protocol identifier. |
void | acceptConnection virtual | Accepts a pending client connection, initializes the server-side SSL context on the new socket, and fires the AcceptConnection signal. |
void | onConnect virtual | Called when the TCP connection is established; starts reading and initiates the client-side SSL handshake. |
void | onRead virtual | Feeds 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
loopEvent 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
-
sslContextThe SSL context to use for this connection. -
loopEvent 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
-
sslContextThe SSL context to use for this connection. -
sessionA previously saved session to attempt resumption with. -
loopEvent 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
peerAddressThe 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
-
hostHostname or IP address string. -
portDestination 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
-
addressLocal address to bind to. -
flagsOptional 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
backlogMaximum 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
-
dataPointer to the plaintext payload. -
lenNumber of bytes to send. -
flagsReserved; 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
-
dataPointer to the plaintext payload. -
lenNumber of bytes to send. -
peerAddressIgnored for SSL/TCP; present for interface conformance. -
flagsReserved; 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
-
dataPointer to the encrypted bytes. -
lenNumber of bytes received.
Protected Attributes
| Return | Name | Description |
|---|---|---|
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
| Name | Description |
|---|---|
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 >,SocketSubclassed by:SSLSocket
TCP socket implementation.
Public Attributes
| Return | Name | Description |
|---|---|---|
LocalSignal< void(const net::TCPSocket::Ptr &)> | AcceptConnection | Fired 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
| Return | Name | Description |
|---|---|---|
TCPSocket | Constructs the TCPSocket and initializes the underlying libuv handle. | |
TCPSocket | Deleted constructor. | |
TCPSocket | Deleted constructor. | |
bool | shutdown virtual | Sends a TCP shutdown request; the socket closes after the peer acknowledges. |
void | close virtual | Closes the socket immediately, releasing all associated resources. |
void | connect virtual | Connects to peerAddress using a libuv connect request. On success, calls onConnect(); on failure, calls setUVError(). |
void | connect virtual | Resolves host via DNS (or maps "localhost"), then connects. |
ssize_t | send virtual | Writes len bytes to the connected peer. |
ssize_t | sendOwned virtual | Sends an owned payload buffer to the connected peer. |
ssize_t | send virtual | Writes len bytes; peerAddress is ignored for TCP (connected stream). |
ssize_t | sendOwned virtual | |
void | bind virtual | Binds the socket to address. Resets and reinitializes the handle if the address family changes. |
void | listen virtual | Starts listening for incoming connections with the given backlog. |
void | acceptConnection virtual | Accepts the next pending client connection and fires AcceptConnection. |
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. |
bool | setNoDelay | Enables or disables TCP_NODELAY (Nagle's algorithm). |
bool | setKeepAlive | Enables or disables TCP keep-alive probes. |
bool | setSimultaneousAccepts | Enables or disables simultaneous accepts on Windows. No-op and returns false on non-Windows platforms. |
void | setMode | Sets the socket mode (ServerSide or ClientSide). |
SocketMode | mode const | Returns the current socket mode. |
void | setError virtual | Sets 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 const | Returns the current socket error, if any. |
bool | closed virtual const | Returns true if the native socket handle is closed. |
net::Address | address virtual const | Returns the IP address and port number of the socket. A wildcard address is returned if the socket is not connected. |
net::Address | peerAddress virtual const | Returns the IP address and port number of the peer socket. A wildcard address is returned if the socket is not connected. |
net::TransportType | transport virtual const | Returns the TCP transport protocol. |
uv::Loop * | loop virtual const | Returns the event loop associated with this socket. |
void | onConnect virtual | Called by the stream layer when the TCP connection is established. |
void | onRead virtual | Called by the stream layer with raw received bytes; wraps them in a MutableBuffer. |
void | onRecv virtual | Dispatches a received buffer to all socket adapters via onSocketRecv. |
void | onError virtual | Dispatches the error to adapters and closes the socket. |
void | onClose virtual | Dispatches the close event to all socket adapters. |
{#tcpsocket-1}
TCPSocket
TCPSocket(uv::Loop * loop)
Constructs the TCPSocket and initializes the underlying libuv handle.
Parameters
loopEvent 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
peerAddressThe 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
-
hostHostname or IP address string. -
portDestination 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
-
dataPointer to the data to send. -
lenNumber of bytes to send. -
flagsReserved; 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
-
dataPointer to the data to send. -
lenNumber of bytes to send. -
peerAddressIgnored; present for interface conformance. -
flagsReserved; 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
-
addressLocal address to bind to. -
flagsOptional 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
backlogMaximum 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
enabletrue 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
-
enabletrue to enable keep-alive. -
delayInitial 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
enabletrue 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
modeThe 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
errThe 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
-
dataPointer to received bytes. -
lenNumber of bytes received.
{#onrecv}
onRecv
virtual
virtual void onRecv(const MutableBuffer & buf)
Dispatches a received buffer to all socket adapters via onSocketRecv.
Parameters
bufThe 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
errorThe error that occurred.
{#onclose-1}
onClose
virtual
virtual void onClose()
Dispatches the close event to all socket adapters.
Protected Attributes
| Return | Name | Description |
|---|---|---|
SocketMode | _mode | |
net::Address | _peerAddress | Cached 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
| Return | Name | Description |
|---|---|---|
void | init virtual | Initializes the underlying socket context. |
void | reset virtual | Resets 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
| Name | Description |
|---|---|
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
| Return | Name | Description |
|---|---|---|
Transaction inline | Constructs a Transaction on the given socket targeting peerAddress. | |
bool | send virtual inline | 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. |
void | cancel virtual inline | Cancels the transaction and stops the timeout timer. |
void | dispose virtual inline | Stops the timer and unregisters callbacks. |
Address | peerAddress const inline | Returns 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
-
socketThe socket to send/receive packets on. -
peerAddressThe remote address for the request and response matching. -
timeoutMilliseconds to wait for a response before failing. -
retriesNumber 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
| Return | Name | Description |
|---|---|---|
Address | _peerAddress |
{#_peeraddress-1}
_peerAddress
Address _peerAddress
Protected Methods
| Return | Name | Description |
|---|---|---|
bool | onPacket virtual inline | Checks whether packet is a matching response for the pending request. If it matches, the transaction completes; socket data propagation stops. |
void | onResponse virtual inline | Called when a confirmed response is received; emits the response via PacketSignal. |
bool | checkResponse virtual inline | Returns 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
packetThe 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
packetThe candidate response packet.
Returns
true if the packet satisfies the response criteria.
Public Types
| Name | Description |
|---|---|
BaseT |
{#baset}
BaseT
PacketTransaction< PacketT > BaseT()
{#udpsocket}
UDPSocket
#include <icy/net/udpsocket.h>
Inherits:
Handle< uv_udp_t >,Socket
UDP socket implementation.
Public Methods
| Return | Name | Description |
|---|---|---|
UDPSocket | Constructs the UDPSocket and initializes the underlying libuv handle. | |
UDPSocket | Deleted constructor. | |
UDPSocket | Deleted constructor. | |
void | connect virtual | Records the peer address and fires the Connect signal to mimic TCP socket behaviour. UDP is connectionless; this call does not send any data. |
void | connect virtual | Resolves host via DNS (or maps "localhost"), then calls connect(Address). |
void | close virtual | Stops receiving and closes the underlying UDP handle. |
void | bind virtual | Binds the socket to address and starts the receive loop. |
ssize_t | send virtual | Sends len bytes to the previously connected peer address. Returns -1 if no peer address has been set. |
ssize_t | sendOwned virtual | Sends an owned payload buffer to the connected peer. |
ssize_t | send virtual | Sends len bytes to peerAddress. Returns -1 if the socket is uninitialized or the address is not authorized. |
ssize_t | sendOwned virtual | |
bool | setBroadcast | Enables or disables UDP broadcast. |
bool | setMulticastLoop | Enables or disables IP multicast loopback. |
bool | setMulticastTTL | Sets the IP multicast time-to-live (hop limit). |
net::Address | address virtual const | Returns the locally bound address, or a wildcard address if unbound. |
net::Address | peerAddress virtual const | Returns the connected peer address set by connect(), or a wildcard address if unconnected. |
net::TransportType | transport virtual const | Returns the UDP transport protocol. |
void | setError virtual | Sets the socket error and triggers close. |
const icy::Error & | error virtual const | Returns the current socket error, if any. |
bool | closed virtual const | Returns true if the native socket handle is closed. |
uv::Loop * | loop virtual const | Returns the event loop associated with this socket. |
void | onRecv virtual | Dispatches 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
loopEvent 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
peerAddressThe 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
-
hostHostname or IP address string. -
portDestination 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
-
addressLocal address to bind to. -
flagsOptional 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
-
dataPointer to the data to send. -
lenNumber of bytes to send. -
flagsReserved; 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
-
dataPointer to the data to send. -
lenNumber of bytes to send. -
peerAddressDestination address; must match the connected peer if one is set. -
flagsReserved; 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
flagtrue to enable broadcast.
Returns
true if the option was set successfully.
{#setmulticastloop}
setMulticastLoop
bool setMulticastLoop(bool flag)
Enables or disables IP multicast loopback.
Parameters
flagtrue 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
ttlValue in the range [1, 255].
Returns
true if the option was set successfully.
Exceptions
std::invalid_argumentifttlis 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
errThe 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
-
bufBuffer containing the received datagram payload. -
addressAddress of the sender.
Protected Attributes
| Return | Name | Description |
|---|---|---|
net::Address | _peer | |
Buffer | _buffer |
{#_peer}
_peer
net::Address _peer
{#_buffer}
_buffer
Buffer _buffer
Protected Methods
| Return | Name | Description |
|---|---|---|
void | init virtual | Initializes the underlying socket context. |
void | reset virtual | Resets the socket context for reuse. |
void | onError virtual | Called by [setError()](#seterror-3) after the error state has been updated. |
void | onClose virtual | Called by [close()](#close-16) after the context has been released. |
bool | recvStart virtual | |
bool | recvStop 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
errorThe 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
| Name | Description |
|---|---|
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
| Return | Name | Description |
|---|---|---|
VerificationErrorDetails | Creates the VerificationErrorDetails. _ignoreError is per default set to false. | |
~VerificationErrorDetails | Destroys the VerificationErrorDetails. | |
const crypto::X509Certificate & | certificate const inline | Returns the certificate that caused the error. |
int | errorDepth const inline | Returns the position of the certificate in the certificate chain. |
int | errorNumber const inline | Returns the id of the error. |
const std::string & | errorMessage const inline | Returns the textual presentation of the errorNumber. |
void | setIgnoreError inline | setIgnoreError to true, if a verification error is judged non-fatal by the user. |
bool | getIgnoreError const inline | returns 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
| Return | Name | Description |
|---|---|---|
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
| Return | Name | Description |
|---|---|---|
Socket::Ptr | socket | The source socket. |
Address | peerAddress | The 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
| Return | Name | Description |
|---|---|---|
PacketInfo inline | Constructs PacketInfo with the originating socket and peer address. | |
PacketInfo inline | Copy constructor. | |
std::unique_ptr< IPacketInfo > | clone virtual const inline | Returns 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
-
socketShared pointer to the socket that received the packet. -
peerAddressAddress of the remote peer that sent the packet.
{#packetinfo-2}
PacketInfo
inline
inline PacketInfo(const PacketInfo & r)
Copy constructor.
Parameters
rSource PacketInfo to copy from.
{#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
| Return | Name | Description |
|---|---|---|
auto | resolve inline | Resolves 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
-
hostHostname or IP address string to resolve. -
portPort number to associate with the resolved address. -
callbackInvoked with (status, resolved Address); status is 0 on success. -
loopEvent loop to use; defaults to the default loop.
Returns
A request handle whose lifetime controls the in-flight DNS query.