7.8 KiB
libnx documentation
libnx is a portable C networking library for Unix-like systems. It targets Linux, macOS (XNU) and the BSDs, and depends on nothing beyond libc and pthreads.
Contents
- Building
- Installing
- Quick start
- Modules
- Event loop
- HTTP client
- Name resolution
- Platform support
- Limits and safety
- Status
Building
make # builds libnx.a and libnx.so
make clean
The backend for the event loop is selected from uname -s at build time:
| OS | Backend | Source |
|---|---|---|
| Linux | epoll | src/reactor/reactor_epoll.c |
| macOS, FreeBSD, NetBSD, OpenBSD, DragonFly | kqueue | src/reactor/reactor_kqueue.c |
| anything else | poll | src/reactor/reactor_poll.c |
The build uses -Werror with a strict warning set. A warning is treated as a
bug, not as noise.
Installing
sudo make install # PREFIX=/usr/local by default
make install PREFIX=$HOME/.local # custom prefix
Headers go to $(PREFIX)/include/nx, libraries to $(PREFIX)/lib.
Quick start
#include <nx/nx.h>
#include <stdio.h>
int main(void)
{
nx_http_request req;
nx_http_response res;
nx_http_request_defaults(&req);
req.user_agent = 1;
if (nx_http_perform("http://example.com/", &req, &res) != 0) {
fprintf(stderr, "request failed: %s\n", nx_http_error());
return 1;
}
printf("%d %s\n", res.status, res.reason);
printf("%.*s\n", (int)res.body.len, res.body.data);
nx_http_response_free(&res);
return 0;
}
Link with -lnx (or the static archive) and -pthread:
cc -o example example.c -I/usr/local/include -L/usr/local/lib -lnx -pthread
Modules
#include <nx/nx.h> pulls in everything. Each header can also be included on
its own; every public header is self-contained.
| Header | What it provides |
|---|---|
nx_types.h |
errno strings, version string, monotonic clock |
nx_sockaddr.h |
portable struct sockaddr handling |
nx_buf.h |
growable byte buffer and fixed-capacity ring buffer |
nx_socket.h |
socket helpers and connections |
nx_reactor.h |
event loop over epoll / kqueue / poll |
nx_dns.h |
blocking and async name resolution |
nx_signal.h |
self-pipe and signal handlers safe for a reactor |
nx_url.h |
URL parsing for HTTP request targets |
nx_http.h |
HTTP/1.1 client |
Buffers
nx_buf is a byte buffer with a read cursor. nx_ring is a fixed-capacity
circular buffer for length-delimited protocols where a peer must not be able to
dictate allocation.
nx_buf b = NX_BUF_INIT;
nx_buf_append_str(&b, "hello");
nx_buf_appendf(&b, ", %s", "world");
nx_buf_free(&b);
Addresses
struct sockaddr_storage ss;
socklen_t len;
if (nx_addr_parse_ip("127.0.0.1", 8080, &ss) == 0) {
char text[64];
nx_addr_format((struct sockaddr *)&ss, text, sizeof(text));
}
Sockets
nx_socket creates a socket with close-on-exec set and SIGPIPE suppression
applied the way each platform needs it. nx_connect_timeout drives a
non-blocking connect to completion with poll, so it works for both blocking
and non-blocking sockets.
int fd = nx_socket(AF_INET, SOCK_STREAM, 0);
nx_set_timeouts(fd, 5000);
if (nx_connect_timeout(fd, (struct sockaddr *)&ss, len, 5000) != 0) {
/* errno is ETIMEDOUT on timeout */
}
nx_close(&fd);
Event loop
The reactor is level-triggered on every backend, so a partially drained socket reports again. A callback may add, modify or delete events while it runs; the removal of an event that is currently being dispatched is deferred until the current loop finishes.
static void on_readable(nx_event *ev, int revents)
{
char buf[4096];
int fd = nx_event_fd(ev);
ssize_t n = nx_recv(fd, buf, sizeof(buf), 0);
if (n <= 0) {
nx_reactor_del(nx_event_reactor(ev), ev);
nx_close(&fd);
return;
}
(void)nx_send_all(fd, buf, (size_t)n, 0);
(void)revents;
}
void serve(int lfd)
{
nx_reactor *r;
nx_event *ev;
nx_reactor_new(&r);
ev = nx_event_new(lfd, on_readable, NULL);
nx_reactor_add(r, ev, lfd, NX_READ, on_readable, NULL);
nx_reactor_run(r); /* returns when nx_reactor_stop is called */
nx_event_free(ev);
nx_reactor_free(r);
}
nx_reactor_wakeup interrupts a blocking wait from another thread;
nx_reactor_stop stops the innermost nx_reactor_run.
HTTP client
nx_http_perform runs a request to completion over a fresh connection. It
returns 0 for any HTTP status, including 4xx and 5xx, and -1 only for
transport or protocol errors.
nx_http_request req;
nx_http_response res;
nx_http_request_defaults(&req);
req.timeout_ms = 10000;
req.follow_redirect = 5;
req.user_agent = 1;
if (nx_http_perform("http://example.com/path?q=1", &req, &res) == 0) {
const char *ct = nx_http_header_get(&res, "content-type");
/* res.body holds the decoded entity, with chunked framing removed */
nx_http_response_free(&res);
}
The custom header array is borrowed, not copied:
nx_http_header hdrs[] = {
{ "Accept", "application/json" },
};
req.headers = hdrs;
req.nheaders = 1;
nx_http_perform_fd runs an exchange over an already-connected socket, for use
on top of the reactor. nx_http_read_response parses a response from a socket
given a caller-owned scratch buffer.
Only plain HTTP is supported. See FAQ for why.
Name resolution
struct sockaddr_storage ss;
socklen_t len;
if (nx_resolve_blocking("example.com", 80, &ss, &len, NULL) == 0) {
/* connected address */
}
nx_resolve returns a list of addresses. nx_resolve_ip parses numeric
addresses without touching DNS. nx_resolve_async resolves on a worker thread
and delivers the result to a callback on the reactor thread.
Name resolution delegates to the system's getaddrinfo. AI_ADDRCONFIG is not
requested, because it hides working IPv4 names on hosts with no global IPv6
route. A resolution in flight cannot be cancelled: getaddrinfo offers no way
to interrupt it.
Platform support
- Linux: epoll backend,
accept4,pipe2. - macOS and BSDs: kqueue backend,
SO_NOSIGPIPE. - Other Unix: poll backend.
The portability differences handled centrally are BSD sa_len, BSD/macOS
SO_NOSIGPIPE versus Linux MSG_NOSIGNAL, accept4 versus accept plus
fcntl, and the sun_path length rules for Unix sockets.
Limits and safety
The HTTP parser assumes the peer is hostile:
- header block limited to 64 KiB, 128 fields, 8 KiB per line;
- response body limited to 16 MiB by default (
req.max_body); - duplicate or malformed
Content-Lengthrejected; Content-Lengthtogether withTransfer-Encodingrejected;- chunk sizes parsed with overflow checks, chunk terminators required to be exactly CRLF;
- control characters rejected in URLs, request targets and headers.
https:// is parsed and then refused. TLS would require X.509 parsing, a
certificate store and AEAD ciphers, none of which can be built on libc alone.
Status
The library builds to libnx.a and libnx.so and every public header compiles
standalone. The test targets in the Makefile (make test) expect a suite
under tests/; that suite is not written yet, so make test currently has
nothing to run.