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"
75 lxc_log_define(lxc_start
, lxc
);
77 const struct ns_info ns_info
[LXC_NS_MAX
] = {
78 [LXC_NS_MNT
] = {"mnt", CLONE_NEWNS
},
79 [LXC_NS_PID
] = {"pid", CLONE_NEWPID
},
80 [LXC_NS_UTS
] = {"uts", CLONE_NEWUTS
},
81 [LXC_NS_IPC
] = {"ipc", CLONE_NEWIPC
},
82 [LXC_NS_USER
] = {"user", CLONE_NEWUSER
},
83 [LXC_NS_NET
] = {"net", CLONE_NEWNET
}
86 static void print_top_failing_dir(const char *path
)
88 size_t len
= strlen(path
);
89 char *copy
= alloca(len
+1), *p
, *e
, saved
;
95 while (p
< e
&& *p
== '/') p
++;
96 while (p
< e
&& *p
!= '/') p
++;
99 if (access(copy
, X_OK
)) {
100 SYSERROR("could not access %s. Please grant it 'x' " \
101 "access, or add an ACL for the container root.",
109 static void close_ns(int ns_fd
[LXC_NS_MAX
]) {
112 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
120 static int preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
) {
122 char path
[MAXPATHLEN
];
124 for (i
= 0; i
< LXC_NS_MAX
; i
++)
127 if (access("/proc/self/ns", X_OK
)) {
128 WARN("Kernel does not support attach; preserve_ns ignored");
132 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
133 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
135 snprintf(path
, MAXPATHLEN
, "/proc/self/ns/%s", ns_info
[i
].proc_name
);
136 ns_fd
[i
] = open(path
, O_RDONLY
| O_CLOEXEC
);
147 SYSERROR("failed to open '%s'", path
);
151 static int attach_ns(const int ns_fd
[LXC_NS_MAX
]) {
154 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
158 if (setns(ns_fd
[i
], 0) != 0)
164 SYSERROR("failed to set namespace '%s'", ns_info
[i
].proc_name
);
168 static int match_fd(int fd
)
170 return (fd
== 0 || fd
== 1 || fd
== 2);
174 * Check for any fds we need to close
175 * * if fd_to_ignore != -1, then if we find that fd open we will ignore it.
176 * * By default we warn about open fds we find.
177 * * If closeall is true, we will close open fds.
178 * * If lxc-start was passed "-C", then conf->close_all_fds will be true,
179 * in which case we also close all open fds.
180 * * A daemonized container will always pass closeall=true.
182 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
, int fd_to_ignore
)
184 struct dirent dirent
, *direntp
;
188 if (conf
&& conf
->close_all_fds
)
192 dir
= opendir("/proc/self/fd");
194 WARN("failed to open directory: %m");
200 while (!readdir_r(dir
, &dirent
, &direntp
)) {
204 if (!strcmp(direntp
->d_name
, "."))
207 if (!strcmp(direntp
->d_name
, ".."))
210 fd
= atoi(direntp
->d_name
);
212 if (fd
== fddir
|| fd
== lxc_log_fd
|| fd
== fd_to_ignore
)
215 if (current_config
&& fd
== current_config
->logfd
)
224 INFO("closed inherited fd %d", fd
);
227 WARN("inherited fd %d", fd
);
230 closedir(dir
); /* cannot fail */
234 static int setup_signal_fd(sigset_t
*oldmask
)
239 /* Block everything except serious error signals */
240 if (sigfillset(&mask
) ||
241 sigdelset(&mask
, SIGILL
) ||
242 sigdelset(&mask
, SIGSEGV
) ||
243 sigdelset(&mask
, SIGBUS
) ||
244 sigdelset(&mask
, SIGWINCH
) ||
245 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
246 SYSERROR("failed to set signal mask");
250 fd
= signalfd(-1, &mask
, 0);
252 SYSERROR("failed to create the signal fd");
256 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
257 SYSERROR("failed to set sigfd to close-on-exec");
262 DEBUG("sigchild handler set");
267 static int signal_handler(int fd
, uint32_t events
, void *data
,
268 struct lxc_epoll_descr
*descr
)
270 struct signalfd_siginfo siginfo
;
274 bool init_died
= false;
276 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
278 ERROR("failed to read signal info");
282 if (ret
!= sizeof(siginfo
)) {
283 ERROR("unexpected siginfo size");
287 // check whether init is running
289 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
290 if (ret
== 0 && info
.si_pid
== *pid
) {
294 if (siginfo
.ssi_signo
!= SIGCHLD
) {
295 kill(*pid
, siginfo
.ssi_signo
);
296 INFO("forwarded signal %d to pid %d", siginfo
.ssi_signo
, *pid
);
297 return init_died
? 1 : 0;
300 if (siginfo
.ssi_code
== CLD_STOPPED
||
301 siginfo
.ssi_code
== CLD_CONTINUED
) {
302 INFO("container init process was stopped/continued");
303 return init_died
? 1 : 0;
306 /* more robustness, protect ourself from a SIGCHLD sent
307 * by a process different from the container init
309 if (siginfo
.ssi_pid
!= *pid
) {
310 WARN("invalid pid for SIGCHLD");
311 return init_died
? 1 : 0;
314 DEBUG("container init process exited");
318 int lxc_set_state(const char *name
, struct lxc_handler
*handler
, lxc_state_t state
)
320 handler
->state
= state
;
321 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
325 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
327 int sigfd
= handler
->sigfd
;
328 int pid
= handler
->pid
;
329 struct lxc_epoll_descr descr
;
331 if (lxc_mainloop_open(&descr
)) {
332 ERROR("failed to create mainloop");
336 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
337 ERROR("failed to add handler for the signal");
338 goto out_mainloop_open
;
341 if (lxc_console_mainloop_add(&descr
, handler
)) {
342 ERROR("failed to add console handler to mainloop");
343 goto out_mainloop_open
;
346 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
347 ERROR("failed to add command handler to mainloop");
348 goto out_mainloop_open
;
351 if (handler
->conf
->need_utmp_watch
) {
352 #if HAVE_SYS_CAPABILITY_H
353 if (lxc_utmp_mainloop_add(&descr
, handler
)) {
354 ERROR("failed to add utmp handler to mainloop");
355 goto out_mainloop_open
;
358 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support");
362 return lxc_mainloop(&descr
, -1);
365 lxc_mainloop_close(&descr
);
371 struct lxc_handler
*lxc_init(const char *name
, struct lxc_conf
*conf
, const char *lxcpath
)
373 struct lxc_handler
*handler
;
375 handler
= malloc(sizeof(*handler
));
379 memset(handler
, 0, sizeof(*handler
));
381 handler
->ttysock
[0] = handler
->ttysock
[1] = -1;
382 handler
->conf
= conf
;
383 handler
->lxcpath
= lxcpath
;
388 handler
->name
= strdup(name
);
389 if (!handler
->name
) {
390 ERROR("failed to allocate memory");
394 if (lxc_cmd_init(name
, handler
, lxcpath
))
397 if (lxc_read_seccomp_config(conf
) != 0) {
398 ERROR("failed loading seccomp policy");
399 goto out_close_maincmd_fd
;
402 /* Begin by setting the state to STARTING */
403 if (lxc_set_state(name
, handler
, STARTING
)) {
404 ERROR("failed to set state '%s'", lxc_state2str(STARTING
));
405 goto out_close_maincmd_fd
;
408 /* Start of environment variable setup for hooks */
409 if (name
&& setenv("LXC_NAME", name
, 1)) {
410 SYSERROR("failed to set environment variable for container name");
412 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
413 SYSERROR("failed to set environment variable for config path");
415 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
416 SYSERROR("failed to set environment variable for rootfs mount");
418 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
419 SYSERROR("failed to set environment variable for rootfs mount");
421 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1)) {
422 SYSERROR("failed to set environment variable for console path");
424 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1)) {
425 SYSERROR("failed to set environment variable for console log");
427 /* End of environment variable setup for hooks */
429 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
430 ERROR("failed to run pre-start hooks for container '%s'.", name
);
434 /* the signal fd has to be created before forking otherwise
435 * if the child process exits before we setup the signal fd,
436 * the event will be lost and the command will be stuck */
437 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
438 if (handler
->sigfd
< 0) {
439 ERROR("failed to set sigchild fd handler");
443 /* do this after setting up signals since it might unblock SIGWINCH */
444 if (lxc_console_create(conf
)) {
445 ERROR("failed to create console");
446 goto out_restore_sigmask
;
449 if (ttys_shift_ids(conf
) < 0) {
450 ERROR("Failed to shift tty into container");
451 goto out_restore_sigmask
;
454 INFO("'%s' is initialized", name
);
458 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
460 lxc_delete_tty(&conf
->tty_info
);
462 lxc_set_state(name
, handler
, ABORTING
);
463 out_close_maincmd_fd
:
464 close(conf
->maincmd_fd
);
465 conf
->maincmd_fd
= -1;
468 handler
->name
= NULL
;
474 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
476 /* The STOPPING state is there for future cleanup code
477 * which can take awhile
479 lxc_set_state(name
, handler
, STOPPING
);
480 lxc_set_state(name
, handler
, STOPPED
);
482 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
))
483 ERROR("failed to run post-stop hooks for container '%s'.", name
);
485 /* reset mask set by setup_signal_fd */
486 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
487 WARN("failed to restore sigprocmask");
489 lxc_console_delete(&handler
->conf
->console
);
490 lxc_delete_tty(&handler
->conf
->tty_info
);
491 close(handler
->conf
->maincmd_fd
);
492 handler
->conf
->maincmd_fd
= -1;
494 if (handler
->ttysock
[0] != -1) {
495 close(handler
->ttysock
[0]);
496 close(handler
->ttysock
[1]);
498 cgroup_destroy(handler
);
502 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
506 lxc_set_state(name
, handler
, ABORTING
);
507 if (handler
->pid
> 0)
508 kill(handler
->pid
, SIGKILL
);
509 while ((ret
= waitpid(-1, &status
, 0)) > 0) ;
512 #include <sys/reboot.h>
513 #include <linux/reboot.h>
516 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
517 * in a child pid namespace if container reboot support exists.
518 * Otherwise, it will either succeed or return -EPERM.
520 static int container_reboot_supported(void *arg
)
526 if (ret
== -1 && errno
== EINVAL
)
531 static int must_drop_cap_sys_boot(struct lxc_conf
*conf
)
534 int ret
, cmd
, v
, flags
;
535 long stack_size
= 4096;
536 void *stack
= alloca(stack_size
);
540 f
= fopen("/proc/sys/kernel/ctrl-alt-del", "r");
542 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
546 ret
= fscanf(f
, "%d", &v
);
549 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
552 cmd
= v
? LINUX_REBOOT_CMD_CAD_ON
: LINUX_REBOOT_CMD_CAD_OFF
;
554 flags
= CLONE_NEWPID
| SIGCHLD
;
555 if (!lxc_list_empty(&conf
->id_map
))
556 flags
|= CLONE_NEWUSER
;
559 pid
= __clone2(container_reboot_supported
, stack
, stack_size
, flags
, &cmd
);
562 pid
= clone(container_reboot_supported
, stack
, flags
, &cmd
);
565 if (flags
& CLONE_NEWUSER
)
566 ERROR("failed to clone (%#x): %s (includes CLONE_NEWUSER)", flags
, strerror(errno
));
568 ERROR("failed to clone (%#x): %s", flags
, strerror(errno
));
571 if (wait(&status
) < 0) {
572 SYSERROR("unexpected wait error: %m");
576 if (WEXITSTATUS(status
) != 1)
583 * netpipe is used in the unprivileged case to transfer the ifindexes
584 * from parent to child
586 static int netpipe
= -1;
588 static inline int count_veths(struct lxc_list
*network
)
590 struct lxc_list
*iterator
;
591 struct lxc_netdev
*netdev
;
594 lxc_list_for_each(iterator
, network
) {
595 netdev
= iterator
->elem
;
596 if (netdev
->type
!= LXC_NET_VETH
)
603 static int read_unpriv_netifindex(struct lxc_list
*network
)
605 struct lxc_list
*iterator
;
606 struct lxc_netdev
*netdev
;
610 lxc_list_for_each(iterator
, network
) {
611 netdev
= iterator
->elem
;
612 if (netdev
->type
!= LXC_NET_VETH
)
614 if (!(netdev
->name
= malloc(IFNAMSIZ
))) {
615 ERROR("Out of memory");
619 if (read(netpipe
, netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
628 static int do_start(void *data
)
630 struct lxc_list
*iterator
;
631 struct lxc_handler
*handler
= data
;
633 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
634 SYSERROR("failed to set sigprocmask");
638 /* This prctl must be before the synchro, so if the parent
639 * dies before we set the parent death signal, we will detect
640 * its death with the synchro right after, otherwise we have
641 * a window where the parent can exit before we set the pdeath
642 * signal leading to a unsupervized container.
644 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
645 SYSERROR("failed to set pdeath signal");
649 lxc_sync_fini_parent(handler
);
651 /* don't leak the pinfd to the container */
652 if (handler
->pinfd
>= 0) {
653 close(handler
->pinfd
);
656 /* Tell the parent task it can begin to configure the
657 * container and wait for it to finish
659 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
662 if (read_unpriv_netifindex(&handler
->conf
->network
) < 0)
663 goto out_warn_father
;
666 * if we are in a new user namespace, become root there to have
667 * privilege over our namespace
669 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
670 NOTICE("switching to gid/uid 0 in new user namespace");
673 goto out_warn_father
;
677 goto out_warn_father
;
679 if (setgroups(0, NULL
)) {
680 SYSERROR("setgroups");
681 goto out_warn_father
;
685 if (access(handler
->lxcpath
, X_OK
)) {
686 print_top_failing_dir(handler
->lxcpath
);
687 goto out_warn_father
;
690 #if HAVE_SYS_CAPABILITY_H
691 if (handler
->conf
->need_utmp_watch
) {
692 if (prctl(PR_CAPBSET_DROP
, CAP_SYS_BOOT
, 0, 0, 0)) {
693 SYSERROR("failed to remove CAP_SYS_BOOT capability");
694 goto out_warn_father
;
696 DEBUG("Dropped cap_sys_boot");
700 /* Setup the container, ip, names, utsname, ... */
701 if (lxc_setup(handler
)) {
702 ERROR("failed to setup the container");
703 goto out_warn_father
;
706 /* ask father to setup cgroups and wait for him to finish */
707 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
710 /* Set the label to change to when we exec(2) the container's init */
711 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
712 goto out_warn_father
;
714 /* Some init's such as busybox will set sane tty settings on stdin,
715 * stdout, stderr which it thinks is the console. We already set them
716 * the way we wanted on the real terminal, and we want init to do its
717 * setup on its console ie. the pty allocated in lxc_console_create()
718 * so make sure that that pty is stdin,stdout,stderr.
720 if (lxc_console_set_stdfds(handler
) < 0)
721 goto out_warn_father
;
723 /* If we mounted a temporary proc, then unmount it now */
724 tmp_proc_unmount(handler
->conf
);
726 if (lxc_seccomp_load(handler
->conf
) != 0)
727 goto out_warn_father
;
729 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
730 ERROR("failed to run start hooks for container '%s'.", handler
->name
);
731 goto out_warn_father
;
734 /* The clearenv() and putenv() calls have been moved here
735 * to allow us to use environment variables passed to the various
736 * hooks, such as the start hook above. Not all of the
737 * variables like CONFIG_PATH or ROOTFS are valid in this
738 * context but others are. */
740 SYSERROR("failed to clear environment");
741 /* don't error out though */
744 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
745 if (putenv((char *)iterator
->elem
)) {
746 SYSERROR("failed to set environment variable '%s'", (char *)iterator
->elem
);
747 goto out_warn_father
;
751 if (putenv("container=lxc")) {
752 SYSERROR("failed to set environment variable 'container=lxc'");
753 goto out_warn_father
;
756 if (handler
->conf
->pty_names
) {
757 if (putenv(handler
->conf
->pty_names
)) {
758 SYSERROR("failed to set environment variable for container ptys");
759 goto out_warn_father
;
763 close(handler
->sigfd
);
765 if (handler
->backgrounded
&& null_stdfds() < 0)
766 goto out_warn_father
;
768 /* after this call, we are in error because this
769 * ops should not return as it execs */
770 handler
->ops
->start(handler
, handler
->data
);
773 /* we want the parent to know something went wrong, so any
774 * value other than what it expects is ok. */
775 lxc_sync_wake_parent(handler
, LXC_SYNC_POST_CONFIGURE
);
779 static int save_phys_nics(struct lxc_conf
*conf
)
781 struct lxc_list
*iterator
;
783 lxc_list_for_each(iterator
, &conf
->network
) {
784 struct lxc_netdev
*netdev
= iterator
->elem
;
786 if (netdev
->type
!= LXC_NET_PHYS
)
788 conf
->saved_nics
= realloc(conf
->saved_nics
,
789 (conf
->num_savednics
+1)*sizeof(struct saved_nic
));
790 if (!conf
->saved_nics
) {
791 SYSERROR("failed to allocate memory");
794 conf
->saved_nics
[conf
->num_savednics
].ifindex
= netdev
->ifindex
;
795 conf
->saved_nics
[conf
->num_savednics
].orig_name
= strdup(netdev
->link
);
796 if (!conf
->saved_nics
[conf
->num_savednics
].orig_name
) {
797 SYSERROR("failed to allocate memory");
800 INFO("stored saved_nic #%d idx %d name %s", conf
->num_savednics
,
801 conf
->saved_nics
[conf
->num_savednics
].ifindex
,
802 conf
->saved_nics
[conf
->num_savednics
].orig_name
);
803 conf
->num_savednics
++;
809 static int recv_fd(int sock
, int *fd
)
811 if (lxc_abstract_unix_recv_fd(sock
, fd
, NULL
, 0) < 0) {
812 SYSERROR("Error receiving tty fd from child");
820 static int recv_ttys_from_child(struct lxc_handler
*handler
)
822 struct lxc_conf
*conf
= handler
->conf
;
823 int i
, sock
= handler
->ttysock
[1];
824 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
829 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
)*conf
->tty
);
830 if (!tty_info
->pty_info
) {
831 SYSERROR("failed to allocate pty_info");
835 for (i
= 0; i
< conf
->tty
; i
++) {
836 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
838 if (recv_fd(sock
, &pty_info
->slave
) < 0 ||
839 recv_fd(sock
, &pty_info
->master
) < 0) {
840 ERROR("Error receiving tty info from child");
844 tty_info
->nbtty
= conf
->tty
;
849 void resolve_clone_flags(struct lxc_handler
*handler
)
851 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
853 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
854 INFO("Cloning a new user namespace");
855 handler
->clone_flags
|= CLONE_NEWUSER
;
858 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
859 if (!lxc_requests_empty_network(handler
))
860 handler
->clone_flags
|= CLONE_NEWNET
;
862 INFO("Inheriting a net namespace");
865 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1) {
866 handler
->clone_flags
|= CLONE_NEWIPC
;
868 INFO("Inheriting an IPC namespace");
871 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1) {
872 handler
->clone_flags
|= CLONE_NEWUTS
;
874 INFO("Inheriting a UTS namespace");
878 static int lxc_spawn(struct lxc_handler
*handler
)
880 int failed_before_rename
= 0;
881 const char *name
= handler
->name
;
882 bool cgroups_connected
= false;
883 int saved_ns_fd
[LXC_NS_MAX
];
884 int preserve_mask
= 0, i
;
885 int netpipepair
[2], nveths
;
889 for (i
= 0; i
< LXC_NS_MAX
; i
++)
890 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
891 preserve_mask
|= ns_info
[i
].clone_flag
;
893 if (lxc_sync_init(handler
))
896 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, handler
->ttysock
) < 0) {
897 lxc_sync_fini(handler
);
901 resolve_clone_flags(handler
);
903 if (handler
->clone_flags
& CLONE_NEWNET
) {
904 if (!lxc_list_empty(&handler
->conf
->network
)) {
906 /* Find gateway addresses from the link device, which is
907 * no longer accessible inside the container. Do this
908 * before creating network interfaces, since goto
909 * out_delete_net does not work before lxc_clone. */
910 if (lxc_find_gateway_addresses(handler
)) {
911 ERROR("failed to find gateway addresses");
912 lxc_sync_fini(handler
);
916 /* that should be done before the clone because we will
917 * fill the netdev index and use them in the child
919 if (lxc_create_network(handler
)) {
920 ERROR("failed to create the network");
921 lxc_sync_fini(handler
);
926 if (save_phys_nics(handler
->conf
)) {
927 ERROR("failed to save physical nic info");
932 if (!cgroup_init(handler
)) {
933 ERROR("failed initializing cgroup support");
937 cgroups_connected
= true;
939 if (!cgroup_create(handler
)) {
940 ERROR("failed creating cgroups");
945 * if the rootfs is not a blockdev, prevent the container from
946 * marking it readonly.
948 * if the container is unprivileged then skip rootfs pinning
950 if (lxc_list_empty(&handler
->conf
->id_map
)) {
951 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
952 if (handler
->pinfd
== -1)
953 INFO("failed to pin the container's rootfs");
956 if (preserve_ns(saved_ns_fd
, preserve_mask
) < 0)
958 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
961 if (am_unpriv() && (nveths
= count_veths(&handler
->conf
->network
))) {
962 if (pipe(netpipepair
) < 0) {
963 SYSERROR("Error creating pipe");
966 /* store netpipe in the global var for do_start's use */
967 netpipe
= netpipepair
[0];
970 /* Create a process in a new set of namespaces */
971 handler
->pid
= lxc_clone(do_start
, handler
, handler
->clone_flags
);
972 if (handler
->pid
< 0) {
973 SYSERROR("failed to fork into a new namespace");
977 if (attach_ns(saved_ns_fd
))
978 WARN("failed to restore saved namespaces");
980 lxc_sync_fini_child(handler
);
982 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
))
983 failed_before_rename
= 1;
985 if (!cgroup_create_legacy(handler
)) {
986 ERROR("failed to setup the legacy cgroups for %s", name
);
989 if (!cgroup_setup_limits(handler
, false)) {
990 ERROR("failed to setup the cgroup limits for '%s'", name
);
994 if (!cgroup_enter(handler
))
997 if (!cgroup_chown(handler
))
1000 if (failed_before_rename
)
1001 goto out_delete_net
;
1003 /* Create the network configuration */
1004 if (handler
->clone_flags
& CLONE_NEWNET
) {
1005 if (lxc_assign_network(&handler
->conf
->network
, handler
->pid
)) {
1006 ERROR("failed to create the configured network");
1007 goto out_delete_net
;
1011 if (netpipe
!= -1) {
1012 struct lxc_list
*iterator
;
1013 struct lxc_netdev
*netdev
;
1016 lxc_list_for_each(iterator
, &handler
->conf
->network
) {
1017 netdev
= iterator
->elem
;
1018 if (netdev
->type
!= LXC_NET_VETH
)
1020 if (write(netpipepair
[1], netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
1021 ERROR("Error writing veth name to container");
1022 goto out_delete_net
;
1025 close(netpipepair
[1]);
1028 /* map the container uids - the container became an invalid
1029 * userid the moment it was cloned with CLONE_NEWUSER - this
1030 * call doesn't change anything immediately, but allows the
1031 * container to setuid(0) (0 being mapped to something else on
1032 * the host) later to become a valid uid again */
1033 if (lxc_map_ids(&handler
->conf
->id_map
, handler
->pid
)) {
1034 ERROR("failed to set up id mapping");
1035 goto out_delete_net
;
1038 /* Tell the child to continue its initialization. we'll get
1039 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
1041 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1042 goto out_delete_net
;
1044 if (!cgroup_setup_limits(handler
, true)) {
1045 ERROR("failed to setup the devices cgroup for '%s'", name
);
1046 goto out_delete_net
;
1049 cgroup_disconnect();
1050 cgroups_connected
= false;
1052 /* read tty fds allocated by child */
1053 if (recv_ttys_from_child(handler
) < 0) {
1054 ERROR("failed to receive tty info from child");
1055 goto out_delete_net
;
1058 /* Tell the child to complete its initialization and wait for
1059 * it to exec or return an error. (the child will never
1060 * return LXC_SYNC_POST_CGROUP+1. It will either close the
1061 * sync pipe, causing lxc_sync_barrier_child to return
1062 * success, or return a different value, causing us to error
1065 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1068 if (detect_shared_rootfs())
1069 umount2(handler
->conf
->rootfs
.mount
, MNT_DETACH
);
1071 if (handler
->ops
->post_start(handler
, handler
->data
))
1074 if (lxc_set_state(name
, handler
, RUNNING
)) {
1075 ERROR("failed to set state to %s",
1076 lxc_state2str(RUNNING
));
1080 lxc_sync_fini(handler
);
1085 if (cgroups_connected
)
1086 cgroup_disconnect();
1087 if (handler
->clone_flags
& CLONE_NEWNET
)
1088 lxc_delete_network(handler
);
1090 lxc_abort(name
, handler
);
1091 lxc_sync_fini(handler
);
1092 if (handler
->pinfd
>= 0) {
1093 close(handler
->pinfd
);
1094 handler
->pinfd
= -1;
1100 int get_netns_fd(int pid
)
1102 char path
[MAXPATHLEN
];
1105 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/net", pid
);
1106 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1107 WARN("Failed to pin netns file for pid %d", pid
);
1111 fd
= open(path
, O_RDONLY
);
1113 WARN("Failed to pin netns file %s for pid %d: %s",
1114 path
, pid
, strerror(errno
));
1120 int __lxc_start(const char *name
, struct lxc_conf
*conf
,
1121 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1124 struct lxc_handler
*handler
;
1129 handler
= lxc_init(name
, conf
, lxcpath
);
1131 ERROR("failed to initialize the container");
1135 handler
->data
= data
;
1136 handler
->backgrounded
= backgrounded
;
1138 if (must_drop_cap_sys_boot(handler
->conf
)) {
1139 #if HAVE_SYS_CAPABILITY_H
1140 DEBUG("Dropping cap_sys_boot");
1142 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
1145 DEBUG("Not dropping cap_sys_boot or watching utmp");
1146 handler
->conf
->need_utmp_watch
= 0;
1149 if (!attach_block_device(handler
->conf
)) {
1150 ERROR("Failure attaching block device");
1151 goto out_fini_nonet
;
1154 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1155 /* if the backing store is a device, mount it here and now */
1156 if (rootfs_is_blockdev(conf
)) {
1157 if (unshare(CLONE_NEWNS
) < 0) {
1158 ERROR("Error unsharing mounts");
1159 goto out_fini_nonet
;
1161 remount_all_slave();
1162 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1163 ERROR("Error setting up rootfs mount as root before spawn");
1164 goto out_fini_nonet
;
1166 INFO("Set up container rootfs as host root");
1170 err
= lxc_spawn(handler
);
1172 ERROR("failed to spawn '%s'", name
);
1173 goto out_detach_blockdev
;
1176 handler
->conf
->reboot
= 0;
1178 netnsfd
= get_netns_fd(handler
->pid
);
1180 err
= lxc_poll(name
, handler
);
1182 ERROR("mainloop exited with an error");
1188 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1192 * If the child process exited but was not signaled,
1193 * it didn't call reboot. This should mean it was an
1194 * lxc-execute which simply exited. In any case, treat
1197 if (WIFSIGNALED(status
)) {
1198 switch(WTERMSIG(status
)) {
1199 case SIGINT
: /* halt */
1200 DEBUG("Container halting");
1202 case SIGHUP
: /* reboot */
1203 DEBUG("Container rebooting");
1204 handler
->conf
->reboot
= 1;
1206 case SIGSYS
: /* seccomp */
1207 DEBUG("Container violated its seccomp policy");
1210 DEBUG("unknown exit status for init: %d", WTERMSIG(status
));
1215 lxc_rename_phys_nics_on_shutdown(netnsfd
, handler
->conf
);
1219 if (handler
->pinfd
>= 0) {
1220 close(handler
->pinfd
);
1221 handler
->pinfd
= -1;
1224 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1225 err
= lxc_error_set_and_log(handler
->pid
, status
);
1227 lxc_delete_network(handler
);
1229 out_detach_blockdev
:
1230 detach_block_device(handler
->conf
);
1233 lxc_fini(name
, handler
);
1237 lxc_abort(name
, handler
);
1245 static int start(struct lxc_handler
*handler
, void* data
)
1247 struct start_args
*arg
= data
;
1249 NOTICE("exec'ing '%s'", arg
->argv
[0]);
1251 execvp(arg
->argv
[0], arg
->argv
);
1252 SYSERROR("failed to exec %s", arg
->argv
[0]);
1256 static int post_start(struct lxc_handler
*handler
, void* data
)
1258 struct start_args
*arg
= data
;
1260 NOTICE("'%s' started with pid '%d'", arg
->argv
[0], handler
->pid
);
1264 static struct lxc_operations start_ops
= {
1266 .post_start
= post_start
1269 int lxc_start(const char *name
, char *const argv
[], struct lxc_conf
*conf
,
1270 const char *lxcpath
, bool backgrounded
)
1272 struct start_args start_arg
= {
1276 conf
->need_utmp_watch
= 1;
1277 return __lxc_start(name
, conf
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);