]> git.proxmox.com Git - mirror_lxc.git/blobdiff - src/lxc/attach.c
spelling: potentially
[mirror_lxc.git] / src / lxc / attach.c
index da8bcda0076ea8e68c01daa954837d2ab6a89ccf..117e3778fab182de29b24cf7c5754a149d973649 100644 (file)
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#define _GNU_SOURCE
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE 1
+#endif
 #include <errno.h>
 #include <fcntl.h>
-#include <termios.h>
 #include <grp.h>
+#include <linux/unistd.h>
 #include <pwd.h>
+#include <pthread.h>
 #include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
-#include <linux/unistd.h>
 #include <sys/mount.h>
 #include <sys/param.h>
 #include <sys/prctl.h>
 #include <sys/socket.h>
 #include <sys/syscall.h>
 #include <sys/wait.h>
+#include <termios.h>
+#include <unistd.h>
 
 #include <lxc/lxccontainer.h>
 
-#ifndef HAVE_DECL_PR_CAPBSET_DROP
-#define PR_CAPBSET_DROP 24
-#endif
-
-#ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
-#define PR_SET_NO_NEW_PRIVS 38
-#endif
-
-#ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
-#define PR_GET_NO_NEW_PRIVS 39
-#endif
-
 #include "af_unix.h"
 #include "attach.h"
 #include "caps.h"
 #include "lsm/lsm.h"
 #include "lxclock.h"
 #include "lxcseccomp.h"
+#include "macro.h"
 #include "mainloop.h"
 #include "namespace.h"
+#include "raw_syscalls.h"
+#include "syscall_wrappers.h"
 #include "terminal.h"
 #include "utils.h"
 
 #include <sys/personality.h>
 #endif
 
-#ifndef SOCK_CLOEXEC
-#define SOCK_CLOEXEC 02000000
-#endif
-
-#ifndef MS_REC
-#define MS_REC 16384
-#endif
-
-#ifndef MS_SLAVE
-#define MS_SLAVE (1 << 19)
-#endif
-
 lxc_log_define(attach, lxc);
 
