axil(3)axil

NAME

axil - axil API

- Core API and configuration types.

SYNOPSIS

Data Structures

struct axil_config
struct cmd_slot

Macros

#define ENV_KEY_LEN 128
#define ENV_LEN (BUFSIZ * 2)
#define ENV_VALUE_LEN (ENV_LEN - ENV_KEY_LEN - 2)
#define TELNET_CMD(fd, ...)

Typedefs

typedef int socket_t

Socket descriptor type.

typedef int axil_handler_t(socket_t cfd, char *body)
typedef socket_t axil_ws_upstream_t(socket_t client_fd)

Enumerations

enum descr_flags { DF_CONNECTED = 1, DF_WEBSOCKET = 4, DF_TO_CLOSE = 8, DF_ACCEPTED = 16, DF_AUTHENTICATED = 32, DF_TUNNEL = 64, DF_WS_WAITING = 128, DF_WS_PROXY_PENDING = 256, DF_EXTERN = 512, DF_HEAD = 1024, DF_DEFERRED = 2048, DF_AUTH_AUTO = 4096, DF_UNIX = 8192 }
enum axil_srv_flags { AXIL_WAKE = 1, AXIL_SSL = 2, AXIL_ROOT = 4, AXIL_SSL_ONLY = 8, AXIL_DETACH = 16, AXIL_AUTOAUTH = 32, AXIL_LOOPBACK = 64 }
enum axil_req_flags { AXIL_POST = 1, AXIL_PUT = 2, AXIL_DELETE = 4, AXIL_HEAD = 8, AXIL_OPTIONS = 16 }
enum cmd_flags { CF_NOAUTH = 1, CF_NOTRIM = 2 }

Functions

void axil_register (char *name, axil_cb_t *cb, int flags)
int axil_main (void)
void axil_stop (void)
void axil_register_handler (char *path, axil_handler_t handler)
int axil_register_fallback_handler (axil_handler_t handler)
int axil_deny_prefix (const char *prefix)
int axil_proxy_prefix (const char *prefix, const char *host, unsigned short port)
void axil_ws_handler (char *path, axil_ws_upstream_t handler)
int axil_ws_upgrade (socket_t fd)
int axil_ws_write (socket_t fd, const void *data, size_t len)
ssize_t axil_ws_read (socket_t fd, void *buf, size_t len)
int axil_ws_close (socket_t fd)
int axil_ws_printf (socket_t fd, const char *fmt,...)
int axil_post_chroot (void) WEAK
void axil_post_bind (void) WEAK
void axil_update (unsigned long long dt) WEAK
void axil_vim (socket_t fd, int argc, char *argv[]) WEAK
int axil_accept (socket_t fd) WEAK
int axil_connect (socket_t fd) WEAK
void axil_disconnect (socket_t fd) WEAK
void axil_command (socket_t fd, int argc, char *argv[]) WEAK
void axil_flush (socket_t fd, int argc, char *argv[]) WEAK
char * axil_auth_check (socket_t fd) WEAK
int axil_write (socket_t fd, void *data, size_t len)
int axil_dwritef (socket_t fd, const char *fmt, va_list va)
int axil_writef (socket_t fd, const char *fmt,...)
void axil_wall (const char *msg)
int axil_flags (socket_t fd)
unsigned long long axil_generation (socket_t fd)
void axil_close (socket_t fd)
void axil_set_flags (socket_t fd, int flags)
int axil_auth (socket_t fd, char *username)
unsigned axil_env (socket_t fd)
void axil_cert_add (char *str)
void axil_certs_add (char *fname)
ssize_t axil_mmap (char **mapped, char *file)
char * axil_mmap_iter (char *start, size_t *pos)
void axil_env_clear (socket_t fd)
int axil_env_get (socket_t fd, char *target, size_t dest_len, char *key)
int axil_env_put (socket_t fd, char *key, char *value)
int axil_query_parse (char *body)
int axil_query_param (const char *name, char *buf, size_t buf_len)
int axil_param (socket_t fd, const char *name, char *buf, size_t buf_len)
int axil_param_int (socket_t fd, const char *name, int default_val)
int axil_param_bool (socket_t fd, const char *name, int default_val)
int axil_req_param (socket_t fd, const char *body, const char *name, char *buf, size_t buf_len)
int axil_req_param_int (socket_t fd, const char *body, const char *name, int default_val)
int axil_req_param_bool (socket_t fd, const char *body, const char *name, int default_val)
const char * axil_status_text (int code)
int axil_url_encode (const char *in, char *out, size_t outlen)
size_t axil_url_decode (const char *src, size_t src_len, char *out, size_t out_len)
int axil_json_escape (const char *in, char *out, size_t outlen)
int axil_slugify (const char *title, size_t title_len, char *result, size_t result_len)
int axil_get_pw (socket_t fd, struct passwd *out)
void axil_fd_watch (socket_t fd)
void axil_fd_unwatch (socket_t fd)
void axil_fork_child_reset (void)
int axil_peer_cred (socket_t fd, uid_t *uid, gid_t *gid)
int axil_privsep_key (unsigned char out[32])
int axil_drop_ids (uid_t *uid, gid_t *gid)
void axil_header_set (socket_t fd, const char *key, const char *value)
int axil_header_get (socket_t fd, const char *key, char *buf, size_t buf_len)
void axil_respond (socket_t fd, int code, const char *body)
void * axil_respond_defer (socket_t fd, int code)
void axil_respond_defer_finish (void *handle, const char *body)
void axil_respond_defer_done (void *handle)
void axil_respond_defer_abort (void *handle)
int axil_respond_file (socket_t fd, const char *path, const char *allowed_exts)
void axil_sendfile (socket_t fd, const char *path)
void axil_exec (socket_t cfd, char *const args[], cmd_cb_t callback, void *input, size_t input_len)
int axil_exec_loop (socket_t cfd)

