2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
8 * Serge Hallyn <serge@hallyn.com>
9 * Christian Brauner <christian.brauner@ubuntu.com>
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
40 #include <sys/mount.h>
41 #include <sys/param.h>
42 #include <sys/prctl.h>
43 #include <sys/socket.h>
45 #include <sys/syscall.h>
46 #include <sys/types.h>
55 #include "commands_utils.h"
58 #include "confile_utils.h"
60 #include "file_utils.h"
64 #include "lxccontainer.h"
66 #include "lxcseccomp.h"
69 #include "memory_utils.h"
71 #include "namespace.h"
73 #include "raw_syscalls.h"
75 #include "storage/storage.h"
76 #include "storage/storage_utils.h"
78 #include "syscall_wrappers.h"
83 #include <sys/capability.h>
87 #include "include/strlcpy.h"
90 lxc_log_define(start
, lxc
);
92 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
93 static bool do_destroy_container(struct lxc_handler
*handler
);
94 static int lxc_rmdir_onedev_wrapper(void *data
);
95 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
98 static void print_top_failing_dir(const char *path
)
100 __do_free
char *copy
= NULL
;
104 copy
= must_copy_string(path
);
106 e
= copy
+ strlen(path
);
109 while (p
< e
&& *p
== '/')
112 while (p
< e
&& *p
!= '/')
118 ret
= access(copy
, X_OK
);
120 SYSERROR("Could not access %s. Please grant it x "
121 "access, or add an ACL for the container "
129 static void lxc_put_nsfds(struct lxc_handler
*handler
)
133 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
134 if (handler
->nsfd
[i
] < 0)
137 close(handler
->nsfd
[i
]);
138 handler
->nsfd
[i
] = -EBADF
;
142 static int lxc_try_preserve_ns(const int pid
, const char *ns
)
146 fd
= lxc_preserve_ns(pid
, ns
);
148 if (errno
!= ENOENT
) {
149 SYSERROR("Failed to preserve %s namespace", ns
);
153 SYSWARN("Kernel does not support preserving %s namespaces", ns
);
160 /* lxc_try_preserve_namespaces: open /proc/@pid/ns/@ns for each namespace
161 * specified in ns_clone_flags.
162 * Return true on success, false on failure.
164 static bool lxc_try_preserve_namespaces(struct lxc_handler
*handler
,
165 int ns_clone_flags
, pid_t pid
)
169 for (i
= 0; i
< LXC_NS_MAX
; i
++)
170 handler
->nsfd
[i
] = -EBADF
;
172 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
175 if ((ns_clone_flags
& ns_info
[i
].clone_flag
) == 0)
178 fd
= lxc_try_preserve_ns(pid
, ns_info
[i
].proc_name
);
180 /* Do not fail to start container on kernels that do
181 * not support interacting with namespaces through
184 if (fd
== -EOPNOTSUPP
)
187 lxc_put_nsfds(handler
);
191 handler
->nsfd
[i
] = fd
;
192 DEBUG("Preserved %s namespace via fd %d", ns_info
[i
].proc_name
,
199 static inline bool match_stdfds(int fd
)
201 return (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
);
205 static bool match_dlog_fds(struct dirent
*direntp
)
207 char path
[PATH_MAX
] = {0};
208 char link
[PATH_MAX
] = {0};
212 ret
= snprintf(path
, PATH_MAX
, "/proc/self/fd/%s", direntp
->d_name
);
213 if (ret
< 0 || ret
>= PATH_MAX
) {
214 ERROR("Failed to create file descriptor name");
218 linklen
= readlink(path
, link
, PATH_MAX
);
220 SYSERROR("Failed to read link path - \"%s\"", path
);
222 } else if (linklen
>= PATH_MAX
) {
223 ERROR("The name of link path is too long - \"%s\"", path
);
227 if (strcmp(link
, "/dev/log_main") == 0 ||
228 strcmp(link
, "/dev/log_system") == 0 ||
229 strcmp(link
, "/dev/log_radio") == 0)
236 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
237 int *fds_to_ignore
, size_t len_fds
)
242 struct dirent
*direntp
;
244 if (conf
&& conf
->close_all_fds
)
248 dir
= opendir("/proc/self/fd");
250 SYSWARN("Failed to open directory");
256 while ((direntp
= readdir(dir
))) {
258 struct lxc_list
*cur
;
259 bool matched
= false;
261 if (strcmp(direntp
->d_name
, ".") == 0)
264 if (strcmp(direntp
->d_name
, "..") == 0)
267 ret
= lxc_safe_int(direntp
->d_name
, &fd
);
269 INFO("Could not parse file descriptor for \"%s\"", direntp
->d_name
);
273 for (i
= 0; i
< len_fds
; i
++)
274 if (fds_to_ignore
[i
] == fd
)
277 if (fd
== fddir
|| fd
== lxc_log_fd
||
278 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
281 /* Keep state clients that wait on reboots. */
283 lxc_list_for_each(cur
, &conf
->state_clients
) {
284 struct lxc_state_client
*client
= cur
->elem
;
286 if (client
->clientfd
!= fd
)
297 if (current_config
&& fd
== current_config
->logfd
)
300 if (match_stdfds(fd
))
304 if (match_dlog_fds(direntp
))
311 INFO("Closed inherited fd %d", fd
);
314 WARN("Inherited fd %d", fd
);
317 /* Only enable syslog at this point to avoid the above logging function
318 * to open a new fd and make the check_inherited function enter an
321 lxc_log_enable_syslog();
323 closedir(dir
); /* cannot fail */
327 static int setup_signal_fd(sigset_t
*oldmask
)
331 const int signals
[] = {SIGBUS
, SIGILL
, SIGSEGV
, SIGWINCH
};
333 /* Block everything except serious error signals. */
334 ret
= sigfillset(&mask
);
338 for (int sig
= 0; sig
< (sizeof(signals
) / sizeof(signals
[0])); sig
++) {
339 ret
= sigdelset(&mask
, signals
[sig
]);
344 ret
= pthread_sigmask(SIG_BLOCK
, &mask
, oldmask
);
346 SYSERROR("Failed to set signal mask");
350 ret
= signalfd(-1, &mask
, SFD_CLOEXEC
);
352 SYSERROR("Failed to create signal file descriptor");
356 TRACE("Created signal file descriptor %d", ret
);
361 static int signal_handler(int fd
, uint32_t events
, void *data
,
362 struct lxc_epoll_descr
*descr
)
366 struct signalfd_siginfo siginfo
;
367 struct lxc_handler
*hdlr
= data
;
369 ret
= lxc_read_nointr(fd
, &siginfo
, sizeof(siginfo
));
371 ERROR("Failed to read signal info from signal file descriptor %d", fd
);
372 return LXC_MAINLOOP_ERROR
;
375 if (ret
!= sizeof(siginfo
)) {
376 ERROR("Unexpected size for struct signalfd_siginfo");
380 /* Check whether init is running. */
382 ret
= waitid(P_PID
, hdlr
->pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
383 if (ret
== 0 && info
.si_pid
== hdlr
->pid
)
384 hdlr
->init_died
= true;
386 /* Try to figure out a reasonable exit status to report. */
387 if (hdlr
->init_died
) {
388 switch (info
.si_code
) {
390 hdlr
->exit_status
= info
.si_status
<< 8;
395 hdlr
->exit_status
= info
.si_status
<< 8 | 0x7f;
398 /* Huh? The waitid() told us it's dead *and* continued? */
399 WARN("Init %d dead and continued?", hdlr
->pid
);
400 hdlr
->exit_status
= 1;
403 ERROR("Unknown si_code: %d", info
.si_code
);
404 hdlr
->exit_status
= 1;
408 if (siginfo
.ssi_signo
== SIGHUP
) {
409 kill(hdlr
->pid
, SIGTERM
);
410 INFO("Killing %d since terminal hung up", hdlr
->pid
);
411 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
412 : LXC_MAINLOOP_CONTINUE
;
415 if (siginfo
.ssi_signo
!= SIGCHLD
) {
416 kill(hdlr
->pid
, siginfo
.ssi_signo
);
417 INFO("Forwarded signal %d to pid %d", siginfo
.ssi_signo
, hdlr
->pid
);
418 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
419 : LXC_MAINLOOP_CONTINUE
;
422 /* More robustness, protect ourself from a SIGCHLD sent
423 * by a process different from the container init.
425 if (siginfo
.ssi_pid
!= hdlr
->pid
) {
426 NOTICE("Received %d from pid %d instead of container init %d",
427 siginfo
.ssi_signo
, siginfo
.ssi_pid
, hdlr
->pid
);
428 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
429 : LXC_MAINLOOP_CONTINUE
;
432 if (siginfo
.ssi_code
== CLD_STOPPED
) {
433 INFO("Container init process was stopped");
434 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
435 : LXC_MAINLOOP_CONTINUE
;
438 if (siginfo
.ssi_code
== CLD_CONTINUED
) {
439 INFO("Container init process was continued");
440 return hdlr
->init_died
? LXC_MAINLOOP_CLOSE
441 : LXC_MAINLOOP_CONTINUE
;
444 DEBUG("Container init process %d exited", hdlr
->pid
);
446 return LXC_MAINLOOP_CLOSE
;
449 int lxc_serve_state_clients(const char *name
, struct lxc_handler
*handler
,
454 struct lxc_list
*cur
, *next
;
455 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
458 handler
->state
= RUNNING
;
460 handler
->state
= state
;
462 TRACE("Set container state to %s", lxc_state2str(state
));
464 if (lxc_list_empty(&handler
->conf
->state_clients
)) {
465 TRACE("No state clients registered");
469 retlen
= strlcpy(msg
.name
, name
, sizeof(msg
.name
));
470 if (retlen
>= sizeof(msg
.name
))
473 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
474 struct lxc_state_client
*client
= cur
->elem
;
476 if (client
->states
[state
] == 0) {
477 TRACE("State %s not registered for state client %d",
478 lxc_state2str(state
), client
->clientfd
);
482 TRACE("Sending state %s to state client %d",
483 lxc_state2str(state
), client
->clientfd
);
485 ret
= lxc_send_nointr(client
->clientfd
, &msg
, sizeof(msg
), MSG_NOSIGNAL
);
487 SYSERROR("Failed to send message to client");
489 /* kick client from list */
491 close(client
->clientfd
);
499 static int lxc_serve_state_socket_pair(const char *name
,
500 struct lxc_handler
*handler
,
505 if (!handler
->daemonize
||
506 handler
->state_socket_pair
[1] < 0 ||
510 /* Close read end of the socket pair. */
511 close(handler
->state_socket_pair
[0]);
512 handler
->state_socket_pair
[0] = -1;
515 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
516 &(int){state
}, sizeof(int));
518 SYSERROR("Failed to send state to %d", handler
->state_socket_pair
[1]);
526 if (ret
!= sizeof(int)) {
527 ERROR("Message too long : %d", handler
->state_socket_pair
[1]);
531 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
532 handler
->state_socket_pair
[1]);
534 /* Close write end of the socket pair. */
535 close(handler
->state_socket_pair
[1]);
536 handler
->state_socket_pair
[1] = -1;
541 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
546 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
548 ERROR("Failed to synchronize via anonymous pair of unix sockets");
552 ret
= lxc_serve_state_clients(name
, handler
, state
);
556 /* This function will try to connect to the legacy lxc-monitord state
557 * server and only exists for backwards compatibility.
559 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
564 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
567 bool has_console
= true;
568 struct lxc_epoll_descr descr
, descr_console
;
570 if (handler
->conf
->console
.path
&&
571 strcmp(handler
->conf
->console
.path
, "none") == 0)
574 ret
= lxc_mainloop_open(&descr
);
576 ERROR("Failed to create mainloop");
581 ret
= lxc_mainloop_open(&descr_console
);
583 ERROR("Failed to create console mainloop");
588 ret
= lxc_mainloop_add_handler(&descr
, handler
->sigfd
, signal_handler
, handler
);
590 ERROR("Failed to add signal handler for %d to mainloop", handler
->sigfd
);
591 goto out_mainloop_console
;
594 ret
= lxc_seccomp_setup_proxy(&handler
->conf
->seccomp
, &descr
, handler
);
596 ERROR("Failed to setup seccomp proxy");
597 goto out_mainloop_console
;
601 struct lxc_terminal
*console
= &handler
->conf
->console
;
603 ret
= lxc_terminal_mainloop_add(&descr
, console
);
605 ERROR("Failed to add console handlers to mainloop");
606 goto out_mainloop_console
;
609 ret
= lxc_terminal_mainloop_add(&descr_console
, console
);
611 ERROR("Failed to add console handlers to console mainloop");
612 goto out_mainloop_console
;
615 handler
->conf
->console
.descr
= &descr
;
618 ret
= lxc_cmd_mainloop_add(name
, &descr
, handler
);
620 ERROR("Failed to add command handler to mainloop");
621 goto out_mainloop_console
;
624 TRACE("Mainloop is ready");
626 ret
= lxc_mainloop(&descr
, -1);
629 if (ret
< 0 || !handler
->init_died
)
630 goto out_mainloop_console
;
633 ret
= lxc_mainloop(&descr_console
, 0);
635 out_mainloop_console
:
637 lxc_mainloop_close(&descr_console
);
638 TRACE("Closed console mainloop");
642 lxc_mainloop_close(&descr
);
643 TRACE("Closed mainloop");
646 close(handler
->sigfd
);
647 TRACE("Closed signal file descriptor %d", handler
->sigfd
);
648 handler
->sigfd
= -EBADF
;
653 void lxc_zero_handler(struct lxc_handler
*handler
)
657 memset(handler
, 0, sizeof(struct lxc_handler
));
663 for (i
= 0; i
< LXC_NS_MAX
; i
++)
664 handler
->nsfd
[i
] = -1;
666 handler
->data_sock
[0] = -1;
667 handler
->data_sock
[1] = -1;
669 handler
->state_socket_pair
[0] = -1;
670 handler
->state_socket_pair
[1] = -1;
672 handler
->sync_sock
[0] = -1;
673 handler
->sync_sock
[1] = -1;
676 void lxc_free_handler(struct lxc_handler
*handler
)
678 if (handler
->pinfd
>= 0)
679 close(handler
->pinfd
);
681 if (handler
->sigfd
>= 0)
682 close(handler
->sigfd
);
684 lxc_put_nsfds(handler
);
686 if (handler
->conf
&& handler
->conf
->reboot
== REBOOT_NONE
)
687 if (handler
->conf
->maincmd_fd
>= 0)
688 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
690 if (handler
->state_socket_pair
[0] >= 0)
691 close(handler
->state_socket_pair
[0]);
693 if (handler
->state_socket_pair
[1] >= 0)
694 close(handler
->state_socket_pair
[1]);
696 if (handler
->cgroup_ops
)
697 cgroup_exit(handler
->cgroup_ops
);
699 handler
->conf
= NULL
;
704 struct lxc_handler
*lxc_init_handler(const char *name
, struct lxc_conf
*conf
,
705 const char *lxcpath
, bool daemonize
)
708 struct lxc_handler
*handler
;
710 handler
= malloc(sizeof(*handler
));
714 memset(handler
, 0, sizeof(*handler
));
716 /* Note that am_guest_unpriv() checks the effective uid. We
717 * probably don't care if we are real root only if we are running
718 * as root so this should be fine.
720 handler
->am_root
= !am_guest_unpriv();
721 handler
->data_sock
[0] = handler
->data_sock
[1] = -1;
722 handler
->conf
= conf
;
723 handler
->lxcpath
= lxcpath
;
725 handler
->sigfd
= -EBADF
;
726 handler
->init_died
= false;
727 handler
->state_socket_pair
[0] = handler
->state_socket_pair
[1] = -1;
728 if (handler
->conf
->reboot
== REBOOT_NONE
)
729 lxc_list_init(&handler
->conf
->state_clients
);
731 for (i
= 0; i
< LXC_NS_MAX
; i
++)
732 handler
->nsfd
[i
] = -1;
734 handler
->name
= name
;
736 if (daemonize
&& handler
->conf
->reboot
== REBOOT_NONE
) {
737 /* Create socketpair() to synchronize on daemonized startup.
738 * When the container reboots we don't need to synchronize
739 * again currently so don't open another socketpair().
741 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
742 handler
->state_socket_pair
);
744 ERROR("Failed to create anonymous pair of unix sockets");
748 TRACE("Created anonymous pair {%d,%d} of unix sockets",
749 handler
->state_socket_pair
[0],
750 handler
->state_socket_pair
[1]);
753 if (handler
->conf
->reboot
== REBOOT_NONE
) {
754 handler
->conf
->maincmd_fd
= lxc_cmd_init(name
, lxcpath
, "command");
755 if (handler
->conf
->maincmd_fd
< 0) {
756 ERROR("Failed to set up command socket");
761 TRACE("Unix domain socket %d for command server is ready",
762 handler
->conf
->maincmd_fd
);
767 lxc_free_handler(handler
);
772 int lxc_init(const char *name
, struct lxc_handler
*handler
)
775 const char *loglevel
;
776 struct lxc_conf
*conf
= handler
->conf
;
778 handler
->monitor_pid
= lxc_raw_getpid();
781 TRACE("Initialized LSM");
783 ret
= lxc_read_seccomp_config(conf
);
785 ERROR("Failed loading seccomp policy");
786 goto out_close_maincmd_fd
;
788 TRACE("Read seccomp policy");
790 /* Begin by setting the state to STARTING. */
791 ret
= lxc_set_state(name
, handler
, STARTING
);
793 ERROR("Failed to set state to \"%s\"", lxc_state2str(STARTING
));
794 goto out_close_maincmd_fd
;
796 TRACE("Set container state to \"STARTING\"");
798 /* Start of environment variable setup for hooks. */
799 ret
= setenv("LXC_NAME", name
, 1);
801 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name
);
804 ret
= setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1);
806 SYSERROR("Failed to set environment variable: "
807 "LXC_CONFIG_FILE=%s", conf
->rcfile
);
810 if (conf
->rootfs
.mount
) {
811 ret
= setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1);
813 SYSERROR("Failed to set environment variable: "
814 "LXC_ROOTFS_MOUNT=%s", conf
->rootfs
.mount
);
817 if (conf
->rootfs
.path
) {
818 ret
= setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1);
820 SYSERROR("Failed to set environment variable: "
821 "LXC_ROOTFS_PATH=%s", conf
->rootfs
.path
);
824 if (conf
->console
.path
) {
825 ret
= setenv("LXC_CONSOLE", conf
->console
.path
, 1);
827 SYSERROR("Failed to set environment variable: "
828 "LXC_CONSOLE=%s", conf
->console
.path
);
831 if (conf
->console
.log_path
) {
832 ret
= setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1);
834 SYSERROR("Failed to set environment variable: "
835 "LXC_CONSOLE_LOGPATH=%s", conf
->console
.log_path
);
838 if (cgns_supported()) {
839 ret
= setenv("LXC_CGNS_AWARE", "1", 1);
841 SYSERROR("Failed to set environment variable "
845 loglevel
= lxc_log_priority_to_string(lxc_log_get_level());
846 ret
= setenv("LXC_LOG_LEVEL", loglevel
, 1);
848 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s",
851 if (conf
->hooks_version
== 0)
852 ret
= setenv("LXC_HOOK_VERSION", "0", 1);
854 ret
= setenv("LXC_HOOK_VERSION", "1", 1);
856 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf
->hooks_version
);
857 /* End of environment variable setup for hooks. */
859 TRACE("Set environment variables");
861 ret
= run_lxc_hooks(name
, "pre-start", conf
, NULL
);
863 ERROR("Failed to run lxc.hook.pre-start for container \"%s\"", name
);
866 TRACE("Ran pre-start hooks");
868 /* The signal fd has to be created before forking otherwise if the child
869 * process exits before we setup the signal fd, the event will be lost
870 * and the command will be stuck.
872 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
873 if (handler
->sigfd
< 0) {
874 ERROR("Failed to setup SIGCHLD fd handler.");
877 TRACE("Set up signal fd");
879 /* Do this after setting up signals since it might unblock SIGWINCH. */
880 ret
= lxc_terminal_setup(conf
);
882 ERROR("Failed to create console");
883 goto out_restore_sigmask
;
885 TRACE("Created console");
887 ret
= lxc_terminal_map_ids(conf
, &conf
->console
);
889 ERROR("Failed to chown console");
890 goto out_delete_terminal
;
892 TRACE("Chowned console");
894 handler
->cgroup_ops
= cgroup_init(handler
->conf
);
895 if (!handler
->cgroup_ops
) {
896 ERROR("Failed to initialize cgroup driver");
897 goto out_delete_terminal
;
899 TRACE("Initialized cgroup driver");
901 ret
= lsm_process_prepare(conf
, handler
->lxcpath
);
903 ERROR("Failed to initialize LSM");
904 goto out_destroy_cgroups
;
906 TRACE("Initialized LSM");
908 INFO("Container \"%s\" is initialized", name
);
912 handler
->cgroup_ops
->payload_destroy(handler
->cgroup_ops
, handler
);
913 handler
->cgroup_ops
->monitor_destroy(handler
->cgroup_ops
, handler
);
916 lxc_terminal_delete(&handler
->conf
->console
);
919 (void)pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
922 lxc_delete_tty(&conf
->ttys
);
925 (void)lxc_set_state(name
, handler
, ABORTING
);
927 out_close_maincmd_fd
:
928 lxc_abstract_unix_close(conf
->maincmd_fd
);
929 conf
->maincmd_fd
= -1;
933 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
937 struct lxc_list
*cur
, *next
;
938 char *namespaces
[LXC_NS_MAX
+ 1];
939 size_t namespace_count
= 0;
940 struct cgroup_ops
*cgroup_ops
= handler
->cgroup_ops
;
942 /* The STOPPING state is there for future cleanup code which can take
945 lxc_set_state(name
, handler
, STOPPING
);
947 self
= lxc_raw_getpid();
948 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
949 if (handler
->nsfd
[i
] < 0)
952 if (handler
->conf
->hooks_version
== 0)
953 ret
= asprintf(&namespaces
[namespace_count
],
954 "%s:/proc/%d/fd/%d", ns_info
[i
].proc_name
,
955 self
, handler
->nsfd
[i
]);
957 ret
= asprintf(&namespaces
[namespace_count
],
958 "/proc/%d/fd/%d", self
, handler
->nsfd
[i
]);
960 SYSERROR("Failed to allocate memory");
964 if (handler
->conf
->hooks_version
== 0) {
969 ret
= setenv(ns_info
[i
].env_name
, namespaces
[namespace_count
], 1);
971 SYSERROR("Failed to set environment variable %s=%s",
972 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
974 TRACE("Set environment variable %s=%s",
975 ns_info
[i
].env_name
, namespaces
[namespace_count
]);
979 namespaces
[namespace_count
] = NULL
;
981 if (handler
->conf
->reboot
> REBOOT_NONE
) {
982 ret
= setenv("LXC_TARGET", "reboot", 1);
984 SYSERROR("Failed to set environment variable: "
985 "LXC_TARGET=reboot");
988 if (handler
->conf
->reboot
== REBOOT_NONE
) {
989 ret
= setenv("LXC_TARGET", "stop", 1);
991 SYSERROR("Failed to set environment variable: "
995 if (handler
->conf
->hooks_version
== 0)
996 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, namespaces
);
998 ret
= run_lxc_hooks(name
, "stop", handler
->conf
, NULL
);
1000 ERROR("Failed to run \"lxc.hook.stop\" hook");
1002 while (namespace_count
--)
1003 free(namespaces
[namespace_count
]);
1005 lsm_process_cleanup(handler
->conf
, handler
->lxcpath
);
1007 cgroup_ops
->payload_destroy(cgroup_ops
, handler
);
1008 cgroup_ops
->monitor_destroy(cgroup_ops
, handler
);
1010 if (handler
->conf
->reboot
== REBOOT_NONE
) {
1011 /* For all new state clients simply close the command socket.
1012 * This will inform all state clients that the container is
1013 * STOPPED and also prevents a race between a open()/close() on
1014 * the command socket causing a new process to get ECONNREFUSED
1015 * because we haven't yet closed the command socket.
1017 lxc_abstract_unix_close(handler
->conf
->maincmd_fd
);
1018 handler
->conf
->maincmd_fd
= -1;
1019 TRACE("Closed command socket");
1021 /* This function will try to connect to the legacy lxc-monitord
1022 * state server and only exists for backwards compatibility.
1024 lxc_monitor_send_state(name
, STOPPED
, handler
->lxcpath
);
1026 /* The command socket is closed so no one can acces the command
1027 * socket anymore so there's no need to lock it.
1029 handler
->state
= STOPPED
;
1030 TRACE("Set container state to \"STOPPED\"");
1032 lxc_set_state(name
, handler
, STOPPED
);
1035 /* Avoid lingering namespace references. */
1036 lxc_put_nsfds(handler
);
1038 ret
= run_lxc_hooks(name
, "post-stop", handler
->conf
, NULL
);
1040 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name
);
1041 if (handler
->conf
->reboot
> REBOOT_NONE
) {
1042 WARN("Container will be stopped instead of rebooted");
1043 handler
->conf
->reboot
= REBOOT_NONE
;
1045 ret
= setenv("LXC_TARGET", "stop", 1);
1047 WARN("Failed to set environment variable: "
1052 /* Reset mask set by setup_signal_fd. */
1053 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1055 SYSWARN("Failed to restore signal mask");
1057 lxc_terminal_delete(&handler
->conf
->console
);
1058 lxc_delete_tty(&handler
->conf
->ttys
);
1060 /* The command socket is now closed, no more state clients can register
1061 * themselves from now on. So free the list of state clients.
1063 lxc_list_for_each_safe(cur
, &handler
->conf
->state_clients
, next
) {
1064 struct lxc_state_client
*client
= cur
->elem
;
1066 /* Keep state clients that want to be notified about reboots. */
1067 if ((handler
->conf
->reboot
> REBOOT_NONE
) &&
1068 (client
->states
[RUNNING
] == 2))
1071 /* close state client socket */
1073 close(client
->clientfd
);
1078 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= REBOOT_REQ
)
1079 lxc_destroy_container_on_signal(handler
, name
);
1081 lxc_free_handler(handler
);
1084 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
1088 lxc_set_state(name
, handler
, ABORTING
);
1090 if (handler
->pid
> 0) {
1091 ret
= kill(handler
->pid
, SIGKILL
);
1093 SYSERROR("Failed to send SIGKILL to %d", handler
->pid
);
1096 while ((ret
= waitpid(-1, &status
, 0)) > 0) {
1101 static int do_start(void *data
)
1103 struct lxc_handler
*handler
= data
;
1104 ATTR_UNUSED __do_close_prot_errno
int data_sock0
= handler
->data_sock
[0],
1105 data_sock1
= handler
->data_sock
[1];
1107 char path
[PATH_MAX
];
1110 struct lxc_list
*iterator
;
1113 int devnull_fd
= -1;
1115 lxc_sync_fini_parent(handler
);
1117 /* This prctl must be before the synchro, so if the parent dies before
1118 * we set the parent death signal, we will detect its death with the
1119 * synchro right after, otherwise we have a window where the parent can
1120 * exit before we set the pdeath signal leading to a unsupervized
1123 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
);
1125 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1126 goto out_warn_father
;
1129 ret
= lxc_ambient_caps_up();
1131 ERROR("Failed to raise ambient capabilities");
1132 goto out_warn_father
;
1135 ret
= pthread_sigmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
1137 SYSERROR("Failed to set signal mask");
1138 goto out_warn_father
;
1141 /* Don't leak the pinfd to the container. */
1142 if (handler
->pinfd
>= 0)
1143 close(handler
->pinfd
);
1145 ret
= lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
);
1147 goto out_warn_father
;
1149 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1150 * https://github.com/lxc/lxd/issues/1978.
1152 if ((handler
->ns_clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
1153 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
1154 ret
= unshare(CLONE_NEWNET
);
1156 SYSERROR("Failed to unshare CLONE_NEWNET");
1157 goto out_warn_father
;
1159 INFO("Unshared CLONE_NEWNET");
1162 /* Tell the parent task it can begin to configure the container and wait
1165 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
);
1169 ret
= lxc_network_recv_veth_names_from_parent(handler
);
1171 ERROR("Failed to receive veth names from parent");
1172 goto out_warn_father
;
1175 /* If we are in a new user namespace, become root there to have
1176 * privilege over our namespace.
1178 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
1179 if (!handler
->conf
->root_nsuid_map
)
1180 nsuid
= handler
->conf
->init_uid
;
1182 if (!handler
->conf
->root_nsgid_map
)
1183 nsgid
= handler
->conf
->init_gid
;
1185 if (!lxc_switch_uid_gid(nsuid
, nsgid
))
1186 goto out_warn_father
;
1188 /* Drop groups only after we switched to a valid gid in the new
1191 if (!lxc_setgroups(0, NULL
) &&
1192 (handler
->am_root
|| errno
!= EPERM
))
1193 goto out_warn_father
;
1195 ret
= prctl(PR_SET_DUMPABLE
, prctl_arg(1), prctl_arg(0),
1196 prctl_arg(0), prctl_arg(0));
1198 goto out_warn_father
;
1200 /* set{g,u}id() clears deathsignal */
1201 ret
= lxc_set_death_signal(SIGKILL
, handler
->monitor_pid
);
1203 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1204 goto out_warn_father
;
1208 ret
= access(handler
->lxcpath
, X_OK
);
1210 print_top_failing_dir(handler
->lxcpath
);
1211 goto out_warn_father
;
1214 ret
= snprintf(path
, sizeof(path
), "%s/dev/null",
1215 handler
->conf
->rootfs
.mount
);
1216 if (ret
< 0 || ret
>= sizeof(path
))
1217 goto out_warn_father
;
1219 /* In order to checkpoint restore, we need to have everything in the
1220 * same mount namespace. However, some containers may not have a
1221 * reasonable /dev (in particular, they may not have /dev/null), so we
1222 * can't set init's std fds to /dev/null by opening it from inside the
1225 * If that's the case, fall back to using the host's /dev/null. This
1226 * means that migration won't work, but at least we won't spew output
1227 * where it isn't wanted.
1229 if (handler
->daemonize
&& !handler
->conf
->autodev
) {
1230 ret
= access(path
, F_OK
);
1232 devnull_fd
= open_devnull();
1235 goto out_warn_father
;
1236 WARN("Using /dev/null from the host for container "
1237 "init's standard file descriptors. Migration will "
1242 /* Ask father to setup cgroups and wait for him to finish. */
1243 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
);
1247 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1248 * earlier we end up with a wrong view of /proc/self/cgroup. For
1249 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1250 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1251 * /proc/self/cgroup would show us:
1255 * whereas it should actually show
1259 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1260 ret
= unshare(CLONE_NEWCGROUP
);
1262 if (errno
!= EINVAL
) {
1263 SYSERROR("Failed to unshare CLONE_NEWCGROUP");
1264 goto out_warn_father
;
1267 handler
->ns_clone_flags
&= ~CLONE_NEWCGROUP
;
1268 SYSINFO("Kernel does not support CLONE_NEWCGROUP");
1270 INFO("Unshared CLONE_NEWCGROUP");
1274 /* Add the requested environment variables to the current environment to
1275 * allow them to be used by the various hooks, such as the start hook
1278 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1279 ret
= putenv((char *)iterator
->elem
);
1281 SYSERROR("Failed to set environment variable: %s",
1282 (char *)iterator
->elem
);
1283 goto out_warn_father
;
1287 /* Setup the container, ip, names, utsname, ... */
1288 ret
= lxc_setup(handler
);
1290 ERROR("Failed to setup container \"%s\"", handler
->name
);
1291 goto out_warn_father
;
1294 /* Set the label to change to when we exec(2) the container's init. */
1295 ret
= lsm_process_label_set(NULL
, handler
->conf
, true);
1297 goto out_warn_father
;
1299 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1300 * before we aren't allowed anymore.
1302 if (handler
->conf
->no_new_privs
) {
1303 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
1304 prctl_arg(0), prctl_arg(0));
1306 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block "
1307 "execve() gainable privileges");
1308 goto out_warn_father
;
1310 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable "
1314 /* Some init's such as busybox will set sane tty settings on stdin,
1315 * stdout, stderr which it thinks is the console. We already set them
1316 * the way we wanted on the real terminal, and we want init to do its
1317 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
1318 * make sure that that pty is stdin,stdout,stderr.
1320 if (handler
->conf
->console
.slave
>= 0) {
1321 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
1322 ret
= set_stdfds(handler
->conf
->console
.slave
);
1324 ret
= lxc_terminal_set_stdfds(handler
->conf
->console
.slave
);
1326 ERROR("Failed to redirect std{in,out,err} to pty file "
1327 "descriptor %d", handler
->conf
->console
.slave
);
1328 goto out_warn_father
;
1332 /* If we mounted a temporary proc, then unmount it now. */
1333 tmp_proc_unmount(handler
->conf
);
1335 ret
= lxc_seccomp_load(handler
->conf
);
1337 goto out_warn_father
;
1339 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, data_sock0
);
1341 SYSERROR("Failed to send seccomp notify fd to parent");
1342 goto out_warn_father
;
1345 ret
= run_lxc_hooks(handler
->name
, "start", handler
->conf
, NULL
);
1347 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1349 goto out_warn_father
;
1352 close(handler
->sigfd
);
1354 if (handler
->conf
->console
.slave
< 0 && handler
->daemonize
) {
1355 if (devnull_fd
< 0) {
1356 devnull_fd
= open_devnull();
1358 goto out_warn_father
;
1361 ret
= set_stdfds(devnull_fd
);
1363 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
1364 goto out_warn_father
;
1368 if (devnull_fd
>= 0) {
1375 if (handler
->conf
->init_cwd
) {
1376 ret
= chdir(handler
->conf
->init_cwd
);
1378 SYSERROR("Could not change directory to \"%s\"",
1379 handler
->conf
->init_cwd
);
1380 goto out_warn_father
;
1384 ret
= lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
);
1386 goto out_warn_father
;
1388 /* Reset the environment variables the user requested in a clear
1392 /* Don't error out though. */
1394 SYSERROR("Failed to clear environment.");
1396 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
1397 ret
= putenv((char *)iterator
->elem
);
1399 SYSERROR("Failed to set environment variable: %s",
1400 (char *)iterator
->elem
);
1401 goto out_warn_father
;
1405 ret
= putenv("container=lxc");
1407 SYSERROR("Failed to set environment variable: container=lxc");
1408 goto out_warn_father
;
1411 if (handler
->conf
->ttys
.tty_names
) {
1412 ret
= putenv(handler
->conf
->ttys
.tty_names
);
1414 SYSERROR("Failed to set environment variable for container ptys");
1415 goto out_warn_father
;
1419 /* The container has been setup. We can now switch to an unprivileged
1422 new_uid
= handler
->conf
->init_uid
;
1423 new_gid
= handler
->conf
->init_gid
;
1425 /* Avoid unnecessary syscalls. */
1426 if (new_uid
== nsuid
)
1427 new_uid
= LXC_INVALID_UID
;
1429 if (new_gid
== nsgid
)
1430 new_gid
= LXC_INVALID_GID
;
1432 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
1433 goto out_warn_father
;
1435 /* If we are in a new user namespace we already dropped all groups when
1436 * we switched to root in the new user namespace further above. Only
1437 * drop groups if we can, so ensure that we have necessary privilege.
1439 if (lxc_list_empty(&handler
->conf
->id_map
))
1441 if (lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
))
1443 if (!lxc_setgroups(0, NULL
))
1444 goto out_warn_father
;
1446 ret
= lxc_ambient_caps_down();
1448 ERROR("Failed to clear ambient capabilities");
1449 goto out_warn_father
;
1452 if (handler
->conf
->monitor_signal_pdeath
!= SIGKILL
) {
1453 ret
= lxc_set_death_signal(handler
->conf
->monitor_signal_pdeath
, handler
->monitor_pid
);
1455 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1456 handler
->conf
->monitor_signal_pdeath
);
1457 goto out_warn_father
;
1461 /* After this call, we are in error because this ops should not return
1464 handler
->ops
->start(handler
, handler
->data
);
1467 /* We want the parent to know something went wrong, so we return a
1468 * special error code.
1470 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1473 if (devnull_fd
>= 0)
1479 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1482 struct lxc_terminal_info
*tty
;
1484 int sock
= handler
->data_sock
[1];
1485 struct lxc_conf
*conf
= handler
->conf
;
1486 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1488 if (!conf
->ttys
.max
)
1491 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
1495 for (i
= 0; i
< conf
->ttys
.max
; i
++) {
1498 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1502 tty
= &ttys
->tty
[i
];
1504 tty
->master
= ttyfds
[0];
1505 tty
->slave
= ttyfds
[1];
1506 TRACE("Received pty with master fd %d and slave fd %d from "
1507 "parent", tty
->master
, tty
->slave
);
1511 SYSERROR("Failed to receive %zu ttys from child", ttys
->max
);
1513 TRACE("Received %zu ttys from child", ttys
->max
);
1518 int resolve_clone_flags(struct lxc_handler
*handler
)
1521 struct lxc_conf
*conf
= handler
->conf
;
1523 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1524 if (conf
->ns_keep
) {
1525 if (!(conf
->ns_keep
& ns_info
[i
].clone_flag
))
1526 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1527 } else if (conf
->ns_clone
) {
1528 if ((conf
->ns_clone
& ns_info
[i
].clone_flag
))
1529 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1531 if (i
== LXC_NS_USER
&& lxc_list_empty(&handler
->conf
->id_map
))
1534 if (i
== LXC_NS_NET
&& lxc_requests_empty_network(handler
))
1537 if (i
== LXC_NS_CGROUP
&& !cgns_supported())
1540 handler
->ns_clone_flags
|= ns_info
[i
].clone_flag
;
1543 if (!conf
->ns_share
[i
])
1546 handler
->ns_clone_flags
&= ~ns_info
[i
].clone_flag
;
1547 TRACE("Sharing %s namespace", ns_info
[i
].proc_name
);
1553 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1554 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1555 * But since the memory between parent and child is shared on CLONE_VM this
1556 * would invalidate the getpid() cache that glibc used to maintain and so
1557 * getpid() in the child would return the parent's pid. This is all fixed in
1558 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1559 * not reset anymore.
1560 * However, if for whatever reason you - dear committer - somehow need to get the
1561 * pid of the dummy intermediate process for do_share_ns() you need to call
1562 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1565 static inline int do_share_ns(void *arg
)
1568 struct lxc_handler
*handler
= arg
;
1570 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1571 if (handler
->nsfd
[i
] < 0)
1574 ret
= setns(handler
->nsfd
[i
], 0);
1577 * Note that joining a user and/or mount namespace
1578 * requires the process is not multithreaded otherwise
1579 * setns() will fail here.
1581 SYSERROR("Failed to inherit %s namespace",
1582 ns_info
[i
].proc_name
);
1586 DEBUG("Inherited %s namespace", ns_info
[i
].proc_name
);
1589 flags
= handler
->ns_on_clone_flags
;
1590 flags
|= CLONE_PARENT
;
1591 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
, flags
);
1592 if (handler
->pid
< 0)
1598 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1599 * exec()s the requested container binary.
1600 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1601 * right here should be double checked if they'd pose a security risk. (For
1602 * example, any {u}mount() operations performed here will be reflected on the
1605 static int lxc_spawn(struct lxc_handler
*handler
)
1607 __do_close_prot_errno
int data_sock0
= -EBADF
, data_sock1
= -EBADF
;
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
);
1640 data_sock0
= handler
->data_sock
[0];
1641 data_sock1
= handler
->data_sock
[1];
1643 ret
= resolve_clone_flags(handler
);
1647 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1648 if (!lxc_list_empty(&conf
->network
)) {
1650 /* Find gateway addresses from the link device, which is
1651 * no longer accessible inside the container. Do this
1652 * before creating network interfaces, since goto
1653 * out_delete_net does not work before lxc_clone.
1655 ret
= lxc_find_gateway_addresses(handler
);
1657 ERROR("Failed to find gateway addresses");
1661 /* That should be done before the clone because we will
1662 * fill the netdev index and use them in the child.
1664 ret
= lxc_create_network_priv(handler
);
1666 ERROR("Failed to create the network");
1667 goto out_delete_net
;
1672 if (!cgroup_ops
->payload_create(cgroup_ops
, handler
)) {
1673 ERROR("Failed creating cgroups");
1674 goto out_delete_net
;
1677 /* If the rootfs is not a blockdev, prevent the container from marking
1679 * If the container is unprivileged then skip rootfs pinning.
1681 if (!wants_to_map_ids
) {
1682 handler
->pinfd
= pin_rootfs(conf
->rootfs
.path
);
1683 if (handler
->pinfd
== -1)
1684 INFO("Failed to pin the rootfs for container \"%s\"", handler
->name
);
1687 /* Create a process in a new set of namespaces. */
1688 handler
->ns_on_clone_flags
= handler
->ns_clone_flags
;
1689 if (handler
->ns_clone_flags
& CLONE_NEWUSER
) {
1690 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1691 * clone a new user namespace first and only later unshare our
1692 * network namespace to ensure that network devices ownership is
1695 handler
->ns_on_clone_flags
&= ~CLONE_NEWNET
;
1697 /* The cgroup namespace gets unshare()ed not clone()ed. */
1698 handler
->ns_on_clone_flags
&= ~CLONE_NEWCGROUP
;
1703 attacher_pid
= lxc_clone(do_share_ns
, handler
,
1704 CLONE_VFORK
| CLONE_VM
| CLONE_FILES
);
1705 if (attacher_pid
< 0) {
1706 SYSERROR(LXC_CLONE_ERROR
);
1707 goto out_delete_net
;
1710 ret
= wait_for_pid(attacher_pid
);
1712 SYSERROR("Intermediate process failed");
1713 goto out_delete_net
;
1716 handler
->pid
= lxc_raw_clone_cb(do_start
, handler
,
1717 handler
->ns_on_clone_flags
);
1719 if (handler
->pid
< 0) {
1720 SYSERROR(LXC_CLONE_ERROR
);
1721 goto out_delete_net
;
1723 TRACE("Cloned child process %d", handler
->pid
);
1725 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1726 if (handler
->ns_on_clone_flags
& ns_info
[i
].clone_flag
)
1727 INFO("Cloned %s", ns_info
[i
].flag_name
);
1729 if (!lxc_try_preserve_namespaces(handler
, handler
->ns_on_clone_flags
, handler
->pid
)) {
1730 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1731 goto out_delete_net
;
1734 lxc_sync_fini_child(handler
);
1736 /* Map the container uids. The container became an invalid userid the
1737 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1738 * anything immediately, but allows the container to setuid(0) (0 being
1739 * mapped to something else on the host.) later to become a valid uid
1742 if (wants_to_map_ids
) {
1743 if (!handler
->conf
->ns_share
[LXC_NS_USER
] &&
1744 (handler
->conf
->ns_keep
& CLONE_NEWUSER
) == 0) {
1745 ret
= lxc_map_ids(id_map
, handler
->pid
);
1747 ERROR("Failed to set up id mapping.");
1748 goto out_delete_net
;
1753 ret
= lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
);
1755 goto out_delete_net
;
1757 ret
= lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
);
1759 goto out_delete_net
;
1761 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
->conf
, false)) {
1762 ERROR("Failed to setup cgroup limits for container \"%s\"", name
);
1763 goto out_delete_net
;
1766 if (!cgroup_ops
->payload_enter(cgroup_ops
, handler
->pid
))
1767 goto out_delete_net
;
1769 if (!cgroup_ops
->chown(cgroup_ops
, handler
->conf
))
1770 goto out_delete_net
;
1772 /* Now we're ready to preserve the network namespace */
1773 ret
= lxc_try_preserve_ns(handler
->pid
, "net");
1775 if (ret
!= -EOPNOTSUPP
) {
1776 SYSERROR("Failed to preserve net namespace");
1777 goto out_delete_net
;
1780 handler
->nsfd
[LXC_NS_NET
] = ret
;
1781 DEBUG("Preserved net namespace via fd %d", ret
);
1783 ret
= lxc_netns_set_nsid(handler
->nsfd
[LXC_NS_NET
]);
1785 SYSWARN("Failed to allocate new network namespace id");
1787 TRACE("Allocated new network namespace id");
1790 /* Create the network configuration. */
1791 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
1792 ret
= lxc_network_move_created_netdev_priv(handler
->lxcpath
,
1797 ERROR("Failed to create the configured network");
1798 goto out_delete_net
;
1801 ret
= lxc_create_network_unpriv(handler
->lxcpath
, handler
->name
,
1802 &conf
->network
, handler
->pid
, conf
->hooks_version
);
1804 ERROR("Failed to create the configured network");
1805 goto out_delete_net
;
1809 ret
= lxc_network_send_veth_names_to_child(handler
);
1811 ERROR("Failed to send veth names to child");
1812 goto out_delete_net
;
1815 if (!lxc_list_empty(&conf
->procs
)) {
1816 ret
= setup_proc_filesystem(&conf
->procs
, handler
->pid
);
1818 goto out_delete_net
;
1821 /* Tell the child to continue its initialization. We'll get
1822 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1824 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
);
1826 goto out_delete_net
;
1828 if (!lxc_list_empty(&conf
->limits
)) {
1829 ret
= setup_resource_limits(&conf
->limits
, handler
->pid
);
1831 ERROR("Failed to setup resource limits");
1832 goto out_delete_net
;
1836 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
);
1838 goto out_delete_net
;
1840 if (!cgroup_ops
->setup_limits(cgroup_ops
, handler
->conf
, true)) {
1841 ERROR("Failed to setup legacy device cgroup controller limits");
1842 goto out_delete_net
;
1844 TRACE("Set up legacy device cgroup controller limits");
1846 if (handler
->ns_clone_flags
& CLONE_NEWCGROUP
) {
1847 /* Now we're ready to preserve the cgroup namespace */
1848 ret
= lxc_try_preserve_ns(handler
->pid
, "cgroup");
1850 if (ret
!= -EOPNOTSUPP
) {
1851 SYSERROR("Failed to preserve cgroup namespace");
1852 goto out_delete_net
;
1855 handler
->nsfd
[LXC_NS_CGROUP
] = ret
;
1856 DEBUG("Preserved cgroup namespace via fd %d", ret
);
1860 ret
= snprintf(pidstr
, 20, "%d", handler
->pid
);
1861 if (ret
< 0 || ret
>= 20)
1862 goto out_delete_net
;
1864 ret
= setenv("LXC_PID", pidstr
, 1);
1866 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr
);
1868 /* Run any host-side start hooks */
1869 ret
= run_lxc_hooks(name
, "start-host", conf
, NULL
);
1871 ERROR("Failed to run lxc.hook.start-host");
1872 goto out_delete_net
;
1875 /* Tell the child to complete its initialization and wait for it to exec
1876 * or return an error. (The child will never return
1877 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1878 * lxc_sync_barrier_child to return success, or return a different
1879 * value, causing us to error out).
1881 ret
= lxc_sync_barrier_child(handler
, LXC_SYNC_READY_START
);
1883 goto out_delete_net
;
1885 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
1887 ERROR("Failed to receive names and ifindices for network "
1888 "devices from child");
1889 goto out_delete_net
;
1892 /* Now all networks are created, network devices are moved into place,
1893 * and the correct names and ifindices in the respective namespaces have
1894 * been recorded. The corresponding structs have now all been filled. So
1895 * log them for debugging purposes.
1897 lxc_log_configured_netdevs(conf
);
1899 /* Read tty fds allocated by child. */
1900 ret
= lxc_recv_ttys_from_child(handler
);
1902 ERROR("Failed to receive tty info from child process");
1903 goto out_delete_net
;
1906 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, data_sock1
);
1908 SYSERROR("Failed to receive seccomp notify fd from child");
1909 goto out_delete_net
;
1912 ret
= handler
->ops
->post_start(handler
, handler
->data
);
1916 ret
= lxc_set_state(name
, handler
, RUNNING
);
1918 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING
));
1922 lxc_sync_fini(handler
);
1927 if (handler
->ns_clone_flags
& CLONE_NEWNET
)
1928 lxc_delete_network(handler
);
1931 lxc_abort(name
, handler
);
1934 lxc_sync_fini(handler
);
1935 if (handler
->pinfd
>= 0) {
1936 close(handler
->pinfd
);
1937 handler
->pinfd
= -1;
1943 int __lxc_start(const char *name
, struct lxc_handler
*handler
,
1944 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1945 bool daemonize
, int *error_num
)
1948 struct lxc_conf
*conf
= handler
->conf
;
1949 struct cgroup_ops
*cgroup_ops
;
1951 ret
= lxc_init(name
, handler
);
1953 ERROR("Failed to initialize container \"%s\"", name
);
1957 handler
->data
= data
;
1958 handler
->daemonize
= daemonize
;
1959 cgroup_ops
= handler
->cgroup_ops
;
1961 if (!attach_block_device(handler
->conf
)) {
1962 ERROR("Failed to attach block device");
1964 goto out_fini_nonet
;
1967 if (!cgroup_ops
->monitor_create(cgroup_ops
, handler
)) {
1968 ERROR("Failed to create monitor cgroup");
1970 goto out_fini_nonet
;
1973 if (!cgroup_ops
->monitor_enter(cgroup_ops
, handler
->monitor_pid
)) {
1974 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
;
2005 handler
->conf
->reboot
= REBOOT_NONE
;
2007 ret
= lxc_poll(name
, handler
);
2009 ERROR("LXC mainloop exited with error: %d", ret
);
2013 if (!handler
->init_died
&& handler
->pid
> 0) {
2014 ERROR("Child process is not killed");
2019 status
= lxc_wait_for_pid_status(handler
->pid
);
2021 SYSERROR("Failed to retrieve status for %d", handler
->pid
);
2023 /* If the child process exited but was not signaled, it didn't call
2024 * reboot. This should mean it was an lxc-execute which simply exited.
2025 * In any case, treat it as a 'halt'.
2027 if (WIFSIGNALED(status
)) {
2028 switch(WTERMSIG(status
)) {
2029 case SIGINT
: /* halt */
2030 DEBUG("Container \"%s\" is halting", name
);
2032 case SIGHUP
: /* reboot */
2033 DEBUG("Container \"%s\" is rebooting", name
);
2034 handler
->conf
->reboot
= REBOOT_REQ
;
2036 case SIGSYS
: /* seccomp */
2037 DEBUG("Container \"%s\" violated its seccomp policy", name
);
2040 DEBUG("Unknown exit status for container \"%s\" init %d", name
, WTERMSIG(status
));
2045 ret
= lxc_restore_phys_nics_to_netns(handler
);
2047 ERROR("Failed to move physical network devices back to parent "
2048 "network namespace");
2050 if (handler
->pinfd
>= 0) {
2051 close(handler
->pinfd
);
2052 handler
->pinfd
= -1;
2055 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
2056 lxc_error_set_and_log(handler
->pid
, status
);
2058 *error_num
= handler
->exit_status
;
2061 lxc_delete_network(handler
);
2063 out_detach_blockdev
:
2064 detach_block_device(handler
->conf
);
2067 lxc_fini(name
, handler
);
2071 lxc_abort(name
, handler
);
2079 static int start(struct lxc_handler
*handler
, void* data
)
2081 struct start_args
*arg
= data
;
2083 NOTICE("Exec'ing \"%s\"", arg
->argv
[0]);
2085 execvp(arg
->argv
[0], arg
->argv
);
2086 SYSERROR("Failed to exec \"%s\"", arg
->argv
[0]);
2090 static int post_start(struct lxc_handler
*handler
, void* data
)
2092 struct start_args
*arg
= data
;
2094 NOTICE("Started \"%s\" with pid \"%d\"", arg
->argv
[0], handler
->pid
);
2098 static struct lxc_operations start_ops
= {
2100 .post_start
= post_start
2103 int lxc_start(const char *name
, char *const argv
[], struct lxc_handler
*handler
,
2104 const char *lxcpath
, bool daemonize
, int *error_num
)
2106 struct start_args start_arg
= {
2110 TRACE("Doing lxc_start");
2111 return __lxc_start(name
, handler
, &start_ops
, &start_arg
, lxcpath
, daemonize
, error_num
);
2114 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
2117 char destroy
[PATH_MAX
];
2118 struct lxc_container
*c
;
2122 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
2123 bret
= do_destroy_container(handler
);
2125 ERROR("Error destroying rootfs for container \"%s\"", name
);
2129 INFO("Destroyed rootfs for container \"%s\"", name
);
2131 ret
= snprintf(destroy
, PATH_MAX
, "%s/%s", handler
->lxcpath
, name
);
2132 if (ret
< 0 || ret
>= PATH_MAX
) {
2133 ERROR("Error destroying directory for container \"%s\"", name
);
2137 c
= lxc_container_new(name
, handler
->lxcpath
);
2139 if (container_disk_lock(c
)) {
2140 INFO("Could not update lxc_snapshots file");
2141 lxc_container_put(c
);
2143 mod_all_rdeps(c
, false);
2144 container_disk_unlock(c
);
2145 lxc_container_put(c
);
2149 if (!handler
->am_root
)
2150 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
2151 destroy
, "lxc_rmdir_onedev_wrapper");
2153 ret
= lxc_rmdir_onedev(destroy
, NULL
);
2156 ERROR("Error destroying directory for container \"%s\"", name
);
2159 INFO("Destroyed directory for container \"%s\"", name
);
2162 static int lxc_rmdir_onedev_wrapper(void *data
)
2164 char *arg
= (char *) data
;
2165 return lxc_rmdir_onedev(arg
, NULL
);
2168 static bool do_destroy_container(struct lxc_handler
*handler
)
2172 if (!handler
->am_root
) {
2173 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
2174 handler
->conf
, "storage_destroy_wrapper");
2181 return storage_destroy(handler
->conf
);