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>
30 #include "cgroups/cgroup.h"
31 #include "cgroups/cgroup_utils.h"
33 #include "commands_utils.h"
37 #include "confile_utils.h"
39 #include "file_utils.h"
43 #include "lxccontainer.h"
45 #include "lxcseccomp.h"
48 #include "memory_utils.h"
50 #include "namespace.h"
52 #include "process_utils.h"
54 #include "storage/storage.h"
55 #include "storage/storage_utils.h"
57 #include "syscall_wrappers.h"
62 #include <sys/capability.h>
66 #include "include/strlcpy.h"
69 lxc_log_define(start
, lxc
);
71 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
72 static bool do_destroy_container(struct lxc_handler
*handler
);
73 static int lxc_rmdir_onedev_wrapper(void *data
);
74 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
77 static void print_top_failing_dir(const char *path
)
79 __do_free
char *copy
= NULL
;
83 copy
= must_copy_string(path
);
85 e
= copy
+ strlen(path
);
88 while (p
< e
&& *p
== '/')
91 while (p
< e
&& *p
!= '/')
97 ret
= access(copy
, X_OK
);
99 SYSERROR("Could not access %s. Please grant it x access, or add an ACL for the container " "root", copy
);
106 static void lxc_put_nsfds(struct lxc_handler
*handler
)
108 for (int i
= 0; i
< LXC_NS_MAX
; i
++) {
109 if (handler
->nsfd
[i
] < 0)
112 close_prot_errno_disarm(handler
->nsfd
[i
]);
116 static int lxc_try_preserve_namespace(struct lxc_handler
*handler
,
117 lxc_namespace_t idx
, const char *ns
)
119 __do_close
int fd
= -EBADF
;
122 fd
= lxc_preserve_ns(handler
->pid
, ns
);
126 ret
= strnprintf(handler
->nsfd_paths
[idx
],
127 sizeof(handler
->nsfd_paths
[idx
]), "%s:/proc/%d/fd/%d",
128 ns_info
[idx
].proc_name
, handler
->monitor_pid
, fd
);
130 return ret_errno(EIO
);
133 * In case LXC is configured for exposing information to hooks as
134 * argv-style arguments prepare an argv array we can use.
136 handler
->hook_argv
[handler
->hook_argc
] = handler
->nsfd_paths
[idx
];
137 handler
->hook_argc
++;
139 DEBUG("Preserved %s namespace via fd %d and stashed path as %s",
140 ns_info
[idx
].proc_name
, fd
, handler
->nsfd_paths
[idx
]);
142 handler
->nsfd
[idx
] = move_fd(fd
);
146 /* lxc_try_preserve_namespaces: open /proc/@pid/ns/@ns for each namespace
147 * specified in ns_clone_flags.
148 * Return true on success, false on failure.
150 static bool lxc_try_preserve_namespaces(struct lxc_handler
*handler
,
153 for (lxc_namespace_t ns_idx
= 0; ns_idx
< LXC_NS_MAX
; ns_idx
++)
154 handler
->nsfd
[ns_idx
] = -EBADF
;
156 for (lxc_namespace_t ns_idx
= 0; ns_idx
< LXC_NS_MAX
; ns_idx
++) {
158 const char *ns
= ns_info
[ns_idx
].proc_name
;
160 if ((ns_clone_flags
& ns_info
[ns_idx
].clone_flag
) == 0)
163 ret
= lxc_try_preserve_namespace(handler
, ns_idx
,
164 ns_info
[ns_idx
].proc_name
);
166 if (ret
== -ENOENT
) {
167 SYSERROR("Kernel does not support preserving %s namespaces", ns
);
172 * Handle kernels that do not support interacting with
173 * namespaces through procfs.
175 lxc_put_nsfds(handler
);
176 return log_error_errno(false, errno
, "Failed to preserve %s namespace", ns
);
183 static inline bool match_stdfds(int fd
)
185 return (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
);
189 static bool match_dlog_fds(struct dirent
*direntp
)
191 char path
[PATH_MAX
] = {0};
192 char link
[PATH_MAX
] = {0};
196 ret
= strnprintf(path
, sizeof(path
), "/proc/self/fd/%s", direntp
->d_name
);
198 return log_error(false, "Failed to create file descriptor name");
200 linklen
= readlink(path
, link
, PATH_MAX
);
202 return log_error(false, "Failed to read link path - \"%s\"", path
);
203 else if (linklen
>= PATH_MAX
)
204 return log_error(false, "The name of link path is too long - \"%s\"", path
);
206 if (strequal(link
, "/dev/log_main") ||
207 strequal(link
, "/dev/log_system") ||
208 strequal(link
, "/dev/log_radio"))
215 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
216 int *fds_to_ignore
, size_t len_fds
)
221 struct dirent
*direntp
;
223 if (conf
&& conf
->close_all_fds
)
227 * Disable syslog at this point to avoid the above logging
228 * function to open a new fd and make the check_inherited function
229 * enter an infinite loop.
231 lxc_log_syslog_disable();
234 dir
= opendir("/proc/self/fd");
236 return log_warn(-1, "Failed to open directory");
240 while ((direntp
= readdir(dir
))) {
242 struct lxc_list
*cur
;
243 bool matched
= false;
245 if (strequal(direntp
->d_name
, "."))
248 if (strequal(direntp
->d_name
, ".."))
251 ret
= lxc_safe_int(direntp
->d_name
, &fd
);
253 INFO("Could not parse file descriptor for \"%s\"", direntp
->d_name
);
257 for (i
= 0; i
< len_fds
; i
++)
258 if (fds_to_ignore
[i
] == fd
)
261 if (fd
== fddir
|| fd
== lxc_log_fd
||
262 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
265 /* Keep state clients that wait on reboots. */
267 lxc_list_for_each(cur
, &conf
->state_clients
) {
268 struct lxc_state_client
*client
= cur
->elem
;
270 if (client
->clientfd
!= fd
)
281 if (current_config
&& fd
== current_config
->logfd
)
284 if (match_stdfds(fd
))
288 if (match_dlog_fds(direntp
))
294 SYSINFO("Closed inherited fd %d", fd
);
296 INFO("Closed inherited fd %d", fd
);
300 WARN("Inherited fd %d", fd
);
305 * Only enable syslog at this point to avoid the above logging
306 * function to open a new fd and make the check_inherited function
307 * enter an infinite loop.
309 lxc_log_syslog_enable();
314 static int setup_signal_fd(sigset_t
*oldmask
)
318 const int signals
[] = {SIGBUS
, SIGILL
, SIGSEGV
, SIGWINCH
};
320 /* Block everything except serious error signals. */
321 ret
= sigfillset(&mask
);
325 for (int sig
= 0; sig
< (sizeof(signals
) / sizeof(signals
[0])); sig
++) {
326 ret
= sigdelset(&mask
, signals
[sig
]);
331 ret
= pthread_sigmask(SIG_BLOCK
, &mask
, oldmask
);
333 return log_error_errno(-EBADF
, errno
,
334 "Failed to set signal mask");
336 ret
= signalfd(-1, &mask
, SFD_CLOEXEC
);
338 return log_error_errno(-EBADF
,
339 errno
, "Failed to create signal file descriptor");
341 TRACE("Created signal file descriptor %d", ret
);
346 static int signal_handler(int fd
, uint32_t events
, void *data
,
347 struct lxc_epoll_descr
*descr
)
351 struct signalfd_siginfo siginfo
;
352 struct lxc_handler
*hdlr
= data
;
354 ret
= lxc_read_nointr(fd
, &siginfo
, sizeof(siginfo
));
356 return log_error(LXC_MAINLOOP_ERROR
, "Failed to read signal info from signal file descriptor %d", fd
);
358 if (ret
!= sizeof(siginfo
))
359 return log_error(LXC_MAINLOOP_ERROR
, "Unexpected size for struct signalfd_siginfo");
361 /* Check whether init is running. */
363 ret
= waitid(P_PID
, hdlr
->pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
364 if (ret
== 0 && info
.si_pid
== hdlr
->pid
)
365 hdlr
->init_died
= true;
367 /* Try to figure out a reasonable exit status to report. */
368 if (hdlr
->init_died
) {
369 switch (info
.si_code
) {
371 hdlr
->exit_status
= info
.si_status
<< 8;
376 hdlr
->exit_status
= info
.si_status
<< 8 | 0x7f;
379 /* Huh? The waitid() told us it's dead *and* continued? */
380 WARN("Init %d dead and continued?", hdlr
->pid
);
381 hdlr
->exit_status
= 1;
384 ERROR("Unknown si_code: %d", info
.si_code
);
385 hdlr
->exit_status
= 1;
389 if (siginfo
.ssi_signo
== SIGHUP
) {
390 if (hdlr
->pidfd
>= 0)
391 lxc_raw_pidfd_send_signal(hdlr
->pidfd
, SIGTERM
, NULL
, 0);
393 kill(hdlr
->pid
, SIGTERM
);
394 INFO("Killing %d since terminal hung up", hdlr
->pid
);
395 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
396 : LXC_MAINLOOP_CONTINUE
;
399 if (siginfo
.ssi_signo
!= SIGCHLD
) {
400 if (hdlr
->pidfd
>= 0)
401 lxc_raw_pidfd_send_signal(hdlr
->pidfd
,
402 siginfo
.ssi_signo
, NULL
, 0);
404 kill(hdlr
->pid
, siginfo
.ssi_signo
);
405 INFO("Forwarded signal %d to pid %d", siginfo
.ssi_signo
, hdlr
->pid
);
406 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
407 : LXC_MAINLOOP_CONTINUE
;
410 /* More robustness, protect ourself from a SIGCHLD sent
411 * by a process different from the container init.
413 if (siginfo
.ssi_pid
!= hdlr
->pid
) {
414 NOTICE("Received %d from pid %d instead of container init %d",
415 siginfo
.ssi_signo
, siginfo
.ssi_pid
, hdlr
->pid
);
416 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
417 : LXC_MAINLOOP_CONTINUE
;
420 if (siginfo
.ssi_code
== CLD_STOPPED
) {
421 INFO("Container init process was stopped");
422 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
423 : LXC_MAINLOOP_CONTINUE
;
426 if (siginfo
.ssi_code
== CLD_CONTINUED
) {
427 INFO("Container init process was continued");
428 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
429 : LXC_MAINLOOP_CONTINUE
;
432 return log_debug(LXC_MAINLOOP_CLOSE
, "Container init process %d exited", hdlr
->pid
);
435 int lxc_serve_state_clients(const char *name
, struct lxc_handler
*handler
,
440 struct lxc_list
*cur
, *next
;
441 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
444 handler
->state
= RUNNING
;
446 handler
->state
= state
;
448 TRACE("Set container state to %s", lxc_state2str(state
));
450 if (lxc_list_empty(&handler
->conf
->state_clients
))
451 return log_trace(0, "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_prot_errno_disarm(handler
->state_socket_pair
[0]);
498 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
499 &(int){state
}, sizeof(int));
501 SYSERROR("Failed to send state to %d", handler
->state_socket_pair
[1]);
509 if (ret
!= sizeof(int))
510 return log_error(-1, "Message too long : %d", handler
->state_socket_pair
[1]);
512 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
513 handler
->state_socket_pair
[1]);
515 /* Close write end of the socket pair. */
516 close_prot_errno_disarm(handler
->state_socket_pair
[1]);
521 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
526 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
528 return log_error(-1, "Failed to synchronize via anonymous pair of unix sockets");
530 ret
= lxc_serve_state_clients(name
, handler
, state
);
534 /* This function will try to connect to the legacy lxc-monitord state
535 * server and only exists for backwards compatibility.
537 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
542 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
545 bool has_console
= true;
546 struct lxc_epoll_descr descr
, descr_console
;
548 if (handler
->conf
->console
.path
&&
549 strequal(handler
->conf
->console
.path
, "none"))
552 ret
= lxc_mainloop_open(&descr
);
554 ERROR("Failed to create mainloop");
559 ret
= lxc_mainloop_open(&descr_console
);
561 ERROR("Failed to create console mainloop");
566 ret
= lxc_mainloop_add_handler(&descr
, handler
->sigfd
, signal_handler
, handler
);
568 ERROR("Failed to add signal handler for %d to mainloop", handler
->sigfd
);
569 goto out_mainloop_console
;
572 ret
= lxc_seccomp_setup_proxy(&handler
->conf
->seccomp
, &descr
, handler
);
574 ERROR("Failed to setup seccomp proxy");
575 goto out_mainloop_console
;
579 struct lxc_terminal
*console
= &handler
->conf
->console
;
581 ret
= lxc_terminal_mainloop_add(&descr
, console
);
583 ERROR("Failed to add console handlers to mainloop");
584 goto out_mainloop_console
;
587 ret
= lxc_terminal_mainloop_add(&descr_console
, console
);
589 ERROR("Failed to add console handlers to console mainloop");
590 goto out_mainloop_console
;
593 handler
->conf
->console
.descr
= &descr
;
596 ret
= lxc_cmd_mainloop_add(name
, &descr
, handler
);
598 ERROR("Failed to add command handler to mainloop");
599 goto out_mainloop_console
;
602 TRACE("Mainloop is ready");
604 ret
= lxc_mainloop(&descr
, -1);
605 close_prot_errno_disarm(descr
.epfd
);
606 if (ret
< 0 || !handler
->init_died
)
607 goto out_mainloop_console
;
610 ret
= lxc_mainloop(&descr_console
, 0);
612 out_mainloop_console
:
614 lxc_mainloop_close(&descr_console
);
615 TRACE("Closed console mainloop");
619 lxc_mainloop_close(&descr
);
620 TRACE("Closed mainloop");
623 TRACE("Closed signal file descriptor %d", handler
->sigfd
);
624 close_prot_errno_disarm(handler
->sigfd
);
629 void lxc_put_handler(struct lxc_handler
*handler
)
631 close_prot_errno_disarm(handler
->pidfd
);
632 close_prot_errno_disarm(handler
->sigfd
);
633 lxc_put_nsfds(handler
);
634 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
635 close_prot_errno_disarm(handler
->conf
->maincmd_fd
);
636 close_prot_errno_disarm(handler
->monitor_status_fd
);
637 close_prot_errno_disarm(handler
->state_socket_pair
[0]);
638 close_prot_errno_disarm(handler
->state_socket_pair
[1]);
639 cgroup_exit(handler
->cgroup_ops
);
640 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
641 free_disarm(handler
);
643 handler
->conf
= NULL
;
646 struct lxc_handler
*lxc_init_handler(struct lxc_handler
*old
,
647 const char *name
, struct lxc_conf
*conf
,
648 const char *lxcpath
, bool daemonize
)
652 struct lxc_handler
*handler
;
655 handler
= zalloc(sizeof(*handler
));
661 /* Note that am_guest_unpriv() checks the effective uid. We
662 * probably don't care if we are real root only if we are running
663 * as root so this should be fine.
665 handler
->am_root
= !am_guest_unpriv();
666 handler
->conf
= conf
;
667 handler
->lxcpath
= lxcpath
;
668 handler
->init_died
= false;
669 handler
->data_sock
[0] = -EBADF
;
670 handler
->data_sock
[1] = -EBADF
;
671 handler
->monitor_status_fd
= -EBADF
;
672 handler
->pidfd
= -EBADF
;
673 handler
->sigfd
= -EBADF
;
674 handler
->state_socket_pair
[0] = -EBADF
;
675 handler
->state_socket_pair
[1] = -EBADF
;
676 if (handler
->conf
->reboot
== REBOOT_NONE
)
677 lxc_list_init(&handler
->conf
->state_clients
);
679 for (lxc_namespace_t idx
= 0; idx
< LXC_NS_MAX
; idx
++) {
680 handler
->nsfd
[idx
] = -EBADF
;
682 if (handler
->conf
->reboot
== REBOOT_NONE
)
685 handler
->nsfd_paths
[idx
][0] = '\0';
686 handler
->hook_argv
[idx
] = NULL
;
688 if (handler
->hook_argc
!= 0)
689 handler
->hook_argc
= 0;
692 handler
->name
= name
;
694 handler
->transient_pid
= lxc_raw_getpid();
696 handler
->transient_pid
= -1;
698 if (daemonize
&& handler
->conf
->reboot
== REBOOT_NONE
) {
699 /* Create socketpair() to synchronize on daemonized startup.
700 * When the container reboots we don't need to synchronize
701 * again currently so don't open another socketpair().
703 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
704 handler
->state_socket_pair
);
706 ERROR("Failed to create anonymous pair of unix sockets");
710 TRACE("Created anonymous pair {%d,%d} of unix sockets",
711 handler
->state_socket_pair
[0],
712 handler
->state_socket_pair
[1]);
713 handler
->keep_fds
[nr_keep_fds
++] = handler
->state_socket_pair
[0];
714 handler
->keep_fds
[nr_keep_fds
++] = handler
->state_socket_pair
[1];
717 if (handler
->conf
->reboot
== REBOOT_NONE
) {
718 handler
->conf
->maincmd_fd
= lxc_cmd_init(name
, lxcpath
, "command");
719 if (handler
->conf
->maincmd_fd
< 0) {
720 ERROR("Failed to set up command socket");
723 handler
->keep_fds
[nr_keep_fds
++] = handler
->conf
->maincmd_fd
;
726 TRACE("Unix domain socket %d for command server is ready",
727 handler
->conf
->maincmd_fd
);
732 lxc_put_handler(handler
);
737 int lxc_init(const char *name
, struct lxc_handler
*handler
)
739 __do_close
int status_fd
= -EBADF
;
741 const char *loglevel
;
742 struct lxc_conf
*conf
= handler
->conf
;
744 handler
->monitor_pid
= lxc_raw_getpid();
745 status_fd
= open("/proc/self/status", O_RDONLY
| O_CLOEXEC
);
747 return log_error_errno(-1, errno
, "Failed to open monitor status fd");
749 handler
->lsm_ops
= lsm_init_static();
750 TRACE("Initialized LSM");
752 /* Begin by setting the state to STARTING. */
753 ret
= lxc_set_state(name
, handler
, STARTING
);
755 return log_error(-1, "Failed to set state to \"%s\"", lxc_state2str(STARTING
));
756 TRACE("Set container state to \"STARTING\"");
758 /* Start of environment variable setup for hooks. */
759 ret
= setenv("LXC_NAME", name
, 1);
761 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name
);
764 ret
= setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1);
766 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s", conf
->rcfile
);
769 if (conf
->rootfs
.mount
) {
770 ret
= setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1);
772 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s", conf
->rootfs
.mount
);
775 if (conf
->rootfs
.path
) {
776 ret
= setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1);
778 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s", conf
->rootfs
.path
);
781 if (conf
->console
.path
) {
782 ret
= setenv("LXC_CONSOLE", conf
->console
.path
, 1);
784 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s", conf
->console
.path
);
787 if (conf
->console
.log_path
) {
788 ret
= setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1);
790 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s", conf
->console
.log_path
);
793 if (cgns_supported()) {
794 ret
= setenv("LXC_CGNS_AWARE", "1", 1);
796 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1");
799 loglevel
= lxc_log_priority_to_string(lxc_log_get_level());
800 ret
= setenv("LXC_LOG_LEVEL", loglevel
, 1);
802 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s", loglevel
);
804 if (conf
->hooks_version
== 0)
805 ret
= setenv("LXC_HOOK_VERSION", "0", 1);
807 ret
= setenv("LXC_HOOK_VERSION", "1", 1);
809 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf
->hooks_version
);
810 /* End of environment variable setup for hooks. */
812 TRACE("Set environment variables");
814 ret
= run_lxc_hooks(name
, "pre-start", conf
, NULL
);
816 return log_error(-1, "Failed to run lxc.hook.pre-start for container \"%s\"", name
);
817 TRACE("Ran pre-start hooks");
819 /* The signal fd has to be created before forking otherwise if the child
820 * process exits before we setup the signal fd, the event will be lost
821 * and the command will be stuck.
823 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
824 if (handler
->sigfd
< 0)
825 return log_error(-1, "Failed to setup SIGCHLD fd handler.");
826 TRACE("Set up signal fd");
828 /* Do this after setting up signals since it might unblock SIGWINCH. */
829 ret
= lxc_terminal_setup(conf
);
831 ERROR("Failed to create console");
832 goto out_restore_sigmask
;
834 TRACE("Created console");
836 handler
->cgroup_ops
= cgroup_init(handler
->conf
);
837 if (!handler
->cgroup_ops
) {
838 ERROR("Failed to initialize cgroup driver");
839 goto out_delete_terminal
;
841 TRACE("Initialized cgroup driver");
843 ret
= lxc_read_seccomp_config(conf
);
845 return log_error(-1, "Failed loading seccomp policy");
846 TRACE("Read seccomp policy");
848 ret
= handler
->lsm_ops
->prepare(handler
->lsm_ops
, conf
, handler
->lxcpath
);
850 ERROR("Failed to initialize LSM");
851 goto out_delete_terminal
;
853 TRACE("Initialized LSM");
855 INFO("Container \"%s\" is initialized", name
);
856 handler
->monitor_status_fd
= move_fd(status_fd
);
860 lxc_terminal_delete(&handler
->conf
->console
);
863 (void)pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
868 void lxc_expose_namespace_environment(const struct lxc_handler
*handler
)
870 for (lxc_namespace_t i
= 0; i
< LXC_NS_MAX
; i
++) {
874 if (handler
->nsfd
[i
] < 0)
877 fd_path
= handler
->nsfd_paths
[i
] + strcspn(handler
->nsfd_paths
[i
], "/");
878 ret
= setenv(ns_info
[i
].env_name
, fd_path
, 1);
880 SYSERROR("Failed to set environment variable %s=%s",
881 ns_info
[i
].env_name
, fd_path
);
883 TRACE("Set environment variable %s=%s",
884 ns_info
[i
].env_name
, fd_path
);
888 void lxc_end(struct lxc_handler
*handler
)
891 struct lxc_list
*cur
, *next
;
892 const char *name
= handler
->name
;
893 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
895 /* The STOPPING state is there for future cleanup code which can take
898 lxc_set_state(name
, handler
, STOPPING
);
900 /* Passing information to hooks via environment variables. */
901 if (handler
->conf
->hooks_version
> 0)
902 lxc_expose_namespace_environment(handler
);
904 if (handler
->conf
->reboot
> REBOOT_NONE
) {
905 ret
= setenv("LXC_TARGET", "reboot", 1);
907 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot");
910 if (handler
->conf
->reboot
== REBOOT_NONE
) {
911 ret
= setenv("LXC_TARGET", "stop", 1);
913 SYSERROR("Failed to set environment variable: LXC_TARGET=stop");
916 if (handler
->conf
->hooks_version
== 0)
917 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, handler
->hook_argv
);
919 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, NULL
);
921 ERROR("Failed to run \"lxc.hook.stop\" hook");
923 handler
->lsm_ops
->cleanup(handler
->lsm_ops
, handler
->conf
, handler
->lxcpath
);
926 cgroup_ops
->payload_destroy(cgroup_ops
, handler
);
927 cgroup_ops
->monitor_destroy(cgroup_ops
, handler
);
930 put_lxc_rootfs(&handler
->conf
->rootfs
, true);
932 if (handler
->conf
->reboot
== REBOOT_NONE
) {
933 /* For all new state clients simply close the command socket.
934 * This will inform all state clients that the container is
935 * STOPPED and also prevents a race between a open()/close() on
936 * the command socket causing a new process to get ECONNREFUSED
937 * because we haven't yet closed the command socket.
939 close_prot_errno_disarm(handler
->conf
->maincmd_fd
);
940 TRACE("Closed command socket");
942 /* This function will try to connect to the legacy lxc-monitord
943 * state server and only exists for backwards compatibility.
945 lxc_monitor_send_state(name
, STOPPED
, handler
->lxcpath
);
947 /* The command socket is closed so no one can acces the command
948 * socket anymore so there's no need to lock it.
950 handler
->state
= STOPPED
;
951 TRACE("Set container state to \"STOPPED\"");
953 lxc_set_state(name
, handler
, STOPPED
);
954 TRACE("Set container state to \"STOPPED\"");
957 /* Avoid lingering namespace references. */
958 lxc_put_nsfds(handler
);
960 ret
= run_lxc_hooks(name
, "post-stop", handler
->conf
, NULL
);
962 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name
);
963 if (handler
->conf
->reboot
> REBOOT_NONE
) {
964 WARN("Container will be stopped instead of rebooted");
965 handler
->conf
->reboot
= REBOOT_NONE
;
967 ret
= setenv("LXC_TARGET", "stop", 1);
969 WARN("Failed to set environment variable: LXC_TARGET=stop");
973 /* Reset mask set by setup_signal_fd. */
974 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
976 SYSWARN("Failed to restore signal mask");
978 lxc_terminal_delete(&handler
->conf
->console
);
979 lxc_delete_tty(&handler
->conf
->ttys
);
980 close_prot_errno_disarm(handler
->conf
->devpts_fd
);
982 /* The command socket is now closed, no more state clients can register
983 * themselves from now on. So free the list of state clients.
985 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
986 struct lxc_state_client
*client
= cur
->elem
;
988 /* Keep state clients that want to be notified about reboots. */
989 if ((handler
->conf
->reboot
> REBOOT_NONE
) &&
990 (client
->states
[RUNNING
] == 2))
993 /* close state client socket */
995 close(client
->clientfd
);
1000 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= REBOOT_REQ
)
1001 lxc_destroy_container_on_signal(handler
, name
);
1003 lxc_put_handler(handler
);
1006 void lxc_abort(struct lxc_handler
*handler
)
1011 lxc_set_state(handler
->name
, handler
, ABORTING
);
1013 if (handler
->pidfd
>= 0) {
1014 ret
= lxc_raw_pidfd_send_signal(handler
->pidfd
, SIGKILL
, NULL
, 0);
1016 SYSWARN("Failed to send SIGKILL via pidfd %d for process %d",
1017 handler
->pidfd
, handler
->pid
);
1020 if ((!ret
|| errno
!= ESRCH
) && handler
->pid
> 0)
1021 if (kill(handler
->pid
, SIGKILL
))
1022 SYSWARN("Failed to send SIGKILL to %d", handler
->pid
);
1025 ret
= waitpid(-1, &status
, 0);
1029 static int do_start(void *data
)
1031 struct lxc_handler
*handler
= data
;
1032 __lxc_unused __do_close
int data_sock0
= handler
->data_sock
[0],
1033 data_sock1
= handler
->data_sock
[1];
1034 __do_close
int devnull_fd
= -EBADF
, status_fd
= -EBADF
;
1038 struct lxc_list
*iterator
;
1042 lxc_sync_fini_parent(handler
);
1044 if (lxc_abstract_unix_recv_one_fd(data_sock1
, &status_fd
, NULL
, 0) < 0) {
1045 ERROR("Failed to receive status file descriptor to child process");
1046 goto out_warn_father
;
1049 /* This prctl must be before the synchro, so if the parent dies before
1050 * we set the parent death signal, we will detect its death with the
1051 * synchro right after, otherwise we have a window where the parent can
1052 * exit before we set the pdeath signal leading to a unsupervized
1055 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
, status_fd
);
1057 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1058 goto out_warn_father
;
1061 ret
= lxc_ambient_caps_up();
1063 ERROR("Failed to raise ambient capabilities");
1064 goto out_warn_father
;
1067 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1069 SYSERROR("Failed to set signal mask");
1070 goto out_warn_father
;
1073 if (!lxc_sync_wait_parent(handler
, START_SYNC_STARTUP
))
1074 goto out_warn_father
;
1076 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1077 * https://github.com/lxc/lxd/issues/1978.
1079 if (handler
->ns_unshare_flags
& CLONE_NEWNET
) {
1080 ret
= unshare(CLONE_NEWNET
);
1082 SYSERROR("Failed to unshare CLONE_NEWNET");
1083 goto out_warn_father
;
1085 INFO("Unshared CLONE_NEWNET");
1088 /* Tell the parent task it can begin to configure the container and wait
1091 if (!lxc_sync_barrier_parent(handler
, START_SYNC_CONFIGURE
))
1094 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1095 ret
= lxc_network_recv_from_parent(handler
);
1097 ERROR("Failed to receive veth names from parent");
1098 goto out_warn_father
;
1102 /* If we are in a new user namespace, become root there to have
1103 * privilege over our namespace.
1105 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1106 if (!handler
->conf
->root_nsuid_map
)
1107 nsuid
= handler
->conf
->init_uid
;
1109 if (!handler
->conf
->root_nsgid_map
)
1110 nsgid
= handler
->conf
->init_gid
;
1112 /* Drop groups only after we switched to a valid gid in the new
1115 if (!lxc_drop_groups() &&
1116 (handler
->am_root
|| errno
!= EPERM
))
1117 goto out_warn_father
;
1119 if (!lxc_switch_uid_gid(nsuid
, nsgid
))
1120 goto out_warn_father
;
1122 ret
= prctl(PR_SET_DUMPABLE
, prctl_arg(1), prctl_arg(0),
1123 prctl_arg(0), prctl_arg(0));
1125 goto out_warn_father
;
1127 /* set{g,u}id() clears deathsignal */
1128 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
, status_fd
);
1130 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1131 goto out_warn_father
;
1135 ret
= access(handler
->lxcpath
, X_OK
);
1137 print_top_failing_dir(handler
->lxcpath
);
1138 goto out_warn_father
;
1141 /* In order to checkpoint restore, we need to have everything in the
1142 * same mount namespace. However, some containers may not have a
1143 * reasonable /dev (in particular, they may not have /dev/null), so we
1144 * can't set init's std fds to /dev/null by opening it from inside the
1147 * If that's the case, fall back to using the host's /dev/null. This
1148 * means that migration won't work, but at least we won't spew output
1149 * where it isn't wanted.
1151 if (handler
->daemonize
&& !handler
->conf
->autodev
) {
1152 char path
[PATH_MAX
];
1154 ret
= strnprintf(path
, sizeof(path
), "%s/dev/null",
1155 handler
->conf
->rootfs
.mount
);
1157 goto out_warn_father
;
1159 ret
= access(path
, F_OK
);
1161 devnull_fd
= open_devnull();
1164 goto out_warn_father
;
1165 WARN("Using /dev/null from the host for container init's standard file descriptors. Migration will not work");
1169 /* Ask father to setup cgroups and wait for him to finish. */
1170 if (!lxc_sync_barrier_parent(handler
, START_SYNC_CGROUP
))
1173 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1174 * earlier we end up with a wrong view of /proc/self/cgroup. For
1175 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1176 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1177 * /proc/self/cgroup would show us:
1181 * whereas it should actually show
1185 if (handler
->ns_unshare_flags
& CLONE_NEWCGROUP
) {
1186 ret
= unshare(CLONE_NEWCGROUP
);
1188 if (errno
!= EINVAL
) {
1189 SYSERROR("Failed to unshare CLONE_NEWCGROUP");
1190 goto out_warn_father
;
1193 handler
->ns_clone_flags
&= ~CLONE_NEWCGROUP
;
1194 SYSINFO("Kernel does not support CLONE_NEWCGROUP");
1196 INFO("Unshared CLONE_NEWCGROUP");
1200 if (handler
->ns_unshare_flags
& CLONE_NEWTIME
) {
1201 ret
= unshare(CLONE_NEWTIME
);
1203 if (errno
!= EINVAL
) {
1204 SYSERROR("Failed to unshare CLONE_NEWTIME");
1205 goto out_warn_father
;
1208 handler
->ns_clone_flags
&= ~CLONE_NEWTIME
;
1209 SYSINFO("Kernel does not support CLONE_NEWTIME");
1211 __do_close
int timens_fd
= -EBADF
;
1213 INFO("Unshared CLONE_NEWTIME");
1215 if (handler
->conf
->timens
.s_boot
)
1216 ret
= timens_offset_write(CLOCK_BOOTTIME
, handler
->conf
->timens
.s_boot
, 0);
1217 else if (handler
->conf
->timens
.ns_boot
)
1218 ret
= timens_offset_write(CLOCK_BOOTTIME
, 0, handler
->conf
->timens
.ns_boot
);
1220 SYSERROR("Failed to write CLONE_BOOTTIME offset");
1221 goto out_warn_father
;
1223 TRACE("Wrote CLOCK_BOOTTIME offset");
1225 if (handler
->conf
->timens
.s_monotonic
)
1226 ret
= timens_offset_write(CLOCK_MONOTONIC
, handler
->conf
->timens
.s_monotonic
, 0);
1227 else if (handler
->conf
->timens
.ns_monotonic
)
1228 ret
= timens_offset_write(CLOCK_MONOTONIC
, 0, handler
->conf
->timens
.ns_monotonic
);
1230 SYSERROR("Failed to write CLONE_MONOTONIC offset");
1231 goto out_warn_father
;
1233 TRACE("Wrote CLOCK_MONOTONIC offset");
1235 timens_fd
= open("/proc/self/ns/time_for_children", O_RDONLY
| O_CLOEXEC
);
1236 if (timens_fd
< 0) {
1237 SYSERROR("Failed to open \"/proc/self/ns/time_for_children\"");
1238 goto out_warn_father
;
1241 ret
= setns(timens_fd
, CLONE_NEWTIME
);
1243 SYSERROR("Failed to setns(%d(\"/proc/self/ns/time_for_children\"))", timens_fd
);
1244 goto out_warn_father
;
1249 /* Add the requested environment variables to the current environment to
1250 * allow them to be used by the various hooks, such as the start hook
1253 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1254 ret
= putenv((char *)iterator
->elem
);
1256 SYSERROR("Failed to set environment variable: %s",
1257 (char *)iterator
->elem
);
1258 goto out_warn_father
;
1262 /* Setup the container, ip, names, utsname, ... */
1263 ret
= lxc_setup(handler
);
1265 ERROR("Failed to setup container \"%s\"", handler
->name
);
1266 goto out_warn_father
;
1269 /* Set the label to change to when we exec(2) the container's init. */
1270 ret
= handler
->lsm_ops
->process_label_set(handler
->lsm_ops
, NULL
, handler
->conf
, true);
1272 goto out_warn_father
;
1274 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1275 * before we aren't allowed anymore.
1277 if (handler
->conf
->no_new_privs
) {
1278 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
1279 prctl_arg(0), prctl_arg(0));
1281 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges");
1282 goto out_warn_father
;
1284 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges");
1287 /* If we mounted a temporary proc, then unmount it now. */
1288 tmp_proc_unmount(handler
->conf
);
1290 ret
= lxc_seccomp_load(handler
->conf
);
1292 goto out_warn_father
;
1294 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, data_sock0
);
1296 SYSERROR("Failed to send seccomp notify fd to parent");
1297 goto out_warn_father
;
1300 ret
= run_lxc_hooks(handler
->name
, "start", handler
->conf
, NULL
);
1302 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1304 goto out_warn_father
;
1307 close_prot_errno_disarm(handler
->sigfd
);
1309 if (handler
->conf
->console
.pty
< 0 && handler
->daemonize
) {
1310 if (devnull_fd
< 0) {
1311 devnull_fd
= open_devnull();
1313 goto out_warn_father
;
1316 ret
= set_stdfds(devnull_fd
);
1318 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
1319 goto out_warn_father
;
1323 close_prot_errno_disarm(devnull_fd
);
1327 if (handler
->conf
->init_cwd
) {
1328 ret
= chdir(handler
->conf
->init_cwd
);
1330 SYSERROR("Could not change directory to \"%s\"",
1331 handler
->conf
->init_cwd
);
1332 goto out_warn_father
;
1336 if (!lxc_sync_barrier_parent(handler
, START_SYNC_CGROUP_LIMITS
))
1337 goto out_warn_father
;
1339 /* Reset the environment variables the user requested in a clear
1343 /* Don't error out though. */
1345 SYSERROR("Failed to clear environment.");
1347 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1348 ret
= putenv((char *)iterator
->elem
);
1350 SYSERROR("Failed to set environment variable: %s",
1351 (char *)iterator
->elem
);
1352 goto out_warn_father
;
1356 ret
= putenv("container=lxc");
1358 SYSERROR("Failed to set environment variable: container=lxc");
1359 goto out_warn_father
;
1362 if (handler
->conf
->ttys
.tty_names
) {
1363 ret
= putenv(handler
->conf
->ttys
.tty_names
);
1365 SYSERROR("Failed to set environment variable for container ptys");
1366 goto out_warn_father
;
1370 /* The container has been setup. We can now switch to an unprivileged
1373 new_uid
= handler
->conf
->init_uid
;
1374 new_gid
= handler
->conf
->init_gid
;
1376 /* Avoid unnecessary syscalls. */
1377 if (new_uid
== nsuid
)
1378 new_uid
= LXC_INVALID_UID
;
1380 if (new_gid
== nsgid
)
1381 new_gid
= LXC_INVALID_GID
;
1383 /* Make sure that the processes STDIO is correctly owned by the user that we are switching to */
1384 ret
= fix_stdio_permissions(new_uid
);
1386 WARN("Failed to ajust stdio permissions");
1388 /* If we are in a new user namespace we already dropped all groups when
1389 * we switched to root in the new user namespace further above. Only
1390 * drop groups if we can, so ensure that we have necessary privilege.
1392 if (lxc_list_empty(&handler
->conf
->id_map
)) {
1394 if (lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
))
1397 if (handler
->conf
->init_groups
.size
> 0) {
1398 if (!lxc_setgroups(handler
->conf
->init_groups
.list
,
1399 handler
->conf
->init_groups
.size
))
1400 goto out_warn_father
;
1402 if (!lxc_drop_groups())
1403 goto out_warn_father
;
1408 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
1409 goto out_warn_father
;
1411 ret
= lxc_ambient_caps_down();
1413 ERROR("Failed to clear ambient capabilities");
1414 goto out_warn_father
;
1417 if (handler
->conf
->monitor_signal_pdeath
!= SIGKILL
) {
1418 ret
= lxc_set_death_signal(handler
->conf
->monitor_signal_pdeath
,
1419 handler
->monitor_pid
, status_fd
);
1421 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1422 handler
->conf
->monitor_signal_pdeath
);
1423 goto out_warn_father
;
1428 * After this call, we are in error because this ops should not return
1431 handler
->ops
->start(handler
, handler
->data
);
1435 * We want the parent to know something went wrong, so we return a
1436 * special error code.
1438 lxc_sync_wake_parent(handler
, SYNC_ERROR
);
1444 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1447 struct lxc_terminal_info
*tty
;
1449 int sock
= handler
->data_sock
[1];
1450 struct lxc_conf
*conf
= handler
->conf
;
1451 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1453 if (!conf
->ttys
.max
)
1456 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
1460 for (i
= 0; i
< conf
->ttys
.max
; i
++) {
1463 ret
= lxc_abstract_unix_recv_two_fds(sock
, ttyfds
);
1467 tty
= &ttys
->tty
[i
];
1469 tty
->ptx
= ttyfds
[0];
1470 tty
->pty
= ttyfds
[1];
1471 TRACE("Received pty with ptx fd %d and pty fd %d from child", tty
->ptx
, tty
->pty
);
1475 SYSERROR("Failed to receive %zu ttys from child", ttys
->max
);
1477 TRACE("Received %zu ttys from child", ttys
->max
);
1482 int resolve_clone_flags(struct lxc_handler
*handler
)
1485 struct lxc_conf
*conf
= handler
->conf
;
1486 bool wants_timens
= conf
->timens
.s_boot
|| conf
->timens
.ns_boot
||
1487 conf
->timens
.s_monotonic
|| conf
->timens
.ns_monotonic
;
1489 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1490 if (conf
->ns_keep
) {
1491 if (!(conf
->ns_keep
& ns_info
[i
].clone_flag
))
1492 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1493 } else if (conf
->ns_clone
) {
1494 if ((conf
->ns_clone
& ns_info
[i
].clone_flag
))
1495 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1497 if (i
== LXC_NS_USER
&& lxc_list_empty(&handler
->conf
->id_map
))
1500 if (i
== LXC_NS_NET
&& lxc_requests_empty_network(handler
))
1503 if (i
== LXC_NS_CGROUP
&& !cgns_supported())
1506 if (i
== LXC_NS_TIME
&& !wants_timens
)
1509 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1512 if (!conf
->ns_share
[i
])
1515 handler
->ns_clone_flags
&= ~ns_info
[i
].clone_flag
;
1516 TRACE("Sharing %s namespace", ns_info
[i
].proc_name
);
1519 if (wants_timens
&& (conf
->ns_keep
& ns_info
[LXC_NS_TIME
].clone_flag
))
1520 return log_trace_errno(-1, EINVAL
, "Requested to keep time namespace while also specifying offsets");
1522 /* Deal with namespaces that are unshared. */
1523 if (handler
->ns_clone_flags
& CLONE_NEWTIME
)
1524 handler
->ns_unshare_flags
|= CLONE_NEWTIME
;
1526 if (!pure_unified_layout(handler
->cgroup_ops
) && handler
->ns_clone_flags
& CLONE_NEWCGROUP
)
1527 handler
->ns_unshare_flags
|= CLONE_NEWCGROUP
;
1529 if ((handler
->ns_clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
1530 (CLONE_NEWNET
| CLONE_NEWUSER
))
1531 handler
->ns_unshare_flags
|= CLONE_NEWNET
;
1533 /* Deal with namespaces that are spawned. */
1534 handler
->ns_on_clone_flags
= handler
->ns_clone_flags
& ~handler
->ns_unshare_flags
;
1536 handler
->clone_flags
= handler
->ns_on_clone_flags
| CLONE_PIDFD
;
1541 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1542 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1543 * But since the memory between parent and child is shared on CLONE_VM this
1544 * would invalidate the getpid() cache that glibc used to maintain and so
1545 * getpid() in the child would return the parent's pid. This is all fixed in
1546 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1547 * not reset anymore.
1548 * However, if for whatever reason you - dear committer - somehow need to get the
1549 * pid of the dummy intermediate process for do_share_ns() you need to call
1550 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1553 static inline int do_share_ns(void *arg
)
1556 struct lxc_handler
*handler
= arg
;
1558 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1559 if (handler
->nsfd
[i
] < 0)
1562 ret
= setns(handler
->nsfd
[i
], 0);
1565 * Note that joining a user and/or mount namespace
1566 * requires the process is not multithreaded otherwise
1567 * setns() will fail here.
1569 SYSERROR("Failed to inherit %s namespace",
1570 ns_info
[i
].proc_name
);
1574 DEBUG("Inherited %s namespace", ns_info
[i
].proc_name
);
1577 flags
= handler
->ns_on_clone_flags
;
1578 flags
|= CLONE_PARENT
;
1579 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, CLONE_PIDFD
| flags
,
1581 if (handler
->pid
< 0)
1587 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1588 * exec()s the requested container binary.
1589 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1590 * right here should be double checked if they'd pose a security risk. (For
1591 * example, any {u}mount() operations performed here will be reflected on the
1594 static int lxc_spawn(struct lxc_handler
*handler
)
1596 __do_close
int data_sock0
= -EBADF
, data_sock1
= -EBADF
;
1599 bool wants_to_map_ids
;
1600 struct lxc_list
*id_map
;
1601 const char *name
= handler
->name
;
1602 const char *lxcpath
= handler
->lxcpath
;
1603 bool share_ns
= false;
1604 struct lxc_conf
*conf
= handler
->conf
;
1605 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
1607 id_map
= &conf
->id_map
;
1608 wants_to_map_ids
= !lxc_list_empty(id_map
);
1610 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1611 if (!conf
->ns_share
[i
])
1614 handler
->nsfd
[i
] = lxc_inherit_namespace(conf
->ns_share
[i
], lxcpath
, ns_info
[i
].proc_name
);
1615 if (handler
->nsfd
[i
] < 0)
1621 if (!lxc_sync_init(handler
))
1624 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1625 handler
->data_sock
);
1628 data_sock0
= handler
->data_sock
[0];
1629 data_sock1
= handler
->data_sock
[1];
1631 ret
= resolve_clone_flags(handler
);
1635 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1636 ret
= lxc_find_gateway_addresses(handler
);
1638 ERROR("Failed to find gateway addresses");
1643 if (!cgroup_ops
->payload_create(cgroup_ops
, handler
)) {
1644 ERROR("Failed creating cgroups");
1645 goto out_delete_net
;
1648 /* If the rootfs is not a blockdev, prevent the container from marking
1650 * If the container is unprivileged then skip rootfs pinning.
1652 ret
= lxc_rootfs_prepare(&conf
->rootfs
, wants_to_map_ids
);
1654 ERROR("Failed to handle rootfs pinning for container \"%s\"", handler
->name
);
1655 goto out_delete_net
;
1658 /* Create a process in a new set of namespaces. */
1662 attacher_pid
= lxc_clone(do_share_ns
, handler
,
1663 CLONE_VFORK
| CLONE_VM
| CLONE_FILES
, NULL
);
1664 if (attacher_pid
< 0) {
1665 SYSERROR(LXC_CLONE_ERROR
);
1666 goto out_delete_net
;
1669 ret
= wait_for_pid(attacher_pid
);
1671 SYSERROR("Intermediate process failed");
1672 goto out_delete_net
;
1675 if (handler
->pid
< 0) {
1676 SYSERROR(LXC_CLONE_ERROR
);
1677 goto out_delete_net
;
1680 int cgroup_fd
= -EBADF
;
1682 struct lxc_clone_args clone_args
= {
1683 .flags
= handler
->clone_flags
,
1684 .pidfd
= ptr_to_u64(&handler
->pidfd
),
1685 .exit_signal
= SIGCHLD
,
1688 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1689 cgroup_fd
= cgroup_unified_fd(cgroup_ops
);
1690 if (cgroup_fd
>= 0) {
1691 handler
->clone_flags
|= CLONE_INTO_CGROUP
;
1692 clone_args
.flags
|= CLONE_INTO_CGROUP
;
1693 clone_args
.cgroup
= cgroup_fd
;
1697 /* Try to spawn directly into target cgroup. */
1698 handler
->pid
= lxc_clone3(&clone_args
, CLONE_ARGS_SIZE_VER2
);
1699 if (handler
->pid
< 0) {
1700 SYSTRACE("Failed to spawn container directly into target cgroup");
1702 /* Kernel might simply be too old for CLONE_INTO_CGROUP. */
1703 handler
->clone_flags
&= ~(CLONE_INTO_CGROUP
| CLONE_NEWCGROUP
);
1704 handler
->ns_on_clone_flags
&= ~CLONE_NEWCGROUP
;
1705 handler
->ns_unshare_flags
|= CLONE_NEWCGROUP
;
1707 clone_args
.flags
= handler
->clone_flags
;
1709 handler
->pid
= lxc_clone3(&clone_args
, CLONE_ARGS_SIZE_VER0
);
1710 } else if (cgroup_fd
>= 0) {
1711 TRACE("Spawned container directly into target cgroup via cgroup2 fd %d", cgroup_fd
);
1714 /* Kernel might be too old for clone3(). */
1715 if (handler
->pid
< 0) {
1716 SYSTRACE("Failed to spawn container via clone3()");
1717 handler
->pid
= lxc_raw_legacy_clone(handler
->clone_flags
, &handler
->pidfd
);
1720 if (handler
->pid
< 0) {
1721 SYSERROR(LXC_CLONE_ERROR
);
1722 goto out_delete_net
;
1725 if (handler
->pid
== 0) {
1726 (void)do_start(handler
);
1727 _exit(EXIT_FAILURE
);
1730 if (handler
->pidfd
< 0)
1731 handler
->clone_flags
&= ~CLONE_PIDFD
;
1732 TRACE("Cloned child process %d", handler
->pid
);
1734 /* Verify that we can actually make use of pidfds. */
1735 if (!lxc_can_use_pidfd(handler
->pidfd
))
1736 close_prot_errno_disarm(handler
->pidfd
);
1738 ret
= strnprintf(pidstr
, 20, "%d", handler
->pid
);
1740 goto out_delete_net
;
1742 ret
= setenv("LXC_PID", pidstr
, 1);
1744 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr
);
1746 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1747 if (handler
->ns_on_clone_flags
& ns_info
[i
].clone_flag
)
1748 INFO("Cloned %s", ns_info
[i
].flag_name
);
1750 if (!lxc_try_preserve_namespaces(handler
, handler
->ns_on_clone_flags
)) {
1751 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1752 goto out_delete_net
;
1755 lxc_sync_fini_child(handler
);
1757 if (lxc_abstract_unix_send_fds(handler
->data_sock
[0], &handler
->monitor_status_fd
, 1, NULL
, 0) < 0) {
1758 ERROR("Failed to send status file descriptor to child process");
1759 goto out_delete_net
;
1761 close_prot_errno_disarm(handler
->monitor_status_fd
);
1763 /* Map the container uids. The container became an invalid userid the
1764 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1765 * anything immediately, but allows the container to setuid(0) (0 being
1766 * mapped to something else on the host.) later to become a valid uid
1769 if (wants_to_map_ids
) {
1770 if (!handler
->conf
->ns_share
[LXC_NS_USER
] &&
1771 (handler
->conf
->ns_keep
& CLONE_NEWUSER
) == 0) {
1772 ret
= lxc_map_ids(id_map
, handler
->pid
);
1774 ERROR("Failed to set up id mapping.");
1775 goto out_delete_net
;
1780 if (!lxc_sync_wake_child(handler
, START_SYNC_STARTUP
))
1781 goto out_delete_net
;
1783 if (!lxc_sync_wait_child(handler
, START_SYNC_CONFIGURE
))
1784 goto out_delete_net
;
1786 if (!cgroup_ops
->setup_limits_legacy(cgroup_ops
, handler
->conf
, false)) {
1787 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1788 goto out_delete_net
;
1791 if (!cgroup_ops
->payload_delegate_controllers(cgroup_ops
)) {
1792 ERROR("Failed to delegate controllers to payload cgroup");
1793 goto out_delete_net
;
1796 if (!cgroup_ops
->payload_enter(cgroup_ops
, handler
)) {
1797 ERROR("Failed to enter cgroups");
1798 goto out_delete_net
;
1801 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
)) {
1802 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1803 goto out_delete_net
;
1806 if (!cgroup_ops
->chown(cgroup_ops
, handler
->conf
))
1807 goto out_delete_net
;
1809 /* If not done yet, we're now ready to preserve the network namespace */
1810 if (handler
->nsfd
[LXC_NS_NET
] < 0) {
1811 ret
= lxc_try_preserve_namespace(handler
, LXC_NS_NET
, "net");
1813 if (ret
!= -ENOENT
) {
1814 SYSERROR("Failed to preserve net namespace");
1815 goto out_delete_net
;
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_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 * START_SYNC_CGROUP when it is ready for us to setup cgroups.
1849 if (!lxc_sync_barrier_child(handler
, START_SYNC_POST_CONFIGURE
))
1850 goto out_delete_net
;
1852 if (!lxc_list_empty(&conf
->limits
)) {
1853 ret
= setup_resource_limits(&conf
->limits
, handler
->pid
);
1855 ERROR("Failed to setup resource limits");
1856 goto out_delete_net
;
1860 if (!lxc_sync_barrier_child(handler
, START_SYNC_CGROUP_UNSHARE
))
1861 goto out_delete_net
;
1864 * With isolation the limiting devices cgroup was already setup, so
1865 * only setup devices here if we have no namespace directory.
1867 if (!handler
->conf
->cgroup_meta
.namespace_dir
&&
1868 !cgroup_ops
->setup_limits_legacy(cgroup_ops
, handler
->conf
, true)) {
1869 ERROR("Failed to setup legacy device cgroup controller limits");
1870 goto out_delete_net
;
1872 TRACE("Set up legacy device cgroup controller limits");
1874 if (!cgroup_ops
->devices_activate(cgroup_ops
, handler
)) {
1875 ERROR("Failed to setup cgroup2 device controller limits");
1876 goto out_delete_net
;
1878 TRACE("Set up cgroup2 device controller limits");
1880 if (handler
->ns_unshare_flags
& CLONE_NEWCGROUP
) {
1881 /* Now we're ready to preserve the cgroup namespace */
1882 ret
= lxc_try_preserve_namespace(handler
, LXC_NS_CGROUP
, "cgroup");
1884 if (ret
!= -ENOENT
) {
1885 SYSERROR("Failed to preserve cgroup namespace");
1886 goto out_delete_net
;
1891 cgroup_ops
->finalize(cgroup_ops
);
1892 TRACE("Finished setting up cgroups");
1894 if (handler
->ns_unshare_flags
& CLONE_NEWTIME
) {
1895 /* Now we're ready to preserve the time namespace */
1896 ret
= lxc_try_preserve_namespace(handler
, LXC_NS_TIME
, "time");
1898 if (ret
!= -ENOENT
) {
1899 SYSERROR("Failed to preserve time namespace");
1900 goto out_delete_net
;
1905 /* Run any host-side start hooks */
1906 ret
= run_lxc_hooks(name
, "start-host", conf
, NULL
);
1908 ERROR("Failed to run lxc.hook.start-host");
1909 goto out_delete_net
;
1912 /* Tell the child to complete its initialization and wait for it to exec
1913 * or return an error. (The child will never return
1914 * START_SYNC_READY_START+1. It will either close the sync pipe, causing
1915 * lxc_sync_barrier_child to return success, or return a different
1916 * value, causing us to error out).
1918 if (!lxc_sync_barrier_child(handler
, START_SYNC_READY_START
))
1919 goto out_delete_net
;
1921 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1922 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
1924 ERROR("Failed to receive names and ifindices for network devices from child");
1925 goto out_delete_net
;
1929 ret
= lxc_setup_devpts_parent(handler
);
1931 SYSERROR("Failed to receive devpts fd from child");
1932 goto out_delete_net
;
1935 /* Now all networks are created, network devices are moved into place,
1936 * and the correct names and ifindices in the respective namespaces have
1937 * been recorded. The corresponding structs have now all been filled. So
1938 * log them for debugging purposes.
1940 lxc_log_configured_netdevs(conf
);
1942 /* Read tty fds allocated by child. */
1943 ret
= lxc_recv_ttys_from_child(handler
);
1945 ERROR("Failed to receive tty info from child process");
1946 goto out_delete_net
;
1949 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, data_sock1
);
1951 SYSERROR("Failed to receive seccomp notify fd from child");
1952 goto out_delete_net
;
1955 ret
= handler
->ops
->post_start(handler
, handler
->data
);
1959 ret
= lxc_set_state(name
, handler
, RUNNING
);
1961 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING
));
1965 lxc_sync_fini(handler
);
1970 if (handler
->ns_clone_flags
& CLONE_NEWNET
)
1971 lxc_delete_network(handler
);
1977 lxc_sync_fini(handler
);
1982 int __lxc_start(struct lxc_handler
*handler
, struct lxc_operations
*ops
,
1983 void *data
, const char *lxcpath
, bool daemonize
, int *error_num
)
1986 const char *name
= handler
->name
;
1987 struct lxc_conf
*conf
= handler
->conf
;
1988 struct cgroup_ops
*cgroup_ops
;
1990 ret
= lxc_init(name
, handler
);
1992 ERROR("Failed to initialize container \"%s\"", name
);
1996 handler
->data
= data
;
1997 handler
->daemonize
= daemonize
;
1998 cgroup_ops
= handler
->cgroup_ops
;
2000 if (!attach_block_device(handler
->conf
)) {
2001 ERROR("Failed to attach block device");
2006 if (!cgroup_ops
->monitor_create(cgroup_ops
, handler
)) {
2007 ERROR("Failed to create monitor cgroup");
2012 if (!cgroup_ops
->monitor_delegate_controllers(cgroup_ops
)) {
2013 ERROR("Failed to delegate controllers to monitor cgroup");
2018 if (!cgroup_ops
->monitor_enter(cgroup_ops
, handler
)) {
2019 ERROR("Failed to enter monitor cgroup");
2024 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
2025 /* If the backing store is a device, mount it here and now. */
2026 if (rootfs_is_blockdev(conf
)) {
2027 ret
= unshare(CLONE_NEWNS
);
2029 ERROR("Failed to unshare CLONE_NEWNS");
2032 INFO("Unshared CLONE_NEWNS");
2034 turn_into_dependent_mounts();
2035 ret
= lxc_setup_rootfs_prepare_root(conf
, name
, lxcpath
);
2037 ERROR("Error setting up rootfs mount as root before spawn");
2040 INFO("Set up container rootfs as host root");
2044 ret
= lxc_spawn(handler
);
2046 ERROR("Failed to spawn container \"%s\"", name
);
2047 goto out_detach_blockdev
;
2050 handler
->conf
->reboot
= REBOOT_NONE
;
2052 ret
= lxc_poll(name
, handler
);
2054 ERROR("LXC mainloop exited with error: %d", ret
);
2055 goto out_delete_network
;
2058 if (!handler
->init_died
&& handler
->pid
> 0) {
2059 ERROR("Child process is not killed");
2061 goto out_delete_network
;
2064 status
= lxc_wait_for_pid_status(handler
->pid
);
2066 SYSERROR("Failed to retrieve status for %d", handler
->pid
);
2068 /* If the child process exited but was not signaled, it didn't call
2069 * reboot. This should mean it was an lxc-execute which simply exited.
2070 * In any case, treat it as a 'halt'.
2072 if (WIFSIGNALED(status
)) {
2073 switch(WTERMSIG(status
)) {
2074 case SIGINT
: /* halt */
2075 DEBUG("Container \"%s\" is halting", name
);
2077 case SIGHUP
: /* reboot */
2078 DEBUG("Container \"%s\" is rebooting", name
);
2079 handler
->conf
->reboot
= REBOOT_REQ
;
2081 case SIGSYS
: /* seccomp */
2082 DEBUG("Container \"%s\" violated its seccomp policy", name
);
2085 DEBUG("Unknown exit status for container \"%s\" init %d", name
, WTERMSIG(status
));
2090 ret
= lxc_restore_phys_nics_to_netns(handler
);
2092 ERROR("Failed to move physical network devices back to parent network namespace");
2094 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
2095 lxc_error_set_and_log(handler
->pid
, status
);
2097 *error_num
= handler
->exit_status
;
2099 lxc_delete_network(handler
);
2100 detach_block_device(handler
->conf
);
2109 out_detach_blockdev
:
2111 detach_block_device(handler
->conf
);
2117 lxc_restore_phys_nics_to_netns(handler
);
2118 lxc_delete_network(handler
);
2119 detach_block_device(handler
->conf
);
2128 static int start(struct lxc_handler
*handler
, void* data
)
2130 struct start_args
*arg
= data
;
2132 NOTICE("Exec'ing \"%s\"", arg
->argv
[0]);
2134 execvp(arg
->argv
[0], arg
->argv
);
2135 SYSERROR("Failed to exec \"%s\"", arg
->argv
[0]);
2139 static int post_start(struct lxc_handler
*handler
, void* data
)
2141 struct start_args
*arg
= data
;
2143 NOTICE("Started \"%s\" with pid \"%d\"", arg
->argv
[0], handler
->pid
);
2147 static struct lxc_operations start_ops
= {
2149 .post_start
= post_start
2152 int lxc_start(char *const argv
[], struct lxc_handler
*handler
,
2153 const char *lxcpath
, bool daemonize
, int *error_num
)
2155 struct start_args start_arg
= {
2159 TRACE("Doing lxc_start");
2160 return __lxc_start(handler
, &start_ops
, &start_arg
, lxcpath
, daemonize
, error_num
);
2163 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
2166 char destroy
[PATH_MAX
];
2167 struct lxc_container
*c
;
2171 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
2172 bret
= do_destroy_container(handler
);
2174 ERROR("Error destroying rootfs for container \"%s\"", name
);
2178 INFO("Destroyed rootfs for container \"%s\"", name
);
2180 ret
= strnprintf(destroy
, sizeof(destroy
), "%s/%s", handler
->lxcpath
, name
);
2182 ERROR("Error destroying directory for container \"%s\"", name
);
2186 c
= lxc_container_new(name
, handler
->lxcpath
);
2188 if (container_disk_lock(c
)) {
2189 INFO("Could not update lxc_snapshots file");
2190 lxc_container_put(c
);
2192 mod_all_rdeps(c
, false);
2193 container_disk_unlock(c
);
2194 lxc_container_put(c
);
2198 if (!handler
->am_root
)
2199 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
2200 destroy
, "lxc_rmdir_onedev_wrapper");
2202 ret
= lxc_rmdir_onedev(destroy
, NULL
);
2205 ERROR("Error destroying directory for container \"%s\"", name
);
2208 INFO("Destroyed directory for container \"%s\"", name
);
2211 static int lxc_rmdir_onedev_wrapper(void *data
)
2213 char *arg
= (char *) data
;
2214 return lxc_rmdir_onedev(arg
, NULL
);
2217 static bool do_destroy_container(struct lxc_handler
*handler
)
2221 if (!handler
->am_root
) {
2222 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
2223 handler
->conf
, "storage_destroy_wrapper");
2230 return storage_destroy(handler
->conf
);