]>
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 #ifndef HAVE_DECL_PR_CAPBSET_DROP
56 #define PR_CAPBSET_DROP 24
59 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
60 #define PR_SET_NO_NEW_PRIVS 38
63 #ifndef 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"
77 #include "lxccontainer.h"
79 #include "lxcseccomp.h"
82 #include "namespace.h"
86 #include "storage_utils.h"
91 lxc_log_define(lxc_start
, lxc
);
93 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
94 static bool do_destroy_container(struct lxc_handler
*handler
);
95 static int lxc_rmdir_onedev_wrapper(void *data
);
96 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
99 static void print_top_failing_dir(const char *path
)
101 size_t len
= strlen(path
);
102 char *copy
= alloca(len
+ 1), *p
, *e
, saved
;
108 while (p
< e
&& *p
== '/')
110 while (p
< e
&& *p
!= '/')
114 if (access(copy
, X_OK
)) {
115 SYSERROR("Could not access %s. Please grant it x "
116 "access, or add an ACL for the container "
124 static void close_ns(int ns_fd
[LXC_NS_MAX
])
128 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
136 /* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
138 * Return true on success, false on failure.
140 static bool preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
)
144 for (i
= 0; i
< LXC_NS_MAX
; i
++)
147 ret
= lxc_preserve_ns(pid
, "");
149 SYSERROR("Kernel does not support attaching to namespaces.");
155 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
156 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
158 ns_fd
[i
] = lxc_preserve_ns(pid
, ns_info
[i
].proc_name
);
167 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info
[i
].proc_name
);
169 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info
[i
].proc_name
, strerror(errno
));
174 static int attach_ns(const int ns_fd
[LXC_NS_MAX
]) {
177 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
181 if (setns(ns_fd
[i
], 0) != 0)
187 SYSERROR("Failed to attach %s namespace.", ns_info
[i
].proc_name
);
191 static int match_fd(int fd
)
193 return (fd
== 0 || fd
== 1 || fd
== 2);
196 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
,
197 int *fds_to_ignore
, size_t len_fds
)
199 struct dirent
*direntp
;
204 if (conf
&& conf
->close_all_fds
)
208 dir
= opendir("/proc/self/fd");
210 WARN("Failed to open directory: %s.", strerror(errno
));
216 while ((direntp
= readdir(dir
))) {
220 if (!strcmp(direntp
->d_name
, "."))
223 if (!strcmp(direntp
->d_name
, ".."))
226 if (lxc_safe_int(direntp
->d_name
, &fd
) < 0) {
227 INFO("Could not parse file descriptor for: %s", direntp
->d_name
);
231 for (i
= 0; i
< len_fds
; i
++)
232 if (fds_to_ignore
[i
] == fd
)
235 if (fd
== fddir
|| fd
== lxc_log_fd
||
236 (i
< len_fds
&& fd
== fds_to_ignore
[i
]))
239 if (current_config
&& fd
== current_config
->logfd
)
248 INFO("Closed inherited fd: %d.", fd
);
251 WARN("Inherited fd: %d.", fd
);
254 /* Only enable syslog at this point to avoid the above logging function
255 * to open a new fd and make the check_inherited function enter an
258 lxc_log_enable_syslog();
260 closedir(dir
); /* cannot fail */
264 static int setup_signal_fd(sigset_t
*oldmask
)
269 /* Block everything except serious error signals. */
270 if (sigfillset(&mask
) ||
271 sigdelset(&mask
, SIGILL
) ||
272 sigdelset(&mask
, SIGSEGV
) ||
273 sigdelset(&mask
, SIGBUS
) ||
274 sigdelset(&mask
, SIGWINCH
) ||
275 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
276 SYSERROR("Failed to set signal mask.");
280 fd
= signalfd(-1, &mask
, 0);
282 SYSERROR("Failed to create signal file descriptor.");
286 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
287 SYSERROR("Failed to set FD_CLOEXEC on the signal file descriptor: %d.", fd
);
292 DEBUG("Set SIGCHLD handler with file descriptor: %d.", fd
);
297 static int signal_handler(int fd
, uint32_t events
, void *data
,
298 struct lxc_epoll_descr
*descr
)
300 struct signalfd_siginfo siginfo
;
304 bool init_died
= false;
306 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
308 ERROR("Failed to read signal info from signal file descriptor: %d.", fd
);
312 if (ret
!= sizeof(siginfo
)) {
313 ERROR("Unexpected size for siginfo struct.");
317 /* Check whether init is running. */
319 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
320 if (ret
== 0 && info
.si_pid
== *pid
)
323 if (siginfo
.ssi_signo
!= SIGCHLD
) {
324 kill(*pid
, siginfo
.ssi_signo
);
325 INFO("Forwarded signal %d to pid %d.", siginfo
.ssi_signo
, *pid
);
326 return init_died
? 1 : 0;
329 if (siginfo
.ssi_code
== CLD_STOPPED
) {
330 INFO("Container init process was stopped.");
331 return init_died
? 1 : 0;
332 } else if (siginfo
.ssi_code
== CLD_CONTINUED
) {
333 INFO("Container init process was continued.");
334 return init_died
? 1 : 0;
337 /* More robustness, protect ourself from a SIGCHLD sent
338 * by a process different from the container init.
340 if (siginfo
.ssi_pid
!= *pid
) {
341 NOTICE("Received SIGCHLD from pid %d instead of container init %d.", siginfo
.ssi_pid
, *pid
);
342 return init_died
? 1 : 0;
345 DEBUG("Container init process %d exited.", *pid
);
349 static int lxc_serve_state_clients(const char *name
,
350 struct lxc_handler
*handler
,
354 struct lxc_list
*cur
, *next
;
355 struct state_client
*client
;
356 struct lxc_msg msg
= {.type
= lxc_msg_state
, .value
= state
};
360 /* Only set state under process lock held so that we don't cause
361 * lxc_cmd_add_state_client() to miss a state.
363 handler
->state
= state
;
364 TRACE("set container state to %s", lxc_state2str(state
));
366 if (lxc_list_empty(&handler
->state_clients
)) {
367 TRACE("no state clients registered");
369 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
373 strncpy(msg
.name
, name
, sizeof(msg
.name
));
374 msg
.name
[sizeof(msg
.name
) - 1] = 0;
376 lxc_list_for_each_safe(cur
, &handler
->state_clients
, next
) {
379 if (!client
->states
[state
]) {
380 TRACE("state %s not registered for state client %d",
381 lxc_state2str(state
), client
->clientfd
);
385 TRACE("sending state %s to state client %d",
386 lxc_state2str(state
), client
->clientfd
);
389 ret
= send(client
->clientfd
, &msg
, sizeof(msg
), 0);
391 if (errno
== EINTR
) {
392 TRACE("Caught EINTR; retrying");
396 ERROR("failed to send message to client");
399 /* kick client from list */
400 close(client
->clientfd
);
410 static int lxc_serve_state_socket_pair(const char *name
,
411 struct lxc_handler
*handler
,
416 if (!handler
->backgrounded
||
417 handler
->state_socket_pair
[1] < 0 ||
421 /* Close read end of the socket pair. */
422 close(handler
->state_socket_pair
[0]);
423 handler
->state_socket_pair
[0] = -1;
426 ret
= lxc_abstract_unix_send_credential(handler
->state_socket_pair
[1],
427 &(int){state
}, sizeof(int));
428 if (ret
!= sizeof(int)) {
431 SYSERROR("Failed to send state to %d",
432 handler
->state_socket_pair
[1]);
436 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state
),
437 handler
->state_socket_pair
[1]);
439 /* Close write end of the socket pair. */
440 close(handler
->state_socket_pair
[1]);
441 handler
->state_socket_pair
[1] = -1;
446 int lxc_set_state(const char *name
, struct lxc_handler
*handler
,
451 ret
= lxc_serve_state_socket_pair(name
, handler
, state
);
453 ERROR("Failed to synchronize via anonymous pair of unix sockets");
457 ret
= lxc_serve_state_clients(name
, handler
, state
);
461 /* This function will try to connect to the legacy lxc-monitord state
462 * server and only exists for backwards compatibility.
464 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
469 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
471 int sigfd
= handler
->sigfd
;
472 int pid
= handler
->pid
;
473 struct lxc_epoll_descr descr
;
475 if (lxc_mainloop_open(&descr
)) {
476 ERROR("Failed to create LXC mainloop.");
480 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
481 ERROR("Failed to add signal handler with file descriptor %d to LXC mainloop.", sigfd
);
482 goto out_mainloop_open
;
485 if (lxc_console_mainloop_add(&descr
, handler
->conf
)) {
486 ERROR("Failed to add console handler to LXC mainloop.");
487 goto out_mainloop_open
;
490 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
491 ERROR("Failed to add command handler to LXC mainloop.");
492 goto out_mainloop_open
;
495 TRACE("lxc mainloop is ready");
497 return lxc_mainloop(&descr
, -1);
500 lxc_mainloop_close(&descr
);
508 void lxc_free_handler(struct lxc_handler
*handler
)
510 if (handler
->conf
&& handler
->conf
->maincmd_fd
)
511 close(handler
->conf
->maincmd_fd
);
513 if (handler
->state_socket_pair
[0] >= 0)
514 close(handler
->state_socket_pair
[0]);
516 if (handler
->state_socket_pair
[1] >= 0)
517 close(handler
->state_socket_pair
[1]);
522 handler
->conf
= NULL
;
526 struct lxc_handler
*lxc_init_handler(const char *name
, struct lxc_conf
*conf
,
527 const char *lxcpath
, bool daemonize
)
530 struct lxc_handler
*handler
;
532 handler
= malloc(sizeof(*handler
));
534 ERROR("failed to allocate memory");
538 memset(handler
, 0, sizeof(*handler
));
540 /* Note that am_unpriv() checks the effective uid. We probably don't
541 * care if we are real root only if we are running as root so this
544 handler
->am_root
= !am_unpriv();
545 handler
->data_sock
[0] = handler
->data_sock
[1] = -1;
546 handler
->conf
= conf
;
547 handler
->lxcpath
= lxcpath
;
549 handler
->state_socket_pair
[0] = handler
->state_socket_pair
[1] = -1;
550 lxc_list_init(&handler
->state_clients
);
552 for (i
= 0; i
< LXC_NS_MAX
; i
++)
553 handler
->nsfd
[i
] = -1;
555 handler
->name
= strdup(name
);
556 if (!handler
->name
) {
557 ERROR("failed to allocate memory");
561 if (daemonize
&& !handler
->conf
->reboot
) {
562 /* Create socketpair() to synchronize on daemonized startup.
563 * When the container reboots we don't need to synchronize again
564 * currently so don't open another socketpair().
566 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
567 handler
->state_socket_pair
);
569 ERROR("Failed to create anonymous pair of unix sockets");
572 TRACE("Created anonymous pair {%d,%d} of unix sockets",
573 handler
->state_socket_pair
[0],
574 handler
->state_socket_pair
[1]);
577 if (lxc_cmd_init(name
, handler
, lxcpath
)) {
578 ERROR("failed to set up command socket");
582 TRACE("unix domain socket %d for command server is ready",
583 handler
->conf
->maincmd_fd
);
588 lxc_free_handler(handler
);
593 int lxc_init(const char *name
, struct lxc_handler
*handler
)
595 struct lxc_conf
*conf
= handler
->conf
;
598 TRACE("initialized LSM");
600 if (lxc_read_seccomp_config(conf
) != 0) {
601 ERROR("Failed loading seccomp policy.");
602 goto out_close_maincmd_fd
;
604 TRACE("read seccomp policy");
606 /* Begin by setting the state to STARTING. */
607 if (lxc_set_state(name
, handler
, STARTING
)) {
608 ERROR("Failed to set state for container \"%s\" to \"%s\".", name
, lxc_state2str(STARTING
));
609 goto out_close_maincmd_fd
;
611 TRACE("set container state to \"STARTING\"");
613 /* Start of environment variable setup for hooks. */
614 if (name
&& setenv("LXC_NAME", name
, 1))
615 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name
);
617 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
618 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf
->rcfile
);
620 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
621 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf
->rootfs
.mount
);
623 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
624 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf
->rootfs
.path
);
626 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
627 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf
->console
.path
);
629 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
630 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf
->console
.log_path
);
632 if (setenv("LXC_CGNS_AWARE", "1", 1))
633 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
634 /* End of environment variable setup for hooks. */
636 TRACE("set environment variables");
638 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
639 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name
);
642 TRACE("ran pre-start hooks");
644 /* The signal fd has to be created before forking otherwise if the child
645 * process exits before we setup the signal fd, the event will be lost
646 * and the command will be stuck.
648 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
649 if (handler
->sigfd
< 0) {
650 ERROR("Failed to setup SIGCHLD fd handler.");
653 TRACE("set up signal fd");
655 /* Do this after setting up signals since it might unblock SIGWINCH. */
656 if (lxc_console_create(conf
)) {
657 ERROR("Failed to create console for container \"%s\".", name
);
658 goto out_restore_sigmask
;
660 TRACE("created console");
662 if (lxc_ttys_shift_ids(conf
) < 0) {
663 ERROR("Failed to shift tty into container.");
664 goto out_restore_sigmask
;
666 TRACE("shifted tty ids");
668 INFO("container \"%s\" is initialized", name
);
672 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
674 lxc_delete_tty(&conf
->tty_info
);
676 lxc_set_state(name
, handler
, ABORTING
);
677 out_close_maincmd_fd
:
678 close(conf
->maincmd_fd
);
679 conf
->maincmd_fd
= -1;
683 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
686 struct lxc_list
*cur
, *next
;
687 pid_t self
= getpid();
688 char *namespaces
[LXC_NS_MAX
+ 1];
689 size_t namespace_count
= 0;
691 /* The STOPPING state is there for future cleanup code which can take
694 lxc_set_state(name
, handler
, STOPPING
);
696 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
697 if (handler
->nsfd
[i
] != -1) {
698 rc
= asprintf(&namespaces
[namespace_count
], "%s:/proc/%d/fd/%d",
699 ns_info
[i
].proc_name
, self
, handler
->nsfd
[i
]);
701 SYSERROR("Failed to allocate memory.");
707 namespaces
[namespace_count
] = NULL
;
709 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1))
710 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
712 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1))
713 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
715 if (run_lxc_hooks(name
, "stop", handler
->conf
, handler
->lxcpath
, namespaces
))
716 ERROR("Failed to run lxc.hook.stop for container \"%s\".", name
);
718 while (namespace_count
--)
719 free(namespaces
[namespace_count
]);
720 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
721 if (handler
->nsfd
[i
] != -1) {
722 close(handler
->nsfd
[i
]);
723 handler
->nsfd
[i
] = -1;
727 if (handler
->netnsfd
>= 0) {
728 close(handler
->netnsfd
);
729 handler
->netnsfd
= -1;
732 cgroup_destroy(handler
);
734 lxc_set_state(name
, handler
, STOPPED
);
736 /* close command socket */
737 close(handler
->conf
->maincmd_fd
);
738 handler
->conf
->maincmd_fd
= -1;
740 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
)) {
741 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name
);
742 if (handler
->conf
->reboot
) {
743 WARN("Container will be stopped instead of rebooted.");
744 handler
->conf
->reboot
= 0;
745 if (setenv("LXC_TARGET", "stop", 1))
746 WARN("Failed to set environment variable: LXC_TARGET=stop.");
750 /* Reset mask set by setup_signal_fd. */
751 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
752 WARN("Failed to restore signal mask.");
754 lxc_console_delete(&handler
->conf
->console
);
755 lxc_delete_tty(&handler
->conf
->tty_info
);
757 /* The command socket is now closed, no more state clients can register
758 * themselves from now on. So free the list of state clients.
760 lxc_list_for_each_safe(cur
, &handler
->state_clients
, next
) {
761 struct state_client
*client
= cur
->elem
;
762 /* close state client socket */
763 close(client
->clientfd
);
769 if (handler
->data_sock
[0] != -1) {
770 close(handler
->data_sock
[0]);
771 close(handler
->data_sock
[1]);
774 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1)
775 lxc_destroy_container_on_signal(handler
, name
);
781 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
785 lxc_set_state(name
, handler
, ABORTING
);
786 if (handler
->pid
> 0)
787 kill(handler
->pid
, SIGKILL
);
788 while ((ret
= waitpid(-1, &status
, 0)) > 0) {
793 static int do_start(void *data
)
795 struct lxc_list
*iterator
;
796 struct lxc_handler
*handler
= data
;
797 int devnull_fd
= -1, ret
;
800 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
801 SYSERROR("Failed to set signal mask.");
805 /* This prctl must be before the synchro, so if the parent dies before
806 * we set the parent death signal, we will detect its death with the
807 * synchro right after, otherwise we have a window where the parent can
808 * exit before we set the pdeath signal leading to a unsupervized
811 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
812 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL.");
816 lxc_sync_fini_parent(handler
);
818 /* Don't leak the pinfd to the container. */
819 if (handler
->pinfd
>= 0) {
820 close(handler
->pinfd
);
823 if (lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
))
826 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
827 * https://github.com/lxc/lxd/issues/1978.
829 if ((handler
->clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
830 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
831 ret
= unshare(CLONE_NEWNET
);
833 SYSERROR("Failed to unshare CLONE_NEWNET.");
834 goto out_warn_father
;
836 INFO("Unshared CLONE_NEWNET.");
839 /* Tell the parent task it can begin to configure the container and wait
842 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
845 if (lxc_network_recv_veth_names_from_parent(handler
) < 0) {
846 ERROR("Failed to receive veth names from parent");
847 goto out_warn_father
;
850 /* If we are in a new user namespace, become root there to have
851 * privilege over our namespace.
853 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
854 if (lxc_switch_uid_gid(0, 0) < 0)
855 goto out_warn_father
;
857 /* Drop groups only after we switched to a valid gid in the new
860 if (lxc_setgroups(0, NULL
) < 0)
861 goto out_warn_father
;
864 if (access(handler
->lxcpath
, X_OK
)) {
865 print_top_failing_dir(handler
->lxcpath
);
866 goto out_warn_father
;
869 ret
= snprintf(path
, sizeof(path
), "%s/dev/null", handler
->conf
->rootfs
.mount
);
870 if (ret
< 0 || ret
>= sizeof(path
))
871 goto out_warn_father
;
873 /* In order to checkpoint restore, we need to have everything in the
874 * same mount namespace. However, some containers may not have a
875 * reasonable /dev (in particular, they may not have /dev/null), so we
876 * can't set init's std fds to /dev/null by opening it from inside the
879 * If that's the case, fall back to using the host's /dev/null. This
880 * means that migration won't work, but at least we won't spew output
881 * where it isn't wanted.
883 if (handler
->backgrounded
&& !handler
->conf
->autodev
&& access(path
, F_OK
) < 0) {
884 devnull_fd
= open_devnull();
887 goto out_warn_father
;
888 WARN("Using /dev/null from the host for container init's "
889 "standard file descriptors. Migration will not work.");
892 /* Ask father to setup cgroups and wait for him to finish. */
893 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
896 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
897 * earlier we end up with a wrong view of /proc/self/cgroup. For
898 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
899 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
900 * /proc/self/cgroup would show us:
904 * whereas it should actually show
908 if (cgns_supported()) {
909 if (unshare(CLONE_NEWCGROUP
) < 0) {
910 INFO("Failed to unshare CLONE_NEWCGROUP.");
911 goto out_warn_father
;
913 INFO("Unshared CLONE_NEWCGROUP.");
916 /* The clearenv() and putenv() calls have been moved here to allow us to
917 * use environment variables passed to the various hooks, such as the
918 * start hook above. Not all of the variables like CONFIG_PATH or ROOTFS
919 * are valid in this context but others are.
922 SYSERROR("Failed to clear environment.");
923 /* Don't error out though. */
926 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
927 if (putenv((char *)iterator
->elem
)) {
928 SYSERROR("Failed to set environment variable: %s.", (char *)iterator
->elem
);
929 goto out_warn_father
;
933 /* Setup the container, ip, names, utsname, ... */
934 ret
= lxc_setup(handler
);
935 close(handler
->data_sock
[0]);
936 close(handler
->data_sock
[1]);
938 ERROR("Failed to setup container \"%s\".", handler
->name
);
939 goto out_warn_father
;
942 /* Set the label to change to when we exec(2) the container's init. */
943 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
944 goto out_warn_father
;
946 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
947 * before we aren't allowed anymore.
949 if (handler
->conf
->no_new_privs
) {
950 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
951 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
952 goto out_warn_father
;
954 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
957 /* Some init's such as busybox will set sane tty settings on stdin,
958 * stdout, stderr which it thinks is the console. We already set them
959 * the way we wanted on the real terminal, and we want init to do its
960 * setup on its console ie. the pty allocated in lxc_console_create() so
961 * make sure that that pty is stdin,stdout,stderr.
963 if (handler
->conf
->console
.slave
>= 0)
964 if (set_stdfds(handler
->conf
->console
.slave
) < 0) {
965 ERROR("Failed to redirect std{in,out,err} to pty file "
967 handler
->conf
->console
.slave
);
968 goto out_warn_father
;
971 /* If we mounted a temporary proc, then unmount it now. */
972 tmp_proc_unmount(handler
->conf
);
974 if (lxc_seccomp_load(handler
->conf
) != 0)
975 goto out_warn_father
;
977 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
978 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler
->name
);
979 goto out_warn_father
;
982 close(handler
->sigfd
);
984 if (devnull_fd
< 0) {
985 devnull_fd
= open_devnull();
988 goto out_warn_father
;
991 if (handler
->conf
->console
.slave
< 0 && handler
->backgrounded
)
992 if (set_stdfds(devnull_fd
) < 0) {
993 ERROR("Failed to redirect std{in,out,err} to "
995 goto out_warn_father
;
998 if (devnull_fd
>= 0) {
1005 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP_LIMITS
))
1006 goto out_warn_father
;
1008 if (putenv("container=lxc")) {
1009 SYSERROR("Failed to set environment variable: container=lxc.");
1010 goto out_warn_father
;
1013 if (handler
->conf
->pty_names
) {
1014 if (putenv(handler
->conf
->pty_names
)) {
1015 SYSERROR("Failed to set environment variable for container ptys.");
1016 goto out_warn_father
;
1020 /* The container has been setup. We can now switch to an unprivileged
1023 if (handler
->conf
->is_execute
) {
1024 bool have_cap_setgid
;
1025 uid_t new_uid
= handler
->conf
->init_uid
;
1026 gid_t new_gid
= handler
->conf
->init_gid
;
1028 /* If we are in a new user namespace we already dropped all
1029 * groups when we switched to root in the new user namespace
1030 * further above. Only drop groups if we can, so ensure that we
1031 * have necessary privilege.
1034 have_cap_setgid
= lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
);
1036 have_cap_setgid
= false;
1038 if (lxc_list_empty(&handler
->conf
->id_map
) && have_cap_setgid
) {
1039 if (lxc_setgroups(0, NULL
) < 0)
1040 goto out_warn_father
;
1043 if (lxc_switch_uid_gid(new_uid
, new_gid
) < 0)
1044 goto out_warn_father
;
1047 /* After this call, we are in error because this ops should not return
1050 handler
->ops
->start(handler
, handler
->data
);
1053 /* We want the parent to know something went wrong, so we return a
1054 * special error code.
1056 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
1059 if (devnull_fd
>= 0)
1065 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
1068 struct lxc_pty_info
*pty_info
;
1070 int sock
= handler
->data_sock
[1];
1071 struct lxc_conf
*conf
= handler
->conf
;
1072 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
1077 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
) * conf
->tty
);
1078 if (!tty_info
->pty_info
)
1081 for (i
= 0; i
< conf
->tty
; i
++) {
1084 ret
= lxc_abstract_unix_recv_fds(sock
, ttyfds
, 2, NULL
, 0);
1088 pty_info
= &tty_info
->pty_info
[i
];
1090 pty_info
->master
= ttyfds
[0];
1091 pty_info
->slave
= ttyfds
[1];
1092 TRACE("Received pty with master fd %d and slave fd %d from "
1093 "parent", pty_info
->master
, pty_info
->slave
);
1096 ERROR("Failed to receive %d ttys from child: %s", conf
->tty
,
1099 TRACE("Received %d ttys from child", conf
->tty
);
1101 tty_info
->nbtty
= conf
->tty
;
1106 void resolve_clone_flags(struct lxc_handler
*handler
)
1108 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
1110 if (!lxc_list_empty(&handler
->conf
->id_map
))
1111 handler
->clone_flags
|= CLONE_NEWUSER
;
1113 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
1114 if (!lxc_requests_empty_network(handler
))
1115 handler
->clone_flags
|= CLONE_NEWNET
;
1117 INFO("Inheriting a NET namespace.");
1120 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1)
1121 handler
->clone_flags
|= CLONE_NEWIPC
;
1123 INFO("Inheriting an IPC namespace.");
1125 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1)
1126 handler
->clone_flags
|= CLONE_NEWUTS
;
1128 INFO("Inheriting a UTS namespace.");
1131 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1132 * exec()s the requested container binary.
1133 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1134 * right here should be double checked if they'd pose a security risk. (For
1135 * example, any {u}mount() operations performed here will be reflected on the
1138 static int lxc_spawn(struct lxc_handler
*handler
)
1141 const char *name
= handler
->name
;
1142 bool wants_to_map_ids
;
1143 int saved_ns_fd
[LXC_NS_MAX
];
1144 struct lxc_list
*id_map
;
1145 int preserve_mask
= 0;
1146 bool cgroups_connected
= false;
1148 id_map
= &handler
->conf
->id_map
;
1149 wants_to_map_ids
= !lxc_list_empty(id_map
);
1151 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1152 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
1153 preserve_mask
|= ns_info
[i
].clone_flag
;
1155 if (lxc_sync_init(handler
))
1158 ret
= socketpair(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0,
1159 handler
->data_sock
);
1161 lxc_sync_fini(handler
);
1165 resolve_clone_flags(handler
);
1167 if (handler
->clone_flags
& CLONE_NEWNET
) {
1168 if (!lxc_list_empty(&handler
->conf
->network
)) {
1170 /* Find gateway addresses from the link device, which is
1171 * no longer accessible inside the container. Do this
1172 * before creating network interfaces, since goto
1173 * out_delete_net does not work before lxc_clone.
1175 if (lxc_find_gateway_addresses(handler
)) {
1176 ERROR("Failed to find gateway addresses.");
1177 lxc_sync_fini(handler
);
1181 /* That should be done before the clone because we will
1182 * fill the netdev index and use them in the child.
1184 if (lxc_create_network_priv(handler
)) {
1185 ERROR("Failed to create the network.");
1186 lxc_sync_fini(handler
);
1192 if (!cgroup_init(handler
)) {
1193 ERROR("Failed initializing cgroup support.");
1194 goto out_delete_net
;
1197 cgroups_connected
= true;
1199 if (!cgroup_create(handler
)) {
1200 ERROR("Failed creating cgroups.");
1201 goto out_delete_net
;
1204 /* If the rootfs is not a blockdev, prevent the container from marking
1206 * If the container is unprivileged then skip rootfs pinning.
1208 if (!wants_to_map_ids
) {
1209 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
1210 if (handler
->pinfd
== -1)
1211 INFO("Failed to pin the rootfs for container \"%s\".", handler
->name
);
1214 if (!preserve_ns(saved_ns_fd
, preserve_mask
, getpid()))
1215 goto out_delete_net
;
1217 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
1218 goto out_delete_net
;
1220 /* Create a process in a new set of namespaces. */
1221 flags
= handler
->clone_flags
;
1222 if (handler
->clone_flags
& CLONE_NEWUSER
) {
1223 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1224 * clone a new user namespace first and only later unshare our
1225 * network namespace to ensure that network devices ownership is
1228 flags
&= ~CLONE_NEWNET
;
1230 handler
->pid
= lxc_clone(do_start
, handler
, flags
);
1231 if (handler
->pid
< 0) {
1232 SYSERROR("Failed to clone a new set of namespaces.");
1233 goto out_delete_net
;
1236 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1237 if (flags
& ns_info
[i
].clone_flag
)
1238 INFO("Cloned %s.", ns_info
[i
].flag_name
);
1240 if (!preserve_ns(handler
->nsfd
, handler
->clone_flags
| preserve_mask
, handler
->pid
))
1241 INFO("Failed to preserve namespace for lxc.hook.stop.");
1243 if (attach_ns(saved_ns_fd
))
1244 WARN("Failed to restore saved namespaces.");
1246 lxc_sync_fini_child(handler
);
1248 /* Map the container uids. The container became an invalid userid the
1249 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1250 * anything immediately, but allows the container to setuid(0) (0 being
1251 * mapped to something else on the host.) later to become a valid uid
1254 if (wants_to_map_ids
&& lxc_map_ids(id_map
, handler
->pid
)) {
1255 ERROR("Failed to set up id mapping.");
1256 goto out_delete_net
;
1259 if (lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
))
1260 goto out_delete_net
;
1262 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
))
1263 goto out_delete_net
;
1265 if (!cgroup_create_legacy(handler
)) {
1266 ERROR("Failed to setup legacy cgroups for container \"%s\".", name
);
1267 goto out_delete_net
;
1269 if (!cgroup_setup_limits(handler
, false)) {
1270 ERROR("Failed to setup cgroup limits for container \"%s\".", name
);
1271 goto out_delete_net
;
1274 if (!cgroup_enter(handler
))
1275 goto out_delete_net
;
1277 if (!cgroup_chown(handler
))
1278 goto out_delete_net
;
1280 handler
->netnsfd
= lxc_preserve_ns(handler
->pid
, "net");
1281 if (handler
->netnsfd
< 0) {
1282 ERROR("Failed to preserve network namespace");
1283 goto out_delete_net
;
1286 /* Create the network configuration. */
1287 if (handler
->clone_flags
& CLONE_NEWNET
) {
1288 if (lxc_network_move_created_netdev_priv(handler
->lxcpath
,
1290 &handler
->conf
->network
,
1292 ERROR("Failed to create the configured network.");
1293 goto out_delete_net
;
1296 if (lxc_create_network_unpriv(handler
->lxcpath
, handler
->name
,
1297 &handler
->conf
->network
,
1299 ERROR("Failed to create the configured network.");
1300 goto out_delete_net
;
1304 if (lxc_network_send_veth_names_to_child(handler
) < 0) {
1305 ERROR("Failed to send veth names to child");
1306 goto out_delete_net
;
1309 /* Tell the child to continue its initialization. We'll get
1310 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1312 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1313 goto out_delete_net
;
1315 if (!lxc_list_empty(&handler
->conf
->limits
) && setup_resource_limits(&handler
->conf
->limits
, handler
->pid
)) {
1316 ERROR("failed to setup resource limits for '%s'", name
);
1317 goto out_delete_net
;
1320 if (lxc_sync_barrier_child(handler
, LXC_SYNC_CGROUP_UNSHARE
))
1321 goto out_delete_net
;
1323 if (!cgroup_setup_limits(handler
, true)) {
1324 ERROR("Failed to setup the devices cgroup for container \"%s\".", name
);
1325 goto out_delete_net
;
1327 TRACE("Set up cgroup device limits");
1329 cgroup_disconnect();
1330 cgroups_connected
= false;
1332 /* Tell the child to complete its initialization and wait for it to exec
1333 * or return an error. (The child will never return
1334 * LXC_SYNC_POST_CGROUP+1. It will either close the sync pipe, causing
1335 * lxc_sync_barrier_child to return success, or return a different
1336 * value, causing us to error out).
1338 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1341 if (lxc_network_recv_name_and_ifindex_from_child(handler
) < 0) {
1342 ERROR("Failed to receive names and ifindices for network "
1343 "devices from child");
1344 goto out_delete_net
;
1347 /* Now all networks are created, network devices are moved into place,
1348 * and the correct names and ifindeces in the respective namespaces have
1349 * been recorded. The corresponding structs have now all been filled. So
1350 * log them for debugging purposes.
1352 lxc_log_configured_netdevs(handler
->conf
);
1354 /* Read tty fds allocated by child. */
1355 if (lxc_recv_ttys_from_child(handler
) < 0) {
1356 ERROR("Failed to receive tty info from child process.");
1357 goto out_delete_net
;
1360 if (handler
->ops
->post_start(handler
, handler
->data
))
1363 if (lxc_set_state(name
, handler
, RUNNING
)) {
1364 ERROR("Failed to set state for container \"%s\" to \"%s\".", name
,
1365 lxc_state2str(RUNNING
));
1369 lxc_sync_fini(handler
);
1374 if (cgroups_connected
)
1375 cgroup_disconnect();
1377 if (handler
->clone_flags
& CLONE_NEWNET
) {
1378 DEBUG("Tearing down network devices");
1379 if (!lxc_delete_network_priv(handler
))
1380 DEBUG("Failed tearing down network devices");
1382 if (!lxc_delete_network_unpriv(handler
))
1383 DEBUG("Failed tearing down network devices");
1387 lxc_abort(name
, handler
);
1388 lxc_sync_fini(handler
);
1389 if (handler
->pinfd
>= 0) {
1390 close(handler
->pinfd
);
1391 handler
->pinfd
= -1;
1394 if (handler
->netnsfd
>= 0) {
1395 close(handler
->netnsfd
);
1396 handler
->netnsfd
= -1;
1402 int __lxc_start(const char *name
, struct lxc_handler
*handler
,
1403 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1408 struct lxc_conf
*conf
= handler
->conf
;
1410 if (lxc_init(name
, handler
) < 0) {
1411 ERROR("Failed to initialize container \"%s\".", name
);
1415 handler
->data
= data
;
1416 handler
->backgrounded
= backgrounded
;
1417 handler
->netnsfd
= -1;
1419 if (!attach_block_device(handler
->conf
)) {
1420 ERROR("Failed to attach block device.");
1421 goto out_fini_nonet
;
1424 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1425 /* If the backing store is a device, mount it here and now. */
1426 if (rootfs_is_blockdev(conf
)) {
1427 if (unshare(CLONE_NEWNS
) < 0) {
1428 ERROR("Failed to unshare CLONE_NEWNS.");
1429 goto out_fini_nonet
;
1431 INFO("Unshared CLONE_NEWNS.");
1433 remount_all_slave();
1434 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1435 ERROR("Error setting up rootfs mount as root before spawn.");
1436 goto out_fini_nonet
;
1438 INFO("Set up container rootfs as host root.");
1442 err
= lxc_spawn(handler
);
1444 ERROR("Failed to spawn container \"%s\".", name
);
1445 goto out_detach_blockdev
;
1448 handler
->conf
->reboot
= 0;
1450 err
= lxc_poll(name
, handler
);
1452 ERROR("LXC mainloop exited with error: %d.", err
);
1456 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1459 /* If the child process exited but was not signaled, it didn't call
1460 * reboot. This should mean it was an lxc-execute which simply exited.
1461 * In any case, treat it as a 'halt'.
1463 if (WIFSIGNALED(status
)) {
1464 switch(WTERMSIG(status
)) {
1465 case SIGINT
: /* halt */
1466 DEBUG("Container \"%s\" is halting.", name
);
1468 case SIGHUP
: /* reboot */
1469 DEBUG("Container \"%s\" is rebooting.", name
);
1470 handler
->conf
->reboot
= 1;
1472 case SIGSYS
: /* seccomp */
1473 DEBUG("Container \"%s\" violated its seccomp policy.", name
);
1476 DEBUG("Unknown exit status for container \"%s\" init %d.", name
, WTERMSIG(status
));
1481 err
= lxc_restore_phys_nics_to_netns(handler
);
1483 ERROR("Failed to move physical network devices back to parent "
1484 "network namespace");
1486 if (handler
->pinfd
>= 0) {
1487 close(handler
->pinfd
);
1488 handler
->pinfd
= -1;
1491 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1492 err
= lxc_error_set_and_log(handler
->pid
, status
);
1495 DEBUG("Tearing down network devices");
1496 if (!lxc_delete_network_priv(handler
))
1497 DEBUG("Failed tearing down network devices");
1499 if (!lxc_delete_network_unpriv(handler
))
1500 DEBUG("Failed tearing down network devices");
1502 if (handler
->netnsfd
>= 0) {
1503 close(handler
->netnsfd
);
1504 handler
->netnsfd
= -1;
1507 out_detach_blockdev
:
1508 detach_block_device(handler
->conf
);
1511 lxc_fini(name
, handler
);
1515 lxc_abort(name
, handler
);
1523 static int start(struct lxc_handler
*handler
, void* data
)
1525 struct start_args
*arg
= data
;
1527 NOTICE("Exec'ing \"%s\".", arg
->argv
[0]);
1529 execvp(arg
->argv
[0], arg
->argv
);
1530 SYSERROR("Failed to exec \"%s\".", arg
->argv
[0]);
1534 static int post_start(struct lxc_handler
*handler
, void* data
)
1536 struct start_args
*arg
= data
;
1538 NOTICE("Started \"%s\" with pid \"%d\".", arg
->argv
[0], handler
->pid
);
1542 static struct lxc_operations start_ops
= {
1544 .post_start
= post_start
1547 int lxc_start(const char *name
, char *const argv
[], struct lxc_handler
*handler
,
1548 const char *lxcpath
, bool backgrounded
)
1550 struct start_args start_arg
= {
1554 return __lxc_start(name
, handler
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1557 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1560 char destroy
[MAXPATHLEN
];
1563 struct lxc_container
*c
;
1564 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1565 bret
= do_destroy_container(handler
);
1567 ERROR("Error destroying rootfs for container \"%s\".", name
);
1571 INFO("Destroyed rootfs for container \"%s\".", name
);
1573 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1574 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1575 ERROR("Error destroying directory for container \"%s\".", name
);
1579 c
= lxc_container_new(name
, handler
->lxcpath
);
1581 if (container_disk_lock(c
)) {
1582 INFO("Could not update lxc_snapshots file.");
1583 lxc_container_put(c
);
1585 mod_all_rdeps(c
, false);
1586 container_disk_unlock(c
);
1587 lxc_container_put(c
);
1591 if (!handler
->am_root
)
1592 ret
= userns_exec_full(handler
->conf
, lxc_rmdir_onedev_wrapper
,
1593 destroy
, "lxc_rmdir_onedev_wrapper");
1595 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1598 ERROR("Error destroying directory for container \"%s\".", name
);
1601 INFO("Destroyed directory for container \"%s\".", name
);
1604 static int lxc_rmdir_onedev_wrapper(void *data
)
1606 char *arg
= (char *) data
;
1607 return lxc_rmdir_onedev(arg
, NULL
);
1610 static bool do_destroy_container(struct lxc_handler
*handler
) {
1613 if (!handler
->am_root
) {
1614 ret
= userns_exec_full(handler
->conf
, storage_destroy_wrapper
,
1615 handler
->conf
, "storage_destroy_wrapper");
1622 return storage_destroy(handler
->conf
);