Variables

char axil_execbuf [BUFSIZ *64]

Detailed Description

Core API and configuration types.

Macro Definition Documentation

#define ENV_KEY_LEN 128

Max key size for request environment.

#define ENV_LEN (BUFSIZ * 2)

Maximum environment string size.

#define ENV_VALUE_LEN (ENV_LEN - ENV_KEY_LEN - 2)

Max value size for request environment.

#define TELNET_CMD( fd, ...)

Value:

    do { \
    unsigned char _tc[] = { __VA_ARGS__ }; \
    axil_send_telnet_cmd(fd, _tc, sizeof(_tc)); \
} while (0)

Build and send a TELNET command from a literal byte sequence.

Typedef Documentation

typedef int axil_handler_t(socket_t cfd, char *body)

HTTP handler callback signature.

body points at the request body: exactly Content-Length bytes, NUL-terminated, so strlen(body) gives its length. A request without a Content-Length has an empty body. A final read can overshoot Content-Length with the start of a following request; those bytes are discarded.

typedef socket_t axil_ws_upstream_t(socket_t client_fd)

WebSocket tunnel callback: connects to upstream and returns socket. axil handles forwarding the HTTP upgrade request, reading the response, and establishing the tunnel.

Enumeration Type Documentation

enum axil_req_flags

Request flags used internally.

Enumerator

AXIL_POST
Request is POST.
AXIL_PUT
Request is PUT.
AXIL_DELETE
Request is DELETE.
AXIL_HEAD
Request is HEAD.
AXIL_OPTIONS
Request is OPTIONS.

enum axil_srv_flags

Server configuration flags.

Enumerator

AXIL_WAKE
Wake on activity.
AXIL_SSL
Enable TLS.
AXIL_ROOT
Root multiplex mode.
AXIL_SSL_ONLY
Redirect HTTP to HTTPS when SSL enabled.
AXIL_DETACH
Detach into the background.
AXIL_AUTOAUTH
Auto-authenticate all WebSocket connections (dev/testing only).
AXIL_LOOPBACK
Bind listening sockets to 127.0.0.1 instead of INADDR_ANY.

enum cmd_flags

Command flags.

Enumerator

CF_NOAUTH
Allow command without authentication.
CF_NOTRIM
Do not trim trailing CR from input.

enum descr_flags

Descriptor state flags.

Enumerator

