Overview / Networking

network

TCP, UDP, the in-house ETL-RUDP reliable protocol over UDP, a completion-based event loop and an encrypted channel.

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

network_inc.hpp

#include <ethereal/cpp/network/network_inc.hpp>

Aggregate entry point of the Network module.

TCP and UDP sockets, with the shared layer kept apart and each protocol in its own file, so a caller that needs one does not load the other.

No header of this module includes <winsock2.h>. The handle is an opaque integer and the whole system API lives inside the .cpp files. The reason is at the top of net_common.hpp: including Winsock after <windows.h> breaks the build with dozens of redefinitions, and the defense here is structural.

What to use:

  • Ethereal::Network::CAddress: name and address resolution, IPv4 and IPv6.
  • TCP and UDP: see tcp.hpp and udp.hpp.

Including this header brings the whole module.

eventloop.hpp

#include <ethereal/cpp/network/eventloop.hpp>

Completion based event loop of the Network module, over IOCP, epoll or poll.

Up to here the Network module blocks: Accept waits for a connection, Receive waits for a byte. That serves clients and small servers, and stops serving with many connections: a thread per connection does not go past a few thousand before the cost of context switches and stacks dominates. This file is the way out: thousands of connections over a few threads.

1. Completion, not readiness. There are two models and they are not interchangeable. Readiness ("tell me when I can read, and I read") is the model of epoll and kqueue. Completion ("read for me, and tell me when it is done") is the model of Windows IOCP and Linux io_uring. This class exposes completion. The reason is Windows: IOCP has no readiness mode, and emulating it there would fall back to WSAPoll, which walks the whole handle list on every call and undoes the very scale this is for. The other way around, emulating completion over epoll, is cheap: wait for readiness, do the operation, deliver the result. That is what this class does on Linux, and the same design Boost.Asio has used for twenty years. The cost of emulating is one extra system call per operation on POSIX. The cost of not emulating would be a Windows that does not scale, where the library runs the most.

2. Implementations:

  • Windows: native IOCP. GetQueuedCompletionStatus on a queue fed by the kernel, and several threads can wait on the same queue without contention.
  • Linux: epoll with EPOLLONESHOT. The one shot flag is what makes the loop safe with several threads: without it, two threads wake up for the same handle and both call recv for the same operation. After each event the handle is rearmed on purpose.
  • Others: poll. Correct and portable, and walks the whole list every round, O(n) per call. Serves macOS and any POSIX until kqueue comes in. CEventLoop::BackendName says which one is in use, so it is never a surprise in production.

3. The caller owns the buffer. An operation keeps the pointer it was given, and the system writes to it later, possibly on another thread. The buffer must stay alive and untouched until the completion arrives. A buffer on the caller's stack, or a vector that grew in the meantime, is freed memory being written by the kernel, and the damage shows up far from the cause. The alternative would be for the loop to copy everything: one copy per operation in exchange for one class of error, and in a component whose reason to exist is performance that trade does not pay. The contract is explicit, and Unregister exists to make the end safe.

4. The end of a connection, where this kind of code usually breaks. Closing a handle with pending operations leaves the kernel writing to a buffer the caller already considers free. Unregister solves it: it cancels whatever is pending and only returns after every completion of that handle was delivered, each one marked with SCompletion::bAborted. When it returns, no buffer of that handle is in use and closing is safe. Calling Unregister from inside a completion of the same handle would wait for itself. In that case it marks and returns, and the wait ends when the current completion leaves.

5. Timers, asynchronous connect, posts and the closing that does not wait came with stage H3 of the Http module, whose asynchronous client runs on this loop (decision L2 of AI-03):

  • PostConnect creates the socket, registers it and connects without blocking (ConnectEx on Windows).
  • PostTimer delivers a completion after a delay, and CancelTimer removes it before that.
  • Post delivers a completion on a thread of the loop as soon as possible: the way another thread hands work to the loop.
  • CloseAsync cancels what is pending and closes the handle after the last completion, without waiting. Unlike Unregister, it is safe from inside a completion of the same handle, and it never delivers a completion on the calling thread. 6. Left out: io_uring and kqueue. Both come in without changing this interface, which is why it is completion based.
enum

EOperation

Ethereal::Network#
C++
enum class EOperation : ETL_UINT8
{
    /// @brief  Connection accept. The new handle comes in
    ///             SCompletion::AcceptedSocket.
    eAccept = 0,

    /// @brief  Receive on a stream socket.
    eReceive,

    /// @brief  Send on a stream socket.
    eSend,

    /// @brief  Datagram receive. The source comes in SCompletion::Peer.
    eReceiveFrom,

    /// @brief  Datagram send.
    eSendTo,

    /// @brief  Connection of a socket created by CEventLoop::PostConnect. SCompletion::Net
    ///             says whether it connected.
    eConnect,

    /// @brief  A timer of CEventLoop::PostTimer expired. SCompletion::TimerId says which,
    ///             and SCompletion::Handle is INVALID_SOCKET_HANDLE.
    eTimer,

    /// @brief  A CEventLoop::Post. SCompletion::Handle is INVALID_SOCKET_HANDLE.
    ePosted
};

What a completion was doing.

function

OperationToString

Ethereal::Network#
const char * OperationToString( const EOperation eOperation ) noexcept;

Readable name of an EOperation.

struct

SCompletion

Ethereal::Network#
C++
ETL_BEGIN_INTENDED_PADDING
struct   SCompletion   final
{
    /// @brief  What finished.
    EOperation        eOperation = EOperation::eReceive;

    /// @brief  The handle the operation was requested on.
    SocketHandle    Handle = INVALID_SOCKET_HANDLE;

    /// @brief  The pointer the caller passed when requesting the operation.
    ///
    /// @details  The loop does not look at it nor free it: it is the only link between
    ///            the operation and the caller's object. One std::function per
    ///            operation would be more comfortable and would allocate on every
    ///            request.
    void *            pUserData = nullptr;

    /// @brief  Bytes transferred.
    ///
    /// @details  Zero on a stream receive means the other side closed in an orderly
    ///            way. It is the same signal as the blocking recv, not an error.
    std::size_t        uTransferred = 0;

    /// @brief  System result. ENetError::eOk on success.
    SNetStatus        Net;

    /// @brief  The operation was cancelled, not completed.
    ///
    /// @details  Happens in CEventLoop::Unregister and in CEventLoop::Close. The buffer
    ///            was not touched, and from this completion on it is free.
    bool            bAborted = false;

    /// @brief  Only for EOperation::eAccept: the handle of the accepted connection.
    ///
    /// @warning  The receiver becomes its owner. Not closing it leaks one handle per
    ///               connection, the easiest leak to miss in a server.
    SocketHandle    AcceptedSocket = INVALID_SOCKET_HANDLE;

    /// @brief  For EOperation::eAccept and EOperation::eReceiveFrom: the other side.
    CAddress        Peer;

    /// @brief  For EOperation::eTimer: the id CEventLoop::PostTimer returned.
    /// @details  A timer cancelled too late (CancelTimer returned false) still completes,
    ///            and the id is how the caller tells it from the timer it armed after.
    ETL_UINT64        TimerId = 0;
};

An operation that finished.

No ETL_STRUCT_ALIGN: it is handed by reference on every completion, on the hottest path of this library.
alias

void

Ethereal::Network#
using CompletionFn = std::function< void( const SCompletion & ) >;
struct

SEventLoopConfig

Ethereal::Network#
C++
struct   SEventLoopConfig   final
{
    /// @brief  Completions collected per wait round.
    ///
    /// @details  Collecting in batches reduces system calls. A batch too large delays
    ///            the first completion of the next batch.
    ETL_UINT32 uBatchSize = 64;

    /// @brief  Handles the loop expects to track.
    ///
    /// @details  Only sizes internal structures. Going over it does not fail.
    ETL_UINT32 uExpectedHandles = 1024;
};

What can be tuned in the loop.

class

CEventLoop

Ethereal::Network#

Completion based event loop, over IOCP, epoll or poll.

class CEventLoop final

The usage is always the same: open, register handles, request operations, and call Run, from one thread or from several.

The class is safe for use from several threads: Run, PostReceive and the other requests can be called at the same time from different threads. It is the opposite of CRudpPeer, because here concurrency is the product, not an accident.
constructor

CEventLoop

#
CEventLoop();

Creates a closed loop.

constructor

CEventLoop

#
CEventLoop( CEventLoop && Other ) noexcept;

Takes the state of Other, which is left closed.

operator

operator=

#
CEventLoop & operator=( CEventLoop && Other ) noexcept;

Closes this loop and takes the state of Other.

function

Open

#
SNetStatus Open( const SEventLoopConfig & Config = SEventLoopConfig() );

Creates the loop.

function

Close

#
void Close();

Closes the loop, cancelling everything pending.

Every pending operation completes with SCompletion::bAborted, so the caller knows the buffers are free. The handles are not closed: they still belong to whoever registered them.

function

IsOpen

#
bool IsOpen() const noexcept;

Whether the loop is open.

function

BackendName

#
const char * BackendName() const noexcept;

Name of the implementation in use: "IOCP", "epoll" or "poll".

Exposed because the difference is large and silent. Finding out in production that the loop fell back to poll is expensive, asking first is free.

function

Register

#
SNetStatus Register( const SocketHandle Handle );

Starts tracking Handle.

The loop does not become the owner of the handle: closing it is still up to whoever created it, and only after Unregister.
function

Unregister

#
void Unregister( const SocketHandle Handle );

Stops tracking Handle, cancelling whatever is pending.

Blocks until every completion of that handle was delivered. When it returns, no buffer of that handle is in use and closing it is safe. See rule 4 in the file header.

function

SetHandler

#
void SetHandler( CompletionFn Handler );

Installs the function called on each completion.

Must be installed before any request. One for the whole loop, not one per operation: one per operation would allocate on every request, on the hottest path there is here.

function

PostAccept

#
SNetStatus PostAccept( const SocketHandle Listener, void * pUserData = nullptr );

Requests the accept of a connection on Listener.

function

PostReceive

#
SNetStatus PostReceive( const SocketHandle Handle, std::span< std::uint8_t > Buffer, void * pUserData = nullptr );

Requests a stream receive.

Buffer must stay alive until the completion. See rule 3.
function

PostSend

#
SNetStatus PostSend( const SocketHandle Handle, std::span< const std::uint8_t > Data, void * pUserData = nullptr );

Requests a stream send.

Data must stay alive and untouched until the completion.
function

PostReceiveFrom

#
SNetStatus PostReceiveFrom( const SocketHandle Handle, std::span< std::uint8_t > Buffer, void * pUserData = nullptr );

Requests the receive of a datagram.

function

PostSendTo

#
SNetStatus PostSendTo( const SocketHandle Handle, std::span< const std::uint8_t > Data, const CAddress & To, void * pUserData = nullptr );

Requests the send of a datagram.

function

PostConnect

#
SNetStatus PostConnect( const CAddress & To, SocketHandle & OutHandle, void * pUserData = nullptr );

