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 "process_utils.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 access, or add an ACL for the container " "root", copy
);
104 static void lxc_put_nsfds(struct lxc_handler
*handler
)
106 for (int i
= 0; i
< LXC_NS_MAX
; i
++) {
107 if (handler
->nsfd
[i
] < 0)
110 close_prot_errno_disarm(handler
->nsfd
[i
]);
114 static int lxc_try_preserve_ns(const int pid
, const char *ns
)
118 fd
= lxc_preserve_ns(pid
, ns
);
121 return log_error_errno(-EINVAL
,
122 errno
, "Failed to preserve %s namespace",
125 return log_warn_errno(-EOPNOTSUPP
,
126 errno
, "Kernel does not support preserving %s namespaces",
133 /* lxc_try_preserve_namespaces: open /proc/@pid/ns/@ns for each namespace
134 * specified in ns_clone_flags.
135 * Return true on success, false on failure.
137 static bool lxc_try_preserve_namespaces(struct lxc_handler
*handler
,
138 int ns_clone_flags
, pid_t pid
)
142 for (i
= 0; i
< LXC_NS_MAX
; i
++)
143 handler
->nsfd
[i
] = -EBADF
;
145 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
148 if ((ns_clone_flags
& ns_info
[i
].clone_flag
) == 0)
151 fd
= lxc_try_preserve_ns(pid
, ns_info
[i
].proc_name
);
153 /* Do not fail to start container on kernels that do
154 * not support interacting with namespaces through
157 if (fd
== -EOPNOTSUPP
)
160 lxc_put_nsfds(handler
);
164 handler
->nsfd
[i
] = fd
;
165 DEBUG("Preserved %s namespace via fd %d", ns_info
[i
].proc_name
,
172 static inline bool match_stdfds(int fd
)
174 return (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
);
178 static bool match_dlog_fds(struct dirent
*direntp
)
180 char path
[PATH_MAX
] = {0};
181 char link
[PATH_MAX
] = {0};
185 ret
= snprintf(path
, PATH_MAX
, "/proc/self/fd/%s", direntp
->d_name
);
186 if (ret
< 0 || ret
>= PATH_MAX
)
187 return log_error(false, "Failed to create file descriptor name");
189 linklen
= readlink(path
, link
, PATH_MAX
);
191 return log_error(false, "Failed to read link path - \"%s\"", path
);
192 else if (linklen
>= PATH_MAX
)
193 return log_error(false, "The name of link path is too long - \"%s\"", path
);
195 if (strcmp(link
, "/dev/log_main") == 0 ||
196 strcmp(link
, "/dev/log_system") == 0 ||
197 strcmp(link
, "/dev/log_radio") == 0)
204 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
205 int *fds_to_ignore
, size_t len_fds
)
210 struct dirent
*direntp
;
212 if (conf
&& conf
->close_all_fds
)
216 * Disable syslog at this point to avoid the above logging
217 * function to open a new fd and make the check_inherited function
218 * enter an infinite loop.
220 lxc_log_syslog_disable();
223 dir
= opendir("/proc/self/fd");
225 return log_warn(-1, "Failed to open directory");
229 while ((direntp
= readdir(dir
))) {
231 struct lxc_list
*cur
;
232 bool matched
= false;
234 if (strcmp(direntp
->d_name
, ".") == 0)
237 if (strcmp(direntp
->d_name
, "..") == 0)
240 ret
= lxc_safe_int(direntp
->d_name
, &fd
);
242 INFO("Could not parse file descriptor for \"%s\"", direntp
->d_name
);
246 for (i
= 0; i
< len_fds
; i
++)
247 if (fds_to_ignore
[i
] == fd
)
250 if (fd
== fddir
|| fd
== lxc_log_fd
||
251 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
254 /* Keep state clients that wait on reboots. */
256 lxc_list_for_each(cur
, &conf
->state_clients
) {
257 struct lxc_state_client
*client
= cur
->elem
;
259 if (client
->clientfd
!= fd
)
270 if (current_config
&& fd
== current_config
->logfd
)
273 if (match_stdfds(fd
))
277 if (match_dlog_fds(direntp
))
283 SYSINFO("Closed inherited fd %d", fd
);
285 INFO("Closed inherited fd %d", fd
);
289 WARN("Inherited fd %d", fd
);
294 * Only enable syslog at this point to avoid the above logging
295 * function to open a new fd and make the check_inherited function
296 * enter an infinite loop.
298 lxc_log_syslog_enable();
303 static int setup_signal_fd(sigset_t
*oldmask
)
307 const int signals
[] = {SIGBUS
, SIGILL
, SIGSEGV
, SIGWINCH
};
309 /* Block everything except serious error signals. */
310 ret
= sigfillset(&mask
);
314 for (int sig
= 0; sig
< (sizeof(signals
) / sizeof(signals
[0])); sig
++) {
315 ret
= sigdelset(&mask
, signals
[sig
]);
320 ret
= pthread_sigmask(SIG_BLOCK
, &mask
, oldmask
);
322 return log_error_errno(-EBADF
, errno
,
323 "Failed to set signal mask");
325 ret
= signalfd(-1, &mask
, SFD_CLOEXEC
);
327 return log_error_errno(-EBADF
,
328 errno
, "Failed to create signal file descriptor");
330 TRACE("Created signal file descriptor %d", ret
);
335 static int signal_handler(int fd
, uint32_t events
, void *data
,
336 struct lxc_epoll_descr
*descr
)
340 struct signalfd_siginfo siginfo
;
341 struct lxc_handler
*hdlr
= data
;
343 ret
= lxc_read_nointr(fd
, &siginfo
, sizeof(siginfo
));
345 return log_error(LXC_MAINLOOP_ERROR
, "Failed to read signal info from signal file descriptor %d", fd
);
347 if (ret
!= sizeof(siginfo
))
348 return log_error(LXC_MAINLOOP_ERROR
, "Unexpected size for struct signalfd_siginfo");
350 /* Check whether init is running. */
352 ret
= waitid(P_PID
, hdlr
->pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
353 if (ret
== 0 && info
.si_pid
== hdlr
->pid
)
354 hdlr
->init_died
= true;
356 /* Try to figure out a reasonable exit status to report. */
357 if (hdlr
->init_died
) {
358 switch (info
.si_code
) {
360 hdlr
->exit_status
= info
.si_status
<< 8;
365 hdlr
->exit_status
= info
.si_status
<< 8 | 0x7f;
368 /* Huh? The waitid() told us it's dead *and* continued? */
369 WARN("Init %d dead and continued?", hdlr
->pid
);
370 hdlr
->exit_status
= 1;
373 ERROR("Unknown si_code: %d", info
.si_code
);
374 hdlr
->exit_status
= 1;
378 if (siginfo
.ssi_signo
== SIGHUP
) {
379 if (hdlr
->pidfd
>= 0)
380 lxc_raw_pidfd_send_signal(hdlr
->pidfd
, SIGTERM
, NULL
, 0);
382 kill(hdlr
->pid
, SIGTERM
);
383 INFO("Killing %d since terminal hung up", hdlr
->pid
);
384 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
385 : LXC_MAINLOOP_CONTINUE
;
388 if (siginfo
.ssi_signo
!= SIGCHLD
) {
389 if (hdlr
->pidfd
>= 0)
390 lxc_raw_pidfd_send_signal(hdlr
->pidfd
,
391 siginfo
.ssi_signo
, NULL
, 0);
393 kill(hdlr
->pid
, siginfo
.ssi_signo
);
394 INFO("Forwarded signal %d to pid %d", siginfo
.ssi_signo
, hdlr
->pid
);
395 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
396 : LXC_MAINLOOP_CONTINUE
;
399 /* More robustness, protect ourself from a SIGCHLD sent
400 * by a process different from the container init.
402 if (siginfo
.ssi_pid
!= hdlr
->pid
) {
403 NOTICE("Received %d from pid %d instead of container init %d",
404 siginfo
.ssi_signo
, siginfo
.ssi_pid
, hdlr
->pid
);
405 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
406 : LXC_MAINLOOP_CONTINUE
;
409 if (siginfo
.ssi_code
== CLD_STOPPED
) {
410 INFO("Container init process was stopped");
411 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
412 : LXC_MAINLOOP_CONTINUE
;
415 if (siginfo
.ssi_code
== CLD_CONTINUED
) {
416 INFO("Container init process was continued");
417 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
418 : LXC_MAINLOOP_CONTINUE
;
421 return log_debug(LXC_MAINLOOP_CLOSE
, "Container init process %d exited", hdlr
->pid
);
424 int lxc_serve_state_clients(const char *name
, struct lxc_handler
*handler
,
429 struct lxc_list
*cur
, *next
;
430 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
433 handler
->state
= RUNNING
;
435 handler
->state
= state
;
437 TRACE("Set container state to %s", lxc_state2str(state
));
439 if (lxc_list_empty(&handler
->conf
->state_clients
))
440 return log_trace(0, "No state clients registered");
442 retlen
= strlcpy(msg
.name
, name
, sizeof(msg
.name
));
443 if (retlen
>= sizeof(msg
.name
))
446 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
447 struct lxc_state_client
*client
= cur
->elem
;
449 if (client
->states
[state
] == 0) {
450 TRACE("State %s not registered for state client %d",
451 lxc_state2str(state
), client
->clientfd
);
455 TRACE("Sending state %s to state client %d",
456 lxc_state2str(state
), client
->clientfd
);
458 ret
= lxc_send_nointr(client
->clientfd
, &msg
, sizeof(msg
), MSG_NOSIGNAL
);
460 SYSERROR("Failed to send message to client");
462 /* kick client from list */
464 close(client
->clientfd
);
472 static int lxc_serve_state_socket_pair(const char *name
,
473 struct lxc_handler
*handler
,
478 if (!handler
->daemonize
||
479 handler
->state_socket_pair
[1] < 0 ||
483 /* Close read end of the socket pair. */
484 close_prot_errno_disarm(handler
->state_socket_pair
[0]);
487 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
488 &(int){state
}, sizeof(int));
490 SYSERROR("Failed to send state to %d", handler
->state_socket_pair
[1]);
498 if (ret
!= sizeof(int))
499 return log_error(-1, "Message too long : %d", handler
->state_socket_pair
[1]);
501 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
502 handler
->state_socket_pair
[1]);
504 /* Close write end of the socket pair. */
505 close_prot_errno_disarm(handler
->state_socket_pair
[1]);
510 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
515 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
517 return log_error(-1, "Failed to synchronize via anonymous pair of unix sockets");
519 ret
= lxc_serve_state_clients(name
, handler
, state
);
523 /* This function will try to connect to the legacy lxc-monitord state
524 * server and only exists for backwards compatibility.
526 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
531 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
534 bool has_console
= true;
535 struct lxc_epoll_descr descr
, descr_console
;
537 if (handler
->conf
->console
.path
&&
538 strcmp(handler
->conf
->console
.path
, "none") == 0)
541 ret
= lxc_mainloop_open(&descr
);
543 ERROR("Failed to create mainloop");
548 ret
= lxc_mainloop_open(&descr_console
);
550 ERROR("Failed to create console mainloop");
555 ret
= lxc_mainloop_add_handler(&descr
, handler
->sigfd
, signal_handler
, handler
);
557 ERROR("Failed to add signal handler for %d to mainloop", handler
->sigfd
);
558 goto out_mainloop_console
;
561 ret
= lxc_seccomp_setup_proxy(&handler
->conf
->seccomp
, &descr
, handler
);
563 ERROR("Failed to setup seccomp proxy");
564 goto out_mainloop_console
;
568 struct lxc_terminal
*console
= &handler
->conf
->console
;
570 ret
= lxc_terminal_mainloop_add(&descr
, console
);
572 ERROR("Failed to add console handlers to mainloop");
573 goto out_mainloop_console
;
576 ret
= lxc_terminal_mainloop_add(&descr_console
, console
);
578 ERROR("Failed to add console handlers to console mainloop");
579 goto out_mainloop_console
;
582 handler
->conf
->console
.descr
= &descr
;
585 ret
= lxc_cmd_mainloop_add(name
, &descr
, handler
);
587 ERROR("Failed to add command handler to mainloop");
588 goto out_mainloop_console
;
591 TRACE("Mainloop is ready");
593 ret
= lxc_mainloop(&descr
, -1);
594 close_prot_errno_disarm(descr
.epfd
);
595 if (ret
< 0 || !handler
->init_died
)
596 goto out_mainloop_console
;
599 ret
= lxc_mainloop(&descr_console
, 0);
601 out_mainloop_console
:
603 lxc_mainloop_close(&descr_console
);
604 TRACE("Closed console mainloop");
608 lxc_mainloop_close(&descr
);
609 TRACE("Closed mainloop");
612 TRACE("Closed signal file descriptor %d", handler
->sigfd
);
613 close_prot_errno_disarm(handler
->sigfd
);
618 void lxc_put_handler(struct lxc_handler
*handler
)
620 close_prot_errno_disarm(handler
->pinfd
);
621 close_prot_errno_disarm(handler
->pidfd
);
622 close_prot_errno_disarm(handler
->sigfd
);
623 lxc_put_nsfds(handler
);
624 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
625 close_prot_errno_disarm(handler
->conf
->maincmd_fd
);
626 close_prot_errno_disarm(handler
->monitor_status_fd
);
627 close_prot_errno_disarm(handler
->state_socket_pair
[0]);
628 close_prot_errno_disarm(handler
->state_socket_pair
[1]);
629 cgroup_exit(handler
->cgroup_ops
);
630 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
631 free_disarm(handler
);
633 handler
->conf
= NULL
;
636 struct lxc_handler
*lxc_init_handler(struct lxc_handler
*old
,
637 const char *name
, struct lxc_conf
*conf
,
638 const char *lxcpath
, bool daemonize
)
642 struct lxc_handler
*handler
;
645 handler
= zalloc(sizeof(*handler
));
651 /* Note that am_guest_unpriv() checks the effective uid. We
652 * probably don't care if we are real root only if we are running
653 * as root so this should be fine.
655 handler
->am_root
= !am_guest_unpriv();
656 handler
->conf
= conf
;
657 handler
->lxcpath
= lxcpath
;
658 handler
->init_died
= false;
659 handler
->data_sock
[0] = -EBADF
;
660 handler
->data_sock
[1] = -EBADF
;
661 handler
->monitor_status_fd
= -EBADF
;
662 handler
->pinfd
= -EBADF
;
663 handler
->pidfd
= -EBADF
;
664 handler
->sigfd
= -EBADF
;
665 handler
->state_socket_pair
[0] = -EBADF
;
666 handler
->state_socket_pair
[1] = -EBADF
;
667 if (handler
->conf
->reboot
== REBOOT_NONE
)
668 lxc_list_init(&handler
->conf
->state_clients
);
670 for (int i
= 0; i
< LXC_NS_MAX
; i
++)
671 handler
->nsfd
[i
] = -EBADF
;
673 handler
->name
= name
;
675 handler
->transient_pid
= lxc_raw_getpid();
677 handler
->transient_pid
= -1;
679 if (daemonize
&& handler
->conf
->reboot
== REBOOT_NONE
) {
680 /* Create socketpair() to synchronize on daemonized startup.
681 * When the container reboots we don't need to synchronize
682 * again currently so don't open another socketpair().
684 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
685 handler
->state_socket_pair
);
687 ERROR("Failed to create anonymous pair of unix sockets");
691 TRACE("Created anonymous pair {%d,%d} of unix sockets",
692 handler
->state_socket_pair
[0],
693 handler
->state_socket_pair
[1]);
694 handler
->keep_fds
[nr_keep_fds
++] = handler
->state_socket_pair
[0];
695 handler
->keep_fds
[nr_keep_fds
++] = handler
->state_socket_pair
[1];
698 if (handler
->conf
->reboot
== REBOOT_NONE
) {
699 handler
->conf
->maincmd_fd
= lxc_cmd_init(name
, lxcpath
, "command");
700 if (handler
->conf
->maincmd_fd
< 0) {
701 ERROR("Failed to set up command socket");
704 handler
->keep_fds
[nr_keep_fds
++] = handler
->conf
->maincmd_fd
;
707 TRACE("Unix domain socket %d for command server is ready",
708 handler
->conf
->maincmd_fd
);
713 lxc_put_handler(handler
);
718 int lxc_init(const char *name
, struct lxc_handler
*handler
)
720 __do_close
int status_fd
= -EBADF
;
722 const char *loglevel
;
723 struct lxc_conf
*conf
= handler
->conf
;
725 handler
->monitor_pid
= lxc_raw_getpid();
726 status_fd
= open("/proc/self/status", O_RDONLY
| O_CLOEXEC
);
728 return log_error_errno(-1, errno
, "Failed to open monitor status fd");
731 TRACE("Initialized LSM");
733 /* Begin by setting the state to STARTING. */
734 ret
= lxc_set_state(name
, handler
, STARTING
);
736 return log_error(-1, "Failed to set state to \"%s\"", lxc_state2str(STARTING
));
737 TRACE("Set container state to \"STARTING\"");
739 /* Start of environment variable setup for hooks. */
740 ret
= setenv("LXC_NAME", name
, 1);
742 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name
);
745 ret
= setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1);
747 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s", conf
->rcfile
);
750 if (conf
->rootfs
.mount
) {
751 ret
= setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1);
753 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s", conf
->rootfs
.mount
);
756 if (conf
->rootfs
.path
) {
757 ret
= setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1);
759 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s", conf
->rootfs
.path
);
762 if (conf
->console
.path
) {
763 ret
= setenv("LXC_CONSOLE", conf
->console
.path
, 1);
765 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s", conf
->console
.path
);
768 if (conf
->console
.log_path
) {
769 ret
= setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1);
771 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s", conf
->console
.log_path
);
774 if (cgns_supported()) {
775 ret
= setenv("LXC_CGNS_AWARE", "1", 1);
777 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1");
780 loglevel
= lxc_log_priority_to_string(lxc_log_get_level());
781 ret
= setenv("LXC_LOG_LEVEL", loglevel
, 1);
783 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s", loglevel
);
785 if (conf
->hooks_version
== 0)
786 ret
= setenv("LXC_HOOK_VERSION", "0", 1);
788 ret
= setenv("LXC_HOOK_VERSION", "1", 1);
790 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf
->hooks_version
);
791 /* End of environment variable setup for hooks. */
793 TRACE("Set environment variables");
795 ret
= run_lxc_hooks(name
, "pre-start", conf
, NULL
);
797 return log_error(-1, "Failed to run lxc.hook.pre-start for container \"%s\"", name
);
798 TRACE("Ran pre-start hooks");
800 /* The signal fd has to be created before forking otherwise if the child
801 * process exits before we setup the signal fd, the event will be lost
802 * and the command will be stuck.
804 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
805 if (handler
->sigfd
< 0)
806 return log_error(-1, "Failed to setup SIGCHLD fd handler.");
807 TRACE("Set up signal fd");
809 /* Do this after setting up signals since it might unblock SIGWINCH. */
810 ret
= lxc_terminal_setup(conf
);
812 ERROR("Failed to create console");
813 goto out_restore_sigmask
;
815 TRACE("Created console");
817 ret
= lxc_terminal_map_ids(conf
, &conf
->console
);
819 ERROR("Failed to chown console");
820 goto out_delete_terminal
;
822 TRACE("Chowned console");
824 handler
->cgroup_ops
= cgroup_init(handler
->conf
);
825 if (!handler
->cgroup_ops
) {
826 ERROR("Failed to initialize cgroup driver");
827 goto out_delete_terminal
;
829 TRACE("Initialized cgroup driver");
831 ret
= lxc_read_seccomp_config(conf
);
833 return log_error(-1, "Failed loading seccomp policy");
834 TRACE("Read seccomp policy");
836 ret
= lsm_process_prepare(conf
, handler
->lxcpath
);
838 ERROR("Failed to initialize LSM");
839 goto out_delete_terminal
;
841 TRACE("Initialized LSM");
843 INFO("Container \"%s\" is initialized", name
);
844 handler
->monitor_status_fd
= move_fd(status_fd
);
848 lxc_terminal_delete(&handler
->conf
->console
);
851 (void)pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
856 void lxc_end(struct lxc_handler
*handler
)
860 struct lxc_list
*cur
, *next
;
861 char *namespaces
[LXC_NS_MAX
+ 1];
862 size_t namespace_count
= 0;
863 const char *name
= handler
->name
;
864 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
866 /* The STOPPING state is there for future cleanup code which can take
869 lxc_set_state(name
, handler
, STOPPING
);
871 self
= lxc_raw_getpid();
872 for (int i
= 0; i
< LXC_NS_MAX
; i
++) {
873 if (handler
->nsfd
[i
] < 0)
876 if (handler
->conf
->hooks_version
== 0)
877 ret
= asprintf(&namespaces
[namespace_count
],
878 "%s:/proc/%d/fd/%d", ns_info
[i
].proc_name
,
879 self
, handler
->nsfd
[i
]);
881 ret
= asprintf(&namespaces
[namespace_count
],
882 "/proc/%d/fd/%d", self
, handler
->nsfd
[i
]);
884 SYSERROR("Failed to allocate memory");
888 if (handler
->conf
->hooks_version
== 0) {
893 ret
= setenv(ns_info
[i
].env_name
, namespaces
[namespace_count
], 1);
895 SYSERROR("Failed to set environment variable %s=%s",
896 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
898 TRACE("Set environment variable %s=%s",
899 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
903 namespaces
[namespace_count
] = NULL
;
905 if (handler
->conf
->reboot
> REBOOT_NONE
) {
906 ret
= setenv("LXC_TARGET", "reboot", 1);
908 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot");
911 if (handler
->conf
->reboot
== REBOOT_NONE
) {
912 ret
= setenv("LXC_TARGET", "stop", 1);
914 SYSERROR("Failed to set environment variable: LXC_TARGET=stop");
917 if (handler
->conf
->hooks_version
== 0)
918 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, namespaces
);
920 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, NULL
);
922 ERROR("Failed to run \"lxc.hook.stop\" hook");
924 while (namespace_count
--)
925 free(namespaces
[namespace_count
]);
927 lsm_process_cleanup(handler
->conf
, handler
->lxcpath
);
930 cgroup_ops
->payload_destroy(cgroup_ops
, handler
);
931 cgroup_ops
->monitor_destroy(cgroup_ops
, handler
);
934 if (handler
->conf
->reboot
== REBOOT_NONE
) {
935 /* For all new state clients simply close the command socket.
936 * This will inform all state clients that the container is
937 * STOPPED and also prevents a race between a open()/close() on
938 * the command socket causing a new process to get ECONNREFUSED
939 * because we haven't yet closed the command socket.
941 close_prot_errno_disarm(handler
->conf
->maincmd_fd
);
942 TRACE("Closed command socket");
944 /* This function will try to connect to the legacy lxc-monitord
945 * state server and only exists for backwards compatibility.
947 lxc_monitor_send_state(name
, STOPPED
, handler
->lxcpath
);
949 /* The command socket is closed so no one can acces the command
950 * socket anymore so there's no need to lock it.
952 handler
->state
= STOPPED
;
953 TRACE("Set container state to \"STOPPED\"");
955 lxc_set_state(name
, handler
, STOPPED
);
956 TRACE("Set container state to \"STOPPED\"");
959 /* Avoid lingering namespace references. */
960 lxc_put_nsfds(handler
);
962 ret
= run_lxc_hooks(name
, "post-stop", handler
->conf
, NULL
);
964 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name
);
965 if (handler
->conf
->reboot
> REBOOT_NONE
) {
966 WARN("Container will be stopped instead of rebooted");
967 handler
->conf
->reboot
= REBOOT_NONE
;
969 ret
= setenv("LXC_TARGET", "stop", 1);
971 WARN("Failed to set environment variable: LXC_TARGET=stop");
975 /* Reset mask set by setup_signal_fd. */
976 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
978 SYSWARN("Failed to restore signal mask");
980 lxc_terminal_delete(&handler
->conf
->console
);
981 lxc_delete_tty(&handler
->conf
->ttys
);
983 /* The command socket is now closed, no more state clients can register
984 * themselves from now on. So free the list of state clients.
986 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
987 struct lxc_state_client
*client
= cur
->elem
;
989 /* Keep state clients that want to be notified about reboots. */
990 if ((handler
->conf
->reboot
> REBOOT_NONE
) &&
991 (client
->states
[RUNNING
] == 2))
994 /* close state client socket */
996 close(client
->clientfd
);
1001 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= REBOOT_REQ
)
1002 lxc_destroy_container_on_signal(handler
, name
);
1004 lxc_put_handler(handler
);
1007 void lxc_abort(struct lxc_handler
*handler
)
1012 lxc_set_state(handler
->name
, handler
, ABORTING
);
1014 if (handler
->pidfd
>= 0) {
1015 ret
= lxc_raw_pidfd_send_signal(handler
->pidfd
, SIGKILL
, NULL
, 0);
1017 SYSWARN("Failed to send SIGKILL via pidfd %d for process %d",
1018 handler
->pidfd
, handler
->pid
);
1021 if ((!ret
|| errno
!= ESRCH
) && handler
->pid
> 0)
1022 if (kill(handler
->pid
, SIGKILL
))
1023 SYSWARN("Failed to send SIGKILL to %d", handler
->pid
);
1026 ret
= waitpid(-1, &status
, 0);
1030 static int do_start(void *data
)
1032 struct lxc_handler
*handler
= data
;
1033 __lxc_unused __do_close
int data_sock0
= handler
->data_sock
[0],
1034 data_sock1
= handler
->data_sock
[1];
1035 __do_close
int devnull_fd
= -EBADF
, status_fd
= -EBADF
;
1039 struct lxc_list
*iterator
;
1043 lxc_sync_fini_parent(handler
);
1045 if (lxc_abstract_unix_recv_fds(data_sock1
, &status_fd
, 1, NULL
, 0) < 0) {
1046 ERROR("Failed to receive status file descriptor to child process");
1047 goto out_warn_father
;
1050 /* This prctl must be before the synchro, so if the parent dies before
1051 * we set the parent death signal, we will detect its death with the
1052 * synchro right after, otherwise we have a window where the parent can
1053 * exit before we set the pdeath signal leading to a unsupervized
1056 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
, status_fd
);
1058 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1059 goto out_warn_father
;
1062 ret
= lxc_ambient_caps_up();
1064 ERROR("Failed to raise ambient capabilities");
1065 goto out_warn_father
;
1068 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1070 SYSERROR("Failed to set signal mask");
1071 goto out_warn_father
;
1074 /* Don't leak the pinfd to the container. */
1075 close_prot_errno_disarm(handler
->pinfd
);
1077 ret
= lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
);
1079 goto out_warn_father
;
1081 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1082 * https://github.com/lxc/lxd/issues/1978.
1084 if (handler
->ns_unshare_flags
& CLONE_NEWNET
) {
1085 ret
= unshare(CLONE_NEWNET
);
1087 SYSERROR("Failed to unshare CLONE_NEWNET");
1088 goto out_warn_father
;
1090 INFO("Unshared CLONE_NEWNET");
1093 /* Tell the parent task it can begin to configure the container and wait
1096 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
);
1100 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1101 ret
= lxc_network_recv_from_parent(handler
);
1103 ERROR("Failed to receive veth names from parent");
1104 goto out_warn_father
;
1108 /* If we are in a new user namespace, become root there to have
1109 * privilege over our namespace.
1111 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1112 if (!handler
->conf
->root_nsuid_map
)
1113 nsuid
= handler
->conf
->init_uid
;
1115 if (!handler
->conf
->root_nsgid_map
)
1116 nsgid
= handler
->conf
->init_gid
;
1118 /* Drop groups only after we switched to a valid gid in the new
1121 if (!lxc_setgroups(0, NULL
) &&
1122 (handler
->am_root
|| errno
!= EPERM
))
1123 goto out_warn_father
;
1125 if (!lxc_switch_uid_gid(nsuid
, nsgid
))
1126 goto out_warn_father
;
1128 ret
= prctl(PR_SET_DUMPABLE
, prctl_arg(1), prctl_arg(0),
1129 prctl_arg(0), prctl_arg(0));
1131 goto out_warn_father
;
1133 /* set{g,u}id() clears deathsignal */
1134 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
, status_fd
);
1136 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1137 goto out_warn_father
;
1141 ret
= access(handler
->lxcpath
, X_OK
);
1143 print_top_failing_dir(handler
->lxcpath
);
1144 goto out_warn_father
;
1147 /* In order to checkpoint restore, we need to have everything in the
1148 * same mount namespace. However, some containers may not have a
1149 * reasonable /dev (in particular, they may not have /dev/null), so we
1150 * can't set init's std fds to /dev/null by opening it from inside the
1153 * If that's the case, fall back to using the host's /dev/null. This
1154 * means that migration won't work, but at least we won't spew output
1155 * where it isn't wanted.
1157 if (handler
->daemonize
&& !handler
->conf
->autodev
) {
1158 char path
[PATH_MAX
];
1160 ret
= snprintf(path
, sizeof(path
), "%s/dev/null",
1161 handler
->conf
->rootfs
.mount
);
1162 if (ret
< 0 || ret
>= sizeof(path
))
1163 goto out_warn_father
;
1165 ret
= access(path
, F_OK
);
1167 devnull_fd
= open_devnull();
1170 goto out_warn_father
;
1171 WARN("Using /dev/null from the host for container init's standard file descriptors. Migration will not work");
1175 /* Ask father to setup cgroups and wait for him to finish. */
1176 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
);
1180 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1181 * earlier we end up with a wrong view of /proc/self/cgroup. For
1182 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1183 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1184 * /proc/self/cgroup would show us:
1188 * whereas it should actually show
1192 if (handler
->ns_unshare_flags
& CLONE_NEWCGROUP
) {
1193 ret
= unshare(CLONE_NEWCGROUP
);
1195 if (errno
!= EINVAL
) {
1196 SYSERROR("Failed to unshare CLONE_NEWCGROUP");
1197 goto out_warn_father
;
1200 handler
->ns_clone_flags
&= ~CLONE_NEWCGROUP
;
1201 SYSINFO("Kernel does not support CLONE_NEWCGROUP");
1203 INFO("Unshared CLONE_NEWCGROUP");
1207 if (handler
->ns_unshare_flags
& CLONE_NEWTIME
) {
1208 ret
= unshare(CLONE_NEWTIME
);
1210 if (errno
!= EINVAL
) {
1211 SYSERROR("Failed to unshare CLONE_NEWTIME");
1212 goto out_warn_father
;
1215 handler
->ns_clone_flags
&= ~CLONE_NEWTIME
;
1216 SYSINFO("Kernel does not support CLONE_NEWTIME");
1218 __do_close
int timens_fd
= -EBADF
;
1220 INFO("Unshared CLONE_NEWTIME");
1222 if (handler
->conf
->timens
.s_boot
)
1223 ret
= timens_offset_write(CLOCK_BOOTTIME
, handler
->conf
->timens
.s_boot
, 0);
1224 else if (handler
->conf
->timens
.ns_boot
)
1225 ret
= timens_offset_write(CLOCK_BOOTTIME
, 0, handler
->conf
->timens
.ns_boot
);
1227 SYSERROR("Failed to write CLONE_BOOTTIME offset");
1228 goto out_warn_father
;
1230 TRACE("Wrote CLOCK_BOOTTIME offset");
1232 if (handler
->conf
->timens
.s_monotonic
)
1233 ret
= timens_offset_write(CLOCK_MONOTONIC
, handler
->conf
->timens
.s_monotonic
, 0);
1234 else if (handler
->conf
->timens
.ns_monotonic
)
1235 ret
= timens_offset_write(CLOCK_MONOTONIC
, 0, handler
->conf
->timens
.ns_monotonic
);
1237 SYSERROR("Failed to write CLONE_MONOTONIC offset");
1238 goto out_warn_father
;
1240 TRACE("Wrote CLOCK_MONOTONIC offset");
1242 timens_fd
= open("/proc/self/ns/time_for_children", O_RDONLY
| O_CLOEXEC
);
1243 if (timens_fd
< 0) {
1244 SYSERROR("Failed to open \"/proc/self/ns/time_for_children\"");
1245 goto out_warn_father
;
1248 ret
= setns(timens_fd
, CLONE_NEWTIME
);
1250 SYSERROR("Failed to setns(%d(\"/proc/self/ns/time_for_children\"))", timens_fd
);
1251 goto out_warn_father
;
1256 /* Add the requested environment variables to the current environment to
1257 * allow them to be used by the various hooks, such as the start hook
1260 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1261 ret
= putenv((char *)iterator
->elem
);
1263 SYSERROR("Failed to set environment variable: %s",
1264 (char *)iterator
->elem
);
1265 goto out_warn_father
;
1269 /* Setup the container, ip, names, utsname, ... */
1270 ret
= lxc_setup(handler
);
1272 ERROR("Failed to setup container \"%s\"", handler
->name
);
1273 goto out_warn_father
;
1276 /* Set the label to change to when we exec(2) the container's init. */
1277 ret
= lsm_process_label_set(NULL
, handler
->conf
, true);
1279 goto out_warn_father
;
1281 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1282 * before we aren't allowed anymore.
1284 if (handler
->conf
->no_new_privs
) {
1285 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
1286 prctl_arg(0), prctl_arg(0));
1288 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges");
1289 goto out_warn_father
;
1291 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges");
1294 /* Some init's such as busybox will set sane tty settings on stdin,
1295 * stdout, stderr which it thinks is the console. We already set them
1296 * the way we wanted on the real terminal, and we want init to do its
1297 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
1298 * make sure that that pty is stdin,stdout,stderr.
1300 if (handler
->conf
->console
.pty
>= 0) {
1301 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
1302 ret
= set_stdfds(handler
->conf
->console
.pty
);
1304 ret
= lxc_terminal_set_stdfds(handler
->conf
->console
.pty
);
1306 ERROR("Failed to redirect std{in,out,err} to pty file descriptor %d",
1307 handler
->conf
->console
.pty
);
1308 goto out_warn_father
;
1312 /* If we mounted a temporary proc, then unmount it now. */
1313 tmp_proc_unmount(handler
->conf
);
1315 ret
= lxc_seccomp_load(handler
->conf
);
1317 goto out_warn_father
;
1319 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, data_sock0
);
1321 SYSERROR("Failed to send seccomp notify fd to parent");
1322 goto out_warn_father
;
1325 ret
= run_lxc_hooks(handler
->name
, "start", handler
->conf
, NULL
);
1327 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1329 goto out_warn_father
;
1332 close_prot_errno_disarm(handler
->sigfd
);
1334 if (handler
->conf
->console
.pty
< 0 && handler
->daemonize
) {
1335 if (devnull_fd
< 0) {
1336 devnull_fd
= open_devnull();
1338 goto out_warn_father
;
1341 ret
= set_stdfds(devnull_fd
);
1343 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
1344 goto out_warn_father
;
1348 close_prot_errno_disarm(devnull_fd
);
1352 if (handler
->conf
->init_cwd
) {
1353 ret
= chdir(handler
->conf
->init_cwd
);
1355 SYSERROR("Could not change directory to \"%s\"",
1356 handler
->conf
->init_cwd
);
1357 goto out_warn_father
;
1361 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
);
1363 goto out_warn_father
;
1365 /* Reset the environment variables the user requested in a clear
1369 /* Don't error out though. */
1371 SYSERROR("Failed to clear environment.");
1373 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1374 ret
= putenv((char *)iterator
->elem
);
1376 SYSERROR("Failed to set environment variable: %s",
1377 (char *)iterator
->elem
);
1378 goto out_warn_father
;
1382 ret
= putenv("container=lxc");
1384 SYSERROR("Failed to set environment variable: container=lxc");
1385 goto out_warn_father
;
1388 if (handler
->conf
->ttys
.tty_names
) {
1389 ret
= putenv(handler
->conf
->ttys
.tty_names
);
1391 SYSERROR("Failed to set environment variable for container ptys");
1392 goto out_warn_father
;
1396 /* The container has been setup. We can now switch to an unprivileged
1399 new_uid
= handler
->conf
->init_uid
;
1400 new_gid
= handler
->conf
->init_gid
;
1402 /* Avoid unnecessary syscalls. */
1403 if (new_uid
== nsuid
)
1404 new_uid
= LXC_INVALID_UID
;
1406 if (new_gid
== nsgid
)
1407 new_gid
= LXC_INVALID_GID
;
1409 /* Make sure that the processes STDIO is correctly owned by the user that we are switching to */
1410 ret
= fix_stdio_permissions(new_uid
);
1412 WARN("Failed to ajust stdio permissions");
1414 /* If we are in a new user namespace we already dropped all groups when
1415 * we switched to root in the new user namespace further above. Only
1416 * drop groups if we can, so ensure that we have necessary privilege.
1418 if (lxc_list_empty(&handler
->conf
->id_map
))
1420 if (lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
))
1422 if (!lxc_setgroups(0, NULL
))
1423 goto out_warn_father
;
1425 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
1426 goto out_warn_father
;
1428 ret
= lxc_ambient_caps_down();
1430 ERROR("Failed to clear ambient capabilities");
1431 goto out_warn_father
;
1434 if (handler
->conf
->monitor_signal_pdeath
!= SIGKILL
) {
1435 ret
= lxc_set_death_signal(handler
->conf
->monitor_signal_pdeath
,
1436 handler
->monitor_pid
, status_fd
);
1438 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1439 handler
->conf
->monitor_signal_pdeath
);
1440 goto out_warn_father
;
1445 * After this call, we are in error because this ops should not return
1448 handler
->ops
->start(handler
, handler
->data
);
1452 * We want the parent to know something went wrong, so we return a
1453 * special error code.
1455 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1461 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1464 struct lxc_terminal_info
*tty
;
1466 int sock
= handler
->data_sock
[1];
1467 struct lxc_conf
*conf
= handler
->conf
;
1468 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1470 if (!conf
->ttys
.max
)
1473 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
1477 for (i
= 0; i
< conf
->ttys
.max
; i
++) {
1480 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1484 tty
= &ttys
->tty
[i
];
1486 tty
->ptx
= ttyfds
[0];
1487 tty
->pty
= ttyfds
[1];
1488 TRACE("Received pty with ptx fd %d and pty fd %d from child", tty
->ptx
, tty
->pty
);
1492 SYSERROR("Failed to receive %zu ttys from child", ttys
->max
);
1494 TRACE("Received %zu ttys from child", ttys
->max
);
1499 int resolve_clone_flags(struct lxc_handler
*handler
)
1502 struct lxc_conf
*conf
= handler
->conf
;
1503 bool wants_timens
= conf
->timens
.s_boot
|| conf
->timens
.ns_boot
||
1504 conf
->timens
.s_monotonic
|| conf
->timens
.ns_monotonic
;
1506 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1507 if (conf
->ns_keep
) {
1508 if (!(conf
->ns_keep
& ns_info
[i
].clone_flag
))
1509 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1510 } else if (conf
->ns_clone
) {
1511 if ((conf
->ns_clone
& ns_info
[i
].clone_flag
))
1512 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1514 if (i
== LXC_NS_USER
&& lxc_list_empty(&handler
->conf
->id_map
))
1517 if (i
== LXC_NS_NET
&& lxc_requests_empty_network(handler
))
1520 if (i
== LXC_NS_CGROUP
&& !cgns_supported())
1523 if (i
== LXC_NS_TIME
&& !wants_timens
)
1526 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1529 if (!conf
->ns_share
[i
])
1532 handler
->ns_clone_flags
&= ~ns_info
[i
].clone_flag
;
1533 TRACE("Sharing %s namespace", ns_info
[i
].proc_name
);
1536 if (wants_timens
&& (conf
->ns_keep
& ns_info
[LXC_NS_TIME
].clone_flag
))
1537 return log_trace_errno(-1, EINVAL
, "Requested to keep time namespace while also specifying offsets");
1539 /* Deal with namespaces that are unshared. */
1540 if (handler
->ns_clone_flags
& CLONE_NEWTIME
)
1541 handler
->ns_unshare_flags
|= CLONE_NEWTIME
;
1543 if (!pure_unified_layout(handler
->cgroup_ops
) && handler
->ns_clone_flags
& CLONE_NEWCGROUP
)
1544 handler
->ns_unshare_flags
|= CLONE_NEWCGROUP
;
1546 if ((handler
->ns_clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
1547 (CLONE_NEWNET
| CLONE_NEWUSER
))
1548 handler
->ns_unshare_flags
|= CLONE_NEWNET
;
1550 /* Deal with namespaces that are spawned. */
1551 handler
->ns_on_clone_flags
= handler
->ns_clone_flags
& ~handler
->ns_unshare_flags
;
1553 handler
->clone_flags
= handler
->ns_on_clone_flags
| CLONE_PIDFD
;
1558 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1559 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1560 * But since the memory between parent and child is shared on CLONE_VM this
1561 * would invalidate the getpid() cache that glibc used to maintain and so
1562 * getpid() in the child would return the parent's pid. This is all fixed in
1563 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1564 * not reset anymore.
1565 * However, if for whatever reason you - dear committer - somehow need to get the
1566 * pid of the dummy intermediate process for do_share_ns() you need to call
1567 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1570 static inline int do_share_ns(void *arg
)
1573 struct lxc_handler
*handler
= arg
;
1575 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1576 if (handler
->nsfd
[i
] < 0)
1579 ret
= setns(handler
->nsfd
[i
], 0);
1582 * Note that joining a user and/or mount namespace
1583 * requires the process is not multithreaded otherwise
1584 * setns() will fail here.
1586 SYSERROR("Failed to inherit %s namespace",
1587 ns_info
[i
].proc_name
);
1591 DEBUG("Inherited %s namespace", ns_info
[i
].proc_name
);
1594 flags
= handler
->ns_on_clone_flags
;
1595 flags
|= CLONE_PARENT
;
1596 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, CLONE_PIDFD
| flags
,
1598 if (handler
->pid
< 0)
1604 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1605 * exec()s the requested container binary.
1606 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1607 * right here should be double checked if they'd pose a security risk. (For
1608 * example, any {u}mount() operations performed here will be reflected on the
1611 static int lxc_spawn(struct lxc_handler
*handler
)
1613 __do_close
int data_sock0
= -EBADF
, data_sock1
= -EBADF
;
1616 bool wants_to_map_ids
;
1617 struct lxc_list
*id_map
;
1618 const char *name
= handler
->name
;
1619 const char *lxcpath
= handler
->lxcpath
;
1620 bool share_ns
= false;
1621 struct lxc_conf
*conf
= handler
->conf
;
1622 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
1624 id_map
= &conf
->id_map
;
1625 wants_to_map_ids
= !lxc_list_empty(id_map
);
1627 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1628 if (!conf
->ns_share
[i
])
1631 handler
->nsfd
[i
] = lxc_inherit_namespace(conf
->ns_share
[i
], lxcpath
, ns_info
[i
].proc_name
);
1632 if (handler
->nsfd
[i
] < 0)
1638 ret
= lxc_sync_init(handler
);
1642 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1643 handler
->data_sock
);
1646 data_sock0
= handler
->data_sock
[0];
1647 data_sock1
= handler
->data_sock
[1];
1649 ret
= resolve_clone_flags(handler
);
1653 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1654 ret
= lxc_find_gateway_addresses(handler
);
1656 ERROR("Failed to find gateway addresses");
1661 if (!cgroup_ops
->payload_create(cgroup_ops
, handler
)) {
1662 ERROR("Failed creating cgroups");
1663 goto out_delete_net
;
1666 /* If the rootfs is not a blockdev, prevent the container from marking
1668 * If the container is unprivileged then skip rootfs pinning.
1670 if (!wants_to_map_ids
) {
1671 handler
->pinfd
= pin_rootfs(conf
->rootfs
.path
);
1672 if (handler
->pinfd
== -EBADF
)
1673 INFO("Failed to pin the rootfs for container \"%s\"", handler
->name
);
1676 /* Create a process in a new set of namespaces. */
1680 attacher_pid
= lxc_clone(do_share_ns
, handler
,
1681 CLONE_VFORK
| CLONE_VM
| CLONE_FILES
, NULL
);
1682 if (attacher_pid
< 0) {
1683 SYSERROR(LXC_CLONE_ERROR
);
1684 goto out_delete_net
;
1687 ret
= wait_for_pid(attacher_pid
);
1689 SYSERROR("Intermediate process failed");
1690 goto out_delete_net
;
1693 if (handler
->pid
< 0) {
1694 SYSERROR(LXC_CLONE_ERROR
);
1695 goto out_delete_net
;
1698 int cgroup_fd
= -EBADF
;
1700 struct lxc_clone_args clone_args
= {
1701 .flags
= handler
->clone_flags
,
1702 .pidfd
= ptr_to_u64(&handler
->pidfd
),
1703 .exit_signal
= SIGCHLD
,
1706 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1707 cgroup_fd
= cgroup_unified_fd(cgroup_ops
);
1708 if (cgroup_fd
>= 0) {
1709 handler
->clone_flags
|= CLONE_INTO_CGROUP
;
1710 clone_args
.flags
|= CLONE_INTO_CGROUP
;
1711 clone_args
.cgroup
= cgroup_fd
;
1715 /* Try to spawn directly into target cgroup. */
1716 handler
->pid
= lxc_clone3(&clone_args
, CLONE_ARGS_SIZE_VER2
);
1717 if (handler
->pid
< 0) {
1718 SYSTRACE("Failed to spawn container directly into target cgroup");
1720 /* Kernel might simply be too old for CLONE_INTO_CGROUP. */
1721 handler
->clone_flags
&= ~(CLONE_INTO_CGROUP
| CLONE_NEWCGROUP
);
1722 handler
->ns_on_clone_flags
&= ~CLONE_NEWCGROUP
;
1723 handler
->ns_unshare_flags
|= CLONE_NEWCGROUP
;
1725 clone_args
.flags
= handler
->clone_flags
;
1727 handler
->pid
= lxc_clone3(&clone_args
, CLONE_ARGS_SIZE_VER0
);
1728 } else if (cgroup_fd
>= 0) {
1729 TRACE("Spawned container directly into target cgroup via cgroup2 fd %d", cgroup_fd
);
1732 /* Kernel might be too old for clone3(). */
1733 if (handler
->pid
< 0) {
1734 SYSTRACE("Failed to spawn container via clone3()");
1735 handler
->pid
= lxc_raw_legacy_clone(handler
->clone_flags
, &handler
->pidfd
);
1738 if (handler
->pid
< 0) {
1739 SYSERROR(LXC_CLONE_ERROR
);
1740 goto out_delete_net
;
1743 if (handler
->pid
== 0) {
1744 (void)do_start(handler
);
1745 _exit(EXIT_FAILURE
);
1748 if (handler
->pidfd
< 0)
1749 handler
->clone_flags
&= ~CLONE_PIDFD
;
1750 TRACE("Cloned child process %d", handler
->pid
);
1752 /* Verify that we can actually make use of pidfds. */
1753 if (!lxc_can_use_pidfd(handler
->pidfd
))
1754 close_prot_errno_disarm(handler
->pidfd
);
1756 ret
= snprintf(pidstr
, 20, "%d", handler
->pid
);
1757 if (ret
< 0 || ret
>= 20)
1758 goto out_delete_net
;
1760 ret
= setenv("LXC_PID", pidstr
, 1);
1762 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr
);
1764 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1765 if (handler
->ns_on_clone_flags
& ns_info
[i
].clone_flag
)
1766 INFO("Cloned %s", ns_info
[i
].flag_name
);
1768 if (!lxc_try_preserve_namespaces(handler
, handler
->ns_on_clone_flags
, handler
->pid
)) {
1769 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1770 goto out_delete_net
;
1773 lxc_sync_fini_child(handler
);
1775 if (lxc_abstract_unix_send_fds(handler
->data_sock
[0], &handler
->monitor_status_fd
, 1, NULL
, 0) < 0) {
1776 ERROR("Failed to send status file descriptor to child process");
1777 goto out_delete_net
;
1779 close_prot_errno_disarm(handler
->monitor_status_fd
);
1781 /* Map the container uids. The container became an invalid userid the
1782 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1783 * anything immediately, but allows the container to setuid(0) (0 being
1784 * mapped to something else on the host.) later to become a valid uid
1787 if (wants_to_map_ids
) {
1788 if (!handler
->conf
->ns_share
[LXC_NS_USER
] &&
1789 (handler
->conf
->ns_keep
& CLONE_NEWUSER
) == 0) {
1790 ret
= lxc_map_ids(id_map
, handler
->pid
);
1792 ERROR("Failed to set up id mapping.");
1793 goto out_delete_net
;
1798 ret
= lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
);
1800 goto out_delete_net
;
1802 ret
= lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
);
1804 goto out_delete_net
;
1806 if (!cgroup_ops
->setup_limits_legacy(cgroup_ops
, handler
->conf
, false)) {
1807 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1808 goto out_delete_net
;
1811 if (!cgroup_ops
->payload_enter(cgroup_ops
, handler
)) {
1812 ERROR("Failed to enter cgroups");
1813 goto out_delete_net
;
1816 if (!cgroup_ops
->payload_delegate_controllers(cgroup_ops
)) {
1817 ERROR("Failed to delegate controllers to payload cgroup");
1818 goto out_delete_net
;
1821 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
)) {
1822 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1823 goto out_delete_net
;
1826 if (!cgroup_ops
->chown(cgroup_ops
, handler
->conf
))
1827 goto out_delete_net
;
1829 /* If not done yet, we're now ready to preserve the network namespace */
1830 if (handler
->nsfd
[LXC_NS_NET
] < 0) {
1831 ret
= lxc_try_preserve_ns(handler
->pid
, "net");
1833 if (ret
!= -EOPNOTSUPP
) {
1834 SYSERROR("Failed to preserve net namespace");
1835 goto out_delete_net
;
1838 handler
->nsfd
[LXC_NS_NET
] = ret
;
1839 DEBUG("Preserved net namespace via fd %d", ret
);
1842 ret
= lxc_netns_set_nsid(handler
->nsfd
[LXC_NS_NET
]);
1844 SYSWARN("Failed to allocate new network namespace id");
1846 TRACE("Allocated new network namespace id");
1848 /* Create the network configuration. */
1849 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1850 ret
= lxc_create_network(handler
);
1852 ERROR("Failed to create the network");
1853 goto out_delete_net
;
1856 ret
= lxc_network_send_to_child(handler
);
1858 ERROR("Failed to send veth names to child");
1859 goto out_delete_net
;
1863 if (!lxc_list_empty(&conf
->procs
)) {
1864 ret
= setup_proc_filesystem(&conf
->procs
, handler
->pid
);
1866 goto out_delete_net
;
1869 /* Tell the child to continue its initialization. We'll get
1870 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1872 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
);
1874 goto out_delete_net
;
1876 if (!lxc_list_empty(&conf
->limits
)) {
1877 ret
= setup_resource_limits(&conf
->limits
, handler
->pid
);
1879 ERROR("Failed to setup resource limits");
1880 goto out_delete_net
;
1884 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
);
1886 goto out_delete_net
;
1889 * with isolation the limiting devices cgroup was already setup, so
1890 * only setup devices here if we have no namespace directory
1892 if (!handler
->conf
->cgroup_meta
.namespace_dir
&&
1893 !cgroup_ops
->setup_limits_legacy(cgroup_ops
, handler
->conf
, true)) {
1894 ERROR("Failed to setup legacy device cgroup controller limits");
1895 goto out_delete_net
;
1897 TRACE("Set up legacy device cgroup controller limits");
1899 if (!cgroup_ops
->devices_activate(cgroup_ops
, handler
)) {
1900 ERROR("Failed to setup cgroup2 device controller limits");
1901 goto out_delete_net
;
1903 TRACE("Set up cgroup2 device controller limits");
1905 if (handler
->ns_unshare_flags
& CLONE_NEWCGROUP
) {
1906 /* Now we're ready to preserve the cgroup namespace */
1907 ret
= lxc_try_preserve_ns(handler
->pid
, "cgroup");
1909 if (ret
!= -EOPNOTSUPP
) {
1910 SYSERROR("Failed to preserve cgroup namespace");
1911 goto out_delete_net
;
1914 handler
->nsfd
[LXC_NS_CGROUP
] = ret
;
1915 DEBUG("Preserved cgroup namespace via fd %d", ret
);
1919 cgroup_ops
->payload_finalize(cgroup_ops
);
1920 TRACE("Finished setting up cgroups");
1922 if (handler
->ns_unshare_flags
& CLONE_NEWTIME
) {
1923 /* Now we're ready to preserve the cgroup namespace */
1924 ret
= lxc_try_preserve_ns(handler
->pid
, "time");
1926 if (ret
!= -EOPNOTSUPP
) {
1927 SYSERROR("Failed to preserve time namespace");
1928 goto out_delete_net
;
1931 handler
->nsfd
[LXC_NS_TIME
] = ret
;
1932 DEBUG("Preserved time namespace via fd %d", ret
);
1936 /* Run any host-side start hooks */
1937 ret
= run_lxc_hooks(name
, "start-host", conf
, NULL
);
1939 ERROR("Failed to run lxc.hook.start-host");
1940 goto out_delete_net
;
1943 /* Tell the child to complete its initialization and wait for it to exec
1944 * or return an error. (The child will never return
1945 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1946 * lxc_sync_barrier_child to return success, or return a different
1947 * value, causing us to error out).
1949 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_READY_START
);
1951 goto out_delete_net
;
1953 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1954 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
1956 ERROR("Failed to receive names and ifindices for network devices from child");
1957 goto out_delete_net
;
1961 /* Now all networks are created, network devices are moved into place,
1962 * and the correct names and ifindices in the respective namespaces have
1963 * been recorded. The corresponding structs have now all been filled. So
1964 * log them for debugging purposes.
1966 lxc_log_configured_netdevs(conf
);
1968 /* Read tty fds allocated by child. */
1969 ret
= lxc_recv_ttys_from_child(handler
);
1971 ERROR("Failed to receive tty info from child process");
1972 goto out_delete_net
;
1975 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, data_sock1
);
1977 SYSERROR("Failed to receive seccomp notify fd from child");
1978 goto out_delete_net
;
1981 ret
= handler
->ops
->post_start(handler
, handler
->data
);
1985 ret
= lxc_set_state(name
, handler
, RUNNING
);
1987 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING
));
1991 lxc_sync_fini(handler
);
1996 if (handler
->ns_clone_flags
& CLONE_NEWNET
)
1997 lxc_delete_network(handler
);
2003 lxc_sync_fini(handler
);
2004 close_prot_errno_disarm(handler
->pinfd
);
2009 int __lxc_start(struct lxc_handler
*handler
, struct lxc_operations
*ops
,
2010 void *data
, const char *lxcpath
, bool daemonize
, int *error_num
)
2013 const char *name
= handler
->name
;
2014 struct lxc_conf
*conf
= handler
->conf
;
2015 struct cgroup_ops
*cgroup_ops
;
2017 ret
= lxc_init(name
, handler
);
2019 ERROR("Failed to initialize container \"%s\"", name
);
2023 handler
->data
= data
;
2024 handler
->daemonize
= daemonize
;
2025 cgroup_ops
= handler
->cgroup_ops
;
2027 if (!attach_block_device(handler
->conf
)) {
2028 ERROR("Failed to attach block device");
2033 if (!cgroup_ops
->monitor_create(cgroup_ops
, handler
)) {
2034 ERROR("Failed to create monitor cgroup");
2039 if (!cgroup_ops
->monitor_enter(cgroup_ops
, handler
)) {
2040 ERROR("Failed to enter monitor cgroup");
2045 if (!cgroup_ops
->monitor_delegate_controllers(cgroup_ops
)) {
2046 ERROR("Failed to delegate controllers to monitor cgroup");
2051 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
2052 /* If the backing store is a device, mount it here and now. */
2053 if (rootfs_is_blockdev(conf
)) {
2054 ret
= unshare(CLONE_NEWNS
);
2056 ERROR("Failed to unshare CLONE_NEWNS");
2059 INFO("Unshared CLONE_NEWNS");
2061 turn_into_dependent_mounts();
2062 ret
= lxc_setup_rootfs_prepare_root(conf
, name
, lxcpath
);
2064 ERROR("Error setting up rootfs mount as root before spawn");
2067 INFO("Set up container rootfs as host root");
2071 ret
= lxc_spawn(handler
);
2073 ERROR("Failed to spawn container \"%s\"", name
);
2074 goto out_detach_blockdev
;
2077 handler
->conf
->reboot
= REBOOT_NONE
;
2079 ret
= lxc_poll(name
, handler
);
2081 ERROR("LXC mainloop exited with error: %d", ret
);
2082 goto out_delete_network
;
2085 if (!handler
->init_died
&& handler
->pid
> 0) {
2086 ERROR("Child process is not killed");
2088 goto out_delete_network
;
2091 status
= lxc_wait_for_pid_status(handler
->pid
);
2093 SYSERROR("Failed to retrieve status for %d", handler
->pid
);
2095 /* If the child process exited but was not signaled, it didn't call
2096 * reboot. This should mean it was an lxc-execute which simply exited.
2097 * In any case, treat it as a 'halt'.
2099 if (WIFSIGNALED(status
)) {
2100 switch(WTERMSIG(status
)) {
2101 case SIGINT
: /* halt */
2102 DEBUG("Container \"%s\" is halting", name
);
2104 case SIGHUP
: /* reboot */
2105 DEBUG("Container \"%s\" is rebooting", name
);
2106 handler
->conf
->reboot
= REBOOT_REQ
;
2108 case SIGSYS
: /* seccomp */
2109 DEBUG("Container \"%s\" violated its seccomp policy", name
);
2112 DEBUG("Unknown exit status for container \"%s\" init %d", name
, WTERMSIG(status
));
2117 ret
= lxc_restore_phys_nics_to_netns(handler
);
2119 ERROR("Failed to move physical network devices back to parent network namespace");
2121 close_prot_errno_disarm(handler
->pinfd
);
2123 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
2124 lxc_error_set_and_log(handler
->pid
, status
);
2126 *error_num
= handler
->exit_status
;
2128 /* These are not the droids you are looking for. */
2130 lxc_delete_network(handler
);
2133 detach_block_device(handler
->conf
);
2140 /* These are the droids you are looking for. */
2143 goto __private_goto3
;
2145 out_detach_blockdev
:
2147 goto __private_goto2
;
2151 goto __private_goto1
;
2158 static int start(struct lxc_handler
*handler
, void* data
)
2160 struct start_args
*arg
= data
;
2162 NOTICE("Exec'ing \"%s\"", arg
->argv
[0]);
2164 execvp(arg
->argv
[0], arg
->argv
);
2165 SYSERROR("Failed to exec \"%s\"", arg
->argv
[0]);
2169 static int post_start(struct lxc_handler
*handler
, void* data
)
2171 struct start_args
*arg
= data
;
2173 NOTICE("Started \"%s\" with pid \"%d\"", arg
->argv
[0], handler
->pid
);
2177 static struct lxc_operations start_ops
= {
2179 .post_start
= post_start
2182 int lxc_start(char *const argv
[], struct lxc_handler
*handler
,
2183 const char *lxcpath
, bool daemonize
, int *error_num
)
2185 struct start_args start_arg
= {
2189 TRACE("Doing lxc_start");
2190 return __lxc_start(handler
, &start_ops
, &start_arg
, lxcpath
, daemonize
, error_num
);
2193 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
2196 char destroy
[PATH_MAX
];
2197 struct lxc_container
*c
;
2201 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
2202 bret
= do_destroy_container(handler
);
2204 ERROR("Error destroying rootfs for container \"%s\"", name
);
2208 INFO("Destroyed rootfs for container \"%s\"", name
);
2210 ret
= snprintf(destroy
, PATH_MAX
, "%s/%s", handler
->lxcpath
, name
);
2211 if (ret
< 0 || ret
>= PATH_MAX
) {
2212 ERROR("Error destroying directory for container \"%s\"", name
);
2216 c
= lxc_container_new(name
, handler
->lxcpath
);
2218 if (container_disk_lock(c
)) {
2219 INFO("Could not update lxc_snapshots file");
2220 lxc_container_put(c
);
2222 mod_all_rdeps(c
, false);
2223 container_disk_unlock(c
);
2224 lxc_container_put(c
);
2228 if (!handler
->am_root
)
2229 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
2230 destroy
, "lxc_rmdir_onedev_wrapper");
2232 ret
= lxc_rmdir_onedev(destroy
, NULL
);
2235 ERROR("Error destroying directory for container \"%s\"", name
);
2238 INFO("Destroyed directory for container \"%s\"", name
);
2241 static int lxc_rmdir_onedev_wrapper(void *data
)
2243 char *arg
= (char *) data
;
2244 return lxc_rmdir_onedev(arg
, NULL
);
2247 static bool do_destroy_container(struct lxc_handler
*handler
)
2251 if (!handler
->am_root
) {
2252 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
2253 handler
->conf
, "storage_destroy_wrapper");
2260 return storage_destroy(handler
->conf
);