ubusio

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ubusio

CI Go Reference Version Go Version

A pure-Go client and server library for ubus, the OpenWrt micro bus.

ubusio speaks the ubus wire protocol directly over the ubusd unix socket. It uses only the Go standard library: no cgo, no libubus, no spawning of the ubus command line tool. Binaries are static and cross-compile to any router architecture Go supports (arm, arm64, mips, mipsle, 386, amd64, ...).

Status

Pre-1.0. The API may still change before v1.0.0. All features below are implemented and covered by unit tests against an in-process stand-in for ubusd. These unit tests, and the compatibility and stress tests of the same library code against private instances of ubusd with the ubus CLI and libubus, pass on two physical routers: arm64 with OpenWrt 25.12.5 and ARMv7 with OpenWrt 21.02.2. Virtual machine and emulation runs are listed separately under Compatibility. amd64 and mips hardware has not been used.

Area State
blobmsg encoding/decoding implemented, unit + fuzz tested
Connection, lookup, object listing (incl. prefix* wildcards), calls implemented
Exporting objects and method handlers implemented
Events: listen (patterns), send implemented
Subscriptions and notifications (both sides) implemented
File descriptor passing (SCM_RIGHTS) implemented; verified against the real ubusd of 25.12.5 (arm64) and 21.02 (ARMv7, arm64)
Traffic monitor (ubus monitor, root only) implemented; verified against the real ubusd of 25.12.5 (arm64) and 21.02 (ARMv7, arm64)
Reconnect with restoration of objects, listeners and subscriptions implemented
Compatibility test bench against real ubusd/libubus compat/

Usage

go get github.com/ddffcczz/ubusio
conn, err := ubusio.Dial(ctx)                    // /var/run/ubus/ubus.sock
info, err := conn.Call(ctx, "system", "board", nil)
model, _ := info.String("model")

var sysinfo struct {
	Uptime int64 `blobmsg:"uptime"`
	Memory struct {
		Free int64 `blobmsg:"free"`
	} `blobmsg:"memory"`
}
err = conn.CallInto(ctx, "system", "info", nil, &sysinfo)

objs, err := conn.Objects(ctx, "network.interface.*")

obj, err := conn.AddObject(ctx, "demo", []ubusio.Method{{
	Name: "hello",
	Args: []ubusio.ArgSignature{{Name: "name", Type: blobmsg.TypeString}},
	Handler: func(ctx context.Context, req *ubusio.Request) error {
		name, _ := req.Args.String("name")
		return req.Reply(map[string]any{"message": "hello " + name})
	},
}})

l, err := conn.Listen(ctx, func(ev ubusio.Event) { /* ... */ }, "network.*")
err = conn.Send(ctx, "demo.started", map[string]any{"pid": 1})

// Like `ubus monitor`: every message ubusd receives or sends (root only).
mon, err := conn.Monitor(ctx, func(ev ubusio.MonitorEvent) {
	fmt.Println(ev.Client, ev.Type, ev.ToClient, ev.Path, ev.Method, ev.Data)
}, ubusio.MonitorTypes(ubusio.MessageInvoke), ubusio.MonitorExcludeSelf())
defer mon.Close()

// A descriptor goes with the call; the method may return one too.
_, replyFD, err := conn.CallFD(ctx, "demo", "upload", nil, os.Stdin)

sub, err := conn.NewSubscriber(ctx, func(ctx context.Context, n *ubusio.Request) error {
	return nil
})
err = sub.Watch(ctx, "hostapd.wlan0")
err = obj.Notify(ctx, "changed", map[string]any{"value": 42})

More in example_test.go and the package documentation.

