Compare commits

...

2 Commits

Author SHA1 Message Date
Luca Boccassi c9a29d33aa
Merge a2bc7476fb into b7eefa1996 2024-11-21 14:32:25 +09:00
Luca Boccassi a2bc7476fb detect-virt: check the inode number of the pid namespace
The indoe number of root pid namespace is hardcoded in the kernel to
0xEFFFFFFC since 3.8, so check the inode number of our pid namespace
if all else fails. If it's not 0xEFFFFFFC then we are in a pid
namespace, hence a container environment.

Fixes https://github.com/systemd/systemd/issues/35249
2024-11-21 01:18:34 +00:00
2 changed files with 19 additions and 0 deletions

View File

@ -674,6 +674,7 @@ static Virtualization detect_container_files(void) {
Virtualization detect_container(void) { Virtualization detect_container(void) {
static thread_local Virtualization cached_found = _VIRTUALIZATION_INVALID; static thread_local Virtualization cached_found = _VIRTUALIZATION_INVALID;
_cleanup_free_ char *m = NULL, *o = NULL, *p = NULL; _cleanup_free_ char *m = NULL, *o = NULL, *p = NULL;
_cleanup_close_ int pidns_fd = -EBADF;
const char *e = NULL; const char *e = NULL;
Virtualization v; Virtualization v;
int r; int r;
@ -796,6 +797,22 @@ check_files:
if (r < 0) if (r < 0)
log_debug_errno(r, "Failed to detect cgroup namespace: %m"); log_debug_errno(r, "Failed to detect cgroup namespace: %m");
/* Finally, the root pid namespace has an hardcoded inode number of 0xEFFFFFFC since kernel 3.8, so
* if all else fails we can check the inode number of our pid namespace and compare it. */
pidns_fd = namespace_open_by_type(NAMESPACE_PID);
if (pidns_fd < 0)
log_debug_errno(pidns_fd, "Failed to open PID namespace, ignoring: %m");
else {
struct stat st;
if (fstat(pidns_fd, &st) < 0)
log_debug_errno(errno, "Failed to fstat pid namespace fd, ignoring: %m");
else if ((uint64_t) st.st_ino != 0xEFFFFFFC) {
v = VIRTUALIZATION_CONTAINER_OTHER;
goto finish;
}
}
/* If none of that worked, give up, assume no container manager. */ /* If none of that worked, give up, assume no container manager. */
v = VIRTUALIZATION_NONE; v = VIRTUALIZATION_NONE;
goto finish; goto finish;

View File

@ -5,3 +5,5 @@ set -o pipefail
SYSTEMD_IN_CHROOT=1 systemd-detect-virt --chroot SYSTEMD_IN_CHROOT=1 systemd-detect-virt --chroot
(! SYSTEMD_IN_CHROOT=0 systemd-detect-virt --chroot) (! SYSTEMD_IN_CHROOT=0 systemd-detect-virt --chroot)
unshare --mount-proc --fork --user --pid systemd-detect-virt --container