]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/start.c
lxc-oracle: export upstart environment variable for maygetty
[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 #include "config.h"
25
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <dirent.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <signal.h>
33 #include <fcntl.h>
34 #include <grp.h>
35 #include <poll.h>
36 #include <sys/param.h>
37 #include <sys/file.h>
38 #include <sys/mount.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <sys/socket.h>
42 #include <sys/prctl.h>
43 #include <sys/types.h>
44 #include <sys/wait.h>
45 #include <sys/un.h>
46 #include <sys/syscall.h>
47
48 #if HAVE_SYS_CAPABILITY_H
49 #include <sys/capability.h>
50 #endif
51
52 #if !HAVE_DECL_PR_CAPBSET_DROP
53 #define PR_CAPBSET_DROP 24
54 #endif
55
56 #include "start.h"
57 #include "conf.h"
58 #include "log.h"
59 #include "cgroup.h"
60 #include "error.h"
61 #include "af_unix.h"
62 #include "mainloop.h"
63 #include "utils.h"
64 #include "lxcutmp.h"
65 #include "monitor.h"
66 #include "commands.h"
67 #include "console.h"
68 #include "sync.h"
69 #include "namespace.h"
70 #include "lxcseccomp.h"
71 #include "caps.h"
72 #include "lsm/lsm.h"
73
74 lxc_log_define(lxc_start, lxc);
75
76 const struct ns_info ns_info[LXC_NS_MAX] = {
77 [LXC_NS_MNT] = {"mnt", CLONE_NEWNS},
78 [LXC_NS_PID] = {"pid", CLONE_NEWPID},
79 [LXC_NS_UTS] = {"uts", CLONE_NEWUTS},
80 [LXC_NS_IPC] = {"ipc", CLONE_NEWIPC},
81 [LXC_NS_USER] = {"user", CLONE_NEWUSER},
82 [LXC_NS_NET] = {"net", CLONE_NEWNET}
83 };
84
85 static void print_top_failing_dir(const char *path)
86 {
87 size_t len = strlen(path);
88 char *copy = alloca(len+1), *p, *e, saved;
89 strcpy(copy, path);
90
91 p = copy;
92 e = copy + len;
93 while (p < e) {
94 while (p < e && *p == '/') p++;
95 while (p < e && *p != '/') p++;
96 saved = *p;
97 *p = '\0';
98 if (access(copy, X_OK)) {
99 SYSERROR("could not access %s. Please grant it 'x' " \
100 "access, or add an ACL for the container root.",
101 copy);
102 return;
103 }
104 *p = saved;
105 }
106 }
107
108 static void close_ns(int ns_fd[LXC_NS_MAX]) {
109 int i;
110
111 for (i = 0; i < LXC_NS_MAX; i++) {
112 if (ns_fd[i] > -1) {
113 close(ns_fd[i]);
114 ns_fd[i] = -1;
115 }
116 }
117 }
118
119 static int preserve_ns(int ns_fd[LXC_NS_MAX], int clone_flags) {
120 int i, saved_errno;
121 char path[MAXPATHLEN];
122
123 for (i = 0; i < LXC_NS_MAX; i++)
124 ns_fd[i] = -1;
125
126 if (access("/proc/self/ns", X_OK)) {
127 WARN("Kernel does not support attach; preserve_ns ignored");
128 return 0;
129 }
130
131 for (i = 0; i < LXC_NS_MAX; i++) {
132 if ((clone_flags & ns_info[i].clone_flag) == 0)
133 continue;
134 snprintf(path, MAXPATHLEN, "/proc/self/ns/%s", ns_info[i].proc_name);
135 ns_fd[i] = open(path, O_RDONLY | O_CLOEXEC);
136 if (ns_fd[i] < 0)
137 goto error;
138 }
139
140 return 0;
141
142 error:
143 saved_errno = errno;
144 close_ns(ns_fd);
145 errno = saved_errno;
146 SYSERROR("failed to open '%s'", path);
147 return -1;
148 }
149
150 static int attach_ns(const int ns_fd[LXC_NS_MAX]) {
151 int i;
152
153 for (i = 0; i < LXC_NS_MAX; i++) {
154 if (ns_fd[i] < 0)
155 continue;
156
157 if (setns(ns_fd[i], 0) != 0)
158 goto error;
159 }
160 return 0;
161
162 error:
163 SYSERROR("failed to set namespace '%s'", ns_info[i].proc_name);
164 return -1;
165 }
166
167 static int match_fd(int fd)
168 {
169 return (fd == 0 || fd == 1 || fd == 2);
170 }
171
172 int lxc_check_inherited(struct lxc_conf *conf, int fd_to_ignore)
173 {
174 struct dirent dirent, *direntp;
175 int fd, fddir;
176 DIR *dir;
177
178 restart:
179 dir = opendir("/proc/self/fd");
180 if (!dir) {
181 WARN("failed to open directory: %m");
182 return -1;
183 }
184
185 fddir = dirfd(dir);
186
187 while (!readdir_r(dir, &dirent, &direntp)) {
188 if (!direntp)
189 break;
190
191 if (!strcmp(direntp->d_name, "."))
192 continue;
193
194 if (!strcmp(direntp->d_name, ".."))
195 continue;
196
197 fd = atoi(direntp->d_name);
198
199 if (fd == fddir || fd == lxc_log_fd || fd == fd_to_ignore)
200 continue;
201
202 if (match_fd(fd))
203 continue;
204
205 if (conf->close_all_fds) {
206 close(fd);
207 closedir(dir);
208 INFO("closed inherited fd %d", fd);
209 goto restart;
210 }
211 WARN("inherited fd %d", fd);
212 }
213
214 closedir(dir); /* cannot fail */
215 return 0;
216 }
217
218 static int setup_signal_fd(sigset_t *oldmask)
219 {
220 sigset_t mask;
221 int fd;
222
223 /* Block everything except serious error signals */
224 if (sigfillset(&mask) ||
225 sigdelset(&mask, SIGILL) ||
226 sigdelset(&mask, SIGSEGV) ||
227 sigdelset(&mask, SIGBUS) ||
228 sigdelset(&mask, SIGWINCH) ||
229 sigprocmask(SIG_BLOCK, &mask, oldmask)) {
230 SYSERROR("failed to set signal mask");
231 return -1;
232 }
233
234 fd = signalfd(-1, &mask, 0);
235 if (fd < 0) {
236 SYSERROR("failed to create the signal fd");
237 return -1;
238 }
239
240 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
241 SYSERROR("failed to set sigfd to close-on-exec");
242 close(fd);
243 return -1;
244 }
245
246 DEBUG("sigchild handler set");
247
248 return fd;
249 }
250
251 static int signal_handler(int fd, uint32_t events, void *data,
252 struct lxc_epoll_descr *descr)
253 {
254 struct signalfd_siginfo siginfo;
255 siginfo_t info;
256 int ret;
257 pid_t *pid = data;
258 bool init_died = false;
259
260 ret = read(fd, &siginfo, sizeof(siginfo));
261 if (ret < 0) {
262 ERROR("failed to read signal info");
263 return -1;
264 }
265
266 if (ret != sizeof(siginfo)) {
267 ERROR("unexpected siginfo size");
268 return -1;
269 }
270
271 // check whether init is running
272 info.si_pid = 0;
273 ret = waitid(P_PID, *pid, &info, WEXITED | WNOWAIT | WNOHANG);
274 if (ret == 0 && info.si_pid == *pid) {
275 init_died = true;
276 }
277
278 if (siginfo.ssi_signo != SIGCHLD) {
279 kill(*pid, siginfo.ssi_signo);
280 INFO("forwarded signal %d to pid %d", siginfo.ssi_signo, *pid);
281 return init_died ? 1 : 0;
282 }
283
284 if (siginfo.ssi_code == CLD_STOPPED ||
285 siginfo.ssi_code == CLD_CONTINUED) {
286 INFO("container init process was stopped/continued");
287 return init_died ? 1 : 0;
288 }
289
290 /* more robustness, protect ourself from a SIGCHLD sent
291 * by a process different from the container init
292 */
293 if (siginfo.ssi_pid != *pid) {
294 WARN("invalid pid for SIGCHLD");
295 return init_died ? 1 : 0;
296 }
297
298 DEBUG("container init process exited");
299 return 1;
300 }
301
302 static int lxc_set_state(const char *name, struct lxc_handler *handler, lxc_state_t state)
303 {
304 handler->state = state;
305 lxc_monitor_send_state(name, state, handler->lxcpath);
306 return 0;
307 }
308
309 static int lxc_poll(const char *name, struct lxc_handler *handler)
310 {
311 int sigfd = handler->sigfd;
312 int pid = handler->pid;
313 struct lxc_epoll_descr descr;
314
315 if (lxc_mainloop_open(&descr)) {
316 ERROR("failed to create mainloop");
317 goto out_sigfd;
318 }
319
320 if (lxc_mainloop_add_handler(&descr, sigfd, signal_handler, &pid)) {
321 ERROR("failed to add handler for the signal");
322 goto out_mainloop_open;
323 }
324
325 if (lxc_console_mainloop_add(&descr, handler)) {
326 ERROR("failed to add console handler to mainloop");
327 goto out_mainloop_open;
328 }
329
330 if (lxc_cmd_mainloop_add(name, &descr, handler)) {
331 ERROR("failed to add command handler to mainloop");
332 goto out_mainloop_open;
333 }
334
335 if (handler->conf->need_utmp_watch) {
336 #if HAVE_SYS_CAPABILITY_H
337 if (lxc_utmp_mainloop_add(&descr, handler)) {
338 ERROR("failed to add utmp handler to mainloop");
339 goto out_mainloop_open;
340 }
341 #else
342 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support");
343 #endif
344 }
345
346 return lxc_mainloop(&descr, -1);
347
348 out_mainloop_open:
349 lxc_mainloop_close(&descr);
350 out_sigfd:
351 close(sigfd);
352 return -1;
353 }
354
355 struct lxc_handler *lxc_init(const char *name, struct lxc_conf *conf, const char *lxcpath)
356 {
357 struct lxc_handler *handler;
358
359 handler = malloc(sizeof(*handler));
360 if (!handler)
361 return NULL;
362
363 memset(handler, 0, sizeof(*handler));
364
365 handler->conf = conf;
366 handler->lxcpath = lxcpath;
367 handler->pinfd = -1;
368
369 lsm_init();
370
371 handler->name = strdup(name);
372 if (!handler->name) {
373 ERROR("failed to allocate memory");
374 goto out_free;
375 }
376
377 if (lxc_cmd_init(name, handler, lxcpath))
378 goto out_free_name;
379
380 if (lxc_read_seccomp_config(conf) != 0) {
381 ERROR("failed loading seccomp policy");
382 goto out_close_maincmd_fd;
383 }
384
385 /* Begin by setting the state to STARTING */
386 if (lxc_set_state(name, handler, STARTING)) {
387 ERROR("failed to set state '%s'", lxc_state2str(STARTING));
388 goto out_close_maincmd_fd;
389 }
390
391 /* Start of environment variable setup for hooks */
392 if (setenv("LXC_NAME", name, 1)) {
393 SYSERROR("failed to set environment variable for container name");
394 }
395 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
396 SYSERROR("failed to set environment variable for config path");
397 }
398 if (setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
399 SYSERROR("failed to set environment variable for rootfs mount");
400 }
401 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
402 SYSERROR("failed to set environment variable for rootfs mount");
403 }
404 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1)) {
405 SYSERROR("failed to set environment variable for console path");
406 }
407 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1)) {
408 SYSERROR("failed to set environment variable for console log");
409 }
410 /* End of environment variable setup for hooks */
411
412 if (run_lxc_hooks(name, "pre-start", conf, handler->lxcpath, NULL)) {
413 ERROR("failed to run pre-start hooks for container '%s'.", name);
414 goto out_aborting;
415 }
416
417 if (lxc_create_tty(name, conf)) {
418 ERROR("failed to create the ttys");
419 goto out_aborting;
420 }
421
422 /* the signal fd has to be created before forking otherwise
423 * if the child process exits before we setup the signal fd,
424 * the event will be lost and the command will be stuck */
425 handler->sigfd = setup_signal_fd(&handler->oldmask);
426 if (handler->sigfd < 0) {
427 ERROR("failed to set sigchild fd handler");
428 goto out_delete_tty;
429 }
430
431 /* do this after setting up signals since it might unblock SIGWINCH */
432 if (lxc_console_create(conf)) {
433 ERROR("failed to create console");
434 goto out_restore_sigmask;
435 }
436
437 if (ttys_shift_ids(conf) < 0) {
438 ERROR("Failed to shift tty into container");
439 goto out_restore_sigmask;
440 }
441
442 INFO("'%s' is initialized", name);
443 return handler;
444
445 out_restore_sigmask:
446 sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
447 out_delete_tty:
448 lxc_delete_tty(&conf->tty_info);
449 out_aborting:
450 lxc_set_state(name, handler, ABORTING);
451 out_close_maincmd_fd:
452 close(conf->maincmd_fd);
453 conf->maincmd_fd = -1;
454 out_free_name:
455 free(handler->name);
456 handler->name = NULL;
457 out_free:
458 free(handler);
459 return NULL;
460 }
461
462 static void lxc_fini(const char *name, struct lxc_handler *handler)
463 {
464 /* The STOPPING state is there for future cleanup code
465 * which can take awhile
466 */
467 lxc_set_state(name, handler, STOPPING);
468 lxc_set_state(name, handler, STOPPED);
469
470 if (run_lxc_hooks(name, "post-stop", handler->conf, handler->lxcpath, NULL))
471 ERROR("failed to run post-stop hooks for container '%s'.", name);
472
473 /* reset mask set by setup_signal_fd */
474 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
475 WARN("failed to restore sigprocmask");
476
477 lxc_console_delete(&handler->conf->console);
478 lxc_delete_tty(&handler->conf->tty_info);
479 close(handler->conf->maincmd_fd);
480 handler->conf->maincmd_fd = -1;
481 free(handler->name);
482 cgroup_destroy(handler);
483 free(handler);
484 }
485
486 static void lxc_abort(const char *name, struct lxc_handler *handler)
487 {
488 int ret, status;
489
490 lxc_set_state(name, handler, ABORTING);
491 if (handler->pid > 0)
492 kill(handler->pid, SIGKILL);
493 while ((ret = waitpid(-1, &status, 0)) > 0) ;
494 }
495
496 #include <sys/reboot.h>
497 #include <linux/reboot.h>
498
499 /*
500 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
501 * in a child pid namespace if container reboot support exists.
502 * Otherwise, it will either succeed or return -EPERM.
503 */
504 static int container_reboot_supported(void *arg)
505 {
506 int *cmd = arg;
507 int ret;
508
509 ret = reboot(*cmd);
510 if (ret == -1 && errno == EINVAL)
511 return 1;
512 return 0;
513 }
514
515 static int must_drop_cap_sys_boot(struct lxc_conf *conf)
516 {
517 FILE *f;
518 int ret, cmd, v, flags;
519 long stack_size = 4096;
520 void *stack = alloca(stack_size);
521 int status;
522 pid_t pid;
523
524 f = fopen("/proc/sys/kernel/ctrl-alt-del", "r");
525 if (!f) {
526 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
527 return 1;
528 }
529
530 ret = fscanf(f, "%d", &v);
531 fclose(f);
532 if (ret != 1) {
533 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
534 return 1;
535 }
536 cmd = v ? LINUX_REBOOT_CMD_CAD_ON : LINUX_REBOOT_CMD_CAD_OFF;
537
538 flags = CLONE_NEWPID | SIGCHLD;
539 if (!lxc_list_empty(&conf->id_map))
540 flags |= CLONE_NEWUSER;
541
542 #ifdef __ia64__
543 pid = __clone2(container_reboot_supported, stack, stack_size, flags, &cmd);
544 #else
545 stack += stack_size;
546 pid = clone(container_reboot_supported, stack, flags, &cmd);
547 #endif
548 if (pid < 0) {
549 SYSERROR("failed to clone");
550 return -1;
551 }
552 if (wait(&status) < 0) {
553 SYSERROR("unexpected wait error: %m");
554 return -1;
555 }
556
557 if (WEXITSTATUS(status) != 1)
558 return 1;
559
560 return 0;
561 }
562
563 /*
564 * netpipe is used in the unprivileged case to transfer the ifindexes
565 * from parent to child
566 */
567 static int netpipe = -1;
568
569 static inline int count_veths(struct lxc_list *network)
570 {
571 struct lxc_list *iterator;
572 struct lxc_netdev *netdev;
573 int count = 0;
574
575 lxc_list_for_each(iterator, network) {
576 netdev = iterator->elem;
577 if (netdev->type != LXC_NET_VETH)
578 continue;
579 count++;
580 }
581 return count;
582 }
583
584 static int read_unpriv_netifindex(struct lxc_list *network)
585 {
586 struct lxc_list *iterator;
587 struct lxc_netdev *netdev;
588
589 if (netpipe == -1)
590 return 0;
591 lxc_list_for_each(iterator, network) {
592 netdev = iterator->elem;
593 if (netdev->type != LXC_NET_VETH)
594 continue;
595 if (!(netdev->name = malloc(IFNAMSIZ))) {
596 ERROR("Out of memory");
597 close(netpipe);
598 return -1;
599 }
600 if (read(netpipe, netdev->name, IFNAMSIZ) != IFNAMSIZ) {
601 close(netpipe);
602 return -1;
603 }
604 }
605 close(netpipe);
606 return 0;
607 }
608
609 static int do_start(void *data)
610 {
611 struct lxc_handler *handler = data;
612 const char *lsm_label = NULL;
613
614 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL)) {
615 SYSERROR("failed to set sigprocmask");
616 return -1;
617 }
618
619 /* This prctl must be before the synchro, so if the parent
620 * dies before we set the parent death signal, we will detect
621 * its death with the synchro right after, otherwise we have
622 * a window where the parent can exit before we set the pdeath
623 * signal leading to a unsupervized container.
624 */
625 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
626 SYSERROR("failed to set pdeath signal");
627 return -1;
628 }
629
630 lxc_sync_fini_parent(handler);
631
632 /* don't leak the pinfd to the container */
633 if (handler->pinfd >= 0) {
634 close(handler->pinfd);
635 }
636
637 /* Tell the parent task it can begin to configure the
638 * container and wait for it to finish
639 */
640 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE))
641 return -1;
642
643 if (read_unpriv_netifindex(&handler->conf->network) < 0)
644 goto out_warn_father;
645
646 /*
647 * if we are in a new user namespace, become root there to have
648 * privilege over our namespace
649 */
650 if (!lxc_list_empty(&handler->conf->id_map)) {
651 NOTICE("switching to gid/uid 0 in new user namespace");
652 if (setgid(0)) {
653 SYSERROR("setgid");
654 goto out_warn_father;
655 }
656 if (setuid(0)) {
657 SYSERROR("setuid");
658 goto out_warn_father;
659 }
660 if (setgroups(0, NULL)) {
661 SYSERROR("setgroups");
662 goto out_warn_father;
663 }
664 }
665
666 if (access(handler->lxcpath, X_OK)) {
667 print_top_failing_dir(handler->lxcpath);
668 goto out_warn_father;
669 }
670
671 #if HAVE_SYS_CAPABILITY_H
672 if (handler->conf->need_utmp_watch) {
673 if (prctl(PR_CAPBSET_DROP, CAP_SYS_BOOT, 0, 0, 0)) {
674 SYSERROR("failed to remove CAP_SYS_BOOT capability");
675 goto out_warn_father;
676 }
677 DEBUG("Dropped cap_sys_boot");
678 }
679 #endif
680
681 /* Setup the container, ip, names, utsname, ... */
682 if (lxc_setup(handler)) {
683 ERROR("failed to setup the container");
684 goto out_warn_father;
685 }
686
687 /* ask father to setup cgroups and wait for him to finish */
688 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP))
689 return -1;
690
691 /* Set the label to change to when we exec(2) the container's init */
692 if (!strcmp(lsm_name(), "AppArmor"))
693 lsm_label = handler->conf->lsm_aa_profile;
694 else if (!strcmp(lsm_name(), "SELinux"))
695 lsm_label = handler->conf->lsm_se_context;
696 if (lsm_process_label_set(lsm_label, 1, 1) < 0)
697 goto out_warn_father;
698
699 /* Some init's such as busybox will set sane tty settings on stdin,
700 * stdout, stderr which it thinks is the console. We already set them
701 * the way we wanted on the real terminal, and we want init to do its
702 * setup on its console ie. the pty allocated in lxc_console_create()
703 * so make sure that that pty is stdin,stdout,stderr.
704 */
705 if (lxc_console_set_stdfds(handler) < 0)
706 goto out_warn_father;
707
708 /* If we mounted a temporary proc, then unmount it now */
709 tmp_proc_unmount(handler->conf);
710
711 if (lxc_seccomp_load(handler->conf) != 0)
712 goto out_warn_father;
713
714 if (run_lxc_hooks(handler->name, "start", handler->conf, handler->lxcpath, NULL)) {
715 ERROR("failed to run start hooks for container '%s'.", handler->name);
716 goto out_warn_father;
717 }
718
719 /* The clearenv() and putenv() calls have been moved here
720 * to allow us to use enviroment variables passed to the various
721 * hooks, such as the start hook above. Not all of the
722 * variables like CONFIG_PATH or ROOTFS are valid in this
723 * context but others are. */
724 if (clearenv()) {
725 SYSERROR("failed to clear environment");
726 /* don't error out though */
727 }
728
729 if (putenv("container=lxc")) {
730 SYSERROR("failed to set environment variable");
731 goto out_warn_father;
732 }
733
734 close(handler->sigfd);
735
736 /* after this call, we are in error because this
737 * ops should not return as it execs */
738 handler->ops->start(handler, handler->data);
739
740 out_warn_father:
741 /* we want the parent to know something went wrong, so any
742 * value other than what it expects is ok. */
743 lxc_sync_wake_parent(handler, LXC_SYNC_POST_CONFIGURE);
744 return -1;
745 }
746
747 static int save_phys_nics(struct lxc_conf *conf)
748 {
749 struct lxc_list *iterator;
750
751 lxc_list_for_each(iterator, &conf->network) {
752 struct lxc_netdev *netdev = iterator->elem;
753
754 if (netdev->type != LXC_NET_PHYS)
755 continue;
756 conf->saved_nics = realloc(conf->saved_nics,
757 (conf->num_savednics+1)*sizeof(struct saved_nic));
758 if (!conf->saved_nics) {
759 SYSERROR("failed to allocate memory");
760 return -1;
761 }
762 conf->saved_nics[conf->num_savednics].ifindex = netdev->ifindex;
763 conf->saved_nics[conf->num_savednics].orig_name = strdup(netdev->link);
764 if (!conf->saved_nics[conf->num_savednics].orig_name) {
765 SYSERROR("failed to allocate memory");
766 return -1;
767 }
768 INFO("stored saved_nic #%d idx %d name %s", conf->num_savednics,
769 conf->saved_nics[conf->num_savednics].ifindex,
770 conf->saved_nics[conf->num_savednics].orig_name);
771 conf->num_savednics++;
772 }
773
774 return 0;
775 }
776
777 static int lxc_spawn(struct lxc_handler *handler)
778 {
779 int failed_before_rename = 0;
780 const char *name = handler->name;
781 bool cgroups_connected = false;
782 int saved_ns_fd[LXC_NS_MAX];
783 int preserve_mask = 0, i;
784 int netpipepair[2], nveths;
785
786 netpipe = -1;
787
788 for (i = 0; i < LXC_NS_MAX; i++)
789 if (handler->conf->inherit_ns_fd[i] != -1)
790 preserve_mask |= ns_info[i].clone_flag;
791
792 if (lxc_sync_init(handler))
793 return -1;
794
795 handler->clone_flags = CLONE_NEWPID|CLONE_NEWNS;
796 if (!lxc_list_empty(&handler->conf->id_map)) {
797 INFO("Cloning a new user namespace");
798 handler->clone_flags |= CLONE_NEWUSER;
799 }
800
801 if (handler->conf->inherit_ns_fd[LXC_NS_NET] == -1) {
802 if (!lxc_requests_empty_network(handler))
803 handler->clone_flags |= CLONE_NEWNET;
804
805 if (!lxc_list_empty(&handler->conf->network)) {
806
807 /* Find gateway addresses from the link device, which is
808 * no longer accessible inside the container. Do this
809 * before creating network interfaces, since goto
810 * out_delete_net does not work before lxc_clone. */
811 if (lxc_find_gateway_addresses(handler)) {
812 ERROR("failed to find gateway addresses");
813 lxc_sync_fini(handler);
814 return -1;
815 }
816
817 /* that should be done before the clone because we will
818 * fill the netdev index and use them in the child
819 */
820 if (lxc_create_network(handler)) {
821 ERROR("failed to create the network");
822 lxc_sync_fini(handler);
823 return -1;
824 }
825 }
826
827 if (save_phys_nics(handler->conf)) {
828 ERROR("failed to save physical nic info");
829 goto out_abort;
830 }
831 } else {
832 INFO("Inheriting a net namespace");
833 }
834
835 if (handler->conf->inherit_ns_fd[LXC_NS_IPC] == -1) {
836 handler->clone_flags |= CLONE_NEWIPC;
837 } else {
838 INFO("Inheriting an IPC namespace");
839 }
840
841 if (handler->conf->inherit_ns_fd[LXC_NS_UTS] == -1) {
842 handler->clone_flags |= CLONE_NEWUTS;
843 } else {
844 INFO("Inheriting a UTS namespace");
845 }
846
847
848 if (!cgroup_init(handler)) {
849 ERROR("failed initializing cgroup support");
850 goto out_delete_net;
851 }
852
853 cgroups_connected = true;
854
855 if (!cgroup_create(handler)) {
856 ERROR("failed creating cgroups");
857 goto out_delete_net;
858 }
859
860 /*
861 * if the rootfs is not a blockdev, prevent the container from
862 * marking it readonly.
863 *
864 * if the container is unprivileged then skip rootfs pinning
865 */
866 if (lxc_list_empty(&handler->conf->id_map)) {
867 handler->pinfd = pin_rootfs(handler->conf->rootfs.path);
868 if (handler->pinfd == -1)
869 INFO("failed to pin the container's rootfs");
870 }
871
872 if (preserve_ns(saved_ns_fd, preserve_mask) < 0)
873 goto out_delete_net;
874 if (attach_ns(handler->conf->inherit_ns_fd) < 0)
875 goto out_delete_net;
876
877 if (am_unpriv() && (nveths = count_veths(&handler->conf->network))) {
878 if (pipe(netpipepair) < 0) {
879 SYSERROR("Error creating pipe");
880 goto out_delete_net;
881 }
882 /* store netpipe in the global var for do_start's use */
883 netpipe = netpipepair[0];
884 }
885
886 /* Create a process in a new set of namespaces */
887 handler->pid = lxc_clone(do_start, handler, handler->clone_flags);
888 if (handler->pid < 0) {
889 SYSERROR("failed to fork into a new namespace");
890 goto out_delete_net;
891 }
892
893 if (attach_ns(saved_ns_fd))
894 WARN("failed to restore saved namespaces");
895
896 lxc_sync_fini_child(handler);
897
898 if (lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE))
899 failed_before_rename = 1;
900
901 if (!cgroup_create_legacy(handler)) {
902 ERROR("failed to setup the legacy cgroups for %s", name);
903 goto out_delete_net;
904 }
905 if (!cgroup_setup_limits(handler, false)) {
906 ERROR("failed to setup the cgroup limits for '%s'", name);
907 goto out_delete_net;
908 }
909
910 if (!cgroup_enter(handler))
911 goto out_delete_net;
912
913 if (!cgroup_chown(handler))
914 goto out_delete_net;
915
916 if (failed_before_rename)
917 goto out_delete_net;
918
919 /* Create the network configuration */
920 if (handler->clone_flags & CLONE_NEWNET) {
921 if (lxc_assign_network(&handler->conf->network, handler->pid)) {
922 ERROR("failed to create the configured network");
923 goto out_delete_net;
924 }
925 }
926
927 if (netpipe != -1) {
928 struct lxc_list *iterator;
929 struct lxc_netdev *netdev;
930
931 close(netpipe);
932 lxc_list_for_each(iterator, &handler->conf->network) {
933 netdev = iterator->elem;
934 if (netdev->type != LXC_NET_VETH)
935 continue;
936 if (write(netpipepair[1], netdev->name, IFNAMSIZ) != IFNAMSIZ) {
937 ERROR("Error writing veth name to container");
938 goto out_delete_net;
939 }
940 }
941 close(netpipepair[1]);
942 }
943
944 /* map the container uids - the container became an invalid
945 * userid the moment it was cloned with CLONE_NEWUSER - this
946 * call doesn't change anything immediately, but allows the
947 * container to setuid(0) (0 being mapped to something else on
948 * the host) later to become a valid uid again */
949 if (lxc_map_ids(&handler->conf->id_map, handler->pid)) {
950 ERROR("failed to set up id mapping");
951 goto out_delete_net;
952 }
953
954 /* Tell the child to continue its initialization. we'll get
955 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
956 */
957 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE))
958 goto out_delete_net;
959
960 if (!cgroup_setup_limits(handler, true)) {
961 ERROR("failed to setup the devices cgroup for '%s'", name);
962 goto out_delete_net;
963 }
964
965 cgroup_disconnect();
966 cgroups_connected = false;
967
968 /* Tell the child to complete its initialization and wait for
969 * it to exec or return an error. (the child will never
970 * return LXC_SYNC_POST_CGROUP+1. It will either close the
971 * sync pipe, causing lxc_sync_barrier_child to return
972 * success, or return a different value, causing us to error
973 * out).
974 */
975 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CGROUP))
976 return -1;
977
978 if (detect_shared_rootfs())
979 umount2(handler->conf->rootfs.mount, MNT_DETACH);
980
981 if (handler->ops->post_start(handler, handler->data))
982 goto out_abort;
983
984 if (lxc_set_state(name, handler, RUNNING)) {
985 ERROR("failed to set state to %s",
986 lxc_state2str(RUNNING));
987 goto out_abort;
988 }
989
990 lxc_sync_fini(handler);
991
992 return 0;
993
994 out_delete_net:
995 if (cgroups_connected)
996 cgroup_disconnect();
997 if (handler->clone_flags & CLONE_NEWNET)
998 lxc_delete_network(handler);
999 out_abort:
1000 lxc_abort(name, handler);
1001 lxc_sync_fini(handler);
1002 if (handler->pinfd >= 0) {
1003 close(handler->pinfd);
1004 handler->pinfd = -1;
1005 }
1006
1007 return -1;
1008 }
1009
1010 int get_netns_fd(int pid)
1011 {
1012 char path[MAXPATHLEN];
1013 int ret, fd;
1014
1015 ret = snprintf(path, MAXPATHLEN, "/proc/%d/ns/net", pid);
1016 if (ret < 0 || ret >= MAXPATHLEN) {
1017 WARN("Failed to pin netns file for pid %d", pid);
1018 return -1;
1019 }
1020
1021 fd = open(path, O_RDONLY);
1022 if (fd < 0) {
1023 WARN("Failed to pin netns file %s for pid %d: %s",
1024 path, pid, strerror(errno));
1025 return -1;
1026 }
1027 return fd;
1028 }
1029
1030 int __lxc_start(const char *name, struct lxc_conf *conf,
1031 struct lxc_operations* ops, void *data, const char *lxcpath)
1032 {
1033 struct lxc_handler *handler;
1034 int err = -1;
1035 int status;
1036 int netnsfd = -1;
1037
1038 handler = lxc_init(name, conf, lxcpath);
1039 if (!handler) {
1040 ERROR("failed to initialize the container");
1041 return -1;
1042 }
1043 handler->ops = ops;
1044 handler->data = data;
1045
1046 if (must_drop_cap_sys_boot(handler->conf)) {
1047 #if HAVE_SYS_CAPABILITY_H
1048 DEBUG("Dropping cap_sys_boot");
1049 #else
1050 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
1051 #endif
1052 } else {
1053 DEBUG("Not dropping cap_sys_boot or watching utmp");
1054 handler->conf->need_utmp_watch = 0;
1055 }
1056
1057 err = lxc_spawn(handler);
1058 if (err) {
1059 ERROR("failed to spawn '%s'", name);
1060 goto out_fini_nonet;
1061 }
1062
1063 netnsfd = get_netns_fd(handler->pid);
1064
1065 err = lxc_poll(name, handler);
1066 if (err) {
1067 ERROR("mainloop exited with an error");
1068 if (netnsfd >= 0)
1069 close(netnsfd);
1070 goto out_abort;
1071 }
1072
1073 while (waitpid(handler->pid, &status, 0) < 0 && errno == EINTR)
1074 continue;
1075
1076 /*
1077 * If the child process exited but was not signaled,
1078 * it didn't call reboot. This should mean it was an
1079 * lxc-execute which simply exited. In any case, treat
1080 * it as a 'halt'
1081 */
1082 if (WIFSIGNALED(status)) {
1083 switch(WTERMSIG(status)) {
1084 case SIGINT: /* halt */
1085 DEBUG("Container halting");
1086 break;
1087 case SIGHUP: /* reboot */
1088 DEBUG("Container rebooting");
1089 handler->conf->reboot = 1;
1090 break;
1091 case SIGSYS: /* seccomp */
1092 DEBUG("Container violated its seccomp policy");
1093 break;
1094 default:
1095 DEBUG("unknown exit status for init: %d", WTERMSIG(status));
1096 break;
1097 }
1098 }
1099
1100 lxc_rename_phys_nics_on_shutdown(netnsfd, handler->conf);
1101 if (netnsfd >= 0)
1102 close(netnsfd);
1103
1104 if (handler->pinfd >= 0) {
1105 close(handler->pinfd);
1106 handler->pinfd = -1;
1107 }
1108
1109 err = lxc_error_set_and_log(handler->pid, status);
1110 out_fini:
1111 lxc_delete_network(handler);
1112
1113 out_fini_nonet:
1114 lxc_fini(name, handler);
1115 return err;
1116
1117 out_abort:
1118 lxc_abort(name, handler);
1119 goto out_fini;
1120 }
1121
1122 struct start_args {
1123 char *const *argv;
1124 };
1125
1126 static int start(struct lxc_handler *handler, void* data)
1127 {
1128 struct start_args *arg = data;
1129
1130 NOTICE("exec'ing '%s'", arg->argv[0]);
1131
1132 execvp(arg->argv[0], arg->argv);
1133 SYSERROR("failed to exec %s", arg->argv[0]);
1134 return 0;
1135 }
1136
1137 static int post_start(struct lxc_handler *handler, void* data)
1138 {
1139 struct start_args *arg = data;
1140
1141 NOTICE("'%s' started with pid '%d'", arg->argv[0], handler->pid);
1142 return 0;
1143 }
1144
1145 static struct lxc_operations start_ops = {
1146 .start = start,
1147 .post_start = post_start
1148 };
1149
1150 int lxc_start(const char *name, char *const argv[], struct lxc_conf *conf,
1151 const char *lxcpath)
1152 {
1153 struct start_args start_arg = {
1154 .argv = argv,
1155 };
1156
1157 if (lxc_check_inherited(conf, -1))
1158 return -1;
1159
1160 conf->need_utmp_watch = 1;
1161 return __lxc_start(name, conf, &start_ops, &start_arg, lxcpath);
1162 }