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
67 #include "lxcseccomp.h"
71 #include "namespace.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
},
86 [LXC_NS_CGROUP
] = {"cgroup", CLONE_NEWCGROUP
}
89 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
90 static bool do_destroy_container(struct lxc_conf
*conf
);
91 static int lxc_rmdir_onedev_wrapper(void *data
);
92 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
95 static void print_top_failing_dir(const char *path
)
97 size_t len
= strlen(path
);
98 char *copy
= alloca(len
+ 1), *p
, *e
, saved
;
104 while (p
< e
&& *p
== '/')
106 while (p
< e
&& *p
!= '/')
110 if (access(copy
, X_OK
)) {
111 SYSERROR("could not access %s. Please grant it 'x' " \
112 "access, or add an ACL for the container root.",
120 static void close_ns(int ns_fd
[LXC_NS_MAX
]) {
123 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
132 * preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
134 * Return true on success, false on failure. On failure, leave an error
135 * message in *errmsg, which caller must free.
137 static bool preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
,
141 char path
[MAXPATHLEN
];
143 for (i
= 0; i
< LXC_NS_MAX
; i
++)
146 snprintf(path
, MAXPATHLEN
, "/proc/%d/ns", pid
);
147 if (access(path
, X_OK
)) {
148 if (asprintf(errmsg
, "Kernel does not support setns.") == -1)
153 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
154 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
156 snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
,
157 ns_info
[i
].proc_name
);
158 ns_fd
[i
] = open(path
, O_RDONLY
| O_CLOEXEC
);
166 if (errno
== ENOENT
) {
167 ret
= asprintf(errmsg
, "Kernel does not support setns for %s",
168 ns_info
[i
].proc_name
);
170 ret
= asprintf(errmsg
, "Failed to open %s: %s",
171 path
, strerror(errno
));
179 static int attach_ns(const int ns_fd
[LXC_NS_MAX
]) {
182 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
186 if (setns(ns_fd
[i
], 0) != 0)
192 SYSERROR("failed to set namespace '%s'", ns_info
[i
].proc_name
);
196 static int match_fd(int fd
)
198 return (fd
== 0 || fd
== 1 || fd
== 2);
202 * Check for any fds we need to close
203 * * if fd_to_ignore != -1, then if we find that fd open we will ignore it.
204 * * By default we warn about open fds we find.
205 * * If closeall is true, we will close open fds.
206 * * If lxc-start was passed "-C", then conf->close_all_fds will be true,
207 * in which case we also close all open fds.
208 * * A daemonized container will always pass closeall=true.
210 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
, int fd_to_ignore
)
212 struct dirent
*direntp
;
216 if (conf
&& conf
->close_all_fds
)
220 dir
= opendir("/proc/self/fd");
222 WARN("failed to open directory: %m");
228 while ((direntp
= readdir(dir
))) {
232 if (!strcmp(direntp
->d_name
, "."))
235 if (!strcmp(direntp
->d_name
, ".."))
238 fd
= atoi(direntp
->d_name
);
240 if (fd
== fddir
|| fd
== lxc_log_fd
|| fd
== fd_to_ignore
)
243 if (current_config
&& fd
== current_config
->logfd
)
252 INFO("closed inherited fd %d", fd
);
255 WARN("inherited fd %d", fd
);
259 * only enable syslog at this point to avoid the above logging function
260 * to open a new fd and make the check_inherited function enter an
263 lxc_log_enable_syslog();
265 closedir(dir
); /* cannot fail */
269 static int setup_signal_fd(sigset_t
*oldmask
)
274 /* Block everything except serious error signals */
275 if (sigfillset(&mask
) ||
276 sigdelset(&mask
, SIGILL
) ||
277 sigdelset(&mask
, SIGSEGV
) ||
278 sigdelset(&mask
, SIGBUS
) ||
279 sigdelset(&mask
, SIGWINCH
) ||
280 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
281 SYSERROR("failed to set signal mask");
285 fd
= signalfd(-1, &mask
, 0);
287 SYSERROR("failed to create the signal fd");
291 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
292 SYSERROR("failed to set sigfd to close-on-exec");
297 DEBUG("sigchild handler set");
302 static int signal_handler(int fd
, uint32_t events
, void *data
,
303 struct lxc_epoll_descr
*descr
)
305 struct signalfd_siginfo siginfo
;
309 bool init_died
= false;
311 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
313 ERROR("failed to read signal info");
317 if (ret
!= sizeof(siginfo
)) {
318 ERROR("unexpected siginfo size");
322 // check whether init is running
324 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
325 if (ret
== 0 && info
.si_pid
== *pid
) {
329 if (siginfo
.ssi_signo
!= SIGCHLD
) {
330 kill(*pid
, siginfo
.ssi_signo
);
331 INFO("forwarded signal %d to pid %d", siginfo
.ssi_signo
, *pid
);
332 return init_died
? 1 : 0;
335 if (siginfo
.ssi_code
== CLD_STOPPED
||
336 siginfo
.ssi_code
== CLD_CONTINUED
) {
337 INFO("container init process was stopped/continued");
338 return init_died
? 1 : 0;
341 /* more robustness, protect ourself from a SIGCHLD sent
342 * by a process different from the container init
344 if (siginfo
.ssi_pid
!= *pid
) {
345 WARN("invalid pid for SIGCHLD");
346 return init_died
? 1 : 0;
349 DEBUG("container init process exited");
353 int lxc_set_state(const char *name
, struct lxc_handler
*handler
, lxc_state_t state
)
355 handler
->state
= state
;
356 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
360 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
362 int sigfd
= handler
->sigfd
;
363 int pid
= handler
->pid
;
364 struct lxc_epoll_descr descr
;
366 if (lxc_mainloop_open(&descr
)) {
367 ERROR("failed to create mainloop");
371 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
372 ERROR("failed to add handler for the signal");
373 goto out_mainloop_open
;
376 if (lxc_console_mainloop_add(&descr
, handler
->conf
)) {
377 ERROR("failed to add console handler to mainloop");
378 goto out_mainloop_open
;
381 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
382 ERROR("failed to add command handler to mainloop");
383 goto out_mainloop_open
;
386 if (handler
->conf
->need_utmp_watch
) {
387 #if HAVE_SYS_CAPABILITY_H
388 if (lxc_utmp_mainloop_add(&descr
, handler
)) {
389 ERROR("failed to add utmp handler to mainloop");
390 goto out_mainloop_open
;
393 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support");
397 return lxc_mainloop(&descr
, -1);
400 lxc_mainloop_close(&descr
);
406 struct lxc_handler
*lxc_init(const char *name
, struct lxc_conf
*conf
, const char *lxcpath
)
409 struct lxc_handler
*handler
;
411 handler
= malloc(sizeof(*handler
));
415 memset(handler
, 0, sizeof(*handler
));
417 handler
->ttysock
[0] = handler
->ttysock
[1] = -1;
418 handler
->conf
= conf
;
419 handler
->lxcpath
= lxcpath
;
422 for (i
= 0; i
< LXC_NS_MAX
; i
++)
423 handler
->nsfd
[i
] = -1;
427 handler
->name
= strdup(name
);
428 if (!handler
->name
) {
429 ERROR("failed to allocate memory");
433 if (lxc_cmd_init(name
, handler
, lxcpath
))
436 if (lxc_read_seccomp_config(conf
) != 0) {
437 ERROR("failed loading seccomp policy");
438 goto out_close_maincmd_fd
;
441 /* Begin by setting the state to STARTING */
442 if (lxc_set_state(name
, handler
, STARTING
)) {
443 ERROR("failed to set state '%s'", lxc_state2str(STARTING
));
444 goto out_close_maincmd_fd
;
447 /* Start of environment variable setup for hooks */
448 if (name
&& setenv("LXC_NAME", name
, 1)) {
449 SYSERROR("failed to set environment variable for container name");
451 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
452 SYSERROR("failed to set environment variable for config path");
454 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
455 SYSERROR("failed to set environment variable for rootfs mount");
457 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
458 SYSERROR("failed to set environment variable for rootfs mount");
460 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1)) {
461 SYSERROR("failed to set environment variable for console path");
463 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1)) {
464 SYSERROR("failed to set environment variable for console log");
466 if (setenv("LXC_CGNS_AWARE", "1", 1)) {
467 SYSERROR("failed to set LXC_CGNS_AWARE environment variable");
469 /* End of environment variable setup for hooks */
471 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
472 ERROR("failed to run pre-start hooks for container '%s'.", name
);
476 /* the signal fd has to be created before forking otherwise
477 * if the child process exits before we setup the signal fd,
478 * the event will be lost and the command will be stuck */
479 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
480 if (handler
->sigfd
< 0) {
481 ERROR("failed to set sigchild fd handler");
485 /* do this after setting up signals since it might unblock SIGWINCH */
486 if (lxc_console_create(conf
)) {
487 ERROR("failed to create console");
488 goto out_restore_sigmask
;
491 if (ttys_shift_ids(conf
) < 0) {
492 ERROR("Failed to shift tty into container");
493 goto out_restore_sigmask
;
496 INFO("'%s' is initialized", name
);
500 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
502 lxc_delete_tty(&conf
->tty_info
);
504 lxc_set_state(name
, handler
, ABORTING
);
505 out_close_maincmd_fd
:
506 close(conf
->maincmd_fd
);
507 conf
->maincmd_fd
= -1;
510 handler
->name
= NULL
;
516 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
519 pid_t self
= getpid();
520 char *namespaces
[LXC_NS_MAX
+1];
521 size_t namespace_count
= 0;
523 /* The STOPPING state is there for future cleanup code
524 * which can take awhile
526 lxc_set_state(name
, handler
, STOPPING
);
528 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
529 if (handler
->nsfd
[i
] != -1) {
530 rc
= asprintf(&namespaces
[namespace_count
], "%s:/proc/%d/fd/%d",
531 ns_info
[i
].proc_name
, self
, handler
->nsfd
[i
]);
533 SYSERROR("failed to allocate memory");
539 namespaces
[namespace_count
] = NULL
;
541 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1)) {
542 SYSERROR("failed to set environment variable for stop target");
544 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1)) {
545 SYSERROR("failed to set environment variable for stop target");
548 if (run_lxc_hooks(name
, "stop", handler
->conf
, handler
->lxcpath
, namespaces
))
549 ERROR("failed to run stop hooks for container '%s'.", name
);
551 while (namespace_count
--)
552 free(namespaces
[namespace_count
]);
553 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
554 if (handler
->nsfd
[i
] != -1) {
555 close(handler
->nsfd
[i
]);
556 handler
->nsfd
[i
] = -1;
559 lxc_set_state(name
, handler
, STOPPED
);
561 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
)) {
562 ERROR("failed to run post-stop hooks for container '%s'.", name
);
563 if (handler
->conf
->reboot
) {
564 WARN("Container will be stopped instead of rebooted.");
565 handler
->conf
->reboot
= 0;
566 setenv("LXC_TARGET", "stop", 1);
570 /* reset mask set by setup_signal_fd */
571 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
572 WARN("failed to restore sigprocmask");
574 lxc_console_delete(&handler
->conf
->console
);
575 lxc_delete_tty(&handler
->conf
->tty_info
);
576 close(handler
->conf
->maincmd_fd
);
577 handler
->conf
->maincmd_fd
= -1;
579 if (handler
->ttysock
[0] != -1) {
580 close(handler
->ttysock
[0]);
581 close(handler
->ttysock
[1]);
584 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1)
585 lxc_destroy_container_on_signal(handler
, name
);
587 cgroup_destroy(handler
);
591 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
595 lxc_set_state(name
, handler
, ABORTING
);
596 if (handler
->pid
> 0)
597 kill(handler
->pid
, SIGKILL
);
598 while ((ret
= waitpid(-1, &status
, 0)) > 0) ;
601 #include <sys/reboot.h>
602 #include <linux/reboot.h>
605 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
606 * in a child pid namespace if container reboot support exists.
607 * Otherwise, it will either succeed or return -EPERM.
609 static int container_reboot_supported(void *arg
)
615 if (ret
== -1 && errno
== EINVAL
)
620 static int must_drop_cap_sys_boot(struct lxc_conf
*conf
)
623 int ret
, cmd
, v
, flags
;
624 long stack_size
= 4096;
625 void *stack
= alloca(stack_size
);
629 f
= fopen("/proc/sys/kernel/ctrl-alt-del", "r");
631 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
635 ret
= fscanf(f
, "%d", &v
);
638 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
641 cmd
= v
? LINUX_REBOOT_CMD_CAD_ON
: LINUX_REBOOT_CMD_CAD_OFF
;
643 flags
= CLONE_NEWPID
| SIGCHLD
;
644 if (!lxc_list_empty(&conf
->id_map
))
645 flags
|= CLONE_NEWUSER
;
648 pid
= __clone2(container_reboot_supported
, stack
, stack_size
, flags
, &cmd
);
651 pid
= clone(container_reboot_supported
, stack
, flags
, &cmd
);
654 if (flags
& CLONE_NEWUSER
)
655 ERROR("failed to clone (%#x): %s (includes CLONE_NEWUSER)", flags
, strerror(errno
));
657 ERROR("failed to clone (%#x): %s", flags
, strerror(errno
));
660 if (wait(&status
) < 0) {
661 SYSERROR("unexpected wait error: %m");
665 if (WEXITSTATUS(status
) != 1)
672 * netpipe is used in the unprivileged case to transfer the ifindexes
673 * from parent to child
675 static int netpipe
= -1;
677 static inline int count_veths(struct lxc_list
*network
)
679 struct lxc_list
*iterator
;
680 struct lxc_netdev
*netdev
;
683 lxc_list_for_each(iterator
, network
) {
684 netdev
= iterator
->elem
;
685 if (netdev
->type
!= LXC_NET_VETH
)
692 static int read_unpriv_netifindex(struct lxc_list
*network
)
694 struct lxc_list
*iterator
;
695 struct lxc_netdev
*netdev
;
699 lxc_list_for_each(iterator
, network
) {
700 netdev
= iterator
->elem
;
701 if (netdev
->type
!= LXC_NET_VETH
)
703 if (!(netdev
->name
= malloc(IFNAMSIZ
))) {
704 ERROR("Out of memory");
708 if (read(netpipe
, netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
717 static int do_start(void *data
)
719 struct lxc_list
*iterator
;
720 struct lxc_handler
*handler
= data
;
721 int devnull_fd
= -1, ret
;
724 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
725 SYSERROR("failed to set sigprocmask");
729 /* This prctl must be before the synchro, so if the parent
730 * dies before we set the parent death signal, we will detect
731 * its death with the synchro right after, otherwise we have
732 * a window where the parent can exit before we set the pdeath
733 * signal leading to a unsupervized container.
735 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
736 SYSERROR("failed to set pdeath signal");
740 lxc_sync_fini_parent(handler
);
742 /* don't leak the pinfd to the container */
743 if (handler
->pinfd
>= 0) {
744 close(handler
->pinfd
);
747 if (lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
))
750 /* Unshare CLONE_NEWNET after CLONE_NEWUSER - see
751 https://github.com/lxc/lxd/issues/1978 */
752 if ((handler
->clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
753 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
754 ret
= unshare(CLONE_NEWNET
);
756 SYSERROR("Error unsharing network namespace");
757 goto out_warn_father
;
761 /* Tell the parent task it can begin to configure the
762 * container and wait for it to finish
764 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
767 if (read_unpriv_netifindex(&handler
->conf
->network
) < 0)
768 goto out_warn_father
;
771 * if we are in a new user namespace, become root there to have
772 * privilege over our namespace. When using lxc-execute we default to root,
773 * but this can be overriden using the lxc.init_uid and lxc.init_gid
774 * configuration options.
776 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
778 if (handler
->conf
->is_execute
&& handler
->conf
->init_gid
)
779 new_gid
= handler
->conf
->init_gid
;
782 if (handler
->conf
->is_execute
&& handler
->conf
->init_uid
)
783 new_uid
= handler
->conf
->init_uid
;
785 NOTICE("switching to gid/uid %d/%d in new user namespace", new_gid
, new_uid
);
786 if (setgid(new_gid
)) {
788 goto out_warn_father
;
790 if (setuid(new_uid
)) {
792 goto out_warn_father
;
794 if (setgroups(0, NULL
)) {
795 SYSERROR("setgroups");
796 goto out_warn_father
;
800 if (access(handler
->lxcpath
, X_OK
)) {
801 print_top_failing_dir(handler
->lxcpath
);
802 goto out_warn_father
;
805 #if HAVE_SYS_CAPABILITY_H
806 if (handler
->conf
->need_utmp_watch
) {
807 if (prctl(PR_CAPBSET_DROP
, CAP_SYS_BOOT
, 0, 0, 0)) {
808 SYSERROR("failed to remove CAP_SYS_BOOT capability");
809 goto out_warn_father
;
811 DEBUG("Dropped cap_sys_boot");
815 ret
= snprintf(path
, sizeof(path
), "%s/dev/null", handler
->conf
->rootfs
.mount
);
816 if (ret
< 0 || ret
>= sizeof(path
)) {
817 SYSERROR("sprintf'd too many chars");
818 goto out_warn_father
;
821 /* In order to checkpoint restore, we need to have everything in the
822 * same mount namespace. However, some containers may not have a
823 * reasonable /dev (in particular, they may not have /dev/null), so we
824 * can't set init's std fds to /dev/null by opening it from inside the
827 * If that's the case, fall back to using the host's /dev/null. This
828 * means that migration won't work, but at least we won't spew output
829 * where it isn't wanted.
831 if (handler
->backgrounded
&& !handler
->conf
->autodev
&& access(path
, F_OK
) < 0) {
832 devnull_fd
= open_devnull();
835 goto out_warn_father
;
836 WARN("using host's /dev/null for container init's std fds, migraiton won't work");
839 /* Setup the container, ip, names, utsname, ... */
840 if (lxc_setup(handler
)) {
841 ERROR("failed to setup the container");
842 goto out_warn_father
;
845 /* ask father to setup cgroups and wait for him to finish */
846 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
849 /* Set the label to change to when we exec(2) the container's init */
850 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
851 goto out_warn_father
;
853 /* Some init's such as busybox will set sane tty settings on stdin,
854 * stdout, stderr which it thinks is the console. We already set them
855 * the way we wanted on the real terminal, and we want init to do its
856 * setup on its console ie. the pty allocated in lxc_console_create()
857 * so make sure that that pty is stdin,stdout,stderr.
859 if (lxc_console_set_stdfds(handler
->conf
->console
.slave
) < 0)
860 goto out_warn_father
;
862 /* If we mounted a temporary proc, then unmount it now */
863 tmp_proc_unmount(handler
->conf
);
865 if (lxc_seccomp_load(handler
->conf
) != 0)
866 goto out_warn_father
;
868 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
869 ERROR("failed to run start hooks for container '%s'.", handler
->name
);
870 goto out_warn_father
;
873 /* The clearenv() and putenv() calls have been moved here
874 * to allow us to use environment variables passed to the various
875 * hooks, such as the start hook above. Not all of the
876 * variables like CONFIG_PATH or ROOTFS are valid in this
877 * context but others are. */
879 SYSERROR("failed to clear environment");
880 /* don't error out though */
883 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
884 if (putenv((char *)iterator
->elem
)) {
885 SYSERROR("failed to set environment variable '%s'", (char *)iterator
->elem
);
886 goto out_warn_father
;
890 if (putenv("container=lxc")) {
891 SYSERROR("failed to set environment variable 'container=lxc'");
892 goto out_warn_father
;
895 if (handler
->conf
->pty_names
) {
896 if (putenv(handler
->conf
->pty_names
)) {
897 SYSERROR("failed to set environment variable for container ptys");
898 goto out_warn_father
;
902 close(handler
->sigfd
);
904 if (devnull_fd
< 0) {
905 devnull_fd
= open_devnull();
908 goto out_warn_father
;
911 if (handler
->backgrounded
&& set_stdfds(devnull_fd
))
912 goto out_warn_father
;
914 if (devnull_fd
>= 0) {
919 if (cgns_supported() && unshare(CLONE_NEWCGROUP
) != 0) {
920 SYSERROR("Failed to unshare cgroup namespace");
921 goto out_warn_father
;
926 /* after this call, we are in error because this
927 * ops should not return as it execs */
928 handler
->ops
->start(handler
, handler
->data
);
931 /* we want the parent to know something went wrong, so we return a special
933 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
942 static int save_phys_nics(struct lxc_conf
*conf
)
944 struct lxc_list
*iterator
;
945 int am_root
= (getuid() == 0);
950 lxc_list_for_each(iterator
, &conf
->network
) {
951 struct lxc_netdev
*netdev
= iterator
->elem
;
953 if (netdev
->type
!= LXC_NET_PHYS
)
955 conf
->saved_nics
= realloc(conf
->saved_nics
,
956 (conf
->num_savednics
+1)*sizeof(struct saved_nic
));
957 if (!conf
->saved_nics
) {
958 SYSERROR("failed to allocate memory");
961 conf
->saved_nics
[conf
->num_savednics
].ifindex
= netdev
->ifindex
;
962 conf
->saved_nics
[conf
->num_savednics
].orig_name
= strdup(netdev
->link
);
963 if (!conf
->saved_nics
[conf
->num_savednics
].orig_name
) {
964 SYSERROR("failed to allocate memory");
967 INFO("stored saved_nic #%d idx %d name %s", conf
->num_savednics
,
968 conf
->saved_nics
[conf
->num_savednics
].ifindex
,
969 conf
->saved_nics
[conf
->num_savednics
].orig_name
);
970 conf
->num_savednics
++;
976 static int recv_fd(int sock
, int *fd
)
978 if (lxc_abstract_unix_recv_fd(sock
, fd
, NULL
, 0) < 0) {
979 SYSERROR("Error receiving tty fd from child");
987 static int recv_ttys_from_child(struct lxc_handler
*handler
)
989 struct lxc_conf
*conf
= handler
->conf
;
990 int i
, sock
= handler
->ttysock
[1];
991 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
996 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
)*conf
->tty
);
997 if (!tty_info
->pty_info
) {
998 SYSERROR("failed to allocate pty_info");
1002 for (i
= 0; i
< conf
->tty
; i
++) {
1003 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
1005 if (recv_fd(sock
, &pty_info
->slave
) < 0 ||
1006 recv_fd(sock
, &pty_info
->master
) < 0) {
1007 ERROR("Error receiving tty info from child");
1011 tty_info
->nbtty
= conf
->tty
;
1016 void resolve_clone_flags(struct lxc_handler
*handler
)
1018 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
1020 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1021 INFO("Cloning a new user namespace");
1022 handler
->clone_flags
|= CLONE_NEWUSER
;
1025 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
1026 if (!lxc_requests_empty_network(handler
))
1027 handler
->clone_flags
|= CLONE_NEWNET
;
1029 INFO("Inheriting a net namespace");
1032 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1) {
1033 handler
->clone_flags
|= CLONE_NEWIPC
;
1035 INFO("Inheriting an IPC namespace");
1038 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1) {
1039 handler
->clone_flags
|= CLONE_NEWUTS
;
1041 INFO("Inheriting a UTS namespace");
1045 static int lxc_spawn(struct lxc_handler
*handler
)
1047 int failed_before_rename
= 0;
1048 const char *name
= handler
->name
;
1049 char *errmsg
= NULL
;
1050 bool cgroups_connected
= false;
1051 int saved_ns_fd
[LXC_NS_MAX
];
1052 int preserve_mask
= 0, i
, flags
;
1053 int netpipepair
[2], nveths
;
1057 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1058 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
1059 preserve_mask
|= ns_info
[i
].clone_flag
;
1061 if (lxc_sync_init(handler
))
1064 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, handler
->ttysock
) < 0) {
1065 lxc_sync_fini(handler
);
1069 resolve_clone_flags(handler
);
1071 if (handler
->clone_flags
& CLONE_NEWNET
) {
1072 if (!lxc_list_empty(&handler
->conf
->network
)) {
1074 /* Find gateway addresses from the link device, which is
1075 * no longer accessible inside the container. Do this
1076 * before creating network interfaces, since goto
1077 * out_delete_net does not work before lxc_clone. */
1078 if (lxc_find_gateway_addresses(handler
)) {
1079 ERROR("failed to find gateway addresses");
1080 lxc_sync_fini(handler
);
1084 /* that should be done before the clone because we will
1085 * fill the netdev index and use them in the child
1087 if (lxc_create_network(handler
)) {
1088 ERROR("failed to create the network");
1089 lxc_sync_fini(handler
);
1094 if (save_phys_nics(handler
->conf
)) {
1095 ERROR("failed to save physical nic info");
1100 if (!cgroup_init(handler
)) {
1101 ERROR("failed initializing cgroup support");
1102 goto out_delete_net
;
1105 cgroups_connected
= true;
1107 if (!cgroup_create(handler
)) {
1108 ERROR("failed creating cgroups");
1109 goto out_delete_net
;
1113 * if the rootfs is not a blockdev, prevent the container from
1114 * marking it readonly.
1116 * if the container is unprivileged then skip rootfs pinning
1118 if (lxc_list_empty(&handler
->conf
->id_map
)) {
1119 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
1120 if (handler
->pinfd
== -1)
1121 INFO("failed to pin the container's rootfs");
1124 if (!preserve_ns(saved_ns_fd
, preserve_mask
, getpid(), &errmsg
)) {
1125 SYSERROR("Failed to preserve requested namespaces: %s",
1126 errmsg
? errmsg
: "(Out of memory)");
1128 goto out_delete_net
;
1130 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
1131 goto out_delete_net
;
1133 if (am_unpriv() && (nveths
= count_veths(&handler
->conf
->network
))) {
1134 if (pipe(netpipepair
) < 0) {
1135 SYSERROR("Error creating pipe");
1136 goto out_delete_net
;
1138 /* store netpipe in the global var for do_start's use */
1139 netpipe
= netpipepair
[0];
1142 /* Create a process in a new set of namespaces */
1143 flags
= handler
->clone_flags
;
1144 if (handler
->clone_flags
& CLONE_NEWUSER
)
1145 flags
&= ~CLONE_NEWNET
;
1146 handler
->pid
= lxc_clone(do_start
, handler
, handler
->clone_flags
);
1147 if (handler
->pid
< 0) {
1148 SYSERROR("failed to fork into a new namespace");
1149 goto out_delete_net
;
1152 if (!preserve_ns(handler
->nsfd
, handler
->clone_flags
| preserve_mask
, handler
->pid
, &errmsg
)) {
1153 INFO("Failed to store namespace references for stop hook: %s",
1154 errmsg
? errmsg
: "(Out of memory)");
1158 if (attach_ns(saved_ns_fd
))
1159 WARN("failed to restore saved namespaces");
1161 lxc_sync_fini_child(handler
);
1163 /* map the container uids - the container became an invalid
1164 * userid the moment it was cloned with CLONE_NEWUSER - this
1165 * call doesn't change anything immediately, but allows the
1166 * container to setuid(0) (0 being mapped to something else on
1167 * the host) later to become a valid uid again */
1168 if (lxc_map_ids(&handler
->conf
->id_map
, handler
->pid
)) {
1169 ERROR("failed to set up id mapping");
1170 goto out_delete_net
;
1173 if (lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
)) {
1174 failed_before_rename
= 1;
1175 goto out_delete_net
;
1178 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
)) {
1179 failed_before_rename
= 1;
1180 goto out_delete_net
;
1183 if (!cgroup_create_legacy(handler
)) {
1184 ERROR("failed to setup the legacy cgroups for %s", name
);
1185 goto out_delete_net
;
1187 if (!cgroup_setup_limits(handler
, false)) {
1188 ERROR("failed to setup the cgroup limits for '%s'", name
);
1189 goto out_delete_net
;
1192 if (!cgroup_enter(handler
))
1193 goto out_delete_net
;
1195 if (!cgroup_chown(handler
))
1196 goto out_delete_net
;
1198 if (failed_before_rename
)
1199 goto out_delete_net
;
1201 /* Create the network configuration */
1202 if (handler
->clone_flags
& CLONE_NEWNET
) {
1203 if (lxc_assign_network(handler
->lxcpath
, handler
->name
,
1204 &handler
->conf
->network
, handler
->pid
)) {
1205 ERROR("failed to create the configured network");
1206 goto out_delete_net
;
1210 if (netpipe
!= -1) {
1211 struct lxc_list
*iterator
;
1212 struct lxc_netdev
*netdev
;
1215 lxc_list_for_each(iterator
, &handler
->conf
->network
) {
1216 netdev
= iterator
->elem
;
1217 if (netdev
->type
!= LXC_NET_VETH
)
1219 if (write(netpipepair
[1], netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
1220 ERROR("Error writing veth name to container");
1221 goto out_delete_net
;
1224 close(netpipepair
[1]);
1227 /* Tell the child to continue its initialization. we'll get
1228 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
1230 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1231 goto out_delete_net
;
1233 if (!cgroup_setup_limits(handler
, true)) {
1234 ERROR("failed to setup the devices cgroup for '%s'", name
);
1235 goto out_delete_net
;
1238 cgroup_disconnect();
1239 cgroups_connected
= false;
1241 /* read tty fds allocated by child */
1242 if (recv_ttys_from_child(handler
) < 0) {
1243 ERROR("failed to receive tty info from child");
1244 goto out_delete_net
;
1247 /* Tell the child to complete its initialization and wait for
1248 * it to exec or return an error. (the child will never
1249 * return LXC_SYNC_POST_CGROUP+1. It will either close the
1250 * sync pipe, causing lxc_sync_barrier_child to return
1251 * success, or return a different value, causing us to error
1254 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1257 if (detect_shared_rootfs())
1258 umount2(handler
->conf
->rootfs
.mount
, MNT_DETACH
);
1260 if (handler
->ops
->post_start(handler
, handler
->data
))
1263 if (lxc_set_state(name
, handler
, RUNNING
)) {
1264 ERROR("failed to set state to %s",
1265 lxc_state2str(RUNNING
));
1269 lxc_sync_fini(handler
);
1274 if (cgroups_connected
)
1275 cgroup_disconnect();
1276 if (handler
->clone_flags
& CLONE_NEWNET
)
1277 lxc_delete_network(handler
);
1279 lxc_abort(name
, handler
);
1280 lxc_sync_fini(handler
);
1281 if (handler
->pinfd
>= 0) {
1282 close(handler
->pinfd
);
1283 handler
->pinfd
= -1;
1289 int get_netns_fd(int pid
)
1291 char path
[MAXPATHLEN
];
1294 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/net", pid
);
1295 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1296 WARN("Failed to pin netns file for pid %d", pid
);
1300 fd
= open(path
, O_RDONLY
);
1302 WARN("Failed to pin netns file %s for pid %d: %s",
1303 path
, pid
, strerror(errno
));
1309 int __lxc_start(const char *name
, struct lxc_conf
*conf
,
1310 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1313 struct lxc_handler
*handler
;
1318 handler
= lxc_init(name
, conf
, lxcpath
);
1320 ERROR("failed to initialize the container");
1324 handler
->data
= data
;
1325 handler
->backgrounded
= backgrounded
;
1327 if (must_drop_cap_sys_boot(handler
->conf
)) {
1328 #if HAVE_SYS_CAPABILITY_H
1329 DEBUG("Dropping cap_sys_boot");
1331 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
1334 DEBUG("Not dropping cap_sys_boot or watching utmp");
1335 handler
->conf
->need_utmp_watch
= 0;
1338 if (!attach_block_device(handler
->conf
)) {
1339 ERROR("Failure attaching block device");
1340 goto out_fini_nonet
;
1343 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1344 /* if the backing store is a device, mount it here and now */
1345 if (rootfs_is_blockdev(conf
)) {
1346 if (unshare(CLONE_NEWNS
) < 0) {
1347 ERROR("Error unsharing mounts");
1348 goto out_fini_nonet
;
1350 remount_all_slave();
1351 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1352 ERROR("Error setting up rootfs mount as root before spawn");
1353 goto out_fini_nonet
;
1355 INFO("Set up container rootfs as host root");
1359 err
= lxc_spawn(handler
);
1361 ERROR("failed to spawn '%s'", name
);
1362 goto out_detach_blockdev
;
1365 handler
->conf
->reboot
= 0;
1367 netnsfd
= get_netns_fd(handler
->pid
);
1369 err
= lxc_poll(name
, handler
);
1371 ERROR("mainloop exited with an error");
1377 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1381 * If the child process exited but was not signaled,
1382 * it didn't call reboot. This should mean it was an
1383 * lxc-execute which simply exited. In any case, treat
1386 if (WIFSIGNALED(status
)) {
1387 switch(WTERMSIG(status
)) {
1388 case SIGINT
: /* halt */
1389 DEBUG("Container halting");
1391 case SIGHUP
: /* reboot */
1392 DEBUG("Container rebooting");
1393 handler
->conf
->reboot
= 1;
1395 case SIGSYS
: /* seccomp */
1396 DEBUG("Container violated its seccomp policy");
1399 DEBUG("unknown exit status for init: %d", WTERMSIG(status
));
1404 DEBUG("Pushing physical nics back to host namespace");
1405 lxc_rename_phys_nics_on_shutdown(netnsfd
, handler
->conf
);
1407 DEBUG("Tearing down virtual network devices used by container");
1408 lxc_delete_network(handler
);
1413 if (handler
->pinfd
>= 0) {
1414 close(handler
->pinfd
);
1415 handler
->pinfd
= -1;
1418 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1419 err
= lxc_error_set_and_log(handler
->pid
, status
);
1421 lxc_delete_network(handler
);
1423 out_detach_blockdev
:
1424 detach_block_device(handler
->conf
);
1427 lxc_fini(name
, handler
);
1431 lxc_abort(name
, handler
);
1439 static int start(struct lxc_handler
*handler
, void* data
)
1441 struct start_args
*arg
= data
;
1443 NOTICE("exec'ing '%s'", arg
->argv
[0]);
1445 execvp(arg
->argv
[0], arg
->argv
);
1446 SYSERROR("failed to exec %s", arg
->argv
[0]);
1450 static int post_start(struct lxc_handler
*handler
, void* data
)
1452 struct start_args
*arg
= data
;
1454 NOTICE("'%s' started with pid '%d'", arg
->argv
[0], handler
->pid
);
1458 static struct lxc_operations start_ops
= {
1460 .post_start
= post_start
1463 int lxc_start(const char *name
, char *const argv
[], struct lxc_conf
*conf
,
1464 const char *lxcpath
, bool backgrounded
)
1466 struct start_args start_arg
= {
1470 conf
->need_utmp_watch
= 1;
1471 return __lxc_start(name
, conf
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1474 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1477 char destroy
[MAXPATHLEN
];
1480 struct lxc_container
*c
;
1481 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1482 bret
= do_destroy_container(handler
->conf
);
1484 ERROR("Error destroying rootfs for %s", name
);
1488 INFO("Destroyed rootfs for %s", name
);
1490 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1491 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1492 ERROR("Error printing path for %s", name
);
1493 ERROR("Error destroying directory for %s", name
);
1497 c
= lxc_container_new(name
, handler
->lxcpath
);
1499 if (container_disk_lock(c
)) {
1500 INFO("Could not update lxc_snapshots file");
1501 lxc_container_put(c
);
1503 mod_all_rdeps(c
, false);
1504 container_disk_unlock(c
);
1505 lxc_container_put(c
);
1510 ret
= userns_exec_1(handler
->conf
, lxc_rmdir_onedev_wrapper
, destroy
);
1512 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1515 ERROR("Error destroying directory for %s", name
);
1518 INFO("Destroyed directory for %s", name
);
1521 static int lxc_rmdir_onedev_wrapper(void *data
)
1523 char *arg
= (char *) data
;
1524 return lxc_rmdir_onedev(arg
, NULL
);
1527 static bool do_destroy_container(struct lxc_conf
*conf
) {
1529 if (userns_exec_1(conf
, bdev_destroy_wrapper
, conf
) < 0)
1533 return bdev_destroy(conf
);