-/* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
-#define __PROC_STATUS_LEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
+/* Define default options if no options are supplied by the user. */
+static lxc_attach_options_t attach_static_default_options = LXC_ATTACH_OPTIONS_DEFAULT;
+
 static struct lxc_proc_context_info *lxc_proc_get_context_info(pid_t pid)
 {
        int ret;
        bool found;
        FILE *proc_file;
-       char proc_fn[__PROC_STATUS_LEN];
+       char proc_fn[LXC_PROC_STATUS_LEN];
        size_t line_bufsz = 0;
        char *line = NULL;
        struct lxc_proc_context_info *info = NULL;
 
        /* Read capabilities. */
-       ret = snprintf(proc_fn, __PROC_STATUS_LEN, "/proc/%d/status", pid);
-       if (ret < 0 || ret >= __PROC_STATUS_LEN)
+       ret = snprintf(proc_fn, LXC_PROC_STATUS_LEN, "/proc/%d/status", pid);
+       if (ret < 0 || ret >= LXC_PROC_STATUS_LEN)
                goto on_error;
 
        proc_file = fopen(proc_fn, "r");
        if (!proc_file) {
-               SYSERROR("Could not open %s.", proc_fn);
+               SYSERROR("Could not open %s", proc_fn);
                goto on_error;
        }
 
        info = calloc(1, sizeof(*info));
        if (!info) {
-               SYSERROR("Could not allocate memory.");
+               SYSERROR("Could not allocate memory");
                fclose(proc_file);
                return NULL;
        }
 
        found = false;
+
        while (getline(&line, &line_bufsz, proc_file) != -1) {
                ret = sscanf(line, "CapBnd: %llx", &info->capability_mask);
                if (ret != EOF && ret == 1) {
@@ -132,9 +116,8 @@ static struct lxc_proc_context_info *lxc_proc_get_context_info(pid_t pid)
        fclose(proc_file);
 
        if (!found) {
-               SYSERROR("Could not read capability bounding set from %s.",
-                        proc_fn);
-               errno = ENOENT;
+               ERROR("Could not read capability bounding set from %s",
+                     proc_fn);
                goto on_error;
        }
 
@@ -156,6 +139,7 @@ static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info *ctx)
        for (i = 0; i < LXC_NS_MAX; i++) {
                if (ctx->ns_fd[i] < 0)
                        continue;
+
                close(ctx->ns_fd[i]);
                ctx->ns_fd[i] = -EBADF;
        }
@@ -189,6 +173,7 @@ static void lxc_proc_put_context_info(struct lxc_proc_context_info *ctx)
 static int in_same_namespace(pid_t pid1, pid_t pid2, const char *ns)
 {
        int ns_fd1 = -1, ns_fd2 = -1, ret = -1;
+       int saved_errno;
        struct stat ns_st1, ns_st2;
 
        ns_fd1 = lxc_preserve_ns(pid1, ns);
@@ -215,21 +200,25 @@ static int in_same_namespace(pid_t pid1, pid_t pid2, const char *ns)
                goto out;
 
        /* processes are in the same namespace */
-       ret = -EINVAL;
-       if ((ns_st1.st_dev == ns_st2.st_dev ) && (ns_st1.st_ino == ns_st2.st_ino))
+       if ((ns_st1.st_dev == ns_st2.st_dev ) && (ns_st1.st_ino == ns_st2.st_ino)) {
+               ret = -EINVAL;
                goto out;
+       }
 
        /* processes are in different namespaces */
        ret = ns_fd2;
        ns_fd2 = -1;
 
 out:
+       saved_errno = errno;
 
        if (ns_fd1 >= 0)
                close(ns_fd1);
+
        if (ns_fd2 >= 0)
                close(ns_fd2);
 
+       errno = saved_errno;
        return ret;
 }
 
@@ -244,7 +233,7 @@ static int lxc_attach_to_ns(pid_t pid, struct lxc_proc_context_info *ctx)
                ret = setns(ctx->ns_fd[i], ns_info[i].clone_flag);
                if (ret < 0) {
                        SYSERROR("Failed to attach to %s namespace of %d",
-                                ns_info[i].proc_name, pid);
+                                ns_info[i].proc_name, pid);
                        return -1;
                }
 
@@ -260,13 +249,13 @@ static int lxc_attach_remount_sys_proc(void)
 
        ret = unshare(CLONE_NEWNS);
        if (ret < 0) {
-               SYSERROR("Failed to unshare mount namespace.");
+               SYSERROR("Failed to unshare mount namespace");
                return -1;
        }
 
        if (detect_shared_rootfs()) {
                if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL)) {
-                       SYSERROR("Failed to make / rslave.");
+                       SYSERROR("Failed to make / rslave");
                        ERROR("Continuing...");
                }
        }
@@ -274,13 +263,13 @@ static int lxc_attach_remount_sys_proc(void)
        /* Assume /proc is always mounted, so remount it. */
        ret = umount2("/proc", MNT_DETACH);
        if (ret < 0) {
-               SYSERROR("Failed to unmount /proc.");
+               SYSERROR("Failed to unmount /proc");
                return -1;
        }
 
        ret = mount("none", "/proc", "proc", 0, NULL);
        if (ret < 0) {
-               SYSERROR("Failed to remount /proc.");
+               SYSERROR("Failed to remount /proc");
                return -1;
        }
 
@@ -289,13 +278,13 @@ static int lxc_attach_remount_sys_proc(void)
         */
        ret = umount2("/sys", MNT_DETACH);
        if (ret < 0 && errno != EINVAL) {
-               SYSERROR("Failed to unmount /sys.");
+               SYSERROR("Failed to unmount /sys");
                return -1;
        } else if (ret == 0) {
                /* Remount it. */
                ret = mount("none", "/sys", "sysfs", 0, NULL);
                if (ret < 0) {
-                       SYSERROR("Failed to remount /sys.");
+                       SYSERROR("Failed to remount /sys");
                        return -1;
                }
        }
@@ -312,10 +301,12 @@ static int lxc_attach_drop_privs(struct lxc_proc_context_info *ctx)
                if (ctx->capability_mask & (1LL << cap))
                        continue;
 
-               if (prctl(PR_CAPBSET_DROP, cap, 0, 0, 0)) {
+               if (prctl(PR_CAPBSET_DROP, prctl_arg(cap), prctl_arg(0),
+                         prctl_arg(0), prctl_arg(0))) {
                        SYSERROR("Failed to drop capability %d", cap);
                        return -1;
                }
+
                TRACE("Dropped capability %d", cap);
        }
 
