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