]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/start.c
start: add lxc_init_handler()
[mirror_lxc.git] / src / lxc / start.c
1 /*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
7 * Daniel Lezcano <daniel.lezcano at free.fr>
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24 #define _GNU_SOURCE
25 #include "config.h"
26
27 #include <alloca.h>
28 #include <dirent.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <grp.h>
32 #include <poll.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <sys/file.h>
39 #include <sys/mount.h>
40 #include <sys/param.h>
41 #include <sys/prctl.h>
42 #include <sys/socket.h>
43 #include <sys/stat.h>
44 #include <sys/syscall.h>
45 #include <sys/types.h>
46 #include <sys/un.h>
47 #include <sys/wait.h>
48
49 #if HAVE_LIBCAP
50 #include <sys/capability.h>
51 #endif
52
53 #ifndef HAVE_DECL_PR_CAPBSET_DROP
54 #define PR_CAPBSET_DROP 24
55 #endif
56
57 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
58 #define PR_SET_NO_NEW_PRIVS 38
59 #endif
60
61 #ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
62 #define PR_GET_NO_NEW_PRIVS 39
63 #endif
64
65 #include "af_unix.h"
66 #include "bdev.h"
67 #include "caps.h"
68 #include "cgroup.h"
69 #include "commands.h"
70 #include "conf.h"
71 #include "console.h"
72 #include "error.h"
73 #include "log.h"
74 #include "lxclock.h"
75 #include "lxcseccomp.h"
76 #include "lxcutmp.h"
77 #include "mainloop.h"
78 #include "monitor.h"
79 #include "namespace.h"
80 #include "start.h"
81 #include "sync.h"
82 #include "utils.h"
83 #include "lsm/lsm.h"
84
85 lxc_log_define(lxc_start, lxc);
86
87 extern void mod_all_rdeps(struct lxc_container *c, bool inc);
88 static bool do_destroy_container(struct lxc_conf *conf);
89 static int lxc_rmdir_onedev_wrapper(void *data);
90 static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
91 const char *name);
92
93 static void print_top_failing_dir(const char *path)
94 {
95 size_t len = strlen(path);
96 char *copy = alloca(len + 1), *p, *e, saved;
97 strcpy(copy, path);
98
99 p = copy;
100 e = copy + len;
101 while (p < e) {
102 while (p < e && *p == '/')
103 p++;
104 while (p < e && *p != '/')
105 p++;
106 saved = *p;
107 *p = '\0';
108 if (access(copy, X_OK)) {
109 SYSERROR("Could not access %s. Please grant it x "
110 "access, or add an ACL for the container "
111 "root.", copy);
112 return;
113 }
114 *p = saved;
115 }
116 }
117
118 static void close_ns(int ns_fd[LXC_NS_MAX])
119 {
120 int i;
121
122 for (i = 0; i < LXC_NS_MAX; i++) {
123 if (ns_fd[i] > -1) {
124 close(ns_fd[i]);
125 ns_fd[i] = -1;
126 }
127 }
128 }
129
130 /* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
131 * in clone_flags.
132 * Return true on success, false on failure.
133 */
134 static bool preserve_ns(int ns_fd[LXC_NS_MAX], int clone_flags, pid_t pid)
135 {
136 int i, ret;
137
138 for (i = 0; i < LXC_NS_MAX; i++)
139 ns_fd[i] = -1;
140
141 ret = lxc_preserve_ns(pid, "");
142 if (ret < 0) {
143 SYSERROR("Kernel does not support attaching to namespaces.");
144 return false;
145 } else {
146 close(ret);
147 }
148
149 for (i = 0; i < LXC_NS_MAX; i++) {
150 if ((clone_flags & ns_info[i].clone_flag) == 0)
151 continue;
152 ns_fd[i] = lxc_preserve_ns(pid, ns_info[i].proc_name);
153 if (ns_fd[i] < 0)
154 goto error;
155 }
156
157 return true;
158
159 error:
160 if (errno == ENOENT)
161 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info[i].proc_name);
162 else
163 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info[i].proc_name, strerror(errno));
164 close_ns(ns_fd);
165 return false;
166 }
167
168 static int attach_ns(const int ns_fd[LXC_NS_MAX]) {
169 int i;
170
171 for (i = 0; i < LXC_NS_MAX; i++) {
172 if (ns_fd[i] < 0)
173 continue;
174
175 if (setns(ns_fd[i], 0) != 0)
176 goto error;
177 }
178 return 0;
179
180 error:
181 SYSERROR("Failed to attach %s namespace.", ns_info[i].proc_name);
182 return -1;
183 }
184
185 static int match_fd(int fd)
186 {
187 return (fd == 0 || fd == 1 || fd == 2);
188 }
189
190 /* Check for any fds we need to close.
191 * - If fd_to_ignore != -1, then if we find that fd open we will ignore it.
192 * - By default we warn about open fds we find.
193 * - If closeall is true, we will close open fds.
194 * - If lxc-start was passed "-C", then conf->close_all_fds will be true, in
195 * which case we also close all open fds.
196 * - A daemonized container will always pass closeall=true.
197 */
198 int lxc_check_inherited(struct lxc_conf *conf, bool closeall, int fd_to_ignore)
199 {
200 struct dirent *direntp;
201 int fd, fddir;
202 DIR *dir;
203
204 if (conf && conf->close_all_fds)
205 closeall = true;
206
207 restart:
208 dir = opendir("/proc/self/fd");
209 if (!dir) {
210 WARN("Failed to open directory: %m.");
211 return -1;
212 }
213
214 fddir = dirfd(dir);
215
216 while ((direntp = readdir(dir))) {
217 if (!direntp)
218 break;
219
220 if (!strcmp(direntp->d_name, "."))
221 continue;
222
223 if (!strcmp(direntp->d_name, ".."))
224 continue;
225
226 if (lxc_safe_int(direntp->d_name, &fd) < 0) {
227 INFO("Could not parse file descriptor for: %s", direntp->d_name);
228 continue;
229 }
230
231 if (fd == fddir || fd == lxc_log_fd || fd == fd_to_ignore)
232 continue;
233
234 if (current_config && fd == current_config->logfd)
235 continue;
236
237 if (match_fd(fd))
238 continue;
239
240 if (closeall) {
241 close(fd);
242 closedir(dir);
243 INFO("Closed inherited fd: %d.", fd);
244 goto restart;
245 }
246 WARN("Inherited fd: %d.", fd);
247 }
248
249 /* Only enable syslog at this point to avoid the above logging function
250 * to open a new fd and make the check_inherited function enter an
251 * infinite loop.
252 */
253 lxc_log_enable_syslog();
254
255 closedir(dir); /* cannot fail */
256 return 0;
257 }
258
259 static int setup_signal_fd(sigset_t *oldmask)
260 {
261 sigset_t mask;
262 int fd;
263
264 /* Block everything except serious error signals. */
265 if (sigfillset(&mask) ||
266 sigdelset(&mask, SIGILL) ||
267 sigdelset(&mask, SIGSEGV) ||
268 sigdelset(&mask, SIGBUS) ||
269 sigdelset(&mask, SIGWINCH) ||
270 sigprocmask(SIG_BLOCK, &mask, oldmask)) {
271 SYSERROR("Failed to set signal mask.");
272 return -1;
273 }
274
275 fd = signalfd(-1, &mask, 0);
276 if (fd < 0) {
277 SYSERROR("Failed to create signal file descriptor.");
278 return -1;
279 }
280
281 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
282 SYSERROR("Failed to set FD_CLOEXEC on the signal file descriptor: %d.", fd);
283 close(fd);
284 return -1;
285 }
286
287 DEBUG("Set SIGCHLD handler with file descriptor: %d.", fd);
288
289 return fd;
290 }
291
292 static int signal_handler(int fd, uint32_t events, void *data,
293 struct lxc_epoll_descr *descr)
294 {
295 struct signalfd_siginfo siginfo;
296 siginfo_t info;
297 int ret;
298 pid_t *pid = data;
299 bool init_died = false;
300
301 ret = read(fd, &siginfo, sizeof(siginfo));
302 if (ret < 0) {
303 ERROR("Failed to read signal info from signal file descriptor: %d.", fd);
304 return -1;
305 }
306
307 if (ret != sizeof(siginfo)) {
308 ERROR("Unexpected size for siginfo struct.");
309 return -1;
310 }
311
312 /* Check whether init is running. */
313 info.si_pid = 0;
314 ret = waitid(P_PID, *pid, &info, WEXITED | WNOWAIT | WNOHANG);
315 if (ret == 0 && info.si_pid == *pid)
316 init_died = true;
317
318 if (siginfo.ssi_signo != SIGCHLD) {
319 kill(*pid, siginfo.ssi_signo);
320 INFO("Forwarded signal %d to pid %d.", siginfo.ssi_signo, *pid);
321 return init_died ? 1 : 0;
322 }
323
324 if (siginfo.ssi_code == CLD_STOPPED) {
325 INFO("Container init process was stopped.");
326 return init_died ? 1 : 0;
327 } else if (siginfo.ssi_code == CLD_CONTINUED) {
328 INFO("Container init process was continued.");
329 return init_died ? 1 : 0;
330 }
331
332 /* More robustness, protect ourself from a SIGCHLD sent
333 * by a process different from the container init.
334 */
335 if (siginfo.ssi_pid != *pid) {
336 NOTICE("Received SIGCHLD from pid %d instead of container init %d.", siginfo.ssi_pid, *pid);
337 return init_died ? 1 : 0;
338 }
339
340 DEBUG("Container init process %d exited.", *pid);
341 return 1;
342 }
343
344 int lxc_set_state(const char *name, struct lxc_handler *handler, lxc_state_t state)
345 {
346 handler->state = state;
347 lxc_monitor_send_state(name, state, handler->lxcpath);
348 return 0;
349 }
350
351 int lxc_poll(const char *name, struct lxc_handler *handler)
352 {
353 int sigfd = handler->sigfd;
354 int pid = handler->pid;
355 struct lxc_epoll_descr descr;
356
357 if (lxc_mainloop_open(&descr)) {
358 ERROR("Failed to create LXC mainloop.");
359 goto out_sigfd;
360 }
361
362 if (lxc_mainloop_add_handler(&descr, sigfd, signal_handler, &pid)) {
363 ERROR("Failed to add signal handler with file descriptor %d to LXC mainloop.", sigfd);
364 goto out_mainloop_open;
365 }
366
367 if (lxc_console_mainloop_add(&descr, handler->conf)) {
368 ERROR("Failed to add console handler to LXC mainloop.");
369 goto out_mainloop_open;
370 }
371
372 if (lxc_cmd_mainloop_add(name, &descr, handler)) {
373 ERROR("Failed to add command handler to LXC mainloop.");
374 goto out_mainloop_open;
375 }
376
377 if (handler->conf->need_utmp_watch) {
378 #if HAVE_LIBCAP
379 if (lxc_utmp_mainloop_add(&descr, handler)) {
380 ERROR("Failed to add utmp handler to LXC mainloop.");
381 goto out_mainloop_open;
382 }
383 #else
384 DEBUG("Not starting utmp handler as CAP_SYS_BOOT cannot be dropped without capabilities support.");
385 #endif
386 }
387
388 return lxc_mainloop(&descr, -1);
389
390 out_mainloop_open:
391 lxc_mainloop_close(&descr);
392
393 out_sigfd:
394 close(sigfd);
395
396 return -1;
397 }
398
399 struct lxc_handler *lxc_init_handler(const char *name, struct lxc_conf *conf,
400 const char *lxcpath)
401 {
402 int i;
403 struct lxc_handler *handler;
404
405 handler = malloc(sizeof(*handler));
406 if (!handler) {
407 ERROR("failed to allocate memory");
408 return NULL;
409 }
410
411 memset(handler, 0, sizeof(*handler));
412
413 handler->ttysock[0] = handler->ttysock[1] = -1;
414 handler->conf = conf;
415 handler->lxcpath = lxcpath;
416 handler->pinfd = -1;
417
418 for (i = 0; i < LXC_NS_MAX; i++)
419 handler->nsfd[i] = -1;
420
421 handler->name = strdup(name);
422 if (!handler->name) {
423 ERROR("failed to allocate memory");
424 goto do_partial_cleanup;
425 }
426
427 if (lxc_cmd_init(name, handler, lxcpath)) {
428 ERROR("failed to set up command socket");
429 goto do_full_cleanup;
430 }
431
432 TRACE("unix domain socket %d for command server is ready",
433 handler->conf->maincmd_fd);
434
435 return handler;
436
437 do_full_cleanup:
438 free(handler->name);
439
440 do_partial_cleanup:
441 free(handler);
442
443 return NULL;
444 }
445
446 int lxc_init(const char *name, struct lxc_handler *handler)
447 {
448 struct lxc_conf *conf = handler->conf;
449
450 lsm_init();
451 TRACE("initialized LSM");
452
453 if (lxc_read_seccomp_config(conf) != 0) {
454 ERROR("Failed loading seccomp policy.");
455 goto out_close_maincmd_fd;
456 }
457
458 /* Begin by setting the state to STARTING. */
459 if (lxc_set_state(name, handler, STARTING)) {
460 ERROR("Failed to set state for container \"%s\" to \"%s\".", name, lxc_state2str(STARTING));
461 goto out_close_maincmd_fd;
462 }
463
464 /* Start of environment variable setup for hooks. */
465 if (name && setenv("LXC_NAME", name, 1))
466 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name);
467
468 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
469 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf->rcfile);
470
471 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1))
472 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf->rootfs.mount);
473
474 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
475 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf->rootfs.path);
476
477 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1))
478 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf->console.path);
479
480 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1))
481 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf->console.log_path);
482
483 if (setenv("LXC_CGNS_AWARE", "1", 1))
484 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
485 /* End of environment variable setup for hooks. */
486
487 if (run_lxc_hooks(name, "pre-start", conf, handler->lxcpath, NULL)) {
488 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name);
489 goto out_aborting;
490 }
491
492 /* The signal fd has to be created before forking otherwise if the child
493 * process exits before we setup the signal fd, the event will be lost
494 * and the command will be stuck.
495 */
496 handler->sigfd = setup_signal_fd(&handler->oldmask);
497 if (handler->sigfd < 0) {
498 ERROR("Failed to setup SIGCHLD fd handler.");
499 goto out_delete_tty;
500 }
501
502 /* Do this after setting up signals since it might unblock SIGWINCH. */
503 if (lxc_console_create(conf)) {
504 ERROR("Failed to create console for container \"%s\".", name);
505 goto out_restore_sigmask;
506 }
507
508 if (lxc_ttys_shift_ids(conf) < 0) {
509 ERROR("Failed to shift tty into container.");
510 goto out_restore_sigmask;
511 }
512
513 INFO("Container \"%s\" is initialized.", name);
514 return 0;
515
516 out_restore_sigmask:
517 sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
518 out_delete_tty:
519 lxc_delete_tty(&conf->tty_info);
520 out_aborting:
521 lxc_set_state(name, handler, ABORTING);
522 out_close_maincmd_fd:
523 close(conf->maincmd_fd);
524 conf->maincmd_fd = -1;
525 return -1;
526 }
527
528 void lxc_fini(const char *name, struct lxc_handler *handler)
529 {
530 int i, rc;
531 pid_t self = getpid();
532 char *namespaces[LXC_NS_MAX+1];
533 size_t namespace_count = 0;
534
535 /* The STOPPING state is there for future cleanup code which can take
536 * awhile.
537 */
538 lxc_set_state(name, handler, STOPPING);
539
540 for (i = 0; i < LXC_NS_MAX; i++) {
541 if (handler->nsfd[i] != -1) {
542 rc = asprintf(&namespaces[namespace_count], "%s:/proc/%d/fd/%d",
543 ns_info[i].proc_name, self, handler->nsfd[i]);
544 if (rc == -1) {
545 SYSERROR("Failed to allocate memory.");
546 break;
547 }
548 ++namespace_count;
549 }
550 }
551 namespaces[namespace_count] = NULL;
552
553 if (handler->conf->reboot && setenv("LXC_TARGET", "reboot", 1))
554 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
555
556 if (!handler->conf->reboot && setenv("LXC_TARGET", "stop", 1))
557 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
558
559 if (run_lxc_hooks(name, "stop", handler->conf, handler->lxcpath, namespaces))
560 ERROR("Failed to run lxc.hook.stop for container \"%s\".", name);
561
562 while (namespace_count--)
563 free(namespaces[namespace_count]);
564 for (i = 0; i < LXC_NS_MAX; i++) {
565 if (handler->nsfd[i] != -1) {
566 close(handler->nsfd[i]);
567 handler->nsfd[i] = -1;
568 }
569 }
570
571 if (handler->netnsfd >= 0) {
572 close(handler->netnsfd);
573 handler->netnsfd = -1;
574 }
575
576 lxc_set_state(name, handler, STOPPED);
577
578 if (run_lxc_hooks(name, "post-stop", handler->conf, handler->lxcpath, NULL)) {
579 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name);
580 if (handler->conf->reboot) {
581 WARN("Container will be stopped instead of rebooted.");
582 handler->conf->reboot = 0;
583 if (setenv("LXC_TARGET", "stop", 1))
584 WARN("Failed to set environment variable: LXC_TARGET=stop.");
585 }
586 }
587
588 /* Reset mask set by setup_signal_fd. */
589 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
590 WARN("Failed to restore signal mask.");
591
592 lxc_console_delete(&handler->conf->console);
593 lxc_delete_tty(&handler->conf->tty_info);
594 close(handler->conf->maincmd_fd);
595 handler->conf->maincmd_fd = -1;
596 free(handler->name);
597 if (handler->ttysock[0] != -1) {
598 close(handler->ttysock[0]);
599 close(handler->ttysock[1]);
600 }
601
602 if (handler->conf->ephemeral == 1 && handler->conf->reboot != 1)
603 lxc_destroy_container_on_signal(handler, name);
604
605 cgroup_destroy(handler);
606 free(handler);
607 }
608
609 void lxc_abort(const char *name, struct lxc_handler *handler)
610 {
611 int ret, status;
612
613 lxc_set_state(name, handler, ABORTING);
614 if (handler->pid > 0)
615 kill(handler->pid, SIGKILL);
616 while ((ret = waitpid(-1, &status, 0)) > 0) {
617 ;
618 }
619 }
620
621 #include <sys/reboot.h>
622 #include <linux/reboot.h>
623
624 /* reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL in a child pid namespace
625 * if container reboot support exists. Otherwise, it will either succeed or
626 * return -EPERM.
627 */
628 static int container_reboot_supported(void *arg)
629 {
630 int *cmd = arg;
631 int ret;
632
633 ret = reboot(*cmd);
634 if (ret == -1 && errno == EINVAL)
635 return 1;
636 return 0;
637 }
638
639 static int must_drop_cap_sys_boot(struct lxc_conf *conf)
640 {
641 FILE *f;
642 int ret, cmd, v, flags;
643 long stack_size = 4096;
644 void *stack = alloca(stack_size);
645 int status;
646 pid_t pid;
647
648 f = fopen("/proc/sys/kernel/ctrl-alt-del", "r");
649 if (!f) {
650 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
651 return 1;
652 }
653
654 ret = fscanf(f, "%d", &v);
655 fclose(f);
656 if (ret != 1) {
657 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del.");
658 return 1;
659 }
660 cmd = v ? LINUX_REBOOT_CMD_CAD_ON : LINUX_REBOOT_CMD_CAD_OFF;
661
662 flags = CLONE_NEWPID | SIGCHLD;
663 if (!lxc_list_empty(&conf->id_map))
664 flags |= CLONE_NEWUSER;
665
666 #ifdef __ia64__
667 pid = __clone2(container_reboot_supported, stack, stack_size, flags, &cmd);
668 #else
669 stack += stack_size;
670 pid = clone(container_reboot_supported, stack, flags, &cmd);
671 #endif
672 if (pid < 0) {
673 if (flags & CLONE_NEWUSER)
674 ERROR("Failed to clone (%#x): %s (includes CLONE_NEWUSER).", flags, strerror(errno));
675 else
676 ERROR("Failed to clone (%#x): %s.", flags, strerror(errno));
677 return -1;
678 }
679 if (wait(&status) < 0) {
680 SYSERROR("Unexpected wait error: %m.");
681 return -1;
682 }
683
684 if (WEXITSTATUS(status) != 1)
685 return 1;
686
687 return 0;
688 }
689
690 /* netpipe is used in the unprivileged case to transfer the ifindexes from
691 * parent to child
692 */
693 static int netpipe = -1;
694
695 static inline int count_veths(struct lxc_list *network)
696 {
697 struct lxc_list *iterator;
698 struct lxc_netdev *netdev;
699 int count = 0;
700
701 lxc_list_for_each(iterator, network) {
702 netdev = iterator->elem;
703 if (netdev->type != LXC_NET_VETH)
704 continue;
705 count++;
706 }
707 return count;
708 }
709
710 static int read_unpriv_netifindex(struct lxc_list *network)
711 {
712 struct lxc_list *iterator;
713 struct lxc_netdev *netdev;
714
715 if (netpipe == -1)
716 return 0;
717 lxc_list_for_each(iterator, network) {
718 netdev = iterator->elem;
719 if (netdev->type != LXC_NET_VETH)
720 continue;
721 if (!(netdev->name = malloc(IFNAMSIZ))) {
722 ERROR("Out of memory.");
723 close(netpipe);
724 return -1;
725 }
726 if (read(netpipe, netdev->name, IFNAMSIZ) != IFNAMSIZ) {
727 close(netpipe);
728 return -1;
729 }
730 }
731 close(netpipe);
732 return 0;
733 }
734
735 static int do_start(void *data)
736 {
737 struct lxc_list *iterator;
738 struct lxc_handler *handler = data;
739 int devnull_fd = -1, ret;
740 char path[PATH_MAX];
741
742 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL)) {
743 SYSERROR("Failed to set signal mask.");
744 return -1;
745 }
746
747 /* This prctl must be before the synchro, so if the parent dies before
748 * we set the parent death signal, we will detect its death with the
749 * synchro right after, otherwise we have a window where the parent can
750 * exit before we set the pdeath signal leading to a unsupervized
751 * container.
752 */
753 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
754 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL.");
755 return -1;
756 }
757
758 lxc_sync_fini_parent(handler);
759
760 /* Don't leak the pinfd to the container. */
761 if (handler->pinfd >= 0) {
762 close(handler->pinfd);
763 }
764
765 if (lxc_sync_wait_parent(handler, LXC_SYNC_STARTUP))
766 return -1;
767
768 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
769 * https://github.com/lxc/lxd/issues/1978.
770 */
771 if ((handler->clone_flags & (CLONE_NEWNET | CLONE_NEWUSER)) ==
772 (CLONE_NEWNET | CLONE_NEWUSER)) {
773 ret = unshare(CLONE_NEWNET);
774 if (ret < 0) {
775 SYSERROR("Failed to unshare CLONE_NEWNET.");
776 goto out_warn_father;
777 }
778 INFO("Unshared CLONE_NEWNET.");
779 }
780
781 /* Tell the parent task it can begin to configure the container and wait
782 * for it to finish.
783 */
784 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE))
785 return -1;
786
787 if (read_unpriv_netifindex(&handler->conf->network) < 0)
788 goto out_warn_father;
789
790 /* If we are in a new user namespace, become root there to have
791 * privilege over our namespace.
792 */
793 if (!lxc_list_empty(&handler->conf->id_map)) {
794 if (lxc_switch_uid_gid(0, 0) < 0)
795 goto out_warn_father;
796
797 /* Drop groups only after we switched to a valid gid in the new
798 * user namespace.
799 */
800 if (lxc_setgroups(0, NULL) < 0)
801 goto out_warn_father;
802 }
803
804 if (access(handler->lxcpath, X_OK)) {
805 print_top_failing_dir(handler->lxcpath);
806 goto out_warn_father;
807 }
808
809 #if HAVE_LIBCAP
810 if (handler->conf->need_utmp_watch) {
811 if (prctl(PR_CAPBSET_DROP, CAP_SYS_BOOT, 0, 0, 0)) {
812 SYSERROR("Failed to remove the CAP_SYS_BOOT capability.");
813 goto out_warn_father;
814 }
815 DEBUG("Dropped the CAP_SYS_BOOT capability.");
816 }
817 #endif
818
819 ret = snprintf(path, sizeof(path), "%s/dev/null", handler->conf->rootfs.mount);
820 if (ret < 0 || ret >= sizeof(path))
821 goto out_warn_father;
822
823 /* In order to checkpoint restore, we need to have everything in the
824 * same mount namespace. However, some containers may not have a
825 * reasonable /dev (in particular, they may not have /dev/null), so we
826 * can't set init's std fds to /dev/null by opening it from inside the
827 * container.
828 *
829 * If that's the case, fall back to using the host's /dev/null. This
830 * means that migration won't work, but at least we won't spew output
831 * where it isn't wanted.
832 */
833 if (handler->backgrounded && !handler->conf->autodev && access(path, F_OK) < 0) {
834 devnull_fd = open_devnull();
835
836 if (devnull_fd < 0)
837 goto out_warn_father;
838 WARN("Using /dev/null from the host for container init's "
839 "standard file descriptors. Migration will not work.");
840 }
841
842 /* Setup the container, ip, names, utsname, ... */
843 if (lxc_setup(handler)) {
844 ERROR("Failed to setup container \"%s\".", handler->name);
845 goto out_warn_father;
846 }
847
848 /* Ask father to setup cgroups and wait for him to finish. */
849 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP))
850 goto out_error;
851
852 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
853 * earlier we end up with a wrong view of /proc/self/cgroup. For
854 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
855 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
856 * /proc/self/cgroup would show us:
857 *
858 * 8:cpuset:/lxc/c
859 *
860 * whereas it should actually show
861 *
862 * 8:cpuset:/
863 */
864 if (cgns_supported()) {
865 if (unshare(CLONE_NEWCGROUP) < 0) {
866 INFO("Failed to unshare CLONE_NEWCGROUP.");
867 goto out_warn_father;
868 }
869 INFO("Unshared CLONE_NEWCGROUP.");
870 }
871
872 /* Set the label to change to when we exec(2) the container's init. */
873 if (lsm_process_label_set(NULL, handler->conf, 1, 1) < 0)
874 goto out_warn_father;
875
876 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
877 * before we aren't allowed anymore.
878 */
879 if (handler->conf->no_new_privs) {
880 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
881 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
882 goto out_warn_father;
883 }
884 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
885 }
886
887 /* Some init's such as busybox will set sane tty settings on stdin,
888 * stdout, stderr which it thinks is the console. We already set them
889 * the way we wanted on the real terminal, and we want init to do its
890 * setup on its console ie. the pty allocated in lxc_console_create() so
891 * make sure that that pty is stdin,stdout,stderr.
892 */
893 if (lxc_console_set_stdfds(handler->conf->console.slave) < 0)
894 goto out_warn_father;
895
896 /* If we mounted a temporary proc, then unmount it now. */
897 tmp_proc_unmount(handler->conf);
898
899 if (lxc_seccomp_load(handler->conf) != 0)
900 goto out_warn_father;
901
902 if (run_lxc_hooks(handler->name, "start", handler->conf, handler->lxcpath, NULL)) {
903 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler->name);
904 goto out_warn_father;
905 }
906
907 /* The container has been setup. We can now switch to an unprivileged
908 * uid/gid.
909 */
910 if (handler->conf->is_execute) {
911 bool have_cap_setgid;
912 uid_t new_uid = handler->conf->init_uid;
913 gid_t new_gid = handler->conf->init_gid;
914
915 /* If we are in a new user namespace we already dropped all
916 * groups when we switched to root in the new user namespace
917 * further above. Only drop groups if we can, so ensure that we
918 * have necessary privilege.
919 */
920 #if HAVE_LIBCAP
921 have_cap_setgid = lxc_proc_cap_is_set(CAP_SETGID, CAP_EFFECTIVE);
922 #else
923 have_cap_setgid = false;
924 #endif
925 if (lxc_list_empty(&handler->conf->id_map) && have_cap_setgid) {
926 if (lxc_setgroups(0, NULL) < 0)
927 goto out_warn_father;
928 }
929
930 if (lxc_switch_uid_gid(new_uid, new_gid) < 0)
931 goto out_warn_father;
932 }
933
934 /* The clearenv() and putenv() calls have been moved here to allow us to
935 * use environment variables passed to the various hooks, such as the
936 * start hook above. Not all of the variables like CONFIG_PATH or ROOTFS
937 * are valid in this context but others are.
938 */
939 if (clearenv()) {
940 SYSERROR("Failed to clear environment.");
941 /* Don't error out though. */
942 }
943
944 lxc_list_for_each(iterator, &handler->conf->environment) {
945 if (putenv((char *)iterator->elem)) {
946 SYSERROR("Failed to set environment variable: %s.", (char *)iterator->elem);
947 goto out_warn_father;
948 }
949 }
950
951 if (putenv("container=lxc")) {
952 SYSERROR("Failed to set environment variable: container=lxc.");
953 goto out_warn_father;
954 }
955
956 if (handler->conf->pty_names) {
957 if (putenv(handler->conf->pty_names)) {
958 SYSERROR("Failed to set environment variable for container ptys.");
959 goto out_warn_father;
960 }
961 }
962
963 close(handler->sigfd);
964
965 if (devnull_fd < 0) {
966 devnull_fd = open_devnull();
967
968 if (devnull_fd < 0)
969 goto out_warn_father;
970 }
971
972 if (handler->backgrounded && set_stdfds(devnull_fd))
973 goto out_warn_father;
974
975 if (devnull_fd >= 0) {
976 close(devnull_fd);
977 devnull_fd = -1;
978 }
979
980 setsid();
981
982 /* After this call, we are in error because this ops should not return
983 * as it execs.
984 */
985 handler->ops->start(handler, handler->data);
986
987 out_warn_father:
988 /* We want the parent to know something went wrong, so we return a
989 * special error code.
990 */
991 lxc_sync_wake_parent(handler, LXC_SYNC_ERROR);
992
993 out_error:
994 if (devnull_fd >= 0)
995 close(devnull_fd);
996
997 return -1;
998 }
999
1000 static int save_phys_nics(struct lxc_conf *conf)
1001 {
1002 struct lxc_list *iterator;
1003 int am_root = (getuid() == 0);
1004
1005 if (!am_root)
1006 return 0;
1007
1008 lxc_list_for_each(iterator, &conf->network) {
1009 struct lxc_netdev *netdev = iterator->elem;
1010
1011 if (netdev->type != LXC_NET_PHYS)
1012 continue;
1013 conf->saved_nics = realloc(conf->saved_nics,
1014 (conf->num_savednics+1)*sizeof(struct saved_nic));
1015 if (!conf->saved_nics)
1016 return -1;
1017 conf->saved_nics[conf->num_savednics].ifindex = netdev->ifindex;
1018 conf->saved_nics[conf->num_savednics].orig_name = strdup(netdev->link);
1019 if (!conf->saved_nics[conf->num_savednics].orig_name)
1020 return -1;
1021 INFO("Stored saved_nic #%d idx %d name %s.", conf->num_savednics,
1022 conf->saved_nics[conf->num_savednics].ifindex,
1023 conf->saved_nics[conf->num_savednics].orig_name);
1024 conf->num_savednics++;
1025 }
1026
1027 return 0;
1028 }
1029
1030 static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
1031 {
1032 int i;
1033 int *ttyfds;
1034 struct lxc_pty_info *pty_info;
1035 int ret = -1;
1036 int sock = handler->ttysock[1];
1037 struct lxc_conf *conf = handler->conf;
1038 struct lxc_tty_info *tty_info = &conf->tty_info;
1039 size_t num_ttyfds = (2 * conf->tty);
1040
1041 if (!conf->tty)
1042 return 0;
1043
1044 tty_info->pty_info = malloc(sizeof(*tty_info->pty_info) * conf->tty);
1045 if (!tty_info->pty_info)
1046 return -1;
1047
1048 ttyfds = malloc(num_ttyfds * sizeof(int));
1049 if (!ttyfds)
1050 return -1;
1051
1052 ret = lxc_abstract_unix_recv_fds(sock, ttyfds, num_ttyfds, NULL, 0);
1053 for (i = 0; (ret >= 0 && *ttyfds != -1) && (i < num_ttyfds); i++) {
1054 pty_info = &tty_info->pty_info[i / 2];
1055 pty_info->busy = 0;
1056 pty_info->slave = ttyfds[i++];
1057 pty_info->master = ttyfds[i];
1058 TRACE("received pty with master fd %d and slave fd %d from "
1059 "parent", pty_info->master, pty_info->slave);
1060 }
1061
1062 tty_info->nbtty = conf->tty;
1063
1064 free(ttyfds);
1065
1066 if (ret < 0)
1067 ERROR("failed to receive %d ttys from child: %s", conf->tty,
1068 strerror(errno));
1069 else
1070 TRACE("received %d ttys from child", conf->tty);
1071
1072 return ret;
1073 }
1074
1075 void resolve_clone_flags(struct lxc_handler *handler)
1076 {
1077 handler->clone_flags = CLONE_NEWPID | CLONE_NEWNS;
1078
1079 if (!lxc_list_empty(&handler->conf->id_map))
1080 handler->clone_flags |= CLONE_NEWUSER;
1081
1082 if (handler->conf->inherit_ns_fd[LXC_NS_NET] == -1) {
1083 if (!lxc_requests_empty_network(handler))
1084 handler->clone_flags |= CLONE_NEWNET;
1085 } else {
1086 INFO("Inheriting a NET namespace.");
1087 }
1088
1089 if (handler->conf->inherit_ns_fd[LXC_NS_IPC] == -1)
1090 handler->clone_flags |= CLONE_NEWIPC;
1091 else
1092 INFO("Inheriting an IPC namespace.");
1093
1094 if (handler->conf->inherit_ns_fd[LXC_NS_UTS] == -1)
1095 handler->clone_flags |= CLONE_NEWUTS;
1096 else
1097 INFO("Inheriting a UTS namespace.");
1098 }
1099
1100 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1101 * exec()s the requested container binary.
1102 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1103 * right here should be double checked if they'd pose a security risk. (For
1104 * example, any {u}mount() operations performed here will be reflected on the
1105 * host!)
1106 */
1107 static int lxc_spawn(struct lxc_handler *handler)
1108 {
1109 int failed_before_rename = 0;
1110 const char *name = handler->name;
1111 bool cgroups_connected = false;
1112 int saved_ns_fd[LXC_NS_MAX];
1113 int preserve_mask = 0, i, flags;
1114 int netpipepair[2], nveths;
1115 bool wants_to_map_ids;
1116 struct lxc_list *id_map;
1117
1118 netpipe = -1;
1119 id_map = &handler->conf->id_map;
1120 wants_to_map_ids = !lxc_list_empty(id_map);
1121
1122 for (i = 0; i < LXC_NS_MAX; i++)
1123 if (handler->conf->inherit_ns_fd[i] != -1)
1124 preserve_mask |= ns_info[i].clone_flag;
1125
1126 if (lxc_sync_init(handler))
1127 return -1;
1128
1129 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, handler->ttysock) < 0) {
1130 lxc_sync_fini(handler);
1131 return -1;
1132 }
1133
1134 resolve_clone_flags(handler);
1135
1136 if (handler->clone_flags & CLONE_NEWNET) {
1137 if (!lxc_list_empty(&handler->conf->network)) {
1138
1139 /* Find gateway addresses from the link device, which is
1140 * no longer accessible inside the container. Do this
1141 * before creating network interfaces, since goto
1142 * out_delete_net does not work before lxc_clone.
1143 */
1144 if (lxc_find_gateway_addresses(handler)) {
1145 ERROR("Failed to find gateway addresses.");
1146 lxc_sync_fini(handler);
1147 return -1;
1148 }
1149
1150 /* That should be done before the clone because we will
1151 * fill the netdev index and use them in the child.
1152 */
1153 if (lxc_create_network(handler)) {
1154 ERROR("Failed to create the network.");
1155 lxc_sync_fini(handler);
1156 return -1;
1157 }
1158 }
1159
1160 if (save_phys_nics(handler->conf)) {
1161 ERROR("Failed to save physical nic info.");
1162 goto out_abort;
1163 }
1164 }
1165
1166 if (!cgroup_init(handler)) {
1167 ERROR("Failed initializing cgroup support.");
1168 goto out_delete_net;
1169 }
1170
1171 cgroups_connected = true;
1172
1173 if (!cgroup_create(handler)) {
1174 ERROR("Failed creating cgroups.");
1175 goto out_delete_net;
1176 }
1177
1178 /* If the rootfs is not a blockdev, prevent the container from marking
1179 * it readonly.
1180 * If the container is unprivileged then skip rootfs pinning.
1181 */
1182 if (!wants_to_map_ids) {
1183 handler->pinfd = pin_rootfs(handler->conf->rootfs.path);
1184 if (handler->pinfd == -1)
1185 INFO("Failed to pin the rootfs for container \"%s\".", handler->name);
1186 }
1187
1188 if (!preserve_ns(saved_ns_fd, preserve_mask, getpid()))
1189 goto out_delete_net;
1190
1191 if (attach_ns(handler->conf->inherit_ns_fd) < 0)
1192 goto out_delete_net;
1193
1194 if (am_unpriv() && (nveths = count_veths(&handler->conf->network))) {
1195 if (pipe(netpipepair) < 0) {
1196 SYSERROR("Failed to create pipe.");
1197 goto out_delete_net;
1198 }
1199 /* Store netpipe in the global var for do_start's use. */
1200 netpipe = netpipepair[0];
1201 }
1202
1203 /* Create a process in a new set of namespaces. */
1204 flags = handler->clone_flags;
1205 if (handler->clone_flags & CLONE_NEWUSER) {
1206 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1207 * clone a new user namespace first and only later unshare our
1208 * network namespace to ensure that network devices ownership is
1209 * set up correctly.
1210 */
1211 flags &= ~CLONE_NEWNET;
1212 }
1213 handler->pid = lxc_clone(do_start, handler, flags);
1214 if (handler->pid < 0) {
1215 SYSERROR("Failed to clone a new set of namespaces.");
1216 goto out_delete_net;
1217 }
1218 for (i = 0; i < LXC_NS_MAX; i++)
1219 if (flags & ns_info[i].clone_flag)
1220 INFO("Cloned %s.", ns_info[i].flag_name);
1221
1222 if (!preserve_ns(handler->nsfd, handler->clone_flags | preserve_mask, handler->pid))
1223 INFO("Failed to preserve namespace for lxc.hook.stop.");
1224
1225 if (attach_ns(saved_ns_fd))
1226 WARN("Failed to restore saved namespaces.");
1227
1228 lxc_sync_fini_child(handler);
1229
1230 /* Map the container uids. The container became an invalid userid the
1231 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1232 * anything immediately, but allows the container to setuid(0) (0 being
1233 * mapped to something else on the host.) later to become a valid uid
1234 * again.
1235 */
1236 if (wants_to_map_ids && lxc_map_ids(id_map, handler->pid)) {
1237 ERROR("Failed to set up id mapping.");
1238 goto out_delete_net;
1239 }
1240
1241 if (lxc_sync_wake_child(handler, LXC_SYNC_STARTUP)) {
1242 failed_before_rename = 1;
1243 goto out_delete_net;
1244 }
1245
1246 if (lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE)) {
1247 failed_before_rename = 1;
1248 goto out_delete_net;
1249 }
1250
1251 if (!cgroup_create_legacy(handler)) {
1252 ERROR("Failed to setup legacy cgroups for container \"%s\".", name);
1253 goto out_delete_net;
1254 }
1255 if (!cgroup_setup_limits(handler, false)) {
1256 ERROR("Failed to setup cgroup limits for container \"%s\".", name);
1257 goto out_delete_net;
1258 }
1259
1260 if (!cgroup_enter(handler))
1261 goto out_delete_net;
1262
1263 if (!cgroup_chown(handler))
1264 goto out_delete_net;
1265
1266 if (failed_before_rename)
1267 goto out_delete_net;
1268
1269 /* Create the network configuration. */
1270 if (handler->clone_flags & CLONE_NEWNET) {
1271 if (lxc_assign_network(handler->lxcpath, handler->name,
1272 &handler->conf->network, handler->pid)) {
1273 ERROR("Failed to create the configured network.");
1274 goto out_delete_net;
1275 }
1276 }
1277
1278 if (netpipe != -1) {
1279 struct lxc_list *iterator;
1280 struct lxc_netdev *netdev;
1281
1282 close(netpipe);
1283 lxc_list_for_each(iterator, &handler->conf->network) {
1284 netdev = iterator->elem;
1285 if (netdev->type != LXC_NET_VETH)
1286 continue;
1287 if (write(netpipepair[1], netdev->name, IFNAMSIZ) != IFNAMSIZ) {
1288 ERROR("Error writing veth name to container.");
1289 goto out_delete_net;
1290 }
1291 }
1292 close(netpipepair[1]);
1293 }
1294
1295 /* Tell the child to continue its initialization. We'll get
1296 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1297 */
1298 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE))
1299 goto out_delete_net;
1300
1301 if (!lxc_list_empty(&handler->conf->limits) && setup_resource_limits(&handler->conf->limits, handler->pid)) {
1302 ERROR("failed to setup resource limits for '%s'", name);
1303 goto out_delete_net;
1304 }
1305
1306 if (!cgroup_setup_limits(handler, true)) {
1307 ERROR("Failed to setup the devices cgroup for container \"%s\".", name);
1308 goto out_delete_net;
1309 }
1310
1311 cgroup_disconnect();
1312 cgroups_connected = false;
1313
1314 /* Read tty fds allocated by child. */
1315 if (lxc_recv_ttys_from_child(handler) < 0) {
1316 ERROR("Failed to receive tty info from child process.");
1317 goto out_delete_net;
1318 }
1319
1320 /* Tell the child to complete its initialization and wait for it to exec
1321 * or return an error. (The child will never return
1322 * LXC_SYNC_POST_CGROUP+1. It will either close the sync pipe, causing
1323 * lxc_sync_barrier_child to return success, or return a different
1324 * value, causing us to error out).
1325 */
1326 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CGROUP))
1327 return -1;
1328
1329 if (handler->ops->post_start(handler, handler->data))
1330 goto out_abort;
1331
1332 if (lxc_set_state(name, handler, RUNNING)) {
1333 ERROR("Failed to set state for container \"%s\" to \"%s\".", name,
1334 lxc_state2str(RUNNING));
1335 goto out_abort;
1336 }
1337
1338 lxc_sync_fini(handler);
1339 handler->netnsfd = lxc_preserve_ns(handler->pid, "net");
1340
1341 return 0;
1342
1343 out_delete_net:
1344 if (cgroups_connected)
1345 cgroup_disconnect();
1346 if (handler->clone_flags & CLONE_NEWNET)
1347 lxc_delete_network(handler);
1348 out_abort:
1349 lxc_abort(name, handler);
1350 lxc_sync_fini(handler);
1351 if (handler->pinfd >= 0) {
1352 close(handler->pinfd);
1353 handler->pinfd = -1;
1354 }
1355
1356 return -1;
1357 }
1358
1359 int __lxc_start(const char *name, struct lxc_handler *handler,
1360 struct lxc_operations* ops, void *data, const char *lxcpath,
1361 bool backgrounded)
1362 {
1363 int status;
1364 int err = -1;
1365 bool removed_all_netdevs = true;
1366 struct lxc_conf *conf = handler->conf;
1367
1368 if (lxc_init(name, handler) < 0) {
1369 ERROR("Failed to initialize container \"%s\".", name);
1370 return -1;
1371 }
1372 handler->ops = ops;
1373 handler->data = data;
1374 handler->backgrounded = backgrounded;
1375 handler->netnsfd = -1;
1376
1377 if (must_drop_cap_sys_boot(handler->conf)) {
1378 #if HAVE_LIBCAP
1379 DEBUG("Dropping CAP_SYS_BOOT capability.");
1380 #else
1381 DEBUG("Not dropping CAP_SYS_BOOT capability as capabilities aren't supported.");
1382 #endif
1383 } else {
1384 DEBUG("Not dropping CAP_SYS_BOOT or watching utmp.");
1385 handler->conf->need_utmp_watch = 0;
1386 }
1387
1388 if (!attach_block_device(handler->conf)) {
1389 ERROR("Failed to attach block device.");
1390 goto out_fini_nonet;
1391 }
1392
1393 if (geteuid() == 0 && !lxc_list_empty(&conf->id_map)) {
1394 /* If the backing store is a device, mount it here and now. */
1395 if (rootfs_is_blockdev(conf)) {
1396 if (unshare(CLONE_NEWNS) < 0) {
1397 ERROR("Failed to unshare CLONE_NEWNS.");
1398 goto out_fini_nonet;
1399 }
1400 INFO("Unshared CLONE_NEWNS.");
1401
1402 remount_all_slave();
1403 if (do_rootfs_setup(conf, name, lxcpath) < 0) {
1404 ERROR("Error setting up rootfs mount as root before spawn.");
1405 goto out_fini_nonet;
1406 }
1407 INFO("Set up container rootfs as host root.");
1408 }
1409 }
1410
1411 err = lxc_spawn(handler);
1412 if (err) {
1413 ERROR("Failed to spawn container \"%s\".", name);
1414 goto out_detach_blockdev;
1415 }
1416
1417 handler->conf->reboot = 0;
1418
1419 err = lxc_poll(name, handler);
1420 if (err) {
1421 ERROR("LXC mainloop exited with error: %d.", err);
1422 if (handler->netnsfd >= 0) {
1423 close(handler->netnsfd);
1424 handler->netnsfd = -1;
1425 }
1426 goto out_abort;
1427 }
1428
1429 while (waitpid(handler->pid, &status, 0) < 0 && errno == EINTR)
1430 continue;
1431
1432 /* If the child process exited but was not signaled, it didn't call
1433 * reboot. This should mean it was an lxc-execute which simply exited.
1434 * In any case, treat it as a 'halt'.
1435 */
1436 if (WIFSIGNALED(status)) {
1437 switch(WTERMSIG(status)) {
1438 case SIGINT: /* halt */
1439 DEBUG("Container \"%s\" is halting.", name);
1440 break;
1441 case SIGHUP: /* reboot */
1442 DEBUG("Container \"%s\" is rebooting.", name);
1443 handler->conf->reboot = 1;
1444 break;
1445 case SIGSYS: /* seccomp */
1446 DEBUG("Container \"%s\" violated its seccomp policy.", name);
1447 break;
1448 default:
1449 DEBUG("Unknown exit status for container \"%s\" init %d.", name, WTERMSIG(status));
1450 break;
1451 }
1452 }
1453
1454 DEBUG("Pushing physical nics back to host namespace");
1455 lxc_restore_phys_nics_to_netns(handler->netnsfd, handler->conf);
1456
1457 DEBUG("Tearing down virtual network devices used by container \"%s\".", name);
1458 removed_all_netdevs = lxc_delete_network(handler);
1459
1460 if (handler->pinfd >= 0) {
1461 close(handler->pinfd);
1462 handler->pinfd = -1;
1463 }
1464
1465 lxc_monitor_send_exit_code(name, status, handler->lxcpath);
1466 err = lxc_error_set_and_log(handler->pid, status);
1467 out_fini:
1468 if (!removed_all_netdevs) {
1469 DEBUG("Failed tearing down network devices used by container. Trying again!");
1470 removed_all_netdevs = lxc_delete_network(handler);
1471 if (!removed_all_netdevs)
1472 DEBUG("Failed tearing down network devices used by container. Not trying again!");
1473 }
1474
1475 out_detach_blockdev:
1476 detach_block_device(handler->conf);
1477
1478 out_fini_nonet:
1479 lxc_fini(name, handler);
1480 return err;
1481
1482 out_abort:
1483 lxc_abort(name, handler);
1484 goto out_fini;
1485 }
1486
1487 struct start_args {
1488 char *const *argv;
1489 };
1490
1491 static int start(struct lxc_handler *handler, void* data)
1492 {
1493 struct start_args *arg = data;
1494
1495 NOTICE("Exec'ing \"%s\".", arg->argv[0]);
1496
1497 execvp(arg->argv[0], arg->argv);
1498 SYSERROR("Failed to exec \"%s\".", arg->argv[0]);
1499 return 0;
1500 }
1501
1502 static int post_start(struct lxc_handler *handler, void* data)
1503 {
1504 struct start_args *arg = data;
1505
1506 NOTICE("Started \"%s\" with pid \"%d\".", arg->argv[0], handler->pid);
1507 return 0;
1508 }
1509
1510 static struct lxc_operations start_ops = {
1511 .start = start,
1512 .post_start = post_start
1513 };
1514
1515 int lxc_start(const char *name, char *const argv[], struct lxc_handler *handler,
1516 const char *lxcpath, bool backgrounded)
1517 {
1518 struct start_args start_arg = {
1519 .argv = argv,
1520 };
1521
1522 handler->conf->need_utmp_watch = 1;
1523 return __lxc_start(name, handler, &start_ops, &start_arg, lxcpath, backgrounded);
1524 }
1525
1526 static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
1527 const char *name)
1528 {
1529 char destroy[MAXPATHLEN];
1530 bool bret = true;
1531 int ret = 0;
1532 struct lxc_container *c;
1533 if (handler->conf->rootfs.path && handler->conf->rootfs.mount) {
1534 bret = do_destroy_container(handler->conf);
1535 if (!bret) {
1536 ERROR("Error destroying rootfs for container \"%s\".", name);
1537 return;
1538 }
1539 }
1540 INFO("Destroyed rootfs for container \"%s\".", name);
1541
1542 ret = snprintf(destroy, MAXPATHLEN, "%s/%s", handler->lxcpath, name);
1543 if (ret < 0 || ret >= MAXPATHLEN) {
1544 ERROR("Error destroying directory for container \"%s\".", name);
1545 return;
1546 }
1547
1548 c = lxc_container_new(name, handler->lxcpath);
1549 if (c) {
1550 if (container_disk_lock(c)) {
1551 INFO("Could not update lxc_snapshots file.");
1552 lxc_container_put(c);
1553 } else {
1554 mod_all_rdeps(c, false);
1555 container_disk_unlock(c);
1556 lxc_container_put(c);
1557 }
1558 }
1559
1560 if (am_unpriv())
1561 ret = userns_exec_1(handler->conf, lxc_rmdir_onedev_wrapper,
1562 destroy, "lxc_rmdir_onedev_wrapper");
1563 else
1564 ret = lxc_rmdir_onedev(destroy, NULL);
1565
1566 if (ret < 0) {
1567 ERROR("Error destroying directory for container \"%s\".", name);
1568 return;
1569 }
1570 INFO("Destroyed directory for container \"%s\".", name);
1571 }
1572
1573 static int lxc_rmdir_onedev_wrapper(void *data)
1574 {
1575 char *arg = (char *) data;
1576 return lxc_rmdir_onedev(arg, NULL);
1577 }
1578
1579 static bool do_destroy_container(struct lxc_conf *conf) {
1580 if (am_unpriv()) {
1581 if (userns_exec_1(conf, bdev_destroy_wrapper, conf,
1582 "bdev_destroy_wrapper") < 0)
1583 return false;
1584 return true;
1585 }
1586 return bdev_destroy(conf);
1587 }