2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
8 * Serge Hallyn <serge@hallyn.com>
9 * Christian Brauner <christian.brauner@ubuntu.com>
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
40 #include <sys/mount.h>
41 #include <sys/param.h>
42 #include <sys/prctl.h>
43 #include <sys/socket.h>
45 #include <sys/syscall.h>
46 #include <sys/types.h>
55 #include "commands_utils.h"
58 #include "confile_utils.h"
60 #include "file_utils.h"
64 #include "lxccontainer.h"
66 #include "lxcseccomp.h"
69 #include "memory_utils.h"
71 #include "namespace.h"
73 #include "raw_syscalls.h"
75 #include "storage/storage.h"
76 #include "storage/storage_utils.h"
78 #include "syscall_wrappers.h"
83 #include <sys/capability.h>
87 #include "include/strlcpy.h"
90 lxc_log_define(start
, lxc
);
92 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
93 static bool do_destroy_container(struct lxc_handler
*handler
);
94 static int lxc_rmdir_onedev_wrapper(void *data
);
95 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
98 static void print_top_failing_dir(const char *path
)
100 __do_free
char *copy
= NULL
;
104 copy
= must_copy_string(path
);
106 e
= copy
+ strlen(path
);
109 while (p
< e
&& *p
== '/')
112 while (p
< e
&& *p
!= '/')
118 ret
= access(copy
, X_OK
);
120 SYSERROR("Could not access %s. Please grant it x "
121 "access, or add an ACL for the container "
129 static void lxc_put_nsfds(struct lxc_handler
*handler
)
133 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
134 if (handler
->nsfd
[i
] < 0)
137 close(handler
->nsfd
[i
]);
138 handler
->nsfd
[i
] = -EBADF
;
142 static int lxc_try_preserve_ns(const int pid
, const char *ns
)
146 fd
= lxc_preserve_ns(pid
, ns
);
148 if (errno
!= ENOENT
) {
149 SYSERROR("Failed to preserve %s namespace", ns
);
153 SYSWARN("Kernel does not support preserving %s namespaces", ns
);
160 /* lxc_try_preserve_namespaces: open /proc/@pid/ns/@ns for each namespace
161 * specified in ns_clone_flags.
162 * Return true on success, false on failure.
164 static bool lxc_try_preserve_namespaces(struct lxc_handler
*handler
,
165 int ns_clone_flags
, pid_t pid
)
169 for (i
= 0; i
< LXC_NS_MAX
; i
++)
170 handler
->nsfd
[i
] = -EBADF
;
172 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
175 if ((ns_clone_flags
& ns_info
[i
].clone_flag
) == 0)
178 fd
= lxc_try_preserve_ns(pid
, ns_info
[i
].proc_name
);
180 /* Do not fail to start container on kernels that do
181 * not support interacting with namespaces through
184 if (fd
== -EOPNOTSUPP
)
187 lxc_put_nsfds(handler
);
191 handler
->nsfd
[i
] = fd
;
192 DEBUG("Preserved %s namespace via fd %d", ns_info
[i
].proc_name
,
199 static inline bool match_stdfds(int fd
)
201 return (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
);
205 static bool match_dlog_fds(struct dirent
*direntp
)
207 char path
[PATH_MAX
] = {0};
208 char link
[PATH_MAX
] = {0};
212 ret
= snprintf(path
, PATH_MAX
, "/proc/self/fd/%s", direntp
->d_name
);
213 if (ret
< 0 || ret
>= PATH_MAX
) {
214 ERROR("Failed to create file descriptor name");
218 linklen
= readlink(path
, link
, PATH_MAX
);
220 SYSERROR("Failed to read link path - \"%s\"", path
);
222 } else if (linklen
>= PATH_MAX
) {
223 ERROR("The name of link path is too long - \"%s\"", path
);
227 if (strcmp(link
, "/dev/log_main") == 0 ||
228 strcmp(link
, "/dev/log_system") == 0 ||
229 strcmp(link
, "/dev/log_radio") == 0)
236 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
237 int *fds_to_ignore
, size_t len_fds
)
242 struct dirent
*direntp
;
244 if (conf
&& conf
->close_all_fds
)
248 dir
= opendir("/proc/self/fd");
250 SYSWARN("Failed to open directory");
256 while ((direntp
= readdir(dir
))) {
258 struct lxc_list
*cur
;
259 bool matched
= false;
261 if (strcmp(direntp
->d_name
, ".") == 0)
264 if (strcmp(direntp
->d_name
, "..") == 0)
267 ret
= lxc_safe_int(direntp
->d_name
, &fd
);
269 INFO("Could not parse file descriptor for \"%s\"", direntp
->d_name
);
273 for (i
= 0; i
< len_fds
; i
++)
274 if (fds_to_ignore
[i
] == fd
)
277 if (fd
== fddir
|| fd
== lxc_log_fd
||
278 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
281 /* Keep state clients that wait on reboots. */
283 lxc_list_for_each(cur
, &conf
->state_clients
) {
284 struct lxc_state_client
*client
= cur
->elem
;
286 if (client
->clientfd
!= fd
)
297 if (current_config
&& fd
== current_config
->logfd
)
300 if (match_stdfds(fd
))
304 if (match_dlog_fds(direntp
))
311 INFO("Closed inherited fd %d", fd
);
314 WARN("Inherited fd %d", fd
);
317 /* Only enable syslog at this point to avoid the above logging function
318 * to open a new fd and make the check_inherited function enter an
321 lxc_log_enable_syslog();
323 closedir(dir
); /* cannot fail */
327 static int setup_signal_fd(sigset_t
*oldmask
)
331 const int signals
[] = {SIGBUS
, SIGILL
, SIGSEGV
, SIGWINCH
};
333 /* Block everything except serious error signals. */
334 ret
= sigfillset(&mask
);
338 for (int sig
= 0; sig
< (sizeof(signals
) / sizeof(signals
[0])); sig
++) {
339 ret
= sigdelset(&mask
, signals
[sig
]);
344 ret
= pthread_sigmask(SIG_BLOCK
, &mask
, oldmask
);
346 SYSERROR("Failed to set signal mask");
350 ret
= signalfd(-1, &mask
, SFD_CLOEXEC
);
352 SYSERROR("Failed to create signal file descriptor");
356 TRACE("Created signal file descriptor %d", ret
);
361 static int signal_handler(int fd
, uint32_t events
, void *data
,
362 struct lxc_epoll_descr
*descr
)
366 struct signalfd_siginfo siginfo
;
367 struct lxc_handler
*hdlr
= data
;
369 ret
= lxc_read_nointr(fd
, &siginfo
, sizeof(siginfo
));
371 ERROR("Failed to read signal info from signal file descriptor %d", fd
);
372 return LXC_MAINLOOP_ERROR
;
375 if (ret
!= sizeof(siginfo
)) {
376 ERROR("Unexpected size for struct signalfd_siginfo");
380 /* Check whether init is running. */
382 ret
= waitid(P_PID
, hdlr
->pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
383 if (ret
== 0 && info
.si_pid
== hdlr
->pid
)
384 hdlr
->init_died
= true;
386 /* Try to figure out a reasonable exit status to report. */
387 if (hdlr
->init_died
) {
388 switch (info
.si_code
) {
390 hdlr
->exit_status
= info
.si_status
<< 8;
395 hdlr
->exit_status
= info
.si_status
<< 8 | 0x7f;
398 /* Huh? The waitid() told us it's dead *and* continued? */
399 WARN("Init %d dead and continued?", hdlr
->pid
);
400 hdlr
->exit_status
= 1;
403 ERROR("Unknown si_code: %d", info
.si_code
);
404 hdlr
->exit_status
= 1;
408 if (siginfo
.ssi_signo
== SIGHUP
) {
409 if (hdlr
->proc_pidfd
>= 0)
410 lxc_raw_pidfd_send_signal(hdlr
->proc_pidfd
, SIGTERM
, NULL
, 0);
412 kill(hdlr
->pid
, SIGTERM
);
413 INFO("Killing %d since terminal hung up", hdlr
->pid
);
414 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
415 : LXC_MAINLOOP_CONTINUE
;
418 if (siginfo
.ssi_signo
!= SIGCHLD
) {
419 if (hdlr
->proc_pidfd
>= 0)
420 lxc_raw_pidfd_send_signal(hdlr
->proc_pidfd
,
421 siginfo
.ssi_signo
, NULL
, 0);
423 kill(hdlr
->pid
, siginfo
.ssi_signo
);
424 INFO("Forwarded signal %d to pid %d", siginfo
.ssi_signo
, hdlr
->pid
);
425 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
426 : LXC_MAINLOOP_CONTINUE
;
429 /* More robustness, protect ourself from a SIGCHLD sent
430 * by a process different from the container init.
432 if (siginfo
.ssi_pid
!= hdlr
->pid
) {
433 NOTICE("Received %d from pid %d instead of container init %d",
434 siginfo
.ssi_signo
, siginfo
.ssi_pid
, hdlr
->pid
);
435 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
436 : LXC_MAINLOOP_CONTINUE
;
439 if (siginfo
.ssi_code
== CLD_STOPPED
) {
440 INFO("Container init process was stopped");
441 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
442 : LXC_MAINLOOP_CONTINUE
;
445 if (siginfo
.ssi_code
== CLD_CONTINUED
) {
446 INFO("Container init process was continued");
447 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
448 : LXC_MAINLOOP_CONTINUE
;
451 DEBUG("Container init process %d exited", hdlr
->pid
);
453 return LXC_MAINLOOP_CLOSE
;
456 int lxc_serve_state_clients(const char *name
, struct lxc_handler
*handler
,
461 struct lxc_list
*cur
, *next
;
462 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
465 handler
->state
= RUNNING
;
467 handler
->state
= state
;
469 TRACE("Set container state to %s", lxc_state2str(state
));
471 if (lxc_list_empty(&handler
->conf
->state_clients
)) {
472 TRACE("No state clients registered");
476 retlen
= strlcpy(msg
.name
, name
, sizeof(msg
.name
));
477 if (retlen
>= sizeof(msg
.name
))
480 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
481 struct lxc_state_client
*client
= cur
->elem
;
483 if (client
->states
[state
] == 0) {
484 TRACE("State %s not registered for state client %d",
485 lxc_state2str(state
), client
->clientfd
);
489 TRACE("Sending state %s to state client %d",
490 lxc_state2str(state
), client
->clientfd
);
492 ret
= lxc_send_nointr(client
->clientfd
, &msg
, sizeof(msg
), MSG_NOSIGNAL
);
494 SYSERROR("Failed to send message to client");
496 /* kick client from list */
498 close(client
->clientfd
);
506 static int lxc_serve_state_socket_pair(const char *name
,
507 struct lxc_handler
*handler
,
512 if (!handler
->daemonize
||
513 handler
->state_socket_pair
[1] < 0 ||
517 /* Close read end of the socket pair. */
518 close(handler
->state_socket_pair
[0]);
519 handler
->state_socket_pair
[0] = -1;
522 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
523 &(int){state
}, sizeof(int));
525 SYSERROR("Failed to send state to %d", handler
->state_socket_pair
[1]);
533 if (ret
!= sizeof(int)) {
534 ERROR("Message too long : %d", handler
->state_socket_pair
[1]);
538 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
539 handler
->state_socket_pair
[1]);
541 /* Close write end of the socket pair. */
542 close(handler
->state_socket_pair
[1]);
543 handler
->state_socket_pair
[1] = -1;
548 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
553 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
555 ERROR("Failed to synchronize via anonymous pair of unix sockets");
559 ret
= lxc_serve_state_clients(name
, handler
, state
);
563 /* This function will try to connect to the legacy lxc-monitord state
564 * server and only exists for backwards compatibility.
566 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
571 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
574 bool has_console
= true;
575 struct lxc_epoll_descr descr
, descr_console
;
577 if (handler
->conf
->console
.path
&&
578 strcmp(handler
->conf
->console
.path
, "none") == 0)
581 ret
= lxc_mainloop_open(&descr
);
583 ERROR("Failed to create mainloop");
588 ret
= lxc_mainloop_open(&descr_console
);
590 ERROR("Failed to create console mainloop");
595 ret
= lxc_mainloop_add_handler(&descr
, handler
->sigfd
, signal_handler
, handler
);
597 ERROR("Failed to add signal handler for %d to mainloop", handler
->sigfd
);
598 goto out_mainloop_console
;
601 ret
= lxc_seccomp_setup_proxy(&handler
->conf
->seccomp
, &descr
, handler
);
603 ERROR("Failed to setup seccomp proxy");
604 goto out_mainloop_console
;
608 struct lxc_terminal
*console
= &handler
->conf
->console
;
610 ret
= lxc_terminal_mainloop_add(&descr
, console
);
612 ERROR("Failed to add console handlers to mainloop");
613 goto out_mainloop_console
;
616 ret
= lxc_terminal_mainloop_add(&descr_console
, console
);
618 ERROR("Failed to add console handlers to console mainloop");
619 goto out_mainloop_console
;
622 handler
->conf
->console
.descr
= &descr
;
625 ret
= lxc_cmd_mainloop_add(name
, &descr
, handler
);
627 ERROR("Failed to add command handler to mainloop");
628 goto out_mainloop_console
;
631 TRACE("Mainloop is ready");
633 ret
= lxc_mainloop(&descr
, -1);
636 if (ret
< 0 || !handler
->init_died
)
637 goto out_mainloop_console
;
640 ret
= lxc_mainloop(&descr_console
, 0);
642 out_mainloop_console
:
644 lxc_mainloop_close(&descr_console
);
645 TRACE("Closed console mainloop");
649 lxc_mainloop_close(&descr
);
650 TRACE("Closed mainloop");
653 close(handler
->sigfd
);
654 TRACE("Closed signal file descriptor %d", handler
->sigfd
);
655 handler
->sigfd
= -EBADF
;
660 void lxc_zero_handler(struct lxc_handler
*handler
)
664 memset(handler
, 0, sizeof(struct lxc_handler
));
668 handler
->proc_pidfd
= -EBADF
;
672 for (i
= 0; i
< LXC_NS_MAX
; i
++)
673 handler
->nsfd
[i
] = -1;
675 handler
->data_sock
[0] = -1;
676 handler
->data_sock
[1] = -1;
678 handler
->state_socket_pair
[0] = -1;
679 handler
->state_socket_pair
[1] = -1;
681 handler
->sync_sock
[0] = -1;
682 handler
->sync_sock
[1] = -1;
685 void lxc_free_handler(struct lxc_handler
*handler
)
687 if (handler
->pinfd
>= 0)
688 close(handler
->pinfd
);
690 if (handler
->proc_pidfd
>= 0)
691 close(handler
->proc_pidfd
);
693 if (handler
->sigfd
>= 0)
694 close(handler
->sigfd
);
696 lxc_put_nsfds(handler
);
698 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
699 if (handler
->conf
->maincmd_fd
>= 0)
700 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
702 if (handler
->state_socket_pair
[0] >= 0)
703 close(handler
->state_socket_pair
[0]);
705 if (handler
->state_socket_pair
[1] >= 0)
706 close(handler
->state_socket_pair
[1]);
708 if (handler
->cgroup_ops
)
709 cgroup_exit(handler
->cgroup_ops
);
711 handler
->conf
= NULL
;
716 struct lxc_handler
*lxc_init_handler(const char *name
, struct lxc_conf
*conf
,
717 const char *lxcpath
, bool daemonize
)
720 struct lxc_handler
*handler
;
722 handler
= malloc(sizeof(*handler
));
726 memset(handler
, 0, sizeof(*handler
));
728 /* Note that am_guest_unpriv() checks the effective uid. We
729 * probably don't care if we are real root only if we are running
730 * as root so this should be fine.
732 handler
->am_root
= !am_guest_unpriv();
733 handler
->data_sock
[0] = handler
->data_sock
[1] = -1;
734 handler
->conf
= conf
;
735 handler
->lxcpath
= lxcpath
;
737 handler
->proc_pidfd
= -EBADF
;
738 handler
->sigfd
= -EBADF
;
739 handler
->init_died
= false;
740 handler
->state_socket_pair
[0] = handler
->state_socket_pair
[1] = -1;
741 if (handler
->conf
->reboot
== REBOOT_NONE
)
742 lxc_list_init(&handler
->conf
->state_clients
);
744 for (i
= 0; i
< LXC_NS_MAX
; i
++)
745 handler
->nsfd
[i
] = -1;
747 handler
->name
= name
;
749 if (daemonize
&& handler
->conf
->reboot
== REBOOT_NONE
) {
750 /* Create socketpair() to synchronize on daemonized startup.
751 * When the container reboots we don't need to synchronize
752 * again currently so don't open another socketpair().
754 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
755 handler
->state_socket_pair
);
757 ERROR("Failed to create anonymous pair of unix sockets");
761 TRACE("Created anonymous pair {%d,%d} of unix sockets",
762 handler
->state_socket_pair
[0],
763 handler
->state_socket_pair
[1]);
766 if (handler
->conf
->reboot
== REBOOT_NONE
) {
767 handler
->conf
->maincmd_fd
= lxc_cmd_init(name
, lxcpath
, "command");
768 if (handler
->conf
->maincmd_fd
< 0) {
769 ERROR("Failed to set up command socket");
774 TRACE("Unix domain socket %d for command server is ready",
775 handler
->conf
->maincmd_fd
);
780 lxc_free_handler(handler
);
785 int lxc_init(const char *name
, struct lxc_handler
*handler
)
788 const char *loglevel
;
789 struct lxc_conf
*conf
= handler
->conf
;
791 handler
->monitor_pid
= lxc_raw_getpid();
794 TRACE("Initialized LSM");
796 ret
= lxc_read_seccomp_config(conf
);
798 ERROR("Failed loading seccomp policy");
799 goto out_close_maincmd_fd
;
801 TRACE("Read seccomp policy");
803 /* Begin by setting the state to STARTING. */
804 ret
= lxc_set_state(name
, handler
, STARTING
);
806 ERROR("Failed to set state to \"%s\"", lxc_state2str(STARTING
));
807 goto out_close_maincmd_fd
;
809 TRACE("Set container state to \"STARTING\"");
811 /* Start of environment variable setup for hooks. */
812 ret
= setenv("LXC_NAME", name
, 1);
814 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name
);
817 ret
= setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1);
819 SYSERROR("Failed to set environment variable: "
820 "LXC_CONFIG_FILE=%s", conf
->rcfile
);
823 if (conf
->rootfs
.mount
) {
824 ret
= setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1);
826 SYSERROR("Failed to set environment variable: "
827 "LXC_ROOTFS_MOUNT=%s", conf
->rootfs
.mount
);
830 if (conf
->rootfs
.path
) {
831 ret
= setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1);
833 SYSERROR("Failed to set environment variable: "
834 "LXC_ROOTFS_PATH=%s", conf
->rootfs
.path
);
837 if (conf
->console
.path
) {
838 ret
= setenv("LXC_CONSOLE", conf
->console
.path
, 1);
840 SYSERROR("Failed to set environment variable: "
841 "LXC_CONSOLE=%s", conf
->console
.path
);
844 if (conf
->console
.log_path
) {
845 ret
= setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1);
847 SYSERROR("Failed to set environment variable: "
848 "LXC_CONSOLE_LOGPATH=%s", conf
->console
.log_path
);
851 if (cgns_supported()) {
852 ret
= setenv("LXC_CGNS_AWARE", "1", 1);
854 SYSERROR("Failed to set environment variable "
858 loglevel
= lxc_log_priority_to_string(lxc_log_get_level());
859 ret
= setenv("LXC_LOG_LEVEL", loglevel
, 1);
861 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s",
864 if (conf
->hooks_version
== 0)
865 ret
= setenv("LXC_HOOK_VERSION", "0", 1);
867 ret
= setenv("LXC_HOOK_VERSION", "1", 1);
869 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf
->hooks_version
);
870 /* End of environment variable setup for hooks. */
872 TRACE("Set environment variables");
874 ret
= run_lxc_hooks(name
, "pre-start", conf
, NULL
);
876 ERROR("Failed to run lxc.hook.pre-start for container \"%s\"", name
);
879 TRACE("Ran pre-start hooks");
881 /* The signal fd has to be created before forking otherwise if the child
882 * process exits before we setup the signal fd, the event will be lost
883 * and the command will be stuck.
885 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
886 if (handler
->sigfd
< 0) {
887 ERROR("Failed to setup SIGCHLD fd handler.");
890 TRACE("Set up signal fd");
892 /* Do this after setting up signals since it might unblock SIGWINCH. */
893 ret
= lxc_terminal_setup(conf
);
895 ERROR("Failed to create console");
896 goto out_restore_sigmask
;
898 TRACE("Created console");
900 ret
= lxc_terminal_map_ids(conf
, &conf
->console
);
902 ERROR("Failed to chown console");
903 goto out_delete_terminal
;
905 TRACE("Chowned console");
907 handler
->cgroup_ops
= cgroup_init(handler
->conf
);
908 if (!handler
->cgroup_ops
) {
909 ERROR("Failed to initialize cgroup driver");
910 goto out_delete_terminal
;
912 TRACE("Initialized cgroup driver");
914 ret
= lsm_process_prepare(conf
, handler
->lxcpath
);
916 ERROR("Failed to initialize LSM");
917 goto out_destroy_cgroups
;
919 TRACE("Initialized LSM");
921 INFO("Container \"%s\" is initialized", name
);
925 handler
->cgroup_ops
->payload_destroy(handler
->cgroup_ops
, handler
);
926 handler
->cgroup_ops
->monitor_destroy(handler
->cgroup_ops
, handler
);
929 lxc_terminal_delete(&handler
->conf
->console
);
932 (void)pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
935 lxc_delete_tty(&conf
->ttys
);
938 (void)lxc_set_state(name
, handler
, ABORTING
);
940 out_close_maincmd_fd
:
941 lxc_abstract_unix_close(conf
->maincmd_fd
);
942 conf
->maincmd_fd
= -1;
946 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
950 struct lxc_list
*cur
, *next
;
951 char *namespaces
[LXC_NS_MAX
+ 1];
952 size_t namespace_count
= 0;
953 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
955 /* The STOPPING state is there for future cleanup code which can take
958 lxc_set_state(name
, handler
, STOPPING
);
960 self
= lxc_raw_getpid();
961 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
962 if (handler
->nsfd
[i
] < 0)
965 if (handler
->conf
->hooks_version
== 0)
966 ret
= asprintf(&namespaces
[namespace_count
],
967 "%s:/proc/%d/fd/%d", ns_info
[i
].proc_name
,
968 self
, handler
->nsfd
[i
]);
970 ret
= asprintf(&namespaces
[namespace_count
],
971 "/proc/%d/fd/%d", self
, handler
->nsfd
[i
]);
973 SYSERROR("Failed to allocate memory");
977 if (handler
->conf
->hooks_version
== 0) {
982 ret
= setenv(ns_info
[i
].env_name
, namespaces
[namespace_count
], 1);
984 SYSERROR("Failed to set environment variable %s=%s",
985 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
987 TRACE("Set environment variable %s=%s",
988 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
992 namespaces
[namespace_count
] = NULL
;
994 if (handler
->conf
->reboot
> REBOOT_NONE
) {
995 ret
= setenv("LXC_TARGET", "reboot", 1);
997 SYSERROR("Failed to set environment variable: "
998 "LXC_TARGET=reboot");
1001 if (handler
->conf
->reboot
== REBOOT_NONE
) {
1002 ret
= setenv("LXC_TARGET", "stop", 1);
1004 SYSERROR("Failed to set environment variable: "
1008 if (handler
->conf
->hooks_version
== 0)
1009 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, namespaces
);
1011 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, NULL
);
1013 ERROR("Failed to run \"lxc.hook.stop\" hook");
1015 while (namespace_count
--)
1016 free(namespaces
[namespace_count
]);
1018 lsm_process_cleanup(handler
->conf
, handler
->lxcpath
);
1020 cgroup_ops
->payload_destroy(cgroup_ops
, handler
);
1021 cgroup_ops
->monitor_destroy(cgroup_ops
, handler
);
1023 if (handler
->conf
->reboot
== REBOOT_NONE
) {
1024 /* For all new state clients simply close the command socket.
1025 * This will inform all state clients that the container is
1026 * STOPPED and also prevents a race between a open()/close() on
1027 * the command socket causing a new process to get ECONNREFUSED
1028 * because we haven't yet closed the command socket.
1030 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
1031 handler
->conf
->maincmd_fd
= -1;
1032 TRACE("Closed command socket");
1034 /* This function will try to connect to the legacy lxc-monitord
1035 * state server and only exists for backwards compatibility.
1037 lxc_monitor_send_state(name
, STOPPED
, handler
->lxcpath
);
1039 /* The command socket is closed so no one can acces the command
1040 * socket anymore so there's no need to lock it.
1042 handler
->state
= STOPPED
;
1043 TRACE("Set container state to \"STOPPED\"");
1045 lxc_set_state(name
, handler
, STOPPED
);
1048 /* Avoid lingering namespace references. */
1049 lxc_put_nsfds(handler
);
1051 ret
= run_lxc_hooks(name
, "post-stop", handler
->conf
, NULL
);
1053 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name
);
1054 if (handler
->conf
->reboot
> REBOOT_NONE
) {
1055 WARN("Container will be stopped instead of rebooted");
1056 handler
->conf
->reboot
= REBOOT_NONE
;
1058 ret
= setenv("LXC_TARGET", "stop", 1);
1060 WARN("Failed to set environment variable: "
1065 /* Reset mask set by setup_signal_fd. */
1066 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1068 SYSWARN("Failed to restore signal mask");
1070 lxc_terminal_delete(&handler
->conf
->console
);
1071 lxc_delete_tty(&handler
->conf
->ttys
);
1073 /* The command socket is now closed, no more state clients can register
1074 * themselves from now on. So free the list of state clients.
1076 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
1077 struct lxc_state_client
*client
= cur
->elem
;
1079 /* Keep state clients that want to be notified about reboots. */
1080 if ((handler
->conf
->reboot
> REBOOT_NONE
) &&
1081 (client
->states
[RUNNING
] == 2))
1084 /* close state client socket */
1086 close(client
->clientfd
);
1091 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= REBOOT_REQ
)
1092 lxc_destroy_container_on_signal(handler
, name
);
1094 lxc_free_handler(handler
);
1097 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
1101 lxc_set_state(name
, handler
, ABORTING
);
1103 if (handler
->pid
> 0) {
1104 ret
= lxc_raw_pidfd_send_signal(handler
->proc_pidfd
, SIGKILL
, NULL
, 0);
1106 SYSERROR("Failed to send SIGKILL to %d", handler
->pid
);
1109 while ((ret
= waitpid(-1, &status
, 0)) > 0) {
1114 static int do_start(void *data
)
1116 struct lxc_handler
*handler
= data
;
1117 ATTR_UNUSED __do_close_prot_errno
int data_sock0
= handler
->data_sock
[0],
1118 data_sock1
= handler
->data_sock
[1];
1120 char path
[PATH_MAX
];
1123 struct lxc_list
*iterator
;
1126 int devnull_fd
= -1;
1128 lxc_sync_fini_parent(handler
);
1130 /* This prctl must be before the synchro, so if the parent dies before
1131 * we set the parent death signal, we will detect its death with the
1132 * synchro right after, otherwise we have a window where the parent can
1133 * exit before we set the pdeath signal leading to a unsupervized
1136 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
);
1138 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1139 goto out_warn_father
;
1142 ret
= lxc_ambient_caps_up();
1144 ERROR("Failed to raise ambient capabilities");
1145 goto out_warn_father
;
1148 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1150 SYSERROR("Failed to set signal mask");
1151 goto out_warn_father
;
1154 /* Don't leak the pinfd to the container. */
1155 if (handler
->pinfd
>= 0)
1156 close(handler
->pinfd
);
1158 ret
= lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
);
1160 goto out_warn_father
;
1162 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1163 * https://github.com/lxc/lxd/issues/1978.
1165 if ((handler
->ns_clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
1166 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
1167 ret
= unshare(CLONE_NEWNET
);
1169 SYSERROR("Failed to unshare CLONE_NEWNET");
1170 goto out_warn_father
;
1172 INFO("Unshared CLONE_NEWNET");
1175 /* Tell the parent task it can begin to configure the container and wait
1178 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
);
1182 ret
= lxc_network_recv_veth_names_from_parent(handler
);
1184 ERROR("Failed to receive veth names from parent");
1185 goto out_warn_father
;
1188 /* If we are in a new user namespace, become root there to have
1189 * privilege over our namespace.
1191 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1192 if (!handler
->conf
->root_nsuid_map
)
1193 nsuid
= handler
->conf
->init_uid
;
1195 if (!handler
->conf
->root_nsgid_map
)
1196 nsgid
= handler
->conf
->init_gid
;
1198 if (!lxc_switch_uid_gid(nsuid
, nsgid
))
1199 goto out_warn_father
;
1201 /* Drop groups only after we switched to a valid gid in the new
1204 if (!lxc_setgroups(0, NULL
) &&
1205 (handler
->am_root
|| errno
!= EPERM
))
1206 goto out_warn_father
;
1208 ret
= prctl(PR_SET_DUMPABLE
, prctl_arg(1), prctl_arg(0),
1209 prctl_arg(0), prctl_arg(0));
1211 goto out_warn_father
;
1213 /* set{g,u}id() clears deathsignal */
1214 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
);
1216 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1217 goto out_warn_father
;
1221 ret
= access(handler
->lxcpath
, X_OK
);
1223 print_top_failing_dir(handler
->lxcpath
);
1224 goto out_warn_father
;
1227 ret
= snprintf(path
, sizeof(path
), "%s/dev/null",
1228 handler
->conf
->rootfs
.mount
);
1229 if (ret
< 0 || ret
>= sizeof(path
))
1230 goto out_warn_father
;
1232 /* In order to checkpoint restore, we need to have everything in the
1233 * same mount namespace. However, some containers may not have a
1234 * reasonable /dev (in particular, they may not have /dev/null), so we
1235 * can't set init's std fds to /dev/null by opening it from inside the
1238 * If that's the case, fall back to using the host's /dev/null. This
1239 * means that migration won't work, but at least we won't spew output
1240 * where it isn't wanted.
1242 if (handler
->daemonize
&& !handler
->conf
->autodev
) {
1243 ret
= access(path
, F_OK
);
1245 devnull_fd
= open_devnull();
1248 goto out_warn_father
;
1249 WARN("Using /dev/null from the host for container "
1250 "init's standard file descriptors. Migration will "
1255 /* Ask father to setup cgroups and wait for him to finish. */
1256 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
);
1260 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1261 * earlier we end up with a wrong view of /proc/self/cgroup. For
1262 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1263 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1264 * /proc/self/cgroup would show us:
1268 * whereas it should actually show
1272 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1273 ret
= unshare(CLONE_NEWCGROUP
);
1275 if (errno
!= EINVAL
) {
1276 SYSERROR("Failed to unshare CLONE_NEWCGROUP");
1277 goto out_warn_father
;
1280 handler
->ns_clone_flags
&= ~CLONE_NEWCGROUP
;
1281 SYSINFO("Kernel does not support CLONE_NEWCGROUP");
1283 INFO("Unshared CLONE_NEWCGROUP");
1287 /* Add the requested environment variables to the current environment to
1288 * allow them to be used by the various hooks, such as the start hook
1291 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1292 ret
= putenv((char *)iterator
->elem
);
1294 SYSERROR("Failed to set environment variable: %s",
1295 (char *)iterator
->elem
);
1296 goto out_warn_father
;
1300 /* Setup the container, ip, names, utsname, ... */
1301 ret
= lxc_setup(handler
);
1303 ERROR("Failed to setup container \"%s\"", handler
->name
);
1304 goto out_warn_father
;
1307 /* Set the label to change to when we exec(2) the container's init. */
1308 ret
= lsm_process_label_set(NULL
, handler
->conf
, true);
1310 goto out_warn_father
;
1312 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1313 * before we aren't allowed anymore.
1315 if (handler
->conf
->no_new_privs
) {
1316 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
1317 prctl_arg(0), prctl_arg(0));
1319 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block "
1320 "execve() gainable privileges");
1321 goto out_warn_father
;
1323 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable "
1327 /* Some init's such as busybox will set sane tty settings on stdin,
1328 * stdout, stderr which it thinks is the console. We already set them
1329 * the way we wanted on the real terminal, and we want init to do its
1330 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
1331 * make sure that that pty is stdin,stdout,stderr.
1333 if (handler
->conf
->console
.slave
>= 0) {
1334 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
1335 ret
= set_stdfds(handler
->conf
->console
.slave
);
1337 ret
= lxc_terminal_set_stdfds(handler
->conf
->console
.slave
);
1339 ERROR("Failed to redirect std{in,out,err} to pty file "
1340 "descriptor %d", handler
->conf
->console
.slave
);
1341 goto out_warn_father
;
1345 /* If we mounted a temporary proc, then unmount it now. */
1346 tmp_proc_unmount(handler
->conf
);
1348 ret
= lxc_seccomp_load(handler
->conf
);
1350 goto out_warn_father
;
1352 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, data_sock0
);
1354 SYSERROR("Failed to send seccomp notify fd to parent");
1355 goto out_warn_father
;
1358 ret
= run_lxc_hooks(handler
->name
, "start", handler
->conf
, NULL
);
1360 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1362 goto out_warn_father
;
1365 close(handler
->sigfd
);
1367 if (handler
->conf
->console
.slave
< 0 && handler
->daemonize
) {
1368 if (devnull_fd
< 0) {
1369 devnull_fd
= open_devnull();
1371 goto out_warn_father
;
1374 ret
= set_stdfds(devnull_fd
);
1376 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
1377 goto out_warn_father
;
1381 if (devnull_fd
>= 0) {
1388 if (handler
->conf
->init_cwd
) {
1389 ret
= chdir(handler
->conf
->init_cwd
);
1391 SYSERROR("Could not change directory to \"%s\"",
1392 handler
->conf
->init_cwd
);
1393 goto out_warn_father
;
1397 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
);
1399 goto out_warn_father
;
1401 /* Reset the environment variables the user requested in a clear
1405 /* Don't error out though. */
1407 SYSERROR("Failed to clear environment.");
1409 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1410 ret
= putenv((char *)iterator
->elem
);
1412 SYSERROR("Failed to set environment variable: %s",
1413 (char *)iterator
->elem
);
1414 goto out_warn_father
;
1418 ret
= putenv("container=lxc");
1420 SYSERROR("Failed to set environment variable: container=lxc");
1421 goto out_warn_father
;
1424 if (handler
->conf
->ttys
.tty_names
) {
1425 ret
= putenv(handler
->conf
->ttys
.tty_names
);
1427 SYSERROR("Failed to set environment variable for container ptys");
1428 goto out_warn_father
;
1432 /* The container has been setup. We can now switch to an unprivileged
1435 new_uid
= handler
->conf
->init_uid
;
1436 new_gid
= handler
->conf
->init_gid
;
1438 /* Avoid unnecessary syscalls. */
1439 if (new_uid
== nsuid
)
1440 new_uid
= LXC_INVALID_UID
;
1442 if (new_gid
== nsgid
)
1443 new_gid
= LXC_INVALID_GID
;
1445 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
1446 goto out_warn_father
;
1448 /* If we are in a new user namespace we already dropped all groups when
1449 * we switched to root in the new user namespace further above. Only
1450 * drop groups if we can, so ensure that we have necessary privilege.
1452 if (lxc_list_empty(&handler
->conf
->id_map
))
1454 if (lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
))
1456 if (!lxc_setgroups(0, NULL
))
1457 goto out_warn_father
;
1459 ret
= lxc_ambient_caps_down();
1461 ERROR("Failed to clear ambient capabilities");
1462 goto out_warn_father
;
1465 if (handler
->conf
->monitor_signal_pdeath
!= SIGKILL
) {
1466 ret
= lxc_set_death_signal(handler
->conf
->monitor_signal_pdeath
, handler
->monitor_pid
);
1468 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1469 handler
->conf
->monitor_signal_pdeath
);
1470 goto out_warn_father
;
1474 /* After this call, we are in error because this ops should not return
1477 handler
->ops
->start(handler
, handler
->data
);
1480 /* We want the parent to know something went wrong, so we return a
1481 * special error code.
1483 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1486 if (devnull_fd
>= 0)
1492 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1495 struct lxc_terminal_info
*tty
;
1497 int sock
= handler
->data_sock
[1];
1498 struct lxc_conf
*conf
= handler
->conf
;
1499 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1501 if (!conf
->ttys
.max
)
1504 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
1508 for (i
= 0; i
< conf
->ttys
.max
; i
++) {
1511 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1515 tty
= &ttys
->tty
[i
];
1517 tty
->master
= ttyfds
[0];
1518 tty
->slave
= ttyfds
[1];
1519 TRACE("Received pty with master fd %d and slave fd %d from "
1520 "parent", tty
->master
, tty
->slave
);
1524 SYSERROR("Failed to receive %zu ttys from child", ttys
->max
);
1526 TRACE("Received %zu ttys from child", ttys
->max
);
1531 int resolve_clone_flags(struct lxc_handler
*handler
)
1534 struct lxc_conf
*conf
= handler
->conf
;
1536 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1537 if (conf
->ns_keep
) {
1538 if (!(conf
->ns_keep
& ns_info
[i
].clone_flag
))
1539 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1540 } else if (conf
->ns_clone
) {
1541 if ((conf
->ns_clone
& ns_info
[i
].clone_flag
))
1542 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1544 if (i
== LXC_NS_USER
&& lxc_list_empty(&handler
->conf
->id_map
))
1547 if (i
== LXC_NS_NET
&& lxc_requests_empty_network(handler
))
1550 if (i
== LXC_NS_CGROUP
&& !cgns_supported())
1553 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1556 if (!conf
->ns_share
[i
])
1559 handler
->ns_clone_flags
&= ~ns_info
[i
].clone_flag
;
1560 TRACE("Sharing %s namespace", ns_info
[i
].proc_name
);
1566 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1567 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1568 * But since the memory between parent and child is shared on CLONE_VM this
1569 * would invalidate the getpid() cache that glibc used to maintain and so
1570 * getpid() in the child would return the parent's pid. This is all fixed in
1571 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1572 * not reset anymore.
1573 * However, if for whatever reason you - dear committer - somehow need to get the
1574 * pid of the dummy intermediate process for do_share_ns() you need to call
1575 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1578 static inline int do_share_ns(void *arg
)
1581 struct lxc_handler
*handler
= arg
;
1583 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1584 if (handler
->nsfd
[i
] < 0)
1587 ret
= setns(handler
->nsfd
[i
], 0);
1590 * Note that joining a user and/or mount namespace
1591 * requires the process is not multithreaded otherwise
1592 * setns() will fail here.
1594 SYSERROR("Failed to inherit %s namespace",
1595 ns_info
[i
].proc_name
);
1599 DEBUG("Inherited %s namespace", ns_info
[i
].proc_name
);
1602 flags
= handler
->ns_on_clone_flags
;
1603 flags
|= CLONE_PARENT
;
1604 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, flags
);
1605 if (handler
->pid
< 0)
1611 static int proc_pidfd_open(pid_t pid
)
1613 __do_close_prot_errno
int proc_pidfd
= -EBADF
;
1616 snprintf(path
, sizeof(path
), "/proc/%d", pid
);
1617 proc_pidfd
= open(path
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1618 if (proc_pidfd
< 0) {
1619 SYSERROR("Failed to open %s", path
);
1623 /* Test whether we can send signals. */
1624 if (lxc_raw_pidfd_send_signal(proc_pidfd
, 0, NULL
, 0)) {
1625 SYSERROR("Failed to send signal through pidfd");
1629 return move_fd(proc_pidfd
);
1632 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1633 * exec()s the requested container binary.
1634 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1635 * right here should be double checked if they'd pose a security risk. (For
1636 * example, any {u}mount() operations performed here will be reflected on the
1639 static int lxc_spawn(struct lxc_handler
*handler
)
1641 __do_close_prot_errno
int data_sock0
= -EBADF
, data_sock1
= -EBADF
;
1644 bool wants_to_map_ids
;
1645 struct lxc_list
*id_map
;
1646 const char *name
= handler
->name
;
1647 const char *lxcpath
= handler
->lxcpath
;
1648 bool share_ns
= false;
1649 struct lxc_conf
*conf
= handler
->conf
;
1650 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
1652 id_map
= &conf
->id_map
;
1653 wants_to_map_ids
= !lxc_list_empty(id_map
);
1655 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1656 if (!conf
->ns_share
[i
])
1659 handler
->nsfd
[i
] = lxc_inherit_namespace(conf
->ns_share
[i
], lxcpath
, ns_info
[i
].proc_name
);
1660 if (handler
->nsfd
[i
] < 0)
1666 ret
= lxc_sync_init(handler
);
1670 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1671 handler
->data_sock
);
1674 data_sock0
= handler
->data_sock
[0];
1675 data_sock1
= handler
->data_sock
[1];
1677 ret
= resolve_clone_flags(handler
);
1681 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1682 if (!lxc_list_empty(&conf
->network
)) {
1684 /* Find gateway addresses from the link device, which is
1685 * no longer accessible inside the container. Do this
1686 * before creating network interfaces, since goto
1687 * out_delete_net does not work before lxc_clone.
1689 ret
= lxc_find_gateway_addresses(handler
);
1691 ERROR("Failed to find gateway addresses");
1695 /* That should be done before the clone because we will
1696 * fill the netdev index and use them in the child.
1698 ret
= lxc_create_network_priv(handler
);
1700 ERROR("Failed to create the network");
1701 goto out_delete_net
;
1706 if (!cgroup_ops
->payload_create(cgroup_ops
, handler
)) {
1707 ERROR("Failed creating cgroups");
1708 goto out_delete_net
;
1711 /* If the rootfs is not a blockdev, prevent the container from marking
1713 * If the container is unprivileged then skip rootfs pinning.
1715 if (!wants_to_map_ids
) {
1716 handler
->pinfd
= pin_rootfs(conf
->rootfs
.path
);
1717 if (handler
->pinfd
== -1)
1718 INFO("Failed to pin the rootfs for container \"%s\"", handler
->name
);
1721 /* Create a process in a new set of namespaces. */
1722 handler
->ns_on_clone_flags
= handler
->ns_clone_flags
;
1723 if (handler
->ns_clone_flags
& CLONE_NEWUSER
) {
1724 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1725 * clone a new user namespace first and only later unshare our
1726 * network namespace to ensure that network devices ownership is
1729 handler
->ns_on_clone_flags
&= ~CLONE_NEWNET
;
1731 /* The cgroup namespace gets unshare()ed not clone()ed. */
1732 handler
->ns_on_clone_flags
&= ~CLONE_NEWCGROUP
;
1737 attacher_pid
= lxc_clone(do_share_ns
, handler
,
1738 CLONE_VFORK
| CLONE_VM
| CLONE_FILES
);
1739 if (attacher_pid
< 0) {
1740 SYSERROR(LXC_CLONE_ERROR
);
1741 goto out_delete_net
;
1744 ret
= wait_for_pid(attacher_pid
);
1746 SYSERROR("Intermediate process failed");
1747 goto out_delete_net
;
1750 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
,
1751 handler
->ns_on_clone_flags
);
1753 if (handler
->pid
< 0) {
1754 SYSERROR(LXC_CLONE_ERROR
);
1755 goto out_delete_net
;
1757 TRACE("Cloned child process %d", handler
->pid
);
1759 handler
->proc_pidfd
= proc_pidfd_open(handler
->pid
);
1760 if (handler
->proc_pidfd
< 0 && (errno
!= ENOSYS
))
1761 goto out_delete_net
;
1763 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1764 if (handler
->ns_on_clone_flags
& ns_info
[i
].clone_flag
)
1765 INFO("Cloned %s", ns_info
[i
].flag_name
);
1767 if (!lxc_try_preserve_namespaces(handler
, handler
->ns_on_clone_flags
, handler
->pid
)) {
1768 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1769 goto out_delete_net
;
1772 lxc_sync_fini_child(handler
);
1774 /* Map the container uids. The container became an invalid userid the
1775 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1776 * anything immediately, but allows the container to setuid(0) (0 being
1777 * mapped to something else on the host.) later to become a valid uid
1780 if (wants_to_map_ids
) {
1781 if (!handler
->conf
->ns_share
[LXC_NS_USER
] &&
1782 (handler
->conf
->ns_keep
& CLONE_NEWUSER
) == 0) {
1783 ret
= lxc_map_ids(id_map
, handler
->pid
);
1785 ERROR("Failed to set up id mapping.");
1786 goto out_delete_net
;
1791 ret
= lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
);
1793 goto out_delete_net
;
1795 ret
= lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
);
1797 goto out_delete_net
;
1799 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
->conf
, false)) {
1800 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1801 goto out_delete_net
;
1804 if (!cgroup_ops
->payload_enter(cgroup_ops
, handler
->pid
))
1805 goto out_delete_net
;
1807 if (!cgroup_ops
->chown(cgroup_ops
, handler
->conf
))
1808 goto out_delete_net
;
1810 /* Now we're ready to preserve the network namespace */
1811 ret
= lxc_try_preserve_ns(handler
->pid
, "net");
1813 if (ret
!= -EOPNOTSUPP
) {
1814 SYSERROR("Failed to preserve net namespace");
1815 goto out_delete_net
;
1818 handler
->nsfd
[LXC_NS_NET
] = ret
;
1819 DEBUG("Preserved net namespace via fd %d", ret
);
1821 ret
= lxc_netns_set_nsid(handler
->nsfd
[LXC_NS_NET
]);
1823 SYSWARN("Failed to allocate new network namespace id");
1825 TRACE("Allocated new network namespace id");
1828 /* Create the network configuration. */
1829 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1830 ret
= lxc_network_move_created_netdev_priv(handler
->lxcpath
,
1835 ERROR("Failed to create the configured network");
1836 goto out_delete_net
;
1839 ret
= lxc_create_network_unpriv(handler
->lxcpath
, handler
->name
,
1840 &conf
->network
, handler
->pid
, conf
->hooks_version
);
1842 ERROR("Failed to create the configured network");
1843 goto out_delete_net
;
1847 ret
= lxc_network_send_veth_names_to_child(handler
);
1849 ERROR("Failed to send veth names to child");
1850 goto out_delete_net
;
1853 if (!lxc_list_empty(&conf
->procs
)) {
1854 ret
= setup_proc_filesystem(&conf
->procs
, handler
->pid
);
1856 goto out_delete_net
;
1859 /* Tell the child to continue its initialization. We'll get
1860 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1862 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
);
1864 goto out_delete_net
;
1866 if (!lxc_list_empty(&conf
->limits
)) {
1867 ret
= setup_resource_limits(&conf
->limits
, handler
->pid
);
1869 ERROR("Failed to setup resource limits");
1870 goto out_delete_net
;
1874 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
);
1876 goto out_delete_net
;
1878 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
->conf
, true)) {
1879 ERROR("Failed to setup legacy device cgroup controller limits");
1880 goto out_delete_net
;
1882 TRACE("Set up legacy device cgroup controller limits");
1884 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1885 /* Now we're ready to preserve the cgroup namespace */
1886 ret
= lxc_try_preserve_ns(handler
->pid
, "cgroup");
1888 if (ret
!= -EOPNOTSUPP
) {
1889 SYSERROR("Failed to preserve cgroup namespace");
1890 goto out_delete_net
;
1893 handler
->nsfd
[LXC_NS_CGROUP
] = ret
;
1894 DEBUG("Preserved cgroup namespace via fd %d", ret
);
1898 ret
= snprintf(pidstr
, 20, "%d", handler
->pid
);
1899 if (ret
< 0 || ret
>= 20)
1900 goto out_delete_net
;
1902 ret
= setenv("LXC_PID", pidstr
, 1);
1904 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr
);
1906 /* Run any host-side start hooks */
1907 ret
= run_lxc_hooks(name
, "start-host", conf
, NULL
);
1909 ERROR("Failed to run lxc.hook.start-host");
1910 goto out_delete_net
;
1913 /* Tell the child to complete its initialization and wait for it to exec
1914 * or return an error. (The child will never return
1915 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1916 * lxc_sync_barrier_child to return success, or return a different
1917 * value, causing us to error out).
1919 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_READY_START
);
1921 goto out_delete_net
;
1923 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
1925 ERROR("Failed to receive names and ifindices for network "
1926 "devices from child");
1927 goto out_delete_net
;
1930 /* Now all networks are created, network devices are moved into place,
1931 * and the correct names and ifindices in the respective namespaces have
1932 * been recorded. The corresponding structs have now all been filled. So
1933 * log them for debugging purposes.
1935 lxc_log_configured_netdevs(conf
);
1937 /* Read tty fds allocated by child. */
1938 ret
= lxc_recv_ttys_from_child(handler
);
1940 ERROR("Failed to receive tty info from child process");
1941 goto out_delete_net
;
1944 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, data_sock1
);
1946 SYSERROR("Failed to receive seccomp notify fd from child");
1947 goto out_delete_net
;
1950 ret
= handler
->ops
->post_start(handler
, handler
->data
);
1954 ret
= lxc_set_state(name
, handler
, RUNNING
);
1956 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING
));
1960 lxc_sync_fini(handler
);
1965 if (handler
->ns_clone_flags
& CLONE_NEWNET
)
1966 lxc_delete_network(handler
);
1969 lxc_abort(name
, handler
);
1972 lxc_sync_fini(handler
);
1973 if (handler
->pinfd
>= 0) {
1974 close(handler
->pinfd
);
1975 handler
->pinfd
= -1;
1981 int __lxc_start(const char *name
, struct lxc_handler
*handler
,
1982 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1983 bool daemonize
, int *error_num
)
1986 struct lxc_conf
*conf
= handler
->conf
;
1987 struct cgroup_ops
*cgroup_ops
;
1989 ret
= lxc_init(name
, handler
);
1991 ERROR("Failed to initialize container \"%s\"", name
);
1995 handler
->data
= data
;
1996 handler
->daemonize
= daemonize
;
1997 cgroup_ops
= handler
->cgroup_ops
;
1999 if (!attach_block_device(handler
->conf
)) {
2000 ERROR("Failed to attach block device");
2002 goto out_fini_nonet
;
2005 if (!cgroup_ops
->monitor_create(cgroup_ops
, handler
)) {
2006 ERROR("Failed to create monitor cgroup");
2008 goto out_fini_nonet
;
2011 if (!cgroup_ops
->monitor_enter(cgroup_ops
, handler
->monitor_pid
)) {
2012 ERROR("Failed to enter monitor cgroup");
2014 goto out_fini_nonet
;
2017 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
2018 /* If the backing store is a device, mount it here and now. */
2019 if (rootfs_is_blockdev(conf
)) {
2020 ret
= unshare(CLONE_NEWNS
);
2022 ERROR("Failed to unshare CLONE_NEWNS");
2023 goto out_fini_nonet
;
2025 INFO("Unshared CLONE_NEWNS");
2027 remount_all_slave();
2028 ret
= lxc_setup_rootfs_prepare_root(conf
, name
, lxcpath
);
2030 ERROR("Error setting up rootfs mount as root before spawn");
2031 goto out_fini_nonet
;
2033 INFO("Set up container rootfs as host root");
2037 ret
= lxc_spawn(handler
);
2039 ERROR("Failed to spawn container \"%s\"", name
);
2040 goto out_detach_blockdev
;
2043 handler
->conf
->reboot
= REBOOT_NONE
;
2045 ret
= lxc_poll(name
, handler
);
2047 ERROR("LXC mainloop exited with error: %d", ret
);
2051 if (!handler
->init_died
&& handler
->pid
> 0) {
2052 ERROR("Child process is not killed");
2057 status
= lxc_wait_for_pid_status(handler
->pid
);
2059 SYSERROR("Failed to retrieve status for %d", handler
->pid
);
2061 /* If the child process exited but was not signaled, it didn't call
2062 * reboot. This should mean it was an lxc-execute which simply exited.
2063 * In any case, treat it as a 'halt'.
2065 if (WIFSIGNALED(status
)) {
2066 switch(WTERMSIG(status
)) {
2067 case SIGINT
: /* halt */
2068 DEBUG("Container \"%s\" is halting", name
);
2070 case SIGHUP
: /* reboot */
2071 DEBUG("Container \"%s\" is rebooting", name
);
2072 handler
->conf
->reboot
= REBOOT_REQ
;
2074 case SIGSYS
: /* seccomp */
2075 DEBUG("Container \"%s\" violated its seccomp policy", name
);
2078 DEBUG("Unknown exit status for container \"%s\" init %d", name
, WTERMSIG(status
));
2083 ret
= lxc_restore_phys_nics_to_netns(handler
);
2085 ERROR("Failed to move physical network devices back to parent "
2086 "network namespace");
2088 if (handler
->pinfd
>= 0) {
2089 close(handler
->pinfd
);
2090 handler
->pinfd
= -1;
2093 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
2094 lxc_error_set_and_log(handler
->pid
, status
);
2096 *error_num
= handler
->exit_status
;
2099 lxc_delete_network(handler
);
2101 out_detach_blockdev
:
2102 detach_block_device(handler
->conf
);
2105 lxc_fini(name
, handler
);
2109 lxc_abort(name
, handler
);
2117 static int start(struct lxc_handler
*handler
, void* data
)
2119 struct start_args
*arg
= data
;
2121 NOTICE("Exec'ing \"%s\"", arg
->argv
[0]);
2123 execvp(arg
->argv
[0], arg
->argv
);
2124 SYSERROR("Failed to exec \"%s\"", arg
->argv
[0]);
2128 static int post_start(struct lxc_handler
*handler
, void* data
)
2130 struct start_args
*arg
= data
;
2132 NOTICE("Started \"%s\" with pid \"%d\"", arg
->argv
[0], handler
->pid
);
2136 static struct lxc_operations start_ops
= {
2138 .post_start
= post_start
2141 int lxc_start(const char *name
, char *const argv
[], struct lxc_handler
*handler
,
2142 const char *lxcpath
, bool daemonize
, int *error_num
)
2144 struct start_args start_arg
= {
2148 TRACE("Doing lxc_start");
2149 return __lxc_start(name
, handler
, &start_ops
, &start_arg
, lxcpath
, daemonize
, error_num
);
2152 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
2155 char destroy
[PATH_MAX
];
2156 struct lxc_container
*c
;
2160 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
2161 bret
= do_destroy_container(handler
);
2163 ERROR("Error destroying rootfs for container \"%s\"", name
);
2167 INFO("Destroyed rootfs for container \"%s\"", name
);
2169 ret
= snprintf(destroy
, PATH_MAX
, "%s/%s", handler
->lxcpath
, name
);
2170 if (ret
< 0 || ret
>= PATH_MAX
) {
2171 ERROR("Error destroying directory for container \"%s\"", name
);
2175 c
= lxc_container_new(name
, handler
->lxcpath
);
2177 if (container_disk_lock(c
)) {
2178 INFO("Could not update lxc_snapshots file");
2179 lxc_container_put(c
);
2181 mod_all_rdeps(c
, false);
2182 container_disk_unlock(c
);
2183 lxc_container_put(c
);
2187 if (!handler
->am_root
)
2188 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
2189 destroy
, "lxc_rmdir_onedev_wrapper");
2191 ret
= lxc_rmdir_onedev(destroy
, NULL
);
2194 ERROR("Error destroying directory for container \"%s\"", name
);
2197 INFO("Destroyed directory for container \"%s\"", name
);
2200 static int lxc_rmdir_onedev_wrapper(void *data
)
2202 char *arg
= (char *) data
;
2203 return lxc_rmdir_onedev(arg
, NULL
);
2206 static bool do_destroy_container(struct lxc_handler
*handler
)
2210 if (!handler
->am_root
) {
2211 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
2212 handler
->conf
, "storage_destroy_wrapper");
2219 return storage_destroy(handler
->conf
);