]>
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>
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>
50 #include <sys/capability.h>
53 #ifndef HAVE_DECL_PR_CAPBSET_DROP
54 #define PR_CAPBSET_DROP 24
57 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
58 #define PR_SET_NO_NEW_PRIVS 38
61 #ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
62 #define PR_GET_NO_NEW_PRIVS 39
69 #include "commands_utils.h"
71 #include "confile_utils.h"
75 #include "lxccontainer.h"
77 #include "lxcseccomp.h"
80 #include "namespace.h"
84 #include "storage_utils.h"
89 lxc_log_define(lxc_start
, lxc
);
91 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
92 static bool do_destroy_container(struct lxc_handler
*handler
);
93 static int lxc_rmdir_onedev_wrapper(void *data
);
94 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
97 static void print_top_failing_dir(const char *path
)
99 size_t len
= strlen(path
);
100 char *copy
= alloca(len
+ 1), *p
, *e
, saved
;
106 while (p
< e
&& *p
== '/')
108 while (p
< e
&& *p
!= '/')
112 if (access(copy
, X_OK
)) {
113 SYSERROR("Could not access %s. Please grant it x "
114 "access, or add an ACL for the container "
122 static void close_ns(int ns_fd
[LXC_NS_MAX
])
126 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
134 /* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
136 * Return true on success, false on failure.
138 static bool preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
)
142 for (i
= 0; i
< LXC_NS_MAX
; i
++)
145 ret
= lxc_preserve_ns(pid
, "");
147 SYSERROR("Kernel does not support attaching to namespaces.");
153 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
154 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
156 ns_fd
[i
] = lxc_preserve_ns(pid
, ns_info
[i
].proc_name
);
165 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info
[i
].proc_name
);
167 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info
[i
].proc_name
, strerror(errno
));
172 static int attach_ns(const int ns_fd
[LXC_NS_MAX
]) {
175 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
179 if (setns(ns_fd
[i
], 0) != 0)
185 SYSERROR("Failed to attach %s namespace.", ns_info
[i
].proc_name
);
189 static int match_fd(int fd
)
191 return (fd
== 0 || fd
== 1 || fd
== 2);
194 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
195 int *fds_to_ignore
, size_t len_fds
)
197 struct dirent
*direntp
;
202 if (conf
&& conf
->close_all_fds
)
206 dir
= opendir("/proc/self/fd");
208 WARN("Failed to open directory: %s.", strerror(errno
));
214 while ((direntp
= readdir(dir
))) {
218 if (!strcmp(direntp
->d_name
, "."))
221 if (!strcmp(direntp
->d_name
, ".."))
224 if (lxc_safe_int(direntp
->d_name
, &fd
) < 0) {
225 INFO("Could not parse file descriptor for: %s", direntp
->d_name
);
229 for (i
= 0; i
< len_fds
; i
++)
230 if (fds_to_ignore
[i
] == fd
)
233 if (fd
== fddir
|| fd
== lxc_log_fd
||
234 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
237 if (current_config
&& fd
== current_config
->logfd
)
246 INFO("Closed inherited fd: %d.", fd
);
249 WARN("Inherited fd: %d.", fd
);
252 /* Only enable syslog at this point to avoid the above logging function
253 * to open a new fd and make the check_inherited function enter an
256 lxc_log_enable_syslog();
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 signal file descriptor.");
284 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
285 SYSERROR("Failed to set FD_CLOEXEC on the signal file descriptor: %d.", fd
);
290 DEBUG("Set SIGCHLD handler with file descriptor: %d.", fd
);
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 from signal file descriptor: %d.", fd
);
310 if (ret
!= sizeof(siginfo
)) {
311 ERROR("Unexpected size for siginfo struct.");
315 /* Check whether init is running. */
317 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
318 if (ret
== 0 && info
.si_pid
== *pid
)
321 if (siginfo
.ssi_signo
!= SIGCHLD
) {
322 kill(*pid
, siginfo
.ssi_signo
);
323 INFO("Forwarded signal %d to pid %d.", siginfo
.ssi_signo
, *pid
);
324 return init_died
? 1 : 0;
327 if (siginfo
.ssi_code
== CLD_STOPPED
) {
328 INFO("Container init process was stopped.");
329 return init_died
? 1 : 0;
330 } else if (siginfo
.ssi_code
== CLD_CONTINUED
) {
331 INFO("Container init process was continued.");
332 return init_died
? 1 : 0;
335 /* More robustness, protect ourself from a SIGCHLD sent
336 * by a process different from the container init.
338 if (siginfo
.ssi_pid
!= *pid
) {
339 NOTICE("Received SIGCHLD from pid %d instead of container init %d.", siginfo
.ssi_pid
, *pid
);
340 return init_died
? 1 : 0;
343 DEBUG("Container init process %d exited.", *pid
);
347 static int lxc_serve_state_clients(const char *name
,
348 struct lxc_handler
*handler
,
352 struct lxc_list
*cur
, *next
;
353 struct state_client
*client
;
354 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
358 /* Only set state under process lock held so that we don't cause
359 * lxc_cmd_add_state_client() to miss a state.
361 handler
->state
= state
;
362 TRACE("set container state to %s", lxc_state2str(state
));
364 if (lxc_list_empty(&handler
->state_clients
)) {
365 TRACE("no state clients registered");
367 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
371 strncpy(msg
.name
, name
, sizeof(msg
.name
));
372 msg
.name
[sizeof(msg
.name
) - 1] = 0;
374 lxc_list_for_each_safe(cur
, &handler
->state_clients
, next
) {
377 if (!client
->states
[state
]) {
378 TRACE("state %s not registered for state client %d",
379 lxc_state2str(state
), client
->clientfd
);
383 TRACE("sending state %s to state client %d",
384 lxc_state2str(state
), client
->clientfd
);
387 ret
= send(client
->clientfd
, &msg
, sizeof(msg
), 0);
389 if (errno
== EINTR
) {
390 TRACE("Caught EINTR; retrying");
394 ERROR("failed to send message to client");
397 /* kick client from list */
398 close(client
->clientfd
);
408 static int lxc_serve_state_socket_pair(const char *name
,
409 struct lxc_handler
*handler
,
414 if (!handler
->backgrounded
||
415 handler
->state_socket_pair
[1] < 0 ||
419 /* Close read end of the socket pair. */
420 close(handler
->state_socket_pair
[0]);
421 handler
->state_socket_pair
[0] = -1;
424 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
425 &(int){state
}, sizeof(int));
426 if (ret
!= sizeof(int)) {
429 SYSERROR("Failed to send state to %d",
430 handler
->state_socket_pair
[1]);
434 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
435 handler
->state_socket_pair
[1]);
437 /* Close write end of the socket pair. */
438 close(handler
->state_socket_pair
[1]);
439 handler
->state_socket_pair
[1] = -1;
444 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
449 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
451 ERROR("Failed to synchronize via anonymous pair of unix sockets");
455 ret
= lxc_serve_state_clients(name
, handler
, state
);
459 /* This function will try to connect to the legacy lxc-monitord state
460 * server and only exists for backwards compatibility.
462 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
467 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
469 int sigfd
= handler
->sigfd
;
470 int pid
= handler
->pid
;
471 struct lxc_epoll_descr descr
;
473 if (lxc_mainloop_open(&descr
)) {
474 ERROR("Failed to create LXC mainloop.");
478 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
479 ERROR("Failed to add signal handler with file descriptor %d to LXC mainloop.", sigfd
);
480 goto out_mainloop_open
;
483 if (lxc_console_mainloop_add(&descr
, handler
->conf
)) {
484 ERROR("Failed to add console handler to LXC mainloop.");
485 goto out_mainloop_open
;
488 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
489 ERROR("Failed to add command handler to LXC mainloop.");
490 goto out_mainloop_open
;
493 TRACE("lxc mainloop is ready");
495 return lxc_mainloop(&descr
, -1);
498 lxc_mainloop_close(&descr
);
506 void lxc_free_handler(struct lxc_handler
*handler
)
508 if (handler
->conf
&& handler
->conf
->maincmd_fd
)
509 close(handler
->conf
->maincmd_fd
);
511 if (handler
->state_socket_pair
[0] >= 0)
512 close(handler
->state_socket_pair
[0]);
514 if (handler
->state_socket_pair
[1] >= 0)
515 close(handler
->state_socket_pair
[1]);
520 handler
->conf
= NULL
;
524 struct lxc_handler
*lxc_init_handler(const char *name
, struct lxc_conf
*conf
,
525 const char *lxcpath
, bool daemonize
)
528 struct lxc_handler
*handler
;
530 handler
= malloc(sizeof(*handler
));
532 ERROR("failed to allocate memory");
536 memset(handler
, 0, sizeof(*handler
));
538 /* Note that am_unpriv() checks the effective uid. We probably don't
539 * care if we are real root only if we are running as root so this
542 handler
->am_root
= !am_unpriv();
543 handler
->data_sock
[0] = handler
->data_sock
[1] = -1;
544 handler
->conf
= conf
;
545 handler
->lxcpath
= lxcpath
;
547 handler
->state_socket_pair
[0] = handler
->state_socket_pair
[1] = -1;
548 lxc_list_init(&handler
->state_clients
);
550 for (i
= 0; i
< LXC_NS_MAX
; i
++)
551 handler
->nsfd
[i
] = -1;
553 handler
->name
= strdup(name
);
554 if (!handler
->name
) {
555 ERROR("failed to allocate memory");
559 if (daemonize
&& !handler
->conf
->reboot
) {
560 /* Create socketpair() to synchronize on daemonized startup.
561 * When the container reboots we don't need to synchronize again
562 * currently so don't open another socketpair().
564 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
565 handler
->state_socket_pair
);
567 ERROR("Failed to create anonymous pair of unix sockets");
570 TRACE("Created anonymous pair {%d,%d} of unix sockets",
571 handler
->state_socket_pair
[0],
572 handler
->state_socket_pair
[1]);
575 if (lxc_cmd_init(name
, handler
, lxcpath
)) {
576 ERROR("failed to set up command socket");
580 TRACE("unix domain socket %d for command server is ready",
581 handler
->conf
->maincmd_fd
);
586 lxc_free_handler(handler
);
591 int lxc_init(const char *name
, struct lxc_handler
*handler
)
593 struct lxc_conf
*conf
= handler
->conf
;
596 TRACE("initialized LSM");
598 if (lxc_read_seccomp_config(conf
) != 0) {
599 ERROR("Failed loading seccomp policy.");
600 goto out_close_maincmd_fd
;
602 TRACE("read seccomp policy");
604 /* Begin by setting the state to STARTING. */
605 if (lxc_set_state(name
, handler
, STARTING
)) {
606 ERROR("Failed to set state for container \"%s\" to \"%s\".", name
, lxc_state2str(STARTING
));
607 goto out_close_maincmd_fd
;
609 TRACE("set container state to \"STARTING\"");
611 /* Start of environment variable setup for hooks. */
612 if (name
&& setenv("LXC_NAME", name
, 1))
613 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name
);
615 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
616 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf
->rcfile
);
618 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
619 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf
->rootfs
.mount
);
621 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
622 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf
->rootfs
.path
);
624 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
625 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf
->console
.path
);
627 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
628 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf
->console
.log_path
);
630 if (setenv("LXC_CGNS_AWARE", "1", 1))
631 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
632 /* End of environment variable setup for hooks. */
634 TRACE("set environment variables");
636 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
637 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name
);
640 TRACE("ran pre-start hooks");
642 /* The signal fd has to be created before forking otherwise if the child
643 * process exits before we setup the signal fd, the event will be lost
644 * and the command will be stuck.
646 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
647 if (handler
->sigfd
< 0) {
648 ERROR("Failed to setup SIGCHLD fd handler.");
651 TRACE("set up signal fd");
653 /* Do this after setting up signals since it might unblock SIGWINCH. */
654 if (lxc_console_create(conf
)) {
655 ERROR("Failed to create console for container \"%s\".", name
);
656 goto out_restore_sigmask
;
658 TRACE("created console");
660 if (lxc_ttys_shift_ids(conf
) < 0) {
661 ERROR("Failed to shift tty into container.");
662 goto out_restore_sigmask
;
664 TRACE("shifted tty ids");
666 INFO("container \"%s\" is initialized", name
);
670 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
672 lxc_delete_tty(&conf
->tty_info
);
674 lxc_set_state(name
, handler
, ABORTING
);
675 out_close_maincmd_fd
:
676 close(conf
->maincmd_fd
);
677 conf
->maincmd_fd
= -1;
681 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
684 struct lxc_list
*cur
, *next
;
685 pid_t self
= getpid();
686 char *namespaces
[LXC_NS_MAX
+ 1];
687 size_t namespace_count
= 0;
689 /* The STOPPING state is there for future cleanup code which can take
692 lxc_set_state(name
, handler
, STOPPING
);
694 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
695 if (handler
->nsfd
[i
] != -1) {
696 rc
= asprintf(&namespaces
[namespace_count
], "%s:/proc/%d/fd/%d",
697 ns_info
[i
].proc_name
, self
, handler
->nsfd
[i
]);
699 SYSERROR("Failed to allocate memory.");
705 namespaces
[namespace_count
] = NULL
;
707 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1))
708 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
710 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1))
711 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
713 if (run_lxc_hooks(name
, "stop", handler
->conf
, handler
->lxcpath
, namespaces
))
714 ERROR("Failed to run lxc.hook.stop for container \"%s\".", name
);
716 while (namespace_count
--)
717 free(namespaces
[namespace_count
]);
718 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
719 if (handler
->nsfd
[i
] != -1) {
720 close(handler
->nsfd
[i
]);
721 handler
->nsfd
[i
] = -1;
725 if (handler
->netnsfd
>= 0) {
726 close(handler
->netnsfd
);
727 handler
->netnsfd
= -1;
730 cgroup_destroy(handler
);
732 lxc_set_state(name
, handler
, STOPPED
);
734 /* close command socket */
735 close(handler
->conf
->maincmd_fd
);
736 handler
->conf
->maincmd_fd
= -1;
738 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
)) {
739 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name
);
740 if (handler
->conf
->reboot
) {
741 WARN("Container will be stopped instead of rebooted.");
742 handler
->conf
->reboot
= 0;
743 if (setenv("LXC_TARGET", "stop", 1))
744 WARN("Failed to set environment variable: LXC_TARGET=stop.");
748 /* Reset mask set by setup_signal_fd. */
749 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
750 WARN("Failed to restore signal mask.");
752 lxc_console_delete(&handler
->conf
->console
);
753 lxc_delete_tty(&handler
->conf
->tty_info
);
755 /* The command socket is now closed, no more state clients can register
756 * themselves from now on. So free the list of state clients.
758 lxc_list_for_each_safe(cur
, &handler
->state_clients
, next
) {
759 struct state_client
*client
= cur
->elem
;
760 /* close state client socket */
761 close(client
->clientfd
);
767 if (handler
->data_sock
[0] != -1) {
768 close(handler
->data_sock
[0]);
769 close(handler
->data_sock
[1]);
772 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1)
773 lxc_destroy_container_on_signal(handler
, name
);
779 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
783 lxc_set_state(name
, handler
, ABORTING
);
784 if (handler
->pid
> 0)
785 kill(handler
->pid
, SIGKILL
);
786 while ((ret
= waitpid(-1, &status
, 0)) > 0) {
791 static int do_start(void *data
)
793 struct lxc_list
*iterator
;
794 struct lxc_handler
*handler
= data
;
795 int devnull_fd
= -1, ret
;
798 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
799 SYSERROR("Failed to set signal mask.");
803 /* This prctl must be before the synchro, so if the parent dies before
804 * we set the parent death signal, we will detect its death with the
805 * synchro right after, otherwise we have a window where the parent can
806 * exit before we set the pdeath signal leading to a unsupervized
809 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
810 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL.");
814 lxc_sync_fini_parent(handler
);
816 /* Don't leak the pinfd to the container. */
817 if (handler
->pinfd
>= 0) {
818 close(handler
->pinfd
);
821 if (lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
))
824 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
825 * https://github.com/lxc/lxd/issues/1978.
827 if ((handler
->clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
828 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
829 ret
= unshare(CLONE_NEWNET
);
831 SYSERROR("Failed to unshare CLONE_NEWNET.");
832 goto out_warn_father
;
834 INFO("Unshared CLONE_NEWNET.");
837 /* Tell the parent task it can begin to configure the container and wait
840 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
843 if (lxc_network_recv_veth_names_from_parent(handler
) < 0) {
844 ERROR("Failed to receive veth names from parent");
845 goto out_warn_father
;
848 /* If we are in a new user namespace, become root there to have
849 * privilege over our namespace.
851 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
852 if (lxc_switch_uid_gid(0, 0) < 0)
853 goto out_warn_father
;
855 /* Drop groups only after we switched to a valid gid in the new
858 if (lxc_setgroups(0, NULL
) < 0)
859 goto out_warn_father
;
862 if (access(handler
->lxcpath
, X_OK
)) {
863 print_top_failing_dir(handler
->lxcpath
);
864 goto out_warn_father
;
867 ret
= snprintf(path
, sizeof(path
), "%s/dev/null", handler
->conf
->rootfs
.mount
);
868 if (ret
< 0 || ret
>= sizeof(path
))
869 goto out_warn_father
;
871 /* In order to checkpoint restore, we need to have everything in the
872 * same mount namespace. However, some containers may not have a
873 * reasonable /dev (in particular, they may not have /dev/null), so we
874 * can't set init's std fds to /dev/null by opening it from inside the
877 * If that's the case, fall back to using the host's /dev/null. This
878 * means that migration won't work, but at least we won't spew output
879 * where it isn't wanted.
881 if (handler
->backgrounded
&& !handler
->conf
->autodev
&& access(path
, F_OK
) < 0) {
882 devnull_fd
= open_devnull();
885 goto out_warn_father
;
886 WARN("Using /dev/null from the host for container init's "
887 "standard file descriptors. Migration will not work.");
890 /* Ask father to setup cgroups and wait for him to finish. */
891 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
894 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
895 * earlier we end up with a wrong view of /proc/self/cgroup. For
896 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
897 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
898 * /proc/self/cgroup would show us:
902 * whereas it should actually show
906 if (cgns_supported()) {
907 if (unshare(CLONE_NEWCGROUP
) < 0) {
908 INFO("Failed to unshare CLONE_NEWCGROUP.");
909 goto out_warn_father
;
911 INFO("Unshared CLONE_NEWCGROUP.");
914 /* Setup the container, ip, names, utsname, ... */
915 if (lxc_setup(handler
)) {
916 ERROR("Failed to setup container \"%s\".", handler
->name
);
917 goto out_warn_father
;
920 /* Set the label to change to when we exec(2) the container's init. */
921 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
922 goto out_warn_father
;
924 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
925 * before we aren't allowed anymore.
927 if (handler
->conf
->no_new_privs
) {
928 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
929 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
930 goto out_warn_father
;
932 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
935 /* Some init's such as busybox will set sane tty settings on stdin,
936 * stdout, stderr which it thinks is the console. We already set them
937 * the way we wanted on the real terminal, and we want init to do its
938 * setup on its console ie. the pty allocated in lxc_console_create() so
939 * make sure that that pty is stdin,stdout,stderr.
941 if (handler
->conf
->console
.slave
>= 0)
942 if (set_stdfds(handler
->conf
->console
.slave
) < 0) {
943 ERROR("Failed to redirect std{in,out,err} to pty file "
945 handler
->conf
->console
.slave
);
946 goto out_warn_father
;
949 /* If we mounted a temporary proc, then unmount it now. */
950 tmp_proc_unmount(handler
->conf
);
952 if (lxc_seccomp_load(handler
->conf
) != 0)
953 goto out_warn_father
;
955 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
956 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler
->name
);
957 goto out_warn_father
;
960 /* The container has been setup. We can now switch to an unprivileged
963 if (handler
->conf
->is_execute
) {
964 bool have_cap_setgid
;
965 uid_t new_uid
= handler
->conf
->init_uid
;
966 gid_t new_gid
= handler
->conf
->init_gid
;
968 /* If we are in a new user namespace we already dropped all
969 * groups when we switched to root in the new user namespace
970 * further above. Only drop groups if we can, so ensure that we
971 * have necessary privilege.
974 have_cap_setgid
= lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
);
976 have_cap_setgid
= false;
978 if (lxc_list_empty(&handler
->conf
->id_map
) && have_cap_setgid
) {
979 if (lxc_setgroups(0, NULL
) < 0)
980 goto out_warn_father
;
983 if (lxc_switch_uid_gid(new_uid
, new_gid
) < 0)
984 goto out_warn_father
;
987 /* The clearenv() and putenv() calls have been moved here to allow us to
988 * use environment variables passed to the various hooks, such as the
989 * start hook above. Not all of the variables like CONFIG_PATH or ROOTFS
990 * are valid in this context but others are.
993 SYSERROR("Failed to clear environment.");
994 /* Don't error out though. */
997 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
998 if (putenv((char *)iterator
->elem
)) {
999 SYSERROR("Failed to set environment variable: %s.", (char *)iterator
->elem
);
1000 goto out_warn_father
;
1004 if (putenv("container=lxc")) {
1005 SYSERROR("Failed to set environment variable: container=lxc.");
1006 goto out_warn_father
;
1009 if (handler
->conf
->pty_names
) {
1010 if (putenv(handler
->conf
->pty_names
)) {
1011 SYSERROR("Failed to set environment variable for container ptys.");
1012 goto out_warn_father
;
1016 close(handler
->sigfd
);
1018 if (devnull_fd
< 0) {
1019 devnull_fd
= open_devnull();
1022 goto out_warn_father
;
1025 if (handler
->conf
->console
.slave
< 0 && handler
->backgrounded
)
1026 if (set_stdfds(devnull_fd
) < 0) {
1027 ERROR("Failed to redirect std{in,out,err} to "
1029 goto out_warn_father
;
1032 if (devnull_fd
>= 0) {
1039 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
))
1040 goto out_warn_father
;
1042 /* After this call, we are in error because this ops should not return
1045 handler
->ops
->start(handler
, handler
->data
);
1048 /* We want the parent to know something went wrong, so we return a
1049 * special error code.
1051 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1054 if (devnull_fd
>= 0)
1060 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1063 struct lxc_pty_info
*pty_info
;
1065 int sock
= handler
->data_sock
[1];
1066 struct lxc_conf
*conf
= handler
->conf
;
1067 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
1072 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
) * conf
->tty
);
1073 if (!tty_info
->pty_info
)
1076 for (i
= 0; i
< conf
->tty
; i
++) {
1079 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1083 pty_info
= &tty_info
->pty_info
[i
];
1085 pty_info
->master
= ttyfds
[0];
1086 pty_info
->slave
= ttyfds
[1];
1087 TRACE("Received pty with master fd %d and slave fd %d from "
1088 "parent", pty_info
->master
, pty_info
->slave
);
1091 ERROR("Failed to receive %d ttys from child: %s", conf
->tty
,
1094 TRACE("Received %d ttys from child", conf
->tty
);
1096 tty_info
->nbtty
= conf
->tty
;
1101 void resolve_clone_flags(struct lxc_handler
*handler
)
1103 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
1105 if (!lxc_list_empty(&handler
->conf
->id_map
))
1106 handler
->clone_flags
|= CLONE_NEWUSER
;
1108 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
1109 if (!lxc_requests_empty_network(handler
))
1110 handler
->clone_flags
|= CLONE_NEWNET
;
1112 INFO("Inheriting a NET namespace.");
1115 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1)
1116 handler
->clone_flags
|= CLONE_NEWIPC
;
1118 INFO("Inheriting an IPC namespace.");
1120 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1)
1121 handler
->clone_flags
|= CLONE_NEWUTS
;
1123 INFO("Inheriting a UTS namespace.");
1126 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1127 * exec()s the requested container binary.
1128 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1129 * right here should be double checked if they'd pose a security risk. (For
1130 * example, any {u}mount() operations performed here will be reflected on the
1133 static int lxc_spawn(struct lxc_handler
*handler
)
1136 const char *name
= handler
->name
;
1137 bool wants_to_map_ids
;
1138 int saved_ns_fd
[LXC_NS_MAX
];
1139 struct lxc_list
*id_map
;
1140 int failed_before_rename
= 0, preserve_mask
= 0;
1141 bool cgroups_connected
= false;
1143 id_map
= &handler
->conf
->id_map
;
1144 wants_to_map_ids
= !lxc_list_empty(id_map
);
1146 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1147 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
1148 preserve_mask
|= ns_info
[i
].clone_flag
;
1150 if (lxc_sync_init(handler
))
1153 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1154 handler
->data_sock
);
1156 lxc_sync_fini(handler
);
1160 resolve_clone_flags(handler
);
1162 if (handler
->clone_flags
& CLONE_NEWNET
) {
1163 if (!lxc_list_empty(&handler
->conf
->network
)) {
1165 /* Find gateway addresses from the link device, which is
1166 * no longer accessible inside the container. Do this
1167 * before creating network interfaces, since goto
1168 * out_delete_net does not work before lxc_clone.
1170 if (lxc_find_gateway_addresses(handler
)) {
1171 ERROR("Failed to find gateway addresses.");
1172 lxc_sync_fini(handler
);
1176 /* That should be done before the clone because we will
1177 * fill the netdev index and use them in the child.
1179 if (lxc_create_network_priv(handler
)) {
1180 ERROR("Failed to create the network.");
1181 lxc_sync_fini(handler
);
1187 if (!cgroup_init(handler
)) {
1188 ERROR("Failed initializing cgroup support.");
1189 goto out_delete_net
;
1192 cgroups_connected
= true;
1194 if (!cgroup_create(handler
)) {
1195 ERROR("Failed creating cgroups.");
1196 goto out_delete_net
;
1199 /* If the rootfs is not a blockdev, prevent the container from marking
1201 * If the container is unprivileged then skip rootfs pinning.
1203 if (!wants_to_map_ids
) {
1204 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
1205 if (handler
->pinfd
== -1)
1206 INFO("Failed to pin the rootfs for container \"%s\".", handler
->name
);
1209 if (!preserve_ns(saved_ns_fd
, preserve_mask
, getpid()))
1210 goto out_delete_net
;
1212 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
1213 goto out_delete_net
;
1215 /* Create a process in a new set of namespaces. */
1216 flags
= handler
->clone_flags
;
1217 if (handler
->clone_flags
& CLONE_NEWUSER
) {
1218 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1219 * clone a new user namespace first and only later unshare our
1220 * network namespace to ensure that network devices ownership is
1223 flags
&= ~CLONE_NEWNET
;
1225 handler
->pid
= lxc_clone(do_start
, handler
, flags
);
1226 if (handler
->pid
< 0) {
1227 SYSERROR("Failed to clone a new set of namespaces.");
1228 goto out_delete_net
;
1231 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1232 if (flags
& ns_info
[i
].clone_flag
)
1233 INFO("Cloned %s.", ns_info
[i
].flag_name
);
1235 if (!preserve_ns(handler
->nsfd
, handler
->clone_flags
| preserve_mask
, handler
->pid
))
1236 INFO("Failed to preserve namespace for lxc.hook.stop.");
1238 if (attach_ns(saved_ns_fd
))
1239 WARN("Failed to restore saved namespaces.");
1241 lxc_sync_fini_child(handler
);
1243 /* Map the container uids. The container became an invalid userid the
1244 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1245 * anything immediately, but allows the container to setuid(0) (0 being
1246 * mapped to something else on the host.) later to become a valid uid
1249 if (wants_to_map_ids
&& lxc_map_ids(id_map
, handler
->pid
)) {
1250 ERROR("Failed to set up id mapping.");
1251 goto out_delete_net
;
1254 if (lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
)) {
1255 failed_before_rename
= 1;
1256 goto out_delete_net
;
1259 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
)) {
1260 failed_before_rename
= 1;
1261 goto out_delete_net
;
1264 if (!cgroup_create_legacy(handler
)) {
1265 ERROR("Failed to setup legacy cgroups for container \"%s\".", name
);
1266 goto out_delete_net
;
1268 if (!cgroup_setup_limits(handler
, false)) {
1269 ERROR("Failed to setup cgroup limits for container \"%s\".", name
);
1270 goto out_delete_net
;
1273 if (!cgroup_enter(handler
))
1274 goto out_delete_net
;
1276 if (!cgroup_chown(handler
))
1277 goto out_delete_net
;
1279 if (failed_before_rename
)
1280 goto out_delete_net
;
1282 handler
->netnsfd
= lxc_preserve_ns(handler
->pid
, "net");
1283 if (handler
->netnsfd
< 0) {
1284 ERROR("Failed to preserve network namespace");
1285 goto out_delete_net
;
1288 /* Create the network configuration. */
1289 if (handler
->clone_flags
& CLONE_NEWNET
) {
1290 if (lxc_network_move_created_netdev_priv(handler
->lxcpath
,
1292 &handler
->conf
->network
,
1294 ERROR("Failed to create the configured network.");
1295 goto out_delete_net
;
1298 if (lxc_create_network_unpriv(handler
->lxcpath
, handler
->name
,
1299 &handler
->conf
->network
,
1301 ERROR("Failed to create the configured network.");
1302 goto out_delete_net
;
1306 if (lxc_network_send_veth_names_to_child(handler
) < 0) {
1307 ERROR("Failed to send veth names to child");
1308 goto out_delete_net
;
1311 /* Tell the child to continue its initialization. We'll get
1312 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1314 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1315 goto out_delete_net
;
1317 if (!lxc_list_empty(&handler
->conf
->limits
) && setup_resource_limits(&handler
->conf
->limits
, handler
->pid
)) {
1318 ERROR("failed to setup resource limits for '%s'", name
);
1319 goto out_delete_net
;
1322 if (lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
))
1323 goto out_delete_net
;
1325 if (!cgroup_setup_limits(handler
, true)) {
1326 ERROR("Failed to setup the devices cgroup for container \"%s\".", name
);
1327 goto out_delete_net
;
1329 TRACE("Set up cgroup device limits");
1331 cgroup_disconnect();
1332 cgroups_connected
= false;
1334 /* Tell the child to complete its initialization and wait for it to exec
1335 * or return an error. (The child will never return
1336 * LXC_SYNC_POST_CGROUP+1. It will either close the sync pipe, causing
1337 * lxc_sync_barrier_child to return success, or return a different
1338 * value, causing us to error out).
1340 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1343 if (lxc_network_recv_name_and_ifindex_from_child(handler
) < 0) {
1344 ERROR("Failed to receive names and ifindices for network "
1345 "devices from child");
1346 goto out_delete_net
;
1349 /* Now all networks are created, network devices are moved into place,
1350 * and the correct names and ifindeces in the respective namespaces have
1351 * been recorded. The corresponding structs have now all been filled. So
1352 * log them for debugging purposes.
1354 lxc_log_configured_netdevs(handler
->conf
);
1356 /* Read tty fds allocated by child. */
1357 if (lxc_recv_ttys_from_child(handler
) < 0) {
1358 ERROR("Failed to receive tty info from child process.");
1359 goto out_delete_net
;
1362 if (handler
->ops
->post_start(handler
, handler
->data
))
1365 if (lxc_set_state(name
, handler
, RUNNING
)) {
1366 ERROR("Failed to set state for container \"%s\" to \"%s\".", name
,
1367 lxc_state2str(RUNNING
));
1371 lxc_sync_fini(handler
);
1376 if (cgroups_connected
)
1377 cgroup_disconnect();
1379 if (handler
->clone_flags
& CLONE_NEWNET
) {
1380 DEBUG("Tearing down network devices");
1381 if (!lxc_delete_network_priv(handler
))
1382 DEBUG("Failed tearing down network devices");
1384 if (!lxc_delete_network_unpriv(handler
))
1385 DEBUG("Failed tearing down network devices");
1389 lxc_abort(name
, handler
);
1390 lxc_sync_fini(handler
);
1391 if (handler
->pinfd
>= 0) {
1392 close(handler
->pinfd
);
1393 handler
->pinfd
= -1;
1396 if (handler
->netnsfd
>= 0) {
1397 close(handler
->netnsfd
);
1398 handler
->netnsfd
= -1;
1404 int __lxc_start(const char *name
, struct lxc_handler
*handler
,
1405 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1410 struct lxc_conf
*conf
= handler
->conf
;
1412 if (lxc_init(name
, handler
) < 0) {
1413 ERROR("Failed to initialize container \"%s\".", name
);
1417 handler
->data
= data
;
1418 handler
->backgrounded
= backgrounded
;
1419 handler
->netnsfd
= -1;
1421 if (!attach_block_device(handler
->conf
)) {
1422 ERROR("Failed to attach block device.");
1423 goto out_fini_nonet
;
1426 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1427 /* If the backing store is a device, mount it here and now. */
1428 if (rootfs_is_blockdev(conf
)) {
1429 if (unshare(CLONE_NEWNS
) < 0) {
1430 ERROR("Failed to unshare CLONE_NEWNS.");
1431 goto out_fini_nonet
;
1433 INFO("Unshared CLONE_NEWNS.");
1435 remount_all_slave();
1436 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1437 ERROR("Error setting up rootfs mount as root before spawn.");
1438 goto out_fini_nonet
;
1440 INFO("Set up container rootfs as host root.");
1444 err
= lxc_spawn(handler
);
1446 ERROR("Failed to spawn container \"%s\".", name
);
1447 goto out_detach_blockdev
;
1450 handler
->conf
->reboot
= 0;
1452 err
= lxc_poll(name
, handler
);
1454 ERROR("LXC mainloop exited with error: %d.", err
);
1458 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1461 /* If the child process exited but was not signaled, it didn't call
1462 * reboot. This should mean it was an lxc-execute which simply exited.
1463 * In any case, treat it as a 'halt'.
1465 if (WIFSIGNALED(status
)) {
1466 switch(WTERMSIG(status
)) {
1467 case SIGINT
: /* halt */
1468 DEBUG("Container \"%s\" is halting.", name
);
1470 case SIGHUP
: /* reboot */
1471 DEBUG("Container \"%s\" is rebooting.", name
);
1472 handler
->conf
->reboot
= 1;
1474 case SIGSYS
: /* seccomp */
1475 DEBUG("Container \"%s\" violated its seccomp policy.", name
);
1478 DEBUG("Unknown exit status for container \"%s\" init %d.", name
, WTERMSIG(status
));
1483 err
= lxc_restore_phys_nics_to_netns(handler
);
1485 ERROR("Failed to move physical network devices back to parent "
1486 "network namespace");
1488 if (handler
->pinfd
>= 0) {
1489 close(handler
->pinfd
);
1490 handler
->pinfd
= -1;
1493 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1494 err
= lxc_error_set_and_log(handler
->pid
, status
);
1497 DEBUG("Tearing down network devices");
1498 if (!lxc_delete_network_priv(handler
))
1499 DEBUG("Failed tearing down network devices");
1501 if (!lxc_delete_network_unpriv(handler
))
1502 DEBUG("Failed tearing down network devices");
1504 if (handler
->netnsfd
>= 0) {
1505 close(handler
->netnsfd
);
1506 handler
->netnsfd
= -1;
1509 out_detach_blockdev
:
1510 detach_block_device(handler
->conf
);
1513 lxc_fini(name
, handler
);
1517 lxc_abort(name
, handler
);
1525 static int start(struct lxc_handler
*handler
, void* data
)
1527 struct start_args
*arg
= data
;
1529 NOTICE("Exec'ing \"%s\".", arg
->argv
[0]);
1531 execvp(arg
->argv
[0], arg
->argv
);
1532 SYSERROR("Failed to exec \"%s\".", arg
->argv
[0]);
1536 static int post_start(struct lxc_handler
*handler
, void* data
)
1538 struct start_args
*arg
= data
;
1540 NOTICE("Started \"%s\" with pid \"%d\".", arg
->argv
[0], handler
->pid
);
1544 static struct lxc_operations start_ops
= {
1546 .post_start
= post_start
1549 int lxc_start(const char *name
, char *const argv
[], struct lxc_handler
*handler
,
1550 const char *lxcpath
, bool backgrounded
)
1552 struct start_args start_arg
= {
1556 return __lxc_start(name
, handler
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1559 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1562 char destroy
[MAXPATHLEN
];
1565 struct lxc_container
*c
;
1566 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1567 bret
= do_destroy_container(handler
);
1569 ERROR("Error destroying rootfs for container \"%s\".", name
);
1573 INFO("Destroyed rootfs for container \"%s\".", name
);
1575 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1576 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1577 ERROR("Error destroying directory for container \"%s\".", name
);
1581 c
= lxc_container_new(name
, handler
->lxcpath
);
1583 if (container_disk_lock(c
)) {
1584 INFO("Could not update lxc_snapshots file.");
1585 lxc_container_put(c
);
1587 mod_all_rdeps(c
, false);
1588 container_disk_unlock(c
);
1589 lxc_container_put(c
);
1593 if (!handler
->am_root
)
1594 ret
= userns_exec_1(handler
->conf
, lxc_rmdir_onedev_wrapper
,
1595 destroy
, "lxc_rmdir_onedev_wrapper");
1597 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1600 ERROR("Error destroying directory for container \"%s\".", name
);
1603 INFO("Destroyed directory for container \"%s\".", name
);
1606 static int lxc_rmdir_onedev_wrapper(void *data
)
1608 char *arg
= (char *) data
;
1609 return lxc_rmdir_onedev(arg
, NULL
);
1612 static bool do_destroy_container(struct lxc_handler
*handler
) {
1613 if (!handler
->am_root
) {
1614 if (userns_exec_1(handler
->conf
, storage_destroy_wrapper
,
1615 handler
->conf
, "storage_destroy_wrapper") < 0)
1621 return storage_destroy(handler
->conf
);