]>
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>
52 #include <sys/capability.h>
55 #if !HAVE_DECL_PR_CAPBSET_DROP
56 #define PR_CAPBSET_DROP 24
59 #if !HAVE_DECL_PR_SET_NO_NEW_PRIVS
60 #define PR_SET_NO_NEW_PRIVS 38
63 #if !HAVE_DECL_PR_GET_NO_NEW_PRIVS
64 #define PR_GET_NO_NEW_PRIVS 39
71 #include "commands_utils.h"
73 #include "confile_utils.h"
78 #include "lxccontainer.h"
80 #include "lxcseccomp.h"
83 #include "namespace.h"
89 #include "storage/storage.h"
90 #include "storage/storage_utils.h"
92 lxc_log_define(lxc_start
, lxc
);
94 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
95 static bool do_destroy_container(struct lxc_handler
*handler
);
96 static int lxc_rmdir_onedev_wrapper(void *data
);
97 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
100 static void print_top_failing_dir(const char *path
)
104 char *copy
, *e
, *p
, saved
;
107 copy
= alloca(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 close_ns(int ns_fd
[LXC_NS_MAX
])
136 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
144 /* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
146 * Return true on success, false on failure.
148 static bool preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
)
152 for (i
= 0; i
< LXC_NS_MAX
; i
++)
155 ret
= lxc_preserve_ns(pid
, "");
157 SYSERROR("Kernel does not support attaching to namespaces.");
163 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
164 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
167 ns_fd
[i
] = lxc_preserve_ns(pid
, ns_info
[i
].proc_name
);
171 DEBUG("Preserved %s namespace via fd %d", ns_info
[i
].proc_name
, ns_fd
[i
]);
178 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info
[i
].proc_name
);
180 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info
[i
].proc_name
, strerror(errno
));
185 static int match_fd(int fd
)
187 return (fd
== 0 || fd
== 1 || fd
== 2);
190 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
191 int *fds_to_ignore
, size_t len_fds
)
193 struct dirent
*direntp
;
198 if (conf
&& conf
->close_all_fds
)
202 dir
= opendir("/proc/self/fd");
204 WARN("Failed to open directory: %s.", strerror(errno
));
210 while ((direntp
= readdir(dir
))) {
211 struct lxc_list
*cur
;
212 bool matched
= false;
214 if (!strcmp(direntp
->d_name
, "."))
217 if (!strcmp(direntp
->d_name
, ".."))
220 if (lxc_safe_int(direntp
->d_name
, &fd
) < 0) {
221 INFO("Could not parse file descriptor for: %s", direntp
->d_name
);
225 for (i
= 0; i
< len_fds
; i
++)
226 if (fds_to_ignore
[i
] == fd
)
229 if (fd
== fddir
|| fd
== lxc_log_fd
||
230 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
233 /* Keep state clients that wait on reboots. */
235 lxc_list_for_each(cur
, &conf
->state_clients
) {
236 struct lxc_state_client
*client
= cur
->elem
;
238 if (client
->clientfd
!= fd
)
249 if (current_config
&& fd
== current_config
->logfd
)
258 INFO("Closed inherited fd %d", fd
);
261 WARN("Inherited fd %d", fd
);
264 /* Only enable syslog at this point to avoid the above logging function
265 * to open a new fd and make the check_inherited function enter an
268 lxc_log_enable_syslog();
270 closedir(dir
); /* cannot fail */
274 static int setup_signal_fd(sigset_t
*oldmask
)
278 int signals
[] = {SIGBUS
, SIGILL
, SIGSEGV
, SIGWINCH
};
280 /* Block everything except serious error signals. */
281 ret
= sigfillset(&mask
);
285 for (sig
= 0; sig
< (sizeof(signals
) / sizeof(signals
[0])); sig
++) {
286 ret
= sigdelset(&mask
, signals
[sig
]);
291 ret
= sigprocmask(SIG_BLOCK
, &mask
, oldmask
);
293 SYSERROR("Failed to set signal mask");
297 ret
= signalfd(-1, &mask
, SFD_CLOEXEC
);
299 SYSERROR("Failed to create signal file descriptor");
303 TRACE("Created signal file descriptor %d", ret
);
308 static int signal_handler(int fd
, uint32_t events
, void *data
,
309 struct lxc_epoll_descr
*descr
)
313 struct signalfd_siginfo siginfo
;
314 struct lxc_handler
*hdlr
= data
;
316 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
318 ERROR("Failed to read signal info from signal file descriptor: %d.", fd
);
322 if (ret
!= sizeof(siginfo
)) {
323 ERROR("Unexpected size for siginfo struct.");
327 /* Check whether init is running. */
329 ret
= waitid(P_PID
, hdlr
->pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
330 if (ret
== 0 && info
.si_pid
== hdlr
->pid
)
331 hdlr
->init_died
= true;
333 /* Try to figure out a reasonable exit status to report. */
334 if (hdlr
->init_died
) {
335 switch (info
.si_code
) {
337 hdlr
->exit_status
= info
.si_status
<< 8;
342 hdlr
->exit_status
= info
.si_status
<< 8 | 0x7f;
345 /* Huh? The waitid() told us it's dead *and* continued? */
346 WARN("Init %d dead and continued?", hdlr
->pid
);
347 hdlr
->exit_status
= 1;
350 ERROR("Unknown si_code: %d", hdlr
->init_died
);
351 hdlr
->exit_status
= 1;
355 if (siginfo
.ssi_signo
== SIGHUP
) {
356 kill(hdlr
->pid
, SIGTERM
);
357 INFO("Killing %d since terminal hung up", hdlr
->pid
);
358 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
: 0;
361 /* More robustness, protect ourself from a SIGCHLD sent
362 * by a process different from the container init.
364 if (siginfo
.ssi_pid
!= hdlr
->pid
) {
365 NOTICE("Received %d from pid %d instead of container init %d.", siginfo
.ssi_signo
, siginfo
.ssi_pid
, hdlr
->pid
);
366 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
: 0;
369 if (siginfo
.ssi_signo
!= SIGCHLD
) {
370 kill(hdlr
->pid
, siginfo
.ssi_signo
);
371 INFO("Forwarded signal %d to pid %d.", siginfo
.ssi_signo
, hdlr
->pid
);
372 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
: 0;
375 if (siginfo
.ssi_code
== CLD_STOPPED
) {
376 INFO("Container init process was stopped.");
377 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
: 0;
378 } else if (siginfo
.ssi_code
== CLD_CONTINUED
) {
379 INFO("Container init process was continued.");
380 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
: 0;
383 DEBUG("Container init process %d exited.", hdlr
->pid
);
384 return LXC_MAINLOOP_CLOSE
;
387 int lxc_serve_state_clients(const char *name
, struct lxc_handler
*handler
,
391 struct lxc_list
*cur
, *next
;
392 struct lxc_state_client
*client
;
393 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
397 handler
->state
= RUNNING
;
399 handler
->state
= state
;
401 TRACE("Set container state to %s", lxc_state2str(state
));
403 if (lxc_list_empty(&handler
->conf
->state_clients
)) {
404 TRACE("No state clients registered");
409 strncpy(msg
.name
, name
, sizeof(msg
.name
));
410 msg
.name
[sizeof(msg
.name
) - 1] = 0;
412 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
415 if (client
->states
[state
] == 0) {
416 TRACE("State %s not registered for state client %d",
417 lxc_state2str(state
), client
->clientfd
);
421 TRACE("Sending state %s to state client %d",
422 lxc_state2str(state
), client
->clientfd
);
425 ret
= send(client
->clientfd
, &msg
, sizeof(msg
), 0);
427 if (errno
== EINTR
) {
428 TRACE("Caught EINTR; retrying");
432 ERROR("%s - Failed to send message to client",
436 /* kick client from list */
438 close(client
->clientfd
);
447 static int lxc_serve_state_socket_pair(const char *name
,
448 struct lxc_handler
*handler
,
453 if (!handler
->backgrounded
||
454 handler
->state_socket_pair
[1] < 0 ||
458 /* Close read end of the socket pair. */
459 close(handler
->state_socket_pair
[0]);
460 handler
->state_socket_pair
[0] = -1;
463 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
464 &(int){state
}, sizeof(int));
465 if (ret
!= sizeof(int)) {
468 SYSERROR("Failed to send state to %d",
469 handler
->state_socket_pair
[1]);
473 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
474 handler
->state_socket_pair
[1]);
476 /* Close write end of the socket pair. */
477 close(handler
->state_socket_pair
[1]);
478 handler
->state_socket_pair
[1] = -1;
483 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
488 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
490 ERROR("Failed to synchronize via anonymous pair of unix sockets");
494 ret
= lxc_serve_state_clients(name
, handler
, state
);
498 /* This function will try to connect to the legacy lxc-monitord state
499 * server and only exists for backwards compatibility.
501 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
506 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
509 bool has_console
= true;
510 struct lxc_epoll_descr descr
, descr_console
;
512 if (handler
->conf
->console
.path
&& !strcmp(handler
->conf
->console
.path
, "none"))
515 ret
= lxc_mainloop_open(&descr
);
517 ERROR("Failed to create mainloop");
522 ret
= lxc_mainloop_open(&descr_console
);
524 ERROR("Failed to create console mainloop");
529 ret
= lxc_mainloop_add_handler(&descr
, handler
->sigfd
, signal_handler
, handler
);
531 ERROR("Failed to add signal handler for %d to mainloop", handler
->sigfd
);
532 goto out_mainloop_console
;
536 struct lxc_console
*console
= &handler
->conf
->console
;
538 ret
= lxc_console_mainloop_add(&descr
, console
);
540 ERROR("Failed to add console handlers to mainloop");
541 goto out_mainloop_console
;
544 ret
= lxc_console_mainloop_add(&descr_console
, console
);
546 ERROR("Failed to add console handlers to console mainloop");
547 goto out_mainloop_console
;
550 handler
->conf
->console
.descr
= &descr
;
553 ret
= lxc_cmd_mainloop_add(name
, &descr
, handler
);
555 ERROR("Failed to add command handler to mainloop");
556 goto out_mainloop_console
;
559 TRACE("Mainloop is ready");
561 ret
= lxc_mainloop(&descr
, -1);
564 if (ret
< 0 || !handler
->init_died
)
565 goto out_mainloop_console
;
568 ret
= lxc_mainloop(&descr_console
, 0);
570 out_mainloop_console
:
572 lxc_mainloop_close(&descr_console
);
573 TRACE("Closed console mainloop");
577 lxc_mainloop_close(&descr
);
578 TRACE("Closed mainloop");
581 close(handler
->sigfd
);
582 TRACE("Closed signal file descriptor %d", handler
->sigfd
);
583 handler
->sigfd
= -EBADF
;
588 void lxc_zero_handler(struct lxc_handler
*handler
)
592 memset(handler
, 0, sizeof(struct lxc_handler
));
594 handler
->clone_flags
= -1;
600 for (i
= 0; i
< LXC_NS_MAX
; i
++)
601 handler
->nsfd
[i
] = -1;
603 handler
->data_sock
[0] = -1;
604 handler
->data_sock
[1] = -1;
606 handler
->state_socket_pair
[0] = -1;
607 handler
->state_socket_pair
[1] = -1;
609 handler
->sync_sock
[0] = -1;
610 handler
->sync_sock
[1] = -1;
613 static void lxc_put_nsfds(struct lxc_handler
*handler
)
617 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
618 if (handler
->nsfd
[i
] < 0)
621 close(handler
->nsfd
[i
]);
622 handler
->nsfd
[i
] = -EBADF
;
626 void lxc_free_handler(struct lxc_handler
*handler
)
628 if (handler
->pinfd
>= 0)
629 close(handler
->pinfd
);
631 if (handler
->sigfd
>= 0)
632 close(handler
->sigfd
);
634 lxc_put_nsfds(handler
);
636 if (handler
->conf
&& handler
->conf
->reboot
== 0)
637 if (handler
->conf
->maincmd_fd
>= 0)
638 close(handler
->conf
->maincmd_fd
);
640 if (handler
->state_socket_pair
[0] >= 0)
641 close(handler
->state_socket_pair
[0]);
643 if (handler
->state_socket_pair
[1] >= 0)
644 close(handler
->state_socket_pair
[1]);
646 handler
->conf
= NULL
;
651 struct lxc_handler
*lxc_init_handler(const char *name
, struct lxc_conf
*conf
,
652 const char *lxcpath
, bool daemonize
)
655 struct lxc_handler
*handler
;
657 handler
= malloc(sizeof(*handler
));
659 ERROR("failed to allocate memory");
663 memset(handler
, 0, sizeof(*handler
));
665 /* Note that am_guest_unpriv() checks the effective uid. We probably don't
666 * care if we are real root only if we are running as root so this
669 handler
->am_root
= !am_guest_unpriv();
670 handler
->data_sock
[0] = handler
->data_sock
[1] = -1;
671 handler
->conf
= conf
;
672 handler
->lxcpath
= lxcpath
;
674 handler
->sigfd
= -EBADF
;
675 handler
->init_died
= false;
676 handler
->state_socket_pair
[0] = handler
->state_socket_pair
[1] = -1;
677 if (handler
->conf
->reboot
== 0)
678 lxc_list_init(&handler
->conf
->state_clients
);
680 for (i
= 0; i
< LXC_NS_MAX
; i
++)
681 handler
->nsfd
[i
] = -1;
683 handler
->name
= name
;
685 if (daemonize
&& !handler
->conf
->reboot
) {
686 /* Create socketpair() to synchronize on daemonized startup.
687 * When the container reboots we don't need to synchronize again
688 * currently so don't open another socketpair().
690 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
691 handler
->state_socket_pair
);
693 ERROR("Failed to create anonymous pair of unix sockets");
696 TRACE("Created anonymous pair {%d,%d} of unix sockets",
697 handler
->state_socket_pair
[0],
698 handler
->state_socket_pair
[1]);
701 if (handler
->conf
->reboot
== 0) {
702 handler
->conf
->maincmd_fd
= lxc_cmd_init(name
, lxcpath
, "command");
703 if (handler
->conf
->maincmd_fd
< 0) {
704 ERROR("Failed to set up command socket");
708 TRACE("Unix domain socket %d for command server is ready",
709 handler
->conf
->maincmd_fd
);
714 lxc_free_handler(handler
);
719 int lxc_init(const char *name
, struct lxc_handler
*handler
)
722 const char *loglevel
;
723 struct lxc_conf
*conf
= handler
->conf
;
726 TRACE("initialized LSM");
728 if (lxc_read_seccomp_config(conf
) != 0) {
729 ERROR("Failed loading seccomp policy.");
730 goto out_close_maincmd_fd
;
732 TRACE("read seccomp policy");
734 /* Begin by setting the state to STARTING. */
735 if (lxc_set_state(name
, handler
, STARTING
)) {
736 ERROR("Failed to set state for container \"%s\" to \"%s\".", name
, lxc_state2str(STARTING
));
737 goto out_close_maincmd_fd
;
739 TRACE("set container state to \"STARTING\"");
741 /* Start of environment variable setup for hooks. */
742 if (name
&& setenv("LXC_NAME", name
, 1))
743 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name
);
745 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
746 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf
->rcfile
);
748 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
749 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf
->rootfs
.mount
);
751 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
752 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf
->rootfs
.path
);
754 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
755 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf
->console
.path
);
757 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
758 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf
->console
.log_path
);
760 if (setenv("LXC_CGNS_AWARE", "1", 1))
761 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
763 loglevel
= lxc_log_priority_to_string(lxc_log_get_level());
764 if (setenv("LXC_LOG_LEVEL", loglevel
, 1))
765 SYSERROR("Failed to set environment variable LXC_LOG_LEVEL=%s", loglevel
);
767 if (conf
->hooks_version
== 0)
768 ret
= setenv("LXC_HOOK_VERSION", "0", 1);
770 ret
= setenv("LXC_HOOK_VERSION", "1", 1);
772 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf
->hooks_version
);
773 /* End of environment variable setup for hooks. */
775 TRACE("set environment variables");
777 if (run_lxc_hooks(name
, "pre-start", conf
, NULL
)) {
778 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name
);
781 TRACE("ran pre-start hooks");
783 /* The signal fd has to be created before forking otherwise if the child
784 * process exits before we setup the signal fd, the event will be lost
785 * and the command will be stuck.
787 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
788 if (handler
->sigfd
< 0) {
789 ERROR("Failed to setup SIGCHLD fd handler.");
792 TRACE("set up signal fd");
794 /* Do this after setting up signals since it might unblock SIGWINCH. */
795 ret
= lxc_console_create(conf
);
797 ERROR("Failed to create console");
798 goto out_restore_sigmask
;
800 TRACE("Created console");
802 ret
= lxc_pty_map_ids(conf
, &conf
->console
);
804 ERROR("Failed to shift tty into container.");
805 goto out_restore_sigmask
;
807 TRACE("shifted tty ids");
809 INFO("container \"%s\" is initialized", name
);
813 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
815 lxc_delete_tty(&conf
->tty_info
);
817 lxc_set_state(name
, handler
, ABORTING
);
818 out_close_maincmd_fd
:
819 close(conf
->maincmd_fd
);
820 conf
->maincmd_fd
= -1;
824 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
828 struct lxc_list
*cur
, *next
;
829 char *namespaces
[LXC_NS_MAX
+ 1];
830 size_t namespace_count
= 0;
832 /* The STOPPING state is there for future cleanup code which can take
835 lxc_set_state(name
, handler
, STOPPING
);
837 self
= lxc_raw_getpid();
838 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
839 if (handler
->nsfd
[i
] < 0)
842 if (handler
->conf
->hooks_version
== 0)
843 rc
= asprintf(&namespaces
[namespace_count
],
844 "%s:/proc/%d/fd/%d", ns_info
[i
].proc_name
,
845 self
, handler
->nsfd
[i
]);
847 rc
= asprintf(&namespaces
[namespace_count
],
848 "/proc/%d/fd/%d", self
, handler
->nsfd
[i
]);
850 SYSERROR("Failed to allocate memory.");
854 if (handler
->conf
->hooks_version
== 0) {
859 rc
= setenv(ns_info
[i
].env_name
, namespaces
[namespace_count
], 1);
861 SYSERROR("Failed to set environment variable %s=%s",
862 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
864 TRACE("Set environment variable %s=%s",
865 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
869 namespaces
[namespace_count
] = NULL
;
871 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1))
872 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
874 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1))
875 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
877 if (handler
->conf
->hooks_version
== 0)
878 rc
= run_lxc_hooks(name
, "stop", handler
->conf
, namespaces
);
880 rc
= run_lxc_hooks(name
, "stop", handler
->conf
, NULL
);
882 while (namespace_count
--)
883 free(namespaces
[namespace_count
]);
885 cgroup_destroy(handler
);
887 if (handler
->conf
->reboot
== 0) {
888 /* For all new state clients simply close the command socket.
889 * This will inform all state clients that the container is
890 * STOPPED and also prevents a race between a open()/close() on
891 * the command socket causing a new process to get ECONNREFUSED
892 * because we haven't yet closed the command socket.
894 close(handler
->conf
->maincmd_fd
);
895 handler
->conf
->maincmd_fd
= -1;
896 TRACE("Closed command socket");
898 /* This function will try to connect to the legacy lxc-monitord
899 * state server and only exists for backwards compatibility.
901 lxc_monitor_send_state(name
, STOPPED
, handler
->lxcpath
);
903 /* The command socket is closed so no one can acces the command
904 * socket anymore so there's no need to lock it.
906 handler
->state
= STOPPED
;
907 TRACE("Set container state to \"STOPPED\"");
909 lxc_set_state(name
, handler
, STOPPED
);
912 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, NULL
)) {
913 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name
);
914 if (handler
->conf
->reboot
) {
915 WARN("Container will be stopped instead of rebooted.");
916 handler
->conf
->reboot
= 0;
917 if (setenv("LXC_TARGET", "stop", 1))
918 WARN("Failed to set environment variable: LXC_TARGET=stop.");
922 /* Reset mask set by setup_signal_fd. */
923 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
924 WARN("Failed to restore signal mask.");
926 lxc_console_delete(&handler
->conf
->console
);
927 lxc_delete_tty(&handler
->conf
->tty_info
);
929 /* The command socket is now closed, no more state clients can register
930 * themselves from now on. So free the list of state clients.
932 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
933 struct lxc_state_client
*client
= cur
->elem
;
935 /* Keep state clients that want to be notified about reboots. */
936 if ((handler
->conf
->reboot
> 0) && (client
->states
[RUNNING
] == 2))
939 /* close state client socket */
940 close(client
->clientfd
);
946 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1)
947 lxc_destroy_container_on_signal(handler
, name
);
949 lxc_free_handler(handler
);
952 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
956 lxc_set_state(name
, handler
, ABORTING
);
957 if (handler
->pid
> 0)
958 kill(handler
->pid
, SIGKILL
);
959 while ((ret
= waitpid(-1, &status
, 0)) > 0) {
964 static int lxc_set_death_signal(int signal
)
969 ret
= prctl(PR_SET_PDEATHSIG
, signal
, 0, 0, 0);
971 /* Check whether we have been orphaned. */
972 ppid
= (pid_t
)syscall(SYS_getppid
);
976 self
= lxc_raw_getpid();
977 ret
= kill(self
, SIGKILL
);
983 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal
);
990 static int do_start(void *data
)
993 struct lxc_list
*iterator
;
995 struct lxc_handler
*handler
= data
;
996 bool have_cap_setgid
;
1001 lxc_sync_fini_parent(handler
);
1003 /* This prctl must be before the synchro, so if the parent dies before
1004 * we set the parent death signal, we will detect its death with the
1005 * synchro right after, otherwise we have a window where the parent can
1006 * exit before we set the pdeath signal leading to a unsupervized
1009 ret
= lxc_set_death_signal(SIGKILL
);
1011 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1012 goto out_warn_father
;
1015 ret
= sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1017 SYSERROR("Failed to set signal mask");
1018 goto out_warn_father
;
1021 /* Don't leak the pinfd to the container. */
1022 if (handler
->pinfd
>= 0)
1023 close(handler
->pinfd
);
1025 ret
= lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
);
1027 goto out_warn_father
;
1029 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1030 * https://github.com/lxc/lxd/issues/1978.
1032 if ((handler
->clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
1033 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
1034 ret
= unshare(CLONE_NEWNET
);
1036 SYSERROR("Failed to unshare CLONE_NEWNET.");
1037 goto out_warn_father
;
1039 INFO("Unshared CLONE_NEWNET.");
1042 /* Tell the parent task it can begin to configure the container and wait
1045 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
1048 if (lxc_network_recv_veth_names_from_parent(handler
) < 0) {
1049 ERROR("Failed to receive veth names from parent");
1050 goto out_warn_father
;
1053 /* If we are in a new user namespace, become root there to have
1054 * privilege over our namespace.
1056 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1057 uid_t nsuid
= (handler
->conf
->root_nsuid_map
!= NULL
)
1059 : handler
->conf
->init_uid
;
1060 gid_t nsgid
= (handler
->conf
->root_nsgid_map
!= NULL
)
1062 : handler
->conf
->init_gid
;
1064 ret
= lxc_switch_uid_gid(nsuid
, nsgid
);
1066 goto out_warn_father
;
1068 /* Drop groups only after we switched to a valid gid in the new
1071 ret
= lxc_setgroups(0, NULL
);
1072 if (ret
< 0 && (handler
->am_root
|| errno
!= EPERM
))
1073 goto out_warn_father
;
1075 if (!handler
->am_root
) {
1076 ret
= prctl(PR_SET_DUMPABLE
, 1, 0, 0, 0);
1078 goto out_warn_father
;
1081 /* set{g,u}id() clears deathsignal */
1082 ret
= lxc_set_death_signal(SIGKILL
);
1084 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1085 goto out_warn_father
;
1089 if (access(handler
->lxcpath
, X_OK
)) {
1090 print_top_failing_dir(handler
->lxcpath
);
1091 goto out_warn_father
;
1094 ret
= snprintf(path
, sizeof(path
), "%s/dev/null", handler
->conf
->rootfs
.mount
);
1095 if (ret
< 0 || ret
>= sizeof(path
))
1096 goto out_warn_father
;
1098 /* In order to checkpoint restore, we need to have everything in the
1099 * same mount namespace. However, some containers may not have a
1100 * reasonable /dev (in particular, they may not have /dev/null), so we
1101 * can't set init's std fds to /dev/null by opening it from inside the
1104 * If that's the case, fall back to using the host's /dev/null. This
1105 * means that migration won't work, but at least we won't spew output
1106 * where it isn't wanted.
1108 if (handler
->backgrounded
&& !handler
->conf
->autodev
&& access(path
, F_OK
) < 0) {
1109 devnull_fd
= open_devnull();
1112 goto out_warn_father
;
1113 WARN("Using /dev/null from the host for container init's "
1114 "standard file descriptors. Migration will not work.");
1117 /* Ask father to setup cgroups and wait for him to finish. */
1118 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
1121 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1122 * earlier we end up with a wrong view of /proc/self/cgroup. For
1123 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1124 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1125 * /proc/self/cgroup would show us:
1129 * whereas it should actually show
1133 if (handler
->clone_flags
& CLONE_NEWCGROUP
) {
1134 if (unshare(CLONE_NEWCGROUP
) < 0) {
1135 INFO("Failed to unshare CLONE_NEWCGROUP.");
1136 goto out_warn_father
;
1138 INFO("Unshared CLONE_NEWCGROUP.");
1141 /* Add the requested environment variables to the current environment to
1142 * allow them to be used by the various hooks, such as the start hook
1145 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1146 if (putenv((char *)iterator
->elem
)) {
1147 SYSERROR("Failed to set environment variable: %s.", (char *)iterator
->elem
);
1148 goto out_warn_father
;
1152 /* Setup the container, ip, names, utsname, ... */
1153 ret
= lxc_setup(handler
);
1154 close(handler
->data_sock
[1]);
1155 close(handler
->data_sock
[0]);
1157 ERROR("Failed to setup container \"%s\".", handler
->name
);
1158 goto out_warn_father
;
1161 /* Set the label to change to when we exec(2) the container's init. */
1162 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
1163 goto out_warn_father
;
1165 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1166 * before we aren't allowed anymore.
1168 if (handler
->conf
->no_new_privs
) {
1169 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
1170 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
1171 goto out_warn_father
;
1173 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
1176 /* Some init's such as busybox will set sane tty settings on stdin,
1177 * stdout, stderr which it thinks is the console. We already set them
1178 * the way we wanted on the real terminal, and we want init to do its
1179 * setup on its console ie. the pty allocated in lxc_console_create() so
1180 * make sure that that pty is stdin,stdout,stderr.
1182 if (handler
->conf
->console
.slave
>= 0) {
1183 if (handler
->backgrounded
|| handler
->conf
->is_execute
== 0)
1184 ret
= set_stdfds(handler
->conf
->console
.slave
);
1186 ret
= lxc_console_set_stdfds(handler
->conf
->console
.slave
);
1188 ERROR("Failed to redirect std{in,out,err} to pty file "
1190 handler
->conf
->console
.slave
);
1191 goto out_warn_father
;
1195 /* If we mounted a temporary proc, then unmount it now. */
1196 tmp_proc_unmount(handler
->conf
);
1198 if (lxc_seccomp_load(handler
->conf
) != 0)
1199 goto out_warn_father
;
1201 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, NULL
)) {
1202 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler
->name
);
1203 goto out_warn_father
;
1206 close(handler
->sigfd
);
1208 if (devnull_fd
< 0) {
1209 devnull_fd
= open_devnull();
1212 goto out_warn_father
;
1215 if (handler
->conf
->console
.slave
< 0 && handler
->backgrounded
)
1216 if (set_stdfds(devnull_fd
) < 0) {
1217 ERROR("Failed to redirect std{in,out,err} to "
1219 goto out_warn_father
;
1222 if (devnull_fd
>= 0) {
1229 if (handler
->conf
->init_cwd
&& chdir(handler
->conf
->init_cwd
)) {
1230 SYSERROR("Could not change directory to \"%s\"", handler
->conf
->init_cwd
);
1231 goto out_warn_father
;
1234 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
))
1235 goto out_warn_father
;
1237 /* Reset the environment variables the user requested in a clear
1241 SYSERROR("Failed to clear environment.");
1242 /* Don't error out though. */
1245 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1246 if (putenv((char *)iterator
->elem
)) {
1247 SYSERROR("Failed to set environment variable: %s.", (char *)iterator
->elem
);
1248 goto out_warn_father
;
1252 if (putenv("container=lxc")) {
1253 SYSERROR("Failed to set environment variable: container=lxc.");
1254 goto out_warn_father
;
1257 if (handler
->conf
->pty_names
) {
1258 if (putenv(handler
->conf
->pty_names
)) {
1259 SYSERROR("Failed to set environment variable for container ptys.");
1260 goto out_warn_father
;
1264 /* The container has been setup. We can now switch to an unprivileged
1267 new_uid
= handler
->conf
->init_uid
;
1268 new_gid
= handler
->conf
->init_gid
;
1270 /* If we are in a new user namespace we already dropped all
1271 * groups when we switched to root in the new user namespace
1272 * further above. Only drop groups if we can, so ensure that we
1273 * have necessary privilege.
1276 have_cap_setgid
= lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
);
1278 have_cap_setgid
= false;
1280 if (lxc_list_empty(&handler
->conf
->id_map
) && have_cap_setgid
) {
1281 if (lxc_setgroups(0, NULL
) < 0)
1282 goto out_warn_father
;
1285 if (lxc_switch_uid_gid(new_uid
, new_gid
) < 0)
1286 goto out_warn_father
;
1288 /* After this call, we are in error because this ops should not return
1291 handler
->ops
->start(handler
, handler
->data
);
1294 /* We want the parent to know something went wrong, so we return a
1295 * special error code.
1297 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1300 if (devnull_fd
>= 0)
1306 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1309 struct lxc_pty_info
*pty_info
;
1311 int sock
= handler
->data_sock
[1];
1312 struct lxc_conf
*conf
= handler
->conf
;
1313 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
1318 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
) * conf
->tty
);
1319 if (!tty_info
->pty_info
)
1322 for (i
= 0; i
< conf
->tty
; i
++) {
1325 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1329 pty_info
= &tty_info
->pty_info
[i
];
1331 pty_info
->master
= ttyfds
[0];
1332 pty_info
->slave
= ttyfds
[1];
1333 TRACE("Received pty with master fd %d and slave fd %d from "
1334 "parent", pty_info
->master
, pty_info
->slave
);
1337 ERROR("Failed to receive %d ttys from child: %s", conf
->tty
,
1340 TRACE("Received %d ttys from child", conf
->tty
);
1342 tty_info
->nbtty
= conf
->tty
;
1347 int resolve_clone_flags(struct lxc_handler
*handler
)
1350 struct lxc_conf
*conf
= handler
->conf
;
1352 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1353 if (conf
->ns_keep
!= 0) {
1354 if ((conf
->ns_keep
& ns_info
[i
].clone_flag
) == 0)
1355 handler
->clone_flags
|= ns_info
[i
].clone_flag
;
1356 } else if (conf
->ns_clone
!= 0) {
1357 if ((conf
->ns_clone
& ns_info
[i
].clone_flag
) > 0)
1358 handler
->clone_flags
|= ns_info
[i
].clone_flag
;
1360 if (i
== LXC_NS_USER
&& lxc_list_empty(&handler
->conf
->id_map
))
1363 if (i
== LXC_NS_NET
&& lxc_requests_empty_network(handler
))
1366 if (i
== LXC_NS_CGROUP
&& !cgns_supported())
1369 handler
->clone_flags
|= ns_info
[i
].clone_flag
;
1372 if (!conf
->ns_share
[i
])
1375 handler
->clone_flags
&= ~ns_info
[i
].clone_flag
;
1376 TRACE("Sharing %s namespace", ns_info
[i
].proc_name
);
1382 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1383 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1384 * But since the memory between parent and child is shared on CLONE_VM this
1385 * would invalidate the getpid() cache that glibc used to maintain and so
1386 * getpid() in the child would return the parent's pid. This is all fixed in
1387 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1388 * not reset anymore.
1389 * However, if for whatever reason you - dear commiter - somehow need to get the
1390 * pid of the dummy intermediate process for do_share_ns() you need to call
1391 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1394 static inline int do_share_ns(void *arg
)
1397 struct lxc_handler
*handler
= arg
;
1399 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1400 if (handler
->nsfd
[i
] < 0)
1403 ret
= setns(handler
->nsfd
[i
], 0);
1407 DEBUG("Inherited %s namespace", ns_info
[i
].proc_name
);
1410 flags
= handler
->on_clone_flags
;
1411 flags
|= CLONE_PARENT
;
1412 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, flags
);
1413 if (handler
->pid
< 0)
1419 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1420 * exec()s the requested container binary.
1421 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1422 * right here should be double checked if they'd pose a security risk. (For
1423 * example, any {u}mount() operations performed here will be reflected on the
1426 static int lxc_spawn(struct lxc_handler
*handler
)
1430 bool wants_to_map_ids
;
1431 struct lxc_list
*id_map
;
1432 const char *name
= handler
->name
;
1433 const char *lxcpath
= handler
->lxcpath
;
1434 bool cgroups_connected
= false, share_ns
= false;
1435 struct lxc_conf
*conf
= handler
->conf
;
1437 id_map
= &conf
->id_map
;
1438 wants_to_map_ids
= !lxc_list_empty(id_map
);
1440 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1441 if (!conf
->ns_share
[i
])
1444 handler
->nsfd
[i
] = lxc_inherit_namespace(conf
->ns_share
[i
], lxcpath
, ns_info
[i
].proc_name
);
1445 if (handler
->nsfd
[i
] < 0)
1451 if (lxc_sync_init(handler
))
1454 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1455 handler
->data_sock
);
1457 lxc_sync_fini(handler
);
1461 ret
= resolve_clone_flags(handler
);
1463 lxc_sync_fini(handler
);
1467 if (handler
->clone_flags
& CLONE_NEWNET
) {
1468 if (!lxc_list_empty(&conf
->network
)) {
1470 /* Find gateway addresses from the link device, which is
1471 * no longer accessible inside the container. Do this
1472 * before creating network interfaces, since goto
1473 * out_delete_net does not work before lxc_clone.
1475 if (lxc_find_gateway_addresses(handler
)) {
1476 ERROR("Failed to find gateway addresses.");
1477 lxc_sync_fini(handler
);
1481 /* That should be done before the clone because we will
1482 * fill the netdev index and use them in the child.
1484 if (lxc_create_network_priv(handler
)) {
1485 ERROR("Failed to create the network.");
1486 lxc_sync_fini(handler
);
1492 if (!cgroup_init(handler
)) {
1493 ERROR("Failed initializing cgroup support.");
1494 goto out_delete_net
;
1497 cgroups_connected
= true;
1499 if (!cgroup_create(handler
)) {
1500 ERROR("Failed creating cgroups.");
1501 goto out_delete_net
;
1504 /* If the rootfs is not a blockdev, prevent the container from marking
1506 * If the container is unprivileged then skip rootfs pinning.
1508 if (!wants_to_map_ids
) {
1509 handler
->pinfd
= pin_rootfs(conf
->rootfs
.path
);
1510 if (handler
->pinfd
== -1)
1511 INFO("Failed to pin the rootfs for container \"%s\".", handler
->name
);
1514 /* Create a process in a new set of namespaces. */
1515 handler
->on_clone_flags
= handler
->clone_flags
;
1516 if (handler
->clone_flags
& CLONE_NEWUSER
) {
1517 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1518 * clone a new user namespace first and only later unshare our
1519 * network namespace to ensure that network devices ownership is
1522 handler
->on_clone_flags
&= ~CLONE_NEWNET
;
1524 /* The cgroup namespace gets unshare()ed not clone()ed. */
1525 handler
->on_clone_flags
&= ~CLONE_NEWCGROUP
;
1530 attacher_pid
= lxc_clone(do_share_ns
, handler
, CLONE_VFORK
| CLONE_VM
| CLONE_FILES
);
1531 if (attacher_pid
< 0) {
1532 SYSERROR(LXC_CLONE_ERROR
);
1533 goto out_delete_net
;
1536 ret
= wait_for_pid(attacher_pid
);
1538 SYSERROR("Intermediate process failed");
1539 goto out_delete_net
;
1542 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, handler
->on_clone_flags
);
1544 if (handler
->pid
< 0) {
1545 SYSERROR(LXC_CLONE_ERROR
);
1546 goto out_delete_net
;
1548 TRACE("Cloned child process %d", handler
->pid
);
1550 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1551 if (handler
->on_clone_flags
& ns_info
[i
].clone_flag
)
1552 INFO("Cloned %s", ns_info
[i
].flag_name
);
1554 if (!preserve_ns(handler
->nsfd
, handler
->on_clone_flags
, handler
->pid
)) {
1555 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1556 goto out_delete_net
;
1559 lxc_sync_fini_child(handler
);
1561 /* Map the container uids. The container became an invalid userid the
1562 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1563 * anything immediately, but allows the container to setuid(0) (0 being
1564 * mapped to something else on the host.) later to become a valid uid
1567 if (wants_to_map_ids
) {
1568 if (!handler
->conf
->ns_share
[LXC_NS_USER
] &&
1569 (handler
->conf
->ns_keep
& CLONE_NEWUSER
) == 0) {
1570 ret
= lxc_map_ids(id_map
, handler
->pid
);
1572 ERROR("Failed to set up id mapping.");
1573 goto out_delete_net
;
1578 if (lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
))
1579 goto out_delete_net
;
1581 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
))
1582 goto out_delete_net
;
1584 if (!cgroup_create_legacy(handler
)) {
1585 ERROR("Failed to setup legacy cgroups for container \"%s\".", name
);
1586 goto out_delete_net
;
1588 if (!cgroup_setup_limits(handler
, false)) {
1589 ERROR("Failed to setup cgroup limits for container \"%s\".", name
);
1590 goto out_delete_net
;
1593 if (!cgroup_enter(handler
))
1594 goto out_delete_net
;
1596 if (!cgroup_chown(handler
))
1597 goto out_delete_net
;
1599 /* Now we're ready to preserve the network namespace */
1600 ret
= lxc_preserve_ns(handler
->pid
, "net");
1602 ERROR("%s - Failed to preserve net namespace", strerror(errno
));
1603 goto out_delete_net
;
1605 handler
->nsfd
[LXC_NS_NET
] = ret
;
1606 DEBUG("Preserved net namespace via fd %d", ret
);
1608 /* Create the network configuration. */
1609 if (handler
->clone_flags
& CLONE_NEWNET
) {
1610 if (lxc_network_move_created_netdev_priv(handler
->lxcpath
,
1614 ERROR("Failed to create the configured network.");
1615 goto out_delete_net
;
1618 if (lxc_create_network_unpriv(handler
->lxcpath
, handler
->name
,
1621 ERROR("Failed to create the configured network.");
1622 goto out_delete_net
;
1626 if (lxc_network_send_veth_names_to_child(handler
) < 0) {
1627 ERROR("Failed to send veth names to child");
1628 goto out_delete_net
;
1631 if (!lxc_list_empty(&conf
->procs
)) {
1632 ret
= setup_proc_filesystem(&conf
->procs
, handler
->pid
);
1634 goto out_delete_net
;
1637 /* Tell the child to continue its initialization. We'll get
1638 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1640 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1641 goto out_delete_net
;
1643 if (!lxc_list_empty(&conf
->limits
) && setup_resource_limits(&conf
->limits
, handler
->pid
)) {
1644 ERROR("failed to setup resource limits for '%s'", name
);
1645 goto out_delete_net
;
1648 if (lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
))
1649 goto out_delete_net
;
1651 if (!cgroup_setup_limits(handler
, true)) {
1652 ERROR("Failed to setup the devices cgroup for container \"%s\".", name
);
1653 goto out_delete_net
;
1655 TRACE("Set up cgroup device limits");
1657 cgroup_disconnect();
1658 cgroups_connected
= false;
1660 if (handler
->clone_flags
& CLONE_NEWCGROUP
) {
1661 /* Now we're ready to preserve the cgroup namespace */
1662 ret
= lxc_preserve_ns(handler
->pid
, "cgroup");
1664 ERROR("%s - Failed to preserve cgroup namespace", strerror(errno
));
1665 goto out_delete_net
;
1667 handler
->nsfd
[LXC_NS_CGROUP
] = ret
;
1668 DEBUG("Preserved cgroup namespace via fd %d", ret
);
1671 ret
= snprintf(pidstr
, 20, "%d", handler
->pid
);
1672 if (ret
< 0 || ret
>= 20)
1673 goto out_delete_net
;
1675 if (setenv("LXC_PID", pidstr
, 1))
1676 SYSERROR("Failed to set environment variable: LXC_PID=%s.", pidstr
);
1678 /* Run any host-side start hooks */
1679 if (run_lxc_hooks(name
, "start-host", conf
, NULL
)) {
1680 ERROR("Failed to run lxc.hook.start-host for container \"%s\".", name
);
1681 goto out_delete_net
;
1684 /* Tell the child to complete its initialization and wait for it to exec
1685 * or return an error. (The child will never return
1686 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1687 * lxc_sync_barrier_child to return success, or return a different
1688 * value, causing us to error out).
1690 if (lxc_sync_barrier_child(handler
, LXC_SYNC_READY_START
))
1691 goto out_delete_net
;
1693 if (lxc_network_recv_name_and_ifindex_from_child(handler
) < 0) {
1694 ERROR("Failed to receive names and ifindices for network "
1695 "devices from child");
1696 goto out_delete_net
;
1699 /* Now all networks are created, network devices are moved into place,
1700 * and the correct names and ifindeces in the respective namespaces have
1701 * been recorded. The corresponding structs have now all been filled. So
1702 * log them for debugging purposes.
1704 lxc_log_configured_netdevs(conf
);
1706 /* Read tty fds allocated by child. */
1707 if (lxc_recv_ttys_from_child(handler
) < 0) {
1708 ERROR("Failed to receive tty info from child process.");
1709 goto out_delete_net
;
1712 if (handler
->ops
->post_start(handler
, handler
->data
))
1715 if (lxc_set_state(name
, handler
, RUNNING
)) {
1716 ERROR("Failed to set state for container \"%s\" to \"%s\".", name
,
1717 lxc_state2str(RUNNING
));
1721 lxc_sync_fini(handler
);
1726 if (cgroups_connected
)
1727 cgroup_disconnect();
1729 if (handler
->clone_flags
& CLONE_NEWNET
)
1730 lxc_delete_network(handler
);
1733 lxc_abort(name
, handler
);
1734 lxc_sync_fini(handler
);
1735 if (handler
->pinfd
>= 0) {
1736 close(handler
->pinfd
);
1737 handler
->pinfd
= -1;
1743 int __lxc_start(const char *name
, struct lxc_handler
*handler
,
1744 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1749 struct lxc_conf
*conf
= handler
->conf
;
1751 if (lxc_init(name
, handler
) < 0) {
1752 ERROR("Failed to initialize container \"%s\".", name
);
1756 handler
->data
= data
;
1757 handler
->backgrounded
= backgrounded
;
1759 if (!attach_block_device(handler
->conf
)) {
1760 ERROR("Failed to attach block device.");
1761 goto out_fini_nonet
;
1764 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1765 /* If the backing store is a device, mount it here and now. */
1766 if (rootfs_is_blockdev(conf
)) {
1767 if (unshare(CLONE_NEWNS
) < 0) {
1768 ERROR("Failed to unshare CLONE_NEWNS.");
1769 goto out_fini_nonet
;
1771 INFO("Unshared CLONE_NEWNS.");
1773 remount_all_slave();
1774 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1775 ERROR("Error setting up rootfs mount as root before spawn.");
1776 goto out_fini_nonet
;
1778 INFO("Set up container rootfs as host root.");
1782 err
= lxc_spawn(handler
);
1784 ERROR("Failed to spawn container \"%s\".", name
);
1785 goto out_detach_blockdev
;
1787 /* close parent side of data socket */
1788 close(handler
->data_sock
[0]);
1789 handler
->data_sock
[0] = -1;
1790 close(handler
->data_sock
[1]);
1791 handler
->data_sock
[1] = -1;
1793 handler
->conf
->reboot
= 0;
1795 err
= lxc_poll(name
, handler
);
1797 ERROR("LXC mainloop exited with error: %d.", err
);
1801 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1804 /* If the child process exited but was not signaled, it didn't call
1805 * reboot. This should mean it was an lxc-execute which simply exited.
1806 * In any case, treat it as a 'halt'.
1808 if (WIFSIGNALED(status
)) {
1809 switch(WTERMSIG(status
)) {
1810 case SIGINT
: /* halt */
1811 DEBUG("Container \"%s\" is halting.", name
);
1813 case SIGHUP
: /* reboot */
1814 DEBUG("Container \"%s\" is rebooting.", name
);
1815 handler
->conf
->reboot
= 1;
1817 case SIGSYS
: /* seccomp */
1818 DEBUG("Container \"%s\" violated its seccomp policy.", name
);
1821 DEBUG("Unknown exit status for container \"%s\" init %d.", name
, WTERMSIG(status
));
1826 err
= lxc_restore_phys_nics_to_netns(handler
);
1828 ERROR("Failed to move physical network devices back to parent "
1829 "network namespace");
1831 if (handler
->pinfd
>= 0) {
1832 close(handler
->pinfd
);
1833 handler
->pinfd
= -1;
1836 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1837 lxc_error_set_and_log(handler
->pid
, status
);
1840 lxc_delete_network(handler
);
1842 out_detach_blockdev
:
1843 detach_block_device(handler
->conf
);
1846 lxc_fini(name
, handler
);
1850 lxc_abort(name
, handler
);
1858 static int start(struct lxc_handler
*handler
, void* data
)
1860 struct start_args
*arg
= data
;
1862 NOTICE("Exec'ing \"%s\".", arg
->argv
[0]);
1864 execvp(arg
->argv
[0], arg
->argv
);
1865 SYSERROR("Failed to exec \"%s\".", arg
->argv
[0]);
1869 static int post_start(struct lxc_handler
*handler
, void* data
)
1871 struct start_args
*arg
= data
;
1873 NOTICE("Started \"%s\" with pid \"%d\".", arg
->argv
[0], handler
->pid
);
1877 static struct lxc_operations start_ops
= {
1879 .post_start
= post_start
1882 int lxc_start(const char *name
, char *const argv
[], struct lxc_handler
*handler
,
1883 const char *lxcpath
, bool backgrounded
)
1885 struct start_args start_arg
= {
1889 return __lxc_start(name
, handler
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1892 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1895 char destroy
[MAXPATHLEN
];
1898 struct lxc_container
*c
;
1899 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1900 bret
= do_destroy_container(handler
);
1902 ERROR("Error destroying rootfs for container \"%s\".", name
);
1906 INFO("Destroyed rootfs for container \"%s\".", name
);
1908 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1909 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1910 ERROR("Error destroying directory for container \"%s\".", name
);
1914 c
= lxc_container_new(name
, handler
->lxcpath
);
1916 if (container_disk_lock(c
)) {
1917 INFO("Could not update lxc_snapshots file.");
1918 lxc_container_put(c
);
1920 mod_all_rdeps(c
, false);
1921 container_disk_unlock(c
);
1922 lxc_container_put(c
);
1926 if (!handler
->am_root
)
1927 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
1928 destroy
, "lxc_rmdir_onedev_wrapper");
1930 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1933 ERROR("Error destroying directory for container \"%s\".", name
);
1936 INFO("Destroyed directory for container \"%s\".", name
);
1939 static int lxc_rmdir_onedev_wrapper(void *data
)
1941 char *arg
= (char *) data
;
1942 return lxc_rmdir_onedev(arg
, NULL
);
1945 static bool do_destroy_container(struct lxc_handler
*handler
) {
1948 if (!handler
->am_root
) {
1949 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
1950 handler
->conf
, "storage_destroy_wrapper");
1957 return storage_destroy(handler
->conf
);