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
},
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 dirent
, *direntp
;
216 if (conf
&& conf
->close_all_fds
)
220 dir
= opendir("/proc/self/fd");
222 WARN("failed to open directory: %m");
228 while (!readdir_r(dir
, &dirent
, &direntp
)) {
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
);
258 closedir(dir
); /* cannot fail */
262 static int setup_signal_fd(sigset_t
*oldmask
)
267 /* Block everything except serious error signals */
268 if (sigfillset(&mask
) ||
269 sigdelset(&mask
, SIGILL
) ||
270 sigdelset(&mask
, SIGSEGV
) ||
271 sigdelset(&mask
, SIGBUS
) ||
272 sigdelset(&mask
, SIGWINCH
) ||
273 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
274 SYSERROR("failed to set signal mask");
278 fd
= signalfd(-1, &mask
, 0);
280 SYSERROR("failed to create the signal fd");
284 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
285 SYSERROR("failed to set sigfd to close-on-exec");
290 DEBUG("sigchild handler set");
295 static int signal_handler(int fd
, uint32_t events
, void *data
,
296 struct lxc_epoll_descr
*descr
)
298 struct signalfd_siginfo siginfo
;
302 bool init_died
= false;
304 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
306 ERROR("failed to read signal info");
310 if (ret
!= sizeof(siginfo
)) {
311 ERROR("unexpected siginfo size");
315 // check whether init is running
317 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
318 if (ret
== 0 && info
.si_pid
== *pid
) {
322 if (siginfo
.ssi_signo
!= SIGCHLD
) {
323 kill(*pid
, siginfo
.ssi_signo
);
324 INFO("forwarded signal %d to pid %d", siginfo
.ssi_signo
, *pid
);
325 return init_died
? 1 : 0;
328 if (siginfo
.ssi_code
== CLD_STOPPED
||
329 siginfo
.ssi_code
== CLD_CONTINUED
) {
330 INFO("container init process was stopped/continued");
331 return init_died
? 1 : 0;
334 /* more robustness, protect ourself from a SIGCHLD sent
335 * by a process different from the container init
337 if (siginfo
.ssi_pid
!= *pid
) {
338 WARN("invalid pid for SIGCHLD");
339 return init_died
? 1 : 0;
342 DEBUG("container init process exited");
346 int lxc_set_state(const char *name
, struct lxc_handler
*handler
, lxc_state_t state
)
348 handler
->state
= state
;
349 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
353 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
355 int sigfd
= handler
->sigfd
;
356 int pid
= handler
->pid
;
357 struct lxc_epoll_descr descr
;
359 if (lxc_mainloop_open(&descr
)) {
360 ERROR("failed to create mainloop");
364 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
365 ERROR("failed to add handler for the signal");
366 goto out_mainloop_open
;
369 if (lxc_console_mainloop_add(&descr
, handler
->conf
)) {
370 ERROR("failed to add console handler to mainloop");
371 goto out_mainloop_open
;
374 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
375 ERROR("failed to add command handler to mainloop");
376 goto out_mainloop_open
;
379 if (handler
->conf
->need_utmp_watch
) {
380 #if HAVE_SYS_CAPABILITY_H
381 if (lxc_utmp_mainloop_add(&descr
, handler
)) {
382 ERROR("failed to add utmp handler to mainloop");
383 goto out_mainloop_open
;
386 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support");
390 return lxc_mainloop(&descr
, -1);
393 lxc_mainloop_close(&descr
);
399 struct lxc_handler
*lxc_init(const char *name
, struct lxc_conf
*conf
, const char *lxcpath
)
402 struct lxc_handler
*handler
;
404 handler
= malloc(sizeof(*handler
));
408 memset(handler
, 0, sizeof(*handler
));
410 handler
->ttysock
[0] = handler
->ttysock
[1] = -1;
411 handler
->conf
= conf
;
412 handler
->lxcpath
= lxcpath
;
415 for (i
= 0; i
< LXC_NS_MAX
; i
++)
416 handler
->nsfd
[i
] = -1;
420 handler
->name
= strdup(name
);
421 if (!handler
->name
) {
422 ERROR("failed to allocate memory");
426 if (lxc_cmd_init(name
, handler
, lxcpath
))
429 if (lxc_read_seccomp_config(conf
) != 0) {
430 ERROR("failed loading seccomp policy");
431 goto out_close_maincmd_fd
;
434 /* Begin by setting the state to STARTING */
435 if (lxc_set_state(name
, handler
, STARTING
)) {
436 ERROR("failed to set state '%s'", lxc_state2str(STARTING
));
437 goto out_close_maincmd_fd
;
440 /* Start of environment variable setup for hooks */
441 if (name
&& setenv("LXC_NAME", name
, 1)) {
442 SYSERROR("failed to set environment variable for container name");
444 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
445 SYSERROR("failed to set environment variable for config path");
447 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
448 SYSERROR("failed to set environment variable for rootfs mount");
450 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
451 SYSERROR("failed to set environment variable for rootfs mount");
453 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1)) {
454 SYSERROR("failed to set environment variable for console path");
456 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1)) {
457 SYSERROR("failed to set environment variable for console log");
459 if (setenv("LXC_CGNS_AWARE", "1", 1)) {
460 SYSERROR("failed to set LXC_CGNS_AWARE environment variable");
462 /* End of environment variable setup for hooks */
464 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
465 ERROR("failed to run pre-start hooks for container '%s'.", name
);
469 /* the signal fd has to be created before forking otherwise
470 * if the child process exits before we setup the signal fd,
471 * the event will be lost and the command will be stuck */
472 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
473 if (handler
->sigfd
< 0) {
474 ERROR("failed to set sigchild fd handler");
478 /* do this after setting up signals since it might unblock SIGWINCH */
479 if (lxc_console_create(conf
)) {
480 ERROR("failed to create console");
481 goto out_restore_sigmask
;
484 if (ttys_shift_ids(conf
) < 0) {
485 ERROR("Failed to shift tty into container");
486 goto out_restore_sigmask
;
489 INFO("'%s' is initialized", name
);
493 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
495 lxc_delete_tty(&conf
->tty_info
);
497 lxc_set_state(name
, handler
, ABORTING
);
498 out_close_maincmd_fd
:
499 close(conf
->maincmd_fd
);
500 conf
->maincmd_fd
= -1;
503 handler
->name
= NULL
;
509 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
512 pid_t self
= getpid();
513 char *namespaces
[LXC_NS_MAX
+1];
514 size_t namespace_count
= 0;
516 /* The STOPPING state is there for future cleanup code
517 * which can take awhile
519 lxc_set_state(name
, handler
, STOPPING
);
521 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
522 if (handler
->nsfd
[i
] != -1) {
523 rc
= asprintf(&namespaces
[namespace_count
], "%s:/proc/%d/fd/%d",
524 ns_info
[i
].proc_name
, self
, handler
->nsfd
[i
]);
526 SYSERROR("failed to allocate memory");
532 namespaces
[namespace_count
] = NULL
;
534 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1)) {
535 SYSERROR("failed to set environment variable for stop target");
537 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1)) {
538 SYSERROR("failed to set environment variable for stop target");
541 if (run_lxc_hooks(name
, "stop", handler
->conf
, handler
->lxcpath
, namespaces
))
542 ERROR("failed to run stop hooks for container '%s'.", name
);
544 while (namespace_count
--)
545 free(namespaces
[namespace_count
]);
546 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
547 if (handler
->nsfd
[i
] != -1) {
548 close(handler
->nsfd
[i
]);
549 handler
->nsfd
[i
] = -1;
552 lxc_set_state(name
, handler
, STOPPED
);
554 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
)) {
555 ERROR("failed to run post-stop hooks for container '%s'.", name
);
556 if (handler
->conf
->reboot
) {
557 WARN("Container will be stopped instead of rebooted.");
558 handler
->conf
->reboot
= 0;
559 setenv("LXC_TARGET", "stop", 1);
563 /* reset mask set by setup_signal_fd */
564 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
565 WARN("failed to restore sigprocmask");
567 lxc_console_delete(&handler
->conf
->console
);
568 lxc_delete_tty(&handler
->conf
->tty_info
);
569 close(handler
->conf
->maincmd_fd
);
570 handler
->conf
->maincmd_fd
= -1;
572 if (handler
->ttysock
[0] != -1) {
573 close(handler
->ttysock
[0]);
574 close(handler
->ttysock
[1]);
577 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1)
578 lxc_destroy_container_on_signal(handler
, name
);
580 cgroup_destroy(handler
);
584 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
588 lxc_set_state(name
, handler
, ABORTING
);
589 if (handler
->pid
> 0)
590 kill(handler
->pid
, SIGKILL
);
591 while ((ret
= waitpid(-1, &status
, 0)) > 0) ;
594 #include <sys/reboot.h>
595 #include <linux/reboot.h>
598 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
599 * in a child pid namespace if container reboot support exists.
600 * Otherwise, it will either succeed or return -EPERM.
602 static int container_reboot_supported(void *arg
)
608 if (ret
== -1 && errno
== EINVAL
)
613 static int must_drop_cap_sys_boot(struct lxc_conf
*conf
)
616 int ret
, cmd
, v
, flags
;
617 long stack_size
= 4096;
618 void *stack
= alloca(stack_size
);
622 f
= fopen("/proc/sys/kernel/ctrl-alt-del", "r");
624 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
628 ret
= fscanf(f
, "%d", &v
);
631 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
634 cmd
= v
? LINUX_REBOOT_CMD_CAD_ON
: LINUX_REBOOT_CMD_CAD_OFF
;
636 flags
= CLONE_NEWPID
| SIGCHLD
;
637 if (!lxc_list_empty(&conf
->id_map
))
638 flags
|= CLONE_NEWUSER
;
641 pid
= __clone2(container_reboot_supported
, stack
, stack_size
, flags
, &cmd
);
644 pid
= clone(container_reboot_supported
, stack
, flags
, &cmd
);
647 if (flags
& CLONE_NEWUSER
)
648 ERROR("failed to clone (%#x): %s (includes CLONE_NEWUSER)", flags
, strerror(errno
));
650 ERROR("failed to clone (%#x): %s", flags
, strerror(errno
));
653 if (wait(&status
) < 0) {
654 SYSERROR("unexpected wait error: %m");
658 if (WEXITSTATUS(status
) != 1)
665 * netpipe is used in the unprivileged case to transfer the ifindexes
666 * from parent to child
668 static int netpipe
= -1;
670 static inline int count_veths(struct lxc_list
*network
)
672 struct lxc_list
*iterator
;
673 struct lxc_netdev
*netdev
;
676 lxc_list_for_each(iterator
, network
) {
677 netdev
= iterator
->elem
;
678 if (netdev
->type
!= LXC_NET_VETH
)
685 static int read_unpriv_netifindex(struct lxc_list
*network
)
687 struct lxc_list
*iterator
;
688 struct lxc_netdev
*netdev
;
692 lxc_list_for_each(iterator
, network
) {
693 netdev
= iterator
->elem
;
694 if (netdev
->type
!= LXC_NET_VETH
)
696 if (!(netdev
->name
= malloc(IFNAMSIZ
))) {
697 ERROR("Out of memory");
701 if (read(netpipe
, netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
710 static int do_start(void *data
)
712 struct lxc_list
*iterator
;
713 struct lxc_handler
*handler
= data
;
714 int devnull_fd
= -1, ret
;
717 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
718 SYSERROR("failed to set sigprocmask");
722 /* This prctl must be before the synchro, so if the parent
723 * dies before we set the parent death signal, we will detect
724 * its death with the synchro right after, otherwise we have
725 * a window where the parent can exit before we set the pdeath
726 * signal leading to a unsupervized container.
728 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
729 SYSERROR("failed to set pdeath signal");
733 lxc_sync_fini_parent(handler
);
735 /* don't leak the pinfd to the container */
736 if (handler
->pinfd
>= 0) {
737 close(handler
->pinfd
);
740 if (lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
))
743 /* Unshare CLONE_NEWNET after CLONE_NEWUSER - see
744 https://github.com/lxc/lxd/issues/1978 */
745 if ((handler
->clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
746 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
747 ret
= unshare(CLONE_NEWNET
);
749 SYSERROR("Error unsharing network namespace");
750 goto out_warn_father
;
754 /* Tell the parent task it can begin to configure the
755 * container and wait for it to finish
757 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
760 if (read_unpriv_netifindex(&handler
->conf
->network
) < 0)
761 goto out_warn_father
;
764 * if we are in a new user namespace, become root there to have
765 * privilege over our namespace. When using lxc-execute we default to root,
766 * but this can be overriden using the lxc.init_uid and lxc.init_gid
767 * configuration options.
769 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
771 if (handler
->conf
->is_execute
&& handler
->conf
->init_gid
)
772 new_gid
= handler
->conf
->init_gid
;
775 if (handler
->conf
->is_execute
&& handler
->conf
->init_uid
)
776 new_uid
= handler
->conf
->init_uid
;
778 NOTICE("switching to gid/uid %d/%d in new user namespace", new_gid
, new_uid
);
779 if (setgid(new_gid
)) {
781 goto out_warn_father
;
783 if (setuid(new_uid
)) {
785 goto out_warn_father
;
787 if (setgroups(0, NULL
)) {
788 SYSERROR("setgroups");
789 goto out_warn_father
;
793 if (access(handler
->lxcpath
, X_OK
)) {
794 print_top_failing_dir(handler
->lxcpath
);
795 goto out_warn_father
;
798 #if HAVE_SYS_CAPABILITY_H
799 if (handler
->conf
->need_utmp_watch
) {
800 if (prctl(PR_CAPBSET_DROP
, CAP_SYS_BOOT
, 0, 0, 0)) {
801 SYSERROR("failed to remove CAP_SYS_BOOT capability");
802 goto out_warn_father
;
804 DEBUG("Dropped cap_sys_boot");
808 ret
= snprintf(path
, sizeof(path
), "%s/dev/null", handler
->conf
->rootfs
.mount
);
809 if (ret
< 0 || ret
>= sizeof(path
)) {
810 SYSERROR("sprintf'd too many chars");
811 goto out_warn_father
;
814 /* In order to checkpoint restore, we need to have everything in the
815 * same mount namespace. However, some containers may not have a
816 * reasonable /dev (in particular, they may not have /dev/null), so we
817 * can't set init's std fds to /dev/null by opening it from inside the
820 * If that's the case, fall back to using the host's /dev/null. This
821 * means that migration won't work, but at least we won't spew output
822 * where it isn't wanted.
824 if (handler
->backgrounded
&& !handler
->conf
->autodev
&& access(path
, F_OK
) < 0) {
825 devnull_fd
= open_devnull();
828 goto out_warn_father
;
829 WARN("using host's /dev/null for container init's std fds, migraiton won't work");
832 /* Setup the container, ip, names, utsname, ... */
833 if (lxc_setup(handler
)) {
834 ERROR("failed to setup the container");
835 goto out_warn_father
;
838 /* ask father to setup cgroups and wait for him to finish */
839 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
842 /* Set the label to change to when we exec(2) the container's init */
843 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
844 goto out_warn_father
;
846 /* Some init's such as busybox will set sane tty settings on stdin,
847 * stdout, stderr which it thinks is the console. We already set them
848 * the way we wanted on the real terminal, and we want init to do its
849 * setup on its console ie. the pty allocated in lxc_console_create()
850 * so make sure that that pty is stdin,stdout,stderr.
852 if (lxc_console_set_stdfds(handler
->conf
->console
.slave
) < 0)
853 goto out_warn_father
;
855 /* If we mounted a temporary proc, then unmount it now */
856 tmp_proc_unmount(handler
->conf
);
858 if (lxc_seccomp_load(handler
->conf
) != 0)
859 goto out_warn_father
;
861 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
862 ERROR("failed to run start hooks for container '%s'.", handler
->name
);
863 goto out_warn_father
;
866 /* The clearenv() and putenv() calls have been moved here
867 * to allow us to use environment variables passed to the various
868 * hooks, such as the start hook above. Not all of the
869 * variables like CONFIG_PATH or ROOTFS are valid in this
870 * context but others are. */
872 SYSERROR("failed to clear environment");
873 /* don't error out though */
876 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
877 if (putenv((char *)iterator
->elem
)) {
878 SYSERROR("failed to set environment variable '%s'", (char *)iterator
->elem
);
879 goto out_warn_father
;
883 if (putenv("container=lxc")) {
884 SYSERROR("failed to set environment variable 'container=lxc'");
885 goto out_warn_father
;
888 if (handler
->conf
->pty_names
) {
889 if (putenv(handler
->conf
->pty_names
)) {
890 SYSERROR("failed to set environment variable for container ptys");
891 goto out_warn_father
;
895 close(handler
->sigfd
);
897 if (devnull_fd
< 0) {
898 devnull_fd
= open_devnull();
901 goto out_warn_father
;
904 if (handler
->backgrounded
&& set_stdfds(devnull_fd
))
905 goto out_warn_father
;
907 if (devnull_fd
>= 0) {
912 if (cgns_supported() && unshare(CLONE_NEWCGROUP
) != 0) {
913 SYSERROR("Failed to unshare cgroup namespace");
914 goto out_warn_father
;
919 /* after this call, we are in error because this
920 * ops should not return as it execs */
921 handler
->ops
->start(handler
, handler
->data
);
924 /* we want the parent to know something went wrong, so we return a special
926 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
935 static int save_phys_nics(struct lxc_conf
*conf
)
937 struct lxc_list
*iterator
;
938 int am_root
= (getuid() == 0);
943 lxc_list_for_each(iterator
, &conf
->network
) {
944 struct lxc_netdev
*netdev
= iterator
->elem
;
946 if (netdev
->type
!= LXC_NET_PHYS
)
948 conf
->saved_nics
= realloc(conf
->saved_nics
,
949 (conf
->num_savednics
+1)*sizeof(struct saved_nic
));
950 if (!conf
->saved_nics
) {
951 SYSERROR("failed to allocate memory");
954 conf
->saved_nics
[conf
->num_savednics
].ifindex
= netdev
->ifindex
;
955 conf
->saved_nics
[conf
->num_savednics
].orig_name
= strdup(netdev
->link
);
956 if (!conf
->saved_nics
[conf
->num_savednics
].orig_name
) {
957 SYSERROR("failed to allocate memory");
960 INFO("stored saved_nic #%d idx %d name %s", conf
->num_savednics
,
961 conf
->saved_nics
[conf
->num_savednics
].ifindex
,
962 conf
->saved_nics
[conf
->num_savednics
].orig_name
);
963 conf
->num_savednics
++;
969 static int recv_fd(int sock
, int *fd
)
971 if (lxc_abstract_unix_recv_fd(sock
, fd
, NULL
, 0) < 0) {
972 SYSERROR("Error receiving tty fd from child");
980 static int recv_ttys_from_child(struct lxc_handler
*handler
)
982 struct lxc_conf
*conf
= handler
->conf
;
983 int i
, sock
= handler
->ttysock
[1];
984 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
989 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
)*conf
->tty
);
990 if (!tty_info
->pty_info
) {
991 SYSERROR("failed to allocate pty_info");
995 for (i
= 0; i
< conf
->tty
; i
++) {
996 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
998 if (recv_fd(sock
, &pty_info
->slave
) < 0 ||
999 recv_fd(sock
, &pty_info
->master
) < 0) {
1000 ERROR("Error receiving tty info from child");
1004 tty_info
->nbtty
= conf
->tty
;
1009 void resolve_clone_flags(struct lxc_handler
*handler
)
1011 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
1013 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1014 INFO("Cloning a new user namespace");
1015 handler
->clone_flags
|= CLONE_NEWUSER
;
1018 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
1019 if (!lxc_requests_empty_network(handler
))
1020 handler
->clone_flags
|= CLONE_NEWNET
;
1022 INFO("Inheriting a net namespace");
1025 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1) {
1026 handler
->clone_flags
|= CLONE_NEWIPC
;
1028 INFO("Inheriting an IPC namespace");
1031 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1) {
1032 handler
->clone_flags
|= CLONE_NEWUTS
;
1034 INFO("Inheriting a UTS namespace");
1038 static int lxc_spawn(struct lxc_handler
*handler
)
1040 int failed_before_rename
= 0;
1041 const char *name
= handler
->name
;
1042 char *errmsg
= NULL
;
1043 bool cgroups_connected
= false;
1044 int saved_ns_fd
[LXC_NS_MAX
];
1045 int preserve_mask
= 0, i
, flags
;
1046 int netpipepair
[2], nveths
;
1050 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1051 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
1052 preserve_mask
|= ns_info
[i
].clone_flag
;
1054 if (lxc_sync_init(handler
))
1057 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, handler
->ttysock
) < 0) {
1058 lxc_sync_fini(handler
);
1062 resolve_clone_flags(handler
);
1064 if (handler
->clone_flags
& CLONE_NEWNET
) {
1065 if (!lxc_list_empty(&handler
->conf
->network
)) {
1067 /* Find gateway addresses from the link device, which is
1068 * no longer accessible inside the container. Do this
1069 * before creating network interfaces, since goto
1070 * out_delete_net does not work before lxc_clone. */
1071 if (lxc_find_gateway_addresses(handler
)) {
1072 ERROR("failed to find gateway addresses");
1073 lxc_sync_fini(handler
);
1077 /* that should be done before the clone because we will
1078 * fill the netdev index and use them in the child
1080 if (lxc_create_network(handler
)) {
1081 ERROR("failed to create the network");
1082 lxc_sync_fini(handler
);
1087 if (save_phys_nics(handler
->conf
)) {
1088 ERROR("failed to save physical nic info");
1093 if (!cgroup_init(handler
)) {
1094 ERROR("failed initializing cgroup support");
1095 goto out_delete_net
;
1098 cgroups_connected
= true;
1100 if (!cgroup_create(handler
)) {
1101 ERROR("failed creating cgroups");
1102 goto out_delete_net
;
1106 * if the rootfs is not a blockdev, prevent the container from
1107 * marking it readonly.
1109 * if the container is unprivileged then skip rootfs pinning
1111 if (lxc_list_empty(&handler
->conf
->id_map
)) {
1112 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
1113 if (handler
->pinfd
== -1)
1114 INFO("failed to pin the container's rootfs");
1117 if (!preserve_ns(saved_ns_fd
, preserve_mask
, getpid(), &errmsg
)) {
1118 SYSERROR("Failed to preserve requested namespaces: %s",
1119 errmsg
? errmsg
: "(Out of memory)");
1121 goto out_delete_net
;
1123 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
1124 goto out_delete_net
;
1126 if (am_unpriv() && (nveths
= count_veths(&handler
->conf
->network
))) {
1127 if (pipe(netpipepair
) < 0) {
1128 SYSERROR("Error creating pipe");
1129 goto out_delete_net
;
1131 /* store netpipe in the global var for do_start's use */
1132 netpipe
= netpipepair
[0];
1135 /* Create a process in a new set of namespaces */
1136 flags
= handler
->clone_flags
;
1137 if (handler
->clone_flags
& CLONE_NEWUSER
)
1138 flags
&= ~CLONE_NEWNET
;
1139 handler
->pid
= lxc_clone(do_start
, handler
, handler
->clone_flags
);
1140 if (handler
->pid
< 0) {
1141 SYSERROR("failed to fork into a new namespace");
1142 goto out_delete_net
;
1145 if (!preserve_ns(handler
->nsfd
, handler
->clone_flags
| preserve_mask
, handler
->pid
, &errmsg
)) {
1146 INFO("Failed to store namespace references for stop hook: %s",
1147 errmsg
? errmsg
: "(Out of memory)");
1151 if (attach_ns(saved_ns_fd
))
1152 WARN("failed to restore saved namespaces");
1154 lxc_sync_fini_child(handler
);
1156 /* map the container uids - the container became an invalid
1157 * userid the moment it was cloned with CLONE_NEWUSER - this
1158 * call doesn't change anything immediately, but allows the
1159 * container to setuid(0) (0 being mapped to something else on
1160 * the host) later to become a valid uid again */
1161 if (lxc_map_ids(&handler
->conf
->id_map
, handler
->pid
)) {
1162 ERROR("failed to set up id mapping");
1163 goto out_delete_net
;
1166 if (lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
)) {
1167 failed_before_rename
= 1;
1168 goto out_delete_net
;
1171 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
)) {
1172 failed_before_rename
= 1;
1173 goto out_delete_net
;
1176 if (!cgroup_create_legacy(handler
)) {
1177 ERROR("failed to setup the legacy cgroups for %s", name
);
1178 goto out_delete_net
;
1180 if (!cgroup_setup_limits(handler
, false)) {
1181 ERROR("failed to setup the cgroup limits for '%s'", name
);
1182 goto out_delete_net
;
1185 if (!cgroup_enter(handler
))
1186 goto out_delete_net
;
1188 if (!cgroup_chown(handler
))
1189 goto out_delete_net
;
1191 if (failed_before_rename
)
1192 goto out_delete_net
;
1194 /* Create the network configuration */
1195 if (handler
->clone_flags
& CLONE_NEWNET
) {
1196 if (lxc_assign_network(handler
->lxcpath
, handler
->name
,
1197 &handler
->conf
->network
, handler
->pid
)) {
1198 ERROR("failed to create the configured network");
1199 goto out_delete_net
;
1203 if (netpipe
!= -1) {
1204 struct lxc_list
*iterator
;
1205 struct lxc_netdev
*netdev
;
1208 lxc_list_for_each(iterator
, &handler
->conf
->network
) {
1209 netdev
= iterator
->elem
;
1210 if (netdev
->type
!= LXC_NET_VETH
)
1212 if (write(netpipepair
[1], netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
1213 ERROR("Error writing veth name to container");
1214 goto out_delete_net
;
1217 close(netpipepair
[1]);
1220 /* Tell the child to continue its initialization. we'll get
1221 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
1223 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1224 goto out_delete_net
;
1226 if (!cgroup_setup_limits(handler
, true)) {
1227 ERROR("failed to setup the devices cgroup for '%s'", name
);
1228 goto out_delete_net
;
1231 cgroup_disconnect();
1232 cgroups_connected
= false;
1234 /* read tty fds allocated by child */
1235 if (recv_ttys_from_child(handler
) < 0) {
1236 ERROR("failed to receive tty info from child");
1237 goto out_delete_net
;
1240 /* Tell the child to complete its initialization and wait for
1241 * it to exec or return an error. (the child will never
1242 * return LXC_SYNC_POST_CGROUP+1. It will either close the
1243 * sync pipe, causing lxc_sync_barrier_child to return
1244 * success, or return a different value, causing us to error
1247 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1250 if (detect_shared_rootfs())
1251 umount2(handler
->conf
->rootfs
.mount
, MNT_DETACH
);
1253 if (handler
->ops
->post_start(handler
, handler
->data
))
1256 if (lxc_set_state(name
, handler
, RUNNING
)) {
1257 ERROR("failed to set state to %s",
1258 lxc_state2str(RUNNING
));
1262 lxc_sync_fini(handler
);
1267 if (cgroups_connected
)
1268 cgroup_disconnect();
1269 if (handler
->clone_flags
& CLONE_NEWNET
)
1270 lxc_delete_network(handler
);
1272 lxc_abort(name
, handler
);
1273 lxc_sync_fini(handler
);
1274 if (handler
->pinfd
>= 0) {
1275 close(handler
->pinfd
);
1276 handler
->pinfd
= -1;
1282 int get_netns_fd(int pid
)
1284 char path
[MAXPATHLEN
];
1287 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/ns/net", pid
);
1288 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1289 WARN("Failed to pin netns file for pid %d", pid
);
1293 fd
= open(path
, O_RDONLY
);
1295 WARN("Failed to pin netns file %s for pid %d: %s",
1296 path
, pid
, strerror(errno
));
1302 int __lxc_start(const char *name
, struct lxc_conf
*conf
,
1303 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1306 struct lxc_handler
*handler
;
1311 handler
= lxc_init(name
, conf
, lxcpath
);
1313 ERROR("failed to initialize the container");
1317 handler
->data
= data
;
1318 handler
->backgrounded
= backgrounded
;
1320 if (must_drop_cap_sys_boot(handler
->conf
)) {
1321 #if HAVE_SYS_CAPABILITY_H
1322 DEBUG("Dropping cap_sys_boot");
1324 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
1327 DEBUG("Not dropping cap_sys_boot or watching utmp");
1328 handler
->conf
->need_utmp_watch
= 0;
1331 if (!attach_block_device(handler
->conf
)) {
1332 ERROR("Failure attaching block device");
1333 goto out_fini_nonet
;
1336 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1337 /* if the backing store is a device, mount it here and now */
1338 if (rootfs_is_blockdev(conf
)) {
1339 if (unshare(CLONE_NEWNS
) < 0) {
1340 ERROR("Error unsharing mounts");
1341 goto out_fini_nonet
;
1343 remount_all_slave();
1344 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1345 ERROR("Error setting up rootfs mount as root before spawn");
1346 goto out_fini_nonet
;
1348 INFO("Set up container rootfs as host root");
1352 err
= lxc_spawn(handler
);
1354 ERROR("failed to spawn '%s'", name
);
1355 goto out_detach_blockdev
;
1358 handler
->conf
->reboot
= 0;
1360 netnsfd
= get_netns_fd(handler
->pid
);
1362 err
= lxc_poll(name
, handler
);
1364 ERROR("mainloop exited with an error");
1370 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1374 * If the child process exited but was not signaled,
1375 * it didn't call reboot. This should mean it was an
1376 * lxc-execute which simply exited. In any case, treat
1379 if (WIFSIGNALED(status
)) {
1380 switch(WTERMSIG(status
)) {
1381 case SIGINT
: /* halt */
1382 DEBUG("Container halting");
1384 case SIGHUP
: /* reboot */
1385 DEBUG("Container rebooting");
1386 handler
->conf
->reboot
= 1;
1388 case SIGSYS
: /* seccomp */
1389 DEBUG("Container violated its seccomp policy");
1392 DEBUG("unknown exit status for init: %d", WTERMSIG(status
));
1397 DEBUG("Pushing physical nics back to host namespace");
1398 lxc_rename_phys_nics_on_shutdown(netnsfd
, handler
->conf
);
1400 DEBUG("Tearing down virtual network devices used by container");
1401 lxc_delete_network(handler
);
1406 if (handler
->pinfd
>= 0) {
1407 close(handler
->pinfd
);
1408 handler
->pinfd
= -1;
1411 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1412 err
= lxc_error_set_and_log(handler
->pid
, status
);
1414 lxc_delete_network(handler
);
1416 out_detach_blockdev
:
1417 detach_block_device(handler
->conf
);
1420 lxc_fini(name
, handler
);
1424 lxc_abort(name
, handler
);
1432 static int start(struct lxc_handler
*handler
, void* data
)
1434 struct start_args
*arg
= data
;
1436 NOTICE("exec'ing '%s'", arg
->argv
[0]);
1438 execvp(arg
->argv
[0], arg
->argv
);
1439 SYSERROR("failed to exec %s", arg
->argv
[0]);
1443 static int post_start(struct lxc_handler
*handler
, void* data
)
1445 struct start_args
*arg
= data
;
1447 NOTICE("'%s' started with pid '%d'", arg
->argv
[0], handler
->pid
);
1451 static struct lxc_operations start_ops
= {
1453 .post_start
= post_start
1456 int lxc_start(const char *name
, char *const argv
[], struct lxc_conf
*conf
,
1457 const char *lxcpath
, bool backgrounded
)
1459 struct start_args start_arg
= {
1463 conf
->need_utmp_watch
= 1;
1464 return __lxc_start(name
, conf
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1467 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1470 char destroy
[MAXPATHLEN
];
1473 struct lxc_container
*c
;
1474 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1475 bret
= do_destroy_container(handler
->conf
);
1477 ERROR("Error destroying rootfs for %s", name
);
1481 INFO("Destroyed rootfs for %s", name
);
1483 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1484 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1485 ERROR("Error printing path for %s", name
);
1486 ERROR("Error destroying directory for %s", name
);
1490 c
= lxc_container_new(name
, handler
->lxcpath
);
1492 if (container_disk_lock(c
)) {
1493 INFO("Could not update lxc_snapshots file");
1494 lxc_container_put(c
);
1496 mod_all_rdeps(c
, false);
1497 container_disk_unlock(c
);
1498 lxc_container_put(c
);
1503 ret
= userns_exec_1(handler
->conf
, lxc_rmdir_onedev_wrapper
, destroy
);
1505 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1508 ERROR("Error destroying directory for %s", name
);
1511 INFO("Destroyed directory for %s", name
);
1514 static int lxc_rmdir_onedev_wrapper(void *data
)
1516 char *arg
= (char *) data
;
1517 return lxc_rmdir_onedev(arg
, NULL
);
1520 static bool do_destroy_container(struct lxc_conf
*conf
) {
1522 if (userns_exec_1(conf
, bdev_destroy_wrapper
, conf
) < 0)
1526 return bdev_destroy(conf
);