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"
72 #include "bdev/bdev.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
++) {
128 * preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
130 * Return true on success, false on failure. On failure, leave an error
131 * message in *errmsg, which caller must free.
134 bool preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
, char **errmsg
) {
136 char path
[MAXPATHLEN
];
138 for (i
= 0; i
< LXC_NS_MAX
; i
++)
141 snprintf(path
, MAXPATHLEN
, "/proc/%d/ns", pid
);
142 if (access(path
, X_OK
)) {
143 if (asprintf(errmsg
, "Kernel does not support setns.") == -1)
148 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
149 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
151 snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
,
152 ns_info
[i
].proc_name
);
153 ns_fd
[i
] = open(path
, O_RDONLY
| O_CLOEXEC
);
161 if (errno
== ENOENT
) {
162 ret
= asprintf(errmsg
, "Kernel does not support setns for %s",
163 ns_info
[i
].proc_name
);
165 ret
= asprintf(errmsg
, "Failed to open %s: %s",
166 path
, strerror(errno
));
174 static int attach_ns(const int ns_fd
[LXC_NS_MAX
]) {
177 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
181 if (setns(ns_fd
[i
], 0) != 0)
187 SYSERROR("failed to set namespace '%s'", ns_info
[i
].proc_name
);
191 static int match_fd(int fd
)
193 return (fd
== 0 || fd
== 1 || fd
== 2);
197 * Check for any fds we need to close
198 * * if fd_to_ignore != -1, then if we find that fd open we will ignore it.
199 * * By default we warn about open fds we find.
200 * * If closeall is true, we will close open fds.
201 * * If lxc-start was passed "-C", then conf->close_all_fds will be true,
202 * in which case we also close all open fds.
203 * * A daemonized container will always pass closeall=true.
205 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
, int fd_to_ignore
)
207 struct dirent dirent
, *direntp
;
211 if (conf
&& conf
->close_all_fds
)
215 dir
= opendir("/proc/self/fd");
217 WARN("failed to open directory: %m");
223 while (!readdir_r(dir
, &dirent
, &direntp
)) {
227 if (!strcmp(direntp
->d_name
, "."))
230 if (!strcmp(direntp
->d_name
, ".."))
233 fd
= atoi(direntp
->d_name
);
235 if (fd
== fddir
|| fd
== lxc_log_fd
|| fd
== fd_to_ignore
)
238 if (current_config
&& fd
== current_config
->logfd
)
247 INFO("closed inherited fd %d", fd
);
250 WARN("inherited fd %d", fd
);
253 closedir(dir
); /* cannot fail */
257 static int setup_signal_fd(sigset_t
*oldmask
)
262 /* Block everything except serious error signals */
263 if (sigfillset(&mask
) ||
264 sigdelset(&mask
, SIGILL
) ||
265 sigdelset(&mask
, SIGSEGV
) ||
266 sigdelset(&mask
, SIGBUS
) ||
267 sigdelset(&mask
, SIGWINCH
) ||
268 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
269 SYSERROR("failed to set signal mask");
273 fd
= signalfd(-1, &mask
, 0);
275 SYSERROR("failed to create the signal fd");
279 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
280 SYSERROR("failed to set sigfd to close-on-exec");
285 DEBUG("sigchild handler set");
290 static int signal_handler(int fd
, uint32_t events
, void *data
,
291 struct lxc_epoll_descr
*descr
)
293 struct signalfd_siginfo siginfo
;
297 bool init_died
= false;
299 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
301 ERROR("failed to read signal info");
305 if (ret
!= sizeof(siginfo
)) {
306 ERROR("unexpected siginfo size");
310 // check whether init is running
312 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
313 if (ret
== 0 && info
.si_pid
== *pid
) {
317 if (siginfo
.ssi_signo
!= SIGCHLD
) {
318 kill(*pid
, siginfo
.ssi_signo
);
319 INFO("forwarded signal %d to pid %d", siginfo
.ssi_signo
, *pid
);
320 return init_died
? 1 : 0;
323 if (siginfo
.ssi_code
== CLD_STOPPED
||
324 siginfo
.ssi_code
== CLD_CONTINUED
) {
325 INFO("container init process was stopped/continued");
326 return init_died
? 1 : 0;
329 /* more robustness, protect ourself from a SIGCHLD sent
330 * by a process different from the container init
332 if (siginfo
.ssi_pid
!= *pid
) {
333 WARN("invalid pid for SIGCHLD");
334 return init_died
? 1 : 0;
337 DEBUG("container init process exited");
341 int lxc_set_state(const char *name
, struct lxc_handler
*handler
, lxc_state_t state
)
343 handler
->state
= state
;
344 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
348 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
350 int sigfd
= handler
->sigfd
;
351 int pid
= handler
->pid
;
352 struct lxc_epoll_descr descr
;
354 if (lxc_mainloop_open(&descr
)) {
355 ERROR("failed to create mainloop");
359 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
360 ERROR("failed to add handler for the signal");
361 goto out_mainloop_open
;
364 if (lxc_console_mainloop_add(&descr
, handler
)) {
365 ERROR("failed to add console handler to mainloop");
366 goto out_mainloop_open
;
369 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
370 ERROR("failed to add command handler to mainloop");
371 goto out_mainloop_open
;
374 if (handler
->conf
->need_utmp_watch
) {
375 #if HAVE_SYS_CAPABILITY_H
376 if (lxc_utmp_mainloop_add(&descr
, handler
)) {
377 ERROR("failed to add utmp handler to mainloop");
378 goto out_mainloop_open
;
381 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support");
385 return lxc_mainloop(&descr
, -1);
388 lxc_mainloop_close(&descr
);
394 struct lxc_handler
*lxc_init(const char *name
, struct lxc_conf
*conf
, const char *lxcpath
)
397 struct lxc_handler
*handler
;
399 handler
= malloc(sizeof(*handler
));
403 memset(handler
, 0, sizeof(*handler
));
405 handler
->ttysock
[0] = handler
->ttysock
[1] = -1;
406 handler
->conf
= conf
;
407 handler
->lxcpath
= lxcpath
;
410 for (i
= 0; i
< LXC_NS_MAX
; i
++)
411 handler
->nsfd
[i
] = -1;
415 handler
->name
= strdup(name
);
416 if (!handler
->name
) {
417 ERROR("failed to allocate memory");
421 if (lxc_cmd_init(name
, handler
, lxcpath
))
424 if (lxc_read_seccomp_config(conf
) != 0) {
425 ERROR("failed loading seccomp policy");
426 goto out_close_maincmd_fd
;
429 /* Begin by setting the state to STARTING */
430 if (lxc_set_state(name
, handler
, STARTING
)) {
431 ERROR("failed to set state '%s'", lxc_state2str(STARTING
));
432 goto out_close_maincmd_fd
;
435 /* Start of environment variable setup for hooks */
436 if (name
&& setenv("LXC_NAME", name
, 1)) {
437 SYSERROR("failed to set environment variable for container name");
439 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
440 SYSERROR("failed to set environment variable for config path");
442 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
443 SYSERROR("failed to set environment variable for rootfs mount");
445 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
446 SYSERROR("failed to set environment variable for rootfs mount");
448 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1)) {
449 SYSERROR("failed to set environment variable for console path");
451 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1)) {
452 SYSERROR("failed to set environment variable for console log");
454 if (setenv("LXC_CGNS_AWARE", "1", 1)) {
455 SYSERROR("failed to set LXC_CGNS_AWARE environment variable");
457 /* End of environment variable setup for hooks */
459 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
460 ERROR("failed to run pre-start hooks for container '%s'.", name
);
464 /* the signal fd has to be created before forking otherwise
465 * if the child process exits before we setup the signal fd,
466 * the event will be lost and the command will be stuck */
467 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
468 if (handler
->sigfd
< 0) {
469 ERROR("failed to set sigchild fd handler");
473 /* do this after setting up signals since it might unblock SIGWINCH */
474 if (lxc_console_create(conf
)) {
475 ERROR("failed to create console");
476 goto out_restore_sigmask
;
479 if (ttys_shift_ids(conf
) < 0) {
480 ERROR("Failed to shift tty into container");
481 goto out_restore_sigmask
;
484 INFO("'%s' is initialized", name
);
488 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
490 lxc_delete_tty(&conf
->tty_info
);
492 lxc_set_state(name
, handler
, ABORTING
);
493 out_close_maincmd_fd
:
494 close(conf
->maincmd_fd
);
495 conf
->maincmd_fd
= -1;
498 handler
->name
= NULL
;
504 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
507 pid_t self
= getpid();
508 char *namespaces
[LXC_NS_MAX
+1];
509 size_t namespace_count
= 0;
511 /* The STOPPING state is there for future cleanup code
512 * which can take awhile
514 lxc_set_state(name
, handler
, STOPPING
);
516 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
517 if (handler
->nsfd
[i
] != -1) {
518 rc
= asprintf(&namespaces
[namespace_count
], "%s:/proc/%d/fd/%d",
519 ns_info
[i
].proc_name
, self
, handler
->nsfd
[i
]);
521 SYSERROR("failed to allocate memory");
527 namespaces
[namespace_count
] = NULL
;
529 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1)) {
530 SYSERROR("failed to set environment variable for stop target");
532 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1)) {
533 SYSERROR("failed to set environment variable for stop target");
536 if (run_lxc_hooks(name
, "stop", handler
->conf
, handler
->lxcpath
, namespaces
))
537 ERROR("failed to run stop hooks for container '%s'.", name
);
539 while (namespace_count
--)
540 free(namespaces
[namespace_count
]);
541 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
542 if (handler
->nsfd
[i
] != -1) {
543 close(handler
->nsfd
[i
]);
544 handler
->nsfd
[i
] = -1;
547 lxc_set_state(name
, handler
, STOPPED
);
549 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
))
550 ERROR("failed to run post-stop hooks for container '%s'.", name
);
552 /* reset mask set by setup_signal_fd */
553 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
554 WARN("failed to restore sigprocmask");
556 lxc_console_delete(&handler
->conf
->console
);
557 lxc_delete_tty(&handler
->conf
->tty_info
);
558 close(handler
->conf
->maincmd_fd
);
559 handler
->conf
->maincmd_fd
= -1;
561 if (handler
->ttysock
[0] != -1) {
562 close(handler
->ttysock
[0]);
563 close(handler
->ttysock
[1]);
565 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1) {
566 lxc_destroy_container_on_signal(handler
, name
);
568 cgroup_destroy(handler
);
572 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
576 lxc_set_state(name
, handler
, ABORTING
);
577 if (handler
->pid
> 0)
578 kill(handler
->pid
, SIGKILL
);
579 while ((ret
= waitpid(-1, &status
, 0)) > 0) ;
582 #include <sys/reboot.h>
583 #include <linux/reboot.h>
586 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
587 * in a child pid namespace if container reboot support exists.
588 * Otherwise, it will either succeed or return -EPERM.
590 static int container_reboot_supported(void *arg
)
596 if (ret
== -1 && errno
== EINVAL
)
601 static int must_drop_cap_sys_boot(struct lxc_conf
*conf
)
604 int ret
, cmd
, v
, flags
;
605 long stack_size
= 4096;
606 void *stack
= alloca(stack_size
);
610 f
= fopen("/proc/sys/kernel/ctrl-alt-del", "r");
612 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
616 ret
= fscanf(f
, "%d", &v
);
619 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
622 cmd
= v
? LINUX_REBOOT_CMD_CAD_ON
: LINUX_REBOOT_CMD_CAD_OFF
;
624 flags
= CLONE_NEWPID
| SIGCHLD
;
625 if (!lxc_list_empty(&conf
->id_map
))
626 flags
|= CLONE_NEWUSER
;
629 pid
= __clone2(container_reboot_supported
, stack
, stack_size
, flags
, &cmd
);
632 pid
= clone(container_reboot_supported
, stack
, flags
, &cmd
);
635 if (flags
& CLONE_NEWUSER
)
636 ERROR("failed to clone (%#x): %s (includes CLONE_NEWUSER)", flags
, strerror(errno
));
638 ERROR("failed to clone (%#x): %s", flags
, strerror(errno
));
641 if (wait(&status
) < 0) {
642 SYSERROR("unexpected wait error: %m");
646 if (WEXITSTATUS(status
) != 1)
653 * netpipe is used in the unprivileged case to transfer the ifindexes
654 * from parent to child
656 static int netpipe
= -1;
658 static inline int count_veths(struct lxc_list
*network
)
660 struct lxc_list
*iterator
;
661 struct lxc_netdev
*netdev
;
664 lxc_list_for_each(iterator
, network
) {
665 netdev
= iterator
->elem
;
666 if (netdev
->type
!= LXC_NET_VETH
)
673 static int read_unpriv_netifindex(struct lxc_list
*network
)
675 struct lxc_list
*iterator
;
676 struct lxc_netdev
*netdev
;
680 lxc_list_for_each(iterator
, network
) {
681 netdev
= iterator
->elem
;
682 if (netdev
->type
!= LXC_NET_VETH
)
684 if (!(netdev
->name
= malloc(IFNAMSIZ
))) {
685 ERROR("Out of memory");
689 if (read(netpipe
, netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
698 static int do_start(void *data
)
700 struct lxc_list
*iterator
;
701 struct lxc_handler
*handler
= data
;
703 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
704 SYSERROR("failed to set sigprocmask");
708 /* This prctl must be before the synchro, so if the parent
709 * dies before we set the parent death signal, we will detect
710 * its death with the synchro right after, otherwise we have
711 * a window where the parent can exit before we set the pdeath
712 * signal leading to a unsupervized container.
714 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
715 SYSERROR("failed to set pdeath signal");
719 lxc_sync_fini_parent(handler
);
721 /* don't leak the pinfd to the container */
722 if (handler
->pinfd
>= 0) {
723 close(handler
->pinfd
);
726 /* Tell the parent task it can begin to configure the
727 * container and wait for it to finish
729 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
732 if (read_unpriv_netifindex(&handler
->conf
->network
) < 0)
733 goto out_warn_father
;
736 * if we are in a new user namespace, become root there to have
737 * privilege over our namespace. When using lxc-execute we default to root,
738 * but this can be overriden using the lxc.init_uid and lxc.init_gid
739 * configuration options.
741 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
743 if (handler
->conf
->is_execute
&& handler
->conf
->init_gid
)
744 new_gid
= handler
->conf
->init_gid
;
747 if (handler
->conf
->is_execute
&& handler
->conf
->init_uid
)
748 new_uid
= handler
->conf
->init_uid
;
750 NOTICE("switching to gid/uid %d/%d in new user namespace", new_gid
, new_uid
);
751 if (setgid(new_gid
)) {
753 goto out_warn_father
;
755 if (setuid(new_uid
)) {
757 goto out_warn_father
;
759 if (setgroups(0, NULL
)) {
760 SYSERROR("setgroups");
761 goto out_warn_father
;
765 if (access(handler
->lxcpath
, X_OK
)) {
766 print_top_failing_dir(handler
->lxcpath
);
767 goto out_warn_father
;
770 #if HAVE_SYS_CAPABILITY_H
771 if (handler
->conf
->need_utmp_watch
) {
772 if (prctl(PR_CAPBSET_DROP
, CAP_SYS_BOOT
, 0, 0, 0)) {
773 SYSERROR("failed to remove CAP_SYS_BOOT capability");
774 goto out_warn_father
;
776 DEBUG("Dropped cap_sys_boot");
780 /* Setup the container, ip, names, utsname, ... */
781 if (lxc_setup(handler
)) {
782 ERROR("failed to setup the container");
783 goto out_warn_father
;
786 /* ask father to setup cgroups and wait for him to finish */
787 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
790 /* Set the label to change to when we exec(2) the container's init */
791 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
792 goto out_warn_father
;
794 /* Some init's such as busybox will set sane tty settings on stdin,
795 * stdout, stderr which it thinks is the console. We already set them
796 * the way we wanted on the real terminal, and we want init to do its
797 * setup on its console ie. the pty allocated in lxc_console_create()
798 * so make sure that that pty is stdin,stdout,stderr.
800 if (lxc_console_set_stdfds(handler
) < 0)
801 goto out_warn_father
;
803 /* If we mounted a temporary proc, then unmount it now */
804 tmp_proc_unmount(handler
->conf
);
806 if (lxc_seccomp_load(handler
->conf
) != 0)
807 goto out_warn_father
;
809 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
810 ERROR("failed to run start hooks for container '%s'.", handler
->name
);
811 goto out_warn_father
;
814 /* The clearenv() and putenv() calls have been moved here
815 * to allow us to use environment variables passed to the various
816 * hooks, such as the start hook above. Not all of the
817 * variables like CONFIG_PATH or ROOTFS are valid in this
818 * context but others are. */
820 SYSERROR("failed to clear environment");
821 /* don't error out though */
824 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
825 if (putenv((char *)iterator
->elem
)) {
826 SYSERROR("failed to set environment variable '%s'", (char *)iterator
->elem
);
827 goto out_warn_father
;
831 if (putenv("container=lxc")) {
832 SYSERROR("failed to set environment variable 'container=lxc'");
833 goto out_warn_father
;
836 if (handler
->conf
->pty_names
) {
837 if (putenv(handler
->conf
->pty_names
)) {
838 SYSERROR("failed to set environment variable for container ptys");
839 goto out_warn_father
;
843 close(handler
->sigfd
);
845 if (handler
->backgrounded
&& null_stdfds() < 0)
846 goto out_warn_father
;
848 if (cgns_supported() && unshare(CLONE_NEWCGROUP
) != 0) {
849 SYSERROR("Failed to unshare cgroup namespace");
850 goto out_warn_father
;
853 /* after this call, we are in error because this
854 * ops should not return as it execs */
855 handler
->ops
->start(handler
, handler
->data
);
858 /* we want the parent to know something went wrong, so any
859 * value other than what it expects is ok. */
860 lxc_sync_wake_parent(handler
, LXC_SYNC_POST_CONFIGURE
);
864 static int save_phys_nics(struct lxc_conf
*conf
)
866 struct lxc_list
*iterator
;
867 int am_root
= (getuid() == 0);
872 lxc_list_for_each(iterator
, &conf
->network
) {
873 struct lxc_netdev
*netdev
= iterator
->elem
;
875 if (netdev
->type
!= LXC_NET_PHYS
)
877 conf
->saved_nics
= realloc(conf
->saved_nics
,
878 (conf
->num_savednics
+1)*sizeof(struct saved_nic
));
879 if (!conf
->saved_nics
) {
880 SYSERROR("failed to allocate memory");
883 conf
->saved_nics
[conf
->num_savednics
].ifindex
= netdev
->ifindex
;
884 conf
->saved_nics
[conf
->num_savednics
].orig_name
= strdup(netdev
->link
);
885 if (!conf
->saved_nics
[conf
->num_savednics
].orig_name
) {
886 SYSERROR("failed to allocate memory");
889 INFO("stored saved_nic #%d idx %d name %s", conf
->num_savednics
,
890 conf
->saved_nics
[conf
->num_savednics
].ifindex
,
891 conf
->saved_nics
[conf
->num_savednics
].orig_name
);
892 conf
->num_savednics
++;
898 static int recv_fd(int sock
, int *fd
)
900 if (lxc_abstract_unix_recv_fd(sock
, fd
, NULL
, 0) < 0) {
901 SYSERROR("Error receiving tty fd from child");
909 static int recv_ttys_from_child(struct lxc_handler
*handler
)
911 struct lxc_conf
*conf
= handler
->conf
;
912 int i
, sock
= handler
->ttysock
[1];
913 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
918 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
)*conf
->tty
);
919 if (!tty_info
->pty_info
) {
920 SYSERROR("failed to allocate pty_info");
924 for (i
= 0; i
< conf
->tty
; i
++) {
925 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
927 if (recv_fd(sock
, &pty_info
->slave
) < 0 ||
928 recv_fd(sock
, &pty_info
->master
) < 0) {
929 ERROR("Error receiving tty info from child");
933 tty_info
->nbtty
= conf
->tty
;
938 void resolve_clone_flags(struct lxc_handler
*handler
)
940 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
942 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
943 INFO("Cloning a new user namespace");
944 handler
->clone_flags
|= CLONE_NEWUSER
;
947 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
948 if (!lxc_requests_empty_network(handler
))
949 handler
->clone_flags
|= CLONE_NEWNET
;
951 INFO("Inheriting a net namespace");
954 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1) {
955 handler
->clone_flags
|= CLONE_NEWIPC
;
957 INFO("Inheriting an IPC namespace");
960 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1) {
961 handler
->clone_flags
|= CLONE_NEWUTS
;
963 INFO("Inheriting a UTS namespace");
967 static int lxc_spawn(struct lxc_handler
*handler
)
969 int failed_before_rename
= 0;
970 const char *name
= handler
->name
;
972 bool cgroups_connected
= false;
973 int saved_ns_fd
[LXC_NS_MAX
];
974 int preserve_mask
= 0, i
;
975 int netpipepair
[2], nveths
;
979 for (i
= 0; i
< LXC_NS_MAX
; i
++)
980 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
981 preserve_mask
|= ns_info
[i
].clone_flag
;
983 if (lxc_sync_init(handler
))
986 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, handler
->ttysock
) < 0) {
987 lxc_sync_fini(handler
);
991 resolve_clone_flags(handler
);
993 if (handler
->clone_flags
& CLONE_NEWNET
) {
994 if (!lxc_list_empty(&handler
->conf
->network
)) {
996 /* Find gateway addresses from the link device, which is
997 * no longer accessible inside the container. Do this
998 * before creating network interfaces, since goto
999 * out_delete_net does not work before lxc_clone. */
1000 if (lxc_find_gateway_addresses(handler
)) {
1001 ERROR("failed to find gateway addresses");
1002 lxc_sync_fini(handler
);
1006 /* that should be done before the clone because we will
1007 * fill the netdev index and use them in the child
1009 if (lxc_create_network(handler
)) {
1010 ERROR("failed to create the network");
1011 lxc_sync_fini(handler
);
1016 if (save_phys_nics(handler
->conf
)) {
1017 ERROR("failed to save physical nic info");
1022 if (!cgroup_init(handler
)) {
1023 ERROR("failed initializing cgroup support");
1024 goto out_delete_net
;
1027 cgroups_connected
= true;
1029 if (!cgroup_create(handler
)) {
1030 ERROR("failed creating cgroups");
1031 goto out_delete_net
;
1035 * if the rootfs is not a blockdev, prevent the container from
1036 * marking it readonly.
1038 * if the container is unprivileged then skip rootfs pinning
1040 if (lxc_list_empty(&handler
->conf
->id_map
)) {
1041 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
1042 if (handler
->pinfd
== -1)
1043 INFO("failed to pin the container's rootfs");
1046 if (!preserve_ns(saved_ns_fd
, preserve_mask
, getpid(), &errmsg
)) {
1047 SYSERROR("Failed to preserve requested namespaces: %s",
1048 errmsg
? errmsg
: "(Out of memory)");
1050 goto out_delete_net
;
1052 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
1053 goto out_delete_net
;
1055 if (am_unpriv() && (nveths
= count_veths(&handler
->conf
->network
))) {
1056 if (pipe(netpipepair
) < 0) {
1057 SYSERROR("Error creating pipe");
1058 goto out_delete_net
;
1060 /* store netpipe in the global var for do_start's use */
1061 netpipe
= netpipepair
[0];
1064 /* Create a process in a new set of namespaces */
1065 handler
->pid
= lxc_clone(do_start
, handler
, handler
->clone_flags
);
1066 if (handler
->pid
< 0) {
1067 SYSERROR("failed to fork into a new namespace");
1068 goto out_delete_net
;
1071 if (!preserve_ns(handler
->nsfd
, handler
->clone_flags
| preserve_mask
, handler
->pid
, &errmsg
)) {
1072 INFO("Failed to store namespace references for stop hook: %s",
1073 errmsg
? errmsg
: "(Out of memory)");
1077 if (attach_ns(saved_ns_fd
))
1078 WARN("failed to restore saved namespaces");
1080 lxc_sync_fini_child(handler
);
1082 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
))
1083 failed_before_rename
= 1;
1085 if (!cgroup_create_legacy(handler
)) {
1086 ERROR("failed to setup the legacy cgroups for %s", name
);
1087 goto out_delete_net
;
1089 if (!cgroup_setup_limits(handler
, false)) {
1090 ERROR("failed to setup the cgroup limits for '%s'", name
);
1091 goto out_delete_net
;
1094 if (!cgroup_enter(handler
))
1095 goto out_delete_net
;
1097 if (!cgroup_chown(handler
))
1098 goto out_delete_net
;
1100 if (failed_before_rename
)
1101 goto out_delete_net
;
1103 /* Create the network configuration */
1104 if (handler
->clone_flags
& CLONE_NEWNET
) {
1105 if (lxc_assign_network(handler
->lxcpath
, handler
->name
,
1106 &handler
->conf
->network
, handler
->pid
)) {
1107 ERROR("failed to create the configured network");
1108 goto out_delete_net
;
1112 if (netpipe
!= -1) {
1113 struct lxc_list
*iterator
;
1114 struct lxc_netdev
*netdev
;
1117 lxc_list_for_each(iterator
, &handler
->conf
->network
) {
1118 netdev
= iterator
->elem
;
1119 if (netdev
->type
!= LXC_NET_VETH
)
1121 if (write(netpipepair
[1], netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
1122 ERROR("Error writing veth name to container");
1123 goto out_delete_net
;
1126 close(netpipepair
[1]);
1129 /* map the container uids - the container became an invalid
1130 * userid the moment it was cloned with CLONE_NEWUSER - this
1131 * call doesn't change anything immediately, but allows the
1132 * container to setuid(0) (0 being mapped to something else on
1133 * the host) later to become a valid uid again */
1134 if (lxc_map_ids(&handler
->conf
->id_map
, handler
->pid
)) {
1135 ERROR("failed to set up id mapping");
1136 goto out_delete_net
;
1139 /* Tell the child to continue its initialization. we'll get
1140 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
1142 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1143 goto out_delete_net
;
1145 if (!cgroup_setup_limits(handler
, true)) {
1146 ERROR("failed to setup the devices cgroup for '%s'", name
);
1147 goto out_delete_net
;
1150 cgroup_disconnect();
1151 cgroups_connected
= false;
1153 /* read tty fds allocated by child */
1154 if (recv_ttys_from_child(handler
) < 0) {
1155 ERROR("failed to receive tty info from child");
1156 goto out_delete_net
;
1159 /* Tell the child to complete its initialization and wait for
1160 * it to exec or return an error. (the child will never
1161 * return LXC_SYNC_POST_CGROUP+1. It will either close the
1162 * sync pipe, causing lxc_sync_barrier_child to return
1163 * success, or return a different value, causing us to error
1166 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1169 if (detect_shared_rootfs())
1170 umount2(handler
->conf
->rootfs
.mount
, MNT_DETACH
);
1172 if (handler
->ops
->post_start(handler
, handler
->data
))
1175 if (lxc_set_state(name
, handler
, RUNNING
)) {
1176 ERROR("failed to set state to %s",
1177 lxc_state2str(RUNNING
));
1181 lxc_sync_fini(handler
);
1186 if (cgroups_connected
)
1187 cgroup_disconnect();
1188 if (handler
->clone_flags
& CLONE_NEWNET
)
1189 lxc_delete_network(handler
);
1191 lxc_abort(name
, handler
);
1192 lxc_sync_fini(handler
);
1193 if (handler
->pinfd
>= 0) {
1194 close(handler
->pinfd
);
1195 handler
->pinfd
= -1;
1201 int get_netns_fd(int pid
)
1203 char path
[MAXPATHLEN
];
1206 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/net", pid
);
1207 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1208 WARN("Failed to pin netns file for pid %d", pid
);
1212 fd
= open(path
, O_RDONLY
);
1214 WARN("Failed to pin netns file %s for pid %d: %s",
1215 path
, pid
, strerror(errno
));
1221 int __lxc_start(const char *name
, struct lxc_conf
*conf
,
1222 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1225 struct lxc_handler
*handler
;
1230 handler
= lxc_init(name
, conf
, lxcpath
);
1232 ERROR("failed to initialize the container");
1236 handler
->data
= data
;
1237 handler
->backgrounded
= backgrounded
;
1239 if (must_drop_cap_sys_boot(handler
->conf
)) {
1240 #if HAVE_SYS_CAPABILITY_H
1241 DEBUG("Dropping cap_sys_boot");
1243 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
1246 DEBUG("Not dropping cap_sys_boot or watching utmp");
1247 handler
->conf
->need_utmp_watch
= 0;
1250 if (!attach_block_device(handler
->conf
)) {
1251 ERROR("Failure attaching block device");
1252 goto out_fini_nonet
;
1255 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1256 /* if the backing store is a device, mount it here and now */
1257 if (rootfs_is_blockdev(conf
)) {
1258 if (unshare(CLONE_NEWNS
) < 0) {
1259 ERROR("Error unsharing mounts");
1260 goto out_fini_nonet
;
1262 remount_all_slave();
1263 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1264 ERROR("Error setting up rootfs mount as root before spawn");
1265 goto out_fini_nonet
;
1267 INFO("Set up container rootfs as host root");
1271 err
= lxc_spawn(handler
);
1273 ERROR("failed to spawn '%s'", name
);
1274 goto out_detach_blockdev
;
1277 handler
->conf
->reboot
= 0;
1279 netnsfd
= get_netns_fd(handler
->pid
);
1281 err
= lxc_poll(name
, handler
);
1283 ERROR("mainloop exited with an error");
1289 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1293 * If the child process exited but was not signaled,
1294 * it didn't call reboot. This should mean it was an
1295 * lxc-execute which simply exited. In any case, treat
1298 if (WIFSIGNALED(status
)) {
1299 switch(WTERMSIG(status
)) {
1300 case SIGINT
: /* halt */
1301 DEBUG("Container halting");
1303 case SIGHUP
: /* reboot */
1304 DEBUG("Container rebooting");
1305 handler
->conf
->reboot
= 1;
1307 case SIGSYS
: /* seccomp */
1308 DEBUG("Container violated its seccomp policy");
1311 DEBUG("unknown exit status for init: %d", WTERMSIG(status
));
1316 DEBUG("Pushing physical nics back to host namespace");
1317 lxc_rename_phys_nics_on_shutdown(netnsfd
, handler
->conf
);
1319 DEBUG("Tearing down virtual network devices used by container");
1320 lxc_delete_network(handler
);
1325 if (handler
->pinfd
>= 0) {
1326 close(handler
->pinfd
);
1327 handler
->pinfd
= -1;
1330 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1331 err
= lxc_error_set_and_log(handler
->pid
, status
);
1333 lxc_delete_network(handler
);
1335 out_detach_blockdev
:
1336 detach_block_device(handler
->conf
);
1339 lxc_fini(name
, handler
);
1343 lxc_abort(name
, handler
);
1351 static int start(struct lxc_handler
*handler
, void* data
)
1353 struct start_args
*arg
= data
;
1355 NOTICE("exec'ing '%s'", arg
->argv
[0]);
1357 execvp(arg
->argv
[0], arg
->argv
);
1358 SYSERROR("failed to exec %s", arg
->argv
[0]);
1362 static int post_start(struct lxc_handler
*handler
, void* data
)
1364 struct start_args
*arg
= data
;
1366 NOTICE("'%s' started with pid '%d'", arg
->argv
[0], handler
->pid
);
1370 static struct lxc_operations start_ops
= {
1372 .post_start
= post_start
1375 int lxc_start(const char *name
, char *const argv
[], struct lxc_conf
*conf
,
1376 const char *lxcpath
, bool backgrounded
)
1378 struct start_args start_arg
= {
1382 conf
->need_utmp_watch
= 1;
1383 return __lxc_start(name
, conf
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1386 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1389 char destroy
[MAXPATHLEN
];
1392 struct lxc_container
*c
;
1393 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1394 bret
= do_destroy_container(handler
->conf
);
1396 ERROR("Error destroying rootfs for %s", name
);
1400 INFO("Destroyed rootfs for %s", name
);
1402 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1403 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1404 ERROR("Error printing path for %s", name
);
1405 ERROR("Error destroying directory for %s", name
);
1409 c
= lxc_container_new(name
, handler
->lxcpath
);
1411 if (container_disk_lock(c
)) {
1412 INFO("Could not update lxc_snapshots file");
1413 lxc_container_put(c
);
1415 mod_all_rdeps(c
, false);
1416 container_disk_unlock(c
);
1417 lxc_container_put(c
);
1422 ret
= userns_exec_1(handler
->conf
, lxc_rmdir_onedev_wrapper
, destroy
);
1424 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1427 ERROR("Error destroying directory for %s", name
);
1430 INFO("Destroyed directory for %s", name
);
1433 static int lxc_rmdir_onedev_wrapper(void *data
)
1435 char *arg
= (char *) data
;
1436 return lxc_rmdir_onedev(arg
, NULL
);
1439 static bool do_destroy_container(struct lxc_conf
*conf
) {
1441 if (userns_exec_1(conf
, bdev_destroy_wrapper
, conf
) < 0)
1445 return bdev_destroy(conf
);