Creates a TCP socket, registers it and starts connecting to To.

PostConnect The socket is non blocking, not inherited by child processes, and has TCP_NODELAY. The completion (EOperation::eConnect) says whether it connected. Windows uses ConnectEx. POSIX waits for the socket to become writable and reads SO_ERROR. The caller owns the handle from the call on, as with any registered handle: it ends with CloseAsync, or with Unregister and a close.

To
The destination.
OutHandle
Receives the socket. INVALID_SOCKET_HANDLE when the call fails, and then nothing is left open.
pUserData
Returned in the completion.
The status of the request. A connection refused later comes in the completion.
function

PostTimer

#
SNetStatus PostTimer( const ETL_UINT32 uDelayMs, void * pUserData, ETL_UINT64 & OutTimerId );

Delivers an EOperation::eTimer completion after uDelayMs.

PostTimer Any thread inside Run delivers it, once. The resolution is the one of the system wait (about a millisecond, about 16 ms on an idle Windows).

uDelayMs
The delay. Zero delivers at the next Run round.
pUserData
Returned in the completion.
OutTimerId
Receives the id, never zero. Also in SCompletion::TimerId.
The status. eNoBuffers when the memory ran out.
function

CancelTimer

#
bool CancelTimer( const ETL_UINT64 TimerId ) noexcept;

Removes a timer that has not been delivered.

CancelTimer

true when it was removed, and then no completion comes. false when it had already been taken for delivery (or never existed): the completion comes or came, and SCompletion::TimerId identifies it.
function

Post

#
SNetStatus Post( void * pUserData );

Delivers an EOperation::ePosted completion on a thread of the loop, as soon as one is free. Safe from any thread.

Post This is how another thread hands work to the loop without a lock shared with it: the completion runs where the rest of the work runs.

pUserData
Returned in the completion.
The status. eNoBuffers when the memory ran out.
function

CloseAsync

#
void CloseAsync( const SocketHandle Handle );

Cancels what is pending on Handle and closes it after the last completion.

CloseAsync Returns at once. The pending operations complete with SCompletion::bAborted on the threads of the loop, never on the calling thread, so it is safe from inside a completion of the same handle and under the caller's own locks. When the last one has been delivered, the loop closes the handle and forgets it. Handle must not be used after the call.

function

Run

#
std::size_t Run( const ETL_UINT32 uTimeoutMs = 0 );

Collects completions until the deadline ends.

Can be called from several threads at the same time. That is how the loop uses more than one core.

uTimeoutMs
How long to wait when nothing is ready. Zero returns at once.
How many completions were delivered.
function

Stop

#
void Stop();

Wakes every thread blocked in Run and makes it return.

Marks the loop as stopping: from then on Run returns without waiting. It is the orderly shutdown of a server.

function

IsStopping

#
bool IsStopping() const noexcept;

Whether Stop was called.

function

PendingOperations

#
std::size_t PendingOperations() const;

Operations requested and not yet completed.

function

RegisteredHandles

#
std::size_t RegisteredHandles() const;

Registered handles.

function

CompletionsDelivered

#
ETL_UINT64 CompletionsDelivered() const noexcept;

Total completions delivered since the loop was opened.

function

PendingTimers

#
std::size_t PendingTimers() const;

Timers armed and not yet delivered.

net_common.hpp

#include <ethereal/cpp/network/net_common.hpp>

Shared layer of the Network module: handle, error, subsystem and address.

Common to TCP and UDP. Nothing here is specific to one protocol. What is specific lives in tcp.hpp and udp.hpp, each with its own error enumeration.

The rules: 1. This header does not include <winsock2.h>, and no public header does. Including Winsock in a public header forces every consumer of Ethereal to load it, and in the right order: <windows.h> before <winsock2.h> pulls Winsock 1.1 and the build dies with dozens of redefinitions. It is the classic error of this module. The defense is structural: the handle is an opaque integer and the whole system API lives inside the .cpp files. (pch_base.h defines WIN32_LEAN_AND_MEAN, which keeps Winsock 1.1 out of <windows.h>. That makes the ground safe but does not replace the rule: a consumer that includes <windows.h> on its own, without the macro, would break again.) 2. Errors have two levels and both are kept. ENetError is the portable cause, comparable across systems. The raw system code comes along in SNetStatus::iOsCode, because translating into an enumeration always loses information, and what is lost is what is missing when someone has to diagnose a rare case in production. 3. A handle can be moved, never copied. A handle copied and closed twice closes a handle already reused by something else, on Windows typically a file opened by another part of the program. It is the same family as the double free that existed in this library's CDataChunk. 4. The subsystem is reference counted. On Windows, Winsock needs WSAStartup and WSACleanup in pairs. Each CSocket holds a reference, so the caller does not need to know about it, and calling Initialize once too often breaks nothing.

alias

SocketHandle

Ethereal::Network#
using SocketHandle = std::uintptr_t;

System socket handle, as an opaque integer.

On Windows SOCKET is a UINT_PTR and the invalid value is ~0. On POSIX it is an int and the invalid value is -1. Both fit here, and the conversion to the real type happens only inside the .cpp files (see rule 1 in the file header).

const

INVALID_SOCKET_HANDLE

Ethereal::Network#
constexpr SocketHandle INVALID_SOCKET_HANDLE = static_cast< SocketHandle >( ~static_cast< std::uintptr_t >( 0 ) );

Value that means "no socket".

enum

ENetError

Ethereal::Network#
C++
enum class ENetError : ETL_UINT8
{
    /// @brief  No error.
    eOk = 0,

    /// @brief  The operation could not complete now, on a non blocking socket.
    ///             This is not a failure: it is the normal answer for "no data yet" or
    ///             "the send buffer is full".
    eWouldBlock,

    /// @brief  The configured time ran out before the operation completed.
    eTimedOut,

    /// @brief  Interrupted by a signal before transferring anything. Retrying the
    ///             call is the correct behavior.
    eInterrupted,

    /// @brief  Nothing is listening at the destination.
    eConnectionRefused,

    /// @brief  The other side dropped the connection abruptly.
    eConnectionReset,

    /// @brief  The connection was aborted locally, typically on a timeout.
    eConnectionAborted,

    /// @brief  The operation needs an established connection and there is none.
    eNotConnected,

    /// @brief  The socket is already connected.
    eAlreadyConnected,

    /// @brief  The address and port are already in use.
    eAddressInUse,

    /// @brief  The requested address does not belong to this machine.
    eAddressNotAvailable,

    /// @brief  The network interface is down.
    eNetworkDown,

    /// @brief  There is no route to the destination network.
    eNetworkUnreachable,

    /// @brief  There is no route to the destination host.
    eHostUnreachable,

    /// @brief  The datagram is larger than the path accepts. UDP only.
    eMessageTooLarge,

    /// @brief  Invalid argument: closed socket, malformed address, zero size where
    ///             zero is not accepted.
    eInvalidArgument,

    /// @brief  The system ran out of buffers or handles.
    eNoBuffers,

    /// @brief  The socket was already shut down for this direction.
    eShutdown,

    /// @brief  Permission denied: privileged port, or system policy.
    eAccessDenied,

    /// @brief  The network subsystem was not initialized. Windows only.
    eNotInitialized,

    /// @brief  The name could not be resolved into an address.
    eResolveFailed,

    /// @brief  The system returned a code this translation does not know.
    ///
    /// @details  SNetStatus::iOsCode still carries the exact number, and that number
    ///            identifies the case.
    eUnknown,

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

Portable cause of a network failure.

The names describe the cause, not the code the system returned. The same ENetError::eConnectionReset comes from WSAECONNRESET on Windows and from ECONNRESET on POSIX. Callers that need the exact number have SNetStatus::iOsCode.

struct

SNetStatus

Ethereal::Network#
C++
struct   SNetStatus   final
{
    /// @brief  Portable cause.
    ENetError eError = ENetError::eOk;

    /// @brief  Exact code returned by the system: WSAGetLastError on Windows, errno
    ///             on POSIX. Zero when there was no error.
    ///
    /// @details  Kept because the translation into ENetError always loses
    ///            information, and that information is what is missing when someone
    ///            has to diagnose a rare case at a customer.
    ETL_INT32 iOsCode = 0;


    /// @brief  Whether the operation succeeded.
    ///
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT        { return eError == ENetError::eOk; }

    /// @brief  Whether the operation simply could not happen yet, without failing.
    ///
    ETL_API_NOIGN    bool IsRetryable() const ETL_NOEXCEPT
    {
        return eError == ENetError::eWouldBlock || eError == ENetError::eInterrupted;
    }

    /// @brief  Same as IsOk.
    ///
    ETL_API_NOIGN    explicit operator bool() const ETL_NOEXCEPT    { return IsOk(); }
};

Result of a network operation: the portable cause and the raw system code.

No ETL_STRUCT_ALIGN: a value type, returned by every call. See the note on Ethereal::Network::STcpResult.
function

NetErrorToString

Ethereal::Network#
const char * NetErrorToString( const ENetError eError ) noexcept;

Readable name of an ENetError, for logs and diagnostics.

function

OsErrorToString

Ethereal::Network#
std::string OsErrorToString( const ETL_INT32 iOsCode );

Description of the failure given by the operating system itself.

It is the system message for iOsCode, which usually says more than the enumeration.

iOsCode
Raw system code.
The message, or an empty string when there is no error.
function

Initialize

Ethereal::Network#
SNetStatus Initialize();

Prepares the network subsystem of the operating system.

On Windows it calls WSAStartup. On POSIX there is nothing to do and the call only counts the reference. Reference counted, so calling it many times is safe as long as each call has its Shutdown.

The sockets of this library call it on their own. It is exposed for callers that prefer to pay the cost once, at program start, instead of on the first connection.

function

Shutdown

Ethereal::Network#
void Shutdown() noexcept;

Releases one reference to the subsystem, shutting it down on the last one.

function

CloseSocket

Ethereal::Network#
void CloseSocket( const SocketHandle Handle ) noexcept;

Closes a raw socket handle.

The classes of this module close their own handles. This is for the handles that arrive loose. The one in Ethereal::Network::SCompletion::AcceptedSocket, handed out by the event loop, is the case that exists today.

Without this, the caller would own that handle with no way to close it: one leak per accepted connection, the kind of leak that only shows when the server runs out of process handles.

Handle
The handle. INVALID_SOCKET_HANDLE is ignored.
enum

EAddressFamily

Ethereal::Network#
C++
enum class EAddressFamily : ETL_UINT8
{
    /// @brief  Not resolved.
    eNone = 0,

    /// @brief  IPv4.
    eIPv4,

