Skip to content

feat: retry binds on EADDRINUSE, document rebinding fixed ports - #95

Merged
Frando merged 2 commits into
mainfrom
test/reflector-reuseaddr
Nov 25, 2026
Merged

Frando merged 2 commits into
mainfrom
test/reflector-reuseaddr

Conversation

@Frando

@Frando Frando commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

A NAT test failed now and then with EADDRINUSE when the reflector bound the port that a probe had just closed.

Cause

When any thread spawns a child process, the child gets a copy of every open fd of the process. The copies stay open until the child calls exec. A socket closed in that window keeps its port bound, usually for under 2 ms. Under heavy load we measured up to 129 ms.

This happens with posix_spawn as well as fork, so plain std::process and tokio::process are affected. Patchbay's own nft, tc and podman calls are affected too. The race also hits TCP. SO_REUSEADDR does not help there, because Linux refuses a bind while a copied listener is still open.

Changes

  • New public patchbay::util::retry_addr_in_use(|| bind(..)). It tries the bind again on EADDRINUSE for up to one second, with a short backoff.
  • The probe and reflector binds in test_utils use it. This replaces the earlier SO_REUSEADDR approach in this PR, which only fixed UDP and needed both sockets to set the option.
  • New "Rebinding a fixed port" section in the testing guide. It explains the race and when to use the helper.

Testing

  • New unit tests for the helper:
    • the bind succeeds once the port is free;
    • other errors return at once;
    • it gives up after the deadline.
  • In a standalone repro (one thread rebinding a port while other threads spawn processes), plain rebinds failed hundreds to thousands of times per 200k iterations. With the retry, there were 0 failures, for UDP and for TCP.
  • cargo test --workspace passes. The hairpin and NAT tests also passed on 3 extra runs.

🤖 Generated with Claude Code

Frando and others added 2 commits November 25, 2026 11:38
A NAT test failed now and then with EADDRINUSE when the reflector bound
the port a probe had just closed. When any thread spawns a child, the
child holds a copy of every open socket until it execs, so a socket
closed in that moment keeps its port bound for a few milliseconds. This
happens with posix_spawn as well as fork, and for TCP as well as UDP.

