[PR #3327] feat: follow server IP changes behind the host name without a manual reconnect #3198

Open
opened 2026-10-27 06:18:54 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/amnezia-vpn/amnezia-client/pull/3327
Author: @justSunny12
Created: 10/26/2026
Status: 🔄 Open

Base: dev ← Head: feat/reresolve-endpoint-on-stale-handshake


📝 Commits (1)

  • 1b3ae0a feat: follow server IP changes behind the host name without a manual reconnect

📊 Changes

25 files changed (+741 additions, -6 deletions)

View changed files

📝 .github/workflows/deploy.yml (+3 -0)
📝 client/android/protocolApi/src/main/kotlin/Protocol.kt (+9 -1)
📝 client/android/src/org/amnezia/vpn/AmneziaVpnService.kt (+1 -1)
📝 client/android/utils/src/main/kotlin/net/NetworkUtils.kt (+10 -0)
➕ client/android/wireguard/src/main/kotlin/org/amnezia/vpn/protocol/wireguard/EndpointWatchdog.kt (+71 -0)
📝 client/android/wireguard/src/main/kotlin/org/amnezia/vpn/protocol/wireguard/Wireguard.kt (+94 -1)
📝 client/android/wireguard/src/main/kotlin/org/amnezia/vpn/protocol/wireguard/WireguardConfig.kt (+2 -1)
📝 client/cmake/sources.cmake (+2 -0)
📝 client/core/protocols/vpnProtocol.h (+3 -0)
📝 client/core/protocols/wireGuardProtocol.cpp (+56 -2)
📝 client/core/protocols/wireGuardProtocol.h (+16 -0)
➕ client/core/utils/endpointWatchdog.cpp (+53 -0)
➕ client/core/utils/endpointWatchdog.h (+56 -0)
📝 client/daemon/daemon.cpp (+3 -0)
📝 client/ios/networkextension/CMakeLists.txt (+1 -0)
📝 client/macos/networkextension/CMakeLists.txt (+1 -0)
📝 client/mozilla/controllerimpl.h (+5 -0)
📝 client/mozilla/localsocketcontroller.cpp (+7 -0)
➕ client/platforms/ios/EndpointWatchdog.swift (+75 -0)
📝 client/platforms/ios/PacketTunnelProvider+WireGuard.swift (+100 -0)

...and 5 more files

📄 Description

Problem

A WireGuard/AWG config can name the server by host name (Endpoint = vpn.example.com:443). The client resolves that name once per connection and keeps using the resulting IP. When the address behind the name changes, every connected device keeps sending to the old IP and stays offline until the user toggles the tunnel by hand.

This happens in practice when:

  • a self-hosted server fails over to a standby: the DNS record is switched to the standby, which has the same keys;
  • a server is moved to another hosting or region and the DNS record is updated;
  • the server has a dynamic IP behind DDNS;
  • the provider changes the server's IP during maintenance.

In all these cases the server side cannot fix it, and the user often doesn't understand why "the VPN is connected but nothing works".

Why nothing recovers today (checked against dev @ 3121775 and amneziawg-apple @ bdaf0b3):

Platform Where the name is resolved What happens later
Windows / Linux / macOS (daemon) WireguardProtocol::startMzImpl() overwrites hostName in m_rawConfig with the IP Reconnects on networkChanged / wakeup call start() again, but the config already holds the IP, so they reuse the old address
Android parseInetAddress() in Wireguard.configWireguard() reconnectVpn() reuses the saved WireguardConfig with the resolved address
iOS WireGuardAdapter.start() → resolvePeers() didReceivePathUpdate() → endpointUapiConfiguration() re-resolves the already resolved IP (resolvedEndpoints) for NAT64 synthesis, not the host name
macOS (NE) same as iOS path updates only call wgBumpSockets()

The engine cannot recover on its own either:

  • No re-resolution. amneziawg-go never resolves names. After MaxHandshakeAttempts it gives up until the next outgoing packet.
  • No roaming. Android and iOS call DisableSomeRoamingForBrokenMobileSemantics(), so a packet from a new source address doesn't move the endpoint. Even without that, stateful NAT drops packets from an address the device didn't contact.

Solution

Detect a tunnel that is up on the device but no longer reaches its server, then resolve the configured host name again. The detection rule is the one from wireguard-tools' contrib/reresolve-dns: the latest handshake is older than a rekey cycle while the device keeps sending to the peer.

A live session with traffic or PersistentKeepalive renews its handshake every 120 s (REKEY_AFTER_TIME); a failed renewal is retried for 90 s more (REKEY_ATTEMPT_TIME). So "no handshake for 180 s and tx grew during that window" means the server is unreachable.

An idle tunnel without keepalive never handshakes and sends nothing, so it is never treated as stale. Before the first handshake, the age is counted from the tunnel start.

The same small state machine is implemented on every platform. It is pure logic with no I/O, and the C++ version is unit-tested:

  • client/core/utils/endpointWatchdog.{h,cpp} — desktop, with client/tests/testEndpointWatchdog.cpp
  • client/android/wireguard/.../EndpointWatchdog.kt
  • client/platforms/ios/EndpointWatchdog.swift

It also rate-limits refreshes: the delay doubles after each attempt and resets on the next successful handshake.

Desktop (Windows, Linux, macOS with daemon)

  • WireguardProtocol keeps the host names exactly as configured and resolves them on every start(). This alone makes the existing reconnects on network change and wakeup follow DNS changes.
  • If resolution fails at start, the last address that worked is used, so a short DNS outage right after the old tunnel went down (e.g. with the kill switch on) doesn't break the reconnect.
  • While the tunnel is up and the endpoint is a host name, WireguardProtocol polls checkStatus() every 20 s.
  • The daemon's status reply gets an optional lastHandshake field (ms since epoch, from PeerStatus::m_handshake). LocalSocketController emits it as the new ControllerImpl::peerStatusUpdated() signal.
  • When the tunnel is stale, the protocol emits the new VpnProtocol::reconnectRequested(). VpnConnection::onProtocolReconnectRequested() restarts the protocol exactly like reconnectToVpn(), but without requiring the Connected state: after a reconnect to an unreachable server the UI state may already be different.
  • DNS cannot be queried while a dead full tunnel holds the routes, so desktop reconnects instead of comparing addresses first. The backoff is 3 min, doubling up to 30 min. A reconnect to a dead tunnel costs nothing, since no traffic was flowing anyway.

Android

  • Wireguard remembers the configured host name (null for IP literals; new isNumericAddress() in utils, which never queries DNS).
  • A coroutine polls awgGetConfig() every 20 s. When the tunnel is stale, it resolves the name on an underlying network (Network.getAllByName() on a non-VPN network with INTERNET), because DNS through the dead tunnel doesn't work.
  • It reconnects only if the address changed, preferring the same address family. WireguardConfig.endpoint becomes a var. The protocol asks the service through a new optional requestReconnect parameter of Protocol.initialize() (default {}, so other protocols are untouched), and AmneziaVpnService passes its existing reconnect().
  • DNS is asked at most once a minute while the tunnel stays stale.

iOS and macOS (Network Extension)

  • PacketTunnelProvider keeps the started TunnelConfiguration and polls getRuntimeConfiguration() every 20 s on its own queue.
  • When the tunnel is stale, it resolves the endpoint with WireGuardKit's own DNSResolver.resolveSync() and compares the result with the address the name had at tunnel start. Comparing with the engine's runtime endpoint would be wrong on NAT64 networks, where it holds a synthesized IPv6.
  • If the address changed, it calls the public WireGuardAdapter.update(tunnelConfiguration:), which resolves peers again and applies the configuration. No change to the amneziawg-apple submodule is needed.
  • DNS is asked at most once a minute while the tunnel stays stale. The watch restarts on startWireguard() and on a configuration switch from the app, and stops in stopWireguard().

Behaviour

Situation Before After
Name's IP changed, old IP dead offline until manual reconnect back online ~3.5 min after the old IP stopped answering (180 s + one poll); desktop then reconnects, mobile switches only if DNS really changed
Server down, IP unchanged offline, "connected" mobile: DNS checked once a minute, nothing else. Desktop: reconnect every 3 → 6 → … → 30 min until the server is back
Healthy tunnel — a status poll every 20 s, nothing else
Idle tunnel without keepalive — never considered stale
Endpoint is an IP literal — not watched, behaviour unchanged
Older daemon with newer client (or vice versa) — field is optional on both ends; the watch is just inactive

Only WireGuard and AWG are affected. OpenVPN, Xray and IKEv2 code paths are untouched.

Backward compatibility

  • Configs. No format change: the existing hostName is used.
  • Daemon IPC. One optional field in the status reply.
  • Android API. Protocol.initialize() gets a new parameter with a default value.
  • amneziawg-go / amneziawg-android / amneziawg-apple. Untouched: only already exported or public APIs are used (awgGetConfig, UAPI last_handshake_time_* / tx_bytes, WireGuardAdapter.update, DNSResolver.resolveSync).

Testing

Everything below was run on this branch (dev @ 3121775 + this change). All scripts and full logs are attached in the collapsible sections, so every step can be reproduced.

Environment

Host macOS 27.0.1, Apple Silicon (arm64), Xcode 27.1 (27A9275)
Linux Debian 13 (trixie), kernel 6.12.111 aarch64, in a Lima VM (vz)
Qt 6.10.1 (aqtinstall 3.3.0): macos, ios, android_arm64_v8a, linux_gcc_arm64
Build tools conan 2.28.0, cmake 3.31.10, ninja 1.13.2 — the versions used in .github/workflows/deploy.yml
Android JDK 17.0.21 (Temurin), NDK 27.0.11718014, platforms 28 and 36, build-tools 35.0.0 / 36.0.0, emulator 37.2.12 with system image android-35;google_apis;arm64-v8a r9
Engines under test Android: awg-go backend v3.1.20260814 (as built by recipes/awg-android). Linux desktop: amneziawg-go built by the project. Lab servers: AmneziaWG kernel module and amneziawg-tools 3.1.20260812. Android test servers: amneziawg-go @ 457d920a1a7d (userspace, netstack)
Submodules amneziawg-apple @ bdaf0b3 (unchanged)

Builds

All builds use deploy/build.sh as in CI. For Apple targets the generated Xcode project is built with signing disabled, because the team's provisioning profiles are not available outside CI.

Target Command Result
macOS (daemon), with tests AMNEZIA_BUILD_TESTS=ON deploy/build.sh --generator Ninja ✅ No new warnings in changed files
Linux arm64 (daemon), with tests same, CMAKE_PREFIX_PATH=<qt>/gcc_arm64 ✅ No new warnings in changed files
macOS NE deploy/build.sh -t macos-ne, then xcodebuild -target AmneziaVPNNetworkExtension CODE_SIGNING_ALLOWED=NO ✅ Extension (arm64 + x86_64) compiled and linked, no warnings in changed files ¹
iOS deploy/build.sh -t ios, then xcodebuild -target networkextension -sdk iphoneos CODE_SIGNING_ALLOWED=NO ✅ BUILD SUCCEEDED, no warnings in changed files
Android arm64 deploy/build.sh -t android --abi arm64-v8a --sign (throwaway keystore) ✅ All Kotlin modules incl. :compileOssReleaseKotlin and :compilePlayReleaseKotlin, signed APK

¹ The macOS NE app target fails on unchanged platforms/ios/LogController.swift (std.string(...): no exact matches) with the Xcode 27 SDK. That is unrelated to this change; CI uses Xcode 26.3.

Unit tests

ctest on the full test set. The new EndpointWatchdogTest is registered in client/tests/CMakeLists.txt and added to the three CI test matrices.

  • macOS: 27/27 passed
  • Linux arm64: 27/27 passed
ctest, Linux arm64
Test  #1: MultipleImportsTest ...................   Passed    1.05 sec
Test  #2: ServerEditTest ........................   Passed    1.05 sec
Test  #3: DefaultServerChangeTest ...............   Passed    1.05 sec
Test  #4: ServerEdgeCasesTest ...................   Passed    1.05 sec
Test  #5: SignalOrderTest .......................   Passed    1.10 sec
Test  #6: ServersModelSyncTest ..................   Passed    1.10 sec
Test  #7: ServerRenameTest ......................   Passed    1.09 sec
Test  #8: SettingsSignalsTest ...................   Passed    3.21 sec
Test  #9: UiServersModelAndControllerTest .......   Passed    1.11 sec
Test #10: XraySerializationTest .................   Passed    1.11 sec
Test #11: ConfigFormatVersionTest ...............   Passed    1.11 sec
Test #12: UiLanguageModelAndControllerTest ......   Passed    1.07 sec
Test #13: UiIpModelAndControllerTest ............   Passed    1.16 sec
Test #14: UiAppSTModelAndControllerTest .........   Passed    1.07 sec
Test #15: UiAllowedDnsModelAndControllerTest ....   Passed    1.07 sec
Test #16: BackupExportImportTest ................   Passed    1.01 sec
Test #17: FavoriteLocationsRestoreTest ..........   Passed    1.02 sec
Test #18: ConnectionTest ........................   Passed    0.98 sec
Test #19: OpenSSLLibraryTest ....................   Passed    0.04 sec
Test #20: LogsControllerTest ....................   Passed    0.03 sec
Test #21: EndpointWatchdogTest ..................   Passed    0.03 sec
Test #22: AdminSelfHostedExportTest .............   Passed    0.99 sec
Test #23: SelfHostedServerSetupTest .............   Passed    0.99 sec
Test #24: MultipleExportsTest ...................   Passed    0.98 sec
Test #25: UiApiServicesModelAndControllerTest ...   Passed    0.98 sec
Test #26: UiNewsModelAndControllerTest ..........   Passed    1.00 sec
Test #27: GatewayServiceImportTest ..............   Passed    1.00 sec
100% tests passed, 0 tests failed out of 27
EndpointWatchdogTest, macOS (per test function)
********* Start testing of TestEndpointWatchdog *********
Config: Using QtTest library 6.10.1, Qt 6.10.1 (arm64-little_endian-lp64 shared (dynamic) release build; by Apple LLVM 16.0.0 (clang-1600.0.26.3)), macos 27.0.1
PASS   : TestEndpointWatchdog::initTestCase()
PASS   : TestEndpointWatchdog::liveTunnelIsNotStale()
PASS   : TestEndpointWatchdog::sendingWithoutHandshakeIsStale()
PASS   : TestEndpointWatchdog::neverHandshakedSinceStartIsStale()
PASS   : TestEndpointWatchdog::idleTunnelWithoutKeepaliveIsNotStale()
PASS   : TestEndpointWatchdog::refreshIsRepeatedWithGrowingDelay()
PASS   : TestEndpointWatchdog::handshakeResetsTheDelay()
PASS   : TestEndpointWatchdog::counterResetAfterRestartIsNotTraffic()
PASS   : TestEndpointWatchdog::cleanupTestCase()
Totals: 9 passed, 0 failed, 0 skipped, 0 blacklisted, 1ms
********* Finished testing of TestEndpointWatchdog *********

Live scenarios

Every scenario uses real AmneziaWG timers and has two servers with the same keys and AWG parameters:

  • A — the server the client starts on;
  • B — the standby that the host name vpn.test is moved to.

The client config uses Endpoint = vpn.test:51820 and PersistentKeepalive 25, except where stated.

# Platform Setup Scenario Expected Result
1 AWG kernel, rule only 3 netns, client = kernel AWG; the stale verdict comes from endpointWatchdog.cpp itself, fed with awg show dump every 20 s A dies, vpn.test → B refresh → endpoint B ✅ refresh at 191 s, back online via B, 180 s offline
2 AWG kernel, rule only same, no keepalive, no traffic A dies, vpn.test → B; user traffic starts at 312 s no refresh while idle; refresh as soon as traffic is not answered ✅ nothing for 312 s, refresh 20 s after traffic started
3 AWG kernel, rule only same A dies, vpn.test stays on A refresh once a minute, endpoint kept ✅ 5 checks, endpoint unchanged
4 Android app, emulator release APK; full tunnel 0.0.0.0/0, DNS inside the tunnel (so DNS through the dead tunnel cannot work) A dies, vpn.test → B app resolves outside the tunnel and reconnects to B ✅ it moved to …: reconnecting, handshake with B, 160 s offline
5 Android app, emulator same A dies, vpn.test stays on A DNS checked once a minute, no reconnect ✅ 4 checks, 0 reconnects
6 Linux desktop: real AmneziaVPN-service (root) + VpnConnection client netns behind a router netns; config imported and connected through ConnectionUiController::toggleConnection() A dies, vpn.test → B reconnect, name resolved again, Connected on B ✅ Reconnecting at 180 s, Connected at 184 s, ping through the tunnel, 155 s offline
7 Linux desktop, same same A dies, vpn.test stays on A reconnects with backoff, not in a loop ✅ 2 reconnects in 12 min (180 s, 380 s; the next one is due ≥ 740 s)

Not run live: iOS and macOS NE. A Network Extension doesn't run in the simulator and needs provisioning to run on a device. Both extensions compile and link with the change.

The Swift watchdog passes the same scenarios as the C++ one, and the Apple code path uses only WireGuardKit's own DNSResolver.resolveSync() and the public WireGuardAdapter.update().

Scenarios 1–3: log
=== moved 420
     0s  connected via 198.51.100.2
    30s  server A goes down
    31s  vpn.test now resolves to 203.0.113.2
   191s  STALE (handshake 191s ago, tx=1832): 198.51.100.2:51820 -> 203.0.113.2:51820
   211s  BACK ONLINE via B: offline for 180s
RESULT moved: PASS
=== idle 600
     0s  connected via 198.51.100.2
    31s  server A goes down
    31s  vpn.test now resolves to 203.0.113.2
   312s  user traffic starts
   332s  STALE (handshake 332s ago, tx=1284): 198.51.100.2:51820 -> 203.0.113.2:51820
   352s  BACK ONLINE via B: offline for 321s
RESULT idle: PASS (moved only after traffic)
=== dead 420
     0s  connected via 198.51.100.2
    30s  server A goes down
   191s  STALE (handshake 191s ago, tx=1980): address unchanged, nothing to do
   251s  STALE (handshake 251s ago, tx=3460): address unchanged, nothing to do
   311s  STALE (handshake 311s ago, tx=4644): address unchanged, nothing to do
   371s  STALE (handshake 371s ago, tx=6420): address unchanged, nothing to do
   431s  STALE (handshake 431s ago, tx=7456): address unchanged, nothing to do
RESULT dead: PASS (5 checks, endpoint kept)
Scenario 4 (Android, moved): log
22s  emulator booted
    32s  app installed
    37s  connected to A
    67s  server A goes down, vpn.test -> 192.168.1.207
   227s  handshake with B: offline for 160s
    10-26 14:51:24.262 I/Wireguard( 3538): No handshake with vpn.test, it moved to 192.168.1.207: reconnecting
RESULT android: PASS
Scenario 5 (Android, dead): log
14s  emulator booted
    22s  app installed
    26s  connected to A
    56s  server A goes down, vpn.test stays on 10.0.2.2
    10-26 14:52:45.017 I/Wireguard( 2911): awg-go backend v3.1.20260814
    10-26 14:55:45.099 I/Wireguard( 2911): No handshake with vpn.test, its address is unchanged
    10-26 14:56:45.113 I/Wireguard( 2911): No handshake with vpn.test, its address is unchanged
    10-26 14:57:45.123 I/Wireguard( 2911): No handshake with vpn.test, its address is unchanged
    10-26 14:58:45.141 I/Wireguard( 2911): No handshake with vpn.test, its address is unchanged
RESULT android-dead: PASS (4 checks, no reconnect)
Scenario 6 (desktop, moved): log
2s  service: /var/tmp/build-linux/service/server/AmneziaVPN-service
     7s  connected to A
    37s  server A goes down, vpn.test -> 203.0.113.2
   192s  handshake with B and ping through the tunnel: offline for 155s
    E2E     0s imported, connecting
    E2E     0s state Connecting...
    E2E     0s state Connected
    WireguardProtocol: no handshake with "vpn.test" while sending, reconnecting to resolve its address again
    Reconnect requested by the protocol: the server stopped answering
    E2E   180s state Reconnecting...
    E2E   184s state Connected
    E2E   480s done, disconnecting
    E2E   480s state Disconnecting...
    E2E   480s state Disconnected
RESULT desktop: PASS
Scenario 7 (desktop, dead): log
2s  service: /var/tmp/build-linux/service/server/AmneziaVPN-service
     7s  connected to A
    37s  server A goes down, vpn.test stays on A
    E2E     0s imported, connecting
    E2E     0s state Connecting...
    E2E     0s state Connected
    WireguardProtocol: no handshake with "vpn.test" while sending, reconnecting to resolve its address again
    Reconnect requested by the protocol: the server stopped answering
    E2E   180s state Reconnecting...
    WireguardProtocol: no handshake with "vpn.test" while sending, reconnecting to resolve its address again
    Reconnect requested by the protocol: the server stopped answering
    E2E   380s state Reconnecting...
    E2E   720s done, disconnecting
    E2E   720s state Disconnecting...
RESULT desktop-dead: PASS (2 reconnects with backoff)

Test harness (not part of the change)

e2e.sh — scenarios 1–3 (Linux, root, network namespaces)
#!/usr/bin/env bash
# Live check of the stale-tunnel rule on real AmneziaWG timers.
#
#   cli ── veth ── srvA (198.51.100.2)    both servers: same private key,
#     └─── veth ── srvB (203.0.113.2)     same tunnel address 10.8.0.1
#
# The client names its server "vpn.test" (/etc/netns/cli/hosts). Every 20 s the
# loop feeds `awg show dump` of the client into EndpointWatchdog (the C++ class
# of the change); when it says "refresh", the name is resolved again and, if the
# address changed, set as the new endpoint - what the Android / iOS code does.
#
# usage: e2e.sh <scenario> [seconds]
#   moved      keepalive 25, server A dies and the name moves to B
#   idle       no keepalive, no traffic: A dies, nothing must happen; then
#              traffic starts and the client must move to B
#   dead       keepalive 25, A dies, the name stays on A: refresh is attempted
#              once a minute, the endpoint is never changed
set -u
SCEN=${1:?scenario}
DUR=${2:-480}
BIN=/var/tmp/awge2e/driver
POLL=20

say() { printf '%6ss  %s\n' "$(( $(date +%s) - T0 ))" "$*"; }
nsx() { local ns=$1; shift; sudo ip netns exec "$ns" "$@"; }

cleanup() {
    for ns in cli srvA srvB; do sudo ip netns del $ns 2>/dev/null; done
    sudo rm -rf /etc/netns/cli
}
trap cleanup EXIT
cleanup

SRV_KEY=$(awg genkey); SRV_PUB=$(echo "$SRV_KEY" | awg pubkey)
CLI_KEY=$(awg genkey); CLI_PUB=$(echo "$CLI_KEY" | awg pubkey)

for ns in cli srvA srvB; do sudo ip netns add $ns; nsx $ns ip link set lo up; done
sudo ip link add va netns cli type veth peer name va netns srvA
sudo ip link add vb netns cli type veth peer name vb netns srvB
nsx cli  ip addr add 198.51.100.1/24 dev va; nsx cli ip link set va up
nsx srvA ip addr add 198.51.100.2/24 dev va; nsx srvA ip link set va up
nsx cli  ip addr add 203.0.113.1/24 dev vb; nsx cli ip link set vb up
nsx srvB ip addr add 203.0.113.2/24 dev vb; nsx srvB ip link set vb up

for ns in srvA srvB; do
    nsx $ns ip link add awg0 type amneziawg
    nsx $ns bash -c "awg set awg0 private-key <(echo $SRV_KEY) listen-port 51820 peer $CLI_PUB allowed-ips 10.8.0.2/32"
    nsx $ns ip addr add 10.8.0.1/24 dev awg0; nsx $ns ip link set awg0 up
done

sudo mkdir -p /etc/netns/cli
printf '127.0.0.1 localhost\n198.51.100.2 vpn.test\n' | sudo tee /etc/netns/cli/hosts >/dev/null
KA=25; [ "$SCEN" = idle ] && KA=0
resolve() { nsx cli getent hosts vpn.test | awk '{print $1; exit}'; }
nsx cli ip link add awg0 type amneziawg
nsx cli bash -c "awg set awg0 private-key <(echo $CLI_KEY) peer $SRV_PUB allowed-ips 10.8.0.0/24 endpoint $(resolve):51820 persistent-keepalive $KA"
nsx cli ip addr add 10.8.0.2/24 dev awg0; nsx cli ip link set awg0 up

coproc DRV { "$BIN" 60000 60000; }
T0=$(date +%s)
echo "start $((T0 * 1000))" >&"${DRV[1]}"; read -r _ <&"${DRV[0]}"

nsx cli ping -c1 -W2 10.8.0.1 >/dev/null && say "connected via $(resolve)" || say "FIRST HANDSHAKE FAILED"
[ "$SCEN" = idle ] && nsx cli ping -c3 -i0.3 -W2 10.8.0.1 >/dev/null

TRAFFIC_PID=""
sleep 30
say "server A goes down"
nsx srvA ip link set awg0 down
if [ "$SCEN" != dead ]; then
    printf '127.0.0.1 localhost\n203.0.113.2 vpn.test\n' | sudo tee /etc/netns/cli/hosts >/dev/null
    say "vpn.test now resolves to $(resolve)"
fi

IDLE_BAD=""; MOVED=""; DOWN_AT=$(( $(date +%s) - T0 )); REFRESHES=0
while (( $(date +%s) - T0 < DUR )); do
    if [ "$SCEN" = idle ] && [ -z "$TRAFFIC_PID" ] && (( $(date +%s) - T0 >= DUR / 2 )); then
        say "user traffic starts"
        nsx cli ping -i5 -W1 10.8.0.1 >/dev/null 2>&1 &
        TRAFFIC_PID=$!
    fi
    sleep $POLL
    line=$(nsx cli awg show awg0 dump | sed -n 2p)
    ep=$(echo "$line" | awk '{print $3}'); hs=$(echo "$line" | awk '{print $5}'); tx=$(echo "$line" | awk '{print $7}')
    echo "$(( $(date +%s) * 1000 )) $(( hs * 1000 )) $tx" >&"${DRV[1]}"; read -r verdict <&"${DRV[0]}"
    age=$(( hs > 0 ? $(date +%s) - hs : -1 ))
    if [ "$verdict" = 1 ]; then
        REFRESHES=$((REFRESHES + 1))
        [ "$SCEN" = idle ] && [ -z "$TRAFFIC_PID" ] && IDLE_BAD=1
        new=$(resolve)
        if [ "${ep%:*}" != "$new" ]; then
            nsx cli awg set awg0 peer "$SRV_PUB" endpoint "$new:51820"
            say "STALE (handshake ${age}s ago, tx=$tx): $ep -> $new:51820"
        else
            say "STALE (handshake ${age}s ago, tx=$tx): address unchanged, nothing to do"
        fi
    fi
    if [ -z "$MOVED" ] && [ "$ep" = "203.0.113.2:51820" ] && (( hs > 0 )) && (( $(date +%s) - hs < 30 )) \
        && nsx cli ping -c1 -W2 10.8.0.1 >/dev/null; then
        MOVED=$(( $(date +%s) - T0 ))
        say "BACK ONLINE via B: offline for $(( MOVED - DOWN_AT ))s"
    fi
done
[ -n "$TRAFFIC_PID" ] && sudo kill "$TRAFFIC_PID" 2>/dev/null

case "$SCEN" in
    moved) [ -n "$MOVED" ] && echo "RESULT moved: PASS" || echo "RESULT moved: FAIL" ;;
    idle)  [ -n "$MOVED" ] && [ -z "$IDLE_BAD" ] && echo "RESULT idle: PASS (moved only after traffic)" || echo "RESULT idle: FAIL" ;;
    dead)  [ -z "$MOVED" ] && (( REFRESHES >= 2 )) && echo "RESULT dead: PASS ($REFRESHES checks, endpoint kept)" \
               || echo "RESULT dead: FAIL ($REFRESHES checks)" ;;
