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"
36 #include "confile_utils.h"
38 #include "file_utils.h"
42 #include "lxccontainer.h"
44 #include "lxcseccomp.h"
47 #include "memory_utils.h"
49 #include "namespace.h"
51 #include "process_utils.h"
53 #include "storage/storage.h"
54 #include "storage/storage_utils.h"
56 #include "syscall_wrappers.h"
61 #include <sys/capability.h>
65 #include "include/strlcpy.h"
68 lxc_log_define(start
, lxc
);
70 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
71 static bool do_destroy_container(struct lxc_handler
*handler
);
72 static int lxc_rmdir_onedev_wrapper(void *data
);
73 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
76 static void print_top_failing_dir(const char *path
)
78 __do_free
char *copy
= NULL
;
82 copy
= must_copy_string(path
);
84 e
= copy
+ strlen(path
);
87 while (p
< e
&& *p
== '/')
90 while (p
< e
&& *p
!= '/')
96 ret
= access(copy
, X_OK
);
98 SYSERROR("Could not access %s. Please grant it x access, or add an ACL for the container " "root", copy
);
105 static void lxc_put_nsfds(struct lxc_handler
*handler
)
107 for (int i
= 0; i
< LXC_NS_MAX
; i
++) {
108 if (handler
->nsfd
[i
] < 0)
111 close_prot_errno_disarm(handler
->nsfd
[i
]);
115 static int lxc_try_preserve_ns(const int pid
, const char *ns
)
119 fd
= lxc_preserve_ns(pid
, ns
);
122 return log_error_errno(-EINVAL
,
123 errno
, "Failed to preserve %s namespace",
126 return log_warn_errno(-EOPNOTSUPP
,
127 errno
, "Kernel does not support preserving %s namespaces",
134 /* lxc_try_preserve_namespaces: open /proc/@pid/ns/@ns for each namespace
135 * specified in ns_clone_flags.
136 * Return true on success, false on failure.
138 static bool lxc_try_preserve_namespaces(struct lxc_handler
*handler
,
139 int ns_clone_flags
, pid_t pid
)
143 for (i
= 0; i
< LXC_NS_MAX
; i
++)
144 handler
->nsfd
[i
] = -EBADF
;
146 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
149 if ((ns_clone_flags
& ns_info
[i
].clone_flag
) == 0)
152 fd
= lxc_try_preserve_ns(pid
, ns_info
[i
].proc_name
);
154 /* Do not fail to start container on kernels that do
155 * not support interacting with namespaces through
158 if (fd
== -EOPNOTSUPP
)
161 lxc_put_nsfds(handler
);
165 handler
->nsfd
[i
] = fd
;
166 DEBUG("Preserved %s namespace via fd %d", ns_info
[i
].proc_name
,
173 static inline bool match_stdfds(int fd
)
175 return (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
);
179 static bool match_dlog_fds(struct dirent
*direntp
)
181 char path
[PATH_MAX
] = {0};
182 char link
[PATH_MAX
] = {0};
186 ret
= snprintf(path
, PATH_MAX
, "/proc/self/fd/%s", direntp
->d_name
);
187 if (ret
< 0 || ret
>= PATH_MAX
)
188 return log_error(false, "Failed to create file descriptor name");
190 linklen
= readlink(path
, link
, PATH_MAX
);
192 return log_error(false, "Failed to read link path - \"%s\"", path
);
193 else if (linklen
>= PATH_MAX
)
194 return log_error(false, "The name of link path is too long - \"%s\"", path
);
196 if (strcmp(link
, "/dev/log_main") == 0 ||
197 strcmp(link
, "/dev/log_system") == 0 ||
198 strcmp(link
, "/dev/log_radio") == 0)
205 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
206 int *fds_to_ignore
, size_t len_fds
)
211 struct dirent
*direntp
;
213 if (conf
&& conf
->close_all_fds
)
217 * Disable syslog at this point to avoid the above logging
218 * function to open a new fd and make the check_inherited function
219 * enter an infinite loop.
221 lxc_log_syslog_disable();
224 dir
= opendir("/proc/self/fd");
226 return log_warn(-1, "Failed to open directory");
230 while ((direntp
= readdir(dir
))) {
232 struct lxc_list
*cur
;
233 bool matched
= false;
235 if (strcmp(direntp
->d_name
, ".") == 0)
238 if (strcmp(direntp
->d_name
, "..") == 0)
241 ret
= lxc_safe_int(direntp
->d_name
, &fd
);
243 INFO("Could not parse file descriptor for \"%s\"", direntp
->d_name
);
247 for (i
= 0; i
< len_fds
; i
++)
248 if (fds_to_ignore
[i
] == fd
)
251 if (fd
== fddir
|| fd
== lxc_log_fd
||
252 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
255 /* Keep state clients that wait on reboots. */
257 lxc_list_for_each(cur
, &conf
->state_clients
) {
258 struct lxc_state_client
*client
= cur
->elem
;
260 if (client
->clientfd
!= fd
)
271 if (current_config
&& fd
== current_config
->logfd
)
274 if (match_stdfds(fd
))
278 if (match_dlog_fds(direntp
))
284 SYSINFO("Closed inherited fd %d", fd
);
286 INFO("Closed inherited fd %d", fd
);
290 WARN("Inherited fd %d", fd
);
295 * Only enable syslog at this point to avoid the above logging
296 * function to open a new fd and make the check_inherited function
297 * enter an infinite loop.
299 lxc_log_syslog_enable();
304 static int setup_signal_fd(sigset_t
*oldmask
)
308 const int signals
[] = {SIGBUS
, SIGILL
, SIGSEGV
, SIGWINCH
};
310 /* Block everything except serious error signals. */
311 ret
= sigfillset(&mask
);
315 for (int sig
= 0; sig
< (sizeof(signals
) / sizeof(signals
[0])); sig
++) {
316 ret
= sigdelset(&mask
, signals
[sig
]);
321 ret
= pthread_sigmask(SIG_BLOCK
, &mask
, oldmask
);
323 return log_error_errno(-EBADF
, errno
,
324 "Failed to set signal mask");
326 ret
= signalfd(-1, &mask
, SFD_CLOEXEC
);
328 return log_error_errno(-EBADF
,
329 errno
, "Failed to create signal file descriptor");
331 TRACE("Created signal file descriptor %d", ret
);
336 static int signal_handler(int fd
, uint32_t events
, void *data
,
337 struct lxc_epoll_descr
*descr
)
341 struct signalfd_siginfo siginfo
;
342 struct lxc_handler
*hdlr
= data
;
344 ret
= lxc_read_nointr(fd
, &siginfo
, sizeof(siginfo
));
346 return log_error(LXC_MAINLOOP_ERROR
, "Failed to read signal info from signal file descriptor %d", fd
);
348 if (ret
!= sizeof(siginfo
))
349 return log_error(LXC_MAINLOOP_ERROR
, "Unexpected size for struct signalfd_siginfo");
351 /* Check whether init is running. */
353 ret
= waitid(P_PID
, hdlr
->pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
354 if (ret
== 0 && info
.si_pid
== hdlr
->pid
)
355 hdlr
->init_died
= true;
357 /* Try to figure out a reasonable exit status to report. */
358 if (hdlr
->init_died
) {
359 switch (info
.si_code
) {
361 hdlr
->exit_status
= info
.si_status
<< 8;
366 hdlr
->exit_status
= info
.si_status
<< 8 | 0x7f;
369 /* Huh? The waitid() told us it's dead *and* continued? */
370 WARN("Init %d dead and continued?", hdlr
->pid
);
371 hdlr
->exit_status
= 1;
374 ERROR("Unknown si_code: %d", info
.si_code
);
375 hdlr
->exit_status
= 1;
379 if (siginfo
.ssi_signo
== SIGHUP
) {
380 if (hdlr
->pidfd
>= 0)
381 lxc_raw_pidfd_send_signal(hdlr
->pidfd
, SIGTERM
, NULL
, 0);
383 kill(hdlr
->pid
, SIGTERM
);
384 INFO("Killing %d since terminal hung up", hdlr
->pid
);
385 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
386 : LXC_MAINLOOP_CONTINUE
;
389 if (siginfo
.ssi_signo
!= SIGCHLD
) {
390 if (hdlr
->pidfd
>= 0)
391 lxc_raw_pidfd_send_signal(hdlr
->pidfd
,
392 siginfo
.ssi_signo
, NULL
, 0);
394 kill(hdlr
->pid
, siginfo
.ssi_signo
);
395 INFO("Forwarded signal %d to pid %d", siginfo
.ssi_signo
, hdlr
->pid
);
396 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
397 : LXC_MAINLOOP_CONTINUE
;
400 /* More robustness, protect ourself from a SIGCHLD sent
401 * by a process different from the container init.
403 if (siginfo
.ssi_pid
!= hdlr
->pid
) {
404 NOTICE("Received %d from pid %d instead of container init %d",
405 siginfo
.ssi_signo
, siginfo
.ssi_pid
, hdlr
->pid
);
406 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
407 : LXC_MAINLOOP_CONTINUE
;
410 if (siginfo
.ssi_code
== CLD_STOPPED
) {
411 INFO("Container init process was stopped");
412 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
413 : LXC_MAINLOOP_CONTINUE
;
416 if (siginfo
.ssi_code
== CLD_CONTINUED
) {
417 INFO("Container init process was continued");
418 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
419 : LXC_MAINLOOP_CONTINUE
;
422 return log_debug(LXC_MAINLOOP_CLOSE
, "Container init process %d exited", hdlr
->pid
);
425 int lxc_serve_state_clients(const char *name
, struct lxc_handler
*handler
,
430 struct lxc_list
*cur
, *next
;
431 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
434 handler
->state
= RUNNING
;
436 handler
->state
= state
;
438 TRACE("Set container state to %s", lxc_state2str(state
));
440 if (lxc_list_empty(&handler
->conf
->state_clients
))
441 return log_trace(0, "No state clients registered");
443 retlen
= strlcpy(msg
.name
, name
, sizeof(msg
.name
));
444 if (retlen
>= sizeof(msg
.name
))
447 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
448 struct lxc_state_client
*client
= cur
->elem
;
450 if (client
->states
[state
] == 0) {
451 TRACE("State %s not registered for state client %d",
452 lxc_state2str(state
), client
->clientfd
);
456 TRACE("Sending state %s to state client %d",
457 lxc_state2str(state
), client
->clientfd
);
459 ret
= lxc_send_nointr(client
->clientfd
, &msg
, sizeof(msg
), MSG_NOSIGNAL
);
461 SYSERROR("Failed to send message to client");
463 /* kick client from list */
465 close(client
->clientfd
);
473 static int lxc_serve_state_socket_pair(const char *name
,
474 struct lxc_handler
*handler
,
479 if (!handler
->daemonize
||
480 handler
->state_socket_pair
[1] < 0 ||
484 /* Close read end of the socket pair. */
485 close_prot_errno_disarm(handler
->state_socket_pair
[0]);
488 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
489 &(int){state
}, sizeof(int));
491 SYSERROR("Failed to send state to %d", handler
->state_socket_pair
[1]);
499 if (ret
!= sizeof(int))
500 return log_error(-1, "Message too long : %d", handler
->state_socket_pair
[1]);
502 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
503 handler
->state_socket_pair
[1]);
505 /* Close write end of the socket pair. */
506 close_prot_errno_disarm(handler
->state_socket_pair
[1]);
511 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
516 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
518 return log_error(-1, "Failed to synchronize via anonymous pair of unix sockets");
520 ret
= lxc_serve_state_clients(name
, handler
, state
);
524 /* This function will try to connect to the legacy lxc-monitord state
525 * server and only exists for backwards compatibility.
527 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
532 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
535 bool has_console
= true;
536 struct lxc_epoll_descr descr
, descr_console
;
538 if (handler
->conf
->console
.path
&&
539 strcmp(handler
->conf
->console
.path
, "none") == 0)
542 ret
= lxc_mainloop_open(&descr
);
544 ERROR("Failed to create mainloop");
549 ret
= lxc_mainloop_open(&descr_console
);
551 ERROR("Failed to create console mainloop");
556 ret
= lxc_mainloop_add_handler(&descr
, handler
->sigfd
, signal_handler
, handler
);
558 ERROR("Failed to add signal handler for %d to mainloop", handler
->sigfd
);
559 goto out_mainloop_console
;
562 ret
= lxc_seccomp_setup_proxy(&handler
->conf
->seccomp
, &descr
, handler
);
564 ERROR("Failed to setup seccomp proxy");
565 goto out_mainloop_console
;
569 struct lxc_terminal
*console
= &handler
->conf
->console
;
571 ret
= lxc_terminal_mainloop_add(&descr
, console
);
573 ERROR("Failed to add console handlers to mainloop");
574 goto out_mainloop_console
;
577 ret
= lxc_terminal_mainloop_add(&descr_console
, console
);
579 ERROR("Failed to add console handlers to console mainloop");
580 goto out_mainloop_console
;
583 handler
->conf
->console
.descr
= &descr
;
586 ret
= lxc_cmd_mainloop_add(name
, &descr
, handler
);
588 ERROR("Failed to add command handler to mainloop");
589 goto out_mainloop_console
;
592 TRACE("Mainloop is ready");
594 ret
= lxc_mainloop(&descr
, -1);
595 close_prot_errno_disarm(descr
.epfd
);
596 if (ret
< 0 || !handler
->init_died
)
597 goto out_mainloop_console
;
600 ret
= lxc_mainloop(&descr_console
, 0);
602 out_mainloop_console
:
604 lxc_mainloop_close(&descr_console
);
605 TRACE("Closed console mainloop");
609 lxc_mainloop_close(&descr
);
610 TRACE("Closed mainloop");
613 TRACE("Closed signal file descriptor %d", handler
->sigfd
);
614 close_prot_errno_disarm(handler
->sigfd
);
619 void lxc_put_handler(struct lxc_handler
*handler
)
621 close_prot_errno_disarm(handler
->pinfd
);
622 close_prot_errno_disarm(handler
->pidfd
);
623 close_prot_errno_disarm(handler
->sigfd
);
624 lxc_put_nsfds(handler
);
625 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
626 close_prot_errno_disarm(handler
->conf
->maincmd_fd
);
627 close_prot_errno_disarm(handler
->monitor_status_fd
);
628 close_prot_errno_disarm(handler
->state_socket_pair
[0]);
629 close_prot_errno_disarm(handler
->state_socket_pair
[1]);
630 cgroup_exit(handler
->cgroup_ops
);
631 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
632 free_disarm(handler
);
634 handler
->conf
= NULL
;
637 struct lxc_handler
*lxc_init_handler(struct lxc_handler
*old
,
638 const char *name
, struct lxc_conf
*conf
,
639 const char *lxcpath
, bool daemonize
)
643 struct lxc_handler
*handler
;
646 handler
= zalloc(sizeof(*handler
));
652 /* Note that am_guest_unpriv() checks the effective uid. We
653 * probably don't care if we are real root only if we are running
654 * as root so this should be fine.
656 handler
->am_root
= !am_guest_unpriv();
657 handler
->conf
= conf
;
658 handler
->lxcpath
= lxcpath
;
659 handler
->init_died
= false;
660 handler
->data_sock
[0] = -EBADF
;
661 handler
->data_sock
[1] = -EBADF
;
662 handler
->monitor_status_fd
= -EBADF
;
663 handler
->pinfd
= -EBADF
;
664 handler
->pidfd
= -EBADF
;
665 handler
->sigfd
= -EBADF
;
666 handler
->state_socket_pair
[0] = -EBADF
;
667 handler
->state_socket_pair
[1] = -EBADF
;
668 if (handler
->conf
->reboot
== REBOOT_NONE
)
669 lxc_list_init(&handler
->conf
->state_clients
);
671 for (int i
= 0; i
< LXC_NS_MAX
; i
++)
672 handler
->nsfd
[i
] = -EBADF
;
674 handler
->name
= name
;
676 handler
->transient_pid
= lxc_raw_getpid();
678 handler
->transient_pid
= -1;
680 if (daemonize
&& handler
->conf
->reboot
== REBOOT_NONE
) {
681 /* Create socketpair() to synchronize on daemonized startup.
682 * When the container reboots we don't need to synchronize
683 * again currently so don't open another socketpair().
685 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
686 handler
->state_socket_pair
);
688 ERROR("Failed to create anonymous pair of unix sockets");
692 TRACE("Created anonymous pair {%d,%d} of unix sockets",
693 handler
->state_socket_pair
[0],
694 handler
->state_socket_pair
[1]);
695 handler
->keep_fds
[nr_keep_fds
++] = handler
->state_socket_pair
[0];
696 handler
->keep_fds
[nr_keep_fds
++] = handler
->state_socket_pair
[1];
699 if (handler
->conf
->reboot
== REBOOT_NONE
) {
700 handler
->conf
->maincmd_fd
= lxc_cmd_init(name
, lxcpath
, "command");
701 if (handler
->conf
->maincmd_fd
< 0) {
702 ERROR("Failed to set up command socket");
705 handler
->keep_fds
[nr_keep_fds
++] = handler
->conf
->maincmd_fd
;
708 TRACE("Unix domain socket %d for command server is ready",
709 handler
->conf
->maincmd_fd
);
714 lxc_put_handler(handler
);
719 int lxc_init(const char *name
, struct lxc_handler
*handler
)
721 __do_close
int status_fd
= -EBADF
;
723 const char *loglevel
;
724 struct lxc_conf
*conf
= handler
->conf
;
726 handler
->monitor_pid
= lxc_raw_getpid();
727 status_fd
= open("/proc/self/status", O_RDONLY
| O_CLOEXEC
);
729 return log_error_errno(-1, errno
, "Failed to open monitor status fd");
732 TRACE("Initialized LSM");
734 /* Begin by setting the state to STARTING. */
735 ret
= lxc_set_state(name
, handler
, STARTING
);
737 return log_error(-1, "Failed to set state to \"%s\"", lxc_state2str(STARTING
));
738 TRACE("Set container state to \"STARTING\"");
740 /* Start of environment variable setup for hooks. */
741 ret
= setenv("LXC_NAME", name
, 1);
743 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name
);
746 ret
= setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1);
748 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s", conf
->rcfile
);
751 if (conf
->rootfs
.mount
) {
752 ret
= setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1);
754 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s", conf
->rootfs
.mount
);
757 if (conf
->rootfs
.path
) {
758 ret
= setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1);
760 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s", conf
->rootfs
.path
);
763 if (conf
->console
.path
) {
764 ret
= setenv("LXC_CONSOLE", conf
->console
.path
, 1);
766 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s", conf
->console
.path
);
769 if (conf
->console
.log_path
) {
770 ret
= setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1);
772 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s", conf
->console
.log_path
);
775 if (cgns_supported()) {
776 ret
= setenv("LXC_CGNS_AWARE", "1", 1);
778 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1");
781 loglevel
= lxc_log_priority_to_string(lxc_log_get_level());
782 ret
= setenv("LXC_LOG_LEVEL", loglevel
, 1);
784 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s", loglevel
);
786 if (conf
->hooks_version
== 0)
787 ret
= setenv("LXC_HOOK_VERSION", "0", 1);
789 ret
= setenv("LXC_HOOK_VERSION", "1", 1);
791 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf
->hooks_version
);
792 /* End of environment variable setup for hooks. */
794 TRACE("Set environment variables");
796 ret
= run_lxc_hooks(name
, "pre-start", conf
, NULL
);
798 return log_error(-1, "Failed to run lxc.hook.pre-start for container \"%s\"", name
);
799 TRACE("Ran pre-start hooks");
801 /* The signal fd has to be created before forking otherwise if the child
802 * process exits before we setup the signal fd, the event will be lost
803 * and the command will be stuck.
805 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
806 if (handler
->sigfd
< 0)
807 return log_error(-1, "Failed to setup SIGCHLD fd handler.");
808 TRACE("Set up signal fd");
810 /* Do this after setting up signals since it might unblock SIGWINCH. */
811 ret
= lxc_terminal_setup(conf
);
813 ERROR("Failed to create console");
814 goto out_restore_sigmask
;
816 TRACE("Created console");
818 ret
= lxc_terminal_map_ids(conf
, &conf
->console
);
820 ERROR("Failed to chown console");
821 goto out_delete_terminal
;
823 TRACE("Chowned console");
825 handler
->cgroup_ops
= cgroup_init(handler
->conf
);
826 if (!handler
->cgroup_ops
) {
827 ERROR("Failed to initialize cgroup driver");
828 goto out_delete_terminal
;
830 TRACE("Initialized cgroup driver");
832 ret
= lxc_read_seccomp_config(conf
);
834 return log_error(-1, "Failed loading seccomp policy");
835 TRACE("Read seccomp policy");
837 ret
= lsm_process_prepare(conf
, handler
->lxcpath
);
839 ERROR("Failed to initialize LSM");
840 goto out_delete_terminal
;
842 TRACE("Initialized LSM");
844 INFO("Container \"%s\" is initialized", name
);
845 handler
->monitor_status_fd
= move_fd(status_fd
);
849 lxc_terminal_delete(&handler
->conf
->console
);
852 (void)pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
857 void lxc_end(struct lxc_handler
*handler
)
861 struct lxc_list
*cur
, *next
;
862 char *namespaces
[LXC_NS_MAX
+ 1];
863 size_t namespace_count
= 0;
864 const char *name
= handler
->name
;
865 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
867 /* The STOPPING state is there for future cleanup code which can take
870 lxc_set_state(name
, handler
, STOPPING
);
872 self
= lxc_raw_getpid();
873 for (int i
= 0; i
< LXC_NS_MAX
; i
++) {
874 if (handler
->nsfd
[i
] < 0)
877 if (handler
->conf
->hooks_version
== 0)
878 ret
= asprintf(&namespaces
[namespace_count
],
879 "%s:/proc/%d/fd/%d", ns_info
[i
].proc_name
,
880 self
, handler
->nsfd
[i
]);
882 ret
= asprintf(&namespaces
[namespace_count
],
883 "/proc/%d/fd/%d", self
, handler
->nsfd
[i
]);
885 SYSERROR("Failed to allocate memory");
889 if (handler
->conf
->hooks_version
== 0) {
894 ret
= setenv(ns_info
[i
].env_name
, namespaces
[namespace_count
], 1);
896 SYSERROR("Failed to set environment variable %s=%s",
897 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
899 TRACE("Set environment variable %s=%s",
900 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
904 namespaces
[namespace_count
] = NULL
;
906 if (handler
->conf
->reboot
> REBOOT_NONE
) {
907 ret
= setenv("LXC_TARGET", "reboot", 1);
909 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot");
912 if (handler
->conf
->reboot
== REBOOT_NONE
) {
913 ret
= setenv("LXC_TARGET", "stop", 1);
915 SYSERROR("Failed to set environment variable: LXC_TARGET=stop");
918 if (handler
->conf
->hooks_version
== 0)
919 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, namespaces
);
921 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, NULL
);
923 ERROR("Failed to run \"lxc.hook.stop\" hook");
925 while (namespace_count
--)
926 free(namespaces
[namespace_count
]);
928 lsm_process_cleanup(handler
->conf
, handler
->lxcpath
);
931 cgroup_ops
->payload_destroy(cgroup_ops
, handler
);
932 cgroup_ops
->monitor_destroy(cgroup_ops
, handler
);
935 if (handler
->conf
->reboot
== REBOOT_NONE
) {
936 /* For all new state clients simply close the command socket.
937 * This will inform all state clients that the container is
938 * STOPPED and also prevents a race between a open()/close() on
939 * the command socket causing a new process to get ECONNREFUSED
940 * because we haven't yet closed the command socket.
942 close_prot_errno_disarm(handler
->conf
->maincmd_fd
);
943 TRACE("Closed command socket");
945 /* This function will try to connect to the legacy lxc-monitord
946 * state server and only exists for backwards compatibility.
948 lxc_monitor_send_state(name
, STOPPED
, handler
->lxcpath
);
950 /* The command socket is closed so no one can acces the command
951 * socket anymore so there's no need to lock it.
953 handler
->state
= STOPPED
;
954 TRACE("Set container state to \"STOPPED\"");
956 lxc_set_state(name
, handler
, STOPPED
);
957 TRACE("Set container state to \"STOPPED\"");
960 /* Avoid lingering namespace references. */
961 lxc_put_nsfds(handler
);
963 ret
= run_lxc_hooks(name
, "post-stop", handler
->conf
, NULL
);
965 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name
);
966 if (handler
->conf
->reboot
> REBOOT_NONE
) {
967 WARN("Container will be stopped instead of rebooted");
968 handler
->conf
->reboot
= REBOOT_NONE
;
970 ret
= setenv("LXC_TARGET", "stop", 1);
972 WARN("Failed to set environment variable: LXC_TARGET=stop");
976 /* Reset mask set by setup_signal_fd. */
977 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
979 SYSWARN("Failed to restore signal mask");
981 lxc_terminal_delete(&handler
->conf
->console
);
982 lxc_delete_tty(&handler
->conf
->ttys
);
984 /* The command socket is now closed, no more state clients can register
985 * themselves from now on. So free the list of state clients.
987 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
988 struct lxc_state_client
*client
= cur
->elem
;
990 /* Keep state clients that want to be notified about reboots. */
991 if ((handler
->conf
->reboot
> REBOOT_NONE
) &&
992 (client
->states
[RUNNING
] == 2))
995 /* close state client socket */
997 close(client
->clientfd
);
1002 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= REBOOT_REQ
)
1003 lxc_destroy_container_on_signal(handler
, name
);
1005 lxc_put_handler(handler
);
1008 void lxc_abort(struct lxc_handler
*handler
)
1013 lxc_set_state(handler
->name
, handler
, ABORTING
);
1015 if (handler
->pidfd
>= 0) {
1016 ret
= lxc_raw_pidfd_send_signal(handler
->pidfd
, SIGKILL
, NULL
, 0);
1018 SYSWARN("Failed to send SIGKILL via pidfd %d for process %d",
1019 handler
->pidfd
, handler
->pid
);
1022 if ((!ret
|| errno
!= ESRCH
) && handler
->pid
> 0)
1023 if (kill(handler
->pid
, SIGKILL
))
1024 SYSWARN("Failed to send SIGKILL to %d", handler
->pid
);
1027 ret
= waitpid(-1, &status
, 0);
1031 static int do_start(void *data
)
1033 struct lxc_handler
*handler
= data
;
1034 __lxc_unused __do_close
int data_sock0
= handler
->data_sock
[0],
1035 data_sock1
= handler
->data_sock
[1];
1036 __do_close
int devnull_fd
= -EBADF
, status_fd
= -EBADF
;
1040 struct lxc_list
*iterator
;
1044 lxc_sync_fini_parent(handler
);
1046 if (lxc_abstract_unix_recv_fds(data_sock1
, &status_fd
, 1, NULL
, 0) < 0) {
1047 ERROR("Failed to receive status file descriptor to child process");
1048 goto out_warn_father
;
1051 /* This prctl must be before the synchro, so if the parent dies before
1052 * we set the parent death signal, we will detect its death with the
1053 * synchro right after, otherwise we have a window where the parent can
1054 * exit before we set the pdeath signal leading to a unsupervized
1057 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
, status_fd
);
1059 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1060 goto out_warn_father
;
1063 ret
= lxc_ambient_caps_up();
1065 ERROR("Failed to raise ambient capabilities");
1066 goto out_warn_father
;
1069 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1071 SYSERROR("Failed to set signal mask");
1072 goto out_warn_father
;
1075 /* Don't leak the pinfd to the container. */
1076 close_prot_errno_disarm(handler
->pinfd
);
1078 ret
= lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
);
1080 goto out_warn_father
;
1082 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1083 * https://github.com/lxc/lxd/issues/1978.
1085 if (handler
->ns_unshare_flags
& CLONE_NEWNET
) {
1086 ret
= unshare(CLONE_NEWNET
);
1088 SYSERROR("Failed to unshare CLONE_NEWNET");
1089 goto out_warn_father
;
1091 INFO("Unshared CLONE_NEWNET");
1094 /* Tell the parent task it can begin to configure the container and wait
1097 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
);
1101 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1102 ret
= lxc_network_recv_from_parent(handler
);
1104 ERROR("Failed to receive veth names from parent");
1105 goto out_warn_father
;
1109 /* If we are in a new user namespace, become root there to have
1110 * privilege over our namespace.
1112 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1113 if (!handler
->conf
->root_nsuid_map
)
1114 nsuid
= handler
->conf
->init_uid
;
1116 if (!handler
->conf
->root_nsgid_map
)
1117 nsgid
= handler
->conf
->init_gid
;
1119 /* Drop groups only after we switched to a valid gid in the new
1122 if (!lxc_setgroups(0, NULL
) &&
1123 (handler
->am_root
|| errno
!= EPERM
))
1124 goto out_warn_father
;
1126 if (!lxc_switch_uid_gid(nsuid
, nsgid
))
1127 goto out_warn_father
;
1129 ret
= prctl(PR_SET_DUMPABLE
, prctl_arg(1), prctl_arg(0),
1130 prctl_arg(0), prctl_arg(0));
1132 goto out_warn_father
;
1134 /* set{g,u}id() clears deathsignal */
1135 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
, status_fd
);
1137 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1138 goto out_warn_father
;
1142 ret
= access(handler
->lxcpath
, X_OK
);
1144 print_top_failing_dir(handler
->lxcpath
);
1145 goto out_warn_father
;
1148 /* In order to checkpoint restore, we need to have everything in the
1149 * same mount namespace. However, some containers may not have a
1150 * reasonable /dev (in particular, they may not have /dev/null), so we
1151 * can't set init's std fds to /dev/null by opening it from inside the
1154 * If that's the case, fall back to using the host's /dev/null. This
1155 * means that migration won't work, but at least we won't spew output
1156 * where it isn't wanted.
1158 if (handler
->daemonize
&& !handler
->conf
->autodev
) {
1159 char path
[PATH_MAX
];
1161 ret
= snprintf(path
, sizeof(path
), "%s/dev/null",
1162 handler
->conf
->rootfs
.mount
);
1163 if (ret
< 0 || ret
>= sizeof(path
))
1164 goto out_warn_father
;
1166 ret
= access(path
, F_OK
);
1168 devnull_fd
= open_devnull();
1171 goto out_warn_father
;
1172 WARN("Using /dev/null from the host for container init's standard file descriptors. Migration will not work");
1176 /* Ask father to setup cgroups and wait for him to finish. */
1177 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
);
1181 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1182 * earlier we end up with a wrong view of /proc/self/cgroup. For
1183 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1184 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1185 * /proc/self/cgroup would show us:
1189 * whereas it should actually show
1193 if (handler
->ns_unshare_flags
& CLONE_NEWCGROUP
) {
1194 ret
= unshare(CLONE_NEWCGROUP
);
1196 if (errno
!= EINVAL
) {
1197 SYSERROR("Failed to unshare CLONE_NEWCGROUP");
1198 goto out_warn_father
;
1201 handler
->ns_clone_flags
&= ~CLONE_NEWCGROUP
;
1202 SYSINFO("Kernel does not support CLONE_NEWCGROUP");
1204 INFO("Unshared CLONE_NEWCGROUP");
1208 if (handler
->ns_unshare_flags
& CLONE_NEWTIME
) {
1209 ret
= unshare(CLONE_NEWTIME
);
1211 if (errno
!= EINVAL
) {
1212 SYSERROR("Failed to unshare CLONE_NEWTIME");
1213 goto out_warn_father
;
1216 handler
->ns_clone_flags
&= ~CLONE_NEWTIME
;
1217 SYSINFO("Kernel does not support CLONE_NEWTIME");
1219 __do_close
int timens_fd
= -EBADF
;
1221 INFO("Unshared CLONE_NEWTIME");
1223 if (handler
->conf
->timens
.s_boot
)
1224 ret
= timens_offset_write(CLOCK_BOOTTIME
, handler
->conf
->timens
.s_boot
, 0);
1225 else if (handler
->conf
->timens
.ns_boot
)
1226 ret
= timens_offset_write(CLOCK_BOOTTIME
, 0, handler
->conf
->timens
.ns_boot
);
1228 SYSERROR("Failed to write CLONE_BOOTTIME offset");
1229 goto out_warn_father
;
1231 TRACE("Wrote CLOCK_BOOTTIME offset");
1233 if (handler
->conf
->timens
.s_monotonic
)
1234 ret
= timens_offset_write(CLOCK_MONOTONIC
, handler
->conf
->timens
.s_monotonic
, 0);
1235 else if (handler
->conf
->timens
.ns_monotonic
)
1236 ret
= timens_offset_write(CLOCK_MONOTONIC
, 0, handler
->conf
->timens
.ns_monotonic
);
1238 SYSERROR("Failed to write CLONE_MONOTONIC offset");
1239 goto out_warn_father
;
1241 TRACE("Wrote CLOCK_MONOTONIC offset");
1243 timens_fd
= open("/proc/self/ns/time_for_children", O_RDONLY
| O_CLOEXEC
);
1244 if (timens_fd
< 0) {
1245 SYSERROR("Failed to open \"/proc/self/ns/time_for_children\"");
1246 goto out_warn_father
;
1249 ret
= setns(timens_fd
, CLONE_NEWTIME
);
1251 SYSERROR("Failed to setns(%d(\"/proc/self/ns/time_for_children\"))", timens_fd
);
1252 goto out_warn_father
;
1257 /* Add the requested environment variables to the current environment to
1258 * allow them to be used by the various hooks, such as the start hook
1261 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1262 ret
= putenv((char *)iterator
->elem
);
1264 SYSERROR("Failed to set environment variable: %s",
1265 (char *)iterator
->elem
);
1266 goto out_warn_father
;
1270 /* Setup the container, ip, names, utsname, ... */
1271 ret
= lxc_setup(handler
);
1273 ERROR("Failed to setup container \"%s\"", handler
->name
);
1274 goto out_warn_father
;
1277 /* Set the label to change to when we exec(2) the container's init. */
1278 ret
= lsm_process_label_set(NULL
, handler
->conf
, true);
1280 goto out_warn_father
;
1282 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1283 * before we aren't allowed anymore.
1285 if (handler
->conf
->no_new_privs
) {
1286 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
1287 prctl_arg(0), prctl_arg(0));
1289 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges");
1290 goto out_warn_father
;
1292 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges");
1295 /* Some init's such as busybox will set sane tty settings on stdin,
1296 * stdout, stderr which it thinks is the console. We already set them
1297 * the way we wanted on the real terminal, and we want init to do its
1298 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
1299 * make sure that that pty is stdin,stdout,stderr.
1301 if (handler
->conf
->console
.pty
>= 0) {
1302 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
1303 ret
= set_stdfds(handler
->conf
->console
.pty
);
1305 ret
= lxc_terminal_set_stdfds(handler
->conf
->console
.pty
);
1307 ERROR("Failed to redirect std{in,out,err} to pty file descriptor %d",
1308 handler
->conf
->console
.pty
);
1309 goto out_warn_father
;
1313 /* If we mounted a temporary proc, then unmount it now. */
1314 tmp_proc_unmount(handler
->conf
);
1316 ret
= lxc_seccomp_load(handler
->conf
);
1318 goto out_warn_father
;
1320 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, data_sock0
);
1322 SYSERROR("Failed to send seccomp notify fd to parent");
1323 goto out_warn_father
;
1326 ret
= run_lxc_hooks(handler
->name
, "start", handler
->conf
, NULL
);
1328 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1330 goto out_warn_father
;
1333 close_prot_errno_disarm(handler
->sigfd
);
1335 if (handler
->conf
->console
.pty
< 0 && handler
->daemonize
) {
1336 if (devnull_fd
< 0) {
1337 devnull_fd
= open_devnull();
1339 goto out_warn_father
;
1342 ret
= set_stdfds(devnull_fd
);
1344 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
1345 goto out_warn_father
;
1349 close_prot_errno_disarm(devnull_fd
);
1353 if (handler
->conf
->init_cwd
) {
1354 ret
= chdir(handler
->conf
->init_cwd
);
1356 SYSERROR("Could not change directory to \"%s\"",
1357 handler
->conf
->init_cwd
);
1358 goto out_warn_father
;
1362 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
);
1364 goto out_warn_father
;
1366 /* Reset the environment variables the user requested in a clear
1370 /* Don't error out though. */
1372 SYSERROR("Failed to clear environment.");
1374 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1375 ret
= putenv((char *)iterator
->elem
);
1377 SYSERROR("Failed to set environment variable: %s",
1378 (char *)iterator
->elem
);
1379 goto out_warn_father
;
1383 ret
= putenv("container=lxc");
1385 SYSERROR("Failed to set environment variable: container=lxc");
1386 goto out_warn_father
;
1389 if (handler
->conf
->ttys
.tty_names
) {
1390 ret
= putenv(handler
->conf
->ttys
.tty_names
);
1392 SYSERROR("Failed to set environment variable for container ptys");
1393 goto out_warn_father
;
1397 /* The container has been setup. We can now switch to an unprivileged
1400 new_uid
= handler
->conf
->init_uid
;
1401 new_gid
= handler
->conf
->init_gid
;
1403 /* Avoid unnecessary syscalls. */
1404 if (new_uid
== nsuid
)
1405 new_uid
= LXC_INVALID_UID
;
1407 if (new_gid
== nsgid
)
1408 new_gid
= LXC_INVALID_GID
;
1410 /* Make sure that the processes STDIO is correctly owned by the user that we are switching to */
1411 ret
= fix_stdio_permissions(new_uid
);
1413 WARN("Failed to ajust stdio permissions");
1415 /* If we are in a new user namespace we already dropped all groups when
1416 * we switched to root in the new user namespace further above. Only
1417 * drop groups if we can, so ensure that we have necessary privilege.
1419 if (lxc_list_empty(&handler
->conf
->id_map
))
1421 if (lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
))
1423 if (!lxc_setgroups(0, NULL
))
1424 goto out_warn_father
;
1426 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
1427 goto out_warn_father
;
1429 ret
= lxc_ambient_caps_down();
1431 ERROR("Failed to clear ambient capabilities");
1432 goto out_warn_father
;
1435 if (handler
->conf
->monitor_signal_pdeath
!= SIGKILL
) {
1436 ret
= lxc_set_death_signal(handler
->conf
->monitor_signal_pdeath
,
1437 handler
->monitor_pid
, status_fd
);
1439 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1440 handler
->conf
->monitor_signal_pdeath
);
1441 goto out_warn_father
;
1446 * After this call, we are in error because this ops should not return
1449 handler
->ops
->start(handler
, handler
->data
);
1453 * We want the parent to know something went wrong, so we return a
1454 * special error code.
1456 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1462 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1465 struct lxc_terminal_info
*tty
;
1467 int sock
= handler
->data_sock
[1];
1468 struct lxc_conf
*conf
= handler
->conf
;
1469 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1471 if (!conf
->ttys
.max
)
1474 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
1478 for (i
= 0; i
< conf
->ttys
.max
; i
++) {
1481 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1485 tty
= &ttys
->tty
[i
];
1487 tty
->ptx
= ttyfds
[0];
1488 tty
->pty
= ttyfds
[1];
1489 TRACE("Received pty with ptx fd %d and pty fd %d from child", tty
->ptx
, tty
->pty
);
1493 SYSERROR("Failed to receive %zu ttys from child", ttys
->max
);
1495 TRACE("Received %zu ttys from child", ttys
->max
);
1500 int resolve_clone_flags(struct lxc_handler
*handler
)
1503 struct lxc_conf
*conf
= handler
->conf
;
1504 bool wants_timens
= conf
->timens
.s_boot
|| conf
->timens
.ns_boot
||
1505 conf
->timens
.s_monotonic
|| conf
->timens
.ns_monotonic
;
1507 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1508 if (conf
->ns_keep
) {
1509 if (!(conf
->ns_keep
& ns_info
[i
].clone_flag
))
1510 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1511 } else if (conf
->ns_clone
) {
1512 if ((conf
->ns_clone
& ns_info
[i
].clone_flag
))
1513 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1515 if (i
== LXC_NS_USER
&& lxc_list_empty(&handler
->conf
->id_map
))
1518 if (i
== LXC_NS_NET
&& lxc_requests_empty_network(handler
))
1521 if (i
== LXC_NS_CGROUP
&& !cgns_supported())
1524 if (i
== LXC_NS_TIME
&& !wants_timens
)
1527 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1530 if (!conf
->ns_share
[i
])
1533 handler
->ns_clone_flags
&= ~ns_info
[i
].clone_flag
;
1534 TRACE("Sharing %s namespace", ns_info
[i
].proc_name
);
1537 if (wants_timens
&& (conf
->ns_keep
& ns_info
[LXC_NS_TIME
].clone_flag
))
1538 return log_trace_errno(-1, EINVAL
, "Requested to keep time namespace while also specifying offsets");
1540 /* Deal with namespaces that are unshared. */
1541 if (handler
->ns_clone_flags
& CLONE_NEWTIME
)
1542 handler
->ns_unshare_flags
|= CLONE_NEWTIME
;
1544 if (!pure_unified_layout(handler
->cgroup_ops
) && handler
->ns_clone_flags
& CLONE_NEWCGROUP
)
1545 handler
->ns_unshare_flags
|= CLONE_NEWCGROUP
;
1547 if ((handler
->ns_clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
1548 (CLONE_NEWNET
| CLONE_NEWUSER
))
1549 handler
->ns_unshare_flags
|= CLONE_NEWNET
;
1551 /* Deal with namespaces that are spawned. */
1552 handler
->ns_on_clone_flags
= handler
->ns_clone_flags
& ~handler
->ns_unshare_flags
;
1554 handler
->clone_flags
= handler
->ns_on_clone_flags
| CLONE_PIDFD
;
1559 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1560 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1561 * But since the memory between parent and child is shared on CLONE_VM this
1562 * would invalidate the getpid() cache that glibc used to maintain and so
1563 * getpid() in the child would return the parent's pid. This is all fixed in
1564 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1565 * not reset anymore.
1566 * However, if for whatever reason you - dear committer - somehow need to get the
1567 * pid of the dummy intermediate process for do_share_ns() you need to call
1568 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1571 static inline int do_share_ns(void *arg
)
1574 struct lxc_handler
*handler
= arg
;
1576 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1577 if (handler
->nsfd
[i
] < 0)
1580 ret
= setns(handler
->nsfd
[i
], 0);
1583 * Note that joining a user and/or mount namespace
1584 * requires the process is not multithreaded otherwise
1585 * setns() will fail here.
1587 SYSERROR("Failed to inherit %s namespace",
1588 ns_info
[i
].proc_name
);
1592 DEBUG("Inherited %s namespace", ns_info
[i
].proc_name
);
1595 flags
= handler
->ns_on_clone_flags
;
1596 flags
|= CLONE_PARENT
;
1597 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, CLONE_PIDFD
| flags
,
1599 if (handler
->pid
< 0)
1605 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1606 * exec()s the requested container binary.
1607 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1608 * right here should be double checked if they'd pose a security risk. (For
1609 * example, any {u}mount() operations performed here will be reflected on the
1612 static int lxc_spawn(struct lxc_handler
*handler
)
1614 __do_close
int data_sock0
= -EBADF
, data_sock1
= -EBADF
;
1617 bool wants_to_map_ids
;
1618 struct lxc_list
*id_map
;
1619 const char *name
= handler
->name
;
1620 const char *lxcpath
= handler
->lxcpath
;
1621 bool share_ns
= false;
1622 struct lxc_conf
*conf
= handler
->conf
;
1623 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
1625 id_map
= &conf
->id_map
;
1626 wants_to_map_ids
= !lxc_list_empty(id_map
);
1628 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1629 if (!conf
->ns_share
[i
])
1632 handler
->nsfd
[i
] = lxc_inherit_namespace(conf
->ns_share
[i
], lxcpath
, ns_info
[i
].proc_name
);
1633 if (handler
->nsfd
[i
] < 0)
1639 ret
= lxc_sync_init(handler
);
1643 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1644 handler
->data_sock
);
1647 data_sock0
= handler
->data_sock
[0];
1648 data_sock1
= handler
->data_sock
[1];
1650 ret
= resolve_clone_flags(handler
);
1654 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1655 ret
= lxc_find_gateway_addresses(handler
);
1657 ERROR("Failed to find gateway addresses");
1662 if (!cgroup_ops
->payload_create(cgroup_ops
, handler
)) {
1663 ERROR("Failed creating cgroups");
1664 goto out_delete_net
;
1667 /* If the rootfs is not a blockdev, prevent the container from marking
1669 * If the container is unprivileged then skip rootfs pinning.
1671 if (!wants_to_map_ids
) {
1672 handler
->pinfd
= pin_rootfs(conf
->rootfs
.path
);
1673 if (handler
->pinfd
== -EBADF
)
1674 INFO("Failed to pin the rootfs for container \"%s\"", handler
->name
);
1677 /* Create a process in a new set of namespaces. */
1681 attacher_pid
= lxc_clone(do_share_ns
, handler
,
1682 CLONE_VFORK
| CLONE_VM
| CLONE_FILES
, NULL
);
1683 if (attacher_pid
< 0) {
1684 SYSERROR(LXC_CLONE_ERROR
);
1685 goto out_delete_net
;
1688 ret
= wait_for_pid(attacher_pid
);
1690 SYSERROR("Intermediate process failed");
1691 goto out_delete_net
;
1694 if (handler
->pid
< 0) {
1695 SYSERROR(LXC_CLONE_ERROR
);
1696 goto out_delete_net
;
1699 int cgroup_fd
= -EBADF
;
1701 struct lxc_clone_args clone_args
= {
1702 .flags
= handler
->clone_flags
,
1703 .pidfd
= ptr_to_u64(&handler
->pidfd
),
1704 .exit_signal
= SIGCHLD
,
1707 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1708 cgroup_fd
= cgroup_unified_fd(cgroup_ops
);
1709 if (cgroup_fd
>= 0) {
1710 handler
->clone_flags
|= CLONE_INTO_CGROUP
;
1711 clone_args
.flags
|= CLONE_INTO_CGROUP
;
1712 clone_args
.cgroup
= cgroup_fd
;
1716 /* Try to spawn directly into target cgroup. */
1717 handler
->pid
= lxc_clone3(&clone_args
, CLONE_ARGS_SIZE_VER2
);
1718 if (handler
->pid
< 0) {
1719 SYSTRACE("Failed to spawn container directly into target cgroup");
1721 /* Kernel might simply be too old for CLONE_INTO_CGROUP. */
1722 handler
->clone_flags
&= ~(CLONE_INTO_CGROUP
| CLONE_NEWCGROUP
);
1723 handler
->ns_on_clone_flags
&= ~CLONE_NEWCGROUP
;
1724 handler
->ns_unshare_flags
|= CLONE_NEWCGROUP
;
1726 clone_args
.flags
= handler
->clone_flags
;
1728 handler
->pid
= lxc_clone3(&clone_args
, CLONE_ARGS_SIZE_VER0
);
1729 } else if (cgroup_fd
>= 0) {
1730 TRACE("Spawned container directly into target cgroup via cgroup2 fd %d", cgroup_fd
);
1733 /* Kernel might be too old for clone3(). */
1734 if (handler
->pid
< 0) {
1735 SYSTRACE("Failed to spawn container via clone3()");
1736 handler
->pid
= lxc_raw_legacy_clone(handler
->clone_flags
, &handler
->pidfd
);
1739 if (handler
->pid
< 0) {
1740 SYSERROR(LXC_CLONE_ERROR
);
1741 goto out_delete_net
;
1744 if (handler
->pid
== 0) {
1745 (void)do_start(handler
);
1746 _exit(EXIT_FAILURE
);
1749 if (handler
->pidfd
< 0)
1750 handler
->clone_flags
&= ~CLONE_PIDFD
;
1751 TRACE("Cloned child process %d", handler
->pid
);
1753 /* Verify that we can actually make use of pidfds. */
1754 if (!lxc_can_use_pidfd(handler
->pidfd
))
1755 close_prot_errno_disarm(handler
->pidfd
);
1757 ret
= snprintf(pidstr
, 20, "%d", handler
->pid
);
1758 if (ret
< 0 || ret
>= 20)
1759 goto out_delete_net
;
1761 ret
= setenv("LXC_PID", pidstr
, 1);
1763 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr
);
1765 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1766 if (handler
->ns_on_clone_flags
& ns_info
[i
].clone_flag
)
1767 INFO("Cloned %s", ns_info
[i
].flag_name
);
1769 if (!lxc_try_preserve_namespaces(handler
, handler
->ns_on_clone_flags
, handler
->pid
)) {
1770 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1771 goto out_delete_net
;
1774 lxc_sync_fini_child(handler
);
1776 if (lxc_abstract_unix_send_fds(handler
->data_sock
[0], &handler
->monitor_status_fd
, 1, NULL
, 0) < 0) {
1777 ERROR("Failed to send status file descriptor to child process");
1778 goto out_delete_net
;
1780 close_prot_errno_disarm(handler
->monitor_status_fd
);
1782 /* Map the container uids. The container became an invalid userid the
1783 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1784 * anything immediately, but allows the container to setuid(0) (0 being
1785 * mapped to something else on the host.) later to become a valid uid
1788 if (wants_to_map_ids
) {
1789 if (!handler
->conf
->ns_share
[LXC_NS_USER
] &&
1790 (handler
->conf
->ns_keep
& CLONE_NEWUSER
) == 0) {
1791 ret
= lxc_map_ids(id_map
, handler
->pid
);
1793 ERROR("Failed to set up id mapping.");
1794 goto out_delete_net
;
1799 ret
= lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
);
1801 goto out_delete_net
;
1803 ret
= lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
);
1805 goto out_delete_net
;
1807 if (!cgroup_ops
->setup_limits_legacy(cgroup_ops
, handler
->conf
, false)) {
1808 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1809 goto out_delete_net
;
1812 if (!cgroup_ops
->payload_enter(cgroup_ops
, handler
)) {
1813 ERROR("Failed to enter cgroups");
1814 goto out_delete_net
;
1817 if (!cgroup_ops
->payload_delegate_controllers(cgroup_ops
)) {
1818 ERROR("Failed to delegate controllers to payload cgroup");
1819 goto out_delete_net
;
1822 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
)) {
1823 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1824 goto out_delete_net
;
1827 if (!cgroup_ops
->chown(cgroup_ops
, handler
->conf
))
1828 goto out_delete_net
;
1830 /* If not done yet, we're now ready to preserve the network namespace */
1831 if (handler
->nsfd
[LXC_NS_NET
] < 0) {
1832 ret
= lxc_try_preserve_ns(handler
->pid
, "net");
1834 if (ret
!= -EOPNOTSUPP
) {
1835 SYSERROR("Failed to preserve net namespace");
1836 goto out_delete_net
;
1839 handler
->nsfd
[LXC_NS_NET
] = ret
;
1840 DEBUG("Preserved net namespace via fd %d", ret
);
1843 ret
= lxc_netns_set_nsid(handler
->nsfd
[LXC_NS_NET
]);
1845 SYSWARN("Failed to allocate new network namespace id");
1847 TRACE("Allocated new network namespace id");
1849 /* Create the network configuration. */
1850 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1851 ret
= lxc_create_network(handler
);
1853 ERROR("Failed to create the network");
1854 goto out_delete_net
;
1857 ret
= lxc_network_send_to_child(handler
);
1859 ERROR("Failed to send veth names to child");
1860 goto out_delete_net
;
1864 if (!lxc_list_empty(&conf
->procs
)) {
1865 ret
= setup_proc_filesystem(&conf
->procs
, handler
->pid
);
1867 goto out_delete_net
;
1870 /* Tell the child to continue its initialization. We'll get
1871 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1873 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
);
1875 goto out_delete_net
;
1877 if (!lxc_list_empty(&conf
->limits
)) {
1878 ret
= setup_resource_limits(&conf
->limits
, handler
->pid
);
1880 ERROR("Failed to setup resource limits");
1881 goto out_delete_net
;
1885 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
);
1887 goto out_delete_net
;
1890 * with isolation the limiting devices cgroup was already setup, so
1891 * only setup devices here if we have no namespace directory
1893 if (!handler
->conf
->cgroup_meta
.namespace_dir
&&
1894 !cgroup_ops
->setup_limits_legacy(cgroup_ops
, handler
->conf
, true)) {
1895 ERROR("Failed to setup legacy device cgroup controller limits");
1896 goto out_delete_net
;
1898 TRACE("Set up legacy device cgroup controller limits");
1900 if (!cgroup_ops
->devices_activate(cgroup_ops
, handler
)) {
1901 ERROR("Failed to setup cgroup2 device controller limits");
1902 goto out_delete_net
;
1904 TRACE("Set up cgroup2 device controller limits");
1906 if (handler
->ns_unshare_flags
& CLONE_NEWCGROUP
) {
1907 /* Now we're ready to preserve the cgroup namespace */
1908 ret
= lxc_try_preserve_ns(handler
->pid
, "cgroup");
1910 if (ret
!= -EOPNOTSUPP
) {
1911 SYSERROR("Failed to preserve cgroup namespace");
1912 goto out_delete_net
;
1915 handler
->nsfd
[LXC_NS_CGROUP
] = ret
;
1916 DEBUG("Preserved cgroup namespace via fd %d", ret
);
1920 cgroup_ops
->payload_finalize(cgroup_ops
);
1921 TRACE("Finished setting up cgroups");
1923 if (handler
->ns_unshare_flags
& CLONE_NEWTIME
) {
1924 /* Now we're ready to preserve the cgroup namespace */
1925 ret
= lxc_try_preserve_ns(handler
->pid
, "time");
1927 if (ret
!= -EOPNOTSUPP
) {
1928 SYSERROR("Failed to preserve time namespace");
1929 goto out_delete_net
;
1932 handler
->nsfd
[LXC_NS_TIME
] = ret
;
1933 DEBUG("Preserved time namespace via fd %d", ret
);
1937 /* Run any host-side start hooks */
1938 ret
= run_lxc_hooks(name
, "start-host", conf
, NULL
);
1940 ERROR("Failed to run lxc.hook.start-host");
1941 goto out_delete_net
;
1944 /* Tell the child to complete its initialization and wait for it to exec
1945 * or return an error. (The child will never return
1946 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1947 * lxc_sync_barrier_child to return success, or return a different
1948 * value, causing us to error out).
1950 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_READY_START
);
1952 goto out_delete_net
;
1954 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1955 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
1957 ERROR("Failed to receive names and ifindices for network devices from child");
1958 goto out_delete_net
;
1962 /* Now all networks are created, network devices are moved into place,
1963 * and the correct names and ifindices in the respective namespaces have
1964 * been recorded. The corresponding structs have now all been filled. So
1965 * log them for debugging purposes.
1967 lxc_log_configured_netdevs(conf
);
1969 /* Read tty fds allocated by child. */
1970 ret
= lxc_recv_ttys_from_child(handler
);
1972 ERROR("Failed to receive tty info from child process");
1973 goto out_delete_net
;
1976 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, data_sock1
);
1978 SYSERROR("Failed to receive seccomp notify fd from child");
1979 goto out_delete_net
;
1982 ret
= handler
->ops
->post_start(handler
, handler
->data
);
1986 ret
= lxc_set_state(name
, handler
, RUNNING
);
1988 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING
));
1992 lxc_sync_fini(handler
);
1997 if (handler
->ns_clone_flags
& CLONE_NEWNET
)
1998 lxc_delete_network(handler
);
2004 lxc_sync_fini(handler
);
2005 close_prot_errno_disarm(handler
->pinfd
);
2010 int __lxc_start(struct lxc_handler
*handler
, struct lxc_operations
*ops
,
2011 void *data
, const char *lxcpath
, bool daemonize
, int *error_num
)
2014 const char *name
= handler
->name
;
2015 struct lxc_conf
*conf
= handler
->conf
;
2016 struct cgroup_ops
*cgroup_ops
;
2018 ret
= lxc_init(name
, handler
);
2020 ERROR("Failed to initialize container \"%s\"", name
);
2024 handler
->data
= data
;
2025 handler
->daemonize
= daemonize
;
2026 cgroup_ops
= handler
->cgroup_ops
;
2028 if (!attach_block_device(handler
->conf
)) {
2029 ERROR("Failed to attach block device");
2034 if (!cgroup_ops
->monitor_create(cgroup_ops
, handler
)) {
2035 ERROR("Failed to create monitor cgroup");
2040 if (!cgroup_ops
->monitor_enter(cgroup_ops
, handler
)) {
2041 ERROR("Failed to enter monitor cgroup");
2046 if (!cgroup_ops
->monitor_delegate_controllers(cgroup_ops
)) {
2047 ERROR("Failed to delegate controllers to monitor cgroup");
2052 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
2053 /* If the backing store is a device, mount it here and now. */
2054 if (rootfs_is_blockdev(conf
)) {
2055 ret
= unshare(CLONE_NEWNS
);
2057 ERROR("Failed to unshare CLONE_NEWNS");
2060 INFO("Unshared CLONE_NEWNS");
2062 turn_into_dependent_mounts();
2063 ret
= lxc_setup_rootfs_prepare_root(conf
, name
, lxcpath
);
2065 ERROR("Error setting up rootfs mount as root before spawn");
2068 INFO("Set up container rootfs as host root");
2072 ret
= lxc_spawn(handler
);
2074 ERROR("Failed to spawn container \"%s\"", name
);
2075 goto out_detach_blockdev
;
2078 handler
->conf
->reboot
= REBOOT_NONE
;
2080 ret
= lxc_poll(name
, handler
);
2082 ERROR("LXC mainloop exited with error: %d", ret
);
2083 goto out_delete_network
;
2086 if (!handler
->init_died
&& handler
->pid
> 0) {
2087 ERROR("Child process is not killed");
2089 goto out_delete_network
;
2092 status
= lxc_wait_for_pid_status(handler
->pid
);
2094 SYSERROR("Failed to retrieve status for %d", handler
->pid
);
2096 /* If the child process exited but was not signaled, it didn't call
2097 * reboot. This should mean it was an lxc-execute which simply exited.
2098 * In any case, treat it as a 'halt'.
2100 if (WIFSIGNALED(status
)) {
2101 switch(WTERMSIG(status
)) {
2102 case SIGINT
: /* halt */
2103 DEBUG("Container \"%s\" is halting", name
);
2105 case SIGHUP
: /* reboot */
2106 DEBUG("Container \"%s\" is rebooting", name
);
2107 handler
->conf
->reboot
= REBOOT_REQ
;
2109 case SIGSYS
: /* seccomp */
2110 DEBUG("Container \"%s\" violated its seccomp policy", name
);
2113 DEBUG("Unknown exit status for container \"%s\" init %d", name
, WTERMSIG(status
));
2118 ret
= lxc_restore_phys_nics_to_netns(handler
);
2120 ERROR("Failed to move physical network devices back to parent network namespace");
2122 close_prot_errno_disarm(handler
->pinfd
);
2124 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
2125 lxc_error_set_and_log(handler
->pid
, status
);
2127 *error_num
= handler
->exit_status
;
2129 lxc_delete_network(handler
);
2130 detach_block_device(handler
->conf
);
2139 out_detach_blockdev
:
2141 detach_block_device(handler
->conf
);
2147 lxc_delete_network(handler
);
2148 detach_block_device(handler
->conf
);
2157 static int start(struct lxc_handler
*handler
, void* data
)
2159 struct start_args
*arg
= data
;
2161 NOTICE("Exec'ing \"%s\"", arg
->argv
[0]);
2163 execvp(arg
->argv
[0], arg
->argv
);
2164 SYSERROR("Failed to exec \"%s\"", arg
->argv
[0]);
2168 static int post_start(struct lxc_handler
*handler
, void* data
)
2170 struct start_args
*arg
= data
;
2172 NOTICE("Started \"%s\" with pid \"%d\"", arg
->argv
[0], handler
->pid
);
2176 static struct lxc_operations start_ops
= {
2178 .post_start
= post_start
2181 int lxc_start(char *const argv
[], struct lxc_handler
*handler
,
2182 const char *lxcpath
, bool daemonize
, int *error_num
)
2184 struct start_args start_arg
= {
2188 TRACE("Doing lxc_start");
2189 return __lxc_start(handler
, &start_ops
, &start_arg
, lxcpath
, daemonize
, error_num
);
2192 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
2195 char destroy
[PATH_MAX
];
2196 struct lxc_container
*c
;
2200 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
2201 bret
= do_destroy_container(handler
);
2203 ERROR("Error destroying rootfs for container \"%s\"", name
);
2207 INFO("Destroyed rootfs for container \"%s\"", name
);
2209 ret
= snprintf(destroy
, PATH_MAX
, "%s/%s", handler
->lxcpath
, name
);
2210 if (ret
< 0 || ret
>= PATH_MAX
) {
2211 ERROR("Error destroying directory for container \"%s\"", name
);
2215 c
= lxc_container_new(name
, handler
->lxcpath
);
2217 if (container_disk_lock(c
)) {
2218 INFO("Could not update lxc_snapshots file");
2219 lxc_container_put(c
);
2221 mod_all_rdeps(c
, false);
2222 container_disk_unlock(c
);
2223 lxc_container_put(c
);
2227 if (!handler
->am_root
)
2228 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
2229 destroy
, "lxc_rmdir_onedev_wrapper");
2231 ret
= lxc_rmdir_onedev(destroy
, NULL
);
2234 ERROR("Error destroying directory for container \"%s\"", name
);
2237 INFO("Destroyed directory for container \"%s\"", name
);
2240 static int lxc_rmdir_onedev_wrapper(void *data
)
2242 char *arg
= (char *) data
;
2243 return lxc_rmdir_onedev(arg
, NULL
);
2246 static bool do_destroy_container(struct lxc_handler
*handler
)
2250 if (!handler
->am_root
) {
2251 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
2252 handler
->conf
, "storage_destroy_wrapper");
2259 return storage_destroy(handler
->conf
);