Skip to content

listeners: clean up stale Unix socket files on Windows - #7676

Merged
steadytao merged 3 commits into
caddyserver:masterfrom
mfrischknecht:mf/delete-stale-unix-domain-socket-files-on-windows
Apr 29, 2026
Merged

steadytao merged 3 commits into
caddyserver:masterfrom
mfrischknecht:mf/delete-stale-unix-domain-socket-files-on-windows

Conversation

@mfrischknecht

Copy link
Copy Markdown
Contributor

The current non-unix implementation of reuseUnixSocket is essentially a no-op, and the reuse mechanism is entirely centered around fakeCloseListener wrappers and a refcounting mechanism in listenerPool.

The unix implementation of reuseUnixSocket, on the other hand, also performs an unlink() on any orphaned unix domain socket files that might have been left behind by earlier processes, which is not covered by the non-unix implementation.

This makes it rather painful to operate Caddy as a Windows service if it is configured to use a unix/ socket for its admin interface: In practice, it isn't all that rare that a Caddy instance fails to clean up its socket file, which breaks all subsequent startup attempts (meaning someone will have to manually delete the file in question). Caddy will fail to start with the following error in such cases:

Error: loading initial config: loading new config: starting caddy administration endpoint: listen unix C:\path\to\admin.sock: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.

This change introduces a separate reuseUnixSocket implementation for Windows that will try to delete such socket files if they don't already belong to the current Caddy process. I've left the function as a no-op for other platforms (i.e. non-unix, non-windows + solaris) since I'm not certain they provide the same failure modes as Windows.

Testing

As this change relates to socket state management, I've only tested this manually. An easy way to do so looks like this:

Caddyfile:

{
    admin unix/C:\path\to\admin.sock
}

In a shell (assuming pwsh):

caddy run

# In another pwsh:
taskkill /f /im caddy.exe

# After that, there's an orphaned socket file in C:\path\to\admin.sock
# Restarting caddy will fail from now on (but succeed with this PR's change):
caddy run
...
Error: loading initial config: loading new config: starting caddy administration endpoint: listen unix C:\path\to\admin.sock: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.

# With the change applied, repeatedly reloading the config keeps working:
Invoke-WebRequest `
    -SkipHttpErrorCheck `
    -Method Post `
    -ContentType "text/caddyfile" `
    -InFile Caddyfile `
    -UnixSocket C:\path\to\admin.sock `
    -Uri http://caddy/load
...
StatusCode        : 200
StatusDescription : OK
...

# Specifying a different UNIX domain socket as the admin socket and reloading the config
# also reliably causes caddy to switch sockets.

Invoke-WebRequest `
    -SkipHttpErrorCheck `
    -UnixSocket C:\path\to\admin.sock `
    -Method Post `
    -ContentType "application/json" `
    -Body ("unix/C:\path\to\admin2.sock" | ConvertTo-Json) `
    -Uri http://caddy/config/admin/listen
...
StatusCode        : 200
StatusDescription : OK
...


[System.IO.File]::Exists("C:\path\to\admin.sock")
False

[System.IO.File]::Exists("C:\path\to\admin2.sock")
True

On the isAbstractUnixSocket if statement