    /// @brief  IPv6.
    eIPv6
};

Address family.

class

CAddress

Ethereal::Network#

A destination: address and port, IPv4 or IPv6.

class CAddress final

IPv6 is not optional. A new library that only speaks IPv4 is born with a limit that cannot be removed later without touching every signature that carries an address.

Name resolution uses getaddrinfo, the portable way and the only one that returns both families. gethostbyname is obsolete, not thread safe, and only speaks IPv4.

Not guaranteed to be thread safe. Copying is free, it is just a value.
constructor

CAddress

#
CAddress() noexcept;

Creates an unresolved address.

function

Resolve

#
static SNetStatus Resolve( std::string_view Host, const ETL_UINT16 uPort, CAddress & OutAddress, const EAddressFamily ePreferred = EAddressFamily::eNone );

Resolves Host and uPort into an address.

Accepts a name ("example.com"), IPv4 text ("192.168.0.1") and IPv6 text ("::1", "fe80::1"). When the name resolves to several addresses, the first one returned by the system is chosen. Use ResolveAll to see them all and decide.

Host
Name or address text.
uPort
Port.
OutAddress
Receives the address.
ePreferred
Wanted family. eNone accepts either.
The status. eResolveFailed when nothing was found.
Resolving a name can block for seconds: it is a network query. Resolving an address given as text makes no query.
function

ResolveAll

#
static SNetStatus ResolveAll( std::string_view Host, const ETL_UINT16 uPort, std::vector< CAddress > & OutAddresses, const EAddressFamily ePreferred = EAddressFamily::eNone );

All addresses for Host, in the order the system returned them.

The order matters: the system already picks it by RFC 6724, taking into account which families this machine can really use. Walking the list in order and trying each one is what makes a client work on an IPv6 only network and on an IPv4 only network without changing a line.

Host
Name or address text.
uPort
Port.
OutAddresses
Receives the addresses. Cleared first.
ePreferred
Wanted family. eNone accepts either.
The status. eResolveFailed when nothing was found.
function

Local

#
static CAddress Local( const ETL_UINT16 uPort, const bool bAnyInterface = false, const EAddressFamily eFamily = EAddressFamily::eIPv4 ) noexcept;

Local listening address for uPort.

uPort
Port.
bAnyInterface
true listens on every interface. false listens only on loopback (127.0.0.1 or ::1), which is what an internal service should do to avoid being exposed to the network by accident.
eFamily
Family of the address.
The address.
function

IsValid

#
bool IsValid() const noexcept;

Whether the address was resolved.

function

Family

#
EAddressFamily Family() const noexcept;

Family of the address. eNone when it was not resolved.

function

Port

#
ETL_UINT16 Port() const noexcept;

Port, in host order.

function

Ip

#
std::string Ip() const;

Only the address, without the port: "192.168.0.1", "::1".

function

ToString

#
std::string ToString() const;

Address and port together, in the usual form.

IPv6 is written in brackets ("[::1]:8080"), because without them the colon of the port is confused with the colons of the address. It is the RFC 3986 form, and the one everybody expects to see in a log.

operator

operator==

#
bool operator==( const CAddress & Other ) const noexcept;

Compares family, address and port, field by field.

operator

operator!=

#
bool operator!=( const CAddress & Other ) const noexcept;

Negation of operator==.

function

NativeData

#
const void * NativeData() const noexcept;

Pointer to the stored sockaddr.

Exists so the .cpp files of this module can pass the address to the system calls. The real type is not visible here on purpose (see rule 1 in the file header).
function

NativeData

#
void * NativeData() noexcept;

Pointer to the stored sockaddr, writable.

function

NativeSize

#
std::size_t NativeSize() const noexcept;

Size of the stored sockaddr.

function

SetNativeSize

#
void SetNativeSize( const std::size_t uSize ) noexcept;

Records the size filled in by a system call.

rudp.hpp

#include <ethereal/cpp/network/rudp.hpp>

ETL-RUDP, reliable delivery over UDP, protocol version 1.

Written from scratch. The techniques are public and documented for decades, but no line comes from SLikeNet, RakNet or any other code base: both are licensed with attribution clauses, and this library is sold.

This block is the specification, and it comes before the code on purpose. Once two programs speak a wire format, it cannot change without breaking one of them. It includes fields the implementation does not use yet, reserved now so that using them later is not a break.

1. Every datagram starts with the same 8 byte header: 0..1 signature, 0xE7 0x4C 2 protocol version (1) 3 datagram type 4..7 connection id, 32 bits little-endian

The signature exists to discard cheaply. An open UDP port gets scans, stray packets of other protocols and garbage. Checking two bytes first avoids spending work on them.

The connection id is drawn by the server in the handshake and is not predictable. It does two jobs: it tells a reconnection from the same address and port apart from an old connection that has not died yet, and it forces anyone who wants to inject a packet into someone else's conversation to guess 32 bits.

2. Datagram types: 0x01 REQUEST client -> server 0x02 CHALLENGE server -> client 0x03 RESPONSE client -> server 0x04 ACCEPTED server -> client 0x05 REJECTED server -> client 0x06 DISCONNECT either direction 0x07 DATA either direction 0x08 PING either direction 0x09 PONG reply to a ping

3. The handshake has four steps: client server | --- REQUEST (version, nonce) ---> | stores nothing | <-- CHALLENGE (cookie) ---------- | cookie = hash(secret, ip, port, epoch) | --- RESPONSE (cookie back) -----> | checks the cookie, only then allocates | <-- ACCEPTED (connection id) ---- |

Three steps would be enough to connect. The fourth exists for one reason: the server cannot allocate state because of a single packet. The UDP source address is not verified, so an attacker forges thousands of addresses, sends one request from each, and the server ends up with thousands of half open connections from machines that do not exist.

The cookie is derived from the source address and from a secret only the server knows. Whoever is not really at that address does not receive the challenge and cannot send it back. The server stores nothing between challenge and response: the cookie itself is the memory. Same reasoning as the TCP SYN cookies.

The epoch in the cookie is a counter that moves from time to time. Cookies of the current and of the previous epoch are accepted, older ones are not. That gives the challenge a validity without storing when it was issued.

4. Data datagram: 8..9 sequence of this datagram, 16 bits 10..11 last sequence received from the other side, 16 bits 12..15 bit map of the 32 sequences before that one 16.. one or more message blocks, up to the end

The sequence belongs to the datagram, not to the message, and is only used for acknowledgement.

The acknowledgement is a bit map, not a cumulative number. In UDP packets are lost out of order: receiving 5 and 7 without 6 is routine. A cumulative number could only say "received up to 5" and 7 would be lost from view. The map acknowledges 33 datagrams at once, and since every new datagram repeats the map, losing an acknowledgement packet costs no retransmission: the next one carries the same information.

Bit N of the map is sequence (last - 1 - N).

The sequence wraps at 65536, and comparing with '<' is wrong: right after the wrap, 0 is newer than 65535. The correct comparison uses the signed difference, in SequenceGreaterThan.

5. Message block: 0 flags bits 0..2 delivery mode (EDelivery) bit 3 fragmented message bits 4..7 reserved, must be zero 1 channel 2..3 message id, 16 bits [if fragmented] 4..5 fragment group id, 16 bits 6..7 index of this fragment, 16 bits 8..9 total fragments, 16 bits n..n+1 payload length, 16 bits ... payload

The message id is present in every mode, including the unreliable one, where it is not used. It costs 2 bytes per message. A variable size header per mode would save those bytes and complicate the parser on the hottest path of the protocol. The choice is simplicity, and it is written here so it can be reviewed with numbers in hand.

Several messages fit in one datagram. That makes twenty small updates per frame cheap: one syscall instead of twenty, and one 16 byte header instead of twenty.

6. Delivery modes: 0 UNRELIABLE send and forget. Can vanish, arrive out of order or twice. 1 UNRELIABLE SEQUENCED send and forget, but the receiver drops anything older than what it already delivered. For state that is replaced: position, health, score. 2 RELIABLE retransmits until acknowledged. Arrives, order not guaranteed. 3 RELIABLE ORDERED retransmits and delivers in order. What arrives early waits for what is missing. 4 RELIABLE SEQUENCED retransmits and delivers only the newest. An old value that finally arrived no longer matters.

Order is per channel. Without that, an ordered file transfer holds the whole conversation behind it, the classic head of line blocking. Separate channels are separate queues.

7. Fragmentation: a message larger than the useful payload of a datagram is split into fragments, which are always treated as reliable. With one missing the whole message does not exist, and retransmitting what is missing is cheaper than sending everything again.

The receiver keeps the fragments of a group until it is complete. There is a ceiling of open groups and a deadline for each one, otherwise a malicious peer sends fragment 1 of 65535 different groups and the receiver keeps them all.

8. Retransmission: a reliable datagram is kept until its acknowledgement arrives. If the deadline passes first, the reliable content it carried is sent again in a new datagram, with a new sequence. The sequence identifies the datagram, and reusing it would confuse the acknowledgement.

The deadline follows RFC 6298: a mean of the round trip time and its variation are kept, and the deadline is 'mean + 4 x variation', clamped to a minimum and a maximum. A fixed deadline does not work: 100 ms is too short on a satellite link and too long on a local network, and being wrong either way is expensive.

The retransmission uses a new sequence, and that removes the need for Karn's algorithm. Karn exists for protocols that reuse the number on retransmission: there the acknowledgement can answer the original or the copy, and the way out is to discard the sample. Here the two datagrams have different numbers, so the acknowledgement names one of them without ambiguity and the sample is always valid.

On each retransmission of the same content the deadline doubles, up to the ceiling. Retransmitting at a fixed interval during congestion is exactly what prolongs it.

9. Not implemented yet, and reserved in the format:

  • Real congestion control. What exists is a ceiling of unacknowledged datagrams. A window that grows and shrinks with loss is the next step and does not change the format.
  • MTU discovery. The useful size is configured, with a default that crosses any path.
  • NAT traversal.
  • Encryption. The hook is the ITransform of TCP, applied to the datagram payload after the 8 byte header, which must stay in clear so the receiver knows which connection it is before decrypting.

Nothing here is guaranteed to be thread safe. See CRudpPeer.

const

RUDP_SIGNATURE_0

Ethereal::Network#
constexpr std::uint8_t RUDP_SIGNATURE_0 = 0xE7;

Signature of every datagram of the protocol, first byte.

const

RUDP_SIGNATURE_1

Ethereal::Network#
constexpr std::uint8_t RUDP_SIGNATURE_1 = 0x4C;

Signature of every datagram of the protocol, second byte.

const

RUDP_VERSION

Ethereal::Network#
constexpr std::uint8_t RUDP_VERSION = 1;

Protocol version spoken by this implementation.

const

RUDP_HEADER_SIZE

Ethereal::Network#
constexpr std::size_t RUDP_HEADER_SIZE = 8;

Size of the header shared by every datagram.

const

RUDP_DEFAULT_MTU

Ethereal::Network#
constexpr std::size_t RUDP_DEFAULT_MTU = 1200;

Default useful payload of a datagram.

1200 bytes crosses any path of the modern internet, tunnels included, without IP fragmentation. It is not the maximum possible, it is the maximum that does not depend on the user's network.

const

RUDP_ACK_BITS

Ethereal::Network#
constexpr std::size_t RUDP_ACK_BITS = 32;

Number of acknowledgements the bit map carries, besides the last one.

enum

EDelivery

Ethereal::Network#
C++
enum class EDelivery : ETL_UINT8
{
    /// @brief  Send and forget. Can vanish, arrive out of order or twice.
    ///
    /// @details  The cheapest. For what is sent all the time and whose loss does not
    ///            matter because the next one corrects it: visual effects, sound,
    ///            trails.
    eUnreliable = 0,

