]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/start.c
Merge pull request #1658 from 0x0916/2017-06-30/new-configuration-keys
[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: %s.", strerror(errno));
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,
345 lxc_state_t state)
346 {
347 ssize_t ret;
348 struct lxc_list *cur, *next;
349 struct state_client *client;
350 struct lxc_msg msg = {.type = lxc_msg_state, .value = state};
351
352 process_lock();
353 /* Only set state under process lock held so that we don't cause
354 * lxc_cmd_state_server() to miss a state.
355 */
356 handler->state = state;
357 TRACE("set container state to %s", lxc_state2str(state));
358
359 if (lxc_list_empty(&handler->state_clients)) {
360 TRACE("no state clients registered");
361 process_unlock();
362 lxc_monitor_send_state(name, state, handler->lxcpath);
363 return 0;
364 }
365
366 strncpy(msg.name, name, sizeof(msg.name));
367 msg.name[sizeof(msg.name) - 1] = 0;
368
369 lxc_list_for_each_safe(cur, &handler->state_clients, next) {
370 client = cur->elem;
371
372 if (!client->states[state]) {
373 TRACE("state %s not registered for state client %d",
374 lxc_state2str(state), client->clientfd);
375 continue;
376 }
377
378 TRACE("sending state %s to state client %d",
379 lxc_state2str(state), client->clientfd);
380
381 again:
382 ret = send(client->clientfd, &msg, sizeof(msg), 0);
383 if (ret < 0) {
384 if (errno == EINTR)
385 goto again;
386
387 ERROR("failed to send message to client");
388 }
389
390 /* kick client from list */
391 close(client->clientfd);
392 lxc_list_del(cur);
393 free(cur->elem);
394 free(cur);
395 }
396 process_unlock();
397
398 /* This function will try to connect to the legacy lxc-monitord state
399 * server and only exists for backwards compatibility.
400 */
401 lxc_monitor_send_state(name, state, handler->lxcpath);
402
403 return 0;
404 }
405
406 int lxc_poll(const char *name, struct lxc_handler *handler)
407 {
408 int sigfd = handler->sigfd;
409 int pid = handler->pid;
410 struct lxc_epoll_descr descr;
411
412 if (lxc_mainloop_open(&descr)) {
413 ERROR("Failed to create LXC mainloop.");
414 goto out_sigfd;
415 }
416
417 if (lxc_mainloop_add_handler(&descr, sigfd, signal_handler, &pid)) {
418 ERROR("Failed to add signal handler with file descriptor %d to LXC mainloop.", sigfd);
419 goto out_mainloop_open;
420 }
421
422 if (lxc_console_mainloop_add(&descr, handler->conf)) {
423 ERROR("Failed to add console handler to LXC mainloop.");
424 goto out_mainloop_open;
425 }
426
427 if (lxc_cmd_mainloop_add(name, &descr, handler)) {
428 ERROR("Failed to add command handler to LXC mainloop.");
429 goto out_mainloop_open;
430 }
431
432 if (handler->conf->need_utmp_watch) {
433 #if HAVE_LIBCAP
434 if (lxc_utmp_mainloop_add(&descr, handler)) {
435 ERROR("Failed to add utmp handler to LXC mainloop.");
436 goto out_mainloop_open;
437 }
438 #else
439 DEBUG("Not starting utmp handler as CAP_SYS_BOOT cannot be dropped without capabilities support.");
440 #endif
441 }
442 TRACE("lxc mainloop is ready");
443
444 return lxc_mainloop(&descr, -1);
445
446 out_mainloop_open:
447 lxc_mainloop_close(&descr);
448
449 out_sigfd:
450 close(sigfd);
451
452 return -1;
453 }
454
455 void lxc_free_handler(struct lxc_handler *handler)
456 {
457 if (handler->conf && handler->conf->maincmd_fd)
458 close(handler->conf->maincmd_fd);
459
460 if (handler->name)
461 free(handler->name);
462
463 handler->conf = NULL;
464 free(handler);
465 }
466
467 struct lxc_handler *lxc_init_handler(const char *name, struct lxc_conf *conf,
468 const char *lxcpath)
469 {
470 int i;
471 struct lxc_handler *handler;
472
473 handler = malloc(sizeof(*handler));
474 if (!handler) {
475 ERROR("failed to allocate memory");
476 return NULL;
477 }
478
479 memset(handler, 0, sizeof(*handler));
480
481 handler->ttysock[0] = handler->ttysock[1] = -1;
482 handler->conf = conf;
483 handler->lxcpath = lxcpath;
484 handler->pinfd = -1;
485 lxc_list_init(&handler->state_clients);
486
487 for (i = 0; i < LXC_NS_MAX; i++)
488 handler->nsfd[i] = -1;
489
490 handler->name = strdup(name);
491 if (!handler->name) {
492 ERROR("failed to allocate memory");
493 goto on_error;
494 }
495
496 if (lxc_cmd_init(name, handler, lxcpath)) {
497 ERROR("failed to set up command socket");
498 goto on_error;
499 }
500
501 TRACE("unix domain socket %d for command server is ready",
502 handler->conf->maincmd_fd);
503
504 return handler;
505
506 on_error:
507 lxc_free_handler(handler);
508
509 return NULL;
510 }
511
512 int lxc_init(const char *name, struct lxc_handler *handler)
513 {
514 struct lxc_conf *conf = handler->conf;
515
516 lsm_init();
517 TRACE("initialized LSM");
518
519 if (lxc_read_seccomp_config(conf) != 0) {
520 ERROR("Failed loading seccomp policy.");
521 goto out_close_maincmd_fd;
522 }
523 TRACE("read seccomp policy");
524
525 /* Begin by setting the state to STARTING. */
526 if (lxc_set_state(name, handler, STARTING)) {
527 ERROR("Failed to set state for container \"%s\" to \"%s\".", name, lxc_state2str(STARTING));
528 goto out_close_maincmd_fd;
529 }
530 TRACE("set container state to \"STARTING\"");
531
532 /* Start of environment variable setup for hooks. */
533 if (name && setenv("LXC_NAME", name, 1))
534 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name);
535
536 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
537 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf->rcfile);
538
539 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1))
540 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf->rootfs.mount);
541
542 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
543 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf->rootfs.path);
544
545 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1))
546 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf->console.path);
547
548 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1))
549 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf->console.log_path);
550
551 if (setenv("LXC_CGNS_AWARE", "1", 1))
552 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
553 /* End of environment variable setup for hooks. */
554
555 TRACE("set environment variables");
556
557 if (run_lxc_hooks(name, "pre-start", conf, handler->lxcpath, NULL)) {
558 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name);
559 goto out_aborting;
560 }
561 TRACE("ran pre-start hooks");
562
563 /* The signal fd has to be created before forking otherwise if the child
564 * process exits before we setup the signal fd, the event will be lost
565 * and the command will be stuck.
566 */
567 handler->sigfd = setup_signal_fd(&handler->oldmask);
568 if (handler->sigfd < 0) {
569 ERROR("Failed to setup SIGCHLD fd handler.");
570 goto out_delete_tty;
571 }
572 TRACE("set up signal fd");
573
574 /* Do this after setting up signals since it might unblock SIGWINCH. */
575 if (lxc_console_create(conf)) {
576 ERROR("Failed to create console for container \"%s\".", name);
577 goto out_restore_sigmask;
578 }
579 TRACE("created console");
580
581 if (lxc_ttys_shift_ids(conf) < 0) {
582 ERROR("Failed to shift tty into container.");
583 goto out_restore_sigmask;
584 }
585 TRACE("shifted tty ids");
586
587 INFO("container \"%s\" is initialized", name);
588 return 0;
589
590 out_restore_sigmask:
591 sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
592 out_delete_tty:
593 lxc_delete_tty(&conf->tty_info);
594 out_aborting:
595 lxc_set_state(name, handler, ABORTING);
596 out_close_maincmd_fd:
597 close(conf->maincmd_fd);
598 conf->maincmd_fd = -1;
599 return -1;
600 }
601
602 void lxc_fini(const char *name, struct lxc_handler *handler)
603 {
604 int i, rc;
605 struct lxc_list *cur, *next;
606 pid_t self = getpid();
607 char *namespaces[LXC_NS_MAX + 1];
608 size_t namespace_count = 0;
609
610 /* The STOPPING state is there for future cleanup code which can take
611 * awhile.
612 */
613 lxc_set_state(name, handler, STOPPING);
614
615 for (i = 0; i < LXC_NS_MAX; i++) {
616 if (handler->nsfd[i] != -1) {
617 rc = asprintf(&namespaces[namespace_count], "%s:/proc/%d/fd/%d",
618 ns_info[i].proc_name, self, handler->nsfd[i]);
619 if (rc == -1) {
620 SYSERROR("Failed to allocate memory.");
621 break;
622 }
623 ++namespace_count;
624 }
625 }
626 namespaces[namespace_count] = NULL;
627
628 if (handler->conf->reboot && setenv("LXC_TARGET", "reboot", 1))
629 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
630
631 if (!handler->conf->reboot && setenv("LXC_TARGET", "stop", 1))
632 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
633
634 if (run_lxc_hooks(name, "stop", handler->conf, handler->lxcpath, namespaces))
635 ERROR("Failed to run lxc.hook.stop for container \"%s\".", name);
636
637 while (namespace_count--)
638 free(namespaces[namespace_count]);
639 for (i = 0; i < LXC_NS_MAX; i++) {
640 if (handler->nsfd[i] != -1) {
641 close(handler->nsfd[i]);
642 handler->nsfd[i] = -1;
643 }
644 }
645
646 if (handler->netnsfd >= 0) {
647 close(handler->netnsfd);
648 handler->netnsfd = -1;
649 }
650
651 lxc_set_state(name, handler, STOPPED);
652
653 if (run_lxc_hooks(name, "post-stop", handler->conf, handler->lxcpath, NULL)) {
654 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name);
655 if (handler->conf->reboot) {
656 WARN("Container will be stopped instead of rebooted.");
657 handler->conf->reboot = 0;
658 if (setenv("LXC_TARGET", "stop", 1))
659 WARN("Failed to set environment variable: LXC_TARGET=stop.");
660 }
661 }
662
663 /* Reset mask set by setup_signal_fd. */
664 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
665 WARN("Failed to restore signal mask.");
666
667 lxc_console_delete(&handler->conf->console);
668 lxc_delete_tty(&handler->conf->tty_info);
669
670 /* close the command socket */
671 close(handler->conf->maincmd_fd);
672 handler->conf->maincmd_fd = -1;
673
674 /* The command socket is now closed, no more state clients can register
675 * themselves from now on. So free the list of state clients.
676 */
677 lxc_list_for_each_safe(cur, &handler->state_clients, next) {
678 struct state_client *client = cur->elem;
679 /* close state client socket */
680 close(client->clientfd);
681 lxc_list_del(cur);
682 free(cur->elem);
683 free(cur);
684 }
685
686 free(handler->name);
687 if (handler->ttysock[0] != -1) {
688 close(handler->ttysock[0]);
689 close(handler->ttysock[1]);
690 }
691
692 if (handler->conf->ephemeral == 1 && handler->conf->reboot != 1)
693 lxc_destroy_container_on_signal(handler, name);
694
695 cgroup_destroy(handler);
696 free(handler);
697 }
698
699 void lxc_abort(const char *name, struct lxc_handler *handler)
700 {
701 int ret, status;
702
703 lxc_set_state(name, handler, ABORTING);
704 if (handler->pid > 0)
705 kill(handler->pid, SIGKILL);
706 while ((ret = waitpid(-1, &status, 0)) > 0) {
707 ;
708 }
709 }
710
711 #include <sys/reboot.h>
712 #include <linux/reboot.h>
713
714 /* reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL in a child pid namespace
715 * if container reboot support exists. Otherwise, it will either succeed or
716 * return -EPERM.
717 */
718 static int container_reboot_supported(void *arg)
719 {
720 int *cmd = arg;
721 int ret;
722
723 ret = reboot(*cmd);
724 if (ret == -1 && errno == EINVAL)
725 return 1;
726 return 0;
727 }
728
729 static int must_drop_cap_sys_boot(struct lxc_conf *conf)
730 {
731 FILE *f;
732 int ret, cmd, v, flags;
733 long stack_size = 4096;
734 void *stack = alloca(stack_size);
735 int status;
736 pid_t pid;
737
738 f = fopen("/proc/sys/kernel/ctrl-alt-del", "r");
739 if (!f) {
740 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
741 return 1;
742 }
743
744 ret = fscanf(f, "%d", &v);
745 fclose(f);
746 if (ret != 1) {
747 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del.");
748 return 1;
749 }
750 cmd = v ? LINUX_REBOOT_CMD_CAD_ON : LINUX_REBOOT_CMD_CAD_OFF;
751
752 flags = CLONE_NEWPID | SIGCHLD;
753 if (!lxc_list_empty(&conf->id_map))
754 flags |= CLONE_NEWUSER;
755
756 #ifdef __ia64__
757 pid = __clone2(container_reboot_supported, stack, stack_size, flags, &cmd);
758 #else
759 stack += stack_size;
760 pid = clone(container_reboot_supported, stack, flags, &cmd);
761 #endif
762 if (pid < 0) {
763 if (flags & CLONE_NEWUSER)
764 ERROR("Failed to clone (%#x): %s (includes CLONE_NEWUSER).", flags, strerror(errno));
765 else
766 ERROR("Failed to clone (%#x): %s.", flags, strerror(errno));
767 return -1;
768 }
769 if (wait(&status) < 0) {
770 SYSERROR("Unexpected wait error: %s.", strerror(errno));
771 return -1;
772 }
773
774 if (WEXITSTATUS(status) != 1)
775 return 1;
776
777 return 0;
778 }
779
780 /* netpipe is used in the unprivileged case to transfer the ifindexes from
781 * parent to child
782 */
783 static int netpipe = -1;
784
785 static inline int count_veths(struct lxc_list *network)
786 {
787 struct lxc_list *iterator;
788 struct lxc_netdev *netdev;
789 int count = 0;
790
791 lxc_list_for_each(iterator, network) {
792 netdev = iterator->elem;
793 if (netdev->type != LXC_NET_VETH)
794 continue;
795 count++;
796 }
797 return count;
798 }
799
800 static int read_unpriv_netifindex(struct lxc_list *network)
801 {
802 struct lxc_list *iterator;
803 struct lxc_netdev *netdev;
804
805 if (netpipe == -1)
806 return 0;
807 lxc_list_for_each(iterator, network) {
808 netdev = iterator->elem;
809 if (netdev->type != LXC_NET_VETH)
810 continue;
811 if (!(netdev->name = malloc(IFNAMSIZ))) {
812 ERROR("Out of memory.");
813 close(netpipe);
814 return -1;
815 }
816 if (read(netpipe, netdev->name, IFNAMSIZ) != IFNAMSIZ) {
817 close(netpipe);
818 return -1;
819 }
820 }
821 close(netpipe);
822 return 0;
823 }
824
825 static int do_start(void *data)
826 {
827 struct lxc_list *iterator;
828 struct lxc_handler *handler = data;
829 int devnull_fd = -1, ret;
830 char path[PATH_MAX];
831
832 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL)) {
833 SYSERROR("Failed to set signal mask.");
834 return -1;
835 }
836
837 /* This prctl must be before the synchro, so if the parent dies before
838 * we set the parent death signal, we will detect its death with the
839 * synchro right after, otherwise we have a window where the parent can
840 * exit before we set the pdeath signal leading to a unsupervized
841 * container.
842 */
843 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
844 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL.");
845 return -1;
846 }
847
848 lxc_sync_fini_parent(handler);
849
850 /* Don't leak the pinfd to the container. */
851 if (handler->pinfd >= 0) {
852 close(handler->pinfd);
853 }
854
855 if (lxc_sync_wait_parent(handler, LXC_SYNC_STARTUP))
856 return -1;
857
858 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
859 * https://github.com/lxc/lxd/issues/1978.
860 */
861 if ((handler->clone_flags & (CLONE_NEWNET | CLONE_NEWUSER)) ==
862 (CLONE_NEWNET | CLONE_NEWUSER)) {
863 ret = unshare(CLONE_NEWNET);
864 if (ret < 0) {
865 SYSERROR("Failed to unshare CLONE_NEWNET.");
866 goto out_warn_father;
867 }
868 INFO("Unshared CLONE_NEWNET.");
869 }
870
871 /* Tell the parent task it can begin to configure the container and wait
872 * for it to finish.
873 */
874 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE))
875 return -1;
876
877 if (read_unpriv_netifindex(&handler->conf->network) < 0)
878 goto out_warn_father;
879
880 /* If we are in a new user namespace, become root there to have
881 * privilege over our namespace.
882 */
883 if (!lxc_list_empty(&handler->conf->id_map)) {
884 if (lxc_switch_uid_gid(0, 0) < 0)
885 goto out_warn_father;
886
887 /* Drop groups only after we switched to a valid gid in the new
888 * user namespace.
889 */
890 if (lxc_setgroups(0, NULL) < 0)
891 goto out_warn_father;
892 }
893
894 if (access(handler->lxcpath, X_OK)) {
895 print_top_failing_dir(handler->lxcpath);
896 goto out_warn_father;
897 }
898
899 #if HAVE_LIBCAP
900 if (handler->conf->need_utmp_watch) {
901 if (prctl(PR_CAPBSET_DROP, CAP_SYS_BOOT, 0, 0, 0)) {
902 SYSERROR("Failed to remove the CAP_SYS_BOOT capability.");
903 goto out_warn_father;
904 }
905 DEBUG("Dropped the CAP_SYS_BOOT capability.");
906 }
907 #endif
908
909 ret = snprintf(path, sizeof(path), "%s/dev/null", handler->conf->rootfs.mount);
910 if (ret < 0 || ret >= sizeof(path))
911 goto out_warn_father;
912
913 /* In order to checkpoint restore, we need to have everything in the
914 * same mount namespace. However, some containers may not have a
915 * reasonable /dev (in particular, they may not have /dev/null), so we
916 * can't set init's std fds to /dev/null by opening it from inside the
917 * container.
918 *
919 * If that's the case, fall back to using the host's /dev/null. This
920 * means that migration won't work, but at least we won't spew output
921 * where it isn't wanted.
922 */
923 if (handler->backgrounded && !handler->conf->autodev && access(path, F_OK) < 0) {
924 devnull_fd = open_devnull();
925
926 if (devnull_fd < 0)
927 goto out_warn_father;
928 WARN("Using /dev/null from the host for container init's "
929 "standard file descriptors. Migration will not work.");
930 }
931
932 /* Setup the container, ip, names, utsname, ... */
933 if (lxc_setup(handler)) {
934 ERROR("Failed to setup container \"%s\".", handler->name);
935 goto out_warn_father;
936 }
937
938 /* Ask father to setup cgroups and wait for him to finish. */
939 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP))
940 goto out_error;
941
942 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
943 * earlier we end up with a wrong view of /proc/self/cgroup. For
944 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
945 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
946 * /proc/self/cgroup would show us:
947 *
948 * 8:cpuset:/lxc/c
949 *
950 * whereas it should actually show
951 *
952 * 8:cpuset:/
953 */
954 if (cgns_supported()) {
955 if (unshare(CLONE_NEWCGROUP) < 0) {
956 INFO("Failed to unshare CLONE_NEWCGROUP.");
957 goto out_warn_father;
958 }
959 INFO("Unshared CLONE_NEWCGROUP.");
960 }
961
962 /* Set the label to change to when we exec(2) the container's init. */
963 if (lsm_process_label_set(NULL, handler->conf, 1, 1) < 0)
964 goto out_warn_father;
965
966 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
967 * before we aren't allowed anymore.
968 */
969 if (handler->conf->no_new_privs) {
970 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
971 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
972 goto out_warn_father;
973 }
974 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
975 }
976
977 /* Some init's such as busybox will set sane tty settings on stdin,
978 * stdout, stderr which it thinks is the console. We already set them
979 * the way we wanted on the real terminal, and we want init to do its
980 * setup on its console ie. the pty allocated in lxc_console_create() so
981 * make sure that that pty is stdin,stdout,stderr.
982 */
983 if (lxc_console_set_stdfds(handler->conf->console.slave) < 0)
984 goto out_warn_father;
985
986 /* If we mounted a temporary proc, then unmount it now. */
987 tmp_proc_unmount(handler->conf);
988
989 if (lxc_seccomp_load(handler->conf) != 0)
990 goto out_warn_father;
991
992 if (run_lxc_hooks(handler->name, "start", handler->conf, handler->lxcpath, NULL)) {
993 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler->name);
994 goto out_warn_father;
995 }
996
997 /* The container has been setup. We can now switch to an unprivileged
998 * uid/gid.
999 */
1000 if (handler->conf->is_execute) {
1001 bool have_cap_setgid;
1002 uid_t new_uid = handler->conf->init_uid;
1003 gid_t new_gid = handler->conf->init_gid;
1004
1005 /* If we are in a new user namespace we already dropped all
1006 * groups when we switched to root in the new user namespace
1007 * further above. Only drop groups if we can, so ensure that we
1008 * have necessary privilege.
1009 */
1010 #if HAVE_LIBCAP
1011 have_cap_setgid = lxc_proc_cap_is_set(CAP_SETGID, CAP_EFFECTIVE);
1012 #else
1013 have_cap_setgid = false;
1014 #endif
1015 if (lxc_list_empty(&handler->conf->id_map) && have_cap_setgid) {
1016 if (lxc_setgroups(0, NULL) < 0)
1017 goto out_warn_father;
1018 }
1019
1020 if (lxc_switch_uid_gid(new_uid, new_gid) < 0)
1021 goto out_warn_father;
1022 }
1023
1024 /* The clearenv() and putenv() calls have been moved here to allow us to
1025 * use environment variables passed to the various hooks, such as the
1026 * start hook above. Not all of the variables like CONFIG_PATH or ROOTFS
1027 * are valid in this context but others are.
1028 */
1029 if (clearenv()) {
1030 SYSERROR("Failed to clear environment.");
1031 /* Don't error out though. */
1032 }
1033
1034 lxc_list_for_each(iterator, &handler->conf->environment) {
1035 if (putenv((char *)iterator->elem)) {
1036 SYSERROR("Failed to set environment variable: %s.", (char *)iterator->elem);
1037 goto out_warn_father;
1038 }
1039 }
1040
1041 if (putenv("container=lxc")) {
1042 SYSERROR("Failed to set environment variable: container=lxc.");
1043 goto out_warn_father;
1044 }
1045
1046 if (handler->conf->pty_names) {
1047 if (putenv(handler->conf->pty_names)) {
1048 SYSERROR("Failed to set environment variable for container ptys.");
1049 goto out_warn_father;
1050 }
1051 }
1052
1053 close(handler->sigfd);
1054
1055 if (devnull_fd < 0) {
1056 devnull_fd = open_devnull();
1057
1058 if (devnull_fd < 0)
1059 goto out_warn_father;
1060 }
1061
1062 if (handler->backgrounded && set_stdfds(devnull_fd))
1063 goto out_warn_father;
1064
1065 if (devnull_fd >= 0) {
1066 close(devnull_fd);
1067 devnull_fd = -1;
1068 }
1069
1070 setsid();
1071
1072 /* After this call, we are in error because this ops should not return
1073 * as it execs.
1074 */
1075 handler->ops->start(handler, handler->data);
1076
1077 out_warn_father:
1078 /* We want the parent to know something went wrong, so we return a
1079 * special error code.
1080 */
1081 lxc_sync_wake_parent(handler, LXC_SYNC_ERROR);
1082
1083 out_error:
1084 if (devnull_fd >= 0)
1085 close(devnull_fd);
1086
1087 return -1;
1088 }
1089
1090 static int save_phys_nics(struct lxc_conf *conf)
1091 {
1092 struct lxc_list *iterator;
1093 int am_root = (getuid() == 0);
1094
1095 if (!am_root)
1096 return 0;
1097
1098 lxc_list_for_each(iterator, &conf->network) {
1099 struct lxc_netdev *netdev = iterator->elem;
1100
1101 if (netdev->type != LXC_NET_PHYS)
1102 continue;
1103 conf->saved_nics = realloc(conf->saved_nics,
1104 (conf->num_savednics+1)*sizeof(struct saved_nic));
1105 if (!conf->saved_nics)
1106 return -1;
1107 conf->saved_nics[conf->num_savednics].ifindex = netdev->ifindex;
1108 conf->saved_nics[conf->num_savednics].orig_name = strdup(netdev->link);
1109 if (!conf->saved_nics[conf->num_savednics].orig_name)
1110 return -1;
1111 INFO("Stored saved_nic #%d idx %d name %s.", conf->num_savednics,
1112 conf->saved_nics[conf->num_savednics].ifindex,
1113 conf->saved_nics[conf->num_savednics].orig_name);
1114 conf->num_savednics++;
1115 }
1116
1117 return 0;
1118 }
1119
1120 static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
1121 {
1122 int i;
1123 int *ttyfds;
1124 struct lxc_pty_info *pty_info;
1125 int ret = -1;
1126 int sock = handler->ttysock[1];
1127 struct lxc_conf *conf = handler->conf;
1128 struct lxc_tty_info *tty_info = &conf->tty_info;
1129 size_t num_ttyfds = (2 * conf->tty);
1130
1131 if (!conf->tty)
1132 return 0;
1133
1134 tty_info->pty_info = malloc(sizeof(*tty_info->pty_info) * conf->tty);
1135 if (!tty_info->pty_info)
1136 return -1;
1137
1138 ttyfds = malloc(num_ttyfds * sizeof(int));
1139 if (!ttyfds)
1140 return -1;
1141
1142 ret = lxc_abstract_unix_recv_fds(sock, ttyfds, num_ttyfds, NULL, 0);
1143 for (i = 0; (ret >= 0 && *ttyfds != -1) && (i < num_ttyfds); i++) {
1144 pty_info = &tty_info->pty_info[i / 2];
1145 pty_info->busy = 0;
1146 pty_info->slave = ttyfds[i++];
1147 pty_info->master = ttyfds[i];
1148 TRACE("received pty with master fd %d and slave fd %d from "
1149 "parent", pty_info->master, pty_info->slave);
1150 }
1151
1152 tty_info->nbtty = conf->tty;
1153
1154 free(ttyfds);
1155
1156 if (ret < 0)
1157 ERROR("failed to receive %d ttys from child: %s", conf->tty,
1158 strerror(errno));
1159 else
1160 TRACE("received %d ttys from child", conf->tty);
1161
1162 return ret;
1163 }
1164
1165 void resolve_clone_flags(struct lxc_handler *handler)
1166 {
1167 handler->clone_flags = CLONE_NEWPID | CLONE_NEWNS;
1168
1169 if (!lxc_list_empty(&handler->conf->id_map))
1170 handler->clone_flags |= CLONE_NEWUSER;
1171
1172 if (handler->conf->inherit_ns_fd[LXC_NS_NET] == -1) {
1173 if (!lxc_requests_empty_network(handler))
1174 handler->clone_flags |= CLONE_NEWNET;
1175 } else {
1176 INFO("Inheriting a NET namespace.");
1177 }
1178
1179 if (handler->conf->inherit_ns_fd[LXC_NS_IPC] == -1)
1180 handler->clone_flags |= CLONE_NEWIPC;
1181 else
1182 INFO("Inheriting an IPC namespace.");
1183
1184 if (handler->conf->inherit_ns_fd[LXC_NS_UTS] == -1)
1185 handler->clone_flags |= CLONE_NEWUTS;
1186 else
1187 INFO("Inheriting a UTS namespace.");
1188 }
1189
1190 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1191 * exec()s the requested container binary.
1192 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1193 * right here should be double checked if they'd pose a security risk. (For
1194 * example, any {u}mount() operations performed here will be reflected on the
1195 * host!)
1196 */
1197 static int lxc_spawn(struct lxc_handler *handler)
1198 {
1199 int failed_before_rename = 0;
1200 const char *name = handler->name;
1201 bool cgroups_connected = false;
1202 int saved_ns_fd[LXC_NS_MAX];
1203 int preserve_mask = 0, i, flags;
1204 int netpipepair[2], nveths;
1205 bool wants_to_map_ids;
1206 struct lxc_list *id_map;
1207
1208 netpipe = -1;
1209 id_map = &handler->conf->id_map;
1210 wants_to_map_ids = !lxc_list_empty(id_map);
1211
1212 for (i = 0; i < LXC_NS_MAX; i++)
1213 if (handler->conf->inherit_ns_fd[i] != -1)
1214 preserve_mask |= ns_info[i].clone_flag;
1215
1216 if (lxc_sync_init(handler))
1217 return -1;
1218
1219 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, handler->ttysock) < 0) {
1220 lxc_sync_fini(handler);
1221 return -1;
1222 }
1223
1224 resolve_clone_flags(handler);
1225
1226 if (handler->clone_flags & CLONE_NEWNET) {
1227 if (!lxc_list_empty(&handler->conf->network)) {
1228
1229 /* Find gateway addresses from the link device, which is
1230 * no longer accessible inside the container. Do this
1231 * before creating network interfaces, since goto
1232 * out_delete_net does not work before lxc_clone.
1233 */
1234 if (lxc_find_gateway_addresses(handler)) {
1235 ERROR("Failed to find gateway addresses.");
1236 lxc_sync_fini(handler);
1237 return -1;
1238 }
1239
1240 /* That should be done before the clone because we will
1241 * fill the netdev index and use them in the child.
1242 */
1243 if (lxc_setup_networks_in_parent_namespaces(handler)) {
1244 ERROR("Failed to create the network.");
1245 lxc_sync_fini(handler);
1246 return -1;
1247 }
1248 }
1249
1250 if (save_phys_nics(handler->conf)) {
1251 ERROR("Failed to save physical nic info.");
1252 goto out_abort;
1253 }
1254 }
1255
1256 if (!cgroup_init(handler)) {
1257 ERROR("Failed initializing cgroup support.");
1258 goto out_delete_net;
1259 }
1260
1261 cgroups_connected = true;
1262
1263 if (!cgroup_create(handler)) {
1264 ERROR("Failed creating cgroups.");
1265 goto out_delete_net;
1266 }
1267
1268 /* If the rootfs is not a blockdev, prevent the container from marking
1269 * it readonly.
1270 * If the container is unprivileged then skip rootfs pinning.
1271 */
1272 if (!wants_to_map_ids) {
1273 handler->pinfd = pin_rootfs(handler->conf->rootfs.path);
1274 if (handler->pinfd == -1)
1275 INFO("Failed to pin the rootfs for container \"%s\".", handler->name);
1276 }
1277
1278 if (!preserve_ns(saved_ns_fd, preserve_mask, getpid()))
1279 goto out_delete_net;
1280
1281 if (attach_ns(handler->conf->inherit_ns_fd) < 0)
1282 goto out_delete_net;
1283
1284 if (am_unpriv() && (nveths = count_veths(&handler->conf->network))) {
1285 if (pipe(netpipepair) < 0) {
1286 SYSERROR("Failed to create pipe.");
1287 goto out_delete_net;
1288 }
1289 /* Store netpipe in the global var for do_start's use. */
1290 netpipe = netpipepair[0];
1291 }
1292
1293 /* Create a process in a new set of namespaces. */
1294 flags = handler->clone_flags;
1295 if (handler->clone_flags & CLONE_NEWUSER) {
1296 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1297 * clone a new user namespace first and only later unshare our
1298 * network namespace to ensure that network devices ownership is
1299 * set up correctly.
1300 */
1301 flags &= ~CLONE_NEWNET;
1302 }
1303 handler->pid = lxc_clone(do_start, handler, flags);
1304 if (handler->pid < 0) {
1305 SYSERROR("Failed to clone a new set of namespaces.");
1306 goto out_delete_net;
1307 }
1308 for (i = 0; i < LXC_NS_MAX; i++)
1309 if (flags & ns_info[i].clone_flag)
1310 INFO("Cloned %s.", ns_info[i].flag_name);
1311
1312 if (!preserve_ns(handler->nsfd, handler->clone_flags | preserve_mask, handler->pid))
1313 INFO("Failed to preserve namespace for lxc.hook.stop.");
1314
1315 if (attach_ns(saved_ns_fd))
1316 WARN("Failed to restore saved namespaces.");
1317
1318 lxc_sync_fini_child(handler);
1319
1320 /* Map the container uids. The container became an invalid userid the
1321 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1322 * anything immediately, but allows the container to setuid(0) (0 being
1323 * mapped to something else on the host.) later to become a valid uid
1324 * again.
1325 */
1326 if (wants_to_map_ids && lxc_map_ids(id_map, handler->pid)) {
1327 ERROR("Failed to set up id mapping.");
1328 goto out_delete_net;
1329 }
1330
1331 if (lxc_sync_wake_child(handler, LXC_SYNC_STARTUP)) {
1332 failed_before_rename = 1;
1333 goto out_delete_net;
1334 }
1335
1336 if (lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE)) {
1337 failed_before_rename = 1;
1338 goto out_delete_net;
1339 }
1340
1341 if (!cgroup_create_legacy(handler)) {
1342 ERROR("Failed to setup legacy cgroups for container \"%s\".", name);
1343 goto out_delete_net;
1344 }
1345 if (!cgroup_setup_limits(handler, false)) {
1346 ERROR("Failed to setup cgroup limits for container \"%s\".", name);
1347 goto out_delete_net;
1348 }
1349
1350 if (!cgroup_enter(handler))
1351 goto out_delete_net;
1352
1353 if (!cgroup_chown(handler))
1354 goto out_delete_net;
1355
1356 if (failed_before_rename)
1357 goto out_delete_net;
1358
1359 /* Create the network configuration. */
1360 if (handler->clone_flags & CLONE_NEWNET) {
1361 if (lxc_assign_network(handler->lxcpath, handler->name,
1362 &handler->conf->network, handler->pid)) {
1363 ERROR("Failed to create the configured network.");
1364 goto out_delete_net;
1365 }
1366 }
1367
1368 if (netpipe != -1) {
1369 struct lxc_list *iterator;
1370 struct lxc_netdev *netdev;
1371
1372 close(netpipe);
1373 lxc_list_for_each(iterator, &handler->conf->network) {
1374 netdev = iterator->elem;
1375 if (netdev->type != LXC_NET_VETH)
1376 continue;
1377 if (write(netpipepair[1], netdev->name, IFNAMSIZ) != IFNAMSIZ) {
1378 ERROR("Error writing veth name to container.");
1379 goto out_delete_net;
1380 }
1381 }
1382 close(netpipepair[1]);
1383 }
1384
1385 /* Tell the child to continue its initialization. We'll get
1386 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1387 */
1388 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE))
1389 goto out_delete_net;
1390
1391 if (!lxc_list_empty(&handler->conf->limits) && setup_resource_limits(&handler->conf->limits, handler->pid)) {
1392 ERROR("failed to setup resource limits for '%s'", name);
1393 goto out_delete_net;
1394 }
1395
1396 if (!cgroup_setup_limits(handler, true)) {
1397 ERROR("Failed to setup the devices cgroup for container \"%s\".", name);
1398 goto out_delete_net;
1399 }
1400
1401 cgroup_disconnect();
1402 cgroups_connected = false;
1403
1404 /* Read tty fds allocated by child. */
1405 if (lxc_recv_ttys_from_child(handler) < 0) {
1406 ERROR("Failed to receive tty info from child process.");
1407 goto out_delete_net;
1408 }
1409
1410 /* Tell the child to complete its initialization and wait for it to exec
1411 * or return an error. (The child will never return
1412 * LXC_SYNC_POST_CGROUP+1. It will either close the sync pipe, causing
1413 * lxc_sync_barrier_child to return success, or return a different
1414 * value, causing us to error out).
1415 */
1416 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CGROUP))
1417 return -1;
1418
1419 if (handler->ops->post_start(handler, handler->data))
1420 goto out_abort;
1421
1422 if (lxc_set_state(name, handler, RUNNING)) {
1423 ERROR("Failed to set state for container \"%s\" to \"%s\".", name,
1424 lxc_state2str(RUNNING));
1425 goto out_abort;
1426 }
1427
1428 lxc_sync_fini(handler);
1429 handler->netnsfd = lxc_preserve_ns(handler->pid, "net");
1430
1431 return 0;
1432
1433 out_delete_net:
1434 if (cgroups_connected)
1435 cgroup_disconnect();
1436 if (handler->clone_flags & CLONE_NEWNET)
1437 lxc_delete_network(handler);
1438 out_abort:
1439 lxc_abort(name, handler);
1440 lxc_sync_fini(handler);
1441 if (handler->pinfd >= 0) {
1442 close(handler->pinfd);
1443 handler->pinfd = -1;
1444 }
1445
1446 return -1;
1447 }
1448
1449 int __lxc_start(const char *name, struct lxc_handler *handler,
1450 struct lxc_operations* ops, void *data, const char *lxcpath,
1451 bool backgrounded)
1452 {
1453 int status;
1454 int err = -1;
1455 bool removed_all_netdevs = true;
1456 struct lxc_conf *conf = handler->conf;
1457
1458 if (lxc_init(name, handler) < 0) {
1459 ERROR("Failed to initialize container \"%s\".", name);
1460 return -1;
1461 }
1462 handler->ops = ops;
1463 handler->data = data;
1464 handler->backgrounded = backgrounded;
1465 handler->netnsfd = -1;
1466
1467 if (must_drop_cap_sys_boot(handler->conf)) {
1468 #if HAVE_LIBCAP
1469 DEBUG("Dropping CAP_SYS_BOOT capability.");
1470 #else
1471 DEBUG("Not dropping CAP_SYS_BOOT capability as capabilities aren't supported.");
1472 #endif
1473 } else {
1474 DEBUG("Not dropping CAP_SYS_BOOT or watching utmp.");
1475 handler->conf->need_utmp_watch = 0;
1476 }
1477
1478 if (!attach_block_device(handler->conf)) {
1479 ERROR("Failed to attach block device.");
1480 goto out_fini_nonet;
1481 }
1482
1483 if (geteuid() == 0 && !lxc_list_empty(&conf->id_map)) {
1484 /* If the backing store is a device, mount it here and now. */
1485 if (rootfs_is_blockdev(conf)) {
1486 if (unshare(CLONE_NEWNS) < 0) {
1487 ERROR("Failed to unshare CLONE_NEWNS.");
1488 goto out_fini_nonet;
1489 }
1490 INFO("Unshared CLONE_NEWNS.");
1491
1492 remount_all_slave();
1493 if (do_rootfs_setup(conf, name, lxcpath) < 0) {
1494 ERROR("Error setting up rootfs mount as root before spawn.");
1495 goto out_fini_nonet;
1496 }
1497 INFO("Set up container rootfs as host root.");
1498 }
1499 }
1500
1501 err = lxc_spawn(handler);
1502 if (err) {
1503 ERROR("Failed to spawn container \"%s\".", name);
1504 goto out_detach_blockdev;
1505 }
1506
1507 handler->conf->reboot = 0;
1508
1509 err = lxc_poll(name, handler);
1510 if (err) {
1511 ERROR("LXC mainloop exited with error: %d.", err);
1512 if (handler->netnsfd >= 0) {
1513 close(handler->netnsfd);
1514 handler->netnsfd = -1;
1515 }
1516 goto out_abort;
1517 }
1518
1519 while (waitpid(handler->pid, &status, 0) < 0 && errno == EINTR)
1520 continue;
1521
1522 /* If the child process exited but was not signaled, it didn't call
1523 * reboot. This should mean it was an lxc-execute which simply exited.
1524 * In any case, treat it as a 'halt'.
1525 */
1526 if (WIFSIGNALED(status)) {
1527 switch(WTERMSIG(status)) {
1528 case SIGINT: /* halt */
1529 DEBUG("Container \"%s\" is halting.", name);
1530 break;
1531 case SIGHUP: /* reboot */
1532 DEBUG("Container \"%s\" is rebooting.", name);
1533 handler->conf->reboot = 1;
1534 break;
1535 case SIGSYS: /* seccomp */
1536 DEBUG("Container \"%s\" violated its seccomp policy.", name);
1537 break;
1538 default:
1539 DEBUG("Unknown exit status for container \"%s\" init %d.", name, WTERMSIG(status));
1540 break;
1541 }
1542 }
1543
1544 DEBUG("Pushing physical nics back to host namespace");
1545 lxc_restore_phys_nics_to_netns(handler->netnsfd, handler->conf);
1546
1547 DEBUG("Tearing down virtual network devices used by container \"%s\".", name);
1548 removed_all_netdevs = lxc_delete_network(handler);
1549
1550 if (handler->pinfd >= 0) {
1551 close(handler->pinfd);
1552 handler->pinfd = -1;
1553 }
1554
1555 lxc_monitor_send_exit_code(name, status, handler->lxcpath);
1556 err = lxc_error_set_and_log(handler->pid, status);
1557 out_fini:
1558 if (!removed_all_netdevs) {
1559 DEBUG("Failed tearing down network devices used by container. Trying again!");
1560 removed_all_netdevs = lxc_delete_network(handler);
1561 if (!removed_all_netdevs)
1562 DEBUG("Failed tearing down network devices used by container. Not trying again!");
1563 }
1564
1565 out_detach_blockdev:
1566 detach_block_device(handler->conf);
1567
1568 out_fini_nonet:
1569 lxc_fini(name, handler);
1570 return err;
1571
1572 out_abort:
1573 lxc_abort(name, handler);
1574 goto out_fini;
1575 }
1576
1577 struct start_args {
1578 char *const *argv;
1579 };
1580
1581 static int start(struct lxc_handler *handler, void* data)
1582 {
1583 struct start_args *arg = data;
1584
1585 NOTICE("Exec'ing \"%s\".", arg->argv[0]);
1586
1587 execvp(arg->argv[0], arg->argv);
1588 SYSERROR("Failed to exec \"%s\".", arg->argv[0]);
1589 return 0;
1590 }
1591
1592 static int post_start(struct lxc_handler *handler, void* data)
1593 {
1594 struct start_args *arg = data;
1595
1596 NOTICE("Started \"%s\" with pid \"%d\".", arg->argv[0], handler->pid);
1597 return 0;
1598 }
1599
1600 static struct lxc_operations start_ops = {
1601 .start = start,
1602 .post_start = post_start
1603 };
1604
1605 int lxc_start(const char *name, char *const argv[], struct lxc_handler *handler,
1606 const char *lxcpath, bool backgrounded)
1607 {
1608 struct start_args start_arg = {
1609 .argv = argv,
1610 };
1611
1612 handler->conf->need_utmp_watch = 1;
1613 return __lxc_start(name, handler, &start_ops, &start_arg, lxcpath, backgrounded);
1614 }
1615
1616 static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
1617 const char *name)
1618 {
1619 char destroy[MAXPATHLEN];
1620 bool bret = true;
1621 int ret = 0;
1622 struct lxc_container *c;
1623 if (handler->conf->rootfs.path && handler->conf->rootfs.mount) {
1624 bret = do_destroy_container(handler->conf);
1625 if (!bret) {
1626 ERROR("Error destroying rootfs for container \"%s\".", name);
1627 return;
1628 }
1629 }
1630 INFO("Destroyed rootfs for container \"%s\".", name);
1631
1632 ret = snprintf(destroy, MAXPATHLEN, "%s/%s", handler->lxcpath, name);
1633 if (ret < 0 || ret >= MAXPATHLEN) {
1634 ERROR("Error destroying directory for container \"%s\".", name);
1635 return;
1636 }
1637
1638 c = lxc_container_new(name, handler->lxcpath);
1639 if (c) {
1640 if (container_disk_lock(c)) {
1641 INFO("Could not update lxc_snapshots file.");
1642 lxc_container_put(c);
1643 } else {
1644 mod_all_rdeps(c, false);
1645 container_disk_unlock(c);
1646 lxc_container_put(c);
1647 }
1648 }
1649
1650 if (am_unpriv())
1651 ret = userns_exec_1(handler->conf, lxc_rmdir_onedev_wrapper,
1652 destroy, "lxc_rmdir_onedev_wrapper");
1653 else
1654 ret = lxc_rmdir_onedev(destroy, NULL);
1655
1656 if (ret < 0) {
1657 ERROR("Error destroying directory for container \"%s\".", name);
1658 return;
1659 }
1660 INFO("Destroyed directory for container \"%s\".", name);
1661 }
1662
1663 static int lxc_rmdir_onedev_wrapper(void *data)
1664 {
1665 char *arg = (char *) data;
1666 return lxc_rmdir_onedev(arg, NULL);
1667 }
1668
1669 static bool do_destroy_container(struct lxc_conf *conf) {
1670 if (am_unpriv()) {
1671 if (userns_exec_1(conf, bdev_destroy_wrapper, conf,
1672 "bdev_destroy_wrapper") < 0)
1673 return false;
1674 return true;
1675 }
1676 return bdev_destroy(conf);
1677 }