This commit is contained in:
2026-09-29 20:42:04 +01:00
commit 354797a5de
30 changed files with 4144 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 homueicon
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.
+67
View File
@@ -0,0 +1,67 @@
CC ?= cc
AR ?= ar
PREFIX ?= /usr/local
UNAME_S := $(shell uname -s)
WARNINGS := -Wall -Wextra -Wpedantic -Wshadow -Wconversion -Wsign-conversion \
-Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wpointer-arith \
-Wwrite-strings -Wformat=2 -Wundef -Wdouble-promotion
CFLAGS ?= -O2 -g
CFLAGS += -std=c11 -D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE -pthread
CFLAGS += -Iinclude -Isrc/core -Isrc/reactor -Isrc/net -Isrc/proto
CFLAGS += $(WARNINGS) -Werror -fPIC
LDFLAGS += -pthread
ifeq ($(UNAME_S),Linux)
BACKEND := src/reactor/reactor_epoll.c
else ifeq ($(UNAME_S),Darwin)
BACKEND := src/reactor/reactor_kqueue.c
else ifneq (,$(filter $(UNAME_S),FreeBSD NetBSD OpenBSD DragonFly))
BACKEND := src/reactor/reactor_kqueue.c
else
BACKEND := src/reactor/reactor_poll.c
endif
SRCS := src/core/util.c src/core/sockaddr.c src/core/buf.c \
src/net/socket.c \
src/reactor/reactor.c $(BACKEND) \
src/net/dns.c src/net/signal.c \
src/proto/url.c src/proto/http.c
OBJS := $(SRCS:.c=.o)
STATIC := libnx.a
SHARED := libnx.so
TEST_BINS := tests/test_buf tests/test_sockaddr tests/test_url \
tests/test_reactor tests/test_socket tests/test_http
.PHONY: all clean test install
all: $(STATIC) $(SHARED)
$(STATIC): $(OBJS)
$(AR) rcs $@ $^
$(SHARED): $(OBJS)
$(CC) -shared -o $@ $^ $(LDFLAGS)
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
tests/%: tests/%.c $(STATIC)
$(CC) $(CFLAGS) -o $@ $< $(STATIC) $(LDFLAGS)
test: $(TEST_BINS)
@for t in $(TEST_BINS); do echo "== $$t"; ./$$t || exit 1; done
@echo "all tests passed"
clean:
rm -f $(OBJS) $(STATIC) $(SHARED) $(TEST_BINS)
install: all
install -d $(DESTDIR)$(PREFIX)/include/nx $(DESTDIR)$(PREFIX)/lib
install -m 644 include/nx/*.h $(DESTDIR)$(PREFIX)/include/nx/
install -m 644 $(STATIC) $(DESTDIR)$(PREFIX)/lib/
install -m 755 $(SHARED) $(DESTDIR)$(PREFIX)/lib/
+36
View File
@@ -0,0 +1,36 @@
# libnx
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
![License](LICENSE)
LibNX is an HTTP/1.1 networking library for Unix-like systems (XNU/macOS, Linux
and the BSDs), written in C with no external dependencies other than libc and
pthreads.
## What does LibNX provide?
LibNX provides the stable plumbing a network client needs without pulling in
TLS, HTTP helpers or a build system.
## Scope
Nothing beyond base UNIX TCP sockets, event loops and async name resolution.
### Minimal scopes
- HTTP/1.1 client
- URL parsing
## Unsupported
TLS and HTTPS are not supported. They would need X.509 parsing, a certificate
store and AEAD ciphers, none of which can be done on libc alone.
## Documentation
- [Docs](md/docs.md)
- [Q&A](md/FAQ.md)
## License
Released under the MIT License. See [LICENSE](LICENSE).
+23
View File
@@ -0,0 +1,23 @@
#ifndef NX_H
#define NX_H
#define NX_VERSION_MAJOR 0
#define NX_VERSION_MINOR 1
#define NX_VERSION_PATCH 0
#define NX_STR2(x) #x
#define NX_STR(x) NX_STR2(x)
#define NX_VERSION_STRING \
NX_STR(NX_VERSION_MAJOR) "." NX_STR(NX_VERSION_MINOR) "." NX_STR(NX_VERSION_PATCH)
#include "nx_types.h"
#include "nx_sockaddr.h"
#include "nx_buf.h"
#include "nx_socket.h"
#include "nx_reactor.h"
#include "nx_dns.h"
#include "nx_signal.h"
#include "nx_url.h"
#include "nx_http.h"
#endif
+65
View File
@@ -0,0 +1,65 @@
#ifndef NX_BUF_H
#define NX_BUF_H
#include "nx_types.h"
#if defined(__cplusplus)
extern "C" {
#endif
typedef struct nx_buf {
uint8_t *data;
size_t len;
size_t pos;
size_t cap;
} nx_buf;
#define NX_BUF_INIT {NULL, 0, 0, 0}
void nx_buf_init(nx_buf *b);
void nx_buf_free(nx_buf *b);
void nx_buf_reset(nx_buf *b);
int nx_buf_reserve(nx_buf *b, size_t extra);
int nx_buf_append(nx_buf *b, const void *p, size_t n);
int nx_buf_append_str(nx_buf *b, const char *s);
int nx_buf_append_char(nx_buf *b, char c);
int nx_buf_appendf(nx_buf *b, const char *fmt, ...);
static inline size_t nx_buf_avail(const nx_buf *b) { return b->len - b->pos; }
static inline uint8_t *nx_buf_head(nx_buf *b) { return b->data + b->pos; }
void nx_buf_consume(nx_buf *b, size_t n);
void nx_buf_compact(nx_buf *b);
int nx_buf_read_line(nx_buf *b, size_t max_line, size_t *pos,
const uint8_t **line, size_t *line_len);
typedef struct nx_ring {
uint8_t *data;
size_t cap;
size_t head;
size_t tail;
} nx_ring;
#define NX_RING_INIT {NULL, 0, 0, 0}
int nx_ring_init(nx_ring *r, size_t cap);
void nx_ring_free(nx_ring *r);
static inline size_t nx_ring_used(const nx_ring *r) { return r->head - r->tail; }
static inline size_t nx_ring_free_space(const nx_ring *r) { return r->cap - nx_ring_used(r); }
static inline int nx_ring_is_empty(const nx_ring *r) { return r->head == r->tail; }
size_t nx_ring_write(nx_ring *r, const void *p, size_t n);
size_t nx_ring_read(nx_ring *r, void *p, size_t n);
size_t nx_ring_peek(const nx_ring *r, const void **p, size_t n);
#if defined(__cplusplus)
}
#endif
#endif
+45
View File
@@ -0,0 +1,45 @@
#ifndef NX_DNS_H
#define NX_DNS_H
#include "nx_types.h"
#include "nx_sockaddr.h"
#include "nx_reactor.h"
#if defined(__cplusplus)
extern "C" {
#endif
#define NX_RESOLVE_TIMEOUT_MS 5000
int nx_resolve(const char *host, const char *service, int family,
int socktype, struct sockaddr_storage *out, socklen_t *outlen,
int max, int *gai_err);
int nx_resolve_one(const char *host, const char *service, int family,
int socktype, struct sockaddr_storage *out,
socklen_t *outlen, int *gai_err);
int nx_resolve_ip(const char *host, int port, struct sockaddr_storage *out,
socklen_t *outlen);
typedef struct nx_resolve_req nx_resolve_req;
typedef void (*nx_resolve_cb)(nx_resolve_req *req, int status,
const struct sockaddr *addr, socklen_t addrlen,
void *userdata);
int nx_resolve_async(nx_reactor *r, const char *host, const char *service,
int family, int socktype, int timeout_ms,
nx_resolve_cb cb, void *userdata);
int nx_resolve_blocking(const char *host, int port,
struct sockaddr_storage *out, socklen_t *outlen,
int *gai_err);
const char *nx_gai_strerror(int err);
#if defined(__cplusplus)
}
#endif
#endif
+76
View File
@@ -0,0 +1,76 @@
#ifndef NX_HTTP_H
#define NX_HTTP_H
#include "nx_types.h"
#include "nx_buf.h"
#include "nx_socket.h"
#include "nx_sockaddr.h"
#if defined(__cplusplus)
extern "C" {
#endif
#define NX_HTTP_MAX_HEADER_BYTES (64 * 1024)
#define NX_HTTP_MAX_HEADERS 128
#define NX_HTTP_MAX_LINE 8192
#define NX_HTTP_MAX_BODY (16 * 1024 * 1024)
#define NX_HTTP_DEFAULT_PORT 80
#define NX_HTTP_TIMEOUT_MS 10000
typedef struct nx_http_header {
const char *name;
const char *value;
} nx_http_header;
typedef struct nx_http_response {
int status;
char reason[128];
char version[16];
nx_buf headers_buf;
nx_http_header headers[NX_HTTP_MAX_HEADERS];
int nheaders;
nx_buf body;
int has_body;
int chunked;
int keep_alive;
} nx_http_response;
typedef struct nx_http_request {
const char *method;
const char *host;
const char *path;
const void *body;
size_t body_len;
nx_http_header *headers;
int nheaders;
int timeout_ms;
int max_body;
int follow_redirect;
int user_agent;
} nx_http_request;
void nx_http_request_defaults(nx_http_request *req);
void nx_http_response_free(nx_http_response *res);
int nx_http_perform(const char *url, nx_http_request *req,
nx_http_response *res);
int nx_http_perform_fd(int fd, const char *host, const char *path,
nx_http_request *req, nx_http_response *res);
int nx_http_read_response(int fd, nx_buf *scratch, nx_http_request *req,
nx_http_response *res);
const char *nx_http_header_get(const nx_http_response *res, const char *name);
const char *nx_http_error(void);
#if defined(__cplusplus)
}
#endif
#endif
+57
View File
@@ -0,0 +1,57 @@
#ifndef NX_REACTOR_H
#define NX_REACTOR_H
#include "nx_types.h"
#if defined(__cplusplus)
extern "C" {
#endif
#define NX_READ 0x01
#define NX_WRITE 0x02
#define NX_ERROR 0x04
#define NX_HUP 0x08
typedef struct nx_reactor nx_reactor;
typedef struct nx_event nx_event;
typedef void (*nx_cb)(nx_event *ev, int revents);
nx_event *nx_event_new(int fd, nx_cb cb, void *userdata);
void nx_event_free(nx_event *ev);
int nx_reactor_new(nx_reactor **out);
void nx_reactor_free(nx_reactor *r);
int nx_reactor_add(nx_reactor *r, nx_event *ev, int fd, int events,
nx_cb cb, void *userdata);
int nx_reactor_mod(nx_reactor *r, nx_event *ev, int events);
int nx_reactor_del(nx_reactor *r, nx_event *ev);
int nx_reactor_wait(nx_reactor *r, int timeout_ms);
int nx_reactor_run(nx_reactor *r);
void nx_reactor_stop(nx_reactor *r);
int nx_reactor_wakeup(nx_reactor *r);
const char *nx_reactor_backend(void);
size_t nx_reactor_nactive(const nx_reactor *r);
int nx_event_fd(const nx_event *ev);
void *nx_event_userdata(const nx_event *ev);
nx_reactor *nx_event_reactor(const nx_event *ev);
int nx_event_interested(const nx_event *ev, int flag);
#if defined(__cplusplus)
}
#endif
#endif
+28
View File
@@ -0,0 +1,28 @@
#ifndef NX_SIGNAL_H
#define NX_SIGNAL_H
#include "nx_types.h"
#if defined(__cplusplus)
extern "C" {
#endif
typedef struct nx_selfpipe nx_selfpipe;
int nx_selfpipe_new(nx_selfpipe **out);
void nx_selfpipe_free(nx_selfpipe *p);
int nx_selfpipe_read_fd(const nx_selfpipe *p);
int nx_selfpipe_write_fd(const nx_selfpipe *p);
int nx_selfpipe_notify(nx_selfpipe *p);
int nx_selfpipe_drain(nx_selfpipe *p);
int nx_signal_set(int signo, void (*handler)(int));
#if defined(__cplusplus)
}
#endif
#endif
+125
View File
@@ -0,0 +1,125 @@
#ifndef NX_SOCKADDR_H
#define NX_SOCKADDR_H
#include "nx_types.h"
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <string.h>
#if defined(__cplusplus)
extern "C" {
#endif
#if !defined(AF_UNIX) && defined(AF_LOCAL)
#define AF_UNIX AF_LOCAL
#endif
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
defined(__OpenBSD__) || defined(__DragonFly__)
#define NX_HAS_SA_LEN 1
#else
#define NX_HAS_SA_LEN 0
#endif
static inline socklen_t nx_sockaddr_len(const struct sockaddr *sa)
{
if (sa == NULL) {
return 0;
}
switch (sa->sa_family) {
case AF_INET:
return (socklen_t)sizeof(struct sockaddr_in);
case AF_INET6:
return (socklen_t)sizeof(struct sockaddr_in6);
#ifdef AF_UNIX
case AF_UNIX: {
const struct sockaddr_un *un = (const struct sockaddr_un *)(const void *)sa;
size_t path = strnlen(un->sun_path, sizeof(un->sun_path));
if (path == 0) {
return (socklen_t)sizeof(struct sockaddr_un);
}
return (socklen_t)(offsetof(struct sockaddr_un, sun_path) + path + 1);
}
#endif
default:
#if NX_HAS_SA_LEN
return (socklen_t)sa->sa_len;
#else
return (socklen_t)sizeof(struct sockaddr_storage);
#endif
}
}
static inline void nx_set_len(struct sockaddr *sa, socklen_t len)
{
#if NX_HAS_SA_LEN
sa->sa_len = (unsigned char)len;
#else
(void)sa;
(void)len;
#endif
}
static inline struct sockaddr_in *nx_sin(struct sockaddr *sa)
{
return (struct sockaddr_in *)(void *)sa;
}
static inline const struct sockaddr_in *nx_csin(const struct sockaddr *sa)
{
return (const struct sockaddr_in *)(const void *)sa;
}
static inline struct sockaddr_in6 *nx_sin6(struct sockaddr *sa)
{
return (struct sockaddr_in6 *)(void *)sa;
}
static inline const struct sockaddr_in6 *nx_csin6(const struct sockaddr *sa)
{
return (const struct sockaddr_in6 *)(const void *)sa;
}
static inline struct sockaddr_un *nx_sun(struct sockaddr *sa)
{
return (struct sockaddr_un *)(void *)sa;
}
static inline const struct sockaddr_un *nx_csun(const struct sockaddr *sa)
{
return (const struct sockaddr_un *)(const void *)sa;
}
static inline socklen_t nx_family_size(int family)
{
switch (family) {
case AF_INET:
return (socklen_t)sizeof(struct sockaddr_in);
case AF_INET6:
return (socklen_t)sizeof(struct sockaddr_in6);
default:
return 0;
}
}
int nx_addr_equal(const struct sockaddr *a, const struct sockaddr *b);
int nx_addr_format(const struct sockaddr *sa, char *buf, size_t len);
int nx_addr_port(const struct sockaddr *sa);
int nx_addr_is_loopback(const struct sockaddr *sa);
int nx_addr_parse(const char *host, int port, struct sockaddr_storage *out);
void nx_addr_set_port(struct sockaddr *sa, int port);
int nx_addr_parse_ip(const char *host, int port, struct sockaddr_storage *out);
#if defined(__cplusplus)
}
#endif
#endif
+58
View File
@@ -0,0 +1,58 @@
#ifndef NX_SOCKET_H
#define NX_SOCKET_H
#include "nx_types.h"
#include "nx_buf.h"
#include "nx_sockaddr.h"
#if defined(__cplusplus)
extern "C" {
#endif
#ifdef MSG_NOSIGNAL
#define NX_SOCK_MSG_NOSIGNAL MSG_NOSIGNAL
#else
#define NX_SOCK_MSG_NOSIGNAL 0
#endif
int nx_socket(int domain, int type, int protocol);
int nx_set_nonblock(int fd, int on);
int nx_set_cloexec(int fd, int on);
int nx_set_reuseaddr(int fd, int on);
int nx_set_nosigpipe(int fd, int on);
int nx_socket_nosigpipe(void);
int nx_set_timeouts(int fd, int timeout_ms);
int nx_bind(int fd, const struct sockaddr *addr, socklen_t addrlen);
int nx_listen(int fd, int backlog);
int nx_accept(int fd, struct sockaddr_storage *peer, socklen_t *peerlen);
int nx_connect_timeout(int fd, const struct sockaddr *addr, socklen_t addrlen,
int timeout_ms);
int nx_listen_unix(const char *path, int backlog, int *abstract_out);
int nx_connect_unix(const char *path);
ssize_t nx_recv(int fd, void *buf, size_t n, int flags);
ssize_t nx_send(int fd, const void *buf, size_t n, int flags);
int nx_send_all(int fd, const void *buf, size_t n, int flags);
ssize_t nx_recv_line(int fd, nx_buf *scratch, char *line, size_t limit);
void nx_close(int *fd);
#if defined(__cplusplus)
}
#endif
#endif
+23
View File
@@ -0,0 +1,23 @@
#ifndef NX_TYPES_H
#define NX_TYPES_H
#include <stddef.h>
#include <stdint.h>
#if defined(__cplusplus)
extern "C" {
#endif
#define NX_MAX_ERROR 256
const char *nx_strerror(int err);
const char *nx_version_string(void);
int64_t nx_now_ms(void);
#if defined(__cplusplus)
}
#endif
#endif
+42
View File
@@ -0,0 +1,42 @@
#ifndef NX_URL_H
#define NX_URL_H
#include "nx_types.h"
#if defined(__cplusplus)
extern "C" {
#endif
#define NX_URL_MAX_HOST 256
#define NX_URL_MAX_PATH 2048
typedef enum {
NX_SCHEME_HTTP,
NX_SCHEME_HTTPS,
NX_SCHEME_UNKNOWN
} nx_scheme;
typedef struct nx_url {
nx_scheme scheme;
char host[NX_URL_MAX_HOST];
int port;
int host_is_ipv6_literal;
char path[NX_URL_MAX_PATH];
const char *query;
const char *fragment;
char request_target[NX_URL_MAX_PATH];
} nx_url;
int nx_url_parse(const char *url, nx_url *out);
const char *nx_url_error(void);
#if defined(__cplusplus)
}
#endif
#endif
+134
View File
@@ -0,0 +1,134 @@
# libnx Q&A
## What is libnx?
A portable C networking library for Unix-like systems: TCP and Unix sockets, an
event loop, name resolution, URL parsing and an HTTP/1.1 client, with no
dependency beyond libc and pthreads.
## Why is there no HTTPS / TLS support?
TLS needs three things libc does not provide: X.509 certificate parsing, a
certificate trust store, and AEAD cipher implementations (AES-GCM,
ChaCha20-Poly1305) plus a safe random source and a TLS state machine. A correct
implementation of any one of those is a project of its own, and a subtly wrong
one is worse than none. `https://` is recognised, rejected, and reported through
`nx_url_error()` and `nx_http_error()`.
## Can I add TLS later?
Yes. Nothing in the design prevents a separate module from wrapping a connected
socket. The library deliberately does not ship a fake or best-effort TLS layer,
because a TLS layer that silently downgrades or skips verification is a security
hole.
## Why not just link OpenSSL / mbedTLS / wolfSSL?
Because one of the project's constraints is zero external dependencies. If you
want TLS, link the library of your choice on top of a libnx socket; libnx will
not do it for you.
## Why HTTP/1.1 and not HTTP/2 or HTTP/3?
Both need HPACK or QPACK and, for HTTP/3, QUIC over UDP. Those are large protocol
implementations with their own state machines and congestion control. HTTP/1.1
covers the common request/response case and keeps the framing logic small enough
to review.
## Why is HTTP included if this is "just a networking library"?
The library was scoped to be useful for a network client without dragging in an
HTTP library as a dependency. The HTTP client is deliberately small: one request
at a time, no connection pooling, no pipelining.
## Does it support Windows?
No. It targets Unix-like systems (Linux, macOS/XNU, the BSDs). Windows
networking differs enough (Winsock, IOCP, no `epoll`/`kqueue`) that supporting it
would be a separate port, not a build flag.
## Why `getaddrinfo` instead of a custom resolver?
A custom resolver means shipping a stub resolver, `/etc/hosts` handling, DNS wire
format, caching and TCP fallback for truncated answers. `getaddrinfo` already
does all of that, is on every target, and respects the system's resolver
configuration. The cost is that it blocks, which the API states instead of
hiding.
## Is name resolution non-blocking?
`nx_resolve` and `nx_resolve_blocking` block. `nx_resolve_async` runs the lookup
on a worker thread and delivers the result on the reactor thread through the
reactor's wakeup pipe. An in-flight async lookup cannot be cancelled, because
`getaddrinfo` cannot be interrupted.
## How do I do non-blocking I/O?
Create the socket, put it in non-blocking mode with `nx_set_nonblock`, and drive
it from the reactor. `nx_connect_timeout` handles an in-progress connect and
restores the socket's original blocking mode when it returns.
## Why is the reactor level-triggered?
Because level-triggered behaviour is the same on epoll, kqueue and poll. With
edge triggering, a socket that is not drained to `EAGAIN` never reports again,
and getting that wrong is silent data corruption. Level triggering trades a few
extra wakeups for a correctness property that holds on every backend.
## Can I modify events from inside a callback?
Yes. `nx_reactor_add`, `nx_reactor_mod` and `nx_reactor_del` are all safe to call
from a callback. A deletion that targets the event currently being dispatched is
deferred until the dispatch loop finishes, so the event is not freed from under
its own callback.
## Why does `nx_reactor_add` take the fd, callback and userdata again?
`nx_event_new` allocates the token and `nx_reactor_add` registers it. The add
call takes the same fields so that an `nx_event` embedded in a larger struct can
be registered without a separate `nx_event_new` allocation.
## Is libnx thread-safe?
The reactor is not: it must be driven from one thread. `nx_reactor_wakeup` is the
one function safe to call from another thread, and it is what async DNS uses.
Error strings are kept in a thread-local buffer, so they never take a lock.
`nx_selfpipe_notify` is async-signal-safe.
## Why is there no logging?
A library that logs decides for the application. Every failure returns an error
code, `nx_strerror` / `nx_http_error` / `nx_url_error` / `nx_gai_strerror`
provide the message, and the application decides whether and where to print it.
## Why does `nx_http_perform` return 0 for a 404?
Because a `404` is a completed HTTP exchange, not a transport failure. Return
`-1` means the request could not be sent or the response could not be parsed.
Check `res.status` for the HTTP result.
## How do I build and install it?
```sh
make
sudo make install
```
See [docs.md](docs.md) for the details and the list of backends.
## How do I run the tests?
```sh
make test
```
The test suite under `tests/` is not written yet, so there is currently nothing
to run.
## Can I use libnx from C++?
Yes. All public headers are wrapped in `extern "C"` and compile as C++.
## What license is libnx under?
MIT. See [LICENSE](../LICENSE).
+266
View File
@@ -0,0 +1,266 @@
# 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](#building)
- [Installing](#installing)
- [Quick start](#quick-start)
- [Modules](#modules)
- [Event loop](#event-loop)
- [HTTP client](#http-client)
- [Name resolution](#name-resolution)
- [Platform support](#platform-support)
- [Limits and safety](#limits-and-safety)
- [Status](#status)
## Building
```sh
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
```sh
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
```c
#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`:
```sh
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.
```c
nx_buf b = NX_BUF_INIT;
nx_buf_append_str(&b, "hello");
nx_buf_appendf(&b, ", %s", "world");
nx_buf_free(&b);
```
### Addresses
```c
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.
```c
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.
```c
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.
```c
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:
```c
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](FAQ.md) for why.
## Name resolution
```c
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-Length` rejected;
- `Content-Length` together with `Transfer-Encoding` rejected;
- 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.
+1
View File
@@ -0,0 +1 @@
All Markdown files were written by LLM (except README.md)
+226
View File
@@ -0,0 +1,226 @@
#include "nx_internal.h"
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NX_BUF_MAX_GROW (16u * 1024u * 1024u)
void nx_buf_init(nx_buf *b)
{
b->data = NULL;
b->len = b->pos = b->cap = 0;
}
void nx_buf_free(nx_buf *b)
{
free(b->data);
nx_buf_init(b);
}
void nx_buf_reset(nx_buf *b)
{
b->len = b->pos = 0;
}
void nx_buf_compact(nx_buf *b)
{
if (b->pos == 0) return;
size_t avail = b->len - b->pos;
if (avail > 0) memmove(b->data, b->data + b->pos, avail);
b->len = avail;
b->pos = 0;
}
int nx_buf_reserve(nx_buf *b, size_t extra)
{
size_t need, cap;
uint8_t *p;
if (extra > NX_BUF_MAX_GROW || b->len + extra < b->len) {
errno = ENOMEM;
return -1;
}
if (b->pos > 0 && b->len + extra > b->cap) {
nx_buf_compact(b);
}
need = b->len + extra;
if (need <= b->cap) return 0;
cap = b->cap ? b->cap : 256;
while (cap < need) {
size_t next = cap * 2;
if (next < cap) { cap = need; break; }
cap = next;
}
p = (uint8_t *)realloc(b->data, cap);
if (p == NULL) { errno = ENOMEM; return -1; }
b->data = p;
b->cap = cap;
return 0;
}
int nx_buf_append(nx_buf *b, const void *p, size_t n)
{
if (n == 0) return 0;
if (nx_buf_reserve(b, n) != 0) return -1;
memcpy(b->data + b->len, p, n);
b->len += n;
return 0;
}
int nx_buf_append_str(nx_buf *b, const char *s)
{
return nx_buf_append(b, s, strlen(s));
}
int nx_buf_append_char(nx_buf *b, char c)
{
return nx_buf_append(b, &c, 1);
}
int nx_buf_appendf(nx_buf *b, const char *fmt, ...)
{
va_list ap;
int n;
size_t avail;
va_start(ap, fmt);
avail = b->cap - b->len;
if (avail > 0) {
n = vsnprintf((char *)b->data + b->len, avail, fmt, ap);
va_end(ap);
if (n < 0) return -1;
if ((size_t)n < avail) {
b->len += (size_t)n;
return 0;
}
} else {
va_end(ap);
}
va_start(ap, fmt);
n = vsnprintf(NULL, 0, fmt, ap);
va_end(ap);
if (n < 0) return -1;
if (nx_buf_reserve(b, (size_t)n + 1) != 0) return -1;
va_start(ap, fmt);
n = vsnprintf((char *)b->data + b->len, b->cap - b->len, fmt, ap);
va_end(ap);
if (n < 0) return -1;
b->len += (size_t)n;
return 0;
}
void nx_buf_consume(nx_buf *b, size_t n)
{
size_t avail = b->len - b->pos;
if (n >= avail) { b->pos = b->len; return; }
b->pos += n;
}
int nx_buf_read_line(nx_buf *b, size_t max_line, size_t *pos,
const uint8_t **line, size_t *line_len)
{
const uint8_t *start = nx_buf_head(b);
size_t avail = nx_buf_avail(b);
const uint8_t *nl;
if (pos) *pos = b->pos;
if (avail == 0) return 0;
nl = (const uint8_t *)memchr(start, '\n', avail);
if (nl == NULL) {
if (avail > max_line) return -1;
return 0;
}
{
size_t n = (size_t)(nl - start);
size_t trimmed = n;
if (trimmed > 0 && start[trimmed - 1] == '\r') trimmed--;
if (trimmed > max_line) return -1;
if (line) *line = start;
if (line_len) *line_len = trimmed;
}
return 1;
}
int nx_ring_init(nx_ring *r, size_t cap)
{
if (cap == 0) { errno = EINVAL; return -1; }
r->data = (uint8_t *)malloc(cap);
if (r->data == NULL) { errno = ENOMEM; return -1; }
r->cap = cap;
r->head = r->tail = 0;
return 0;
}
void nx_ring_free(nx_ring *r)
{
free(r->data);
r->data = NULL;
r->cap = r->head = r->tail = 0;
}
size_t nx_ring_write(nx_ring *r, const void *p, size_t n)
{
const uint8_t *src = (const uint8_t *)p;
size_t space = nx_ring_free_space(r);
size_t first;
if (n > space) n = space;
if (n == 0) return 0;
first = r->cap - r->head;
if (first > n) first = n;
memcpy(r->data + r->head, src, first);
if (n > first) memcpy(r->data, src + first, n - first);
r->head = (r->head + n) % r->cap;
return n;
}
size_t nx_ring_read(nx_ring *r, void *p, size_t n)
{
uint8_t *dst = (uint8_t *)p;
size_t used = nx_ring_used(r);
size_t first;
if (n > used) n = used;
if (n == 0) return 0;
first = r->cap - r->tail;
if (first > n) first = n;
memcpy(dst, r->data + r->tail, first);
if (n > first) memcpy(dst + first, r->data, n - first);
r->tail = (r->tail + n) % r->cap;
return n;
}
size_t nx_ring_peek(const nx_ring *r, const void **p, size_t n)
{
size_t used = nx_ring_used(r);
size_t first;
if (n > used) n = used;
if (n == 0 || p == NULL) return 0;
first = r->cap - r->tail;
if (first > n) first = n;
if (first == n) {
*p = r->data + r->tail;
return n;
}
*p = r->data + r->tail;
return first;
}
+48
View File
@@ -0,0 +1,48 @@
#ifndef NX_INTERNAL_H
#define NX_INTERNAL_H
#include <nx/nx.h>
#if defined(__linux__)
# define NX_PLATFORM_LINUX 1
# define NX_BACKEND_EPOLL 1
#elif defined(__APPLE__)
# define NX_PLATFORM_APPLE 1
# define NX_BACKEND_KQUEUE 1
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
defined(__DragonFly__)
# define NX_PLATFORM_BSD 1
# define NX_BACKEND_KQUEUE 1
#else
# define NX_PLATFORM_UNKNOWN 1
# define NX_BACKEND_POLL 1
#endif
#if defined(__linux__) && defined(SYS_accept4)
# define NX_HAVE_ACCEPT4 1
#else
# define NX_HAVE_ACCEPT4 0
#endif
#if defined(SO_REUSEPORT)
# define NX_HAVE_REUSEPORT 1
#else
# define NX_HAVE_REUSEPORT 0
#endif
#if defined(SO_NOSIGPIPE)
# define NX_HAVE_SO_NOSIGPIPE 1
#else
# define NX_HAVE_SO_NOSIGPIPE 0
#endif
int nx_strcasecmp_ascii(const char *a, const char *b);
void nx_strlowercase(char *dst, size_t dstsz, const char *src);
size_t nx_strlcpy(char *dst, const char *src, size_t dstsz);
int nx_has_ctl(const char *s, size_t n);
void nx_url_percent_decode(char *dst, size_t dstsz, const char *src);
#endif
+163
View File
@@ -0,0 +1,163 @@
#include "nx_internal.h"
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
int nx_addr_equal(const struct sockaddr *a, const struct sockaddr *b)
{
if (a == NULL || b == NULL) return 0;
if (a->sa_family != b->sa_family) return 0;
switch (a->sa_family) {
case AF_INET: {
const struct sockaddr_in *x = nx_csin(a);
const struct sockaddr_in *y = nx_csin(b);
return x->sin_port == y->sin_port && x->sin_addr.s_addr == y->sin_addr.s_addr;
}
case AF_INET6: {
const struct sockaddr_in6 *x = nx_csin6(a);
const struct sockaddr_in6 *y = nx_csin6(b);
return x->sin6_port == y->sin6_port &&
memcmp(&x->sin6_addr, &y->sin6_addr, sizeof(x->sin6_addr)) == 0 &&
x->sin6_scope_id == y->sin6_scope_id;
}
#ifdef AF_UNIX
case AF_UNIX: {
const struct sockaddr_un *x = nx_csun(a);
const struct sockaddr_un *y = nx_csun(b);
return strncmp(x->sun_path, y->sun_path, sizeof(x->sun_path)) == 0;
}
#endif
default:
return 0;
}
}
int nx_addr_format(const struct sockaddr *sa, char *buf, size_t len)
{
if (sa == NULL || buf == NULL || len == 0) return -1;
buf[0] = '\0';
switch (sa->sa_family) {
case AF_INET:
if (inet_ntop(AF_INET, &nx_csin(sa)->sin_addr, buf, (socklen_t)len) == NULL)
return -1;
return (int)strlen(buf);
case AF_INET6:
if (inet_ntop(AF_INET6, &nx_csin6(sa)->sin6_addr, buf, (socklen_t)len) == NULL)
return -1;
{
const struct sockaddr_in6 *s6 = nx_csin6(sa);
if (s6->sin6_scope_id != 0) {
char tmp[64];
int n = snprintf(tmp, sizeof(tmp), "%%%u", s6->sin6_scope_id);
if (n > 0 && strlen(buf) + (size_t)n < len) {
memcpy(buf + strlen(buf), tmp, (size_t)n + 1);
}
}
}
return (int)strlen(buf);
case AF_UNIX:
return (int)nx_strlcpy(buf, nx_csun(sa)->sun_path, len);
default:
return -1;
}
}
int nx_addr_port(const struct sockaddr *sa)
{
if (sa == NULL) return -1;
switch (sa->sa_family) {
case AF_INET: return ntohs(nx_csin(sa)->sin_port);
case AF_INET6: return ntohs(nx_csin6(sa)->sin6_port);
default: return -1;
}
}
int nx_addr_is_loopback(const struct sockaddr *sa)
{
if (sa == NULL) return 0;
switch (sa->sa_family) {
case AF_INET: {
uint32_t a = ntohl(nx_csin(sa)->sin_addr.s_addr);
return (a >> 24) == 127;
}
case AF_INET6:
return IN6_IS_ADDR_LOOPBACK(&nx_csin6(sa)->sin6_addr) ? 1 : 0;
default:
return 0;
}
}
static int unbracket(const char *in, char *out, size_t outsz)
{
size_t n = strlen(in);
if (n >= 2 && in[0] == '[' && in[n - 1] == ']') {
if (n - 2 + 1 > outsz) return -1;
memcpy(out, in + 1, n - 2);
out[n - 2] = '\0';
return 1;
}
if (nx_strlcpy(out, in, outsz) >= outsz) return -1;
return 0;
}
int nx_addr_parse_ip(const char *host, int port, struct sockaddr_storage *out)
{
struct in_addr v4;
struct in6_addr v6;
char bare[128];
int br;
if (host == NULL || out == NULL) { errno = EINVAL; return -1; }
if (port < 0 || port > 65535) { errno = EINVAL; return -1; }
br = unbracket(host, bare, sizeof(bare));
if (br < 0) { errno = EINVAL; return -1; }
if (br == 1) memset(out, 0, sizeof(*out));
if (inet_pton(AF_INET, bare, &v4) == 1) {
struct sockaddr_in *sa = (struct sockaddr_in *)(void *)out;
memset(out, 0, sizeof(*out));
sa->sin_family = AF_INET;
sa->sin_port = htons((uint16_t)port);
sa->sin_addr = v4;
nx_set_len((struct sockaddr *)sa, (socklen_t)sizeof(*sa));
return 0;
}
if (inet_pton(AF_INET6, bare, &v6) == 1) {
struct sockaddr_in6 *sa = (struct sockaddr_in6 *)(void *)out;
memset(out, 0, sizeof(*out));
sa->sin6_family = AF_INET6;
sa->sin6_port = htons((uint16_t)port);
sa->sin6_addr = v6;
nx_set_len((struct sockaddr *)sa, (socklen_t)sizeof(*sa));
return 0;
}
errno = EINVAL;
return -1;
}
int nx_addr_parse(const char *host, int port, struct sockaddr_storage *out)
{
return nx_addr_parse_ip(host, port, out);
}
void nx_addr_set_port(struct sockaddr *sa, int port)
{
if (sa == NULL) return;
switch (sa->sa_family) {
case AF_INET:
nx_sin(sa)->sin_port = htons((uint16_t)port);
break;
case AF_INET6:
nx_sin6(sa)->sin6_port = htons((uint16_t)port);
break;
default:
break;
}
}
+86
View File
@@ -0,0 +1,86 @@
#include "nx_internal.h"
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
static _Thread_local char nx_errbuf[NX_MAX_ERROR];
const char *nx_strerror(int err)
{
#if defined(__GLIBC__) && defined(_GNU_SOURCE)
char *msg = strerror_r(err, nx_errbuf, sizeof(nx_errbuf));
return msg ? msg : "unknown error";
#else
if (strerror_r(err, nx_errbuf, sizeof(nx_errbuf)) != 0) {
snprintf(nx_errbuf, sizeof(nx_errbuf), "errno %d", err);
}
return nx_errbuf;
#endif
}
const char *nx_version_string(void)
{
return "libnx " NX_VERSION_STRING;
}
int64_t nx_now_ms(void)
{
struct timespec ts;
#if defined(CLOCK_MONOTONIC)
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
#endif
if (clock_gettime(CLOCK_REALTIME, &ts) == 0) {
return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
return 0;
}
int nx_strcasecmp_ascii(const char *a, const char *b)
{
while (*a && *b) {
unsigned char ca = (unsigned char)*a++;
unsigned char cb = (unsigned char)*b++;
if (ca >= 'A' && ca <= 'Z') ca = (unsigned char)(ca - 'A' + 'a');
if (cb >= 'A' && cb <= 'Z') cb = (unsigned char)(cb - 'A' + 'a');
if (ca != cb) return (int)ca - (int)cb;
}
return (int)(unsigned char)*a - (int)(unsigned char)*b;
}
void nx_strlowercase(char *dst, size_t dstsz, const char *src)
{
if (dstsz == 0) return;
size_t i = 0;
for (; src[i] && i + 1 < dstsz; i++) {
unsigned char c = (unsigned char)src[i];
dst[i] = (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : (char)c;
}
dst[i] = '\0';
}
size_t nx_strlcpy(char *dst, const char *src, size_t dstsz)
{
size_t len = strlen(src);
if (dstsz != 0) {
size_t n = len < dstsz - 1 ? len : dstsz - 1;
memcpy(dst, src, n);
dst[n] = '\0';
}
return len;
}
int nx_has_ctl(const char *s, size_t n)
{
for (size_t i = 0; i < n; i++) {
unsigned char c = (unsigned char)s[i];
if (c < 0x20 || c == 0x7f) return 1;
}
return 0;
}
+262
View File
@@ -0,0 +1,262 @@
#include "nx_internal.h"
#include "reactor_internal.h"
#include <errno.h>
#include <netdb.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
const char *nx_gai_strerror(int err)
{
const char *s = gai_strerror(err);
return s ? s : "unknown name resolution error";
}
int nx_resolve(const char *host, const char *service, int family,
int socktype, struct sockaddr_storage *out, socklen_t *outlen,
int max, int *gai_err)
{
struct addrinfo hints;
struct addrinfo *res = NULL, *ai;
int n = 0;
int rc;
if (gai_err) *gai_err = 0;
if (host == NULL || out == NULL || outlen == NULL || max <= 0) {
if (gai_err) *gai_err = EAI_FAIL;
return -1;
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = family;
hints.ai_socktype = socktype;
rc = getaddrinfo(host, service, &hints, &res);
if (rc != 0) {
if (gai_err) *gai_err = rc;
return -1;
}
for (ai = res; ai != NULL && n < max; ai = ai->ai_next) {
if (ai->ai_addr == NULL || ai->ai_addrlen == 0) continue;
if (ai->ai_addrlen > sizeof(struct sockaddr_storage)) continue;
memset(&out[n], 0, sizeof(out[n]));
memcpy(&out[n], ai->ai_addr, ai->ai_addrlen);
outlen[n] = ai->ai_addrlen;
n++;
}
freeaddrinfo(res);
if (n == 0) {
if (gai_err) *gai_err = EAI_NONAME;
return -1;
}
return n;
}
int nx_resolve_one(const char *host, const char *service, int family,
int socktype, struct sockaddr_storage *out,
socklen_t *outlen, int *gai_err)
{
return nx_resolve(host, service, family, socktype, out, outlen, 1,
gai_err) == 1
? 0
: -1;
}
int nx_resolve_ip(const char *host, int port, struct sockaddr_storage *out,
socklen_t *outlen)
{
char service[8];
int n;
if (outlen) *outlen = 0;
if (port < 0 || port > 65535) return -1;
snprintf(service, sizeof(service), "%d", port);
n = nx_resolve(host, service, AF_UNSPEC, SOCK_STREAM, out, outlen, 1, NULL);
return n == 1 ? 0 : -1;
}
int nx_resolve_blocking(const char *host, int port,
struct sockaddr_storage *out, socklen_t *outlen,
int *gai_err)
{
char service[8];
int n;
if (outlen) *outlen = 0;
if (host == NULL || out == NULL) {
if (gai_err) *gai_err = EAI_FAIL;
return -1;
}
if (port < 0 || port > 65535) {
if (gai_err) *gai_err = EAI_FAIL;
return -1;
}
snprintf(service, sizeof(service), "%d", port);
n = nx_resolve(host, service, AF_UNSPEC, SOCK_STREAM, out, outlen, 1,
gai_err);
return n == 1 ? 0 : -1;
}
struct nx_resolve_req {
nx_reactor *r;
nx_resolve_cb cb;
void *userdata;
char *host;
char *service;
int family;
int socktype;
struct sockaddr_storage addr;
socklen_t addrlen;
int status;
pthread_mutex_t lock;
int done;
nx_resolve_req *prev;
nx_resolve_req *next;
};
static void req_free(nx_resolve_req *req)
{
if (req == NULL) return;
pthread_mutex_destroy(&req->lock);
free(req->host);
free(req->service);
free(req);
}
static nx_resolve_req *req_alloc(void)
{
nx_resolve_req *req = calloc(1, sizeof(*req));
if (req == NULL) return NULL;
if (pthread_mutex_init(&req->lock, NULL) != 0) { free(req); return NULL; }
return req;
}
static void *resolve_worker(void *arg)
{
nx_resolve_req *req = (nx_resolve_req *)arg;
int gai = 0;
int n;
n = nx_resolve(req->host, req->service, req->family, req->socktype,
&req->addr, &req->addrlen, 1, &gai);
req->status = (n == 1) ? 0 : gai;
pthread_mutex_lock(&req->lock);
req->done = 1;
pthread_mutex_unlock(&req->lock);
if (req->r != NULL) (void)nx_reactor_wakeup(req->r);
return NULL;
}
static void on_wakeup(nx_reactor *r, void *ud)
{
nx_resolve_req *req, *next;
(void)ud;
for (req = r->resolving; req != NULL; req = next) {
int done;
next = req->next;
pthread_mutex_lock(&req->lock);
done = req->done;
pthread_mutex_unlock(&req->lock);
if (!done) continue;
if (req->prev) req->prev->next = req->next;
else r->resolving = req->next;
if (req->next) req->next->prev = req->prev;
r->nresolving--;
if (req->cb != NULL) {
req->cb(req, req->status,
req->status == 0 ? (const struct sockaddr *)(void *)&req->addr
: NULL,
req->addrlen, req->userdata);
}
req_free(req);
}
}
static int start(nx_resolve_req **out, nx_reactor *r, const char *host,
const char *service, int family, int socktype,
nx_resolve_cb cb, void *userdata)
{
nx_resolve_req *req;
pthread_attr_t attr;
pthread_t tid;
int rc;
req = req_alloc();
if (req == NULL) { errno = ENOMEM; return -1; }
req->r = r;
req->cb = cb;
req->userdata = userdata;
req->family = family;
req->socktype = socktype;
req->host = strdup(host);
req->service = service ? strdup(service) : NULL;
if (req->host == NULL || (service != NULL && req->service == NULL)) {
req_free(req);
errno = ENOMEM;
return -1;
}
req->prev = NULL;
req->next = r->resolving;
if (r->resolving) r->resolving->prev = req;
r->resolving = req;
r->nresolving++;
if (pthread_attr_init(&attr) != 0) {
req_free(req);
errno = ENOMEM;
return -1;
}
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
rc = pthread_create(&tid, &attr, resolve_worker, req);
pthread_attr_destroy(&attr);
if (rc != 0) {
if (req->prev) req->prev->next = req->next;
else r->resolving = req->next;
if (req->next) req->next->prev = req->prev;
r->nresolving--;
req_free(req);
errno = rc;
return -1;
}
*out = req;
return 0;
}
int nx_resolve_async(nx_reactor *r, const char *host, const char *service,
int family, int socktype, int timeout_ms,
nx_resolve_cb cb, void *userdata)
{
(void)timeout_ms;
if (r == NULL || host == NULL) { errno = EINVAL; return -1; }
if (r->wakeup_cb == NULL) r->wakeup_cb = on_wakeup;
{
nx_resolve_req *req = NULL;
return start(&req, r, host, service, family, socktype, cb, userdata);
}
}
+109
View File
@@ -0,0 +1,109 @@
#include "nx_internal.h"
#include "reactor_internal.h"
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct nx_selfpipe {
int rfd;
int wfd;
};
int nx_selfpipe_new(nx_selfpipe **out)
{
nx_selfpipe *p;
int fds[2];
if (out == NULL) { errno = EINVAL; return -1; }
*out = NULL;
#if defined(__linux__) && defined(__NR_pipe2)
if (pipe2(fds, O_NONBLOCK | O_CLOEXEC) != 0) return -1;
#else
if (pipe(fds) != 0) return -1;
if (fcntl(fds[0], F_SETFL, O_NONBLOCK) != 0 ||
fcntl(fds[1], F_SETFL, O_NONBLOCK) != 0 ||
fcntl(fds[0], F_SETFD, FD_CLOEXEC) != 0 ||
fcntl(fds[1], F_SETFD, FD_CLOEXEC) != 0) {
int saved = errno;
close(fds[0]);
close(fds[1]);
errno = saved;
return -1;
}
#endif
p = (nx_selfpipe *)calloc(1, sizeof(*p));
if (p == NULL) {
int saved = errno;
close(fds[0]);
close(fds[1]);
errno = saved;
return -1;
}
p->rfd = fds[0];
p->wfd = fds[1];
*out = p;
return 0;
}
void nx_selfpipe_free(nx_selfpipe *p)
{
if (p == NULL) return;
if (p->rfd >= 0) close(p->rfd);
if (p->wfd >= 0) close(p->wfd);
free(p);
}
int nx_selfpipe_read_fd(const nx_selfpipe *p) { return p ? p->rfd : -1; }
int nx_selfpipe_write_fd(const nx_selfpipe *p) { return p ? p->wfd : -1; }
int nx_selfpipe_notify(nx_selfpipe *p)
{
unsigned char b = 1;
ssize_t n;
if (p == NULL) { errno = EINVAL; return -1; }
for (;;) {
n = write(p->wfd, &b, 1);
if (n == 1) return 0;
if (n < 0 && errno == EINTR) continue;
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return 0;
return -1;
}
}
int nx_selfpipe_drain(nx_selfpipe *p)
{
unsigned char scratch[256];
int total = 0;
if (p == NULL) { errno = EINVAL; return -1; }
for (;;) {
ssize_t n = read(p->rfd, scratch, sizeof(scratch));
if (n > 0) { total += (int)n; continue; }
if (n < 0 && errno == EINTR) continue;
break;
}
return total;
}
int nx_signal_set(int signo, void (*handler)(int))
{
struct sigaction sa;
if (handler == NULL) { errno = EINVAL; return -1; }
memset(&sa, 0, sizeof(sa));
sa.sa_handler = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
return sigaction(signo, &sa, NULL) < 0 ? -1 : 0;
}
+362
View File
@@ -0,0 +1,362 @@
#include "nx_internal.h"
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static int connect_wait(int fd, int timeout_ms);
int nx_socket_nosigpipe(void)
{
#if NX_HAVE_SO_NOSIGPIPE
return 1;
#else
return 0;
#endif
}
int nx_set_cloexec(int fd, int on)
{
int flags = fcntl(fd, F_GETFD, 0);
if (flags < 0) return -1;
if (on) flags |= FD_CLOEXEC; else flags &= ~FD_CLOEXEC;
return fcntl(fd, F_SETFD, flags) < 0 ? -1 : 0;
}
int nx_set_nonblock(int fd, int on)
{
int flags = fcntl(fd, F_GETFL, 0);
if (flags < 0) return -1;
if (on) flags |= O_NONBLOCK; else flags &= ~O_NONBLOCK;
return fcntl(fd, F_SETFL, flags) < 0 ? -1 : 0;
}
int nx_set_nosigpipe(int fd, int on)
{
#if NX_HAVE_SO_NOSIGPIPE
int v = on ? 1 : 0;
return setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &v, sizeof(v)) < 0 ? -1 : 0;
#else
(void)fd; (void)on;
return 0;
#endif
}
int nx_set_reuseaddr(int fd, int on)
{
int v = on ? 1 : 0;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) < 0) return -1;
#if NX_HAVE_REUSEPORT
(void)setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v));
#endif
return 0;
}
int nx_set_timeouts(int fd, int timeout_ms)
{
struct timeval tv;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) return -1;
if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0) return -1;
return 0;
}
int nx_socket(int domain, int type, int protocol)
{
int fd = socket(domain, type, protocol);
if (fd < 0) return -1;
if (nx_set_cloexec(fd, 1) != 0) goto fail;
#if NX_HAVE_SO_NOSIGPIPE
if (nx_set_nosigpipe(fd, 1) != 0) goto fail;
#endif
return fd;
fail: {
int saved = errno;
close(fd);
errno = saved;
return -1;
}
}
int nx_bind(int fd, const struct sockaddr *addr, socklen_t addrlen)
{
if (addrlen == 0) addrlen = nx_sockaddr_len(addr);
nx_set_len((struct sockaddr *)(void *)(size_t)(const void *)addr, addrlen);
return bind(fd, addr, addrlen);
}
int nx_listen(int fd, int backlog)
{
if (nx_set_reuseaddr(fd, 1) != 0) return -1;
return listen(fd, backlog);
}
static int accept_finish(int nfd, socklen_t len, socklen_t *peerlen)
{
if (nx_set_cloexec(nfd, 1) != 0) goto fail;
#if NX_HAVE_SO_NOSIGPIPE
if (nx_set_nosigpipe(nfd, 1) != 0) goto fail;
#else
(void)0;
#endif
if (peerlen) *peerlen = len;
return nfd;
fail: {
int saved = errno;
close(nfd);
errno = saved;
return -1;
}
}
int nx_accept(int fd, struct sockaddr_storage *peer, socklen_t *peerlen)
{
socklen_t len = peerlen ? *peerlen : 0;
int nfd;
#if NX_HAVE_ACCEPT4
nfd = accept4(fd, (struct sockaddr *)(void *)peer, &len, SOCK_CLOEXEC);
if (nfd >= 0) {
#if NX_HAVE_SO_NOSIGPIPE
if (nx_set_nosigpipe(nfd, 1) != 0) {
int saved = errno;
close(nfd);
errno = saved;
return -1;
}
#endif
if (peerlen) *peerlen = len;
return nfd;
}
if (errno != ENOSYS) return -1;
#endif
nfd = accept(fd, (struct sockaddr *)(void *)peer, &len);
if (nfd < 0) return -1;
return accept_finish(nfd, len, peerlen);
}
ssize_t nx_recv(int fd, void *buf, size_t n, int flags)
{
return recv(fd, buf, n, flags);
}
ssize_t nx_send(int fd, const void *buf, size_t n, int flags)
{
return send(fd, buf, n, flags | NX_SOCK_MSG_NOSIGNAL);
}
int nx_send_all(int fd, const void *buf, size_t n, int flags)
{
const uint8_t *p = (const uint8_t *)buf;
size_t done = 0;
while (done < n) {
ssize_t w = nx_send(fd, p + done, n - done, flags);
if (w > 0) { done += (size_t)w; continue; }
if (w < 0 && errno == EINTR) continue;
if (w < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
errno = ETIMEDOUT;
return -1;
}
if (w == 0) { errno = EPIPE; return -1; }
return -1;
}
return 0;
}
ssize_t nx_recv_line(int fd, nx_buf *scratch, char *line, size_t limit)
{
if (limit == 0) { errno = EINVAL; return -1; }
for (;;) {
const uint8_t *start = nx_buf_head(scratch);
size_t avail = nx_buf_avail(scratch);
const uint8_t *nl;
if (avail > limit) { errno = EMSGSIZE; return -1; }
if (avail > 0 && (nl = (const uint8_t *)memchr(start, '\n', avail)) != NULL) {
size_t n = (size_t)(nl - start);
size_t consumed = n + 1;
if (n > 0 && start[n - 1] == '\r') { n--; consumed++; }
if (n + 1 > limit) { errno = EMSGSIZE; return -1; }
memcpy(line, start, n);
line[n] = '\0';
nx_buf_consume(scratch, consumed);
return (ssize_t)n;
}
if (nx_buf_reserve(scratch, 4096) != 0) return -1;
{
ssize_t got = nx_recv(fd, scratch->data + scratch->len,
scratch->cap - scratch->len, 0);
if (got < 0) {
if (errno == EINTR) continue;
return -1;
}
if (got == 0) {
if (avail == 0) return 0;
if (avail + 1 > limit) { errno = EMSGSIZE; return -1; }
memcpy(line, start, avail);
line[avail] = '\0';
nx_buf_consume(scratch, avail);
return (ssize_t)avail;
}
scratch->len += (size_t)got;
}
}
}
void nx_close(int *fd)
{
if (fd == NULL || *fd < 0) return;
(void)close(*fd);
*fd = -1;
}
int nx_connect_timeout(int fd, const struct sockaddr *addr, socklen_t addrlen,
int timeout_ms)
{
int orig_flags;
int rc;
if (addrlen == 0) addrlen = nx_sockaddr_len(addr);
rc = connect(fd, addr, addrlen);
if (rc == 0) return 0;
if (errno != EINPROGRESS && errno != EALREADY && errno != EINTR) return -1;
if (errno == EINTR) {
}
orig_flags = fcntl(fd, F_GETFL, 0);
if (orig_flags < 0) return -1;
if (nx_set_nonblock(fd, 1) != 0) return -1;
rc = connect_wait(fd, timeout_ms);
if (fcntl(fd, F_SETFL, orig_flags) < 0 && rc == 0) return -1;
if (rc != 0) return -1;
return 0;
}
static int connect_wait(int fd, int timeout_ms)
{
int64_t deadline = nx_now_ms() + (timeout_ms > 0 ? timeout_ms : 0);
for (;;) {
struct pollfd pfd;
int64_t remaining;
int ms;
int soerr = 0;
socklen_t slen = sizeof(soerr);
pfd.fd = fd;
pfd.events = POLLOUT;
pfd.revents = 0;
remaining = deadline - nx_now_ms();
if (timeout_ms > 0 && remaining <= 0) { errno = ETIMEDOUT; return -1; }
ms = timeout_ms > 0 ? (remaining > INT32_MAX ? INT32_MAX : (int)remaining) : -1;
if (poll(&pfd, 1, ms) < 0) {
if (errno == EINTR) continue;
return -1;
}
if (pfd.revents == 0) { errno = ETIMEDOUT; return -1; }
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &slen) < 0) return -1;
if (soerr != 0) { errno = soerr; return -1; }
return 0;
}
}
int nx_listen_unix(const char *path, int backlog, int *abstract_out)
{
struct sockaddr_un addr;
int fd, abstract = 0;
if (abstract_out) *abstract_out = 0;
if (path == NULL || path[0] == '\0') { errno = EINVAL; return -1; }
if (path[0] == '\0' || (path[0] == '@' && path[1] != '\0')) {
#if defined(NX_PLATFORM_LINUX)
abstract = 1;
if (path[0] == '@') {
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, path + 1, strlen(path));
} else {
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, path, strlen(path));
}
#else
errno = EAFNOSUPPORT;
return -1;
#endif
} else {
if (strlen(path) >= sizeof(addr.sun_path)) { errno = ENAMETOOLONG; return -1; }
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, path, strlen(path) + 1);
}
if (!abstract) (void)unlink(path);
fd = nx_socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) return -1;
{
socklen_t alen = nx_sockaddr_len((struct sockaddr *)(void *)&addr);
nx_set_len((struct sockaddr *)(void *)&addr, alen);
if (bind(fd, (struct sockaddr *)(void *)&addr, alen) < 0) goto fail;
if (listen(fd, backlog) < 0) goto fail;
}
if (abstract_out) *abstract_out = abstract;
return fd;
fail: {
int saved = errno;
close(fd);
if (!abstract) (void)unlink(path);
errno = saved;
return -1;
}
}
int nx_connect_unix(const char *path)
{
struct sockaddr_un addr;
int fd;
if (path == NULL || path[0] == '\0') { errno = EINVAL; return -1; }
if (strlen(path) >= sizeof(addr.sun_path)) { errno = ENAMETOOLONG; return -1; }
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, path, strlen(path) + 1);
fd = nx_socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) return -1;
if (connect(fd, (struct sockaddr *)(void *)&addr,
nx_sockaddr_len((struct sockaddr *)(void *)&addr)) < 0) {
int saved = errno;
close(fd);
errno = saved;
return -1;
}
return fd;
}
+661
View File
@@ -0,0 +1,661 @@
#include "nx_internal.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static const char *http_err = "no error";
const char *nx_http_error(void)
{
return http_err;
}
static int hfail(const char *reason, int err)
{
http_err = reason;
if (err) errno = err;
return -1;
}
void nx_http_request_defaults(nx_http_request *req)
{
if (req == NULL) return;
memset(req, 0, sizeof(*req));
req->method = "GET";
req->timeout_ms = NX_HTTP_TIMEOUT_MS;
req->max_body = NX_HTTP_MAX_BODY;
}
void nx_http_response_free(nx_http_response *res)
{
if (res == NULL) return;
nx_buf_free(&res->body);
nx_buf_free(&res->headers_buf);
res->nheaders = 0;
}
static char *trim(char *s)
{
char *end;
while (*s == ' ' || *s == '\t') s++;
end = s + strlen(s);
while (end > s && (end[-1] == ' ' || end[-1] == '\t')) end--;
*end = '\0';
return s;
}
static int parse_content_length(const char *v, int64_t *out)
{
int64_t n = 0;
size_t i;
if (v == NULL || *v == '\0') return -1;
for (i = 0; v[i]; i++) {
if (v[i] < '0' || v[i] > '9') return -1;
if (n > (INT64_MAX - (v[i] - '0')) / 10) return -1;
n = n * 10 + (v[i] - '0');
}
*out = n;
return 0;
}
static int parse_chunk_size(const char *line, int64_t *out)
{
int64_t n = 0;
size_t i = 0;
if (line == NULL || line[0] == '\0') return -1;
for (; i < 8 && line[i]; i++) {
char c = line[i];
int d;
if (c >= '0' && c <= '9') d = c - '0';
else if (c >= 'a' && c <= 'f') d = c - 'a' + 10;
else if (c >= 'A' && c <= 'F') d = c - 'A' + 10;
else break;
if (n > (INT64_MAX - d) / 16) return -1;
n = n * 16 + d;
}
if (i == 0) return -1;
if (line[i] != '\0' && line[i] != ';') return -1;
*out = n;
return 0;
}
static int parse_status_line(const char *line, nx_http_response *res)
{
const char *p = line;
int major = 0, minor = 0;
const char *sp1, *sp2;
if (strncmp(p, "HTTP/", 5) != 0)
return hfail("malformed status line", 0);
p += 5;
if (*p < '0' || *p > '9') return hfail("malformed HTTP version", 0);
major = *p++ - '0';
if (*p++ != '.') return hfail("malformed HTTP version", 0);
if (*p < '0' || *p > '9') return hfail("malformed HTTP version", 0);
minor = *p++ - '0';
if (*p != ' ' && *p != '\t') return hfail("malformed HTTP version", 0);
snprintf(res->version, sizeof(res->version), "HTTP/%d.%d", major, minor);
if (major != 1) return hfail("unsupported HTTP version", 0);
while (*p == ' ' || *p == '\t') p++;
if (*p < '0' || *p > '9') return hfail("malformed status code", 0);
{
int code = 0;
while (*p >= '0' && *p <= '9') {
code = code * 10 + (*p - '0');
if (code > 999) return hfail("malformed status code", 0);
p++;
}
res->status = code;
}
sp1 = p;
while (*p == ' ' || *p == '\t') p++;
sp2 = p;
nx_strlcpy(res->reason, sp2, sizeof(res->reason));
(void)sp1;
return 0;
}
const char *nx_http_header_get(const nx_http_response *res, const char *name)
{
int i;
if (res == NULL || name == NULL) return NULL;
for (i = 0; i < res->nheaders; i++) {
if (nx_strcasecmp_ascii(res->headers[i].name, name) == 0)
return res->headers[i].value;
}
return NULL;
}
static int add_header(nx_http_response *res, const char *name, size_t nlen,
const char *value, size_t vlen)
{
if (res->nheaders >= NX_HTTP_MAX_HEADERS)
return hfail("too many response headers", 0);
if (nx_buf_reserve(&res->headers_buf, nlen + 1 + vlen + 1) != 0)
return hfail("out of memory", ENOMEM);
{
char *base = (char *)res->headers_buf.data + res->headers_buf.len;
size_t i;
for (i = 0; i < nlen; i++) {
char c = name[i];
base[i] = (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : c;
}
base[nlen] = '\0';
memcpy(base + nlen + 1, value, vlen);
base[nlen + 1 + vlen] = '\0';
res->headers[res->nheaders].name = base;
res->headers[res->nheaders].value = base + nlen + 1;
res->nheaders++;
res->headers_buf.len += nlen + 1 + vlen + 1;
}
return 0;
}
typedef struct {
int64_t content_length;
int have_length;
int chunked;
int close;
} framing;
static int read_headers(int fd, nx_buf *scratch, nx_http_response *res,
framing *f)
{
char line[NX_HTTP_MAX_LINE];
int first = 1;
int count = 0;
size_t total_bytes = 0;
ssize_t n;
nx_buf_init(&res->headers_buf);
while ((n = nx_recv_line(fd, scratch, line, sizeof(line))) > 0) {
char *colon;
if (first) {
if (parse_status_line(line, res) != 0) return -1;
first = 0;
continue;
}
if (line[0] == '\0') break;
if (++count > NX_HTTP_MAX_HEADERS)
return hfail("too many response headers", 0);
total_bytes += (size_t)n + 2;
if (total_bytes > NX_HTTP_MAX_HEADER_BYTES)
return hfail("response headers too large", 0);
colon = strchr(line, ':');
if (colon == NULL || colon == line)
return hfail("malformed header field", 0);
{
const char *p;
for (p = line; p < colon; p++) {
unsigned char c = (unsigned char)*p;
if (c <= 0x20 || c == 0x7f)
return hfail("invalid character in header name", 0);
}
}
{
const char *value = trim(colon + 1);
if (add_header(res, line, (size_t)(colon - line), value,
strlen(value)) != 0) {
return -1;
}
}
}
if (n < 0) return -1;
if (first) return hfail("empty response", 0);
{
const char *te = nx_http_header_get(res, "transfer-encoding");
const char *cl = nx_http_header_get(res, "content-length");
const char *conn = nx_http_header_get(res, "connection");
if (te != NULL) {
char lowered[64];
nx_strlowercase(lowered, sizeof(lowered), te);
{
char *semi = strchr(lowered, ';');
size_t l;
if (semi) *semi = '\0';
l = strlen(lowered);
while (l > 0 && (lowered[l - 1] == ' ' || lowered[l - 1] == '\t'))
lowered[--l] = '\0';
l = 0;
while (lowered[l] == ' ' || lowered[l] == '\t') l++;
if (strcmp(lowered + l, "chunked") != 0)
return hfail("unsupported transfer-encoding", 0);
}
if (cl != NULL)
return hfail("both transfer-encoding and content-length", 0);
f->chunked = 1;
} else if (cl != NULL) {
if (parse_content_length(cl, &f->content_length) != 0)
return hfail("malformed content-length", 0);
f->have_length = 1;
}
if (conn != NULL) {
char lowered[64];
nx_strlowercase(lowered, sizeof(lowered), conn);
if (strstr(lowered, "close") != NULL) f->close = 1;
}
}
res->chunked = f->chunked;
return 0;
}
static int copy_exact(int fd, nx_buf *scratch, nx_buf *dst, int64_t n,
int max_body)
{
while (n > 0) {
size_t avail = nx_buf_avail(scratch);
size_t take;
ssize_t got;
if (avail > 0) {
take = (int64_t)avail < n ? avail : (size_t)n;
if (nx_buf_append(dst, nx_buf_head(scratch), take) != 0)
return hfail("out of memory", ENOMEM);
nx_buf_consume(scratch, take);
n -= (int64_t)take;
if (n == 0) break;
if (max_body > 0 && (int64_t)nx_buf_avail(dst) > max_body)
return hfail("response body exceeds limit", 0);
continue;
}
if (nx_buf_reserve(scratch, 16384) != 0)
return hfail("out of memory", ENOMEM);
got = nx_recv(fd, scratch->data + scratch->len,
scratch->cap - scratch->len, 0);
if (got < 0) {
if (errno == EINTR) continue;
return hfail("read error", 0);
}
if (got == 0)
return hfail("connection closed before body complete", 0);
scratch->len += (size_t)got;
}
return 0;
}
static int read_body(int fd, nx_buf *scratch, nx_http_response *res,
const framing *f, int max_body)
{
res->has_body = 1;
if (f->chunked) {
for (;;) {
char sizebuf[NX_HTTP_MAX_LINE];
int64_t size;
ssize_t n;
n = nx_recv_line(fd, scratch, sizebuf, sizeof(sizebuf));
if (n < 0) return -1;
if (n == 0) return hfail("truncated chunked body", 0);
if (parse_chunk_size(sizebuf, &size) != 0)
return hfail("malformed chunk size", 0);
if (size == 0) break;
if (max_body > 0 && (int64_t)nx_buf_avail(&res->body) + size > max_body)
return hfail("response body exceeds limit", 0);
if (copy_exact(fd, scratch, &res->body, size, max_body) != 0)
return -1;
{
unsigned char crlf[2];
size_t got = 0;
while (got < 2) {
size_t avail = nx_buf_avail(scratch);
if (avail > 0) {
memcpy(crlf + got, nx_buf_head(scratch), 2 - got);
nx_buf_consume(scratch, 2 - got);
got = 2;
break;
}
if (nx_buf_reserve(scratch, 2) != 0)
return hfail("out of memory", ENOMEM);
{
ssize_t r = nx_recv(fd, scratch->data + scratch->len,
scratch->cap - scratch->len, 0);
if (r < 0) {
if (errno == EINTR) continue;
return hfail("read error", 0);
}
if (r == 0)
return hfail("truncated chunk terminator", 0);
scratch->len += (size_t)r;
}
}
if (crlf[0] != '\r' || crlf[1] != '\n')
return hfail("malformed chunk terminator", 0);
}
}
for (;;) {
char line[NX_HTTP_MAX_LINE];
ssize_t n = nx_recv_line(fd, scratch, line, sizeof(line));
if (n < 0) return -1;
if (n == 0 || line[0] == '\0') break;
}
return 0;
}
if (f->have_length) {
if (max_body > 0 && f->content_length > max_body)
return hfail("response body exceeds limit", 0);
if (f->content_length == 0) { res->has_body = 0; return 0; }
if (copy_exact(fd, scratch, &res->body, f->content_length, max_body) != 0)
return -1;
return 0;
}
for (;;) {
ssize_t got;
if (nx_buf_reserve(scratch, 16384) != 0)
return hfail("out of memory", ENOMEM);
got = nx_recv(fd, scratch->data + scratch->len,
scratch->cap - scratch->len, 0);
if (got < 0) {
if (errno == EINTR) continue;
return hfail("read error", 0);
}
if (got == 0) break;
if (max_body > 0 && (int64_t)nx_buf_avail(&res->body) + got > max_body)
return hfail("response body exceeds limit", 0);
if (nx_buf_append(&res->body, scratch->data + scratch->len,
(size_t)got) != 0) {
return hfail("out of memory", ENOMEM);
}
nx_buf_consume(scratch, (size_t)got);
}
return 0;
}
static int body_forbidden(int status, const char *method)
{
if (method != NULL && nx_strcasecmp_ascii(method, "HEAD") == 0) return 1;
if (status >= 100 && status < 200) return 1;
if (status == 204) return 1;
if (status == 304) return 1;
return 0;
}
static int build_request(nx_buf *out, const char *method, const char *host,
int port, int is_tls, const char *target,
nx_http_request *req)
{
int i;
int added_host = 0, added_len = 0, added_conn = 0;
if (nx_has_ctl(target, strlen(target)))
return hfail("control character in request target", EINVAL);
if (nx_has_ctl(method, strlen(method)))
return hfail("control character in method", EINVAL);
nx_buf_appendf(out, "%s %s HTTP/1.1\r\n", method, target);
if (host != NULL && *host != '\0') {
if (req->host != NULL) {
if (nx_buf_appendf(out, "Host: %s\r\n", req->host) != 0)
return hfail("out of memory", ENOMEM);
} else if (port == NX_HTTP_DEFAULT_PORT && !is_tls) {
if (nx_buf_appendf(out, "Host: %s\r\n", host) != 0)
return hfail("out of memory", ENOMEM);
} else if (nx_buf_appendf(out, "Host: %s:%d\r\n", host, port) != 0) {
return hfail("out of memory", ENOMEM);
}
added_host = 1;
}
if (!added_host)
return hfail("cannot determine Host header", EINVAL);
for (i = 0; i < req->nheaders; i++) {
const char *n = req->headers[i].name;
const char *v = req->headers[i].value;
if (n == NULL || v == NULL) continue;
if (nx_has_ctl(n, strlen(n)) || nx_has_ctl(v, strlen(v)))
return hfail("control character in header", EINVAL);
if (nx_strcasecmp_ascii(n, "host") == 0) continue;
if (nx_buf_appendf(out, "%s: %s\r\n", n, v) != 0)
return hfail("out of memory", ENOMEM);
if (nx_strcasecmp_ascii(n, "content-length") == 0) added_len = 1;
if (nx_strcasecmp_ascii(n, "connection") == 0) added_conn = 1;
}
if (req->user_agent &&
nx_buf_appendf(out, "User-Agent: libnx/%s\r\n",
NX_VERSION_STRING) != 0) {
return hfail("out of memory", ENOMEM);
}
if (!added_len) {
if (req->body != NULL && req->body_len > 0) {
if (nx_buf_appendf(out, "Content-Length: %zu\r\n", req->body_len) != 0)
return hfail("out of memory", ENOMEM);
} else if (strcmp(method, "POST") == 0 ||
strcmp(method, "PUT") == 0 ||
strcmp(method, "PATCH") == 0) {
if (nx_buf_appendf(out, "Content-Length: 0\r\n") != 0)
return hfail("out of memory", ENOMEM);
}
}
if (!added_conn && nx_buf_appendf(out, "Connection: close\r\n") != 0)
return hfail("out of memory", ENOMEM);
if (nx_buf_appendf(out, "\r\n") != 0)
return hfail("out of memory", ENOMEM);
if (req->body != NULL && req->body_len > 0) {
if (nx_buf_append(out, req->body, req->body_len) != 0)
return hfail("out of memory", ENOMEM);
}
return 0;
}
int nx_http_perform_fd(int fd, const char *host, const char *path,
nx_http_request *req, nx_http_response *res)
{
nx_buf scratch;
int rc;
(void)host;
(void)path;
if (req == NULL || res == NULL) return hfail("null argument", EINVAL);
nx_buf_init(&scratch);
rc = nx_http_read_response(fd, &scratch, req, res);
nx_buf_free(&scratch);
return rc;
}
int nx_http_read_response(int fd, nx_buf *scratch, nx_http_request *req,
nx_http_response *res)
{
framing f;
int max_body;
int rc;
if (scratch == NULL || req == NULL || res == NULL)
return hfail("null argument", EINVAL);
max_body = req->max_body > 0 ? req->max_body : NX_HTTP_MAX_BODY;
memset(&f, 0, sizeof(f));
f.content_length = -1;
rc = read_headers(fd, scratch, res, &f);
if (rc != 0) return rc;
if (!body_forbidden(res->status, req->method)) {
rc = read_body(fd, scratch, res, &f, max_body);
if (rc != 0) return rc;
} else {
res->has_body = 0;
}
res->keep_alive = !f.close && !(f.chunked == 0 && !f.have_length);
return 0;
}
int nx_http_perform(const char *url, nx_http_request *req,
nx_http_response *res)
{
nx_url u;
nx_buf out;
struct sockaddr_storage addr;
socklen_t addrlen = 0;
int gai = 0;
int fd = -1;
int timeout;
int redirects = 0;
int rc = -1;
char current[4096];
http_err = "no error";
if (url == NULL || req == NULL || res == NULL)
return hfail("null argument", EINVAL);
if (nx_strlcpy(current, url, sizeof(current)) >= sizeof(current))
return hfail("url too long", EINVAL);
timeout = req->timeout_ms > 0 ? req->timeout_ms : NX_HTTP_TIMEOUT_MS;
for (;;) {
const char *method = req->method ? req->method : "GET";
const char *path;
int is_redirect;
memset(res, 0, sizeof(*res));
nx_buf_init(&res->body);
nx_buf_init(&res->headers_buf);
if (nx_url_parse(current, &u) != 0)
return hfail(nx_url_error(), errno);
if (nx_resolve_one(u.host, NULL, AF_UNSPEC, SOCK_STREAM, &addr, &addrlen,
&gai) != 0) {
return hfail(nx_gai_strerror(gai), 0);
}
nx_addr_set_port((struct sockaddr *)(void *)&addr, u.port);
path = req->path ? req->path : u.request_target;
nx_buf_init(&out);
if (build_request(&out, method, u.host, u.port,
u.scheme == NX_SCHEME_HTTPS, path, req) != 0) {
nx_buf_free(&out);
return -1;
}
fd = nx_socket(addr.ss_family, SOCK_STREAM, 0);
if (fd < 0) { nx_buf_free(&out); return hfail("socket failed", 0); }
if (nx_set_timeouts(fd, timeout) != 0) {
nx_buf_free(&out);
nx_close(&fd);
return hfail("setsockopt failed", 0);
}
if (nx_connect_timeout(fd, (struct sockaddr *)(void *)&addr, addrlen,
timeout) != 0) {
int saved = errno;
nx_buf_free(&out);
nx_close(&fd);
return hfail(nx_strerror(saved), saved);
}
if (nx_send_all(fd, out.data, out.len, 0) != 0) {
int saved = errno;
nx_buf_free(&out);
nx_close(&fd);
return hfail(nx_strerror(saved), saved);
}
nx_buf_free(&out);
rc = nx_http_perform_fd(fd, u.host, path, req, res);
if (rc != 0) {
int saved = errno;
nx_close(&fd);
return hfail(http_err, saved);
}
nx_close(&fd);
is_redirect = (res->status == 301 || res->status == 302 ||
res->status == 303 || res->status == 307 ||
res->status == 308);
if (!is_redirect || !req->follow_redirect) return 0;
if (redirects >= req->follow_redirect)
return hfail("too many redirects", 0);
{
const char *loc = nx_http_header_get(res, "location");
char next[4096];
if (loc == NULL || *loc == '\0')
return hfail("redirect without location", 0);
if (strstr(loc, "://") != NULL) {
if (nx_strlcpy(next, loc, sizeof(next)) >= sizeof(next))
return hfail("redirect target too long", 0);
} else {
const char *slash = strchr(u.path, '/');
const char *last = strrchr(slash ? slash : u.path, '/');
size_t base = (size_t)((last ? last : u.path) - current);
if (loc[0] == '/') {
const char *root = strstr(current, "://");
root = root ? root + 3 : current;
if (nx_strlcpy(next, root, sizeof(next)) >= sizeof(next))
return hfail("redirect target too long", 0);
if (nx_strlcpy(next + strlen(next), loc,
sizeof(next) - strlen(next)) >=
sizeof(next) - strlen(next)) {
return hfail("redirect target too long", 0);
}
} else {
if (base + strlen(loc) + 1 >= sizeof(next))
return hfail("redirect target too long", 0);
memcpy(next, current, base);
nx_strlcpy(next + base, loc, sizeof(next) - base);
}
}
if (res->status == 303 ||
((res->status == 301 || res->status == 302) &&
nx_strcasecmp_ascii(method, "GET") != 0 &&
nx_strcasecmp_ascii(method, "HEAD") != 0)) {
req->method = "GET";
req->body = NULL;
req->body_len = 0;
}
redirects++;
if (nx_strlcpy(current, next, sizeof(current)) >= sizeof(current))
return hfail("redirect target too long", 0);
nx_http_response_free(res);
continue;
}
}
}
+356
View File
@@ -0,0 +1,356 @@
#include "nx_internal.h"
#include <arpa/inet.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *url_err = "no error";
const char *nx_url_error(void)
{
return url_err;
}
static int fail(const char *reason)
{
url_err = reason;
errno = EINVAL;
return -1;
}
static int is_hex(char c)
{
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F');
}
static int unhex(char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
return c - 'A' + 10;
}
static int valid_label(const char *s, size_t n)
{
size_t i;
if (n == 0 || n > 63) return 0;
if (s[0] == '-' || s[n - 1] == '-') return 0;
for (i = 0; i < n; i++) {
char c = s[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-') {
continue;
}
return 0;
}
return 1;
}
static int valid_ipv4(const char *s, size_t n)
{
unsigned parts = 0;
size_t i = 0;
while (i <= n) {
unsigned v = 0;
size_t digits = 0;
while (i < n && s[i] >= '0' && s[i] <= '9') {
v = v * 10 + (unsigned)(s[i] - '0');
if (v > 255) return 0;
digits++;
if (digits > 3) return 0;
i++;
}
if (digits == 0) return 0;
parts++;
if (i == n) break;
if (s[i] != '.') return 0;
i++;
if (i == n) return 0;
}
return parts == 4;
}
static int valid_ipv6(const char *s, size_t n)
{
char tmp[64];
struct in6_addr dummy;
if (n == 0 || n >= sizeof(tmp)) return 0;
memcpy(tmp, s, n);
tmp[n] = '\0';
return inet_pton(AF_INET6, tmp, &dummy) == 1;
}
static int valid_host(const char *s, size_t n, int *is_ipv6)
{
size_t i, label_start = 0;
*is_ipv6 = 0;
if (n == 0) return 0;
if (n > 253) return 0;
if (s[0] == '[') {
if (s[n - 1] != ']') return 0;
if (!valid_ipv6(s + 1, n - 2)) return 0;
*is_ipv6 = 1;
return 1;
}
if (valid_ipv4(s, n)) return 1;
if (memchr(s, ':', n) != NULL) {
return 0;
}
for (i = 0; i <= n; i++) {
if (i == n || s[i] == '.') {
if (!valid_label(s + label_start, i - label_start)) return 0;
label_start = i + 1;
}
}
return 1;
}
static int parse_authority(nx_url *u, const char *host, size_t hostlen,
const char *port, size_t portlen)
{
int is6 = 0;
if (!valid_host(host, hostlen, &is6))
return fail("invalid host");
if (hostlen >= NX_URL_MAX_HOST) return fail("host too long");
if (host[0] == '[') {
if (hostlen - 2 >= NX_URL_MAX_HOST) return fail("host too long");
memcpy(u->host, host + 1, hostlen - 2);
u->host[hostlen - 2] = '\0';
u->host_is_ipv6_literal = 1;
} else {
memcpy(u->host, host, hostlen);
u->host[hostlen] = '\0';
u->host_is_ipv6_literal = 0;
}
(void)is6;
if (portlen == 0) {
u->port = (u->scheme == NX_SCHEME_HTTPS) ? 443 : NX_HTTP_DEFAULT_PORT;
} else {
long v = 0;
size_t i;
if (portlen > 5) return fail("port out of range");
for (i = 0; i < portlen; i++) {
if (port[i] < '0' || port[i] > '9') return fail("invalid port");
v = v * 10 + (port[i] - '0');
}
if (v < 1 || v > 65535) return fail("port out of range");
u->port = (int)v;
}
return 0;
}
static void percent_decode(char *dst, size_t dstsz, const char *src,
size_t srclen)
{
size_t i = 0, o = 0;
while (i < srclen && o + 1 < dstsz) {
if (src[i] == '%' && i + 2 < srclen && is_hex(src[i + 1]) &&
is_hex(src[i + 2])) {
dst[o++] = (char)((unhex(src[i + 1]) << 4) | unhex(src[i + 2]));
i += 3;
} else {
dst[o++] = src[i++];
}
}
dst[o] = '\0';
}
static int valid_target(const char *s, size_t n)
{
size_t i;
for (i = 0; i < n; i++) {
unsigned char c = (unsigned char)s[i];
if (c <= 0x20 || c == 0x7f) return 0;
}
return 1;
}
int nx_url_parse(const char *url, nx_url *out)
{
const char *p, *end, *host, *hostend, *port, *portend;
const char *path, *pathend, *query = NULL, *queryend = NULL;
const char *frag = NULL, *fragend = NULL;
size_t n, pathlen;
int bracketed = 0;
url_err = "no error";
if (url == NULL || out == NULL) return fail("null argument");
memset(out, 0, sizeof(*out));
n = strlen(url);
if (n == 0) return fail("empty url");
if (nx_has_ctl(url, n)) return fail("control character in url");
p = url;
end = url + n;
{
const char *colon = memchr(p, ':', (size_t)(end - p));
const char *q;
if (colon == NULL) return fail("missing scheme");
for (q = p; q < colon; q++) {
char c = *q;
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.')) {
return fail("invalid scheme");
}
}
if (colon == p) return fail("empty scheme");
{
size_t slen = (size_t)(colon - p);
char scheme[16];
if (slen >= sizeof(scheme)) return fail("scheme too long");
memcpy(scheme, p, slen);
scheme[slen] = '\0';
nx_strlowercase(scheme, sizeof(scheme), scheme);
if (strcmp(scheme, "http") == 0) {
out->scheme = NX_SCHEME_HTTP;
} else if (strcmp(scheme, "https") == 0) {
out->scheme = NX_SCHEME_HTTPS;
} else {
return fail("unsupported scheme, expected http");
}
}
p = colon + 1;
}
if ((size_t)(end - p) < 2 || p[0] != '/' || p[1] != '/')
return fail("expected // after scheme");
{
const char *slash = memchr(p + 2, '/', (size_t)(end - (p + 2)));
const char *authend = slash ? slash : end;
const char *at;
{
const char *q = memchr(p + 2, '?', (size_t)(end - (p + 2)));
if (q != NULL && (slash == NULL || q < slash)) {
authend = q;
slash = NULL;
}
}
host = p + 2;
hostend = authend;
at = (const char *)memchr(host, '@', (size_t)(hostend - host));
if (at != NULL) return fail("credentials in url are not accepted");
port = NULL;
portend = NULL;
if (host[0] == '[') {
const char *rb = (const char *)memchr(host, ']',
(size_t)(hostend - host));
if (rb == NULL) return fail("unterminated IPv6 literal");
bracketed = 1;
if (rb + 1 < hostend) {
if (rb[1] != ':') return fail("invalid authority");
port = rb + 2;
portend = hostend;
}
hostend = rb + 1;
} else {
const char *c = (const char *)memchr(host, ':',
(size_t)(hostend - host));
if (c != NULL) {
port = c + 1;
portend = hostend;
hostend = c;
}
}
(void)bracketed;
if (parse_authority(out, host, (size_t)(hostend - host), port,
(size_t)(portend - port)) != 0) {
return -1;
}
p = slash ? slash : end;
}
{
const char *h = (const char *)memchr(p, '#', (size_t)(end - p));
const char *q = (const char *)memchr(p, '?', (size_t)(end - p));
if (h != NULL && (q == NULL || h < q)) {
frag = h + 1;
fragend = end;
end = h;
}
q = (const char *)memchr(p, '?', (size_t)(end - p));
if (q != NULL) {
query = q + 1;
queryend = (frag != NULL) ? frag - 1 : end;
end = q;
}
}
path = p;
pathend = end;
pathlen = (size_t)(pathend - path);
if (pathlen == 0) {
path = "/";
pathlen = 1;
} else if (path[0] != '/') {
return fail("path must be absolute");
}
if (pathlen >= NX_URL_MAX_PATH) return fail("path too long");
if (!valid_target(path, pathlen))
return fail("invalid character in path");
memcpy(out->path, path, pathlen);
out->path[pathlen] = '\0';
if (query != NULL) {
size_t qlen = (size_t)(queryend - query);
if (!valid_target(query, qlen))
return fail("invalid character in query");
if (pathlen + 1 + qlen >= NX_URL_MAX_PATH) return fail("url too long");
memcpy(out->path + pathlen, "?", 1);
memcpy(out->path + pathlen + 1, query, qlen);
out->path[pathlen + 1 + qlen] = '\0';
}
if (frag != NULL) {
size_t flen = (size_t)(fragend - frag);
if (!valid_target(frag, flen))
return fail("invalid character in fragment");
out->fragment = frag;
}
nx_strlcpy(out->request_target, out->path, sizeof(out->request_target));
out->query = out->path[0] ? strchr(out->path, '?') : NULL;
if (out->query) out->query++;
if (out->scheme == NX_SCHEME_HTTPS) {
url_err = "https requires TLS, which libnx does not implement";
errno = ENOTSUP;
return -1;
}
return 0;
}
void nx_url_percent_decode(char *dst, size_t dstsz, const char *src)
{
percent_decode(dst, dstsz, src, strlen(src));
}
+262
View File
@@ -0,0 +1,262 @@
#include "nx_internal.h"
#include "reactor_internal.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
const char *nx_reactor_backend(void)
{
#if defined(NX_BACKEND_EPOLL)
return "epoll";
#elif defined(NX_BACKEND_KQUEUE)
return "kqueue";
#else
return "poll";
#endif
}
void nx_reactor_free(nx_reactor *r)
{
if (r == NULL) return;
nx_backend_destroy(r);
if (r->evpipe_read >= 0) close(r->evpipe_read);
if (r->evpipe_write >= 0) close(r->evpipe_write);
free(r->evs);
free(r);
}
int nx_reactor_new(nx_reactor **out)
{
nx_reactor *r;
int fds[2];
if (out == NULL) { errno = EINVAL; return -1; }
*out = NULL;
r = (nx_reactor *)calloc(1, sizeof(*r));
if (r == NULL) { errno = ENOMEM; return -1; }
r->evpipe_read = r->evpipe_write = -1;
r->running = 0;
r->stopped = 0;
if (pipe(fds) != 0) { free(r); return -1; }
if (nx_set_nonblock(fds[0], 1) != 0 || nx_set_nonblock(fds[1], 1) != 0 ||
nx_set_cloexec(fds[0], 1) != 0 || nx_set_cloexec(fds[1], 1) != 0) {
int saved = errno;
close(fds[0]);
close(fds[1]);
free(r);
errno = saved;
return -1;
}
r->evpipe_read = fds[0];
r->evpipe_write = fds[1];
if (nx_backend_init(r) != 0) {
int saved = errno;
close(r->evpipe_read);
close(r->evpipe_write);
free(r);
errno = saved;
return -1;
}
*out = r;
return 0;
}
nx_event *nx_event_new(int fd, nx_cb cb, void *userdata)
{
nx_event *ev = (nx_event *)calloc(1, sizeof(*ev));
if (ev == NULL) { errno = ENOMEM; return NULL; }
ev->fd = fd;
ev->cb = cb;
ev->userdata = userdata;
ev->r = NULL;
ev->events = 0;
ev->revents = 0;
ev->index = (size_t)-1;
ev->deleted = 0;
return ev;
}
void nx_event_free(nx_event *ev)
{
if (ev == NULL) return;
if (ev->r != NULL) { errno = EBUSY; return; }
free(ev);
}
int nx_reactor_add(nx_reactor *r, nx_event *ev, int fd, int events, nx_cb cb,
void *userdata)
{
if (r == NULL || ev == NULL || cb == NULL) { errno = EINVAL; return -1; }
if (ev->r != NULL) {
errno = EEXIST;
return -1;
}
ev->fd = fd;
ev->cb = cb;
ev->userdata = userdata;
ev->events = events;
ev->revents = 0;
ev->deleted = 0;
if (registry_add(r, ev) != 0) return -1;
if (nx_backend_add(r, ev) != 0) {
registry_remove(r, ev);
return -1;
}
ev->r = r;
return 0;
}
int nx_reactor_mod(nx_reactor *r, nx_event *ev, int events)
{
if (r == NULL || ev == NULL) { errno = EINVAL; return -1; }
if (ev->r != r) { errno = ENOENT; return -1; }
if (ev->events == events && !ev->deleted) return 0;
ev->events = events;
return nx_backend_mod(r, ev);
}
int nx_reactor_del(nx_reactor *r, nx_event *ev)
{
if (r == NULL || ev == NULL) { errno = EINVAL; return -1; }
if (ev->r != r) { errno = ENOENT; return -1; }
ev->deleted = 1;
if (ev->in_callback) return 0;
(void)nx_backend_del(r, ev);
registry_remove(r, ev);
ev->r = NULL;
return 0;
}
int registry_add(nx_reactor *r, nx_event *ev)
{
if (r->nevs == r->capevs) {
size_t ncap = r->capevs ? r->capevs * 2 : 16;
nx_event **ne = (nx_event **)realloc(r->evs, ncap * sizeof(*ne));
if (ne == NULL) { errno = ENOMEM; return -1; }
r->evs = ne;
r->capevs = ncap;
}
ev->index = r->nevs;
r->evs[r->nevs++] = ev;
r->nactive++;
return 0;
}
void registry_remove(nx_reactor *r, nx_event *ev)
{
size_t i, last;
if (ev->index == (size_t)-1) return;
i = ev->index;
last = r->nevs - 1;
if (i != last) {
r->evs[i] = r->evs[last];
r->evs[i]->index = i;
}
r->nevs--;
r->nactive--;
ev->index = (size_t)-1;
}
int nx_reactor_wakeup(nx_reactor *r)
{
if (r == NULL || r->evpipe_write < 0) { errno = EINVAL; return -1; }
for (;;) {
unsigned char byte = 1;
ssize_t n = write(r->evpipe_write, &byte, 1);
if (n == 1) return 0;
if (n < 0 && errno == EINTR) continue;
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return 0;
return -1;
}
}
void nx_reactor_on_wakeup(nx_reactor *r)
{
if (r->wakeup_cb != NULL) r->wakeup_cb(r, r->wakeup_ud);
}
int dispatch_ready(nx_reactor *r)
{
int dispatched = 0;
int i;
for (i = 0; i < r->ready_n; i++) {
nx_event *ev = r->ready[i];
if (ev->deleted) continue;
if (ev->revents == 0) continue;
ev->in_callback = 1;
ev->cb(ev, ev->revents);
ev->in_callback = 0;
dispatched++;
if (ev->deleted) {
(void)nx_backend_del(r, ev);
registry_remove(r, ev);
ev->r = NULL;
}
}
return dispatched;
}
int nx_reactor_wait(nx_reactor *r, int timeout_ms)
{
if (r == NULL) { errno = EINVAL; return -1; }
r->stopped = 0;
return nx_backend_wait(r, timeout_ms);
}
int nx_reactor_run(nx_reactor *r)
{
if (r == NULL) { errno = EINVAL; return -1; }
r->running = 1;
r->stopped = 0;
while (!r->stopped) {
if (nx_reactor_wait(r, -1) < 0) {
if (errno == EINTR) continue;
r->running = 0;
return -1;
}
}
r->running = 0;
return 0;
}
void nx_reactor_stop(nx_reactor *r)
{
if (r == NULL) return;
r->stopped = 1;
(void)nx_reactor_wakeup(r);
}
size_t nx_reactor_nactive(const nx_reactor *r)
{
return r ? r->nactive : 0;
}
int nx_event_fd(const nx_event *ev) { return ev ? ev->fd : -1; }
void *nx_event_userdata(const nx_event *ev) { return ev ? ev->userdata : NULL; }
nx_reactor *nx_event_reactor(const nx_event *ev) { return ev ? ev->r : NULL; }
int nx_event_interested(const nx_event *ev, int flag)
{
return ev ? (ev->events & flag) != 0 : 0;
}
+126
View File
@@ -0,0 +1,126 @@
#include "nx_internal.h"
#include "reactor_internal.h"
#include <errno.h>
#include <sys/epoll.h>
#include <unistd.h>
#ifndef EPOLLRDHUP
#define EPOLLRDHUP 0
#endif
static uint32_t to_epoll(int events)
{
uint32_t e = 0;
if (events & NX_READ) e |= (uint32_t)EPOLLIN;
if (events & NX_WRITE) e |= (uint32_t)EPOLLOUT;
return e;
}
static int from_epoll(uint32_t e)
{
int r = 0;
if (e & (uint32_t)EPOLLIN) r |= NX_READ;
if (e & (uint32_t)EPOLLOUT) r |= NX_WRITE;
if (e & (uint32_t)EPOLLERR) r |= NX_ERROR;
if (e & (uint32_t)EPOLLHUP) r |= NX_HUP;
if (e & (uint32_t)EPOLLRDHUP) {
r |= NX_READ | NX_HUP;
}
return r;
}
int nx_backend_init(nx_reactor *r)
{
struct epoll_event ee;
r->epfd = epoll_create1(EPOLL_CLOEXEC);
if (r->epfd < 0) return -1;
r->pipe_ev.fd = r->evpipe_read;
r->pipe_ev.events = NX_READ;
r->pipe_ev.r = r;
r->pipe_ev.cb = NULL;
r->pipe_ev.index = (size_t)-1;
memset(&ee, 0, sizeof(ee));
ee.events = (uint32_t)EPOLLIN;
ee.data.ptr = &r->pipe_ev;
if (epoll_ctl(r->epfd, EPOLL_CTL_ADD, r->evpipe_read, &ee) < 0) {
int saved = errno;
close(r->epfd);
errno = saved;
return -1;
}
return 0;
}
void nx_backend_destroy(nx_reactor *r)
{
if (r->epfd >= 0) { close(r->epfd); r->epfd = -1; }
}
int nx_backend_add(nx_reactor *r, nx_event *ev)
{
struct epoll_event ee;
memset(&ee, 0, sizeof(ee));
ee.events = to_epoll(ev->events);
ee.data.ptr = ev;
return epoll_ctl(r->epfd, EPOLL_CTL_ADD, ev->fd, &ee);
}
int nx_backend_mod(nx_reactor *r, nx_event *ev)
{
struct epoll_event ee;
memset(&ee, 0, sizeof(ee));
ee.events = to_epoll(ev->events);
ee.data.ptr = ev;
return epoll_ctl(r->epfd, EPOLL_CTL_MOD, ev->fd, &ee);
}
int nx_backend_del(nx_reactor *r, nx_event *ev)
{
if (epoll_ctl(r->epfd, EPOLL_CTL_DEL, ev->fd, NULL) < 0) {
if (errno == ENOENT || errno == EBADF) return 0;
return -1;
}
return 0;
}
int nx_backend_wait(nx_reactor *r, int timeout_ms)
{
struct epoll_event evs[NX_MAX_READY];
int n, i, dispatched = 0;
r->ready_n = 0;
n = epoll_wait(r->epfd, evs, NX_MAX_READY, timeout_ms);
if (n < 0) return -1;
for (i = 0; i < n; i++) {
nx_event *ev = (nx_event *)evs[i].data.ptr;
if (ev == &r->pipe_ev) {
unsigned char scratch[256];
for (;;) {
ssize_t got = read(ev->fd, scratch, sizeof(scratch));
if (got > 0) continue;
if (got < 0 && errno == EINTR) continue;
break;
}
nx_reactor_on_wakeup(r);
continue;
}
if (ev->cb == NULL) continue;
if (r->ready_n < NX_MAX_READY) {
ev->revents = from_epoll(evs[i].events);
r->ready[r->ready_n++] = ev;
}
}
dispatched = dispatch_ready(r);
return dispatched;
}
+80
View File
@@ -0,0 +1,80 @@
#ifndef NX_REACTOR_INTERNAL_H
#define NX_REACTOR_INTERNAL_H
#include "nx_internal.h"
#if defined(NX_BACKEND_EPOLL)
#include <sys/epoll.h>
#elif defined(NX_BACKEND_KQUEUE)
#include <sys/event.h>
#else
#include <poll.h>
#endif
struct nx_event {
int fd;
nx_cb cb;
void *userdata;
nx_reactor *r;
int events;
int revents;
int in_callback;
int deleted;
size_t index;
};
#define NX_MAX_READY 256
struct nx_reactor {
nx_event **evs;
size_t nevs;
size_t capevs;
size_t nactive;
int evpipe_read;
int evpipe_write;
int running;
int stopped;
nx_event pipe_ev;
void (*wakeup_cb)(nx_reactor *r, void *ud);
void *wakeup_ud;
nx_event *ready[NX_MAX_READY];
int ready_n;
struct nx_resolve_req *resolving;
int nresolving;
#if defined(NX_BACKEND_EPOLL)
int epfd;
#elif defined(NX_BACKEND_KQUEUE)
int kq;
struct kevent *kevs;
int nkevs;
#else
struct pollfd *pfds;
int npfds;
#endif
};
int registry_add(nx_reactor *r, nx_event *ev);
void registry_remove(nx_reactor *r, nx_event *ev);
int nx_backend_init(nx_reactor *r);
void nx_backend_destroy(nx_reactor *r);
int nx_backend_add(nx_reactor *r, nx_event *ev);
int nx_backend_mod(nx_reactor *r, nx_event *ev);
int nx_backend_del(nx_reactor *r, nx_event *ev);
int nx_backend_wait(nx_reactor *r, int timeout_ms);
int dispatch_ready(nx_reactor *r);
void nx_reactor_on_wakeup(nx_reactor *r);
#endif
+196
View File
@@ -0,0 +1,196 @@
#include "nx_internal.h"
#include "reactor_internal.h"
#include <errno.h>
#include <sys/event.h>
#include <sys/time.h>
#include <unistd.h>
typedef struct {
short filter;
int interest;
} kmap;
static int kmap_for(const nx_event *ev, int idx, kmap *out)
{
if (idx == 0) {
if (ev->events & NX_READ) {
out->filter = EVFILT_READ;
out->interest = NX_READ;
return 0;
}
} else if (idx == 1) {
if (ev->events & NX_WRITE) {
out->filter = EVFILT_WRITE;
out->interest = NX_WRITE;
return 0;
}
}
return -1;
}
static int nfilters(const nx_event *ev)
{
return ((ev->events & NX_READ) ? 1 : 0) + ((ev->events & NX_WRITE) ? 1 : 0);
}
static int from_kevent(const struct kevent *kev)
{
int r = 0;
if (kev->filter == EVFILT_READ) r |= NX_READ;
if (kev->filter == EVFILT_WRITE) r |= NX_WRITE;
if (kev->flags & EV_ERROR) r |= NX_ERROR;
if (kev->flags & EV_EOF) r |= NX_HUP;
return r;
}
int nx_backend_init(nx_reactor *r)
{
struct kevent kev;
r->kq = kqueue();
if (r->kq < 0) return -1;
r->nkevs = NX_MAX_READY;
r->kevs = (struct kevent *)calloc((size_t)r->nkevs, sizeof(*r->kevs));
if (r->kevs == NULL) {
int saved = errno;
close(r->kq);
r->kq = -1;
errno = saved;
return -1;
}
r->pipe_ev.fd = r->evpipe_read;
r->pipe_ev.events = NX_READ;
r->pipe_ev.r = r;
r->pipe_ev.cb = NULL;
r->pipe_ev.index = (size_t)-1;
EV_SET(&kev, (uintptr_t)r->evpipe_read, EVFILT_READ, EV_ADD | EV_CLOEXEC,
0, 0, &r->pipe_ev);
if (kevent(r->kq, &kev, 1, NULL, 0, NULL) < 0) {
int saved = errno;
free(r->kevs);
r->kevs = NULL;
close(r->kq);
r->kq = -1;
errno = saved;
return -1;
}
return 0;
}
void nx_backend_destroy(nx_reactor *r)
{
free(r->kevs);
r->kevs = NULL;
r->nkevs = 0;
if (r->kq >= 0) { close(r->kq); r->kq = -1; }
}
static int submit(nx_reactor *r, nx_event *ev, short action_extra)
{
struct kevent ks[2];
int n = nfilters(ev), i, nw = 0;
for (i = 0; i < n; i++) {
kmap m;
if (kmap_for(ev, i, &m) != 0) continue;
EV_SET(&ks[nw], (uintptr_t)ev->fd, m.filter,
(uint16_t)(EV_ADD | EV_CLEAR | EV_CLOEXEC | action_extra),
0, 0, ev);
nw++;
}
if (nw == 0) { errno = EINVAL; return -1; }
if (kevent(r->kq, ks, nw, NULL, 0, NULL) < 0) return -1;
return 0;
}
int nx_backend_add(nx_reactor *r, nx_event *ev)
{
return submit(r, ev, 0);
}
int nx_backend_mod(nx_reactor *r, nx_event *ev)
{
static const short both[2] = { EVFILT_READ, EVFILT_WRITE };
int i;
for (i = 0; i < 2; i++) {
struct kevent ks;
EV_SET(&ks, (uintptr_t)ev->fd, both[i], EV_DELETE, 0, 0, NULL);
if (kevent(r->kq, &ks, 1, NULL, 0, NULL) < 0) {
if (errno != ENOENT && errno != EBADF) return -1;
}
}
return submit(r, ev, 0);
}
int nx_backend_del(nx_reactor *r, nx_event *ev)
{
static const short both[2] = { EVFILT_READ, EVFILT_WRITE };
int i;
for (i = 0; i < 2; i++) {
struct kevent ks;
EV_SET(&ks, (uintptr_t)ev->fd, both[i], EV_DELETE, 0, 0, NULL);
if (kevent(r->kq, &ks, 1, NULL, 0, NULL) < 0) {
if (errno == ENOENT || errno == EBADF) continue;
return -1;
}
}
return 0;
}
int nx_backend_wait(nx_reactor *r, int timeout_ms)
{
struct timespec ts, *tsp = NULL;
int n, i;
r->ready_n = 0;
if (timeout_ms >= 0) {
ts.tv_sec = timeout_ms / 1000;
ts.tv_nsec = (long)(timeout_ms % 1000) * 1000000L;
tsp = &ts;
}
n = kevent(r->kq, NULL, 0, r->kevs, r->nkevs, tsp);
if (n < 0) return -1;
for (i = 0; i < n; i++) {
nx_event *ev = (nx_event *)r->kevs[i].udata;
if (ev == &r->pipe_ev) {
unsigned char scratch[256];
for (;;) {
ssize_t got = read(ev->fd, scratch, sizeof(scratch));
if (got > 0) continue;
if (got < 0 && errno == EINTR) continue;
break;
}
nx_reactor_on_wakeup(r);
continue;
}
if (ev == NULL) continue;
{
int bits = from_kevent(&r->kevs[i]);
int j, staged = 0;
for (j = 0; j < r->ready_n; j++) {
if (r->ready[j] == ev) { staged = 1; break; }
}
if (staged) {
ev->revents |= bits;
} else if (r->ready_n < NX_MAX_READY) {
ev->revents = bits;
r->ready[r->ready_n++] = ev;
}
}
}
return dispatch_ready(r);
}
+140
View File
@@ -0,0 +1,140 @@
#include "nx_internal.h"
#include "reactor_internal.h"
#include <errno.h>
#include <poll.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int nx_backend_init(nx_reactor *r)
{
r->pfds = NULL;
r->npfds = 0;
r->pipe_ev.fd = r->evpipe_read;
r->pipe_ev.events = NX_READ;
r->pipe_ev.r = r;
r->pipe_ev.cb = NULL;
r->pipe_ev.index = (size_t)-1;
return 0;
}
void nx_backend_destroy(nx_reactor *r)
{
free(r->pfds);
r->pfds = NULL;
r->npfds = 0;
}
static int ensure(nx_reactor *r, size_t nevs)
{
size_t need = nevs + 1;
struct pollfd *np;
if (need <= (size_t)r->npfds) return 0;
np = (struct pollfd *)realloc(r->pfds, need * sizeof(*np));
if (np == NULL) { errno = ENOMEM; return -1; }
r->pfds = np;
r->npfds = (int)need;
return 0;
}
static int rebuild(nx_reactor *r)
{
size_t i;
if (ensure(r, r->nevs) != 0) return -1;
for (i = 0; i < r->nevs; i++) {
nx_event *ev = r->evs[i];
short events = 0;
if (ev->events & NX_READ) events |= POLLIN;
if (ev->events & NX_WRITE) events |= POLLOUT;
r->pfds[i].fd = ev->fd;
r->pfds[i].events = events;
r->pfds[i].revents = 0;
}
r->pfds[r->nevs].fd = r->evpipe_read;
r->pfds[r->nevs].events = POLLIN;
r->pfds[r->nevs].revents = 0;
return 0;
}
int nx_backend_add(nx_reactor *r, nx_event *ev)
{
(void)r; (void)ev;
return 0;
}
int nx_backend_mod(nx_reactor *r, nx_event *ev)
{
(void)r; (void)ev;
return 0;
}
int nx_backend_del(nx_reactor *r, nx_event *ev)
{
(void)r; (void)ev;
return 0;
}
static short to_poll(int events)
{
short p = 0;
if (events & NX_READ) p |= POLLIN;
if (events & NX_WRITE) p |= POLLOUT;
return p;
}
static int from_poll(short revents)
{
int r = 0;
if (revents & POLLIN) r |= NX_READ;
if (revents & POLLOUT) r |= NX_WRITE;
if (revents & POLLERR) r |= NX_ERROR;
if (revents & POLLHUP) r |= NX_HUP;
if (revents & POLLNVAL) r |= NX_ERROR;
return r;
}
int nx_backend_wait(nx_reactor *r, int timeout_ms)
{
int n;
size_t i;
r->ready_n = 0;
if (r->nevs == 0 && r->stopped) return 0;
if (rebuild(r) != 0) return -1;
n = poll(r->pfds, (nfds_t)r->nevs + 1, timeout_ms);
if (n < 0) return -1;
for (i = 0; i < r->nevs; i++) {
nx_event *ev = r->evs[i];
short revents = r->pfds[i].revents;
if (revents == 0) continue;
if (r->ready_n < NX_MAX_READY) {
ev->revents = from_poll(revents);
r->ready[r->ready_n++] = ev;
}
}
if (r->pfds[r->nevs].revents & POLLIN) {
unsigned char scratch[256];
for (;;) {
ssize_t got = read(r->evpipe_read, scratch, sizeof(scratch));
if (got > 0) continue;
if (got < 0 && errno == EINTR) continue;
break;
}
nx_reactor_on_wakeup(r);
}
return dispatch_ready(r);
}