openwrt-iac / uapi / docs / 4.0.1 / uapi architecture

uapi architecture

Reader-facing technical overview. The design contract lives in CLAUDE.md; this document explains the current shape of the implementation: where state lives, how a request is served, what locks are held when, how ETags are computed, how rate limits and metrics are stored, what the failure modes are.

Process model

uapi is not a daemon. There is no uapi process. There is no uapid, no procd service definition, no procmon entry.

The code runs inside uhttpd's existing fork-per-request CGI workers via uhttpd-mod-ucode. A single list ucode_prefix '/api/v4=/usr/share/uapi/main.uc' entry in /etc/config/uhttpd is the entire wiring.

Specifically, uapi shares the default main uhttpd instance with LuCI. Both serve configuration use cases; sharing keeps the footprint minimal and lets uapi inherit whatever TLS configuration the operator already set up for LuCI (acme certs, custom listen addresses, etc.). A dedicated uapi uhttpd instance was considered and rejected: it doubles the runtime cost without earning the isolation back (an attacker who can reach LuCI can already reach the same box).

                         uhttpd parent (always running)
                         ├── compiles main.uc once at startup
                         ├── module-level state warm in parent VM
                         │   (RESOURCES, SINGLETONS, RESOURCE_SOURCES,
                         │    BARE_RESOURCES, BARE_SINGLETONS, VERSION,
                         │    LOGGING)
                         │
        client ─HTTP─►  forks a child per request
                         │
                         child
                         ├── inherits parent VM via copy-on-write
                         ├── handle_request(env) runs
                         ├── any mutation is private to this fork
                         └── exit(0)

