Ubus IPC

The ubus module provides functions for OpenWrt inter-process communication, including access to ubus registered modules and their methods, as well as monitoring and publish/subscribe activity on the ubus message bus.

Functions can be individually imported using named import syntax:

import { connect } from 'ubus';

const ubus = connect();
const result = ubus.call("session", "get", { key: "value" });

Alternatively, the module namespace can be imported using a wildcard import:

import * as ubus from 'ubus';

const ctx = ubus.connect();

The ubus module may also be loaded via the -lubus interpreter switch.

Architecture

Ubus uses a broker pattern architecture with three main components:

  • ubusd: The central message router/broker that manages registrations and forwards messages between objects
  • Server objects: Interfaces/daemons that register methods for clients to call
  • Client objects: Callers that invoke server object methods

All connections go through ubusd, significantly reducing the number of IPC connections compared to traditional client-server models.

Communication Schemes

Ubus provides three delivery schemes for IPC:

  1. Invoke (one-to-one): Direct method calls to a specific object by ID
  2. Subscribe/Notify (one-to-many, group by object): Notifications sent to all subscribers of a particular object
  3. Event Broadcast (one-to-many, group by event): Events broadcast to all listeners registered for a matching event pattern

Roles in Ubus

  • Object: Process registered to ubusd, including services and service callers
  • Method: Procedures provided by objects; servers can provide multiple methods
  • Data: Information in JSON format carried by requests or replies
  • Subscriber: Object subscribed to a target service; notified when the target sends notifications
  • Event: Identified by a string event pattern; objects can register to events and send data with matching patterns
  • Event Registrant: Object registered to an event pattern; receives forwarded data when matching messages are received

Data Format

All data is transferred in JSON format via blobmsg. Method calls, requests, and replies all use JSON for data serialization.

Usage Examples

Basic connection and method call

const ubus = require("ubus");

// Connect to ubus and call a method
const conn = ubus.connect();
if (conn) {
    const result = conn.call("network.interface", "status", {});
    printf("Interface status: %.J\n", result);
    conn.disconnect();
}

Asynchronous method invocation with callback

const ubus = require("ubus");

// Typical pattern: async call with callback
const conn = ubus.connect();

conn.defer("some.object", "some_method", {}, (rc, result) => {
    if (rc == 0) {
        printf("Result: %.J\n", result);
    }
});

Persistent connection pattern

const ubus = require("ubus");

// Keep connection alive to prevent GC
const ubus_conn = ubus.connect();

function handle_request(request) {
    ubus_conn.defer("some.object", "some_method", {}, (rc, data) => {
        request.reply({ result: data });
    });
}

Publishing an object

const ubus = require("ubus");

const conn = ubus.connect();
const obj = conn.publish("my.service", {
    "hello": (req, msg) => {
        req.reply({ message: "Hello from " + msg.name });
    }
});

Event broadcasting

const ubus = require("ubus");

const conn = ubus.connect();

// Register as event listener
const listener = conn.listener("my.event.*", (pattern, data) => {
    printf("Received event: %s %.J\n", pattern, data);
});

// Send an event
conn.event("my.event.test", { data: "test payload" });

Classes

ubus.channel

Represents a channel connection to the ubus bus.

Channels provide bidirectional communication between two ubus objects through file descriptors. They are created via open_channel() or from an incoming request via new_channel().

Channels are useful for:

  • Establishing dedicated communication paths between specific objects
  • Streaming data or multiple requests over a single connection
  • File descriptor passing between processes

ubus.connection

Represents a connection to the ubus bus.

A connection is established via connect() and serves as the primary interface for all ubus operations. Through a connection, you can:

  • Discover and invoke methods on remote objects (list(), call())
  • Publish your own objects to the bus (publish())
  • Subscribe to notifications from other objects (subscriber())
  • Register event listeners for pattern-based events (listener())
  • Send broadcast events to other listeners (event())

The connection uses the broker pattern, routing all communication through ubusd. It supports both synchronous (call) and asynchronous (defer) method invocations.

ubus.deferred

Represents a deferred ubus request.

A deferred request is created when invoking a method asynchronously using defer() or defer(). Instead of blocking and waiting for the result, the operation returns immediately with a deferred object that can be used to:

  • Check if the request has completed (completed())
  • Wait synchronously for completion (await())
  • Abort the pending request if no longer needed (abort())

This pattern is useful for:

  • Non-blocking operations in event-driven applications
  • Timeout handling and request cancellation
  • Concurrent execution of multiple ubus method calls

ubus.listener

Represents an event listener for pattern-based events.