esac
driver.cpp — feeds `awg show dump` samples into EndpointWatchdog
// Feeds "now_ms handshake_ms tx_bytes" lines to EndpointWatchdog, prints "1" when a
// refresh should happen (and records the attempt), "0" otherwise.
#include <cstdio>
#include <iostream>
#include <string>

#include "endpointWatchdog.h"

int main(int argc, char **argv)
{
    const int64_t first = argc > 1 ? std::stoll(argv[1]) : 60000;
    const int64_t max = argc > 2 ? std::stoll(argv[2]) : 60000;
    EndpointWatchdog w(first, max);
    int64_t now, hs;
    uint64_t tx;
    std::string cmd;
    while (std::cin >> cmd) {
        if (cmd == "start") {
            std::cin >> now;
            w.tunnelStarted(now);
            std::cout << "ok" << std::endl;
            continue;
        }
        now = std::stoll(cmd);
        std::cin >> hs >> tx;
        const bool refresh = w.observe(now, hs, tx);
        if (refresh) {
            w.refreshAttempted(now);
        }
        std::cout << (refresh ? 1 : 0) << std::endl;
    }
}
android-e2e.sh — scenarios 4–5 (macOS host, Android emulator)
#!/usr/bin/env bash
# Live check of the Android change in an emulator, no root on the host.
#   server A: awgsrv on 127.0.0.1:51820    (the emulator sees it as 10.0.2.2)
#   server B: awgsrv on $LAN_IP:51820       (same keys, same AWG params)
#   DNS:      dns.py, vpn.test from dns-vpn.txt (the emulator uses it via -dns-server)
# The app connects to vpn.test with a full tunnel (0.0.0.0/0, DNS inside the tunnel),
# then A dies and the record moves to B. Expect: the app notices, resolves vpn.test
# outside the tunnel, reconnects to B by itself.
#
# keys.txt (one line): server_private server_public client_private client_public, e.g.
#   S=$(awg genkey); C=$(awg genkey); echo $S $(echo $S | awg pubkey) $C $(echo $C | awg pubkey) > keys.txt
# usage: android-e2e.sh [moved|dead]
set -u
MODE=${1:-moved}   # moved: the record moves to B; dead: it stays on A
E=$(cd "$(dirname "$0")" && pwd)
T=~/.claude/awg-bot/upstream/toolchain
SDK=$T/android-sdk
ADB=$SDK/platform-tools/adb
APK=~/.claude/awg-bot/upstream/build-android/client/android-build/AmneziaVPN.apk
LAN_IP=${LAN_IP:-$(ipconfig getifaddr en0)}
export JAVA_HOME=$T/jdk/Contents/Home ANDROID_HOME=$SDK ANDROID_SDK_ROOT=$SDK ANDROID_AVD_HOME=$T/avd
T0=$(date +%s)
say() { printf '%6ss  %s\n' "$(( $(date +%s) - T0 ))" "$*"; }