    /// @brief  Send and forget, but drops anything older than the last one delivered
    ///             on that channel.
    ///
    /// @details  For state that is replaced: position, health, score. Getting an old
    ///            position after a new one is worse than getting nothing.
    eUnreliableSequenced = 1,

    /// @brief  Retransmits until acknowledged. Order is not guaranteed.
    eReliable = 2,

    /// @brief  Retransmits and delivers in order, within the channel.
    ///
    /// @details  What arrives early waits for what is missing. It is the mode for
    ///            commands, transactions, anything where the order is the meaning.
    eReliableOrdered = 3,

    /// @brief  Retransmits, and delivers only when newer than the last one delivered.
    eReliableSequenced = 4
};

How a message must be delivered.

The values go on the wire, in the three low bits of the message block flags. They cannot be reordered or renumbered.

function

DeliveryToString

Ethereal::Network#
const char * DeliveryToString( const EDelivery eMode ) noexcept;

Readable name of an EDelivery.

enum

ERudpError

Ethereal::Network#
C++
enum class ERudpError : ETL_UINT8
{
    /// @brief  No error.
    eOk = 0,

    /// @brief  The peer is not open, neither listening nor connecting.
    eNotOpen,

    /// @brief  Already open.
    eAlreadyOpen,

    /// @brief  There is no connection with that id.
    eUnknownPeer,

    /// @brief  The connection exists but has not finished the handshake.
    eNotConnected,

    /// @brief  The message is above SRudpConfig::uMaxMessageBytes.
    eMessageTooLarge,

    /// @brief  There is no room in the send queue.
    ///
    /// @details  Happens when sending faster than the network drains. Not a library
    ///            failure: it is the signal that the sender has to slow down.
    eSendQueueFull,

    /// @brief  The limit of simultaneous connections was reached.
    eTooManyConnections,

    /// @brief  Socket failure. Details in SRudpResult::Net.
    eSocket,

    /// @brief  Invalid argument from the caller.
    eInvalidArgument,

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

Failures specific to RUDP.

An enumeration of the protocol only, like the TCP and UDP ones. The system error, when there is one, comes apart in SRudpResult::Net.

function

RudpErrorToString

Ethereal::Network#
const char * RudpErrorToString( const ERudpError eError ) noexcept;

Readable name of an ERudpError.

struct

SRudpResult

Ethereal::Network#
C++
struct   SRudpResult   final
{
    /// @brief  Cause at the protocol level.
    ERudpError    eError = ERudpError::eOk;

    /// @brief  Cause at the system level, when eError is eSocket.
    SNetStatus    Net;

    /// @brief  Whether the operation succeeded.
    ///
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT                { return eError == ERudpError::eOk; }

    /// @brief  Same as IsOk.
    ///
    ETL_API_NOIGN    explicit operator bool() const ETL_NOEXCEPT    { return IsOk(); }

    /// @brief  One line describing the failure, with both levels.
    ///
    ETL_API_NOIGN    std::string ToString() const;
};

Result of an RUDP operation.

No ETL_STRUCT_ALIGN: a value type. See the note on STcpResult.
enum

EDisconnectReason

Ethereal::Network#
C++
enum class EDisconnectReason : ETL_UINT8
{
    /// @brief  The other side asked to close.
    ePeerRequested = 0,

    /// @brief  This side asked to close.
    eLocalRequested,

    /// @brief  Silence for longer than SRudpConfig::uTimeoutMs.
    eTimedOut,

    /// @brief  A reliable message used up its retransmission attempts.
    eDeliveryFailed,

    /// @brief  The server refused the connection request.
    eRejected,

    /// @brief  The handshake did not finish in time.
    eHandshakeTimedOut,

    /// @brief  Incompatible protocol version.
    eVersionMismatch
};

Why a connection ended.

function

DisconnectReasonToString

Ethereal::Network#
const char * DisconnectReasonToString( const EDisconnectReason eReason ) noexcept;

Readable name of an EDisconnectReason.

enum

ERudpEventType

Ethereal::Network#
C++
enum class ERudpEventType : ETL_UINT8
{
    /// @brief  Nothing happened in this call.
    eNone = 0,

    /// @brief  A connection was established.
    eConnected,

    /// @brief  A connection ended. The reason is in SRudpEvent::eReason.
    eDisconnected,

    /// @brief  A message arrived and is complete.
    eMessage
};

What CRudpPeer::Poll can return.

struct

SRudpEvent

Ethereal::Network#
C++
ETL_BEGIN_INTENDED_PADDING
struct   SRudpEvent   final
{
    /// @brief  What happened.
    ERudpEventType        eType = ERudpEventType::eNone;

    /// @brief  Id of the connection involved.
    ETL_UINT32            uPeerId = 0;

    /// @brief  Address of the other side.
    CAddress            Peer;

    /// @brief  Payload, when eType is ERudpEventType::eMessage.
    std::vector< std::uint8_t >    Data;

    /// @brief  Channel of the message.
    ETL_UINT8            uChannel = 0;

    /// @brief  Mode the message was sent with.
    EDelivery            eDelivery = EDelivery::eUnreliable;

    /// @brief  Reason, when eType is ERudpEventType::eDisconnected.
    EDisconnectReason    eReason = EDisconnectReason::ePeerRequested;
};

Something that happened on the network.

struct

SRudpPeerStats

Ethereal::Network#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Per connection statistics
///=============================================================================


/// @brief  Numbers of a connection, for diagnostics and to judge its quality.
///
struct   SRudpPeerStats   final
{
    /// @brief  Smoothed round trip time, in milliseconds.
    ETL_DOUBLE    dRttMs = 0.0;

    /// @brief  Variation of the round trip time, in milliseconds.
    ETL_DOUBLE    dRttVarianceMs = 0.0;

    /// @brief  Current retransmission deadline, in milliseconds.
    ETL_DOUBLE    dRetransmitTimeoutMs = 0.0;

    /// @brief  The highest retransmission deadline this connection has reached.
    ///
    /// @details  The current one does not tell whether there was a back off. It is
    ///            recomputed on every measured round trip, and after a successful
    ///            retransmission it goes down again, possibly below the initial one.
    ///            To know whether the connection backed off, look at the peak, since
    ///            the current value no longer shows it.
    ETL_DOUBLE    dRetransmitTimeoutPeakMs = 0.0;

    /// @brief  Datagrams sent.
    ETL_UINT64    uDatagramsSent = 0;

    /// @brief  Datagrams received.
    ETL_UINT64    uDatagramsReceived = 0;

    /// @brief  Datagrams retransmitted.
    ETL_UINT64    uDatagramsRetransmitted = 0;

    /// @brief  Datagrams the other side confirmed it did not receive.
    ETL_UINT64    uDatagramsLost = 0;

    /// @brief  Messages sent.
    ETL_UINT64    uMessagesSent = 0;

    /// @brief  Messages received.
    ETL_UINT64    uMessagesReceived = 0;

    /// @brief  Messages dropped for being older than the last one delivered.
    ETL_UINT64    uMessagesDropped = 0;

    /// @brief  Duplicates received and discarded.
    ETL_UINT64    uDuplicatesDiscarded = 0;

    /// @brief  Bytes sent.
    ETL_UINT64    uBytesSent = 0;

    /// @brief  Bytes received.
    ETL_UINT64    uBytesReceived = 0;

    /// @brief  Reliable datagrams still waiting for acknowledgement.
    std::size_t    uPendingReliable = 0;


    /// @brief  Fraction of the sent datagrams that were lost, between 0 and 1.
    ///
    /// @details  Zero when nothing was sent yet, and not NaN, for the same reason as
    ///            the Stats module: NaN spreads through every later computation.
    ///
    ETL_API_NOIGN    ETL_DOUBLE LossRatio() const ETL_NOEXCEPT;
};
struct

SRudpConfig

Ethereal::Network#
C++
struct   SRudpConfig   final
{
    /// Sizes.

    /// @brief  Largest datagram sent, header included.
    ///
    /// @warning  Above ~1200 the datagram starts to depend on the path: it still works,
    ///               and stops working when someone connects through a tunnel or a VPN.
    ///               Raising this is a bet on the user's network.
    ETL_UINT32 uMtuBytes = static_cast< ETL_UINT32 >( RUDP_DEFAULT_MTU );

    /// @brief  Largest message accepted, before fragmentation.
    ///
    /// @details  Limits how much a peer can make the other keep during reassembly.
    ETL_UINT32 uMaxMessageBytes = 4u * 1024u * 1024u;

    /// @brief  How many channels exist. Each one has its own order.
    ETL_UINT8 uChannelCount = 4;


    /// Times.

    /// @brief  Silence, in milliseconds, before the connection is considered dead.
    ETL_UINT32 uTimeoutMs = 10000;

    /// @brief  Interval between pings, when there is nothing to send.
    ETL_UINT32 uPingIntervalMs = 1000;

    /// @brief  Deadline of the whole handshake.
    ETL_UINT32 uHandshakeTimeoutMs = 5000;

    /// @brief  Interval between resends of a handshake step.
    ETL_UINT32 uHandshakeRetryMs = 250;

    /// @brief  Smallest possible retransmission deadline.
    ///
    /// @details  A floor is needed: without it, on a local network the computed
    ///            deadline drops to fractions of a millisecond and any hesitation
    ///            becomes a retransmission.
    ETL_UINT32 uMinRetransmitMs = 30;

    /// @brief  Largest retransmission deadline, after all the doublings.
    ETL_UINT32 uMaxRetransmitMs = 3000;

    /// @brief  Deadline used before the first round trip measurement.
    ETL_UINT32 uInitialRetransmitMs = 300;

    /// @brief  Retransmissions before the connection is given up as lost.
    ETL_UINT32 uMaxRetransmits = 10;

    /// @brief  Deadline to complete a fragment group.
    ETL_UINT32 uFragmentTimeoutMs = 10000;

    /// @brief  How long to wait for an outgoing datagram before sending an
    ///             acknowledgement on its own.
    ///
    /// @details  The acknowledgement normally rides along on a data datagram, for free.
    ///            But a peer with nothing to say (a server that only receives
    ///            telemetry, for example) would never have a ride, and the other side
    ///            would retransmit everything until the connection died.
    ///
    ///           This deadline is the wait for the ride. Zero sends the
    ///            acknowledgement right away, at the cost of one datagram per datagram
    ///            received.
    ETL_UINT32 uAckDelayMs = 5;


    /// Limits.

    /// @brief  Simultaneous connections accepted. Zero refuses all, a pure client.
    ETL_UINT32 uMaxConnections = 64;

