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