A listener is registered via listener() to receive events matching a specific pattern. Listeners are part of the event broadcast communication scheme, where events are sent to all registered listeners with matching event patterns.

Event patterns support wildcards (e.g., `system.*`, `network.interface.*`) allowing flexible event routing and subscription.

ubus.notify

Represents an asynchronous notification request.

A notify object is created when sending a notification to subscribers via notify(). It allows tracking the delivery status of the notification and provides the ability to abort if needed.

Notifications are delivered to all subscribers of an object in the subscribe/notify communication scheme. The notify object provides non-blocking status checking and cancellation capabilities.

ubus.object

Represents a ubus object published on the bus.

A published object is a service registered with ubusd that provides methods for other processes to call. Objects are created via publish() and can:

  • Expose multiple methods for remote invocation
  • Receive notifications from subscribers (subscribed(), notify())
  • Be removed from the bus when no longer needed (remove())

Objects are identified by their path (e.g., system, network.interface) and can be discovered by other processes using list().

ubus.request

Represents a deferred ubus method call context.

A request object is created when a published object method is invoked asynchronously. It provides the server-side interface for handling incoming method calls and sending responses.

The request context allows the method handler to:

This is used internally by the ubus module when a published object's method is called by a client.

ubus.subscriber

Represents a subscriber to an object's notifications.

A subscriber is registered via subscriber() to receive notifications from a specific object. Subscribers are part of the subscribe/notify communication scheme, where the target object can send notifications that are delivered to all registered subscribers.

When a subscriber is registered, the target object receives a notification about the new subscription. Similarly, when a subscriber is removed, the target object is notified of the unsubscription.

Methods

connect(socketopt, timeoutopt) → {connection}nullable

Establish a connection to the ubus bus.

Connects to the specified ubus socket path or the default socket if none is provided.

Returns a connection resource on success.

Returns null if the connection could not be established.

Parameters:
NameTypeDescription
socketstring(optional)

The path to the ubus socket to connect to. If omitted, the default socket path is used.

timeoutnumber(optional, default: 30)

The timeout in seconds to use for subsequent ubus operations.

Returns: connection

error(numericopt) → {string|number}

Query ubus error information.

Returns a string containing a description of the last ubus error when the numeric argument is absent or false.

Returns a ubus status code number when the numeric argument is true.

Returns null if there is no error information.

Parameters:
NameTypeDescription
numericboolean(optional)

Whether to return a numeric status code (true) or a human readable error message (false).

Returns: string | number

guard(handleropt) → {function|boolean}

Get or set the ubus exception handler.

When called without arguments, returns the currently registered exception handler function. When called with a function argument, registers it as the exception handler for ubus operations.

Returns the current exception handler when called without arguments.

Returns true when a new handler was set.

Parameters:
NameTypeDescription
handlerfunction(optional)

The exception handler function to register.

Returns: function | boolean

open_channel(fd, cb, disconnect_cbopt, timeoutopt) → {channel}nullable

Connect to a ubus channel from a file descriptor.

Creates a channel connection from an existing file descriptor, typically received from a method call. The callback will be invoked for incoming messages on the channel.

Returns a channel connection resource.

Returns null if the channel could not be created.

Parameters:
NameTypeDescription
fdnumber

The file descriptor of the channel to connect to.

cbfunction

Callback invoked for incoming messages on the channel.

disconnect_cbfunction(optional)

Optional callback invoked when the channel is disconnected.

timeoutnumber(optional, default: 30)

The timeout in seconds for subsequent operations.

Returns: channel

Type Definitions

Ubus status codes

Properties
NameTypeDescription
STATUS_OKnumber

Operation successful

STATUS_INVALID_COMMANDnumber

Invalid command

STATUS_INVALID_ARGUMENTnumber

Invalid argument

STATUS_METHOD_NOT_FOUNDnumber

Method not found

STATUS_NOT_FOUNDnumber

Object not found

STATUS_NO_DATAnumber

No data available

STATUS_PERMISSION_DENIEDnumber

Permission denied

STATUS_TIMEOUTnumber

Operation timed out

STATUS_NOT_SUPPORTEDnumber

Operation not supported

STATUS_UNKNOWN_ERRORnumber

Unknown error

STATUS_CONNECTION_FAILEDnumber

Connection failed

STATUS_NO_MEMORYnumber

Out of memory (new)

STATUS_PARSE_ERRORnumber

Parse error (new)

STATUS_SYSTEM_ERRORnumber

System error (new)

STATUS_CONTINUEnumber

Virtual code for continued replies

Ubus system object IDs

Properties
NameTypeDescription
SYSTEM_OBJECT_ACLnumber

System object ACL identifier, used to query ACL data via call() with an integer object ID