    /// @brief  Unacknowledged datagrams that can be in flight at once.
    ///
    /// @details  It is the congestion control that exists today: a fixed ceiling. A
    ///            window that grows and shrinks with loss is the next step, and does
    ///            not change the wire format.
    ETL_UINT32 uMaxUnacked = 64;

    /// @brief  Messages waiting to be sent, per connection.
    ETL_UINT32 uMaxSendQueue = 4096;

    /// @brief  Fragment groups open at the same time, per connection.
    ///
    /// @details  Without a ceiling, a malicious peer sends the first fragment of
    ///            thousands of groups and the receiver keeps them all.
    ETL_UINT32 uMaxFragmentGroups = 64;


    /// Socket.

    /// @brief  Socket receive buffer, in bytes. Zero uses the system default.
    ///
    /// @details  It matters more here than anywhere else: when it fills up, the system
    ///            silently drops datagrams, and the protocol sees them as network loss.
    ETL_UINT32 uReceiveBufferBytes = 256u * 1024u;

    /// @brief  Socket send buffer, in bytes. Zero uses the system default.
    ETL_UINT32 uSendBufferBytes = 256u * 1024u;
};

Everything that can be tuned in the protocol.

function

SequenceGreaterThan

Ethereal::Network#
constexpr bool SequenceGreaterThan( const ETL_UINT16 uA, const ETL_UINT16 uB ) noexcept

Whether uA is newer than uB, taking the wrap into account.

The sequence has 16 bits and wraps every 65536 datagrams. Right after the wrap, 0 is newer than 65535, and '0 < 65535' would say the opposite.

The correct comparison reads the difference as a signed number: when it falls in the positive half of the circle, uA comes after. It is the same rule TCP uses for its sequence numbers (RFC 1982).

uA
First sequence.
uB
Second sequence.
true when uA comes after uB.
function

SequenceDistance

Ethereal::Network#
constexpr std::int32_t SequenceDistance( const ETL_UINT16 uA, const ETL_UINT16 uB ) noexcept

Distance from uB to uA, taking the wrap into account.

class

CRudpPeer

Ethereal::Network#

One end of the protocol: works as client, as server, or both.

class CRudpPeer final

The same class serves both roles because in the protocol they differ only in the handshake. A server listens and accepts, a client connects, and nothing stops a program from doing both.

Everything happens inside Poll. Receiving, acknowledging, retransmitting, reassembling fragments, detecting timeouts and delivering events, all in one place, called by the user. There is no hidden thread.

Not thread safe, and that is the decision, not the lack of one. A protocol with per connection state, retransmission queues and fragment reassembly is either locked as a whole (and the lock becomes the bottleneck it was meant to avoid) or used by one thread. To pump on one thread and consume on another, put a queue between them: the Containers module has a lock free one (Ethereal::Containers::CSpscQueue) made for exactly that.
constructor

CRudpPeer

#
CRudpPeer();

Creates a closed peer.

constructor

CRudpPeer

#
CRudpPeer( CRudpPeer && Other ) noexcept;

Takes the state of Other, which is left closed.

operator

operator=

#
CRudpPeer & operator=( CRudpPeer && Other ) noexcept;

Closes this peer and takes the state of Other.

function

Listen

#
SRudpResult Listen( const ETL_UINT16 uPort, const bool bAnyInterface = false, const SRudpConfig & Config = SRudpConfig() );

Opens on a port and starts accepting connections.

uPort
Zero lets the system pick. Query LocalAddress.
bAnyInterface
false listens only on loopback.
Config
Protocol configuration.
The result.
function

Open

#
SRudpResult Open( const SRudpConfig & Config = SRudpConfig() );

Opens without listening, for callers that only connect.

function

Connect

#
SRudpResult Connect( const CAddress & Address, ETL_UINT32 * pOutPeerId = nullptr );

Starts the handshake with Address.

Returns as soon as the request goes out. The connection only really exists when Poll delivers ERudpEventType::eConnected, or fails with ERudpEventType::eDisconnected.

Address
Destination.
pOutPeerId
Receives the provisional id of the connection in progress.
The result.
function

ConnectTo

#
SRudpResult ConnectTo( std::string_view Host, const ETL_UINT16 uPort, ETL_UINT32 * pOutPeerId = nullptr );

Resolves Host and starts the handshake.

function

Close

#
void Close();

Closes everything, telling the peers.

function

Poll

#
bool Poll( SRudpEvent & OutEvent );

Moves the protocol forward and delivers the next event.

Call this often. Everything depends on it: datagrams are only read here, acknowledgements only go out here, retransmissions only happen here, and a connection only finds out it died here. In a game loop, once per frame. In a service, in its own loop with a short wait.

OutEvent
Receives the event.
false when there is nothing else to report in this round. The usual pattern is 'while( Peer.Poll( Event ) ) { ... }'.
function

Send

#
SRudpResult Send( const ETL_UINT32 uPeerId, std::span< const std::uint8_t > Data, const EDelivery eMode = EDelivery::eReliableOrdered, const ETL_UINT8 uChannel = 0 );

Sends a message to a connection.

uPeerId
Destination connection.
Data
The message.
eMode
How to deliver. See EDelivery.
uChannel
Channel. Order is per channel. Must be below SRudpConfig::uChannelCount.
The result.
function

Broadcast

#
SRudpResult Broadcast( std::span< const std::uint8_t > Data, const EDelivery eMode = EDelivery::eReliableOrdered, const ETL_UINT8 uChannel = 0, const ETL_UINT32 uExceptPeerId = 0 );

Sends the same message to every established connection.

function

Disconnect

#
SRudpResult Disconnect( const ETL_UINT32 uPeerId, const bool bImmediate = false );

Closes a connection.

uPeerId
The connection.
bImmediate
true cuts it now. false tries to deliver what is still in the reliable queue before closing.
The result.
function

IsOpen

#
bool IsOpen() const noexcept;

Whether the peer is open.

function

LocalAddress

#
CAddress LocalAddress() const;

Local address, with the port the system chose.

function

ConnectionCount

#
std::size_t ConnectionCount() const noexcept;

How many established connections exist.

function

Connections

#
std::vector< ETL_UINT32 > Connections() const;

Ids of the established connections.

function

IsConnected

#
bool IsConnected( const ETL_UINT32 uPeerId ) const noexcept;

Whether uPeerId is an established connection.

function

PeerAddress

#
CAddress PeerAddress( const ETL_UINT32 uPeerId ) const;

Address of a connection. Invalid when it does not exist.

function

PeerStats

#
bool PeerStats( const ETL_UINT32 uPeerId, SRudpPeerStats & OutStats ) const;

Numbers of a connection. false when it does not exist.

function

Config

#
const SRudpConfig & Config() const noexcept;

Current configuration.

function

SetTransform

#
void SetTransform( ITransform * pTransform ) noexcept;

Installs the transform applied to the datagram payloads.

Same interface as TCP. The 8 byte header stays in clear: the receiver must know which connection the datagram belongs to before it can decrypt it. Does not take ownership of the object.

alias

bool

#
using DatagramFilter = std::function< bool( const bool, std::span< const std::uint8_t > ) >;

Decides whether a datagram passes or is dropped.

The first argument (bOutgoing) is true for an outgoing datagram and false for an incoming one. Returning false drops the datagram, as the network would.

function

SetDatagramFilter

#
void SetDatagramFilter( DatagramFilter Filter );

Installs a filter that can drop datagrams.

It serves two real purposes, so it is not a test ornament.

Verification. Retransmission, ordering under reordering and duplicate suppression only happen when there is loss. On a loopback connection nothing is lost, and a test that cannot produce loss does not cover the core of the protocol: it covers the happy path and gives the impression of the rest.

Field quality. It is the bad network simulator used to try how a product behaves at 10% loss and 300 ms of latency, without needing a real bad network.

The filter sees the whole datagram, header included, and is called after the transform on the way out and before it on the way in. So it sees exactly the bytes the wire would see.

Null removes the filter.

function

SetClock

#
void SetClock( std::function< ETL_UINT64() > Clock );

Replaces the protocol clock.

Exists for the tests. Retransmission, timeouts and fragment deadlines depend on elapsed time, and waiting seconds of real time in a test makes it slow and flaky, the two things that make a suite ignored.

With an injected clock, the test moves time forward and observes the effect deterministically.

secure.hpp

#include <ethereal/cpp/network/secure.hpp>

Encrypted channel of the Network module (ChaCha20-Poly1305).

The cipher is the easy part. Almost every real cryptography disaster happens in the layer around it, and that layer is what this file delivers:

  • the nonce, which cannot repeat.
  • separate keys per direction.
  • replay protection.
  • what to do when the numbers run out.

1. The nonce is the easiest thing to get wrong, and the worst. Repeating a nonce with the same key, in a stream AEAD, destroys security completely. Two messages encrypted with the same (key, nonce) pair reveal the XOR of the plain texts, and in Poly1305 the reuse also allows recovering the authenticator key and forging messages. Here the nonce is a counter that only goes up, never restarts, and goes on the wire with the message. When it reaches the end, CSecureTransform::Encode refuses to encrypt instead of wrapping. Refusing stops the program. Wrapping keeps it running with no security at all, and nobody notices.

2. Each direction has its own key. Two keys come from the same secret, by HKDF with different labels: one for the side that started the connection, one for the side that accepted it. Without that, both sides would encrypt with the same key, and their counters would move independently, so sooner or later both would use the same (key, nonce) pair, exactly the case of rule 1. And a packet reflected back to its sender would be decrypted by it as legitimate.

3. Replay protection. The cipher says the message was not altered. It says nothing about the message having been recorded and sent again later, and "transfer a thousand dollars" repeated ten times still carries a perfect tag. On a stream (TCP) it is enough to require the counter to move. On datagrams it is not: they arrive out of order by nature, and requiring strict order would drop legitimate traffic. The way out is a window: anything newer than the top is accepted, and what is behind it only if not seen yet. See SSecureConfig::uReplayWindow.

4. Wire format: [ 8 bytes : counter, little-endian ][ cipher text ][ 16 bytes : tag ]

The counter goes in clear because the receiver needs it to decrypt, and it is authenticated as associated data, so changing it invalidates the message. The full 12 byte nonce is the 8 byte counter preceded by 4 bytes that identify the direction. So even if the two keys were equal by mistake, the two sides would never use the same value.

5. What this layer does not do: key agreement. The secret arrives ready. There is no RSA, elliptic curve or Diffie-Hellman here, on purpose: they are the algorithms with the subtlest failure modes, the least forgiving ones, and the ones no test catches. The right answer is an audited library, and the secret it produces comes in through CSecureTransform::Start. Meanwhile, what honestly works is a secret agreed out of band: configuration, license file, provisioning.

enum

ESecureRole

Ethereal::Network#
C++
enum class ESecureRole : ETL_UINT8
{
    /// @brief  The side that started the connection, typically the client.
    eInitiator = 0,

