]>
git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/start.c
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
41 #include <sys/mount.h>
42 #include <sys/param.h>
43 #include <sys/prctl.h>
44 #include <sys/socket.h>
46 #include <sys/syscall.h>
47 #include <sys/types.h>
56 #include "commands_utils.h"
59 #include "confile_utils.h"
61 #include "file_utils.h"
65 #include "lxccontainer.h"
67 #include "lxcseccomp.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
)
102 char *copy
, *e
, *p
, saved
;
105 copy
= alloca(len
+ 1);
106 (void)strlcpy(copy
, path
, len
+ 1);
112 while (p
< e
&& *p
== '/')
115 while (p
< e
&& *p
!= '/')
121 ret
= access(copy
, X_OK
);
123 SYSERROR("Could not access %s. Please grant it x "
124 "access, or add an ACL for the container "
132 static void lxc_put_nsfds(struct lxc_handler
*handler
)
136 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
137 if (handler
->nsfd
[i
] < 0)
140 close(handler
->nsfd
[i
]);
141 handler
->nsfd
[i
] = -EBADF
;
145 static int lxc_try_preserve_ns(const int pid
, const char *ns
)
149 fd
= lxc_preserve_ns(pid
, ns
);
151 if (errno
!= ENOENT
) {
152 SYSERROR("Failed to preserve %s namespace", ns
);
156 SYSWARN("Kernel does not support preserving %s namespaces", ns
);
163 /* lxc_try_preserve_namespaces: open /proc/@pid/ns/@ns for each namespace
164 * specified in ns_clone_flags.
165 * Return true on success, false on failure.
167 static bool lxc_try_preserve_namespaces(struct lxc_handler
*handler
,
168 int ns_clone_flags
, pid_t pid
)
172 for (i
= 0; i
< LXC_NS_MAX
; i
++)
173 handler
->nsfd
[i
] = -EBADF
;
175 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
178 if ((ns_clone_flags
& ns_info
[i
].clone_flag
) == 0)
181 fd
= lxc_try_preserve_ns(pid
, ns_info
[i
].proc_name
);
183 /* Do not fail to start container on kernels that do
184 * not support interacting with namespaces through
187 if (fd
== -EOPNOTSUPP
)
190 lxc_put_nsfds(handler
);
194 handler
->nsfd
[i
] = fd
;
195 DEBUG("Preserved %s namespace via fd %d", ns_info
[i
].proc_name
,
202 static inline bool match_stdfds(int fd
)
204 return (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
);
208 static bool match_dlog_fds(struct dirent
*direntp
)
210 char path
[PATH_MAX
] = {0};
211 char link
[PATH_MAX
] = {0};
215 ret
= snprintf(path
, PATH_MAX
, "/proc/self/fd/%s", direntp
->d_name
);
216 if (ret
< 0 || ret
>= PATH_MAX
) {
217 ERROR("Failed to create file descriptor name");
221 linklen
= readlink(path
, link
, PATH_MAX
);
223 SYSERROR("Failed to read link path - \"%s\"", path
);
225 } else if (linklen
>= PATH_MAX
) {
226 ERROR("The name of link path is too long - \"%s\"", path
);
230 if (strcmp(link
, "/dev/log_main") == 0 ||
231 strcmp(link
, "/dev/log_system") == 0 ||
232 strcmp(link
, "/dev/log_radio") == 0)
239 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
240 int *fds_to_ignore
, size_t len_fds
)
245 struct dirent
*direntp
;
247 if (conf
&& conf
->close_all_fds
)
251 dir
= opendir("/proc/self/fd");
253 SYSWARN("Failed to open directory");
259 while ((direntp
= readdir(dir
))) {
261 struct lxc_list
*cur
;
262 bool matched
= false;
264 if (strcmp(direntp
->d_name
, ".") == 0)
267 if (strcmp(direntp
->d_name
, "..") == 0)
270 ret
= lxc_safe_int(direntp
->d_name
, &fd
);
272 INFO("Could not parse file descriptor for \"%s\"", direntp
->d_name
);
276 for (i
= 0; i
< len_fds
; i
++)
277 if (fds_to_ignore
[i
] == fd
)
280 if (fd
== fddir
|| fd
== lxc_log_fd
||
281 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
284 /* Keep state clients that wait on reboots. */
286 lxc_list_for_each(cur
, &conf
->state_clients
) {
287 struct lxc_state_client
*client
= cur
->elem
;
289 if (client
->clientfd
!= fd
)
300 if (current_config
&& fd
== current_config
->logfd
)
303 if (match_stdfds(fd
))
307 if (match_dlog_fds(direntp
))
314 INFO("Closed inherited fd %d", fd
);
317 WARN("Inherited fd %d", fd
);
320 /* Only enable syslog at this point to avoid the above logging function
321 * to open a new fd and make the check_inherited function enter an
324 lxc_log_enable_syslog();
326 closedir(dir
); /* cannot fail */
330 static int setup_signal_fd(sigset_t
*oldmask
)
334 const int signals
[] = {SIGBUS
, SIGILL
, SIGSEGV
, SIGWINCH
};
336 /* Block everything except serious error signals. */
337 ret
= sigfillset(&mask
);
341 for (int sig
= 0; sig
< (sizeof(signals
) / sizeof(signals
[0])); sig
++) {
342 ret
= sigdelset(&mask
, signals
[sig
]);
347 ret
= pthread_sigmask(SIG_BLOCK
, &mask
, oldmask
);
349 SYSERROR("Failed to set signal mask");
353 ret
= signalfd(-1, &mask
, SFD_CLOEXEC
);
355 SYSERROR("Failed to create signal file descriptor");
359 TRACE("Created signal file descriptor %d", ret
);
364 static int signal_handler(int fd
, uint32_t events
, void *data
,
365 struct lxc_epoll_descr
*descr
)
369 struct signalfd_siginfo siginfo
;
370 struct lxc_handler
*hdlr
= data
;
372 ret
= lxc_read_nointr(fd
, &siginfo
, sizeof(siginfo
));
374 ERROR("Failed to read signal info from signal file descriptor %d", fd
);
375 return LXC_MAINLOOP_ERROR
;
378 if (ret
!= sizeof(siginfo
)) {
379 ERROR("Unexpected size for struct signalfd_siginfo");
383 /* Check whether init is running. */
385 ret
= waitid(P_PID
, hdlr
->pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
386 if (ret
== 0 && info
.si_pid
== hdlr
->pid
)
387 hdlr
->init_died
= true;
389 /* Try to figure out a reasonable exit status to report. */
390 if (hdlr
->init_died
) {
391 switch (info
.si_code
) {
393 hdlr
->exit_status
= info
.si_status
<< 8;
398 hdlr
->exit_status
= info
.si_status
<< 8 | 0x7f;
401 /* Huh? The waitid() told us it's dead *and* continued? */
402 WARN("Init %d dead and continued?", hdlr
->pid
);
403 hdlr
->exit_status
= 1;
406 ERROR("Unknown si_code: %d", info
.si_code
);
407 hdlr
->exit_status
= 1;
411 if (siginfo
.ssi_signo
== SIGHUP
) {
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 kill(hdlr
->pid
, siginfo
.ssi_signo
);
420 INFO("Forwarded signal %d to pid %d", siginfo
.ssi_signo
, hdlr
->pid
);
421 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
422 : LXC_MAINLOOP_CONTINUE
;
425 /* More robustness, protect ourself from a SIGCHLD sent
426 * by a process different from the container init.
428 if (siginfo
.ssi_pid
!= hdlr
->pid
) {
429 NOTICE("Received %d from pid %d instead of container init %d",
430 siginfo
.ssi_signo
, siginfo
.ssi_pid
, hdlr
->pid
);
431 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
432 : LXC_MAINLOOP_CONTINUE
;
435 if (siginfo
.ssi_code
== CLD_STOPPED
) {
436 INFO("Container init process was stopped");
437 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
438 : LXC_MAINLOOP_CONTINUE
;
441 if (siginfo
.ssi_code
== CLD_CONTINUED
) {
442 INFO("Container init process was continued");
443 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
444 : LXC_MAINLOOP_CONTINUE
;
447 DEBUG("Container init process %d exited", hdlr
->pid
);
449 return LXC_MAINLOOP_CLOSE
;
452 int lxc_serve_state_clients(const char *name
, struct lxc_handler
*handler
,
457 struct lxc_list
*cur
, *next
;
458 struct lxc_state_client
*client
;
459 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
462 handler
->state
= RUNNING
;
464 handler
->state
= state
;
466 TRACE("Set container state to %s", lxc_state2str(state
));
468 if (lxc_list_empty(&handler
->conf
->state_clients
)) {
469 TRACE("No state clients registered");
473 retlen
= strlcpy(msg
.name
, name
, sizeof(msg
.name
));
474 if (retlen
>= sizeof(msg
.name
))
477 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
480 if (client
->states
[state
] == 0) {
481 TRACE("State %s not registered for state client %d",
482 lxc_state2str(state
), client
->clientfd
);
486 TRACE("Sending state %s to state client %d",
487 lxc_state2str(state
), client
->clientfd
);
489 ret
= lxc_send_nointr(client
->clientfd
, &msg
, sizeof(msg
), MSG_NOSIGNAL
);
491 SYSERROR("Failed to send message to client");
493 /* kick client from list */
495 close(client
->clientfd
);
503 static int lxc_serve_state_socket_pair(const char *name
,
504 struct lxc_handler
*handler
,
509 if (!handler
->daemonize
||
510 handler
->state_socket_pair
[1] < 0 ||
514 /* Close read end of the socket pair. */
515 close(handler
->state_socket_pair
[0]);
516 handler
->state_socket_pair
[0] = -1;
519 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
520 &(int){state
}, sizeof(int));
522 SYSERROR("Failed to send state to %d", handler
->state_socket_pair
[1]);
530 if (ret
!= sizeof(int)) {
531 ERROR("Message too long : %d", handler
->state_socket_pair
[1]);
535 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
536 handler
->state_socket_pair
[1]);
538 /* Close write end of the socket pair. */
539 close(handler
->state_socket_pair
[1]);
540 handler
->state_socket_pair
[1] = -1;
545 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
550 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
552 ERROR("Failed to synchronize via anonymous pair of unix sockets");
556 ret
= lxc_serve_state_clients(name
, handler
, state
);
560 /* This function will try to connect to the legacy lxc-monitord state
561 * server and only exists for backwards compatibility.
563 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
568 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
571 bool has_console
= true;
572 struct lxc_epoll_descr descr
, descr_console
;
574 if (handler
->conf
->console
.path
&&
575 strcmp(handler
->conf
->console
.path
, "none") == 0)
578 ret
= lxc_mainloop_open(&descr
);
580 ERROR("Failed to create mainloop");
585 ret
= lxc_mainloop_open(&descr_console
);
587 ERROR("Failed to create console mainloop");
592 ret
= lxc_mainloop_add_handler(&descr
, handler
->sigfd
, signal_handler
, handler
);
594 ERROR("Failed to add signal handler for %d to mainloop", handler
->sigfd
);
595 goto out_mainloop_console
;
599 struct lxc_terminal
*console
= &handler
->conf
->console
;
601 ret
= lxc_terminal_mainloop_add(&descr
, console
);
603 ERROR("Failed to add console handlers to mainloop");
604 goto out_mainloop_console
;
607 ret
= lxc_terminal_mainloop_add(&descr_console
, console
);
609 ERROR("Failed to add console handlers to console mainloop");
610 goto out_mainloop_console
;
613 handler
->conf
->console
.descr
= &descr
;
616 ret
= lxc_cmd_mainloop_add(name
, &descr
, handler
);
618 ERROR("Failed to add command handler to mainloop");
619 goto out_mainloop_console
;
622 TRACE("Mainloop is ready");
624 ret
= lxc_mainloop(&descr
, -1);
627 if (ret
< 0 || !handler
->init_died
)
628 goto out_mainloop_console
;
631 ret
= lxc_mainloop(&descr_console
, 0);
633 out_mainloop_console
:
635 lxc_mainloop_close(&descr_console
);
636 TRACE("Closed console mainloop");
640 lxc_mainloop_close(&descr
);
641 TRACE("Closed mainloop");
644 close(handler
->sigfd
);
645 TRACE("Closed signal file descriptor %d", handler
->sigfd
);
646 handler
->sigfd
= -EBADF
;
651 void lxc_zero_handler(struct lxc_handler
*handler
)
655 memset(handler
, 0, sizeof(struct lxc_handler
));
661 for (i
= 0; i
< LXC_NS_MAX
; i
++)
662 handler
->nsfd
[i
] = -1;
664 handler
->data_sock
[0] = -1;
665 handler
->data_sock
[1] = -1;
667 handler
->state_socket_pair
[0] = -1;
668 handler
->state_socket_pair
[1] = -1;
670 handler
->sync_sock
[0] = -1;
671 handler
->sync_sock
[1] = -1;
674 void lxc_free_handler(struct lxc_handler
*handler
)
676 if (handler
->pinfd
>= 0)
677 close(handler
->pinfd
);
679 if (handler
->sigfd
>= 0)
680 close(handler
->sigfd
);
682 lxc_put_nsfds(handler
);
684 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
685 if (handler
->conf
->maincmd_fd
>= 0)
686 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
688 if (handler
->state_socket_pair
[0] >= 0)
689 close(handler
->state_socket_pair
[0]);
691 if (handler
->state_socket_pair
[1] >= 0)
692 close(handler
->state_socket_pair
[1]);
694 if (handler
->cgroup_ops
)
695 cgroup_exit(handler
->cgroup_ops
);
697 handler
->conf
= NULL
;
702 struct lxc_handler
*lxc_init_handler(const char *name
, struct lxc_conf
*conf
,
703 const char *lxcpath
, bool daemonize
)
706 struct lxc_handler
*handler
;
708 handler
= malloc(sizeof(*handler
));
712 memset(handler
, 0, sizeof(*handler
));
714 /* Note that am_guest_unpriv() checks the effective uid. We
715 * probably don't care if we are real root only if we are running
716 * as root so this should be fine.
718 handler
->am_root
= !am_guest_unpriv();
719 handler
->data_sock
[0] = handler
->data_sock
[1] = -1;
720 handler
->conf
= conf
;
721 handler
->lxcpath
= lxcpath
;
723 handler
->sigfd
= -EBADF
;
724 handler
->init_died
= false;
725 handler
->state_socket_pair
[0] = handler
->state_socket_pair
[1] = -1;
726 if (handler
->conf
->reboot
== REBOOT_NONE
)
727 lxc_list_init(&handler
->conf
->state_clients
);
729 for (i
= 0; i
< LXC_NS_MAX
; i
++)
730 handler
->nsfd
[i
] = -1;
732 handler
->name
= name
;
734 if (daemonize
&& handler
->conf
->reboot
== REBOOT_NONE
) {
735 /* Create socketpair() to synchronize on daemonized startup.
736 * When the container reboots we don't need to synchronize
737 * again currently so don't open another socketpair().
739 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
740 handler
->state_socket_pair
);
742 ERROR("Failed to create anonymous pair of unix sockets");
746 TRACE("Created anonymous pair {%d,%d} of unix sockets",
747 handler
->state_socket_pair
[0],
748 handler
->state_socket_pair
[1]);
751 if (handler
->conf
->reboot
== REBOOT_NONE
) {
752 handler
->conf
->maincmd_fd
= lxc_cmd_init(name
, lxcpath
, "command");
753 if (handler
->conf
->maincmd_fd
< 0) {
754 ERROR("Failed to set up command socket");
759 TRACE("Unix domain socket %d for command server is ready",
760 handler
->conf
->maincmd_fd
);
765 lxc_free_handler(handler
);
770 int lxc_init(const char *name
, struct lxc_handler
*handler
)
773 const char *loglevel
;
774 struct lxc_conf
*conf
= handler
->conf
;
776 handler
->monitor_pid
= lxc_raw_getpid();
779 TRACE("Initialized LSM");
781 ret
= lxc_read_seccomp_config(conf
);
783 ERROR("Failed loading seccomp policy");
784 goto out_close_maincmd_fd
;
786 TRACE("Read seccomp policy");
788 /* Begin by setting the state to STARTING. */
789 ret
= lxc_set_state(name
, handler
, STARTING
);
791 ERROR("Failed to set state to \"%s\"", lxc_state2str(STARTING
));
792 goto out_close_maincmd_fd
;
794 TRACE("Set container state to \"STARTING\"");
796 /* Start of environment variable setup for hooks. */
797 ret
= setenv("LXC_NAME", name
, 1);
799 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name
);
802 ret
= setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1);
804 SYSERROR("Failed to set environment variable: "
805 "LXC_CONFIG_FILE=%s", conf
->rcfile
);
808 if (conf
->rootfs
.mount
) {
809 ret
= setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1);
811 SYSERROR("Failed to set environment variable: "
812 "LXC_ROOTFS_MOUNT=%s", conf
->rootfs
.mount
);
815 if (conf
->rootfs
.path
) {
816 ret
= setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1);
818 SYSERROR("Failed to set environment variable: "
819 "LXC_ROOTFS_PATH=%s", conf
->rootfs
.path
);
822 if (conf
->console
.path
) {
823 ret
= setenv("LXC_CONSOLE", conf
->console
.path
, 1);
825 SYSERROR("Failed to set environment variable: "
826 "LXC_CONSOLE=%s", conf
->console
.path
);
829 if (conf
->console
.log_path
) {
830 ret
= setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1);
832 SYSERROR("Failed to set environment variable: "
833 "LXC_CONSOLE_LOGPATH=%s", conf
->console
.log_path
);
836 if (cgns_supported()) {
837 ret
= setenv("LXC_CGNS_AWARE", "1", 1);
839 SYSERROR("Failed to set environment variable "
843 loglevel
= lxc_log_priority_to_string(lxc_log_get_level());
844 ret
= setenv("LXC_LOG_LEVEL", loglevel
, 1);
846 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s",
849 if (conf
->hooks_version
== 0)
850 ret
= setenv("LXC_HOOK_VERSION", "0", 1);
852 ret
= setenv("LXC_HOOK_VERSION", "1", 1);
854 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf
->hooks_version
);
855 /* End of environment variable setup for hooks. */
857 TRACE("Set environment variables");
859 ret
= run_lxc_hooks(name
, "pre-start", conf
, NULL
);
861 ERROR("Failed to run lxc.hook.pre-start for container \"%s\"", name
);
864 TRACE("Ran pre-start hooks");
866 /* The signal fd has to be created before forking otherwise if the child
867 * process exits before we setup the signal fd, the event will be lost
868 * and the command will be stuck.
870 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
871 if (handler
->sigfd
< 0) {
872 ERROR("Failed to setup SIGCHLD fd handler.");
875 TRACE("Set up signal fd");
877 /* Do this after setting up signals since it might unblock SIGWINCH. */
878 ret
= lxc_terminal_setup(conf
);
880 ERROR("Failed to create console");
881 goto out_restore_sigmask
;
883 TRACE("Created console");
885 ret
= lxc_terminal_map_ids(conf
, &conf
->console
);
887 ERROR("Failed to chown console");
888 goto out_delete_terminal
;
890 TRACE("Chowned console");
892 handler
->cgroup_ops
= cgroup_init(handler
->conf
);
893 if (!handler
->cgroup_ops
) {
894 ERROR("Failed to initialize cgroup driver");
895 goto out_delete_terminal
;
897 TRACE("Initialized cgroup driver");
899 ret
= lsm_process_prepare(conf
, handler
->lxcpath
);
901 ERROR("Failed to initialize LSM");
902 goto out_destroy_cgroups
;
904 TRACE("Initialized LSM");
906 INFO("Container \"%s\" is initialized", name
);
910 handler
->cgroup_ops
->payload_destroy(handler
->cgroup_ops
, handler
);
911 handler
->cgroup_ops
->monitor_destroy(handler
->cgroup_ops
, handler
);
914 lxc_terminal_delete(&handler
->conf
->console
);
917 (void)pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
920 lxc_delete_tty(&conf
->ttys
);
923 (void)lxc_set_state(name
, handler
, ABORTING
);
925 out_close_maincmd_fd
:
926 lxc_abstract_unix_close(conf
->maincmd_fd
);
927 conf
->maincmd_fd
= -1;
931 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
935 struct lxc_list
*cur
, *next
;
936 char *namespaces
[LXC_NS_MAX
+ 1];
937 size_t namespace_count
= 0;
938 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
940 /* The STOPPING state is there for future cleanup code which can take
943 lxc_set_state(name
, handler
, STOPPING
);
945 self
= lxc_raw_getpid();
946 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
947 if (handler
->nsfd
[i
] < 0)
950 if (handler
->conf
->hooks_version
== 0)
951 ret
= asprintf(&namespaces
[namespace_count
],
952 "%s:/proc/%d/fd/%d", ns_info
[i
].proc_name
,
953 self
, handler
->nsfd
[i
]);
955 ret
= asprintf(&namespaces
[namespace_count
],
956 "/proc/%d/fd/%d", self
, handler
->nsfd
[i
]);
958 SYSERROR("Failed to allocate memory");
962 if (handler
->conf
->hooks_version
== 0) {
967 ret
= setenv(ns_info
[i
].env_name
, namespaces
[namespace_count
], 1);
969 SYSERROR("Failed to set environment variable %s=%s",
970 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
972 TRACE("Set environment variable %s=%s",
973 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
977 namespaces
[namespace_count
] = NULL
;
979 if (handler
->conf
->reboot
> REBOOT_NONE
) {
980 ret
= setenv("LXC_TARGET", "reboot", 1);
982 SYSERROR("Failed to set environment variable: "
983 "LXC_TARGET=reboot");
986 if (handler
->conf
->reboot
== REBOOT_NONE
) {
987 ret
= setenv("LXC_TARGET", "stop", 1);
989 SYSERROR("Failed to set environment variable: "
993 if (handler
->conf
->hooks_version
== 0)
994 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, namespaces
);
996 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, NULL
);
998 ERROR("Failed to run \"lxc.hook.stop\" hook");
1000 while (namespace_count
--)
1001 free(namespaces
[namespace_count
]);
1003 lsm_process_cleanup(handler
->conf
, handler
->lxcpath
);
1005 cgroup_ops
->payload_destroy(cgroup_ops
, handler
);
1006 cgroup_ops
->monitor_destroy(cgroup_ops
, handler
);
1008 if (handler
->conf
->reboot
== REBOOT_NONE
) {
1009 /* For all new state clients simply close the command socket.
1010 * This will inform all state clients that the container is
1011 * STOPPED and also prevents a race between a open()/close() on
1012 * the command socket causing a new process to get ECONNREFUSED
1013 * because we haven't yet closed the command socket.
1015 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
1016 handler
->conf
->maincmd_fd
= -1;
1017 TRACE("Closed command socket");
1019 /* This function will try to connect to the legacy lxc-monitord
1020 * state server and only exists for backwards compatibility.
1022 lxc_monitor_send_state(name
, STOPPED
, handler
->lxcpath
);
1024 /* The command socket is closed so no one can acces the command
1025 * socket anymore so there's no need to lock it.
1027 handler
->state
= STOPPED
;
1028 TRACE("Set container state to \"STOPPED\"");
1030 lxc_set_state(name
, handler
, STOPPED
);
1033 ret
= run_lxc_hooks(name
, "post-stop", handler
->conf
, NULL
);
1035 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name
);
1036 if (handler
->conf
->reboot
> REBOOT_NONE
) {
1037 WARN("Container will be stopped instead of rebooted");
1038 handler
->conf
->reboot
= REBOOT_NONE
;
1040 ret
= setenv("LXC_TARGET", "stop", 1);
1042 WARN("Failed to set environment variable: "
1047 /* Reset mask set by setup_signal_fd. */
1048 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1050 SYSWARN("Failed to restore signal mask");
1052 lxc_terminal_delete(&handler
->conf
->console
);
1053 lxc_delete_tty(&handler
->conf
->ttys
);
1055 /* The command socket is now closed, no more state clients can register
1056 * themselves from now on. So free the list of state clients.
1058 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
1059 struct lxc_state_client
*client
= cur
->elem
;
1061 /* Keep state clients that want to be notified about reboots. */
1062 if ((handler
->conf
->reboot
> REBOOT_NONE
) &&
1063 (client
->states
[RUNNING
] == 2))
1066 /* close state client socket */
1068 close(client
->clientfd
);
1073 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= REBOOT_REQ
)
1074 lxc_destroy_container_on_signal(handler
, name
);
1076 lxc_free_handler(handler
);
1079 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
1083 lxc_set_state(name
, handler
, ABORTING
);
1085 if (handler
->pid
> 0) {
1086 ret
= kill(handler
->pid
, SIGKILL
);
1088 SYSERROR("Failed to send SIGKILL to %d", handler
->pid
);
1091 while ((ret
= waitpid(-1, &status
, 0)) > 0) {
1096 static int do_start(void *data
)
1099 char path
[PATH_MAX
];
1102 struct lxc_list
*iterator
;
1105 int devnull_fd
= -1;
1106 struct lxc_handler
*handler
= data
;
1108 lxc_sync_fini_parent(handler
);
1110 /* This prctl must be before the synchro, so if the parent dies before
1111 * we set the parent death signal, we will detect its death with the
1112 * synchro right after, otherwise we have a window where the parent can
1113 * exit before we set the pdeath signal leading to a unsupervized
1116 ret
= lxc_set_death_signal(SIGKILL
, 0);
1118 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1119 goto out_warn_father
;
1122 ret
= lxc_ambient_caps_up();
1124 ERROR("Failed to raise ambient capabilities");
1125 goto out_warn_father
;
1128 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1130 SYSERROR("Failed to set signal mask");
1131 goto out_warn_father
;
1134 /* Don't leak the pinfd to the container. */
1135 if (handler
->pinfd
>= 0)
1136 close(handler
->pinfd
);
1138 ret
= lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
);
1140 goto out_warn_father
;
1142 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1143 * https://github.com/lxc/lxd/issues/1978.
1145 if ((handler
->ns_clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
1146 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
1147 ret
= unshare(CLONE_NEWNET
);
1149 SYSERROR("Failed to unshare CLONE_NEWNET");
1150 goto out_warn_father
;
1152 INFO("Unshared CLONE_NEWNET");
1155 /* Tell the parent task it can begin to configure the container and wait
1158 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
);
1162 ret
= lxc_network_recv_veth_names_from_parent(handler
);
1164 ERROR("Failed to receive veth names from parent");
1165 goto out_warn_father
;
1168 /* If we are in a new user namespace, become root there to have
1169 * privilege over our namespace.
1171 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1172 if (!handler
->conf
->root_nsuid_map
)
1173 nsuid
= handler
->conf
->init_uid
;
1175 if (!handler
->conf
->root_nsgid_map
)
1176 nsgid
= handler
->conf
->init_gid
;
1178 if (!lxc_switch_uid_gid(nsuid
, nsgid
))
1179 goto out_warn_father
;
1181 /* Drop groups only after we switched to a valid gid in the new
1184 if (!lxc_setgroups(0, NULL
) &&
1185 (handler
->am_root
|| errno
!= EPERM
))
1186 goto out_warn_father
;
1188 ret
= prctl(PR_SET_DUMPABLE
, prctl_arg(1), prctl_arg(0),
1189 prctl_arg(0), prctl_arg(0));
1191 goto out_warn_father
;
1193 /* set{g,u}id() clears deathsignal */
1194 ret
= lxc_set_death_signal(SIGKILL
, 0);
1196 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1197 goto out_warn_father
;
1201 ret
= access(handler
->lxcpath
, X_OK
);
1203 print_top_failing_dir(handler
->lxcpath
);
1204 goto out_warn_father
;
1207 ret
= snprintf(path
, sizeof(path
), "%s/dev/null",
1208 handler
->conf
->rootfs
.mount
);
1209 if (ret
< 0 || ret
>= sizeof(path
))
1210 goto out_warn_father
;
1212 /* In order to checkpoint restore, we need to have everything in the
1213 * same mount namespace. However, some containers may not have a
1214 * reasonable /dev (in particular, they may not have /dev/null), so we
1215 * can't set init's std fds to /dev/null by opening it from inside the
1218 * If that's the case, fall back to using the host's /dev/null. This
1219 * means that migration won't work, but at least we won't spew output
1220 * where it isn't wanted.
1222 if (handler
->daemonize
&& !handler
->conf
->autodev
) {
1223 ret
= access(path
, F_OK
);
1225 devnull_fd
= open_devnull();
1228 goto out_warn_father
;
1229 WARN("Using /dev/null from the host for container "
1230 "init's standard file descriptors. Migration will "
1235 /* Ask father to setup cgroups and wait for him to finish. */
1236 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
);
1240 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1241 * earlier we end up with a wrong view of /proc/self/cgroup. For
1242 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1243 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1244 * /proc/self/cgroup would show us:
1248 * whereas it should actually show
1252 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1253 ret
= unshare(CLONE_NEWCGROUP
);
1255 if (errno
!= EINVAL
) {
1256 SYSERROR("Failed to unshare CLONE_NEWCGROUP");
1257 goto out_warn_father
;
1260 handler
->ns_clone_flags
&= ~CLONE_NEWCGROUP
;
1261 SYSINFO("Kernel does not support CLONE_NEWCGROUP");
1263 INFO("Unshared CLONE_NEWCGROUP");
1267 /* Add the requested environment variables to the current environment to
1268 * allow them to be used by the various hooks, such as the start hook
1271 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1272 ret
= putenv((char *)iterator
->elem
);
1274 SYSERROR("Failed to set environment variable: %s",
1275 (char *)iterator
->elem
);
1276 goto out_warn_father
;
1280 /* Setup the container, ip, names, utsname, ... */
1281 ret
= lxc_setup(handler
);
1282 close(handler
->data_sock
[1]);
1283 close(handler
->data_sock
[0]);
1285 ERROR("Failed to setup container \"%s\"", handler
->name
);
1286 goto out_warn_father
;
1289 /* Set the label to change to when we exec(2) the container's init. */
1290 ret
= lsm_process_label_set(NULL
, handler
->conf
, true);
1292 goto out_warn_father
;
1294 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1295 * before we aren't allowed anymore.
1297 if (handler
->conf
->no_new_privs
) {
1298 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
1299 prctl_arg(0), prctl_arg(0));
1301 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block "
1302 "execve() gainable privileges");
1303 goto out_warn_father
;
1305 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable "
1309 /* Some init's such as busybox will set sane tty settings on stdin,
1310 * stdout, stderr which it thinks is the console. We already set them
1311 * the way we wanted on the real terminal, and we want init to do its
1312 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
1313 * make sure that that pty is stdin,stdout,stderr.
1315 if (handler
->conf
->console
.slave
>= 0) {
1316 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
1317 ret
= set_stdfds(handler
->conf
->console
.slave
);
1319 ret
= lxc_terminal_set_stdfds(handler
->conf
->console
.slave
);
1321 ERROR("Failed to redirect std{in,out,err} to pty file "
1322 "descriptor %d", handler
->conf
->console
.slave
);
1323 goto out_warn_father
;
1327 /* If we mounted a temporary proc, then unmount it now. */
1328 tmp_proc_unmount(handler
->conf
);
1330 ret
= lxc_seccomp_load(handler
->conf
);
1332 goto out_warn_father
;
1334 ret
= run_lxc_hooks(handler
->name
, "start", handler
->conf
, NULL
);
1336 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1338 goto out_warn_father
;
1341 close(handler
->sigfd
);
1343 if (handler
->conf
->console
.slave
< 0 && handler
->daemonize
) {
1344 if (devnull_fd
< 0) {
1345 devnull_fd
= open_devnull();
1347 goto out_warn_father
;
1350 ret
= set_stdfds(devnull_fd
);
1352 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
1353 goto out_warn_father
;
1357 if (devnull_fd
>= 0) {
1364 if (handler
->conf
->init_cwd
) {
1365 ret
= chdir(handler
->conf
->init_cwd
);
1367 SYSERROR("Could not change directory to \"%s\"",
1368 handler
->conf
->init_cwd
);
1369 goto out_warn_father
;
1373 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
);
1375 goto out_warn_father
;
1377 /* Reset the environment variables the user requested in a clear
1381 /* Don't error out though. */
1383 SYSERROR("Failed to clear environment.");
1385 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1386 ret
= putenv((char *)iterator
->elem
);
1388 SYSERROR("Failed to set environment variable: %s",
1389 (char *)iterator
->elem
);
1390 goto out_warn_father
;
1394 ret
= putenv("container=lxc");
1396 SYSERROR("Failed to set environment variable: container=lxc");
1397 goto out_warn_father
;
1400 if (handler
->conf
->ttys
.tty_names
) {
1401 ret
= putenv(handler
->conf
->ttys
.tty_names
);
1403 SYSERROR("Failed to set environment variable for container ptys");
1404 goto out_warn_father
;
1408 /* The container has been setup. We can now switch to an unprivileged
1411 new_uid
= handler
->conf
->init_uid
;
1412 new_gid
= handler
->conf
->init_gid
;
1414 /* Avoid unnecessary syscalls. */
1415 if (new_uid
== nsuid
)
1416 new_uid
= LXC_INVALID_UID
;
1418 if (new_gid
== nsgid
)
1419 new_gid
= LXC_INVALID_GID
;
1421 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
1422 goto out_warn_father
;
1424 /* If we are in a new user namespace we already dropped all groups when
1425 * we switched to root in the new user namespace further above. Only
1426 * drop groups if we can, so ensure that we have necessary privilege.
1428 if (lxc_list_empty(&handler
->conf
->id_map
))
1430 if (lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
))
1432 if (!lxc_setgroups(0, NULL
))
1433 goto out_warn_father
;
1435 ret
= lxc_ambient_caps_down();
1437 ERROR("Failed to clear ambient capabilities");
1438 goto out_warn_father
;
1441 if (handler
->conf
->monitor_signal_pdeath
!= SIGKILL
) {
1442 ret
= lxc_set_death_signal(handler
->conf
->monitor_signal_pdeath
, 0);
1444 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1445 handler
->conf
->monitor_signal_pdeath
);
1446 goto out_warn_father
;
1450 /* After this call, we are in error because this ops should not return
1453 handler
->ops
->start(handler
, handler
->data
);
1456 /* We want the parent to know something went wrong, so we return a
1457 * special error code.
1459 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1462 if (devnull_fd
>= 0)
1468 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1471 struct lxc_terminal_info
*tty
;
1473 int sock
= handler
->data_sock
[1];
1474 struct lxc_conf
*conf
= handler
->conf
;
1475 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1477 if (!conf
->ttys
.max
)
1480 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
1484 for (i
= 0; i
< conf
->ttys
.max
; i
++) {
1487 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1491 tty
= &ttys
->tty
[i
];
1493 tty
->master
= ttyfds
[0];
1494 tty
->slave
= ttyfds
[1];
1495 TRACE("Received pty with master fd %d and slave fd %d from "
1496 "parent", tty
->master
, tty
->slave
);
1500 SYSERROR("Failed to receive %zu ttys from child", ttys
->max
);
1502 TRACE("Received %zu ttys from child", ttys
->max
);
1507 int resolve_clone_flags(struct lxc_handler
*handler
)
1510 struct lxc_conf
*conf
= handler
->conf
;
1512 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1513 if (conf
->ns_keep
> 0) {
1514 if ((conf
->ns_keep
& ns_info
[i
].clone_flag
) == 0)
1515 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1516 } else if (conf
->ns_clone
> 0) {
1517 if ((conf
->ns_clone
& ns_info
[i
].clone_flag
) > 0)
1518 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1520 if (i
== LXC_NS_USER
&& lxc_list_empty(&handler
->conf
->id_map
))
1523 if (i
== LXC_NS_NET
&& lxc_requests_empty_network(handler
))
1526 if (i
== LXC_NS_CGROUP
&& !cgns_supported())
1529 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1532 if (!conf
->ns_share
[i
])
1535 handler
->ns_clone_flags
&= ~ns_info
[i
].clone_flag
;
1536 TRACE("Sharing %s namespace", ns_info
[i
].proc_name
);
1542 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1543 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1544 * But since the memory between parent and child is shared on CLONE_VM this
1545 * would invalidate the getpid() cache that glibc used to maintain and so
1546 * getpid() in the child would return the parent's pid. This is all fixed in
1547 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1548 * not reset anymore.
1549 * However, if for whatever reason you - dear committer - somehow need to get the
1550 * pid of the dummy intermediate process for do_share_ns() you need to call
1551 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1554 static inline int do_share_ns(void *arg
)
1557 struct lxc_handler
*handler
= arg
;
1559 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1560 if (handler
->nsfd
[i
] < 0)
1563 ret
= setns(handler
->nsfd
[i
], 0);
1566 * Note that joining a user and/or mount namespace
1567 * requires the process is not multithreaded otherwise
1568 * setns() will fail here.
1570 SYSERROR("Failed to inherit %s namespace",
1571 ns_info
[i
].proc_name
);
1575 DEBUG("Inherited %s namespace", ns_info
[i
].proc_name
);
1578 flags
= handler
->ns_on_clone_flags
;
1579 flags
|= CLONE_PARENT
;
1580 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, flags
);
1581 if (handler
->pid
< 0)
1587 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1588 * exec()s the requested container binary.
1589 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1590 * right here should be double checked if they'd pose a security risk. (For
1591 * example, any {u}mount() operations performed here will be reflected on the
1594 static int lxc_spawn(struct lxc_handler
*handler
)
1598 bool wants_to_map_ids
;
1599 struct lxc_list
*id_map
;
1600 const char *name
= handler
->name
;
1601 const char *lxcpath
= handler
->lxcpath
;
1602 bool share_ns
= false;
1603 struct lxc_conf
*conf
= handler
->conf
;
1604 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
1606 id_map
= &conf
->id_map
;
1607 wants_to_map_ids
= !lxc_list_empty(id_map
);
1609 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1610 if (!conf
->ns_share
[i
])
1613 handler
->nsfd
[i
] = lxc_inherit_namespace(conf
->ns_share
[i
], lxcpath
, ns_info
[i
].proc_name
);
1614 if (handler
->nsfd
[i
] < 0)
1620 ret
= lxc_sync_init(handler
);
1624 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1625 handler
->data_sock
);
1629 ret
= resolve_clone_flags(handler
);
1633 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1634 if (!lxc_list_empty(&conf
->network
)) {
1636 /* Find gateway addresses from the link device, which is
1637 * no longer accessible inside the container. Do this
1638 * before creating network interfaces, since goto
1639 * out_delete_net does not work before lxc_clone.
1641 ret
= lxc_find_gateway_addresses(handler
);
1643 ERROR("Failed to find gateway addresses");
1647 /* That should be done before the clone because we will
1648 * fill the netdev index and use them in the child.
1650 ret
= lxc_create_network_priv(handler
);
1652 ERROR("Failed to create the network");
1653 goto out_delete_net
;
1658 if (!cgroup_ops
->payload_create(cgroup_ops
, handler
)) {
1659 ERROR("Failed creating cgroups");
1660 goto out_delete_net
;
1663 /* If the rootfs is not a blockdev, prevent the container from marking
1665 * If the container is unprivileged then skip rootfs pinning.
1667 if (!wants_to_map_ids
) {
1668 handler
->pinfd
= pin_rootfs(conf
->rootfs
.path
);
1669 if (handler
->pinfd
== -1)
1670 INFO("Failed to pin the rootfs for container \"%s\"", handler
->name
);
1673 /* Create a process in a new set of namespaces. */
1674 handler
->ns_on_clone_flags
= handler
->ns_clone_flags
;
1675 if (handler
->ns_clone_flags
& CLONE_NEWUSER
) {
1676 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1677 * clone a new user namespace first and only later unshare our
1678 * network namespace to ensure that network devices ownership is
1681 handler
->ns_on_clone_flags
&= ~CLONE_NEWNET
;
1683 /* The cgroup namespace gets unshare()ed not clone()ed. */
1684 handler
->ns_on_clone_flags
&= ~CLONE_NEWCGROUP
;
1689 attacher_pid
= lxc_clone(do_share_ns
, handler
,
1690 CLONE_VFORK
| CLONE_VM
| CLONE_FILES
);
1691 if (attacher_pid
< 0) {
1692 SYSERROR(LXC_CLONE_ERROR
);
1693 goto out_delete_net
;
1696 ret
= wait_for_pid(attacher_pid
);
1698 SYSERROR("Intermediate process failed");
1699 goto out_delete_net
;
1702 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
,
1703 handler
->ns_on_clone_flags
);
1705 if (handler
->pid
< 0) {
1706 SYSERROR(LXC_CLONE_ERROR
);
1707 goto out_delete_net
;
1709 TRACE("Cloned child process %d", handler
->pid
);
1711 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1712 if (handler
->ns_on_clone_flags
& ns_info
[i
].clone_flag
)
1713 INFO("Cloned %s", ns_info
[i
].flag_name
);
1715 if (!lxc_try_preserve_namespaces(handler
, handler
->ns_on_clone_flags
, handler
->pid
)) {
1716 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1717 goto out_delete_net
;
1720 lxc_sync_fini_child(handler
);
1722 /* Map the container uids. The container became an invalid userid the
1723 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1724 * anything immediately, but allows the container to setuid(0) (0 being
1725 * mapped to something else on the host.) later to become a valid uid
1728 if (wants_to_map_ids
) {
1729 if (!handler
->conf
->ns_share
[LXC_NS_USER
] &&
1730 (handler
->conf
->ns_keep
& CLONE_NEWUSER
) == 0) {
1731 ret
= lxc_map_ids(id_map
, handler
->pid
);
1733 ERROR("Failed to set up id mapping.");
1734 goto out_delete_net
;
1739 ret
= lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
);
1741 goto out_delete_net
;
1743 ret
= lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
);
1745 goto out_delete_net
;
1747 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
->conf
, false)) {
1748 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1749 goto out_delete_net
;
1752 if (!cgroup_ops
->payload_enter(cgroup_ops
, handler
->pid
))
1753 goto out_delete_net
;
1755 if (!cgroup_ops
->chown(cgroup_ops
, handler
->conf
))
1756 goto out_delete_net
;
1758 /* Now we're ready to preserve the network namespace */
1759 ret
= lxc_try_preserve_ns(handler
->pid
, "net");
1761 if (ret
!= -EOPNOTSUPP
) {
1762 SYSERROR("Failed to preserve net namespace");
1763 goto out_delete_net
;
1766 handler
->nsfd
[LXC_NS_NET
] = ret
;
1767 DEBUG("Preserved net namespace via fd %d", ret
);
1769 ret
= lxc_netns_set_nsid(handler
->nsfd
[LXC_NS_NET
]);
1771 SYSWARN("Failed to allocate new network namespace id");
1773 TRACE("Allocated new network namespace id");
1776 /* Create the network configuration. */
1777 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1778 ret
= lxc_network_move_created_netdev_priv(handler
->lxcpath
,
1783 ERROR("Failed to create the configured network");
1784 goto out_delete_net
;
1787 ret
= lxc_create_network_unpriv(handler
->lxcpath
, handler
->name
,
1788 &conf
->network
, handler
->pid
, conf
->hooks_version
);
1790 ERROR("Failed to create the configured network");
1791 goto out_delete_net
;
1795 ret
= lxc_network_send_veth_names_to_child(handler
);
1797 ERROR("Failed to send veth names to child");
1798 goto out_delete_net
;
1801 if (!lxc_list_empty(&conf
->procs
)) {
1802 ret
= setup_proc_filesystem(&conf
->procs
, handler
->pid
);
1804 goto out_delete_net
;
1807 /* Tell the child to continue its initialization. We'll get
1808 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1810 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
);
1812 goto out_delete_net
;
1814 if (!lxc_list_empty(&conf
->limits
)) {
1815 ret
= setup_resource_limits(&conf
->limits
, handler
->pid
);
1817 ERROR("Failed to setup resource limits");
1818 goto out_delete_net
;
1822 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
);
1824 goto out_delete_net
;
1826 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
->conf
, true)) {
1827 ERROR("Failed to setup legacy device cgroup controller limits");
1828 goto out_delete_net
;
1830 TRACE("Set up legacy device cgroup controller limits");
1832 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1833 /* Now we're ready to preserve the cgroup namespace */
1834 ret
= lxc_try_preserve_ns(handler
->pid
, "cgroup");
1836 if (ret
!= -EOPNOTSUPP
) {
1837 SYSERROR("Failed to preserve cgroup namespace");
1838 goto out_delete_net
;
1841 handler
->nsfd
[LXC_NS_CGROUP
] = ret
;
1842 DEBUG("Preserved cgroup namespace via fd %d", ret
);
1846 ret
= snprintf(pidstr
, 20, "%d", handler
->pid
);
1847 if (ret
< 0 || ret
>= 20)
1848 goto out_delete_net
;
1850 ret
= setenv("LXC_PID", pidstr
, 1);
1852 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr
);
1854 /* Run any host-side start hooks */
1855 ret
= run_lxc_hooks(name
, "start-host", conf
, NULL
);
1857 ERROR("Failed to run lxc.hook.start-host");
1858 goto out_delete_net
;
1861 /* Tell the child to complete its initialization and wait for it to exec
1862 * or return an error. (The child will never return
1863 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1864 * lxc_sync_barrier_child to return success, or return a different
1865 * value, causing us to error out).
1867 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_READY_START
);
1869 goto out_delete_net
;
1871 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
1873 ERROR("Failed to receive names and ifindices for network "
1874 "devices from child");
1875 goto out_delete_net
;
1878 /* Now all networks are created, network devices are moved into place,
1879 * and the correct names and ifindices in the respective namespaces have
1880 * been recorded. The corresponding structs have now all been filled. So
1881 * log them for debugging purposes.
1883 lxc_log_configured_netdevs(conf
);
1885 /* Read tty fds allocated by child. */
1886 ret
= lxc_recv_ttys_from_child(handler
);
1888 ERROR("Failed to receive tty info from child process");
1889 goto out_delete_net
;
1892 ret
= handler
->ops
->post_start(handler
, handler
->data
);
1896 ret
= lxc_set_state(name
, handler
, RUNNING
);
1898 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING
));
1902 lxc_sync_fini(handler
);
1907 if (handler
->ns_clone_flags
& CLONE_NEWNET
)
1908 lxc_delete_network(handler
);
1911 lxc_abort(name
, handler
);
1914 lxc_sync_fini(handler
);
1915 if (handler
->pinfd
>= 0) {
1916 close(handler
->pinfd
);
1917 handler
->pinfd
= -1;
1923 int __lxc_start(const char *name
, struct lxc_handler
*handler
,
1924 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1925 bool daemonize
, int *error_num
)
1928 struct lxc_conf
*conf
= handler
->conf
;
1929 struct cgroup_ops
*cgroup_ops
;
1931 ret
= lxc_init(name
, handler
);
1933 ERROR("Failed to initialize container \"%s\"", name
);
1937 handler
->data
= data
;
1938 handler
->daemonize
= daemonize
;
1939 cgroup_ops
= handler
->cgroup_ops
;
1941 if (!attach_block_device(handler
->conf
)) {
1942 ERROR("Failed to attach block device");
1943 goto out_fini_nonet
;
1946 if (!cgroup_ops
->monitor_create(cgroup_ops
, handler
)) {
1947 ERROR("Failed to create monitor cgroup");
1948 goto out_fini_nonet
;
1951 if (!cgroup_ops
->monitor_enter(cgroup_ops
, handler
->monitor_pid
)) {
1952 ERROR("Failed to enter monitor cgroup");
1953 goto out_fini_nonet
;
1956 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1957 /* If the backing store is a device, mount it here and now. */
1958 if (rootfs_is_blockdev(conf
)) {
1959 ret
= unshare(CLONE_NEWNS
);
1961 ERROR("Failed to unshare CLONE_NEWNS");
1962 goto out_fini_nonet
;
1964 INFO("Unshared CLONE_NEWNS");
1966 remount_all_slave();
1967 ret
= lxc_setup_rootfs_prepare_root(conf
, name
, lxcpath
);
1969 ERROR("Error setting up rootfs mount as root before spawn");
1970 goto out_fini_nonet
;
1972 INFO("Set up container rootfs as host root");
1976 ret
= lxc_spawn(handler
);
1978 ERROR("Failed to spawn container \"%s\"", name
);
1979 goto out_detach_blockdev
;
1981 /* close parent side of data socket */
1982 close(handler
->data_sock
[0]);
1983 handler
->data_sock
[0] = -1;
1984 close(handler
->data_sock
[1]);
1985 handler
->data_sock
[1] = -1;
1987 handler
->conf
->reboot
= REBOOT_NONE
;
1989 ret
= lxc_poll(name
, handler
);
1991 ERROR("LXC mainloop exited with error: %d", ret
);
1995 if (!handler
->init_died
&& handler
->pid
> 0) {
1996 ERROR("Child process is not killed");
2000 status
= lxc_wait_for_pid_status(handler
->pid
);
2002 SYSERROR("Failed to retrieve status for %d", handler
->pid
);
2004 /* If the child process exited but was not signaled, it didn't call
2005 * reboot. This should mean it was an lxc-execute which simply exited.
2006 * In any case, treat it as a 'halt'.
2008 if (WIFSIGNALED(status
)) {
2009 switch(WTERMSIG(status
)) {
2010 case SIGINT
: /* halt */
2011 DEBUG("Container \"%s\" is halting", name
);
2013 case SIGHUP
: /* reboot */
2014 DEBUG("Container \"%s\" is rebooting", name
);
2015 handler
->conf
->reboot
= REBOOT_REQ
;
2017 case SIGSYS
: /* seccomp */
2018 DEBUG("Container \"%s\" violated its seccomp policy", name
);
2021 DEBUG("Unknown exit status for container \"%s\" init %d", name
, WTERMSIG(status
));
2026 ret
= lxc_restore_phys_nics_to_netns(handler
);
2028 ERROR("Failed to move physical network devices back to parent "
2029 "network namespace");
2031 if (handler
->pinfd
>= 0) {
2032 close(handler
->pinfd
);
2033 handler
->pinfd
= -1;
2036 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
2037 lxc_error_set_and_log(handler
->pid
, status
);
2039 *error_num
= handler
->exit_status
;
2042 lxc_delete_network(handler
);
2044 out_detach_blockdev
:
2045 detach_block_device(handler
->conf
);
2048 lxc_fini(name
, handler
);
2052 lxc_abort(name
, handler
);
2060 static int start(struct lxc_handler
*handler
, void* data
)
2062 struct start_args
*arg
= data
;
2064 NOTICE("Exec'ing \"%s\"", arg
->argv
[0]);
2066 execvp(arg
->argv
[0], arg
->argv
);
2067 SYSERROR("Failed to exec \"%s\"", arg
->argv
[0]);
2071 static int post_start(struct lxc_handler
*handler
, void* data
)
2073 struct start_args
*arg
= data
;
2075 NOTICE("Started \"%s\" with pid \"%d\"", arg
->argv
[0], handler
->pid
);
2079 static struct lxc_operations start_ops
= {
2081 .post_start
= post_start
2084 int lxc_start(const char *name
, char *const argv
[], struct lxc_handler
*handler
,
2085 const char *lxcpath
, bool daemonize
, int *error_num
)
2087 struct start_args start_arg
= {
2091 TRACE("Doing lxc_start");
2092 return __lxc_start(name
, handler
, &start_ops
, &start_arg
, lxcpath
, daemonize
, error_num
);
2095 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
2098 char destroy
[PATH_MAX
];
2099 struct lxc_container
*c
;
2103 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
2104 bret
= do_destroy_container(handler
);
2106 ERROR("Error destroying rootfs for container \"%s\"", name
);
2110 INFO("Destroyed rootfs for container \"%s\"", name
);
2112 ret
= snprintf(destroy
, PATH_MAX
, "%s/%s", handler
->lxcpath
, name
);
2113 if (ret
< 0 || ret
>= PATH_MAX
) {
2114 ERROR("Error destroying directory for container \"%s\"", name
);
2118 c
= lxc_container_new(name
, handler
->lxcpath
);
2120 if (container_disk_lock(c
)) {
2121 INFO("Could not update lxc_snapshots file");
2122 lxc_container_put(c
);
2124 mod_all_rdeps(c
, false);
2125 container_disk_unlock(c
);
2126 lxc_container_put(c
);
2130 if (!handler
->am_root
)
2131 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
2132 destroy
, "lxc_rmdir_onedev_wrapper");
2134 ret
= lxc_rmdir_onedev(destroy
, NULL
);
2137 ERROR("Error destroying directory for container \"%s\"", name
);
2140 INFO("Destroyed directory for container \"%s\"", name
);
2143 static int lxc_rmdir_onedev_wrapper(void *data
)
2145 char *arg
= (char *) data
;
2146 return lxc_rmdir_onedev(arg
, NULL
);
2149 static bool do_destroy_container(struct lxc_handler
*handler
)
2153 if (!handler
->am_root
) {
2154 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
2155 handler
->conf
, "storage_destroy_wrapper");
2162 return storage_destroy(handler
->conf
);