<p align="center">
  <img src="assets/logo.png" alt="axil logo" width="220" />
</p>

# axil

[![npm](https://img.shields.io/badge/npm-@tty--pt/axil-CB3837?logo=npm)](npm/README.md)
[![C99](https://img.shields.io/badge/C-C99-555?logo=c)](#)
[![BSD-2-Clause](https://img.shields.io/badge/License-BSD--2--Clause-blue)](#)
[![HTTP(S)+WS daemon](https://img.shields.io/badge/HTTP%28S%29%2BWS-daemon-4B8BBE)](#)
[![libxylem compatible](https://img.shields.io/badge/modules-libxylem-16A34A)](#)

> High-throughput, non-blocking HTTP(S), WebSocket, and PTY daemon in plain C with dynamic module loading and chroot jail isolation. Canonical header is `<ttypt/axil.h>`.

---

## 1. Quickstart

### Launch Server from CLI
Start the daemon in foreground on port 8080 loading dynamic modules (via system binary or npm prebuild):

```bash
axil -d -p 8080 -m libaxil-auth -m libaxil-hyle
# Or directly via the @tty-pt/axil N-API CLI without system C packages:
npx @tty-pt/axil -d -p 4242 -m axil-auren
```

### Embed in Pure C
Serve non-blocking HTTP endpoints and WebSocket streams in under 25 lines:

```c
#include <stdio.h>
#include <ttypt/axil.h>

static int handle_hello(socket_t fd, char *body) {
    (void)body;
    axil_respond_plain(fd, 200, "Hello from axil!\n");
    return 0;
}

static int handle_ws_echo(socket_t fd, char *body) {
    (void)body;
    if (axil_ws_upgrade(fd) == 0) {
        axil_ws_write(fd, "Connected to echo server\n", 25);
    }
    return 0;
}

int main(void) {
    axil_config.port = 8080;
    axil_register_handler("/api/hello", handle_hello);
    axil_register_handler("/ws/echo", handle_ws_echo);

    printf("Serving on http://localhost:8080/api/hello\n");
    return axil_main(); // Enters non-blocking event loop
}
```

Compile and link:
```sh
cc my_server.c $(pkg-config --cflags --libs axil) -o my_server
```

---

## 2. CLI Options Reference

| Option | Argument | Description |
| :--- | :--- | :--- |
| `-p` | `PORT` | Listen port for HTTP/WS connections (`0` binds an ephemeral port) |
| `-s` | `PORT` | Listen port for HTTPS/WSS connections (POSIX) |
| `-C` | `PATH` | Change directory (`chroot` + `chdir("/")` as root, `chdir` otherwise) before binding |
| `-u` | `USER` | Drop privileges permanently to `USER` after bind (POSIX) |
| `-U` | `PATH` | Listen on an `AF_UNIX` socket `PATH` instead of HTTP TCP (POSIX) |
| `-K` | `PATH` | Load SSL certificate mappings (`domain:cert:key` per line, POSIX) |
| `-k` | `CERT` | Add a single SSL certificate mapping `domain:cert:key` (POSIX) |
| `-B` | `BYTES` | Maximum POST body size in bytes (default: `10485760`) |
| `-D` | `PREFIX` | Deny URL prefix with `403 Forbidden` (repeatable) |
| `-P` | `PREFIX=TARGET` | Reverse-proxy URL prefix to an upstream TCP `host:port` or `unix:/path` (repeatable) |
| `-m` | `MODS` | Colon-separated list of Xylem `.so` module paths to load |
| `-A` | *none* | Auto-authenticate all WebSocket connections (dev/testing) |
| `-d` | *none* | Run in foreground (do not detach/daemonize) |
| `-l` | *none* | Bind listening sockets to `127.0.0.1` only (`AXIL_LOOPBACK`) |
| `-r` | *none* | Root multiplex mode (`AXIL_ROOT`) |

---

## 3. Core API Reference

| Function | Signature | Description |
| :--- | :--- | :--- |
| `axil_main` | `int axil_main(void)` | Enter non-blocking network event loop |
| `axil_stop` | `void axil_stop(void)` | Signal a running `axil_main()` loop to exit cleanly (thread/signal-safe) |
| `axil_cli` | `int axil_cli(int argc, char *argv[])` | Parse CLI flags, load `-m` modules, and enter `axil_main()` |
| `axil_register_handler` | `void axil_register_handler(path, cb)` | Map HTTP path or `:param` / `*` pattern to a handler callback (`GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `OPTIONS`) |
| `axil_register_fallback_handler` | `int axil_register_fallback_handler(cb)` | Register a fallback handler invoked after static files and primary routes decline |
| `axil_deny_prefix` | `int axil_deny_prefix(prefix)` | Register a URL prefix to reject with `403 Forbidden` before proxy/static/handler routing |
| `axil_proxy_prefix` | `int axil_proxy_prefix(prefix, host, port)` | Register an HTTP reverse-proxy route for a URL prefix (`host:port` or `unix:/path`, longest segment match wins) |
| `axil_post_bind` / `on_axil_post_bind` | `void axil_post_bind(void)` / XY hook | Invoked once after listeners are bound (and privileges dropped) before entering the event loop |
| `axil_peer_cred` | `int axil_peer_cred(fd, uid, gid)` | Query kernel-verified peer `uid`/`gid` on an `AF_UNIX` client socket (`DF_UNIX`, POSIX) |
| `axil_privsep_key` | `int axil_privsep_key(unsigned char out[32])` | Copy the per-boot 32-byte privsep HMAC key inside `on_axil_post_chroot()` before `setuid()` cleanses it (POSIX) |
| `axil_drop_ids` | `int axil_drop_ids(uid_t *uid, gid_t *gid)` | Retrieve resolved `-u USER` privilege-drop `uid`/`gid` (POSIX) |
| `axil_respond_plain` | `void axil_respond_plain(fd, status, body)` | Send HTTP response with `text/plain` |
| `axil_respond_json` | `void axil_respond_json(fd, status, json)` | Send HTTP response with `application/json` |
| `axil_ws_upgrade` | `int axil_ws_upgrade(socket_t fd)` | Perform WebSocket handshake upgrade |
| `axil_ws_write` | `int axil_ws_write(fd, data, len)` | Transmit binary/text frame to WebSocket client |

👉 *For the browser WebSocket and WebAssembly capability transport, see the canonical [htdocs/axil-cap.js](htdocs/axil-cap.js).*

---

## 4. Production Hardening & Security

- **Privilege Separation & Chroot Isolation**: Confines the process to a designated root via `-C` (`chroot(2)` when started as root, `chdir(2)` otherwise), drops privileges permanently after bind via `-u USER`, supports `AF_UNIX` listeners (`-U PATH`), `unix:/path` reverse-proxy targets, kernel peer-credential checks (`axil_peer_cred()`), and per-boot privsep HMAC keys (`axil_privsep_key()`, cleansed before `setuid()`), plus `-l` (`AXIL_LOOPBACK`) and `-D` prefix deny rules.
- **Framing & Anti-Smuggling**: Automatic `Content-Length` enforcement, deferred `DF_TO_CLOSE` handling across large static transfers and `DF_DEFERRED` responses, `Connection: close` defaults, and strict RFC 7230 request line parsing.
- **Cross-Platform & Mobile Embedding**: Supports Linux, OpenBSD, FreeBSD, macOS, Windows, and Android/iOS POSIX sandboxes (loopback binding, ephemeral port writeback, `axil_post_bind`, `axil_stop`, and UTF-8 slugify fallback).

---

## 5. Installation, Services & Build

### Prebuilt Packages
Prebuilt packages are distributed on tty.pt for Linux (APT / Alpine / Arch / Fedora-RHEL), macOS (Homebrew), Windows (winget / Scoop / MSYS2), OpenBSD, and mobile static sysroots for Android (`https://tty.pt/android/` — `arm64-v8a`, `x86_64`) and iOS (`https://tty.pt/ios/` — `axil.xcframework` + SwiftPM). Follow the [installation instructions](https://github.com/tty-pt/ci/blob/main/docs/install.md) and use **axil** as the package name.

### Build from Source
Building from source requires `libstele` (runtime substrate, `<ttypt/iso_json.h>` used by `axil_json_escape()`, and shared `ttypt/include.mk` build rules), `libcorm`, and `libxylem`:

```sh
make                  # builds bin/axil and lib/libaxil.so
make test             # run unit and integration test suite
sudo make install     # install binary, headers, library, and OS service files
```

The core library is organized into modular C units (`src/libaxil.c`, `src/axil-http.c`, `src/axil-query.c`, `src/axil-tls.c`, `src/axil-encode.c`, `src/axil-status.c`, `src/axil-posix.c`, `src/axil-win.c`, `src/ws.c`). Cross-platform daemon definitions live under `services/` (`services/systemd/axil.service`, `services/openrc/axil`, `services/freebsd/axil`, `services/rc.d/axil`, `services/launchd/pt.tty.axil.plist`, `services/windows/axil.xml`, and `services/windows/install-service.ps1`) and are installed automatically via `make install-services`.

---

## 6. JavaScript, WebAssembly & N-API Bindings (`@tty-pt/axil`)

For browser, Node.js, and WebSocket clients—as well as zero-compile N-API daemon hosting—`axil` ships `@tty-pt/axil` on npm (and the self-hosted `tty.pt` registry):

```sh
npm config set @tty-pt:registry https://tty.pt/npm/
npm install @tty-pt/axil
```

- **N-API Daemon Host & CLI (`axil`)**: Bundles `axil.node` (`axil_cli`) and `bin/axil.js` with automatic `@tty-pt/*` prebuild module resolution (`-m axil-auren`) and clean background daemonization.
- **Multiplexed WebSocket Client & WASM Bridge**: Provides `AxilClient` and `createAxilBridge`, registering `stele:ws_*` runtime capability handlers on `libstele` via `registerSteleMainHandler` / `registerSteleWorkerHandler` with zero hardcoded dispatch in `libstele`.
- **Native String & HTTP Utilities**: Exposes `statusText`, `urlEncode`, `urlDecode`, `jsonEscape`, and `slugify` (accelerated via N-API in Node.js with pure-JS fallbacks for browsers).

See [npm/README.md](npm/README.md) for the full CLI, N-API, TypeScript, and WebSocket bridge API reference.

---

## License

BSD 2-Clause License. Copyright (c) 2025, tty-pt. See `LICENSE`.