    /// @brief  The side that accepted it, typically the server.
    eResponder = 1
};

The role of this side in the connection.

Decides which of the two keys encrypts and which decrypts. The two sides must disagree: if both declare themselves initiators, each one encrypts with the key the other uses to encrypt, and nothing is decrypted.

struct

SSecureConfig

Ethereal::Network#
C++
struct   SSecureConfig   final
{
    /// @brief  Size of the replay window, in messages.
    ///
    /// @details  Zero requires strict order: only what is newer than everything that
    ///            passed gets through. Right for a stream, where order is guaranteed
    ///            by the transport, and wrong for datagrams, where it would drop good
    ///            traffic.
    ///
    ///           Above zero, a late message is accepted up to this distance from the
    ///            top, as long as it was not seen yet. 64 covers the normal reordering
    ///            of a network.
    ETL_UINT32 uReplayWindow = 64;

    /// @brief  After how many messages the channel should ask for a new key.
    ///
    /// @details  Not a hard limit, the hard limit is the end of the counter. This is
    ///            the warning, and it exists because changing the key with room to
    ///            spare is easy and changing it at the last moment is not.
    ///            CSecureTransform::NeedsRekey starts returning true from here on.
    ETL_UINT64 uRekeyAfter = 1ull << 40;

    /// @brief  Where the send counter starts.
    ///
    /// @details  This exists because of reconnection. A channel that drops and comes
    ///            back with the same secret and the counter at zero reuses the nonces
    ///            already spent, and nonce reuse does not weaken the cipher, it
    ///            destroys it. See rule 1.
    ///
    ///           On reconnection there are two right ways out, and this class serves
    ///            both:
    ///             - agree on a new secret (or a new Salt), the preferred one, or
    ///             - keep the secret and continue the counter where it stopped,
    ///               passing here the CSecureTransform::MessagesSent of the previous
    ///               session.
    ///
    ///           The receiving side needs no adjustment: the replay window anchors on
    ///            the first message that arrives, whatever its counter.
    ETL_UINT64 uStartCounter = 0;
};

What can be tuned in the encrypted channel.

class

CSecureTransform

Ethereal::Network#

Encrypts and authenticates the frame payloads, with nonce discipline.

class CSecureTransform final : public ITransform

Implements ITransform, so installing it on a CTcpSocket or a CRudpPeer with SetTransform makes the traffic of that channel encrypted.

The cipher is injected: this library's by default, and any Ethereal::Crypto::ICipher in its place.

Not guaranteed to be thread safe. The counter and the window are mutable state, and two threads encrypting on the same channel would produce the same nonce, the disaster described in rule 1.
constructor

CSecureTransform

#
CSecureTransform();

Creates a channel that is not ready.

function

Start

#
bool Start( std::span< const std::uint8_t > Secret, const ESecureRole eRole, std::span< const std::uint8_t > Salt = std::span< const std::uint8_t >(), const SSecureConfig & Config = SSecureConfig() );

Prepares the channel from an agreed secret.

Two keys come from the secret, by HKDF with distinct labels. The Salt does not need to be secret and may be empty. When there is something public and unique per session (a pair of handshake nonces, for example), passing it here ties the keys to that session.

Secret
The secret. Must have at least 16 bytes.
eRole
This side. The two sides must use different roles.
Salt
Public salt. May be empty.
Config
Channel configuration.
false when the secret is too short, the cipher refuses the key, or the library is not licensed.
function

SetCipher

#
void SetCipher( Crypto::ICipher * pCipher ) noexcept;

Installs another cipher in place of the default one.

Must be called before Start. Does not take ownership: the object must stay alive while the channel exists.

It is the point to swap in an audited implementation.

function

Reset

#
void Reset() noexcept;

Erases the keys and returns the channel to its initial state.

function

Encode

#
bool Encode( std::span< const std::uint8_t > In, std::vector< std::uint8_t > & Out ) override;

Encrypts a payload. false when the channel is not ready or exhausted.

function

Decode

#
bool Decode( std::span< const std::uint8_t > In, std::vector< std::uint8_t > & Out ) override;

Decrypts a payload. false on an invalid tag, a replay or a bad format.

function

MaxOverheadBytes

#
std::size_t MaxOverheadBytes() const override;

Counter and tag added to each payload.

function

IsReady

#
bool IsReady() const noexcept;

Whether Start succeeded.

function

MessagesSent

#
ETL_UINT64 MessagesSent() const noexcept;

How many messages this side has encrypted.

function

MessagesReceived

#
ETL_UINT64 MessagesReceived() const noexcept;

How many messages were accepted.

function

MessagesRejected

#
ETL_UINT64 MessagesRejected() const noexcept;

How many were refused: invalid tag, replay or format.

On a healthy network this number is zero. A rise means corruption or someone tampering, and in both cases it is the first sign to appear.

function

ReplaysRejected

#
ETL_UINT64 ReplaysRejected() const noexcept;

How many were refused specifically as replays.

function

NeedsRekey

#
bool NeedsRekey() const noexcept;

Whether SSecureConfig::uRekeyAfter was passed.

Not a failure: it is the time to agree on a new key with room to spare.

function

IsExhausted

#
bool IsExhausted() const noexcept;

Whether the counter ran out and nothing else will be encrypted.

From here on Encode always returns false. It is the end of the channel, and it is deliberately impassable. See rule 1.

tcp.hpp

#include <ethereal/cpp/network/tcp.hpp>

TCP sockets of the Network module: raw bytes, frames, typed payloads and files.

TCP delivers a stream of bytes, not messages. A Send of 1000 bytes can arrive as two reads of 500, or as one of 1400 together with part of the next send. Code that ignores this works on loopback and fails on a real network, when the message finally splits.

So this file has two layers that do not mix:

  • CTcpSocket::Send and CTcpSocket::Receive: raw bytes, exactly what the system delivered. They can transfer less than requested, and that is normal.
  • CTcpSocket::SendFrame and CTcpSocket::ReceiveFrame: messages. The length goes first, and the read only returns when the whole message has arrived.

Everything typed (BitStream, object, raw struct, file) travels over frames, never over raw bytes.

Frame format: [ 4 bytes : payload length, little-endian ][ payload ]

The length does not include its own 4 bytes. Little-endian for the same reason as the Serialization module: it is the order the library already uses, and converting by shifts makes the result independent of the machine that wrote it.

A length above STcpConfig::uMaxFrameBytes is refused without reading the payload. In a network protocol this is the defense that matters: four corrupted bytes announcing 4 GB cannot turn into a memory request.

Payload by type, always inside a frame:

  • BitStream: [ 4 bytes : number of bits used, LE ][ stream bytes ]. The bit count goes along because it cannot be deduced from the bytes: a 3 bit stream takes 1 byte, and without the field the other side would read 8.
  • Object: the Serialization envelope, untouched. Its schema version still applies, and the other side uses it to decide how to interpret the data.
  • Raw struct: the bytes of the object as they are in memory. See the warning on CTcpSocket::SendRaw, this does not cross compilers.
  • File: one header frame (Serialization envelope with name and size) followed by N content frames. See CTcpSocket::SendFile.

Left out on purpose:

  • TLS. It would need a vendored crypto library, the same blocker as the http module. Its place is the ITransform hook below.
  • A high performance reactor (IOCP, epoll, kqueue). Each one is a separate implementation, and that is where portability gets expensive. Until it exists, blocking calls with a timeout serve clients and small servers.
enum

ETcpError

Ethereal::Network#
C++
enum class ETcpError : ETL_UINT8
{
    /// @brief  No error.
    eOk = 0,

    /// @brief  The socket was not created, or was already closed.
    eNotOpen,

    /// @brief  The operation needs an established connection.
    eNotConnected,

    /// @brief  The operation needs a listening socket.
    eNotListening,

    /// @brief  The socket is already connected or listening.
    eAlreadyOpen,

    /// @brief  The other side closed the connection in an orderly way.
    ///
    /// @details  Not a failure: it is the normal end of a connection. Distinct from
    ///            eSocket with eConnectionReset, which is the abrupt end.
    ePeerClosed,

    /// @brief  The announced frame is above STcpConfig::uMaxFrameBytes.
    ///
    /// @details  Refused before reading the payload and before allocating. Either the
    ///            other side is sending something too large, or the four length bytes
    ///            arrived corrupted, and both cases end badly if obeyed.
    eFrameTooLarge,

    /// @brief  The stream is not a valid frame at this point.
    eFrameMalformed,

    /// @brief  The configured time ran out.
    eTimedOut,

    /// @brief  On a non blocking socket, the operation cannot happen yet.
    eWouldBlock,

    /// @brief  Socket failure. What happened is in STcpResult::Net.
    eSocket,

    /// @brief  Failure reading or writing the local file during a transfer.
    eFile,

    /// @brief  The client lost its connection and is trying to restore it.
    eReconnecting,

    /// @brief  Invalid argument from the caller.
    eInvalidArgument,

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

Failures specific to the TCP of this library.

An enumeration of the protocol only: it describes what the frame and connection layer knows, not what the operating system returned. The system error comes apart, in STcpResult::Net, and the two together tell the whole story.

function

TcpErrorToString

Ethereal::Network#
const char * TcpErrorToString( const ETcpError eError ) noexcept;

Readable name of an ETcpError.

struct

STcpResult

Ethereal::Network#
C++
struct   STcpResult   final
{
    /// @brief  Cause at the protocol level.
    ETcpError eError = ETcpError::eOk;

    /// @brief  Cause at the system level. Only filled when eError is
    ///             ETcpError::eSocket.
    SNetStatus Net;

    /// @brief  Bytes actually transferred by the operation.
    std::size_t uTransferred = 0;


    /// @brief  Whether the operation succeeded.
    ///
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT        { return eError == ETcpError::eOk; }

    /// @brief  Same as IsOk.
    ///
    ETL_API_NOIGN    explicit operator bool() const ETL_NOEXCEPT    { return IsOk(); }