read -r SK SP CK CP < "$E/keys.txt"
pkill -f "awgsrv -listen" 2>/dev/null
"$E/awgsrv/awgsrv" -listen 127.0.0.1 -priv "$SK" -peer "$CP" -name A > "$E/android-srvA.log" 2>&1 &
PID_A=$!
"$E/awgsrv/awgsrv" -listen "$LAN_IP" -priv "$SK" -peer "$CP" -name B > "$E/android-srvB.log" 2>&1 &
PID_B=$!
echo 10.0.2.2 > "$E/dns-vpn.txt"

mkdir -p "$ANDROID_AVD_HOME"
if [ ! -d "$ANDROID_AVD_HOME/awgtest.avd" ]; then
    echo no | "$SDK/cmdline-tools/latest/bin/avdmanager" create avd -n awgtest \
        -k "system-images;android-35;google_apis;arm64-v8a" -d pixel_6 >/dev/null
fi
"$SDK/emulator/emulator" -avd awgtest -no-window -no-audio -no-boot-anim -no-snapshot \
    -gpu swiftshader_indirect -dns-server 127.0.0.1 > "$E/emulator.log" 2>&1 &
PID_EMU=$!
trap 'kill $PID_A $PID_B 2>/dev/null; $ADB emu kill >/dev/null 2>&1; kill $PID_EMU 2>/dev/null' EXIT