The probe and reflector binds now try again on EADDRINUSE for up to one
second. The helper is public so tests that rebind a fixed port can use
it too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Frando
Frando force-pushed the test/reflector-reuseaddr branch from 85134aa to 5eb0fb2 Compare November 25, 2026 10:51
@Frando Frando changed the title test: bind probe and reflector sockets with SO_REUSEADDR feat: retry binds on EADDRINUSE, document rebinding fixed ports Nov 25, 2026
@Frando
Frando merged commit cf7a86b into main Nov 25, 2026
7 of 8 checks passed
Frando added a commit that referenced this pull request Nov 26, 2026
…s_root() (#94)

## Problem

patchbay had two bootstraps. `init_userns()` mapped the user to uid 0,
which breaks services that check the caller's uid, such as the session
D-Bus and PipeWire portals. `init_userns_keep_uid()` kept the uid, but
then no command could run as root. A process had to pick one, and each
had a libc-only `_for_ctor` twin.

## Approach

One bootstrap, `init_userns()`. The process always keeps its uid and
gid.

If the host has a subordinate id range for the user
(`newuidmap`/`newgidmap` on `PATH`, `/etc/subuid` and `/etc/subgid`
entries), the ids around the user's map onto that range. For uid 1000
and `100000:65536`:

```
1000  1000    1       the user, to itself
0     100000  1000    inner 0..=999
1001  101000  64536   inner 1001..=65536
```

Root, system users and `nobody` exist inside, so a daemon that drops
from root to another user works.

Commands run as root through `Device::as_root()`, `Router::as_root()`
and `Ix::as_root()` (the IX root namespace):

```rust
let child = device.as_root().spawn_command_sync(cmd)?;
```

`as_root()` returns an `AsRoot` handle with `spawn_command` and
`spawn_command_sync`. They set uid and gid 0 on the command. The
patchbay process has `CAP_SETUID` in the namespace, so this needs no
setuid binary. In a sim, `run` and `spawn` steps take `root = true`.

Root is only for spawned commands. The patchbay process already has all
capabilities in the namespace, and glibc applies `setuid` to every
thread, so an in-process "become root" would not be clean.

Without root, the spawn error says why: no subordinate ids, a nested
user namespace (where patchbay does not try the helpers), or the
helpers' own error output. If `newuidmap` or `newgidmap` fails after the
unshare, the bootstrap falls back to the single-id map instead of
leaving the process without a mapping.

`patchbay-cli` now enters the user namespace only for `run` and
`inspect`. `test` and `compare` start cargo, whose test binaries set up
their own namespace. `vm` runs qemu and virtiofsd as the host user.
Before, test binaries under `patchbay test` ran nested, and with this PR
they would have lost root. `run-in` also stays outside: from there the
user owns the inspect session's namespace, so `nsenter` may join it.
Before, it entered its own sibling namespace and `nsenter` failed (also
on main). `run-in` passes `--preserve-credentials` to `nsenter`, so the
command runs as the user and not as root. Where `nsenter` supports
`--keep-caps` (util-linux 2.39 or later), the command also gets the
capabilities of the namespace. With an older `nsenter`, `run-in` warns
and runs the command without capabilities.

The DNS overlay files (`/etc/hosts` and `/etc/resolv.conf` of a device)
now have mode 0644 under any umask. A root command that switches to
another user, such as `nobody`, can then read them. This fix comes from
#45.

## Breaking changes

- `init_userns()` keeps the caller's uid instead of mapping it to 0.
Commands that need uid 0 must be spawned through `as_root()`.
- Sim steps no longer run as root. Steps that need uid 0 (for example
`mount`, `chown`, or tools that check for root) need `root = true`.
`nft`, `tc`, `ip`, `ping` and low ports work without it.
- `init_userns_for_ctor()` is deprecated. It calls `init_userns()`,
ignores the error, and keeps the uid like `init_userns()`. Replace
`unsafe { patchbay::init_userns_for_ctor() }` with `let _ =
patchbay::init_userns();`, which also works from a `#[ctor]`.
- `init_userns_keep_uid()` and `init_userns_keep_uid_for_ctor()` (from
#91) are removed. No release contains them.
- `patchbay test` and `patchbay compare` no longer run cargo inside a
user namespace. Each test binary must call `init_userns()` itself, as
the testing guide shows. Before, a test binary without this call worked
under `patchbay test`.

## Impact

- Root inside the namespace is a subordinate id on the host. Files that
a root command creates outside the lab belong to it, and the user needs
`podman unshare rm` to remove them. The docs say to prefer running as
the user.
- On a host without `/etc/subuid`, there is no root. Labs work as
before.
- The NAT and hairpin tests that already flake on main flake more often
with this change. #95, now on main, fixes the cause (a forked child
briefly holding a closed probe socket).

## Testing

- `tests/userns.rs`: the uid maps to itself and 0, 1 and 65534 exist;
`as_root()` spawns run as uid 0 with the full bounding set and can
switch to `nobody`; the async variant works; plain spawns run as the
user. Root is required where the host is set up for it, unless the test
runs nested (or always with `PATCHBAY_EXPECT_ROOT`, which CI sets). The
root test runs under umask 077 and reads the DNS files as `nobody`. The
deprecated `init_userns_for_ctor()` does nothing after the bootstrap.
- `tests/userns_fallback.rs`: runs its own binary with failing helpers
first on `PATH`: both failing, and only `newgidmap` failing. Checks the
fallback, a working lab, and that the root error carries the helper's
message.
- CLI: a sim with a `root = true` step and a plain step checks both
uids.
- `patchbay-cli/tests/run_in.rs`: starts a real `inspect` session and
runs `run-in` from the initial user namespace. Checks the uid, the
network namespace and `CAP_NET_ADMIN` of the command.
- Checked by hand:
- `patchbay test -p patchbay --test userns` runs the root test for real,
with no helper noise.
- The same binary under `unshare --user` skips root with the nesting
reason.
- `patchbay vm --backend qemu up` works. Files the guest writes to
`/work`, also as guest root, are owned by the user on the host.
- `busctl --user status` and `pw-cli info 0` work from inside the
namespace.
  - `patchbay run` with failing helpers prints the fallback warning.
- `run-in` with an `nsenter` that has no `--keep-caps` warns, and runs
the command as the user without capabilities.
- The lib suite flaked in NAT and hairpin tests more often than on main.
With #95 applied on top, 14 of 14 runs passed. Merged with current main,
the workspace suite passes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant