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>
47 #include <sys/syscall.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
70 #include "namespace.h"
72 #include "lxcseccomp.h"
75 lxc_log_define(lxc_start
, lxc
);
77 static int match_fd(int fd
)
79 return (fd
== 0 || fd
== 1 || fd
== 2);
82 int lxc_check_inherited(struct lxc_conf
*conf
, int fd_to_ignore
)
84 struct dirent dirent
, *direntp
;
89 dir
= opendir("/proc/self/fd");
91 WARN("failed to open directory: %m");
97 while (!readdir_r(dir
, &dirent
, &direntp
)) {
101 if (!strcmp(direntp
->d_name
, "."))
104 if (!strcmp(direntp
->d_name
, ".."))
107 fd
= atoi(direntp
->d_name
);
109 if (fd
== fddir
|| fd
== lxc_log_fd
|| fd
== fd_to_ignore
)
115 if (conf
->close_all_fds
) {
118 INFO("closed inherited fd %d", fd
);
121 WARN("inherited fd %d", fd
);
124 closedir(dir
); /* cannot fail */
128 static int setup_signal_fd(sigset_t
*oldmask
)
133 /* Block everything except serious error signals */
134 if (sigfillset(&mask
) ||
135 sigdelset(&mask
, SIGILL
) ||
136 sigdelset(&mask
, SIGSEGV
) ||
137 sigdelset(&mask
, SIGBUS
) ||
138 sigdelset(&mask
, SIGWINCH
) ||
139 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
140 SYSERROR("failed to set signal mask");
144 fd
= signalfd(-1, &mask
, 0);
146 SYSERROR("failed to create the signal fd");
150 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
151 SYSERROR("failed to set sigfd to close-on-exec");
156 DEBUG("sigchild handler set");
161 static int signal_handler(int fd
, void *data
,
162 struct lxc_epoll_descr
*descr
)
164 struct signalfd_siginfo siginfo
;
168 bool init_died
= false;
170 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
172 ERROR("failed to read signal info");
176 if (ret
!= sizeof(siginfo
)) {
177 ERROR("unexpected siginfo size");
181 // check whether init is running
183 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
184 if (ret
== 0 && info
.si_pid
== *pid
) {
188 if (siginfo
.ssi_signo
!= SIGCHLD
) {
189 kill(*pid
, siginfo
.ssi_signo
);
190 INFO("forwarded signal %d to pid %d", siginfo
.ssi_signo
, *pid
);
191 return init_died
? 1 : 0;
194 if (siginfo
.ssi_code
== CLD_STOPPED
||
195 siginfo
.ssi_code
== CLD_CONTINUED
) {
196 INFO("container init process was stopped/continued");
197 return init_died
? 1 : 0;
200 /* more robustness, protect ourself from a SIGCHLD sent
201 * by a process different from the container init
203 if (siginfo
.ssi_pid
!= *pid
) {
204 WARN("invalid pid for SIGCHLD");
205 return init_died
? 1 : 0;
208 DEBUG("container init process exited");
212 int lxc_set_state(const char *name
, struct lxc_handler
*handler
, lxc_state_t state
)
214 handler
->state
= state
;
215 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
219 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
221 int sigfd
= handler
->sigfd
;
222 int pid
= handler
->pid
;
223 struct lxc_epoll_descr descr
;
225 if (lxc_mainloop_open(&descr
)) {
226 ERROR("failed to create mainloop");
230 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
231 ERROR("failed to add handler for the signal");
232 goto out_mainloop_open
;
235 if (lxc_console_mainloop_add(&descr
, handler
)) {
236 ERROR("failed to add console handler to mainloop");
237 goto out_mainloop_open
;
240 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
241 ERROR("failed to add command handler to mainloop");
242 goto out_mainloop_open
;
245 if (handler
->conf
->need_utmp_watch
) {
246 #if HAVE_SYS_CAPABILITY_H
247 if (lxc_utmp_mainloop_add(&descr
, handler
)) {
248 ERROR("failed to add utmp handler to mainloop");
249 goto out_mainloop_open
;
252 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support\n");
256 return lxc_mainloop(&descr
, -1);
259 lxc_mainloop_close(&descr
);
265 struct lxc_handler
*lxc_init(const char *name
, struct lxc_conf
*conf
, const char *lxcpath
)
267 struct lxc_handler
*handler
;
269 handler
= malloc(sizeof(*handler
));
273 memset(handler
, 0, sizeof(*handler
));
275 handler
->conf
= conf
;
276 handler
->lxcpath
= lxcpath
;
279 apparmor_handler_init(handler
);
280 handler
->name
= strdup(name
);
281 if (!handler
->name
) {
282 ERROR("failed to allocate memory");
286 if (lxc_cmd_init(name
, handler
, lxcpath
))
289 if (lxc_read_seccomp_config(conf
) != 0) {
290 ERROR("failed loading seccomp policy");
291 goto out_close_maincmd_fd
;
294 /* Begin by setting the state to STARTING */
295 if (lxc_set_state(name
, handler
, STARTING
)) {
296 ERROR("failed to set state '%s'", lxc_state2str(STARTING
));
297 goto out_close_maincmd_fd
;
300 /* Start of environment variable setup for hooks */
301 if (setenv("LXC_NAME", name
, 1)) {
302 SYSERROR("failed to set environment variable for container name");
304 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
305 SYSERROR("failed to set environment variable for config path");
307 if (setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
308 SYSERROR("failed to set environment variable for rootfs mount");
310 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
311 SYSERROR("failed to set environment variable for rootfs mount");
313 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1)) {
314 SYSERROR("failed to set environment variable for console path");
316 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1)) {
317 SYSERROR("failed to set environment variable for console log");
319 /* End of environment variable setup for hooks */
321 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
322 ERROR("failed to run pre-start hooks for container '%s'.", name
);
326 if (lxc_create_tty(name
, conf
)) {
327 ERROR("failed to create the ttys");
331 /* the signal fd has to be created before forking otherwise
332 * if the child process exits before we setup the signal fd,
333 * the event will be lost and the command will be stuck */
334 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
335 if (handler
->sigfd
< 0) {
336 ERROR("failed to set sigchild fd handler");
340 /* do this after setting up signals since it might unblock SIGWINCH */
341 if (lxc_console_create(conf
)) {
342 ERROR("failed to create console");
343 goto out_restore_sigmask
;
346 INFO("'%s' is initialized", name
);
350 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
352 lxc_delete_tty(&conf
->tty_info
);
354 lxc_set_state(name
, handler
, ABORTING
);
355 out_close_maincmd_fd
:
356 close(conf
->maincmd_fd
);
357 conf
->maincmd_fd
= -1;
360 handler
->name
= NULL
;
366 static void lxc_fini(const char *name
, struct lxc_handler
*handler
)
368 /* The STOPPING state is there for future cleanup code
369 * which can take awhile
371 lxc_set_state(name
, handler
, STOPPING
);
372 lxc_set_state(name
, handler
, STOPPED
);
374 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
))
375 ERROR("failed to run post-stop hooks for container '%s'.", name
);
377 /* reset mask set by setup_signal_fd */
378 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
379 WARN("failed to restore sigprocmask");
381 lxc_console_delete(&handler
->conf
->console
);
382 lxc_delete_tty(&handler
->conf
->tty_info
);
383 close(handler
->conf
->maincmd_fd
);
384 handler
->conf
->maincmd_fd
= -1;
386 if (handler
->cgroup
) {
387 lxc_cgroup_destroy_desc(handler
->cgroup
);
388 handler
->cgroup
= NULL
;
393 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
397 lxc_set_state(name
, handler
, ABORTING
);
398 if (handler
->pid
> 0)
399 kill(handler
->pid
, SIGKILL
);
400 while ((ret
= waitpid(-1, &status
, 0)) > 0) ;
403 #include <sys/reboot.h>
404 #include <linux/reboot.h>
407 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
408 * in a child pid namespace if container reboot support exists.
409 * Otherwise, it will either succeed or return -EPERM.
411 static int container_reboot_supported(void *arg
)
417 if (ret
== -1 && errno
== EINVAL
)
422 static int must_drop_cap_sys_boot(struct lxc_conf
*conf
)
424 FILE *f
= fopen("/proc/sys/kernel/ctrl-alt-del", "r");
425 int ret
, cmd
, v
, flags
;
426 long stack_size
= 4096;
427 void *stack
= alloca(stack_size
);
432 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
436 ret
= fscanf(f
, "%d", &v
);
439 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
442 cmd
= v
? LINUX_REBOOT_CMD_CAD_ON
: LINUX_REBOOT_CMD_CAD_OFF
;
444 flags
= CLONE_NEWPID
| SIGCHLD
;
445 if (!lxc_list_empty(&conf
->id_map
))
446 flags
|= CLONE_NEWUSER
;
449 pid
= __clone2(container_reboot_supported
, stack
, stack_size
, flags
, &cmd
);
452 pid
= clone(container_reboot_supported
, stack
, flags
, &cmd
);
455 SYSERROR("failed to clone\n");
458 if (wait(&status
) < 0) {
459 SYSERROR("unexpected wait error: %m\n");
463 if (WEXITSTATUS(status
) != 1)
469 static int do_start(void *data
)
471 struct lxc_handler
*handler
= data
;
473 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
474 SYSERROR("failed to set sigprocmask");
478 /* This prctl must be before the synchro, so if the parent
479 * dies before we set the parent death signal, we will detect
480 * its death with the synchro right after, otherwise we have
481 * a window where the parent can exit before we set the pdeath
482 * signal leading to a unsupervized container.
484 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
485 SYSERROR("failed to set pdeath signal");
489 lxc_sync_fini_parent(handler
);
491 /* don't leak the pinfd to the container */
492 if (handler
->pinfd
>= 0)
493 close(handler
->pinfd
);
495 /* Tell the parent task it can begin to configure the
496 * container and wait for it to finish
498 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
502 * if we are in a new user namespace, become root there to have
503 * privilege over our namespace
505 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
506 NOTICE("switching to gid/uid 0 in new user namespace");
509 goto out_warn_father
;
513 goto out_warn_father
;
517 #if HAVE_SYS_CAPABILITY_H
518 if (handler
->conf
->need_utmp_watch
) {
519 if (prctl(PR_CAPBSET_DROP
, CAP_SYS_BOOT
, 0, 0, 0)) {
520 SYSERROR("failed to remove CAP_SYS_BOOT capability");
521 goto out_warn_father
;
523 DEBUG("Dropped cap_sys_boot\n");
527 /* Setup the container, ip, names, utsname, ... */
528 if (lxc_setup(handler
->name
, handler
->conf
, handler
->lxcpath
)) {
529 ERROR("failed to setup the container");
530 goto out_warn_father
;
533 /* ask father to setup cgroups and wait for him to finish */
534 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
537 if (apparmor_load(handler
) < 0)
538 goto out_warn_father
;
540 if (lxc_seccomp_load(handler
->conf
) != 0)
541 goto out_warn_father
;
543 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
544 ERROR("failed to run start hooks for container '%s'.", handler
->name
);
545 goto out_warn_father
;
548 /* The clearenv() and putenv() calls have been moved here
549 * to allow us to use enviroment variables passed to the various
550 * hooks, such as the start hook above. Not all of the
551 * variables like CONFIG_PATH or ROOTFS are valid in this
552 * context but others are. */
554 SYSERROR("failed to clear environment");
555 /* don't error out though */
558 if (putenv("container=lxc")) {
559 SYSERROR("failed to set environment variable");
560 goto out_warn_father
;
563 close(handler
->sigfd
);
565 /* after this call, we are in error because this
566 * ops should not return as it execs */
567 handler
->ops
->start(handler
, handler
->data
);
570 /* we want the parent to know something went wrong, so any
571 * value other than what it expects is ok. */
572 lxc_sync_wake_parent(handler
, LXC_SYNC_POST_CONFIGURE
);
576 int save_phys_nics(struct lxc_conf
*conf
)
578 struct lxc_list
*iterator
;
580 lxc_list_for_each(iterator
, &conf
->network
) {
581 struct lxc_netdev
*netdev
= iterator
->elem
;
583 if (netdev
->type
!= LXC_NET_PHYS
)
585 conf
->saved_nics
= realloc(conf
->saved_nics
,
586 (conf
->num_savednics
+1)*sizeof(struct saved_nic
));
587 if (!conf
->saved_nics
) {
588 SYSERROR("failed to allocate memory");
591 conf
->saved_nics
[conf
->num_savednics
].ifindex
= netdev
->ifindex
;
592 conf
->saved_nics
[conf
->num_savednics
].orig_name
= strdup(netdev
->link
);
593 if (!conf
->saved_nics
[conf
->num_savednics
].orig_name
) {
594 SYSERROR("failed to allocate memory");
597 INFO("stored saved_nic #%d idx %d name %s\n", conf
->num_savednics
,
598 conf
->saved_nics
[conf
->num_savednics
].ifindex
,
599 conf
->saved_nics
[conf
->num_savednics
].orig_name
);
600 conf
->num_savednics
++;
606 extern bool is_in_subcgroup(int pid
, const char *subsystem
, struct cgroup_desc
*d
);
607 int lxc_spawn(struct lxc_handler
*handler
)
609 int failed_before_rename
= 0;
610 const char *name
= handler
->name
;
612 if (lxc_sync_init(handler
))
615 handler
->clone_flags
= CLONE_NEWUTS
|CLONE_NEWPID
|CLONE_NEWIPC
|CLONE_NEWNS
;
616 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
617 INFO("Cloning a new user namespace");
618 handler
->clone_flags
|= CLONE_NEWUSER
;
620 if (!lxc_list_empty(&handler
->conf
->network
)) {
622 handler
->clone_flags
|= CLONE_NEWNET
;
624 /* Find gateway addresses from the link device, which is
625 * no longer accessible inside the container. Do this
626 * before creating network interfaces, since goto
627 * out_delete_net does not work before lxc_clone. */
628 if (lxc_find_gateway_addresses(handler
)) {
629 ERROR("failed to find gateway addresses");
630 lxc_sync_fini(handler
);
634 /* that should be done before the clone because we will
635 * fill the netdev index and use them in the child
637 if (lxc_create_network(handler
)) {
638 ERROR("failed to create the network");
639 lxc_sync_fini(handler
);
644 if (save_phys_nics(handler
->conf
)) {
645 ERROR("failed to save physical nic info");
650 * if the rootfs is not a blockdev, prevent the container from
651 * marking it readonly.
654 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
655 if (handler
->pinfd
== -1) {
656 ERROR("failed to pin the container's rootfs");
660 /* Create a process in a new set of namespaces */
661 handler
->pid
= lxc_clone(do_start
, handler
, handler
->clone_flags
);
662 if (handler
->pid
< 0) {
663 SYSERROR("failed to fork into a new namespace");
667 lxc_sync_fini_child(handler
);
669 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
))
670 failed_before_rename
= 1;
672 if ((handler
->cgroup
= lxc_cgroup_path_create(name
)) == NULL
)
675 if (setup_cgroup(handler
, &handler
->conf
->cgroup
)) {
676 ERROR("failed to setup the cgroups for '%s'", name
);
680 if (lxc_cgroup_enter(handler
->cgroup
, handler
->pid
) < 0)
683 if (failed_before_rename
)
686 /* Create the network configuration */
687 if (handler
->clone_flags
& CLONE_NEWNET
) {
688 if (lxc_assign_network(&handler
->conf
->network
, handler
->pid
)) {
689 ERROR("failed to create the configured network");
694 /* map the container uids - the container became an invalid
695 * userid the moment it was cloned with CLONE_NEWUSER - this
696 * call doesn't change anything immediately, but allows the
697 * container to setuid(0) (0 being mapped to something else on
698 * the host) later to become a valid uid again */
699 if (lxc_map_ids(&handler
->conf
->id_map
, handler
->pid
)) {
700 ERROR("failed to set up id mapping");
704 /* Tell the child to continue its initialization. we'll get
705 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
707 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
710 if (setup_cgroup_devices(handler
, &handler
->conf
->cgroup
)) {
711 ERROR("failed to setup the devices cgroup for '%s'", name
);
715 /* Tell the child to complete its initialization and wait for
716 * it to exec or return an error. (the child will never
717 * return LXC_SYNC_POST_CGROUP+1. It will either close the
718 * sync pipe, causing lxc_sync_barrier_child to return
719 * success, or return a different value, causing us to error
722 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
725 if (detect_shared_rootfs())
726 umount2(handler
->conf
->rootfs
.mount
, MNT_DETACH
);
728 /* If child is in a fresh user namespace, chown his ptys for
730 if (uid_shift_ttys(handler
->pid
, handler
->conf
))
731 DEBUG("Failed to chown ptys.\n");
733 if (handler
->ops
->post_start(handler
, handler
->data
))
736 if (lxc_set_state(name
, handler
, RUNNING
)) {
737 ERROR("failed to set state to %s",
738 lxc_state2str(RUNNING
));
742 lxc_sync_fini(handler
);
747 if (handler
->clone_flags
& CLONE_NEWNET
)
748 lxc_delete_network(handler
);
750 lxc_abort(name
, handler
);
751 lxc_sync_fini(handler
);
752 if (handler
->pinfd
>= 0) {
753 close(handler
->pinfd
);
760 int __lxc_start(const char *name
, struct lxc_conf
*conf
,
761 struct lxc_operations
* ops
, void *data
, const char *lxcpath
)
763 struct lxc_handler
*handler
;
767 handler
= lxc_init(name
, conf
, lxcpath
);
769 ERROR("failed to initialize the container");
773 handler
->data
= data
;
775 if (must_drop_cap_sys_boot(handler
->conf
)) {
776 #if HAVE_SYS_CAPABILITY_H
777 DEBUG("Dropping cap_sys_boot\n");
779 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported\n");
782 DEBUG("Not dropping cap_sys_boot or watching utmp\n");
783 handler
->conf
->need_utmp_watch
= 0;
786 err
= lxc_spawn(handler
);
788 ERROR("failed to spawn '%s'", name
);
792 err
= lxc_poll(name
, handler
);
794 ERROR("mainloop exited with an error");
798 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
802 * If the child process exited but was not signaled,
803 * it didn't call reboot. This should mean it was an
804 * lxc-execute which simply exited. In any case, treat
807 if (WIFSIGNALED(status
)) {
808 switch(WTERMSIG(status
)) {
809 case SIGINT
: /* halt */
810 DEBUG("Container halting");
812 case SIGHUP
: /* reboot */
813 DEBUG("Container rebooting");
814 handler
->conf
->reboot
= 1;
817 DEBUG("unknown exit status for init: %d\n", WTERMSIG(status
));
822 lxc_rename_phys_nics_on_shutdown(handler
->conf
);
824 if (handler
->pinfd
>= 0) {
825 close(handler
->pinfd
);
829 err
= lxc_error_set_and_log(handler
->pid
, status
);
831 lxc_delete_network(handler
);
834 lxc_fini(name
, handler
);
838 lxc_abort(name
, handler
);
846 static int start(struct lxc_handler
*handler
, void* data
)
848 struct start_args
*arg
= data
;
850 NOTICE("exec'ing '%s'", arg
->argv
[0]);
852 execvp(arg
->argv
[0], arg
->argv
);
853 SYSERROR("failed to exec %s", arg
->argv
[0]);
857 static int post_start(struct lxc_handler
*handler
, void* data
)
859 struct start_args
*arg
= data
;
861 NOTICE("'%s' started with pid '%d'", arg
->argv
[0], handler
->pid
);
865 static struct lxc_operations start_ops
= {
867 .post_start
= post_start
870 int lxc_start(const char *name
, char *const argv
[], struct lxc_conf
*conf
,
873 struct start_args start_arg
= {
877 if (lxc_check_inherited(conf
, -1))
880 conf
->need_utmp_watch
= 1;
881 return __lxc_start(name
, conf
, &start_ops
, &start_arg
, lxcpath
);