@@ -350,6 +341,7 @@ static int lxc_attach_set_environment(struct lxc_proc_context_info *init_ctx,
                                        if (!extra_keep_store[i]) {
                                                while (i > 0)
                                                        free(extra_keep_store[--i]);
+
                                                free(extra_keep_store);
                                                return -1;
                                        }
@@ -370,7 +362,7 @@ static int lxc_attach_set_environment(struct lxc_proc_context_info *init_ctx,
                                free(extra_keep_store);
                        }
 
-                       SYSERROR("Failed to clear environment");
+                       ERROR("Failed to clear environment");
                        return -1;
                }
 
@@ -383,8 +375,10 @@ static int lxc_attach_set_environment(struct lxc_proc_context_info *init_ctx,
                                        if (ret < 0)
                                                SYSWARN("Failed to set environment variable");
                                }
+
                                free(extra_keep_store[i]);
                        }
+
                        free(extra_keep_store);
                }
 
@@ -427,6 +421,7 @@ static int lxc_attach_set_environment(struct lxc_proc_context_info *init_ctx,
        if (extra_env) {
                for (; *extra_env; extra_env++) {
                        char *p;
+
                        /* We just assume the user knows what they are doing, so
                         * we don't do any checks.
                         */
@@ -482,7 +477,7 @@ static char *lxc_attach_getpwshell(uid_t uid)
                ret = dup2(pipes[1], STDOUT_FILENO);
                close(pipes[1]);
                if (ret < 0)
-                       exit(EXIT_FAILURE);
+                       _exit(EXIT_FAILURE);
 
                /* Get rid of stdin/stderr, so we try to associate it with
                 * /dev/null.
@@ -500,11 +495,11 @@ static char *lxc_attach_getpwshell(uid_t uid)
                /* Finish argument list. */
                ret = snprintf(uid_buf, sizeof(uid_buf), "%ld", (long)uid);
                if (ret <= 0 || ret >= sizeof(uid_buf))
-                       exit(EXIT_FAILURE);
+                       _exit(EXIT_FAILURE);
 
                /* Try to run getent program. */
                (void)execvp("getent", arguments);
-               exit(EXIT_FAILURE);
+               _exit(EXIT_FAILURE);
        }
 
        close(pipes[1]);
@@ -523,6 +518,9 @@ static char *lxc_attach_getpwshell(uid_t uid)
                if (found)
                        continue;
 
+               if (!line)
+                       continue;
+
                /* Trim line on the right hand side. */
                for (i = strlen(line); i > 0 && (line[i - 1] == '\n' || line[i - 1] == '\r'); --i)
                        line[i - 1] = '\0';
@@ -541,7 +539,7 @@ static char *lxc_attach_getpwshell(uid_t uid)
                token = strtok_r(NULL, ":", &saveptr);
                value = token ? strtol(token, &endptr, 10) : 0;
                if (!token || !endptr || *endptr || value == LONG_MIN ||
-                               value == LONG_MAX)
+                   value == LONG_MAX)
                        continue;
 
                /* dummy sanity check: user id matches */
@@ -554,8 +552,10 @@ static char *lxc_attach_getpwshell(uid_t uid)
                        if (!token)
                                continue;
                }
+
                if (!token)
                        continue;
+
                free(result);
                result = strdup(token);
 
@@ -566,6 +566,7 @@ static char *lxc_attach_getpwshell(uid_t uid)
 
                found = true;
        }
+
        free(line);
        fclose(pipe_f);
 
@@ -586,7 +587,7 @@ static char *lxc_attach_getpwshell(uid_t uid)
 static void lxc_attach_get_init_uidgid(uid_t *init_uid, gid_t *init_gid)
 {
        FILE *proc_file;
-       char proc_fn[__PROC_STATUS_LEN];
+       char proc_fn[LXC_PROC_STATUS_LEN];
        int ret;
        char *line = NULL;
        size_t line_bufsz = 0;
@@ -594,8 +595,8 @@ static void lxc_attach_get_init_uidgid(uid_t *init_uid, gid_t *init_gid)
        uid_t uid = (uid_t)-1;
        gid_t gid = (gid_t)-1;
 
-       ret = snprintf(proc_fn, __PROC_STATUS_LEN, "/proc/%d/status", 1);
-       if (ret < 0 || ret >= __PROC_STATUS_LEN)
+       ret = snprintf(proc_fn, LXC_PROC_STATUS_LEN, "/proc/%d/status", 1);
+       if (ret < 0 || ret >= LXC_PROC_STATUS_LEN)
                return;
 
        proc_file = fopen(proc_fn, "r");
@@ -614,6 +615,7 @@ static void lxc_attach_get_init_uidgid(uid_t *init_uid, gid_t *init_gid)
                        if (ret != EOF && ret == 1)
                                gid = (gid_t)value;
                }
