]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
namespace-util: add new helper is_our_namespace()
authorLennart Poettering <lennart@poettering.net>
Wed, 6 Dec 2023 10:35:04 +0000 (11:35 +0100)
committerLennart Poettering <lennart@poettering.net>
Sat, 6 Apr 2024 14:08:23 +0000 (16:08 +0200)
src/basic/namespace-util.c
src/basic/namespace-util.h

index 0e54a1e2358a2b5dd84198a856736ab08fd84e96..5b4e43f9210ef90f488950a61edd71611fb34419 100644 (file)
@@ -34,6 +34,14 @@ const struct namespace_info namespace_info[] = {
 
 #define pid_namespace_path(pid, type) procfs_file_alloca(pid, namespace_info[type].proc_path)
 
+static NamespaceType clone_flag_to_namespace_type(unsigned long clone_flag) {
+        for (NamespaceType t = 0; t < _NAMESPACE_TYPE_MAX; t++)
+                if (((namespace_info[t].clone_flag ^ clone_flag) & (CLONE_NEWCGROUP|CLONE_NEWIPC|CLONE_NEWNET|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUSER|CLONE_NEWUTS|CLONE_NEWTIME)) == 0)
+                        return t;
+
+        return _NAMESPACE_TYPE_INVALID;
+}
+
 int namespace_open(
                 pid_t pid,
                 int *ret_pidns_fd,
@@ -442,3 +450,34 @@ int namespace_open_by_type(NamespaceType type) {
 
         return fd;
 }
+
+int is_our_namespace(int fd, NamespaceType request_type) {
+        int clone_flag;
+
+        assert(fd >= 0);
+
+        clone_flag = ioctl(fd, NS_GET_NSTYPE);
+        if (clone_flag < 0)
+                return -errno;
+
+        NamespaceType found_type = clone_flag_to_namespace_type(clone_flag);
+        if (found_type < 0)
+                return -EBADF; /* Uh? Unknown namespace type? */
+
+        if (request_type >= 0 && request_type != found_type) /* It's a namespace, but not of the right type? */
+                return -EUCLEAN;
+
+        struct stat st_fd, st_ours;
+        if (fstat(fd, &st_fd) < 0)
+                return -errno;
+
+        const char *p = pid_namespace_path(0, found_type);
+        if (stat(p, &st_ours) < 0) {
+                if (errno == ENOENT)
+                        return proc_mounted() == 0 ? -ENOSYS : -ENOENT;
+
+                return -errno;
+        }
+
+        return stat_inode_same(&st_ours, &st_fd);
+}
index 972ef05d539d7e2c84e492f3ffd476501eb94d6e..545952a5d1093f6067846a1a058bd6c800076cb7 100644 (file)
@@ -62,3 +62,5 @@ int in_same_namespace(pid_t pid1, pid_t pid2, NamespaceType type);
 int parse_userns_uid_range(const char *s, uid_t *ret_uid_shift, uid_t *ret_uid_range);
 
 int namespace_open_by_type(NamespaceType type);
+
+int is_our_namespace(int fd, NamespaceType type);