Behaviour worth knowing
  • Values. Decoding is lossless: a blobmsg.Table keeps field order, the exact wire type of each value (int8/int16/int32/int64, float64, string, nested Table/Array) and duplicate names. Higher-level views are strict: Table.Map() and blobmsg.Decode (into structs with blobmsg:"name" tags) reject duplicate names unless last-wins is requested, never use Go int, and fail on integer overflow. On encoding, Go int is sent as INT32 when it fits, else INT64; bool as INT8.
  • Calls. Call returns the single data reply and fails with ErrMultipleReplies if a method sends more than one; CallMany returns all, CallEach streams them, CallInto decodes into a struct. A path ending in * must match exactly one object (ErrMultipleObjects otherwise); Objects lists matches. Operations without a context deadline get a default timeout (30 s) for the operation as a whole, the wait for a new connection included, and every socket write is bounded by a write timeout (10 s) so a stuck ubusd cannot block goroutines.
  • Errors are *ubusio.Error wrapping a Status or one of the Err* values; use errors.Is(err, ubusio.StatusNotFound). They never contain call data.
  • Size limit. Messages over 1 MiB are refused before sending (ErrMessageTooLarge): ubusd would drop the whole connection.
  • Memory. Everything a connection has received but not yet consumed (replies, queued events, notifications and method calls) shares one budget, 4 MiB by default (WithMemoryBudget). Beyond it requests fail with ErrMemoryBudget, events, notifications and monitor reports are dropped and method calls get the overload status, all counted in Conn.Stats. CallMany, NotifyWait and the listings of Objects and wildcard Lookup accumulate at most 1024 replies / 4 MiB (WithReplyLimits, ErrTooManyReplies; Objects returns what it got); CallEach streams without accumulating. A cancelled context ends a request at once, even with replies buffered.
  • Handlers run on a bounded worker pool (default 4 workers, queue 64). When it is full, calls are answered with StatusNoMemory (configurable). Event listeners and subscribers receive their messages one at a time, in order; when they fall behind, excess messages are dropped and counted (Listener.Dropped, Subscriber.Dropped, Monitor.Dropped, Conn.Stats).
  • Events and notifications are best-effort. ubusd silently drops messages for a client whose output queue exceeds 1 MiB, and the protocol has no sequence numbers, so such loss cannot be detected. Consumers that track state should resynchronise by querying periodically. Events are not delivered back to the connection that sent them.
  • Monitor. Conn.Monitor needs root; ubusd keeps one monitor per connection (ErrMonitorActive) and reports all traffic, including call data. See docs/monitor.md.
  • Lifecycle. Conn.Close is immediate and never waits for handlers (safe to call from one). Conn.Shutdown(ctx) refuses new work, lets running and queued handlers finish and reply (they may still make calls with their context while they run), waits for requests in flight, then closes. Each Shutdown caller gets its own result: nil when drained, its context error when its own context ended (the connection is then closed by force), ErrShutdownAborted when somebody else forced it. After Close of a listener, subscriber, monitor or object no new handler of it starts and queued work is discarded.
  • Waiting is not stopping. Close, and a Shutdown whose context ends, stop waiting for handlers; they cannot stop their execution. A running handler goes on after they return, cancelling its context only asks it to end, and its side effects are neither prevented nor undone. When the context of Shutdown ends, it guarantees that the connection is closed, not that user code or its side effects have stopped. Track your handlers if you need to know they have finished. See docs/lifecycle.md.
  • Registrations (AddObject, Listen, Monitor, NewSubscriber/Subscribe) return handles with an idempotent Close and CloseOnDone(ctx). The ctx passed to these calls bounds only the wait for the registration (the convention of net.Dialer.DialContext), not the lifetime of the registration; use CloseOnDone to tie a registration to a context. With WithReconnect or WithLazyConnect, active registrations are restored from their descriptors on the new connection; closed ones are not. Registrations that fail to restore are retried with backoff (WithRestoreRetry, default 8 tries; permission errors are final) and listed by Conn.RestoreStatus; operations on them return ErrNotRegistered meanwhile. Requests in flight when the connection breaks fail with ErrConnectionLost and are never retried.
  • Object ids change on reconnect. ubusd assigns new ids and drops remote subscriptions to the old objects; remote subscribers must subscribe again (libubus auto-subscribe and this library's path subscriptions do so when ubus.object.add announces the object). Path subscriptions made here re-resolve the path and resubscribe when the remote service restarts.
  • File descriptors. CallFD and Request.TakeFD/SetReplyFD pass one descriptor with a call and one with the final status (SCM_RIGHTS); see docs/fd.md.
  • Not supported: libubus channels.

Goals

  • Complete coverage of the ubus client protocol: lookup, call, objects, events, subscribe/notify.
  • Safe by default: strict decoding with size and depth limits, bounded queues and in-flight limits, context-aware calls, errors that never echo request payloads.
  • Predictable concurrency: one reader goroutine per connection, handlers run on a bounded worker pool, ordered delivery per listener.
  • Optional automatic reconnect that re-registers objects, event listeners and subscriptions.

Compatibility

Targets are OpenWrt 25.12 and 21.02, default socket /var/run/ubus/ubus.sock. 19.07 and older (/var/run/ubus.sock, tried as a fallback) are not targeted.

What was run for v0.2.0, by kind of environment. Details and test counts: docs/compatibility.md.

Kind Environment Arch Result
Hardware MediaTek MT7981 router, OpenWrt 25.12.5; private instances of its ubusd arm64 unit, compatibility (C peer, ACL) and 10 minute stress runs passed; no race detector
Hardware Orange Pi Zero, OpenWrt 21.02.2; private instances of its ubusd ARMv7 the same; no race detector (Go has none for 32-bit ARM)
Virtual machine Debian 11, kernel 5.10; ubusd and libubus built from the 21.02 and 25.12 commits arm64 compatibility passed for both releases, plain and with the race detector; unit tests and 3 minute stress runs with the race detector passed
Emulation x86-64 macOS test binaries under Rosetta; in-process stand-in, no real ubusd amd64 unit and 3 minute stress runs with the race detector passed; macOS uses the unbuffered receive path
Emulation x86-64 test binaries under qemu-user 7.2 on that virtual machine, against its arm64 ubusd amd64 compatibility, unit (2 skipped: qemu does not report truncated ancillary data) and 3 minute stress runs passed; no race detector
Not run amd64 hardware; mips, mipsle (cross-compiled and vetted only)

Details per feature: docs/compatibility.md.

Go: the module declares go 1.23. Binaries are meant to be cross-compiled on a build host with CGO_ENABLED=0; the Go version shipped in a router SDK does not matter.

Benchmarks

Against libubus on the two physical routers: medians of 7 alternating runs of the ubusio client (commit 4c024fa; later library changes are in error and close paths) and of 14 runs of the libubus client on the same boards in the same sessions. libubus is faster in every speed row on both boards and uses much less client CPU and, with few clients, memory. The Go client also does more work per call, and the 8 and 64 client rows compare one Go process with as many C processes. Ranges, method, the comparison with the previous client and a virtual machine run (of the previous client; it says nothing about routers): docs/performance-results.md, docs/benchmarks.md.

Metric (median) MT7981: libubus MT7981: ubusio Orange Pi Zero: libubus Orange Pi Zero: ubusio
Small call p50, µs 87.5 268 177 333
Small call p99, µs 223 605 204 477
64 KiB call p50, µs 1 048 1 741 1 257 3 217
Calls/s, 1 client 10 043 2 854 5 713 2 804
Calls/s, 8 clients 14 988 8 901 13 371 7 680
Calls/s, 64 clients 13 263 9 607 10 782 9 110
CPU µs/call, 1 client 30.1 241 56.4 407
CPU µs/call, 64 clients 47 99 73.5 250
Events sent/s 14 589 4 216 9 276 3 396
Events received/s 14 212 12 457 9 274 5 927
Incoming invoke p50, µs 88.6 383 172 463
List 1000 objects p50, µs 6 731 9 454 9 882 13 873
Connect, lookup, call p50, µs 601 1 493 525 1 631
Process start to exit p50, µs 2 900 7 889 3 688 12 164
Idle VmRSS, KB 848 3 936 532 3 372
After sequential calls VmRSS, KB 1 052 8 532 872 7 700

Development

make ci      # gofmt check, go vet, race tests, cross-compilation
make fuzz    # run every fuzz target for FUZZTIME (default 30s)

License

MIT, see LICENSE.

ubusio is an independent implementation written from the public description of the ubus wire protocol; the upstream sources were consulted only to verify protocol facts and compatibility, and no code from ubus or libubox was copied.

Documentation

Overview

Package ubusio is a pure-Go client and server library for ubus, the OpenWrt micro bus.

It talks the ubus wire protocol directly over the unix socket of ubusd and has no cgo or external process dependencies. The blobmsg subpackage implements the blob/blobmsg message encoding used on the wire.

The package is under active development; the API is not yet stable.

Example (Call)
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/ddffcczz/ubusio"
	"github.com/ddffcczz/ubusio/blobmsg"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	conn, err := ubusio.Dial(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	info, err := conn.Call(ctx, "system", "board", nil)
	if err != nil {
		log.Fatal(err)
	}
	model, _ := info.String("model")
	fmt.Println("model:", model)

	// Decoding into a struct: strict (duplicate keys are errors) and with
	// explicit integer widths.
	var board struct {
		Model   string `blobmsg:"model"`
		Release struct {
			Version string `blobmsg:"version"`
		} `blobmsg:"release"`
	}
	if err := blobmsg.Decode(info, &board, blobmsg.MapOptions{}); err != nil {
		log.Fatal(err)
	}
	fmt.Println(board.Release.Version)
}
Example (Events)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ddffcczz/ubusio"
)

func main() {
	ctx := context.Background()
	conn, err := ubusio.Dial(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	l, err := conn.Listen(ctx, func(ev ubusio.Event) {
		m, err := ev.Data.Map()
		fmt.Println(ev.Type, m, err)
	}, "network.interface", "demo.*")
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	if err := conn.Send(ctx, "demo.started", map[string]any{"pid": 1}); err != nil {
		log.Fatal(err)
	}
}
Example (Notify)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ddffcczz/ubusio"
)

func main() {
	ctx := context.Background()
	conn, err := ubusio.Dial(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	obj, err := conn.AddObject(ctx, "demo.notifier", nil, ubusio.OnSubscribers(func(active bool) {
		fmt.Println("subscribers present:", active)
	}))
	if err != nil {
		log.Fatal(err)
	}
	if obj.HasSubscribers() {
		obj.Notify(ctx, "changed", map[string]any{"value": 42})
	}
}
Example (Objects)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ddffcczz/ubusio"
)

