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
++) {
140 * preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
142 * Return true on success, false on failure. On failure, leave an error
143 * message in *errmsg, which caller must free.
145 static bool preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
,
149 char path
[MAXPATHLEN
];
151 for (i
= 0; i
< LXC_NS_MAX
; i
++)
154 snprintf(path
, MAXPATHLEN
, "/proc/%d/ns", pid
);
155 if (access(path
, X_OK
)) {
156 if (asprintf(errmsg
, "Kernel does not support setns.") == -1)
161 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
162 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
164 snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
,
165 ns_info
[i
].proc_name
);
166 ns_fd
[i
] = open(path
, O_RDONLY
| O_CLOEXEC
);
174 if (errno
== ENOENT
) {
175 ret
= asprintf(errmsg
, "Kernel does not support setns for %s",
176 ns_info
[i
].proc_name
);
178 ret
= asprintf(errmsg
, "Failed to open %s: %s",
179 path
, strerror(errno
));
187 static int attach_ns(const int ns_fd
[LXC_NS_MAX
]) {
190 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
194 if (setns(ns_fd
[i
], 0) != 0)
200 SYSERROR("failed to set namespace '%s'", ns_info
[i
].proc_name
);
204 static int match_fd(int fd
)
206 return (fd
== 0 || fd
== 1 || fd
== 2);
210 * Check for any fds we need to close
211 * * if fd_to_ignore != -1, then if we find that fd open we will ignore it.
212 * * By default we warn about open fds we find.
213 * * If closeall is true, we will close open fds.
214 * * If lxc-start was passed "-C", then conf->close_all_fds will be true,
215 * in which case we also close all open fds.
216 * * A daemonized container will always pass closeall=true.
218 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
, int fd_to_ignore
)
220 struct dirent
*direntp
;
224 if (conf
&& conf
->close_all_fds
)
228 dir
= opendir("/proc/self/fd");
230 WARN("failed to open directory: %m");
236 while ((direntp
= readdir(dir
))) {
240 if (!strcmp(direntp
->d_name
, "."))
243 if (!strcmp(direntp
->d_name
, ".."))
246 fd
= atoi(direntp
->d_name
);
248 if (fd
== fddir
|| fd
== lxc_log_fd
|| fd
== fd_to_ignore
)
251 if (current_config
&& fd
== current_config
->logfd
)
260 INFO("closed inherited fd %d", fd
);
263 WARN("inherited fd %d", fd
);
267 * only enable syslog at this point to avoid the above logging function
268 * to open a new fd and make the check_inherited function enter an
271 lxc_log_enable_syslog();
273 closedir(dir
); /* cannot fail */
277 static int setup_signal_fd(sigset_t
*oldmask
)
282 /* Block everything except serious error signals */
283 if (sigfillset(&mask
) ||
284 sigdelset(&mask
, SIGILL
) ||
285 sigdelset(&mask
, SIGSEGV
) ||
286 sigdelset(&mask
, SIGBUS
) ||
287 sigdelset(&mask
, SIGWINCH
) ||
288 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
289 SYSERROR("failed to set signal mask");
293 fd
= signalfd(-1, &mask
, 0);
295 SYSERROR("failed to create the signal fd");
299 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
300 SYSERROR("failed to set sigfd to close-on-exec");
305 DEBUG("sigchild handler set");
310 static int signal_handler(int fd
, uint32_t events
, void *data
,
311 struct lxc_epoll_descr
*descr
)
313 struct signalfd_siginfo siginfo
;
317 bool init_died
= false;
319 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
321 ERROR("failed to read signal info");
325 if (ret
!= sizeof(siginfo
)) {
326 ERROR("unexpected siginfo size");
330 // check whether init is running
332 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
333 if (ret
== 0 && info
.si_pid
== *pid
) {
337 if (siginfo
.ssi_signo
!= SIGCHLD
) {
338 kill(*pid
, siginfo
.ssi_signo
);
339 INFO("forwarded signal %d to pid %d", siginfo
.ssi_signo
, *pid
);
340 return init_died
? 1 : 0;
343 if (siginfo
.ssi_code
== CLD_STOPPED
||
344 siginfo
.ssi_code
== CLD_CONTINUED
) {
345 INFO("container init process was stopped/continued");
346 return init_died
? 1 : 0;
349 /* more robustness, protect ourself from a SIGCHLD sent
350 * by a process different from the container init
352 if (siginfo
.ssi_pid
!= *pid
) {
353 WARN("invalid pid for SIGCHLD");
354 return init_died
? 1 : 0;
357 DEBUG("container init process exited");
361 int lxc_set_state(const char *name
, struct lxc_handler
*handler
, lxc_state_t state
)
363 handler
->state
= state
;
364 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
368 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
370 int sigfd
= handler
->sigfd
;
371 int pid
= handler
->pid
;
372 struct lxc_epoll_descr descr
;
374 if (lxc_mainloop_open(&descr
)) {
375 ERROR("failed to create mainloop");
379 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
380 ERROR("failed to add handler for the signal");
381 goto out_mainloop_open
;
384 if (lxc_console_mainloop_add(&descr
, handler
->conf
)) {
385 ERROR("failed to add console handler to mainloop");
386 goto out_mainloop_open
;
389 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
390 ERROR("failed to add command handler to mainloop");
391 goto out_mainloop_open
;
394 if (handler
->conf
->need_utmp_watch
) {
395 #if HAVE_SYS_CAPABILITY_H
396 if (lxc_utmp_mainloop_add(&descr
, handler
)) {
397 ERROR("failed to add utmp handler to mainloop");
398 goto out_mainloop_open
;
401 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support");
405 return lxc_mainloop(&descr
, -1);
408 lxc_mainloop_close(&descr
);
414 struct lxc_handler
*lxc_init(const char *name
, struct lxc_conf
*conf
, const char *lxcpath
)
417 struct lxc_handler
*handler
;
419 handler
= malloc(sizeof(*handler
));
423 memset(handler
, 0, sizeof(*handler
));
425 handler
->ttysock
[0] = handler
->ttysock
[1] = -1;
426 handler
->conf
= conf
;
427 handler
->lxcpath
= lxcpath
;
430 for (i
= 0; i
< LXC_NS_MAX
; i
++)
431 handler
->nsfd
[i
] = -1;
435 handler
->name
= strdup(name
);
436 if (!handler
->name
) {
437 ERROR("failed to allocate memory");
441 if (lxc_cmd_init(name
, handler
, lxcpath
))
444 if (lxc_read_seccomp_config(conf
) != 0) {
445 ERROR("failed loading seccomp policy");
446 goto out_close_maincmd_fd
;
449 /* Begin by setting the state to STARTING */
450 if (lxc_set_state(name
, handler
, STARTING
)) {
451 ERROR("failed to set state '%s'", lxc_state2str(STARTING
));
452 goto out_close_maincmd_fd
;
455 /* Start of environment variable setup for hooks */
456 if (name
&& setenv("LXC_NAME", name
, 1)) {
457 SYSERROR("failed to set environment variable for container name");
459 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
460 SYSERROR("failed to set environment variable for config path");
462 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
463 SYSERROR("failed to set environment variable for rootfs mount");
465 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
466 SYSERROR("failed to set environment variable for rootfs mount");
468 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1)) {
469 SYSERROR("failed to set environment variable for console path");
471 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1)) {
472 SYSERROR("failed to set environment variable for console log");
474 if (setenv("LXC_CGNS_AWARE", "1", 1)) {
475 SYSERROR("failed to set LXC_CGNS_AWARE environment variable");
477 /* End of environment variable setup for hooks */
479 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
480 ERROR("failed to run pre-start hooks for container '%s'.", name
);
484 /* the signal fd has to be created before forking otherwise
485 * if the child process exits before we setup the signal fd,
486 * the event will be lost and the command will be stuck */
487 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
488 if (handler
->sigfd
< 0) {
489 ERROR("failed to set sigchild fd handler");
493 /* do this after setting up signals since it might unblock SIGWINCH */
494 if (lxc_console_create(conf
)) {
495 ERROR("failed to create console");
496 goto out_restore_sigmask
;
499 if (ttys_shift_ids(conf
) < 0) {
500 ERROR("Failed to shift tty into container");
501 goto out_restore_sigmask
;
504 INFO("'%s' is initialized", name
);
508 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
510 lxc_delete_tty(&conf
->tty_info
);
512 lxc_set_state(name
, handler
, ABORTING
);
513 out_close_maincmd_fd
:
514 close(conf
->maincmd_fd
);
515 conf
->maincmd_fd
= -1;
518 handler
->name
= NULL
;
524 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
527 pid_t self
= getpid();
528 char *namespaces
[LXC_NS_MAX
+1];
529 size_t namespace_count
= 0;
531 /* The STOPPING state is there for future cleanup code
532 * which can take awhile
534 lxc_set_state(name
, handler
, STOPPING
);
536 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
537 if (handler
->nsfd
[i
] != -1) {
538 rc
= asprintf(&namespaces
[namespace_count
], "%s:/proc/%d/fd/%d",
539 ns_info
[i
].proc_name
, self
, handler
->nsfd
[i
]);
541 SYSERROR("failed to allocate memory");
547 namespaces
[namespace_count
] = NULL
;
549 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1)) {
550 SYSERROR("failed to set environment variable for stop target");
552 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1)) {
553 SYSERROR("failed to set environment variable for stop target");
556 if (run_lxc_hooks(name
, "stop", handler
->conf
, handler
->lxcpath
, namespaces
))
557 ERROR("failed to run stop hooks for container '%s'.", name
);
559 while (namespace_count
--)
560 free(namespaces
[namespace_count
]);
561 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
562 if (handler
->nsfd
[i
] != -1) {
563 close(handler
->nsfd
[i
]);
564 handler
->nsfd
[i
] = -1;
568 if (handler
->netnsfd
>= 0) {
569 close(handler
->netnsfd
);
570 handler
->netnsfd
= -1;
573 lxc_set_state(name
, handler
, STOPPED
);
575 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
)) {
576 ERROR("failed to run post-stop hooks for container '%s'.", name
);
577 if (handler
->conf
->reboot
) {
578 WARN("Container will be stopped instead of rebooted.");
579 handler
->conf
->reboot
= 0;
580 setenv("LXC_TARGET", "stop", 1);
584 /* reset mask set by setup_signal_fd */
585 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
586 WARN("failed to restore sigprocmask");
588 lxc_console_delete(&handler
->conf
->console
);
589 lxc_delete_tty(&handler
->conf
->tty_info
);
590 close(handler
->conf
->maincmd_fd
);
591 handler
->conf
->maincmd_fd
= -1;
593 if (handler
->ttysock
[0] != -1) {
594 close(handler
->ttysock
[0]);
595 close(handler
->ttysock
[1]);
598 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1)
599 lxc_destroy_container_on_signal(handler
, name
);
601 cgroup_destroy(handler
);
605 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
609 lxc_set_state(name
, handler
, ABORTING
);
610 if (handler
->pid
> 0)
611 kill(handler
->pid
, SIGKILL
);
612 while ((ret
= waitpid(-1, &status
, 0)) > 0) ;
615 #include <sys/reboot.h>
616 #include <linux/reboot.h>
619 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
620 * in a child pid namespace if container reboot support exists.
621 * Otherwise, it will either succeed or return -EPERM.
623 static int container_reboot_supported(void *arg
)
629 if (ret
== -1 && errno
== EINVAL
)
634 static int must_drop_cap_sys_boot(struct lxc_conf
*conf
)
637 int ret
, cmd
, v
, flags
;
638 long stack_size
= 4096;
639 void *stack
= alloca(stack_size
);
643 f
= fopen("/proc/sys/kernel/ctrl-alt-del", "r");
645 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
649 ret
= fscanf(f
, "%d", &v
);
652 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
655 cmd
= v
? LINUX_REBOOT_CMD_CAD_ON
: LINUX_REBOOT_CMD_CAD_OFF
;
657 flags
= CLONE_NEWPID
| SIGCHLD
;
658 if (!lxc_list_empty(&conf
->id_map
))
659 flags
|= CLONE_NEWUSER
;
662 pid
= __clone2(container_reboot_supported
, stack
, stack_size
, flags
, &cmd
);
665 pid
= clone(container_reboot_supported
, stack
, flags
, &cmd
);
668 if (flags
& CLONE_NEWUSER
)
669 ERROR("failed to clone (%#x): %s (includes CLONE_NEWUSER)", flags
, strerror(errno
));
671 ERROR("failed to clone (%#x): %s", flags
, strerror(errno
));
674 if (wait(&status
) < 0) {
675 SYSERROR("unexpected wait error: %m");
679 if (WEXITSTATUS(status
) != 1)
686 * netpipe is used in the unprivileged case to transfer the ifindexes
687 * from parent to child
689 static int netpipe
= -1;
691 static inline int count_veths(struct lxc_list
*network
)
693 struct lxc_list
*iterator
;
694 struct lxc_netdev
*netdev
;
697 lxc_list_for_each(iterator
, network
) {
698 netdev
= iterator
->elem
;
699 if (netdev
->type
!= LXC_NET_VETH
)
706 static int read_unpriv_netifindex(struct lxc_list
*network
)
708 struct lxc_list
*iterator
;
709 struct lxc_netdev
*netdev
;
713 lxc_list_for_each(iterator
, network
) {
714 netdev
= iterator
->elem
;
715 if (netdev
->type
!= LXC_NET_VETH
)
717 if (!(netdev
->name
= malloc(IFNAMSIZ
))) {
718 ERROR("Out of memory");
722 if (read(netpipe
, netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
731 static int do_start(void *data
)
733 struct lxc_list
*iterator
;
734 struct lxc_handler
*handler
= data
;
735 int devnull_fd
= -1, ret
;
738 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
739 SYSERROR("failed to set sigprocmask");
743 /* This prctl must be before the synchro, so if the parent
744 * dies before we set the parent death signal, we will detect
745 * its death with the synchro right after, otherwise we have
746 * a window where the parent can exit before we set the pdeath
747 * signal leading to a unsupervized container.
749 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
750 SYSERROR("failed to set pdeath signal");
754 lxc_sync_fini_parent(handler
);
756 /* don't leak the pinfd to the container */
757 if (handler
->pinfd
>= 0) {
758 close(handler
->pinfd
);
761 if (lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
))
764 /* Unshare CLONE_NEWNET after CLONE_NEWUSER - see
765 https://github.com/lxc/lxd/issues/1978 */
766 if ((handler
->clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
767 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
768 ret
= unshare(CLONE_NEWNET
);
770 SYSERROR("Error unsharing network namespace");
771 goto out_warn_father
;
775 /* Tell the parent task it can begin to configure the
776 * container and wait for it to finish
778 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
781 if (read_unpriv_netifindex(&handler
->conf
->network
) < 0)
782 goto out_warn_father
;
785 * if we are in a new user namespace, become root there to have
786 * privilege over our namespace. When using lxc-execute we default to root,
787 * but this can be overriden using the lxc.init_uid and lxc.init_gid
788 * configuration options.
790 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
792 if (handler
->conf
->is_execute
&& handler
->conf
->init_gid
)
793 new_gid
= handler
->conf
->init_gid
;
796 if (handler
->conf
->is_execute
&& handler
->conf
->init_uid
)
797 new_uid
= handler
->conf
->init_uid
;
799 NOTICE("switching to gid/uid %d/%d in new user namespace", new_gid
, new_uid
);
800 if (setgid(new_gid
)) {
802 goto out_warn_father
;
804 if (setuid(new_uid
)) {
806 goto out_warn_father
;
808 if (setgroups(0, NULL
)) {
809 SYSERROR("setgroups");
810 goto out_warn_father
;
814 if (access(handler
->lxcpath
, X_OK
)) {
815 print_top_failing_dir(handler
->lxcpath
);
816 goto out_warn_father
;
819 #if HAVE_SYS_CAPABILITY_H
820 if (handler
->conf
->need_utmp_watch
) {
821 if (prctl(PR_CAPBSET_DROP
, CAP_SYS_BOOT
, 0, 0, 0)) {
822 SYSERROR("failed to remove CAP_SYS_BOOT capability");
823 goto out_warn_father
;
825 DEBUG("Dropped cap_sys_boot");
829 ret
= snprintf(path
, sizeof(path
), "%s/dev/null", handler
->conf
->rootfs
.mount
);
830 if (ret
< 0 || ret
>= sizeof(path
)) {
831 SYSERROR("sprintf'd too many chars");
832 goto out_warn_father
;
835 /* In order to checkpoint restore, we need to have everything in the
836 * same mount namespace. However, some containers may not have a
837 * reasonable /dev (in particular, they may not have /dev/null), so we
838 * can't set init's std fds to /dev/null by opening it from inside the
841 * If that's the case, fall back to using the host's /dev/null. This
842 * means that migration won't work, but at least we won't spew output
843 * where it isn't wanted.
845 if (handler
->backgrounded
&& !handler
->conf
->autodev
&& access(path
, F_OK
) < 0) {
846 devnull_fd
= open_devnull();
849 goto out_warn_father
;
850 WARN("using host's /dev/null for container init's std fds, migraiton won't work");
853 /* Setup the container, ip, names, utsname, ... */
854 if (lxc_setup(handler
)) {
855 ERROR("failed to setup the container");
856 goto out_warn_father
;
859 /* ask father to setup cgroups and wait for him to finish */
860 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
863 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
864 * earlier we end up with a wrong view of /proc/self/cgroup. For
865 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
866 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
867 * /proc/self/cgroup would show us:
871 * whereas it should actually show
875 if (cgns_supported()) {
876 if (unshare(CLONE_NEWCGROUP
) < 0) {
877 INFO("Failed to unshare CLONE_NEWCGROUP.");
878 goto out_warn_father
;
880 INFO("Unshared CLONE_NEWCGROUP.");
883 /* Set the label to change to when we exec(2) the container's init */
884 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
885 goto out_warn_father
;
887 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
888 * before we aren't allowed anymore. */
889 if (handler
->conf
->no_new_privs
) {
890 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
891 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
892 goto out_warn_father
;
894 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
897 /* Some init's such as busybox will set sane tty settings on stdin,
898 * stdout, stderr which it thinks is the console. We already set them
899 * the way we wanted on the real terminal, and we want init to do its
900 * setup on its console ie. the pty allocated in lxc_console_create()
901 * so make sure that that pty is stdin,stdout,stderr.
903 if (lxc_console_set_stdfds(handler
->conf
->console
.slave
) < 0)
904 goto out_warn_father
;
906 /* If we mounted a temporary proc, then unmount it now */
907 tmp_proc_unmount(handler
->conf
);
909 if (lxc_seccomp_load(handler
->conf
) != 0)
910 goto out_warn_father
;
912 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
913 ERROR("failed to run start hooks for container '%s'.", handler
->name
);
914 goto out_warn_father
;
917 /* The clearenv() and putenv() calls have been moved here
918 * to allow us to use environment variables passed to the various
919 * hooks, such as the start hook above. Not all of the
920 * variables like CONFIG_PATH or ROOTFS are valid in this
921 * context but others are. */
923 SYSERROR("failed to clear environment");
924 /* don't error out though */
927 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
928 if (putenv((char *)iterator
->elem
)) {
929 SYSERROR("failed to set environment variable '%s'", (char *)iterator
->elem
);
930 goto out_warn_father
;
934 if (putenv("container=lxc")) {
935 SYSERROR("failed to set environment variable 'container=lxc'");
936 goto out_warn_father
;
939 if (handler
->conf
->pty_names
) {
940 if (putenv(handler
->conf
->pty_names
)) {
941 SYSERROR("failed to set environment variable for container ptys");
942 goto out_warn_father
;
946 close(handler
->sigfd
);
948 if (devnull_fd
< 0) {
949 devnull_fd
= open_devnull();
952 goto out_warn_father
;
955 if (handler
->backgrounded
&& set_stdfds(devnull_fd
))
956 goto out_warn_father
;
958 if (devnull_fd
>= 0) {
965 /* after this call, we are in error because this
966 * ops should not return as it execs */
967 handler
->ops
->start(handler
, handler
->data
);
970 /* we want the parent to know something went wrong, so we return a special
972 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
981 static int save_phys_nics(struct lxc_conf
*conf
)
983 struct lxc_list
*iterator
;
984 int am_root
= (getuid() == 0);
989 lxc_list_for_each(iterator
, &conf
->network
) {
990 struct lxc_netdev
*netdev
= iterator
->elem
;
992 if (netdev
->type
!= LXC_NET_PHYS
)
994 conf
->saved_nics
= realloc(conf
->saved_nics
,
995 (conf
->num_savednics
+1)*sizeof(struct saved_nic
));
996 if (!conf
->saved_nics
) {
997 SYSERROR("failed to allocate memory");
1000 conf
->saved_nics
[conf
->num_savednics
].ifindex
= netdev
->ifindex
;
1001 conf
->saved_nics
[conf
->num_savednics
].orig_name
= strdup(netdev
->link
);
1002 if (!conf
->saved_nics
[conf
->num_savednics
].orig_name
) {
1003 SYSERROR("failed to allocate memory");
1006 INFO("stored saved_nic #%d idx %d name %s", conf
->num_savednics
,
1007 conf
->saved_nics
[conf
->num_savednics
].ifindex
,
1008 conf
->saved_nics
[conf
->num_savednics
].orig_name
);
1009 conf
->num_savednics
++;
1015 static int recv_fd(int sock
, int *fd
)
1017 if (lxc_abstract_unix_recv_fd(sock
, fd
, NULL
, 0) < 0) {
1018 SYSERROR("Error receiving tty fd from child");
1026 static int recv_ttys_from_child(struct lxc_handler
*handler
)
1028 struct lxc_conf
*conf
= handler
->conf
;
1029 int i
, sock
= handler
->ttysock
[1];
1030 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
1035 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
)*conf
->tty
);
1036 if (!tty_info
->pty_info
) {
1037 SYSERROR("failed to allocate pty_info");
1041 for (i
= 0; i
< conf
->tty
; i
++) {
1042 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
1044 if (recv_fd(sock
, &pty_info
->slave
) < 0 ||
1045 recv_fd(sock
, &pty_info
->master
) < 0) {
1046 ERROR("Error receiving tty info from child");
1050 tty_info
->nbtty
= conf
->tty
;
1055 void resolve_clone_flags(struct lxc_handler
*handler
)
1057 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
1059 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1060 INFO("Cloning a new USER namespace");
1061 handler
->clone_flags
|= CLONE_NEWUSER
;
1064 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
1065 if (!lxc_requests_empty_network(handler
)) {
1066 INFO("Cloning a new NET namespace");
1067 handler
->clone_flags
|= CLONE_NEWNET
;
1070 INFO("Inheriting a NET namespace");
1073 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1) {
1074 INFO("Cloning a new IPC namespace");
1075 handler
->clone_flags
|= CLONE_NEWIPC
;
1077 INFO("Inheriting an IPC namespace");
1080 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1) {
1081 INFO("Cloning a new UTS namespace");
1082 handler
->clone_flags
|= CLONE_NEWUTS
;
1084 INFO("Inheriting a UTS namespace");
1088 static int lxc_spawn(struct lxc_handler
*handler
)
1090 int failed_before_rename
= 0;
1091 const char *name
= handler
->name
;
1092 char *errmsg
= NULL
;
1093 bool cgroups_connected
= false;
1094 int saved_ns_fd
[LXC_NS_MAX
];
1095 int preserve_mask
= 0, i
, flags
;
1096 int netpipepair
[2], nveths
;
1100 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1101 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
1102 preserve_mask
|= ns_info
[i
].clone_flag
;
1104 if (lxc_sync_init(handler
))
1107 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, handler
->ttysock
) < 0) {
1108 lxc_sync_fini(handler
);
1112 resolve_clone_flags(handler
);
1114 if (handler
->clone_flags
& CLONE_NEWNET
) {
1115 if (!lxc_list_empty(&handler
->conf
->network
)) {
1117 /* Find gateway addresses from the link device, which is
1118 * no longer accessible inside the container. Do this
1119 * before creating network interfaces, since goto
1120 * out_delete_net does not work before lxc_clone. */
1121 if (lxc_find_gateway_addresses(handler
)) {
1122 ERROR("failed to find gateway addresses");
1123 lxc_sync_fini(handler
);
1127 /* that should be done before the clone because we will
1128 * fill the netdev index and use them in the child
1130 if (lxc_create_network(handler
)) {
1131 ERROR("failed to create the network");
1132 lxc_sync_fini(handler
);
1137 if (save_phys_nics(handler
->conf
)) {
1138 ERROR("failed to save physical nic info");
1143 if (!cgroup_init(handler
)) {
1144 ERROR("failed initializing cgroup support");
1145 goto out_delete_net
;
1148 cgroups_connected
= true;
1150 if (!cgroup_create(handler
)) {
1151 ERROR("failed creating cgroups");
1152 goto out_delete_net
;
1156 * if the rootfs is not a blockdev, prevent the container from
1157 * marking it readonly.
1159 * if the container is unprivileged then skip rootfs pinning
1161 if (lxc_list_empty(&handler
->conf
->id_map
)) {
1162 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
1163 if (handler
->pinfd
== -1)
1164 INFO("failed to pin the container's rootfs");
1167 if (!preserve_ns(saved_ns_fd
, preserve_mask
, getpid(), &errmsg
)) {
1168 SYSERROR("Failed to preserve requested namespaces: %s",
1169 errmsg
? errmsg
: "(Out of memory)");
1171 goto out_delete_net
;
1173 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
1174 goto out_delete_net
;
1176 if (am_unpriv() && (nveths
= count_veths(&handler
->conf
->network
))) {
1177 if (pipe(netpipepair
) < 0) {
1178 SYSERROR("Error creating pipe");
1179 goto out_delete_net
;
1181 /* store netpipe in the global var for do_start's use */
1182 netpipe
= netpipepair
[0];
1185 /* Create a process in a new set of namespaces */
1186 flags
= handler
->clone_flags
;
1187 if (handler
->clone_flags
& CLONE_NEWUSER
)
1188 flags
&= ~CLONE_NEWNET
;
1189 handler
->pid
= lxc_clone(do_start
, handler
, flags
);
1190 if (handler
->pid
< 0) {
1191 SYSERROR("failed to fork into a new namespace");
1192 goto out_delete_net
;
1195 if (!preserve_ns(handler
->nsfd
, handler
->clone_flags
| preserve_mask
, handler
->pid
, &errmsg
)) {
1196 INFO("Failed to store namespace references for stop hook: %s",
1197 errmsg
? errmsg
: "(Out of memory)");
1201 if (attach_ns(saved_ns_fd
))
1202 WARN("failed to restore saved namespaces");
1204 lxc_sync_fini_child(handler
);
1206 /* map the container uids - the container became an invalid
1207 * userid the moment it was cloned with CLONE_NEWUSER - this
1208 * call doesn't change anything immediately, but allows the
1209 * container to setuid(0) (0 being mapped to something else on
1210 * the host) later to become a valid uid again */
1211 if (lxc_map_ids(&handler
->conf
->id_map
, handler
->pid
)) {
1212 ERROR("failed to set up id mapping");
1213 goto out_delete_net
;
1216 if (lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
)) {
1217 failed_before_rename
= 1;
1218 goto out_delete_net
;
1221 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
)) {
1222 failed_before_rename
= 1;
1223 goto out_delete_net
;
1226 if (!cgroup_create_legacy(handler
)) {
1227 ERROR("failed to setup the legacy cgroups for %s", name
);
1228 goto out_delete_net
;
1230 if (!cgroup_setup_limits(handler
, false)) {
1231 ERROR("failed to setup the cgroup limits for '%s'", name
);
1232 goto out_delete_net
;
1235 if (!cgroup_enter(handler
))
1236 goto out_delete_net
;
1238 if (!cgroup_chown(handler
))
1239 goto out_delete_net
;
1241 if (failed_before_rename
)
1242 goto out_delete_net
;
1244 /* Create the network configuration */
1245 if (handler
->clone_flags
& CLONE_NEWNET
) {
1246 if (lxc_assign_network(handler
->lxcpath
, handler
->name
,
1247 &handler
->conf
->network
, handler
->pid
)) {
1248 ERROR("failed to create the configured network");
1249 goto out_delete_net
;
1253 if (netpipe
!= -1) {
1254 struct lxc_list
*iterator
;
1255 struct lxc_netdev
*netdev
;
1258 lxc_list_for_each(iterator
, &handler
->conf
->network
) {
1259 netdev
= iterator
->elem
;
1260 if (netdev
->type
!= LXC_NET_VETH
)
1262 if (write(netpipepair
[1], netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
1263 ERROR("Error writing veth name to container");
1264 goto out_delete_net
;
1267 close(netpipepair
[1]);
1270 /* Tell the child to continue its initialization. we'll get
1271 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
1273 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1274 goto out_delete_net
;
1276 if (!cgroup_setup_limits(handler
, true)) {
1277 ERROR("failed to setup the devices cgroup for '%s'", name
);
1278 goto out_delete_net
;
1281 cgroup_disconnect();
1282 cgroups_connected
= false;
1284 /* read tty fds allocated by child */
1285 if (recv_ttys_from_child(handler
) < 0) {
1286 ERROR("failed to receive tty info from child");
1287 goto out_delete_net
;
1290 /* Tell the child to complete its initialization and wait for
1291 * it to exec or return an error. (the child will never
1292 * return LXC_SYNC_POST_CGROUP+1. It will either close the
1293 * sync pipe, causing lxc_sync_barrier_child to return
1294 * success, or return a different value, causing us to error
1297 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1300 if (detect_shared_rootfs())
1301 umount2(handler
->conf
->rootfs
.mount
, MNT_DETACH
);
1303 if (handler
->ops
->post_start(handler
, handler
->data
))
1306 if (lxc_set_state(name
, handler
, RUNNING
)) {
1307 ERROR("failed to set state to %s",
1308 lxc_state2str(RUNNING
));
1312 lxc_sync_fini(handler
);
1313 handler
->netnsfd
= lxc_preserve_ns(handler
->pid
, "net");
1318 if (cgroups_connected
)
1319 cgroup_disconnect();
1320 if (handler
->clone_flags
& CLONE_NEWNET
)
1321 lxc_delete_network(handler
);
1323 lxc_abort(name
, handler
);
1324 lxc_sync_fini(handler
);
1325 if (handler
->pinfd
>= 0) {
1326 close(handler
->pinfd
);
1327 handler
->pinfd
= -1;
1333 int __lxc_start(const char *name
, struct lxc_conf
*conf
,
1334 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1337 struct lxc_handler
*handler
;
1341 handler
= lxc_init(name
, conf
, lxcpath
);
1343 ERROR("failed to initialize the container");
1347 handler
->data
= data
;
1348 handler
->backgrounded
= backgrounded
;
1349 handler
->netnsfd
= -1;
1351 if (must_drop_cap_sys_boot(handler
->conf
)) {
1352 #if HAVE_SYS_CAPABILITY_H
1353 DEBUG("Dropping cap_sys_boot");
1355 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
1358 DEBUG("Not dropping cap_sys_boot or watching utmp");
1359 handler
->conf
->need_utmp_watch
= 0;
1362 if (!attach_block_device(handler
->conf
)) {
1363 ERROR("Failure attaching block device");
1364 goto out_fini_nonet
;
1367 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1368 /* if the backing store is a device, mount it here and now */
1369 if (rootfs_is_blockdev(conf
)) {
1370 if (unshare(CLONE_NEWNS
) < 0) {
1371 ERROR("Error unsharing mounts");
1372 goto out_fini_nonet
;
1374 remount_all_slave();
1375 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1376 ERROR("Error setting up rootfs mount as root before spawn");
1377 goto out_fini_nonet
;
1379 INFO("Set up container rootfs as host root");
1383 err
= lxc_spawn(handler
);
1385 ERROR("failed to spawn '%s'", name
);
1386 goto out_detach_blockdev
;
1389 handler
->conf
->reboot
= 0;
1391 err
= lxc_poll(name
, handler
);
1393 ERROR("mainloop exited with an error");
1394 if (handler
->netnsfd
>= 0) {
1395 close(handler
->netnsfd
);
1396 handler
->netnsfd
= -1;
1401 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1405 * If the child process exited but was not signaled,
1406 * it didn't call reboot. This should mean it was an
1407 * lxc-execute which simply exited. In any case, treat
1410 if (WIFSIGNALED(status
)) {
1411 switch(WTERMSIG(status
)) {
1412 case SIGINT
: /* halt */
1413 DEBUG("Container halting");
1415 case SIGHUP
: /* reboot */
1416 DEBUG("Container rebooting");
1417 handler
->conf
->reboot
= 1;
1419 case SIGSYS
: /* seccomp */
1420 DEBUG("Container violated its seccomp policy");
1423 DEBUG("unknown exit status for init: %d", WTERMSIG(status
));
1428 DEBUG("Pushing physical nics back to host namespace");
1429 lxc_restore_phys_nics_to_netns(handler
->netnsfd
, handler
->conf
);
1431 DEBUG("Tearing down virtual network devices used by container");
1432 lxc_delete_network(handler
);
1434 if (handler
->pinfd
>= 0) {
1435 close(handler
->pinfd
);
1436 handler
->pinfd
= -1;
1439 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1440 err
= lxc_error_set_and_log(handler
->pid
, status
);
1442 lxc_delete_network(handler
);
1444 out_detach_blockdev
:
1445 detach_block_device(handler
->conf
);
1448 lxc_fini(name
, handler
);
1452 lxc_abort(name
, handler
);
1460 static int start(struct lxc_handler
*handler
, void* data
)
1462 struct start_args
*arg
= data
;
1464 NOTICE("exec'ing '%s'", arg
->argv
[0]);
1466 execvp(arg
->argv
[0], arg
->argv
);
1467 SYSERROR("failed to exec %s", arg
->argv
[0]);
1471 static int post_start(struct lxc_handler
*handler
, void* data
)
1473 struct start_args
*arg
= data
;
1475 NOTICE("'%s' started with pid '%d'", arg
->argv
[0], handler
->pid
);
1479 static struct lxc_operations start_ops
= {
1481 .post_start
= post_start
1484 int lxc_start(const char *name
, char *const argv
[], struct lxc_conf
*conf
,
1485 const char *lxcpath
, bool backgrounded
)
1487 struct start_args start_arg
= {
1491 conf
->need_utmp_watch
= 1;
1492 return __lxc_start(name
, conf
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1495 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1498 char destroy
[MAXPATHLEN
];
1501 struct lxc_container
*c
;
1502 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1503 bret
= do_destroy_container(handler
->conf
);
1505 ERROR("Error destroying rootfs for %s", name
);
1509 INFO("Destroyed rootfs for %s", name
);
1511 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1512 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1513 ERROR("Error printing path for %s", name
);
1514 ERROR("Error destroying directory for %s", name
);
1518 c
= lxc_container_new(name
, handler
->lxcpath
);
1520 if (container_disk_lock(c
)) {
1521 INFO("Could not update lxc_snapshots file");
1522 lxc_container_put(c
);
1524 mod_all_rdeps(c
, false);
1525 container_disk_unlock(c
);
1526 lxc_container_put(c
);
1531 ret
= userns_exec_1(handler
->conf
, lxc_rmdir_onedev_wrapper
, destroy
);
1533 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1536 ERROR("Error destroying directory for %s", name
);
1539 INFO("Destroyed directory for %s", name
);
1542 static int lxc_rmdir_onedev_wrapper(void *data
)
1544 char *arg
= (char *) data
;
1545 return lxc_rmdir_onedev(arg
, NULL
);
1548 static bool do_destroy_container(struct lxc_conf
*conf
) {
1550 if (userns_exec_1(conf
, bdev_destroy_wrapper
, conf
) < 0)
1554 return bdev_destroy(conf
);