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
40 #include <sys/mount.h>
41 #include <sys/param.h>
42 #include <sys/prctl.h>
43 #include <sys/socket.h>
45 #include <sys/syscall.h>
46 #include <sys/types.h>
55 #include "commands_utils.h"
58 #include "confile_utils.h"
60 #include "file_utils.h"
64 #include "lxccontainer.h"
66 #include "lxcseccomp.h"
69 #include "memory_utils.h"
71 #include "namespace.h"
73 #include "raw_syscalls.h"
75 #include "storage/storage.h"
76 #include "storage/storage_utils.h"
78 #include "syscall_wrappers.h"
83 #include <sys/capability.h>
87 #include "include/strlcpy.h"
90 lxc_log_define(start
, lxc
);
92 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
93 static bool do_destroy_container(struct lxc_handler
*handler
);
94 static int lxc_rmdir_onedev_wrapper(void *data
);
95 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
98 static void print_top_failing_dir(const char *path
)
100 __do_free
char *copy
= NULL
;
104 copy
= must_copy_string(path
);
106 e
= copy
+ strlen(path
);
109 while (p
< e
&& *p
== '/')
112 while (p
< e
&& *p
!= '/')
118 ret
= access(copy
, X_OK
);
120 SYSERROR("Could not access %s. Please grant it x "
121 "access, or add an ACL for the container "
129 static void lxc_put_nsfds(struct lxc_handler
*handler
)
133 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
134 if (handler
->nsfd
[i
] < 0)
137 close(handler
->nsfd
[i
]);
138 handler
->nsfd
[i
] = -EBADF
;
142 static int lxc_try_preserve_ns(const int pid
, const char *ns
)
146 fd
= lxc_preserve_ns(pid
, ns
);
148 if (errno
!= ENOENT
) {
149 SYSERROR("Failed to preserve %s namespace", ns
);
153 SYSWARN("Kernel does not support preserving %s namespaces", ns
);
160 /* lxc_try_preserve_namespaces: open /proc/@pid/ns/@ns for each namespace
161 * specified in ns_clone_flags.
162 * Return true on success, false on failure.
164 static bool lxc_try_preserve_namespaces(struct lxc_handler
*handler
,
165 int ns_clone_flags
, pid_t pid
)
169 for (i
= 0; i
< LXC_NS_MAX
; i
++)
170 handler
->nsfd
[i
] = -EBADF
;
172 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
175 if ((ns_clone_flags
& ns_info
[i
].clone_flag
) == 0)
178 fd
= lxc_try_preserve_ns(pid
, ns_info
[i
].proc_name
);
180 /* Do not fail to start container on kernels that do
181 * not support interacting with namespaces through
184 if (fd
== -EOPNOTSUPP
)
187 lxc_put_nsfds(handler
);
191 handler
->nsfd
[i
] = fd
;
192 DEBUG("Preserved %s namespace via fd %d", ns_info
[i
].proc_name
,
199 static inline bool match_stdfds(int fd
)
201 return (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
);
205 static bool match_dlog_fds(struct dirent
*direntp
)
207 char path
[PATH_MAX
] = {0};
208 char link
[PATH_MAX
] = {0};
212 ret
= snprintf(path
, PATH_MAX
, "/proc/self/fd/%s", direntp
->d_name
);
213 if (ret
< 0 || ret
>= PATH_MAX
) {
214 ERROR("Failed to create file descriptor name");
218 linklen
= readlink(path
, link
, PATH_MAX
);
220 SYSERROR("Failed to read link path - \"%s\"", path
);
222 } else if (linklen
>= PATH_MAX
) {
223 ERROR("The name of link path is too long - \"%s\"", path
);
227 if (strcmp(link
, "/dev/log_main") == 0 ||
228 strcmp(link
, "/dev/log_system") == 0 ||
229 strcmp(link
, "/dev/log_radio") == 0)
236 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
237 int *fds_to_ignore
, size_t len_fds
)
242 struct dirent
*direntp
;
244 if (conf
&& conf
->close_all_fds
)
248 dir
= opendir("/proc/self/fd");
250 SYSWARN("Failed to open directory");
256 while ((direntp
= readdir(dir
))) {
258 struct lxc_list
*cur
;
259 bool matched
= false;
261 if (strcmp(direntp
->d_name
, ".") == 0)
264 if (strcmp(direntp
->d_name
, "..") == 0)
267 ret
= lxc_safe_int(direntp
->d_name
, &fd
);
269 INFO("Could not parse file descriptor for \"%s\"", direntp
->d_name
);
273 for (i
= 0; i
< len_fds
; i
++)
274 if (fds_to_ignore
[i
] == fd
)
277 if (fd
== fddir
|| fd
== lxc_log_fd
||
278 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
281 /* Keep state clients that wait on reboots. */
283 lxc_list_for_each(cur
, &conf
->state_clients
) {
284 struct lxc_state_client
*client
= cur
->elem
;
286 if (client
->clientfd
!= fd
)
297 if (current_config
&& fd
== current_config
->logfd
)
300 if (match_stdfds(fd
))
304 if (match_dlog_fds(direntp
))
311 INFO("Closed inherited fd %d", fd
);
314 WARN("Inherited fd %d", fd
);
317 /* Only enable syslog at this point to avoid the above logging function
318 * to open a new fd and make the check_inherited function enter an
321 lxc_log_enable_syslog();
323 closedir(dir
); /* cannot fail */
327 static int setup_signal_fd(sigset_t
*oldmask
)
331 const int signals
[] = {SIGBUS
, SIGILL
, SIGSEGV
, SIGWINCH
};
333 /* Block everything except serious error signals. */
334 ret
= sigfillset(&mask
);
338 for (int sig
= 0; sig
< (sizeof(signals
) / sizeof(signals
[0])); sig
++) {
339 ret
= sigdelset(&mask
, signals
[sig
]);
344 ret
= pthread_sigmask(SIG_BLOCK
, &mask
, oldmask
);
346 SYSERROR("Failed to set signal mask");
350 ret
= signalfd(-1, &mask
, SFD_CLOEXEC
);
352 SYSERROR("Failed to create signal file descriptor");
356 TRACE("Created signal file descriptor %d", ret
);
361 static int signal_handler(int fd
, uint32_t events
, void *data
,
362 struct lxc_epoll_descr
*descr
)
366 struct signalfd_siginfo siginfo
;
367 struct lxc_handler
*hdlr
= data
;
369 ret
= lxc_read_nointr(fd
, &siginfo
, sizeof(siginfo
));
371 ERROR("Failed to read signal info from signal file descriptor %d", fd
);
372 return LXC_MAINLOOP_ERROR
;
375 if (ret
!= sizeof(siginfo
)) {
376 ERROR("Unexpected size for struct signalfd_siginfo");
380 /* Check whether init is running. */
382 ret
= waitid(P_PID
, hdlr
->pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
383 if (ret
== 0 && info
.si_pid
== hdlr
->pid
)
384 hdlr
->init_died
= true;
386 /* Try to figure out a reasonable exit status to report. */
387 if (hdlr
->init_died
) {
388 switch (info
.si_code
) {
390 hdlr
->exit_status
= info
.si_status
<< 8;
395 hdlr
->exit_status
= info
.si_status
<< 8 | 0x7f;
398 /* Huh? The waitid() told us it's dead *and* continued? */
399 WARN("Init %d dead and continued?", hdlr
->pid
);
400 hdlr
->exit_status
= 1;
403 ERROR("Unknown si_code: %d", info
.si_code
);
404 hdlr
->exit_status
= 1;
408 if (siginfo
.ssi_signo
== SIGHUP
) {
409 if (hdlr
->pidfd
>= 0)
410 lxc_raw_pidfd_send_signal(hdlr
->pidfd
, SIGTERM
, NULL
, 0);
411 else if (hdlr
->proc_pidfd
>= 0)
412 lxc_raw_pidfd_send_signal(hdlr
->proc_pidfd
, SIGTERM
, NULL
, 0);
414 kill(hdlr
->pid
, SIGTERM
);
415 INFO("Killing %d since terminal hung up", hdlr
->pid
);
416 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
417 : LXC_MAINLOOP_CONTINUE
;
420 if (siginfo
.ssi_signo
!= SIGCHLD
) {
421 if (hdlr
->pidfd
>= 0)
422 lxc_raw_pidfd_send_signal(hdlr
->pidfd
,
423 siginfo
.ssi_signo
, NULL
, 0);
424 else if (hdlr
->proc_pidfd
>= 0)
425 lxc_raw_pidfd_send_signal(hdlr
->proc_pidfd
,
426 siginfo
.ssi_signo
, NULL
, 0);
428 kill(hdlr
->pid
, siginfo
.ssi_signo
);
429 INFO("Forwarded signal %d to pid %d", siginfo
.ssi_signo
, hdlr
->pid
);
430 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
431 : LXC_MAINLOOP_CONTINUE
;
434 /* More robustness, protect ourself from a SIGCHLD sent
435 * by a process different from the container init.
437 if (siginfo
.ssi_pid
!= hdlr
->pid
) {
438 NOTICE("Received %d from pid %d instead of container init %d",
439 siginfo
.ssi_signo
, siginfo
.ssi_pid
, hdlr
->pid
);
440 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
441 : LXC_MAINLOOP_CONTINUE
;
444 if (siginfo
.ssi_code
== CLD_STOPPED
) {
445 INFO("Container init process was stopped");
446 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
447 : LXC_MAINLOOP_CONTINUE
;
450 if (siginfo
.ssi_code
== CLD_CONTINUED
) {
451 INFO("Container init process was continued");
452 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
453 : LXC_MAINLOOP_CONTINUE
;
456 DEBUG("Container init process %d exited", hdlr
->pid
);
458 return LXC_MAINLOOP_CLOSE
;
461 int lxc_serve_state_clients(const char *name
, struct lxc_handler
*handler
,
466 struct lxc_list
*cur
, *next
;
467 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
470 handler
->state
= RUNNING
;
472 handler
->state
= state
;
474 TRACE("Set container state to %s", lxc_state2str(state
));
476 if (lxc_list_empty(&handler
->conf
->state_clients
)) {
477 TRACE("No state clients registered");
481 retlen
= strlcpy(msg
.name
, name
, sizeof(msg
.name
));
482 if (retlen
>= sizeof(msg
.name
))
485 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
486 struct lxc_state_client
*client
= cur
->elem
;
488 if (client
->states
[state
] == 0) {
489 TRACE("State %s not registered for state client %d",
490 lxc_state2str(state
), client
->clientfd
);
494 TRACE("Sending state %s to state client %d",
495 lxc_state2str(state
), client
->clientfd
);
497 ret
= lxc_send_nointr(client
->clientfd
, &msg
, sizeof(msg
), MSG_NOSIGNAL
);
499 SYSERROR("Failed to send message to client");
501 /* kick client from list */
503 close(client
->clientfd
);
511 static int lxc_serve_state_socket_pair(const char *name
,
512 struct lxc_handler
*handler
,
517 if (!handler
->daemonize
||
518 handler
->state_socket_pair
[1] < 0 ||
522 /* Close read end of the socket pair. */
523 close(handler
->state_socket_pair
[0]);
524 handler
->state_socket_pair
[0] = -1;
527 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
528 &(int){state
}, sizeof(int));
530 SYSERROR("Failed to send state to %d", handler
->state_socket_pair
[1]);
538 if (ret
!= sizeof(int)) {
539 ERROR("Message too long : %d", handler
->state_socket_pair
[1]);
543 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
544 handler
->state_socket_pair
[1]);
546 /* Close write end of the socket pair. */
547 close(handler
->state_socket_pair
[1]);
548 handler
->state_socket_pair
[1] = -1;
553 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
558 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
560 ERROR("Failed to synchronize via anonymous pair of unix sockets");
564 ret
= lxc_serve_state_clients(name
, handler
, state
);
568 /* This function will try to connect to the legacy lxc-monitord state
569 * server and only exists for backwards compatibility.
571 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
576 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
579 bool has_console
= true;
580 struct lxc_epoll_descr descr
, descr_console
;
582 if (handler
->conf
->console
.path
&&
583 strcmp(handler
->conf
->console
.path
, "none") == 0)
586 ret
= lxc_mainloop_open(&descr
);
588 ERROR("Failed to create mainloop");
593 ret
= lxc_mainloop_open(&descr_console
);
595 ERROR("Failed to create console mainloop");
600 ret
= lxc_mainloop_add_handler(&descr
, handler
->sigfd
, signal_handler
, handler
);
602 ERROR("Failed to add signal handler for %d to mainloop", handler
->sigfd
);
603 goto out_mainloop_console
;
606 ret
= lxc_seccomp_setup_proxy(&handler
->conf
->seccomp
, &descr
, handler
);
608 ERROR("Failed to setup seccomp proxy");
609 goto out_mainloop_console
;
613 struct lxc_terminal
*console
= &handler
->conf
->console
;
615 ret
= lxc_terminal_mainloop_add(&descr
, console
);
617 ERROR("Failed to add console handlers to mainloop");
618 goto out_mainloop_console
;
621 ret
= lxc_terminal_mainloop_add(&descr_console
, console
);
623 ERROR("Failed to add console handlers to console mainloop");
624 goto out_mainloop_console
;
627 handler
->conf
->console
.descr
= &descr
;
630 ret
= lxc_cmd_mainloop_add(name
, &descr
, handler
);
632 ERROR("Failed to add command handler to mainloop");
633 goto out_mainloop_console
;
636 TRACE("Mainloop is ready");
638 ret
= lxc_mainloop(&descr
, -1);
641 if (ret
< 0 || !handler
->init_died
)
642 goto out_mainloop_console
;
645 ret
= lxc_mainloop(&descr_console
, 0);
647 out_mainloop_console
:
649 lxc_mainloop_close(&descr_console
);
650 TRACE("Closed console mainloop");
654 lxc_mainloop_close(&descr
);
655 TRACE("Closed mainloop");
658 close(handler
->sigfd
);
659 TRACE("Closed signal file descriptor %d", handler
->sigfd
);
660 handler
->sigfd
= -EBADF
;
665 void lxc_zero_handler(struct lxc_handler
*handler
)
669 memset(handler
, 0, sizeof(struct lxc_handler
));
673 handler
->pidfd
= -EBADF
;
675 handler
->proc_pidfd
= -EBADF
;
679 for (i
= 0; i
< LXC_NS_MAX
; i
++)
680 handler
->nsfd
[i
] = -1;
682 handler
->data_sock
[0] = -1;
683 handler
->data_sock
[1] = -1;
685 handler
->state_socket_pair
[0] = -1;
686 handler
->state_socket_pair
[1] = -1;
688 handler
->sync_sock
[0] = -1;
689 handler
->sync_sock
[1] = -1;
692 void lxc_free_handler(struct lxc_handler
*handler
)
694 if (handler
->pinfd
>= 0)
695 close(handler
->pinfd
);
697 if (handler
->pidfd
>= 0)
698 close(handler
->pidfd
);
700 if (handler
->proc_pidfd
>= 0)
701 close(handler
->proc_pidfd
);
703 if (handler
->sigfd
>= 0)
704 close(handler
->sigfd
);
706 lxc_put_nsfds(handler
);
708 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
709 if (handler
->conf
->maincmd_fd
>= 0)
710 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
712 if (handler
->state_socket_pair
[0] >= 0)
713 close(handler
->state_socket_pair
[0]);
715 if (handler
->state_socket_pair
[1] >= 0)
716 close(handler
->state_socket_pair
[1]);
718 if (handler
->cgroup_ops
)
719 cgroup_exit(handler
->cgroup_ops
);
721 handler
->conf
= NULL
;
726 struct lxc_handler
*lxc_init_handler(const char *name
, struct lxc_conf
*conf
,
727 const char *lxcpath
, bool daemonize
)
730 struct lxc_handler
*handler
;
732 handler
= malloc(sizeof(*handler
));
736 memset(handler
, 0, sizeof(*handler
));
738 /* Note that am_guest_unpriv() checks the effective uid. We
739 * probably don't care if we are real root only if we are running
740 * as root so this should be fine.
742 handler
->am_root
= !am_guest_unpriv();
743 handler
->data_sock
[0] = handler
->data_sock
[1] = -1;
744 handler
->conf
= conf
;
745 handler
->lxcpath
= lxcpath
;
747 handler
->pidfd
= -EBADF
;
748 handler
->proc_pidfd
= -EBADF
;
749 handler
->sigfd
= -EBADF
;
750 handler
->init_died
= false;
751 handler
->state_socket_pair
[0] = handler
->state_socket_pair
[1] = -1;
752 if (handler
->conf
->reboot
== REBOOT_NONE
)
753 lxc_list_init(&handler
->conf
->state_clients
);
755 for (i
= 0; i
< LXC_NS_MAX
; i
++)
756 handler
->nsfd
[i
] = -1;
758 handler
->name
= name
;
760 if (daemonize
&& handler
->conf
->reboot
== REBOOT_NONE
) {
761 /* Create socketpair() to synchronize on daemonized startup.
762 * When the container reboots we don't need to synchronize
763 * again currently so don't open another socketpair().
765 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
766 handler
->state_socket_pair
);
768 ERROR("Failed to create anonymous pair of unix sockets");
772 TRACE("Created anonymous pair {%d,%d} of unix sockets",
773 handler
->state_socket_pair
[0],
774 handler
->state_socket_pair
[1]);
777 if (handler
->conf
->reboot
== REBOOT_NONE
) {
778 handler
->conf
->maincmd_fd
= lxc_cmd_init(name
, lxcpath
, "command");
779 if (handler
->conf
->maincmd_fd
< 0) {
780 ERROR("Failed to set up command socket");
785 TRACE("Unix domain socket %d for command server is ready",
786 handler
->conf
->maincmd_fd
);
791 lxc_free_handler(handler
);
796 int lxc_init(const char *name
, struct lxc_handler
*handler
)
799 const char *loglevel
;
800 struct lxc_conf
*conf
= handler
->conf
;
802 handler
->monitor_pid
= lxc_raw_getpid();
805 TRACE("Initialized LSM");
807 ret
= lxc_read_seccomp_config(conf
);
809 ERROR("Failed loading seccomp policy");
810 goto out_close_maincmd_fd
;
812 TRACE("Read seccomp policy");
814 /* Begin by setting the state to STARTING. */
815 ret
= lxc_set_state(name
, handler
, STARTING
);
817 ERROR("Failed to set state to \"%s\"", lxc_state2str(STARTING
));
818 goto out_close_maincmd_fd
;
820 TRACE("Set container state to \"STARTING\"");
822 /* Start of environment variable setup for hooks. */
823 ret
= setenv("LXC_NAME", name
, 1);
825 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name
);
828 ret
= setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1);
830 SYSERROR("Failed to set environment variable: "
831 "LXC_CONFIG_FILE=%s", conf
->rcfile
);
834 if (conf
->rootfs
.mount
) {
835 ret
= setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1);
837 SYSERROR("Failed to set environment variable: "
838 "LXC_ROOTFS_MOUNT=%s", conf
->rootfs
.mount
);
841 if (conf
->rootfs
.path
) {
842 ret
= setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1);
844 SYSERROR("Failed to set environment variable: "
845 "LXC_ROOTFS_PATH=%s", conf
->rootfs
.path
);
848 if (conf
->console
.path
) {
849 ret
= setenv("LXC_CONSOLE", conf
->console
.path
, 1);
851 SYSERROR("Failed to set environment variable: "
852 "LXC_CONSOLE=%s", conf
->console
.path
);
855 if (conf
->console
.log_path
) {
856 ret
= setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1);
858 SYSERROR("Failed to set environment variable: "
859 "LXC_CONSOLE_LOGPATH=%s", conf
->console
.log_path
);
862 if (cgns_supported()) {
863 ret
= setenv("LXC_CGNS_AWARE", "1", 1);
865 SYSERROR("Failed to set environment variable "
869 loglevel
= lxc_log_priority_to_string(lxc_log_get_level());
870 ret
= setenv("LXC_LOG_LEVEL", loglevel
, 1);
872 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s",
875 if (conf
->hooks_version
== 0)
876 ret
= setenv("LXC_HOOK_VERSION", "0", 1);
878 ret
= setenv("LXC_HOOK_VERSION", "1", 1);
880 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf
->hooks_version
);
881 /* End of environment variable setup for hooks. */
883 TRACE("Set environment variables");
885 ret
= run_lxc_hooks(name
, "pre-start", conf
, NULL
);
887 ERROR("Failed to run lxc.hook.pre-start for container \"%s\"", name
);
890 TRACE("Ran pre-start hooks");
892 /* The signal fd has to be created before forking otherwise if the child
893 * process exits before we setup the signal fd, the event will be lost
894 * and the command will be stuck.
896 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
897 if (handler
->sigfd
< 0) {
898 ERROR("Failed to setup SIGCHLD fd handler.");
901 TRACE("Set up signal fd");
903 /* Do this after setting up signals since it might unblock SIGWINCH. */
904 ret
= lxc_terminal_setup(conf
);
906 ERROR("Failed to create console");
907 goto out_restore_sigmask
;
909 TRACE("Created console");
911 ret
= lxc_terminal_map_ids(conf
, &conf
->console
);
913 ERROR("Failed to chown console");
914 goto out_delete_terminal
;
916 TRACE("Chowned console");
918 handler
->cgroup_ops
= cgroup_init(handler
->conf
);
919 if (!handler
->cgroup_ops
) {
920 ERROR("Failed to initialize cgroup driver");
921 goto out_delete_terminal
;
923 TRACE("Initialized cgroup driver");
925 ret
= lsm_process_prepare(conf
, handler
->lxcpath
);
927 ERROR("Failed to initialize LSM");
928 goto out_destroy_cgroups
;
930 TRACE("Initialized LSM");
932 INFO("Container \"%s\" is initialized", name
);
936 handler
->cgroup_ops
->payload_destroy(handler
->cgroup_ops
, handler
);
937 handler
->cgroup_ops
->monitor_destroy(handler
->cgroup_ops
, handler
);
940 lxc_terminal_delete(&handler
->conf
->console
);
943 (void)pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
946 lxc_delete_tty(&conf
->ttys
);
949 (void)lxc_set_state(name
, handler
, ABORTING
);
951 out_close_maincmd_fd
:
952 lxc_abstract_unix_close(conf
->maincmd_fd
);
953 conf
->maincmd_fd
= -1;
957 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
961 struct lxc_list
*cur
, *next
;
962 char *namespaces
[LXC_NS_MAX
+ 1];
963 size_t namespace_count
= 0;
964 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
966 /* The STOPPING state is there for future cleanup code which can take
969 lxc_set_state(name
, handler
, STOPPING
);
971 self
= lxc_raw_getpid();
972 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
973 if (handler
->nsfd
[i
] < 0)
976 if (handler
->conf
->hooks_version
== 0)
977 ret
= asprintf(&namespaces
[namespace_count
],
978 "%s:/proc/%d/fd/%d", ns_info
[i
].proc_name
,
979 self
, handler
->nsfd
[i
]);
981 ret
= asprintf(&namespaces
[namespace_count
],
982 "/proc/%d/fd/%d", self
, handler
->nsfd
[i
]);
984 SYSERROR("Failed to allocate memory");
988 if (handler
->conf
->hooks_version
== 0) {
993 ret
= setenv(ns_info
[i
].env_name
, namespaces
[namespace_count
], 1);
995 SYSERROR("Failed to set environment variable %s=%s",
996 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
998 TRACE("Set environment variable %s=%s",
999 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
1003 namespaces
[namespace_count
] = NULL
;
1005 if (handler
->conf
->reboot
> REBOOT_NONE
) {
1006 ret
= setenv("LXC_TARGET", "reboot", 1);
1008 SYSERROR("Failed to set environment variable: "
1009 "LXC_TARGET=reboot");
1012 if (handler
->conf
->reboot
== REBOOT_NONE
) {
1013 ret
= setenv("LXC_TARGET", "stop", 1);
1015 SYSERROR("Failed to set environment variable: "
1019 if (handler
->conf
->hooks_version
== 0)
1020 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, namespaces
);
1022 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, NULL
);
1024 ERROR("Failed to run \"lxc.hook.stop\" hook");
1026 while (namespace_count
--)
1027 free(namespaces
[namespace_count
]);
1029 lsm_process_cleanup(handler
->conf
, handler
->lxcpath
);
1031 cgroup_ops
->payload_destroy(cgroup_ops
, handler
);
1032 cgroup_ops
->monitor_destroy(cgroup_ops
, handler
);
1034 if (handler
->conf
->reboot
== REBOOT_NONE
) {
1035 /* For all new state clients simply close the command socket.
1036 * This will inform all state clients that the container is
1037 * STOPPED and also prevents a race between a open()/close() on
1038 * the command socket causing a new process to get ECONNREFUSED
1039 * because we haven't yet closed the command socket.
1041 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
1042 handler
->conf
->maincmd_fd
= -1;
1043 TRACE("Closed command socket");
1045 /* This function will try to connect to the legacy lxc-monitord
1046 * state server and only exists for backwards compatibility.
1048 lxc_monitor_send_state(name
, STOPPED
, handler
->lxcpath
);
1050 /* The command socket is closed so no one can acces the command
1051 * socket anymore so there's no need to lock it.
1053 handler
->state
= STOPPED
;
1054 TRACE("Set container state to \"STOPPED\"");
1056 lxc_set_state(name
, handler
, STOPPED
);
1059 /* Avoid lingering namespace references. */
1060 lxc_put_nsfds(handler
);
1062 ret
= run_lxc_hooks(name
, "post-stop", handler
->conf
, NULL
);
1064 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name
);
1065 if (handler
->conf
->reboot
> REBOOT_NONE
) {
1066 WARN("Container will be stopped instead of rebooted");
1067 handler
->conf
->reboot
= REBOOT_NONE
;
1069 ret
= setenv("LXC_TARGET", "stop", 1);
1071 WARN("Failed to set environment variable: "
1076 /* Reset mask set by setup_signal_fd. */
1077 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1079 SYSWARN("Failed to restore signal mask");
1081 lxc_terminal_delete(&handler
->conf
->console
);
1082 lxc_delete_tty(&handler
->conf
->ttys
);
1084 /* The command socket is now closed, no more state clients can register
1085 * themselves from now on. So free the list of state clients.
1087 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
1088 struct lxc_state_client
*client
= cur
->elem
;
1090 /* Keep state clients that want to be notified about reboots. */
1091 if ((handler
->conf
->reboot
> REBOOT_NONE
) &&
1092 (client
->states
[RUNNING
] == 2))
1095 /* close state client socket */
1097 close(client
->clientfd
);
1102 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= REBOOT_REQ
)
1103 lxc_destroy_container_on_signal(handler
, name
);
1105 lxc_free_handler(handler
);
1108 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
1113 lxc_set_state(name
, handler
, ABORTING
);
1115 if (handler
->pidfd
> 0)
1116 ret
= lxc_raw_pidfd_send_signal(handler
->pidfd
, SIGKILL
, NULL
, 0);
1117 else if (handler
->proc_pidfd
> 0)
1118 ret
= lxc_raw_pidfd_send_signal(handler
->proc_pidfd
, SIGKILL
, NULL
, 0);
1119 else if (handler
->pid
> 0)
1120 ret
= kill(handler
->pid
, SIGKILL
);
1122 SYSERROR("Failed to send SIGKILL to %d", handler
->pid
);
1125 ret
= waitpid(-1, &status
, 0);
1129 static int do_start(void *data
)
1131 struct lxc_handler
*handler
= data
;
1132 ATTR_UNUSED __do_close_prot_errno
int data_sock0
= handler
->data_sock
[0],
1133 data_sock1
= handler
->data_sock
[1];
1135 char path
[PATH_MAX
];
1138 struct lxc_list
*iterator
;
1141 int devnull_fd
= -1;
1143 lxc_sync_fini_parent(handler
);
1145 /* This prctl must be before the synchro, so if the parent dies before
1146 * we set the parent death signal, we will detect its death with the
1147 * synchro right after, otherwise we have a window where the parent can
1148 * exit before we set the pdeath signal leading to a unsupervized
1151 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
);
1153 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1154 goto out_warn_father
;
1157 ret
= lxc_ambient_caps_up();
1159 ERROR("Failed to raise ambient capabilities");
1160 goto out_warn_father
;
1163 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1165 SYSERROR("Failed to set signal mask");
1166 goto out_warn_father
;
1169 /* Don't leak the pinfd to the container. */
1170 if (handler
->pinfd
>= 0)
1171 close(handler
->pinfd
);
1173 ret
= lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
);
1175 goto out_warn_father
;
1177 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1178 * https://github.com/lxc/lxd/issues/1978.
1180 if ((handler
->ns_clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
1181 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
1182 ret
= unshare(CLONE_NEWNET
);
1184 SYSERROR("Failed to unshare CLONE_NEWNET");
1185 goto out_warn_father
;
1187 INFO("Unshared CLONE_NEWNET");
1190 /* Tell the parent task it can begin to configure the container and wait
1193 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
);
1197 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1198 ret
= lxc_network_recv_veth_names_from_parent(handler
);
1200 ERROR("Failed to receive veth names from parent");
1201 goto out_warn_father
;
1205 /* If we are in a new user namespace, become root there to have
1206 * privilege over our namespace.
1208 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1209 if (!handler
->conf
->root_nsuid_map
)
1210 nsuid
= handler
->conf
->init_uid
;
1212 if (!handler
->conf
->root_nsgid_map
)
1213 nsgid
= handler
->conf
->init_gid
;
1215 if (!lxc_switch_uid_gid(nsuid
, nsgid
))
1216 goto out_warn_father
;
1218 /* Drop groups only after we switched to a valid gid in the new
1221 if (!lxc_setgroups(0, NULL
) &&
1222 (handler
->am_root
|| errno
!= EPERM
))
1223 goto out_warn_father
;
1225 ret
= prctl(PR_SET_DUMPABLE
, prctl_arg(1), prctl_arg(0),
1226 prctl_arg(0), prctl_arg(0));
1228 goto out_warn_father
;
1230 /* set{g,u}id() clears deathsignal */
1231 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
);
1233 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1234 goto out_warn_father
;
1238 ret
= access(handler
->lxcpath
, X_OK
);
1240 print_top_failing_dir(handler
->lxcpath
);
1241 goto out_warn_father
;
1244 ret
= snprintf(path
, sizeof(path
), "%s/dev/null",
1245 handler
->conf
->rootfs
.mount
);
1246 if (ret
< 0 || ret
>= sizeof(path
))
1247 goto out_warn_father
;
1249 /* In order to checkpoint restore, we need to have everything in the
1250 * same mount namespace. However, some containers may not have a
1251 * reasonable /dev (in particular, they may not have /dev/null), so we
1252 * can't set init's std fds to /dev/null by opening it from inside the
1255 * If that's the case, fall back to using the host's /dev/null. This
1256 * means that migration won't work, but at least we won't spew output
1257 * where it isn't wanted.
1259 if (handler
->daemonize
&& !handler
->conf
->autodev
) {
1260 ret
= access(path
, F_OK
);
1262 devnull_fd
= open_devnull();
1265 goto out_warn_father
;
1266 WARN("Using /dev/null from the host for container "
1267 "init's standard file descriptors. Migration will "
1272 /* Ask father to setup cgroups and wait for him to finish. */
1273 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
);
1277 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1278 * earlier we end up with a wrong view of /proc/self/cgroup. For
1279 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1280 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1281 * /proc/self/cgroup would show us:
1285 * whereas it should actually show
1289 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1290 ret
= unshare(CLONE_NEWCGROUP
);
1292 if (errno
!= EINVAL
) {
1293 SYSERROR("Failed to unshare CLONE_NEWCGROUP");
1294 goto out_warn_father
;
1297 handler
->ns_clone_flags
&= ~CLONE_NEWCGROUP
;
1298 SYSINFO("Kernel does not support CLONE_NEWCGROUP");
1300 INFO("Unshared CLONE_NEWCGROUP");
1304 /* Add the requested environment variables to the current environment to
1305 * allow them to be used by the various hooks, such as the start hook
1308 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1309 ret
= putenv((char *)iterator
->elem
);
1311 SYSERROR("Failed to set environment variable: %s",
1312 (char *)iterator
->elem
);
1313 goto out_warn_father
;
1317 /* Setup the container, ip, names, utsname, ... */
1318 ret
= lxc_setup(handler
);
1320 ERROR("Failed to setup container \"%s\"", handler
->name
);
1321 goto out_warn_father
;
1324 /* Set the label to change to when we exec(2) the container's init. */
1325 ret
= lsm_process_label_set(NULL
, handler
->conf
, true);
1327 goto out_warn_father
;
1329 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1330 * before we aren't allowed anymore.
1332 if (handler
->conf
->no_new_privs
) {
1333 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
1334 prctl_arg(0), prctl_arg(0));
1336 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block "
1337 "execve() gainable privileges");
1338 goto out_warn_father
;
1340 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable "
1344 /* Some init's such as busybox will set sane tty settings on stdin,
1345 * stdout, stderr which it thinks is the console. We already set them
1346 * the way we wanted on the real terminal, and we want init to do its
1347 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
1348 * make sure that that pty is stdin,stdout,stderr.
1350 if (handler
->conf
->console
.slave
>= 0) {
1351 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
1352 ret
= set_stdfds(handler
->conf
->console
.slave
);
1354 ret
= lxc_terminal_set_stdfds(handler
->conf
->console
.slave
);
1356 ERROR("Failed to redirect std{in,out,err} to pty file "
1357 "descriptor %d", handler
->conf
->console
.slave
);
1358 goto out_warn_father
;
1362 /* If we mounted a temporary proc, then unmount it now. */
1363 tmp_proc_unmount(handler
->conf
);
1365 ret
= lxc_seccomp_load(handler
->conf
);
1367 goto out_warn_father
;
1369 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, data_sock0
);
1371 SYSERROR("Failed to send seccomp notify fd to parent");
1372 goto out_warn_father
;
1375 ret
= run_lxc_hooks(handler
->name
, "start", handler
->conf
, NULL
);
1377 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1379 goto out_warn_father
;
1382 close(handler
->sigfd
);
1384 if (handler
->conf
->console
.slave
< 0 && handler
->daemonize
) {
1385 if (devnull_fd
< 0) {
1386 devnull_fd
= open_devnull();
1388 goto out_warn_father
;
1391 ret
= set_stdfds(devnull_fd
);
1393 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
1394 goto out_warn_father
;
1398 if (devnull_fd
>= 0) {
1405 if (handler
->conf
->init_cwd
) {
1406 ret
= chdir(handler
->conf
->init_cwd
);
1408 SYSERROR("Could not change directory to \"%s\"",
1409 handler
->conf
->init_cwd
);
1410 goto out_warn_father
;
1414 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
);
1416 goto out_warn_father
;
1418 /* Reset the environment variables the user requested in a clear
1422 /* Don't error out though. */
1424 SYSERROR("Failed to clear environment.");
1426 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1427 ret
= putenv((char *)iterator
->elem
);
1429 SYSERROR("Failed to set environment variable: %s",
1430 (char *)iterator
->elem
);
1431 goto out_warn_father
;
1435 ret
= putenv("container=lxc");
1437 SYSERROR("Failed to set environment variable: container=lxc");
1438 goto out_warn_father
;
1441 if (handler
->conf
->ttys
.tty_names
) {
1442 ret
= putenv(handler
->conf
->ttys
.tty_names
);
1444 SYSERROR("Failed to set environment variable for container ptys");
1445 goto out_warn_father
;
1449 /* The container has been setup. We can now switch to an unprivileged
1452 new_uid
= handler
->conf
->init_uid
;
1453 new_gid
= handler
->conf
->init_gid
;
1455 /* Avoid unnecessary syscalls. */
1456 if (new_uid
== nsuid
)
1457 new_uid
= LXC_INVALID_UID
;
1459 if (new_gid
== nsgid
)
1460 new_gid
= LXC_INVALID_GID
;
1462 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
1463 goto out_warn_father
;
1465 /* If we are in a new user namespace we already dropped all groups when
1466 * we switched to root in the new user namespace further above. Only
1467 * drop groups if we can, so ensure that we have necessary privilege.
1469 if (lxc_list_empty(&handler
->conf
->id_map
))
1471 if (lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
))
1473 if (!lxc_setgroups(0, NULL
))
1474 goto out_warn_father
;
1476 ret
= lxc_ambient_caps_down();
1478 ERROR("Failed to clear ambient capabilities");
1479 goto out_warn_father
;
1482 if (handler
->conf
->monitor_signal_pdeath
!= SIGKILL
) {
1483 ret
= lxc_set_death_signal(handler
->conf
->monitor_signal_pdeath
, handler
->monitor_pid
);
1485 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1486 handler
->conf
->monitor_signal_pdeath
);
1487 goto out_warn_father
;
1491 /* After this call, we are in error because this ops should not return
1494 handler
->ops
->start(handler
, handler
->data
);
1497 /* We want the parent to know something went wrong, so we return a
1498 * special error code.
1500 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1503 if (devnull_fd
>= 0)
1509 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1512 struct lxc_terminal_info
*tty
;
1514 int sock
= handler
->data_sock
[1];
1515 struct lxc_conf
*conf
= handler
->conf
;
1516 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1518 if (!conf
->ttys
.max
)
1521 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
1525 for (i
= 0; i
< conf
->ttys
.max
; i
++) {
1528 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1532 tty
= &ttys
->tty
[i
];
1534 tty
->master
= ttyfds
[0];
1535 tty
->slave
= ttyfds
[1];
1536 TRACE("Received pty with master fd %d and slave fd %d from "
1537 "parent", tty
->master
, tty
->slave
);
1541 SYSERROR("Failed to receive %zu ttys from child", ttys
->max
);
1543 TRACE("Received %zu ttys from child", ttys
->max
);
1548 int resolve_clone_flags(struct lxc_handler
*handler
)
1551 struct lxc_conf
*conf
= handler
->conf
;
1553 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1554 if (conf
->ns_keep
) {
1555 if (!(conf
->ns_keep
& ns_info
[i
].clone_flag
))
1556 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1557 } else if (conf
->ns_clone
) {
1558 if ((conf
->ns_clone
& ns_info
[i
].clone_flag
))
1559 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1561 if (i
== LXC_NS_USER
&& lxc_list_empty(&handler
->conf
->id_map
))
1564 if (i
== LXC_NS_NET
&& lxc_requests_empty_network(handler
))
1567 if (i
== LXC_NS_CGROUP
&& !cgns_supported())
1570 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1573 if (!conf
->ns_share
[i
])
1576 handler
->ns_clone_flags
&= ~ns_info
[i
].clone_flag
;
1577 TRACE("Sharing %s namespace", ns_info
[i
].proc_name
);
1583 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1584 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1585 * But since the memory between parent and child is shared on CLONE_VM this
1586 * would invalidate the getpid() cache that glibc used to maintain and so
1587 * getpid() in the child would return the parent's pid. This is all fixed in
1588 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1589 * not reset anymore.
1590 * However, if for whatever reason you - dear committer - somehow need to get the
1591 * pid of the dummy intermediate process for do_share_ns() you need to call
1592 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1595 static inline int do_share_ns(void *arg
)
1598 struct lxc_handler
*handler
= arg
;
1600 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1601 if (handler
->nsfd
[i
] < 0)
1604 ret
= setns(handler
->nsfd
[i
], 0);
1607 * Note that joining a user and/or mount namespace
1608 * requires the process is not multithreaded otherwise
1609 * setns() will fail here.
1611 SYSERROR("Failed to inherit %s namespace",
1612 ns_info
[i
].proc_name
);
1616 DEBUG("Inherited %s namespace", ns_info
[i
].proc_name
);
1619 flags
= handler
->ns_on_clone_flags
;
1620 flags
|= CLONE_PARENT
;
1621 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, CLONE_PIDFD
| flags
,
1623 if (handler
->pid
< 0)
1629 static int proc_pidfd_open(pid_t pid
)
1631 __do_close_prot_errno
int proc_pidfd
= -EBADF
;
1634 snprintf(path
, sizeof(path
), "/proc/%d", pid
);
1635 proc_pidfd
= open(path
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1636 if (proc_pidfd
< 0) {
1637 SYSERROR("Failed to open %s", path
);
1641 /* Test whether we can send signals. */
1642 if (lxc_raw_pidfd_send_signal(proc_pidfd
, 0, NULL
, 0)) {
1643 SYSERROR("Failed to send signal through pidfd");
1647 return move_fd(proc_pidfd
);
1650 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1651 * exec()s the requested container binary.
1652 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1653 * right here should be double checked if they'd pose a security risk. (For
1654 * example, any {u}mount() operations performed here will be reflected on the
1657 static int lxc_spawn(struct lxc_handler
*handler
)
1659 __do_close_prot_errno
int data_sock0
= -EBADF
, data_sock1
= -EBADF
;
1662 bool wants_to_map_ids
;
1663 struct lxc_list
*id_map
;
1664 const char *name
= handler
->name
;
1665 const char *lxcpath
= handler
->lxcpath
;
1666 bool share_ns
= false;
1667 struct lxc_conf
*conf
= handler
->conf
;
1668 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
1670 id_map
= &conf
->id_map
;
1671 wants_to_map_ids
= !lxc_list_empty(id_map
);
1673 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1674 if (!conf
->ns_share
[i
])
1677 handler
->nsfd
[i
] = lxc_inherit_namespace(conf
->ns_share
[i
], lxcpath
, ns_info
[i
].proc_name
);
1678 if (handler
->nsfd
[i
] < 0)
1684 ret
= lxc_sync_init(handler
);
1688 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1689 handler
->data_sock
);
1692 data_sock0
= handler
->data_sock
[0];
1693 data_sock1
= handler
->data_sock
[1];
1695 ret
= resolve_clone_flags(handler
);
1699 if (!cgroup_ops
->payload_create(cgroup_ops
, handler
)) {
1700 ERROR("Failed creating cgroups");
1701 goto out_delete_net
;
1704 /* If the rootfs is not a blockdev, prevent the container from marking
1706 * If the container is unprivileged then skip rootfs pinning.
1708 if (!wants_to_map_ids
) {
1709 handler
->pinfd
= pin_rootfs(conf
->rootfs
.path
);
1710 if (handler
->pinfd
== -1)
1711 INFO("Failed to pin the rootfs for container \"%s\"", handler
->name
);
1714 /* Create a process in a new set of namespaces. */
1715 handler
->ns_on_clone_flags
= handler
->ns_clone_flags
;
1716 if (handler
->ns_clone_flags
& CLONE_NEWUSER
) {
1717 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1718 * clone a new user namespace first and only later unshare our
1719 * network namespace to ensure that network devices ownership is
1722 handler
->ns_on_clone_flags
&= ~CLONE_NEWNET
;
1724 /* The cgroup namespace gets unshare()ed not clone()ed. */
1725 handler
->ns_on_clone_flags
&= ~CLONE_NEWCGROUP
;
1730 attacher_pid
= lxc_clone(do_share_ns
, handler
,
1731 CLONE_VFORK
| CLONE_VM
| CLONE_FILES
, NULL
);
1732 if (attacher_pid
< 0) {
1733 SYSERROR(LXC_CLONE_ERROR
);
1734 goto out_delete_net
;
1737 ret
= wait_for_pid(attacher_pid
);
1739 SYSERROR("Intermediate process failed");
1740 goto out_delete_net
;
1743 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
,
1744 CLONE_PIDFD
| handler
->ns_on_clone_flags
,
1747 if (handler
->pid
< 0) {
1748 SYSERROR(LXC_CLONE_ERROR
);
1749 goto out_delete_net
;
1751 TRACE("Cloned child process %d", handler
->pid
);
1753 if (handler
->pidfd
< 0) {
1754 handler
->proc_pidfd
= proc_pidfd_open(handler
->pid
);
1755 if (handler
->proc_pidfd
< 0 && (errno
!= ENOSYS
))
1756 goto out_delete_net
;
1759 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1760 if (handler
->ns_on_clone_flags
& ns_info
[i
].clone_flag
)
1761 INFO("Cloned %s", ns_info
[i
].flag_name
);
1763 if (!lxc_try_preserve_namespaces(handler
, handler
->ns_on_clone_flags
, handler
->pid
)) {
1764 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1765 goto out_delete_net
;
1768 lxc_sync_fini_child(handler
);
1770 /* Map the container uids. The container became an invalid userid the
1771 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1772 * anything immediately, but allows the container to setuid(0) (0 being
1773 * mapped to something else on the host.) later to become a valid uid
1776 if (wants_to_map_ids
) {
1777 if (!handler
->conf
->ns_share
[LXC_NS_USER
] &&
1778 (handler
->conf
->ns_keep
& CLONE_NEWUSER
) == 0) {
1779 ret
= lxc_map_ids(id_map
, handler
->pid
);
1781 ERROR("Failed to set up id mapping.");
1782 goto out_delete_net
;
1787 ret
= lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
);
1789 goto out_delete_net
;
1791 ret
= lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
);
1793 goto out_delete_net
;
1795 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
->conf
, false)) {
1796 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1797 goto out_delete_net
;
1800 if (!cgroup_ops
->payload_enter(cgroup_ops
, handler
->pid
))
1801 goto out_delete_net
;
1803 if (!cgroup_ops
->chown(cgroup_ops
, handler
->conf
))
1804 goto out_delete_net
;
1806 /* If not done yet, we're now ready to preserve the network namespace */
1807 if (handler
->nsfd
[LXC_NS_NET
] < 0) {
1808 ret
= lxc_try_preserve_ns(handler
->pid
, "net");
1810 if (ret
!= -EOPNOTSUPP
) {
1811 SYSERROR("Failed to preserve net namespace");
1812 goto out_delete_net
;
1815 handler
->nsfd
[LXC_NS_NET
] = ret
;
1816 DEBUG("Preserved net namespace via fd %d", ret
);
1819 ret
= lxc_netns_set_nsid(handler
->nsfd
[LXC_NS_NET
]);
1821 SYSWARN("Failed to allocate new network namespace id");
1823 TRACE("Allocated new network namespace id");
1825 /* Create the network configuration. */
1826 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1827 ret
= lxc_create_network(handler
);
1829 ERROR("Failed to create the network");
1830 goto out_delete_net
;
1833 ret
= lxc_network_send_veth_names_to_child(handler
);
1835 ERROR("Failed to send veth names to child");
1836 goto out_delete_net
;
1840 if (!lxc_list_empty(&conf
->procs
)) {
1841 ret
= setup_proc_filesystem(&conf
->procs
, handler
->pid
);
1843 goto out_delete_net
;
1846 /* Tell the child to continue its initialization. We'll get
1847 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1849 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
);
1851 goto out_delete_net
;
1853 if (!lxc_list_empty(&conf
->limits
)) {
1854 ret
= setup_resource_limits(&conf
->limits
, handler
->pid
);
1856 ERROR("Failed to setup resource limits");
1857 goto out_delete_net
;
1861 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
);
1863 goto out_delete_net
;
1865 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
->conf
, true)) {
1866 ERROR("Failed to setup legacy device cgroup controller limits");
1867 goto out_delete_net
;
1869 TRACE("Set up legacy device cgroup controller limits");
1871 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1872 /* Now we're ready to preserve the cgroup namespace */
1873 ret
= lxc_try_preserve_ns(handler
->pid
, "cgroup");
1875 if (ret
!= -EOPNOTSUPP
) {
1876 SYSERROR("Failed to preserve cgroup namespace");
1877 goto out_delete_net
;
1880 handler
->nsfd
[LXC_NS_CGROUP
] = ret
;
1881 DEBUG("Preserved cgroup namespace via fd %d", ret
);
1885 ret
= snprintf(pidstr
, 20, "%d", handler
->pid
);
1886 if (ret
< 0 || ret
>= 20)
1887 goto out_delete_net
;
1889 ret
= setenv("LXC_PID", pidstr
, 1);
1891 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr
);
1893 /* Run any host-side start hooks */
1894 ret
= run_lxc_hooks(name
, "start-host", conf
, NULL
);
1896 ERROR("Failed to run lxc.hook.start-host");
1897 goto out_delete_net
;
1900 /* Tell the child to complete its initialization and wait for it to exec
1901 * or return an error. (The child will never return
1902 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1903 * lxc_sync_barrier_child to return success, or return a different
1904 * value, causing us to error out).
1906 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_READY_START
);
1908 goto out_delete_net
;
1910 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1911 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
1913 ERROR("Failed to receive names and ifindices for network devices from child");
1914 goto out_delete_net
;
1918 /* Now all networks are created, network devices are moved into place,
1919 * and the correct names and ifindices in the respective namespaces have
1920 * been recorded. The corresponding structs have now all been filled. So
1921 * log them for debugging purposes.
1923 lxc_log_configured_netdevs(conf
);
1925 /* Read tty fds allocated by child. */
1926 ret
= lxc_recv_ttys_from_child(handler
);
1928 ERROR("Failed to receive tty info from child process");
1929 goto out_delete_net
;
1932 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, data_sock1
);
1934 SYSERROR("Failed to receive seccomp notify fd from child");
1935 goto out_delete_net
;
1938 ret
= handler
->ops
->post_start(handler
, handler
->data
);
1942 ret
= lxc_set_state(name
, handler
, RUNNING
);
1944 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING
));
1948 lxc_sync_fini(handler
);
1953 if (handler
->ns_clone_flags
& CLONE_NEWNET
)
1954 lxc_delete_network(handler
);
1957 lxc_abort(name
, handler
);
1960 lxc_sync_fini(handler
);
1961 if (handler
->pinfd
>= 0) {
1962 close(handler
->pinfd
);
1963 handler
->pinfd
= -1;
1969 int __lxc_start(const char *name
, struct lxc_handler
*handler
,
1970 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1971 bool daemonize
, int *error_num
)
1974 struct lxc_conf
*conf
= handler
->conf
;
1975 struct cgroup_ops
*cgroup_ops
;
1977 ret
= lxc_init(name
, handler
);
1979 ERROR("Failed to initialize container \"%s\"", name
);
1980 goto out_fini_nonet
;
1983 handler
->data
= data
;
1984 handler
->daemonize
= daemonize
;
1985 cgroup_ops
= handler
->cgroup_ops
;
1987 if (!attach_block_device(handler
->conf
)) {
1988 ERROR("Failed to attach block device");
1990 goto out_fini_nonet
;
1993 if (!cgroup_ops
->monitor_create(cgroup_ops
, handler
)) {
1994 ERROR("Failed to create monitor cgroup");
1996 goto out_fini_nonet
;
1999 if (!cgroup_ops
->monitor_enter(cgroup_ops
, handler
->monitor_pid
)) {
2000 ERROR("Failed to enter monitor cgroup");
2002 goto out_fini_nonet
;
2005 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
2006 /* If the backing store is a device, mount it here and now. */
2007 if (rootfs_is_blockdev(conf
)) {
2008 ret
= unshare(CLONE_NEWNS
);
2010 ERROR("Failed to unshare CLONE_NEWNS");
2011 goto out_fini_nonet
;
2013 INFO("Unshared CLONE_NEWNS");
2015 remount_all_slave();
2016 ret
= lxc_setup_rootfs_prepare_root(conf
, name
, lxcpath
);
2018 ERROR("Error setting up rootfs mount as root before spawn");
2019 goto out_fini_nonet
;
2021 INFO("Set up container rootfs as host root");
2025 ret
= lxc_spawn(handler
);
2027 ERROR("Failed to spawn container \"%s\"", name
);
2028 goto out_detach_blockdev
;
2031 handler
->conf
->reboot
= REBOOT_NONE
;
2033 ret
= lxc_poll(name
, handler
);
2035 ERROR("LXC mainloop exited with error: %d", ret
);
2039 if (!handler
->init_died
&& handler
->pid
> 0) {
2040 ERROR("Child process is not killed");
2045 status
= lxc_wait_for_pid_status(handler
->pid
);
2047 SYSERROR("Failed to retrieve status for %d", handler
->pid
);
2049 /* If the child process exited but was not signaled, it didn't call
2050 * reboot. This should mean it was an lxc-execute which simply exited.
2051 * In any case, treat it as a 'halt'.
2053 if (WIFSIGNALED(status
)) {
2054 switch(WTERMSIG(status
)) {
2055 case SIGINT
: /* halt */
2056 DEBUG("Container \"%s\" is halting", name
);
2058 case SIGHUP
: /* reboot */
2059 DEBUG("Container \"%s\" is rebooting", name
);
2060 handler
->conf
->reboot
= REBOOT_REQ
;
2062 case SIGSYS
: /* seccomp */
2063 DEBUG("Container \"%s\" violated its seccomp policy", name
);
2066 DEBUG("Unknown exit status for container \"%s\" init %d", name
, WTERMSIG(status
));
2071 ret
= lxc_restore_phys_nics_to_netns(handler
);
2073 ERROR("Failed to move physical network devices back to parent "
2074 "network namespace");
2076 if (handler
->pinfd
>= 0) {
2077 close(handler
->pinfd
);
2078 handler
->pinfd
= -1;
2081 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
2082 lxc_error_set_and_log(handler
->pid
, status
);
2084 *error_num
= handler
->exit_status
;
2087 lxc_delete_network(handler
);
2089 out_detach_blockdev
:
2090 detach_block_device(handler
->conf
);
2093 lxc_fini(name
, handler
);
2097 lxc_abort(name
, handler
);
2105 static int start(struct lxc_handler
*handler
, void* data
)
2107 struct start_args
*arg
= data
;
2109 NOTICE("Exec'ing \"%s\"", arg
->argv
[0]);
2111 execvp(arg
->argv
[0], arg
->argv
);
2112 SYSERROR("Failed to exec \"%s\"", arg
->argv
[0]);
2116 static int post_start(struct lxc_handler
*handler
, void* data
)
2118 struct start_args
*arg
= data
;
2120 NOTICE("Started \"%s\" with pid \"%d\"", arg
->argv
[0], handler
->pid
);
2124 static struct lxc_operations start_ops
= {
2126 .post_start
= post_start
2129 int lxc_start(const char *name
, char *const argv
[], struct lxc_handler
*handler
,
2130 const char *lxcpath
, bool daemonize
, int *error_num
)
2132 struct start_args start_arg
= {
2136 TRACE("Doing lxc_start");
2137 return __lxc_start(name
, handler
, &start_ops
, &start_arg
, lxcpath
, daemonize
, error_num
);
2140 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
2143 char destroy
[PATH_MAX
];
2144 struct lxc_container
*c
;
2148 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
2149 bret
= do_destroy_container(handler
);
2151 ERROR("Error destroying rootfs for container \"%s\"", name
);
2155 INFO("Destroyed rootfs for container \"%s\"", name
);
2157 ret
= snprintf(destroy
, PATH_MAX
, "%s/%s", handler
->lxcpath
, name
);
2158 if (ret
< 0 || ret
>= PATH_MAX
) {
2159 ERROR("Error destroying directory for container \"%s\"", name
);
2163 c
= lxc_container_new(name
, handler
->lxcpath
);
2165 if (container_disk_lock(c
)) {
2166 INFO("Could not update lxc_snapshots file");
2167 lxc_container_put(c
);
2169 mod_all_rdeps(c
, false);
2170 container_disk_unlock(c
);
2171 lxc_container_put(c
);
2175 if (!handler
->am_root
)
2176 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
2177 destroy
, "lxc_rmdir_onedev_wrapper");
2179 ret
= lxc_rmdir_onedev(destroy
, NULL
);
2182 ERROR("Error destroying directory for container \"%s\"", name
);
2185 INFO("Destroyed directory for container \"%s\"", name
);
2188 static int lxc_rmdir_onedev_wrapper(void *data
)
2190 char *arg
= (char *) data
;
2191 return lxc_rmdir_onedev(arg
, NULL
);
2194 static bool do_destroy_container(struct lxc_handler
*handler
)
2198 if (!handler
->am_root
) {
2199 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
2200 handler
->conf
, "storage_destroy_wrapper");
2207 return storage_destroy(handler
->conf
);