DF_CONNECTED
Connection established and accepted.
DF_WEBSOCKET
WebSocket mode enabled.
DF_TO_CLOSE
Marked to close after remaining output.
DF_ACCEPTED
Accepted socket (pre-WS).
DF_AUTHENTICATED
Authenticated user.
DF_TUNNEL
Part of a tunnel pair.
DF_WS_WAITING
Waiting for upstream websocket upgrade response.
DF_EXTERN
Externally-watched fd: skip client processing, dispatch via on_fd_tick.
DF_HEAD
Request is HEAD: suppress response body.
DF_DEFERRED
Response deferred: headers sent, body pending axil_respond_defer_finish/done.
DF_AUTH_AUTO
The identity in REMOTE_USER was published by AXIL_AUTOAUTH (-A), not asserted by a user. -A authenticates every connection as the server's own account, so any downstream authorization that trusts REMOTE_USER must refuse a descriptor carrying this flag. Set only by AXIL_AUTOAUTH, so it cannot survive descriptor reuse.
DF_UNIX
Connection accepted on an AF_UNIX listening socket (POSIX-only).

Function Documentation

int axil_accept (socket_t fd) [extern]

Called on accept; return value is ignored.

int axil_auth (socket_t fd, char * username)

Authenticate a user for fd, dropping privileges to them (POSIX).

Marks the connection authenticated and connected (so axil_disconnect() fires and the fd is visible to axil_wall()/DESCR_ITER), publishes REMOTE_USER, and records the user's passwd entry for axil_get_pw(). If the user is unknown to the system, the entry from axil_pw is used instead, so the connection runs with the server's own identity rather than uid 0: validate the name first, e.g. with axil_auth_check().

The name is copied into a fixed BUFSIZ field and truncated to 8191 bytes if it is longer, with a warning; it is not rejected. A truncated name is almost certainly not the account that was intended, so validate length as well as existence before calling.

Returns 0 on success, 1 if the name is unknown to the system (the connection is still marked authenticated), or -1 with errno EBADF if fd is not in [0, FD_SETSIZE).

Warning

The 0/1 return is ADVISORY. Nothing in this library enforces it: axil_platform_auth_try() calls axil_auth() and discards the result, and the platform hook it is invoked through is void (*)(socket_t), so there is nowhere for a verdict to travel. A caller that wants to reject an unknown name must check for itself -- compare against your own account list, or pre-validate with axil_auth_check() -- rather than relying on the 1. The privilege fallback to the server's own identity applies either way, so an unenforced 1 degrades to "runs as the server", not to uid 0.

char * axil_auth_check (socket_t fd) [extern]

Return a username to authenticate the connection, or NULL.

void axil_cert_add (char * str)

Add a certificate mapping: domain:cert.pem:key.pem (POSIX-only).

void axil_certs_add (char * fname)

Load certificate mappings from file (POSIX-only).

void axil_close (socket_t fd)

Close a descriptor.

void axil_command (socket_t fd, int argc, char * argv[]) [extern]

Called before a registered command handler.

int axil_connect (socket_t fd) [extern]

Called after a WebSocket upgrade completes via axil_ws_upgrade(). Return non-zero to mark the connection as established (DF_CONNECTED).

int axil_deny_prefix (const char * prefix)

Register a URL path prefix to deny with 403 Forbidden (exact segment or prefix match). Deny rules are evaluated before reverse-proxy routes, static files, and handlers. Returns 0 on success, -1 on invalid input or when the deny table is full.

void axil_disconnect (socket_t fd) [extern]

Called on disconnect.

Fires whenever a descriptor is torn down, not only when a peer hangs up -- axil_close() and a failed read both reach it. It fires for unauthenticated descriptors too, and deliberately so: a module may attach a pty and spawn a child to a raw telnet terminal or a /tty GET, long before any authentication happens, so a hook gated on auth or on DF_CONNECTED would never clean those up. Because fd numbers are reused, anything a module keys by fd must be released here or it will attach itself to an unrelated later connection.

It also fires for a connection that was only ever HTTP-authenticated, which has no pty and no upstream: axil_auth() marks the descriptor DF_CONNECTED, and that descriptor also enters DESCR_ITER, so axil_wall() broadcasts to it. A module cannot tell an authenticated-but-pty-less connection from any other, so a hook here must tolerate a missing pty and a missing upstream rather than assuming a module connection shape.

int axil_drop_ids (uid_t * uid, gid_t * gid)

