2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
39 #include <sys/mount.h>
40 #include <sys/param.h>
41 #include <sys/prctl.h>
42 #include <sys/socket.h>
44 #include <sys/syscall.h>
45 #include <sys/types.h>
49 #if HAVE_SYS_CAPABILITY_H
50 #include <sys/capability.h>
53 #ifndef HAVE_DECL_PR_CAPBSET_DROP
54 #define PR_CAPBSET_DROP 24
57 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
58 #define PR_SET_NO_NEW_PRIVS 38
61 #ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
62 #define PR_GET_NO_NEW_PRIVS 39
75 #include "lxcseccomp.h"
79 #include "namespace.h"
85 lxc_log_define(lxc_start
, lxc
);
87 const struct ns_info ns_info
[LXC_NS_MAX
] = {
88 [LXC_NS_MNT
] = {"mnt", CLONE_NEWNS
},
89 [LXC_NS_PID
] = {"pid", CLONE_NEWPID
},
90 [LXC_NS_UTS
] = {"uts", CLONE_NEWUTS
},
91 [LXC_NS_IPC
] = {"ipc", CLONE_NEWIPC
},
92 [LXC_NS_USER
] = {"user", CLONE_NEWUSER
},
93 [LXC_NS_NET
] = {"net", CLONE_NEWNET
},
94 [LXC_NS_CGROUP
] = {"cgroup", CLONE_NEWCGROUP
}
97 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
98 static bool do_destroy_container(struct lxc_conf
*conf
);
99 static int lxc_rmdir_onedev_wrapper(void *data
);
100 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
103 static void print_top_failing_dir(const char *path
)
105 size_t len
= strlen(path
);
106 char *copy
= alloca(len
+ 1), *p
, *e
, saved
;
112 while (p
< e
&& *p
== '/')
114 while (p
< e
&& *p
!= '/')
118 if (access(copy
, X_OK
)) {
119 SYSERROR("could not access %s. Please grant it 'x' " \
120 "access, or add an ACL for the container root.",
128 static void close_ns(int ns_fd
[LXC_NS_MAX
]) {
131 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
139 /* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
141 * Return true on success, false on failure.
143 static bool preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
)
147 for (i
= 0; i
< LXC_NS_MAX
; i
++)
150 ret
= lxc_preserve_ns(pid
, "");
152 SYSERROR("Kernel does not support attaching to namespaces.");
158 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
159 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
161 ns_fd
[i
] = lxc_preserve_ns(pid
, ns_info
[i
].proc_name
);
170 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info
[i
].proc_name
);
172 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info
[i
].proc_name
, strerror(errno
));
177 static int attach_ns(const int ns_fd
[LXC_NS_MAX
]) {
180 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
184 if (setns(ns_fd
[i
], 0) != 0)
190 SYSERROR("failed to set namespace '%s'", ns_info
[i
].proc_name
);
194 static int match_fd(int fd
)
196 return (fd
== 0 || fd
== 1 || fd
== 2);
200 * Check for any fds we need to close
201 * * if fd_to_ignore != -1, then if we find that fd open we will ignore it.
202 * * By default we warn about open fds we find.
203 * * If closeall is true, we will close open fds.
204 * * If lxc-start was passed "-C", then conf->close_all_fds will be true,
205 * in which case we also close all open fds.
206 * * A daemonized container will always pass closeall=true.
208 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
, int fd_to_ignore
)
210 struct dirent
*direntp
;
214 if (conf
&& conf
->close_all_fds
)
218 dir
= opendir("/proc/self/fd");
220 WARN("failed to open directory: %m");
226 while ((direntp
= readdir(dir
))) {
230 if (!strcmp(direntp
->d_name
, "."))
233 if (!strcmp(direntp
->d_name
, ".."))
236 fd
= atoi(direntp
->d_name
);
238 if (fd
== fddir
|| fd
== lxc_log_fd
|| fd
== fd_to_ignore
)
241 if (current_config
&& fd
== current_config
->logfd
)
250 INFO("closed inherited fd %d", fd
);
253 WARN("inherited fd %d", fd
);
257 * only enable syslog at this point to avoid the above logging function
258 * to open a new fd and make the check_inherited function enter an
261 lxc_log_enable_syslog();
263 closedir(dir
); /* cannot fail */
267 static int setup_signal_fd(sigset_t
*oldmask
)
272 /* Block everything except serious error signals */
273 if (sigfillset(&mask
) ||
274 sigdelset(&mask
, SIGILL
) ||
275 sigdelset(&mask
, SIGSEGV
) ||
276 sigdelset(&mask
, SIGBUS
) ||
277 sigdelset(&mask
, SIGWINCH
) ||
278 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
279 SYSERROR("failed to set signal mask");
283 fd
= signalfd(-1, &mask
, 0);
285 SYSERROR("failed to create the signal fd");
289 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
290 SYSERROR("failed to set sigfd to close-on-exec");
295 DEBUG("sigchild handler set");
300 static int signal_handler(int fd
, uint32_t events
, void *data
,
301 struct lxc_epoll_descr
*descr
)
303 struct signalfd_siginfo siginfo
;
307 bool init_died
= false;
309 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
311 ERROR("failed to read signal info");
315 if (ret
!= sizeof(siginfo
)) {
316 ERROR("unexpected siginfo size");
320 // check whether init is running
322 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
323 if (ret
== 0 && info
.si_pid
== *pid
) {
327 if (siginfo
.ssi_signo
!= SIGCHLD
) {
328 kill(*pid
, siginfo
.ssi_signo
);
329 INFO("forwarded signal %d to pid %d", siginfo
.ssi_signo
, *pid
);
330 return init_died
? 1 : 0;
333 if (siginfo
.ssi_code
== CLD_STOPPED
||
334 siginfo
.ssi_code
== CLD_CONTINUED
) {
335 INFO("container init process was stopped/continued");
336 return init_died
? 1 : 0;
339 /* more robustness, protect ourself from a SIGCHLD sent
340 * by a process different from the container init
342 if (siginfo
.ssi_pid
!= *pid
) {
343 WARN("invalid pid for SIGCHLD");
344 return init_died
? 1 : 0;
347 DEBUG("container init process exited");
351 int lxc_set_state(const char *name
, struct lxc_handler
*handler
, lxc_state_t state
)
353 handler
->state
= state
;
354 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
358 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
360 int sigfd
= handler
->sigfd
;
361 int pid
= handler
->pid
;
362 struct lxc_epoll_descr descr
;
364 if (lxc_mainloop_open(&descr
)) {
365 ERROR("failed to create mainloop");
369 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
370 ERROR("failed to add handler for the signal");
371 goto out_mainloop_open
;
374 if (lxc_console_mainloop_add(&descr
, handler
->conf
)) {
375 ERROR("failed to add console handler to mainloop");
376 goto out_mainloop_open
;
379 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
380 ERROR("failed to add command handler to mainloop");
381 goto out_mainloop_open
;
384 if (handler
->conf
->need_utmp_watch
) {
385 #if HAVE_SYS_CAPABILITY_H
386 if (lxc_utmp_mainloop_add(&descr
, handler
)) {
387 ERROR("failed to add utmp handler to mainloop");
388 goto out_mainloop_open
;
391 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support");
395 return lxc_mainloop(&descr
, -1);
398 lxc_mainloop_close(&descr
);
404 struct lxc_handler
*lxc_init(const char *name
, struct lxc_conf
*conf
, const char *lxcpath
)
407 struct lxc_handler
*handler
;
409 handler
= malloc(sizeof(*handler
));
413 memset(handler
, 0, sizeof(*handler
));
415 handler
->ttysock
[0] = handler
->ttysock
[1] = -1;
416 handler
->conf
= conf
;
417 handler
->lxcpath
= lxcpath
;
420 for (i
= 0; i
< LXC_NS_MAX
; i
++)
421 handler
->nsfd
[i
] = -1;
425 handler
->name
= strdup(name
);
426 if (!handler
->name
) {
427 ERROR("failed to allocate memory");
431 if (lxc_cmd_init(name
, handler
, lxcpath
))
434 if (lxc_read_seccomp_config(conf
) != 0) {
435 ERROR("failed loading seccomp policy");
436 goto out_close_maincmd_fd
;
439 /* Begin by setting the state to STARTING */
440 if (lxc_set_state(name
, handler
, STARTING
)) {
441 ERROR("failed to set state '%s'", lxc_state2str(STARTING
));
442 goto out_close_maincmd_fd
;
445 /* Start of environment variable setup for hooks */
446 if (name
&& setenv("LXC_NAME", name
, 1)) {
447 SYSERROR("failed to set environment variable for container name");
449 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
450 SYSERROR("failed to set environment variable for config path");
452 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
453 SYSERROR("failed to set environment variable for rootfs mount");
455 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
456 SYSERROR("failed to set environment variable for rootfs mount");
458 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1)) {
459 SYSERROR("failed to set environment variable for console path");
461 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1)) {
462 SYSERROR("failed to set environment variable for console log");
464 if (setenv("LXC_CGNS_AWARE", "1", 1)) {
465 SYSERROR("failed to set LXC_CGNS_AWARE environment variable");
467 /* End of environment variable setup for hooks */
469 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
470 ERROR("failed to run pre-start hooks for container '%s'.", name
);
474 /* the signal fd has to be created before forking otherwise
475 * if the child process exits before we setup the signal fd,
476 * the event will be lost and the command will be stuck */
477 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
478 if (handler
->sigfd
< 0) {
479 ERROR("failed to set sigchild fd handler");
483 /* do this after setting up signals since it might unblock SIGWINCH */
484 if (lxc_console_create(conf
)) {
485 ERROR("failed to create console");
486 goto out_restore_sigmask
;
489 if (ttys_shift_ids(conf
) < 0) {
490 ERROR("Failed to shift tty into container");
491 goto out_restore_sigmask
;
494 INFO("'%s' is initialized", name
);
498 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
500 lxc_delete_tty(&conf
->tty_info
);
502 lxc_set_state(name
, handler
, ABORTING
);
503 out_close_maincmd_fd
:
504 close(conf
->maincmd_fd
);
505 conf
->maincmd_fd
= -1;
508 handler
->name
= NULL
;
514 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
517 pid_t self
= getpid();
518 char *namespaces
[LXC_NS_MAX
+1];
519 size_t namespace_count
= 0;
521 /* The STOPPING state is there for future cleanup code
522 * which can take awhile
524 lxc_set_state(name
, handler
, STOPPING
);
526 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
527 if (handler
->nsfd
[i
] != -1) {
528 rc
= asprintf(&namespaces
[namespace_count
], "%s:/proc/%d/fd/%d",
529 ns_info
[i
].proc_name
, self
, handler
->nsfd
[i
]);
531 SYSERROR("failed to allocate memory");
537 namespaces
[namespace_count
] = NULL
;
539 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1)) {
540 SYSERROR("failed to set environment variable for stop target");
542 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1)) {
543 SYSERROR("failed to set environment variable for stop target");
546 if (run_lxc_hooks(name
, "stop", handler
->conf
, handler
->lxcpath
, namespaces
))
547 ERROR("failed to run stop hooks for container '%s'.", name
);
549 while (namespace_count
--)
550 free(namespaces
[namespace_count
]);
551 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
552 if (handler
->nsfd
[i
] != -1) {
553 close(handler
->nsfd
[i
]);
554 handler
->nsfd
[i
] = -1;
558 if (handler
->netnsfd
>= 0) {
559 close(handler
->netnsfd
);
560 handler
->netnsfd
= -1;
563 lxc_set_state(name
, handler
, STOPPED
);
565 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
)) {
566 ERROR("failed to run post-stop hooks for container '%s'.", name
);
567 if (handler
->conf
->reboot
) {
568 WARN("Container will be stopped instead of rebooted.");
569 handler
->conf
->reboot
= 0;
570 setenv("LXC_TARGET", "stop", 1);
574 /* reset mask set by setup_signal_fd */
575 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
576 WARN("failed to restore sigprocmask");
578 lxc_console_delete(&handler
->conf
->console
);
579 lxc_delete_tty(&handler
->conf
->tty_info
);
580 close(handler
->conf
->maincmd_fd
);
581 handler
->conf
->maincmd_fd
= -1;
583 if (handler
->ttysock
[0] != -1) {
584 close(handler
->ttysock
[0]);
585 close(handler
->ttysock
[1]);
588 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1)
589 lxc_destroy_container_on_signal(handler
, name
);
591 cgroup_destroy(handler
);
595 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
599 lxc_set_state(name
, handler
, ABORTING
);
600 if (handler
->pid
> 0)
601 kill(handler
->pid
, SIGKILL
);
602 while ((ret
= waitpid(-1, &status
, 0)) > 0) ;
605 #include <sys/reboot.h>
606 #include <linux/reboot.h>
609 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
610 * in a child pid namespace if container reboot support exists.
611 * Otherwise, it will either succeed or return -EPERM.
613 static int container_reboot_supported(void *arg
)
619 if (ret
== -1 && errno
== EINVAL
)
624 static int must_drop_cap_sys_boot(struct lxc_conf
*conf
)
627 int ret
, cmd
, v
, flags
;
628 long stack_size
= 4096;
629 void *stack
= alloca(stack_size
);
633 f
= fopen("/proc/sys/kernel/ctrl-alt-del", "r");
635 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
639 ret
= fscanf(f
, "%d", &v
);
642 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
645 cmd
= v
? LINUX_REBOOT_CMD_CAD_ON
: LINUX_REBOOT_CMD_CAD_OFF
;
647 flags
= CLONE_NEWPID
| SIGCHLD
;
648 if (!lxc_list_empty(&conf
->id_map
))
649 flags
|= CLONE_NEWUSER
;
652 pid
= __clone2(container_reboot_supported
, stack
, stack_size
, flags
, &cmd
);
655 pid
= clone(container_reboot_supported
, stack
, flags
, &cmd
);
658 if (flags
& CLONE_NEWUSER
)
659 ERROR("failed to clone (%#x): %s (includes CLONE_NEWUSER)", flags
, strerror(errno
));
661 ERROR("failed to clone (%#x): %s", flags
, strerror(errno
));
664 if (wait(&status
) < 0) {
665 SYSERROR("unexpected wait error: %m");
669 if (WEXITSTATUS(status
) != 1)
676 * netpipe is used in the unprivileged case to transfer the ifindexes
677 * from parent to child
679 static int netpipe
= -1;
681 static inline int count_veths(struct lxc_list
*network
)
683 struct lxc_list
*iterator
;
684 struct lxc_netdev
*netdev
;
687 lxc_list_for_each(iterator
, network
) {
688 netdev
= iterator
->elem
;
689 if (netdev
->type
!= LXC_NET_VETH
)
696 static int read_unpriv_netifindex(struct lxc_list
*network
)
698 struct lxc_list
*iterator
;
699 struct lxc_netdev
*netdev
;
703 lxc_list_for_each(iterator
, network
) {
704 netdev
= iterator
->elem
;
705 if (netdev
->type
!= LXC_NET_VETH
)
707 if (!(netdev
->name
= malloc(IFNAMSIZ
))) {
708 ERROR("Out of memory");
712 if (read(netpipe
, netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
721 static int do_start(void *data
)
723 struct lxc_list
*iterator
;
724 struct lxc_handler
*handler
= data
;
725 int devnull_fd
= -1, ret
;
728 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
729 SYSERROR("failed to set sigprocmask");
733 /* This prctl must be before the synchro, so if the parent
734 * dies before we set the parent death signal, we will detect
735 * its death with the synchro right after, otherwise we have
736 * a window where the parent can exit before we set the pdeath
737 * signal leading to a unsupervized container.
739 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
740 SYSERROR("failed to set pdeath signal");
744 lxc_sync_fini_parent(handler
);
746 /* don't leak the pinfd to the container */
747 if (handler
->pinfd
>= 0) {
748 close(handler
->pinfd
);
751 if (lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
))
754 /* Unshare CLONE_NEWNET after CLONE_NEWUSER - see
755 https://github.com/lxc/lxd/issues/1978 */
756 if ((handler
->clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
757 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
758 ret
= unshare(CLONE_NEWNET
);
760 SYSERROR("Error unsharing network namespace");
761 goto out_warn_father
;
763 INFO("Unshared NET namespace.");
767 /* Tell the parent task it can begin to configure the
768 * container and wait for it to finish
770 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
773 if (read_unpriv_netifindex(&handler
->conf
->network
) < 0)
774 goto out_warn_father
;
777 * if we are in a new user namespace, become root there to have
778 * privilege over our namespace. When using lxc-execute we default to root,
779 * but this can be overriden using the lxc.init_uid and lxc.init_gid
780 * configuration options.
782 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
784 if (handler
->conf
->is_execute
&& handler
->conf
->init_gid
)
785 new_gid
= handler
->conf
->init_gid
;
788 if (handler
->conf
->is_execute
&& handler
->conf
->init_uid
)
789 new_uid
= handler
->conf
->init_uid
;
791 NOTICE("switching to gid/uid %d/%d in new user namespace", new_gid
, new_uid
);
792 if (setgid(new_gid
)) {
794 goto out_warn_father
;
796 if (setuid(new_uid
)) {
798 goto out_warn_father
;
800 if (setgroups(0, NULL
)) {
801 SYSERROR("setgroups");
802 goto out_warn_father
;
806 if (access(handler
->lxcpath
, X_OK
)) {
807 print_top_failing_dir(handler
->lxcpath
);
808 goto out_warn_father
;
811 #if HAVE_SYS_CAPABILITY_H
812 if (handler
->conf
->need_utmp_watch
) {
813 if (prctl(PR_CAPBSET_DROP
, CAP_SYS_BOOT
, 0, 0, 0)) {
814 SYSERROR("failed to remove CAP_SYS_BOOT capability");
815 goto out_warn_father
;
817 DEBUG("Dropped cap_sys_boot");
821 ret
= snprintf(path
, sizeof(path
), "%s/dev/null", handler
->conf
->rootfs
.mount
);
822 if (ret
< 0 || ret
>= sizeof(path
)) {
823 SYSERROR("sprintf'd too many chars");
824 goto out_warn_father
;
827 /* In order to checkpoint restore, we need to have everything in the
828 * same mount namespace. However, some containers may not have a
829 * reasonable /dev (in particular, they may not have /dev/null), so we
830 * can't set init's std fds to /dev/null by opening it from inside the
833 * If that's the case, fall back to using the host's /dev/null. This
834 * means that migration won't work, but at least we won't spew output
835 * where it isn't wanted.
837 if (handler
->backgrounded
&& !handler
->conf
->autodev
&& access(path
, F_OK
) < 0) {
838 devnull_fd
= open_devnull();
841 goto out_warn_father
;
842 WARN("using host's /dev/null for container init's std fds, migraiton won't work");
845 /* Setup the container, ip, names, utsname, ... */
846 if (lxc_setup(handler
)) {
847 ERROR("failed to setup the container");
848 goto out_warn_father
;
851 /* ask father to setup cgroups and wait for him to finish */
852 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
855 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
856 * earlier we end up with a wrong view of /proc/self/cgroup. For
857 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
858 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
859 * /proc/self/cgroup would show us:
863 * whereas it should actually show
867 if (cgns_supported()) {
868 if (unshare(CLONE_NEWCGROUP
) < 0) {
869 INFO("Failed to unshare CLONE_NEWCGROUP.");
870 goto out_warn_father
;
872 INFO("Unshared CLONE_NEWCGROUP.");
875 /* Set the label to change to when we exec(2) the container's init */
876 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
877 goto out_warn_father
;
879 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
880 * before we aren't allowed anymore. */
881 if (handler
->conf
->no_new_privs
) {
882 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
883 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
884 goto out_warn_father
;
886 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
889 /* Some init's such as busybox will set sane tty settings on stdin,
890 * stdout, stderr which it thinks is the console. We already set them
891 * the way we wanted on the real terminal, and we want init to do its
892 * setup on its console ie. the pty allocated in lxc_console_create()
893 * so make sure that that pty is stdin,stdout,stderr.
895 if (lxc_console_set_stdfds(handler
->conf
->console
.slave
) < 0)
896 goto out_warn_father
;
898 /* If we mounted a temporary proc, then unmount it now */
899 tmp_proc_unmount(handler
->conf
);
901 if (lxc_seccomp_load(handler
->conf
) != 0)
902 goto out_warn_father
;
904 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
905 ERROR("failed to run start hooks for container '%s'.", handler
->name
);
906 goto out_warn_father
;
909 /* The clearenv() and putenv() calls have been moved here
910 * to allow us to use environment variables passed to the various
911 * hooks, such as the start hook above. Not all of the
912 * variables like CONFIG_PATH or ROOTFS are valid in this
913 * context but others are. */
915 SYSERROR("failed to clear environment");
916 /* don't error out though */
919 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
920 if (putenv((char *)iterator
->elem
)) {
921 SYSERROR("failed to set environment variable '%s'", (char *)iterator
->elem
);
922 goto out_warn_father
;
926 if (putenv("container=lxc")) {
927 SYSERROR("failed to set environment variable 'container=lxc'");
928 goto out_warn_father
;
931 if (handler
->conf
->pty_names
) {
932 if (putenv(handler
->conf
->pty_names
)) {
933 SYSERROR("failed to set environment variable for container ptys");
934 goto out_warn_father
;
938 close(handler
->sigfd
);
940 if (devnull_fd
< 0) {
941 devnull_fd
= open_devnull();
944 goto out_warn_father
;
947 if (handler
->backgrounded
&& set_stdfds(devnull_fd
))
948 goto out_warn_father
;
950 if (devnull_fd
>= 0) {
957 /* after this call, we are in error because this
958 * ops should not return as it execs */
959 handler
->ops
->start(handler
, handler
->data
);
962 /* we want the parent to know something went wrong, so we return a special
964 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
973 static int save_phys_nics(struct lxc_conf
*conf
)
975 struct lxc_list
*iterator
;
976 int am_root
= (getuid() == 0);
981 lxc_list_for_each(iterator
, &conf
->network
) {
982 struct lxc_netdev
*netdev
= iterator
->elem
;
984 if (netdev
->type
!= LXC_NET_PHYS
)
986 conf
->saved_nics
= realloc(conf
->saved_nics
,
987 (conf
->num_savednics
+1)*sizeof(struct saved_nic
));
988 if (!conf
->saved_nics
) {
989 SYSERROR("failed to allocate memory");
992 conf
->saved_nics
[conf
->num_savednics
].ifindex
= netdev
->ifindex
;
993 conf
->saved_nics
[conf
->num_savednics
].orig_name
= strdup(netdev
->link
);
994 if (!conf
->saved_nics
[conf
->num_savednics
].orig_name
) {
995 SYSERROR("failed to allocate memory");
998 INFO("stored saved_nic #%d idx %d name %s", conf
->num_savednics
,
999 conf
->saved_nics
[conf
->num_savednics
].ifindex
,
1000 conf
->saved_nics
[conf
->num_savednics
].orig_name
);
1001 conf
->num_savednics
++;
1007 static int recv_fd(int sock
, int *fd
)
1009 if (lxc_abstract_unix_recv_fd(sock
, fd
, NULL
, 0) < 0) {
1010 SYSERROR("Error receiving tty fd from child");
1018 static int recv_ttys_from_child(struct lxc_handler
*handler
)
1020 struct lxc_conf
*conf
= handler
->conf
;
1021 int i
, sock
= handler
->ttysock
[1];
1022 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
1027 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
)*conf
->tty
);
1028 if (!tty_info
->pty_info
) {
1029 SYSERROR("failed to allocate pty_info");
1033 for (i
= 0; i
< conf
->tty
; i
++) {
1034 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
1036 if (recv_fd(sock
, &pty_info
->slave
) < 0 ||
1037 recv_fd(sock
, &pty_info
->master
) < 0) {
1038 ERROR("Error receiving tty info from child");
1042 tty_info
->nbtty
= conf
->tty
;
1047 void resolve_clone_flags(struct lxc_handler
*handler
)
1049 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
1050 INFO("Adding CLONE_NEWPID to clone flags.");
1051 INFO("Adding CLONE_NEWNS to clone flags.");
1053 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1054 INFO("Adding CLONE_NEWUSER to clone flags.");
1055 handler
->clone_flags
|= CLONE_NEWUSER
;
1058 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
1059 if (!lxc_requests_empty_network(handler
)) {
1060 INFO("Adding CLONE_NEWNET to clone flags.");
1061 handler
->clone_flags
|= CLONE_NEWNET
;
1064 INFO("Inheriting a NET namespace.");
1067 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1) {
1068 INFO("Adding CLONE_NEWIPC to clone flags.");
1069 handler
->clone_flags
|= CLONE_NEWIPC
;
1071 INFO("Inheriting an IPC namespace.");
1074 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1) {
1075 INFO("Adding CLONE_NEWUTS to clone flags.");
1076 handler
->clone_flags
|= CLONE_NEWUTS
;
1078 INFO("Inheriting a UTS namespace.");
1082 static int lxc_spawn(struct lxc_handler
*handler
)
1084 int failed_before_rename
= 0;
1085 const char *name
= handler
->name
;
1086 bool cgroups_connected
= false;
1087 int saved_ns_fd
[LXC_NS_MAX
];
1088 int preserve_mask
= 0, i
, flags
;
1089 int netpipepair
[2], nveths
;
1093 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1094 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
1095 preserve_mask
|= ns_info
[i
].clone_flag
;
1097 if (lxc_sync_init(handler
))
1100 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, handler
->ttysock
) < 0) {
1101 lxc_sync_fini(handler
);
1105 resolve_clone_flags(handler
);
1107 if (handler
->clone_flags
& CLONE_NEWNET
) {
1108 if (!lxc_list_empty(&handler
->conf
->network
)) {
1110 /* Find gateway addresses from the link device, which is
1111 * no longer accessible inside the container. Do this
1112 * before creating network interfaces, since goto
1113 * out_delete_net does not work before lxc_clone. */
1114 if (lxc_find_gateway_addresses(handler
)) {
1115 ERROR("failed to find gateway addresses");
1116 lxc_sync_fini(handler
);
1120 /* that should be done before the clone because we will
1121 * fill the netdev index and use them in the child
1123 if (lxc_create_network(handler
)) {
1124 ERROR("failed to create the network");
1125 lxc_sync_fini(handler
);
1130 if (save_phys_nics(handler
->conf
)) {
1131 ERROR("failed to save physical nic info");
1136 if (!cgroup_init(handler
)) {
1137 ERROR("failed initializing cgroup support");
1138 goto out_delete_net
;
1141 cgroups_connected
= true;
1143 if (!cgroup_create(handler
)) {
1144 ERROR("failed creating cgroups");
1145 goto out_delete_net
;
1149 * if the rootfs is not a blockdev, prevent the container from
1150 * marking it readonly.
1152 * if the container is unprivileged then skip rootfs pinning
1154 if (lxc_list_empty(&handler
->conf
->id_map
)) {
1155 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
1156 if (handler
->pinfd
== -1)
1157 INFO("failed to pin the container's rootfs");
1160 if (!preserve_ns(saved_ns_fd
, preserve_mask
, getpid()))
1161 goto out_delete_net
;
1163 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
1164 goto out_delete_net
;
1166 if (am_unpriv() && (nveths
= count_veths(&handler
->conf
->network
))) {
1167 if (pipe(netpipepair
) < 0) {
1168 SYSERROR("Error creating pipe");
1169 goto out_delete_net
;
1171 /* store netpipe in the global var for do_start's use */
1172 netpipe
= netpipepair
[0];
1175 /* Create a process in a new set of namespaces */
1176 flags
= handler
->clone_flags
;
1177 if (handler
->clone_flags
& CLONE_NEWUSER
)
1178 flags
&= ~CLONE_NEWNET
;
1179 handler
->pid
= lxc_clone(do_start
, handler
, flags
);
1180 if (handler
->pid
< 0) {
1181 SYSERROR("Failed to fork into a set of new namespaces.");
1182 goto out_delete_net
;
1184 INFO("Cloned a set of new namespaces.");
1187 if (!preserve_ns(handler
->nsfd
, handler
->clone_flags
| preserve_mask
, handler
->pid
))
1188 INFO("Failed to preserve namespace for lxc.hook.stop.");
1190 if (attach_ns(saved_ns_fd
))
1191 WARN("failed to restore saved namespaces");
1193 lxc_sync_fini_child(handler
);
1195 /* map the container uids - the container became an invalid
1196 * userid the moment it was cloned with CLONE_NEWUSER - this
1197 * call doesn't change anything immediately, but allows the
1198 * container to setuid(0) (0 being mapped to something else on
1199 * the host) later to become a valid uid again */
1200 if (lxc_map_ids(&handler
->conf
->id_map
, handler
->pid
)) {
1201 ERROR("failed to set up id mapping");
1202 goto out_delete_net
;
1205 if (lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
)) {
1206 failed_before_rename
= 1;
1207 goto out_delete_net
;
1210 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
)) {
1211 failed_before_rename
= 1;
1212 goto out_delete_net
;
1215 if (!cgroup_create_legacy(handler
)) {
1216 ERROR("failed to setup the legacy cgroups for %s", name
);
1217 goto out_delete_net
;
1219 if (!cgroup_setup_limits(handler
, false)) {
1220 ERROR("failed to setup the cgroup limits for '%s'", name
);
1221 goto out_delete_net
;
1224 if (!cgroup_enter(handler
))
1225 goto out_delete_net
;
1227 if (!cgroup_chown(handler
))
1228 goto out_delete_net
;
1230 if (failed_before_rename
)
1231 goto out_delete_net
;
1233 /* Create the network configuration */
1234 if (handler
->clone_flags
& CLONE_NEWNET
) {
1235 if (lxc_assign_network(handler
->lxcpath
, handler
->name
,
1236 &handler
->conf
->network
, handler
->pid
)) {
1237 ERROR("failed to create the configured network");
1238 goto out_delete_net
;
1242 if (netpipe
!= -1) {
1243 struct lxc_list
*iterator
;
1244 struct lxc_netdev
*netdev
;
1247 lxc_list_for_each(iterator
, &handler
->conf
->network
) {
1248 netdev
= iterator
->elem
;
1249 if (netdev
->type
!= LXC_NET_VETH
)
1251 if (write(netpipepair
[1], netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
1252 ERROR("Error writing veth name to container");
1253 goto out_delete_net
;
1256 close(netpipepair
[1]);
1259 /* Tell the child to continue its initialization. we'll get
1260 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
1262 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1263 goto out_delete_net
;
1265 if (!cgroup_setup_limits(handler
, true)) {
1266 ERROR("failed to setup the devices cgroup for '%s'", name
);
1267 goto out_delete_net
;
1270 cgroup_disconnect();
1271 cgroups_connected
= false;
1273 /* read tty fds allocated by child */
1274 if (recv_ttys_from_child(handler
) < 0) {
1275 ERROR("failed to receive tty info from child");
1276 goto out_delete_net
;
1279 /* Tell the child to complete its initialization and wait for
1280 * it to exec or return an error. (the child will never
1281 * return LXC_SYNC_POST_CGROUP+1. It will either close the
1282 * sync pipe, causing lxc_sync_barrier_child to return
1283 * success, or return a different value, causing us to error
1286 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1289 if (detect_shared_rootfs())
1290 umount2(handler
->conf
->rootfs
.mount
, MNT_DETACH
);
1292 if (handler
->ops
->post_start(handler
, handler
->data
))
1295 if (lxc_set_state(name
, handler
, RUNNING
)) {
1296 ERROR("failed to set state to %s",
1297 lxc_state2str(RUNNING
));
1301 lxc_sync_fini(handler
);
1302 handler
->netnsfd
= lxc_preserve_ns(handler
->pid
, "net");
1307 if (cgroups_connected
)
1308 cgroup_disconnect();
1309 if (handler
->clone_flags
& CLONE_NEWNET
)
1310 lxc_delete_network(handler
);
1312 lxc_abort(name
, handler
);
1313 lxc_sync_fini(handler
);
1314 if (handler
->pinfd
>= 0) {
1315 close(handler
->pinfd
);
1316 handler
->pinfd
= -1;
1322 int __lxc_start(const char *name
, struct lxc_conf
*conf
,
1323 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1326 struct lxc_handler
*handler
;
1329 bool removed_all_netdevs
= true;
1331 handler
= lxc_init(name
, conf
, lxcpath
);
1333 ERROR("failed to initialize the container");
1337 handler
->data
= data
;
1338 handler
->backgrounded
= backgrounded
;
1339 handler
->netnsfd
= -1;
1341 if (must_drop_cap_sys_boot(handler
->conf
)) {
1342 #if HAVE_SYS_CAPABILITY_H
1343 DEBUG("Dropping cap_sys_boot");
1345 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
1348 DEBUG("Not dropping cap_sys_boot or watching utmp");
1349 handler
->conf
->need_utmp_watch
= 0;
1352 if (!attach_block_device(handler
->conf
)) {
1353 ERROR("Failure attaching block device");
1354 goto out_fini_nonet
;
1357 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1358 /* if the backing store is a device, mount it here and now */
1359 if (rootfs_is_blockdev(conf
)) {
1360 if (unshare(CLONE_NEWNS
) < 0) {
1361 ERROR("Error unsharing MOUNT namespace.");
1362 goto out_fini_nonet
;
1364 INFO("Unshared MOUNT namespace.");
1366 remount_all_slave();
1367 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1368 ERROR("Error setting up rootfs mount as root before spawn");
1369 goto out_fini_nonet
;
1371 INFO("Set up container rootfs as host root");
1375 err
= lxc_spawn(handler
);
1377 ERROR("failed to spawn '%s'", name
);
1378 goto out_detach_blockdev
;
1381 handler
->conf
->reboot
= 0;
1383 err
= lxc_poll(name
, handler
);
1385 ERROR("mainloop exited with an error");
1386 if (handler
->netnsfd
>= 0) {
1387 close(handler
->netnsfd
);
1388 handler
->netnsfd
= -1;
1393 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1397 * If the child process exited but was not signaled,
1398 * it didn't call reboot. This should mean it was an
1399 * lxc-execute which simply exited. In any case, treat
1402 if (WIFSIGNALED(status
)) {
1403 switch(WTERMSIG(status
)) {
1404 case SIGINT
: /* halt */
1405 DEBUG("Container halting");
1407 case SIGHUP
: /* reboot */
1408 DEBUG("Container rebooting");
1409 handler
->conf
->reboot
= 1;
1411 case SIGSYS
: /* seccomp */
1412 DEBUG("Container violated its seccomp policy");
1415 DEBUG("unknown exit status for init: %d", WTERMSIG(status
));
1420 DEBUG("Pushing physical nics back to host namespace");
1421 lxc_restore_phys_nics_to_netns(handler
->netnsfd
, handler
->conf
);
1423 DEBUG("Tearing down virtual network devices used by container");
1424 removed_all_netdevs
= lxc_delete_network(handler
);
1426 if (handler
->pinfd
>= 0) {
1427 close(handler
->pinfd
);
1428 handler
->pinfd
= -1;
1431 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1432 err
= lxc_error_set_and_log(handler
->pid
, status
);
1434 if (!removed_all_netdevs
) {
1435 DEBUG("Failed tearing down all network devices used by container. Trying again!");
1436 removed_all_netdevs
= lxc_delete_network(handler
);
1437 if (!removed_all_netdevs
)
1438 DEBUG("Failed tearing down network devices used by container. Not trying again!");
1441 out_detach_blockdev
:
1442 detach_block_device(handler
->conf
);
1445 lxc_fini(name
, handler
);
1449 lxc_abort(name
, handler
);
1457 static int start(struct lxc_handler
*handler
, void* data
)
1459 struct start_args
*arg
= data
;
1461 NOTICE("exec'ing '%s'", arg
->argv
[0]);
1463 execvp(arg
->argv
[0], arg
->argv
);
1464 SYSERROR("failed to exec %s", arg
->argv
[0]);
1468 static int post_start(struct lxc_handler
*handler
, void* data
)
1470 struct start_args
*arg
= data
;
1472 NOTICE("'%s' started with pid '%d'", arg
->argv
[0], handler
->pid
);
1476 static struct lxc_operations start_ops
= {
1478 .post_start
= post_start
1481 int lxc_start(const char *name
, char *const argv
[], struct lxc_conf
*conf
,
1482 const char *lxcpath
, bool backgrounded
)
1484 struct start_args start_arg
= {
1488 conf
->need_utmp_watch
= 1;
1489 return __lxc_start(name
, conf
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1492 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1495 char destroy
[MAXPATHLEN
];
1498 struct lxc_container
*c
;
1499 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1500 bret
= do_destroy_container(handler
->conf
);
1502 ERROR("Error destroying rootfs for %s", name
);
1506 INFO("Destroyed rootfs for %s", name
);
1508 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1509 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1510 ERROR("Error printing path for %s", name
);
1511 ERROR("Error destroying directory for %s", name
);
1515 c
= lxc_container_new(name
, handler
->lxcpath
);
1517 if (container_disk_lock(c
)) {
1518 INFO("Could not update lxc_snapshots file");
1519 lxc_container_put(c
);
1521 mod_all_rdeps(c
, false);
1522 container_disk_unlock(c
);
1523 lxc_container_put(c
);
1528 ret
= userns_exec_1(handler
->conf
, lxc_rmdir_onedev_wrapper
, destroy
);
1530 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1533 ERROR("Error destroying directory for %s", name
);
1536 INFO("Destroyed directory for %s", name
);
1539 static int lxc_rmdir_onedev_wrapper(void *data
)
1541 char *arg
= (char *) data
;
1542 return lxc_rmdir_onedev(arg
, NULL
);
1545 static bool do_destroy_container(struct lxc_conf
*conf
) {
1547 if (userns_exec_1(conf
, bdev_destroy_wrapper
, conf
) < 0)
1551 return bdev_destroy(conf
);