Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/server-features.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
104 changes: 100 additions & 4 deletions src/server/listen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,12 +176,56 @@ fn resolve_socket_addr(host: &str, port: u16) -> Result<SocketAddr> {
.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<UnixListener> {
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)
Expand All @@ -191,6 +235,54 @@ fn bind_unix(path: &Path) -> Result<UnixListener> {
.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,
// 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),
},
}
}

async fn accept_tcp(listener: TcpListener, app: Router, options: ServeOptions) -> Result<()> {
let acceptor = options.tls.map(TlsAcceptor::from);
loop {
Expand Down Expand Up @@ -327,3 +419,7 @@ where
#[cfg(test)]
#[path = "listen_tests.rs"]
mod listen_tests;

#[cfg(all(test, unix))]
#[path = "listen_unix_tests.rs"]
mod listen_unix_tests;
198 changes: 198 additions & 0 deletions src/server/listen_unix_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
// 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_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();
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();
}
Loading