[lxc-devel] [lxc/master] utils: improve switch_to_ns()

brauner on Github lxc-bot at linuxcontainers.org
Tue Mar 12 20:00:45 UTC 2019


A non-text attachment was scrubbed...
Name: not available
Type: text/x-mailbox
Size: 364 bytes
Desc: not available
URL: <http://lists.linuxcontainers.org/pipermail/lxc-devel/attachments/20190312/40a2f6e2/attachment.bin>
-------------- next part --------------
From b6b1a2aba289fb5ed579f77143b8f1a3ab623124 Mon Sep 17 00:00:00 2001
From: Christian Brauner <christian.brauner at ubuntu.com>
Date: Tue, 12 Mar 2019 17:51:50 +0100
Subject: [PATCH] utils: improve switch_to_ns()

Signed-off-by: Christian Brauner <christian.brauner at ubuntu.com>
---
 src/lxc/macro.h |  1 +
 src/lxc/utils.c | 10 +++++-----
 2 files changed, 6 insertions(+), 5 deletions(-)

diff --git a/src/lxc/macro.h b/src/lxc/macro.h
index 6e07516f20..68d4e440b3 100644
--- a/src/lxc/macro.h
+++ b/src/lxc/macro.h
@@ -149,6 +149,7 @@
 #define LXC_LINELEN 4096
 #define LXC_IDMAPLEN 4096
 #define LXC_MAX_BUFFER 4096
+#define LXC_NAMESPACE_NAME_MAX 256
 
 /* /proc/       =    6
  *                +
diff --git a/src/lxc/utils.c b/src/lxc/utils.c
index 0262c7acd4..a55889c7a0 100644
--- a/src/lxc/utils.c
+++ b/src/lxc/utils.c
@@ -693,15 +693,17 @@ int detect_shared_rootfs(void)
 
 bool switch_to_ns(pid_t pid, const char *ns)
 {
-	int fd, ret;
-	char nspath[PATH_MAX];
+	__do_close_prot_errno int fd = -EBADF;
+	int ret;
+	char nspath[STRLITERALLEN("/proc//ns/") + INTTYPE_TO_STRLEN(pid_t) +
+		    LXC_NAMESPACE_NAME_MAX];
 
 	/* Switch to new ns */
 	ret = snprintf(nspath, PATH_MAX, "/proc/%d/ns/%s", pid, ns);
 	if (ret < 0 || ret >= PATH_MAX)
 		return false;
 
-	fd = open(nspath, O_RDONLY);
+	fd = open(nspath, O_RDONLY | O_CLOEXEC);
 	if (fd < 0) {
 		SYSERROR("Failed to open \"%s\"", nspath);
 		return false;
@@ -710,11 +712,9 @@ bool switch_to_ns(pid_t pid, const char *ns)
 	ret = setns(fd, 0);
 	if (ret) {
 		SYSERROR("Failed to set process %d to \"%s\" of %d.", pid, ns, fd);
-		close(fd);
 		return false;
 	}
 
-	close(fd);
 	return true;
 }
 


More information about the lxc-devel mailing list