Validated in tests/integration/01_concurrency_model_test.sh: 5 concurrent requests against a sleeping endpoint observe at least 2 distinct PIDs (the assertion's floor; uhttpd caps concurrent CGI children at 3), total wall time ≈ 1-2s instead of ≈ 5s.

What this buys us

What it costs

Lock layout

Two flock files, used in three patterns:

/var/lock/uapi.lock                   shared by uci transactions,
                                       exclusive by non-uci writes (apk,
                                       password, authorized_keys, cron_jobs)
/var/lock/uapi.pkg.<package>.lock     exclusive per-package; serializes
                                       writes to the same uci package only
Operation Global lock Per-package lock
Read (any) none none
Token last-used stamp (rides on an authed request, throttled to 60s) SH EX on uapi
uci write (any one pkg) SH EX on that one pkg
uci write that restarts unbound (unbound_srv, unbound_ext), or that can reload it (dhcp, and system but not system/timeservers, while /etc/init.d/unbound exists) SH EX on that pkg and on unbound
uci write (multi pkg, /uapi/batch) SH EX on each, sorted lexicographic order
POST /uapi/services/{name}/recover SH EX on each package whose writes reload the service, sorted
Non-uci write (apk, system/password, system/authorized_keys, system/cron_jobs) EX none

The interactions:

All locks are non-blocking (LOCK_NB); contention surfaces as 423 locked so the client can decide whether to back off and retry. The HTTP worker never waits for a uapi lock, but libuci's own flocks on a package file block while LuCI or a shell holds them. It can sleep while it holds a uapi lock: it waits up to 20 s in all for the reloads of a request, the stay-up watch of an unbound reload polls for up to 2 s under the transaction's locks, the dnsmasq --test check of each instance runs for up to 10 s, and the respawn check of a dnsmasq reload waits 1 s, then can stop and start dnsmasq within what is left of the 20 s. POST /uapi/services/{name}/recover holds its locks across one such stop and start, 10 s at most. The restore after a failed reload also waits, for up to 5 s, for libuci's flock on the package file. A load holds that flock while it parses the file, and a uci commit while it reads the file again, writes its temp file and syncs it.

Audit and verification: docs/lock-state-audit.md covers every site in src/ and cli/ that takes an fd, a pipe, a lock, a ubus connection or a uci cursor, with proof of release on every in-request exit path including die(). It also says what runs while each lock is held and what a killed request leaves behind. make lint-lock-audit fails when a site is missing from it.

Transaction recipe

Every write request follows this sequence. Failure at any step short-circuits without uci state change.

  1. Pre-flight checks. For each entry in the resource's reload list, confirm /etc/init.d/<svc> exists and the name matches ^[A-Za-z0-9_-]+$. Miss → 503 init_script_missing with the missing path; no uci write attempted. A service in the resource's reload_if_running list, a daemon that reads the package but that an image can lack or that the operator stopped, such as dnsmasq, odhcpd and unbound for the dhcp writes, is kept when its init script exists. Under the locks of step 1, it joins the reload when a verbose service list shows a config.change trigger for it. That matches a LuCI save, whose commit fires each such trigger that procd holds, whatever the instances of the daemon show. procd holds them from the start of the service to its stop, which removes them, so a write starts again a daemon that crashed too often, and starts dnsmasq when it enables a dnsmasq section while every other one is disabled, as the save does. At boot, unbound.init registers only a trigger on interface events, which starts unbound 3 s after the last of them, so neither starts it earlier. Any config trigger counts, not only one on the package written, because a system write reaches unbound only through ucitrack's affects. Otherwise the daemon is skipped, so it never answers 503, and a reload does not start a daemon that the operator stopped, as the reload of dnsmasq.init and unbound.init would. When the service list call fails, uapi cannot tell, and reloads it. Then confirm /etc/config/<package> exists, because the uci cursor stores nothing in a missing file and reports that only through a null return. Miss → 503 config_missing with the path. A DELETE checks the file first and answers 404 not_found for a missing one, because no section can exist there, and a client reads a 404 on DELETE as already gone. A POST /uapi/batch answers the 503 for a DELETE too, because it commits as one write.
  2. Acquire flock. SH on global + EX on the per-package file (non-blocking), and EX on unbound when one of the reload services, or of the reload_if_running services that step 0 kept, restarts unbound, as unbound and unbound-uci-ext do. EWOULDBLOCK → 423 locked + Retry-After: 1. Then the service list of step 0 runs for each kept service.
  3. Unload. uci_unload(<package>) drops the copy of the package that the preview before the lock loaded into the cursor, which serves every later read from that copy, so a commit by LuCI or a shell in between was invisible to the write.
  4. Validate. check_schema_types, the resource's validate(json, conn, id, delta, partial) and validate_new(json, conn) where a resource has one run inside the lock over the section as the write leaves it, so a stored value that breaks a rule fails the write too (docs/adding-a-resource.md). Any field error → 422 validation_failed with the full set of field errors (not fail-fast), and uci does not change.
  5. Stage. uci_set / uci_create_section / uci_delete mutate the cursor's copy of the package, and bus.uc keeps the writes in order. Nothing is staged outside the request process (see below). A PUT and a PATCH skip a set of the value that uci already holds, a delete of an option that it does not hold, and a default that the read fills in for an option that uci does not hold, such as the enabled '1' that a POST or a LuCI flag leaves out. So one that changes nothing has nothing to commit, and it collects no kernel operations. A PUT of the read still writes what it stores in another form than uci holds, such as a list that uci holds as an option or a number in hex, and the PUT of the read after it changes nothing. A PUT and a PATCH also stage a check that the section still exists, see step 5. The response body is fromUci of the section read back from that copy. So a write answers the body, apart from runtime, and the ETag that a GET then answers, unless another writer commits to the package while the request runs. runtime is read before the reload, and the commit replays the writes over such a commit, which the body does not show. network/wireguard_peers diverges: its runtime comes from wg show, which only a GET runs (read_runtime), so a write answers runtime: {} and reads no kernel state under the lock. Read in fn, it would come from before the kernel apply of step 7, and the write would answer as drift what the apply then changes. A GET in a /uapi/batch that writes answers {} for the same reason, since every sub-request runs before the apply of the batch.
  6. Snapshot and commit. uci_export(<package>) captures the package file into an in-memory string, the snapshot that step 8 restores. When the request wrote to the package, uci_commit(<package>) then loads the package file again, replays the writes over it and writes it through libuci, so a commit by LuCI or a shell while the request ran is kept. The snapshot is taken here, and not at the lock, so that it holds such a commit too, and the restore of step 8 keeps it. Taken at the lock, it put back the file from before such a commit. A commit by another writer between the snapshot and the load of the commit, a few microseconds, is still lost on a restore, as one between that load and libuci's write is lost by every commit. After a commit that wrote, the request reads the file again: that is what it committed, which step 8 compares with, since ucode-mod-uci cannot export what libuci wrote. A commit by another writer between libuci's rename and that read, a few microseconds, reads as the request's own and is lost on a restore. A request that staged only the check of a section loads the file and runs the check, and writes nothing. A replay that no longer applies, or a section that another writer deleted since the request read it, → 409 conflict, and nothing is written. Without the check, a PUT or a PATCH that changed nothing answered 200 for a section that another writer had deleted. A commit that libuci refuses, as on a full overlay, → 500 internal_error. Either way the cursor drops its copy of the package, so nothing later in the request reads the writes that the file does not hold. A request that wrote nothing commits nothing, and skips steps 6 and 7: X-Reload-Status: no_reload, X-Kernel-Status: no_kernel.
  7. Reload. /etc/init.d/<svc> reload per reload_services, exit code checked. Done directly (NOT through ubus) because ubus-mediated reload is fire-and-forget on OpenWrt; only wait4 on a real child gives back the actual exit bit. One shell runs the scripts in order, in the background, with stdin on /dev/null and the output of each in an unlinked file from fs.mkstemp, which is the only one of these files that the script holds. It stops at the first that fails, and writes the exit code of each to another such file, which uapi reads every 20 ms. uapi writes that file full of spaces first, so that the codes land in bytes that the file already holds on a tmpfs that the output of a script has filled, and a file that it cannot fill, or a shell that cannot start the scripts, fails the write. uapi waits for the reloads of a request, those of the restore included, for 20 s in all, and does not kill a reload that runs longer. Such a reload is no failure: the write keeps its commit, runs no stay-up watch and no dnsmasq --test check, since the reload may not have written the config yet, runs the kernel apply, and answers 2xx with X-Reload-Status: unverified. The reloads after it run when it ends, unless it fails. A reload of the restore still running then answers reload_failed_unrecovered, since uapi cannot say that the daemons run the restored config. Through fs.popen, a script that did not end, or a process that it left running with the pipe open, held the request and its locks until uhttpd killed the request at its 60 s script timeout, with no restore and no answer from uapi. Killing the script at a bound does not help: procd_lock of rc.common keeps the lock of the service in the children of the script, such as fw4, so the reload of the restore waited for them and was killed too. system() with a timeout also blocks SIGCHLD in its child, which a script that runs x & wait never sees, so uapi starts the shell with a system() that waits only for the shell that puts the scripts in the background. 20 s of reloads, the checks and the flock wait of a restore fit in the 60 s, see docs/operations.md. procd starts the daemon with its new config on its own, so the init script exits 0 before the daemon has read that config, and a daemon that refuses it stops later. For the reloads that STAY_UP in src/lib/transaction.uc lists, which are unbound, also when a dhcp or system write reloads it, and unbound-uci-ext, the write then watches the procd instances of the daemon that ran before it. It polls service list every 100 ms for 2 s, and an instance that procd reports as not running counts as a failed reload. An instance that service list does not show is being restarted, and does not count. The restore runs the same check. A reload of dnsmasq by a write that commits dhcp is judged by its config instead, because the reload_service() of dnsmasq.init sends SIGHUP right after procd restarts an instance, and on a slow machine that signal can stop the new process for 5 s with a config that dnsmasq takes. The init script writes the config of each instance before it returns. For each instance that service list shows before or after the reload, the write runs its command with --test, and a refusal counts as a failed reload. That includes an instance that is not running, which procd starts on that config, so a config that dnsmasq refused before the write fails the restore too, as reload_failed_unrecovered. fs.popen has no time bound, so the check runs through system() with a timeout of 10 s, its output in a file from fs.mkstemp. A --test that cannot run, because fork fails or no file can be made, counts as a refusal. One that SIGKILL stopped, the timeout or another, judges nothing: the write keeps its commit and answers X-Reload-Status: unverified. A system write reloads dnsmasq too and runs no --test, so that a config that dnsmasq refused before, or a slow parse, cannot fail or undo it. --test parses the config and the files that it includes, and exits. A config that dnsmasq parses but cannot start with, such as two ports that conflict, a lease file in a missing directory or a port that another daemon holds, still answers 2xx. The restore runs the same check. No write waits for the daemon to start, and each pays one parse of the whole config per instance, which grows with its size, and again on a restore. procd counts each death of an instance that ran less than respawn_threshold (3600 s), those of the SIGHUP included, and a reload keeps the count. At the death that takes it above respawn_retry (5), procd clears the respawn of the instance and starts it again only on the next reload (instance_exit() in service/instance.c of procd), which can kill it in the same way. So after every reload of dnsmasq, by any write, uapi waits 1 s and reads service list. An instance that is not running and has no respawn table is one that procd gave up on. One that waits for its respawn keeps the table, so the usual death of the SIGHUP does not count. The reload starts again an instance that procd gave up on, so procd gave up on such an instance during this reload. The config passed, so the write does not restore: it finishes its own reload by another path, once per request. It runs /etc/init.d/dnsmasq stop, which frees the given-up instance at once, polls service list every 100 ms until procd lists no dnsmasq instance, and runs /etc/init.d/dnsmasq start, which sends no SIGHUP and makes instances that count from zero. Both scripts run through the reload shell above. The three steps take up to 3 s, 2 s and 5 s from what is left of the 20 s, and uapi skips them when less than 10 s are left, so they end within the 20 s. A stop still running after its 3 s gets no start, because a start that comes before the delete of the stop leaves dnsmasq out of procd. The write keeps its commit. It answers X-Reload-Status: ok when every instance that procd gave up on runs or waits for its respawn after the start, unverified when the start was still running after its 5 s, and stopped otherwise, with X-Reload-Stopped, which names each instance as dnsmasq/<instance>, also beside unverified. syslog gets uapi-dnsmasq-recovery with the request id and the outcome. On a restore, a dnsmasq that stays down after the one stop and start of the request fails the restore. GET /uapi/diagnostics lists every instance without its respawn table, of the services that POST /uapi/services/{name}/recover takes, as stopped_instances. See Service recovery.
  8. Kernel apply. It takes the peer operations that the write collected (see below), and a check of each interface that a write of network/interfaces leaves on proto wireguard, since netifd restarts it. For each of these interfaces that is enabled, it first asks the peer resource which enabled peers, as the write committed them, hold a value for which wg refuses the config of the whole interface: a live error of the peer, an allowed IP that wg cannot parse, or a link-local %zone that names no interface of the router, which it looks up in /sys/class/net. The proto handler gives wg every peer of the interface at once, so one such peer keeps the interface down, and a wait for its restart cannot tell a restart that the write broke from one that was broken before it. So the write keeps its commit, runs no restore, and answers X-Kernel-Status: blocked with X-Kernel-Blocked, which names each such peer. The apply skips the interface with no wait, and netifd sets the peers from uci at its next setup. A write that fixes, disables or deletes the peer finds none and goes on as below. A check sets no peer.

For each peer operation of an interface that no such peer holds, skip it unless network.interface.<name> reports up, then run the matching wg set. The proto handler restarts a wireguard interface on every peer change, so the check first waits for a setup that is in flight to finish: without the wait the write's own reload would leave the interface mid-cycle, the apply would skip, and netifd would re-apply the peers from uci, which turns a peer that wg refuses into a committed section and a setup_failed interface instead of the 500 below. The waits of an apply end at one deadline 8 s after it starts, whatever the number of interfaces, and those of the reconcile of its restore at another. An interface that reads down with no setup pending twice, half a second apart, skips. A setup that never settles fails a write that sets a peer, with a restore, so the caller gets the 500 for a peer that the platform refuses. A write whose operations on the interface only remove peers, a DELETE or a write that disables them, skips the interface instead and keeps its commit: the next setup reads uci, which no longer holds them, and a restore would give back their access. Since openwrt ecd9120f04, which fixed openwrt/openwrt#24511, the handler leaves out a key, a preshared key, an endpoint or a keepalive that wg would refuse. Three values still keep the interface from settling: an allowed IP that wg refuses, an endpoint host of digits and dots that inet_aton does not read, such as 10.0.0.256, which the handler gives wg as an address, and an IPv6 host that musl refuses. A write refuses each of them that it sends. The apply sets a peer as the handler does, without the endpoint of a host that does not resolve, and answers X-Kernel-Status: omitted. Runs only after the reload returned zero, and reports the same way, so a failure here follows the recipe below. The interfaces actually applied are recorded and reported on the response as X-Kernel-Status and X-Kernel-Applied (docs/errors.md § Response headers), because a skip leaves the peer in uci alone and a caller otherwise cannot tell that from a write that reached the kernel. 8. On reload, stay-up check or apply non-zero: uci_import(<package>, snapshot) → reload, then reconcile each touched interface against the restored uci. Then 500 reload_failed_restored with the captured stderr/exit summary. If the restore itself fails, 500 reload_failed_unrecovered. uci_import writes the snapshot to .<package>.uapi-restore beside the file that the package names, the target of a symlink included, reads it back, because ucode reports no error from close(), and renames it over that file. A kill or a full overlay leaves the package whole, and a restore that cannot write or rename the file answers reload_failed_unrecovered with a restore_error that names the file. Before it writes, the restore takes libuci's flock on the package file, which waits for a load or a commit in progress, and gives up after 5 s. That orders nothing after it: libuci releases the flock before its own rename, so a LuCI commit that held the lock, or waited on it with the old file open, can rename its file over the restored one, as one libuci commit can over another. Under that flock, the restore first compares the file with what the request committed. A commit by LuCI or a shell after step 5, while the daemons reload, goes into the file that the request committed, and the snapshot would undo it with the write. So a file that differs stays as that writer left it, with both writes, and the restore runs no reload and no reconcile and answers 500 reload_failed_unrecovered, whose restore_error names the package and says that another writer committed to it after the commit of the request. The daemons keep what the failed reload left them. The check has the gap of the flock: a commit that libuci renames between the check and the rename of the restore is still undone, as is one in the window of step 5. A file that uapi could not read for the snapshot or after the commit stays as it is too, with a restore_error that says so. ucode has no fsync, so the rename holds against a kill but not against a power cut on a filesystem that writes data back later than the rename, such as ubifs. 9. On success: 200 with the refreshed resource.

Changes that another writer staged

A read reports what the package file holds, and a write commits only its own changes. A shell stages with uci set in /tmp/.uci, and LuCI stages in a directory per session, /var/run/rpcd/uci-<session>. libuci overlays onto a package that it loads by name the delta file of that name in each directory of its search path, and /tmp/.uci is always in that path: ucode's cursor() adds a delta directory but cannot remove that one. rpcd clears the list itself, which ucode cannot. So bus.uc loads each package by its path, which reads the file alone. A uapi write then neither commits nor deletes what a shell staged, and a later uci commit in the shell replays it over what uapi committed.

This also differs from libuci in one place. A load by name reads /var/run/uci/<package>, libuci's override directory, in place of /etc/config/<package> when that file exists, and a commit by name writes there. uapi reads, writes and restores /etc/config/<package> only. Among the package files of the OpenWrt feeds, only procd's reload_config reads /var/run/uci, and nothing writes it. A package that does not load by its path fails the call rather than fall back to a load by name: a read answers null and a write fails. That includes a name that libuci does not load by name, one that starts with a dot or holds a slash, so the temp files of libuci and of the restore are no packages.

libuci commits a package loaded by path by writing the copy that the cursor holds, without reading the file again. The commit of step 5 therefore reloads the file and replays the request's writes, which keeps a commit by another writer that landed while the request ran, as libuci's own replay of a delta does. A replay that no longer applies, because another writer deleted a section that the request wrote into, or that a PUT or a PATCH addressed without writing to it, fails the commit, and the request answers 409 conflict with a message that names the package. A package that the request did not write is not committed, as libuci skips a commit with no changes, so its comments stay, and it gets no reload and no restore. uci_revert and uci_unload drop the copy and the writes, which is the whole of what the request staged.

Why step 7 exists, and why it shells out to wg

The proto handler of wireguard reads the peers of an interface from their own wireguard_<iface> sections, with the config of the interface, so a reload restarts the interface on every peer change and gives wg every peer at once. wg refuses that whole config for one value that it cannot read, so one bad peer keeps the interface down, and the reload reports nothing about it: the write would answer 200 over a committed section and an interface in setup_failed. The wireguard handler is the only proto handler that reads its own uci sections, so this affects exactly one resource.

Why not ask netifd to re-apply. ubus call network.interface.<i> renew returns in 0 ms, so a failed apply is undetectable, and on failure the proto handler calls setup_failed, which takes the interface down: one bad peer drops a working tunnel and its healthy peers. A down+up restart behaves identically and additionally interrupts a healthy tunnel on every peer edit. Every netifd-mediated path applies the whole interface config as one unit, so one bad peer takes the innocent ones with it.

wg set is the only per-peer path: it is atomic, so a bad endpoint fails that one command and changes nothing, it reports a real exit code, and it leaves the rest of the tunnel running. WireGuard exposes no ubus service for peers (wireguard offers only status/genkey/genpsk/pubkey), which is why netifd itself shells out to wg syncconf and LuCI's own backend shells out to wg. Running wg is therefore not a way around the platform's abstraction for peers, it is the platform's abstraction for peers. uci remains the only config writer, the kernel state is derived from committed uci rather than from the request, and nothing new runs in the background.

src/lib/wg.uc makes every value safe for the shell itself, on the value as uci stores it, because the restore after a failed write reads the peers straight from uci, where a value never passed validate(). Every wg and ip command is an argument list, and run() quotes each argument with shellquote, so no caller can forget one. wg.uc also checks the values before it runs a command: route_prefix keeps an address or a CIDR and drops anything else, and the interface and table names must match ^[A-Za-z0-9_-]+$. The checks alone were not enough: a prefix such as ::/0;id>x; passed route_prefix, because the IPv6 prefix length was read with int(), and ip route took it unquoted. A preshared key is passed as a 0600 file on tmpfs, never as an argument, so it never appears in ps.

route_allowed_ips asks for a route per allowed IP, which netifd installs from the proto handler, so the apply installs them too: without that the peer is in the kernel with no path to it and the flag only half works. They are spelled to match netifd exactly (proto static, scope link on v4) and go into ip4table / ip6table when the interface sets one, since netifd puts them there rather than in main. A route is the prefix as netifd installs it: the length as netifd reads it, and the address masked to that length. The handler routes each entry as uci holds it, past a # and a comma that wg reads, so a write takes the entries of the section as it stages it: a PATCH that leaves allowed_ips as it is keeps an option whose routes can differ from the allowed IPs of the read. Routes are compared in that one spelling, so a respelled prefix, or the spelling that the kernel prints, is the same route. A prefix is only withdrawn when no remaining peer and no config route section still wants it, because two peers can carry overlapping allowed_ips. The kernel is never scanned for strays on the request path, only on the reconcile that follows a rollback, so a route uapi did not install is not at risk.

The proto handler, /lib/netifd/proto/wireguard.uc of wireguard-tools, gives wg each value as uci holds it, and expands no escape. It takes a list of allowed IPs as its entries and an option as its words, and it routes each of them. A route takes the address before the first / and the length that ucode's int() reads after it. The handler leaves out a peer without a key, with its routes, and takes disabled and route_allowed_ips as on only when they hold 1. Since openwrt ecd9120f04 it also checks a peer value against the grammar of wg, as uci holds it, and leaves out what wg would refuse: the peer, with its routes, for a key that is not a WireGuard key, and the line for a preshared key, an endpoint or a keepalive. It gives wg an endpoint host of digits and dots as it stands, so wg still refuses the whole config for one that inet_aton does not read, such as 10.0.0.256. An endpoint port is 1 to 65535 in digits or the first field of a /udp line of /etc/services, and an empty one leaves the endpoint out. A peer with a host and no port gets port 51820. The read, the kernel apply, the routes and the reconcile take these rules from wg.uc. So a GET reports an entry that wg refuses as that one entry.

One consequence to know: netifd reports the routes it installs in network.interface.<name> status, and routes installed here are not in that list until the next ifup. The kernel is correct; netifd's bookkeeping lags.

A resource opts in with a kernel_ops(kind, opts, sec_type, existing, staged) hook returning the operations to apply, where staged is the section as the write leaves it in uci. network/interfaces returns a check of the interface, which sets no peer, when the write leaves it on proto wireguard. The hook of network/wireguard_peers reads the uci options rather than the resource view because the view masks preshared_key, and the parent interface off the section type because it is not stored as an option, so a DELETE can only learn it from the section it is about to remove. A rotated public key emits a remove for the old key before the set, or the kernel would keep the previous peer and its access. A disabled peer is removed, matching what netifd omits when it builds the config. A remove takes the stored public_key as the handler gives it to wg, and the kernel holds no peer under a value that is not a WireGuard key. The kernel holds one peer per key, so a remove then sets again each other enabled section of the interface that holds the key, in uci order, as ifup does. A set, in a write or in the reconcile after a failed write, skips a peer whose stored key is not a WireGuard key, as the handler does. The handler runs a peer whose stored preshared_key is not one without a preshared key, so the set gives wg /dev/null for it, as the restart of the handler left it.

An interface that is down, or that netifd does not know, is skipped: there is no kernel state to sync and ifup reads the peers from uci anyway. That is also what keeps a peer orphaned by deleting its parent interface deletable.

Multi-package transactions (/uapi/batch)

POST /uapi/batch composes N sub-requests under one combined snapshot/restore:

  1. Pre-resolve every sub-request's target (path → package + reload services), and check its scope, before the pre-flight checks: their 503 would tell a token whether a package that it has no scope for is installed. An operation out of scope aborts the batch with its 403 before anything runs.
  2. Only WRITE sub-requests contribute to the lock/reload set. Pure-read batches skip lock+snapshot+commit+reload entirely.
  3. Acquire global SH + per-package EX in sorted package order (deadlock-free), unbound included as in step 1 of the single-package recipe, then ask procd which reload_if_running services to reload.
  4. uci_unload() each package, as in step 2 of the single-package recipe. Each commit of step 7 takes the snapshot of its package right before it, as in step 5.
  5. Run each sub-request in order via BARE_RESOURCES/BARE_SINGLETONS - handlers that skip their own per-package flock + snapshot + commit + reload (since the outer multi_transaction has those covered).
  6. First sub-request status ≥ 400 → abort: uci_revert() each package, return { code: "batch_partial_failure", aborted_at_index, error: ..., reverted: true } with the failing sub's status.
  7. All sub-requests 2xx → uci_commit() each package, run the union of the reload services of the packages that the batch committed, then the collected kernel operations. A PUT or a PATCH that changes nothing writes nothing, as in step 4 of the single-package recipe, and a batch that committed nothing runs neither. Same failure recipe as the single-package transaction, and a commit that fails part way counts as a failed reload. Either way only the packages that the batch committed are restored: the snapshot of another one would undo what LuCI or a shell committed to it since, such as the delete that made the replay of the batch fail. Of those, a package that another writer committed to after the batch did stays as in step 8, and the batch answers reload_failed_unrecovered naming it. The restore reloads and checks the daemons of the packages that it wrote back only, and reconciles the kernel only when it wrote network back, so a package that it left is not reloaded on the config that just failed. A restore that wrote no file back runs no reload. Each other package is reverted before that, so that the cursor holds no write that uci did not store, and a reconcile reads network from the file. A commit that fails stops there, with no reload and no reconcile: both come after every commit, so neither ran, and the restore puts a package that the batch committed before the failure back before uapi reloads it. A replay that no longer applies then answers 409 conflict, and a commit that libuci refuses answers 500 reload_failed_restored. Sub-requests accumulate into one ordered operation list shared through their sub-context, so a batch touching the same peer twice ends on its last state, and the restore reconciles rather than replaying, since a batch can apply several peers before failing on a later one.

Service recovery (/uapi/services/{name}/recover)

The write path stops and starts dnsmasq once when procd gave up on it after the reload (step 6). A client that only speaks HTTP has no other way to do it after X-Reload-Status: stopped, and a write that changes nothing runs no init script by design, so that a plan with no change has no side effect. POST /uapi/services/{name}/recover runs the same steps on request, through the same recover() of src/lib/transaction.uc:

  1. Look up {name} in RECOVERABLE: the services that uapi reloads and whose init script sets procd_set_param respawn on every instance that it starts. network, uhttpd and dropbear qualify, and are left out, because the stop acts on the whole service. A stop of network or uhttpd cuts off the request, and a stop of dropbear stops the instance that serves the management SSH session, which a start that fails leaves down. Another name answers 404.
  2. Check the scope: uapi:services:rw, or rw on a domain of a resource whose reload or reload_if_running lists the service. recover_targets() derives the domains and the packages from the resource modules, so a new resource that reloads a service extends both.
  3. Take SH on the global and EX on each of those packages, in sorted order, as a write of them does. A write that reloads the service between the stop and the start would start it while procd still holds the instances of the stop. Contention answers 423.
  4. Read service list for the service. An instance that is not running and has no respawn table is one that procd gave up on. With none, stop and start nothing and answer 200 with an empty recovered, so a retry, a service that runs and one that the operator stopped stay as they are.
  5. Otherwise run stop, wait until procd lists no instance, and run start, with the bounds of step 6, taken from reload_budget_s. The stop and the start act on the whole service, so its other instances restart too.
  6. Read service list again. 200 when every instance of step 4 runs, with recovered naming them. Otherwise 500 recover_failed, with service, stopped and the reason. After a start that ran past its 5 s, the instances are read again rather than judged unknown.

service list cannot tell an instance that procd gave up on from one that has no respawn and ended: instance_exit() clears respawn when it gives up and sets halt, and instance_dump() writes the respawn table only while respawn is set, and never writes halt (service/instance.c of procd 58eb263). So stopped_instances lists only the services of RECOVERABLE, whose instances all have respawn, and a one-shot instance of another service that ended is not reported.

Schema layer

Every resource module exports schema_properties. handler.check_schema_types walks it on every write to enforce:

A PATCH schema-checks the section that it leaves, as a PUT does: the read of the stored section with the request merged in, for a merge PATCH and a JSON Patch alike. That is the read that the sweep checks, so a stored value that breaks a type, an enum, a bound, a pattern or the newline rule fails the write as it fails the sweep, whichever fields the request names. The schema declares what the platform takes, which a read can give, so a value that LuCI or the daemon takes is no error. A keyword under x-uapi-write can narrow what a write may send: the handler checks the fields that the request names against those keywords too, and a stored value past them blocks nothing. A field that the request sends back as the read gives it changes nothing, so those keywords do not judge it, and a PUT of the read passes. A PUT reads the stored section for that comparison only when a keyword refuses a value. Where the read bound and the request bound refuse a sent value with one code, the error gives the message of the request bound. The id of a stored section is left out, since LuCI names sections that the id pattern of a create refuses, such as 4g. The write-only secrets that the handler carries from uci are left out, because the read masks them. The full merged body, secrets included, goes through resource.validate() and validate_new(), next to the fields that the request names, for a rule about the request rather than the section. docs/adding-a-resource.md says when to use which.

Unmodeled uci options: PUT replaces, PATCH preserves

A resource module curates a subset of its uci section's options; toUci emits only those. The write path treats options outside that modeled set differently per verb:

A consequence: the GET-then-PATCH-self round trip is lossless even for options uapi does not model, but GET-then-PUT-self is not (PUT discards them). Tooling that wants to preserve unmodeled state must use PATCH.

Field errors are deduped by (field, code). Schema errors win over validator errors for the same (field, code) tuple. A validate_new() error is dropped only when one of them has its (field, code): each of its rules on a field is its own error, so that one cannot hide another. The newline refusal of the schema check gives way to a validate_new() error with its code on its field, or on the list that holds it (nasid[1] gives way to nasid), which says why the daemon cares and carries live. The request schema check comes last, so a rule that refuses the same value names it. The 422 body carries the full set, so a client fixes everything in one round trip.

ETag derivation

ETag = sha256(canonical_json(body_without_runtime)), truncated to 12 hex chars.

body_without_runtime strips the resource's runtime block before hashing. Runtime fields are live ubus/file state (uptime, signal, lease count) that drifts second-to-second on unchanged config; including them would make ETags non-deterministic and trip spurious 412s.

ETag is per-resource: a function of this section's content only. Sibling sections in the same uci package do not influence each other's ETags, so If-Match fires only when the resource the client is updating has actually changed. (Cross-reference invariants like "rule's src_zone must exist" are enforced at resource.validate() time on every write, not via ETag mixing.)

Two GETs of the same unchanged section always return the same ETag.

Multi-resource collection endpoints (GET /firewall/rules without an id) do not currently carry an ETag. If-Match and If-None-Match only fire on resource-level endpoints; collections operate last-write-wins.

Conditional GET

If-None-Match: "<etag>" (or ?if_none_match=) on a GET: when the response ETag matches, return 304 Not Modified with no body and the ETag header echoed. Cheaper for polling clients (Terraform refresh, dashboards).

If-Match writes (precondition_check)

PUT/PATCH/DELETE with If-Match: "<etag>" (or ?if_match=): when the current ETag doesn't match, return 412 precondition_failed BEFORE any uci write. If-Match: * matches any existing resource. Absent header preserves last-write-wins (opt-in concurrency).

uhttpd-mod-ucode sets an HTTP_* variable only for a fixed list of headers, and If-Match, If-None-Match, X-Request-Id and Idempotency-Key are not on it. It also gives every request header in env.headers, with its name in lower case, and errors.request_context reads the four from there. Each one has a query form for a client that cannot set a header: ?if_match=, ?if_none_match=, ?request_id= and ?idempotency_key=. A header that is not empty wins over its query form, and an X-Request-Id header only when it matches ^[A-Za-z0-9_-]{8,128}$. uhttpd gives an empty header as "", so without that rule an empty If-Match: would turn off the precondition of ?if_match=.

Rate limit token bucket

Per-token bucket, file-backed at /var/run/uapi-ratelimit/<token-id>.txt containing a float and an integer: <tokens_remaining> <last_refill_epoch_ms>. A token name holds up to 63 characters over HTTP and any number with uapi-token, and a file name holds 255 bytes, so a name longer than 63 characters is replaced by its sha256 in the file name (state_dir.token_file). The last-used sentinel is named the same way.

On each authed request:

elapsed_ms = now_ms - last_refill
refilled = min(burst, tokens + elapsed_ms * rate / 1000)
if refilled >= 1: allow, tokens = refilled - 1
else:             deny, retry_after = floor((1 - refilled) * 1000 / rate) + 1
write {tokens, last_refill = now_ms} atomically (tmpfile + rename)

Default rate 100/s, burst 200. Configurable via config ratelimit { option rate '...'; option burst '...' } in /etc/config/uapi. Atomic-write (tmpfile + rename) avoids flock contention on the hot path; the worst-case race is one request's worth of drift across concurrent forks, bounded by the burst size.

Worked example: default config, a client sends 250 req/s sustained against one token. Burst absorbs the first 200; the next 50 spaced over 1s exhaust the bucket at 100/s. Steady-state: 100/s through, 150/s rate-limited → 429.

Metrics

File-backed under /var/run/uapi-metrics/. One file per (series, label-set) combination:

/var/run/uapi-metrics/
  uapi_requests_total/
    method=GET/path=%2Ffirewall%2Frules/status=200/token_id=tf_prod.txt   "1247\n"
    method=POST/path=%2Ffirewall%2Frules/status=422/token_id=tf_prod.txt  "13\n"
  uapi_request_duration_seconds_bucket/
    le=0.01/method=GET/path=%2Ffirewall%2Frules.txt
    ...
  uapi_rate_limit_drops_total/
    token_id=ci_bot.txt

Path segments (/ in label values) are percent-encoded as %2F to keep filenames safe; decoded back when emitting. Increments are read-modify-write with atomic rename; concurrent forks may lose increments under heavy contention - acceptable for operational metrics, not for billing.

A token mint and a token revoke, over HTTP and with uapi-token, run token_store.reap_state under the lock of the uapi package. A mint, over HTTP and with uapi-token create, runs it before its commit, so that a request that uhttpd kills during the reap cannot lose the bearer of a token that it committed. A revoke runs it after its commit. The bucket and the last-used sentinel of each token that no longer authenticates are unlinked, and each of its uapi_requests_total and uapi_rate_limit_drops_total files is added to the file with the same other labels and token_id=-retired, then unlinked once the add is on disk. A token that revokes itself records its revoke after the fold, and a request of a token in flight at its revoke can write its bucket, sentinel or series after the reap, so those wait for the next mint or revoke. docs/operations.md § Metrics says what a scrape sees.

A counter is written to a temp file, which is renamed over it only when its size on disk is the size of the line, and a counter file that holds no count is left out of a scrape and starts again at its next increment.

GET /uapi/metrics walks the tree, decodes the labels, emits Prometheus 0.0.4 text. Path templates are normalized (/firewall/rules/:id not /firewall/rules/r_01HX...) to keep cardinality bounded as clients create/destroy resources. A path that no route serves is recorded as path="unmatched", and a /raw path keeps its package only when /etc/config holds it (metrics.path_label).

Idempotency cache

POST requests carrying Idempotency-Key (header or ?idempotency_key=) are deduplicated for 24 h:

key = sha256(token_name || "|" || key)
file: /var/run/uapi-idempotency/<key>.json
contents: {
    fingerprint: sha256(token || "|" || key || "|" || body_text),
    status, headers, body
}

On second arrival: - Same fingerprint → replay (Idempotent-Replayed: true marker header). - Different fingerprint → 409 idempotency_key_conflict. - Past TTL → cache miss; the new request runs and re-populates.

A key that does not match ^[A-Za-z0-9_-][A-Za-z0-9_.:-]{0,127}$ answers 400 bad_request, and the request does not run.

Cache hits skip the entire handler stack except auth and the rate limiter - the resource handler never runs. A client retrying a network-blipped POST gets the original response back, never a duplicate resource.

An entry can carry a secret, so it is written 0600 into a private directory, see Where state lives. A store writes its entry under a temp name of its own request process before the rename, so two stores of one key at the same moment each write a whole entry. A package install or upgrade removes the directory, so no entry of an older version stays. At most once an hour, a store removes the entries older than the TTL, so the directory holds the writes of about one TTL. A POST /uapi/batch that only reads stores no entry: replaying a read gives nothing that running it again does not give.

Audit and request_id

Every response carries X-Request-Id (a ULID by default; client-supplied via X-Request-Id header or ?request_id= query param, validated against ^[A-Za-z0-9_-]{8,128}$).

Each successful write, each 401 and 403, and each 5xx logs one syslog line that carries the request_id, so it ties a response to its line. A POST /uapi/batch logs one line for the whole request. docs/operations.md § Log categories and § Log line format have the categories and the format.

Where state lives

State Location Lifetime
Tokens (salted hash + meta) /etc/config/uapi Indefinite
uci configuration /etc/config/<package> Indefinite
Authorized SSH keys /etc/dropbear/authorized_keys Indefinite
Root crontab /etc/crontabs/root Indefinite
Package feeds /etc/apk/repositories.d/<name>.list Indefinite
Root password hash /etc/shadow, written by busybox passwd Indefinite
DHCP leases /tmp/dhcp.leases, ubus call dhcp ipv6leases of odhcpd Daemon-managed
Routing table names (read) /etc/iproute2/rt_tables Operator-managed, base-files conffile
Service names (read) /etc/services Operator-managed, base-files conffile
Rate-limit buckets /var/run/uapi-ratelimit/ Until the first mint or revoke after the token is revoked or expires, else until reboot. One that a request in flight at the revoke writes waits for the next
Idempotency cache /var/run/uapi-idempotency/ 24 h, removed by the next store after that
Metrics counters /var/run/uapi-metrics/ Until reboot. A token's series fold into token_id="-retired" at the first mint or revoke after it is revoked or expires. A token that revokes itself, or that has a request in flight at its revoke, keeps that series until the next
Recent errors /var/run/uapi-error-ring/ The last 20, until reboot
Token last-used sentinel /var/run/uapi-token-update/ Until the first mint or revoke after the token is revoked or expires, else until reboot. One that a request in flight at the revoke writes waits for the next
Interrupted-write journal /var/run/uapi-interrupted-writes/ Until reboot. Each record is named by the pid and the start time of its request process, and removed when its write returns. A write that throws or is killed keeps it, because its commit may have landed. A record whose process is gone, or whose pid another process now holds, is reported by /uapi/diagnostics under interrupted_writes
WireGuard preshared key /var/run/uapi.wg.psk, mode 0600 One wg set, unlinked when wg returns
Apk install lock (apk-internal) Per-operation
uapi global flock /var/lock/uapi.lock Per-transaction
uapi per-package flock /var/lock/uapi.pkg.<pkg>.lock Per-transaction

uapi keeps the rate-limit buckets, the idempotency cache, the metrics counters, the recent errors, the last-used sentinels and the interrupted-write journal under /var/run, in directories of mode 0700 with files of mode 0600. It uses one only when state_dir.owned() accepts it: a directory owned by the effective uid of the request process, that neither the group nor others can write. One of its own with another mode is narrowed to 0700. A package install or upgrade, after its uhttpd restart, removes these six directories and the four that an older uapi kept in /tmp, each when it is a directory that root owns. A request of the older version still in flight at the restart can write one of them again.

/var/run is tmpfs on OpenWrt, as /var is /tmp: rate-limit buckets, idempotency entries, metrics counters, recent errors, sentinels and interrupted-write records reset on reboot. This is acceptable: operational counters that span uptime aren't a uapi responsibility - point a node_exporter or central collector at the box and aggregate there.

GET /uapi/diagnostics reports in state_dirs whether uapi uses each of these directories, as it finds them. docs/operations.md § Diagnostics says what each value means and costs, and which directories the request itself creates before the read.