[Dnsmasq-discuss] bind-dynamic race condition
Francesco
francesco.montorsi at gmail.com
Wed Nov 4 11:55:22 UTC 2026
Hi,
Actually the fix for this race condition is very small and
self-contained. Here's the summary for the bug and at the end the
patch to fix it.
The bugfix has been tested&developed with AI tools but I then checked
manually myself the explanation of the bug and the logic around the
fix. I think it's a good fix.
## Summary
`enumerate_interfaces()` asks the kernel for the list of addresses,
then for each
address `iface_allowed()` turns the interface index into a name (`SIOCGIFNAME`,
or `if_indextoname()`) and reads its flags (`SIOCGIFFLAGS`). If the interface is
deleted between the kernel producing the address dump and those two ioctls, they
fail with `ENODEV` (Linux) or `ENXIO` (*BSD, POSIX `if_indextoname()`), and
`iface_allowed()` returns 0.
Returning 0 from the enumeration callback is treated as a fatal error for the
whole enumeration, not just for that one address. With `--bind-dynamic` this
makes dnsmasq drop the listening sockets of interfaces that still exist.
Short-lived interfaces trigger it in practice: veth pairs created and destroyed
by container runtimes, VPN tunnels, hot-plugged USB NICs, Wi-Fi interfaces
bouncing during roaming.
## Mechanism
1. `iface_allowed()` (`src/network.c:257`) returns 0 on the `ENODEV`/`ENXIO`
ioctl failure.
2. `iface_enumerate()` (`src/netlink.c:154`) sets `callback_ok = 0`, stops
calling the callback for every remaining address in the dump, and returns 0.
The BSD implementation in `src/bpf.c` does the same via `goto err`.
3. `enumerate_interfaces()` (`src/network.c:838`) sees `ret == 0` after the
`AF_INET6` pass and skips the `AF_INET` pass entirely.
4. At the start of the pass every `struct irec` was marked `found = 0`. Only the
entries visited before the failure were set back to `found = 1`.
5. With `--bind-dynamic` (`OPT_CLEVERBIND`), the garbage collector at
`src/network.c:848` releases every listener whose `iface->found` is still 0.
These are live interfaces that simply had not been revisited yet. dnsmasq
stops answering on them until the next call to `enumerate_interfaces()`.
6. Side effects for that select cycle, regardless of `--bind-dynamic`: the
address lists for `--local-service`, `--interface-name` and conditional
domains (`--domain=...,<interface>`) are left partially rebuilt, because
they are flushed at the start of the pass and refilled by the callback.
7. At startup, `src/dnsmasq.c:379` treats the 0 return as fatal:
`failed to find list of interfaces: No such device`.
## Reproduction (Linux)
Run dnsmasq with `--bind-dynamic` and several interfaces it listens on, then
create and destroy interfaces in a tight loop so that one disappears between
the netlink dump and the `SIOCGIFNAME` ioctl:
```sh
dnsmasq --no-daemon --bind-dynamic --log-debug --interface=eth0
--interface=eth1 &
while :; do ip link add tmp0 type dummy; ip addr add 10.99.0.1/24 dev
tmp0; ip link del tmp0; done
```
The race window is small, so it can take a while to hit, but when it does the
log shows `stopped listening on eth1(#3): ... port 53` (or `eth0`) even though
`eth0`/`eth1` never changed, followed by `listening on ...` again on the next
enumeration. Queries sent during the gap go unanswered.
Making the window deterministic for testing: insert a `sleep(1)` before the
`indextoname()` call in `iface_allowed()` and delete an interface during the
sleep.
## Fix
The patch makes two independent changes in `src/network.c`:
1. **Skip a vanished interface instead of aborting.** In `iface_allowed()`, if
`indextoname()` or `SIOCGIFFLAGS` fails with `ENODEV` or `ENXIO`, return 1
("not interested in this address") rather than 0. Nothing has been allocated
or recorded for that address at that point, so skipping it is clean. The
`if_index != 0` guard preserves the existing behaviour for index 0, where
`indextoname()` returns 0 without setting `errno`. The Solaris
`indextoname()` now sets `errno = ENXIO` on its "not found" path, as
`if_indextoname()` does, so the check never reads a stale `errno` there.
2. **Only garbage-collect listeners after a complete enumeration.** The
`--bind-dynamic` listener GC now runs only when `ret == 1`, meaning both the
IPv6 and IPv4 passes finished. If a pass was aborted for any reason (for
instance `ENOMEM` in `iface_allowed()`), the `->found` flags are incomplete
and must not be used to close sockets. Interfaces that genuinely vanished
are then cleaned up on the next successful enumeration instead.
## Side effects of the fix (reviewed)
- `iface->found` is also read by `create_bound_listeners()` and
`warn_wild_labels()`. After an aborted pass they already saw partial flags
before the patch; the patch changes nothing there, and a new interface that
was not visited is simply picked up on the next cycle.
- `errno` may be left at `ENODEV`/`ENXIO` after a skipped address. The next
`iface_enumerate()` resets it to 0 via `retry_send()` before its own
`errno != 0` check, and `enumerate_interfaces()` callers only look at
`errno` on a 0 return, so nothing observes it.
- Memory: with the GC skipped after an aborted pass, `struct irec` entries of
vanished interfaces live until the next successful pass. No leak.
- No change in behaviour when enumeration succeeds, which is the normal case.
## Verification
- Builds without warnings in `network.c` on macOS (`HAVE_BSD_NETWORK`) and on
Linux (gcc 13, `HAVE_LINUX_NETWORK`).
- The patch applies cleanly to current master.
Patch:
---
src/network.c | 22 ++++++++++++++++++----
1 file changed, 18 insertions(+), 4 deletions(-)
diff --git a/src/network.c b/src/network.c
index 6c4469d..7e97db1 100644
--- a/src/network.c
+++ b/src/network.c
@@ -91,6 +91,10 @@ int indextoname(int fd, int index, char *name)
return 1;
}
}
+
+ /* Not found: behave like if_indextoname() so callers can tell a
+ vanished interface from a real error. */
+ errno = ENXIO;
return 0;
}
@@ -254,9 +258,16 @@ static int iface_allowed(struct iface_param
*param, int if_index, char *label,
(void)prefixlen;
- if (!indextoname(param->fd, if_index, ifr.ifr_name) ||
- ioctl(param->fd, SIOCGIFFLAGS, &ifr) == -1)
- return 0;
+ /* An interface can disappear between the kernel giving us its address
+ and us looking it up here. That is not an error: skip the address and
+ carry on, since returning zero here aborts the whole enumeration.
+ Linux reports a vanished interface as ENODEV, *BSD and POSIX
+ if_indextoname() as ENXIO. */
+ if (!indextoname(param->fd, if_index, ifr.ifr_name))
+ return if_index != 0 && (errno == ENODEV || errno == ENXIO);
+
+ if (ioctl(param->fd, SIOCGIFFLAGS, &ifr) == -1)
+ return errno == ENODEV || errno == ENXIO;
loopback = ifr.ifr_flags & IFF_LOOPBACK;
@@ -846,7 +857,10 @@ again:
errsave = errno;
close(param.fd);
- if (option_bool(OPT_CLEVERBIND))
+ /* Only garbage-collect when both enumerations completed. If one was
+ aborted, interfaces not yet visited still have ->found == 0 and
+ their listeners would be wrongly closed. */
+ if (option_bool(OPT_CLEVERBIND) && ret == 1)
{
/* Garbage-collect listeners listening on addresses that no longer exist.
Does nothing when not binding interfaces or for listeners on localhost,
--
Il giorno mer 4 nov 2026 alle ore 11:09 Francesco
<francesco.montorsi at gmail.com> ha scritto:
>
> My bad, I see the attachment has been scrubbed by the mailing list rules.
> Let me retry:
>
> diff --git a/tests/bind-dynamic-veth-repro/Dockerfile
> b/tests/bind-dynamic-veth-repro/Dockerfile
> new file mode 100644
> index 0000000000000000000000000000000000000000..f074e433fde94a204a6eb0f6a79fee5336a69e1c
> --- /dev/null
> +++ b/tests/bind-dynamic-veth-repro/Dockerfile
> @@ -0,0 +1,13 @@
> +FROM debian:bookworm-slim AS build
> +
> +RUN apt-get update \
> + && apt-get install -y --no-install-recommends build-essential
> ca-certificates git pkg-config \
> + && rm -rf /var/lib/apt/lists/*
> +
> +WORKDIR /src
> +COPY . .
> +RUN make -j2
> +
> +FROM debian:bookworm-slim
> +COPY --from=build /src/src/dnsmasq /usr/sbin/dnsmasq
> +ENTRYPOINT ["/usr/sbin/dnsmasq"]
> diff --git a/tests/bind-dynamic-veth-repro/README.md
> b/tests/bind-dynamic-veth-repro/README.md
> new file mode 100644
> index 0000000000000000000000000000000000000000..a977247b63373e5fb70309a9e1fd07d75b858f84
> --- /dev/null
> +++ b/tests/bind-dynamic-veth-repro/README.md
> @@ -0,0 +1,44 @@
> +# `bind-dynamic` Docker veth churn reproducer
> +
> +This harness checks whether repeated creation and removal of Docker container
> +endpoints can make dnsmasq lose its IPv4 listeners while running with
> +`bind-dynamic`.
> +
> +Run it only on a disposable Linux Docker host: the dnsmasq test container uses
> +host networking so it receives the host's rtnetlink address notifications. It
> +binds only `127.0.0.1:1053`, avoiding the normal DNS port. Short-lived helper
> +containers use a dedicated Compose bridge with IPv6 enabled; their veth
> +endpoints and addresses are created and removed on the host. The script checks
> +the DNS listener once while each helper endpoint is present and again after it
> +is deleted.
> +
> +```sh
> +./tests/bind-dynamic-veth-repro/run.sh
> +```
> +
> +The default run performs 200 endpoint cycles with a one-second pause between
> +cycles. Override `ITERATIONS` or `INTERVAL_SECONDS` to change the run length or
> +pace. The script checks for both UDP and TCP listeners. On failure it records
> +the iteration, phase, and timestamp in
> `/tmp/dnsmasq-bind-dynamic-veth-repro.log`
> +and prints the listener state and dnsmasq logs. Compose resources are removed
> +on exit.
> +
> +The current dnsmasq Linux code subscribes to address notifications and queues
> +`EVENT_NEWADDR` for `RTM_NEWADDR` and `RTM_DELADDR`; it does not subscribe to
> +`RTM_NEWLINK`. This harness therefore exercises veth address churn, rather
> +than link events alone.
> +
> +A passing run does not rule out a rare race. Increase `ITERATIONS` and repeat
> +on the same kernel/Docker combination where the failure was observed.
> +
> +
> +## Observed result
> +
> +On 2026-11-03, this harness reproduced the failure twice on Linux
> +`7.2.10-200.fc44.x86_64` with Docker Engine `29.9.0`. The first run failed at
> +iteration 11; after adding the build version label, a second run failed at
> +iteration 40. Both failures occurred after deleting the helper endpoint. `ss`
> +showed only the IPv6 listener on `::1:1053`, and dnsmasq logged
> +`stopped listening on lo(#1): 127.0.0.1 port 1053`. The versioned run used
> +source checkout `v2.93-44-g10fbc39`. The Compose project and its network were
> +removed by the runner after each failure.
> diff --git a/tests/bind-dynamic-veth-repro/compose.yaml
> b/tests/bind-dynamic-veth-repro/compose.yaml
> new file mode 100644
> index 0000000000000000000000000000000000000000..a7b7c750cadb9b934bfc2408f7a922ff62e4d56c
> --- /dev/null
> +++ b/tests/bind-dynamic-veth-repro/compose.yaml
> @@ -0,0 +1,23 @@
> +services:
> + dnsmasq:
> + build:
> + context: ../..
> + dockerfile: tests/bind-dynamic-veth-repro/Dockerfile
> + network_mode: host
> + command: ["--keep-in-foreground", "--conf-file=/etc/dnsmasq.conf"]
> + volumes:
> + - ./dnsmasq.conf:/etc/dnsmasq.conf:ro
> +
> + churn:
> + image: alpine:3.20
> + command: ["sh", "-c", "sleep 2"]
> + networks:
> + - churn
> +
> +networks:
> + churn:
> + driver: bridge
> + enable_ipv6: true
> + ipam:
> + config:
> + - subnet: fd42:53:1::/64
> diff --git a/tests/bind-dynamic-veth-repro/dnsmasq.conf
> b/tests/bind-dynamic-veth-repro/dnsmasq.conf
> new file mode 100644
> index 0000000000000000000000000000000000000000..6d2ccb2eec20805be84bd31484d068b87b6606ab
> --- /dev/null
> +++ b/tests/bind-dynamic-veth-repro/dnsmasq.conf
> @@ -0,0 +1,9 @@
> +no-daemon
> +log-facility=-
> +log-debug
> +port=1053
> +no-resolv
> +no-hosts
> +interface=lo
> +listen-address=127.0.0.1
> +bind-dynamic
> diff --git a/tests/bind-dynamic-veth-repro/run.sh
> b/tests/bind-dynamic-veth-repro/run.sh
> new file mode 100755
> index 0000000000000000000000000000000000000000..3c84d3167021a9e77757100a64eba26a71be1725
> --- /dev/null
> +++ b/tests/bind-dynamic-veth-repro/run.sh
> @@ -0,0 +1,68 @@
> +#!/bin/sh
> +set -eu
> +
> +repro_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
> +compose_file="$repro_dir/compose.yaml"
> +iterations=${ITERATIONS:-200}
> +interval=${INTERVAL_SECONDS:-1}
> +result_log=${RESULT_LOG:-/tmp/dnsmasq-bind-dynamic-veth-repro.log}
> +helper_id=
> +
> +compose() {
> + docker compose -f "$compose_file" "$@"
> +}
> +
> +cleanup() {
> + if [ -n "$helper_id" ]; then
> + docker rm -f "$helper_id" >/dev/null 2>&1 || true
> + fi
> + compose down --remove-orphans >/dev/null 2>&1 || true
> +}
> +trap cleanup EXIT HUP INT TERM
> +
> +if ! command -v ss >/dev/null 2>&1; then
> + echo "ss (iproute2) is required on the Docker host" >&2
> + exit 2
> +fi
> +
> +compose build dnsmasq
> +compose up -d dnsmasq
> +sleep 2
> +
> +check_listener() {
> + udp=$(ss -H -lun 'sport = :1053' | awk '$4 == "127.0.0.1:1053" {
> found=1 } END { print found+0 }')
> + tcp=$(ss -H -ltn 'sport = :1053' | awk '$4 == "127.0.0.1:1053" {
> found=1 } END { print found+0 }')
> + [ "$udp" -eq 1 ] && [ "$tcp" -eq 1 ]
> +}
> +
> +fail() {
> + printf '%s FAIL iteration=%s phase=%s: IPv4 UDP/TCP listener
> disappeared\n' "$(date --iso-8601=seconds)" "$iteration" "$1" | tee -a
> "$result_log" >&2
> + ss -H -lnptu 'sport = :1053' >&2 || true
> + compose logs dnsmasq >&2
> + exit 1
> +}
> +
> +if ! check_listener; then
> + iteration=0
> + fail startup
> +fi
> +
> +iteration=1
> +while [ "$iteration" -le "$iterations" ]; do
> + helper_id=$(compose run -d --no-deps churn)
> + sleep 0.2
> + check_listener || fail create
> +
> + docker wait "$helper_id" >/dev/null
> + docker rm "$helper_id" >/dev/null
> + helper_id=
> + check_listener || fail delete
> +
> + if [ $((iteration % 25)) -eq 0 ]; then
> + printf '%s OK iterations=%s\n' "$(date --iso-8601=seconds)"
> "$iteration"
> + fi
> + iteration=$((iteration + 1))
> + sleep "$interval"
> +done
> +
> +printf '%s PASS iterations=%s listener=127.0.0.1:1053/udp,tcp\n'
> "$(date --iso-8601=seconds)" "$iterations" | tee -a "$result_log"
>
>
>
> Il giorno mer 4 nov 2026 alle ore 11:08 Francesco
> <francesco.montorsi at gmail.com> ha scritto:
> >
> > Hi,
> > Looking at the mailing list I see that the standard way to go is
> > attach a patch to the email, so there we go.
> > This patch allows you to reproduce, in a few seconds/minutes the race
> > condition I mentioned in my previous email.
> >
> > I might try to propose a fix if there is interest!
> >
> > Thanks,
> > Francesco
> >
> > Il giorno mar 3 nov 2026 alle ore 14:55 Francesco
> > <francesco.montorsi at gmail.com> ha scritto:
> > >
> > > Hi all,
> > >
> > > First of all thanks for developing and maintaining dnsmasq, it's really useful and I'm the maintainer of an addon that integrates it with HomeAssistant (https://github.com/f18m/ha-addon-dnsmasq-dhcp).
> > >
> > > I recently started using the "bind-dynamic" feature and I have definitively isolated a bug in dnsmasq: I can reproduce an intermittent issue with dnsmasq 2.93-44-g10fbc39 on Linux using bind-dynamic. I created an isolated test to reproduce it, based on docker (compose).
> > >
> > > What happens is that after repeated creation and removal of Docker bridge container endpoints, dnsmasq stops listening on 127.0.0.1 over both UDP and TCP, while the IPv6 listener on ::1 remains. Its log reports:
> > >
> > > stopped listening on lo(#1): 127.0.0.1 port 1053
> > >
> > > The reproducer uses dnsmasq in host networking, bound only to 127.0.0.1:1053, and repeatedly creates/removes short-lived containers on an IPv6-enabled bridge. It reproduced after 11 and 40 cycles on Linux 7.2.10-200.fc44.x86_64 with Docker Engine 29.9.0. I can provide the minimal Docker Compose reproducer.
> > >
> > > I suspect there is a race condition somewhere related to the bind-dynamic implementation.
> > >
> > > What is the best way to share the test that reproduces this issue with you?
> > >
> > > I didn't find any bug tracker and although I git cloned the source, I'm not sure in which format you prefer to receive the test that reproduces the bug... should I send a .patch file?
> > >
> > > Thanks,
> > >
> > > Francesco Montorsi
More information about the Dnsmasq-discuss
mailing list