Retrieve the resolved privilege-drop uid/gid from -u USER (POSIX-only). Returns 0 if -u was configured and resolved before chroot(), -1 otherwise.

int axil_dwritef (socket_t fd, const char * fmt, va_list va)

Write formatted data using a va_list.

unsigned axil_env (socket_t fd)

Return internal env handle for fd (advanced use; stable but not recommended).

void axil_env_clear (socket_t fd)

Clear request environment for fd.

int axil_env_get (socket_t fd, char * target, size_t dest_len, char * key)

Get environment value by key; returns 0 on success.

int axil_env_put (socket_t fd, char * key, char * value)

Set environment key/value; returns 0 on success.

void axil_exec (socket_t cfd, char *const args[], cmd_cb_t callback, void * input, size_t input_len)

Execute a command and stream output via callback (POSIX-only). Callback ofd is 1 for stdout, 0 for stderr.

int axil_exec_loop (socket_t cfd)

Continue processing a command started with axil_exec() (POSIX-only).

void axil_fd_unwatch (socket_t fd)

Remove fd from the server's active and read watch sets (POSIX-only).

void axil_fd_watch (socket_t fd)

Add fd to the server's active (select) watch set as an externally-managed fd. Sets DF_EXTERN so the main loop dispatches it via on_fd_tick rather than treating it as a client connection (POSIX-only).

int axil_flags (socket_t fd)

Get descriptor flags.

void axil_flush (socket_t fd, int argc, char * argv[]) [extern]

Called after a registered command handler.

void axil_fork_child_reset (void )

Reset the cleanup flag in a forked child process (POSIX-only). Must be called immediately after fork() in the child.

unsigned long long axil_generation (socket_t fd)

Get the per-connection generation of a descriptor.

A new value every accept, monotonic, never reused for a different connection. Because fd numbers are recycled, a module that keeps state keyed by fd should record this when it creates the state and refuse to act when it no longer matches -- that is what makes a leaked entry inert instead of silently attaching itself to an unrelated connection. Store it in whatever type the module's state uses; unsigned long long round-trips exactly.

Zero means "not a live descriptor", and is what a freshly zeroed slot reads as, so a default-initialised state can never match a real connection.

int axil_get_pw (socket_t fd, struct passwd * out)

Copy the authenticated user's passwd entry for fd into *out (POSIX-only). Returns 0 on success, -1 if fd is not authenticated.

int axil_header_get (socket_t fd, const char * key, char * buf, size_t buf_len)

Get an incoming request header by its natural name (e.g. "Content-Type"). Copies the value into buf (at most buf_len-1 bytes, NUL-terminated). Returns 0 on success, -1 if the header was not present in the request.

void axil_header_set (socket_t fd, const char * key, const char * value)

Add a response header. Call before axil_respond().

int axil_json_escape (const char * in, char * out, size_t outlen)

JSON-escape a string. Escapes ", \,
, \r, \t and control characters. Returns 0 on success.

int axil_main (void )

Run the main server loop (blocks).

ssize_t axil_mmap (char ** mapped, char * file)

Map a file into memory (POSIX-only).

char * axil_mmap_iter (char * start, size_t * pos)

Iterate mapped lines separated by '

int axil_param (socket_t fd, const char * name, char * buf, size_t buf_len)

Look up a parameter by name from parsed query/form body, falling back to route pattern parameters (PATTERN_PARAM_<NAME>). Returns bytes written, or -1 if the parameter was not found.

int axil_param_bool (socket_t fd, const char * name, int default_val)

Look up a boolean parameter by name via axil_param(), returning default_val if missing or unparseable. Recognizes 1/true/on/yes and 0/false/off/no.

int axil_param_int (socket_t fd, const char * name, int default_val)

Look up an integer parameter by name via axil_param(), returning default_val if missing or unparseable.

int axil_peer_cred (socket_t fd, uid_t * uid, gid_t * gid)

Query kernel-verified peer credentials on an AF_UNIX client socket (POSIX-only). Returns 0 on success and stores peer uid/gid when non-NULL; returns -1 if fd is invalid, not an AF_UNIX socket, or peer credentials are unavailable.

void axil_post_bind (void ) [extern]

Called once after listening sockets are bound (and ephemeral port populated in axil_config.port) and before the event loop begins.

