Files
coms/server/src/include/session.h
2026-02-14 16:02:53 -05:00

97 lines
2.6 KiB
C

#ifndef SESSION_H
#define SESSION_H
#include <libwebsockets.h>
#include <stdbool.h>
#include <stdint.h>
// Includes terminating null.
#define SESSION_USERNAME_MAX_LEN 32
#define SESSION_CHAT_BUF_SIZE 1024
/**
* session_t
* Represents a single WebSocket client session in the chat server.
*/
typedef struct SESSION {
struct lws* wsi; // Libwebsockets connection handle.
uint64_t id; // Unique session ID.
struct SESSION* next; // Next session in the internal list.
char name[SESSION_USERNAME_MAX_LEN]; // Stored username.
bool named; // True once username is set.
unsigned char buf[LWS_PRE + SESSION_CHAT_BUF_SIZE]; // Outgoing buffer per session
size_t buf_len; // Length of data in buf
} Session;
/**
* session_create
* Allocate and initialize a new session, adding it to the internal list.
*
* @param wsi The libwebsockets connection handle.
* @return Pointer to the new session, or NULL on failure.
*/
Session* session_create(struct lws* wsi);
/**
* session_destroy
* Remove the given session from the internal list and free its memory.
*
* @param sess The session to destroy.
*/
void session_destroy(Session* sess);
/**
* session_get_head
* Retrieve the head of the internal session linked list.
*
* @return The first session in the list, or NULL if none.
*/
Session* session_get_head(void);
/**
* session_broadcast
* Iterate every session in the internal list and invoke the callback.
*
* @param cb Function to call for each session.
* @param user Arbitrary user data passed through to each callback.
*/
void session_broadcast(void (*cb)(Session* sess, void* user), void* user);
/**
* session_set_username
* Store a username in the given session.
*
* @param sess The session to update.
* @param username Null-terminated string to copy into the session.
*/
void session_set_username(Session* sess, const char* username);
/**
* session_get_username
* Fetch the username stored in the session.
*
* @param sess The session to query.
* @return Pointer to the stored username (readonly).
*/
const char* session_get_username(const Session* sess);
/**
* session_has_username
* Check whether a session has already set a username.
*
* @param sess The session to query.
* @return True if a username is set, false otherwise.
*/
bool session_has_username(const Session* sess);
/**
* session_get_id
* Fetch the session ID.
*
* @param sess The session to query.
* @return The session's unique ID.
*/
uint64_t session_get_id(const Session* sess);
#endif // SESSION_H