]>
git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/start.c
2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
8 * Serge Hallyn <serge@hallyn.com>
9 * Christian Brauner <christian.brauner@ubuntu.com>
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
41 #include <sys/mount.h>
42 #include <sys/param.h>
43 #include <sys/prctl.h>
44 #include <sys/socket.h>
46 #include <sys/syscall.h>
47 #include <sys/types.h>
52 #include <sys/capability.h>
55 #ifndef HAVE_DECL_PR_CAPBSET_DROP
56 #define PR_CAPBSET_DROP 24
59 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
60 #define PR_SET_NO_NEW_PRIVS 38
63 #ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
64 #define PR_GET_NO_NEW_PRIVS 39
71 #include "commands_utils.h"
73 #include "confile_utils.h"
77 #include "lxccontainer.h"
79 #include "lxcseccomp.h"
82 #include "namespace.h"
86 #include "storage_utils.h"
91 lxc_log_define(lxc_start
, lxc
);
93 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
94 static bool do_destroy_container(struct lxc_handler
*handler
);
95 static int lxc_rmdir_onedev_wrapper(void *data
);
96 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
99 static void print_top_failing_dir(const char *path
)
101 size_t len
= strlen(path
);
102 char *copy
= alloca(len
+ 1), *p
, *e
, saved
;
108 while (p
< e
&& *p
== '/')
110 while (p
< e
&& *p
!= '/')
114 if (access(copy
, X_OK
)) {
115 SYSERROR("Could not access %s. Please grant it x "
116 "access, or add an ACL for the container "
124 static void close_ns(int ns_fd
[LXC_NS_MAX
])
128 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
136 /* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
138 * Return true on success, false on failure.
140 static bool preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
)
144 for (i
= 0; i
< LXC_NS_MAX
; i
++)
147 ret
= lxc_preserve_ns(pid
, "");
149 SYSERROR("Kernel does not support attaching to namespaces.");
155 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
156 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
158 ns_fd
[i
] = lxc_preserve_ns(pid
, ns_info
[i
].proc_name
);
167 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info
[i
].proc_name
);
169 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info
[i
].proc_name
, 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 attach %s namespace.", ns_info
[i
].proc_name
);
191 static int match_fd(int fd
)
193 return (fd
== 0 || fd
== 1 || fd
== 2);
196 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
197 int *fds_to_ignore
, size_t len_fds
)
199 struct dirent
*direntp
;
204 if (conf
&& conf
->close_all_fds
)
208 dir
= opendir("/proc/self/fd");
210 WARN("Failed to open directory: %s.", strerror(errno
));
216 while ((direntp
= readdir(dir
))) {
220 if (!strcmp(direntp
->d_name
, "."))
223 if (!strcmp(direntp
->d_name
, ".."))
226 if (lxc_safe_int(direntp
->d_name
, &fd
) < 0) {
227 INFO("Could not parse file descriptor for: %s", direntp
->d_name
);
231 for (i
= 0; i
< len_fds
; i
++)
232 if (fds_to_ignore
[i
] == fd
)
235 if (fd
== fddir
|| fd
== lxc_log_fd
||
236 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
240 for (i
= 0; i
< LXC_NS_MAX
; i
++)
241 if (conf
->inherit_ns_fd
[i
] == fd
)
248 if (current_config
&& fd
== current_config
->logfd
)
257 INFO("Closed inherited fd: %d.", fd
);
260 WARN("Inherited fd: %d.", fd
);
263 /* Only enable syslog at this point to avoid the above logging function
264 * to open a new fd and make the check_inherited function enter an
267 lxc_log_enable_syslog();
269 closedir(dir
); /* cannot fail */
273 static int setup_signal_fd(sigset_t
*oldmask
)
278 /* Block everything except serious error signals. */
279 if (sigfillset(&mask
) ||
280 sigdelset(&mask
, SIGILL
) ||
281 sigdelset(&mask
, SIGSEGV
) ||
282 sigdelset(&mask
, SIGBUS
) ||
283 sigdelset(&mask
, SIGWINCH
) ||
284 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
285 SYSERROR("Failed to set signal mask.");
289 fd
= signalfd(-1, &mask
, 0);
291 SYSERROR("Failed to create signal file descriptor.");
295 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
296 SYSERROR("Failed to set FD_CLOEXEC on the signal file descriptor: %d.", fd
);
301 DEBUG("Set SIGCHLD handler with file descriptor: %d.", fd
);
306 static int signal_handler(int fd
, uint32_t events
, void *data
,
307 struct lxc_epoll_descr
*descr
)
309 struct signalfd_siginfo siginfo
;
313 bool init_died
= false;
315 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
317 ERROR("Failed to read signal info from signal file descriptor: %d.", fd
);
321 if (ret
!= sizeof(siginfo
)) {
322 ERROR("Unexpected size for siginfo struct.");
326 /* Check whether init is running. */
328 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
329 if (ret
== 0 && info
.si_pid
== *pid
)
332 if (siginfo
.ssi_signo
!= SIGCHLD
) {
333 kill(*pid
, siginfo
.ssi_signo
);
334 INFO("Forwarded signal %d to pid %d.", siginfo
.ssi_signo
, *pid
);
335 return init_died
? 1 : 0;
338 if (siginfo
.ssi_code
== CLD_STOPPED
) {
339 INFO("Container init process was stopped.");
340 return init_died
? 1 : 0;
341 } else if (siginfo
.ssi_code
== CLD_CONTINUED
) {
342 INFO("Container init process was continued.");
343 return init_died
? 1 : 0;
346 /* More robustness, protect ourself from a SIGCHLD sent
347 * by a process different from the container init.
349 if (siginfo
.ssi_pid
!= *pid
) {
350 NOTICE("Received SIGCHLD from pid %d instead of container init %d.", siginfo
.ssi_pid
, *pid
);
351 return init_died
? 1 : 0;
354 DEBUG("Container init process %d exited.", *pid
);
358 static int lxc_serve_state_clients(const char *name
,
359 struct lxc_handler
*handler
,
363 struct lxc_list
*cur
, *next
;
364 struct state_client
*client
;
365 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
369 /* Only set state under process lock held so that we don't cause
370 * lxc_cmd_add_state_client() to miss a state.
372 handler
->state
= state
;
373 TRACE("set container state to %s", lxc_state2str(state
));
375 if (lxc_list_empty(&handler
->state_clients
)) {
376 TRACE("no state clients registered");
378 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
382 strncpy(msg
.name
, name
, sizeof(msg
.name
));
383 msg
.name
[sizeof(msg
.name
) - 1] = 0;
385 lxc_list_for_each_safe(cur
, &handler
->state_clients
, next
) {
388 if (!client
->states
[state
]) {
389 TRACE("state %s not registered for state client %d",
390 lxc_state2str(state
), client
->clientfd
);
394 TRACE("sending state %s to state client %d",
395 lxc_state2str(state
), client
->clientfd
);
398 ret
= send(client
->clientfd
, &msg
, sizeof(msg
), 0);
400 if (errno
== EINTR
) {
401 TRACE("Caught EINTR; retrying");
405 ERROR("failed to send message to client");
408 /* kick client from list */
409 close(client
->clientfd
);
419 static int lxc_serve_state_socket_pair(const char *name
,
420 struct lxc_handler
*handler
,
425 if (!handler
->backgrounded
||
426 handler
->state_socket_pair
[1] < 0 ||
430 /* Close read end of the socket pair. */
431 close(handler
->state_socket_pair
[0]);
432 handler
->state_socket_pair
[0] = -1;
435 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
436 &(int){state
}, sizeof(int));
437 if (ret
!= sizeof(int)) {
440 SYSERROR("Failed to send state to %d",
441 handler
->state_socket_pair
[1]);
445 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
446 handler
->state_socket_pair
[1]);
448 /* Close write end of the socket pair. */
449 close(handler
->state_socket_pair
[1]);
450 handler
->state_socket_pair
[1] = -1;
455 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
460 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
462 ERROR("Failed to synchronize via anonymous pair of unix sockets");
466 ret
= lxc_serve_state_clients(name
, handler
, state
);
470 /* This function will try to connect to the legacy lxc-monitord state
471 * server and only exists for backwards compatibility.
473 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
478 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
480 int sigfd
= handler
->sigfd
;
481 int pid
= handler
->pid
;
482 struct lxc_epoll_descr descr
;
484 if (lxc_mainloop_open(&descr
)) {
485 ERROR("Failed to create LXC mainloop.");
489 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
490 ERROR("Failed to add signal handler with file descriptor %d to LXC mainloop.", sigfd
);
491 goto out_mainloop_open
;
494 if (lxc_console_mainloop_add(&descr
, handler
->conf
)) {
495 ERROR("Failed to add console handler to LXC mainloop.");
496 goto out_mainloop_open
;
499 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
500 ERROR("Failed to add command handler to LXC mainloop.");
501 goto out_mainloop_open
;
504 TRACE("lxc mainloop is ready");
506 return lxc_mainloop(&descr
, -1);
509 lxc_mainloop_close(&descr
);
517 void lxc_free_handler(struct lxc_handler
*handler
)
519 if (handler
->conf
&& handler
->conf
->maincmd_fd
)
520 close(handler
->conf
->maincmd_fd
);
522 if (handler
->state_socket_pair
[0] >= 0)
523 close(handler
->state_socket_pair
[0]);
525 if (handler
->state_socket_pair
[1] >= 0)
526 close(handler
->state_socket_pair
[1]);
531 handler
->conf
= NULL
;
535 struct lxc_handler
*lxc_init_handler(const char *name
, struct lxc_conf
*conf
,
536 const char *lxcpath
, bool daemonize
)
539 struct lxc_handler
*handler
;
541 handler
= malloc(sizeof(*handler
));
543 ERROR("failed to allocate memory");
547 memset(handler
, 0, sizeof(*handler
));
549 /* Note that am_unpriv() checks the effective uid. We probably don't
550 * care if we are real root only if we are running as root so this
553 handler
->am_root
= !am_unpriv();
554 handler
->data_sock
[0] = handler
->data_sock
[1] = -1;
555 handler
->conf
= conf
;
556 handler
->lxcpath
= lxcpath
;
558 handler
->state_socket_pair
[0] = handler
->state_socket_pair
[1] = -1;
559 lxc_list_init(&handler
->state_clients
);
561 for (i
= 0; i
< LXC_NS_MAX
; i
++)
562 handler
->nsfd
[i
] = -1;
564 handler
->name
= strdup(name
);
565 if (!handler
->name
) {
566 ERROR("failed to allocate memory");
570 if (daemonize
&& !handler
->conf
->reboot
) {
571 /* Create socketpair() to synchronize on daemonized startup.
572 * When the container reboots we don't need to synchronize again
573 * currently so don't open another socketpair().
575 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
576 handler
->state_socket_pair
);
578 ERROR("Failed to create anonymous pair of unix sockets");
581 TRACE("Created anonymous pair {%d,%d} of unix sockets",
582 handler
->state_socket_pair
[0],
583 handler
->state_socket_pair
[1]);
586 if (lxc_cmd_init(name
, handler
, lxcpath
)) {
587 ERROR("failed to set up command socket");
591 TRACE("unix domain socket %d for command server is ready",
592 handler
->conf
->maincmd_fd
);
597 lxc_free_handler(handler
);
602 int lxc_init(const char *name
, struct lxc_handler
*handler
)
604 struct lxc_conf
*conf
= handler
->conf
;
607 TRACE("initialized LSM");
609 if (lxc_read_seccomp_config(conf
) != 0) {
610 ERROR("Failed loading seccomp policy.");
611 goto out_close_maincmd_fd
;
613 TRACE("read seccomp policy");
615 /* Begin by setting the state to STARTING. */
616 if (lxc_set_state(name
, handler
, STARTING
)) {
617 ERROR("Failed to set state for container \"%s\" to \"%s\".", name
, lxc_state2str(STARTING
));
618 goto out_close_maincmd_fd
;
620 TRACE("set container state to \"STARTING\"");
622 /* Start of environment variable setup for hooks. */
623 if (name
&& setenv("LXC_NAME", name
, 1))
624 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name
);
626 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
627 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf
->rcfile
);
629 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
630 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf
->rootfs
.mount
);
632 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
633 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf
->rootfs
.path
);
635 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
636 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf
->console
.path
);
638 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
639 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf
->console
.log_path
);
641 if (setenv("LXC_CGNS_AWARE", "1", 1))
642 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
644 if (setenv("LXC_LOG_LEVEL", lxc_log_priority_to_string(handler
->conf
->loglevel
), 1))
645 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
646 /* End of environment variable setup for hooks. */
648 TRACE("set environment variables");
650 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
651 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name
);
654 TRACE("ran pre-start hooks");
656 /* The signal fd has to be created before forking otherwise if the child
657 * process exits before we setup the signal fd, the event will be lost
658 * and the command will be stuck.
660 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
661 if (handler
->sigfd
< 0) {
662 ERROR("Failed to setup SIGCHLD fd handler.");
665 TRACE("set up signal fd");
667 /* Do this after setting up signals since it might unblock SIGWINCH. */
668 if (lxc_console_create(conf
)) {
669 ERROR("Failed to create console for container \"%s\".", name
);
670 goto out_restore_sigmask
;
672 TRACE("created console");
674 if (lxc_ttys_shift_ids(conf
) < 0) {
675 ERROR("Failed to shift tty into container.");
676 goto out_restore_sigmask
;
678 TRACE("shifted tty ids");
680 INFO("container \"%s\" is initialized", name
);
684 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
686 lxc_delete_tty(&conf
->tty_info
);
688 lxc_set_state(name
, handler
, ABORTING
);
689 out_close_maincmd_fd
:
690 close(conf
->maincmd_fd
);
691 conf
->maincmd_fd
= -1;
695 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
698 struct lxc_list
*cur
, *next
;
699 pid_t self
= getpid();
700 char *namespaces
[LXC_NS_MAX
+ 1];
701 size_t namespace_count
= 0;
703 /* The STOPPING state is there for future cleanup code which can take
706 lxc_set_state(name
, handler
, STOPPING
);
708 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
709 if (handler
->nsfd
[i
] != -1) {
710 rc
= asprintf(&namespaces
[namespace_count
], "%s:/proc/%d/fd/%d",
711 ns_info
[i
].proc_name
, self
, handler
->nsfd
[i
]);
713 SYSERROR("Failed to allocate memory.");
719 namespaces
[namespace_count
] = NULL
;
721 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1))
722 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
724 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1))
725 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
727 if (run_lxc_hooks(name
, "stop", handler
->conf
, handler
->lxcpath
, namespaces
))
728 ERROR("Failed to run lxc.hook.stop for container \"%s\".", name
);
730 while (namespace_count
--)
731 free(namespaces
[namespace_count
]);
732 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
733 if (handler
->nsfd
[i
] != -1) {
734 close(handler
->nsfd
[i
]);
735 handler
->nsfd
[i
] = -1;
739 if (handler
->netnsfd
>= 0) {
740 close(handler
->netnsfd
);
741 handler
->netnsfd
= -1;
744 cgroup_destroy(handler
);
746 lxc_set_state(name
, handler
, STOPPED
);
748 /* close command socket */
749 close(handler
->conf
->maincmd_fd
);
750 handler
->conf
->maincmd_fd
= -1;
752 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
)) {
753 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name
);
754 if (handler
->conf
->reboot
) {
755 WARN("Container will be stopped instead of rebooted.");
756 handler
->conf
->reboot
= 0;
757 if (setenv("LXC_TARGET", "stop", 1))
758 WARN("Failed to set environment variable: LXC_TARGET=stop.");
762 /* Reset mask set by setup_signal_fd. */
763 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
764 WARN("Failed to restore signal mask.");
766 lxc_console_delete(&handler
->conf
->console
);
767 lxc_delete_tty(&handler
->conf
->tty_info
);
769 /* The command socket is now closed, no more state clients can register
770 * themselves from now on. So free the list of state clients.
772 lxc_list_for_each_safe(cur
, &handler
->state_clients
, next
) {
773 struct state_client
*client
= cur
->elem
;
774 /* close state client socket */
775 close(client
->clientfd
);
781 if (handler
->data_sock
[0] != -1) {
782 close(handler
->data_sock
[0]);
783 close(handler
->data_sock
[1]);
786 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1)
787 lxc_destroy_container_on_signal(handler
, name
);
793 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
797 lxc_set_state(name
, handler
, ABORTING
);
798 if (handler
->pid
> 0)
799 kill(handler
->pid
, SIGKILL
);
800 while ((ret
= waitpid(-1, &status
, 0)) > 0) {
805 static int do_start(void *data
)
807 struct lxc_list
*iterator
;
808 struct lxc_handler
*handler
= data
;
809 int devnull_fd
= -1, ret
;
812 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
813 SYSERROR("Failed to set signal mask.");
817 /* This prctl must be before the synchro, so if the parent dies before
818 * we set the parent death signal, we will detect its death with the
819 * synchro right after, otherwise we have a window where the parent can
820 * exit before we set the pdeath signal leading to a unsupervized
823 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
824 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL.");
828 lxc_sync_fini_parent(handler
);
830 /* Don't leak the pinfd to the container. */
831 if (handler
->pinfd
>= 0) {
832 close(handler
->pinfd
);
835 if (lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
))
838 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
839 * https://github.com/lxc/lxd/issues/1978.
841 if ((handler
->clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
842 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
843 ret
= unshare(CLONE_NEWNET
);
845 SYSERROR("Failed to unshare CLONE_NEWNET.");
846 goto out_warn_father
;
848 INFO("Unshared CLONE_NEWNET.");
851 /* Tell the parent task it can begin to configure the container and wait
854 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
857 if (lxc_network_recv_veth_names_from_parent(handler
) < 0) {
858 ERROR("Failed to receive veth names from parent");
859 goto out_warn_father
;
862 /* If we are in a new user namespace, become root there to have
863 * privilege over our namespace.
865 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
866 if (lxc_switch_uid_gid(0, 0) < 0)
867 goto out_warn_father
;
869 /* Drop groups only after we switched to a valid gid in the new
872 if (lxc_setgroups(0, NULL
) < 0)
873 goto out_warn_father
;
876 if (access(handler
->lxcpath
, X_OK
)) {
877 print_top_failing_dir(handler
->lxcpath
);
878 goto out_warn_father
;
881 ret
= snprintf(path
, sizeof(path
), "%s/dev/null", handler
->conf
->rootfs
.mount
);
882 if (ret
< 0 || ret
>= sizeof(path
))
883 goto out_warn_father
;
885 /* In order to checkpoint restore, we need to have everything in the
886 * same mount namespace. However, some containers may not have a
887 * reasonable /dev (in particular, they may not have /dev/null), so we
888 * can't set init's std fds to /dev/null by opening it from inside the
891 * If that's the case, fall back to using the host's /dev/null. This
892 * means that migration won't work, but at least we won't spew output
893 * where it isn't wanted.
895 if (handler
->backgrounded
&& !handler
->conf
->autodev
&& access(path
, F_OK
) < 0) {
896 devnull_fd
= open_devnull();
899 goto out_warn_father
;
900 WARN("Using /dev/null from the host for container init's "
901 "standard file descriptors. Migration will not work.");
904 /* Ask father to setup cgroups and wait for him to finish. */
905 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
908 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
909 * earlier we end up with a wrong view of /proc/self/cgroup. For
910 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
911 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
912 * /proc/self/cgroup would show us:
916 * whereas it should actually show
920 if (cgns_supported()) {
921 if (unshare(CLONE_NEWCGROUP
) < 0) {
922 INFO("Failed to unshare CLONE_NEWCGROUP.");
923 goto out_warn_father
;
925 INFO("Unshared CLONE_NEWCGROUP.");
928 /* Add the requested environment variables to the current environment to
929 * allow them to be used by the various hooks, such as the start hook
932 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
933 if (putenv((char *)iterator
->elem
)) {
934 SYSERROR("Failed to set environment variable: %s.", (char *)iterator
->elem
);
935 goto out_warn_father
;
939 /* Setup the container, ip, names, utsname, ... */
940 ret
= lxc_setup(handler
);
941 close(handler
->data_sock
[0]);
942 close(handler
->data_sock
[1]);
944 ERROR("Failed to setup container \"%s\".", handler
->name
);
945 goto out_warn_father
;
948 /* Set the label to change to when we exec(2) the container's init. */
949 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
950 goto out_warn_father
;
952 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
953 * before we aren't allowed anymore.
955 if (handler
->conf
->no_new_privs
) {
956 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
957 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
958 goto out_warn_father
;
960 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
963 /* Some init's such as busybox will set sane tty settings on stdin,
964 * stdout, stderr which it thinks is the console. We already set them
965 * the way we wanted on the real terminal, and we want init to do its
966 * setup on its console ie. the pty allocated in lxc_console_create() so
967 * make sure that that pty is stdin,stdout,stderr.
969 if (handler
->conf
->console
.slave
>= 0)
970 if (set_stdfds(handler
->conf
->console
.slave
) < 0) {
971 ERROR("Failed to redirect std{in,out,err} to pty file "
973 handler
->conf
->console
.slave
);
974 goto out_warn_father
;
977 /* If we mounted a temporary proc, then unmount it now. */
978 tmp_proc_unmount(handler
->conf
);
980 if (lxc_seccomp_load(handler
->conf
) != 0)
981 goto out_warn_father
;
983 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
984 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler
->name
);
985 goto out_warn_father
;
988 close(handler
->sigfd
);
990 if (devnull_fd
< 0) {
991 devnull_fd
= open_devnull();
994 goto out_warn_father
;
997 if (handler
->conf
->console
.slave
< 0 && handler
->backgrounded
)
998 if (set_stdfds(devnull_fd
) < 0) {
999 ERROR("Failed to redirect std{in,out,err} to "
1001 goto out_warn_father
;
1004 if (devnull_fd
>= 0) {
1011 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
))
1012 goto out_warn_father
;
1014 /* Reset the environment variables the user requested in a clear
1018 SYSERROR("Failed to clear environment.");
1019 /* Don't error out though. */
1022 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1023 if (putenv((char *)iterator
->elem
)) {
1024 SYSERROR("Failed to set environment variable: %s.", (char *)iterator
->elem
);
1025 goto out_warn_father
;
1029 if (putenv("container=lxc")) {
1030 SYSERROR("Failed to set environment variable: container=lxc.");
1031 goto out_warn_father
;
1034 if (handler
->conf
->pty_names
) {
1035 if (putenv(handler
->conf
->pty_names
)) {
1036 SYSERROR("Failed to set environment variable for container ptys.");
1037 goto out_warn_father
;
1041 /* The container has been setup. We can now switch to an unprivileged
1044 if (handler
->conf
->is_execute
) {
1045 bool have_cap_setgid
;
1046 uid_t new_uid
= handler
->conf
->init_uid
;
1047 gid_t new_gid
= handler
->conf
->init_gid
;
1049 /* If we are in a new user namespace we already dropped all
1050 * groups when we switched to root in the new user namespace
1051 * further above. Only drop groups if we can, so ensure that we
1052 * have necessary privilege.
1055 have_cap_setgid
= lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
);
1057 have_cap_setgid
= false;
1059 if (lxc_list_empty(&handler
->conf
->id_map
) && have_cap_setgid
) {
1060 if (lxc_setgroups(0, NULL
) < 0)
1061 goto out_warn_father
;
1064 if (lxc_switch_uid_gid(new_uid
, new_gid
) < 0)
1065 goto out_warn_father
;
1068 /* After this call, we are in error because this ops should not return
1071 handler
->ops
->start(handler
, handler
->data
);
1074 /* We want the parent to know something went wrong, so we return a
1075 * special error code.
1077 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1080 if (devnull_fd
>= 0)
1086 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1089 struct lxc_pty_info
*pty_info
;
1091 int sock
= handler
->data_sock
[1];
1092 struct lxc_conf
*conf
= handler
->conf
;
1093 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
1098 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
) * conf
->tty
);
1099 if (!tty_info
->pty_info
)
1102 for (i
= 0; i
< conf
->tty
; i
++) {
1105 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1109 pty_info
= &tty_info
->pty_info
[i
];
1111 pty_info
->master
= ttyfds
[0];
1112 pty_info
->slave
= ttyfds
[1];
1113 TRACE("Received pty with master fd %d and slave fd %d from "
1114 "parent", pty_info
->master
, pty_info
->slave
);
1117 ERROR("Failed to receive %d ttys from child: %s", conf
->tty
,
1120 TRACE("Received %d ttys from child", conf
->tty
);
1122 tty_info
->nbtty
= conf
->tty
;
1127 void resolve_clone_flags(struct lxc_handler
*handler
)
1129 handler
->clone_flags
= CLONE_NEWNS
;
1131 if (!lxc_list_empty(&handler
->conf
->id_map
))
1132 handler
->clone_flags
|= CLONE_NEWUSER
;
1134 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
1135 if (!lxc_requests_empty_network(handler
))
1136 handler
->clone_flags
|= CLONE_NEWNET
;
1138 INFO("Inheriting a NET namespace.");
1141 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1)
1142 handler
->clone_flags
|= CLONE_NEWIPC
;
1144 INFO("Inheriting an IPC namespace.");
1146 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1)
1147 handler
->clone_flags
|= CLONE_NEWUTS
;
1149 INFO("Inheriting a UTS namespace.");
1151 if (handler
->conf
->inherit_ns_fd
[LXC_NS_PID
] == -1)
1152 handler
->clone_flags
|= CLONE_NEWPID
;
1154 INFO("Inheriting a PID namespace.");
1157 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1158 * exec()s the requested container binary.
1159 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1160 * right here should be double checked if they'd pose a security risk. (For
1161 * example, any {u}mount() operations performed here will be reflected on the
1164 static int lxc_spawn(struct lxc_handler
*handler
)
1167 const char *name
= handler
->name
;
1168 bool wants_to_map_ids
;
1169 int saved_ns_fd
[LXC_NS_MAX
];
1170 struct lxc_list
*id_map
;
1171 int preserve_mask
= 0;
1172 bool cgroups_connected
= false;
1174 id_map
= &handler
->conf
->id_map
;
1175 wants_to_map_ids
= !lxc_list_empty(id_map
);
1177 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1178 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
1179 preserve_mask
|= ns_info
[i
].clone_flag
;
1181 if (lxc_sync_init(handler
))
1184 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1185 handler
->data_sock
);
1187 lxc_sync_fini(handler
);
1191 resolve_clone_flags(handler
);
1193 if (handler
->clone_flags
& CLONE_NEWNET
) {
1194 if (!lxc_list_empty(&handler
->conf
->network
)) {
1196 /* Find gateway addresses from the link device, which is
1197 * no longer accessible inside the container. Do this
1198 * before creating network interfaces, since goto
1199 * out_delete_net does not work before lxc_clone.
1201 if (lxc_find_gateway_addresses(handler
)) {
1202 ERROR("Failed to find gateway addresses.");
1203 lxc_sync_fini(handler
);
1207 /* That should be done before the clone because we will
1208 * fill the netdev index and use them in the child.
1210 if (lxc_create_network_priv(handler
)) {
1211 ERROR("Failed to create the network.");
1212 lxc_sync_fini(handler
);
1218 if (!cgroup_init(handler
)) {
1219 ERROR("Failed initializing cgroup support.");
1220 goto out_delete_net
;
1223 cgroups_connected
= true;
1225 if (!cgroup_create(handler
)) {
1226 ERROR("Failed creating cgroups.");
1227 goto out_delete_net
;
1230 /* If the rootfs is not a blockdev, prevent the container from marking
1232 * If the container is unprivileged then skip rootfs pinning.
1234 if (!wants_to_map_ids
) {
1235 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
1236 if (handler
->pinfd
== -1)
1237 INFO("Failed to pin the rootfs for container \"%s\".", handler
->name
);
1240 if (!preserve_ns(saved_ns_fd
, preserve_mask
, getpid()))
1241 goto out_delete_net
;
1243 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
1244 goto out_delete_net
;
1246 /* Create a process in a new set of namespaces. */
1247 flags
= handler
->clone_flags
;
1248 if (handler
->clone_flags
& CLONE_NEWUSER
) {
1249 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1250 * clone a new user namespace first and only later unshare our
1251 * network namespace to ensure that network devices ownership is
1254 flags
&= ~CLONE_NEWNET
;
1256 handler
->pid
= lxc_clone(do_start
, handler
, flags
);
1257 if (handler
->pid
< 0) {
1258 SYSERROR("Failed to clone a new set of namespaces.");
1259 goto out_delete_net
;
1262 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1263 if (flags
& ns_info
[i
].clone_flag
)
1264 INFO("Cloned %s.", ns_info
[i
].flag_name
);
1266 if (!preserve_ns(handler
->nsfd
, handler
->clone_flags
| preserve_mask
, handler
->pid
))
1267 INFO("Failed to preserve namespace for lxc.hook.stop.");
1269 if (attach_ns(saved_ns_fd
))
1270 WARN("Failed to restore saved namespaces.");
1272 lxc_sync_fini_child(handler
);
1274 /* Map the container uids. The container became an invalid userid the
1275 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1276 * anything immediately, but allows the container to setuid(0) (0 being
1277 * mapped to something else on the host.) later to become a valid uid
1280 if (wants_to_map_ids
&& lxc_map_ids(id_map
, handler
->pid
)) {
1281 ERROR("Failed to set up id mapping.");
1282 goto out_delete_net
;
1285 if (lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
))
1286 goto out_delete_net
;
1288 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
))
1289 goto out_delete_net
;
1291 if (!cgroup_create_legacy(handler
)) {
1292 ERROR("Failed to setup legacy cgroups for container \"%s\".", name
);
1293 goto out_delete_net
;
1295 if (!cgroup_setup_limits(handler
, false)) {
1296 ERROR("Failed to setup cgroup limits for container \"%s\".", name
);
1297 goto out_delete_net
;
1300 if (!cgroup_enter(handler
))
1301 goto out_delete_net
;
1303 if (!cgroup_chown(handler
))
1304 goto out_delete_net
;
1306 handler
->netnsfd
= lxc_preserve_ns(handler
->pid
, "net");
1307 if (handler
->netnsfd
< 0) {
1308 ERROR("Failed to preserve network namespace");
1309 goto out_delete_net
;
1312 /* Create the network configuration. */
1313 if (handler
->clone_flags
& CLONE_NEWNET
) {
1314 if (lxc_network_move_created_netdev_priv(handler
->lxcpath
,
1316 &handler
->conf
->network
,
1318 ERROR("Failed to create the configured network.");
1319 goto out_delete_net
;
1322 if (lxc_create_network_unpriv(handler
->lxcpath
, handler
->name
,
1323 &handler
->conf
->network
,
1325 ERROR("Failed to create the configured network.");
1326 goto out_delete_net
;
1330 if (lxc_network_send_veth_names_to_child(handler
) < 0) {
1331 ERROR("Failed to send veth names to child");
1332 goto out_delete_net
;
1335 /* Tell the child to continue its initialization. We'll get
1336 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1338 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1339 goto out_delete_net
;
1341 if (!lxc_list_empty(&handler
->conf
->limits
) && setup_resource_limits(&handler
->conf
->limits
, handler
->pid
)) {
1342 ERROR("failed to setup resource limits for '%s'", name
);
1343 goto out_delete_net
;
1346 if (lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
))
1347 goto out_delete_net
;
1349 if (!cgroup_setup_limits(handler
, true)) {
1350 ERROR("Failed to setup the devices cgroup for container \"%s\".", name
);
1351 goto out_delete_net
;
1353 TRACE("Set up cgroup device limits");
1355 cgroup_disconnect();
1356 cgroups_connected
= false;
1358 /* Tell the child to complete its initialization and wait for it to exec
1359 * or return an error. (The child will never return
1360 * LXC_SYNC_POST_CGROUP+1. It will either close the sync pipe, causing
1361 * lxc_sync_barrier_child to return success, or return a different
1362 * value, causing us to error out).
1364 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1367 if (lxc_network_recv_name_and_ifindex_from_child(handler
) < 0) {
1368 ERROR("Failed to receive names and ifindices for network "
1369 "devices from child");
1370 goto out_delete_net
;
1373 /* Now all networks are created, network devices are moved into place,
1374 * and the correct names and ifindeces in the respective namespaces have
1375 * been recorded. The corresponding structs have now all been filled. So
1376 * log them for debugging purposes.
1378 lxc_log_configured_netdevs(handler
->conf
);
1380 /* Read tty fds allocated by child. */
1381 if (lxc_recv_ttys_from_child(handler
) < 0) {
1382 ERROR("Failed to receive tty info from child process.");
1383 goto out_delete_net
;
1386 if (handler
->ops
->post_start(handler
, handler
->data
))
1389 if (lxc_set_state(name
, handler
, RUNNING
)) {
1390 ERROR("Failed to set state for container \"%s\" to \"%s\".", name
,
1391 lxc_state2str(RUNNING
));
1395 lxc_sync_fini(handler
);
1400 if (cgroups_connected
)
1401 cgroup_disconnect();
1403 if (handler
->clone_flags
& CLONE_NEWNET
) {
1404 DEBUG("Tearing down network devices");
1405 if (!lxc_delete_network_priv(handler
))
1406 DEBUG("Failed tearing down network devices");
1408 if (!lxc_delete_network_unpriv(handler
))
1409 DEBUG("Failed tearing down network devices");
1413 lxc_abort(name
, handler
);
1414 lxc_sync_fini(handler
);
1415 if (handler
->pinfd
>= 0) {
1416 close(handler
->pinfd
);
1417 handler
->pinfd
= -1;
1420 if (handler
->netnsfd
>= 0) {
1421 close(handler
->netnsfd
);
1422 handler
->netnsfd
= -1;
1428 int __lxc_start(const char *name
, struct lxc_handler
*handler
,
1429 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1434 struct lxc_conf
*conf
= handler
->conf
;
1436 if (lxc_init(name
, handler
) < 0) {
1437 ERROR("Failed to initialize container \"%s\".", name
);
1441 handler
->data
= data
;
1442 handler
->backgrounded
= backgrounded
;
1443 handler
->netnsfd
= -1;
1445 if (!attach_block_device(handler
->conf
)) {
1446 ERROR("Failed to attach block device.");
1447 goto out_fini_nonet
;
1450 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1451 /* If the backing store is a device, mount it here and now. */
1452 if (rootfs_is_blockdev(conf
)) {
1453 if (unshare(CLONE_NEWNS
) < 0) {
1454 ERROR("Failed to unshare CLONE_NEWNS.");
1455 goto out_fini_nonet
;
1457 INFO("Unshared CLONE_NEWNS.");
1459 remount_all_slave();
1460 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1461 ERROR("Error setting up rootfs mount as root before spawn.");
1462 goto out_fini_nonet
;
1464 INFO("Set up container rootfs as host root.");
1468 err
= lxc_spawn(handler
);
1470 ERROR("Failed to spawn container \"%s\".", name
);
1471 goto out_detach_blockdev
;
1474 handler
->conf
->reboot
= 0;
1476 err
= lxc_poll(name
, handler
);
1478 ERROR("LXC mainloop exited with error: %d.", err
);
1482 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1485 /* If the child process exited but was not signaled, it didn't call
1486 * reboot. This should mean it was an lxc-execute which simply exited.
1487 * In any case, treat it as a 'halt'.
1489 if (WIFSIGNALED(status
)) {
1490 switch(WTERMSIG(status
)) {
1491 case SIGINT
: /* halt */
1492 DEBUG("Container \"%s\" is halting.", name
);
1494 case SIGHUP
: /* reboot */
1495 DEBUG("Container \"%s\" is rebooting.", name
);
1496 handler
->conf
->reboot
= 1;
1498 case SIGSYS
: /* seccomp */
1499 DEBUG("Container \"%s\" violated its seccomp policy.", name
);
1502 DEBUG("Unknown exit status for container \"%s\" init %d.", name
, WTERMSIG(status
));
1507 err
= lxc_restore_phys_nics_to_netns(handler
);
1509 ERROR("Failed to move physical network devices back to parent "
1510 "network namespace");
1512 if (handler
->pinfd
>= 0) {
1513 close(handler
->pinfd
);
1514 handler
->pinfd
= -1;
1517 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1518 err
= lxc_error_set_and_log(handler
->pid
, status
);
1521 DEBUG("Tearing down network devices");
1522 if (!lxc_delete_network_priv(handler
))
1523 DEBUG("Failed tearing down network devices");
1525 if (!lxc_delete_network_unpriv(handler
))
1526 DEBUG("Failed tearing down network devices");
1528 if (handler
->netnsfd
>= 0) {
1529 close(handler
->netnsfd
);
1530 handler
->netnsfd
= -1;
1533 out_detach_blockdev
:
1534 detach_block_device(handler
->conf
);
1537 lxc_fini(name
, handler
);
1541 lxc_abort(name
, handler
);
1549 static int start(struct lxc_handler
*handler
, void* data
)
1551 struct start_args
*arg
= data
;
1553 NOTICE("Exec'ing \"%s\".", arg
->argv
[0]);
1555 execvp(arg
->argv
[0], arg
->argv
);
1556 SYSERROR("Failed to exec \"%s\".", arg
->argv
[0]);
1560 static int post_start(struct lxc_handler
*handler
, void* data
)
1562 struct start_args
*arg
= data
;
1564 NOTICE("Started \"%s\" with pid \"%d\".", arg
->argv
[0], handler
->pid
);
1568 static struct lxc_operations start_ops
= {
1570 .post_start
= post_start
1573 int lxc_start(const char *name
, char *const argv
[], struct lxc_handler
*handler
,
1574 const char *lxcpath
, bool backgrounded
)
1576 struct start_args start_arg
= {
1580 return __lxc_start(name
, handler
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1583 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1586 char destroy
[MAXPATHLEN
];
1589 struct lxc_container
*c
;
1590 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1591 bret
= do_destroy_container(handler
);
1593 ERROR("Error destroying rootfs for container \"%s\".", name
);
1597 INFO("Destroyed rootfs for container \"%s\".", name
);
1599 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1600 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1601 ERROR("Error destroying directory for container \"%s\".", name
);
1605 c
= lxc_container_new(name
, handler
->lxcpath
);
1607 if (container_disk_lock(c
)) {
1608 INFO("Could not update lxc_snapshots file.");
1609 lxc_container_put(c
);
1611 mod_all_rdeps(c
, false);
1612 container_disk_unlock(c
);
1613 lxc_container_put(c
);
1617 if (!handler
->am_root
)
1618 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
1619 destroy
, "lxc_rmdir_onedev_wrapper");
1621 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1624 ERROR("Error destroying directory for container \"%s\".", name
);
1627 INFO("Destroyed directory for container \"%s\".", name
);
1630 static int lxc_rmdir_onedev_wrapper(void *data
)
1632 char *arg
= (char *) data
;
1633 return lxc_rmdir_onedev(arg
, NULL
);
1636 static bool do_destroy_container(struct lxc_handler
*handler
) {
1639 if (!handler
->am_root
) {
1640 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
1641 handler
->conf
, "storage_destroy_wrapper");
1648 return storage_destroy(handler
->conf
);