int axil_post_chroot (void ) [extern]

Called once after startup's -C chroot/chdir and before any bind.

libaxil fires it from axil_init(), between the platform's init_pre_bind() (which does the chroot/chdir) and axil_bind(). That window is the whole point: the filesystem view has already changed, no socket is listening yet, so a module loading content here resolves every path inside the jail and finishes before the first request can be served. The axil binary forwards it to the composable on_axil_post_chroot XY hook (axil-xy.h); a host that does not define this symbol simply never fires it.

int axil_privsep_key (unsigned char out[32])

Copy the 32-byte per-boot privsep HMAC key (POSIX-only). Generated before chroot() when running as root with -u USER, readable ONLY while geteuid() == 0 (i.e. inside on_axil_post_chroot()), and cleansed from memory before setuid() drops privileges. Returns 0 on success, -1 otherwise.

int axil_proxy_prefix (const char * prefix, const char * host, unsigned short port)

Register an HTTP reverse-proxy route forwarding requests under prefix to host:port or an AF_UNIX upstream ("unix:/path/to/sock" with port == 0 on POSIX). Matches on exact path segment boundaries (longest matching prefix wins). Returns 0 on success, -1 on invalid input or when the proxy table is full.

int axil_query_param (const char * name, char * buf, size_t buf_len)

Look up a key previously parsed by axil_query_parse(). Copies the URL-decoded value into buf (at most buf_len-1 bytes, NUL-terminated). Returns the number of bytes written, or -1 if the key was not found.

int axil_query_parse (char * body)

Parse a URL-encoded form body (application/x-www-form-urlencoded) into an internal key/value store. Call once per request before axil_query_param(). Subsequent calls replace the previous parse result. Returns 0 on success, -1 on error.

void axil_register (char * name, axil_cb_t * cb, int flags)

Register a command handler by name.

int axil_register_fallback_handler (axil_handler_t handler)

Register a fallback HTTP handler. Fallback handlers run after static files, registered handlers, and axil_config.default_handler have declined the request. Return non-zero when the request was handled. Returns 0 on success, -1 when the fallback table is full.

void axil_register_handler (char * path, axil_handler_t handler)

Register an HTTP handler for a path (exact match or pattern). Patterns support :param syntax (e.g., "/items/:id" or "/a/:type/:id"), terminal catch-alls via * (e.g., "/items/" followed by "*"), and optional trailing slash matching on path patterns. Matched parameters are available via PATTERN_PARAM_<NAME> env vars. Example: "/items/:id" matches "/items/123", sets PATTERN_PARAM_ID="123"

int axil_req_param (socket_t fd, const char * body, const char * name, char * buf, size_t buf_len)

Unified request parameter lookup: extracts from parsed query/form params, non-destructively parses non-multipart body on-demand if provided, checks QUERY_STRING, and falls back to route pattern parameters. Returns bytes written, or -1 if not found.

int axil_req_param_bool (socket_t fd, const char * body, const char * name, int default_val)

Unified request boolean parameter lookup with fallback default.

int axil_req_param_int (socket_t fd, const char * body, const char * name, int default_val)

Unified request integer parameter lookup with fallback default.

void axil_respond (socket_t fd, int code, const char * body)

Send HTTP status, accumulated headers, body and close the connection. The connection is ALWAYS closed (even with body == NULL). For a response completed later from the event loop, use axil_respond_defer() instead.

void * axil_respond_defer (socket_t fd, int code)

Defer a response: send status line + accumulated headers now and keep the connection open for a later axil_respond_defer_finish()/done()/abort(). Loop-thread only. Returns a handle, or NULL on invalid fd / already deferred / WebSocket connection.

void axil_respond_defer_abort (void * handle)

Loop-thread only: abandon/abort a deferred response and close the socket (worker failed, client gone). No-op if stale.

void axil_respond_defer_done (void * handle)

Loop-thread only: close a deferred connection WITHOUT a body (end of a streamed response already written via axil_write). No-op if stale.

void axil_respond_defer_finish (void * handle, const char * body)

Loop-thread only: complete a deferred response by writing body and closing the connection. No-op if the handle is stale (closed/reused fd).

int axil_respond_file (socket_t fd, const char * path, const char * allowed_exts)