func main() {
	ctx := context.Background()
	conn, err := ubusio.Dial(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	objs, err := conn.Objects(ctx, "network.interface.*")
	if err != nil {
		log.Fatal(err)
	}
	for _, o := range objs {
		fmt.Printf("%s @%08x\n", o.Path, o.ID)
		for _, m := range o.Signature {
			fmt.Println("  ", m.Name, m.Args)
		}
	}
}
Example (Server)
package main

import (
	"context"
	"log"
	"time"

	"github.com/ddffcczz/ubusio"
	"github.com/ddffcczz/ubusio/blobmsg"
)

func main() {
	ctx := context.Background()
	conn, err := ubusio.Dial(ctx, ubusio.WithReconnect(nil))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	_, err = conn.AddObject(ctx, "demo", []ubusio.Method{
		{
			Name: "hello",
			Args: []ubusio.ArgSignature{{Name: "name", Type: blobmsg.TypeString}},
			Handler: func(ctx context.Context, req *ubusio.Request) error {
				name, ok := req.Args.String("name")
				if !ok {
					return ubusio.StatusInvalidArgument
				}
				return req.Reply(map[string]any{"message": "hello " + name})
			},
		},
		{
			// A deferred reply, completed from another goroutine.
			Name: "slow",
			Handler: func(ctx context.Context, req *ubusio.Request) error {
				req.Defer()
				go func() {
					time.Sleep(time.Second)
					req.Reply(map[string]any{"done": true})
					req.Complete(nil)
				}()
				return nil
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	select {} // serve until killed; try: ubus call demo hello '{"name":"x"}'
}
Example (Subscribe)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ddffcczz/ubusio"
)

func main() {
	ctx := context.Background()
	conn, err := ubusio.Dial(ctx, ubusio.WithReconnect(nil))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	sub, err := conn.NewSubscriber(ctx, func(ctx context.Context, n *ubusio.Request) error {
		fmt.Println("notification", n.Method, n.Args.MapLastWins())
		return nil
	}, ubusio.OnTargetRemoved(func(id uint32, path string) {
		fmt.Println("gone:", path)
	}))
	if err != nil {
		log.Fatal(err)
	}
	// Watch does not require the object to exist yet and follows it
	// across restarts of its owner and reconnects.
	if err := sub.Watch(ctx, "hostapd.wlan0"); err != nil {
		log.Fatal(err)
	}
}

Index

Examples

Constants

View Source
const (
	DefaultSocketPath = "/var/run/ubus/ubus.sock"
	LegacySocketPath  = "/var/run/ubus.sock"
)

Default socket paths. DefaultSocketPath is used by OpenWrt 21.02 and later; LegacySocketPath by older releases and is tried when the default does not exist and no explicit path was configured.

View Source
const (
	DefaultMaxInflight    = 64
	DefaultRequestTimeout = 30 * time.Second
	DefaultWriteTimeout   = 10 * time.Second
	// DefaultMemoryBudget bounds the received data a connection buffers
	// at any time: unconsumed replies, queued events, notifications and
	// method calls. Sized for routers.
	DefaultMemoryBudget = 4 << 20
	// DefaultMaxReplies and DefaultMaxReplyBytes bound the replies that
	// CallMany and NotifyWait accumulate.
	DefaultMaxReplies     = 1024
	DefaultMaxReplyBytes  = 4 << 20
	DefaultHandlerWorkers = 4
	DefaultHandlerQueue   = 64
)

Defaults for the corresponding options.

View Source
const DefaultMaxMessageSize = 1 << 20

DefaultMaxMessageSize is the largest message ubusd accepts by default (UBUS_MAX_MSGLEN). ubusd closes the connection of a client that sends a bigger one.

View Source
const (
	DefaultRestoreAttempts = 8
)

Defaults for WithRestoreRetry.

Variables

View Source
var (
	// ErrClosed is returned after Close.
	ErrClosed = errors.New("ubusio: connection closed")
	// ErrConnectionLost is returned for requests that were in flight
	// (or could not be sent) when the connection to ubusd broke. Such
	// requests are never retried automatically: they may or may not
	// have been executed.
	ErrConnectionLost = errors.New("ubusio: connection lost")
	// ErrMessageTooLarge is returned when an outgoing message exceeds
	// the configured maximum message size. Nothing was sent.
	ErrMessageTooLarge = errors.New("ubusio: message too large")
	// ErrWriteTimeout is returned when ubusd did not accept a message
	// within the write timeout (see WithWriteTimeout). Nothing was sent.
	ErrWriteTimeout = errors.New("ubusio: write timeout")
	// ErrInvalidName is returned for empty names or names containing
	// NUL bytes (object paths, methods, event types and patterns).
	ErrInvalidName = errors.New("ubusio: invalid name")
	// ErrProtocol reports a malformed message received from ubusd. The
	// connection is closed when the framing itself is broken.
	ErrProtocol = errProtocol
)

Errors returned by the library. Library errors never include message payloads.

View Source
var (
	// ErrInvalidFD is returned for a nil-equivalent or closed *os.File
	// passed as a descriptor to send. Nothing was sent.
	ErrInvalidFD = errors.New("ubusio: invalid file descriptor")
	// ErrFDLost is returned by CallFD and CallIDFD, together with the
	// reply and without a file, when the final status arrived with ancillary data that could
	// not be received: the method may have sent a descriptor that is
	// lost. The call itself succeeded.
	ErrFDLost = errors.New("ubusio: a file descriptor sent with the reply was lost")
	// ErrFDUnsupported is returned on platforms without SCM_RIGHTS.
	ErrFDUnsupported = errors.New("ubusio: file descriptor passing is not supported on this platform")
)

Errors of file descriptor passing.

View Source
var (
	// ErrShuttingDown is returned while Shutdown is in progress, for new
	// registrations, for calls that are not made with the context of a
	// running handler of the connection, and for requests that would need
	// a new connection.
	ErrShuttingDown = errors.New("ubusio: connection is shutting down")
	// ErrShutdownInHandler is returned by Shutdown when it is called with
	// the context of a handler of the same connection: waiting would wait
	// for the caller itself. Shutdown has been started and completes on
	// its own; use Close to force it.
	ErrShutdownInHandler = errors.New("ubusio: Shutdown called from a handler")
	// ErrShutdownAborted is returned by a Shutdown that was waiting when
	// the connection was closed by force: by Close, or by another
	// Shutdown whose context ended.
	ErrShutdownAborted = errors.New("ubusio: shutdown aborted: connection closed by force")
)

Errors of the connection lifecycle.

View Source
var ErrAlreadyCompleted = errors.New("ubusio: request already completed")

ErrAlreadyCompleted is returned by Reply and Complete after the request's final status was sent.

View Source
var ErrMemoryBudget = errors.New("ubusio: connection memory budget exhausted")

ErrMemoryBudget is returned when the connection's memory budget for buffered data is exhausted (see WithMemoryBudget).

View Source
var ErrMonitorActive = errors.New("ubusio: a monitor is already active on this connection")

ErrMonitorActive is returned by Monitor when the connection already has an active monitor: ubusd keeps one monitor registration per client.

View Source
var ErrMultipleObjects = errors.New("ubusio: path matches more than one object")

ErrMultipleObjects is returned by Lookup (and Call) when a wildcard path matches more than one object; use Objects to list them.

View Source
var ErrMultipleReplies = errors.New("ubusio: method sent more than one reply")

ErrMultipleReplies is returned by Call and CallID when the method sent more than one data reply; use CallMany or CallEach for such methods. The call itself was executed.

View Source
var ErrNotRegistered = errors.New("ubusio: not registered on the current connection")

ErrNotRegistered is returned for operations on an object, listener or subscriber that is not (yet) registered on the current connection, for example because restoring it after a reconnect failed and is being retried (see Conn.RestoreStatus).

View Source
var ErrTooManyReplies = errors.New("ubusio: too many replies")

ErrTooManyReplies is returned by CallMany, CallIDMany, NotifyWait, Objects and wildcard Lookup when the replies exceed WithReplyLimits.

Functions

This section is empty.

Types

type ArgSignature

type ArgSignature struct {
	Name string
	Type blobmsg.Type
}

ArgSignature is a declared method argument.

type Backoff

type Backoff func(attempt int) time.Duration

Backoff returns the delay before reconnect attempt n (starting at 1).

func ExponentialBackoff

func ExponentialBackoff(min, max time.Duration) Backoff

ExponentialBackoff returns a Backoff doubling from min up to max, with up to 20% random jitter.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn is a connection to ubusd. It is safe for concurrent use.

A single goroutine reads from the socket and routes replies to the requests waiting for them; method, event and notification handlers run on a separate bounded worker pool and never block the reader.

func Dial

func Dial(ctx context.Context, opts ...Option) (*Conn, error)

Dial connects to ubusd and waits for its greeting. The context bounds the connection attempt only.

func (*Conn) AddObject

func (c *Conn) AddObject(ctx context.Context, path string, methods []Method, opts ...ObjectOption) (*Object, error)

AddObject publishes an object at path with the given methods.

ctx bounds only the registration request, like the context of net.Dialer.DialContext: it does not govern the registration once it is established. The registration lasts until Close (or the connection is closed); use CloseOnDone to tie it to a context.

func (*Conn) Call

func (c *Conn) Call(ctx context.Context, path, method string, args any) (blobmsg.Table, error)

Call invokes method on the object at path and returns its data reply, or nil if the method replied with a status only. A method that sends several data replies makes Call fail with ErrMultipleReplies as soon as the second one arrives (never silently picking one, and without buffering the rest). args is encoded with blobmsg.Marshal: nil, a blobmsg.Table, a map with string keys or a struct.

path may end in '*' if it matches exactly one object (see Lookup). Object ids are cached per exact path (see WithLookupCache). When ubusd reports a cached id as unknown, the path is looked up again and the call is sent once more; this is safe because the first attempt never reached a handler.

func (*Conn) CallEach

func (c *Conn) CallEach(ctx context.Context, path, method string, args any, fn func(blobmsg.Table) error) error

CallEach invokes method on the object at path and calls fn for every data reply as it arrives, in order. Methods may send any number of data replies before their final status. If fn returns an error, the remaining replies are discarded and that error is returned.

func (*Conn) CallFD added in v0.2.0

func (c *Conn) CallFD(ctx context.Context, path, method string, args any, fd *os.File) (blobmsg.Table, *os.File, error)

CallFD is Call with file descriptors: it sends fd (if not nil) with the request and returns the descriptor that the method attached to its final status (nil if it sent none). The returned file belongs to the caller, who must close it. The library does not take ownership of fd: the kernel duplicates it, and the caller may close it once CallFD returns. A descriptor is returned only for a successful call.

ubus passes one descriptor per message, and only with the request and the final status; data replies cannot carry one. Descriptors need a platform with SCM_RIGHTS (ErrFDUnsupported otherwise). Descriptors are not counted in the memory budget.

The received file is untrusted input from another process: it may be a FIFO or socket that blocks on read or write, a directory, a device or an O_PATH descriptor. Check it with Stat, use deadlines (SetDeadline works on pipes and sockets) and never use it as the directory of an *at call. If the final status came with ancillary data that could not be received, the reply is returned with ErrFDLost and no file (one that did arrive is closed).

func (*Conn) CallID

func (c *Conn) CallID(ctx context.Context, id uint32, method string, args any) (blobmsg.Table, error)

CallID invokes method on the object with the given id and returns its single data reply, like Call.

func (*Conn) CallIDEach

func (c *Conn) CallIDEach(ctx context.Context, id uint32, method string, args any, fn func(blobmsg.Table) error) error

CallIDEach invokes method on the object with the given id and calls fn for every data reply, like CallEach.

func (*Conn) CallIDFD added in v0.2.0

func (c *Conn) CallIDFD(ctx context.Context, id uint32, method string, args any, fd *os.File) (blobmsg.Table, *os.File, error)

CallIDFD is CallFD for an object id, like CallID.

func (*Conn) CallIDMany

func (c *Conn) CallIDMany(ctx context.Context, id uint32, method string, args any) ([]blobmsg.Table, error)

CallIDMany invokes method on the object with the given id and returns all its data replies, like CallMany.

func (*Conn) CallInto

func (c *Conn) CallInto(ctx context.Context, path, method string, args, out any) error

CallInto invokes method like Call and decodes the single data reply into out with blobmsg.Decode and strict options. A status-only reply leaves out unchanged.

func (*Conn) CallMany

func (c *Conn) CallMany(ctx context.Context, path, method string, args any) ([]blobmsg.Table, error)

CallMany invokes method on the object at path and returns all its data replies in order. The number and total size of replies are limited (see WithReplyLimits); beyond that the call fails with ErrTooManyReplies. On error, the replies received so far are returned with it.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection at once. Pending requests fail with ErrClosed, the context passed to handlers is cancelled, queued handler work is discarded (its memory budget and descriptors released), replies not yet written are dropped, automatic reconnection stops and a connection attempt in progress is aborted. Blocked socket reads and writes are interrupted. It is idempotent and safe for concurrent use. See Shutdown for the graceful variant.

Close never waits for user handlers, so it may be called from inside any handler. It stops waiting for them, it does not stop them: a running handler, and any goroutine it started, goes on after Close returned, cancelling its context only asks it to end, and what it does outside this connection is neither prevented nor undone. Its replies and calls on this connection fail. No further handler is begun, except one whose start was decided just before. To know that handlers have finished, track them in the application.

func (*Conn) ID

func (c *Conn) ID() uint32

ID returns the client id assigned by ubusd to the current connection, or 0 when not connected.

func (*Conn) Listen

func (c *Conn) Listen(ctx context.Context, handler func(Event), patterns ...string) (*Listener, error)

Listen registers handler for events whose type matches one of the patterns. A pattern is an exact event type or a prefix followed by '*'; "*" matches every event. ubusd does not deliver events to the connection that sent them.

When the handler falls behind by more than the handler queue size (see WithHandlerWorkers), further events are dropped and counted (see Dropped).

ctx bounds only the registration request, like the context of net.Dialer.DialContext: it does not govern the registration once it is established. The registration lasts until Close (or the connection is closed); use CloseOnDone to tie it to a context.

func (*Conn) Lookup

func (c *Conn) Lookup(ctx context.Context, path string) (uint32, error)

Lookup returns the id of the object published at path. A path ending in '*' is a prefix pattern that must match exactly one object: several matches give ErrMultipleObjects, none StatusNotFound.

func (*Conn) Monitor added in v0.2.0

func (c *Conn) Monitor(ctx context.Context, handler func(MonitorEvent), opts ...MonitorOption) (*Monitor, error)

Monitor asks ubusd to report all messages it receives and sends, to handler, one at a time in arrival order. ubusd allows this only to clients running as root (uid and gid 0); others get StatusPermissionDenied. The reports contain all call arguments and replies on the bus: treat them as sensitive.

ubusd keeps one monitor per client, so a connection can have one active Monitor; further calls return ErrMonitorActive until it is closed. The monitor is restored after a reconnect like listeners are.

When the handler falls behind by more than the handler queue size (see WithHandlerWorkers) or the memory budget is exhausted, reports are dropped and counted (see Dropped). Reports that ubusd itself dropped are detected by gaps in the sequence (see Missed). A report of a message the handler generates may follow immediately: use MonitorExcludeSelf to avoid feedback.

Reports waiting for the handler use at most a quarter of the memory budget (see WithMemoryBudget), the rest are dropped, so that a flood of monitored traffic leaves room for calls. Handler panics are recovered and dropped. A monitor shares the worker pool and reader with the connection's other work: use a dedicated Conn for it.

ctx bounds only the registration request; the registration lasts until Close (or the connection is closed).

func (*Conn) NewSubscriber

func (c *Conn) NewSubscriber(ctx context.Context, h Handler, opts ...SubscriberOption) (*Subscriber, error)

NewSubscriber creates a subscriber whose notifications are handled by h.

ctx bounds only the registration request, like the context of net.Dialer.DialContext: it does not govern the registration once it is established. The registration lasts until Close (or the connection is closed); use CloseOnDone to tie it to a context.

func (*Conn) Objects

func (c *Conn) Objects(ctx context.Context, pattern string) ([]ObjectInfo, error)

Objects lists published objects. An empty pattern lists all objects, a pattern ending in '*' lists the objects whose path starts with the part before it, and any other pattern matches one exact path. No match yields an empty list and no error.

The number of objects and their total size are limited like call results (WithReplyLimits, default 1024 objects and 4 MiB); beyond that Objects returns the objects received so far together with ErrTooManyReplies. Raise the limits for systems with more objects.

On ubus releases without lookup queuing (e.g. OpenWrt 21.02) ubusd may silently drop parts of very large listings; prefer prefix patterns and always use a context deadline there.

func (*Conn) RestoreStatus added in v0.1.1

func (c *Conn) RestoreStatus() []RestoreFailure

RestoreStatus returns the registrations that are currently not restored on the connection. It is empty when everything is active. A registration that its owner closed is no longer listed.

func (*Conn) Send

func (c *Conn) Send(ctx context.Context, typ string, data any) error

Send emits an event. data is encoded like call arguments; nil sends an empty table. Event types starting with "ubus." are reserved by ubusd.

func (*Conn) Shutdown added in v0.2.0

func (c *Conn) Shutdown(ctx context.Context) error

Shutdown closes the connection gracefully. When it starts:

  • new registrations fail with ErrShuttingDown;
  • new calls, sends and notifications fail with ErrShuttingDown unless they are made with the context of a running handler of this connection (or one derived from it), until it returns or, for a deferred request, completes. Event listener, subscriber OnTargetRemoved, OnSubscribers and monitor callbacks receive no context, so their calls count as external;
  • no new handler invocation is accepted: requests that still arrive are answered with StatusNotFound, events and notifications are dropped;
  • reconnection stops: if the connection is or gets lost, operations that need it fail with ErrShuttingDown;
  • event listeners and the monitor are removed at ubusd and subscriptions ended (best effort). Published objects stay until the connection closes, because ubusd drops the replies of a removed object.

The connection keeps working otherwise: running and queued handlers finish and send their replies, requests in flight and the calls handlers make receive theirs. Every method call or notification admitted before Shutdown started is run and answered as far as the link allows. When all handlers, deferred requests and requests in flight are done, the replies the library owes at that point are written, ubusd is given up to five seconds to confirm that it has processed them, and the transport is closed. That confirmation is best effort: if it does not come, the connection is closed all the same, and replies ubusd had not read may be lost. Refusals of requests that keep arriving after that point are best effort and do not delay it.

The result belongs to the caller:

  • nil: all admitted work finished and the connection was closed by the drain, whether or not ubusd confirmed the last replies; or it was closed before this call, in whatever way;
  • an error wrapping ctx.Err(): the context of this call ended first; this call closed the connection by force, as Close does;
  • ErrShutdownAborted: while this call was waiting, the connection was closed by force, by Close or by another Shutdown whose context ended.

Called with the context of a handler of this connection, Shutdown starts draining and returns ErrShutdownInHandler without waiting. Other contexts cannot be told apart: a handler that calls Shutdown with an unrelated context waits for itself until that context ends.

When the context of a call ends first, Shutdown guarantees that the connection is closed when it returns. It does not guarantee that user code has stopped executing, nor that its side effects stop: as after Close, running handlers, and goroutines they started, go on, cancelling their context only asks them to end, and what they do outside this connection is neither prevented nor undone.

func (*Conn) Stats

func (c *Conn) Stats() Stats

Stats returns the connection's drop counters.

func (*Conn) Subscribe

func (c *Conn) Subscribe(ctx context.Context, path string, h Handler, opts ...SubscriberOption) (*Subscriber, error)

Subscribe is a shortcut that creates a Subscriber with handler h and subscribes it to the object at path (which must exist). Close the returned subscriber to end the subscription.

ctx bounds only the registration request, like the context of net.Dialer.DialContext: it does not govern the registration once it is established. The registration lasts until Close (or the connection is closed); use CloseOnDone to tie it to a context.

type Error

type Error struct {
	Op     string
	Path   string
	Method string
	Err    error
}

Error describes a failed operation. It wraps the underlying cause, typically a Status or one of the Err* values. It names the operation, object and method but never contains message data.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Event

type Event struct {
	Type string
	Data blobmsg.Table
}

Event is a ubus event.

type Handler

type Handler func(ctx context.Context, req *Request) error

Handler handles an incoming method call or subscription notification. It may send any number of data replies with req.Reply. Its return value becomes the reply status: nil is success, a Status is sent as is and any other error is reported as StatusUnknownError. To answer later, call req.Defer and finish with req.Complete.

Handlers run on the connection's worker pool; ctx is cancelled when the connection is closed.

type Listener

type Listener struct {
	// contains filtered or unexported fields
}

Listener receives events matching its patterns. Events are delivered to its handler one at a time, in arrival order.

func (*Listener) Close

func (l *Listener) Close() error

Close stops event delivery. It is idempotent; a closed listener is not restored after a reconnect. It does not wait for the handler and may be called from it: no new handler call starts after Close returns, one in progress may finish, and queued events are discarded. If the daemon does not answer within the request timeout, Close returns the error while the removal goes on; a further Close waits for it.

func (*Listener) CloseOnDone

func (l *Listener) CloseOnDone(ctx context.Context)

CloseOnDone closes the listener when ctx is done.

func (*Listener) Dropped

func (l *Listener) Dropped() uint64

Dropped returns the number of events dropped because the handler could not keep up.

type MessageType added in v0.2.0

type MessageType uint8

MessageType is the type of a ubus protocol message.

const (
	MessageHello        MessageType = msgHello
	MessageStatus       MessageType = msgStatus
	MessageData         MessageType = msgData
	MessagePing         MessageType = msgPing
	MessageLookup       MessageType = msgLookup
	MessageInvoke       MessageType = msgInvoke
	MessageAddObject    MessageType = msgAddObject
	MessageRemoveObject MessageType = msgRemoveObject
	MessageSubscribe    MessageType = msgSubscribe
	MessageUnsubscribe  MessageType = msgUnsubscribe
	MessageNotify       MessageType = msgNotify
)

Message types, as reported by the monitor.

func (MessageType) String added in v0.2.0

func (t MessageType) String() string

String returns the name used by `ubus monitor`, or the number for unknown types.

type Method

type Method struct {
	Name    string
	Args    []ArgSignature
	Handler Handler
}

Method describes an exported method. Args is published as the method signature (as shown by "ubus -v list"); ubus does not enforce it.

type MethodSignature

type MethodSignature struct {
	Name string
	Args []ArgSignature
}

MethodSignature describes a method and its declared arguments.

type Monitor added in v0.2.0

type Monitor struct {
	// contains filtered or unexported fields
}

Monitor is a registration for ubusd's traffic monitor, the interface behind `ubus monitor`. See Conn.Monitor.

func (*Monitor) Close added in v0.2.0

func (m *Monitor) Close() error

Close stops monitoring. It is idempotent; a closed monitor is not restored after a reconnect. It does not wait for the handler and may be called from it: no new handler call starts after Close returns, one in progress may finish, and queued reports are discarded. If the daemon does not answer within the request timeout, Close returns the error while the removal goes on; a further Close waits for it.

func (*Monitor) CloseOnDone added in v0.2.0

func (m *Monitor) CloseOnDone(ctx context.Context)

CloseOnDone closes the monitor when ctx is done.

func (*Monitor) Dropped added in v0.2.0

func (m *Monitor) Dropped() uint64

Dropped returns the number of reports dropped locally because the handler could not keep up.

func (*Monitor) Missed added in v0.2.0

func (m *Monitor) Missed() uint64

Missed returns the number of reports ubusd did not deliver, detected by gaps in its sequence numbers (it drops messages for clients whose output queue is full).

type MonitorDirection added in v0.2.0

type MonitorDirection uint8

MonitorDirection selects the messages a monitor reports.

const (
	MonitorBoth       MonitorDirection = iota
	MonitorToClient                    // only messages sent by ubusd
	MonitorFromClient                  // only messages received by ubusd
)

Monitor directions.

type MonitorEvent added in v0.2.0

type MonitorEvent struct {
	// Seq is ubusd's per-monitor sequence number of this report. Gaps
	// mean that ubusd dropped reports for this client (see Missed).
	Seq uint16
	// Client is the id of the client whose connection carried the
	// message.
	Client uint32
	// ToClient is true for messages ubusd sent to Client and false for
	// messages it received from Client (UBUS_MONITOR_SEND).
	ToClient bool
	// Type is the message type.
	Type MessageType
	// MsgSeq and Peer are the sequence number and peer fields of the
	// message header.
	MsgSeq uint16
	Peer   uint32

	// Decoded message attributes.
	Path       string
	ObjectID   uint32
	Method     string
	ObjectType uint32
	Target     uint32
	User       string
	Group      string
	Active     bool
	NoReply    bool
	// Status is valid when HasStatus is set.
	Status    Status
	HasStatus bool
	// Data is the decoded UBUS_ATTR_DATA table (call arguments, reply
	// or event data) and Signature the decoded object signature.
	Data      blobmsg.Table
	Signature blobmsg.Table

	// Raw is the undecoded attribute block of the message. It belongs to
	// the handler.
	Raw []byte
	// Err is set when the message attributes could not be decoded (the
	// content of a message is not validated by ubusd before it is
	// reported); only the header fields and Raw are valid then.
	Err error
}

MonitorEvent is one message ubusd received from or sent to a client, as reported to a monitor. It carries the message header and the decoded attributes; fields of attributes the message did not have are zero.

type MonitorOption added in v0.2.0

type MonitorOption func(*Monitor)

MonitorOption configures Monitor. Filters are applied locally: ubusd reports everything to a monitor.

func MonitorExcludeSelf added in v0.2.0

func MonitorExcludeSelf() MonitorOption

MonitorExcludeSelf skips messages carried by this connection itself, which avoids a feedback loop when the handler makes calls.

func MonitorOnly added in v0.2.0

func MonitorOnly(d MonitorDirection) MonitorOption

MonitorOnly reports only one direction.

func MonitorTypes added in v0.2.0

func MonitorTypes(types ...MessageType) MonitorOption

MonitorTypes reports only messages of the given types. Repeated use adds types; without arguments it does nothing.

type NotifyResult

type NotifyResult struct {
	Subscriber uint32
	Status     Status
	Data       []blobmsg.Table
	// Done is false if the subscriber did not answer before the
	// context ended.
	Done bool
}

NotifyResult is the answer of one subscriber to NotifyWait.

type Object

type Object struct {
	// contains filtered or unexported fields
}

Object is an object published on the bus.

func (*Object) Close

func (o *Object) Close() error

Close withdraws the object from the bus, like Remove with the default request timeout. It is idempotent.

func (*Object) CloseOnDone

func (o *Object) CloseOnDone(ctx context.Context)

CloseOnDone closes the object when ctx is done.

func (*Object) HasSubscribers

func (o *Object) HasSubscribers() bool

HasSubscribers reports whether the object currently has subscribers.

func (*Object) ID

func (o *Object) ID() uint32

ID returns the object id assigned by ubusd. It changes after a reconnect.

func (*Object) Notify

func (o *Object) Notify(ctx context.Context, method string, data any) error

Notify sends a notification to all subscribers without waiting for replies.

func (*Object) NotifyWait

func (o *Object) NotifyWait(ctx context.Context, method string, data any) ([]NotifyResult, error)

NotifyWait sends a notification and waits until every subscriber has answered or ctx ends. The number of subscribers and the data replies collected are bounded by WithReplyLimits (ErrTooManyReplies). It returns one result per subscriber present when the notification was sent; on timeout the results collected so far are returned together with the context error.

func (*Object) Path

func (o *Object) Path() string

Path returns the object path.

func (*Object) Remove

func (o *Object) Remove(ctx context.Context) error

Remove withdraws the object from the bus. It is idempotent; a removed object is not restored after a reconnect. Remove does not wait for running handlers and may be called from one; calls not started yet are discarded and answered with StatusNotFound, and no handler of the object starts after Remove returns.

ctx bounds only the wait. The removal at ubusd goes on after it ends, and a further Remove waits for it and returns its result.

Note for remote subscribers: after a reconnect the object is published again under a new id and ubusd has dropped existing subscriptions to it. Subscribers must subscribe again (this library does so automatically for path subscriptions, as does libubus auto-subscribe).

type ObjectInfo

type ObjectInfo struct {
	Path   string
	ID     uint32
	TypeID uint32
	// Signature lists the methods visible to this client (ubusd hides
	// methods denied by ACLs) in the order reported by ubusd.
	Signature []MethodSignature
}

ObjectInfo describes a published object as reported by ubusd.

type ObjectOption

type ObjectOption func(*Object)

ObjectOption configures an Object.

func OnSubscribers

func OnSubscribers(fn func(active bool)) ObjectOption

OnSubscribers sets a callback invoked whenever the object gains its first subscriber (true) or loses its last one (false). Calls are delivered in order.

type Option

type Option func(*options)

Option configures a Conn.

func OnDisconnect

func OnDisconnect(fn func(c *Conn, err error)) Option

OnDisconnect sets a hook called when an established connection is lost.

func OnReconnect

func OnReconnect(fn func(c *Conn, err error)) Option

OnReconnect sets a hook called after the connection was re-established. err joins the errors of registrations that could not be restored (they are retried on the next reconnect).

func WithHandlerWorkers

func WithHandlerWorkers(workers, queue int) Option

WithHandlerWorkers sets the number of goroutines running method, event and notification handlers, and the size of the queue in front of them. When the queue is full, method calls are answered with the overload status (see WithOverloadStatus) and events are dropped.

func WithLazyConnect

func WithLazyConnect() Option

WithLazyConnect makes Dial return without connecting: the connection is established by the first request and, after a loss, re-established by the next request (restoring registrations like WithReconnect).

func WithLookupCache

func WithLookupCache(enabled bool) Option

WithLookupCache enables or disables caching of path to object id lookups made by Call (enabled by default). Cached ids are dropped when ubusd reports the object as gone and after reconnects.

func WithMaxDepth

func WithMaxDepth(n int) Option

WithMaxDepth sets the nesting limit for decoding message data.

func WithMaxInflight

func WithMaxInflight(n int) Option

WithMaxInflight limits the number of concurrent outgoing requests. Further requests wait for a free slot or for their context.

func WithMaxMessageSize

func WithMaxMessageSize(n int) Option

WithMaxMessageSize sets the largest message, in bytes, that is sent or accepted. It must not exceed the ubusd limit (1 MiB by default), since ubusd drops clients that send bigger messages.

func WithMemoryBudget added in v0.1.1

func WithMemoryBudget(bytes int) Option

WithMemoryBudget sets the connection-wide budget, in bytes of message data, for everything received but not yet consumed: replies waiting for their caller, queued events, notifications and method calls. When it is exhausted, requests fail with ErrMemoryBudget, events and notifications are dropped (and counted) and method calls are answered with the overload status. It is raised to at least one maximum-size message.

func WithOverloadStatus

func WithOverloadStatus(s Status) Option

WithOverloadStatus sets the status returned to callers when the handler queue is full. The default is StatusNoMemory; use StatusUnknownError for callers on ubus releases that predate it.

func WithReconnect

func WithReconnect(backoff Backoff) Option

WithReconnect makes the connection re-establish itself in the background after it is lost, waiting backoff(n) before attempt n. After reconnecting, published objects are registered again (with new ids), event listeners and path subscriptions are restored and the lookup cache is cleared. Requests that were in flight when the connection broke fail with ErrConnectionLost and are not retried; requests made while disconnected wait for the new connection, bounded by their context.

func WithReplyLimits added in v0.1.1

func WithReplyLimits(maxReplies, maxBytes int) Option

WithReplyLimits bounds the number and total size (in bytes of message data) of the replies accumulated by CallMany, CallIDMany and NotifyWait and of the objects listed by Objects and wildcard Lookup; beyond them these fail with ErrTooManyReplies. CallEach is not limited by them since it does not accumulate.

func WithRequestTimeout

func WithRequestTimeout(d time.Duration) Option

WithRequestTimeout sets the timeout applied to operations whose context has no deadline. It bounds the operation as a whole, from the wait for a connection to the last reply. Zero disables the implicit timeout; a registration or removal that ubusd never answers then lasts, also after its caller gave up, until the connection is lost or closed, and Shutdown waits for a registration as long as its own context allows.

func WithRestoreRetry added in v0.1.1

func WithRestoreRetry(attempts int, backoff Backoff) Option

WithRestoreRetry sets how registrations that could not be restored after a reconnect are retried: up to attempts further tries, waiting backoff(n) before try n (default 8 tries, exponential from 200ms to 10s). Only registrations are retried (objects, event listeners, the monitor, subscribers and path subscriptions), never calls. Permission errors and invalid names are not retried.

func WithSocketPath

func WithSocketPath(path string) Option

WithSocketPath sets the ubusd socket path. Without it the default path is used, falling back to LegacySocketPath when the default is missing.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) Option

WithWriteTimeout bounds every socket write, whatever the context, so that a stuck ubusd cannot block callers or handler workers forever. Zero disables the bound (contexts still apply).

type Request

type Request struct {
	// Method is the method name (for notifications: the notification
	// type chosen by the notifying object).
	Method string
	// Args is the call data.
	Args blobmsg.Table
	// User and Group identify the caller when ubusd provides them.
	User, Group string
	// CallerID is the ubus client id of the caller.
	CallerID uint32
	// NoReply is set for notifications sent without waiting for
	// replies; Reply and Complete are no-ops then.
	NoReply bool
	// contains filtered or unexported fields
}

Request is an incoming method call or notification.

func (*Request) Complete

func (r *Request) Complete(err error) error

Complete sends the final status of the request (see Handler for the mapping of err).

func (*Request) Defer

func (r *Request) Defer()

Defer marks the request as answered later: the handler's return value is ignored and the request stays open until Complete.

func (*Request) Reply

func (r *Request) Reply(data any) error

Reply sends a data reply. It can be called several times before the request completes.

func (*Request) SetReplyFD added in v0.2.0

func (r *Request) SetReplyFD(f *os.File) error

SetReplyFD attaches f to the final status of the request (Complete or the implicit completion after the handler returns); a later call replaces it, nil removes it. The library sends a duplicate and closes it after sending, so the caller keeps ownership of f and may close it right away. Data replies cannot carry descriptors. It is a no-op for notifications (NoReply) and fails with ErrAlreadyCompleted after completion.

func (*Request) TakeFD added in v0.2.0

func (r *Request) TakeFD() *os.File

TakeFD returns the file descriptor the caller sent with the request, or nil if there was none or it was already taken. The caller of TakeFD owns the file and must close it. The file comes from an untrusted process: it may be a FIFO or socket that blocks, a directory, a device or an O_PATH descriptor. Stat it before use, use deadlines and never treat it as a directory for *at calls. A descriptor that the handler does not take is closed when the handler returns, also when it deferred the request: take it before returning.

type RestoreFailure added in v0.1.1

type RestoreFailure struct {
	// Kind is "object", "listener", "monitor", "subscriber" or
	// "subscription".
	Kind string
	// Name is the object path, the listener's patterns or the
	// subscribed path (empty for a subscriber object).
	Name string
	// Err is the last error.
	Err error
	// Attempts counts the tries so far, the first restore included.
	Attempts int
	// GaveUp is set once the failure is no longer retried (permanent
	// error or retries exhausted); the registration stays inactive until
	// the next reconnect or until it is closed and created again.
	GaveUp bool
}

RestoreFailure describes a registration that is not active on the current connection because restoring it after a reconnect failed.

type Stats

type Stats struct {
	// DroppedEvents counts events not delivered because a listener's
	// queue was full.
	DroppedEvents uint64
	// DroppedNotifications counts notifications not delivered because a
	// subscriber's queue was full, or, for those that expect no reply,
	// because their session ended before they were handled.
	DroppedNotifications uint64
	// DroppedMonitorMessages counts monitor messages not delivered
	// because the monitor's queue was full.
	DroppedMonitorMessages uint64
	// FDsLost counts messages that came with ancillary data that could
	// not be received (truncated or malformed): a file descriptor may have
	// been sent with them that was lost. See ErrFDLost.
	FDsLost uint64
	// OverloadedCalls counts incoming method calls answered with the
	// overload status because the handler queue was full.
	OverloadedCalls uint64
	// BudgetExceeded counts messages refused because the memory budget
	// was exhausted (see WithMemoryBudget); they are also counted in the
	// fields above where applicable.
	BudgetExceeded uint64
	// DroppedReplies counts status replies that the library itself owed
	// to a caller (request refused because the object, the connection or
	// the session it arrived on is going away, unknown method, invalid
	// arguments, overload) and did not write: the reply queue of the
	// session (256 replies) was full, the session or the connection ended
	// first, or the write failed. It also counts a failure to send the
	// status when a handler returns. Each lost reply counts once. Errors
	// of Reply and Complete calls are returned to their caller and not
	// counted. OverloadedCalls counts
	// calls refused for overload whether or not that reply got out, so a
	// lost overload reply appears in both.
	DroppedReplies uint64
	// BufferedBytes is the message data currently buffered.
	BufferedBytes int64
}

Stats are counters of messages this connection had to drop.

ubusd itself drops messages silently when a client's output queue exceeds its limit (1 MiB by default) and the protocol has no sequence numbers to detect that, so these counters only cover local drops. Treat events and notifications as best-effort and resynchronise state by querying periodically.

type Status

type Status int32

Status is a ubus status code. Non-zero values are errors and can be compared with errors.Is, e.g. errors.Is(err, ubusio.StatusNotFound).

const (
	StatusOK               Status = 0
	StatusInvalidCommand   Status = 1
	StatusInvalidArgument  Status = 2
	StatusMethodNotFound   Status = 3
	StatusNotFound         Status = 4
	StatusNoData           Status = 5
	StatusPermissionDenied Status = 6
	StatusTimeout          Status = 7
	StatusNotSupported     Status = 8
	StatusUnknownError     Status = 9
	StatusConnectionFailed Status = 10
	StatusNoMemory         Status = 11
	StatusParseError       Status = 12
	StatusSystemError      Status = 13
)

Status codes. Codes 11 to 13 are not known to ubus releases before 2022 (e.g. OpenWrt 21.02); such peers report them as unknown errors.

func (Status) Error

func (s Status) Error() string

Error implements error.

func (Status) String

func (s Status) String() string

type Subscriber

type Subscriber struct {
	// contains filtered or unexported fields
}

Subscriber receives notifications from the objects it subscribes to. Notifications are handled one at a time, in arrival order, by the subscriber's Handler; for notifications sent with NotifyWait the handler's result is returned to the notifying object.

Subscriptions made by path are kept until Unsubscribe or Close: when the target object disappears the subscription becomes pending and is re-established as soon as an object with that path is published again, including after a reconnect.

func (*Subscriber) Close

func (s *Subscriber) Close() error

Close ends the subscriptions and removes the subscriber. It is idempotent; a closed subscriber is not restored after a reconnect. It does not wait for handlers and may be called from one: no new handler call starts after Close returns, one in progress may finish, and queued notifications are discarded. If the daemon does not answer within the request timeout, Close returns the error while the removal goes on; a further Close waits for it.

func (*Subscriber) CloseOnDone

func (s *Subscriber) CloseOnDone(ctx context.Context)

CloseOnDone closes the subscriber when ctx is done.

func (*Subscriber) Dropped

func (s *Subscriber) Dropped() uint64

Dropped returns the number of notifications dropped because the handler could not keep up, or because their session ended before they were handled (those expecting no reply).

func (*Subscriber) ID

func (s *Subscriber) ID() uint32

ID returns the subscriber's object id (it changes after a reconnect).

func (*Subscriber) Subscribe

func (s *Subscriber) Subscribe(ctx context.Context, path string) error

Subscribe subscribes to the object at path, which must exist (also if the path is already watched). ctx bounds only this request; the subscription lasts until Unsubscribe or Close.

func (*Subscriber) SubscribeID

func (s *Subscriber) SubscribeID(ctx context.Context, id uint32) error

SubscribeID subscribes to the object with the given id. Such subscriptions end when the target goes away or the connection is re-established.

func (*Subscriber) Unsubscribe

func (s *Subscriber) Unsubscribe(ctx context.Context, path string) error

Unsubscribe ends a subscription made by path.

func (*Subscriber) UnsubscribeID

func (s *Subscriber) UnsubscribeID(ctx context.Context, id uint32) error

UnsubscribeID ends a subscription made by id.

func (*Subscriber) Watch

func (s *Subscriber) Watch(ctx context.Context, path string) error

Watch subscribes to the object at path as soon as it exists; it does not fail when the object is missing.

type SubscriberOption

type SubscriberOption func(*Subscriber)

SubscriberOption configures a Subscriber.

func OnTargetRemoved

func OnTargetRemoved(fn func(target uint32, path string)) SubscriberOption

OnTargetRemoved sets a callback invoked when a subscribed object goes away (path is empty for subscriptions made by id). It runs in order with the notifications.

Directories

Path Synopsis
Package blobmsg encodes and decodes the blobmsg format, the typed, self-describing message encoding used by ubus.
Package blobmsg encodes and decodes the blobmsg format, the typed, self-describing message encoding used by ubus.
compat
benchgo command
Command benchgo is the Go half of the ubusio vs libubus benchmark (compat/bench.sh).
Command benchgo is the Go half of the ubusio vs libubus benchmark (compat/bench.sh).
size/base command
Command base stands for an existing Go daemon: net, encoding/json, fmt and context without ubusio.
Command base stands for an existing Go daemon: net, encoding/json, fmt and context without ubusio.
size/full command
Command full is base plus a ubusio connection and one call.
Command full is base plus a ubusio connection and one call.
size/hello command
Command hello is the floor: the Go runtime and os only.
Command hello is the floor: the Go runtime and os only.
size/httpbase command
Command httpbase is base plus net/http (a daemon with an HTTP server).
Command httpbase is base plus net/http (a daemon with an HTTP server).
size/httpfull command
Command httpfull is httpbase plus a ubusio connection and one call.
Command httpfull is httpbase plus a ubusio connection and one call.
size/minicall command
Command minicall is the smallest useful ubusio client: connect, call one method, print the reply.
Command minicall is the smallest useful ubusio client: connect, call one method, print the reply.
internal
blob
Package blob implements the raw blob attribute framing shared by the ubus message layer and the blobmsg encoding.
Package blob implements the raw blob attribute framing shared by the ubus message layer and the blobmsg encoding.
fakeubusd
Package fakeubusd is an in-process stand-in for ubusd used by unit tests on hosts where the real daemon is not available.
Package fakeubusd is an in-process stand-in for ubusd used by unit tests on hosts where the real daemon is not available.
scripts
apidiff command
Command apidiff prints the exported API of the package in the current directory, one item per line, so that two versions can be compared (see scripts/apidiff.sh).
Command apidiff prints the exported API of the package in the current directory, one item per line, so that two versions can be compared (see scripts/apidiff.sh).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL