namespace-util: introduce pidref_in_same_namespace()

This commit is contained in:
Mike Yuan
2025-01-04 17:08:01 +01:00
parent a33f691374
commit 92b8e5e72f
4 changed files with 42 additions and 30 deletions
+29 -24
View File
@@ -310,6 +310,35 @@ int namespace_is_init(NamespaceType type) {
return st.st_ino == namespace_info[type].root_inode;
}
int pidref_in_same_namespace(PidRef *pid1, PidRef *pid2, NamespaceType type) {
_cleanup_close_ int ns1 = -EBADF, ns2 = -EBADF;
/* Accepts NULL to indicate our own process */
assert(!pid1 || pidref_is_set(pid1));
assert(!pid2 || pidref_is_set(pid2));
assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
if (pidref_equal(pid1, pid2))
return true;
if (!pid1)
ns1 = namespace_open_by_type(type);
else
ns1 = pidref_namespace_open_by_type(pid1, type);
if (ns1 < 0)
return ns1;
if (!pid2)
ns2 = namespace_open_by_type(type);
else
ns2 = pidref_namespace_open_by_type(pid2, type);
if (ns2 < 0)
return ns2;
return fd_inode_same(ns1, ns2);
}
int namespace_get_leader(pid_t pid, NamespaceType type, pid_t *ret) {
int r;
@@ -506,30 +535,6 @@ int netns_acquire(void) {
return TAKE_FD(netns_fd);
}
int in_same_namespace(pid_t pid1, pid_t pid2, NamespaceType type) {
const char *ns_path;
struct stat ns_st1, ns_st2;
if (pid1 == 0)
pid1 = getpid_cached();
if (pid2 == 0)
pid2 = getpid_cached();
if (pid1 == pid2)
return 1;
ns_path = pid_namespace_path(pid1, type);
if (stat(ns_path, &ns_st1) < 0)
return -errno;
ns_path = pid_namespace_path(pid2, type);
if (stat(ns_path, &ns_st2) < 0)
return -errno;
return stat_inode_same(&ns_st1, &ns_st2);
}
int parse_userns_uid_range(const char *s, uid_t *ret_uid_shift, uid_t *ret_uid_range) {
_cleanup_free_ char *buffer = NULL;
const char *range, *shift;
+9 -2
View File
@@ -53,6 +53,15 @@ int is_our_namespace(int fd, NamespaceType type);
int namespace_is_init(NamespaceType type);
int pidref_in_same_namespace(PidRef *pid1, PidRef *pid2, NamespaceType type);
static inline int in_same_namespace(pid_t pid1, pid_t pid2, NamespaceType type) {
assert(pid1 >= 0);
assert(pid2 >= 0);
return pidref_in_same_namespace(pid1 == 0 ? NULL : &PIDREF_MAKE_FROM_PID(pid1),
pid2 == 0 ? NULL : &PIDREF_MAKE_FROM_PID(pid2),
type);
}
int namespace_get_leader(pid_t pid, NamespaceType type, pid_t *ret);
int detach_mount_namespace(void);
@@ -79,8 +88,6 @@ int userns_acquire(const char *uid_map, const char *gid_map);
int netns_acquire(void);
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 is_idmapping_supported(const char *path);