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
22 changes: 21 additions & 1 deletion src/core/daemon.c
Original file line number Diff line number Diff line change
Expand Up @@ -473,15 +473,35 @@ int daemon_status(const char *pid_file) {
struct stat held, current;
bool owns_path = fstat(owned_pid_fd, &held) == 0 &&
lstat(file_path, &current) == 0 &&
S_ISREG(current.st_mode) && current.st_nlink == 1 &&
S_ISREG(current.st_mode) &&
held.st_dev == current.st_dev && held.st_ino == current.st_ino;
if (owns_path) {
pthread_mutex_unlock(&owned_pid_mutex);
return 1;
}
// A second open could resolve to our locked inode after the check and
// release its process-scoped lock when closed. Fail closed instead.
pthread_mutex_unlock(&owned_pid_mutex);
return -1;
}
pthread_mutex_unlock(&owned_pid_mutex);

// Reject unsafe paths (including hard-linked PID files) before opening.
// Opening and later closing another descriptor for the same inode in this
// process can release our existing process-scoped record lock.
struct stat current;
if (lstat(file_path, &current) == 0) {
if (!S_ISREG(current.st_mode) || current.st_nlink != 1) {
log_error("Unsafe PID file path %s: expected single-link regular file", file_path);
return -1;
}
} else if (errno == ENOENT) {
return 0;
} else {
log_error("Failed to stat PID file %s: %s", file_path, strerror(errno));
return -1;
}

// Open read-only so status checks can work across users (e.g., 0644 PID files)
int fd = open(file_path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK);
if (fd < 0) {
Expand Down
6 changes: 6 additions & 0 deletions tests/unit/test_config.c
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,12 @@ void test_daemon_status_preserves_owned_pid_lock(void) {
int fd = write_pid_file(path);
TEST_ASSERT_TRUE(fd >= 0);
TEST_ASSERT_EQUAL_INT(1, daemon_status(path));
char alias[MAX_PATH_LENGTH];
snprintf(alias, sizeof(alias), "%s/alias.pid", directory);
TEST_ASSERT_EQUAL_INT(0, link(path, alias));
TEST_ASSERT_EQUAL_INT(1, daemon_status(path));
TEST_ASSERT_EQUAL_INT(1, daemon_status(alias));
TEST_ASSERT_EQUAL_INT(0, unlink(alias));

pid_t child = fork();
TEST_ASSERT_TRUE(child >= 0);
Expand Down
Loading