    /// @brief  One line describing the failure, with both levels.
    ///
    ETL_API_NOIGN    std::string ToString() const;
};

Result of a TCP operation: the protocol cause and the system cause.

Both levels go together because neither tells the story alone. eError says what the library concluded, Net says what the operating system answered, with the raw code kept.

No ETL_STRUCT_ALIGN, unlike the library convention. This is a value type, returned by every call of the module. Aligning it to 16 bytes only adds padding to something that lives in registers and on the stack. MSVC warns about it (C4324), and the warning is right.
struct

STcpConfig

Ethereal::Network#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   STcpConfig   final
{
    /// Times.

    /// @brief  Maximum time to establish the connection. Zero waits for the system
    ///             timeout, which is usually over a minute.
    ETL_UINT32 uConnectTimeoutMs = 10000;

    /// @brief  Maximum time of one send. Zero waits forever.
    ETL_UINT32 uSendTimeoutMs = 30000;

    /// @brief  Maximum time of one receive. Zero waits forever.
    ETL_UINT32 uReceiveTimeoutMs = 30000;


    /// Socket.

    /// @brief  Disables the Nagle algorithm.
    ///
    /// @details  When enabled (the system default), Nagle holds small packets to join
    ///            them, and adds tens of milliseconds to every short message. For
    ///            interactive traffic (command and reply, game state) that is exactly
    ///            what is not wanted, so the default here is to disable it. Bulk
    ///            transfers gain by leaving it on.
    bool bNoDelay = true;

    /// @brief  Enables TCP keep-alive.
    ///
    /// @details  Without it, a connection whose peer vanished without notice (cable
    ///            pulled, machine turned off) stays open forever, and this is only
    ///            found on the next send. With it, the system probes and the
    ///            connection dies on its own.
    bool bKeepAlive = true;

    /// @brief  Silence, in milliseconds, before the first probe is sent.
    ETL_UINT32 uKeepAliveIdleMs = 30000;

    /// @brief  Interval between probes.
    ETL_UINT32 uKeepAliveIntervalMs = 5000;

    /// @brief  Allows reusing an address in TIME_WAIT.
    ///
    /// @details  Without it, restarting a server fails with "address in use" for a few
    ///            minutes after each stop, because the previous connections still hold
    ///            the port in the TIME_WAIT state.
    bool bReuseAddress = true;

    /// @brief  Size of the socket send buffer, in bytes. Zero uses the system default.
    ETL_UINT32 uSendBufferBytes = 0;

    /// @brief  Size of the socket receive buffer, in bytes. Zero uses the system default.
    ETL_UINT32 uReceiveBufferBytes = 0;


    /// Frames.

    /// @brief  Largest frame accepted, in bytes.
    ///
    /// @warning  It is the limit that stops a corrupted length from turning into a huge
    ///               allocation. Raising it without a reason opens that door.
    ETL_UINT32 uMaxFrameBytes = 16u * 1024u * 1024u;

    /// @brief  Size of each chunk in a file transfer.
    ETL_UINT32 uFileChunkBytes = 64u * 1024u;


    /// Reconnection.

    /// @brief  Delay of the first reconnection attempt.
    ETL_UINT32 uReconnectDelayMs = 500;

    /// @brief  Ceiling of the delay between attempts.
    ///
    /// @details  The delay doubles on each failed attempt, up to this ceiling. Retrying
    ///            at a short fixed interval turns a server that went down into a flood
    ///            of connections from every client at the same time, which usually
    ///            stops it from coming back.
    ETL_UINT32 uReconnectMaxDelayMs = 30000;

    /// @brief  Attempts before giving up. Zero tries forever.
    ETL_UINT32 uReconnectMaxAttempts = 0;
};

Everything that can be tuned on a TCP socket of this library.

The defaults are those of an interactive client or server. Callers that move bulk data, run under high latency, or have real time needs change what they need. Nothing here is imposed.

class

ITransform

Ethereal::Network#
class ITransform
destructor

~ITransform

#
virtual ~ITransform() = default;

Virtual destructor.

function

Encode

#
virtual bool Encode( std::span< const std::uint8_t > In, std::vector< std::uint8_t > & Out ) = 0;

Transforms the payload before it goes to the wire.

In
Payload to transform.
Out
Receives the transformed payload.
false aborts the send.
function

Decode

#
virtual bool Decode( std::span< const std::uint8_t > In, std::vector< std::uint8_t > & Out ) = 0;

Undoes the transform of a received frame.

In
Payload as received.
Out
Receives the restored payload.
false marks the frame as invalid (ETcpError::eFrameMalformed). This is what happens when the cipher authentication fails, and in that case the payload must not be delivered.
function

MaxOverheadBytes

#
virtual std::size_t MaxOverheadBytes() const = 0;

How much the transform can add to the size, in the worst case.

Used to check the frame limit before transforming, not after. Otherwise a payload at the limit would become a frame above it.

class

CTcpSocket

Ethereal::Network#
class CTcpSocket final
constructor

CTcpSocket

#
CTcpSocket() noexcept;

Creates a closed socket.

constructor

CTcpSocket

#
CTcpSocket( CTcpSocket && Other ) noexcept;

Takes the handle of Other, which is left closed.

operator

operator=

#
CTcpSocket & operator=( CTcpSocket && Other ) noexcept;

Closes this socket and takes the handle of Other.

function

Connect

#
STcpResult Connect( const CAddress & Address, const STcpConfig & Config = STcpConfig() );

Connects to an address already resolved.

Address
Destination.
Config
Socket configuration.
The result of the connection.
function

ConnectTo

#
STcpResult ConnectTo( std::string_view Host, const ETL_UINT16 uPort, const STcpConfig & Config = STcpConfig() );

Resolves Host and connects, trying the addresses in the system order.

A name can resolve to IPv6 and IPv4 at the same time. Trying only the first one makes the client fail on networks where the preferred family has no route. Walking the list makes it work on both.

Host
Name or address text.
uPort
Port.
Config
Socket configuration.
The result of the last attempt.
function

Close

#
void Close() noexcept;

Closes the connection and releases the handle.

function

ShutdownSend

#
STcpResult ShutdownSend() noexcept;

Shuts down sending, telling the other side that nothing else comes.

The other side starts to get ETcpError::ePeerClosed and can still send. It is the orderly end of a conversation, the way to say "I am done talking" without losing what is still on its way.

function

IsOpen

#
bool IsOpen() const noexcept;

Whether there is a handle.

function

LocalAddress

#
CAddress LocalAddress() const;

Local address of the connection.

function

RemoteAddress

#
CAddress RemoteAddress() const;

Address of the other side.

function

Handle

#
SocketHandle Handle() const noexcept;

The raw handle, for calls this class does not expose. INVALID_SOCKET_HANDLE when there is no socket.

function

SetBlocking

#
STcpResult SetBlocking( const bool bBlocking ) noexcept;

Turns blocking mode on or off.

function

IsBlocking

#
bool IsBlocking() const noexcept;

Whether the socket is in blocking mode.

function

ApplyConfig

#
STcpResult ApplyConfig( const STcpConfig & Config );

Applies the configuration again to the open socket.

function

Config

#
const STcpConfig & Config() const noexcept;

Current configuration.

function

SetTransform

#
void SetTransform( ITransform * pTransform ) noexcept;

Installs the transform applied to the frame payloads.

Does not take ownership: the object must stay alive while the socket uses it. Null removes it.

function

Send

#
STcpResult Send( std::span< const std::uint8_t > Data );

Sends up to Data.size() bytes, possibly fewer.

What was sent is in STcpResult::uTransferred. Sending fewer is not a failure, it is how TCP works when the send buffer fills up.

function

Receive

#
STcpResult Receive( std::span< std::uint8_t > Buffer );

Receives up to Buffer.size() bytes, possibly fewer.

ETcpError::ePeerClosed when the other side closed in an orderly way.
function

SendAll

#
STcpResult SendAll( std::span< const std::uint8_t > Data );

Sends everything, repeating until done or failed.

function

ReceiveAll

#
STcpResult ReceiveAll( std::span< std::uint8_t > Buffer );

Receives exactly Buffer.size() bytes.

function

SendFrame

#
STcpResult SendFrame( std::span< const std::uint8_t > Payload );

Sends a frame: length first, payload after.

function

ReceiveFrame

#
STcpResult ReceiveFrame( std::vector< std::uint8_t > & OutPayload );

Receives a whole frame.

Only returns when the complete message has arrived. The payload replaces whatever is in OutPayload.

function

SendBitStream

#
STcpResult SendBitStream( const Bit::CBitStream & Stream );

Sends an Ethereal::Bit::CBitStream, keeping the bit count.

function

ReceiveBitStream

#
STcpResult ReceiveBitStream( Bit::CBitStream & OutStream );

Receives an Ethereal::Bit::CBitStream, with the bit count restored.

The stream is reset and filled with what arrived. The read offset is at the start, ready to be read.

function

SendObject

#
STcpResult SendObject( const Serialization::CWriter & Writer );

Sends the stream built by an Ethereal::Serialization::CWriter.

function

ReceiveObject

#
STcpResult ReceiveObject( std::vector< std::uint8_t > & OutBuffer );

Receives a serialization stream to open a reader on it.

OutBuffer holds the bytes and must stay alive while the reader is used: Ethereal::Serialization::CReader points to it, it does not copy.

function

SendRaw

#
template< typename T > STcpResult SendRaw( const T & Value )

Sends the raw bytes of a trivially copyable object.

Value
The object.
The result of SendFrame.
This does not cross compilers, architectures or versions. What goes on the wire is the memory layout of the type: padding between fields, byte order of integers, size of long, alignment. An x86 client and an ARM server disagree, and the same code built with another option can disagree with itself. Use it only between binaries built together, two processes of the same program for example. For anything else use SendObject, which is portable by construction.
function

ReceiveRaw

#
template< typename T > STcpResult ReceiveRaw( T & OutValue )

Receives the raw bytes of a trivially copyable object.

OutValue
Receives the object.
The result, eFrameMalformed when the size does not match.
Same caveats as SendRaw. The frame must have exactly sizeof(T) bytes, otherwise the read is refused as malformed. It is the only possible defense against a layout mismatch.
alias

void

#
using ProgressFn = std::function< void( const ETL_UINT64, const ETL_UINT64 ) >;

Progress report of a transfer: ( done, total ).

function

SendFile

#
STcpResult SendFile( const std::string & sPath, ProgressFn OnProgress = {}, const std::string & sRemoteName = std::string() );

Sends a file.

Sends a header frame with name and size (Serialization envelope), then the content in frames of STcpConfig::uFileChunkBytes. The file is read in chunks: one of several gigabytes cannot require memory of its size.

sPath
Local file.
OnProgress
Progress report. May be empty.
sRemoteName
Name the other side will see. Empty uses the file name.
The result of the transfer.
function

ReceiveFile

#
STcpResult ReceiveFile( const std::string & sDestinationPath, ProgressFn OnProgress = {}, std::string * pOutRemoteName = nullptr, ETL_UINT64 * pOutSize = nullptr );

Receives a file sent by SendFile.

sDestinationPath
Where to write the file.
OnProgress
Progress report. May be empty.
pOutRemoteName
Receives the name sent by the other side. May be null.
pOutSize
Receives the file size. May be null.
The result of the transfer.
The name that comes from the other side is data, not an instruction: it is not used to build the path. The caller decides where to write, in sDestinationPath, and the received name only arrives in pOutRemoteName, for inspection. Accepting a path from the network is how a malicious peer writes outside the intended directory.
class

CTcpListener

Ethereal::Network#
class CTcpListener final
constructor

CTcpListener

#
CTcpListener() noexcept;

Creates a closed listener.

constructor

CTcpListener

#
CTcpListener( CTcpListener && Other ) noexcept;

Takes the handle of Other, which is left closed.

operator

operator=

#
CTcpListener & operator=( CTcpListener && Other ) noexcept;

Closes this listener and takes the handle of Other.

function

Listen

#
STcpResult Listen( const CAddress & Address, const ETL_INT32 iBacklog = 64, const STcpConfig & Config = STcpConfig() );

Binds to the address and starts listening.

Address
Local address.
iBacklog
How many connections can wait before being refused.
Config
Configuration given to the accepted sockets.
The result.
function

ListenOn

#
STcpResult ListenOn( const ETL_UINT16 uPort, const bool bAnyInterface = false, const ETL_INT32 iBacklog = 64, const STcpConfig & Config = STcpConfig() );

Listens on a local port.

uPort
Port.
bAnyInterface
false listens only on loopback, which is what an internal service should do to avoid being exposed by accident.
iBacklog
How many connections can wait before being refused.
Config
Configuration given to the accepted sockets.
The result.
function

Accept

#
STcpResult Accept( CTcpSocket & OutSocket );

Accepts the next connection.

Blocks until one arrives, or returns ETcpError::eWouldBlock when the listener is in non blocking mode.

function

Close

#
void Close() noexcept;

Stops listening and releases the handle.

function

IsListening

#
bool IsListening() const noexcept;

Whether the listener is open.

function

LocalAddress

#
CAddress LocalAddress() const;

Local address, with the port the system chose.

function

Handle

#
SocketHandle Handle() const noexcept;

The raw handle.

function

SetBlocking

#
STcpResult SetBlocking( const bool bBlocking ) noexcept;

Turns blocking mode on or off.

udp.hpp

#include <ethereal/cpp/network/udp.hpp>

Raw UDP sockets of the Network module.

UDP delivers datagrams: each send arrives whole or does not arrive. There is no stream, no partial read and no framing to do, the message is already the unit. It is the opposite of TCP, and that is why the two live in separate files.

What UDP does not give, and many assume it does:

