[PR #3425] windows: add split tunnelling exclusion routes in one batch #3292

Open
opened 2026-11-07 17:59:01 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/amnezia-vpn/amnezia-client/pull/3425
Author: @OstarkovSN
Created: 11/6/2026
Status: 🔄 Open

Base: dev ← Head: route-batch-dev


📝 Commits (1)

  • ad35f50 windows: add split tunnelling exclusion routes in one batch

📊 Changes

7 files changed (+158 additions, -60 deletions)

View changed files

📝 client/daemon/daemon.cpp (+23 -14)
📝 client/daemon/daemon.h (+1 -1)
📝 client/daemon/wireguardutils.h (+14 -0)
📝 client/platforms/windows/daemon/windowsroutemonitor.cpp (+104 -39)
📝 client/platforms/windows/daemon/windowsroutemonitor.h (+6 -2)
📝 client/platforms/windows/daemon/wireguardutilswindows.cpp (+8 -4)
📝 client/platforms/windows/daemon/wireguardutilswindows.h (+2 -0)

📄 Description

Problem

On Windows, "all sites except" split tunnelling with a large site list makes
activation take minutes. The daemon installs one exclusion route per listed
prefix, and each one re-reads the whole, growing, routing table. With about
8,700 prefixes, 5.1.0.6 took almost 5 minutes from activate to
Connection status: 1.

This PR fixes that slow route install, and only that. A separate issue
remains after activation: the GUI can stay on "Connecting..." for minutes
more, because the daemon's 250 ms checkHandshake() timer is starved while
routeChanged() rescans run on the same thread. This PR does not change
that path; see Known limitations.

Observed symptom

  • AmneziaVPN 5.1.0.6 on Windows 10 22H2, AmneziaWG, "all sites except" mode
    with a Russian-IP bypass list: about 8,700 IPv4 prefixes (8,675 exclusion
    route add attempts in the run below).
  • In the service log, 4 min 57 s pass between Command received: activate
    and Connection status: 1, with 30,428 WindowsRouteMonitor lines in
    between, almost all of them from adding exclusion routes one by one.
  • The reporter also found that installing the same routes from a script
    (netsh -f, 500 commands per batch) is fast. That timing is not included
    here. It suggests, but does not prove, that creating the routes is not the
    bottleneck. The counts below locate the cost.

Root cause

In this mode every listed site becomes an entry in excludedAddresses, and
Daemon::activate() (and Daemon::switchServer()) call
addExclusionRoute() once per address. On Windows,
WindowsRouteMonitor::addExclusionRoute() does the following for every
prefix:

  1. GetIpForwardTable2(): copies the whole routing table out of the kernel.
    The table grows by one row for each exclusion route already added.
  2. updateInterfaceMetrics(): calls GetIpInterfaceTable() and writes one
    debug line per connected interface.
  3. updateCapturedRoutes(family, table): when default route capture is on,
    this calls isRouteExcluded(), which is linear in the number of
    exclusions, for every eligible system route.
  4. updateExclusionRoute(): a linear scan of the table.
  5. One more debug line.

Every log line is flushed to the log file. For N prefixes the cost is O(N²)
table rows copied out of the kernel and scanned. During switchServer(),
where capture is already enabled, it adds O(T·N²) in isRouteExcluded(),
where T is the number of system routes. For N = 8,664 that is about
37 million rows copied (see the measurements below).

Fix

  • Add WindowsRouteMonitor::addExclusionRoutes(const QList<IPAddress>&). For
    each address family it fetches the routing table and interface metrics
    once, then builds each exclusion row, computes its next hop against that
    snapshot with the existing updateExclusionRoute(), installs it, and
    records it in m_exclusionRoutes. updateCapturedRoutes() runs once at
    the end. A single summary line (Added X of N exclusion routes (I installed, F failed) in T ms) replaces the per-prefix debug lines.
    Interface, capture, warning and error lines are logged as before, but
    updateInterfaceMetrics() now runs once per family.
  • addExclusionRoute() keeps its signature, its log line and its return
    value, and now calls the batch with one prefix. The row initialisation
    moved verbatim into initExclusionRow().
  • updateExclusionRoute() now returns false when CreateIpForwardEntry2()
    fails. It still logs the error as before. The batch uses the value only
    for the summary count, and routeChanged() ignores it.
  • WireguardUtils gets a virtual addExclusionRoutes() whose default adds
    the routes one by one, so Linux and macOS routing code is unchanged.
    Windows overrides it, and excludeLocalNetworks() uses it too. The
    daemon-level duplicate handling below applies to every platform.
  • Daemon::addExclusionRoute() is replaced by Daemon::addExclusionRoutes().
    It applies the same m_excludedAddrSet reference counting, but collects
    the not-yet-excluded prefixes and adds them in one call. One difference:
    if a prefix appears twice in the list and the first attempt fails, the
    old loop tried again on the second occurrence. The new code does not.
  • updateInterfaceMetrics() now returns whether it read the interface
    table. The batch keeps calling it for each prefix until it succeeds,
    which matches the old per-prefix retry.

Why the result is the same

updateExclusionRoute() skips every route with the same protocol and metric
as the row being placed: MIB_IPPROTO_NETMGMT with EXCLUSION_ROUTE_METRIC,
which are the exclusion routes this monitor creates. It also skips routes on
the VPN interface, which is where captured routes go. So the rows created
earlier in a batch can never change the next hop chosen for a later prefix,
and, as long as the system routes and interface metrics stay the same, one
snapshot gives the same answer as re-reading the table every time.
If another program changes the IPv4 routing table during the batch, the
existing NotifyRouteChange2() → routeChanged() path re-evaluates every
entry of m_exclusionRoutes afterwards, and the batched rows are in it, as
before. IPv6 has no such notification (see Known limitations). An IPv6
gateway change during the batch is therefore not picked up by the remaining
IPv6 prefixes of that batch, which the per-prefix loop could have seen. The
batch now runs for milliseconds to seconds instead of minutes.
A transient GetIpForwardTable2() failure fails only the prefix that hit
it. The next prefix tries the fetch again, as the per-prefix code did.

Intentional behaviour change

updateCapturedRoutes() used to run before each new prefix was recorded as
excluded. So a route covered by the most recently added exclusion could stay
cloned into the tunnel until the next route change notification. Example:
excluding 192.168.1.0/24 while default route capture is on left
192.168.1.0/24 → tunnel in place. Captured routes are now updated after
the new prefixes are recorded, so this window is gone.

Complexity

N = number of exclusion prefixes, T₀ = size of the system routing table
before connecting (typically tens of rows). Normal case: all fetches
succeed, and capture is not counted.

before after
GetIpForwardTable2 calls N 1 per address family
rows copied from the kernel Σ(T₀+i) ≈ N²/2 T₀ per family
GetIpInterfaceTable calls N 1 per address family
next-hop scan Σ(T₀+i) ≈ N²/2 N·T₀
isRouteExcluded work (capture on) O(T·N²) O(T·N) once
per-prefix debug lines N·(1 + interfaces) 1 summary line + interfaces once
CreateIpForwardEntry2 calls up to N up to N (unchanged)

Testing

  • Host-side equivalence harness. The original and patched
    windowsroutemonitor.cpp were compiled on Linux (Qt 6.8, g++) against a
    stub IP Helper API backed by an in-memory routing table. Both were driven
    through the same scenarios, and the route rows were compared field by
    field (destination, interface, next hop, metric, protocol):

    • initial install of 8,664 prefixes (plus edge cases: exact matches of
      existing routes, longest-prefix and metric ties, loopback/multicast,
      bare addresses, IPv6, a duplicate inside the batch);
    • a default route change followed by routeChanged(), which re-points
      7,254 exclusion rows;
    • single add and duplicate add through addExclusionRoute(), then
      flushExclusionRoutes();
    • default route capture enabled with a tunnel default route present (the
      switchServer() case);
    • the first GetIpForwardTable2() call failing (that prefix fails, and
      the later ones recover);
    • the first three GetIpInterfaceTable() calls failing on a fresh
      monitor.

    The initial install was compared at N = 8,664, 1,500 and 11. The capture
    and failure scenarios use smaller lists, from 11 to 400 prefixes. Results
    are identical in every scenario except the capture-ordering correction
    described above. A deliberate mutation that stops retrying a failed
    interface table read is detected. Two earlier mutations were also
    detected (not recording batched rows, and skipping the interface metric
    refresh), but those mutant builds were not kept. The harness does not model notification delivery or the
    daemon lifecycle; those paths are unchanged apart from the daemon
    duplicate case described above.

    Counted with N = 8,664 and a 12-row system table:

    before after
    GetIpForwardTable2 calls 8,661 2
    rows copied from the kernel 37,014,431 12
    GetIpInterfaceTable calls 8,661 2
    log lines (all levels) 25,986 6
    CreateIpForwardEntry2 calls 8,534 8,534
  • Windows build. Built with the project's Build-Windows CI job
    (MSVC 2022, Qt 6.10.1) to an .msi: https://github.com/autumnfleet/amnezia-client/actions/runs/42018968655
    (fork CI with only this job enabled; the summary log string is present in
    the built AmneziaVPN-service.exe)

  • Real-world test. Windows 10 22H2 (x64), AmneziaWG, "all sites except"
    with the same Russian-IP list, using the MSI from the CI run above (the app reports
    commit 89618b6, which is this commit plus a fork-only CI workflow change).
    It is compared against stock 5.1.0.6 on the same machine, using one
    completed run per build. The runs were on different days, on different
    local networks and in a different boot state: the patched activation began
    about 2.5 minutes after boot. So the totals are indicative only. Times are from the service log (UTC).

    5.1.0.6 this PR
    Command received: activate → Connection status: 1 4 min 57 s (10:33:00.866 → 10:37:57.465) 24.6 s (16:36:48.927 → 16:37:13.528)
    installing the exclusion routes 4 min 49 s, 8,675 Adding exclusion route for lines 418 ms: Added 8673 of 8673 exclusion routes ( 8673 installed, 0 failed) in 418 ms, plus 2 single adds
    WindowsRouteMonitor lines in that window 30,428 12
    Wintun adapter creation (Creating Wintun interface → Using Wintun/0.14) 4.7 s 20.5 s

    Most of the patched run's 24.6 s was Wintun adapter creation: a device
    query timed out and WireGuard retried "because system just booted". That
    is unrelated to this change. The installed routes were not inspected with
    route print. The only evidence that they are correct on Windows is that
    the batch reported 8,673 installed and 0 failed, plus the host-side
    equivalence harness above. The two single adds after the batch logged the
    same Exclusion route already exists warning and Failed to update route: 87 error in both builds.

  • Not run: ctest, and builds or runs on Linux and macOS. On those
    platforms the daemon change goes through the default
    WireguardUtils::addExclusionRoutes(), which adds the routes one by one.

Known limitations not changed by this PR

  • NotifyRouteChange2() is registered for AF_INET only, so IPv6 route
    changes never trigger routeChanged(). This predates the PR. Its only new
    interaction is the snapshot window described above.
  • routeChanged() re-evaluates every exclusion against the full table on
    each notification, which is O(N·T) per notification. These rescans are
    still expensive with large lists, and they can delay the "connected"
    notification (next item).
  • The "connected" notification can still arrive minutes after activation.
    The daemon reports "connected" only from checkHandshake(), driven by a
    250 ms timer. After activation, routeChanged() rescans on the same
    thread appear to starve that timer. In the patched run above, the handshake had
    completed before Connection status: 1, but the first
    Checking for handshake... came 4 min 36 s later, and only then did the GUI
    show "connected". In the 5.1.0.6 run no handshake check appeared in the
    36.5 minutes of log after Connection status: 1. This PR does not touch that path. It is diagnosed in #2516 and
    #3114, which also include their own route batching, so maintainers may
    prefer to take batching from one of those. This PR is the smaller change,
    limited to the route install path.

🤖 Generated with Claude Code


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/amnezia-vpn/amnezia-client/pull/3425 **Author:** [@OstarkovSN](https://github.com/OstarkovSN) **Created:** 11/6/2026 **Status:** 🔄 Open **Base:** `dev` ← **Head:** `route-batch-dev` --- ### 📝 Commits (1) - [`ad35f50`](https://github.com/amnezia-vpn/amnezia-client/commit/ad35f50ce2b7745bc5f08ea0ae482e48c778d0a9) windows: add split tunnelling exclusion routes in one batch ### 📊 Changes **7 files changed** (+158 additions, -60 deletions) <details> <summary>View changed files</summary> 📝 `client/daemon/daemon.cpp` (+23 -14) 📝 `client/daemon/daemon.h` (+1 -1) 📝 `client/daemon/wireguardutils.h` (+14 -0) 📝 `client/platforms/windows/daemon/windowsroutemonitor.cpp` (+104 -39) 📝 `client/platforms/windows/daemon/windowsroutemonitor.h` (+6 -2) 📝 `client/platforms/windows/daemon/wireguardutilswindows.cpp` (+8 -4) 📝 `client/platforms/windows/daemon/wireguardutilswindows.h` (+2 -0) </details> ### 📄 Description ## Problem On Windows, "all sites except" split tunnelling with a large site list makes activation take minutes. The daemon installs one exclusion route per listed prefix, and each one re-reads the whole, growing, routing table. With about 8,700 prefixes, 5.1.0.6 took almost 5 minutes from `activate` to `Connection status: 1`. This PR fixes that slow route install, and only that. A separate issue remains after activation: the GUI can stay on "Connecting..." for minutes more, because the daemon's 250 ms `checkHandshake()` timer is starved while `routeChanged()` rescans run on the same thread. This PR does not change that path; see Known limitations. ## Observed symptom - AmneziaVPN 5.1.0.6 on Windows 10 22H2, AmneziaWG, "all sites except" mode with a Russian-IP bypass list: about 8,700 IPv4 prefixes (8,675 exclusion route add attempts in the run below). - In the service log, 4 min 57 s pass between `Command received: activate` and `Connection status: 1`, with 30,428 `WindowsRouteMonitor` lines in between, almost all of them from adding exclusion routes one by one. - The reporter also found that installing the same routes from a script (`netsh -f`, 500 commands per batch) is fast. That timing is not included here. It suggests, but does not prove, that creating the routes is not the bottleneck. The counts below locate the cost. ## Root cause In this mode every listed site becomes an entry in `excludedAddresses`, and `Daemon::activate()` (and `Daemon::switchServer()`) call `addExclusionRoute()` once per address. On Windows, `WindowsRouteMonitor::addExclusionRoute()` does the following for **every** prefix: 1. `GetIpForwardTable2()`: copies the whole routing table out of the kernel. The table grows by one row for each exclusion route already added. 2. `updateInterfaceMetrics()`: calls `GetIpInterfaceTable()` and writes one debug line per connected interface. 3. `updateCapturedRoutes(family, table)`: when default route capture is on, this calls `isRouteExcluded()`, which is linear in the number of exclusions, for every eligible system route. 4. `updateExclusionRoute()`: a linear scan of the table. 5. One more debug line. Every log line is flushed to the log file. For N prefixes the cost is O(N²) table rows copied out of the kernel and scanned. During `switchServer()`, where capture is already enabled, it adds O(T·N²) in `isRouteExcluded()`, where T is the number of system routes. For N = 8,664 that is about 37 million rows copied (see the measurements below). ## Fix - Add `WindowsRouteMonitor::addExclusionRoutes(const QList<IPAddress>&)`. For each address family it fetches the routing table and interface metrics once, then builds each exclusion row, computes its next hop against that snapshot with the existing `updateExclusionRoute()`, installs it, and records it in `m_exclusionRoutes`. `updateCapturedRoutes()` runs once at the end. A single summary line (`Added X of N exclusion routes (I installed, F failed) in T ms`) replaces the per-prefix debug lines. Interface, capture, warning and error lines are logged as before, but `updateInterfaceMetrics()` now runs once per family. - `addExclusionRoute()` keeps its signature, its log line and its return value, and now calls the batch with one prefix. The row initialisation moved verbatim into `initExclusionRow()`. - `updateExclusionRoute()` now returns `false` when `CreateIpForwardEntry2()` fails. It still logs the error as before. The batch uses the value only for the summary count, and `routeChanged()` ignores it. - `WireguardUtils` gets a virtual `addExclusionRoutes()` whose default adds the routes one by one, so Linux and macOS routing code is unchanged. Windows overrides it, and `excludeLocalNetworks()` uses it too. The daemon-level duplicate handling below applies to every platform. - `Daemon::addExclusionRoute()` is replaced by `Daemon::addExclusionRoutes()`. It applies the same `m_excludedAddrSet` reference counting, but collects the not-yet-excluded prefixes and adds them in one call. One difference: if a prefix appears twice in the list and the first attempt fails, the old loop tried again on the second occurrence. The new code does not. - `updateInterfaceMetrics()` now returns whether it read the interface table. The batch keeps calling it for each prefix until it succeeds, which matches the old per-prefix retry. ### Why the result is the same `updateExclusionRoute()` skips every route with the same protocol and metric as the row being placed: `MIB_IPPROTO_NETMGMT` with `EXCLUSION_ROUTE_METRIC`, which are the exclusion routes this monitor creates. It also skips routes on the VPN interface, which is where captured routes go. So the rows created earlier in a batch can never change the next hop chosen for a later prefix, and, as long as the system routes and interface metrics stay the same, one snapshot gives the same answer as re-reading the table every time. If another program changes the IPv4 routing table during the batch, the existing `NotifyRouteChange2()` → `routeChanged()` path re-evaluates every entry of `m_exclusionRoutes` afterwards, and the batched rows are in it, as before. IPv6 has no such notification (see Known limitations). An IPv6 gateway change during the batch is therefore not picked up by the remaining IPv6 prefixes of that batch, which the per-prefix loop could have seen. The batch now runs for milliseconds to seconds instead of minutes. A transient `GetIpForwardTable2()` failure fails only the prefix that hit it. The next prefix tries the fetch again, as the per-prefix code did. ### Intentional behaviour change `updateCapturedRoutes()` used to run before each new prefix was recorded as excluded. So a route covered by the most recently added exclusion could stay cloned into the tunnel until the next route change notification. Example: excluding `192.168.1.0/24` while default route capture is on left `192.168.1.0/24 → tunnel` in place. Captured routes are now updated after the new prefixes are recorded, so this window is gone. ## Complexity N = number of exclusion prefixes, T₀ = size of the system routing table before connecting (typically tens of rows). Normal case: all fetches succeed, and capture is not counted. | | before | after | |---|---|---| | `GetIpForwardTable2` calls | N | 1 per address family | | rows copied from the kernel | Σ(T₀+i) ≈ N²/2 | T₀ per family | | `GetIpInterfaceTable` calls | N | 1 per address family | | next-hop scan | Σ(T₀+i) ≈ N²/2 | N·T₀ | | `isRouteExcluded` work (capture on) | O(T·N²) | O(T·N) once | | per-prefix debug lines | N·(1 + interfaces) | 1 summary line + interfaces once | | `CreateIpForwardEntry2` calls | up to N | up to N (unchanged) | ## Testing - **Host-side equivalence harness.** The original and patched `windowsroutemonitor.cpp` were compiled on Linux (Qt 6.8, g++) against a stub IP Helper API backed by an in-memory routing table. Both were driven through the same scenarios, and the route rows were compared field by field (destination, interface, next hop, metric, protocol): - initial install of 8,664 prefixes (plus edge cases: exact matches of existing routes, longest-prefix and metric ties, loopback/multicast, bare addresses, IPv6, a duplicate inside the batch); - a default route change followed by `routeChanged()`, which re-points 7,254 exclusion rows; - single add and duplicate add through `addExclusionRoute()`, then `flushExclusionRoutes()`; - default route capture enabled with a tunnel default route present (the `switchServer()` case); - the first `GetIpForwardTable2()` call failing (that prefix fails, and the later ones recover); - the first three `GetIpInterfaceTable()` calls failing on a fresh monitor. The initial install was compared at N = 8,664, 1,500 and 11. The capture and failure scenarios use smaller lists, from 11 to 400 prefixes. Results are identical in every scenario except the capture-ordering correction described above. A deliberate mutation that stops retrying a failed interface table read is detected. Two earlier mutations were also detected (not recording batched rows, and skipping the interface metric refresh), but those mutant builds were not kept. The harness does not model notification delivery or the daemon lifecycle; those paths are unchanged apart from the daemon duplicate case described above. Counted with N = 8,664 and a 12-row system table: | | before | after | |---|---|---| | `GetIpForwardTable2` calls | 8,661 | 2 | | rows copied from the kernel | 37,014,431 | 12 | | `GetIpInterfaceTable` calls | 8,661 | 2 | | log lines (all levels) | 25,986 | 6 | | `CreateIpForwardEntry2` calls | 8,534 | 8,534 | - **Windows build.** Built with the project's `Build-Windows` CI job (MSVC 2022, Qt 6.10.1) to an `.msi`: https://github.com/autumnfleet/amnezia-client/actions/runs/42018968655 (fork CI with only this job enabled; the summary log string is present in the built `AmneziaVPN-service.exe`) - **Real-world test.** Windows 10 22H2 (x64), AmneziaWG, "all sites except" with the same Russian-IP list, using the MSI from the CI run above (the app reports commit `89618b6`, which is this commit plus a fork-only CI workflow change). It is compared against stock 5.1.0.6 on the same machine, using one completed run per build. The runs were on different days, on different local networks and in a different boot state: the patched activation began about 2.5 minutes after boot. So the totals are indicative only. Times are from the service log (UTC). | | 5.1.0.6 | this PR | |---|---|---| | `Command received: activate` → `Connection status: 1` | 4 min 57 s (10:33:00.866 → 10:37:57.465) | 24.6 s (16:36:48.927 → 16:37:13.528) | | installing the exclusion routes | 4 min 49 s, 8,675 `Adding exclusion route for` lines | 418 ms: `Added 8673 of 8673 exclusion routes ( 8673 installed, 0 failed) in 418 ms`, plus 2 single adds | | `WindowsRouteMonitor` lines in that window | 30,428 | 12 | | Wintun adapter creation (`Creating Wintun interface` → `Using Wintun/0.14`) | 4.7 s | 20.5 s | Most of the patched run's 24.6 s was Wintun adapter creation: a device query timed out and WireGuard retried "because system just booted". That is unrelated to this change. The installed routes were not inspected with `route print`. The only evidence that they are correct on Windows is that the batch reported 8,673 installed and 0 failed, plus the host-side equivalence harness above. The two single adds after the batch logged the same `Exclusion route already exists` warning and `Failed to update route: 87` error in both builds. - **Not run:** `ctest`, and builds or runs on Linux and macOS. On those platforms the daemon change goes through the default `WireguardUtils::addExclusionRoutes()`, which adds the routes one by one. ## Known limitations not changed by this PR - `NotifyRouteChange2()` is registered for `AF_INET` only, so IPv6 route changes never trigger `routeChanged()`. This predates the PR. Its only new interaction is the snapshot window described above. - `routeChanged()` re-evaluates every exclusion against the full table on each notification, which is O(N·T) per notification. These rescans are still expensive with large lists, and they can delay the "connected" notification (next item). - The "connected" notification can still arrive minutes after activation. The daemon reports "connected" only from `checkHandshake()`, driven by a 250 ms timer. After activation, `routeChanged()` rescans on the same thread appear to starve that timer. In the patched run above, the handshake had completed before `Connection status: 1`, but the first `Checking for handshake...` came 4 min 36 s later, and only then did the GUI show "connected". In the 5.1.0.6 run no handshake check appeared in the 36.5 minutes of log after `Connection status: 1`. This PR does not touch that path. It is diagnosed in #2516 and #3114, which also include their own route batching, so maintainers may prefer to take batching from one of those. This PR is the smaller change, limited to the route install path. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No labels
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
amnezia-vpn/amnezia-client#3292
No description provided.