diff --git a/src/core/daemon.c b/src/core/daemon.c index 266019cdb..d9dc54ab0 100644 --- a/src/core/daemon.c +++ b/src/core/daemon.c @@ -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, ¤t) == 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, ¤t) == 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) { diff --git a/tests/unit/test_config.c b/tests/unit/test_config.c index 4d2c02e48..7b54b7f5c 100644 --- a/tests/unit/test_config.c +++ b/tests/unit/test_config.c @@ -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);