]>
git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/start.c
0629e90c4271a7eea0c0b1b1a08b7538f3bde1ec
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
42 #include <sys/mount.h>
43 #include <sys/param.h>
44 #include <sys/prctl.h>
45 #include <sys/socket.h>
47 #include <sys/syscall.h>
48 #include <sys/types.h>
53 #include <sys/capability.h>
60 #include "commands_utils.h"
62 #include "confile_utils.h"
64 #include "file_utils.h"
68 #include "lxccontainer.h"
70 #include "lxcseccomp.h"
74 #include "namespace.h"
77 #include "storage/storage.h"
78 #include "storage/storage_utils.h"
84 #include "include/strlcpy.h"
87 lxc_log_define(start
, lxc
);
89 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
90 static bool do_destroy_container(struct lxc_handler
*handler
);
91 static int lxc_rmdir_onedev_wrapper(void *data
);
92 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
95 static void print_top_failing_dir(const char *path
)
99 char *copy
, *e
, *p
, saved
;
102 copy
= alloca(len
+ 1);
103 (void)strlcpy(copy
, path
, len
+ 1);
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 handler
->nsfd
[i
] = -EBADF
;
182 /* Do not fail to start container on kernels that do
183 * not support interacting with namespaces through
186 if (fd
== -EOPNOTSUPP
)
189 lxc_put_nsfds(handler
);
193 handler
->nsfd
[i
] = fd
;
194 DEBUG("Preserved %s namespace via fd %d", ns_info
[i
].proc_name
,
201 static inline bool match_stdfds(int fd
)
203 return (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
);
206 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
207 int *fds_to_ignore
, size_t len_fds
)
212 struct dirent
*direntp
;
214 if (conf
&& conf
->close_all_fds
)
218 dir
= opendir("/proc/self/fd");
220 SYSWARN("Failed to open directory");
226 while ((direntp
= readdir(dir
))) {
228 struct lxc_list
*cur
;
229 bool matched
= false;
231 if (strcmp(direntp
->d_name
, ".") == 0)
234 if (strcmp(direntp
->d_name
, "..") == 0)
237 ret
= lxc_safe_int(direntp
->d_name
, &fd
);
239 INFO("Could not parse file descriptor for \"%s\"", direntp
->d_name
);
243 for (i
= 0; i
< len_fds
; i
++)
244 if (fds_to_ignore
[i
] == fd
)
247 if (fd
== fddir
|| fd
== lxc_log_fd
||
248 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
251 /* Keep state clients that wait on reboots. */
253 lxc_list_for_each(cur
, &conf
->state_clients
) {
254 struct lxc_state_client
*client
= cur
->elem
;
256 if (client
->clientfd
!= fd
)
267 if (current_config
&& fd
== current_config
->logfd
)
270 if (match_stdfds(fd
))
276 INFO("Closed inherited fd %d", fd
);
279 WARN("Inherited fd %d", fd
);
282 /* Only enable syslog at this point to avoid the above logging function
283 * to open a new fd and make the check_inherited function enter an
286 lxc_log_enable_syslog();
288 closedir(dir
); /* cannot fail */
292 static int setup_signal_fd(sigset_t
*oldmask
)
297 const int signals
[] = {SIGBUS
, SIGILL
, SIGSEGV
, SIGWINCH
};
299 /* Block everything except serious error signals. */
300 ret
= sigfillset(&mask
);
304 for (sig
= 0; sig
< (sizeof(signals
) / sizeof(signals
[0])); sig
++) {
305 ret
= sigdelset(&mask
, signals
[sig
]);
310 ret
= pthread_sigmask(SIG_BLOCK
, &mask
, oldmask
);
312 SYSERROR("Failed to set signal mask");
316 ret
= signalfd(-1, &mask
, SFD_CLOEXEC
);
318 SYSERROR("Failed to create signal file descriptor");
322 TRACE("Created signal file descriptor %d", ret
);
327 static int signal_handler(int fd
, uint32_t events
, void *data
,
328 struct lxc_epoll_descr
*descr
)
332 struct signalfd_siginfo siginfo
;
333 struct lxc_handler
*hdlr
= data
;
335 ret
= lxc_read_nointr(fd
, &siginfo
, sizeof(siginfo
));
337 ERROR("Failed to read signal info from signal file descriptor %d", fd
);
338 return LXC_MAINLOOP_ERROR
;
341 if (ret
!= sizeof(siginfo
)) {
342 ERROR("Unexpected size for struct signalfd_siginfo");
346 /* Check whether init is running. */
348 ret
= waitid(P_PID
, hdlr
->pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
349 if (ret
== 0 && info
.si_pid
== hdlr
->pid
)
350 hdlr
->init_died
= true;
352 /* Try to figure out a reasonable exit status to report. */
353 if (hdlr
->init_died
) {
354 switch (info
.si_code
) {
356 hdlr
->exit_status
= info
.si_status
<< 8;
361 hdlr
->exit_status
= info
.si_status
<< 8 | 0x7f;
364 /* Huh? The waitid() told us it's dead *and* continued? */
365 WARN("Init %d dead and continued?", hdlr
->pid
);
366 hdlr
->exit_status
= 1;
369 ERROR("Unknown si_code: %d", info
.si_code
);
370 hdlr
->exit_status
= 1;
374 if (siginfo
.ssi_signo
== SIGHUP
) {
375 kill(hdlr
->pid
, SIGTERM
);
376 INFO("Killing %d since terminal hung up", hdlr
->pid
);
377 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
: LXC_MAINLOOP_CONTINUE
;
380 if (siginfo
.ssi_signo
!= SIGCHLD
) {
381 kill(hdlr
->pid
, siginfo
.ssi_signo
);
382 INFO("Forwarded signal %d to pid %d", siginfo
.ssi_signo
, hdlr
->pid
);
383 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
: LXC_MAINLOOP_CONTINUE
;
386 /* More robustness, protect ourself from a SIGCHLD sent
387 * by a process different from the container init.
389 if (siginfo
.ssi_pid
!= hdlr
->pid
) {
390 NOTICE("Received %d from pid %d instead of container init %d",
391 siginfo
.ssi_signo
, siginfo
.ssi_pid
, hdlr
->pid
);
392 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
: LXC_MAINLOOP_CONTINUE
;
395 if (siginfo
.ssi_code
== CLD_STOPPED
) {
396 INFO("Container init process was stopped");
397 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
: LXC_MAINLOOP_CONTINUE
;
398 } else if (siginfo
.ssi_code
== CLD_CONTINUED
) {
399 INFO("Container init process was continued");
400 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
: LXC_MAINLOOP_CONTINUE
;
403 DEBUG("Container init process %d exited", hdlr
->pid
);
404 return LXC_MAINLOOP_CLOSE
;
407 int lxc_serve_state_clients(const char *name
, struct lxc_handler
*handler
,
412 struct lxc_list
*cur
, *next
;
413 struct lxc_state_client
*client
;
414 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
417 handler
->state
= RUNNING
;
419 handler
->state
= state
;
421 TRACE("Set container state to %s", lxc_state2str(state
));
423 if (lxc_list_empty(&handler
->conf
->state_clients
)) {
424 TRACE("No state clients registered");
428 retlen
= strlcpy(msg
.name
, name
, sizeof(msg
.name
));
429 if (retlen
>= sizeof(msg
.name
))
432 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
435 if (client
->states
[state
] == 0) {
436 TRACE("State %s not registered for state client %d",
437 lxc_state2str(state
), client
->clientfd
);
441 TRACE("Sending state %s to state client %d",
442 lxc_state2str(state
), client
->clientfd
);
444 ret
= lxc_send_nointr(client
->clientfd
, &msg
, sizeof(msg
), MSG_NOSIGNAL
);
446 SYSERROR("Failed to send message to client");
448 /* kick client from list */
450 close(client
->clientfd
);
458 static int lxc_serve_state_socket_pair(const char *name
,
459 struct lxc_handler
*handler
,
464 if (!handler
->daemonize
||
465 handler
->state_socket_pair
[1] < 0 ||
469 /* Close read end of the socket pair. */
470 close(handler
->state_socket_pair
[0]);
471 handler
->state_socket_pair
[0] = -1;
474 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
475 &(int){state
}, sizeof(int));
477 SYSERROR("Failed to send state to %d", handler
->state_socket_pair
[1]);
485 if (ret
!= sizeof(int)) {
486 ERROR("Message too long : %d", handler
->state_socket_pair
[1]);
490 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
491 handler
->state_socket_pair
[1]);
493 /* Close write end of the socket pair. */
494 close(handler
->state_socket_pair
[1]);
495 handler
->state_socket_pair
[1] = -1;
500 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
505 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
507 ERROR("Failed to synchronize via anonymous pair of unix sockets");
511 ret
= lxc_serve_state_clients(name
, handler
, state
);
515 /* This function will try to connect to the legacy lxc-monitord state
516 * server and only exists for backwards compatibility.
518 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
523 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
526 bool has_console
= true;
527 struct lxc_epoll_descr descr
, descr_console
;
529 if (handler
->conf
->console
.path
&&
530 strcmp(handler
->conf
->console
.path
, "none") == 0)
533 ret
= lxc_mainloop_open(&descr
);
535 ERROR("Failed to create mainloop");
540 ret
= lxc_mainloop_open(&descr_console
);
542 ERROR("Failed to create console mainloop");
547 ret
= lxc_mainloop_add_handler(&descr
, handler
->sigfd
, signal_handler
, handler
);
549 ERROR("Failed to add signal handler for %d to mainloop", handler
->sigfd
);
550 goto out_mainloop_console
;
554 struct lxc_terminal
*console
= &handler
->conf
->console
;
556 ret
= lxc_terminal_mainloop_add(&descr
, console
);
558 ERROR("Failed to add console handlers to mainloop");
559 goto out_mainloop_console
;
562 ret
= lxc_terminal_mainloop_add(&descr_console
, console
);
564 ERROR("Failed to add console handlers to console mainloop");
565 goto out_mainloop_console
;
568 handler
->conf
->console
.descr
= &descr
;
571 ret
= lxc_cmd_mainloop_add(name
, &descr
, handler
);
573 ERROR("Failed to add command handler to mainloop");
574 goto out_mainloop_console
;
577 TRACE("Mainloop is ready");
579 ret
= lxc_mainloop(&descr
, -1);
582 if (ret
< 0 || !handler
->init_died
)
583 goto out_mainloop_console
;
586 ret
= lxc_mainloop(&descr_console
, 0);
588 out_mainloop_console
:
590 lxc_mainloop_close(&descr_console
);
591 TRACE("Closed console mainloop");
595 lxc_mainloop_close(&descr
);
596 TRACE("Closed mainloop");
599 close(handler
->sigfd
);
600 TRACE("Closed signal file descriptor %d", handler
->sigfd
);
601 handler
->sigfd
= -EBADF
;
606 void lxc_zero_handler(struct lxc_handler
*handler
)
610 memset(handler
, 0, sizeof(struct lxc_handler
));
616 for (i
= 0; i
< LXC_NS_MAX
; i
++)
617 handler
->nsfd
[i
] = -1;
619 handler
->data_sock
[0] = -1;
620 handler
->data_sock
[1] = -1;
622 handler
->state_socket_pair
[0] = -1;
623 handler
->state_socket_pair
[1] = -1;
625 handler
->sync_sock
[0] = -1;
626 handler
->sync_sock
[1] = -1;
629 void lxc_free_handler(struct lxc_handler
*handler
)
631 if (handler
->pinfd
>= 0)
632 close(handler
->pinfd
);
634 if (handler
->sigfd
>= 0)
635 close(handler
->sigfd
);
637 lxc_put_nsfds(handler
);
639 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
640 if (handler
->conf
->maincmd_fd
>= 0)
641 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
643 if (handler
->state_socket_pair
[0] >= 0)
644 close(handler
->state_socket_pair
[0]);
646 if (handler
->state_socket_pair
[1] >= 0)
647 close(handler
->state_socket_pair
[1]);
649 handler
->conf
= NULL
;
654 struct lxc_handler
*lxc_init_handler(const char *name
, struct lxc_conf
*conf
,
655 const char *lxcpath
, bool daemonize
)
658 struct lxc_handler
*handler
;
660 handler
= malloc(sizeof(*handler
));
664 memset(handler
, 0, sizeof(*handler
));
666 /* Note that am_guest_unpriv() checks the effective uid. We
667 * probably don't care if we are real root only if we are running
668 * as root so this should be fine.
670 handler
->am_root
= !am_guest_unpriv();
671 handler
->data_sock
[0] = handler
->data_sock
[1] = -1;
672 handler
->conf
= conf
;
673 handler
->lxcpath
= lxcpath
;
675 handler
->sigfd
= -EBADF
;
676 handler
->init_died
= false;
677 handler
->state_socket_pair
[0] = handler
->state_socket_pair
[1] = -1;
678 if (handler
->conf
->reboot
== REBOOT_NONE
)
679 lxc_list_init(&handler
->conf
->state_clients
);
681 for (i
= 0; i
< LXC_NS_MAX
; i
++)
682 handler
->nsfd
[i
] = -1;
684 handler
->name
= name
;
686 if (daemonize
&& handler
->conf
->reboot
== REBOOT_NONE
) {
687 /* Create socketpair() to synchronize on daemonized startup.
688 * When the container reboots we don't need to synchronize
689 * again currently so don't open another socketpair().
691 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
692 handler
->state_socket_pair
);
694 ERROR("Failed to create anonymous pair of unix sockets");
698 TRACE("Created anonymous pair {%d,%d} of unix sockets",
699 handler
->state_socket_pair
[0],
700 handler
->state_socket_pair
[1]);
703 if (handler
->conf
->reboot
== REBOOT_NONE
) {
704 handler
->conf
->maincmd_fd
= lxc_cmd_init(name
, lxcpath
, "command");
705 if (handler
->conf
->maincmd_fd
< 0) {
706 ERROR("Failed to set up command socket");
711 TRACE("Unix domain socket %d for command server is ready",
712 handler
->conf
->maincmd_fd
);
717 lxc_free_handler(handler
);
722 int lxc_init(const char *name
, struct lxc_handler
*handler
)
725 const char *loglevel
;
726 struct lxc_conf
*conf
= handler
->conf
;
729 TRACE("Initialized LSM");
731 ret
= lxc_read_seccomp_config(conf
);
733 ERROR("Failed loading seccomp policy");
734 goto out_close_maincmd_fd
;
736 TRACE("Read seccomp policy");
738 /* Begin by setting the state to STARTING. */
739 ret
= lxc_set_state(name
, handler
, STARTING
);
741 ERROR("Failed to set state to \"%s\"", lxc_state2str(STARTING
));
742 goto out_close_maincmd_fd
;
744 TRACE("Set container state to \"STARTING\"");
746 /* Start of environment variable setup for hooks. */
747 ret
= setenv("LXC_NAME", name
, 1);
749 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name
);
752 ret
= setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1);
754 SYSERROR("Failed to set environment variable: "
755 "LXC_CONFIG_FILE=%s", conf
->rcfile
);
758 if (conf
->rootfs
.mount
) {
759 ret
= setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1);
761 SYSERROR("Failed to set environment variable: "
762 "LXC_ROOTFS_MOUNT=%s", conf
->rootfs
.mount
);
765 if (conf
->rootfs
.path
) {
766 ret
= setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1);
768 SYSERROR("Failed to set environment variable: "
769 "LXC_ROOTFS_PATH=%s", conf
->rootfs
.path
);
772 if (conf
->console
.path
) {
773 ret
= setenv("LXC_CONSOLE", conf
->console
.path
, 1);
775 SYSERROR("Failed to set environment variable: "
776 "LXC_CONSOLE=%s", conf
->console
.path
);
779 if (conf
->console
.log_path
) {
780 ret
= setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1);
782 SYSERROR("Failed to set environment variable: "
783 "LXC_CONSOLE_LOGPATH=%s", conf
->console
.log_path
);
786 if (cgns_supported()) {
787 ret
= setenv("LXC_CGNS_AWARE", "1", 1);
789 SYSERROR("Failed to set environment variable "
793 loglevel
= lxc_log_priority_to_string(lxc_log_get_level());
794 ret
= setenv("LXC_LOG_LEVEL", loglevel
, 1);
796 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s",
799 if (conf
->hooks_version
== 0)
800 ret
= setenv("LXC_HOOK_VERSION", "0", 1);
802 ret
= setenv("LXC_HOOK_VERSION", "1", 1);
804 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf
->hooks_version
);
805 /* End of environment variable setup for hooks. */
807 TRACE("Set environment variables");
809 ret
= run_lxc_hooks(name
, "pre-start", conf
, NULL
);
811 ERROR("Failed to run lxc.hook.pre-start for container \"%s\"", name
);
814 TRACE("Ran pre-start hooks");
816 /* The signal fd has to be created before forking otherwise if the child
817 * process exits before we setup the signal fd, the event will be lost
818 * and the command will be stuck.
820 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
821 if (handler
->sigfd
< 0) {
822 ERROR("Failed to setup SIGCHLD fd handler.");
825 TRACE("Set up signal fd");
827 /* Do this after setting up signals since it might unblock SIGWINCH. */
828 ret
= lxc_terminal_setup(conf
);
830 ERROR("Failed to create console");
831 goto out_restore_sigmask
;
833 TRACE("Created console");
835 ret
= lxc_terminal_map_ids(conf
, &conf
->console
);
837 ERROR("Failed to chown console");
838 goto out_delete_terminal
;
840 TRACE("Chowned console");
842 handler
->cgroup_ops
= cgroup_init(handler
->conf
);
843 if (!handler
->cgroup_ops
) {
844 ERROR("Failed to initialize cgroup driver");
845 goto out_delete_terminal
;
847 TRACE("Initialized cgroup driver");
849 ret
= lsm_process_prepare(conf
, handler
->lxcpath
);
851 ERROR("Failed to initialize LSM");
852 goto out_destroy_cgroups
;
854 TRACE("Initialized LSM");
856 INFO("Container \"%s\" is initialized", name
);
860 handler
->cgroup_ops
->destroy(handler
->cgroup_ops
, handler
);
863 lxc_terminal_delete(&handler
->conf
->console
);
866 (void)pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
869 lxc_delete_tty(&conf
->ttys
);
872 (void)lxc_set_state(name
, handler
, ABORTING
);
874 out_close_maincmd_fd
:
875 lxc_abstract_unix_close(conf
->maincmd_fd
);
876 conf
->maincmd_fd
= -1;
880 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
884 struct lxc_list
*cur
, *next
;
885 char *namespaces
[LXC_NS_MAX
+ 1];
886 size_t namespace_count
= 0;
887 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
889 /* The STOPPING state is there for future cleanup code which can take
892 lxc_set_state(name
, handler
, STOPPING
);
894 self
= lxc_raw_getpid();
895 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
896 if (handler
->nsfd
[i
] < 0)
899 if (handler
->conf
->hooks_version
== 0)
900 ret
= asprintf(&namespaces
[namespace_count
],
901 "%s:/proc/%d/fd/%d", ns_info
[i
].proc_name
,
902 self
, handler
->nsfd
[i
]);
904 ret
= asprintf(&namespaces
[namespace_count
],
905 "/proc/%d/fd/%d", self
, handler
->nsfd
[i
]);
907 SYSERROR("Failed to allocate memory");
911 if (handler
->conf
->hooks_version
== 0) {
916 ret
= setenv(ns_info
[i
].env_name
, namespaces
[namespace_count
], 1);
918 SYSERROR("Failed to set environment variable %s=%s",
919 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
921 TRACE("Set environment variable %s=%s",
922 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
926 namespaces
[namespace_count
] = NULL
;
928 if (handler
->conf
->reboot
> REBOOT_NONE
) {
929 ret
= setenv("LXC_TARGET", "reboot", 1);
931 SYSERROR("Failed to set environment variable: "
932 "LXC_TARGET=reboot");
935 if (handler
->conf
->reboot
== REBOOT_NONE
) {
936 ret
= setenv("LXC_TARGET", "stop", 1);
938 SYSERROR("Failed to set environment variable: "
942 if (handler
->conf
->hooks_version
== 0)
943 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, namespaces
);
945 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, NULL
);
947 ERROR("Failed to run \"lxc.hook.stop\" hook");
949 while (namespace_count
--)
950 free(namespaces
[namespace_count
]);
952 lsm_process_cleanup(handler
->conf
, handler
->lxcpath
);
954 cgroup_ops
->destroy(cgroup_ops
, handler
);
955 cgroup_exit(cgroup_ops
);
957 if (handler
->conf
->reboot
== REBOOT_NONE
) {
958 /* For all new state clients simply close the command socket.
959 * This will inform all state clients that the container is
960 * STOPPED and also prevents a race between a open()/close() on
961 * the command socket causing a new process to get ECONNREFUSED
962 * because we haven't yet closed the command socket.
964 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
965 handler
->conf
->maincmd_fd
= -1;
966 TRACE("Closed command socket");
968 /* This function will try to connect to the legacy lxc-monitord
969 * state server and only exists for backwards compatibility.
971 lxc_monitor_send_state(name
, STOPPED
, handler
->lxcpath
);
973 /* The command socket is closed so no one can acces the command
974 * socket anymore so there's no need to lock it.
976 handler
->state
= STOPPED
;
977 TRACE("Set container state to \"STOPPED\"");
979 lxc_set_state(name
, handler
, STOPPED
);
982 ret
= run_lxc_hooks(name
, "post-stop", handler
->conf
, NULL
);
984 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name
);
985 if (handler
->conf
->reboot
> REBOOT_NONE
) {
986 WARN("Container will be stopped instead of rebooted");
987 handler
->conf
->reboot
= REBOOT_NONE
;
989 ret
= setenv("LXC_TARGET", "stop", 1);
991 WARN("Failed to set environment variable: "
996 /* Reset mask set by setup_signal_fd. */
997 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
999 SYSWARN("Failed to restore signal mask");
1001 lxc_terminal_delete(&handler
->conf
->console
);
1002 lxc_delete_tty(&handler
->conf
->ttys
);
1004 /* The command socket is now closed, no more state clients can register
1005 * themselves from now on. So free the list of state clients.
1007 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
1008 struct lxc_state_client
*client
= cur
->elem
;
1010 /* Keep state clients that want to be notified about reboots. */
1011 if ((handler
->conf
->reboot
> REBOOT_NONE
) &&
1012 (client
->states
[RUNNING
] == 2))
1015 /* close state client socket */
1017 close(client
->clientfd
);
1022 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= REBOOT_REQ
)
1023 lxc_destroy_container_on_signal(handler
, name
);
1025 lxc_free_handler(handler
);
1028 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
1032 lxc_set_state(name
, handler
, ABORTING
);
1034 if (handler
->pid
> 0) {
1035 ret
= kill(handler
->pid
, SIGKILL
);
1037 SYSERROR("Failed to send SIGKILL to %d", handler
->pid
);
1040 while ((ret
= waitpid(-1, &status
, 0)) > 0) {
1045 static int do_start(void *data
)
1048 char path
[PATH_MAX
];
1051 struct lxc_list
*iterator
;
1054 int devnull_fd
= -1;
1055 struct lxc_handler
*handler
= data
;
1057 lxc_sync_fini_parent(handler
);
1059 /* This prctl must be before the synchro, so if the parent dies before
1060 * we set the parent death signal, we will detect its death with the
1061 * synchro right after, otherwise we have a window where the parent can
1062 * exit before we set the pdeath signal leading to a unsupervized
1065 ret
= lxc_set_death_signal(SIGKILL
);
1067 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1068 goto out_warn_father
;
1071 ret
= lxc_ambient_caps_up();
1073 ERROR("Failed to raise ambient capabilities");
1074 goto out_warn_father
;
1077 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1079 SYSERROR("Failed to set signal mask");
1080 goto out_warn_father
;
1083 /* Don't leak the pinfd to the container. */
1084 if (handler
->pinfd
>= 0)
1085 close(handler
->pinfd
);
1087 ret
= lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
);
1089 goto out_warn_father
;
1091 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1092 * https://github.com/lxc/lxd/issues/1978.
1094 if ((handler
->ns_clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
1095 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
1096 ret
= unshare(CLONE_NEWNET
);
1098 SYSERROR("Failed to unshare CLONE_NEWNET");
1099 goto out_warn_father
;
1101 INFO("Unshared CLONE_NEWNET");
1104 /* Tell the parent task it can begin to configure the container and wait
1107 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
);
1111 ret
= lxc_network_recv_veth_names_from_parent(handler
);
1113 ERROR("Failed to receive veth names from parent");
1114 goto out_warn_father
;
1117 /* If we are in a new user namespace, become root there to have
1118 * privilege over our namespace.
1120 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1121 if (!handler
->conf
->root_nsuid_map
)
1122 nsuid
= handler
->conf
->init_uid
;
1124 if (!handler
->conf
->root_nsgid_map
)
1125 nsgid
= handler
->conf
->init_gid
;
1127 if (!lxc_switch_uid_gid(nsuid
, nsgid
))
1128 goto out_warn_father
;
1130 /* Drop groups only after we switched to a valid gid in the new
1133 if (!lxc_setgroups(0, NULL
) &&
1134 (handler
->am_root
|| errno
!= EPERM
))
1135 goto out_warn_father
;
1137 ret
= prctl(PR_SET_DUMPABLE
, prctl_arg(1), prctl_arg(0),
1138 prctl_arg(0), prctl_arg(0));
1140 goto out_warn_father
;
1142 /* set{g,u}id() clears deathsignal */
1143 ret
= lxc_set_death_signal(SIGKILL
);
1145 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1146 goto out_warn_father
;
1150 ret
= access(handler
->lxcpath
, X_OK
);
1152 print_top_failing_dir(handler
->lxcpath
);
1153 goto out_warn_father
;
1156 ret
= snprintf(path
, sizeof(path
), "%s/dev/null",
1157 handler
->conf
->rootfs
.mount
);
1158 if (ret
< 0 || ret
>= sizeof(path
))
1159 goto out_warn_father
;
1161 /* In order to checkpoint restore, we need to have everything in the
1162 * same mount namespace. However, some containers may not have a
1163 * reasonable /dev (in particular, they may not have /dev/null), so we
1164 * can't set init's std fds to /dev/null by opening it from inside the
1167 * If that's the case, fall back to using the host's /dev/null. This
1168 * means that migration won't work, but at least we won't spew output
1169 * where it isn't wanted.
1171 if (handler
->daemonize
&& !handler
->conf
->autodev
) {
1172 ret
= access(path
, F_OK
);
1174 devnull_fd
= open_devnull();
1177 goto out_warn_father
;
1178 WARN("Using /dev/null from the host for container "
1179 "init's standard file descriptors. Migration will "
1184 /* Ask father to setup cgroups and wait for him to finish. */
1185 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
);
1189 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1190 * earlier we end up with a wrong view of /proc/self/cgroup. For
1191 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1192 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1193 * /proc/self/cgroup would show us:
1197 * whereas it should actually show
1201 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1202 ret
= unshare(CLONE_NEWCGROUP
);
1204 INFO("Failed to unshare CLONE_NEWCGROUP");
1205 goto out_warn_father
;
1207 INFO("Unshared CLONE_NEWCGROUP");
1210 /* Add the requested environment variables to the current environment to
1211 * allow them to be used by the various hooks, such as the start hook
1214 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1215 ret
= putenv((char *)iterator
->elem
);
1217 SYSERROR("Failed to set environment variable: %s",
1218 (char *)iterator
->elem
);
1219 goto out_warn_father
;
1223 /* Setup the container, ip, names, utsname, ... */
1224 ret
= lxc_setup(handler
);
1225 close(handler
->data_sock
[1]);
1226 close(handler
->data_sock
[0]);
1228 ERROR("Failed to setup container \"%s\"", handler
->name
);
1229 goto out_warn_father
;
1232 /* Set the label to change to when we exec(2) the container's init. */
1233 ret
= lsm_process_label_set(NULL
, handler
->conf
, true);
1235 goto out_warn_father
;
1237 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1238 * before we aren't allowed anymore.
1240 if (handler
->conf
->no_new_privs
) {
1241 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
1242 prctl_arg(0), prctl_arg(0));
1244 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block "
1245 "execve() gainable privileges");
1246 goto out_warn_father
;
1248 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable "
1252 /* Some init's such as busybox will set sane tty settings on stdin,
1253 * stdout, stderr which it thinks is the console. We already set them
1254 * the way we wanted on the real terminal, and we want init to do its
1255 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
1256 * make sure that that pty is stdin,stdout,stderr.
1258 if (handler
->conf
->console
.slave
>= 0) {
1259 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
1260 ret
= set_stdfds(handler
->conf
->console
.slave
);
1262 ret
= lxc_terminal_set_stdfds(handler
->conf
->console
.slave
);
1264 ERROR("Failed to redirect std{in,out,err} to pty file "
1265 "descriptor %d", handler
->conf
->console
.slave
);
1266 goto out_warn_father
;
1270 /* If we mounted a temporary proc, then unmount it now. */
1271 tmp_proc_unmount(handler
->conf
);
1273 ret
= lxc_seccomp_load(handler
->conf
);
1275 goto out_warn_father
;
1277 ret
= run_lxc_hooks(handler
->name
, "start", handler
->conf
, NULL
);
1279 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1281 goto out_warn_father
;
1284 close(handler
->sigfd
);
1286 if (handler
->conf
->console
.slave
< 0 && handler
->daemonize
) {
1287 if (devnull_fd
< 0) {
1288 devnull_fd
= open_devnull();
1290 goto out_warn_father
;
1293 ret
= set_stdfds(devnull_fd
);
1295 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
1296 goto out_warn_father
;
1300 if (devnull_fd
>= 0) {
1307 if (handler
->conf
->init_cwd
) {
1308 ret
= chdir(handler
->conf
->init_cwd
);
1310 SYSERROR("Could not change directory to \"%s\"",
1311 handler
->conf
->init_cwd
);
1312 goto out_warn_father
;
1316 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
);
1318 goto out_warn_father
;
1320 /* Reset the environment variables the user requested in a clear
1324 /* Don't error out though. */
1326 SYSERROR("Failed to clear environment.");
1328 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1329 ret
= putenv((char *)iterator
->elem
);
1331 SYSERROR("Failed to set environment variable: %s",
1332 (char *)iterator
->elem
);
1333 goto out_warn_father
;
1337 ret
= putenv("container=lxc");
1339 SYSERROR("Failed to set environment variable: container=lxc");
1340 goto out_warn_father
;
1343 if (handler
->conf
->ttys
.tty_names
) {
1344 ret
= putenv(handler
->conf
->ttys
.tty_names
);
1346 SYSERROR("Failed to set environment variable for container ptys");
1347 goto out_warn_father
;
1351 /* The container has been setup. We can now switch to an unprivileged
1354 new_uid
= handler
->conf
->init_uid
;
1355 new_gid
= handler
->conf
->init_gid
;
1357 /* Avoid unnecessary syscalls. */
1358 if (new_uid
== nsuid
)
1359 new_uid
= LXC_INVALID_UID
;
1361 if (new_gid
== nsgid
)
1362 new_gid
= LXC_INVALID_GID
;
1364 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
1365 goto out_warn_father
;
1367 /* If we are in a new user namespace we already dropped all groups when
1368 * we switched to root in the new user namespace further above. Only
1369 * drop groups if we can, so ensure that we have necessary privilege.
1371 if (lxc_list_empty(&handler
->conf
->id_map
))
1373 if (lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
))
1375 if (!lxc_setgroups(0, NULL
))
1376 goto out_warn_father
;
1378 ret
= lxc_ambient_caps_down();
1380 ERROR("Failed to clear ambient capabilities");
1381 goto out_warn_father
;
1384 if (handler
->conf
->monitor_signal_pdeath
!= SIGKILL
) {
1385 ret
= lxc_set_death_signal(handler
->conf
->monitor_signal_pdeath
);
1387 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1388 handler
->conf
->monitor_signal_pdeath
);
1389 goto out_warn_father
;
1393 /* After this call, we are in error because this ops should not return
1396 handler
->ops
->start(handler
, handler
->data
);
1399 /* We want the parent to know something went wrong, so we return a
1400 * special error code.
1402 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1405 if (devnull_fd
>= 0)
1411 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1414 struct lxc_terminal_info
*tty
;
1416 int sock
= handler
->data_sock
[1];
1417 struct lxc_conf
*conf
= handler
->conf
;
1418 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1420 if (!conf
->ttys
.max
)
1423 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
1427 for (i
= 0; i
< conf
->ttys
.max
; i
++) {
1430 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1434 tty
= &ttys
->tty
[i
];
1436 tty
->master
= ttyfds
[0];
1437 tty
->slave
= ttyfds
[1];
1438 TRACE("Received pty with master fd %d and slave fd %d from "
1439 "parent", tty
->master
, tty
->slave
);
1443 SYSERROR("Failed to receive %zu ttys from child", ttys
->max
);
1445 TRACE("Received %zu ttys from child", ttys
->max
);
1450 int resolve_clone_flags(struct lxc_handler
*handler
)
1453 struct lxc_conf
*conf
= handler
->conf
;
1455 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1456 if (conf
->ns_keep
!= 0) {
1457 if ((conf
->ns_keep
& ns_info
[i
].clone_flag
) == 0)
1458 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1459 } else if (conf
->ns_clone
!= 0) {
1460 if ((conf
->ns_clone
& ns_info
[i
].clone_flag
) > 0)
1461 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1463 if (i
== LXC_NS_USER
&& lxc_list_empty(&handler
->conf
->id_map
))
1466 if (i
== LXC_NS_NET
&& lxc_requests_empty_network(handler
))
1469 if (i
== LXC_NS_CGROUP
&& !cgns_supported())
1472 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1475 if (!conf
->ns_share
[i
])
1478 handler
->ns_clone_flags
&= ~ns_info
[i
].clone_flag
;
1479 TRACE("Sharing %s namespace", ns_info
[i
].proc_name
);
1485 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1486 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1487 * But since the memory between parent and child is shared on CLONE_VM this
1488 * would invalidate the getpid() cache that glibc used to maintain and so
1489 * getpid() in the child would return the parent's pid. This is all fixed in
1490 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1491 * not reset anymore.
1492 * However, if for whatever reason you - dear commiter - somehow need to get the
1493 * pid of the dummy intermediate process for do_share_ns() you need to call
1494 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1497 static inline int do_share_ns(void *arg
)
1500 struct lxc_handler
*handler
= arg
;
1502 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1503 if (handler
->nsfd
[i
] < 0)
1506 ret
= setns(handler
->nsfd
[i
], 0);
1509 * Note that joining a user and/or mount namespace
1510 * requires the process is not multithreaded otherwise
1511 * setns() will fail here.
1513 SYSERROR("Failed to inherit %s namespace",
1514 ns_info
[i
].proc_name
);
1518 DEBUG("Inherited %s namespace", ns_info
[i
].proc_name
);
1521 flags
= handler
->ns_on_clone_flags
;
1522 flags
|= CLONE_PARENT
;
1523 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, flags
);
1524 if (handler
->pid
< 0)
1530 static int lxc_setup_shmount(struct lxc_conf
*conf
)
1533 char *full_cont_path
;
1536 /* Construct the shmount path under the container root. */
1537 len_cont
= strlen(conf
->rootfs
.mount
) + 1 + strlen(conf
->shmount
.path_cont
);
1538 /* +1 for the terminating '\0' */
1539 full_cont_path
= malloc(len_cont
+ 1);
1540 if (!full_cont_path
) {
1541 SYSERROR("Not enough memory");
1545 ret
= snprintf(full_cont_path
, len_cont
+ 1, "%s/%s",
1546 conf
->rootfs
.mount
, conf
->shmount
.path_cont
);
1547 if (ret
< 0 || ret
>= len_cont
+ 1) {
1548 SYSERROR("Failed to create filename");
1549 free(full_cont_path
);
1553 /* Check if shmount point is already set up. */
1554 if (is_shared_mountpoint(conf
->shmount
.path_host
)) {
1555 INFO("Path \"%s\" is already MS_SHARED. Reusing",
1556 conf
->shmount
.path_host
);
1557 free(full_cont_path
);
1561 /* Create host and cont mount paths */
1562 ret
= mkdir_p(conf
->shmount
.path_host
, 0711);
1563 if (ret
< 0 && errno
!= EEXIST
) {
1564 SYSERROR("Failed to create directory \"%s\"",
1565 conf
->shmount
.path_host
);
1566 free(full_cont_path
);
1570 ret
= mkdir_p(full_cont_path
, 0711);
1571 if (ret
< 0 && errno
!= EEXIST
) {
1572 SYSERROR("Failed to create directory \"%s\"", full_cont_path
);
1573 free(full_cont_path
);
1577 /* Prepare host mountpoint */
1578 ret
= mount("tmpfs", conf
->shmount
.path_host
, "tmpfs", 0,
1579 "size=100k,mode=0711");
1581 SYSERROR("Failed to mount \"%s\"", conf
->shmount
.path_host
);
1582 free(full_cont_path
);
1586 ret
= mount(conf
->shmount
.path_host
, conf
->shmount
.path_host
, "none",
1587 MS_REC
| MS_SHARED
, "");
1589 SYSERROR("Failed to make shared \"%s\"", conf
->shmount
.path_host
);
1590 free(full_cont_path
);
1594 INFO("Setup shared mount point \"%s\"", conf
->shmount
.path_host
);
1595 free(full_cont_path
);
1599 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1600 * exec()s the requested container binary.
1601 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1602 * right here should be double checked if they'd pose a security risk. (For
1603 * example, any {u}mount() operations performed here will be reflected on the
1606 static int lxc_spawn(struct lxc_handler
*handler
)
1610 bool wants_to_map_ids
;
1611 struct lxc_list
*id_map
;
1612 const char *name
= handler
->name
;
1613 const char *lxcpath
= handler
->lxcpath
;
1614 bool share_ns
= false;
1615 struct lxc_conf
*conf
= handler
->conf
;
1616 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
1618 id_map
= &conf
->id_map
;
1619 wants_to_map_ids
= !lxc_list_empty(id_map
);
1621 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1622 if (!conf
->ns_share
[i
])
1625 handler
->nsfd
[i
] = lxc_inherit_namespace(conf
->ns_share
[i
], lxcpath
, ns_info
[i
].proc_name
);
1626 if (handler
->nsfd
[i
] < 0)
1632 ret
= lxc_sync_init(handler
);
1636 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1637 handler
->data_sock
);
1641 ret
= resolve_clone_flags(handler
);
1645 if (conf
->shmount
.path_host
) {
1646 if (!conf
->shmount
.path_cont
)
1649 ret
= lxc_setup_shmount(conf
);
1651 ERROR("Failed to setup shared mount point");
1656 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1657 if (!lxc_list_empty(&conf
->network
)) {
1659 /* Find gateway addresses from the link device, which is
1660 * no longer accessible inside the container. Do this
1661 * before creating network interfaces, since goto
1662 * out_delete_net does not work before lxc_clone.
1664 ret
= lxc_find_gateway_addresses(handler
);
1666 ERROR("Failed to find gateway addresses");
1670 /* That should be done before the clone because we will
1671 * fill the netdev index and use them in the child.
1673 ret
= lxc_create_network_priv(handler
);
1675 ERROR("Failed to create the network");
1676 goto out_delete_net
;
1681 if (!cgroup_ops
->payload_create(cgroup_ops
, handler
)) {
1682 ERROR("Failed creating cgroups");
1683 goto out_delete_net
;
1686 /* If the rootfs is not a blockdev, prevent the container from marking
1688 * If the container is unprivileged then skip rootfs pinning.
1690 if (!wants_to_map_ids
) {
1691 handler
->pinfd
= pin_rootfs(conf
->rootfs
.path
);
1692 if (handler
->pinfd
== -1)
1693 INFO("Failed to pin the rootfs for container \"%s\"", handler
->name
);
1696 /* Create a process in a new set of namespaces. */
1697 handler
->ns_on_clone_flags
= handler
->ns_clone_flags
;
1698 if (handler
->ns_clone_flags
& CLONE_NEWUSER
) {
1699 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1700 * clone a new user namespace first and only later unshare our
1701 * network namespace to ensure that network devices ownership is
1704 handler
->ns_on_clone_flags
&= ~CLONE_NEWNET
;
1706 /* The cgroup namespace gets unshare()ed not clone()ed. */
1707 handler
->ns_on_clone_flags
&= ~CLONE_NEWCGROUP
;
1712 attacher_pid
= lxc_clone(do_share_ns
, handler
,
1713 CLONE_VFORK
| CLONE_VM
| CLONE_FILES
);
1714 if (attacher_pid
< 0) {
1715 SYSERROR(LXC_CLONE_ERROR
);
1716 goto out_delete_net
;
1719 ret
= wait_for_pid(attacher_pid
);
1721 SYSERROR("Intermediate process failed");
1722 goto out_delete_net
;
1725 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
,
1726 handler
->ns_on_clone_flags
);
1728 if (handler
->pid
< 0) {
1729 SYSERROR(LXC_CLONE_ERROR
);
1730 goto out_delete_net
;
1732 TRACE("Cloned child process %d", handler
->pid
);
1734 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1735 if (handler
->ns_on_clone_flags
& ns_info
[i
].clone_flag
)
1736 INFO("Cloned %s", ns_info
[i
].flag_name
);
1738 if (!lxc_try_preserve_namespaces(handler
, handler
->ns_on_clone_flags
, handler
->pid
)) {
1739 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1740 goto out_delete_net
;
1743 lxc_sync_fini_child(handler
);
1745 /* Map the container uids. The container became an invalid userid the
1746 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1747 * anything immediately, but allows the container to setuid(0) (0 being
1748 * mapped to something else on the host.) later to become a valid uid
1751 if (wants_to_map_ids
) {
1752 if (!handler
->conf
->ns_share
[LXC_NS_USER
] &&
1753 (handler
->conf
->ns_keep
& CLONE_NEWUSER
) == 0) {
1754 ret
= lxc_map_ids(id_map
, handler
->pid
);
1756 ERROR("Failed to set up id mapping.");
1757 goto out_delete_net
;
1762 ret
= lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
);
1764 goto out_delete_net
;
1766 ret
= lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
);
1768 goto out_delete_net
;
1770 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
->conf
, false)) {
1771 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1772 goto out_delete_net
;
1775 if (!cgroup_ops
->payload_enter(cgroup_ops
, handler
->pid
))
1776 goto out_delete_net
;
1778 if (!cgroup_ops
->chown(cgroup_ops
, handler
->conf
))
1779 goto out_delete_net
;
1781 /* Now we're ready to preserve the network namespace */
1782 ret
= lxc_try_preserve_ns(handler
->pid
, "net");
1784 if (ret
!= -EOPNOTSUPP
) {
1785 SYSERROR("Failed to preserve net namespace");
1786 goto out_delete_net
;
1789 handler
->nsfd
[LXC_NS_NET
] = ret
;
1790 DEBUG("Preserved net namespace via fd %d", ret
);
1792 ret
= lxc_netns_set_nsid(handler
->nsfd
[LXC_NS_NET
]);
1794 SYSERROR("Failed to allocate new network namespace id");
1796 TRACE("Allocated new network namespace id");
1799 /* Create the network configuration. */
1800 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1801 ret
= lxc_network_move_created_netdev_priv(handler
->lxcpath
,
1806 ERROR("Failed to create the configured network");
1807 goto out_delete_net
;
1810 ret
= lxc_create_network_unpriv(handler
->lxcpath
, handler
->name
,
1811 &conf
->network
, handler
->pid
, conf
->hooks_version
);
1813 ERROR("Failed to create the configured network");
1814 goto out_delete_net
;
1818 ret
= lxc_network_send_veth_names_to_child(handler
);
1820 ERROR("Failed to send veth names to child");
1821 goto out_delete_net
;
1824 if (!lxc_list_empty(&conf
->procs
)) {
1825 ret
= setup_proc_filesystem(&conf
->procs
, handler
->pid
);
1827 goto out_delete_net
;
1830 /* Tell the child to continue its initialization. We'll get
1831 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1833 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
);
1835 goto out_delete_net
;
1837 if (!lxc_list_empty(&conf
->limits
)) {
1838 ret
= setup_resource_limits(&conf
->limits
, handler
->pid
);
1840 ERROR("Failed to setup resource limits");
1841 goto out_delete_net
;
1845 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
);
1847 goto out_delete_net
;
1849 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
->conf
, true)) {
1850 ERROR("Failed to setup legacy device cgroup controller limits");
1851 goto out_delete_net
;
1853 TRACE("Set up legacy device cgroup controller limits");
1855 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1856 /* Now we're ready to preserve the cgroup namespace */
1857 ret
= lxc_try_preserve_ns(handler
->pid
, "cgroup");
1859 if (ret
!= -EOPNOTSUPP
) {
1860 SYSERROR("Failed to preserve cgroup namespace");
1861 goto out_delete_net
;
1864 handler
->nsfd
[LXC_NS_CGROUP
] = ret
;
1865 DEBUG("Preserved cgroup namespace via fd %d", ret
);
1869 ret
= snprintf(pidstr
, 20, "%d", handler
->pid
);
1870 if (ret
< 0 || ret
>= 20)
1871 goto out_delete_net
;
1873 ret
= setenv("LXC_PID", pidstr
, 1);
1875 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr
);
1877 /* Run any host-side start hooks */
1878 ret
= run_lxc_hooks(name
, "start-host", conf
, NULL
);
1880 ERROR("Failed to run lxc.hook.start-host");
1881 goto out_delete_net
;
1884 /* Tell the child to complete its initialization and wait for it to exec
1885 * or return an error. (The child will never return
1886 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1887 * lxc_sync_barrier_child to return success, or return a different
1888 * value, causing us to error out).
1890 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_READY_START
);
1892 goto out_delete_net
;
1894 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
1896 ERROR("Failed to receive names and ifindices for network "
1897 "devices from child");
1898 goto out_delete_net
;
1901 /* Now all networks are created, network devices are moved into place,
1902 * and the correct names and ifindeces in the respective namespaces have
1903 * been recorded. The corresponding structs have now all been filled. So
1904 * log them for debugging purposes.
1906 lxc_log_configured_netdevs(conf
);
1908 /* Read tty fds allocated by child. */
1909 ret
= lxc_recv_ttys_from_child(handler
);
1911 ERROR("Failed to receive tty info from child process");
1912 goto out_delete_net
;
1915 ret
= handler
->ops
->post_start(handler
, handler
->data
);
1919 ret
= lxc_set_state(name
, handler
, RUNNING
);
1921 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING
));
1925 lxc_sync_fini(handler
);
1930 if (handler
->ns_clone_flags
& CLONE_NEWNET
)
1931 lxc_delete_network(handler
);
1934 lxc_abort(name
, handler
);
1937 lxc_sync_fini(handler
);
1938 if (handler
->pinfd
>= 0) {
1939 close(handler
->pinfd
);
1940 handler
->pinfd
= -1;
1946 int __lxc_start(const char *name
, struct lxc_handler
*handler
,
1947 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1948 bool daemonize
, int *error_num
)
1951 struct lxc_conf
*conf
= handler
->conf
;
1952 struct cgroup_ops
*cgroup_ops
;
1954 ret
= lxc_init(name
, handler
);
1956 ERROR("Failed to initialize container \"%s\"", name
);
1960 handler
->data
= data
;
1961 handler
->daemonize
= daemonize
;
1962 cgroup_ops
= handler
->cgroup_ops
;
1964 if (!attach_block_device(handler
->conf
)) {
1965 ERROR("Failed to attach block device");
1966 goto out_fini_nonet
;
1969 if (!cgroup_ops
->monitor_create(cgroup_ops
, handler
)) {
1970 ERROR("Failed to create monitor cgroup");
1971 goto out_fini_nonet
;
1974 if (!cgroup_ops
->monitor_enter(cgroup_ops
, lxc_raw_getpid())) {
1975 ERROR("Failed to enter monitor cgroup");
1976 goto out_fini_nonet
;
1979 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1980 /* If the backing store is a device, mount it here and now. */
1981 if (rootfs_is_blockdev(conf
)) {
1982 ret
= unshare(CLONE_NEWNS
);
1984 ERROR("Failed to unshare CLONE_NEWNS");
1985 goto out_fini_nonet
;
1987 INFO("Unshared CLONE_NEWNS");
1989 remount_all_slave();
1990 ret
= lxc_setup_rootfs_prepare_root(conf
, name
, lxcpath
);
1992 ERROR("Error setting up rootfs mount as root before spawn");
1993 goto out_fini_nonet
;
1995 INFO("Set up container rootfs as host root");
1999 ret
= lxc_spawn(handler
);
2001 ERROR("Failed to spawn container \"%s\"", name
);
2002 goto out_detach_blockdev
;
2004 /* close parent side of data socket */
2005 close(handler
->data_sock
[0]);
2006 handler
->data_sock
[0] = -1;
2007 close(handler
->data_sock
[1]);
2008 handler
->data_sock
[1] = -1;
2010 handler
->conf
->reboot
= REBOOT_NONE
;
2012 ret
= lxc_poll(name
, handler
);
2014 ERROR("LXC mainloop exited with error: %d", ret
);
2018 if (!handler
->init_died
&& handler
->pid
> 0) {
2019 ERROR("Child process is not killed");
2023 status
= lxc_wait_for_pid_status(handler
->pid
);
2025 SYSERROR("Failed to retrieve status for %d", handler
->pid
);
2027 /* If the child process exited but was not signaled, it didn't call
2028 * reboot. This should mean it was an lxc-execute which simply exited.
2029 * In any case, treat it as a 'halt'.
2031 if (WIFSIGNALED(status
)) {
2032 switch(WTERMSIG(status
)) {
2033 case SIGINT
: /* halt */
2034 DEBUG("Container \"%s\" is halting", name
);
2036 case SIGHUP
: /* reboot */
2037 DEBUG("Container \"%s\" is rebooting", name
);
2038 handler
->conf
->reboot
= REBOOT_REQ
;
2040 case SIGSYS
: /* seccomp */
2041 DEBUG("Container \"%s\" violated its seccomp policy", name
);
2044 DEBUG("Unknown exit status for container \"%s\" init %d", name
, WTERMSIG(status
));
2049 ret
= lxc_restore_phys_nics_to_netns(handler
);
2051 ERROR("Failed to move physical network devices back to parent "
2052 "network namespace");
2054 if (handler
->pinfd
>= 0) {
2055 close(handler
->pinfd
);
2056 handler
->pinfd
= -1;
2059 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
2060 lxc_error_set_and_log(handler
->pid
, status
);
2062 *error_num
= handler
->exit_status
;
2065 lxc_delete_network(handler
);
2067 out_detach_blockdev
:
2068 detach_block_device(handler
->conf
);
2071 lxc_fini(name
, handler
);
2075 lxc_abort(name
, handler
);
2083 static int start(struct lxc_handler
*handler
, void* data
)
2085 struct start_args
*arg
= data
;
2087 NOTICE("Exec'ing \"%s\"", arg
->argv
[0]);
2089 execvp(arg
->argv
[0], arg
->argv
);
2090 SYSERROR("Failed to exec \"%s\"", arg
->argv
[0]);
2094 static int post_start(struct lxc_handler
*handler
, void* data
)
2096 struct start_args
*arg
= data
;
2098 NOTICE("Started \"%s\" with pid \"%d\"", arg
->argv
[0], handler
->pid
);
2102 static struct lxc_operations start_ops
= {
2104 .post_start
= post_start
2107 int lxc_start(const char *name
, char *const argv
[], struct lxc_handler
*handler
,
2108 const char *lxcpath
, bool daemonize
, int *error_num
)
2110 struct start_args start_arg
= {
2114 TRACE("Doing lxc_start");
2115 return __lxc_start(name
, handler
, &start_ops
, &start_arg
, lxcpath
, daemonize
, error_num
);
2118 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
2121 char destroy
[MAXPATHLEN
];
2122 struct lxc_container
*c
;
2126 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
2127 bret
= do_destroy_container(handler
);
2129 ERROR("Error destroying rootfs for container \"%s\"", name
);
2133 INFO("Destroyed rootfs for container \"%s\"", name
);
2135 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
2136 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2137 ERROR("Error destroying directory for container \"%s\"", name
);
2141 c
= lxc_container_new(name
, handler
->lxcpath
);
2143 if (container_disk_lock(c
)) {
2144 INFO("Could not update lxc_snapshots file");
2145 lxc_container_put(c
);
2147 mod_all_rdeps(c
, false);
2148 container_disk_unlock(c
);
2149 lxc_container_put(c
);
2153 if (!handler
->am_root
)
2154 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
2155 destroy
, "lxc_rmdir_onedev_wrapper");
2157 ret
= lxc_rmdir_onedev(destroy
, NULL
);
2160 ERROR("Error destroying directory for container \"%s\"", name
);
2163 INFO("Destroyed directory for container \"%s\"", name
);
2166 static int lxc_rmdir_onedev_wrapper(void *data
)
2168 char *arg
= (char *) data
;
2169 return lxc_rmdir_onedev(arg
, NULL
);
2172 static bool do_destroy_container(struct lxc_handler
*handler
)
2176 if (!handler
->am_root
) {
2177 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
2178 handler
->conf
, "storage_destroy_wrapper");
2185 return storage_destroy(handler
->conf
);