+
                if (uid != (uid_t)-1 && gid != (gid_t)-1)
                        break;
        }
@@ -624,6 +626,7 @@ static void lxc_attach_get_init_uidgid(uid_t *init_uid, gid_t *init_gid)
        /* Only override arguments if we found something. */
        if (uid != (uid_t)-1)
                *init_uid = uid;
+
        if (gid != (gid_t)-1)
                *init_gid = gid;
 
@@ -632,17 +635,6 @@ static void lxc_attach_get_init_uidgid(uid_t *init_uid, gid_t *init_gid)
         */
 }
 
-/* Help the optimizer along if it doesn't know that exit always exits. */
-#define rexit(c)                                                               \
-       do {                                                                   \
-               int __c = (c);                                                 \
-               _exit(__c);                                                    \
-               return __c;                                                    \
-       } while (0)
-
-/* Define default options if no options are supplied by the user. */
-static lxc_attach_options_t attach_static_default_options = LXC_ATTACH_OPTIONS_DEFAULT;
-
 static bool fetch_seccomp(struct lxc_container *c, lxc_attach_options_t *options)
 {
        int ret;
@@ -658,14 +650,14 @@ static bool fetch_seccomp(struct lxc_container *c, lxc_attach_options_t *options
 
        /* Remove current setting. */
        if (!c->set_config_item(c, "lxc.seccomp.profile", "") &&
-           !c->set_config_item(c, "lxc.seccomp", "")) {
+           !c->set_config_item(c, "lxc.seccomp", ""))
                return false;
-       }
 
        /* Fetch the current profile path over the cmd interface. */
        path = c->get_running_config_item(c, "lxc.seccomp.profile");
        if (!path) {
                INFO("Failed to retrieve lxc.seccomp.profile");
+
                path = c->get_running_config_item(c, "lxc.seccomp");
                if (!path) {
                        INFO("Failed to retrieve lxc.seccomp");
@@ -741,7 +733,6 @@ struct attach_clone_payload {
 static void lxc_put_attach_clone_payload(struct attach_clone_payload *p)
 {
        if (p->ipc_socket >= 0) {
-               shutdown(p->ipc_socket, SHUT_RDWR);
                close(p->ipc_socket);
                p->ipc_socket = -EBADF;
        }
@@ -762,6 +753,8 @@ static int attach_child_main(struct attach_clone_payload *payload)
        int fd, lsm_fd, ret;
        uid_t new_uid;
        gid_t new_gid;
+       uid_t ns_root_uid = 0;
+       gid_t ns_root_gid = 0;
        lxc_attach_options_t* options = payload->options;
        struct lxc_proc_context_info* init_ctx = payload->init_ctx;
        bool needs_lsm = (options->namespaces & CLONE_NEWNS) &&
@@ -778,6 +771,7 @@ static int attach_child_main(struct attach_clone_payload *payload)
                ret = lxc_attach_remount_sys_proc();
                if (ret < 0)
                        goto on_error;
+
                TRACE("Remounted \"/proc\" and \"/sys\"");
        }
 
@@ -790,9 +784,11 @@ static int attach_child_main(struct attach_clone_payload *payload)
                        new_personality = init_ctx->personality;
                else
                        new_personality = options->personality;
+
                ret = personality(new_personality);
                if (ret < 0)
                        goto on_error;
+
                TRACE("Set new personality");
        }
 #endif
@@ -801,6 +797,7 @@ static int attach_child_main(struct attach_clone_payload *payload)
                ret = lxc_attach_drop_privs(init_ctx);
                if (ret < 0)
                        goto on_error;
+
                TRACE("Dropped capabilities");
        }
 
@@ -813,6 +810,7 @@ static int attach_child_main(struct attach_clone_payload *payload)
                                         options->extra_keep_env);
        if (ret < 0)
                goto on_error;
+
        TRACE("Set up environment");
 
        /* This remark only affects fully unprivileged containers:
@@ -828,8 +826,13 @@ static int attach_child_main(struct attach_clone_payload *payload)
         */
        if (needs_lsm) {
                ret = lxc_abstract_unix_recv_fds(payload->ipc_socket, &lsm_fd, 1, NULL, 0);
-               if (ret <= 0)
+               if (ret <= 0) {
+                       if (ret < 0)
+                               SYSERROR("Failed to receive lsm label fd");
+
                        goto on_error;
+               }
+
                TRACE("Received LSM label file descriptor %d from parent", lsm_fd);
        }
 
@@ -839,37 +842,48 @@ static int attach_child_main(struct attach_clone_payload *payload)
                        goto on_error;
        }
 