I've tried to figure out if the Windows implementation also supports abstract names for unix domain sockets and found that the current state is somewhat contradictory (as stated in the comment). From what I can tell, this isn't implemented in Windows (although the announcement stated otherwise), but the Go standard library also implements the @ -> \0 mapping for Windows, meaning that specifying something akin to admin @some-abstract-socket will nevertheless result in an attempt to listen to an abstract socket (which, strangely, also doesn't fail, leading to an inoperable admin socket but a running Caddy process).

Because of that, I figured it'd be better to have the correct behavior anyway, even if abstract unix sockets don't work. Essentially, avoiding to delete a socket file that won't be created (because of the mapping done by Go) won't hurt, and having the comment with references present will at least document the issue.

Assistance Disclosure

I've made this change in Cursor and used its tab-completion feature to do so.

While Windows doesn't have the need to reuse a socket file descriptor
by dup()ing it on config reloads, there still is a valid need for an
equivalent to the `syscall.Unlink()` call in listen_unix.go (also in
`reuseUnixSocket`).

If a previous Caddy instance didn't terminate properly, the chances it
will leave behind a socket file are very high, breaking all subsequent
starting attempts. Other than for regular files, Windows seemingly has
no way for a process to flag a UNIX domain socket file with `FILE_DELETE_ON_CLOSE`,
which means this scenario can never be avoided entirely (e.g. in the case
of crashes).

For the long comment on `isAbstractUnixSocket`: the logic itself is likely
of dubious value, but I thought it better to explicitly reference the
issue, as I have just spent half an hour searching the web to figure out
whether abstract names will work or not on Windows. At least, the logic
as-is should now do the sensible thing if these are ever implemented
properly (and it matches what the Golang standard library does internally).
@CLAassistant

CLAassistant commented Apr 28, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@steadytao

Copy link
Copy Markdown
Member

Firstly, thank you for signing the CLA and could you please fill out the AI disclosure properly. Requirements are the model provider used (such as Claude, Copilot or ChatGPT rather then the IDE) and how said model was used. Examples are within the pull request template. And;


This looks useful but I think the ownership wording is slightly stronger than what the code actually proves.

The listenerPool check tells us the socket is not owned by this Caddy process but it does not prove the file is stale or orphaned. If another live process owns that AF_UNIX path this can still remove the pathname before binding a replacement socket.

That may be acceptable if the goal is Windows parity with the existing Unix unlink-before-bind behaviour but I think the trade-off should be more explicit. If we want stricter safety here, the Windows path probably needs a liveness probe before removal, for example a short net.DialTimeout("unix", addr, ...), and only delete when the socket path exists but is not connectable.

@mfrischknecht

Copy link
Copy Markdown
Contributor Author

@steadytao Thank you for the quick response!

As for the AI disclosure, Cursor don't document much about the model they use for their tab completion beyond that they use their own proprietary model: https://cursor.com/product/tab

Apparently, they introduced a model called "Fusion" in January 2025 1, but their newest announcement on improvements for the feature 2 fell back to talking about "the model", "the Tab model" and so on (without naming anything substantial).

As far as I'm aware, there's also no way to pick between models for the tab completion. So, as far as the model goes, I don't think I can get more precise than "Cursor's tab completion, as of today"... I didn't use Cursor's agent editing workflow, so the models available there don't apply. Essentially, I just used Cursor as a smarter autocomplete.

Is there some other wording I should add to the description above?


On the net.DialTimeout: I didn't consider that. It would certainly make for a reliable check, but would also potentially introduce delays during config switches (in the worst case) if Caddy is configured to listen to multiple unix domain sockets for downstream connections, right?

Since I'm only really interested in the admin socket part, I can't really judge on how realistic and/or undesirable that is, but I can certainly add it to the PR. Do you think hard-coding a low (2-3 digit) millisecond timeout would work for this, or should this be configurable somehow?

Footnotes

  1. https://cursor.com/blog/tab-update ↩

  2. https://cursor.com/blog/tab-rl ↩

@steadytao

Copy link
Copy Markdown
Member

That is enough context for me, thank you.

Also, I would not make it configurable. This is only internal listener hygiene. If we do add a probe, I would keep it very small and bounded probably tens of milliseconds rather than hundreds and only on Windows when the path exists and is not already in Caddy’s listener pool. That keeps config switches from paying the cost in the normal reuse path.

That said, I do not feel strongly that the probe must be added if the intended behaviour is simply Unix parity. My main point was that the PR should be explicit about the trade-off; without probing, Caddy may remove a socket path owned by another live process which is consistent with unlink-before-bind style behaviour but is not the same as proving the file is orphaned.

As @steadytao pointed out (thanks!), the previous code didn't have
solid proof that an existing unix socket file had really been orphaned,
as it's also possible that there's another server process (still running).

This would still give the Windows implementation parity with the unix
one (as that one also unlinks the socket file without further checks),
but I've performed a couple of small tests and found this way of handling
socket files still problematic at least problematic if Caddy is used as
a reverse proxy in real world scenarios.

In tests with a simple Caddyfile that only declares an admin socket,
starting two caddy instances with the same Caddyfile works and behaves
like one would expect: the second instance removes the first instance's
socket file and "wins" the race.

When Caddy is used as a reverse proxy, though, what'll happen is more
complicated: While the second instance wins the race for the admin
socket, as long as the Caddyfile specifies a TCP downstream socket,
the second process will not be able to take this one over from the first
(also to be expected, that's how socket binding usually works).

This results in a rather broken state: The first process still holds on
to its TCP listening sockets, the second process fails to start because
of the error in its listening attempt, leaving an orphaned admin socket
file in the file system. Afterwards, the second process won't be running
and the first _will_ be running but unable to be controlled because its
admin socket has been replaced. This leaves the system in another state
that is bad from an ops perspective.

With this new change, we try first to connect to any unix socket that
isn't already covered by our current process (with a very low timeout)
and can easily decide if the socket is still in use by another process:

- If the connection is accepted, there's obviously a server process.

- If Windows returns WSACONNREFUSED [^1], there is either no active
  server process for the socket file anymore, or the socket file does
  not exist.

- Any other errors are likely a sign that there still is a server process
  (e.g. a timeout would indicate that it's just slow in accepting new
  connection attempts).

[^1]: https://learn.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2#wsaeconnrefused
@mfrischknecht

Copy link
Copy Markdown
Contributor Author

I've decided to perform another couple of tests for this scenario to get a feel for what this means in our setup.

As you wrote, Caddy would happily remove the unix domain socket file of another (running) process this way (which interestingly isn't how Windows usually deals with files, but it seems to behave differently for unix domain sockets). What I didn't consider is that this can cause real problems in reverse proxy configurations:

If the Caddyfile specifies a TCP downstream port, the dance around the admin socket works as expected (younger process wins), but after that, the conflict around the TCP listening ports will go the other way (the already running process wins). This means that if Caddy is started twice for some reason, the result can still be a broken state: The older process keeps running and serving HTTP, but its admin socket is dead, while the younger process fails to start up and leaves an orphaned admin socket behind. Of course, with proper service handling this shouldn't just happen out of the blue, but if ops still does some things by hand, it is still a possibility.

Because the possible failure case is still an operative risk, I decided to try out the dial attempt you suggested.

@steadytao I'd appreciate your feedback again, if you have the time. Thanks!

@steadytao

steadytao commented Apr 29, 2026 •

Copy link
Copy Markdown
Member

Pushed a small cleanup commit to add the standard Caddy licence headers to the new files, alter the internal socket-in-use error to be unexported and normalise comment formatting.

I think the dial probe addresses the concrete failure mode.

The bad state came from the younger process unlinking the older process’ live admin socket before later losing on another listener, such as a TCP downstream port. With the probe, a live admin socket should be detected before removal so the younger process fails without breaking the older process’ admin endpoint.

There is still an unavoidable race between probe/remove/bind but that is inherent to stale-socket cleanup and is acceptable here.

@steadytao steadytao added the feature ⚙️ New feature or request label Apr 29, 2026
@steadytao steadytao added this to the v2.11.3 milestone Apr 29, 2026
@steadytao steadytao changed the title Delete old unix domain socket files on Windows listeners: clean up stale Unix socket files on Windows Apr 29, 2026

@steadytao steadytao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Review comment history.

@steadytao
steadytao merged commit 6a64bb2 into caddyserver:master Apr 29, 2026
28 checks passed
@steadytao

Copy link
Copy Markdown
Member

@mfrischknecht, thank you for the PR.

social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
caddy 2.11.3

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.

- [ ] `resource` blocks have been checked for updates.
<details>
  <summary>release notes</summary>
  <pre>This release improves several aspects of Caddy with minor features, bug fixes, and security patches. Thank you to everyone and their bots who contributed to help make this release the best one yet!

**Security patches:**

- fastcgi: Carrying over a patch from FrankenPHP for a bug that could allow non-PHP files to be executed; collaborated on by @dunglas, @KC1zs4, and @chenjj.
- vars: A more thorough fix for GHSA-m2w3-8f23-hxxf, collaborated by @everping and @vnxme.
- admin: Array index normalization to prevent remote admin socket auth bypass, by @Amemoyoi and bot.
- admin: More rigorous path prefix matching to prevent remote admin socket auth bypass, by @Amemoyoi and bot.

We've also merged a couple PRs that fix upstream security bugs in other projects like quic-go and CertMagic. Thank you to @marten-seemann for maintaining quic-go so diligently!

## What's Changed
* caddyhttp: Sync placeholder expansion in `vars` and `vars_regexp` by @vnxme in caddyserver/caddy#7573
* caddytls: Avoid ACME fallback for implicit Tailscale *.ts.net policies by @steadytao in caddyserver/caddy#7577
* chore: Resolve recent CI failures by @mholt in caddyserver/caddy#7593
* caddytls: Consolidate empty APs more smartly by @mholt in caddyserver/caddy#7567
* rewrite: skip query rename when source key is absent by @steadytao in caddyserver/caddy#7599
* root: introduce down-propagating Helper.BlockState for other directives/plugins to use by @henderkes in caddyserver/caddy#7594
* http: make zstd checksum configurable by @ottenhoff in caddyserver/caddy#7586
* notify: Always send "READY=1" even after an error by @francislavoie in caddyserver/caddy#7597
* reverseproxy: Fix check for `header_up Host {upstream_hostport}` redundancy by @yubiuser in caddyserver/caddy#7564
* caddytls: Expand placeholders in dns_challenge override_domain tls parameter by @pberkel in caddyserver/caddy#7609
* tls: add system and combined CA pool modules by @HarshPatel5940 in caddyserver/caddy#7406
* vars: Don't expand placeholders in values by @vnxme in caddyserver/caddy#7629
* build(deps): bump go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp from 1.42.0 to 1.43.0 by @dependabot[bot] in caddyserver/caddy#7637
* build(deps): bump the all-updates group across 1 directory with 11 updates by @dependabot[bot] in caddyserver/caddy#7641
* reverseproxy: make stream copy buffer size configurable by @steadytao in caddyserver/caddy#7627
* vars: Add matcher placeholder handling tests by @steadytao in caddyserver/caddy#7640
* build(deps): bump github.com/go-jose/go-jose/v4 from 4.1.3 to 4.1.4 by @dependabot[bot] in caddyserver/caddy#7621
* logging: Add journald encoder wrapper by @steadytao in caddyserver/caddy#7623
* caddyfile: Improve import/global options UX for imports before global options by @steadytao in caddyserver/caddy#7642
* chore: replace `interface{}` with `any` for modernization by @tsinglua in caddyserver/caddy#7571
* chore: bump timberjack to v1.4.1 by @DeRuina in caddyserver/caddy#7618
* logging: Preserve ts for journald-wrapped JSON logs by @steadytao in caddyserver/caddy#7644
* fileserver: show symlink targets verbatim (#7476) by @maxtruxa in caddyserver/caddy#7579
* fix(caddyfile): {block} in snippet by @prettysunflower in caddyserver/caddy#7558
* caddyhttp: Document missing placeholders for escaped URI and prefixed query by @steffenbusch in caddyserver/caddy#7659
* chore: add `AGENTS.md` by @mohammed90 in caddyserver/caddy#7652
* build(deps): bump github.com/jackc/pgx/v5 from 5.8.0 to 5.9.0 by @dependabot[bot] in caddyserver/caddy#7655
* admin: Redact sensitive request headers in API logs by @steadytao in caddyserver/caddy#7578
* reverseproxy: add `lb_retry_match` condition on response status by @seroperson in caddyserver/caddy#7569
* caddyhttp: prefer port 443 in auto-HTTPS and add tests by @mholt in caddyserver/caddy#7666
* fix: Propagate ECH keys to the QUIC listener by @steadytao in caddyserver/caddy#7670
* chore: Use atomics where appropriate by @francislavoie in caddyserver/caddy#7648
* metrics: Implement pushing via OLTP by @dunglas in caddyserver/caddy#7664
* logging: Add regression coverage for rotated file mode by @steadytao in caddyserver/caddy#7620
* httpcaddyfile: Inherit global ACME issuer settings in tls shortcuts by @steadytao in caddyserver/caddy#7617
* build(deps): bump github.com/jackc/pgx/v5 from 5.9.0 to 5.9.2 by @dependabot[bot] in caddyserver/caddy#7668
* admin: require path segment boundary in remote access control by @Amemoyoi in caddyserver/caddy#7673
* reverseproxy: Add ability to clear dynamic upstreams cache during retries by @mholt in caddyserver/caddy#7662
* listeners: clean up stale Unix socket files on Windows by @mfrischknecht in caddyserver/caddy#7676
* admin: reject non-canonical config array indices by @Amemoyoi in caddyserver/caddy#7592
* caddytls: Expand ACME credentials by @tribut in caddyserver/caddy#7554
* caddyauth: set user placeholders before auth rejection by @cyphercodes in caddyserver/caddy#7685
* caddyauth: revert user placeholders on auth rejection by @steadytao in caddyserver/caddy#7688
* chore: Fix golangci-lint 2.12.1 findings by @steadytao in caddyserver/caddy#7690
* httpcaddyfile: accept duration strings for log sampling interval by @tomholford in caddyserver/caddy#7694
* tls: Add alpn to managed HTTPS records by @steadytao in caddyserver/caddy#7653
* caddytls: avoid duplicate automation for wildcard-covered hosts by @Rijul-A in caddyserver/caddy#7697
* docs: add documentation for fileExists and fileStat template functions by @steffenbusch in caddyserver/caddy#7700
* rewrite: escape file matcher paths before rewriting by @cyphercodes in caddyserver/caddy#7683
* metrics: Add nil check for metricsHandler in AdminMetrics.serveHTTP by @Br1an67 in caddyserver/caddy#7553

## New Contributors
* @steadytao made their first contribution in caddyserver/caddy#7577
* @henderkes made their first contribution in caddyserver/caddy#7594
* @yubiuser made their first contribution in caddyserver/caddy#7564
* @pberkel made their first contribution in caddyserver/caddy#7609
* @HarshPatel5940 made their first contribution in caddyserver/caddy#7406
* @tsinglua made their first contribution in caddyserver/caddy#7571
* @maxtruxa made their first contribution in caddyserver/caddy#7579
* @seroperson made their first contribution in caddyserver/caddy#7569
* @Amemoyoi made their first contribution in caddyserver/caddy#7673
* @mfrischknecht made their first contribution in caddyserver/caddy#7676
* @tribut made their first contribution in caddyserver/caddy#7554
* @cyphercodes made their first contribution in caddyserver/caddy#7685
* @tomholford made their first contribution in caddyserver/caddy#7694
* @Rijul-A made their first contribution in caddyserver/caddy#7697
* @Br1an67 made their first contribution in caddyserver/caddy#7553

**Full Changelog**: https://github.com/caddyserver/caddy/compare/v2.11.2...v2.11.3</pre>
  <p>View the full release notes at <a href="https://github.com/caddyserver/caddy/releases/tag/v2.11.3">https://github.com/caddyserver/caddy/releases/tag/v2.11.3</a>.</p>
</details>
<hr>



See merge request: Harmonybrew/homebrew-core!842
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature ⚙️ New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants