openwrt-iac / uapi / docs / 4.0.1 / Lock and resource-state audit

Lock and resource-state audit

This audit lists every site in src/ and cli/ that takes a file descriptor, a pipe, an flock, a ubus connection or a uci cursor. For each site it records which paths release the resource (normal return, early return, error, a propagated die()) and what happens on a path that does not.

uapi runs fork-per-request (docs/concurrency.md). A descriptor that a request does not close ends with the request process. That backstop does not cover a lock that a child process still holds, a lock held across a long operation, or a file left on disk, so those are what the proofs below look at.

ucode has no try/finally. The critical paths use this pattern:

let caught = null;
try { result = fn(); }
catch (e) { caught = e; }
release(resource);
if (caught != null) die(caught);

Reproducing the audit

grep -rnE '\.(open|fdopen|popen|opendir|mkstemp|pipe|writefile|lock|connect|cursor)\(|uloop\.|_lock_one\(|acquire[a-z_]*\(' src/ cli/

The alternatives catch, in order: fs.open and fs_mod.open, the other fs calls that return a handle or write a file, fd.lock, bus.connect and ubus_mod.connect, uci_mod.cursor, any use of uloop, and the lock entry points of src/lib/transaction.uc: _lock_one(, the injected acquire(, default_acquire_pkg(, and acquire_pkg_waiting(, which uapi-token calls.

The earlier command was grep -rn 'fs\.open\|fs\.popen\|\.lock(' src/ cli/. It found 36 lines, one of them a comment. It missed every ubus connection, every uci cursor, the two fs_mod.open calls of the snapshot and the restore in src/lib/bus.uc, and the places where multi_transaction(), transaction() and with_lock() take their locks, because those call _lock_one() or acquire() and not .lock( itself.

The pattern leaves out three things on purpose. fs.readfile and fs.lsdir return a value and hold nothing. Calls to transaction(), multi_transaction() and with_lock() from other modules take a lock, but they release it through the entry point's own proof, so they are listed by function in What runs while a lock is held rather than as sites. The ubus defer, subscriber and listener calls hold resources too, but nothing in the tree uses them. system() holds a child until it exits. default_reload() and run_bounded() call it, each on a line inside the row of its fs.mkstemp(). wep_support() in src/lib/bus.uc calls it for hostapd -vwep or wpa_supplicant -vwep, which holds no file and exits at once.

make lint-lock-audit runs the command above, as written here, and fails when a site is in no row of the table below, when a site is in two rows, when a row holds no site, or when a "covers all N sites" count in this file or in CLAUDE.md is not the number of lines the command prints.

Summary

This audit covers all 61 sites that the command finds. It used to cover 16 of the 36 lines that the earlier command found, and nine modules were absent from it: error_ring, idempotency, metrics, mgmt, ratelimit, token_store, dhcp.leases, dhcp.leases6 (since merged into dhcp.leases) and dhcp.servers.

Every descriptor, pipe and lock below is released on every in-request exit path. What the audit did find is listed under Open findings: a request that uhttpd kills can stop between its commit and its reload.

Sites

File Lines Resource Release proof
src/main.uc 109-115 fd, /usr/share/uapi/VERSION, at module load in the uhttpd parent A failed open returns "unknown" and holds nothing. Otherwise the fd is closed before the return.
src/main.uc 155-160 ubus connection and uci cursor, at module load in the uhttpd parent A failed connect is caught and the defaults are used. The connection is never disconnected, and a ucode ubus connection keeps a reference to itself, so it outlives the last script reference. It is closed by the ucv_gc() that uhttpd's ucode plugin runs once after it loads the handler, before the first fork. The handler loads before uhttpd calls uloop_init(), so the socket is never in uhttpd's event loop.
src/main.uc 333-350 ubus connection and uci cursor, /healthz A failed connect is caught and reported as degraded. Otherwise the connection lives until the request process exits, which closes the socket. Nothing else shares it.
src/main.uc 368-373 fd, /proc/uptime, /healthz A failed open skips the uptime. Otherwise the fd is closed right after one line is read.
src/main.uc 767-772 fd, /proc/uptime, /uapi/diagnostics Same shape.
src/main.uc 836-846 fd, /usr/share/uapi/openapi.json A failed open answers 404. Otherwise the fd is closed before the response is built.
src/main.uc 1048-1053 ubus connection and uci cursor, one per request A failed connect answers 503 and holds nothing. Otherwise both live until the request process exits. The cursor holds no file between calls, because libuci opens and closes the package file inside each load and commit. It loads each package by its path, so libuci reads no delta file for it and writes none: the writes of a request live in the cursor's copy and in the list that the commit replays, and a request that dies before its commit leaves nothing staged.
src/lib/bus.uc 37-84 lock fd on /etc/config/<pkg> and temp file .<pkg>.uapi-restore beside the file that the package names, the restore A missing package or a failed open dies before any fd exists. Every later path reaches the LOCK_UN and the close before the die(). Under the lock, a file that cannot be read dies with a message that names it, and a file that no longer holds what the request committed is left as it is, with no temp file, and the restore returns false. The lock is the flock that libuci takes on the package file. A load holds LOCK_SH on it while it parses, and a commit holds LOCK_EX while it reads the file again, writes its temp file and syncs it. The restore tries LOCK_EX with LOCK_NB every 50 ms for 5 s, then gives up with a message that names the file, so a stuck holder cannot keep it until uhttpd kills the request. A failed create leaves no temp file, and a file that reads back short, a failed chmod and a failed rename each unlink it. The die() reaches _finalize_after_reload(), which answers reload_failed_unrecovered with the message. The restore starts no child, so no copy of the lock fd outlives it. The lock orders nothing after it is released. libuci releases it before its own rename, and the flock is on the file that the rename replaces, so a commit that held the lock, or waited on it with the old file open, can rename its file over the restored one, as between two libuci commits.
src/lib/bus.uc 86-94 ubus connection and uci cursor, created by bus.connect A failed connect dies before any handle exists. The returned object owns both for the rest of the request.
src/lib/bus.uc 229-235 fd, /etc/config/<pkg> read for the snapshot, and after the commit for what the request committed A failed open returns null, and the restore then leaves the package with a message that says the file could not be read, where an empty snapshot was written over the package. The transaction reads the snapshot right before the commit and the other read right after it, so a commit by another writer between libuci's rename and that read reads as the request's own, and a restore undoes it. Otherwise the fd is closed before the return. The read takes no libuci lock, which is safe because libuci and the restore replace the file with a rename, so the read sees either the old file or the new one.
src/lib/transaction.uc 96-156 fds from fs.mkstemp(), one per service and one for the exit codes, and a child from system(), /etc/init.d/<svc> reload in default_reload(), and the stop and the start of a service when procd gave up on it, in the respawn check of dnsmasq and in recover_service() A failed mkstemp returns a message, and the loop at the end closes the files that it made. Otherwise each file is unlinked at once, and uapi fills the file of the exit codes with spaces, four bytes per service, and reads it back, so that the codes land in bytes that the file already holds when the output of a script has filled the tmpfs. A file that it cannot fill fails the reload. system(), with no timeout, so that it neither kills its child nor blocks SIGCHLD in it, runs a shell that puts one subshell in the background and exits, and a shell that exits with a code other than 0 fails the reload. That subshell runs the scripts in order with stdin, stdout and stderr on /dev/null, writes each exit code to the last file, and stops at the first that fails. Each script runs in a subshell of its own that closes every one of the files and then execs it with stdout and stderr on its own output, so that a script, or a daemon that it starts, holds no other file of the request. The exception that system() raises when fork fails is caught, which would otherwise skip the restore. uapi reads the exit codes through /proc/self/fd, every 20 ms, until every script has ended, one has failed, or the 20 s that a request waits for its reloads have run out, and then closes its copies of the files. The subshell keeps its own, and the unlinked files end with the last process that holds one, so a reload still running when uapi answers holds no uapi lock, since the lock fds close on exec, and leaves no file. A killed request leaves the same.
src/lib/transaction.uc 223-237 fd from fs.mkstemp() and a child from system(), in run_bounded(): dnsmasq --test, and apk update for packages.uc A failed mkstemp returns a result that says so and holds nothing. Otherwise the file is unlinked at once, system() runs the command with its output on that file and stdin on /dev/null, and out.close() runs on both paths after it: the read, and the catch of the exception that system() raises when fork or waitpid fails, which would otherwise skip the restore. system() waits for the child alone and sends it SIGKILL at the bound, and the exec makes the command that child. A parse that does not end, such as a conf-file on a mount that hangs, holds the write and its locks for 10 s at most per instance, and as long again in a restore. An apk update that a feed host holds is killed after reload_budget_s. The SIGCHLD that system() blocks in its child harms neither: --test starts no child, and apk reaps its wget with waitpid(). A conf-script child that dnsmasq leaves behind, or the wget of a killed apk, keeps only the unlinked file open, so the request does not wait for it. apk opens its database lock with O_CLOEXEC, so the lock ends with the killed apk and its wget holds no copy. A killed request leaves no file.
src/lib/transaction.uc 423-429 lock fd, _lock_one() A failed open returns { unavailable } and holds nothing. A refused LOCK_NB closes the fd and returns null. Otherwise the fd goes to the caller, who releases it with _release_one(), which closes it. The mode is w+e, and e sets O_CLOEXEC, so no child started under the lock gets a copy of the descriptor. An flock belongs to the open file description, so the close, or the exit of a killed request, is then what releases it. The test "a request killed under its locks" in tests/unit/transaction_test.uc proves the exit: a ucode process takes the global and package locks of multi_transaction(), starts a sleep inside fn and is killed there with SIGKILL, and the test then takes both locks while the sleep still runs. Without e the sleep holds them.
src/lib/transaction.uc 437-439 global EX, default_acquire() Returns the _lock_one() result unchanged. default_release() releases it with _release_one().
src/lib/transaction.uc 456-473 global SH and per-package EX, default_acquire_pkg() Takes the global SH, then the EX of the package and of each package in also, in sorted order. When one fails it releases the per-package locks it already holds and the global one, then returns the contention or the unavailable path. default_release_pkg() releases the per-package locks, then the global one.
src/lib/transaction.uc 484-490 global SH and per-package EX, acquire_pkg_waiting() Calls default_acquire_pkg() every 100 ms until it gets the locks, the lock file cannot be opened, or wait_ms has passed, and returns its last result. A failed attempt holds nothing, as the row above shows, so only the last result can hold locks, and the caller releases them with default_release_pkg().
src/lib/transaction.uc 512-538 global SH and per-package EX, recover_service() Takes the locks through default_acquire_pkg(), for each package that recover_targets() names for the service, so a contention or an unavailable path returns before the try and holds nothing, as the row of default_acquire_pkg() shows. The try covers the service list reads and recover(): the stop, the wait and the start through default_reload(), whose children get no copy of the lock fds, since they close on exec. default_release_pkg() runs after the catch and before die(caught). The action writes no uci and no journal record.
src/lib/transaction.uc 675-741 lock taken by transaction() The pre-flight checks run before the lock, so their early returns hold nothing. installed() stats the init scripts of the reload_if_running daemons there too, so an apk add or apk del of one of them outside uapi between that stat and the reload races as it did before the procd check moved under the lock. Each contention or unavailable result returns before the try. Inside the try run the service list of each reload_if_running daemon, which catches its ubus errors, the unload, fn, the revert or the snapshot and the commit, the reload, the stay-up watch, the dnsmasq --test check, the dnsmasq respawn check, the kernel apply and the restore. A commit that wrote nothing skips the reload, the watch and the apply, and a commit whose replay no longer applies returns a conflict before them. A commit that fails drops the copy of the package that the cursor holds, so nothing after it reads the writes that the file does not hold. release(lock) runs after the catch and before die(caught). A throw after the commit would skip the restore, but nothing on that path throws today: the watch, the respawn check and the kernel apply catch their ubus errors, default_reload() and run_bounded() catch the exception that system() raises when fork fails, the reload of a token mint or revoke, which reaps the token state in tmpfs, catches its own, and _finalize_after_reload() catches the restore's.
src/lib/transaction.uc 758-912 global SH and per-package EX, multi_transaction() Validation and the missing-config check return before any lock. The per-package EX are taken in sorted order, the stay-up daemons included, and each failure releases what is held before it returns. The try covers the service list of each reload_if_running daemon, the unloads, fn, the revert or the snapshot and the commit of each package, the apply and the restore. The restore reverts each package that the batch did not commit before it writes back the ones that it did, so that the cursor holds no write that uci did not store. After a failed commit it runs no reload and no reconcile, because neither the reload nor the kernel apply ran yet. The release loop runs after the catch and before die(caught).
src/lib/transaction.uc 914-934 global EX, with_lock() A contention or unavailable result returns before the try. release(lock) runs after the catch and before die(caught).
src/lib/write_journal.uc 52-66 fd, one journal record read by stale() for /uapi/diagnostics A failed open skips the record. Otherwise the fd is closed right after the read. No lock: the read runs outside the package locks, like the rest of /uapi/diagnostics.
src/lib/non_uci.uc 71-94 fd and temp file, replace_private_file() See the tricky case below. Every exit path closes the fd, and every failure path unlinks the temp file.
src/lib/ids.uc 22-28 fd, /dev/urandom A failed open dies before any fd exists. Otherwise the fd is closed right after the read.
src/lib/packages.uc 11-19 pipe, apk <args> A failed popen returns an error result. Otherwise p.close() always runs and yields the exit code. Under the global EX for add and del, which get reload_budget_s as --timeout and are not killed, and under no lock for the reads. apk update runs through run_bounded() instead.
src/lib/packages.uc 38-58 pipe, apk info A failed popen returns []. Otherwise the pipe is closed right after the read. No lock.
src/lib/packages.uc 171-186 fd per feed file A failed open gives an empty URL. Otherwise the fd is closed after one line. No lock.
src/lib/packages.uc 188-201 fd, one feed file A failed open answers 404. Otherwise the fd is closed after one line. No lock.
src/lib/packages.uc 225-247 fd, a new feed file, wx Under the global EX. O_EXCL refuses a file another writer created after the stat, and a failed open answers 409 or 500. Otherwise the fd is closed before the write is judged. A size on disk short of the URL line unlinks the file and answers 500 before apk update runs, so a retry does not find the file.
src/lib/mgmt.uc 20-28 pipe, ip route get <addr> A failed popen returns null. Otherwise the pipe is closed after one line, and ip has exited or exits once it writes that line. A single write resolves this before its transaction, and /uapi/diagnostics under no lock. A sub-request of /uapi/batch carries no caller address, so the guard opens no pipe there.
src/lib/state_dir.uc 52-61 fd and temp file, replace(), which the idempotency cache, the metrics, the rate limiter and the error ring write through Each caller writes only into a directory that state_dir.owned() accepts: a directory owned by the effective uid of the process, that neither the group nor others can write, narrowed to 0700, and not one that it cannot narrow. A failed open returns false and holds nothing. The temp name is unlinked first, because open() gives its mode only to a file that it creates, so the file is created 0600. The fd is closed before the size on disk is compared with the text, which is how a full tmpfs shows. A short file or a failed rename unlinks the temp file and returns false, and the file that it would replace stays whole.
src/lib/idempotency.uc 59-85 fd, a cache entry A directory that state_dir.owned() does not accept is a miss, and a store into it stores nothing and returns false. A failed open is a miss. Otherwise the fd is closed before the JSON parse. A store writes through state_dir.replace() under a temp name of its own request process, <hash>.json.<pid>, so two stores of one key at the same moment each write a whole file, and the later rename wins. At most once an hour, a store also unlinks the files older than the TTL, a temp file that a killed request left included, and writes its sweep marker .swept through state_dir.replace(). A failed write of the marker leaves the old one, so the next store sweeps again.
src/lib/token_store.uc 24-32 fd, /dev/urandom A failed open dies before any fd exists. Otherwise the fd is closed right after the read.
src/lib/token_store.uc 243-272 fd, the last-used marker, then a uapi transaction A directory that state_dir.owned() does not accept skips the update, marker and transaction both, because without its marker every authenticated request would write /etc/config/uapi. The marker is unlinked and created 0600, as open() gives its mode only to a file that it creates, and closed before the transaction. The transaction then releases its lock through transaction(). The marker is written first, so a 423 on the transaction still throttles the next minute. A mint or a revoke removes the marker of each token that no longer authenticates, see token_store.reap_state, which unlinks no marker in a directory that state_dir.owned() does not accept.
src/lib/metrics.uc 75-81 fd, one counter A directory that state_dir.owned() does not accept counts nothing: an increment reads and writes no file and returns false, a scrape shows no series, and a fold of retired tokens reads and unlinks nothing. A failed open reads as no count. Otherwise the fd is closed after one line. An increment writes through state_dir.replace() under <file>.tmp, which two writers of one counter share, so concurrent increments can be lost, which the module accepts. The size check keeps the counter a whole count.
src/lib/error_ring.uc 15-25 fd, the ring A directory that state_dir.owned() does not accept reads as [] and takes no append. A failed open reads as []. Otherwise the fd is closed before the parse. An append writes through state_dir.replace() under a temp name of its own request process, ring.json.<pid>, so two appends at once write separate files, and the later rename wins. The whole append is in a try that swallows everything.
src/lib/ratelimit.uc 14-31 fd, one bucket A directory that state_dir.owned() does not accept allows every request: a check reads and writes no file, and a reap unlinks nothing. Under /var/run only root can cause that, and refusing instead would answer 429 to every token. A failed open is no state, which is a full bucket, so the limit applies again once the bucket is written. Otherwise the fd is closed before the parse. A check writes through state_dir.replace() under <file>.txt.tmp, which two checks of one token share, so one of them can lose its write, as for the metrics. <file> is the token name, or its sha256 for a name over 63 characters.
src/lib/system_access.uc 58-66 pipe, busybox passwd, write end Under the global EX. A failed popen answers 500. Otherwise both writes run and p.close() yields the exit code. A passwd that exits early makes the writes fail with EPIPE rather than kill the request, because uhttpd ignores SIGPIPE and the request process inherits that.
src/lib/wg.uc 34-40 pipe, wg, ip and nslookup commands A failed popen returns an error result. Otherwise p.close() always runs after the read. Runs under the transaction's lock for network, apart from the wg show <iface> dump that a GET of network/wireguard_peers runs for its runtime and that a GET of network/wireguard_kernel_peers runs for its entries. That read takes no lock: a GET in a /uapi/batch that writes, which runs under the locks of the batch, answers {} and reads nothing, and no write reads it.
src/lib/wg.uc 215-231 fd and file, /var/run/uapi.wg.psk See the wireguard peer apply. The fd is closed before the write is judged. A size on disk short of the key line unlinks the file and returns null, and apply_peer() then fails before it changes anything in the kernel. Otherwise apply_peer() unlinks the file once wg returns.
src/resources/dhcp.leases.uc 24-30 fd, /tmp/dhcp.leases A failed open reads as no leases. Otherwise the fd is closed before the parse. No lock.
src/resources/dhcp.servers.uc 10-16 fd, a lease file A failed open reads as empty. Otherwise the fd is closed before the count. No lock.
cli/uapi-token 22-31 fd, /dev/urandom A failed open dies before any fd exists. Otherwise the fd is closed right after the read.
cli/uapi-token 96-108 global SH and EX of uapi, with_uapi_lock() Takes the locks that an HTTP write of the uapi package takes, through acquire_pkg_waiting(), waiting up to 10 s. A file that cannot be opened dies, holding nothing. Locks still held after 10 s print which one and exit 75, holding nothing. Otherwise fn runs and default_release_pkg() releases them. A die() inside fn ends the process, and the exit releases them, because no child holds a copy.
cli/uapi-token 122-129 fd, creating /etc/config/uapi A failed open dies. Otherwise the fd is closed right after the open.
cli/uapi-token 131-187 uci cursor, create Created inside with_uapi_lock(), so the package is loaded after the locks are taken and committed before they are released, and an HTTP write of /etc/config/uapi cannot run between the two. Freed when the command exits. It reads the file again before it writes, as the commit of the HTTP path does. The command keeps libuci's default cursor, which reads and commits what its shell staged in /tmp/.uci, as uci commit uapi in that shell does. It is a shell command, and that staging is its shell's. A name that another section of /etc/config/uapi holds dies before anything else. reap() then runs token_store.reap_state under the same locks and before the commit, as the HTTP mint does. A mint removes no token, so the reap drops no state of a token that authenticates, also when the commit then fails. A commit that libuci refuses, as on a full overlay, dies with the error of the cursor, before the bearer is printed. After the commit the bearer is printed and flushed.
cli/uapi-token 189-198 uci cursor, list Read only. Freed when the command exits.
cli/uapi-token 200-219 uci cursor, show Read only. Freed when the command exits.
cli/uapi-token 230-245 uci cursor, revoke Created and freed as for create. A commit that libuci refuses dies with the error of the cursor, before the message and before the reap, so the reap cannot drop the state of a token that still authenticates. After the commit the message is printed, then reap() runs token_store.reap_state under the same locks.

What runs while a lock is held

Every uapi lock is taken with LOCK_NB, so no request waits for one. A request that finds it taken answers 423 at once. uapi-token polls instead, for up to 10 s. libuci's own flocks on a package file block, so a load or a commit waits while LuCI or a shell holds them. The restore tries that flock for up to 5 s instead. A load holds it while it parses the file, and a commit while it reads the file again, writes and syncs it. How long a lock is held is set by what runs under it:

Entry point Locks Callers Held across
transaction() global SH, EX of the package, EX of unbound for a write that restarts it or, while it is installed, can reload it handler.uc create, replace, patch, remove, adopt and the singleton patch. raw.uc create, replace, patch and remove. token_store.uc create, remove and update_last_used(), which a GET reaches. The verbose service list of each reload_if_running daemon, fn with its ubus reads and, for a WEP value of wireless/interfaces, hostapd -vwep or wpa_supplicant -vwep, the commit, /etc/init.d/<svc> reload for each service, waited for up to 20 s in all, the stay-up watch, dnsmasq --test for each dnsmasq instance when the write commits dhcp, wg set and ip route for wireguard peers, after a wait of up to 8 s in all for netifd's restart of the wireguard interfaces, and busybox's nslookup for the endpoint host name of each peer that the apply sets. For a token mint, inside fn and before the commit, and for a revoke, as its reload, token_store.reap_state, which walks the rate-limit buckets, the token series of the metrics and the last-used markers. After a failed reload or apply: the restore, which can wait up to 5 s for libuci's flock on the package, a second reload, a second watch and check, and the kernel reconcile, which waits up to 8 s more for netifd under the ucode handler.
multi_transaction() global SH, EX of each package of the batch and of unbound when the batch restarts it or, while it is installed, can reload it main.uc /uapi/batch The verbose service list of each reload_if_running daemon, every sub-request, then one commit per package, and one reload of the services of the packages that the batch committed, one watch and one apply, and the same restore of each package that the batch committed. After a failed commit, only that restore, with no reload and no reconcile.
acquire_pkg_waiting() global SH, EX of uapi cli/uapi-token create and revoke The load of /etc/config/uapi, token_store.reap_state, before the commit for a create and after it for a revoke, and the commit.
recover_service() global SH, EX of each package whose writes reload the service main.uc POST /uapi/services/{name}/recover Two or three service list reads of the service. When procd gave up on an instance, /etc/init.d/<svc> stop, a poll of service list every 100 ms until procd lists no instance, and /etc/init.d/<svc> start, through default_reload(), for up to 3 s, 2 s and 5 s.
with_lock() global EX packages.uc install, remove, feed create, feed remove. system_access.uc password, key add, key replace, key remove. crontab.uc add and remove. apk add, then apk update and apk add again when the first add fails, unless the update was killed. apk del. A feed write or unlink followed by apk update, killed after reload_budget_s. busybox passwd. A rewrite of authorized_keys. A crontab rewrite, /etc/init.d/cron reload, and on failure the old crontab and a second reload, both waited for up to 20 s in all.

Six of these hold a lock longer than the write itself takes.

When the request process is killed

uhttpd sends SIGKILL to the request process when the client closes the connection after its request body has arrived and before the response, and when its script timeout expires (60 s unless script_timeout is set). A Terraform interrupt or a client-side timeout does the first. No release code runs, so this is where the sites rely on process exit:

Open findings

These are recorded here, not fixed. A finding leaves this list when it is fixed, and the CHANGELOG entry of the fix describes it.

Tricky case: non_uci.uc::replace_private_file()

let tmp = path + ".uapi.tmp";
try { fs.unlink(tmp); } catch (e) {}
let f = fs.open(tmp, "w");
if (!f) return false;
try { fs.chmod(tmp, 384); } catch (e) {}  // 0600
f.write(content);
f.close();
if (fs.stat(tmp)?.size != length(content)) {
    try { fs.unlink(tmp); } catch (e) {}
    return false;
}

Four exit paths to verify, in order:

  1. fs.open returns null: early return. No fd held.
  2. fs.chmod fails: it returns null rather than throwing, and the try is only a guard. f.write and f.close still run on the next lines, so the fd is released. The tolerance is deliberate (some filesystems return EPERM): content correctness is the priority, and the file then gets the default umask permissions.
  3. Normal path: f.write and f.close run unconditionally after the chmod, so the fd is released before the result is judged.
  4. Short or failed write: ucode's close() drops fclose's result, and flush() answers inverted on the ucode that CI runs, so a filesystem that runs out of space shows up as a temp file on disk shorter than content. That unlinks the temp file and returns false. Until 3.1.0 nothing checked, and an empty temp file was renamed over the original.

The following fs.rename(tmp, path) is checked: a failure unlinks tmp and returns false. The rename keeps the replacement atomic.

Patterns confirmed

The wireguard peer apply

wg.uc shells out to wg set after the commit, inside the locked region, to push peer changes to the kernel (see docs/architecture.md ยง Transaction recipe step 7). Three things about it are load-bearing here.

Before it waits for an interface, the apply looks for a stored peer that keeps the interface down, still under the lock of network. It compiles the peer resource, reads the peers that the write committed, and looks up the interface of each link-local %zone with fs.access() in /sys/class/net, so it holds no fd of its own. It then skips such an interface with no wait, so the write holds the lock for less time than the 8 s that the wait could take. A write whose restart does not end within the 8 s and that only removes peers keeps its commit and runs no restore, so it releases the lock without the reloads and the reconcile of a restore.

The preshared key is staged at a fixed path, /var/run/uapi.wg.psk, rather than a unique one. That is safe only because every uci transaction holds the per-package exclusive lock for network, so two peer applies can never be in flight at once. If that lock discipline ever changes, this needs a unique path. Mode 0600 is set before the content is written, following the same order as replace_private_file above, and the file is unlinked immediately after the command returns. The write is checked as in replace_private_file, because wg reads an empty key file as no key. apply_peer() stages the key before it removes or sets the peer, so a key that the tmpfs cannot hold fails the apply with the peer as the kernel holds it, and no peer is removed for it. The restore then sets every peer of the interface again from uci and stops at the first one that fails, so on a full tmpfs it answers reload_failed_unrecovered unless no peer of that interface has a key that wg can read in the restored config.

wg show <iface> dump is read on the reconcile path, and for the runtime of a GET of network/wireguard_peers, which holds no lock. A write does not read it, and neither does a GET in a /uapi/batch that writes. Its first line holds the private key of the interface and the second field of each peer line its preshared key, so that output must never be logged or surfaced in an error message. kernel_peers() keeps only the other fields.

Scope

This audit is about logical resource-state correctness. Every site releases explicitly inside the request on every path the request itself takes. The fork-per-request model closes what remains at exit, and When the request process is killed says where that backstop is enough and where it is not.