  • No guaranteed delivery. A datagram can simply vanish.
  • No order. The second can arrive before the first.
  • No duplicate detection. The same one can arrive twice.
  • No congestion control. Sending too fast floods the receiver's network, and the sender is not told.
  • No connection. Connect here only sets the default destination and filters the source. No packet is exchanged, and the other side does not know you exist.

This class is raw UDP and only that. The reliable layer (handshake, sequence numbers, ACK/NAK, retransmission, ordered channels, fragmentation and reassembly, RTT estimation and congestion control) is a project of its own, in rudp.hpp, with the wire format written before the code. A naive "reliable UDP" here would be worse than none: it would seem to work on loopback and lose data on a real network.

Datagram size: a datagram larger than the path supports is fragmented by IP, and losing one fragment loses the whole message. The chance of loss grows fast with the number of fragments. SAFE_PAYLOAD_IPV4 and SAFE_PAYLOAD_IPV6 are the sizes that cross any path without fragmenting. Above them it still works, usually up to ~1472 bytes on a local network, but it then depends on the network and not on your code.

enum

EUdpError

Ethereal::Network#
C++
enum class EUdpError : ETL_UINT8
{
    /// @brief  No error.
    eOk = 0,

    /// @brief  The socket was not created, or was already closed.
    eNotOpen,

    /// @brief  The socket is already open.
    eAlreadyOpen,

    /// @brief  There is no default destination and the operation needs one.
    eNoDefaultPeer,

    /// @brief  The datagram did not fit in the given buffer, and the excess was lost.
    ///
    /// @details  In UDP the rest cannot be read later: what did not fit is dropped by
    ///            the system. It is a sizing error of the caller, so it has its own name
    ///            instead of becoming a "received less".
    eTruncated,

    /// @brief  The datagram is larger than the path accepts.
    eMessageTooLarge,

    /// @brief  The configured time ran out.
    eTimedOut,

    /// @brief  On a non blocking socket, the operation cannot happen yet.
    eWouldBlock,

    /// @brief  Socket failure. What happened is in SUdpResult::Net.
    eSocket,

    /// @brief  Invalid argument from the caller.
    eInvalidArgument,

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

Failures specific to the UDP of this library.

An enumeration of the protocol only, separate from the TCP one because the two fail for different reasons: there is no "peer closed" in UDP, and no "datagram truncated" in TCP.

function

UdpErrorToString

Ethereal::Network#
const char * UdpErrorToString( const EUdpError eError ) noexcept;

Readable name of an EUdpError.

struct

SUdpResult

Ethereal::Network#
C++
struct   SUdpResult   final
{
    /// @brief  Cause at the protocol level.
    EUdpError eError = EUdpError::eOk;

    /// @brief  Cause at the system level. Only filled when eError is
    ///             EUdpError::eSocket.
    SNetStatus Net;

    /// @brief  Bytes of the datagram transferred.
    std::size_t uTransferred = 0;


    /// @brief  Whether the operation succeeded.
    ///
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT        { return eError == EUdpError::eOk; }

    /// @brief  Same as IsOk.
    ///
    ETL_API_NOIGN    explicit operator bool() const ETL_NOEXCEPT    { return IsOk(); }

    /// @brief  One line describing the failure, with both levels.
    ///
    ETL_API_NOIGN    std::string ToString() const;
};

Result of a UDP operation: the protocol cause and the system cause.

No ETL_STRUCT_ALIGN: a value type. See the note on Ethereal::Network::STcpResult.
const

SAFE_PAYLOAD_IPV4

Ethereal::Network#
constexpr std::size_t SAFE_PAYLOAD_IPV4 = 548;

Payload that crosses any IPv4 path without fragmenting.

576 bytes is the minimum RFC 791 requires every IPv4 link to accept. Taking 20 bytes of IP header and 8 of UDP leaves 548.

const

SAFE_PAYLOAD_IPV6

Ethereal::Network#
constexpr std::size_t SAFE_PAYLOAD_IPV6 = 1232;

Payload that crosses any IPv6 path without fragmenting.

1280 bytes is the minimum MTU required by IPv6 (RFC 8200). Taking 40 bytes of IP header and 8 of UDP leaves 1232.

const

MAX_DATAGRAM_BYTES

Ethereal::Network#
constexpr std::size_t MAX_DATAGRAM_BYTES = 65507;

Largest datagram the protocol allows, because of the 16 bit length field of UDP.

struct

SUdpConfig

Ethereal::Network#
C++
struct   SUdpConfig   final
{
    /// @brief  Maximum time of one send. Zero waits forever.
    ETL_UINT32 uSendTimeoutMs = 5000;

    /// @brief  Maximum time of one receive. Zero waits forever.
    ETL_UINT32 uReceiveTimeoutMs = 5000;

    /// @brief  Size of the socket send buffer. Zero uses the system default.
    ETL_UINT32 uSendBufferBytes = 0;

    /// @brief  Size of the socket receive buffer. Zero uses the system default.
    ///
    /// @details  In UDP this buffer matters more than in TCP: when it fills up, the
    ///            system silently drops datagrams, and there is no retransmission to
    ///            recover them. Receivers of bursts should raise it.
    ETL_UINT32 uReceiveBufferBytes = 0;

    /// @brief  Allows reusing the address on bind.
    bool bReuseAddress = true;

    /// @brief  Allows sending to a broadcast address.
    ///
    /// @details  Off by default, and the system refuses the send without it. It is a
    ///            deliberate lock: broadcast reaches the whole local network, and
    ///            turning it on should be a conscious decision.
    bool bBroadcast = false;
};

What can be tuned on a UDP socket of this library.

No ETL_STRUCT_ALIGN: it is passed by value and copied into the socket. See the note on Ethereal::Network::STcpResult.
class

CUdpSocket

Ethereal::Network#

A UDP socket.

class CUdpSocket final

Owns the handle and closes it in the destructor. Movable, never copyable, for the same reason as CTcpSocket.

Not guaranteed to be thread safe.
constructor

CUdpSocket

#
CUdpSocket() noexcept;

Creates a closed socket.

constructor

CUdpSocket

#
CUdpSocket( CUdpSocket && Other ) noexcept;

Takes the handle of Other, which is left closed.

operator

operator=

#
CUdpSocket & operator=( CUdpSocket && Other ) noexcept;

Closes this socket and takes the handle of Other.

function

Open

#
SUdpResult Open( const EAddressFamily eFamily = EAddressFamily::eIPv4, const SUdpConfig & Config = SUdpConfig() );

Opens a socket without binding it to any port.

For callers that only send. The system picks a source port on the first send.

eFamily
Address family.
Config
Socket configuration.
The result.
function

Bind

#
SUdpResult Bind( const CAddress & Address, const SUdpConfig & Config = SUdpConfig() );

Opens and binds to an address, to be able to receive.

function

BindTo

#
SUdpResult BindTo( const ETL_UINT16 uPort, const bool bAnyInterface = false, const SUdpConfig & Config = SUdpConfig() );

Binds to a local port.

uPort
Zero lets the system pick the port. Query LocalAddress afterwards to know which one.
bAnyInterface
false listens only on loopback.
Config
Socket configuration.
The result.
function

Close

#
void Close() noexcept;

Closes the socket and releases the handle.

function

Connect

#
SUdpResult Connect( const CAddress & Address );

Sets the default destination and starts refusing datagrams from other sources.

No packet is exchanged, and the other side is not told. In UDP, connect only configures the socket locally: it sets where Send goes and makes the system drop whatever comes from any other address.

Worth it for two reasons besides convenience: the source filter is done by the system, cheaper and more reliable than doing it by hand, and only this way can the system report ICMP port unreachable, which on a socket without a default destination is simply dropped.

function

Send

#
SUdpResult Send( std::span< const std::uint8_t > Data );

Sends a datagram to the default destination.

EUdpError::eNoDefaultPeer when Connect was not called.
function

SendTo

#
SUdpResult SendTo( std::span< const std::uint8_t > Data, const CAddress & Address );

Sends a datagram to a given destination.

function

Receive

#
SUdpResult Receive( std::span< std::uint8_t > Buffer, CAddress * pOutFrom = nullptr );

Receives a datagram.

Buffer
Receives the datagram.
pOutFrom
When not null, receives the source of the datagram.
The result, with the size in uTransferred.
A datagram larger than Buffer is truncated and the excess is lost. There is no way to read the rest later. The return is EUdpError::eTruncated, and what fit is in Buffer. Size it by MAX_DATAGRAM_BYTES when the size is not known in advance.
function

SendBitStream

#
SUdpResult SendBitStream( const Bit::CBitStream & Stream, const CAddress * pTo = nullptr );

Sends an Ethereal::Bit::CBitStream as one datagram.

The payload is [ 4 bytes: number of bits, LE ][ stream bytes ], the same as TCP. The bit count goes along because it cannot be deduced from the bytes.

function

ReceiveBitStream

#
SUdpResult ReceiveBitStream( Bit::CBitStream & OutStream, CAddress * pOutFrom = nullptr );

Receives a datagram and reads it as an Ethereal::Bit::CBitStream.

function

IsOpen

#
bool IsOpen() const noexcept;

Whether there is a handle.

function

HasDefaultPeer

#
bool HasDefaultPeer() const noexcept;

Whether Connect set a default destination.

function

LocalAddress

#
CAddress LocalAddress() const;

Local address, with the port the system chose.

function

Handle

#
SocketHandle Handle() const noexcept;

The raw handle.

function

SetBlocking

#
SUdpResult SetBlocking( const bool bBlocking ) noexcept;

Turns blocking mode on or off.

function

Config

#
const SUdpConfig & Config() const noexcept;

Current configuration.