-       /* Set {u,g}id. */
-       new_uid = 0;
-       new_gid = 0;
-       /* Ignore errors, we will fall back to root in that case (/proc was not
-        * mounted etc.).
-        */
-       if (options->namespaces & CLONE_NEWUSER)
-               lxc_attach_get_init_uidgid(&new_uid, &new_gid);
+       if (options->namespaces & CLONE_NEWUSER) {
+               /* Check whether nsuid 0 has a mapping. */
+               ns_root_uid = get_ns_uid(0);
 
-       if (options->uid != (uid_t)-1)
-               new_uid = options->uid;
-       if (options->gid != (gid_t)-1)
-               new_gid = options->gid;
+               /* Check whether nsgid 0 has a mapping. */
+               ns_root_gid = get_ns_gid(0);
 
-       /* Try to set the {u,g}id combination. */
-       if (new_uid != 0 || new_gid != 0 || options->namespaces & CLONE_NEWUSER) {
-               ret = lxc_switch_uid_gid(new_uid, new_gid);
-               if (ret < 0)
+               /* If there's no mapping for nsuid 0 try to retrieve the nsuid
+                * init was started with.
+                */
+               if (ns_root_uid == LXC_INVALID_UID)
+                       lxc_attach_get_init_uidgid(&ns_root_uid, &ns_root_gid);
+
+               if (ns_root_uid == LXC_INVALID_UID)
+                       goto on_error;
+
+               if (!lxc_switch_uid_gid(ns_root_uid, ns_root_gid))
                        goto on_error;
        }
 
-       ret = lxc_setgroups(0, NULL);
-       if (ret < 0 && errno != EPERM)
+       if (!lxc_setgroups(0, NULL) && errno != EPERM)
                goto on_error;
 
+       /* Set {u,g}id. */
+       if (options->uid != LXC_INVALID_UID)
+               new_uid = options->uid;
+       else
+               new_uid = ns_root_uid;
+
+       if (options->gid != LXC_INVALID_GID)
+               new_gid = options->gid;
+       else
+               new_gid = ns_root_gid;
+
        if ((init_ctx->container && init_ctx->container->lxc_conf &&
             init_ctx->container->lxc_conf->no_new_privs) ||
            (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) {
-               ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+               ret = prctl(PR_SET_NO_NEW_PRIVS, prctl_arg(1), prctl_arg(0),
+                           prctl_arg(0), prctl_arg(0));
                if (ret < 0)
                        goto on_error;
+
                TRACE("Set PR_SET_NO_NEW_PRIVS");
        }
 
@@ -878,10 +892,12 @@ static int attach_child_main(struct attach_clone_payload *payload)
 
                /* Change into our new LSM profile. */
                on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
+
                ret = lsm_process_label_set_at(lsm_fd, init_ctx->lsm_label, on_exec);
                close(lsm_fd);
                if (ret < 0)
                        goto on_error;
+
                TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx->lsm_label);
        }
 
@@ -890,9 +906,10 @@ static int attach_child_main(struct attach_clone_payload *payload)
                ret = lxc_seccomp_load(init_ctx->container->lxc_conf);
                if (ret < 0)
                        goto on_error;
+
                TRACE("Loaded seccomp profile");
        }
-       shutdown(payload->ipc_socket, SHUT_RDWR);
+
        close(payload->ipc_socket);
        payload->ipc_socket = -EBADF;
        lxc_proc_put_context_info(init_ctx);
