[GH-ISSUE #6368] [Bug]: Updating an AmneziaWG inbound hangs the API request and leaves the device stopped #4321

Closed
opened 2026-10-31 20:38:49 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @IvanSavoskin on GitHub (Aug 30, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6368

Describe the bug

POST /panel/api/inbounds/update/:id on an amneziawg inbound that has active clients does
not return, and afterwards the inbound's UDP port is no longer bound. The panel keeps running
and serving the web UI, and the new value is in fact persisted — only the embedded device
stays down. systemctl restart x-ui brings the listener back with the new settings.

Reproduced several times on an inbound with 11 peers while changing a single field inside
settings.server.

How to reproduce the problem

  1. Create an inbound with protocol: amneziawg and add ~10 clients.
  2. GET /panel/api/inbounds/get/:id and take the returned object as-is.
  3. Change exactly one field inside settings.server (mtu in our case, h1-h4 behaves
    the same) and send the whole object back to POST /panel/api/inbounds/update/:id.
  4. The request does not complete. Abort the client after ~25 seconds.
  5. ss -lunp | grep <port> — nothing is listening any more.
  6. GET /panel/api/inbounds/get/:id — the new value is stored.
  7. systemctl restart x-ui — the port is bound again and the new value is in effect.

Expected behavior

The update either applies and the embedded device is restarted with the new settings, or it
fails with an error response and the device keeps running with the old ones. In both cases
the request should return.

Actual behavior

The request hangs, the embedded interface stays down, the port is unbound, and nothing is
written to the log. The setting is saved, so the panel and the running device disagree until
the service is restarted manually. For an inbound with live users this is an outage that
gives no signal anywhere.

Relevant logs

Nothing is logged around the failing update. The only AmneziaWG lines ever produced are the
normal start/stop pair, and in the failing case even the `started` line does not appear:


INFO - amneziawgnet: stopped embedded interface for removed inbound 47
INFO - amneziawgnet: started embedded interface awg47 for inbound 47
INFO - amneziawgnet: stopped embedded interface for removed inbound 48
INFO - amneziawgnet: started embedded interface awg48 for inbound 48


After the hung request, `journalctl -u x-ui` filtered for `amnezia|awg|error|panic` returns
nothing for the whole window, while the port is gone from `ss -lunp`.

Screenshots

No response

3x-ui version

3.7.0

Xray-core version

26.7.28

How did you install 3x-ui?

install.sh script

Operating system

Ubuntu 24.04 LTS, x86_64

Which parts of the panel are affected?

Backend (API endpoints, login, settings)

Browser (only if it is a UI bug)

No response

Is the panel behind a reverse proxy or CDN?

None

Before submitting

  • I searched existing issues and this bug has not been reported.
  • I am running the latest released version of 3x-ui (or have verified the bug still exists on it).
  • This bug report is written in English.
  • I have redacted any sensitive data (tokens, real domains, client UUIDs).
Originally created by @IvanSavoskin on GitHub (Aug 30, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6368 ### Describe the bug `POST /panel/api/inbounds/update/:id` on an `amneziawg` inbound that has active clients does not return, and afterwards the inbound's UDP port is no longer bound. The panel keeps running and serving the web UI, and the new value is in fact persisted — only the embedded device stays down. `systemctl restart x-ui` brings the listener back with the new settings. Reproduced several times on an inbound with 11 peers while changing a single field inside `settings.server`. ### How to reproduce the problem 1. Create an inbound with `protocol: amneziawg` and add ~10 clients. 2. `GET /panel/api/inbounds/get/:id` and take the returned object as-is. 3. Change exactly one field inside `settings.server` (`mtu` in our case, `h1`-`h4` behaves the same) and send the whole object back to `POST /panel/api/inbounds/update/:id`. 4. The request does not complete. Abort the client after ~25 seconds. 5. `ss -lunp | grep <port>` — nothing is listening any more. 6. `GET /panel/api/inbounds/get/:id` — the new value is stored. 7. `systemctl restart x-ui` — the port is bound again and the new value is in effect. ### Expected behavior The update either applies and the embedded device is restarted with the new settings, or it fails with an error response and the device keeps running with the old ones. In both cases the request should return. ### Actual behavior The request hangs, the embedded interface stays down, the port is unbound, and nothing is written to the log. The setting is saved, so the panel and the running device disagree until the service is restarted manually. For an inbound with live users this is an outage that gives no signal anywhere. ### Relevant logs ```shell Nothing is logged around the failing update. The only AmneziaWG lines ever produced are the normal start/stop pair, and in the failing case even the `started` line does not appear: INFO - amneziawgnet: stopped embedded interface for removed inbound 47 INFO - amneziawgnet: started embedded interface awg47 for inbound 47 INFO - amneziawgnet: stopped embedded interface for removed inbound 48 INFO - amneziawgnet: started embedded interface awg48 for inbound 48 After the hung request, `journalctl -u x-ui` filtered for `amnezia|awg|error|panic` returns nothing for the whole window, while the port is gone from `ss -lunp`. ``` ### Screenshots _No response_ ### 3x-ui version 3.7.0 ### Xray-core version 26.7.28 ### How did you install 3x-ui? install.sh script ### Operating system Ubuntu 24.04 LTS, x86_64 ### Which parts of the panel are affected? Backend (API endpoints, login, settings) ### Browser (only if it is a UI bug) _No response_ ### Is the panel behind a reverse proxy or CDN? None ### Before submitting - [x] I searched [existing issues](../issues?q=is%3Aissue) and this bug has not been reported. - [x] I am running the latest released version of 3x-ui (or have verified the bug still exists on it). - [x] This bug report is written in English. - [x] I have redacted any sensitive data (tokens, real domains, client UUIDs).
bsakaguchi 2026-10-31 20:38:49 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@github-actions[bot] commented on GitHub (Aug 30, 2026):

This is a real bug, and it is a lock inversion inside the embedded AmneziaWG manager: Manager.Ensure holds its own mutex across the device teardown, while the packet-delivery path re-enters that same mutex — so one UDP packet in flight at the moment of the update wedges both goroutines permanently. Every symptom you listed (hang, unbound port, value persisted, nothing logged, restart required) falls out of that single line.

The chain

1. The API saves first, then applies to the runtime synchronously in the request goroutine. internal/web/service/inbound.go:1716 commits the row (tx.Save(oldInbound)), and only afterwards, at internal/web/service/inbound.go:1742:

if postCommitApply != nil {
	postCommitApply()
}

That is exactly why step 6 of your repro finds the new value stored while the request never returns.

2. postCommitApply → rt.UpdateInbound → internal/web/runtime/local.go:196: amneziawgnet.GetManager().Ensure(...).

3. Ensure holds the manager mutex for the whole apply — internal/amneziawgnet/manager.go:86:

func (m *Manager) Ensure(d Desired) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	return m.ensureLocked(d)
}

4. mtu is part of the rebuild fingerprint — internal/amneziawgnet/manager.go:258:

func addressFingerprint(inst amneziawg.Instance) string {
	return fmt.Sprintf("%d|%s", inst.MTU, strings.Join(inst.Address, ","))
}

So an mtu edit takes the rebuild branch and calls cur.dev.Close() at internal/amneziawgnet/manager.go:165 while still holding m.mu.

5. The UDP handler runs inline on the packet-delivery goroutine and re-enters the manager. Unlike the TCP forwarder, which dispatches each connection onto its own goroutine (internal/amneziawgnet/forwarder.go:27, go func(r *tcp.ForwarderRequest)), the UDP handler is called synchronously — internal/amneziawgnet/udp.go:34-40. And the closure ensureLocked attaches, internal/amneziawgnet/manager.go:199:

AttachUDPHandler(dev.Stack, func(src, dst netip.AddrPort, payload []byte) {
	_, peers, ok := m.Lookup(inboundID)

Lookup takes the same mutex — internal/amneziawgnet/manager.go:335-337.

6. That delivery goroutine is a peer's receive goroutine, which the repo documents itself at internal/amneziawgnet/device.go:113: "WARNING: DATA RACE between stack.(*nic).DeliverTransportPacket (the peer's receive goroutine, reading the handler table)". Closing an amneziawg-go device stops every peer, which means joining exactly those receive goroutines.

Request goroutine holds m.mu and waits for the peer receive goroutine; the peer receive goroutine is parked in Lookup waiting for m.mu. Neither ever completes.

Why each of your observations matches

  • Port unbound but request still hanging — the bind is closed before the peer-stop join, so the listener disappears and then the join blocks. This also pins the hang to the window between manager.go:165 (cur.dev.Close()) and the new device's Up(), and rules out the later steps (applyV6Aliases, portForwards.Reconcile), which run after the new device is already listening.
  • Nothing logged — logger.Infof("amneziawgnet: started embedded interface ...") is internal/amneziawgnet/manager.go:239, past the block, and the device's own logger is silent unless AMNEZIAWGNET_DEBUG is set (internal/amneziawgnet/manager.go:27-32).
  • Only a service restart recovers it — after the deadlock, every 10s tick of AmneziaWGJob (internal/web/job/amneziawg_job.go:54 → Reconcile) blocks on the same mutex, so no AmneziaWG interface can ever be (re)started in that process again.
  • h1–h4 behaves the same — those are not in the fingerprint, so they take the in-place branch, internal/amneziawgnet/manager.go:151 (cur.dev.IpcSet(conf)), still under m.mu. Per the code's own note at internal/amneziawgnet/manager.go:96: "amneziawg-go's IpcSet always includes replace_peers=true ... and its own implementation of that op is device.RemoveAllPeers(), unconditionally" — which also has to stop every peer. Same deadlock through a different door. One useful discriminator: in the h1–h4 case the UDP port should stay bound (no bind close on that path). If you saw the port survive there, that confirms the IpcSet variant.

Why it needs active clients: at least one UDP packet must be in flight through the tunnel at the instant of the apply. TCP alone cannot trigger it. With 11 live peers, DNS/QUIC/keepalive traffic makes that near-certain, which is why it reproduces for you every time and not on an idle inbound.

What you can do now

The edit is already persisted before the hang, so systemctl restart x-ui applies it correctly — that is the recovery, and there is no way to avoid it once the request has hung. To avoid hitting it, make mtu / address / obfuscation edits during a window with no peer traffic. Note that disabling the inbound first does not help: Remove (internal/amneziawgnet/manager.go:295) takes the same lock and closes the same device.

If you can reproduce it once more, a goroutine dump would nail the pair conclusively. Set XUI_PPROF=true in /etc/default/x-ui (that is the environment file on Ubuntu), systemctl restart x-ui, then during the hang:

curl -s 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' > /tmp/awg-hang.txt

The two stacks that matter are one in amneziawgnet.(*Manager).Ensure sitting in the device close, and one in amneziawgnet.(*Manager).Lookup sitting in sync.(*Mutex).Lock. It is not required for triage — the inversion is visible in the source — but it would remove the last inferred link.

Verdict: Confirmed bug
Severity: High
Confidence: High
Root cause: internal/amneziawgnet/manager.go:86 — Manager.Ensure holds m.mu for the entire ensureLocked call, which then tears down (manager.go:165, cur.dev.Close()) or replace_peers-reconfigures (manager.go:151, cur.dev.IpcSet) the running device. Both must stop every peer's receive goroutine, and that goroutine is the one that runs the inline UDP handler at manager.go:199-201, which calls m.Lookup → m.mu (manager.go:335-337). Trigger: any AmneziaWG inbound update concurrent with at least one in-flight UDP packet. Introduced by effcccce ("feat(amneziawg): add native AmneziaWG protocol support (#6105)", 2026-08-24) — internal/amneziawgnet/manager.go has no other commit.
Already fixed: Still present on the default branch (git log -- internal/amneziawgnet/manager.go returns only effcccce; git tag --contains effcccce → v3.7.0, dev-latest).
Duplicate of: None. #6323 is the same subsystem but a different symptom (TCP never relayed) and is not established to share this root cause.
Evidence:

  • internal/amneziawgnet/manager.go:86-90 — m.mu.Lock(); defer m.mu.Unlock(); return m.ensureLocked(d)
  • internal/amneziawgnet/manager.go:162-167 — rebuild branch: cur.udpRelay.Close(); cur.portForwards.Close(); cur.dev.Close() under that lock
  • internal/amneziawgnet/manager.go:151 — in-place branch: if err := cur.dev.IpcSet(conf); err != nil { under that lock
  • internal/amneziawgnet/manager.go:96-99 — in-repo statement that IpcSet's replace_peers=true is implemented as device.RemoveAllPeers(), unconditionally
  • internal/amneziawgnet/manager.go:199-201 / :335-337 — the UDP handler closure calls m.Lookup, which locks m.mu
  • internal/amneziawgnet/udp.go:34-40 — SetTransportProtocolHandler calls handler(src, dst, data) inline, no goroutine
  • internal/amneziawgnet/forwarder.go:27 — the TCP path does spawn a goroutine, which is why TCP alone does not reproduce it
  • internal/amneziawgnet/device.go:113-117 — in-repo confirmation that packets are delivered into the stack on "the peer's receive goroutine"
  • internal/web/service/inbound.go:1716 then :1742-1744 — DB commit precedes the synchronous runtime apply
  • internal/web/runtime/local.go:196 — updateAmneziaWGInbound calls Ensure in the request goroutine
  • internal/web/job/amneziawg_job.go:54 — the 10s reconcile takes the same lock, so the wedge is permanent
    Not determined: amneziawg-go v3.1.20260814's own Device.Close / Peer.Stop source was not readable here (no module cache in this checkout), so the exact join that blocks — peer.stopping.Wait() in upstream wireguard-go lineage — is inferred from the upstream contract rather than quoted. The goroutine dump above settles it. Also unverified: the panel's GetStatus calls HasRunning() (internal/web/service/server.go:633), which takes the same mutex, so I would expect the dashboard status endpoint to hang too after the deadlock — you reported the web UI as still serving, so that is worth a second look.

Suggested fix: Stop holding m.mu across the device mutation in ensureLocked — snapshot the *managed under the lock, release it, then Close/IpcSet outside it. Alternatively, give the peer index its own lock (or store it atomically) so the data-path Lookup can never be blocked by an admin apply.

@MHSanaei

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:5468842309 --> @github-actions[bot] commented on GitHub (Aug 30, 2026): This is a real bug, and it is a lock inversion inside the embedded AmneziaWG manager: `Manager.Ensure` holds its own mutex across the device teardown, while the packet-delivery path re-enters that same mutex — so one UDP packet in flight at the moment of the update wedges both goroutines permanently. Every symptom you listed (hang, unbound port, value persisted, nothing logged, restart required) falls out of that single line. ### The chain **1. The API saves first, then applies to the runtime synchronously in the request goroutine.** `internal/web/service/inbound.go:1716` commits the row (`tx.Save(oldInbound)`), and only afterwards, at `internal/web/service/inbound.go:1742`: ```go if postCommitApply != nil { postCommitApply() } ``` That is exactly why step 6 of your repro finds the new value stored while the request never returns. **2. `postCommitApply` → `rt.UpdateInbound` → `internal/web/runtime/local.go:196`:** `amneziawgnet.GetManager().Ensure(...)`. **3. `Ensure` holds the manager mutex for the whole apply** — `internal/amneziawgnet/manager.go:86`: ```go func (m *Manager) Ensure(d Desired) error { m.mu.Lock() defer m.mu.Unlock() return m.ensureLocked(d) } ``` **4. `mtu` is part of the rebuild fingerprint** — `internal/amneziawgnet/manager.go:258`: ```go func addressFingerprint(inst amneziawg.Instance) string { return fmt.Sprintf("%d|%s", inst.MTU, strings.Join(inst.Address, ",")) } ``` So an `mtu` edit takes the rebuild branch and calls `cur.dev.Close()` at `internal/amneziawgnet/manager.go:165` **while still holding `m.mu`**. **5. The UDP handler runs inline on the packet-delivery goroutine and re-enters the manager.** Unlike the TCP forwarder, which dispatches each connection onto its own goroutine (`internal/amneziawgnet/forwarder.go:27`, `go func(r *tcp.ForwarderRequest)`), the UDP handler is called synchronously — `internal/amneziawgnet/udp.go:34-40`. And the closure `ensureLocked` attaches, `internal/amneziawgnet/manager.go:199`: ```go AttachUDPHandler(dev.Stack, func(src, dst netip.AddrPort, payload []byte) { _, peers, ok := m.Lookup(inboundID) ``` `Lookup` takes the same mutex — `internal/amneziawgnet/manager.go:335-337`. **6. That delivery goroutine is a peer's receive goroutine**, which the repo documents itself at `internal/amneziawgnet/device.go:113`: *"WARNING: DATA RACE between stack.(\*nic).DeliverTransportPacket (the peer's receive goroutine, reading the handler table)"*. Closing an amneziawg-go device stops every peer, which means joining exactly those receive goroutines. Request goroutine holds `m.mu` and waits for the peer receive goroutine; the peer receive goroutine is parked in `Lookup` waiting for `m.mu`. Neither ever completes. ### Why each of your observations matches - **Port unbound but request still hanging** — the bind is closed before the peer-stop join, so the listener disappears and *then* the join blocks. This also pins the hang to the window between `manager.go:165` (`cur.dev.Close()`) and the new device's `Up()`, and rules out the later steps (`applyV6Aliases`, `portForwards.Reconcile`), which run after the new device is already listening. - **Nothing logged** — `logger.Infof("amneziawgnet: started embedded interface ...")` is `internal/amneziawgnet/manager.go:239`, past the block, and the device's own logger is silent unless `AMNEZIAWGNET_DEBUG` is set (`internal/amneziawgnet/manager.go:27-32`). - **Only a service restart recovers it** — after the deadlock, every 10s tick of `AmneziaWGJob` (`internal/web/job/amneziawg_job.go:54` → `Reconcile`) blocks on the same mutex, so no AmneziaWG interface can ever be (re)started in that process again. - **`h1`–`h4` behaves the same** — those are not in the fingerprint, so they take the in-place branch, `internal/amneziawgnet/manager.go:151` (`cur.dev.IpcSet(conf)`), still under `m.mu`. Per the code's own note at `internal/amneziawgnet/manager.go:96`: *"amneziawg-go's IpcSet always includes replace_peers=true ... and its own implementation of that op is device.RemoveAllPeers(), unconditionally"* — which also has to stop every peer. Same deadlock through a different door. One useful discriminator: in the `h1`–`h4` case the UDP port should **stay bound** (no bind close on that path). If you saw the port survive there, that confirms the `IpcSet` variant. **Why it needs active clients:** at least one UDP packet must be in flight through the tunnel at the instant of the apply. TCP alone cannot trigger it. With 11 live peers, DNS/QUIC/keepalive traffic makes that near-certain, which is why it reproduces for you every time and not on an idle inbound. ### What you can do now The edit is already persisted before the hang, so `systemctl restart x-ui` applies it correctly — that is the recovery, and there is no way to avoid it once the request has hung. To avoid hitting it, make `mtu` / address / obfuscation edits during a window with no peer traffic. Note that disabling the inbound first does **not** help: `Remove` (`internal/amneziawgnet/manager.go:295`) takes the same lock and closes the same device. If you can reproduce it once more, a goroutine dump would nail the pair conclusively. Set `XUI_PPROF=true` in `/etc/default/x-ui` (that is the environment file on Ubuntu), `systemctl restart x-ui`, then during the hang: ```bash curl -s 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' > /tmp/awg-hang.txt ``` The two stacks that matter are one in `amneziawgnet.(*Manager).Ensure` sitting in the device close, and one in `amneziawgnet.(*Manager).Lookup` sitting in `sync.(*Mutex).Lock`. It is not required for triage — the inversion is visible in the source — but it would remove the last inferred link. Verdict: Confirmed bug Severity: High Confidence: High Root cause: `internal/amneziawgnet/manager.go:86` — `Manager.Ensure` holds `m.mu` for the entire `ensureLocked` call, which then tears down (`manager.go:165`, `cur.dev.Close()`) or replace_peers-reconfigures (`manager.go:151`, `cur.dev.IpcSet`) the running device. Both must stop every peer's receive goroutine, and that goroutine is the one that runs the inline UDP handler at `manager.go:199-201`, which calls `m.Lookup` → `m.mu` (`manager.go:335-337`). Trigger: any AmneziaWG inbound update concurrent with at least one in-flight UDP packet. Introduced by effcccce ("feat(amneziawg): add native AmneziaWG protocol support (#6105)", 2026-08-24) — `internal/amneziawgnet/manager.go` has no other commit. Already fixed: Still present on the default branch (`git log -- internal/amneziawgnet/manager.go` returns only effcccce; `git tag --contains effcccce` → v3.7.0, dev-latest). Duplicate of: None. #6323 is the same subsystem but a different symptom (TCP never relayed) and is not established to share this root cause. Evidence: - `internal/amneziawgnet/manager.go:86-90` — `m.mu.Lock(); defer m.mu.Unlock(); return m.ensureLocked(d)` - `internal/amneziawgnet/manager.go:162-167` — rebuild branch: `cur.udpRelay.Close(); cur.portForwards.Close(); cur.dev.Close()` under that lock - `internal/amneziawgnet/manager.go:151` — in-place branch: `if err := cur.dev.IpcSet(conf); err != nil {` under that lock - `internal/amneziawgnet/manager.go:96-99` — in-repo statement that `IpcSet`'s `replace_peers=true` is implemented as `device.RemoveAllPeers()`, unconditionally - `internal/amneziawgnet/manager.go:199-201` / `:335-337` — the UDP handler closure calls `m.Lookup`, which locks `m.mu` - `internal/amneziawgnet/udp.go:34-40` — `SetTransportProtocolHandler` calls `handler(src, dst, data)` inline, no goroutine - `internal/amneziawgnet/forwarder.go:27` — the TCP path *does* spawn a goroutine, which is why TCP alone does not reproduce it - `internal/amneziawgnet/device.go:113-117` — in-repo confirmation that packets are delivered into the stack on "the peer's receive goroutine" - `internal/web/service/inbound.go:1716` then `:1742-1744` — DB commit precedes the synchronous runtime apply - `internal/web/runtime/local.go:196` — `updateAmneziaWGInbound` calls `Ensure` in the request goroutine - `internal/web/job/amneziawg_job.go:54` — the 10s reconcile takes the same lock, so the wedge is permanent Not determined: amneziawg-go v3.1.20260814's own `Device.Close` / `Peer.Stop` source was not readable here (no module cache in this checkout), so the exact join that blocks — `peer.stopping.Wait()` in upstream wireguard-go lineage — is inferred from the upstream contract rather than quoted. The goroutine dump above settles it. Also unverified: the panel's `GetStatus` calls `HasRunning()` (`internal/web/service/server.go:633`), which takes the same mutex, so I would expect the dashboard status endpoint to hang too after the deadlock — you reported the web UI as still serving, so that is worth a second look. Suggested fix: Stop holding `m.mu` across the device mutation in `ensureLocked` — snapshot the `*managed` under the lock, release it, then `Close`/`IpcSet` outside it. Alternatively, give the peer index its own lock (or store it atomically) so the data-path `Lookup` can never be blocked by an admin apply. @MHSanaei *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Author
Owner

@dawNotPoi commented on GitHub (Sep 3, 2026):

I would like to work on this. I will keep lifecycle operations serialized while removing the data-path re-entry into the manager lock, and add a focused local regression test that calls the production UDP handler while the lifecycle lock is held.

<!-- gh-comment-id:5522630691 --> @dawNotPoi commented on GitHub (Sep 3, 2026): I would like to work on this. I will keep lifecycle operations serialized while removing the data-path re-entry into the manager lock, and add a focused local regression test that calls the production UDP handler while the lifecycle lock is held.
Sign in to join this conversation.
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
MHSanaei/3x-ui#4321
No description provided.