]> git.ipfire.org Git - thirdparty/lxc.git/commitdiff
utils: improve switch_to_ns() 2906/head
authorChristian Brauner <christian.brauner@ubuntu.com>
Tue, 12 Mar 2019 16:51:50 +0000 (17:51 +0100)
committerChristian Brauner <christian.brauner@ubuntu.com>
Thu, 9 May 2019 10:20:14 +0000 (12:20 +0200)
Signed-off-by: Christian Brauner <christian.brauner@ubuntu.com>
src/lxc/macro.h
src/lxc/utils.c

index 7626c5d76b338743e4e16e4db36ac720efba72dd..042e239a71a3dfd708916f55e295ff5a87483dd4 100644 (file)
 #define LXC_LINELEN 4096
 #define LXC_IDMAPLEN 4096
 #define LXC_MAX_BUFFER 4096
+#define LXC_NAMESPACE_NAME_MAX 256
 
 /* /proc/       =    6
  *                +
index ea081c566c842e67036f1f1855c17181c720aea4..f20c6eeac5f41d0d9d24c33d86367077b7d85dcf 100644 (file)
@@ -693,15 +693,18 @@ 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)
+       ret = snprintf(nspath, sizeof(nspath), "/proc/%d/ns/%s", pid, ns);
+       if (ret < 0 || ret >= sizeof(nspath))
                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;
@@ -709,12 +712,11 @@ 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);
+               SYSERROR("Failed to set process %d to \"%s\" of %d.", pid, ns,
+                        fd);
                return false;
        }
 
-       close(fd);
        return true;
 }