From b0881aae6d91845821b2732f3fc8890e3d9ec4d2 Mon Sep 17 00:00:00 2001 From: Stefano Brivio Date: Sun, 21 May 2023 14:47:07 +0200 Subject: util, conf: Add and use ns_is_init() helper We'll need this in isolate_initial(). While at it, don't rely on BUFSIZ: the earlier issue we had with musl reminded me it's not a magic "everything will fit" value. Size the read buffer to what we actually need from uid_map, and check for the final newline too, because uid_map is organised in lines. Signed-off-by: Stefano Brivio --- util.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'util.c') diff --git a/util.c b/util.c index c3e3471..1d00404 100644 --- a/util.c +++ b/util.c @@ -390,6 +390,31 @@ int ns_enter(const struct ctx *c) return 0; } +/** + * ns_is_init() - Is the caller running in the "init" user namespace? + * + * Return: true if caller is in init, false otherwise, won't return on failure + */ +bool ns_is_init(void) +{ + const char root_uid_map[] = " 0 0 4294967295\n"; + char buf[sizeof(root_uid_map)] = { 0 }; + bool ret = true; + int fd; + + if ((fd = open("/proc/self/uid_map", O_RDONLY | O_CLOEXEC)) < 0) { + die("Can't determine if we're in init namespace: %s", + strerror(errno)); + } + + if (read(fd, buf, sizeof(root_uid_map)) != sizeof(root_uid_map) - 1 || + strncmp(buf, root_uid_map, sizeof(root_uid_map))) + ret = false; + + close(fd); + return ret; +} + /** * pid_file() - Write PID to file, if requested to do so, and close it * @fd: Open PID file descriptor, closed on exit, -1 to skip writing it -- cgit v1.2.3