OpenWrt ubus without blocking (4): use ustream for sockets, not a hand-written write state machine
Grow through practice
No need to finish reading — test nowThe point is not to turn every socket write into a state-machine step.
ustreamalready handles nonblocking I/O, edge-triggered reads, read buffering and write buffering. You only handle message boundaries.
The official example: take over the fd in a callback
In openwrt/ubus examples/client.c, the server passes the read end of a pipe over ubus. The client does not call read() directly; it hands the fd to ustream_fd:
static void test_client_fd_cb(struct ubus_request *req, int fd)
{
static struct ustream_fd test_fd;
test_fd.stream.notify_read = test_client_fd_data_cb;
ustream_fd_init(&test_fd, fd);
}
The read callback does not do epoll/select either:
static void test_client_fd_data_cb(struct ustream *s, int bytes)
{
char *data, *sep;
int len;
data = ustream_get_read_buf(s, &len);
if (len < 1)
return;
sep = strchr(data, '\n');
if (!sep)
return;
*sep = 0;
fprintf(stderr, "Got line: %s\n", data);
ustream_consume(s, sep + 1 - data);
}
This is the core of the official USTREAM pattern:
ustream_fd_initregisters the fd with uloop.uloop_fd_addsets the fd toO_NONBLOCK.notify_readruns when data arrives.ustream_get_read_bufgives a contiguous buffer;ustream_consumeremoves consumed bytes.- A partial message stays buffered and is completed by the next callback.
The official example uses a static struct ustream_fd because the stream must outlive the callback. Production code should allocate one struct conn per connection; never reuse one ustream_fd for multiple fds.
What ustream does for you
ustream_fd is “fd + read buffer + write buffer + uloop”:
- Nonblocking: the fd is set nonblocking when registered.
- Edge-triggered: it reads until
EAGAIN, not just one chunk per event. - Partial reads: unconsumed bytes stay in the read buffer.
- Partial writes:
ustream_writetries the socket first and buffers the remainder;ULOOP_WRITEflushes it later. - EOF/errors:
notify_statereportseoforwrite_error. - Backpressure:
ustream_set_read_blockedpauses reading.
So you can write a whole response at once:
ustream_printf(&c->s.stream,
"HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s",
(int)strlen(body), body);
You do not need a three-phase “write header, write body, handle EAGAIN” state machine. ustream_write accepts the whole buffer and handles partial writes internally.
Complete TCP echo example
This listens on 127.0.0.1:9000 and echoes lines. Accept, read and write all run on uloop, with no blocking calls:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <libubox/ustream.h>
struct conn {
struct ustream_fd s;
};
static void conn_state(struct ustream *s)
{
struct conn *c = container_of(s, struct conn, s.stream);
if (s->write_error || (s->eof && ustream_pending_data(s, true) == 0)) {
ustream_free(s);
free(c);
}
}
static void conn_read(struct ustream *s, int bytes)
{
int len;
char *data;
(void)bytes;
while ((data = ustream_get_read_buf(s, &len)) != NULL) {
char *nl = memchr(data, '\n', len);
if (!nl)
break;
int n = nl - data + 1;
ustream_write(s, data, n, false);
ustream_consume(s, n);
}
}
static void on_accept(struct uloop_fd *u, unsigned int events)
{
int fd;
struct conn *c;
(void)events;
fd = accept4(u->fd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (fd < 0)
return;
c = calloc(1, sizeof(*c));
if (!c) {
close(fd);
return;
}
c->s.stream.notify_read = conn_read;
c->s.stream.notify_state = conn_state;
ustream_fd_init(&c->s, fd);
}
int main(void)
{
int fd;
int one = 1;
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(9000),
.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
};
static struct uloop_fd listener;
signal(SIGPIPE, SIG_IGN);
fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd < 0)
return 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
return 1;
if (listen(fd, 16) < 0)
return 1;
listener.fd = fd;
listener.cb = on_accept;
uloop_init();
uloop_fd_add(&listener, ULOOP_READ);
uloop_run();
uloop_done();
close(fd);
return 0;
}
Build (only libubox is needed):
cc -Wall -Wextra ustream-echo.c -o ustream-echo -lubox
Test:
./ustream-echo &
printf 'hello\nworld\n' | nc 127.0.0.1 9000
Measured output:
hello
world
There is no:
- blocking
while (recv(...))polling; - one thread per connection;
- hand-written state machine for every
write; sleep()waiting for the client.
Only accept4, ustream_fd_init and two callbacks.
Why this is not “split every write into a step”
Separate two layers:
- Transport:
ustreamhandles “only half was written”, “the kernel buffer is full”, “the peer is slow”. It uses the write buffer andULOOP_WRITE; you do not split each write.
- Protocol: your protocol still defines message boundaries. The example uses
\n; a binary protocol can use a fixed header plus body, or a length prefix.ustreamdoes not know where your message ends.
The correct statement is:
Do not write a state machine for every socket
write; do write one for protocol parsing.
Backpressure: nonblocking is not enough
If the peer reads slowly, ustream_write keeps buffering and memory grows. Use high and low watermarks:
#define HIGH_WATER (64 * 1024)
#define LOW_WATER (16 * 1024)
static void conn_read(struct ustream *s, int bytes)
{
/* ... parse and ustream_write ... */
if (ustream_pending_data(s, true) > HIGH_WATER)
ustream_set_read_blocked(s, true);
}
static void conn_write(struct ustream *s, int bytes)
{
(void)bytes;
if (ustream_pending_data(s, true) < LOW_WATER)
ustream_set_read_blocked(s, false);
}
Attach conn_write to notify_write. Pausing reads lets the TCP window push back on the sender instead of exhausting memory.
How this relates to ubus
- ubus, uloop and ustream are a single-threaded event loop; never call
ustream_writeorubus_send_replyfrom a worker thread. - A ubus handler should only enqueue with
ustream_writeand return; do not wait for the socket. - To pass an fd to another process, use
ubus_request_set_fd/ubus_request_get_caller_fd, thenustream_fd_init. - Slow work (files, databases, external commands) still belongs in a worker or
uloop_process, signalling the loop through eventfd/pipe. - Run exactly one
uloop_run()per process.
Boundaries
ustreamis for stream fds such as sockets and pipes. A regular file is not a stream; diskwrite()may still block. Do not write large files in the event loop.ustream_writereturns the number of bytes accepted/written, which may be less than the input; the rest is buffered.- On close, call
ustream_freefromnotify_stateand free yourconn. - A static
ustream_fdis fine for a single-connection demo; allocate one per connection in production.
Verification
- ✅ Source:
openwrt/ubus414c60aexamples/client.c, plus libuboxustream.c/ustream-fd.c. - ✅ Local build: the TCP echo server compiles with
cc -Wall -Wextra. - ✅ Local run: listens on
127.0.0.1:9000;ncsends two lines and receives two lines. - ⚠️ Not verified on a physical OpenWrt device;
accept4/SOCK_CLOEXECrequire Linux. - ❓ Not covered: TLS, high-volume bidirectional traffic, backpressure limits, connection limits.
One sentence
ustream turns a nonblocking socket into “data callback, write-complete notification, automatically buffered partial reads/writes”; handle message boundaries, not a state machine for every write.
Source: openwrt/ubus examples/client.c · libubox ustream-fd.c Series: OpenWrt ubus Official Examples · Previous: a minimal C API server/client
Comments 0
No comments yet — be the first!