$ADB wait-for-device
until [ "$($ADB shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = 1 ]; do sleep 3; done
say "emulator booted"
$ADB root >/dev/null; sleep 3; $ADB wait-for-device
$ADB install -r "$APK" >/dev/null && say "app installed"
$ADB shell appops set org.amnezia.vpn ACTIVATE_VPN allow
$ADB logcat -c

CFG=$(cat <<JSON
{"protocol":"awg","description":"e2e","dns1":"10.8.0.1","awg_config_data":{"client_ip":"10.8.0.2/32","allowed_ips":["0.0.0.0/0"],"hostName":"vpn.test","port":51820,"mtu":"1280","persistent_keep_alive":"25","client_priv_key":"$CK","server_pub_key":"$SP","Jc":"4","Jmin":"10","Jmax":"50","S1":"0","S2":"0","H1":"1","H2":"2","H3":"3","H4":"4"}}
JSON
)
$ADB shell "am start-foreground-service -n org.amnezia.vpn/.AwgService --es VPN_CONFIG '$CFG'" >/dev/null
$ADB logcat -v time > "$E/android-logcat.log" 2>&1 &
PID_LOG=$!
trap 'kill $PID_A $PID_B $PID_LOG 2>/dev/null; $ADB emu kill >/dev/null 2>&1; kill $PID_EMU 2>/dev/null' EXIT

for _ in $(seq 30); do
    grep -q "handshake=[1-9]" "$E/android-srvA.log" && break; sleep 2
done
grep -q "handshake=[1-9]" "$E/android-srvA.log" && say "connected to A" || { say "NO HANDSHAKE WITH A"; exit 1; }
sleep 30

if [ "$MODE" = dead ]; then
    say "server A goes down, vpn.test stays on 10.0.2.2"
    kill $PID_A
    sleep 360
    UNCHANGED=$(grep -c "its address is unchanged" "$E/android-logcat.log")
    RECONNECTS=$(grep -c "moved to" "$E/android-logcat.log")
    grep "I/Wireguard" "$E/android-logcat.log" | grep -v "lastHandshake=" | sed 's/^/    /'
    if (( UNCHANGED >= 2 && RECONNECTS == 0 )); then
        echo "RESULT android-dead: PASS ($UNCHANGED checks, no reconnect)"; exit 0
    fi
    echo "RESULT android-dead: FAIL ($UNCHANGED checks, $RECONNECTS reconnects)"; exit 1
fi

say "server A goes down, vpn.test -> $LAN_IP"
echo "$LAN_IP" > "$E/dns-vpn.txt"
kill $PID_A
DOWN=$(( $(date +%s) - T0 ))

for _ in $(seq 60); do
    sleep 10
    if grep -q "handshake=[1-9]" "$E/android-srvB.log"; then
        UP=$(( $(date +%s) - T0 ))
        say "handshake with B: offline for $(( UP - DOWN ))s"
        grep -E "Wireguard|AmneziaVpnService" "$E/android-logcat.log" | grep -iE "handshake with|moved|reconnect|resolve" | sed 's/^/    /'
        echo "RESULT android: PASS"
        exit 0
    fi
done
grep -E "Wireguard" "$E/android-logcat.log" | tail -20 | sed 's/^/    /'
echo "RESULT android: FAIL"
exit 1
awgsrv/main.go — rootless AmneziaWG test server (amneziawg-go + netstack), bound to one IP
// awgsrv: an AmneziaWG server on a gVisor netstack (no root needed), bound to
// one local IP so that two of them can share a port on different addresses.
// It answers ICMP echo on its tunnel address and prints the peer's handshake.
package main

import (
	"bufio"
	"encoding/base64"
	"encoding/hex"
	"flag"
	"fmt"
	"log"
	"net"
	"net/netip"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"github.com/amnezia-vpn/amneziawg-go/conn"
	"github.com/amnezia-vpn/amneziawg-go/device"
	"github.com/amnezia-vpn/amneziawg-go/tun/netstack"
)

type endpoint netip.AddrPort

func (e endpoint) ClearSrc()           {}
func (e endpoint) SrcToString() string { return "" }
func (e endpoint) DstToString() string { return netip.AddrPort(e).String() }
func (e endpoint) DstToBytes() []byte  { b, _ := netip.AddrPort(e).MarshalBinary(); return b }
func (e endpoint) DstIP() netip.Addr   { return netip.AddrPort(e).Addr() }
func (e endpoint) SrcIP() netip.Addr   { return netip.Addr{} }

type bind struct {
	addr netip.Addr
	udp  *net.UDPConn
}

func (b *bind) Open(port uint16) ([]conn.ReceiveFunc, uint16, error) {
	c, err := net.ListenUDP("udp4", net.UDPAddrFromAddrPort(netip.AddrPortFrom(b.addr, port)))
	if err != nil {
		return nil, 0, err
	}
	b.udp = c
	recv := func(packets [][]byte, sizes []int, eps []conn.Endpoint) (int, error) {
		n, a, err := c.ReadFromUDPAddrPort(packets[0])
		if err != nil {
			return 0, err
		}
		sizes[0] = n
		eps[0] = endpoint(netip.AddrPortFrom(a.Addr().Unmap(), a.Port()))
		return 1, nil
	}
	return []conn.ReceiveFunc{recv}, uint16(c.LocalAddr().(*net.UDPAddr).Port), nil
}

func (b *bind) Close() error {
	if b.udp != nil {
		return b.udp.Close()
	}
	return nil
}

func (b *bind) SetMark(uint32) error { return nil }

func (b *bind) Send(bufs [][]byte, ep conn.Endpoint) error {
	for _, buf := range bufs {
		if _, err := b.udp.WriteToUDPAddrPort(buf, netip.AddrPort(ep.(endpoint))); err != nil {
			return err
		}
	}
	return nil
}

func (b *bind) ParseEndpoint(s string) (conn.Endpoint, error) {
	ap, err := netip.ParseAddrPort(s)
	return endpoint(ap), err
}

func (b *bind) BatchSize() int { return 1 }

func hexKey(b64 string) string {
	raw, err := base64.StdEncoding.DecodeString(b64)
	if err != nil || len(raw) != 32 {
		log.Fatalf("bad key %q", b64)
	}
	return hex.EncodeToString(raw)
}

func main() {
	listen := flag.String("listen", "127.0.0.1", "local IP to bind")
	port := flag.Int("port", 51820, "UDP port")
	priv := flag.String("priv", "", "server private key (base64)")
	peer := flag.String("peer", "", "client public key (base64)")
	name := flag.String("name", "srv", "name for the log")
	awg := flag.String("awg", "jc=4\njmin=10\njmax=50\ns1=0\ns2=0\nh1=1\nh2=2\nh3=3\nh4=4", "AWG device params (UAPI lines)")
	flag.Parse()

	tunDev, _, err := netstack.CreateNetTUN([]netip.Addr{netip.MustParseAddr("10.8.0.1")}, nil, 1280)
	if err != nil {
		log.Fatal(err)
	}
	dev := device.NewDevice(tunDev, &bind{addr: netip.MustParseAddr(*listen)}, device.NewLogger(device.LogLevelError, *name+": "))
	conf := fmt.Sprintf("private_key=%s\nlisten_port=%d\n%s\npublic_key=%s\nallowed_ip=10.8.0.2/32\n",
		hexKey(*priv), *port, *awg, hexKey(*peer))
	if err := dev.IpcSet(conf); err != nil {
		log.Fatal(err)
	}
	if err := dev.Up(); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s: listening on %s:%d\n", *name, *listen, *port)

	go func() {
		for range time.Tick(5 * time.Second) {
			state, _ := dev.IpcGet()
			var hs, rx string
			sc := bufio.NewScanner(strings.NewReader(state))
			for sc.Scan() {
				l := sc.Text()
				if v, ok := strings.CutPrefix(l, "last_handshake_time_sec="); ok {
					hs = v
				}
				if v, ok := strings.CutPrefix(l, "rx_bytes="); ok {
					rx = v
				}
			}
			fmt.Printf("%s: %s handshake=%s rx=%s\n", *name, time.Now().Format("15:04:05"), hs, rx)
		}
	}()

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	<-sig
	dev.Close()
}
dns.py — test DNS for the emulator with a switchable record
"""Tiny DNS for the emulator: A record of vpn.test comes from dns-vpn.txt (re-read on
every query, so the record can be switched), everything else is forwarded to 1.1.1.1."""
import pathlib
import socket
import struct
import sys
import time

HERE = pathlib.Path(__file__).parent
REC = HERE / "dns-vpn.txt"
LISTEN = (sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1", 53)


def qname(data, off=12):
    labels = []
    while data[off]:
        n = data[off]
        labels.append(data[off + 1:off + 1 + n].decode())
        off += n + 1
    return ".".join(labels).lower(), off + 1


def answer(query, ip):
    tid = query[:2]
    name, end = qname(query)
    question = query[12:end + 4]
    head = tid + struct.pack(">HHHHH", 0x8180, 1, 1, 0, 0)
    rr = b"\xc0\x0c" + struct.pack(">HHIH", 1, 1, 5, 4) + socket.inet_aton(ip)
    return head + question + rr


def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(LISTEN)
    up = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    up.settimeout(3)
    print("dns on", LISTEN, flush=True)
    while True:
        data, addr = s.recvfrom(2048)
        try:
            name, end = qname(data)
            qtype = struct.unpack(">H", data[end:end + 2])[0]
        except Exception:
            continue
        if name == "vpn.test":
            ip = REC.read_text().strip()
            if qtype == 1:
                s.sendto(answer(data, ip), addr)
            else:  # AAAA etc: empty NOERROR
                s.sendto(data[:2] + struct.pack(">HHHHH", 0x8180, 1, 0, 0, 0) + data[12:end + 4], addr)
            print(time.strftime("%H:%M:%S"), "vpn.test", qtype, "->", ip, "from", addr, flush=True)
            continue
        try:
            up.sendto(data, ("1.1.1.1", 53))
            s.sendto(up.recvfrom(4096)[0], addr)
        except OSError:
            pass


main()
desktop-e2e.sh — scenarios 6–7 (Linux, real service and client)
#!/usr/bin/env bash
# Desktop end-to-end check on Linux: the real AmneziaVPN-service (as root) and the real
# client path (VpnConnection via desktop_e2e) run inside the "cli" network namespace.
#
#   cli (10.0.0.2) ── net (router, 10.0.0.1) ── srvA (198.51.100.2)   kernel AmneziaWG servers:
#                                             └─ srvB (203.0.113.2)   same keys, same AWG params
#
# The client config says Endpoint = vpn.test:51820 (/etc/netns/cli/hosts), full tunnel.
# After the connection is up, A dies and vpn.test moves to B. Expect: the client sees
# no handshake while sending, reconnects, resolves vpn.test again and comes up on B.
set -u
BUILD=${BUILD:-/var/tmp/build-linux}
DUR=${1:-480}
MODE=${2:-moved}   # moved: vpn.test moves to B; dead: it stays on A
W=/var/tmp/awge2e/desktop
mkdir -p $W
nsx() { local ns=$1; shift; sudo ip netns exec "$ns" "$@"; }
T0=$(date +%s)
say() { printf '%6ss  %s\n' "$(( $(date +%s) - T0 ))" "$*"; }

cleanup() {
    sudo pkill -x desktop_e2e 2>/dev/null; sudo pkill -x AmneziaVPN-serv 2>/dev/null; sudo pkill -x amneziawg-go 2>/dev/null
    sleep 1; sudo rm -f /var/run/amneziawg/amn0.sock
    for ns in cli net srvA srvB; do sudo ip netns del $ns 2>/dev/null; done
    sudo rm -rf /etc/netns/cli
}
trap cleanup EXIT
cleanup

AWG="jc 4 jmin 10 jmax 50 s1 0 s2 0 h1 1 h2 2 h3 3 h4 4"
SRV_KEY=$(awg genkey); SRV_PUB=$(echo "$SRV_KEY" | awg pubkey)
CLI_KEY=$(awg genkey); CLI_PUB=$(echo "$CLI_KEY" | awg pubkey)

for ns in cli net srvA srvB; do sudo ip netns add $ns; nsx $ns ip link set lo up; done
sudo ip link add up0 netns cli type veth peer name c0 netns net
sudo ip link add va netns net type veth peer name va netns srvA
sudo ip link add vb netns net type veth peer name vb netns srvB
nsx cli  ip addr add 10.0.0.2/24 dev up0;      nsx cli ip link set up0 up
nsx net  ip addr add 10.0.0.1/24 dev c0;       nsx net ip link set c0 up
nsx net  ip addr add 198.51.100.1/24 dev va;   nsx net ip link set va up
nsx net  ip addr add 203.0.113.1/24 dev vb;    nsx net ip link set vb up
nsx srvA ip addr add 198.51.100.2/24 dev va;   nsx srvA ip link set va up
nsx srvB ip addr add 203.0.113.2/24 dev vb;    nsx srvB ip link set vb up
nsx cli  ip route add default via 10.0.0.1
nsx srvA ip route add default via 198.51.100.1
nsx srvB ip route add default via 203.0.113.1
nsx net  sysctl -qw net.ipv4.ip_forward=1

for ns in srvA srvB; do
    nsx $ns ip link add awg0 type amneziawg
    nsx $ns bash -c "awg set awg0 private-key <(echo $SRV_KEY) listen-port 51820 $AWG peer $CLI_PUB allowed-ips 10.8.0.2/32"
    nsx $ns ip addr add 10.8.0.1/24 dev awg0; nsx $ns ip link set awg0 up
done

sudo mkdir -p /etc/netns/cli
printf '127.0.0.1 localhost\n198.51.100.2 vpn.test\n' | sudo tee /etc/netns/cli/hosts >/dev/null
printf 'nameserver 10.0.0.1\n' | sudo tee /etc/netns/cli/resolv.conf >/dev/null

cat > $W/client.conf <<CONF
[Interface]
PrivateKey = $CLI_KEY
Address = 10.8.0.2/32
DNS = 10.8.0.1
Jc = 4
Jmin = 10
Jmax = 50
S1 = 0
S2 = 0
H1 = 1
H2 = 2
H3 = 3
H4 = 4

[Peer]
PublicKey = $SRV_PUB
AllowedIPs = 0.0.0.0/0
Endpoint = vpn.test:51820
PersistentKeepalive = 25
CONF

SERVICE=$(find "$BUILD" -name AmneziaVPN-service -type f -perm -u+x | head -1)
E2E=$(find "$BUILD" -name desktop_e2e -type f -perm -u+x | head -1)
say "service: $SERVICE"
nsx cli env QT_QPA_PLATFORM=offscreen "$SERVICE" console > $W/service.log 2>&1 &
sleep 3
nsx cli env QT_QPA_PLATFORM=offscreen ${GDB:-} "$E2E" $W/client.conf "$DUR" > $W/client.log 2>&1 &
CLIENT=$!

hs_of() { nsx "$1" awg show awg0 latest-handshakes | awk '{print $2}'; }
for _ in $(seq 30); do (( $(hs_of srvA) > 0 )) && break; sleep 2; done
(( $(hs_of srvA) > 0 )) && say "connected to A" || { say "NO HANDSHAKE WITH A"; cat $W/client.log | tail -20; exit 1; }
sleep 30

if [ "$MODE" = dead ]; then
    say "server A goes down, vpn.test stays on A"
else
    say "server A goes down, vpn.test -> 203.0.113.2"
    printf '127.0.0.1 localhost\n203.0.113.2 vpn.test\n' | sudo tee /etc/netns/cli/hosts >/dev/null
fi
nsx srvA ip link set awg0 down
DOWN=$(( $(date +%s) - T0 ))

RESULT=FAIL
while kill -0 $CLIENT 2>/dev/null; do
    sleep 5
    if [ "$RESULT" = FAIL ] && (( $(hs_of srvB) > 0 )) && nsx cli ping -c1 -W2 10.8.0.1 >/dev/null 2>&1; then
        say "handshake with B and ping through the tunnel: offline for $(( $(date +%s) - T0 - DOWN ))s"
        RESULT=PASS
    fi
done
grep -E "E2E|WireguardProtocol|Reconnect requested" $W/client.log | sed 's/^/    /'
if [ "$MODE" = dead ]; then
    N=$(grep -c "Reconnect requested" $W/client.log)
    [ "$RESULT" = FAIL ] && (( N >= 2 && N <= 3 )) && echo "RESULT desktop-dead: PASS ($N reconnects with backoff)" \
        || echo "RESULT desktop-dead: FAIL ($N reconnects, result $RESULT)"
else
    echo "RESULT desktop: $RESULT"
fi
desktopE2e.cpp — client harness on top of the tests' TestCoreController
// Desktop end-to-end harness (not part of the change): imports an AWG config whose
// endpoint is a host name, connects through the real UI controller path
// (toggleConnection -> prepareConfig -> ConnectionController -> VpnConnection), then
// keeps running and logs every connection state change with a timestamp. The test
// script outside kills server A and moves the name to server B meanwhile.
#include <QApplication>
#include <QDateTime>
#include <QFile>
#include <QTimer>
#include <QUuid>

#include "utils/testCoreController.h"
#include "core/controllers/connectionController.h"
#include "secureQSettings.h"
#include "vpnConnection.h"

using namespace amnezia;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    const QStringList args = app.arguments();
    if (args.size() < 3) {
        qCritical("usage: desktop_e2e <config file> <seconds>");
        return 2;
    }
    QFile file(args.at(1));
    if (!file.open(QIODevice::ReadOnly)) {
        qCritical("cannot read config");
        return 2;
    }
    const QString configText = QString::fromUtf8(file.readAll());
    const int seconds = args.at(2).toInt();
    const qint64 t0 = QDateTime::currentSecsSinceEpoch();
    auto stamp = [t0]() { return QString("%1s").arg(QDateTime::currentSecsSinceEpoch() - t0, 5); };

    auto settings = new SecureQSettings("AmneziaVPN-E2E-" + QUuid::createUuid().toString(), "amnezia-client", nullptr, false);
    auto vpnConnection = QSharedPointer<VpnConnection>::create(nullptr, nullptr);
    auto core = new TestCoreController(vpnConnection, settings, nullptr, &app);

    QObject::connect(vpnConnection.data(), &VpnConnection::connectionStateChanged, &app,
                     [stamp](Vpn::ConnectionState state) {
                         qInfo().noquote() << "E2E" << stamp() << "state" << VpnProtocol::textConnectionState(state);
                     });

    // The UI controller's state handler needs the full application object (network
    // manager, tray); this harness has none, and the UI is not under test.
    if (auto cc = core->findChild<ConnectionController *>()) {
        QObject::disconnect(cc, &ConnectionController::connectionStateChanged, core->m_connectionUiController, nullptr);
    }

    auto imported = core->m_importCoreController->extractConfigFromData(configText);
    if (imported.errorCode != ErrorCode::NoError) {
        qCritical() << "import failed" << imported.errorCode;
        return 1;
    }
    core->m_importCoreController->importConfig(imported.config);
    qInfo().noquote() << "E2E" << stamp() << "imported, connecting";
    core->m_connectionUiController->toggleConnection();

    QTimer::singleShot(seconds * 1000, &app, [&]() {
        qInfo().noquote() << "E2E" << stamp() << "done, disconnecting";
        vpnConnection->disconnectFromVpn();
        QTimer::singleShot(3000, &app, &QCoreApplication::quit);
    });
    const int rc = app.exec();
    settings->clearSettings();
    return rc;
}

Notes on the harness:

  • Desktop harness. It disconnects ConnectionUiController from ConnectionController::connectionStateChanged. Its Connected branch calls amnApp->networkManager(), which does not exist outside the full application. The connection path itself (ConnectionController → VpnConnection → WireguardProtocol → daemon) is untouched.
  • Android harness. It starts AwgService through adb (root) with the same JSON the app sends, and grants VPN consent with appops.

🔄 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/3327 **Author:** [@justSunny12](https://github.com/justSunny12) **Created:** 10/26/2026 **Status:** 🔄 Open **Base:** `dev` ← **Head:** `feat/reresolve-endpoint-on-stale-handshake` --- ### 📝 Commits (1) - [`1b3ae0a`](https://github.com/amnezia-vpn/amnezia-client/commit/1b3ae0aad8ec6c79b5ada7734a073a46613ecbba) feat: follow server IP changes behind the host name without a manual reconnect ### 📊 Changes **25 files changed** (+741 additions, -6 deletions) <details> <summary>View changed files</summary> 📝 `.github/workflows/deploy.yml` (+3 -0) 📝 `client/android/protocolApi/src/main/kotlin/Protocol.kt` (+9 -1) 📝 `client/android/src/org/amnezia/vpn/AmneziaVpnService.kt` (+1 -1) 📝 `client/android/utils/src/main/kotlin/net/NetworkUtils.kt` (+10 -0) ➕ `client/android/wireguard/src/main/kotlin/org/amnezia/vpn/protocol/wireguard/EndpointWatchdog.kt` (+71 -0) 📝 `client/android/wireguard/src/main/kotlin/org/amnezia/vpn/protocol/wireguard/Wireguard.kt` (+94 -1) 📝 `client/android/wireguard/src/main/kotlin/org/amnezia/vpn/protocol/wireguard/WireguardConfig.kt` (+2 -1) 📝 `client/cmake/sources.cmake` (+2 -0) 📝 `client/core/protocols/vpnProtocol.h` (+3 -0) 📝 `client/core/protocols/wireGuardProtocol.cpp` (+56 -2) 📝 `client/core/protocols/wireGuardProtocol.h` (+16 -0) ➕ `client/core/utils/endpointWatchdog.cpp` (+53 -0) ➕ `client/core/utils/endpointWatchdog.h` (+56 -0) 📝 `client/daemon/daemon.cpp` (+3 -0) 📝 `client/ios/networkextension/CMakeLists.txt` (+1 -0) 📝 `client/macos/networkextension/CMakeLists.txt` (+1 -0) 📝 `client/mozilla/controllerimpl.h` (+5 -0) 📝 `client/mozilla/localsocketcontroller.cpp` (+7 -0) ➕ `client/platforms/ios/EndpointWatchdog.swift` (+75 -0) 📝 `client/platforms/ios/PacketTunnelProvider+WireGuard.swift` (+100 -0) _...and 5 more files_ </details> ### 📄 Description ### Problem A WireGuard/AWG config can name the server by host name (`Endpoint = vpn.example.com:443`). The client resolves that name **once per connection** and keeps using the resulting IP. When the address behind the name changes, every connected device keeps sending to the old IP and stays offline until the user toggles the tunnel by hand. This happens in practice when: - a self-hosted server fails over to a standby: the DNS record is switched to the standby, which has the same keys; - a server is moved to another hosting or region and the DNS record is updated; - the server has a dynamic IP behind DDNS; - the provider changes the server's IP during maintenance. In all these cases the server side cannot fix it, and the user often doesn't understand why "the VPN is connected but nothing works". Why nothing recovers today (checked against `dev` @ 3121775 and `amneziawg-apple` @ bdaf0b3): | Platform | Where the name is resolved | What happens later | |---|---|---| | Windows / Linux / macOS (daemon) | `WireguardProtocol::startMzImpl()` overwrites `hostName` in `m_rawConfig` with the IP | Reconnects on `networkChanged` / `wakeup` call `start()` again, but the config already holds the IP, so they reuse the old address | | Android | `parseInetAddress()` in `Wireguard.configWireguard()` | `reconnectVpn()` reuses the saved `WireguardConfig` with the resolved address | | iOS | `WireGuardAdapter.start()` → `resolvePeers()` | `didReceivePathUpdate()` → `endpointUapiConfiguration()` re-resolves the **already resolved IP** (`resolvedEndpoints`) for NAT64 synthesis, not the host name | | macOS (NE) | same as iOS | path updates only call `wgBumpSockets()` | The engine cannot recover on its own either: - **No re-resolution.** `amneziawg-go` never resolves names. After `MaxHandshakeAttempts` it gives up until the next outgoing packet. - **No roaming.** Android and iOS call `DisableSomeRoamingForBrokenMobileSemantics()`, so a packet from a new source address doesn't move the endpoint. Even without that, stateful NAT drops packets from an address the device didn't contact. ### Solution Detect a tunnel that is up on the device but no longer reaches its server, then resolve the configured host name again. The detection rule is the one from wireguard-tools' [`contrib/reresolve-dns`](https://git.zx2c4.com/wireguard-tools/tree/contrib/reresolve-dns/reresolve-dns.sh): **the latest handshake is older than a rekey cycle while the device keeps sending to the peer.** A live session with traffic or PersistentKeepalive renews its handshake every 120 s (`REKEY_AFTER_TIME`); a failed renewal is retried for 90 s more (`REKEY_ATTEMPT_TIME`). So "no handshake for 180 s and tx grew during that window" means the server is unreachable. An idle tunnel without keepalive never handshakes and sends nothing, so it is never treated as stale. Before the first handshake, the age is counted from the tunnel start. The same small state machine is implemented on every platform. It is pure logic with no I/O, and the C++ version is unit-tested: - `client/core/utils/endpointWatchdog.{h,cpp}` — desktop, with `client/tests/testEndpointWatchdog.cpp` - `client/android/wireguard/.../EndpointWatchdog.kt` - `client/platforms/ios/EndpointWatchdog.swift` It also rate-limits refreshes: the delay doubles after each attempt and resets on the next successful handshake. #### Desktop (Windows, Linux, macOS with daemon) - `WireguardProtocol` keeps the host names exactly as configured and resolves them on **every** `start()`. This alone makes the existing reconnects on network change and wakeup follow DNS changes. - If resolution fails at start, the last address that worked is used, so a short DNS outage right after the old tunnel went down (e.g. with the kill switch on) doesn't break the reconnect. - While the tunnel is up and the endpoint is a host name, `WireguardProtocol` polls `checkStatus()` every 20 s. - The daemon's `status` reply gets an optional `lastHandshake` field (ms since epoch, from `PeerStatus::m_handshake`). `LocalSocketController` emits it as the new `ControllerImpl::peerStatusUpdated()` signal. - When the tunnel is stale, the protocol emits the new `VpnProtocol::reconnectRequested()`. `VpnConnection::onProtocolReconnectRequested()` restarts the protocol exactly like `reconnectToVpn()`, but without requiring the `Connected` state: after a reconnect to an unreachable server the UI state may already be different. - DNS cannot be queried while a dead full tunnel holds the routes, so desktop reconnects instead of comparing addresses first. The backoff is 3 min, doubling up to 30 min. A reconnect to a dead tunnel costs nothing, since no traffic was flowing anyway. #### Android - `Wireguard` remembers the configured host name (`null` for IP literals; new `isNumericAddress()` in `utils`, which never queries DNS). - A coroutine polls `awgGetConfig()` every 20 s. When the tunnel is stale, it resolves the name on an **underlying** network (`Network.getAllByName()` on a non-VPN network with `INTERNET`), because DNS through the dead tunnel doesn't work. - It reconnects **only if the address changed**, preferring the same address family. `WireguardConfig.endpoint` becomes a `var`. The protocol asks the service through a new optional `requestReconnect` parameter of `Protocol.initialize()` (default `{}`, so other protocols are untouched), and `AmneziaVpnService` passes its existing `reconnect()`. - DNS is asked at most once a minute while the tunnel stays stale. #### iOS and macOS (Network Extension) - `PacketTunnelProvider` keeps the started `TunnelConfiguration` and polls `getRuntimeConfiguration()` every 20 s on its own queue. - When the tunnel is stale, it resolves the endpoint with WireGuardKit's own `DNSResolver.resolveSync()` and compares the result with the address the name had at tunnel start. Comparing with the engine's runtime endpoint would be wrong on NAT64 networks, where it holds a synthesized IPv6. - If the address changed, it calls the public `WireGuardAdapter.update(tunnelConfiguration:)`, which resolves peers again and applies the configuration. **No change to the `amneziawg-apple` submodule is needed.** - DNS is asked at most once a minute while the tunnel stays stale. The watch restarts on `startWireguard()` and on a configuration switch from the app, and stops in `stopWireguard()`. ### Behaviour | Situation | Before | After | |---|---|---| | Name's IP changed, old IP dead | offline until manual reconnect | back online ~3.5 min after the old IP stopped answering (180 s + one poll); desktop then reconnects, mobile switches only if DNS really changed | | Server down, IP unchanged | offline, "connected" | mobile: DNS checked once a minute, nothing else. Desktop: reconnect every 3 → 6 → … → 30 min until the server is back | | Healthy tunnel | — | a status poll every 20 s, nothing else | | Idle tunnel without keepalive | — | never considered stale | | Endpoint is an IP literal | — | not watched, behaviour unchanged | | Older daemon with newer client (or vice versa) | — | field is optional on both ends; the watch is just inactive | Only WireGuard and AWG are affected. OpenVPN, Xray and IKEv2 code paths are untouched. ### Backward compatibility - **Configs.** No format change: the existing `hostName` is used. - **Daemon IPC.** One optional field in the `status` reply. - **Android API.** `Protocol.initialize()` gets a new parameter with a default value. - **amneziawg-go / amneziawg-android / amneziawg-apple.** Untouched: only already exported or public APIs are used (`awgGetConfig`, UAPI `last_handshake_time_*` / `tx_bytes`, `WireGuardAdapter.update`, `DNSResolver.resolveSync`). ### Testing Everything below was run on this branch (`dev` @ 3121775 + this change). All scripts and full logs are attached in the collapsible sections, so every step can be reproduced. #### Environment | | | |---|---| | Host | macOS 27.0.1, Apple Silicon (arm64), Xcode 27.1 (27A9275) | | Linux | Debian 13 (trixie), kernel 6.12.111 aarch64, in a Lima VM (vz) | | Qt | 6.10.1 (aqtinstall 3.3.0): macos, ios, android_arm64_v8a, linux_gcc_arm64 | | Build tools | conan 2.28.0, cmake 3.31.10, ninja 1.13.2 — the versions used in `.github/workflows/deploy.yml` | | Android | JDK 17.0.21 (Temurin), NDK 27.0.11718014, platforms 28 and 36, build-tools 35.0.0 / 36.0.0, emulator 37.2.12 with system image `android-35;google_apis;arm64-v8a` r9 | | Engines under test | Android: awg-go backend v3.1.20260814 (as built by `recipes/awg-android`). Linux desktop: `amneziawg-go` built by the project. Lab servers: AmneziaWG kernel module and amneziawg-tools 3.1.20260812. Android test servers: amneziawg-go @ 457d920a1a7d (userspace, netstack) | | Submodules | `amneziawg-apple` @ bdaf0b3 (unchanged) | #### Builds All builds use `deploy/build.sh` as in CI. For Apple targets the generated Xcode project is built with signing disabled, because the team's provisioning profiles are not available outside CI. | Target | Command | Result | |---|---|---| | macOS (daemon), with tests | `AMNEZIA_BUILD_TESTS=ON deploy/build.sh --generator Ninja` | ✅ No new warnings in changed files | | Linux arm64 (daemon), with tests | same, `CMAKE_PREFIX_PATH=<qt>/gcc_arm64` | ✅ No new warnings in changed files | | macOS NE | `deploy/build.sh -t macos-ne`, then `xcodebuild -target AmneziaVPNNetworkExtension CODE_SIGNING_ALLOWED=NO` | ✅ Extension (arm64 + x86_64) compiled and linked, no warnings in changed files ¹ | | iOS | `deploy/build.sh -t ios`, then `xcodebuild -target networkextension -sdk iphoneos CODE_SIGNING_ALLOWED=NO` | ✅ BUILD SUCCEEDED, no warnings in changed files | | Android arm64 | `deploy/build.sh -t android --abi arm64-v8a --sign` (throwaway keystore) | ✅ All Kotlin modules incl. `:compileOssReleaseKotlin` and `:compilePlayReleaseKotlin`, signed APK | ¹ The macOS NE **app** target fails on unchanged `platforms/ios/LogController.swift` (`std.string(...)`: no exact matches) with the Xcode 27 SDK. That is unrelated to this change; CI uses Xcode 26.3. #### Unit tests `ctest` on the full test set. The new `EndpointWatchdogTest` is registered in `client/tests/CMakeLists.txt` and added to the three CI test matrices. - macOS: **27/27 passed** - Linux arm64: **27/27 passed** <details><summary>ctest, Linux arm64</summary> ``` Test #1: MultipleImportsTest ................... Passed 1.05 sec Test #2: ServerEditTest ........................ Passed 1.05 sec Test #3: DefaultServerChangeTest ............... Passed 1.05 sec Test #4: ServerEdgeCasesTest ................... Passed 1.05 sec Test #5: SignalOrderTest ....................... Passed 1.10 sec Test #6: ServersModelSyncTest .................. Passed 1.10 sec Test #7: ServerRenameTest ...................... Passed 1.09 sec Test #8: SettingsSignalsTest ................... Passed 3.21 sec Test #9: UiServersModelAndControllerTest ....... Passed 1.11 sec Test #10: XraySerializationTest ................. Passed 1.11 sec Test #11: ConfigFormatVersionTest ............... Passed 1.11 sec Test #12: UiLanguageModelAndControllerTest ...... Passed 1.07 sec Test #13: UiIpModelAndControllerTest ............ Passed 1.16 sec Test #14: UiAppSTModelAndControllerTest ......... Passed 1.07 sec Test #15: UiAllowedDnsModelAndControllerTest .... Passed 1.07 sec Test #16: BackupExportImportTest ................ Passed 1.01 sec Test #17: FavoriteLocationsRestoreTest .......... Passed 1.02 sec Test #18: ConnectionTest ........................ Passed 0.98 sec Test #19: OpenSSLLibraryTest .................... Passed 0.04 sec Test #20: LogsControllerTest .................... Passed 0.03 sec Test #21: EndpointWatchdogTest .................. Passed 0.03 sec Test #22: AdminSelfHostedExportTest ............. Passed 0.99 sec Test #23: SelfHostedServerSetupTest ............. Passed 0.99 sec Test #24: MultipleExportsTest ................... Passed 0.98 sec Test #25: UiApiServicesModelAndControllerTest ... Passed 0.98 sec Test #26: UiNewsModelAndControllerTest .......... Passed 1.00 sec Test #27: GatewayServiceImportTest .............. Passed 1.00 sec 100% tests passed, 0 tests failed out of 27 ``` </details> <details><summary>EndpointWatchdogTest, macOS (per test function)</summary> ``` ********* Start testing of TestEndpointWatchdog ********* Config: Using QtTest library 6.10.1, Qt 6.10.1 (arm64-little_endian-lp64 shared (dynamic) release build; by Apple LLVM 16.0.0 (clang-1600.0.26.3)), macos 27.0.1 PASS : TestEndpointWatchdog::initTestCase() PASS : TestEndpointWatchdog::liveTunnelIsNotStale() PASS : TestEndpointWatchdog::sendingWithoutHandshakeIsStale() PASS : TestEndpointWatchdog::neverHandshakedSinceStartIsStale() PASS : TestEndpointWatchdog::idleTunnelWithoutKeepaliveIsNotStale() PASS : TestEndpointWatchdog::refreshIsRepeatedWithGrowingDelay() PASS : TestEndpointWatchdog::handshakeResetsTheDelay() PASS : TestEndpointWatchdog::counterResetAfterRestartIsNotTraffic() PASS : TestEndpointWatchdog::cleanupTestCase() Totals: 9 passed, 0 failed, 0 skipped, 0 blacklisted, 1ms ********* Finished testing of TestEndpointWatchdog ********* ``` </details> #### Live scenarios Every scenario uses real AmneziaWG timers and has two servers with the same keys and AWG parameters: - **A** — the server the client starts on; - **B** — the standby that the host name `vpn.test` is moved to. The client config uses `Endpoint = vpn.test:51820` and PersistentKeepalive 25, except where stated. | # | Platform | Setup | Scenario | Expected | Result | |---|---|---|---|---|---| | 1 | AWG kernel, rule only | 3 netns, client = kernel AWG; the stale verdict comes from `endpointWatchdog.cpp` itself, fed with `awg show dump` every 20 s | A dies, `vpn.test` → B | refresh → endpoint B | ✅ refresh at 191 s, back online via B, **180 s** offline | | 2 | AWG kernel, rule only | same, **no keepalive, no traffic** | A dies, `vpn.test` → B; user traffic starts at 312 s | no refresh while idle; refresh as soon as traffic is not answered | ✅ nothing for 312 s, refresh 20 s after traffic started | | 3 | AWG kernel, rule only | same | A dies, `vpn.test` stays on A | refresh once a minute, endpoint kept | ✅ 5 checks, endpoint unchanged | | 4 | **Android app**, emulator | release APK; full tunnel `0.0.0.0/0`, DNS inside the tunnel (so DNS through the dead tunnel cannot work) | A dies, `vpn.test` → B | app resolves outside the tunnel and reconnects to B | ✅ `it moved to …: reconnecting`, handshake with B, **160 s** offline | | 5 | **Android app**, emulator | same | A dies, `vpn.test` stays on A | DNS checked once a minute, no reconnect | ✅ 4 checks, 0 reconnects | | 6 | **Linux desktop**: real `AmneziaVPN-service` (root) + `VpnConnection` | client netns behind a router netns; config imported and connected through `ConnectionUiController::toggleConnection()` | A dies, `vpn.test` → B | reconnect, name resolved again, Connected on B | ✅ Reconnecting at 180 s, Connected at 184 s, ping through the tunnel, **155 s** offline | | 7 | **Linux desktop**, same | same | A dies, `vpn.test` stays on A | reconnects with backoff, not in a loop | ✅ 2 reconnects in 12 min (180 s, 380 s; the next one is due ≥ 740 s) | Not run live: iOS and macOS NE. A Network Extension doesn't run in the simulator and needs provisioning to run on a device. Both extensions compile and link with the change. The Swift watchdog passes the same scenarios as the C++ one, and the Apple code path uses only WireGuardKit's own `DNSResolver.resolveSync()` and the public `WireGuardAdapter.update()`. <details><summary>Scenarios 1–3: log</summary> ``` === moved 420 0s connected via 198.51.100.2 30s server A goes down 31s vpn.test now resolves to 203.0.113.2 191s STALE (handshake 191s ago, tx=1832): 198.51.100.2:51820 -> 203.0.113.2:51820 211s BACK ONLINE via B: offline for 180s RESULT moved: PASS === idle 600 0s connected via 198.51.100.2 31s server A goes down 31s vpn.test now resolves to 203.0.113.2 312s user traffic starts 332s STALE (handshake 332s ago, tx=1284): 198.51.100.2:51820 -> 203.0.113.2:51820 352s BACK ONLINE via B: offline for 321s RESULT idle: PASS (moved only after traffic) === dead 420 0s connected via 198.51.100.2 30s server A goes down 191s STALE (handshake 191s ago, tx=1980): address unchanged, nothing to do 251s STALE (handshake 251s ago, tx=3460): address unchanged, nothing to do 311s STALE (handshake 311s ago, tx=4644): address unchanged, nothing to do 371s STALE (handshake 371s ago, tx=6420): address unchanged, nothing to do 431s STALE (handshake 431s ago, tx=7456): address unchanged, nothing to do RESULT dead: PASS (5 checks, endpoint kept) ``` </details> <details><summary>Scenario 4 (Android, moved): log</summary> ``` 22s emulator booted 32s app installed 37s connected to A 67s server A goes down, vpn.test -> 192.168.1.207 227s handshake with B: offline for 160s 10-26 14:51:24.262 I/Wireguard( 3538): No handshake with vpn.test, it moved to 192.168.1.207: reconnecting RESULT android: PASS ``` </details> <details><summary>Scenario 5 (Android, dead): log</summary> ``` 14s emulator booted 22s app installed 26s connected to A 56s server A goes down, vpn.test stays on 10.0.2.2 10-26 14:52:45.017 I/Wireguard( 2911): awg-go backend v3.1.20260814 10-26 14:55:45.099 I/Wireguard( 2911): No handshake with vpn.test, its address is unchanged 10-26 14:56:45.113 I/Wireguard( 2911): No handshake with vpn.test, its address is unchanged 10-26 14:57:45.123 I/Wireguard( 2911): No handshake with vpn.test, its address is unchanged 10-26 14:58:45.141 I/Wireguard( 2911): No handshake with vpn.test, its address is unchanged RESULT android-dead: PASS (4 checks, no reconnect) ``` </details> <details><summary>Scenario 6 (desktop, moved): log</summary> ``` 2s service: /var/tmp/build-linux/service/server/AmneziaVPN-service 7s connected to A 37s server A goes down, vpn.test -> 203.0.113.2 192s handshake with B and ping through the tunnel: offline for 155s E2E 0s imported, connecting E2E 0s state Connecting... E2E 0s state Connected WireguardProtocol: no handshake with "vpn.test" while sending, reconnecting to resolve its address again Reconnect requested by the protocol: the server stopped answering E2E 180s state Reconnecting... E2E 184s state Connected E2E 480s done, disconnecting E2E 480s state Disconnecting... E2E 480s state Disconnected RESULT desktop: PASS ``` </details> <details><summary>Scenario 7 (desktop, dead): log</summary> ``` 2s service: /var/tmp/build-linux/service/server/AmneziaVPN-service 7s connected to A 37s server A goes down, vpn.test stays on A E2E 0s imported, connecting E2E 0s state Connecting... E2E 0s state Connected WireguardProtocol: no handshake with "vpn.test" while sending, reconnecting to resolve its address again Reconnect requested by the protocol: the server stopped answering E2E 180s state Reconnecting... WireguardProtocol: no handshake with "vpn.test" while sending, reconnecting to resolve its address again Reconnect requested by the protocol: the server stopped answering E2E 380s state Reconnecting... E2E 720s done, disconnecting E2E 720s state Disconnecting... RESULT desktop-dead: PASS (2 reconnects with backoff) ``` </details> #### Test harness (not part of the change) <details><summary>e2e.sh — scenarios 1–3 (Linux, root, network namespaces)</summary> ```bash #!/usr/bin/env bash # Live check of the stale-tunnel rule on real AmneziaWG timers. # # cli ── veth ── srvA (198.51.100.2) both servers: same private key, # └─── veth ── srvB (203.0.113.2) same tunnel address 10.8.0.1 # # The client names its server "vpn.test" (/etc/netns/cli/hosts). Every 20 s the # loop feeds `awg show dump` of the client into EndpointWatchdog (the C++ class # of the change); when it says "refresh", the name is resolved again and, if the # address changed, set as the new endpoint - what the Android / iOS code does. # # usage: e2e.sh <scenario> [seconds] # moved keepalive 25, server A dies and the name moves to B # idle no keepalive, no traffic: A dies, nothing must happen; then # traffic starts and the client must move to B # dead keepalive 25, A dies, the name stays on A: refresh is attempted # once a minute, the endpoint is never changed set -u SCEN=${1:?scenario} DUR=${2:-480} BIN=/var/tmp/awge2e/driver POLL=20 say() { printf '%6ss %s\n' "$(( $(date +%s) - T0 ))" "$*"; } nsx() { local ns=$1; shift; sudo ip netns exec "$ns" "$@"; } cleanup() { for ns in cli srvA srvB; do sudo ip netns del $ns 2>/dev/null; done sudo rm -rf /etc/netns/cli } trap cleanup EXIT cleanup SRV_KEY=$(awg genkey); SRV_PUB=$(echo "$SRV_KEY" | awg pubkey) CLI_KEY=$(awg genkey); CLI_PUB=$(echo "$CLI_KEY" | awg pubkey) for ns in cli srvA srvB; do sudo ip netns add $ns; nsx $ns ip link set lo up; done sudo ip link add va netns cli type veth peer name va netns srvA sudo ip link add vb netns cli type veth peer name vb netns srvB nsx cli ip addr add 198.51.100.1/24 dev va; nsx cli ip link set va up nsx srvA ip addr add 198.51.100.2/24 dev va; nsx srvA ip link set va up nsx cli ip addr add 203.0.113.1/24 dev vb; nsx cli ip link set vb up nsx srvB ip addr add 203.0.113.2/24 dev vb; nsx srvB ip link set vb up for ns in srvA srvB; do nsx $ns ip link add awg0 type amneziawg nsx $ns bash -c "awg set awg0 private-key <(echo $SRV_KEY) listen-port 51820 peer $CLI_PUB allowed-ips 10.8.0.2/32" nsx $ns ip addr add 10.8.0.1/24 dev awg0; nsx $ns ip link set awg0 up done sudo mkdir -p /etc/netns/cli printf '127.0.0.1 localhost\n198.51.100.2 vpn.test\n' | sudo tee /etc/netns/cli/hosts >/dev/null KA=25; [ "$SCEN" = idle ] && KA=0 resolve() { nsx cli getent hosts vpn.test | awk '{print $1; exit}'; } nsx cli ip link add awg0 type amneziawg nsx cli bash -c "awg set awg0 private-key <(echo $CLI_KEY) peer $SRV_PUB allowed-ips 10.8.0.0/24 endpoint $(resolve):51820 persistent-keepalive $KA" nsx cli ip addr add 10.8.0.2/24 dev awg0; nsx cli ip link set awg0 up coproc DRV { "$BIN" 60000 60000; } T0=$(date +%s) echo "start $((T0 * 1000))" >&"${DRV[1]}"; read -r _ <&"${DRV[0]}" nsx cli ping -c1 -W2 10.8.0.1 >/dev/null && say "connected via $(resolve)" || say "FIRST HANDSHAKE FAILED" [ "$SCEN" = idle ] && nsx cli ping -c3 -i0.3 -W2 10.8.0.1 >/dev/null TRAFFIC_PID="" sleep 30 say "server A goes down" nsx srvA ip link set awg0 down if [ "$SCEN" != dead ]; then printf '127.0.0.1 localhost\n203.0.113.2 vpn.test\n' | sudo tee /etc/netns/cli/hosts >/dev/null say "vpn.test now resolves to $(resolve)" fi IDLE_BAD=""; MOVED=""; DOWN_AT=$(( $(date +%s) - T0 )); REFRESHES=0 while (( $(date +%s) - T0 < DUR )); do if [ "$SCEN" = idle ] && [ -z "$TRAFFIC_PID" ] && (( $(date +%s) - T0 >= DUR / 2 )); then say "user traffic starts" nsx cli ping -i5 -W1 10.8.0.1 >/dev/null 2>&1 & TRAFFIC_PID=$! fi sleep $POLL line=$(nsx cli awg show awg0 dump | sed -n 2p) ep=$(echo "$line" | awk '{print $3}'); hs=$(echo "$line" | awk '{print $5}'); tx=$(echo "$line" | awk '{print $7}') echo "$(( $(date +%s) * 1000 )) $(( hs * 1000 )) $tx" >&"${DRV[1]}"; read -r verdict <&"${DRV[0]}" age=$(( hs > 0 ? $(date +%s) - hs : -1 )) if [ "$verdict" = 1 ]; then REFRESHES=$((REFRESHES + 1)) [ "$SCEN" = idle ] && [ -z "$TRAFFIC_PID" ] && IDLE_BAD=1 new=$(resolve) if [ "${ep%:*}" != "$new" ]; then nsx cli awg set awg0 peer "$SRV_PUB" endpoint "$new:51820" say "STALE (handshake ${age}s ago, tx=$tx): $ep -> $new:51820" else say "STALE (handshake ${age}s ago, tx=$tx): address unchanged, nothing to do" fi fi if [ -z "$MOVED" ] && [ "$ep" = "203.0.113.2:51820" ] && (( hs > 0 )) && (( $(date +%s) - hs < 30 )) \ && nsx cli ping -c1 -W2 10.8.0.1 >/dev/null; then MOVED=$(( $(date +%s) - T0 )) say "BACK ONLINE via B: offline for $(( MOVED - DOWN_AT ))s" fi done [ -n "$TRAFFIC_PID" ] && sudo kill "$TRAFFIC_PID" 2>/dev/null case "$SCEN" in moved) [ -n "$MOVED" ] && echo "RESULT moved: PASS" || echo "RESULT moved: FAIL" ;; idle) [ -n "$MOVED" ] && [ -z "$IDLE_BAD" ] && echo "RESULT idle: PASS (moved only after traffic)" || echo "RESULT idle: FAIL" ;; dead) [ -z "$MOVED" ] && (( REFRESHES >= 2 )) && echo "RESULT dead: PASS ($REFRESHES checks, endpoint kept)" \ || echo "RESULT dead: FAIL ($REFRESHES checks)" ;; esac ``` </details> <details><summary>driver.cpp — feeds `awg show dump` samples into EndpointWatchdog</summary> ```cpp // Feeds "now_ms handshake_ms tx_bytes" lines to EndpointWatchdog, prints "1" when a // refresh should happen (and records the attempt), "0" otherwise. #include <cstdio> #include <iostream> #include <string> #include "endpointWatchdog.h" int main(int argc, char **argv) { const int64_t first = argc > 1 ? std::stoll(argv[1]) : 60000; const int64_t max = argc > 2 ? std::stoll(argv[2]) : 60000; EndpointWatchdog w(first, max); int64_t now, hs; uint64_t tx; std::string cmd; while (std::cin >> cmd) { if (cmd == "start") { std::cin >> now; w.tunnelStarted(now); std::cout << "ok" << std::endl; continue; } now = std::stoll(cmd); std::cin >> hs >> tx; const bool refresh = w.observe(now, hs, tx); if (refresh) { w.refreshAttempted(now); } std::cout << (refresh ? 1 : 0) << std::endl; } } ``` </details> <details><summary>android-e2e.sh — scenarios 4–5 (macOS host, Android emulator)</summary> ```bash #!/usr/bin/env bash # Live check of the Android change in an emulator, no root on the host. # server A: awgsrv on 127.0.0.1:51820 (the emulator sees it as 10.0.2.2) # server B: awgsrv on $LAN_IP:51820 (same keys, same AWG params) # DNS: dns.py, vpn.test from dns-vpn.txt (the emulator uses it via -dns-server) # The app connects to vpn.test with a full tunnel (0.0.0.0/0, DNS inside the tunnel), # then A dies and the record moves to B. Expect: the app notices, resolves vpn.test # outside the tunnel, reconnects to B by itself. # # keys.txt (one line): server_private server_public client_private client_public, e.g. # S=$(awg genkey); C=$(awg genkey); echo $S $(echo $S | awg pubkey) $C $(echo $C | awg pubkey) > keys.txt # usage: android-e2e.sh [moved|dead] set -u MODE=${1:-moved} # moved: the record moves to B; dead: it stays on A E=$(cd "$(dirname "$0")" && pwd) T=~/.claude/awg-bot/upstream/toolchain SDK=$T/android-sdk ADB=$SDK/platform-tools/adb APK=~/.claude/awg-bot/upstream/build-android/client/android-build/AmneziaVPN.apk LAN_IP=${LAN_IP:-$(ipconfig getifaddr en0)} export JAVA_HOME=$T/jdk/Contents/Home ANDROID_HOME=$SDK ANDROID_SDK_ROOT=$SDK ANDROID_AVD_HOME=$T/avd T0=$(date +%s) say() { printf '%6ss %s\n' "$(( $(date +%s) - T0 ))" "$*"; } read -r SK SP CK CP < "$E/keys.txt" pkill -f "awgsrv -listen" 2>/dev/null "$E/awgsrv/awgsrv" -listen 127.0.0.1 -priv "$SK" -peer "$CP" -name A > "$E/android-srvA.log" 2>&1 & PID_A=$! "$E/awgsrv/awgsrv" -listen "$LAN_IP" -priv "$SK" -peer "$CP" -name B > "$E/android-srvB.log" 2>&1 & PID_B=$! echo 10.0.2.2 > "$E/dns-vpn.txt" mkdir -p "$ANDROID_AVD_HOME" if [ ! -d "$ANDROID_AVD_HOME/awgtest.avd" ]; then echo no | "$SDK/cmdline-tools/latest/bin/avdmanager" create avd -n awgtest \ -k "system-images;android-35;google_apis;arm64-v8a" -d pixel_6 >/dev/null fi "$SDK/emulator/emulator" -avd awgtest -no-window -no-audio -no-boot-anim -no-snapshot \ -gpu swiftshader_indirect -dns-server 127.0.0.1 > "$E/emulator.log" 2>&1 & PID_EMU=$! trap 'kill $PID_A $PID_B 2>/dev/null; $ADB emu kill >/dev/null 2>&1; kill $PID_EMU 2>/dev/null' EXIT $ADB wait-for-device until [ "$($ADB shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = 1 ]; do sleep 3; done say "emulator booted" $ADB root >/dev/null; sleep 3; $ADB wait-for-device $ADB install -r "$APK" >/dev/null && say "app installed" $ADB shell appops set org.amnezia.vpn ACTIVATE_VPN allow $ADB logcat -c CFG=$(cat <<JSON {"protocol":"awg","description":"e2e","dns1":"10.8.0.1","awg_config_data":{"client_ip":"10.8.0.2/32","allowed_ips":["0.0.0.0/0"],"hostName":"vpn.test","port":51820,"mtu":"1280","persistent_keep_alive":"25","client_priv_key":"$CK","server_pub_key":"$SP","Jc":"4","Jmin":"10","Jmax":"50","S1":"0","S2":"0","H1":"1","H2":"2","H3":"3","H4":"4"}} JSON ) $ADB shell "am start-foreground-service -n org.amnezia.vpn/.AwgService --es VPN_CONFIG '$CFG'" >/dev/null $ADB logcat -v time > "$E/android-logcat.log" 2>&1 & PID_LOG=$! trap 'kill $PID_A $PID_B $PID_LOG 2>/dev/null; $ADB emu kill >/dev/null 2>&1; kill $PID_EMU 2>/dev/null' EXIT for _ in $(seq 30); do grep -q "handshake=[1-9]" "$E/android-srvA.log" && break; sleep 2 done grep -q "handshake=[1-9]" "$E/android-srvA.log" && say "connected to A" || { say "NO HANDSHAKE WITH A"; exit 1; } sleep 30 if [ "$MODE" = dead ]; then say "server A goes down, vpn.test stays on 10.0.2.2" kill $PID_A sleep 360 UNCHANGED=$(grep -c "its address is unchanged" "$E/android-logcat.log") RECONNECTS=$(grep -c "moved to" "$E/android-logcat.log") grep "I/Wireguard" "$E/android-logcat.log" | grep -v "lastHandshake=" | sed 's/^/ /' if (( UNCHANGED >= 2 && RECONNECTS == 0 )); then echo "RESULT android-dead: PASS ($UNCHANGED checks, no reconnect)"; exit 0 fi echo "RESULT android-dead: FAIL ($UNCHANGED checks, $RECONNECTS reconnects)"; exit 1 fi say "server A goes down, vpn.test -> $LAN_IP" echo "$LAN_IP" > "$E/dns-vpn.txt" kill $PID_A DOWN=$(( $(date +%s) - T0 )) for _ in $(seq 60); do sleep 10 if grep -q "handshake=[1-9]" "$E/android-srvB.log"; then UP=$(( $(date +%s) - T0 )) say "handshake with B: offline for $(( UP - DOWN ))s" grep -E "Wireguard|AmneziaVpnService" "$E/android-logcat.log" | grep -iE "handshake with|moved|reconnect|resolve" | sed 's/^/ /' echo "RESULT android: PASS" exit 0 fi done grep -E "Wireguard" "$E/android-logcat.log" | tail -20 | sed 's/^/ /' echo "RESULT android: FAIL" exit 1 ``` </details> <details><summary>awgsrv/main.go — rootless AmneziaWG test server (amneziawg-go + netstack), bound to one IP</summary> ```go // awgsrv: an AmneziaWG server on a gVisor netstack (no root needed), bound to // one local IP so that two of them can share a port on different addresses. // It answers ICMP echo on its tunnel address and prints the peer's handshake. package main import ( "bufio" "encoding/base64" "encoding/hex" "flag" "fmt" "log" "net" "net/netip" "os" "os/signal" "strings" "syscall" "time" "github.com/amnezia-vpn/amneziawg-go/conn" "github.com/amnezia-vpn/amneziawg-go/device" "github.com/amnezia-vpn/amneziawg-go/tun/netstack" ) type endpoint netip.AddrPort func (e endpoint) ClearSrc() {} func (e endpoint) SrcToString() string { return "" } func (e endpoint) DstToString() string { return netip.AddrPort(e).String() } func (e endpoint) DstToBytes() []byte { b, _ := netip.AddrPort(e).MarshalBinary(); return b } func (e endpoint) DstIP() netip.Addr { return netip.AddrPort(e).Addr() } func (e endpoint) SrcIP() netip.Addr { return netip.Addr{} } type bind struct { addr netip.Addr udp *net.UDPConn } func (b *bind) Open(port uint16) ([]conn.ReceiveFunc, uint16, error) { c, err := net.ListenUDP("udp4", net.UDPAddrFromAddrPort(netip.AddrPortFrom(b.addr, port))) if err != nil { return nil, 0, err } b.udp = c recv := func(packets [][]byte, sizes []int, eps []conn.Endpoint) (int, error) { n, a, err := c.ReadFromUDPAddrPort(packets[0]) if err != nil { return 0, err } sizes[0] = n eps[0] = endpoint(netip.AddrPortFrom(a.Addr().Unmap(), a.Port())) return 1, nil } return []conn.ReceiveFunc{recv}, uint16(c.LocalAddr().(*net.UDPAddr).Port), nil } func (b *bind) Close() error { if b.udp != nil { return b.udp.Close() } return nil } func (b *bind) SetMark(uint32) error { return nil } func (b *bind) Send(bufs [][]byte, ep conn.Endpoint) error { for _, buf := range bufs { if _, err := b.udp.WriteToUDPAddrPort(buf, netip.AddrPort(ep.(endpoint))); err != nil { return err } } return nil } func (b *bind) ParseEndpoint(s string) (conn.Endpoint, error) { ap, err := netip.ParseAddrPort(s) return endpoint(ap), err } func (b *bind) BatchSize() int { return 1 } func hexKey(b64 string) string { raw, err := base64.StdEncoding.DecodeString(b64) if err != nil || len(raw) != 32 { log.Fatalf("bad key %q", b64) } return hex.EncodeToString(raw) } func main() { listen := flag.String("listen", "127.0.0.1", "local IP to bind") port := flag.Int("port", 51820, "UDP port") priv := flag.String("priv", "", "server private key (base64)") peer := flag.String("peer", "", "client public key (base64)") name := flag.String("name", "srv", "name for the log") awg := flag.String("awg", "jc=4\njmin=10\njmax=50\ns1=0\ns2=0\nh1=1\nh2=2\nh3=3\nh4=4", "AWG device params (UAPI lines)") flag.Parse() tunDev, _, err := netstack.CreateNetTUN([]netip.Addr{netip.MustParseAddr("10.8.0.1")}, nil, 1280) if err != nil { log.Fatal(err) } dev := device.NewDevice(tunDev, &bind{addr: netip.MustParseAddr(*listen)}, device.NewLogger(device.LogLevelError, *name+": ")) conf := fmt.Sprintf("private_key=%s\nlisten_port=%d\n%s\npublic_key=%s\nallowed_ip=10.8.0.2/32\n", hexKey(*priv), *port, *awg, hexKey(*peer)) if err := dev.IpcSet(conf); err != nil { log.Fatal(err) } if err := dev.Up(); err != nil { log.Fatal(err) } fmt.Printf("%s: listening on %s:%d\n", *name, *listen, *port) go func() { for range time.Tick(5 * time.Second) { state, _ := dev.IpcGet() var hs, rx string sc := bufio.NewScanner(strings.NewReader(state)) for sc.Scan() { l := sc.Text() if v, ok := strings.CutPrefix(l, "last_handshake_time_sec="); ok { hs = v } if v, ok := strings.CutPrefix(l, "rx_bytes="); ok { rx = v } } fmt.Printf("%s: %s handshake=%s rx=%s\n", *name, time.Now().Format("15:04:05"), hs, rx) } }() sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) <-sig dev.Close() } ``` </details> <details><summary>dns.py — test DNS for the emulator with a switchable record</summary> ```python """Tiny DNS for the emulator: A record of vpn.test comes from dns-vpn.txt (re-read on every query, so the record can be switched), everything else is forwarded to 1.1.1.1.""" import pathlib import socket import struct import sys import time HERE = pathlib.Path(__file__).parent REC = HERE / "dns-vpn.txt" LISTEN = (sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1", 53) def qname(data, off=12): labels = [] while data[off]: n = data[off] labels.append(data[off + 1:off + 1 + n].decode()) off += n + 1 return ".".join(labels).lower(), off + 1 def answer(query, ip): tid = query[:2] name, end = qname(query) question = query[12:end + 4] head = tid + struct.pack(">HHHHH", 0x8180, 1, 1, 0, 0) rr = b"\xc0\x0c" + struct.pack(">HHIH", 1, 1, 5, 4) + socket.inet_aton(ip) return head + question + rr def main(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(LISTEN) up = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) up.settimeout(3) print("dns on", LISTEN, flush=True) while True: data, addr = s.recvfrom(2048) try: name, end = qname(data) qtype = struct.unpack(">H", data[end:end + 2])[0] except Exception: continue if name == "vpn.test": ip = REC.read_text().strip() if qtype == 1: s.sendto(answer(data, ip), addr) else: # AAAA etc: empty NOERROR s.sendto(data[:2] + struct.pack(">HHHHH", 0x8180, 1, 0, 0, 0) + data[12:end + 4], addr) print(time.strftime("%H:%M:%S"), "vpn.test", qtype, "->", ip, "from", addr, flush=True) continue try: up.sendto(data, ("1.1.1.1", 53)) s.sendto(up.recvfrom(4096)[0], addr) except OSError: pass main() ``` </details> <details><summary>desktop-e2e.sh — scenarios 6–7 (Linux, real service and client)</summary> ```bash #!/usr/bin/env bash # Desktop end-to-end check on Linux: the real AmneziaVPN-service (as root) and the real # client path (VpnConnection via desktop_e2e) run inside the "cli" network namespace. # # cli (10.0.0.2) ── net (router, 10.0.0.1) ── srvA (198.51.100.2) kernel AmneziaWG servers: # └─ srvB (203.0.113.2) same keys, same AWG params # # The client config says Endpoint = vpn.test:51820 (/etc/netns/cli/hosts), full tunnel. # After the connection is up, A dies and vpn.test moves to B. Expect: the client sees # no handshake while sending, reconnects, resolves vpn.test again and comes up on B. set -u BUILD=${BUILD:-/var/tmp/build-linux} DUR=${1:-480} MODE=${2:-moved} # moved: vpn.test moves to B; dead: it stays on A W=/var/tmp/awge2e/desktop mkdir -p $W nsx() { local ns=$1; shift; sudo ip netns exec "$ns" "$@"; } T0=$(date +%s) say() { printf '%6ss %s\n' "$(( $(date +%s) - T0 ))" "$*"; } cleanup() { sudo pkill -x desktop_e2e 2>/dev/null; sudo pkill -x AmneziaVPN-serv 2>/dev/null; sudo pkill -x amneziawg-go 2>/dev/null sleep 1; sudo rm -f /var/run/amneziawg/amn0.sock for ns in cli net srvA srvB; do sudo ip netns del $ns 2>/dev/null; done sudo rm -rf /etc/netns/cli } trap cleanup EXIT cleanup AWG="jc 4 jmin 10 jmax 50 s1 0 s2 0 h1 1 h2 2 h3 3 h4 4" SRV_KEY=$(awg genkey); SRV_PUB=$(echo "$SRV_KEY" | awg pubkey) CLI_KEY=$(awg genkey); CLI_PUB=$(echo "$CLI_KEY" | awg pubkey) for ns in cli net srvA srvB; do sudo ip netns add $ns; nsx $ns ip link set lo up; done sudo ip link add up0 netns cli type veth peer name c0 netns net sudo ip link add va netns net type veth peer name va netns srvA sudo ip link add vb netns net type veth peer name vb netns srvB nsx cli ip addr add 10.0.0.2/24 dev up0; nsx cli ip link set up0 up nsx net ip addr add 10.0.0.1/24 dev c0; nsx net ip link set c0 up nsx net ip addr add 198.51.100.1/24 dev va; nsx net ip link set va up nsx net ip addr add 203.0.113.1/24 dev vb; nsx net ip link set vb up nsx srvA ip addr add 198.51.100.2/24 dev va; nsx srvA ip link set va up nsx srvB ip addr add 203.0.113.2/24 dev vb; nsx srvB ip link set vb up nsx cli ip route add default via 10.0.0.1 nsx srvA ip route add default via 198.51.100.1 nsx srvB ip route add default via 203.0.113.1 nsx net sysctl -qw net.ipv4.ip_forward=1 for ns in srvA srvB; do nsx $ns ip link add awg0 type amneziawg nsx $ns bash -c "awg set awg0 private-key <(echo $SRV_KEY) listen-port 51820 $AWG peer $CLI_PUB allowed-ips 10.8.0.2/32" nsx $ns ip addr add 10.8.0.1/24 dev awg0; nsx $ns ip link set awg0 up done sudo mkdir -p /etc/netns/cli printf '127.0.0.1 localhost\n198.51.100.2 vpn.test\n' | sudo tee /etc/netns/cli/hosts >/dev/null printf 'nameserver 10.0.0.1\n' | sudo tee /etc/netns/cli/resolv.conf >/dev/null cat > $W/client.conf <<CONF [Interface] PrivateKey = $CLI_KEY Address = 10.8.0.2/32 DNS = 10.8.0.1 Jc = 4 Jmin = 10 Jmax = 50 S1 = 0 S2 = 0 H1 = 1 H2 = 2 H3 = 3 H4 = 4 [Peer] PublicKey = $SRV_PUB AllowedIPs = 0.0.0.0/0 Endpoint = vpn.test:51820 PersistentKeepalive = 25 CONF SERVICE=$(find "$BUILD" -name AmneziaVPN-service -type f -perm -u+x | head -1) E2E=$(find "$BUILD" -name desktop_e2e -type f -perm -u+x | head -1) say "service: $SERVICE" nsx cli env QT_QPA_PLATFORM=offscreen "$SERVICE" console > $W/service.log 2>&1 & sleep 3 nsx cli env QT_QPA_PLATFORM=offscreen ${GDB:-} "$E2E" $W/client.conf "$DUR" > $W/client.log 2>&1 & CLIENT=$! hs_of() { nsx "$1" awg show awg0 latest-handshakes | awk '{print $2}'; } for _ in $(seq 30); do (( $(hs_of srvA) > 0 )) && break; sleep 2; done (( $(hs_of srvA) > 0 )) && say "connected to A" || { say "NO HANDSHAKE WITH A"; cat $W/client.log | tail -20; exit 1; } sleep 30 if [ "$MODE" = dead ]; then say "server A goes down, vpn.test stays on A" else say "server A goes down, vpn.test -> 203.0.113.2" printf '127.0.0.1 localhost\n203.0.113.2 vpn.test\n' | sudo tee /etc/netns/cli/hosts >/dev/null fi nsx srvA ip link set awg0 down DOWN=$(( $(date +%s) - T0 )) RESULT=FAIL while kill -0 $CLIENT 2>/dev/null; do sleep 5 if [ "$RESULT" = FAIL ] && (( $(hs_of srvB) > 0 )) && nsx cli ping -c1 -W2 10.8.0.1 >/dev/null 2>&1; then say "handshake with B and ping through the tunnel: offline for $(( $(date +%s) - T0 - DOWN ))s" RESULT=PASS fi done grep -E "E2E|WireguardProtocol|Reconnect requested" $W/client.log | sed 's/^/ /' if [ "$MODE" = dead ]; then N=$(grep -c "Reconnect requested" $W/client.log) [ "$RESULT" = FAIL ] && (( N >= 2 && N <= 3 )) && echo "RESULT desktop-dead: PASS ($N reconnects with backoff)" \ || echo "RESULT desktop-dead: FAIL ($N reconnects, result $RESULT)" else echo "RESULT desktop: $RESULT" fi ``` </details> <details><summary>desktopE2e.cpp — client harness on top of the tests' TestCoreController</summary> ```cpp // Desktop end-to-end harness (not part of the change): imports an AWG config whose // endpoint is a host name, connects through the real UI controller path // (toggleConnection -> prepareConfig -> ConnectionController -> VpnConnection), then // keeps running and logs every connection state change with a timestamp. The test // script outside kills server A and moves the name to server B meanwhile. #include <QApplication> #include <QDateTime> #include <QFile> #include <QTimer> #include <QUuid> #include "utils/testCoreController.h" #include "core/controllers/connectionController.h" #include "secureQSettings.h" #include "vpnConnection.h" using namespace amnezia; int main(int argc, char *argv[]) { QApplication app(argc, argv); const QStringList args = app.arguments(); if (args.size() < 3) { qCritical("usage: desktop_e2e <config file> <seconds>"); return 2; } QFile file(args.at(1)); if (!file.open(QIODevice::ReadOnly)) { qCritical("cannot read config"); return 2; } const QString configText = QString::fromUtf8(file.readAll()); const int seconds = args.at(2).toInt(); const qint64 t0 = QDateTime::currentSecsSinceEpoch(); auto stamp = [t0]() { return QString("%1s").arg(QDateTime::currentSecsSinceEpoch() - t0, 5); }; auto settings = new SecureQSettings("AmneziaVPN-E2E-" + QUuid::createUuid().toString(), "amnezia-client", nullptr, false); auto vpnConnection = QSharedPointer<VpnConnection>::create(nullptr, nullptr); auto core = new TestCoreController(vpnConnection, settings, nullptr, &app); QObject::connect(vpnConnection.data(), &VpnConnection::connectionStateChanged, &app, [stamp](Vpn::ConnectionState state) { qInfo().noquote() << "E2E" << stamp() << "state" << VpnProtocol::textConnectionState(state); }); // The UI controller's state handler needs the full application object (network // manager, tray); this harness has none, and the UI is not under test. if (auto cc = core->findChild<ConnectionController *>()) { QObject::disconnect(cc, &ConnectionController::connectionStateChanged, core->m_connectionUiController, nullptr); } auto imported = core->m_importCoreController->extractConfigFromData(configText); if (imported.errorCode != ErrorCode::NoError) { qCritical() << "import failed" << imported.errorCode; return 1; } core->m_importCoreController->importConfig(imported.config); qInfo().noquote() << "E2E" << stamp() << "imported, connecting"; core->m_connectionUiController->toggleConnection(); QTimer::singleShot(seconds * 1000, &app, [&]() { qInfo().noquote() << "E2E" << stamp() << "done, disconnecting"; vpnConnection->disconnectFromVpn(); QTimer::singleShot(3000, &app, &QCoreApplication::quit); }); const int rc = app.exec(); settings->clearSettings(); return rc; } ``` </details> Notes on the harness: - **Desktop harness.** It disconnects `ConnectionUiController` from `ConnectionController::connectionStateChanged`. Its `Connected` branch calls `amnApp->networkManager()`, which does not exist outside the full application. The connection path itself (`ConnectionController` → `VpnConnection` → `WireguardProtocol` → daemon) is untouched. - **Android harness.** It starts `AwgService` through `adb` (root) with the same JSON the app sends, and grants VPN consent with `appops`. --- <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#3198
No description provided.