Serve a file from disk with validation against allowlisted extensions. Handles MIME type lookup, Content-Length, safe id checking, and streaming. Returns 0 on success, -1 on failure (error response sent).

void axil_sendfile (socket_t fd, const char * path)

Serve a static file with auto-detected MIME type. Closes fd on completion.

void axil_set_flags (socket_t fd, int flags)

Set descriptor flags.

int axil_slugify (const char * title, size_t title_len, char * result, size_t result_len)

Convert a title string to a URL/filesystem-safe slug. Transliterates Unicode to ASCII, lowercases, replaces spaces with underscores, strips non-alphanumeric characters. Falls back to "item" if the result would be empty. Returns 0 on success.

const char * axil_status_text (int code)

Get HTTP status text for a status code. Returns "Unknown" for invalid codes.

void axil_stop (void )

Signal a running axil_main() loop to exit cleanly (thread- and signal-safe).

void axil_update (unsigned long long dt) [extern]

Periodic update hook.

size_t axil_url_decode (const char * src, size_t src_len, char * out, size_t out_len)

URL-decode a percent-encoded substring. Handles XX and +. Returns number of bytes written (excluding NUL).

int axil_url_encode (const char * in, char * out, size_t outlen)

URL-encode a string. Writes percent-encoded output to out (NUL-terminated). Returns number of bytes written (excluding NUL), or -1 on overflow.

void axil_vim (socket_t fd, int argc, char * argv[]) [extern]

Called when a command is not found.

void axil_wall (const char * msg)

Broadcast a message to all connected descriptors.

int axil_write (socket_t fd, void * data, size_t len)

Write raw bytes to a descriptor. Returns bytes written or -1.

int axil_writef (socket_t fd, const char * fmt, ...)

Write formatted data.

int axil_ws_close (socket_t fd)

Close websocket connection. Returns 0, or -1 with errno EBADF if fd is outside [0, FD_SETSIZE).

void axil_ws_handler (char * path, axil_ws_upstream_t handler)

Register a websocket handler for a path. When a websocket request arrives for this path, the handler is called with the client socket. The handler connects to the upstream and returns the upstream socket. axil then forwards the HTTP upgrade, reads the response, and establishes a bidirectional tunnel.

int axil_ws_printf (socket_t fd, const char * fmt, ...)

Formatted write to websocket. Returns the number of bytes written, or -1 on error (same contract as axil_ws_write(), including the EBADF bound).

ssize_t axil_ws_read (socket_t fd, void * buf, size_t len)

Read data from websocket. Returns bytes read (NUL-terminated), 0 on close, -1 on error. A frame larger than len - 1 is refused rather than truncated: -1 with errno EMSGSIZE. A partially received frame returns -1 with errno EAGAIN and stays open, so the caller must wait for readability.

fd must be in [0, FD_SETSIZE); anything else returns -1 with errno EBADF.

int axil_ws_upgrade (socket_t fd)

Upgrade connection to websocket. Reads Sec-WebSocket-Key from the request environment, performs the handshake, and calls axil_connect() on success. Modules should call this explicitly from their GET handler when HTTP_SEC_WEBSOCKET_KEY is present in the request environment.

You must also call axil_fd_watch(fd) immediately afterwards. axil drains incoming frames itself -- it has to, or the event loop spins on a socket that stays readable -- but it only hands them to the module once the fd is watched, via the axil_fd_tick() hook. Without axil_fd_watch() every frame is read and discarded, silently: the connection completes its handshake and then ignores the client. Frames are never parsed as HTTP requests.

int axil_ws_write (socket_t fd, const void * data, size_t len)

Write data to websocket. Returns the size of the frame written, header included, or -1 if the connection failed. On a non-blocking socket a frame too large for the socket buffers is queued whole -- header and payload together, so frames cannot interleave -- and flushed by the event loop, so a non-negative result does not mean the bytes have already left the socket.

fd must be in [0, FD_SETSIZE); anything else returns -1 with errno EBADF rather than indexing the module's descriptor tables out of bounds.

Variable Documentation

char axil_execbuf[BUFSIZ *64] [extern]

Shared exec buffer (legacy). Prefer callbacks; symbol is stable.

Author

Generated automatically by Doxygen for axil from the source code.