Add dlibc, start context work, updated public API

Added vector.h from dlibc (MIT license).

context.h/.c only implemented one thing for now, which was a pain for some reason because I'm tired and couldn't figure out a basic
damn pointer. Will have to test for stupidity later.
This commit is contained in:
2026-10-31 22:14:30 +01:00
parent a4f37e3b87
commit 2c73f4be24
8 changed files with 1149 additions and 75 deletions
+2
View File
@@ -21,6 +21,8 @@ libbravais is licensed under your choice of the GNU Lesser General Public Licens
**Public header exception:** The public API header, `bravais.h` (and the generated `bravais/export.h`), is additionally available under the MIT License, so the header may be used under any of LGPL-2.1-only, LGPL-3.0-only, or MIT. This makes it clear that including the header in proprietary software doesn't impose license terms on that software.
**dlibc exception:** The dlibc headers (`include/dlibc/`) are licensed under the MIT License (only).
This exception applies only to the header(s). Linking against the compiled library is still governed by the LGPL, so applications that distribute the library must comply with its terms (license notice, license text, and the ability for users to replace the library with a modified version).
This makes is possible to use this library in both open source and proprietary software, as long as the terms of the licenses are followed (though proprietary software may wish to use it with dynamic linking to avoid the static linking requirements).
+119 -63
View File
@@ -19,10 +19,14 @@ extern "C" {
#define BRAVAIS_VERSION ((BRAVAIS_VERSION_MAJOR << 16) | (BRAVAIS_VERSION_MINOR << 8) | BRAVAIS_VERSION_PATCH)
#define BRAVAIS_NO_TIMEOUT UINT64_MAX
#define BRAVAIS_NO_CONN UINT64_C(0) // Never a valid connection ID
#define BRAVAIS_MAX_DATAGRAM_SIZE 1500
#define BRAVAIS_MAX_PLAINTEXT_SIZE 65535
// The main header has this, everything else is in the internal one
#define BRAVAIS_X25519_KEY_LENGTH 32 // For X25519 private and public
typedef enum {
// Error codes; Generally <0 = error, 0 = success
BRAVAIS_EMPTY = 1, // Nothing to emit right now
@@ -34,16 +38,14 @@ typedef enum {
BRAVAIS_ERR_UNSUPPORTED = -5,
BRAVAIS_ERR_AUTH = -6,
BRAVAIS_ERR_STATE = -7,
BRAVAIS_ERR_CONN_NOT_FOUND = -8,
BRAVAIS_ERR_CONN_LIMIT = -9,
BRAVAIS_ERR_UNKNOWN = -1000
} bravais_result_t;
typedef enum {
BRAVAIS_ROLE_INITIATOR,
BRAVAIS_ROLE_RESPONDER
} bravais_role_t;
typedef enum {
BRAVAIS_TRANSPORT_MODE_UNSET = 0, // Rejected value
BRAVAIS_TRANSPORT_MODE_RAW,
BRAVAIS_TRANSPORT_MODE_QUIC
} bravais_transport_mode_t;
@@ -63,16 +65,37 @@ typedef enum {
*/
typedef void (*bravais_log_fn_t)(void* userData, bravais_log_level_t level, const char* message);
typedef struct bravais_endpoint {
uint8_t address[16]; // IPv6 address (or IPv4-mapped IPv6) - network byte order
uint16_t port; // Port number - host byte order
} bravais_endpoint_t;
typedef enum {
BRAVAIS_EVENT_CONN_ESTABLISHED = 1,
BRAVAIS_EVENT_CONN_CLOSED,
BRAVAIS_EVENT_CONN_FAILED
} bravais_event_type_t;
typedef struct {
bravais_role_t role;
bravais_transport_mode_t transportMode;
bravais_log_fn_t logFn;
bravais_event_type_t type;
uint64_t connId;
} bravais_event_t;
typedef struct {
uint8_t staticPrivateKey[BRAVAIS_X25519_KEY_LENGTH]; // Copied in, wipe afterwards
uint32_t maxConns; // 0 selects default
bravais_log_fn_t logFn; // NULL disables logging
void* logUserData;
} bravais_context_config_t;
typedef struct {
bravais_transport_mode_t transportMode;
bravais_endpoint_t remoteEndpoint;
uint8_t remoteStaticKey[BRAVAIS_X25519_KEY_LENGTH]; // Responder identity
// TODO: Add more configuration options here as needed
} bravais_config_t;
} bravais_connect_config_t;
typedef struct bravais_conn bravais_conn_t; // Opaque connection type
typedef struct bravais_context bravais_context_t; // Opaque
// =============================================================================
// Public API functions
@@ -85,89 +108,122 @@ typedef struct bravais_conn bravais_conn_t; // Opaque connection type
BRAVAIS_API uint32_t bravais_version(void);
/**
* @brief Initialize the config struct with defaults for all optional fields.
* @param config Pointer to a bravais_config_t struct to initialize.
* @return BRAVAIS_OK on success, or BRAVAIS_ERR_INVALID_ARG if the config pointer is NULL.
* @attention The caller must still set role and transportMode manually.
* @brief Human-readable name of a result code.
* @return A static string; never NULL.
*/
BRAVAIS_API bravais_result_t bravais_config_init(const bravais_config_t* config);
BRAVAIS_API const char* bravais_result_str(bravais_result_t result);
/**
* @brief Create a new connection.
* @param config The configuration to use for the new connection.
* @param outConn A pointer to a bravais_conn_t pointer that will be set to the new connection. Set to NULL on failure.
* @return BRAVAIS_OK on success, BRAVAIS_ERR_INVALID_ARG, or BRAVAIS_ERR_OUT_OF_MEMORY.
* @attention The config is copied. The caller may reuse or discard it afterwards.
* @brief Initialize a context config with defaults for all optional fields.
* @return BRAVAIS_OK, or BRAVAIS_ERR_INVALID_ARG if config is NULL.
* @attention The caller must still set staticPrivateKey.
*/
BRAVAIS_API bravais_result_t bravais_conn_create(const bravais_config_t* config, bravais_conn_t** outConn);
BRAVAIS_API bravais_result_t bravais_context_config_init(bravais_context_config_t* config);
/**
* @brief Destroy a connection.
* @param conn The connection to destroy.
* @brief Create a context.
* @param config The configuration. Copied; the caller may reuse or discard it afterwards.
* @param outCtx Receives the new context. Set to NULL on failure.
* @return BRAVAIS_OK, BRAVAIS_ERR_INVALID_ARG, or BRAVAIS_ERR_OUT_OF_MEMORY.
*/
BRAVAIS_API bravais_result_t bravais_context_create(const bravais_context_config_t* config, bravais_context_t** outCtx);
/**
* @brief Destroy a context and every connection it owns, wiping key material.
* @attention NULL is a no-op.
*/
BRAVAIS_API void bravais_conn_destroy(bravais_conn_t* conn);
BRAVAIS_API void bravais_context_destroy(bravais_context_t* ctx);
/**
* @brief Initialize a connect config with defaults for all optional fields.
* @return BRAVAIS_OK, or BRAVAIS_ERR_INVALID_ARG if config is NULL.
* @attention The caller must still set transportMode, remoteEndpoint and remoteStaticKey.
*/
BRAVAIS_API bravais_result_t bravais_connect_config_init(bravais_connect_config_t* config);
/**
* @brief Start a connection to a remote peer, as the initiator.
* @param ctx The owning context.
* @param config Where and how to connect. Copied.
* @param nowMs Current time (see the note at the top of this header).
* @param outConnId Receives the new connection id. Set to BRAVAIS_NO_CONN on failure.
* @return BRAVAIS_OK, BRAVAIS_ERR_INVALID_ARG, BRAVAIS_ERR_OUT_OF_MEMORY, or BRAVAIS_ERR_LIMIT.
* @attention The handshake's first flight is queued; drain it with bravais_poll_datagram().
*/
BRAVAIS_API bravais_result_t bravais_connect(bravais_context_t* ctx, const bravais_connect_config_t* config, uint64_t nowMs, uint64_t* outConnId);
/**
* @brief Close a connection.
* @return BRAVAIS_OK, BRAVAIS_ERR_INVALID_ARG, or BRAVAIS_ERR_NOT_FOUND.
* @attention The id is invalid as soon as this returns. No CLOSED event is reported for it.
*/
BRAVAIS_API bravais_result_t bravais_close(bravais_context_t* ctx, uint64_t connId, uint64_t nowMs);
/**
* @brief Feed one datagram received from the network.
* @param conn The connection to feed the datagram to.
* @param data The datagram data received from the network.
* @param dataLen The length of the datagram data.
* @param nowMs The current time in milliseconds (unix epoch).
* @return BRAVAIS_OK on success, BRAVAIS_ERR_INVALID_ARG, or BRAVAIS_ERR_MALFORMED (datagram is malformed).
* @param ctx The context. It finds the owning connection, or starts a responder connection for a new handshake.
* @param transportMode The transport of the socket the datagram arrived on.
* @param from The datagram's source address.
* @param data The datagram.
* @param dataLen The length of the datagram.
* @param nowMs Current time.
* @return BRAVAIS_OK, BRAVAIS_ERR_INVALID_ARG, or BRAVAIS_ERR_MALFORMED. A malformed datagram is dropped and affects no connection.
* @attention Any resulting output is queued. Drain it with the poll functions.
*/
BRAVAIS_API bravais_result_t bravais_recv_datagram(bravais_conn_t* conn, const uint8_t* data, size_t dataLen, uint64_t nowMs);
BRAVAIS_API bravais_result_t bravais_recv_datagram(bravais_context_t* ctx, bravais_transport_mode_t transportMode, const bravais_endpoint_t* from, const uint8_t* data, size_t dataLen, uint64_t nowMs);
/**
* @brief Submit one plaintext packet read from the TUN device.
* @param conn The connection to submit the packet to.
* @param data The packet data read from the TUN device.
* @param dataLen The length of the packet data.
* @param nowMs The current time in milliseconds (unix epoch).
* @return BRAVAIS_OK on success, or BRAVAIS_ERR_INVALID_ARG.
* @attention The packet is encrypted and queued for sending. Drain it with bravais_poll_datagram().
* @brief Submit one plaintext packet read from the TUN device, to be sent on a connection.
* @return BRAVAIS_OK, BRAVAIS_ERR_INVALID_ARG, BRAVAIS_ERR_NOT_FOUND, or BRAVAIS_ERR_STATE.
* @attention The packet is encrypted and queued. Drain it with bravais_poll_datagram().
*/
BRAVAIS_API bravais_result_t bravais_send_packet(bravais_conn_t* conn, const uint8_t* data, size_t dataLen, uint64_t nowMs);
BRAVAIS_API bravais_result_t bravais_send_packet(bravais_context_t* ctx, uint64_t connId, const uint8_t* data, size_t dataLen, uint64_t nowMs);
/**
* @brief Take the next datagram to send to the network, if any.
* @param conn The connection to poll for datagrams.
* @param out A buffer to write the datagram to.
* @param outCap The capacity of the output buffer.
* @param outLen A pointer to a size_t that will be set to the length of the datagram written to the output buffer.
* @return BRAVAIS_OK on success, BRAVAIS_EMPTY if no datagram is available (this is NOT an error), or BRAVAIS_ERR_BUFFER_TOO_SMALL.
* @attention The caller must provide a buffer large enough to hold the datagram.
* @brief Take the next datagram to send to the network, from any connection.
* @param out Destination buffer.
* @param outCap Capacity of out.
* @param outLen Receives the datagram length. On BRAVAIS_ERR_BUFFER_TOO_SMALL, receives the required size and the datagram stays queued.
* @param outTo Receives the destination address.
* @param outTransportMode Receives the transport, i.e. which socket to send it from.
* @return BRAVAIS_OK, BRAVAIS_EMPTY if nothing is queued (not an error), or BRAVAIS_ERR_BUFFER_TOO_SMALL.
*/
BRAVAIS_API bravais_result_t bravais_poll_datagram(bravais_conn_t* conn, uint8_t* out, size_t outCap, size_t* outLen);
BRAVAIS_API bravais_result_t bravais_poll_datagram(bravais_context_t* ctx, uint8_t* out, size_t outCap, size_t* outLen, bravais_endpoint_t* outTo, bravais_transport_mode_t* outTransportMode);
/**
* @brief Take the next decrypted packet to write to the TUN device, if any.
* @param conn The connection to poll for packets.
* @param out A buffer to write the packet to.
* @param outCap The capacity of the output buffer.
* @param outLen A pointer to a size_t that will be set to the length of the packet written to the output buffer.
* @return BRAVAIS_OK on success, BRAVAIS_EMPTY if no packet is available (this is NOT an error), or BRAVAIS_ERR_BUFFER_TOO_SMALL.
* @attention The caller must provide a buffer large enough to hold the packet.
* @brief Take the next decrypted packet to write to the TUN device, from any connection.
* @param outConnId Receives the id of the connection it arrived on, for the inner source address check.
* @return BRAVAIS_OK, BRAVAIS_EMPTY if nothing is queued (not an error), or BRAVAIS_ERR_BUFFER_TOO_SMALL.
* @attention Same buffer semantics as bravais_poll_datagram().
*
*/
BRAVAIS_API bravais_result_t bravais_poll_plaintext(bravais_conn_t* conn, uint8_t* out, size_t outCap, size_t* outLen);
BRAVAIS_API bravais_result_t bravais_poll_plaintext(bravais_context_t* ctx, uint8_t* out, size_t outCap, size_t* outLen, uint64_t* outConnId);
/**
* @brief Earliest time the connection needs bravais_on_timeout() called.
* @return Absolute deadline in milliseconds (unix epoch) for the next timeout, or BRAVAIS_NO_TIMEOUT if no timeout is needed.
* @brief Take the next connection lifecycle event.
* @return BRAVAIS_OK, BRAVAIS_EMPTY if there is none (not an error), or BRAVAIS_ERR_INVALID_ARG.
* @attention Poll this every loop iteration: connections that ended are only freed once their last event is taken.
*/
BRAVAIS_API uint64_t bravais_get_next_timeout(bravais_conn_t* conn);
BRAVAIS_API bravais_result_t bravais_poll_event(bravais_context_t* ctx, bravais_event_t* outEvent);
/**
* @brief Run any timers due at nowMs.
* @param conn The connection to run timers for.
* @param nowMs The current time in milliseconds (unix epoch).
* @return BRAVAIS_OK on success, or BRAVAIS_ERR_INVALID_ARG.
* @brief The remote's authenticated static public key.
* @param outKey Receives BRAVAIS_X25519_KEY_LENGTH bytes.
* @return BRAVAIS_OK, BRAVAIS_ERR_INVALID_ARG, BRAVAIS_ERR_NOT_FOUND, or BRAVAIS_ERR_STATE before the handshake has completed.
*/
BRAVAIS_API bravais_result_t bravais_conn_remote_key(const bravais_context_t* ctx, uint64_t connId, uint8_t* outKey);
/**
* @brief Earliest time any connection needs bravais_on_timeout() called.
* @return Absolute deadline on the caller's clock, or BRAVAIS_NO_TIMEOUT.
*/
BRAVAIS_API uint64_t bravais_get_next_timeout(const bravais_context_t* ctx);
/**
* @brief Run any timers due at nowMs, across all connections.
* @return BRAVAIS_OK, or BRAVAIS_ERR_INVALID_ARG.
* @attention Safe to call early. No-op if no timers are due yet.
*/
BRAVAIS_API bravais_result_t bravais_on_timeout(bravais_conn_t* conn, uint64_t nowMs);
BRAVAIS_API bravais_result_t bravais_on_timeout(bravais_context_t* ctx, uint64_t nowMs);
#ifdef __cplusplus
}
+872
View File
@@ -0,0 +1,872 @@
/*
vector.h - Vectors for C
Version: 1.0.0
Description:
Header-only library for vectors in C. Memory safe against the mistakes it can
detect, but not thread-safe (you must implement your own synchronization
mechanisms).
Designed for C23 onwards, but should be compatible with older standards (tested
from C99 onwards).
Guarantees:
- A vector_t must never be duplicated by copying the struct. Two vector_t values
sharing one data pointer both believe they own it, and whichever is destroyed
or moved from first leaves the other holding freed memory. Copying the pointer
(vector_t* b = a;) is fine - that is one vector with two names, and it must be
destroyed exactly once.
- To hand a vector's data to another vector, use vector_move(). The source is
emptied, freed and its pointer set to NULL, so there is only ever one owner.
- To get a second, independent vector with the same contents, use
vector_deep_copy(), which copies the data as well as the vector itself. Deep
copies are only available for vectors without an element destructor, as a
byte-wise copy of owning elements would result in a double free.
- No gaps in the raw data array.
- When a vector is resized, the data is reallocated to a new memory location,
so any pointers into the old data are invalidated. There is no way to
preserve them; re-fetch with vector_get() after the resize.
- Order of elements is preserved.
- It is safe to pass a pointer into a vector's own data as the source element
of vector_push_back(), vector_insert() and vector_set(). Each of them handles
the aliasing in whichever way suits it, so the value survives the reallocation
or the shifting of elements. On a vector with an element destructor this is
rejected with -1 instead, as a byte-wise copy would leave two slots owning the
same memory. To duplicate an owning element, copy what it owns yourself and
push that.
- vector_take_at() and vector_take_back() transfer ownership of the element to the
caller, and do not call the destructor on it. It is the caller's responsibility
to free whatever the element owns.
Element destructors:
A vector may be given an element destructor with vector_set_destructor(). It is
called for every element that leaves the vector, i.e. by vector_pop_back(),
vector_pop_at(), vector_set() (on the element being overwritten), vector_clear()
and vector_destroy().
The destructor is NOT called by vector_take_back() or vector_take_at(), as these
functions transfer ownership of the element to the caller. It is the caller's
responsibility to free whatever the element owns.
The destructor receives a pointer to the element's slot inside the vector's data
array - NOT a pointer that was returned by malloc(). It must free whatever the
element owns, and must never free the pointer it was handed, as that memory
belongs to the vector. For a vector of char* this means:
void free_str(void* element) { free(*(char**)element); }
vector_t* vec = vector_create(sizeof(char*));
vector_set_destructor(vec, free_str);
// ... use the vector ...
vector_destroy(&vec); // Takes the address of your pointer, and NULLs it
A warning regarding misuse:
The vector manages its own buffer correctly: no leaks, no double frees of the data
array, no use of stale pointers internally. It cannot reason about what your
elements own — that is what the destructor is for, and it is your responsibility
to set one and to avoid duplicating owned pointers between slots.
License:
MIT License
Copyright (c) 2026 DcruBro
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef VECTOR_H
#define VECTOR_H
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
typedef void (*vector_destructor_t)(void* element); // Function pointer type for element destructor
/*
A vector. Do not construct, copy or modify this struct directly - the fields are
visible only because the functions below are inline. Create vectors with
vector_create() and use the accessors. A vector_t that did not come from
vector_create() is not a valid vector, and the functions will reject it where
they can and misbehave where they cannot.
*/
typedef struct {
size_t size; // Number of elements in the vector
size_t capacity; // Allocated capacity of the vector
size_t element_size; // Size of each element in the vector
void *data; // Pointer to the raw data array
vector_destructor_t destructor; // Function pointer to the element destructor
} vector_t;
/* Forward declarations */
static inline int vector_is_aliased(const vector_t* vec, const void* ptr);
static inline vector_t* vector_create(size_t element_size);
static inline int vector_set_destructor(vector_t* vec, vector_destructor_t destructor);
static inline vector_destructor_t vector_get_destructor(const vector_t* vec);
static inline int vector_reserve(vector_t* vec, size_t new_capacity);
static inline int vector_grow(vector_t* vec);
static inline int vector_prune(vector_t* vec);
static inline int vector_push_back(vector_t* vec, const void* element);
static inline int vector_pop_back(vector_t* vec);
static inline int vector_pop_at(vector_t* vec, size_t index);
static inline int vector_take_at(vector_t* vec, size_t index, void* out);
static inline int vector_take_back(vector_t* vec, void* out);
static inline int vector_insert(vector_t* vec, size_t index, const void* element);
static inline int vector_clear(vector_t* vec);
static inline int vector_set(vector_t* vec, size_t index, const void* element);
static inline int vector_is_empty(const vector_t* vec);
static inline void* vector_front(vector_t* vec);
static inline const void* vector_front_const(const vector_t* vec);
static inline void* vector_back(vector_t* vec);
static inline const void* vector_back_const(const vector_t* vec);
static inline void* vector_get(vector_t* vec, size_t index);
static inline const void* vector_get_const(const vector_t* vec, size_t index);
static inline size_t vector_size(const vector_t* vec);
static inline size_t vector_capacity(const vector_t* vec);
static inline size_t vector_element_size(const vector_t* vec);
static inline const void* vector_as_c_array(const vector_t* vec);
static inline void* vector_as_c_array_mutable(vector_t* vec);
static inline int vector_move(vector_t* dest, vector_t** src);
static inline vector_t* vector_deep_copy(const vector_t* vec);
static inline int vector_destroy(vector_t** vec);
/*
@brief Checks whether a pointer points inside the vector's own data array. Used internally to make the write functions safe against self-referential input.
@param vec A pointer to the vector to check against.
@param ptr The pointer to check.
@return 1 if the pointer lies within the vector's allocated buffer, 0 otherwise.
@attention This is an internal helper. You are not expected to call it directly, but it is harmless if you do.
*/
static inline int vector_is_aliased(const vector_t* vec, const void* ptr) {
if (!vec || !ptr || !vec->data) {
return 0; // Nothing to alias
}
// Compared as integers rather than pointers, as comparing pointers into
// different objects is not well defined.
uintptr_t base = (uintptr_t)vec->data;
uintptr_t end = base + (vec->capacity * vec->element_size);
uintptr_t target = (uintptr_t)ptr;
return target >= base && target < end;
}
/*
@brief Creates a new vector with the specified element size.
@param element_size The size of each element in the vector. Call with sizeof(type)
@return A pointer to the newly created vector, or NULL if allocation fails. The vector lives on the heap.
@attention The vector must be destroyed with vector_destroy() to free its memory. Failing to do so will result in a memory leak.
@attention The vector's initial capacity is set to 10. If you want to change the initial capacity globally, set the DLIBC_VECTOR_INITIAL_CAPACITY macro before including this header file. The initial capacity must be greater than 0.
@attention The vector's element size must be greater than 0. If you pass 0, the function will return NULL.
@attention The vector is created without an element destructor. If your elements own memory of their own, set one with vector_set_destructor().
*/
static inline vector_t* vector_create(size_t element_size) {
if (element_size == 0) {
return NULL; // Invalid element size
}
#ifndef DLIBC_VECTOR_INITIAL_CAPACITY
size_t initial_capacity = 10; // Default initial capacity
#else
#if DLIBC_VECTOR_INITIAL_CAPACITY <= 0
#error "DLIBC_VECTOR_INITIAL_CAPACITY must be greater than 0"
#endif
size_t initial_capacity = DLIBC_VECTOR_INITIAL_CAPACITY; // Use the macro if defined
#endif
if (SIZE_MAX / element_size < initial_capacity) {
return NULL; // Prevent overflow
}
vector_t* vec = (vector_t*)malloc(sizeof(vector_t));
if (!vec) {
return NULL; // Allocation failed
}
vec->size = 0;
vec->capacity = initial_capacity;
vec->element_size = element_size;
vec->destructor = NULL; // Initialize destructor to NULL
vec->data = malloc(vec->capacity * vec->element_size);
if (!vec->data) {
free(vec);
return NULL; // Allocation failed
}
return vec;
}
/*
@brief Sets the destructor function for the vector's elements. This function will be called on each element as it leaves the vector, allowing for custom cleanup of dynamically allocated memory within the elements.
@param vec A pointer to the vector for which to set the destructor.
@param destructor A function pointer to the destructor function, or NULL to remove the current one. The function should take a single void* parameter, which will be a pointer to the element to be destroyed.
@return 0 on success, -1 if the vector is NULL.
@attention If you do not set a destructor function, the vector will not automatically free any dynamically allocated memory within its elements when it is destroyed. You must ensure that you free any such memory manually before destroying the vector to avoid memory leaks.
@attention The destructor is passed a pointer to the element's slot inside the vector's data array, not a pointer returned by malloc(). It must free what the element owns and must never free the pointer it is given. For a vector of char*, the destructor body is free(*(char**)element);
@attention This assumes that your destructor function is valid and safe to call. If it isn't, bad things will happen and it will not be nice to watch.
@attention Set the destructor before adding any elements. Setting it on a vector that already holds elements is allowed, but elements that were removed beforehand will not have been destroyed.
*/
static inline int vector_set_destructor(vector_t* vec, vector_destructor_t destructor) {
if (!vec) {
return -1; // Invalid vector
}
vec->destructor = destructor;
return 0; // Success
}
/*
@brief Gets the destructor function currently set on the vector.
@param vec A pointer to the vector whose destructor is to be retrieved.
@return The vector's destructor function pointer, or NULL if the vector is NULL or has no destructor set.
*/
static inline vector_destructor_t vector_get_destructor(const vector_t* vec) {
if (!vec) {
return NULL; // Invalid vector
}
return vec->destructor;
}
/*
@brief Ensures the vector has room for at least the specified number of elements.
@param vec A pointer to the vector for which to reserve space.
@param new_capacity The minimum capacity the vector should have.
@return 0 on success, -1 if the vector is NULL, its element size is zero, or allocation fails.
@attention Capacity never decreases. If the vector already has room, this is a no-op and reports success.
@attention If the buffer does grow, it is reallocated, so any pointers into the vector's data are invalidated. Use vector_prune() to release unused memory.
*/
static inline int vector_reserve(vector_t* vec, size_t new_capacity) {
if (!vec) {
return -1; // Invalid vector
}
if (vec->element_size == 0) {
return -1; // Not a usable vector; also guards the division below
}
if (new_capacity <= vec->capacity) {
return 0; // Already have the room. Never shrink
}
if (new_capacity > SIZE_MAX / vec->element_size) {
return -1; // Prevent overflow
}
void* new_data = realloc(vec->data, new_capacity * vec->element_size);
if (!new_data) {
return -1; // Allocation failed
}
vec->data = new_data;
vec->capacity = new_capacity;
return 0; // Success
}
/*
@brief Grows the vector's capacity to make room for at least one more element. Used internally by the functions that add elements.
@param vec A pointer to the vector to grow.
@return 0 on success, -1 if the vector is NULL or allocation fails.
@attention This is an internal helper. You are not expected to call it directly.
*/
static inline int vector_grow(vector_t* vec) {
if (!vec) {
return -1; // Invalid vector
}
if (vec->capacity > SIZE_MAX / 2) {
return -1; // Prevent overflow
}
size_t new_capacity = vec->capacity > 0 ? vec->capacity * 2 : 1; // Double the capacity, or set to 1 if it was 0
return vector_reserve(vec, new_capacity);
}
/*
@brief Prunes the vector to free unused memory. If the vector's size is less than its capacity, this function will reallocate the vector's data array to match its size, freeing any unused memory.
@param vec A pointer to the vector to be pruned.
@return 0 on success, -1 if the vector is NULL or allocation fails.
@attention After calling this function, the vector's capacity will be equal to its size. Any pointers to the old data will be invalidated.
@attention Capacity may never drop below 1, even if the vector is empty.
*/
static inline int vector_prune(vector_t* vec) {
if (!vec) {
return -1; // Invalid vector
}
if (vec->element_size == 0) {
return -1; // Not a usable vector; also guards the division below
}
if (vec->size < vec->capacity) {
size_t new_capacity = vec->size > 0 ? vec->size : 1; // Ensure capacity is at least 1
if (new_capacity > SIZE_MAX / vec->element_size) {
return -1; // Prevent overflow
}
void* new_data = realloc(vec->data, new_capacity * vec->element_size);
if (!new_data) {
return -1; // Allocation failed
}
vec->data = new_data;
vec->capacity = new_capacity;
}
return 0; // Success
}
/*
@brief Adds an element to the end of the vector.
@param vec A pointer to the vector to which the element will be added.
@param element A pointer to the element to be added. The element will be copied into the vector's data array.
@return 0 on success, -1 if the vector is NULL, the element is NULL, if the element is an owning element that is aliased in the vector and a destructor is set, or if reservation fails.
@attention The element must be a pointer to a valid memory location containing data of the same type as the vector's element type. The vector will make a copy of the data, so the original element can be modified or freed after this function returns.
@attention The element may point into the vector's own data array. If growing the vector moves the data, the pointer is followed to its new location automatically.
*/
static inline int vector_push_back(vector_t* vec, const void* element) {
if (!vec || !element) {
return -1; // Invalid vector or element
}
if (vec->destructor && vector_is_aliased(vec, element)) {
return -1; // Refuse to push an owning element that lives inside the vector
}
if (vec->size >= vec->capacity) {
// If the element lives inside our own data array, remember where it sits
// so that we can find it again after the data has been reallocated.
// This must happen before the growth, while the old buffer is still valid
size_t offset = 0;
int aliased = vector_is_aliased(vec, element);
if (aliased) {
offset = (size_t)((const char*)element - (const char*)vec->data);
}
if (vector_grow(vec) != 0) {
return -1; // Failed to grow the vector
}
if (aliased) {
element = (const char*)vec->data + offset;
}
}
// Copy the new element into the vector's data array
memmove((char*)vec->data + (vec->size * vec->element_size), element, vec->element_size);
vec->size++;
return 0; // Success
}
/*
@brief Removes the last element from the vector.
@param vec A pointer to the vector from which the element will be removed.
@return 0 on success, -1 if the vector is NULL or empty.
@attention After calling this function, the vector's size will be reduced by one. The memory occupied by the removed element will not be freed automatically unless a destructor is set (in which case, the destructor will be called on the element being removed if it is set). Use vector_take_back() to retrieve the last element, remove it from the vector, and NOT call the destructor on it (hands ownership to the caller).
*/
static inline int vector_pop_back(vector_t* vec) {
if (!vec || vec->size == 0) {
return -1; // Invalid vector or empty vector
}
if (vec->destructor) {
void* element = (char*)vec->data + ((vec->size - 1) * vec->element_size);
vec->destructor(element); // Call the destructor for the last element
}
vec->size--;
return 0; // Success
}
/*
@brief Removes the element at the specified index from the vector.
@param vec A pointer to the vector from which the element will be removed.
@param index The index of the element to be removed.
@return 0 on success, -1 if the vector is NULL or the index is out of bounds.
@attention After calling this function, the vector's size will be reduced by one. The memory occupied by the removed element will not be freed automatically unless a destructor is set (in which case, the destructor will be called on the element being removed if it is set). Use vector_take_at() to retrieve the element at the specified index, remove it from the vector, and NOT call the destructor on it (hands ownership to the caller).
*/
static inline int vector_pop_at(vector_t* vec, size_t index) {
if (!vec || index >= vec->size) {
return -1; // Invalid vector or index out of bounds
}
if (vec->destructor) {
void* element = (char*)vec->data + (index * vec->element_size);
vec->destructor(element); // Call the destructor for the element to be removed
}
// Move elements after the index one position to the left
if (index + 1 < vec->size) {
memmove((char*)vec->data + (index * vec->element_size),
(char*)vec->data + ((index + 1) * vec->element_size),
(vec->size - index - 1) * vec->element_size);
}
vec->size--;
return 0; // Success
}
/*
@brief Removes the element at the specified index and transfers ownership of it to the caller.
@param vec A pointer to the vector from which the element will be taken.
@param index The index of the element to take.
@param out A pointer to a buffer of at least vector_element_size(vec) bytes, which the element is copied into.
@return 0 on success, -1 if the vector is NULL, out is NULL, out points into the vector's own data, or the index is out of bounds.
@attention The element destructor is deliberately NOT called. Whatever the element owns becomes the caller's responsibility to free.
@attention out must not point into the vector's own data array. Doing so would leave two slots owning the same memory and is rejected with -1.
*/
static inline int vector_take_at(vector_t* vec, size_t index, void* out) {
if (!vec || index >= vec->size || !out) {
return -1; // Invalid vector, index out of bounds, or output pointer is NULL
}
if (vector_is_aliased(vec, out)) {
return -1; // Refuse to take an element into a pointer that lives inside the vector
}
void* slot = (char*)vec->data + (index * vec->element_size);
memcpy(out, slot, vec->element_size); // Copy the element to the output pointer
// Move elements after the index one position to the left
if (index + 1 < vec->size) {
memmove(slot,
(char*)vec->data + ((index + 1) * vec->element_size),
(vec->size - index - 1) * vec->element_size);
}
vec->size--;
return 0; // Success
}
/*
@brief Removes the last element from the vector and transfers ownership of it to the caller.
@param vec A pointer to the vector from which the element will be taken.
@param out A pointer to a buffer of at least vector_element_size(vec) bytes, which the element is copied into.
@return 0 on success, -1 if the vector is NULL, empty, if out aliases the vector's data, or out is NULL.
@attention The element destructor is deliberately NOT called. Whatever the element owns becomes the caller's responsibility to free.
*/
static inline int vector_take_back(vector_t* vec, void* out) {
if (!vec || vec->size == 0 || !out) {
return -1; // Invalid vector, empty vector, or output pointer is NULL
}
return vector_take_at(vec, vec->size - 1, out); // Take the last element
}
/*
@brief Inserts an element at the specified index in the vector.
@param vec A pointer to the vector into which the element will be inserted.
@param index The index at which to insert the element.
@param element A pointer to the element to be inserted. The element will be copied into the vector's data array.
@return 0 on success, -1 if the vector is NULL, the element is NULL, the index is out of bounds, if the element is an owning element that is aliased in the vector and a destructor is set, or if reservation fails.
@attention After calling this function, the vector's size will be increased by one and every element from the index onwards will have moved one position to the right. Any pointers into the vector are invalidated.
@attention The element may point into the vector's own data array. Its value is copied aside first, so that neither the reallocation nor the shifting of elements can corrupt it.
*/
static inline int vector_insert(vector_t* vec, size_t index, const void* element) {
if (!vec || !element || index > vec->size) {
return -1; // Invalid vector, element, or index out of bounds
}
if (vec->destructor && vector_is_aliased(vec, element)) {
return -1; // Refuse to insert an owning element that lives inside the vector
}
// If the element lives inside our own data array, take a copy of it now. Both
// the reservation below and the shifting of elements would otherwise destroy
// the value before it can be read
void* temp = NULL;
if (vector_is_aliased(vec, element)) {
temp = malloc(vec->element_size);
if (!temp) {
return -1; // Allocation failed
}
memcpy(temp, element, vec->element_size);
element = temp;
}
if (vec->size >= vec->capacity) {
if (vector_grow(vec) != 0) {
free(temp);
return -1; // Failed to grow the vector
}
}
// Move elements after the index one position to the right
memmove((char*)vec->data + ((index + 1) * vec->element_size),
(char*)vec->data + (index * vec->element_size),
(vec->size - index) * vec->element_size);
// Copy the new element into the vector's data array at the specified index
memcpy((char*)vec->data + (index * vec->element_size), element, vec->element_size);
vec->size++;
free(temp); // Harmless if no copy was needed, as temp is NULL in that case
return 0; // Success
}
/*
@brief Clears all elements from the vector.
@param vec A pointer to the vector to be cleared.
@return 0 on success, -1 if the vector is NULL.
@attention After calling this function, the vector's size will be zero. The memory occupied by the elements will not be freed automatically unless a destructor is set.
@attention The vector's capacity is left untouched, so the vector may be refilled without reallocating. Call vector_prune() afterwards if you want the memory back.
*/
static inline int vector_clear(vector_t* vec) {
if (!vec) {
return -1; // Invalid vector
}
if (vec->destructor) {
for (size_t i = 0; i < vec->size; ++i) {
void* element = (char*)vec->data + (i * vec->element_size);
vec->destructor(element); // Call the destructor for each element
}
}
vec->size = 0;
return 0; // Success
}
/*
@brief Sets the element at the specified index in the vector, overwriting whatever was there before.
@param vec A pointer to the vector in which to set the element.
@param index The index of the element to set.
@param element A pointer to the element to set. The element will be copied into the vector's data array.
@return 0 on success, -1 if the vector is NULL, the element is NULL, if the element is an owning element that is aliased in the vector and a destructor is set, or if the index is out of bounds.
@attention This never grows the vector. The index must be below the current size.
@attention If a destructor is set, it is called on the element being overwritten before the new value is copied in.
@attention Setting an element to itself is a no-op and reports success.
@attention On a vector without a destructor, the element may point into the
vector's own data array; the copy handles any overlap. On a vector with a
destructor this is refused with -1, as it would leave two slots owning the
same memory.
*/
static inline int vector_set(vector_t* vec, size_t index, const void* element) {
if (!vec || !element || index >= vec->size) {
return -1; // Invalid vector, element, or index out of bounds
}
void* slot = (char*)vec->data + (index * vec->element_size);
if (slot == element) {
return 0; // Setting the element to itself, no action needed
}
if (vec->destructor && vector_is_aliased(vec, element)) {
return -1; // Refuse to set an owning element that lives inside the vector
}
if (vec->destructor) {
vec->destructor(slot); // Call the destructor for the element being overwritten
}
memmove(slot, element, vec->element_size); // memmove, as the element may overlap the slot
return 0; // Success
}
/*
@brief Checks if the vector is empty.
@param vec A pointer to the vector to check.
@return 1 if the vector is empty, 0 if it is not empty.
@attention If the vector is NULL, this function will return 1 (is empty) to indicate that the vector is invalid.
*/
static inline int vector_is_empty(const vector_t* vec) {
if (!vec) {
return 1; // Invalid vector
}
return vec->size == 0;
}
/*
@brief Gets a pointer to the first element in the vector.
@param vec A pointer to the vector from which to get the element.
@return A pointer to the first element in the vector, or NULL if the vector is NULL or empty.
@attention The returned pointer is a generic. You should cast it to the appropriate type before using it. The pointer will become invalid if the vector is resized or destroyed.
*/
static inline void* vector_front(vector_t* vec) {
if (!vec || vec->size == 0) {
return NULL; // Invalid vector or empty vector
}
return vec->data;
}
/*
@brief Gets a const pointer to the first element in the vector. Cannot be used to modify the element.
@param vec A pointer to the vector from which to get the element.
@return A constant pointer to the first element in the vector, or NULL if the vector is NULL or empty.
@attention The returned pointer is a generic. You should cast it to the appropriate type before using it. The pointer will become invalid if the vector is resized or destroyed.
*/
static inline const void* vector_front_const(const vector_t* vec) {
if (!vec || vec->size == 0) {
return NULL; // Invalid vector or empty vector
}
return vec->data;
}
/*
@brief Gets a pointer to the last element in the vector.
@param vec A pointer to the vector from which to get the element.
@return A pointer to the last element in the vector, or NULL if the vector is NULL or empty.
@attention The returned pointer is a generic. You should cast it to the appropriate type before using it. The pointer will become invalid if the vector is resized or destroyed.
*/
static inline void* vector_back(vector_t* vec) {
if (!vec || vec->size == 0) {
return NULL; // Invalid vector or empty vector
}
return (char*)vec->data + ((vec->size - 1) * vec->element_size);
}
/*
@brief Gets a const pointer to the last element in the vector. Cannot be used to modify the element.
@param vec A pointer to the vector from which to get the element.
@return A constant pointer to the last element in the vector, or NULL if the vector is NULL or empty.
@attention The returned pointer is a generic. You should cast it to the appropriate type before using it. The pointer will become invalid if the vector is resized or destroyed.
*/
static inline const void* vector_back_const(const vector_t* vec) {
if (!vec || vec->size == 0) {
return NULL; // Invalid vector or empty vector
}
return (const char*)vec->data + ((vec->size - 1) * vec->element_size);
}
/*
@brief Gets a pointer to the element at the specified index in the vector.
@param vec A pointer to the vector from which to get the element.
@param index The index of the element to get.
@return A pointer to the element at the specified index, or NULL if the vector is NULL or the index is out of bounds.
@attention The returned pointer is a generic. You should cast it to the appropriate type before using it. The pointer will become invalid if the vector is resized or destroyed.
@attention For most read-only operations, consider using vector_get_const() instead, which returns a const pointer to the element.
*/
static inline void* vector_get(vector_t* vec, size_t index) {
if (!vec || index >= vec->size) {
return NULL; // Invalid vector or index out of bounds
}
return (char*)vec->data + (index * vec->element_size);
}
/*
@brief Gets a constant pointer to the element at the specified index in the vector. Cannot be used to modify the element.
@param vec A pointer to the vector from which to get the element.
@param index The index of the element to get.
@return A constant pointer to the element at the specified index, or NULL if the vector is NULL or the index is out of bounds.
@attention The returned pointer is a generic. You should cast it to the appropriate type before using it. The pointer will become invalid if the vector is resized or destroyed.
*/
static inline const void* vector_get_const(const vector_t* vec, size_t index) {
if (!vec || index >= vec->size) {
return NULL; // Invalid vector or index out of bounds
}
return (const char*)vec->data + (index * vec->element_size);
}
/*
@brief Gets the size of the vector.
@param vec A pointer to the vector whose size is to be retrieved.
@return The size of the vector, or 0 if the vector is NULL.
*/
static inline size_t vector_size(const vector_t* vec) {
if (!vec) {
return 0; // Invalid vector
}
return vec->size;
}
/*
@brief Gets the capacity of the vector.
@param vec A pointer to the vector whose capacity is to be retrieved.
@return The capacity of the vector, or 0 if the vector is NULL.
*/
static inline size_t vector_capacity(const vector_t* vec) {
if (!vec) {
return 0; // Invalid vector
}
return vec->capacity;
}
/*
@brief Gets the size of each element in the vector.
@param vec A pointer to the vector whose element size is to be retrieved.
@return The size of each element in the vector, or 0 if the vector is NULL.
*/
static inline size_t vector_element_size(const vector_t* vec) {
if (!vec) {
return 0; // Invalid vector
}
return vec->element_size;
}
/*
@brief Gets a pointer to the underlying C array of the vector. Cannot modify the vector through this pointer.
@param vec A pointer to the vector whose underlying array is to be retrieved.
@return A pointer to the underlying C array, or NULL if the vector is NULL.
@attention The returned pointer is a generic. You should cast it to the appropriate type before using it. The pointer will become invalid if the vector is resized or destroyed.
*/
static inline const void* vector_as_c_array(const vector_t* vec) {
if (!vec) {
return NULL; // Invalid vector
}
return vec->data;
}
/*
@brief Gets a pointer to the underlying C array of the vector. Can be used to modify the vector's elements.
@param vec A pointer to the vector whose underlying array is to be retrieved.
@return A pointer to the underlying C array, or NULL if the vector is NULL.
@attention The returned pointer is a generic. You should cast it to the appropriate type before using it. The pointer will become invalid if the vector is resized or destroyed.
*/
static inline void* vector_as_c_array_mutable(vector_t* vec) {
if (!vec) {
return NULL; // Invalid vector
}
return vec->data;
}
/*
@brief Moves a vector to another vector, transferring ownership of the data. The destination vector will take ownership of the source vector's data, its element size and its destructor.
@param dest A pointer to the destination vector.
@param src A pointer to the pointer holding the source vector. It will be set to NULL.
@return 0 on success, -1 if the destination vector is NULL, the source pointer is NULL, the source vector is NULL, or both vectors share the same data pointer.
@attention After calling this function, the source vector will be freed (excluding data) and the source pointer will be set to NULL, so it cannot be used again.
@attention The destination vector's existing elements will be destroyed (using the destination's own destructor, if it has one) and its data freed. Ensure that you do not need the existing data before calling this function.
@attention Moving a vector onto itself is a no-op and reports success, leaving the vector untouched.
@attention Two vectors can only share a data pointer if a vector_t was duplicated by copying the struct, which is never valid. The move is refused rather than freeing a buffer the source still points at.
*/
static inline int vector_move(vector_t* dest, vector_t** src) {
if (!dest || !src || !*src) {
return -1; // Invalid vectors
}
if (dest == *src) {
return 0; // Moving to itself, no action needed
}
if (dest->data == (*src)->data) {
return -1; // Refuse to move a vector onto another vector that shares its data
// Realistically, this is unreachable via legal use, but... safety.
// Or something. You WILL trigger this if you do shallow copies. DO NOT!
}
// Destroy the destination vector's existing elements with its own destructor,
// then free its data, as it is about to be replaced
vector_clear(dest);
free(dest->data);
// Transfer ownership of the source vector's data to the destination vector
dest->size = (*src)->size;
dest->capacity = (*src)->capacity;
dest->element_size = (*src)->element_size;
dest->data = (*src)->data;
dest->destructor = (*src)->destructor; // The elements keep the cleanup they came with
// Reset the source vector to an empty state
(*src)->size = 0;
(*src)->capacity = 0;
(*src)->element_size = 0;
(*src)->data = NULL;
(*src)->destructor = NULL;
free(*src); // Free the source vector structure, but not its data (ownership transferred)
*src = NULL;
return 0; // Success
}
/*
@brief Creates a deep copy of the vector, including its data.
@param vec A pointer to the vector to be copied.
@return A pointer to the newly created deep copy of the vector, or NULL if allocation fails, if the input vector is NULL, or if the input vector has a destructor set.
@attention The returned vector must be destroyed with vector_destroy() to free its memory. Failing to do so will result in a memory leak.
@attention Vectors with a destructor cannot be deep copied and this function will return NULL for them. The elements are copied byte for byte, so any memory they own would end up owned by both vectors and freed twice. If you need to copy such a vector, do it by hand: create a new vector and push copies of the elements into it yourself.
*/
static inline vector_t* vector_deep_copy(const vector_t* vec) {
if (!vec) {
return NULL; // Invalid vector
}
if (vec->destructor) {
return NULL; // Refuse to byte-copy elements that own memory
}
vector_t* new_vec = vector_create(vec->element_size);
if (!new_vec) {
return NULL; // Allocation failed
}
int r = vector_reserve(new_vec, vec->capacity);
if (r != 0) {
vector_destroy(&new_vec);
return NULL; // Allocation failed
}
if (vec->size > 0) {
memcpy(new_vec->data, vec->data, vec->size * vec->element_size);
new_vec->size = vec->size;
} // vector_create() already sets size to 0 by default
return new_vec;
}
/*
@brief Destroys the vector and frees its memory.
@param vec A pointer to the pointer holding the vector to be destroyed. It will be set to NULL.
@return 0 on success, or if the vector was already NULL. -1 only if the pointer itself is NULL.
@attention After calling this function, the vector pointer should not be used again (It will be set to NULL). Accessing it after destruction will lead to undefined behavior.
@attention Only the pointer you pass in is set to NULL. Copies of that pointer held elsewhere are left dangling and must not be used.
@attention If stored elements own memory of their own, set a destructor with vector_set_destructor() to have it cleaned up here. Otherwise, the vector will only free the memory allocated for the data array and the vector structure itself, but not any dynamically allocated memory within the elements.
*/
static inline int vector_destroy(vector_t** vec) {
if (!vec) {
return -1; // Invalid pointer
}
if (!(*vec)) {
return 0; // Already NULL, nothing to destroy
}
vector_t* target = *vec;
if (target->destructor) {
for (size_t i = 0; i < target->size; ++i) {
void* element = (char*)target->data + (i * target->element_size);
target->destructor(element); // Call the destructor for each element
}
}
free(target->data);
free(target);
*vec = NULL; // Set the pointer to NULL to avoid dangling references
return 0; // Success
}
#endif // VECTOR_H
+2 -1
View File
@@ -54,9 +54,10 @@ bravais_result_t bravais_conn_create(const bravais_config_t* config, bravais_con
void bravais_conn_destroy(bravais_conn_t* conn) {
if (!conn) { return; }
conn_log(conn, BRAVAIS_LOG_LEVEL_DEBUG, "Connection destroyed");
bravais_hygiene_zero(conn, sizeof(*conn));
free(conn);
conn_log(conn, BRAVAIS_LOG_LEVEL_DEBUG, "Connection destroyed");
}
bravais_result_t bravais_recv_datagram(bravais_conn_t* conn, const uint8_t* buf, size_t bufLen, [[maybe_unused]] uint64_t nowMs) {
+115
View File
@@ -0,0 +1,115 @@
// context.c
// The context, connection table and public API surface
// v0 - lifecycle, connection table and event delivery; data path is stubbed
#include "proto/context.h"
#include "util/hygiene.h"
#include <stdlib.h>
#include <string.h>
#define BRAVAIS_DEFAULT_MAX_CONNS 1024
#define BRAVAIS_MAX_CONNS_LIMIT (UINT32_C(1) << 20)
#define BRAVAIS_INITIAL_SLOT_COUNT 8
/* HELPERS */
void bravais_log(const bravais_context_t* ctx, bravais_log_level_t level, const char* message) {
if (!ctx || !ctx->config.logFn) { return; }
ctx->config.logFn(ctx->config.logUserData, level, message);
}
// An all-zero key will almost never happen, but we'll have this just in case
static bool key_is_zero(const uint8_t* key, size_t len) {
uint8_t acc = 0;
for (size_t i = 0; i < len; i++) {
acc |= key[i]; // Actually a pretty cool method instead of an if statement every iteration
}
return acc == 0;
}
static bool transport_mode_is_valid(bravais_transport_mode_t transportMode) {
// UNSET is defined as invalid
return transportMode == BRAVAIS_TRANSPORT_MODE_RAW || transportMode == BRAVAIS_TRANSPORT_MODE_QUIC;
}
/* CONNECTION TABLE */
static uint64_t conn_id_make(uint32_t index, uint32_t generation) {
return ((uint64_t)generation << 32) | index; // bottom/top rule - see the header comment
}
static void conn_id_disassemble(uint64_t connId, uint32_t* index, uint32_t* generation) {
if (!index || !generation) { return; }
*index = (uint32_t)connId;
*generation = (uint32_t)(connId >> 32);
}
static bravais_conn_slot_t* slot_from_id(const bravais_context_t* ctx, uint64_t connId) {
if (!ctx->slots) { return nullptr; }
uint32_t index;
uint32_t generation;
conn_id_disassemble(connId, &index, &generation);
if (generation == 0 || index >= vector_size(ctx->slots)) { return nullptr; }
bravis_conn_slot_t* slot = (bravais_conn_slot_t*)vector_get(ctx->slots, index);
if (!slot || !slot->conn || slot->generation != generation) { return nullptr; }
return slot;
}
// Takes ownership of conn on success only
static bravais_result_t context_insert(bravais_context_t* ctx, bravais_conn_t* conn, uint64_t* outConnId) {
if (!ctx->slots) { return; }
size_t slotCount = vector_size(ctx->slots);
uint32_t index = (uint32_t)slotCount;
for (uint32_t i = 0; i < slotCount; i++) {
const bravais_conn_slot_t* temp = (const bravais_conn_slot_t*)vector_get_const(ctx->slots, i);
if (!temp->conn) {
index = i; // We do this for reuse of dead slots instead of just adding a new entry
break;
}
}
if (index == slotCount) {
if (slotCount >= ctx->maxConns) { return BRAVAIS_ERR_CONN_LIMIT; }
bravais_conn_slot_t slot = {
.conn = conn,
.generation = 1
};
vector_push_back(ctx->slots, &slot);
*outConnId = conn_id_make(index, 1); // 1 is hardcoded here since it's a brand new element; TODO: figure out if bugs arise
return BRAVAIS_OK;
/*uint32_t newCount = slotCount == 0 ? BRAVAIS_INITIAL_SLOT_COUNT : slotCount * 2;
if (newCount > ctx->maxCoons) {
newCount = ctx->maxConns;
}
if (vector_reserve(ctx->slots, newCount) < 0) {
return BRAVAIS_ERR_OUT_OF_MEMORY;
}
// There's probably a better way to do this (i.e. put it in vector.h), but whatever
bravais_conn_slot_t* ptr = (bravais_conn_slot_t*)vector_as_c_array_mutable(ctx->slots);
memset(ptr + slotCount, 0x00, (size_t)(newCount - slotCount) * sizeof(*ptr));*/
}
// Not the last element, change
bravais_conn_slot_t* slot = (bravais_conn_slot_t*)vector_get(ctx->slots, index);
slot->generation++; // Bump the generation
if (slot->generation == 0) {
// uint wraps to 0, 0 is invalid, skip
slot->generation = 1;
}
slot->conn = conn;
// Copy-pasting code, oh well
*outConnId = conn_id_make(index, slot->generation);
return BRAVAIS_OK;
}
+30
View File
@@ -0,0 +1,30 @@
// context.h
// Context internals - the connection table
//
// Connection IDs pack a slot index (low 32 bits) and that slot's generation (high 32 bits).
// A slot's gen is bumped each occupation and is NEVER 0 (BRAVAIS_NO_CONN).
// Never names a live connection, and an ID whose slot was free'd and reused fails lookup instead of reaching the new occupant.
// IDs are internal bookkeeping and NEVER go on the wire.
#ifndef BRAVAIS_CONTEXT_H
#define BRAVAIS_CONTEXT_H
#include "bravais.h"
#include "proto/conn.h"
#include "dlibc/vector.h"
typedef struct {
bravais_conn_t* conn; // nullptr when free
uint32_t generation;
} bravais_conn_slot_t;
struct bravais_context {
bravais_context_config_t config; // Holds the private key, beware! (wipe on destroy)
uint32_t maxConns;
vector_t* slots; // Slots of bravais_conn_slot_t
}
// Safe to call with a context without a log callback
void bravais_log(const bravais_context_t* ctx, bravais_log_level_t level, const char* message);
#endif // BRAVAIS_CONTEXT_H
+2 -5
View File
@@ -8,14 +8,11 @@
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include "bravais.h"
static const uint8_t bravaisEndpointMappedIPv4Prefix[12] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff };
typedef struct bravais_endpoint {
uint8_t address[16]; // IPv6 address (or IPv4-mapped IPv6) - network byte order
uint16_t port; // Port number - host byte order
} bravais_endpoint_t;
bool bravais_endpoint_is_ipv4(const bravais_endpoint_t* endpoint);
#endif // BRAVAIS_ENDPOINT_H
+1
View File
@@ -3,6 +3,7 @@
#include <stdint.h>
#include <string.h>
// This apparently stops the compiler from optimizing away the memset
static void* (*volatile volatileMemset)(void*, int, size_t) = memset;
void bravais_hygiene_zero(void* ptr, size_t len) {