From 155ac62cb726f1427ba835ada35f007dd4da7c53 Mon Sep 17 00:00:00 2001 From: Jaeyeong Choi <144660874+Jaeyeong-CHOI@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:13:14 +0900 Subject: [PATCH 1/2] fix(server): keep a running listener's Unix socket and non-socket paths `bind_unix` removed whatever existed at the `--host .sock` path before it bound. That is right for the socket an earlier run left behind, and the server leaves its own behind when it stops. It also took the path away from a server still listening on it, which kept running unreachable, and deleted a regular file or a symlink found there. The path is now looked at first. An entry that is not a socket is left alone and the start fails. A socket is probed with one non-blocking connect: only "connection refused" (or a path that vanished meanwhile) reads as nobody there, and that socket is removed and the path bound, as before, so a restart on the same path keeps working. An accepted or queued connection, or a full accept queue on Linux, means a listener; any other result (no permission to connect, a socket of another type) leaves the question open. In both cases the start fails and the socket is left as it is. The check and the removal are two steps: two servers started on one stale path at the same instant can both pass it, and the later bind takes the path, as it always did. macOS answers "connection refused" for a full accept queue as well, so a saturated listener cannot be recognised there. --- docs/server-features.md | 8 ++ src/server/listen.rs | 100 ++++++++++++++++- src/server/listen_unix_tests.rs | 188 ++++++++++++++++++++++++++++++++ 3 files changed, 292 insertions(+), 4 deletions(-) create mode 100644 src/server/listen_unix_tests.rs diff --git a/docs/server-features.md b/docs/server-features.md index 48e012ab0..4e42ac08d 100644 --- a/docs/server-features.md +++ b/docs/server-features.md @@ -423,6 +423,14 @@ when migrating an existing llama-server command. TLS is enabled by supplying both `--ssl-cert-file` and `--ssl-key-file`. A `--host` ending in `.sock` starts a Unix-domain-socket listener, and `--api-prefix` nests all routes below a path. +The server does not remove its socket file when it stops, so a start on the same +path replaces a socket nobody listens on any more. It does not replace a socket +another server is still listening on, a socket it cannot probe (no permission to +connect, or a socket of another type), or an entry at that path that is not a +socket (a regular file, a symlink): the start fails and the entry is left as it +is. On macOS a listener whose accept queue is completely full answers like a +socket nobody listens on and is not recognised as in use. + The public set is matched literally against the request path as the client sent it, prefix included. With `--api-prefix /llama` and keys enabled, `/llama/health` and `/llama/v1/health` are therefore not public and need a diff --git a/src/server/listen.rs b/src/server/listen.rs index 3ecd5299d..e4009a307 100644 --- a/src/server/listen.rs +++ b/src/server/listen.rs @@ -176,12 +176,56 @@ fn resolve_socket_addr(host: &str, port: u16) -> Result { .ok_or_else(|| anyhow::anyhow!("--host {host}: resolved to no addresses")) } -/// Bind a Unix domain socket, clearing a stale path first. +/// Bind a Unix domain socket, clearing a stale socket first. +/// +/// A socket file outlives the process that bound it, and the server leaves its +/// own behind on shutdown, so a socket nobody listens on is removed and the +/// path bound again. Everything else is left alone, with an error instead of a +/// bind: an entry that is not a socket (a regular file, a symlink), a socket +/// that still has a listener, which would otherwise keep running with its path +/// taken away, and a socket whose state cannot be determined. +/// +/// The check and the removal are two steps. Two servers started on one stale +/// path at the same moment can both pass the check; the later bind then takes +/// the path, as it always did. #[cfg(unix)] fn bind_unix(path: &Path) -> Result { - if path.exists() { - std::fs::remove_file(path) - .with_context(|| format!("failed to remove stale socket: {}", path.display()))?; + use std::os::unix::fs::FileTypeExt; + + match std::fs::symlink_metadata(path) { + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => { + return Err(error) + .with_context(|| format!("failed to inspect socket path: {}", path.display())); + } + Ok(entry) if !entry.file_type().is_socket() => bail!( + "--host {}: the path exists and is not a socket; it is left as it is. Remove it or \ + choose another path", + path.display() + ), + Ok(_) => { + match probe_unix_socket(path) { + UnixSocketProbe::Stale => {} + UnixSocketProbe::InUse => bail!( + "--host {}: the socket is in use by a running listener; it is left as it is. \ + Stop that server or choose another path", + path.display() + ), + UnixSocketProbe::Unknown(error) => bail!( + "--host {}: cannot tell whether the socket is still in use ({error}); it is \ + left as it is. Remove it or choose another path", + path.display() + ), + } + match std::fs::remove_file(path) { + Err(error) if error.kind() != io::ErrorKind::NotFound => { + return Err(error).with_context(|| { + format!("failed to remove stale socket: {}", path.display()) + }); + } + _ => {} + } + } } if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { std::fs::create_dir_all(parent) @@ -191,6 +235,50 @@ fn bind_unix(path: &Path) -> Result { .with_context(|| format!("failed to bind Unix socket: {}", path.display())) } +/// What one connection attempt says about the socket at a path. +#[cfg(unix)] +enum UnixSocketProbe { + /// The kernel refused the connection: the socket's owner is gone. + Stale, + /// The connection was accepted or queued, or the accept queue is full. + InUse, + /// Neither could be established (no permission to connect, a socket of + /// another type, ...). + Unknown(io::Error), +} + +/// Ask the kernel whether anything still listens on the socket at `path`. +/// +/// One non-blocking connection attempt. Only "connection refused" (and a path +/// that vanished meanwhile) reads as nobody there: that is what the kernel +/// answers for a socket whose owner is gone. Non-blocking, because a blocking +/// connect to a full accept queue waits for the listener to accept; Linux +/// answers "would block" instead, which reads as in use. Any other error +/// leaves the question open, and the caller does not take the path on a guess. +/// +/// macOS answers "connection refused" for a full accept queue too, so a live +/// listener that is saturated at that moment cannot be told from a stale +/// socket there. A socket that is bound but not listening yet reads as stale +/// on both systems. +/// +/// Used by: [`bind_unix`]. +#[cfg(unix)] +fn probe_unix_socket(path: &Path) -> UnixSocketProbe { + let probe = || -> io::Result<()> { + let socket = socket2::Socket::new(socket2::Domain::UNIX, socket2::Type::STREAM, None)?; + socket.set_nonblocking(true)?; + socket.connect(&socket2::SockAddr::unix(path)?) + }; + match probe() { + Ok(()) => UnixSocketProbe::InUse, + Err(error) => match error.kind() { + io::ErrorKind::ConnectionRefused | io::ErrorKind::NotFound => UnixSocketProbe::Stale, + io::ErrorKind::WouldBlock => UnixSocketProbe::InUse, + _ => UnixSocketProbe::Unknown(error), + }, + } +} + async fn accept_tcp(listener: TcpListener, app: Router, options: ServeOptions) -> Result<()> { let acceptor = options.tls.map(TlsAcceptor::from); loop { @@ -327,3 +415,7 @@ where #[cfg(test)] #[path = "listen_tests.rs"] mod listen_tests; + +#[cfg(all(test, unix))] +#[path = "listen_unix_tests.rs"] +mod listen_unix_tests; diff --git a/src/server/listen_unix_tests.rs b/src/server/listen_unix_tests.rs new file mode 100644 index 000000000..1615495e4 --- /dev/null +++ b/src/server/listen_unix_tests.rs @@ -0,0 +1,188 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! What `bind_unix` replaces at its path, and what it leaves alone. + +use std::os::unix::fs::{FileTypeExt, MetadataExt, symlink}; +use std::os::unix::net::{UnixDatagram, UnixListener as StdUnixListener, UnixStream}; +use std::path::Path; + +use super::bind_unix; + +fn directory() -> tempfile::TempDir { + // Keep paths below sun_path's platform limit, including on macOS. + tempfile::Builder::new() + .prefix("mlxcel-bind-") + .tempdir_in("/tmp") + .unwrap() +} + +fn identity(path: &Path) -> (u64, u64, u32) { + let metadata = std::fs::symlink_metadata(path).unwrap(); + (metadata.dev(), metadata.ino(), metadata.mode()) +} + +/// `bind_unix` must refuse `path` with `reason` in the error and leave the +/// entry exactly as it was. +fn assert_left_alone(path: &Path, reason: &str) { + let before = identity(path); + let error = bind_unix(path).expect_err("the entry must not be replaced"); + assert!(error.to_string().contains(reason), "{error}"); + assert_eq!(identity(path), before); +} + +fn is_socket(path: &Path) -> bool { + std::fs::symlink_metadata(path) + .unwrap() + .file_type() + .is_socket() +} + +#[tokio::test] +async fn unix_bind_replaces_the_socket_an_earlier_run_left_behind() { + // The server does not remove its socket on shutdown, so the next start on + // the same path has to. + let directory = directory(); + let path = directory.path().join("server.sock"); + drop(bind_unix(&path).unwrap()); + assert!( + is_socket(&path), + "a dropped listener leaves its socket file" + ); + + let listener = bind_unix(&path).expect("a restart on the same path"); + let _client = UnixStream::connect(&path).unwrap(); + let (_accepted, _) = listener.accept().await.unwrap(); +} + +#[tokio::test] +async fn unix_bind_replaces_a_socket_whose_owner_is_gone() { + let directory = directory(); + let path = directory.path().join("stale.sock"); + drop(StdUnixListener::bind(&path).unwrap()); + assert!(is_socket(&path)); + + // Reachability shows the replacement; an inode number may be reused. + let listener = bind_unix(&path).unwrap(); + let _client = UnixStream::connect(&path).unwrap(); + let (_accepted, _) = listener.accept().await.unwrap(); +} + +#[tokio::test] +async fn unix_bind_leaves_a_live_listener_its_path() { + let directory = directory(); + let path = directory.path().join("live.sock"); + let owner = StdUnixListener::bind(&path).unwrap(); + owner.set_nonblocking(true).unwrap(); + + assert_left_alone(&path, "in use by a running listener"); + + // The probe's own connection, then a client's: the owner still gets both. + let _probe = owner.accept().expect("the probe reached the owner"); + let _client = UnixStream::connect(&path).unwrap(); + owner.accept().expect("the owner still owns the path"); +} + +// Linux answers "would block" for a full accept queue. macOS answers +// "connection refused", the same as for a stale socket, so a saturated +// listener cannot be recognised there and this case is Linux-only. +#[cfg(target_os = "linux")] +#[tokio::test] +async fn unix_bind_leaves_a_listener_with_a_full_backlog_its_path() { + let directory = directory(); + let path = directory.path().join("busy.sock"); + let address = socket2::SockAddr::unix(&path).unwrap(); + let stream = || socket2::Socket::new(socket2::Domain::UNIX, socket2::Type::STREAM, None); + let owner = stream().unwrap(); + owner.bind(&address).unwrap(); + owner.listen(1).unwrap(); + // Fill the accept queue: nothing is accepted while these stay open. + let mut pending = Vec::new(); + for _ in 0..64 { + let socket = stream().unwrap(); + socket.set_nonblocking(true).unwrap(); + match socket.connect(&address) { + Ok(()) => pending.push(socket), + Err(_) => break, + } + } + assert!(pending.len() < 64, "the backlog never filled"); + + assert_left_alone(&path, "in use by a running listener"); + drop(owner); +} + +#[tokio::test] +async fn unix_bind_leaves_a_regular_file() { + let directory = directory(); + let path = directory.path().join("file.sock"); + std::fs::write(&path, b"sentinel").unwrap(); + assert_left_alone(&path, "is not a socket"); + assert_eq!(std::fs::read(path).unwrap(), b"sentinel"); +} + +#[tokio::test] +async fn unix_bind_leaves_both_symlink_kinds() { + let directory = directory(); + let target = directory.path().join("target"); + std::fs::write(&target, b"sentinel").unwrap(); + for (name, target) in [ + ("live.sock", target.clone()), + ("dangling.sock", directory.path().join("absent")), + ] { + let path = directory.path().join(name); + symlink(&target, &path).unwrap(); + assert_left_alone(&path, "is not a socket"); + assert_eq!(std::fs::read_link(path).unwrap(), target); + } + assert_eq!(std::fs::read(target).unwrap(), b"sentinel"); +} + +#[tokio::test] +async fn unix_bind_leaves_a_bound_datagram_socket() { + // Another program's socket of another type: a stream connect is not + // refused with "connection refused", so it is not taken for stale. + let directory = directory(); + let path = directory.path().join("datagram.sock"); + let owner = UnixDatagram::bind(&path).unwrap(); + assert_left_alone(&path, "cannot tell whether the socket is still in use"); + drop(owner); +} + +#[tokio::test] +async fn unix_bind_leaves_a_socket_it_may_not_connect_to() { + use std::os::unix::fs::PermissionsExt; + + // A leftover socket this user has no write permission on: the probe is + // denied, so nothing is known about its owner and it is not removed. + let directory = directory(); + let path = directory.path().join("denied.sock"); + drop(StdUnixListener::bind(&path).unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap(); + match UnixStream::connect(&path) { + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {} + // A privileged user is not denied; there is nothing to test then. + _ => return, + } + assert_left_alone(&path, "cannot tell whether the socket is still in use"); +} + +#[tokio::test] +async fn unix_bind_creates_an_unused_nested_path() { + let directory = directory(); + let path = directory.path().join("a/b/new.sock"); + let listener = bind_unix(&path).unwrap(); + let _client = UnixStream::connect(&path).unwrap(); + let (_accepted, _) = listener.accept().await.unwrap(); +} From df892789a1aff57c5c7f437e60b23f7f8d0f902c Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Sat, 14 Nov 2026 15:31:46 +0900 Subject: [PATCH 2/2] fix(server): treat an in-progress Unix probe as in use The socket probe now reads EINPROGRESS as a listener that answered, so a connection still being set up never makes `bind_unix` remove a live socket. Neither Linux nor macOS reports it for a Unix stream connect today; the case is there so the probe stays conservative. Adds a test that a directory at the socket path is refused and left intact. Validated on macOS (M3 Ultra): the 9 Unix bind tests and the listen tests pass, `cargo clippy --lib --tests -D warnings` is clean, and with a real mlxcel-server a second start on a live socket exits 1 with the in-use error while the first keeps answering `/health`; a restart on the leftover socket after SIGTERM succeeds. Refs #3020 --- src/server/listen.rs | 4 ++++ src/server/listen_unix_tests.rs | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/src/server/listen.rs b/src/server/listen.rs index e4009a307..77206a6f3 100644 --- a/src/server/listen.rs +++ b/src/server/listen.rs @@ -274,6 +274,10 @@ fn probe_unix_socket(path: &Path) -> UnixSocketProbe { Err(error) => match error.kind() { io::ErrorKind::ConnectionRefused | io::ErrorKind::NotFound => UnixSocketProbe::Stale, io::ErrorKind::WouldBlock => UnixSocketProbe::InUse, + // A connection still being set up has reached a listener. Neither + // Linux nor macOS reports this for a Unix stream socket today, but + // it must never read as stale. + _ if error.raw_os_error() == Some(libc::EINPROGRESS) => UnixSocketProbe::InUse, _ => UnixSocketProbe::Unknown(error), }, } diff --git a/src/server/listen_unix_tests.rs b/src/server/listen_unix_tests.rs index 1615495e4..dafa70783 100644 --- a/src/server/listen_unix_tests.rs +++ b/src/server/listen_unix_tests.rs @@ -132,6 +132,16 @@ async fn unix_bind_leaves_a_regular_file() { assert_eq!(std::fs::read(path).unwrap(), b"sentinel"); } +#[tokio::test] +async fn unix_bind_leaves_a_directory() { + let directory = directory(); + let path = directory.path().join("dir.sock"); + std::fs::create_dir(&path).unwrap(); + std::fs::write(path.join("inside"), b"sentinel").unwrap(); + assert_left_alone(&path, "is not a socket"); + assert_eq!(std::fs::read(path.join("inside")).unwrap(), b"sentinel"); +} + #[tokio::test] async fn unix_bind_leaves_both_symlink_kinds() { let directory = directory();