@@ -908,13 +925,13 @@ static int attach_child_main(struct attach_clone_payload *payload)
         * may want to make sure the fds are closed, for example.
         */
        if (options->stdin_fd >= 0 && options->stdin_fd != STDIN_FILENO)
-               dup2(options->stdin_fd, STDIN_FILENO);
+               (void)dup2(options->stdin_fd, STDIN_FILENO);
 
        if (options->stdout_fd >= 0 && options->stdout_fd != STDOUT_FILENO)
-               dup2(options->stdout_fd, STDOUT_FILENO);
+               (void)dup2(options->stdout_fd, STDOUT_FILENO);
 
        if (options->stderr_fd >= 0 && options->stderr_fd != STDERR_FILENO)
-               dup2(options->stderr_fd, STDERR_FILENO);
+               (void)dup2(options->stderr_fd, STDERR_FILENO);
 
        /* close the old fds */
        if (options->stdin_fd > STDERR_FILENO)
@@ -943,15 +960,26 @@ static int attach_child_main(struct attach_clone_payload *payload)
                        SYSERROR("Failed to prepare terminal file descriptor %d", payload->terminal_slave_fd);
                        goto on_error;
                }
+
                TRACE("Prepared terminal file descriptor %d", payload->terminal_slave_fd);
        }
 
+       /* Avoid unnecessary syscalls. */
+       if (new_uid == ns_root_uid)
+               new_uid = LXC_INVALID_UID;
+
+       if (new_gid == ns_root_gid)
+               new_gid = LXC_INVALID_GID;
+
+       if (!lxc_switch_uid_gid(new_uid, new_gid))
+               goto on_error;
+
        /* We're done, so we can now do whatever the user intended us to do. */
-       rexit(payload->exec_function(payload->exec_payload));
+       _exit(payload->exec_function(payload->exec_payload));
 
 on_error:
        lxc_put_attach_clone_payload(payload);
