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
36 #include <sys/param.h>
38 #include <sys/mount.h>
40 #include <sys/types.h>
41 #include <sys/socket.h>
42 #include <sys/prctl.h>
43 #include <sys/types.h>
46 #include <sys/syscall.h>
48 #if HAVE_SYS_CAPABILITY_H
49 #include <sys/capability.h>
52 #if !HAVE_DECL_PR_CAPBSET_DROP
53 #define PR_CAPBSET_DROP 24
69 #include "namespace.h"
70 #include "lxcseccomp.h"
76 lxc_log_define(lxc_start
, lxc
);
78 const struct ns_info ns_info
[LXC_NS_MAX
] = {
79 [LXC_NS_MNT
] = {"mnt", CLONE_NEWNS
},
80 [LXC_NS_PID
] = {"pid", CLONE_NEWPID
},
81 [LXC_NS_UTS
] = {"uts", CLONE_NEWUTS
},
82 [LXC_NS_IPC
] = {"ipc", CLONE_NEWIPC
},
83 [LXC_NS_USER
] = {"user", CLONE_NEWUSER
},
84 [LXC_NS_NET
] = {"net", CLONE_NEWNET
}
87 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
88 static bool do_destroy_container(struct lxc_conf
*conf
);
89 static int lxc_rmdir_onedev_wrapper(void *data
);
90 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
93 static void print_top_failing_dir(const char *path
)
95 size_t len
= strlen(path
);
96 char *copy
= alloca(len
+1), *p
, *e
, saved
;
102 while (p
< e
&& *p
== '/') p
++;
103 while (p
< e
&& *p
!= '/') p
++;
106 if (access(copy
, X_OK
)) {
107 SYSERROR("could not access %s. Please grant it 'x' " \
108 "access, or add an ACL for the container root.",
116 static void close_ns(int ns_fd
[LXC_NS_MAX
]) {
119 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
127 static int preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
) {
129 char path
[MAXPATHLEN
];
131 for (i
= 0; i
< LXC_NS_MAX
; i
++)
134 snprintf(path
, MAXPATHLEN
, "/proc/%d/ns", pid
);
135 if (access(path
, X_OK
)) {
136 WARN("Kernel does not support attach; preserve_ns ignored");
140 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
141 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
143 snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
,
144 ns_info
[i
].proc_name
);
145 ns_fd
[i
] = open(path
, O_RDONLY
| O_CLOEXEC
);
156 SYSERROR("failed to open '%s'", path
);
160 static int attach_ns(const int ns_fd
[LXC_NS_MAX
]) {
163 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
167 if (setns(ns_fd
[i
], 0) != 0)
173 SYSERROR("failed to set namespace '%s'", ns_info
[i
].proc_name
);
177 static int match_fd(int fd
)
179 return (fd
== 0 || fd
== 1 || fd
== 2);
183 * Check for any fds we need to close
184 * * if fd_to_ignore != -1, then if we find that fd open we will ignore it.
185 * * By default we warn about open fds we find.
186 * * If closeall is true, we will close open fds.
187 * * If lxc-start was passed "-C", then conf->close_all_fds will be true,
188 * in which case we also close all open fds.
189 * * A daemonized container will always pass closeall=true.
191 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
, int fd_to_ignore
)
193 struct dirent dirent
, *direntp
;
197 if (conf
&& conf
->close_all_fds
)
201 dir
= opendir("/proc/self/fd");
203 WARN("failed to open directory: %m");
209 while (!readdir_r(dir
, &dirent
, &direntp
)) {
213 if (!strcmp(direntp
->d_name
, "."))
216 if (!strcmp(direntp
->d_name
, ".."))
219 fd
= atoi(direntp
->d_name
);
221 if (fd
== fddir
|| fd
== lxc_log_fd
|| fd
== fd_to_ignore
)
224 if (current_config
&& fd
== current_config
->logfd
)
233 INFO("closed inherited fd %d", fd
);
236 WARN("inherited fd %d", fd
);
239 closedir(dir
); /* cannot fail */
243 static int setup_signal_fd(sigset_t
*oldmask
)
248 /* Block everything except serious error signals */
249 if (sigfillset(&mask
) ||
250 sigdelset(&mask
, SIGILL
) ||
251 sigdelset(&mask
, SIGSEGV
) ||
252 sigdelset(&mask
, SIGBUS
) ||
253 sigdelset(&mask
, SIGWINCH
) ||
254 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
255 SYSERROR("failed to set signal mask");
259 fd
= signalfd(-1, &mask
, 0);
261 SYSERROR("failed to create the signal fd");
265 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
266 SYSERROR("failed to set sigfd to close-on-exec");
271 DEBUG("sigchild handler set");
276 static int signal_handler(int fd
, uint32_t events
, void *data
,
277 struct lxc_epoll_descr
*descr
)
279 struct signalfd_siginfo siginfo
;
283 bool init_died
= false;
285 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
287 ERROR("failed to read signal info");
291 if (ret
!= sizeof(siginfo
)) {
292 ERROR("unexpected siginfo size");
296 // check whether init is running
298 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
299 if (ret
== 0 && info
.si_pid
== *pid
) {
303 if (siginfo
.ssi_signo
!= SIGCHLD
) {
304 kill(*pid
, siginfo
.ssi_signo
);
305 INFO("forwarded signal %d to pid %d", siginfo
.ssi_signo
, *pid
);
306 return init_died
? 1 : 0;
309 if (siginfo
.ssi_code
== CLD_STOPPED
||
310 siginfo
.ssi_code
== CLD_CONTINUED
) {
311 INFO("container init process was stopped/continued");
312 return init_died
? 1 : 0;
315 /* more robustness, protect ourself from a SIGCHLD sent
316 * by a process different from the container init
318 if (siginfo
.ssi_pid
!= *pid
) {
319 WARN("invalid pid for SIGCHLD");
320 return init_died
? 1 : 0;
323 DEBUG("container init process exited");
327 int lxc_set_state(const char *name
, struct lxc_handler
*handler
, lxc_state_t state
)
329 handler
->state
= state
;
330 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
334 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
336 int sigfd
= handler
->sigfd
;
337 int pid
= handler
->pid
;
338 struct lxc_epoll_descr descr
;
340 if (lxc_mainloop_open(&descr
)) {
341 ERROR("failed to create mainloop");
345 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
346 ERROR("failed to add handler for the signal");
347 goto out_mainloop_open
;
350 if (lxc_console_mainloop_add(&descr
, handler
)) {
351 ERROR("failed to add console handler to mainloop");
352 goto out_mainloop_open
;
355 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
356 ERROR("failed to add command handler to mainloop");
357 goto out_mainloop_open
;
360 if (handler
->conf
->need_utmp_watch
) {
361 #if HAVE_SYS_CAPABILITY_H
362 if (lxc_utmp_mainloop_add(&descr
, handler
)) {
363 ERROR("failed to add utmp handler to mainloop");
364 goto out_mainloop_open
;
367 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support");
371 return lxc_mainloop(&descr
, -1);
374 lxc_mainloop_close(&descr
);
380 struct lxc_handler
*lxc_init(const char *name
, struct lxc_conf
*conf
, const char *lxcpath
)
382 struct lxc_handler
*handler
;
384 handler
= malloc(sizeof(*handler
));
388 memset(handler
, 0, sizeof(*handler
));
390 handler
->ttysock
[0] = handler
->ttysock
[1] = -1;
391 handler
->conf
= conf
;
392 handler
->lxcpath
= lxcpath
;
397 handler
->name
= strdup(name
);
398 if (!handler
->name
) {
399 ERROR("failed to allocate memory");
403 if (lxc_cmd_init(name
, handler
, lxcpath
))
406 if (lxc_read_seccomp_config(conf
) != 0) {
407 ERROR("failed loading seccomp policy");
408 goto out_close_maincmd_fd
;
411 /* Begin by setting the state to STARTING */
412 if (lxc_set_state(name
, handler
, STARTING
)) {
413 ERROR("failed to set state '%s'", lxc_state2str(STARTING
));
414 goto out_close_maincmd_fd
;
417 /* Start of environment variable setup for hooks */
418 if (name
&& setenv("LXC_NAME", name
, 1)) {
419 SYSERROR("failed to set environment variable for container name");
421 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
422 SYSERROR("failed to set environment variable for config path");
424 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
425 SYSERROR("failed to set environment variable for rootfs mount");
427 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
428 SYSERROR("failed to set environment variable for rootfs mount");
430 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1)) {
431 SYSERROR("failed to set environment variable for console path");
433 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1)) {
434 SYSERROR("failed to set environment variable for console log");
436 /* End of environment variable setup for hooks */
438 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
439 ERROR("failed to run pre-start hooks for container '%s'.", name
);
443 /* the signal fd has to be created before forking otherwise
444 * if the child process exits before we setup the signal fd,
445 * the event will be lost and the command will be stuck */
446 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
447 if (handler
->sigfd
< 0) {
448 ERROR("failed to set sigchild fd handler");
452 /* do this after setting up signals since it might unblock SIGWINCH */
453 if (lxc_console_create(conf
)) {
454 ERROR("failed to create console");
455 goto out_restore_sigmask
;
458 if (ttys_shift_ids(conf
) < 0) {
459 ERROR("Failed to shift tty into container");
460 goto out_restore_sigmask
;
463 INFO("'%s' is initialized", name
);
467 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
469 lxc_delete_tty(&conf
->tty_info
);
471 lxc_set_state(name
, handler
, ABORTING
);
472 out_close_maincmd_fd
:
473 close(conf
->maincmd_fd
);
474 conf
->maincmd_fd
= -1;
477 handler
->name
= NULL
;
483 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
485 /* The STOPPING state is there for future cleanup code
486 * which can take awhile
488 lxc_set_state(name
, handler
, STOPPING
);
489 lxc_set_state(name
, handler
, STOPPED
);
491 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
))
492 ERROR("failed to run post-stop hooks for container '%s'.", name
);
494 /* reset mask set by setup_signal_fd */
495 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
496 WARN("failed to restore sigprocmask");
498 lxc_console_delete(&handler
->conf
->console
);
499 lxc_delete_tty(&handler
->conf
->tty_info
);
500 close(handler
->conf
->maincmd_fd
);
501 handler
->conf
->maincmd_fd
= -1;
503 if (handler
->ttysock
[0] != -1) {
504 close(handler
->ttysock
[0]);
505 close(handler
->ttysock
[1]);
507 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1) {
508 lxc_destroy_container_on_signal(handler
, name
);
510 cgroup_destroy(handler
);
514 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
518 lxc_set_state(name
, handler
, ABORTING
);
519 if (handler
->pid
> 0)
520 kill(handler
->pid
, SIGKILL
);
521 while ((ret
= waitpid(-1, &status
, 0)) > 0) ;
524 #include <sys/reboot.h>
525 #include <linux/reboot.h>
528 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
529 * in a child pid namespace if container reboot support exists.
530 * Otherwise, it will either succeed or return -EPERM.
532 static int container_reboot_supported(void *arg
)
538 if (ret
== -1 && errno
== EINVAL
)
543 static int must_drop_cap_sys_boot(struct lxc_conf
*conf
)
546 int ret
, cmd
, v
, flags
;
547 long stack_size
= 4096;
548 void *stack
= alloca(stack_size
);
552 f
= fopen("/proc/sys/kernel/ctrl-alt-del", "r");
554 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
558 ret
= fscanf(f
, "%d", &v
);
561 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
564 cmd
= v
? LINUX_REBOOT_CMD_CAD_ON
: LINUX_REBOOT_CMD_CAD_OFF
;
566 flags
= CLONE_NEWPID
| SIGCHLD
;
567 if (!lxc_list_empty(&conf
->id_map
))
568 flags
|= CLONE_NEWUSER
;
571 pid
= __clone2(container_reboot_supported
, stack
, stack_size
, flags
, &cmd
);
574 pid
= clone(container_reboot_supported
, stack
, flags
, &cmd
);
577 if (flags
& CLONE_NEWUSER
)
578 ERROR("failed to clone (%#x): %s (includes CLONE_NEWUSER)", flags
, strerror(errno
));
580 ERROR("failed to clone (%#x): %s", flags
, strerror(errno
));
583 if (wait(&status
) < 0) {
584 SYSERROR("unexpected wait error: %m");
588 if (WEXITSTATUS(status
) != 1)
595 * netpipe is used in the unprivileged case to transfer the ifindexes
596 * from parent to child
598 static int netpipe
= -1;
600 static inline int count_veths(struct lxc_list
*network
)
602 struct lxc_list
*iterator
;
603 struct lxc_netdev
*netdev
;
606 lxc_list_for_each(iterator
, network
) {
607 netdev
= iterator
->elem
;
608 if (netdev
->type
!= LXC_NET_VETH
)
615 static int read_unpriv_netifindex(struct lxc_list
*network
)
617 struct lxc_list
*iterator
;
618 struct lxc_netdev
*netdev
;
622 lxc_list_for_each(iterator
, network
) {
623 netdev
= iterator
->elem
;
624 if (netdev
->type
!= LXC_NET_VETH
)
626 if (!(netdev
->name
= malloc(IFNAMSIZ
))) {
627 ERROR("Out of memory");
631 if (read(netpipe
, netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
640 static int do_start(void *data
)
642 struct lxc_list
*iterator
;
643 struct lxc_handler
*handler
= data
;
645 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
646 SYSERROR("failed to set sigprocmask");
650 /* This prctl must be before the synchro, so if the parent
651 * dies before we set the parent death signal, we will detect
652 * its death with the synchro right after, otherwise we have
653 * a window where the parent can exit before we set the pdeath
654 * signal leading to a unsupervized container.
656 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
657 SYSERROR("failed to set pdeath signal");
661 lxc_sync_fini_parent(handler
);
663 /* don't leak the pinfd to the container */
664 if (handler
->pinfd
>= 0) {
665 close(handler
->pinfd
);
668 /* Tell the parent task it can begin to configure the
669 * container and wait for it to finish
671 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
674 if (read_unpriv_netifindex(&handler
->conf
->network
) < 0)
675 goto out_warn_father
;
678 * if we are in a new user namespace, become root there to have
679 * privilege over our namespace. When using lxc-execute we default to root,
680 * but this can be overriden using the lxc.init_uid and lxc.init_gid
681 * configuration options.
683 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
685 if (handler
->conf
->is_execute
&& handler
->conf
->init_gid
)
686 new_gid
= handler
->conf
->init_gid
;
689 if (handler
->conf
->is_execute
&& handler
->conf
->init_uid
)
690 new_uid
= handler
->conf
->init_uid
;
692 NOTICE("switching to gid/uid %d/%d in new user namespace", new_gid
, new_uid
);
693 if (setgid(new_gid
)) {
695 goto out_warn_father
;
697 if (setuid(new_uid
)) {
699 goto out_warn_father
;
701 if (setgroups(0, NULL
)) {
702 SYSERROR("setgroups");
703 goto out_warn_father
;
707 if (access(handler
->lxcpath
, X_OK
)) {
708 print_top_failing_dir(handler
->lxcpath
);
709 goto out_warn_father
;
712 #if HAVE_SYS_CAPABILITY_H
713 if (handler
->conf
->need_utmp_watch
) {
714 if (prctl(PR_CAPBSET_DROP
, CAP_SYS_BOOT
, 0, 0, 0)) {
715 SYSERROR("failed to remove CAP_SYS_BOOT capability");
716 goto out_warn_father
;
718 DEBUG("Dropped cap_sys_boot");
722 /* Setup the container, ip, names, utsname, ... */
723 if (lxc_setup(handler
)) {
724 ERROR("failed to setup the container");
725 goto out_warn_father
;
728 /* ask father to setup cgroups and wait for him to finish */
729 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
732 /* Set the label to change to when we exec(2) the container's init */
733 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
734 goto out_warn_father
;
736 /* Some init's such as busybox will set sane tty settings on stdin,
737 * stdout, stderr which it thinks is the console. We already set them
738 * the way we wanted on the real terminal, and we want init to do its
739 * setup on its console ie. the pty allocated in lxc_console_create()
740 * so make sure that that pty is stdin,stdout,stderr.
742 if (lxc_console_set_stdfds(handler
) < 0)
743 goto out_warn_father
;
745 /* If we mounted a temporary proc, then unmount it now */
746 tmp_proc_unmount(handler
->conf
);
748 if (lxc_seccomp_load(handler
->conf
) != 0)
749 goto out_warn_father
;
751 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
752 ERROR("failed to run start hooks for container '%s'.", handler
->name
);
753 goto out_warn_father
;
756 /* The clearenv() and putenv() calls have been moved here
757 * to allow us to use environment variables passed to the various
758 * hooks, such as the start hook above. Not all of the
759 * variables like CONFIG_PATH or ROOTFS are valid in this
760 * context but others are. */
762 SYSERROR("failed to clear environment");
763 /* don't error out though */
766 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
767 if (putenv((char *)iterator
->elem
)) {
768 SYSERROR("failed to set environment variable '%s'", (char *)iterator
->elem
);
769 goto out_warn_father
;
773 if (putenv("container=lxc")) {
774 SYSERROR("failed to set environment variable 'container=lxc'");
775 goto out_warn_father
;
778 if (handler
->conf
->pty_names
) {
779 if (putenv(handler
->conf
->pty_names
)) {
780 SYSERROR("failed to set environment variable for container ptys");
781 goto out_warn_father
;
785 close(handler
->sigfd
);
787 if (handler
->backgrounded
&& null_stdfds() < 0)
788 goto out_warn_father
;
790 /* after this call, we are in error because this
791 * ops should not return as it execs */
792 handler
->ops
->start(handler
, handler
->data
);
795 /* we want the parent to know something went wrong, so any
796 * value other than what it expects is ok. */
797 lxc_sync_wake_parent(handler
, LXC_SYNC_POST_CONFIGURE
);
801 static int save_phys_nics(struct lxc_conf
*conf
)
803 struct lxc_list
*iterator
;
805 lxc_list_for_each(iterator
, &conf
->network
) {
806 struct lxc_netdev
*netdev
= iterator
->elem
;
808 if (netdev
->type
!= LXC_NET_PHYS
)
810 conf
->saved_nics
= realloc(conf
->saved_nics
,
811 (conf
->num_savednics
+1)*sizeof(struct saved_nic
));
812 if (!conf
->saved_nics
) {
813 SYSERROR("failed to allocate memory");
816 conf
->saved_nics
[conf
->num_savednics
].ifindex
= netdev
->ifindex
;
817 conf
->saved_nics
[conf
->num_savednics
].orig_name
= strdup(netdev
->link
);
818 if (!conf
->saved_nics
[conf
->num_savednics
].orig_name
) {
819 SYSERROR("failed to allocate memory");
822 INFO("stored saved_nic #%d idx %d name %s", conf
->num_savednics
,
823 conf
->saved_nics
[conf
->num_savednics
].ifindex
,
824 conf
->saved_nics
[conf
->num_savednics
].orig_name
);
825 conf
->num_savednics
++;
831 static int recv_fd(int sock
, int *fd
)
833 if (lxc_abstract_unix_recv_fd(sock
, fd
, NULL
, 0) < 0) {
834 SYSERROR("Error receiving tty fd from child");
842 static int recv_ttys_from_child(struct lxc_handler
*handler
)
844 struct lxc_conf
*conf
= handler
->conf
;
845 int i
, sock
= handler
->ttysock
[1];
846 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
851 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
)*conf
->tty
);
852 if (!tty_info
->pty_info
) {
853 SYSERROR("failed to allocate pty_info");
857 for (i
= 0; i
< conf
->tty
; i
++) {
858 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
860 if (recv_fd(sock
, &pty_info
->slave
) < 0 ||
861 recv_fd(sock
, &pty_info
->master
) < 0) {
862 ERROR("Error receiving tty info from child");
866 tty_info
->nbtty
= conf
->tty
;
871 void resolve_clone_flags(struct lxc_handler
*handler
)
873 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
875 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
876 INFO("Cloning a new user namespace");
877 handler
->clone_flags
|= CLONE_NEWUSER
;
880 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
881 if (!lxc_requests_empty_network(handler
))
882 handler
->clone_flags
|= CLONE_NEWNET
;
884 INFO("Inheriting a net namespace");
887 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1) {
888 handler
->clone_flags
|= CLONE_NEWIPC
;
890 INFO("Inheriting an IPC namespace");
893 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1) {
894 handler
->clone_flags
|= CLONE_NEWUTS
;
896 INFO("Inheriting a UTS namespace");
900 static int lxc_spawn(struct lxc_handler
*handler
)
902 int failed_before_rename
= 0;
903 const char *name
= handler
->name
;
904 bool cgroups_connected
= false;
905 int saved_ns_fd
[LXC_NS_MAX
];
906 int preserve_mask
= 0, i
;
907 int netpipepair
[2], nveths
;
911 for (i
= 0; i
< LXC_NS_MAX
; i
++)
912 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
913 preserve_mask
|= ns_info
[i
].clone_flag
;
915 if (lxc_sync_init(handler
))
918 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, handler
->ttysock
) < 0) {
919 lxc_sync_fini(handler
);
923 resolve_clone_flags(handler
);
925 if (handler
->clone_flags
& CLONE_NEWNET
) {
926 if (!lxc_list_empty(&handler
->conf
->network
)) {
928 /* Find gateway addresses from the link device, which is
929 * no longer accessible inside the container. Do this
930 * before creating network interfaces, since goto
931 * out_delete_net does not work before lxc_clone. */
932 if (lxc_find_gateway_addresses(handler
)) {
933 ERROR("failed to find gateway addresses");
934 lxc_sync_fini(handler
);
938 /* that should be done before the clone because we will
939 * fill the netdev index and use them in the child
941 if (lxc_create_network(handler
)) {
942 ERROR("failed to create the network");
943 lxc_sync_fini(handler
);
948 if (save_phys_nics(handler
->conf
)) {
949 ERROR("failed to save physical nic info");
954 if (!cgroup_init(handler
)) {
955 ERROR("failed initializing cgroup support");
959 cgroups_connected
= true;
961 if (!cgroup_create(handler
)) {
962 ERROR("failed creating cgroups");
967 * if the rootfs is not a blockdev, prevent the container from
968 * marking it readonly.
970 * if the container is unprivileged then skip rootfs pinning
972 if (lxc_list_empty(&handler
->conf
->id_map
)) {
973 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
974 if (handler
->pinfd
== -1)
975 INFO("failed to pin the container's rootfs");
978 if (preserve_ns(saved_ns_fd
, preserve_mask
, getpid()) < 0)
980 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
983 if (am_unpriv() && (nveths
= count_veths(&handler
->conf
->network
))) {
984 if (pipe(netpipepair
) < 0) {
985 SYSERROR("Error creating pipe");
988 /* store netpipe in the global var for do_start's use */
989 netpipe
= netpipepair
[0];
992 /* Create a process in a new set of namespaces */
993 handler
->pid
= lxc_clone(do_start
, handler
, handler
->clone_flags
);
994 if (handler
->pid
< 0) {
995 SYSERROR("failed to fork into a new namespace");
999 if (attach_ns(saved_ns_fd
))
1000 WARN("failed to restore saved namespaces");
1002 lxc_sync_fini_child(handler
);
1004 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
))
1005 failed_before_rename
= 1;
1007 if (!cgroup_create_legacy(handler
)) {
1008 ERROR("failed to setup the legacy cgroups for %s", name
);
1009 goto out_delete_net
;
1011 if (!cgroup_setup_limits(handler
, false)) {
1012 ERROR("failed to setup the cgroup limits for '%s'", name
);
1013 goto out_delete_net
;
1016 if (!cgroup_enter(handler
))
1017 goto out_delete_net
;
1019 if (!cgroup_chown(handler
))
1020 goto out_delete_net
;
1022 if (failed_before_rename
)
1023 goto out_delete_net
;
1025 /* Create the network configuration */
1026 if (handler
->clone_flags
& CLONE_NEWNET
) {
1027 if (lxc_assign_network(&handler
->conf
->network
, handler
->pid
)) {
1028 ERROR("failed to create the configured network");
1029 goto out_delete_net
;
1033 if (netpipe
!= -1) {
1034 struct lxc_list
*iterator
;
1035 struct lxc_netdev
*netdev
;
1038 lxc_list_for_each(iterator
, &handler
->conf
->network
) {
1039 netdev
= iterator
->elem
;
1040 if (netdev
->type
!= LXC_NET_VETH
)
1042 if (write(netpipepair
[1], netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
1043 ERROR("Error writing veth name to container");
1044 goto out_delete_net
;
1047 close(netpipepair
[1]);
1050 /* map the container uids - the container became an invalid
1051 * userid the moment it was cloned with CLONE_NEWUSER - this
1052 * call doesn't change anything immediately, but allows the
1053 * container to setuid(0) (0 being mapped to something else on
1054 * the host) later to become a valid uid again */
1055 if (lxc_map_ids(&handler
->conf
->id_map
, handler
->pid
)) {
1056 ERROR("failed to set up id mapping");
1057 goto out_delete_net
;
1060 /* Tell the child to continue its initialization. we'll get
1061 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
1063 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1064 goto out_delete_net
;
1066 if (!cgroup_setup_limits(handler
, true)) {
1067 ERROR("failed to setup the devices cgroup for '%s'", name
);
1068 goto out_delete_net
;
1071 cgroup_disconnect();
1072 cgroups_connected
= false;
1074 /* read tty fds allocated by child */
1075 if (recv_ttys_from_child(handler
) < 0) {
1076 ERROR("failed to receive tty info from child");
1077 goto out_delete_net
;
1080 /* Tell the child to complete its initialization and wait for
1081 * it to exec or return an error. (the child will never
1082 * return LXC_SYNC_POST_CGROUP+1. It will either close the
1083 * sync pipe, causing lxc_sync_barrier_child to return
1084 * success, or return a different value, causing us to error
1087 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1090 if (detect_shared_rootfs())
1091 umount2(handler
->conf
->rootfs
.mount
, MNT_DETACH
);
1093 if (handler
->ops
->post_start(handler
, handler
->data
))
1096 if (lxc_set_state(name
, handler
, RUNNING
)) {
1097 ERROR("failed to set state to %s",
1098 lxc_state2str(RUNNING
));
1102 lxc_sync_fini(handler
);
1107 if (cgroups_connected
)
1108 cgroup_disconnect();
1109 if (handler
->clone_flags
& CLONE_NEWNET
)
1110 lxc_delete_network(handler
);
1112 lxc_abort(name
, handler
);
1113 lxc_sync_fini(handler
);
1114 if (handler
->pinfd
>= 0) {
1115 close(handler
->pinfd
);
1116 handler
->pinfd
= -1;
1122 int get_netns_fd(int pid
)
1124 char path
[MAXPATHLEN
];
1127 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/net", pid
);
1128 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1129 WARN("Failed to pin netns file for pid %d", pid
);
1133 fd
= open(path
, O_RDONLY
);
1135 WARN("Failed to pin netns file %s for pid %d: %s",
1136 path
, pid
, strerror(errno
));
1142 int __lxc_start(const char *name
, struct lxc_conf
*conf
,
1143 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1146 struct lxc_handler
*handler
;
1151 handler
= lxc_init(name
, conf
, lxcpath
);
1153 ERROR("failed to initialize the container");
1157 handler
->data
= data
;
1158 handler
->backgrounded
= backgrounded
;
1160 if (must_drop_cap_sys_boot(handler
->conf
)) {
1161 #if HAVE_SYS_CAPABILITY_H
1162 DEBUG("Dropping cap_sys_boot");
1164 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
1167 DEBUG("Not dropping cap_sys_boot or watching utmp");
1168 handler
->conf
->need_utmp_watch
= 0;
1171 if (!attach_block_device(handler
->conf
)) {
1172 ERROR("Failure attaching block device");
1173 goto out_fini_nonet
;
1176 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1177 /* if the backing store is a device, mount it here and now */
1178 if (rootfs_is_blockdev(conf
)) {
1179 if (unshare(CLONE_NEWNS
) < 0) {
1180 ERROR("Error unsharing mounts");
1181 goto out_fini_nonet
;
1183 remount_all_slave();
1184 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1185 ERROR("Error setting up rootfs mount as root before spawn");
1186 goto out_fini_nonet
;
1188 INFO("Set up container rootfs as host root");
1192 err
= lxc_spawn(handler
);
1194 ERROR("failed to spawn '%s'", name
);
1195 goto out_detach_blockdev
;
1198 handler
->conf
->reboot
= 0;
1200 netnsfd
= get_netns_fd(handler
->pid
);
1202 err
= lxc_poll(name
, handler
);
1204 ERROR("mainloop exited with an error");
1210 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1214 * If the child process exited but was not signaled,
1215 * it didn't call reboot. This should mean it was an
1216 * lxc-execute which simply exited. In any case, treat
1219 if (WIFSIGNALED(status
)) {
1220 switch(WTERMSIG(status
)) {
1221 case SIGINT
: /* halt */
1222 DEBUG("Container halting");
1224 case SIGHUP
: /* reboot */
1225 DEBUG("Container rebooting");
1226 handler
->conf
->reboot
= 1;
1228 case SIGSYS
: /* seccomp */
1229 DEBUG("Container violated its seccomp policy");
1232 DEBUG("unknown exit status for init: %d", WTERMSIG(status
));
1237 DEBUG("Pushing physical nics back to host namespace");
1238 lxc_rename_phys_nics_on_shutdown(netnsfd
, handler
->conf
);
1240 DEBUG("Tearing down virtual network devices used by container");
1241 lxc_delete_network(handler
);
1246 if (handler
->pinfd
>= 0) {
1247 close(handler
->pinfd
);
1248 handler
->pinfd
= -1;
1251 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1252 err
= lxc_error_set_and_log(handler
->pid
, status
);
1254 lxc_delete_network(handler
);
1256 out_detach_blockdev
:
1257 detach_block_device(handler
->conf
);
1260 lxc_fini(name
, handler
);
1264 lxc_abort(name
, handler
);
1272 static int start(struct lxc_handler
*handler
, void* data
)
1274 struct start_args
*arg
= data
;
1276 NOTICE("exec'ing '%s'", arg
->argv
[0]);
1278 execvp(arg
->argv
[0], arg
->argv
);
1279 SYSERROR("failed to exec %s", arg
->argv
[0]);
1283 static int post_start(struct lxc_handler
*handler
, void* data
)
1285 struct start_args
*arg
= data
;
1287 NOTICE("'%s' started with pid '%d'", arg
->argv
[0], handler
->pid
);
1291 static struct lxc_operations start_ops
= {
1293 .post_start
= post_start
1296 int lxc_start(const char *name
, char *const argv
[], struct lxc_conf
*conf
,
1297 const char *lxcpath
, bool backgrounded
)
1299 struct start_args start_arg
= {
1303 conf
->need_utmp_watch
= 1;
1304 return __lxc_start(name
, conf
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1307 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1310 char destroy
[MAXPATHLEN
];
1313 struct lxc_container
*c
;
1314 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1315 bret
= do_destroy_container(handler
->conf
);
1317 ERROR("Error destroying rootfs for %s", name
);
1321 INFO("Destroyed rootfs for %s", name
);
1323 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1324 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1325 ERROR("Error printing path for %s", name
);
1326 ERROR("Error destroying directory for %s", name
);
1330 c
= lxc_container_new(name
, handler
->lxcpath
);
1332 if (container_disk_lock(c
)) {
1333 INFO("Could not update lxc_snapshots file");
1334 lxc_container_put(c
);
1336 mod_all_rdeps(c
, false);
1337 container_disk_unlock(c
);
1338 lxc_container_put(c
);
1343 ret
= userns_exec_1(handler
->conf
, lxc_rmdir_onedev_wrapper
, destroy
);
1345 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1348 ERROR("Error destroying directory for %s", name
);
1351 INFO("Destroyed directory for %s", name
);
1354 static int lxc_rmdir_onedev_wrapper(void *data
)
1356 char *arg
= (char *) data
;
1357 return lxc_rmdir_onedev(arg
, NULL
);
1360 static bool do_destroy_container(struct lxc_conf
*conf
) {
1362 if (userns_exec_1(conf
, bdev_destroy_wrapper
, conf
) < 0)
1366 return bdev_destroy(conf
);