1 /* SPDX-License-Identifier: LGPL-2.1+ */
17 #include <sys/mount.h>
18 #include <sys/param.h>
19 #include <sys/prctl.h>
20 #include <sys/socket.h>
22 #include <sys/syscall.h>
23 #include <sys/types.h>
32 #include "commands_utils.h"
35 #include "confile_utils.h"
37 #include "file_utils.h"
41 #include "lxccontainer.h"
43 #include "lxcseccomp.h"
46 #include "memory_utils.h"
48 #include "namespace.h"
50 #include "raw_syscalls.h"
52 #include "storage/storage.h"
53 #include "storage/storage_utils.h"
55 #include "syscall_wrappers.h"
60 #include <sys/capability.h>
64 #include "include/strlcpy.h"
67 lxc_log_define(start
, lxc
);
69 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
70 static bool do_destroy_container(struct lxc_handler
*handler
);
71 static int lxc_rmdir_onedev_wrapper(void *data
);
72 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
75 static void print_top_failing_dir(const char *path
)
77 __do_free
char *copy
= NULL
;
81 copy
= must_copy_string(path
);
83 e
= copy
+ strlen(path
);
86 while (p
< e
&& *p
== '/')
89 while (p
< e
&& *p
!= '/')
95 ret
= access(copy
, X_OK
);
97 SYSERROR("Could not access %s. Please grant it x "
98 "access, or add an ACL for the container "
106 static void lxc_put_nsfds(struct lxc_handler
*handler
)
110 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
111 if (handler
->nsfd
[i
] < 0)
114 close(handler
->nsfd
[i
]);
115 handler
->nsfd
[i
] = -EBADF
;
119 static int lxc_try_preserve_ns(const int pid
, const char *ns
)
123 fd
= lxc_preserve_ns(pid
, ns
);
125 if (errno
!= ENOENT
) {
126 SYSERROR("Failed to preserve %s namespace", ns
);
130 SYSWARN("Kernel does not support preserving %s namespaces", ns
);
137 /* lxc_try_preserve_namespaces: open /proc/@pid/ns/@ns for each namespace
138 * specified in ns_clone_flags.
139 * Return true on success, false on failure.
141 static bool lxc_try_preserve_namespaces(struct lxc_handler
*handler
,
142 int ns_clone_flags
, pid_t pid
)
146 for (i
= 0; i
< LXC_NS_MAX
; i
++)
147 handler
->nsfd
[i
] = -EBADF
;
149 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
152 if ((ns_clone_flags
& ns_info
[i
].clone_flag
) == 0)
155 fd
= lxc_try_preserve_ns(pid
, ns_info
[i
].proc_name
);
157 /* Do not fail to start container on kernels that do
158 * not support interacting with namespaces through
161 if (fd
== -EOPNOTSUPP
)
164 lxc_put_nsfds(handler
);
168 handler
->nsfd
[i
] = fd
;
169 DEBUG("Preserved %s namespace via fd %d", ns_info
[i
].proc_name
,
176 static inline bool match_stdfds(int fd
)
178 return (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
);
182 static bool match_dlog_fds(struct dirent
*direntp
)
184 char path
[PATH_MAX
] = {0};
185 char link
[PATH_MAX
] = {0};
189 ret
= snprintf(path
, PATH_MAX
, "/proc/self/fd/%s", direntp
->d_name
);
190 if (ret
< 0 || ret
>= PATH_MAX
) {
191 ERROR("Failed to create file descriptor name");
195 linklen
= readlink(path
, link
, PATH_MAX
);
197 SYSERROR("Failed to read link path - \"%s\"", path
);
199 } else if (linklen
>= PATH_MAX
) {
200 ERROR("The name of link path is too long - \"%s\"", path
);
204 if (strcmp(link
, "/dev/log_main") == 0 ||
205 strcmp(link
, "/dev/log_system") == 0 ||
206 strcmp(link
, "/dev/log_radio") == 0)
213 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
214 int *fds_to_ignore
, size_t len_fds
)
219 struct dirent
*direntp
;
221 if (conf
&& conf
->close_all_fds
)
225 dir
= opendir("/proc/self/fd");
227 SYSWARN("Failed to open directory");
233 while ((direntp
= readdir(dir
))) {
235 struct lxc_list
*cur
;
236 bool matched
= false;
238 if (strcmp(direntp
->d_name
, ".") == 0)
241 if (strcmp(direntp
->d_name
, "..") == 0)
244 ret
= lxc_safe_int(direntp
->d_name
, &fd
);
246 INFO("Could not parse file descriptor for \"%s\"", direntp
->d_name
);
250 for (i
= 0; i
< len_fds
; i
++)
251 if (fds_to_ignore
[i
] == fd
)
254 if (fd
== fddir
|| fd
== lxc_log_fd
||
255 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
258 /* Keep state clients that wait on reboots. */
260 lxc_list_for_each(cur
, &conf
->state_clients
) {
261 struct lxc_state_client
*client
= cur
->elem
;
263 if (client
->clientfd
!= fd
)
274 if (current_config
&& fd
== current_config
->logfd
)
277 if (match_stdfds(fd
))
281 if (match_dlog_fds(direntp
))
288 INFO("Closed inherited fd %d", fd
);
291 WARN("Inherited fd %d", fd
);
294 /* Only enable syslog at this point to avoid the above logging function
295 * to open a new fd and make the check_inherited function enter an
298 lxc_log_enable_syslog();
300 closedir(dir
); /* cannot fail */
304 static int setup_signal_fd(sigset_t
*oldmask
)
308 const int signals
[] = {SIGBUS
, SIGILL
, SIGSEGV
, SIGWINCH
};
310 /* Block everything except serious error signals. */
311 ret
= sigfillset(&mask
);
315 for (int sig
= 0; sig
< (sizeof(signals
) / sizeof(signals
[0])); sig
++) {
316 ret
= sigdelset(&mask
, signals
[sig
]);
321 ret
= pthread_sigmask(SIG_BLOCK
, &mask
, oldmask
);
323 SYSERROR("Failed to set signal mask");
327 ret
= signalfd(-1, &mask
, SFD_CLOEXEC
);
329 SYSERROR("Failed to create signal file descriptor");
333 TRACE("Created signal file descriptor %d", ret
);
338 static int signal_handler(int fd
, uint32_t events
, void *data
,
339 struct lxc_epoll_descr
*descr
)
343 struct signalfd_siginfo siginfo
;
344 struct lxc_handler
*hdlr
= data
;
346 ret
= lxc_read_nointr(fd
, &siginfo
, sizeof(siginfo
));
348 ERROR("Failed to read signal info from signal file descriptor %d", fd
);
349 return LXC_MAINLOOP_ERROR
;
352 if (ret
!= sizeof(siginfo
)) {
353 ERROR("Unexpected size for struct signalfd_siginfo");
357 /* Check whether init is running. */
359 ret
= waitid(P_PID
, hdlr
->pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
360 if (ret
== 0 && info
.si_pid
== hdlr
->pid
)
361 hdlr
->init_died
= true;
363 /* Try to figure out a reasonable exit status to report. */
364 if (hdlr
->init_died
) {
365 switch (info
.si_code
) {
367 hdlr
->exit_status
= info
.si_status
<< 8;
372 hdlr
->exit_status
= info
.si_status
<< 8 | 0x7f;
375 /* Huh? The waitid() told us it's dead *and* continued? */
376 WARN("Init %d dead and continued?", hdlr
->pid
);
377 hdlr
->exit_status
= 1;
380 ERROR("Unknown si_code: %d", info
.si_code
);
381 hdlr
->exit_status
= 1;
385 if (siginfo
.ssi_signo
== SIGHUP
) {
386 if (hdlr
->pidfd
>= 0)
387 lxc_raw_pidfd_send_signal(hdlr
->pidfd
, SIGTERM
, NULL
, 0);
389 kill(hdlr
->pid
, SIGTERM
);
390 INFO("Killing %d since terminal hung up", hdlr
->pid
);
391 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
392 : LXC_MAINLOOP_CONTINUE
;
395 if (siginfo
.ssi_signo
!= SIGCHLD
) {
396 if (hdlr
->pidfd
>= 0)
397 lxc_raw_pidfd_send_signal(hdlr
->pidfd
,
398 siginfo
.ssi_signo
, NULL
, 0);
400 kill(hdlr
->pid
, siginfo
.ssi_signo
);
401 INFO("Forwarded signal %d to pid %d", siginfo
.ssi_signo
, hdlr
->pid
);
402 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
403 : LXC_MAINLOOP_CONTINUE
;
406 /* More robustness, protect ourself from a SIGCHLD sent
407 * by a process different from the container init.
409 if (siginfo
.ssi_pid
!= hdlr
->pid
) {
410 NOTICE("Received %d from pid %d instead of container init %d",
411 siginfo
.ssi_signo
, siginfo
.ssi_pid
, hdlr
->pid
);
412 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
413 : LXC_MAINLOOP_CONTINUE
;
416 if (siginfo
.ssi_code
== CLD_STOPPED
) {
417 INFO("Container init process was stopped");
418 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
419 : LXC_MAINLOOP_CONTINUE
;
422 if (siginfo
.ssi_code
== CLD_CONTINUED
) {
423 INFO("Container init process was continued");
424 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
425 : LXC_MAINLOOP_CONTINUE
;
428 DEBUG("Container init process %d exited", hdlr
->pid
);
430 return LXC_MAINLOOP_CLOSE
;
433 int lxc_serve_state_clients(const char *name
, struct lxc_handler
*handler
,
438 struct lxc_list
*cur
, *next
;
439 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
442 handler
->state
= RUNNING
;
444 handler
->state
= state
;
446 TRACE("Set container state to %s", lxc_state2str(state
));
448 if (lxc_list_empty(&handler
->conf
->state_clients
)) {
449 TRACE("No state clients registered");
453 retlen
= strlcpy(msg
.name
, name
, sizeof(msg
.name
));
454 if (retlen
>= sizeof(msg
.name
))
457 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
458 struct lxc_state_client
*client
= cur
->elem
;
460 if (client
->states
[state
] == 0) {
461 TRACE("State %s not registered for state client %d",
462 lxc_state2str(state
), client
->clientfd
);
466 TRACE("Sending state %s to state client %d",
467 lxc_state2str(state
), client
->clientfd
);
469 ret
= lxc_send_nointr(client
->clientfd
, &msg
, sizeof(msg
), MSG_NOSIGNAL
);
471 SYSERROR("Failed to send message to client");
473 /* kick client from list */
475 close(client
->clientfd
);
483 static int lxc_serve_state_socket_pair(const char *name
,
484 struct lxc_handler
*handler
,
489 if (!handler
->daemonize
||
490 handler
->state_socket_pair
[1] < 0 ||
494 /* Close read end of the socket pair. */
495 close(handler
->state_socket_pair
[0]);
496 handler
->state_socket_pair
[0] = -1;
499 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
500 &(int){state
}, sizeof(int));
502 SYSERROR("Failed to send state to %d", handler
->state_socket_pair
[1]);
510 if (ret
!= sizeof(int)) {
511 ERROR("Message too long : %d", handler
->state_socket_pair
[1]);
515 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
516 handler
->state_socket_pair
[1]);
518 /* Close write end of the socket pair. */
519 close(handler
->state_socket_pair
[1]);
520 handler
->state_socket_pair
[1] = -1;
525 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
530 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
532 ERROR("Failed to synchronize via anonymous pair of unix sockets");
536 ret
= lxc_serve_state_clients(name
, handler
, state
);
540 /* This function will try to connect to the legacy lxc-monitord state
541 * server and only exists for backwards compatibility.
543 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
548 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
551 bool has_console
= true;
552 struct lxc_epoll_descr descr
, descr_console
;
554 if (handler
->conf
->console
.path
&&
555 strcmp(handler
->conf
->console
.path
, "none") == 0)
558 ret
= lxc_mainloop_open(&descr
);
560 ERROR("Failed to create mainloop");
565 ret
= lxc_mainloop_open(&descr_console
);
567 ERROR("Failed to create console mainloop");
572 ret
= lxc_mainloop_add_handler(&descr
, handler
->sigfd
, signal_handler
, handler
);
574 ERROR("Failed to add signal handler for %d to mainloop", handler
->sigfd
);
575 goto out_mainloop_console
;
578 ret
= lxc_seccomp_setup_proxy(&handler
->conf
->seccomp
, &descr
, handler
);
580 ERROR("Failed to setup seccomp proxy");
581 goto out_mainloop_console
;
585 struct lxc_terminal
*console
= &handler
->conf
->console
;
587 ret
= lxc_terminal_mainloop_add(&descr
, console
);
589 ERROR("Failed to add console handlers to mainloop");
590 goto out_mainloop_console
;
593 ret
= lxc_terminal_mainloop_add(&descr_console
, console
);
595 ERROR("Failed to add console handlers to console mainloop");
596 goto out_mainloop_console
;
599 handler
->conf
->console
.descr
= &descr
;
602 ret
= lxc_cmd_mainloop_add(name
, &descr
, handler
);
604 ERROR("Failed to add command handler to mainloop");
605 goto out_mainloop_console
;
608 TRACE("Mainloop is ready");
610 ret
= lxc_mainloop(&descr
, -1);
613 if (ret
< 0 || !handler
->init_died
)
614 goto out_mainloop_console
;
617 ret
= lxc_mainloop(&descr_console
, 0);
619 out_mainloop_console
:
621 lxc_mainloop_close(&descr_console
);
622 TRACE("Closed console mainloop");
626 lxc_mainloop_close(&descr
);
627 TRACE("Closed mainloop");
630 close(handler
->sigfd
);
631 TRACE("Closed signal file descriptor %d", handler
->sigfd
);
632 handler
->sigfd
= -EBADF
;
637 void lxc_zero_handler(struct lxc_handler
*handler
)
641 memset(handler
, 0, sizeof(struct lxc_handler
));
645 handler
->pidfd
= -EBADF
;
649 for (i
= 0; i
< LXC_NS_MAX
; i
++)
650 handler
->nsfd
[i
] = -1;
652 handler
->data_sock
[0] = -1;
653 handler
->data_sock
[1] = -1;
655 handler
->state_socket_pair
[0] = -1;
656 handler
->state_socket_pair
[1] = -1;
658 handler
->sync_sock
[0] = -1;
659 handler
->sync_sock
[1] = -1;
662 void lxc_free_handler(struct lxc_handler
*handler
)
664 if (handler
->pinfd
>= 0)
665 close(handler
->pinfd
);
667 if (handler
->pidfd
>= 0)
668 close(handler
->pidfd
);
670 if (handler
->sigfd
>= 0)
671 close(handler
->sigfd
);
673 lxc_put_nsfds(handler
);
675 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
676 if (handler
->conf
->maincmd_fd
>= 0)
677 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
679 if (handler
->monitor_status_fd
>= 0)
680 close(handler
->monitor_status_fd
);
682 if (handler
->state_socket_pair
[0] >= 0)
683 close(handler
->state_socket_pair
[0]);
685 if (handler
->state_socket_pair
[1] >= 0)
686 close(handler
->state_socket_pair
[1]);
688 if (handler
->cgroup_ops
)
689 cgroup_exit(handler
->cgroup_ops
);
691 handler
->conf
= NULL
;
696 struct lxc_handler
*lxc_init_handler(const char *name
, struct lxc_conf
*conf
,
697 const char *lxcpath
, bool daemonize
)
700 struct lxc_handler
*handler
;
702 handler
= malloc(sizeof(*handler
));
706 memset(handler
, 0, sizeof(*handler
));
708 /* Note that am_guest_unpriv() checks the effective uid. We
709 * probably don't care if we are real root only if we are running
710 * as root so this should be fine.
712 handler
->am_root
= !am_guest_unpriv();
713 handler
->data_sock
[0] = handler
->data_sock
[1] = -1;
714 handler
->conf
= conf
;
715 handler
->lxcpath
= lxcpath
;
716 handler
->monitor_status_fd
= -EBADF
;
718 handler
->pidfd
= -EBADF
;
719 handler
->sigfd
= -EBADF
;
720 handler
->init_died
= false;
721 handler
->state_socket_pair
[0] = handler
->state_socket_pair
[1] = -1;
722 if (handler
->conf
->reboot
== REBOOT_NONE
)
723 lxc_list_init(&handler
->conf
->state_clients
);
725 for (i
= 0; i
< LXC_NS_MAX
; i
++)
726 handler
->nsfd
[i
] = -1;
728 handler
->name
= name
;
730 handler
->transient_pid
= lxc_raw_getpid();
732 handler
->transient_pid
= -1;
734 if (daemonize
&& handler
->conf
->reboot
== REBOOT_NONE
) {
735 /* Create socketpair() to synchronize on daemonized startup.
736 * When the container reboots we don't need to synchronize
737 * again currently so don't open another socketpair().
739 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
740 handler
->state_socket_pair
);
742 ERROR("Failed to create anonymous pair of unix sockets");
746 TRACE("Created anonymous pair {%d,%d} of unix sockets",
747 handler
->state_socket_pair
[0],
748 handler
->state_socket_pair
[1]);
751 if (handler
->conf
->reboot
== REBOOT_NONE
) {
752 handler
->conf
->maincmd_fd
= lxc_cmd_init(name
, lxcpath
, "command");
753 if (handler
->conf
->maincmd_fd
< 0) {
754 ERROR("Failed to set up command socket");
759 TRACE("Unix domain socket %d for command server is ready",
760 handler
->conf
->maincmd_fd
);
765 lxc_free_handler(handler
);
770 int lxc_init(const char *name
, struct lxc_handler
*handler
)
772 __do_close_prot_errno
int status_fd
= -EBADF
;
774 const char *loglevel
;
775 struct lxc_conf
*conf
= handler
->conf
;
777 handler
->monitor_pid
= lxc_raw_getpid();
778 status_fd
= open("/proc/self/status", O_RDONLY
| O_CLOEXEC
);
780 SYSERROR("Failed to open monitor status fd");
781 goto out_close_maincmd_fd
;
785 TRACE("Initialized LSM");
787 ret
= lxc_read_seccomp_config(conf
);
789 ERROR("Failed loading seccomp policy");
790 goto out_close_maincmd_fd
;
792 TRACE("Read seccomp policy");
794 /* Begin by setting the state to STARTING. */
795 ret
= lxc_set_state(name
, handler
, STARTING
);
797 ERROR("Failed to set state to \"%s\"", lxc_state2str(STARTING
));
798 goto out_close_maincmd_fd
;
800 TRACE("Set container state to \"STARTING\"");
802 /* Start of environment variable setup for hooks. */
803 ret
= setenv("LXC_NAME", name
, 1);
805 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name
);
808 ret
= setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1);
810 SYSERROR("Failed to set environment variable: "
811 "LXC_CONFIG_FILE=%s", conf
->rcfile
);
814 if (conf
->rootfs
.mount
) {
815 ret
= setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1);
817 SYSERROR("Failed to set environment variable: "
818 "LXC_ROOTFS_MOUNT=%s", conf
->rootfs
.mount
);
821 if (conf
->rootfs
.path
) {
822 ret
= setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1);
824 SYSERROR("Failed to set environment variable: "
825 "LXC_ROOTFS_PATH=%s", conf
->rootfs
.path
);
828 if (conf
->console
.path
) {
829 ret
= setenv("LXC_CONSOLE", conf
->console
.path
, 1);
831 SYSERROR("Failed to set environment variable: "
832 "LXC_CONSOLE=%s", conf
->console
.path
);
835 if (conf
->console
.log_path
) {
836 ret
= setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1);
838 SYSERROR("Failed to set environment variable: "
839 "LXC_CONSOLE_LOGPATH=%s", conf
->console
.log_path
);
842 if (cgns_supported()) {
843 ret
= setenv("LXC_CGNS_AWARE", "1", 1);
845 SYSERROR("Failed to set environment variable "
849 loglevel
= lxc_log_priority_to_string(lxc_log_get_level());
850 ret
= setenv("LXC_LOG_LEVEL", loglevel
, 1);
852 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s",
855 if (conf
->hooks_version
== 0)
856 ret
= setenv("LXC_HOOK_VERSION", "0", 1);
858 ret
= setenv("LXC_HOOK_VERSION", "1", 1);
860 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf
->hooks_version
);
861 /* End of environment variable setup for hooks. */
863 TRACE("Set environment variables");
865 ret
= run_lxc_hooks(name
, "pre-start", conf
, NULL
);
867 ERROR("Failed to run lxc.hook.pre-start for container \"%s\"", name
);
870 TRACE("Ran pre-start hooks");
872 /* The signal fd has to be created before forking otherwise if the child
873 * process exits before we setup the signal fd, the event will be lost
874 * and the command will be stuck.
876 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
877 if (handler
->sigfd
< 0) {
878 ERROR("Failed to setup SIGCHLD fd handler.");
881 TRACE("Set up signal fd");
883 /* Do this after setting up signals since it might unblock SIGWINCH. */
884 ret
= lxc_terminal_setup(conf
);
886 ERROR("Failed to create console");
887 goto out_restore_sigmask
;
889 TRACE("Created console");
891 ret
= lxc_terminal_map_ids(conf
, &conf
->console
);
893 ERROR("Failed to chown console");
894 goto out_delete_terminal
;
896 TRACE("Chowned console");
898 handler
->cgroup_ops
= cgroup_init(handler
->conf
);
899 if (!handler
->cgroup_ops
) {
900 ERROR("Failed to initialize cgroup driver");
901 goto out_delete_terminal
;
903 TRACE("Initialized cgroup driver");
905 ret
= lsm_process_prepare(conf
, handler
->lxcpath
);
907 ERROR("Failed to initialize LSM");
908 goto out_delete_terminal
;
910 TRACE("Initialized LSM");
912 INFO("Container \"%s\" is initialized", name
);
913 handler
->monitor_status_fd
= move_fd(status_fd
);
917 lxc_terminal_delete(&handler
->conf
->console
);
920 (void)pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
923 lxc_delete_tty(&conf
->ttys
);
926 (void)lxc_set_state(name
, handler
, ABORTING
);
928 out_close_maincmd_fd
:
929 lxc_abstract_unix_close(conf
->maincmd_fd
);
930 conf
->maincmd_fd
= -1;
934 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
938 struct lxc_list
*cur
, *next
;
939 char *namespaces
[LXC_NS_MAX
+ 1];
940 size_t namespace_count
= 0;
941 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
943 /* The STOPPING state is there for future cleanup code which can take
946 lxc_set_state(name
, handler
, STOPPING
);
948 self
= lxc_raw_getpid();
949 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
950 if (handler
->nsfd
[i
] < 0)
953 if (handler
->conf
->hooks_version
== 0)
954 ret
= asprintf(&namespaces
[namespace_count
],
955 "%s:/proc/%d/fd/%d", ns_info
[i
].proc_name
,
956 self
, handler
->nsfd
[i
]);
958 ret
= asprintf(&namespaces
[namespace_count
],
959 "/proc/%d/fd/%d", self
, handler
->nsfd
[i
]);
961 SYSERROR("Failed to allocate memory");
965 if (handler
->conf
->hooks_version
== 0) {
970 ret
= setenv(ns_info
[i
].env_name
, namespaces
[namespace_count
], 1);
972 SYSERROR("Failed to set environment variable %s=%s",
973 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
975 TRACE("Set environment variable %s=%s",
976 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
980 namespaces
[namespace_count
] = NULL
;
982 if (handler
->conf
->reboot
> REBOOT_NONE
) {
983 ret
= setenv("LXC_TARGET", "reboot", 1);
985 SYSERROR("Failed to set environment variable: "
986 "LXC_TARGET=reboot");
989 if (handler
->conf
->reboot
== REBOOT_NONE
) {
990 ret
= setenv("LXC_TARGET", "stop", 1);
992 SYSERROR("Failed to set environment variable: "
996 if (handler
->conf
->hooks_version
== 0)
997 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, namespaces
);
999 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, NULL
);
1001 ERROR("Failed to run \"lxc.hook.stop\" hook");
1003 while (namespace_count
--)
1004 free(namespaces
[namespace_count
]);
1006 lsm_process_cleanup(handler
->conf
, handler
->lxcpath
);
1009 cgroup_ops
->payload_destroy(cgroup_ops
, handler
);
1010 cgroup_ops
->monitor_destroy(cgroup_ops
, handler
);
1013 if (handler
->conf
->reboot
== REBOOT_NONE
) {
1014 /* For all new state clients simply close the command socket.
1015 * This will inform all state clients that the container is
1016 * STOPPED and also prevents a race between a open()/close() on
1017 * the command socket causing a new process to get ECONNREFUSED
1018 * because we haven't yet closed the command socket.
1020 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
1021 handler
->conf
->maincmd_fd
= -1;
1022 TRACE("Closed command socket");
1024 /* This function will try to connect to the legacy lxc-monitord
1025 * state server and only exists for backwards compatibility.
1027 lxc_monitor_send_state(name
, STOPPED
, handler
->lxcpath
);
1029 /* The command socket is closed so no one can acces the command
1030 * socket anymore so there's no need to lock it.
1032 handler
->state
= STOPPED
;
1033 TRACE("Set container state to \"STOPPED\"");
1035 lxc_set_state(name
, handler
, STOPPED
);
1038 /* Avoid lingering namespace references. */
1039 lxc_put_nsfds(handler
);
1041 ret
= run_lxc_hooks(name
, "post-stop", handler
->conf
, NULL
);
1043 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name
);
1044 if (handler
->conf
->reboot
> REBOOT_NONE
) {
1045 WARN("Container will be stopped instead of rebooted");
1046 handler
->conf
->reboot
= REBOOT_NONE
;
1048 ret
= setenv("LXC_TARGET", "stop", 1);
1050 WARN("Failed to set environment variable: "
1055 /* Reset mask set by setup_signal_fd. */
1056 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1058 SYSWARN("Failed to restore signal mask");
1060 lxc_terminal_delete(&handler
->conf
->console
);
1061 lxc_delete_tty(&handler
->conf
->ttys
);
1063 /* The command socket is now closed, no more state clients can register
1064 * themselves from now on. So free the list of state clients.
1066 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
1067 struct lxc_state_client
*client
= cur
->elem
;
1069 /* Keep state clients that want to be notified about reboots. */
1070 if ((handler
->conf
->reboot
> REBOOT_NONE
) &&
1071 (client
->states
[RUNNING
] == 2))
1074 /* close state client socket */
1076 close(client
->clientfd
);
1081 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= REBOOT_REQ
)
1082 lxc_destroy_container_on_signal(handler
, name
);
1084 lxc_free_handler(handler
);
1087 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
1092 lxc_set_state(name
, handler
, ABORTING
);
1094 if (handler
->pidfd
>= 0) {
1095 ret
= lxc_raw_pidfd_send_signal(handler
->pidfd
, SIGKILL
, NULL
, 0);
1097 SYSWARN("Failed to send SIGKILL via pidfd %d for process %d",
1098 handler
->pidfd
, handler
->pid
);
1101 if (!ret
|| errno
!= ESRCH
)
1102 if (kill(handler
->pid
, SIGKILL
))
1103 SYSWARN("Failed to send SIGKILL to %d", handler
->pid
);
1106 ret
= waitpid(-1, &status
, 0);
1110 static int do_start(void *data
)
1112 struct lxc_handler
*handler
= data
;
1113 __lxc_unused __do_close_prot_errno
int data_sock0
= handler
->data_sock
[0],
1114 data_sock1
= handler
->data_sock
[1];
1115 __do_close_prot_errno
int status_fd
= -EBADF
;
1119 struct lxc_list
*iterator
;
1122 int devnull_fd
= -1;
1124 lxc_sync_fini_parent(handler
);
1126 if (lxc_abstract_unix_recv_fds(data_sock1
, &status_fd
, 1, NULL
, 0) < 0) {
1127 ERROR("Failed to receive status file descriptor to child process");
1128 goto out_warn_father
;
1131 /* This prctl must be before the synchro, so if the parent dies before
1132 * we set the parent death signal, we will detect its death with the
1133 * synchro right after, otherwise we have a window where the parent can
1134 * exit before we set the pdeath signal leading to a unsupervized
1137 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
, status_fd
);
1139 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1140 goto out_warn_father
;
1143 ret
= lxc_ambient_caps_up();
1145 ERROR("Failed to raise ambient capabilities");
1146 goto out_warn_father
;
1149 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1151 SYSERROR("Failed to set signal mask");
1152 goto out_warn_father
;
1155 /* Don't leak the pinfd to the container. */
1156 if (handler
->pinfd
>= 0)
1157 close(handler
->pinfd
);
1159 ret
= lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
);
1161 goto out_warn_father
;
1163 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1164 * https://github.com/lxc/lxd/issues/1978.
1166 if ((handler
->ns_clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
1167 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
1168 ret
= unshare(CLONE_NEWNET
);
1170 SYSERROR("Failed to unshare CLONE_NEWNET");
1171 goto out_warn_father
;
1173 INFO("Unshared CLONE_NEWNET");
1176 /* Tell the parent task it can begin to configure the container and wait
1179 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
);
1183 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1184 ret
= lxc_network_recv_from_parent(handler
);
1186 ERROR("Failed to receive veth names from parent");
1187 goto out_warn_father
;
1191 /* If we are in a new user namespace, become root there to have
1192 * privilege over our namespace.
1194 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1195 if (!handler
->conf
->root_nsuid_map
)
1196 nsuid
= handler
->conf
->init_uid
;
1198 if (!handler
->conf
->root_nsgid_map
)
1199 nsgid
= handler
->conf
->init_gid
;
1201 if (!lxc_switch_uid_gid(nsuid
, nsgid
))
1202 goto out_warn_father
;
1204 /* Drop groups only after we switched to a valid gid in the new
1207 if (!lxc_setgroups(0, NULL
) &&
1208 (handler
->am_root
|| errno
!= EPERM
))
1209 goto out_warn_father
;
1211 ret
= prctl(PR_SET_DUMPABLE
, prctl_arg(1), prctl_arg(0),
1212 prctl_arg(0), prctl_arg(0));
1214 goto out_warn_father
;
1216 /* set{g,u}id() clears deathsignal */
1217 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
, status_fd
);
1219 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1220 goto out_warn_father
;
1224 ret
= access(handler
->lxcpath
, X_OK
);
1226 print_top_failing_dir(handler
->lxcpath
);
1227 goto out_warn_father
;
1230 /* In order to checkpoint restore, we need to have everything in the
1231 * same mount namespace. However, some containers may not have a
1232 * reasonable /dev (in particular, they may not have /dev/null), so we
1233 * can't set init's std fds to /dev/null by opening it from inside the
1236 * If that's the case, fall back to using the host's /dev/null. This
1237 * means that migration won't work, but at least we won't spew output
1238 * where it isn't wanted.
1240 if (handler
->daemonize
&& !handler
->conf
->autodev
) {
1241 char path
[PATH_MAX
];
1243 ret
= snprintf(path
, sizeof(path
), "%s/dev/null",
1244 handler
->conf
->rootfs
.mount
);
1245 if (ret
< 0 || ret
>= sizeof(path
))
1246 goto out_warn_father
;
1248 ret
= access(path
, F_OK
);
1250 devnull_fd
= open_devnull();
1253 goto out_warn_father
;
1254 WARN("Using /dev/null from the host for container "
1255 "init's standard file descriptors. Migration will "
1260 /* Ask father to setup cgroups and wait for him to finish. */
1261 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
);
1265 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1266 * earlier we end up with a wrong view of /proc/self/cgroup. For
1267 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1268 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1269 * /proc/self/cgroup would show us:
1273 * whereas it should actually show
1277 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1278 ret
= unshare(CLONE_NEWCGROUP
);
1280 if (errno
!= EINVAL
) {
1281 SYSERROR("Failed to unshare CLONE_NEWCGROUP");
1282 goto out_warn_father
;
1285 handler
->ns_clone_flags
&= ~CLONE_NEWCGROUP
;
1286 SYSINFO("Kernel does not support CLONE_NEWCGROUP");
1288 INFO("Unshared CLONE_NEWCGROUP");
1292 /* Add the requested environment variables to the current environment to
1293 * allow them to be used by the various hooks, such as the start hook
1296 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1297 ret
= putenv((char *)iterator
->elem
);
1299 SYSERROR("Failed to set environment variable: %s",
1300 (char *)iterator
->elem
);
1301 goto out_warn_father
;
1305 /* Setup the container, ip, names, utsname, ... */
1306 ret
= lxc_setup(handler
);
1308 ERROR("Failed to setup container \"%s\"", handler
->name
);
1309 goto out_warn_father
;
1312 /* Set the label to change to when we exec(2) the container's init. */
1313 ret
= lsm_process_label_set(NULL
, handler
->conf
, true);
1315 goto out_warn_father
;
1317 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1318 * before we aren't allowed anymore.
1320 if (handler
->conf
->no_new_privs
) {
1321 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
1322 prctl_arg(0), prctl_arg(0));
1324 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block "
1325 "execve() gainable privileges");
1326 goto out_warn_father
;
1328 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable "
1332 /* Some init's such as busybox will set sane tty settings on stdin,
1333 * stdout, stderr which it thinks is the console. We already set them
1334 * the way we wanted on the real terminal, and we want init to do its
1335 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
1336 * make sure that that pty is stdin,stdout,stderr.
1338 if (handler
->conf
->console
.slave
>= 0) {
1339 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
1340 ret
= set_stdfds(handler
->conf
->console
.slave
);
1342 ret
= lxc_terminal_set_stdfds(handler
->conf
->console
.slave
);
1344 ERROR("Failed to redirect std{in,out,err} to pty file "
1345 "descriptor %d", handler
->conf
->console
.slave
);
1346 goto out_warn_father
;
1350 /* If we mounted a temporary proc, then unmount it now. */
1351 tmp_proc_unmount(handler
->conf
);
1353 ret
= lxc_seccomp_load(handler
->conf
);
1355 goto out_warn_father
;
1357 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, data_sock0
);
1359 SYSERROR("Failed to send seccomp notify fd to parent");
1360 goto out_warn_father
;
1363 ret
= run_lxc_hooks(handler
->name
, "start", handler
->conf
, NULL
);
1365 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1367 goto out_warn_father
;
1370 close(handler
->sigfd
);
1372 if (handler
->conf
->console
.slave
< 0 && handler
->daemonize
) {
1373 if (devnull_fd
< 0) {
1374 devnull_fd
= open_devnull();
1376 goto out_warn_father
;
1379 ret
= set_stdfds(devnull_fd
);
1381 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
1382 goto out_warn_father
;
1386 if (devnull_fd
>= 0) {
1393 if (handler
->conf
->init_cwd
) {
1394 ret
= chdir(handler
->conf
->init_cwd
);
1396 SYSERROR("Could not change directory to \"%s\"",
1397 handler
->conf
->init_cwd
);
1398 goto out_warn_father
;
1402 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
);
1404 goto out_warn_father
;
1406 /* Reset the environment variables the user requested in a clear
1410 /* Don't error out though. */
1412 SYSERROR("Failed to clear environment.");
1414 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1415 ret
= putenv((char *)iterator
->elem
);
1417 SYSERROR("Failed to set environment variable: %s",
1418 (char *)iterator
->elem
);
1419 goto out_warn_father
;
1423 ret
= putenv("container=lxc");
1425 SYSERROR("Failed to set environment variable: container=lxc");
1426 goto out_warn_father
;
1429 if (handler
->conf
->ttys
.tty_names
) {
1430 ret
= putenv(handler
->conf
->ttys
.tty_names
);
1432 SYSERROR("Failed to set environment variable for container ptys");
1433 goto out_warn_father
;
1437 /* The container has been setup. We can now switch to an unprivileged
1440 new_uid
= handler
->conf
->init_uid
;
1441 new_gid
= handler
->conf
->init_gid
;
1443 /* Avoid unnecessary syscalls. */
1444 if (new_uid
== nsuid
)
1445 new_uid
= LXC_INVALID_UID
;
1447 if (new_gid
== nsgid
)
1448 new_gid
= LXC_INVALID_GID
;
1450 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
1451 goto out_warn_father
;
1453 /* If we are in a new user namespace we already dropped all groups when
1454 * we switched to root in the new user namespace further above. Only
1455 * drop groups if we can, so ensure that we have necessary privilege.
1457 if (lxc_list_empty(&handler
->conf
->id_map
))
1459 if (lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
))
1461 if (!lxc_setgroups(0, NULL
))
1462 goto out_warn_father
;
1464 ret
= lxc_ambient_caps_down();
1466 ERROR("Failed to clear ambient capabilities");
1467 goto out_warn_father
;
1470 if (handler
->conf
->monitor_signal_pdeath
!= SIGKILL
) {
1471 ret
= lxc_set_death_signal(handler
->conf
->monitor_signal_pdeath
,
1472 handler
->monitor_pid
, status_fd
);
1474 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1475 handler
->conf
->monitor_signal_pdeath
);
1476 goto out_warn_father
;
1480 /* After this call, we are in error because this ops should not return
1483 handler
->ops
->start(handler
, handler
->data
);
1486 /* We want the parent to know something went wrong, so we return a
1487 * special error code.
1489 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1492 if (devnull_fd
>= 0)
1498 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1501 struct lxc_terminal_info
*tty
;
1503 int sock
= handler
->data_sock
[1];
1504 struct lxc_conf
*conf
= handler
->conf
;
1505 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1507 if (!conf
->ttys
.max
)
1510 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
1514 for (i
= 0; i
< conf
->ttys
.max
; i
++) {
1517 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1521 tty
= &ttys
->tty
[i
];
1523 tty
->master
= ttyfds
[0];
1524 tty
->slave
= ttyfds
[1];
1525 TRACE("Received pty with master fd %d and slave fd %d from "
1526 "child", tty
->master
, tty
->slave
);
1530 SYSERROR("Failed to receive %zu ttys from child", ttys
->max
);
1532 TRACE("Received %zu ttys from child", ttys
->max
);
1537 int resolve_clone_flags(struct lxc_handler
*handler
)
1540 struct lxc_conf
*conf
= handler
->conf
;
1542 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1543 if (conf
->ns_keep
) {
1544 if (!(conf
->ns_keep
& ns_info
[i
].clone_flag
))
1545 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1546 } else if (conf
->ns_clone
) {
1547 if ((conf
->ns_clone
& ns_info
[i
].clone_flag
))
1548 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1550 if (i
== LXC_NS_USER
&& lxc_list_empty(&handler
->conf
->id_map
))
1553 if (i
== LXC_NS_NET
&& lxc_requests_empty_network(handler
))
1556 if (i
== LXC_NS_CGROUP
&& !cgns_supported())
1559 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1562 if (!conf
->ns_share
[i
])
1565 handler
->ns_clone_flags
&= ~ns_info
[i
].clone_flag
;
1566 TRACE("Sharing %s namespace", ns_info
[i
].proc_name
);
1572 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1573 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1574 * But since the memory between parent and child is shared on CLONE_VM this
1575 * would invalidate the getpid() cache that glibc used to maintain and so
1576 * getpid() in the child would return the parent's pid. This is all fixed in
1577 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1578 * not reset anymore.
1579 * However, if for whatever reason you - dear committer - somehow need to get the
1580 * pid of the dummy intermediate process for do_share_ns() you need to call
1581 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1584 static inline int do_share_ns(void *arg
)
1587 struct lxc_handler
*handler
= arg
;
1589 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1590 if (handler
->nsfd
[i
] < 0)
1593 ret
= setns(handler
->nsfd
[i
], 0);
1596 * Note that joining a user and/or mount namespace
1597 * requires the process is not multithreaded otherwise
1598 * setns() will fail here.
1600 SYSERROR("Failed to inherit %s namespace",
1601 ns_info
[i
].proc_name
);
1605 DEBUG("Inherited %s namespace", ns_info
[i
].proc_name
);
1608 flags
= handler
->ns_on_clone_flags
;
1609 flags
|= CLONE_PARENT
;
1610 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, CLONE_PIDFD
| flags
,
1612 if (handler
->pid
< 0)
1618 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1619 * exec()s the requested container binary.
1620 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1621 * right here should be double checked if they'd pose a security risk. (For
1622 * example, any {u}mount() operations performed here will be reflected on the
1625 static int lxc_spawn(struct lxc_handler
*handler
)
1627 __do_close_prot_errno
int data_sock0
= -EBADF
, data_sock1
= -EBADF
;
1630 bool wants_to_map_ids
;
1631 struct lxc_list
*id_map
;
1632 const char *name
= handler
->name
;
1633 const char *lxcpath
= handler
->lxcpath
;
1634 bool share_ns
= false;
1635 struct lxc_conf
*conf
= handler
->conf
;
1636 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
1638 id_map
= &conf
->id_map
;
1639 wants_to_map_ids
= !lxc_list_empty(id_map
);
1641 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1642 if (!conf
->ns_share
[i
])
1645 handler
->nsfd
[i
] = lxc_inherit_namespace(conf
->ns_share
[i
], lxcpath
, ns_info
[i
].proc_name
);
1646 if (handler
->nsfd
[i
] < 0)
1652 ret
= lxc_sync_init(handler
);
1656 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1657 handler
->data_sock
);
1660 data_sock0
= handler
->data_sock
[0];
1661 data_sock1
= handler
->data_sock
[1];
1663 ret
= resolve_clone_flags(handler
);
1667 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1668 ret
= lxc_find_gateway_addresses(handler
);
1670 ERROR("Failed to find gateway addresses");
1675 if (!cgroup_ops
->payload_create(cgroup_ops
, handler
)) {
1676 ERROR("Failed creating cgroups");
1677 goto out_delete_net
;
1680 /* If the rootfs is not a blockdev, prevent the container from marking
1682 * If the container is unprivileged then skip rootfs pinning.
1684 if (!wants_to_map_ids
) {
1685 handler
->pinfd
= pin_rootfs(conf
->rootfs
.path
);
1686 if (handler
->pinfd
== -1)
1687 INFO("Failed to pin the rootfs for container \"%s\"", handler
->name
);
1690 /* Create a process in a new set of namespaces. */
1691 handler
->ns_on_clone_flags
= handler
->ns_clone_flags
;
1692 if (handler
->ns_clone_flags
& CLONE_NEWUSER
) {
1693 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1694 * clone a new user namespace first and only later unshare our
1695 * network namespace to ensure that network devices ownership is
1698 handler
->ns_on_clone_flags
&= ~CLONE_NEWNET
;
1700 /* The cgroup namespace gets unshare()ed not clone()ed. */
1701 handler
->ns_on_clone_flags
&= ~CLONE_NEWCGROUP
;
1706 attacher_pid
= lxc_clone(do_share_ns
, handler
,
1707 CLONE_VFORK
| CLONE_VM
| CLONE_FILES
, NULL
);
1708 if (attacher_pid
< 0) {
1709 SYSERROR(LXC_CLONE_ERROR
);
1710 goto out_delete_net
;
1713 ret
= wait_for_pid(attacher_pid
);
1715 SYSERROR("Intermediate process failed");
1716 goto out_delete_net
;
1719 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
,
1720 CLONE_PIDFD
| handler
->ns_on_clone_flags
,
1723 if (handler
->pid
< 0) {
1724 SYSERROR(LXC_CLONE_ERROR
);
1725 goto out_delete_net
;
1727 TRACE("Cloned child process %d", handler
->pid
);
1729 ret
= snprintf(pidstr
, 20, "%d", handler
->pid
);
1730 if (ret
< 0 || ret
>= 20)
1731 goto out_delete_net
;
1733 ret
= setenv("LXC_PID", pidstr
, 1);
1735 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr
);
1737 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1738 if (handler
->ns_on_clone_flags
& ns_info
[i
].clone_flag
)
1739 INFO("Cloned %s", ns_info
[i
].flag_name
);
1741 if (!lxc_try_preserve_namespaces(handler
, handler
->ns_on_clone_flags
, handler
->pid
)) {
1742 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1743 goto out_delete_net
;
1746 lxc_sync_fini_child(handler
);
1748 if (lxc_abstract_unix_send_fds(handler
->data_sock
[0], &handler
->monitor_status_fd
, 1, NULL
, 0) < 0) {
1749 ERROR("Failed to send status file descriptor to child process");
1750 goto out_delete_net
;
1752 close_prot_errno_disarm(handler
->monitor_status_fd
);
1754 /* Map the container uids. The container became an invalid userid the
1755 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1756 * anything immediately, but allows the container to setuid(0) (0 being
1757 * mapped to something else on the host.) later to become a valid uid
1760 if (wants_to_map_ids
) {
1761 if (!handler
->conf
->ns_share
[LXC_NS_USER
] &&
1762 (handler
->conf
->ns_keep
& CLONE_NEWUSER
) == 0) {
1763 ret
= lxc_map_ids(id_map
, handler
->pid
);
1765 ERROR("Failed to set up id mapping.");
1766 goto out_delete_net
;
1771 ret
= lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
);
1773 goto out_delete_net
;
1775 ret
= lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
);
1777 goto out_delete_net
;
1779 if (!cgroup_ops
->setup_limits_legacy(cgroup_ops
, handler
->conf
, false)) {
1780 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1781 goto out_delete_net
;
1784 if (!cgroup_ops
->payload_enter(cgroup_ops
, handler
)) {
1785 goto out_delete_net
;
1788 if (!cgroup_ops
->payload_delegate_controllers(cgroup_ops
)) {
1789 ERROR("Failed to delegate controllers to payload cgroup");
1790 goto out_delete_net
;
1793 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
)) {
1794 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1795 goto out_delete_net
;
1798 if (!cgroup_ops
->chown(cgroup_ops
, handler
->conf
))
1799 goto out_delete_net
;
1801 /* If not done yet, we're now ready to preserve the network namespace */
1802 if (handler
->nsfd
[LXC_NS_NET
] < 0) {
1803 ret
= lxc_try_preserve_ns(handler
->pid
, "net");
1805 if (ret
!= -EOPNOTSUPP
) {
1806 SYSERROR("Failed to preserve net namespace");
1807 goto out_delete_net
;
1810 handler
->nsfd
[LXC_NS_NET
] = ret
;
1811 DEBUG("Preserved net namespace via fd %d", ret
);
1814 ret
= lxc_netns_set_nsid(handler
->nsfd
[LXC_NS_NET
]);
1816 SYSWARN("Failed to allocate new network namespace id");
1818 TRACE("Allocated new network namespace id");
1820 /* Create the network configuration. */
1821 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1822 ret
= lxc_create_network(handler
);
1824 ERROR("Failed to create the network");
1825 goto out_delete_net
;
1828 ret
= lxc_network_send_to_child(handler
);
1830 ERROR("Failed to send veth names to child");
1831 goto out_delete_net
;
1835 if (!lxc_list_empty(&conf
->procs
)) {
1836 ret
= setup_proc_filesystem(&conf
->procs
, handler
->pid
);
1838 goto out_delete_net
;
1841 /* Tell the child to continue its initialization. We'll get
1842 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1844 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
);
1846 goto out_delete_net
;
1848 if (!lxc_list_empty(&conf
->limits
)) {
1849 ret
= setup_resource_limits(&conf
->limits
, handler
->pid
);
1851 ERROR("Failed to setup resource limits");
1852 goto out_delete_net
;
1856 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
);
1858 goto out_delete_net
;
1860 if (!cgroup_ops
->setup_limits_legacy(cgroup_ops
, handler
->conf
, true)) {
1861 ERROR("Failed to setup legacy device cgroup controller limits");
1862 goto out_delete_net
;
1864 TRACE("Set up legacy device cgroup controller limits");
1866 if (!cgroup_ops
->devices_activate(cgroup_ops
, handler
)) {
1867 ERROR("Failed to setup cgroup2 device controller limits");
1868 goto out_delete_net
;
1870 TRACE("Set up cgroup2 device controller limits");
1872 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1873 /* Now we're ready to preserve the cgroup namespace */
1874 ret
= lxc_try_preserve_ns(handler
->pid
, "cgroup");
1876 if (ret
!= -EOPNOTSUPP
) {
1877 SYSERROR("Failed to preserve cgroup namespace");
1878 goto out_delete_net
;
1881 handler
->nsfd
[LXC_NS_CGROUP
] = ret
;
1882 DEBUG("Preserved cgroup namespace via fd %d", ret
);
1886 cgroup_ops
->payload_finalize(cgroup_ops
);
1887 TRACE("Finished setting up cgroups");
1889 /* Run any host-side start hooks */
1890 ret
= run_lxc_hooks(name
, "start-host", conf
, NULL
);
1892 ERROR("Failed to run lxc.hook.start-host");
1893 goto out_delete_net
;
1896 /* Tell the child to complete its initialization and wait for it to exec
1897 * or return an error. (The child will never return
1898 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1899 * lxc_sync_barrier_child to return success, or return a different
1900 * value, causing us to error out).
1902 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_READY_START
);
1904 goto out_delete_net
;
1906 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1907 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
1909 ERROR("Failed to receive names and ifindices for network devices from child");
1910 goto out_delete_net
;
1914 /* Now all networks are created, network devices are moved into place,
1915 * and the correct names and ifindices in the respective namespaces have
1916 * been recorded. The corresponding structs have now all been filled. So
1917 * log them for debugging purposes.
1919 lxc_log_configured_netdevs(conf
);
1921 /* Read tty fds allocated by child. */
1922 ret
= lxc_recv_ttys_from_child(handler
);
1924 ERROR("Failed to receive tty info from child process");
1925 goto out_delete_net
;
1928 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, data_sock1
);
1930 SYSERROR("Failed to receive seccomp notify fd from child");
1931 goto out_delete_net
;
1934 ret
= handler
->ops
->post_start(handler
, handler
->data
);
1938 ret
= lxc_set_state(name
, handler
, RUNNING
);
1940 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING
));
1944 lxc_sync_fini(handler
);
1949 if (handler
->ns_clone_flags
& CLONE_NEWNET
)
1950 lxc_delete_network(handler
);
1953 lxc_abort(name
, handler
);
1956 lxc_sync_fini(handler
);
1957 if (handler
->pinfd
>= 0) {
1958 close(handler
->pinfd
);
1959 handler
->pinfd
= -1;
1965 int __lxc_start(const char *name
, struct lxc_handler
*handler
,
1966 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1967 bool daemonize
, int *error_num
)
1970 struct lxc_conf
*conf
= handler
->conf
;
1971 struct cgroup_ops
*cgroup_ops
;
1973 ret
= lxc_init(name
, handler
);
1975 ERROR("Failed to initialize container \"%s\"", name
);
1976 goto out_fini_nonet
;
1979 handler
->data
= data
;
1980 handler
->daemonize
= daemonize
;
1981 cgroup_ops
= handler
->cgroup_ops
;
1983 if (!attach_block_device(handler
->conf
)) {
1984 ERROR("Failed to attach block device");
1986 goto out_fini_nonet
;
1989 if (!cgroup_ops
->monitor_create(cgroup_ops
, handler
)) {
1990 ERROR("Failed to create monitor cgroup");
1992 goto out_fini_nonet
;
1995 if (!cgroup_ops
->monitor_enter(cgroup_ops
, handler
)) {
1996 ERROR("Failed to enter monitor cgroup");
1998 goto out_fini_nonet
;
2001 if (!cgroup_ops
->monitor_delegate_controllers(cgroup_ops
)) {
2002 ERROR("Failed to delegate controllers to monitor cgroup");
2004 goto out_fini_nonet
;
2007 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
2008 /* If the backing store is a device, mount it here and now. */
2009 if (rootfs_is_blockdev(conf
)) {
2010 ret
= unshare(CLONE_NEWNS
);
2012 ERROR("Failed to unshare CLONE_NEWNS");
2013 goto out_fini_nonet
;
2015 INFO("Unshared CLONE_NEWNS");
2017 remount_all_slave();
2018 ret
= lxc_setup_rootfs_prepare_root(conf
, name
, lxcpath
);
2020 ERROR("Error setting up rootfs mount as root before spawn");
2021 goto out_fini_nonet
;
2023 INFO("Set up container rootfs as host root");
2027 ret
= lxc_spawn(handler
);
2029 ERROR("Failed to spawn container \"%s\"", name
);
2030 goto out_detach_blockdev
;
2033 handler
->conf
->reboot
= REBOOT_NONE
;
2035 ret
= lxc_poll(name
, handler
);
2037 ERROR("LXC mainloop exited with error: %d", ret
);
2041 if (!handler
->init_died
&& handler
->pid
> 0) {
2042 ERROR("Child process is not killed");
2047 status
= lxc_wait_for_pid_status(handler
->pid
);
2049 SYSERROR("Failed to retrieve status for %d", handler
->pid
);
2051 /* If the child process exited but was not signaled, it didn't call
2052 * reboot. This should mean it was an lxc-execute which simply exited.
2053 * In any case, treat it as a 'halt'.
2055 if (WIFSIGNALED(status
)) {
2056 switch(WTERMSIG(status
)) {
2057 case SIGINT
: /* halt */
2058 DEBUG("Container \"%s\" is halting", name
);
2060 case SIGHUP
: /* reboot */
2061 DEBUG("Container \"%s\" is rebooting", name
);
2062 handler
->conf
->reboot
= REBOOT_REQ
;
2064 case SIGSYS
: /* seccomp */
2065 DEBUG("Container \"%s\" violated its seccomp policy", name
);
2068 DEBUG("Unknown exit status for container \"%s\" init %d", name
, WTERMSIG(status
));
2073 ret
= lxc_restore_phys_nics_to_netns(handler
);
2075 ERROR("Failed to move physical network devices back to parent "
2076 "network namespace");
2078 if (handler
->pinfd
>= 0) {
2079 close(handler
->pinfd
);
2080 handler
->pinfd
= -1;
2083 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
2084 lxc_error_set_and_log(handler
->pid
, status
);
2086 *error_num
= handler
->exit_status
;
2089 lxc_delete_network(handler
);
2091 out_detach_blockdev
:
2092 detach_block_device(handler
->conf
);
2095 lxc_fini(name
, handler
);
2099 lxc_abort(name
, handler
);
2107 static int start(struct lxc_handler
*handler
, void* data
)
2109 struct start_args
*arg
= data
;
2111 NOTICE("Exec'ing \"%s\"", arg
->argv
[0]);
2113 execvp(arg
->argv
[0], arg
->argv
);
2114 SYSERROR("Failed to exec \"%s\"", arg
->argv
[0]);
2118 static int post_start(struct lxc_handler
*handler
, void* data
)
2120 struct start_args
*arg
= data
;
2122 NOTICE("Started \"%s\" with pid \"%d\"", arg
->argv
[0], handler
->pid
);
2126 static struct lxc_operations start_ops
= {
2128 .post_start
= post_start
2131 int lxc_start(const char *name
, char *const argv
[], struct lxc_handler
*handler
,
2132 const char *lxcpath
, bool daemonize
, int *error_num
)
2134 struct start_args start_arg
= {
2138 TRACE("Doing lxc_start");
2139 return __lxc_start(name
, handler
, &start_ops
, &start_arg
, lxcpath
, daemonize
, error_num
);
2142 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
2145 char destroy
[PATH_MAX
];
2146 struct lxc_container
*c
;
2150 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
2151 bret
= do_destroy_container(handler
);
2153 ERROR("Error destroying rootfs for container \"%s\"", name
);
2157 INFO("Destroyed rootfs for container \"%s\"", name
);
2159 ret
= snprintf(destroy
, PATH_MAX
, "%s/%s", handler
->lxcpath
, name
);
2160 if (ret
< 0 || ret
>= PATH_MAX
) {
2161 ERROR("Error destroying directory for container \"%s\"", name
);
2165 c
= lxc_container_new(name
, handler
->lxcpath
);
2167 if (container_disk_lock(c
)) {
2168 INFO("Could not update lxc_snapshots file");
2169 lxc_container_put(c
);
2171 mod_all_rdeps(c
, false);
2172 container_disk_unlock(c
);
2173 lxc_container_put(c
);
2177 if (!handler
->am_root
)
2178 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
2179 destroy
, "lxc_rmdir_onedev_wrapper");
2181 ret
= lxc_rmdir_onedev(destroy
, NULL
);
2184 ERROR("Error destroying directory for container \"%s\"", name
);
2187 INFO("Destroyed directory for container \"%s\"", name
);
2190 static int lxc_rmdir_onedev_wrapper(void *data
)
2192 char *arg
= (char *) data
;
2193 return lxc_rmdir_onedev(arg
, NULL
);
2196 static bool do_destroy_container(struct lxc_handler
*handler
)
2200 if (!handler
->am_root
) {
2201 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
2202 handler
->conf
, "storage_destroy_wrapper");
2209 return storage_destroy(handler
->conf
);