-       rexit(EXIT_FAILURE);
+       _exit(EXIT_FAILURE);
 }
 
 static int lxc_attach_terminal(struct lxc_conf *conf,
@@ -963,7 +991,7 @@ static int lxc_attach_terminal(struct lxc_conf *conf,
 
        ret = lxc_terminal_create(terminal);
        if (ret < 0) {
-               SYSERROR("Failed to create terminal");
+               ERROR("Failed to create terminal");
                return -1;
        }
 
@@ -1055,7 +1083,7 @@ int lxc_attach(const char *name, const char *lxcpath,
 
        ret = access("/proc/self/ns", X_OK);
        if (ret) {
-               ERROR("Does this kernel version support namespaces?");
+               SYSERROR("Does this kernel version support namespaces?");
                return -1;
        }
 
@@ -1092,7 +1120,7 @@ int lxc_attach(const char *name, const char *lxcpath,
                init_ctx->container->lxc_conf = lxc_conf_init();
                if (!init_ctx->container->lxc_conf) {
                        lxc_proc_put_context_info(init_ctx);
-                       return -ENOMEM;
+                       return -1;
                }
        }
        conf = init_ctx->container->lxc_conf;
@@ -1133,8 +1161,9 @@ int lxc_attach(const char *name, const char *lxcpath,
        }
 
        pid = lxc_raw_getpid();
+
        for (i = 0; i < LXC_NS_MAX; i++) {
-               int j, saved_errno;
+               int j;
 
                if (options->namespaces & ns_info[i].clone_flag)
                        init_ctx->ns_fd[i] = lxc_preserve_ns(init_pid, ns_info[i].proc_name);
@@ -1142,6 +1171,7 @@ int lxc_attach(const char *name, const char *lxcpath,
                        init_ctx->ns_fd[i] = in_same_namespace(pid, init_pid, ns_info[i].proc_name);
                else
                        continue;
+
                if (init_ctx->ns_fd[i] >= 0)
                        continue;
 
@@ -1153,16 +1183,15 @@ int lxc_attach(const char *name, const char *lxcpath,
                }
 
                /* We failed to preserve the namespace. */
-               saved_errno = errno;
+               SYSERROR("Failed to attach to %s namespace of %d",
+                        ns_info[i].proc_name, pid);
+
                /* Close all already opened file descriptors before we return an
                 * error, so we don't leak them.
                 */
                for (j = 0; j < i; j++)
                        close(init_ctx->ns_fd[j]);
 
-               errno = saved_errno;
-               SYSERROR("Failed to attach to %s namespace of %d",
-                        ns_info[i].proc_name, pid);
                free(cwd);
                lxc_proc_put_context_info(init_ctx);
                return -1;
@@ -1190,7 +1219,7 @@ int lxc_attach(const char *name, const char *lxcpath,
         * just fork()s away without exec'ing directly after, the socket fd will
         * exist in the forked process from the other thread and any close() in
         * our own child process will not really cause the socket to close
-        * properly, potentiall causing the parent to hang.
+        * properly, potentially causing the parent to hang.
         *
         * For this reason, while IPC is still active, we have to use shutdown()
         * if the child exits prematurely in order to signal that the socket is
@@ -1254,7 +1283,7 @@ int lxc_attach(const char *name, const char *lxcpath,
                if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {
                        struct cgroup_ops *cgroup_ops;
 
-                       cgroup_ops = cgroup_init(NULL);
+                       cgroup_ops = cgroup_init(conf);
                        if (!cgroup_ops)
                                goto on_error;
 
@@ -1283,6 +1312,7 @@ int lxc_attach(const char *name, const char *lxcpath,
                        ret = lxc_attach_terminal_mainloop_init(&terminal, &descr);
                        if (ret < 0)
                                goto on_error;
+
                        TRACE("Initialized terminal mainloop");
                }
 
@@ -1291,12 +1321,14 @@ int lxc_attach(const char *name, const char *lxcpath,
                ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
                if (ret != sizeof(status))
                        goto close_mainloop;
+
                TRACE("Told intermediate process to start initializing");
 
                /* Get pid of attached process from intermediate process. */
                ret = lxc_read_nointr(ipc_sockets[0], &attached_pid, sizeof(attached_pid));
                if (ret != sizeof(attached_pid))
                        goto close_mainloop;
+
                TRACE("Received pid %d of attached process in parent pid namespace", attached_pid);
 
                /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
@@ -1309,6 +1341,7 @@ int lxc_attach(const char *name, const char *lxcpath,
                ret = wait_for_pid(pid);
                if (ret < 0)
                        goto close_mainloop;
+
                TRACE("Intermediate process %d exited", pid);
 
                /* We will always have to reap the attached process now. */
@@ -1326,15 +1359,20 @@ int lxc_attach(const char *name, const char *lxcpath,
                        labelfd = lsm_process_label_fd_get(attached_pid, on_exec);
                        if (labelfd < 0)
                                goto close_mainloop;
+
                        TRACE("Opened LSM label file descriptor %d", labelfd);
 
                        /* Send child fd of the LSM security module to write to. */
                        ret = lxc_abstract_unix_send_fds(ipc_sockets[0], &labelfd, 1, NULL, 0);
-                       close(labelfd);
                        if (ret <= 0) {
-                               SYSERROR("%d", (int)ret);
+                               if (ret < 0)
+                                       SYSERROR("Failed to send lsm label fd");
+
+                               close(labelfd);
                                goto close_mainloop;
                        }
+
+                       close(labelfd);
                        TRACE("Sent LSM label file descriptor %d to child", labelfd);
                }
 
@@ -1352,6 +1390,7 @@ int lxc_attach(const char *name, const char *lxcpath,
 
                ret_parent = 0;
                to_cleanup_pid = -1;
+
                if (options->attach_flags & LXC_ATTACH_TERMINAL) {
                        ret = lxc_mainloop(&descr, -1);
                        if (ret < 0) {
@@ -1377,6 +1416,7 @@ int lxc_attach(const char *name, const char *lxcpath,
                        lxc_terminal_delete(&terminal);
                        lxc_terminal_conf_free(&terminal);
                }
+
                lxc_proc_put_context_info(init_ctx);
                return ret_parent;
        }
@@ -1384,6 +1424,7 @@ int lxc_attach(const char *name, const char *lxcpath,
        /* close unneeded file descriptors */
        close(ipc_sockets[0]);
        ipc_sockets[0] = -EBADF;
+
        if (options->attach_flags & LXC_ATTACH_TERMINAL) {
                lxc_attach_terminal_close_master(&terminal);
                lxc_attach_terminal_close_peer(&terminal);
@@ -1395,8 +1436,9 @@ int lxc_attach(const char *name, const char *lxcpath,
        if (ret != sizeof(status)) {
                shutdown(ipc_sockets[1], SHUT_RDWR);
                lxc_proc_put_context_info(init_ctx);
-               rexit(-1);
+               _exit(EXIT_FAILURE);
        }
+
        TRACE("Intermediate process starting to initialize");
 
        /* Attach now, create another subprocess later, since pid namespaces
@@ -1407,8 +1449,9 @@ int lxc_attach(const char *name, const char *lxcpath,
                ERROR("Failed to enter namespaces");
                shutdown(ipc_sockets[1], SHUT_RDWR);
                lxc_proc_put_context_info(init_ctx);
-               rexit(-1);
+               _exit(EXIT_FAILURE);
        }
+
        /* close namespace file descriptors */
        lxc_proc_close_ns_fd(init_ctx);
 
@@ -1437,15 +1480,26 @@ int lxc_attach(const char *name, const char *lxcpath,
                SYSERROR("Failed to clone attached process");
                shutdown(ipc_sockets[1], SHUT_RDWR);
                lxc_proc_put_context_info(init_ctx);
-               rexit(-1);
+               _exit(EXIT_FAILURE);
        }
 
        if (pid == 0) {
+               if (options->attach_flags & LXC_ATTACH_TERMINAL) {
+                       ret = pthread_sigmask(SIG_SETMASK,
+                                             &terminal.tty_state->oldmask, NULL);
+                       if (ret < 0) {
+                               SYSERROR("Failed to reset signal mask");
+                               _exit(EXIT_FAILURE);
+                       }
+               }
+
                ret = attach_child_main(&payload);
                if (ret < 0)
                        ERROR("Failed to exec");
+
                _exit(EXIT_FAILURE);
        }
+
        if (options->attach_flags & LXC_ATTACH_TERMINAL)
                lxc_attach_terminal_close_slave(&terminal);
 
@@ -1460,22 +1514,35 @@ int lxc_attach(const char *name, const char *lxcpath,
                 */
                shutdown(ipc_sockets[1], SHUT_RDWR);
                lxc_proc_put_context_info(init_ctx);
-               rexit(-1);
+               _exit(EXIT_FAILURE);
        }
+
        TRACE("Sending pid %d of attached process", pid);
 
        /* The rest is in the hands of the initial and the attached process. */
        lxc_proc_put_context_info(init_ctx);
-       rexit(0);
+       _exit(0);
 }
 
-int lxc_attach_run_command(voidpayload)
+int lxc_attach_run_command(void *payload)
 {
-       lxc_attach_command_t* cmd = (lxc_attach_command_t*)payload;
+       int ret = -1;
+       lxc_attach_command_t *cmd = payload;
 
-       execvp(cmd->program, cmd->argv);
-       SYSERROR("Failed to exec \"%s\".", cmd->program);
-       return -1;
+       ret = execvp(cmd->program, cmd->argv);
+       if (ret < 0) {
+               switch (errno) {
+               case ENOEXEC:
+                       ret = 126;
+                       break;
+               case ENOENT:
+                       ret = 127;
+                       break;
+               }
+       }
+
+       SYSERROR("Failed to exec \"%s\"", cmd->program);
+       return ret;
 }
 
 int lxc_attach_run_shell(void* payload)
@@ -1502,7 +1569,7 @@ int lxc_attach_run_shell(void* payload)
                ret = getpwuid_r(uid, &pwent, buf, bufsize, &pwentp);
                if (!pwentp) {
                        if (ret == 0)
-                               WARN("Could not find matched password record.");
+                               WARN("Could not find matched password record");
 
                        WARN("Failed to get password record - %u", uid);
                }
@@ -1518,6 +1585,7 @@ int lxc_attach_run_shell(void* payload)
                user_shell = lxc_attach_getpwshell(uid);
        else
                user_shell = pwent.pw_shell;
+
        if (user_shell)
                execlp(user_shell, user_shell, (char *)NULL);
 
@@ -1525,9 +1593,11 @@ int lxc_attach_run_shell(void* payload)
         * on /bin/sh as a default shell.
         */
        execlp("/bin/sh", "/bin/sh", (char *)NULL);
+
        SYSERROR("Failed to execute shell");
        if (!pwentp)
                free(user_shell);
+
        free(buf);
        return -1;
 }