OpenWrt ubus C API (3): a minimal server and client
Grow through practice
No need to finish reading — test now
ubus callis convenient, but real integration is in C. This article closes the loop from one object and one method toubus_add_objectandubus_invoke.
The loop
server: ubus_connect → ubus_add_uloop → ubus_add_object → uloop_run
client: ubus_connect → ubus_lookup_id → ubus_invoke → callback
object: name + methods[] + policy
payload: blob_buf / blobmsg
Keep three things separate:
- Connection:
ubus_connect(socket)connects toubusd. - Object: the server registers an object and its methods on the bus.
- Call: the client looks up the object id, then sends a blobmsg to a method.
Minimal server
This registers a demo object. hello takes {"name":"openwrt"} and replies with {"message":"hello, openwrt"}.
#include <stdio.h>
#include <string.h>
#include <libubox/blobmsg.h>
#include <libubox/blobmsg_json.h>
#include <libubus.h>
static struct ubus_context *ctx;
static struct blob_buf b;
enum { DEMO_NAME, __DEMO_MAX };
static const struct blobmsg_policy demo_policy[__DEMO_MAX] = {
[DEMO_NAME] = { .name = "name", .type = BLOBMSG_TYPE_STRING },
};
static int demo_hello(struct ubus_context *ctx, struct ubus_object *obj,
struct ubus_request_data *req, const char *method,
struct blob_attr *msg)
{
struct blob_attr *tb[__DEMO_MAX];
const char *name = "world";
char reply[128];
blobmsg_parse(demo_policy, __DEMO_MAX, tb, blob_data(msg), blob_len(msg));
if (tb[DEMO_NAME])
name = blobmsg_get_string(tb[DEMO_NAME]);
snprintf(reply, sizeof(reply), "hello, %s", name);
blob_buf_init(&b, 0);
blobmsg_add_string(&b, "message", reply);
ubus_send_reply(ctx, req, b.head);
return 0;
}
static const struct ubus_method demo_methods[] = {
UBUS_METHOD("hello", demo_hello, demo_policy),
};
static struct ubus_object_type demo_type = UBUS_OBJECT_TYPE("demo", demo_methods);
static struct ubus_object demo_obj = {
.name = "demo",
.type = &demo_type,
.methods = demo_methods,
.n_methods = ARRAY_SIZE(demo_methods),
};
int main(int argc, char **argv)
{
ctx = ubus_connect(argc > 1 ? argv[1] : NULL);
if (!ctx) {
fprintf(stderr, "connect failed\n");
return 1;
}
ubus_add_uloop(ctx);
if (ubus_add_object(ctx, &demo_obj)) {
fprintf(stderr, "add object failed\n");
ubus_free(ctx);
return 1;
}
uloop_run();
ubus_free(ctx);
uloop_done();
return 0;
}
Key points:
ubus_connect(NULL)uses the default socket; a path is useful for an isolatedubusdon a PC.ubus_add_uloop(ctx)attaches the ubus fd to uloop; without it the server will not receive requests.- A failed
ubus_add_objectis usually ACL/permission, not bad C. - Return
0from the handler on success, otherwise aUBUS_STATUS_*value, not errno. blobmsg_parseonly finds fields declared by policy; missing fields need your own defaults.
Minimal client
#include <stdio.h>
#include <stdlib.h>
#include <libubox/blobmsg.h>
#include <libubox/blobmsg_json.h>
#include <libubus.h>
static void reply_cb(struct ubus_request *req, int type, struct blob_attr *msg)
{
char *s = blobmsg_format_json(msg, true);
if (s) {
puts(s);
free(s);
}
}
int main(int argc, char **argv)
{
struct ubus_context *ctx = ubus_connect(argc > 1 ? argv[1] : NULL);
uint32_t id;
struct blob_buf b = {0};
if (!ctx) return 1;
if (ubus_lookup_id(ctx, "demo", &id)) return 2;
blob_buf_init(&b, 0);
blobmsg_add_string(&b, "name", argc > 2 ? argv[2] : "openwrt");
int ret = ubus_invoke(ctx, id, "hello", b.head, reply_cb, NULL, 1000);
blob_buf_free(&b);
ubus_free(ctx);
return ret;
}
The last argument to ubus_invoke is a timeout in milliseconds. It returns UBUS_STATUS_*, not an HTTP status. For long-running work, use ubus_invoke_async with ubus_complete_deferred_request; the official examples/client.c hello demonstrates async plus fd passing.
Compile and run
With pkg-config:
cc demo-server.c -o demo-server $(pkg-config --cflags --libs libubus libubox libblobmsg-json)
cc demo-client.c -o demo-client $(pkg-config --cflags --libs libubus libubox libblobmsg-json)
Without it, pass headers and libraries explicitly (adjust for your SDK):
cc demo-server.c -o demo-server \
-I/usr/local/include -L/usr/local/lib \
-lubus -lubox -lblobmsg_json
In an OpenWrt package, depend on +libubus +libubox +libblobmsg-json and cross-compile with the SDK's $(TARGET_CC).
Run against an isolated socket:
sudo ubusd -s /tmp/ubus.sock
sudo ./demo-server /tmp/ubus.sock
sudo ubus -s /tmp/ubus.sock list -v
./demo-client /tmp/ubus.sock openwrt
Measured output:
'demo' @3227dc21
"hello":{"name":"String"}
{"message":"hello, openwrt"}
@3227dc21 is the object id and changes on every start. name: String in list -v comes from the policy, not from guessing the code.
ACL: the usual “code is fine but it will not run”
A non-root process cannot register arbitrary objects. A typical failure:
Failed to add object: Invalid argument
Verify as root first to separate code from permissions, then configure ACL. Do not run production services as root forever; OpenWrt ubus ACLs restrict objects and methods per user/group and must allow both ubus_add_object and the target methods.
Boundaries
- ubus is transient RPC; it does not persist objects or provide transactions.
- Policy checks name and type, not ranges, defaults or cross-field rules.
- Use
blobmsg_open_table/blobmsg_open_arrayfor nested data instead of nesting JSON strings. - For configuration/state models, use UCI or AMX/TR-181; ubus is not a database.
Verification
- ✅ Source:
openwrt/ubus414c60a,libubus.h,examples/server.c,examples/client.c. - ✅ Local build: the server/client above compile with
cc -Wall -Wextra. - ✅ Local run: isolated
ubusd+/tmp/ubus.sock;ubus list -vand thedemo-clientinvoke returned the expected output. - ⚠️ Not cross-compiled on a physical OpenWrt device; ACL behavior varies by firmware and group.
- ❓ Not covered: complete async fd-passing code, concurrency, timeout and reconnect paths.
One sentence
The server is “object + policy + uloop”; the client is “lookup + invoke + callback”. Get that loop working before async and ACL.
Source: openwrt/ubus (
414c60a) Series: OpenWrt ubus Official Examples · Previous: ubus CLI in practice · Next: sockets with ustream · Data model: blob, blobmsg and policy
Comments 0
No comments yet — be the first!