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 #if !HAVE_DECL_PR_CAPBSET_DROP
54 #define PR_CAPBSET_DROP 24
66 #include "lxcseccomp.h"
70 #include "namespace.h"
74 #include "bdev/bdev.h"
77 lxc_log_define(lxc_start
, lxc
);
79 const struct ns_info ns_info
[LXC_NS_MAX
] = {
80 [LXC_NS_MNT
] = {"mnt", CLONE_NEWNS
},
81 [LXC_NS_PID
] = {"pid", CLONE_NEWPID
},
82 [LXC_NS_UTS
] = {"uts", CLONE_NEWUTS
},
83 [LXC_NS_IPC
] = {"ipc", CLONE_NEWIPC
},
84 [LXC_NS_USER
] = {"user", CLONE_NEWUSER
},
85 [LXC_NS_NET
] = {"net", CLONE_NEWNET
}
88 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
89 static bool do_destroy_container(struct lxc_conf
*conf
);
90 static int lxc_rmdir_onedev_wrapper(void *data
);
91 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
94 static void print_top_failing_dir(const char *path
)
96 size_t len
= strlen(path
);
97 char *copy
= alloca(len
+ 1), *p
, *e
, saved
;
103 while (p
< e
&& *p
== '/')
105 while (p
< e
&& *p
!= '/')
109 if (access(copy
, X_OK
)) {
110 SYSERROR("could not access %s. Please grant it 'x' " \
111 "access, or add an ACL for the container root.",
119 static void close_ns(int ns_fd
[LXC_NS_MAX
]) {
122 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
131 * preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
133 * Return true on success, false on failure. On failure, leave an error
134 * message in *errmsg, which caller must free.
136 static bool preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
,
140 char path
[MAXPATHLEN
];
142 for (i
= 0; i
< LXC_NS_MAX
; i
++)
145 snprintf(path
, MAXPATHLEN
, "/proc/%d/ns", pid
);
146 if (access(path
, X_OK
)) {
147 if (asprintf(errmsg
, "Kernel does not support setns.") == -1)
152 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
153 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
155 snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
,
156 ns_info
[i
].proc_name
);
157 ns_fd
[i
] = open(path
, O_RDONLY
| O_CLOEXEC
);
165 if (errno
== ENOENT
) {
166 ret
= asprintf(errmsg
, "Kernel does not support setns for %s",
167 ns_info
[i
].proc_name
);
169 ret
= asprintf(errmsg
, "Failed to open %s: %s",
170 path
, strerror(errno
));
178 static int attach_ns(const int ns_fd
[LXC_NS_MAX
]) {
181 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
185 if (setns(ns_fd
[i
], 0) != 0)
191 SYSERROR("failed to set namespace '%s'", ns_info
[i
].proc_name
);
195 static int match_fd(int fd
)
197 return (fd
== 0 || fd
== 1 || fd
== 2);
201 * Check for any fds we need to close
202 * * if fd_to_ignore != -1, then if we find that fd open we will ignore it.
203 * * By default we warn about open fds we find.
204 * * If closeall is true, we will close open fds.
205 * * If lxc-start was passed "-C", then conf->close_all_fds will be true,
206 * in which case we also close all open fds.
207 * * A daemonized container will always pass closeall=true.
209 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
, int fd_to_ignore
)
211 struct dirent dirent
, *direntp
;
215 if (conf
&& conf
->close_all_fds
)
219 dir
= opendir("/proc/self/fd");
221 WARN("failed to open directory: %m");
227 while (!readdir_r(dir
, &dirent
, &direntp
)) {
231 if (!strcmp(direntp
->d_name
, "."))
234 if (!strcmp(direntp
->d_name
, ".."))
237 fd
= atoi(direntp
->d_name
);
239 if (fd
== fddir
|| fd
== lxc_log_fd
|| fd
== fd_to_ignore
)
242 if (current_config
&& fd
== current_config
->logfd
)
251 INFO("closed inherited fd %d", fd
);
254 WARN("inherited fd %d", fd
);
257 closedir(dir
); /* cannot fail */
261 static int setup_signal_fd(sigset_t
*oldmask
)
266 /* Block everything except serious error signals */
267 if (sigfillset(&mask
) ||
268 sigdelset(&mask
, SIGILL
) ||
269 sigdelset(&mask
, SIGSEGV
) ||
270 sigdelset(&mask
, SIGBUS
) ||
271 sigdelset(&mask
, SIGWINCH
) ||
272 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
273 SYSERROR("failed to set signal mask");
277 fd
= signalfd(-1, &mask
, 0);
279 SYSERROR("failed to create the signal fd");
283 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
284 SYSERROR("failed to set sigfd to close-on-exec");
289 DEBUG("sigchild handler set");
294 static int signal_handler(int fd
, uint32_t events
, void *data
,
295 struct lxc_epoll_descr
*descr
)
297 struct signalfd_siginfo siginfo
;
301 bool init_died
= false;
303 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
305 ERROR("failed to read signal info");
309 if (ret
!= sizeof(siginfo
)) {
310 ERROR("unexpected siginfo size");
314 // check whether init is running
316 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
317 if (ret
== 0 && info
.si_pid
== *pid
) {
321 if (siginfo
.ssi_signo
!= SIGCHLD
) {
322 kill(*pid
, siginfo
.ssi_signo
);
323 INFO("forwarded signal %d to pid %d", siginfo
.ssi_signo
, *pid
);
324 return init_died
? 1 : 0;
327 if (siginfo
.ssi_code
== CLD_STOPPED
||
328 siginfo
.ssi_code
== CLD_CONTINUED
) {
329 INFO("container init process was stopped/continued");
330 return init_died
? 1 : 0;
333 /* more robustness, protect ourself from a SIGCHLD sent
334 * by a process different from the container init
336 if (siginfo
.ssi_pid
!= *pid
) {
337 WARN("invalid pid for SIGCHLD");
338 return init_died
? 1 : 0;
341 DEBUG("container init process exited");
345 int lxc_set_state(const char *name
, struct lxc_handler
*handler
, lxc_state_t state
)
347 handler
->state
= state
;
348 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
352 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
354 int sigfd
= handler
->sigfd
;
355 int pid
= handler
->pid
;
356 struct lxc_epoll_descr descr
;
358 if (lxc_mainloop_open(&descr
)) {
359 ERROR("failed to create mainloop");
363 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
364 ERROR("failed to add handler for the signal");
365 goto out_mainloop_open
;
368 if (lxc_console_mainloop_add(&descr
, handler
)) {
369 ERROR("failed to add console handler to mainloop");
370 goto out_mainloop_open
;
373 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
374 ERROR("failed to add command handler to mainloop");
375 goto out_mainloop_open
;
378 if (handler
->conf
->need_utmp_watch
) {
379 #if HAVE_SYS_CAPABILITY_H
380 if (lxc_utmp_mainloop_add(&descr
, handler
)) {
381 ERROR("failed to add utmp handler to mainloop");
382 goto out_mainloop_open
;
385 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support");
389 return lxc_mainloop(&descr
, -1);
392 lxc_mainloop_close(&descr
);
398 struct lxc_handler
*lxc_init(const char *name
, struct lxc_conf
*conf
, const char *lxcpath
)
401 struct lxc_handler
*handler
;
403 handler
= malloc(sizeof(*handler
));
407 memset(handler
, 0, sizeof(*handler
));
409 handler
->ttysock
[0] = handler
->ttysock
[1] = -1;
410 handler
->conf
= conf
;
411 handler
->lxcpath
= lxcpath
;
414 for (i
= 0; i
< LXC_NS_MAX
; i
++)
415 handler
->nsfd
[i
] = -1;
419 handler
->name
= strdup(name
);
420 if (!handler
->name
) {
421 ERROR("failed to allocate memory");
425 if (lxc_cmd_init(name
, handler
, lxcpath
))
428 if (lxc_read_seccomp_config(conf
) != 0) {
429 ERROR("failed loading seccomp policy");
430 goto out_close_maincmd_fd
;
433 /* Begin by setting the state to STARTING */
434 if (lxc_set_state(name
, handler
, STARTING
)) {
435 ERROR("failed to set state '%s'", lxc_state2str(STARTING
));
436 goto out_close_maincmd_fd
;
439 /* Start of environment variable setup for hooks */
440 if (name
&& setenv("LXC_NAME", name
, 1)) {
441 SYSERROR("failed to set environment variable for container name");
443 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
444 SYSERROR("failed to set environment variable for config path");
446 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
447 SYSERROR("failed to set environment variable for rootfs mount");
449 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
450 SYSERROR("failed to set environment variable for rootfs mount");
452 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1)) {
453 SYSERROR("failed to set environment variable for console path");
455 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1)) {
456 SYSERROR("failed to set environment variable for console log");
458 if (setenv("LXC_CGNS_AWARE", "1", 1)) {
459 SYSERROR("failed to set LXC_CGNS_AWARE environment variable");
461 /* End of environment variable setup for hooks */
463 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
464 ERROR("failed to run pre-start hooks for container '%s'.", name
);
468 /* the signal fd has to be created before forking otherwise
469 * if the child process exits before we setup the signal fd,
470 * the event will be lost and the command will be stuck */
471 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
472 if (handler
->sigfd
< 0) {
473 ERROR("failed to set sigchild fd handler");
477 /* do this after setting up signals since it might unblock SIGWINCH */
478 if (lxc_console_create(conf
)) {
479 ERROR("failed to create console");
480 goto out_restore_sigmask
;
483 if (ttys_shift_ids(conf
) < 0) {
484 ERROR("Failed to shift tty into container");
485 goto out_restore_sigmask
;
488 INFO("'%s' is initialized", name
);
492 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
494 lxc_delete_tty(&conf
->tty_info
);
496 lxc_set_state(name
, handler
, ABORTING
);
497 out_close_maincmd_fd
:
498 close(conf
->maincmd_fd
);
499 conf
->maincmd_fd
= -1;
502 handler
->name
= NULL
;
508 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
511 pid_t self
= getpid();
512 char *namespaces
[LXC_NS_MAX
+1];
513 size_t namespace_count
= 0;
515 /* The STOPPING state is there for future cleanup code
516 * which can take awhile
518 lxc_set_state(name
, handler
, STOPPING
);
520 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
521 if (handler
->nsfd
[i
] != -1) {
522 rc
= asprintf(&namespaces
[namespace_count
], "%s:/proc/%d/fd/%d",
523 ns_info
[i
].proc_name
, self
, handler
->nsfd
[i
]);
525 SYSERROR("failed to allocate memory");
531 namespaces
[namespace_count
] = NULL
;
533 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1)) {
534 SYSERROR("failed to set environment variable for stop target");
536 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1)) {
537 SYSERROR("failed to set environment variable for stop target");
540 if (run_lxc_hooks(name
, "stop", handler
->conf
, handler
->lxcpath
, namespaces
))
541 ERROR("failed to run stop hooks for container '%s'.", name
);
543 while (namespace_count
--)
544 free(namespaces
[namespace_count
]);
545 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
546 if (handler
->nsfd
[i
] != -1) {
547 close(handler
->nsfd
[i
]);
548 handler
->nsfd
[i
] = -1;
551 lxc_set_state(name
, handler
, STOPPED
);
553 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
)) {
554 ERROR("failed to run post-stop hooks for container '%s'.", name
);
555 if (handler
->conf
->reboot
) {
556 WARN("Container will be stopped instead of rebooted.");
557 handler
->conf
->reboot
= 0;
558 setenv("LXC_TARGET", "stop", 1);
562 /* reset mask set by setup_signal_fd */
563 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
564 WARN("failed to restore sigprocmask");
566 lxc_console_delete(&handler
->conf
->console
);
567 lxc_delete_tty(&handler
->conf
->tty_info
);
568 close(handler
->conf
->maincmd_fd
);
569 handler
->conf
->maincmd_fd
= -1;
571 if (handler
->ttysock
[0] != -1) {
572 close(handler
->ttysock
[0]);
573 close(handler
->ttysock
[1]);
576 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1)
577 lxc_destroy_container_on_signal(handler
, name
);
579 cgroup_destroy(handler
);
583 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
587 lxc_set_state(name
, handler
, ABORTING
);
588 if (handler
->pid
> 0)
589 kill(handler
->pid
, SIGKILL
);
590 while ((ret
= waitpid(-1, &status
, 0)) > 0) ;
593 #include <sys/reboot.h>
594 #include <linux/reboot.h>
597 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
598 * in a child pid namespace if container reboot support exists.
599 * Otherwise, it will either succeed or return -EPERM.
601 static int container_reboot_supported(void *arg
)
607 if (ret
== -1 && errno
== EINVAL
)
612 static int must_drop_cap_sys_boot(struct lxc_conf
*conf
)
615 int ret
, cmd
, v
, flags
;
616 long stack_size
= 4096;
617 void *stack
= alloca(stack_size
);
621 f
= fopen("/proc/sys/kernel/ctrl-alt-del", "r");
623 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
627 ret
= fscanf(f
, "%d", &v
);
630 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
633 cmd
= v
? LINUX_REBOOT_CMD_CAD_ON
: LINUX_REBOOT_CMD_CAD_OFF
;
635 flags
= CLONE_NEWPID
| SIGCHLD
;
636 if (!lxc_list_empty(&conf
->id_map
))
637 flags
|= CLONE_NEWUSER
;
640 pid
= __clone2(container_reboot_supported
, stack
, stack_size
, flags
, &cmd
);
643 pid
= clone(container_reboot_supported
, stack
, flags
, &cmd
);
646 if (flags
& CLONE_NEWUSER
)
647 ERROR("failed to clone (%#x): %s (includes CLONE_NEWUSER)", flags
, strerror(errno
));
649 ERROR("failed to clone (%#x): %s", flags
, strerror(errno
));
652 if (wait(&status
) < 0) {
653 SYSERROR("unexpected wait error: %m");
657 if (WEXITSTATUS(status
) != 1)
664 * netpipe is used in the unprivileged case to transfer the ifindexes
665 * from parent to child
667 static int netpipe
= -1;
669 static inline int count_veths(struct lxc_list
*network
)
671 struct lxc_list
*iterator
;
672 struct lxc_netdev
*netdev
;
675 lxc_list_for_each(iterator
, network
) {
676 netdev
= iterator
->elem
;
677 if (netdev
->type
!= LXC_NET_VETH
)
684 static int read_unpriv_netifindex(struct lxc_list
*network
)
686 struct lxc_list
*iterator
;
687 struct lxc_netdev
*netdev
;
691 lxc_list_for_each(iterator
, network
) {
692 netdev
= iterator
->elem
;
693 if (netdev
->type
!= LXC_NET_VETH
)
695 if (!(netdev
->name
= malloc(IFNAMSIZ
))) {
696 ERROR("Out of memory");
700 if (read(netpipe
, netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
709 static int do_start(void *data
)
711 struct lxc_list
*iterator
;
712 struct lxc_handler
*handler
= data
;
715 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
716 SYSERROR("failed to set sigprocmask");
720 /* This prctl must be before the synchro, so if the parent
721 * dies before we set the parent death signal, we will detect
722 * its death with the synchro right after, otherwise we have
723 * a window where the parent can exit before we set the pdeath
724 * signal leading to a unsupervized container.
726 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
727 SYSERROR("failed to set pdeath signal");
731 lxc_sync_fini_parent(handler
);
733 /* don't leak the pinfd to the container */
734 if (handler
->pinfd
>= 0) {
735 close(handler
->pinfd
);
738 /* Tell the parent task it can begin to configure the
739 * container and wait for it to finish
741 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
744 if (read_unpriv_netifindex(&handler
->conf
->network
) < 0)
745 goto out_warn_father
;
748 * if we are in a new user namespace, become root there to have
749 * privilege over our namespace. When using lxc-execute we default to root,
750 * but this can be overriden using the lxc.init_uid and lxc.init_gid
751 * configuration options.
753 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
755 if (handler
->conf
->is_execute
&& handler
->conf
->init_gid
)
756 new_gid
= handler
->conf
->init_gid
;
759 if (handler
->conf
->is_execute
&& handler
->conf
->init_uid
)
760 new_uid
= handler
->conf
->init_uid
;
762 NOTICE("switching to gid/uid %d/%d in new user namespace", new_gid
, new_uid
);
763 if (setgid(new_gid
)) {
765 goto out_warn_father
;
767 if (setuid(new_uid
)) {
769 goto out_warn_father
;
771 if (setgroups(0, NULL
)) {
772 SYSERROR("setgroups");
773 goto out_warn_father
;
777 if (access(handler
->lxcpath
, X_OK
)) {
778 print_top_failing_dir(handler
->lxcpath
);
779 goto out_warn_father
;
782 #if HAVE_SYS_CAPABILITY_H
783 if (handler
->conf
->need_utmp_watch
) {
784 if (prctl(PR_CAPBSET_DROP
, CAP_SYS_BOOT
, 0, 0, 0)) {
785 SYSERROR("failed to remove CAP_SYS_BOOT capability");
786 goto out_warn_father
;
788 DEBUG("Dropped cap_sys_boot");
792 if (handler
->backgrounded
) {
793 devnull_fd
= open_devnull();
796 goto out_warn_father
;
799 /* Setup the container, ip, names, utsname, ... */
800 if (lxc_setup(handler
)) {
801 ERROR("failed to setup the container");
802 goto out_warn_father
;
805 /* ask father to setup cgroups and wait for him to finish */
806 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
809 /* Set the label to change to when we exec(2) the container's init */
810 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
811 goto out_warn_father
;
813 /* Some init's such as busybox will set sane tty settings on stdin,
814 * stdout, stderr which it thinks is the console. We already set them
815 * the way we wanted on the real terminal, and we want init to do its
816 * setup on its console ie. the pty allocated in lxc_console_create()
817 * so make sure that that pty is stdin,stdout,stderr.
819 if (lxc_console_set_stdfds(handler
->conf
->console
.slave
) < 0)
820 goto out_warn_father
;
822 /* If we mounted a temporary proc, then unmount it now */
823 tmp_proc_unmount(handler
->conf
);
825 if (lxc_seccomp_load(handler
->conf
) != 0)
826 goto out_warn_father
;
828 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
829 ERROR("failed to run start hooks for container '%s'.", handler
->name
);
830 goto out_warn_father
;
833 /* The clearenv() and putenv() calls have been moved here
834 * to allow us to use environment variables passed to the various
835 * hooks, such as the start hook above. Not all of the
836 * variables like CONFIG_PATH or ROOTFS are valid in this
837 * context but others are. */
839 SYSERROR("failed to clear environment");
840 /* don't error out though */
843 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
844 if (putenv((char *)iterator
->elem
)) {
845 SYSERROR("failed to set environment variable '%s'", (char *)iterator
->elem
);
846 goto out_warn_father
;
850 if (putenv("container=lxc")) {
851 SYSERROR("failed to set environment variable 'container=lxc'");
852 goto out_warn_father
;
855 if (handler
->conf
->pty_names
) {
856 if (putenv(handler
->conf
->pty_names
)) {
857 SYSERROR("failed to set environment variable for container ptys");
858 goto out_warn_father
;
862 close(handler
->sigfd
);
864 if (handler
->backgrounded
&& set_stdfds(devnull_fd
))
865 goto out_warn_father
;
867 if (devnull_fd
>= 0) {
872 if (cgns_supported() && unshare(CLONE_NEWCGROUP
) != 0) {
873 SYSERROR("Failed to unshare cgroup namespace");
874 goto out_warn_father
;
879 /* after this call, we are in error because this
880 * ops should not return as it execs */
881 handler
->ops
->start(handler
, handler
->data
);
884 /* we want the parent to know something went wrong, so we return a special
886 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
895 static int save_phys_nics(struct lxc_conf
*conf
)
897 struct lxc_list
*iterator
;
898 int am_root
= (getuid() == 0);
903 lxc_list_for_each(iterator
, &conf
->network
) {
904 struct lxc_netdev
*netdev
= iterator
->elem
;
906 if (netdev
->type
!= LXC_NET_PHYS
)
908 conf
->saved_nics
= realloc(conf
->saved_nics
,
909 (conf
->num_savednics
+1)*sizeof(struct saved_nic
));
910 if (!conf
->saved_nics
) {
911 SYSERROR("failed to allocate memory");
914 conf
->saved_nics
[conf
->num_savednics
].ifindex
= netdev
->ifindex
;
915 conf
->saved_nics
[conf
->num_savednics
].orig_name
= strdup(netdev
->link
);
916 if (!conf
->saved_nics
[conf
->num_savednics
].orig_name
) {
917 SYSERROR("failed to allocate memory");
920 INFO("stored saved_nic #%d idx %d name %s", conf
->num_savednics
,
921 conf
->saved_nics
[conf
->num_savednics
].ifindex
,
922 conf
->saved_nics
[conf
->num_savednics
].orig_name
);
923 conf
->num_savednics
++;
929 static int recv_fd(int sock
, int *fd
)
931 if (lxc_abstract_unix_recv_fd(sock
, fd
, NULL
, 0) < 0) {
932 SYSERROR("Error receiving tty fd from child");
940 static int recv_ttys_from_child(struct lxc_handler
*handler
)
942 struct lxc_conf
*conf
= handler
->conf
;
943 int i
, sock
= handler
->ttysock
[1];
944 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
949 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
)*conf
->tty
);
950 if (!tty_info
->pty_info
) {
951 SYSERROR("failed to allocate pty_info");
955 for (i
= 0; i
< conf
->tty
; i
++) {
956 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
958 if (recv_fd(sock
, &pty_info
->slave
) < 0 ||
959 recv_fd(sock
, &pty_info
->master
) < 0) {
960 ERROR("Error receiving tty info from child");
964 tty_info
->nbtty
= conf
->tty
;
969 void resolve_clone_flags(struct lxc_handler
*handler
)
971 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
973 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
974 INFO("Cloning a new user namespace");
975 handler
->clone_flags
|= CLONE_NEWUSER
;
978 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
979 if (!lxc_requests_empty_network(handler
))
980 handler
->clone_flags
|= CLONE_NEWNET
;
982 INFO("Inheriting a net namespace");
985 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1) {
986 handler
->clone_flags
|= CLONE_NEWIPC
;
988 INFO("Inheriting an IPC namespace");
991 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1) {
992 handler
->clone_flags
|= CLONE_NEWUTS
;
994 INFO("Inheriting a UTS namespace");
998 static int lxc_spawn(struct lxc_handler
*handler
)
1000 int failed_before_rename
= 0;
1001 const char *name
= handler
->name
;
1002 char *errmsg
= NULL
;
1003 bool cgroups_connected
= false;
1004 int saved_ns_fd
[LXC_NS_MAX
];
1005 int preserve_mask
= 0, i
;
1006 int netpipepair
[2], nveths
;
1010 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1011 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
1012 preserve_mask
|= ns_info
[i
].clone_flag
;
1014 if (lxc_sync_init(handler
))
1017 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, handler
->ttysock
) < 0) {
1018 lxc_sync_fini(handler
);
1022 resolve_clone_flags(handler
);
1024 if (handler
->clone_flags
& CLONE_NEWNET
) {
1025 if (!lxc_list_empty(&handler
->conf
->network
)) {
1027 /* Find gateway addresses from the link device, which is
1028 * no longer accessible inside the container. Do this
1029 * before creating network interfaces, since goto
1030 * out_delete_net does not work before lxc_clone. */
1031 if (lxc_find_gateway_addresses(handler
)) {
1032 ERROR("failed to find gateway addresses");
1033 lxc_sync_fini(handler
);
1037 /* that should be done before the clone because we will
1038 * fill the netdev index and use them in the child
1040 if (lxc_create_network(handler
)) {
1041 ERROR("failed to create the network");
1042 lxc_sync_fini(handler
);
1047 if (save_phys_nics(handler
->conf
)) {
1048 ERROR("failed to save physical nic info");
1053 if (!cgroup_init(handler
)) {
1054 ERROR("failed initializing cgroup support");
1055 goto out_delete_net
;
1058 cgroups_connected
= true;
1060 if (!cgroup_create(handler
)) {
1061 ERROR("failed creating cgroups");
1062 goto out_delete_net
;
1066 * if the rootfs is not a blockdev, prevent the container from
1067 * marking it readonly.
1069 * if the container is unprivileged then skip rootfs pinning
1071 if (lxc_list_empty(&handler
->conf
->id_map
)) {
1072 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
1073 if (handler
->pinfd
== -1)
1074 INFO("failed to pin the container's rootfs");
1077 if (!preserve_ns(saved_ns_fd
, preserve_mask
, getpid(), &errmsg
)) {
1078 SYSERROR("Failed to preserve requested namespaces: %s",
1079 errmsg
? errmsg
: "(Out of memory)");
1081 goto out_delete_net
;
1083 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
1084 goto out_delete_net
;
1086 if (am_unpriv() && (nveths
= count_veths(&handler
->conf
->network
))) {
1087 if (pipe(netpipepair
) < 0) {
1088 SYSERROR("Error creating pipe");
1089 goto out_delete_net
;
1091 /* store netpipe in the global var for do_start's use */
1092 netpipe
= netpipepair
[0];
1095 /* Create a process in a new set of namespaces */
1096 handler
->pid
= lxc_clone(do_start
, handler
, handler
->clone_flags
);
1097 if (handler
->pid
< 0) {
1098 SYSERROR("failed to fork into a new namespace");
1099 goto out_delete_net
;
1102 if (!preserve_ns(handler
->nsfd
, handler
->clone_flags
| preserve_mask
, handler
->pid
, &errmsg
)) {
1103 INFO("Failed to store namespace references for stop hook: %s",
1104 errmsg
? errmsg
: "(Out of memory)");
1108 if (attach_ns(saved_ns_fd
))
1109 WARN("failed to restore saved namespaces");
1111 lxc_sync_fini_child(handler
);
1113 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
))
1114 failed_before_rename
= 1;
1116 if (!cgroup_create_legacy(handler
)) {
1117 ERROR("failed to setup the legacy cgroups for %s", name
);
1118 goto out_delete_net
;
1120 if (!cgroup_setup_limits(handler
, false)) {
1121 ERROR("failed to setup the cgroup limits for '%s'", name
);
1122 goto out_delete_net
;
1125 if (!cgroup_enter(handler
))
1126 goto out_delete_net
;
1128 if (!cgroup_chown(handler
))
1129 goto out_delete_net
;
1131 if (failed_before_rename
)
1132 goto out_delete_net
;
1134 /* Create the network configuration */
1135 if (handler
->clone_flags
& CLONE_NEWNET
) {
1136 if (lxc_assign_network(handler
->lxcpath
, handler
->name
,
1137 &handler
->conf
->network
, handler
->pid
)) {
1138 ERROR("failed to create the configured network");
1139 goto out_delete_net
;
1143 if (netpipe
!= -1) {
1144 struct lxc_list
*iterator
;
1145 struct lxc_netdev
*netdev
;
1148 lxc_list_for_each(iterator
, &handler
->conf
->network
) {
1149 netdev
= iterator
->elem
;
1150 if (netdev
->type
!= LXC_NET_VETH
)
1152 if (write(netpipepair
[1], netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
1153 ERROR("Error writing veth name to container");
1154 goto out_delete_net
;
1157 close(netpipepair
[1]);
1160 /* map the container uids - the container became an invalid
1161 * userid the moment it was cloned with CLONE_NEWUSER - this
1162 * call doesn't change anything immediately, but allows the
1163 * container to setuid(0) (0 being mapped to something else on
1164 * the host) later to become a valid uid again */
1165 if (lxc_map_ids(&handler
->conf
->id_map
, handler
->pid
)) {
1166 ERROR("failed to set up id mapping");
1167 goto out_delete_net
;
1170 /* Tell the child to continue its initialization. we'll get
1171 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
1173 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1174 goto out_delete_net
;
1176 if (!cgroup_setup_limits(handler
, true)) {
1177 ERROR("failed to setup the devices cgroup for '%s'", name
);
1178 goto out_delete_net
;
1181 cgroup_disconnect();
1182 cgroups_connected
= false;
1184 /* read tty fds allocated by child */
1185 if (recv_ttys_from_child(handler
) < 0) {
1186 ERROR("failed to receive tty info from child");
1187 goto out_delete_net
;
1190 /* Tell the child to complete its initialization and wait for
1191 * it to exec or return an error. (the child will never
1192 * return LXC_SYNC_POST_CGROUP+1. It will either close the
1193 * sync pipe, causing lxc_sync_barrier_child to return
1194 * success, or return a different value, causing us to error
1197 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1200 if (detect_shared_rootfs())
1201 umount2(handler
->conf
->rootfs
.mount
, MNT_DETACH
);
1203 if (handler
->ops
->post_start(handler
, handler
->data
))
1206 if (lxc_set_state(name
, handler
, RUNNING
)) {
1207 ERROR("failed to set state to %s",
1208 lxc_state2str(RUNNING
));
1212 lxc_sync_fini(handler
);
1217 if (cgroups_connected
)
1218 cgroup_disconnect();
1219 if (handler
->clone_flags
& CLONE_NEWNET
)
1220 lxc_delete_network(handler
);
1222 lxc_abort(name
, handler
);
1223 lxc_sync_fini(handler
);
1224 if (handler
->pinfd
>= 0) {
1225 close(handler
->pinfd
);
1226 handler
->pinfd
= -1;
1232 int get_netns_fd(int pid
)
1234 char path
[MAXPATHLEN
];
1237 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/net", pid
);
1238 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1239 WARN("Failed to pin netns file for pid %d", pid
);
1243 fd
= open(path
, O_RDONLY
);
1245 WARN("Failed to pin netns file %s for pid %d: %s",
1246 path
, pid
, strerror(errno
));
1252 int __lxc_start(const char *name
, struct lxc_conf
*conf
,
1253 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1256 struct lxc_handler
*handler
;
1261 handler
= lxc_init(name
, conf
, lxcpath
);
1263 ERROR("failed to initialize the container");
1267 handler
->data
= data
;
1268 handler
->backgrounded
= backgrounded
;
1270 if (must_drop_cap_sys_boot(handler
->conf
)) {
1271 #if HAVE_SYS_CAPABILITY_H
1272 DEBUG("Dropping cap_sys_boot");
1274 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
1277 DEBUG("Not dropping cap_sys_boot or watching utmp");
1278 handler
->conf
->need_utmp_watch
= 0;
1281 if (!attach_block_device(handler
->conf
)) {
1282 ERROR("Failure attaching block device");
1283 goto out_fini_nonet
;
1286 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1287 /* if the backing store is a device, mount it here and now */
1288 if (rootfs_is_blockdev(conf
)) {
1289 if (unshare(CLONE_NEWNS
) < 0) {
1290 ERROR("Error unsharing mounts");
1291 goto out_fini_nonet
;
1293 remount_all_slave();
1294 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1295 ERROR("Error setting up rootfs mount as root before spawn");
1296 goto out_fini_nonet
;
1298 INFO("Set up container rootfs as host root");
1302 err
= lxc_spawn(handler
);
1304 ERROR("failed to spawn '%s'", name
);
1305 goto out_detach_blockdev
;
1308 handler
->conf
->reboot
= 0;
1310 netnsfd
= get_netns_fd(handler
->pid
);
1312 err
= lxc_poll(name
, handler
);
1314 ERROR("mainloop exited with an error");
1320 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1324 * If the child process exited but was not signaled,
1325 * it didn't call reboot. This should mean it was an
1326 * lxc-execute which simply exited. In any case, treat
1329 if (WIFSIGNALED(status
)) {
1330 switch(WTERMSIG(status
)) {
1331 case SIGINT
: /* halt */
1332 DEBUG("Container halting");
1334 case SIGHUP
: /* reboot */
1335 DEBUG("Container rebooting");
1336 handler
->conf
->reboot
= 1;
1338 case SIGSYS
: /* seccomp */
1339 DEBUG("Container violated its seccomp policy");
1342 DEBUG("unknown exit status for init: %d", WTERMSIG(status
));
1347 DEBUG("Pushing physical nics back to host namespace");
1348 lxc_rename_phys_nics_on_shutdown(netnsfd
, handler
->conf
);
1350 DEBUG("Tearing down virtual network devices used by container");
1351 lxc_delete_network(handler
);
1356 if (handler
->pinfd
>= 0) {
1357 close(handler
->pinfd
);
1358 handler
->pinfd
= -1;
1361 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1362 err
= lxc_error_set_and_log(handler
->pid
, status
);
1364 lxc_delete_network(handler
);
1366 out_detach_blockdev
:
1367 detach_block_device(handler
->conf
);
1370 lxc_fini(name
, handler
);
1374 lxc_abort(name
, handler
);
1382 static int start(struct lxc_handler
*handler
, void* data
)
1384 struct start_args
*arg
= data
;
1386 NOTICE("exec'ing '%s'", arg
->argv
[0]);
1388 execvp(arg
->argv
[0], arg
->argv
);
1389 SYSERROR("failed to exec %s", arg
->argv
[0]);
1393 static int post_start(struct lxc_handler
*handler
, void* data
)
1395 struct start_args
*arg
= data
;
1397 NOTICE("'%s' started with pid '%d'", arg
->argv
[0], handler
->pid
);
1401 static struct lxc_operations start_ops
= {
1403 .post_start
= post_start
1406 int lxc_start(const char *name
, char *const argv
[], struct lxc_conf
*conf
,
1407 const char *lxcpath
, bool backgrounded
)
1409 struct start_args start_arg
= {
1413 conf
->need_utmp_watch
= 1;
1414 return __lxc_start(name
, conf
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1417 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1420 char destroy
[MAXPATHLEN
];
1423 struct lxc_container
*c
;
1424 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1425 bret
= do_destroy_container(handler
->conf
);
1427 ERROR("Error destroying rootfs for %s", name
);
1431 INFO("Destroyed rootfs for %s", name
);
1433 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1434 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1435 ERROR("Error printing path for %s", name
);
1436 ERROR("Error destroying directory for %s", name
);
1440 c
= lxc_container_new(name
, handler
->lxcpath
);
1442 if (container_disk_lock(c
)) {
1443 INFO("Could not update lxc_snapshots file");
1444 lxc_container_put(c
);
1446 mod_all_rdeps(c
, false);
1447 container_disk_unlock(c
);
1448 lxc_container_put(c
);
1453 ret
= userns_exec_1(handler
->conf
, lxc_rmdir_onedev_wrapper
, destroy
);
1455 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1458 ERROR("Error destroying directory for %s", name
);
1461 INFO("Destroyed directory for %s", name
);
1464 static int lxc_rmdir_onedev_wrapper(void *data
)
1466 char *arg
= (char *) data
;
1467 return lxc_rmdir_onedev(arg
, NULL
);
1470 static bool do_destroy_container(struct lxc_conf
*conf
) {
1472 if (userns_exec_1(conf
, bdev_destroy_wrapper
, conf
) < 0)
1476 return bdev_destroy(conf
);