]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/start.c
c/r: re-open fds after clone()
[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->ttysock[0] = handler->ttysock[1] = -1;
379 handler->conf = conf;
380 handler->lxcpath = lxcpath;
381 handler->pinfd = -1;
382
383 lsm_init();
384
385 handler->name = strdup(name);
386 if (!handler->name) {
387 ERROR("failed to allocate memory");
388 goto out_free;
389 }
390
391 if (lxc_cmd_init(name, handler, lxcpath))
392 goto out_free_name;
393
394 if (lxc_read_seccomp_config(conf) != 0) {
395 ERROR("failed loading seccomp policy");
396 goto out_close_maincmd_fd;
397 }
398
399 /* Begin by setting the state to STARTING */
400 if (lxc_set_state(name, handler, STARTING)) {
401 ERROR("failed to set state '%s'", lxc_state2str(STARTING));
402 goto out_close_maincmd_fd;
403 }
404
405 /* Start of environment variable setup for hooks */
406 if (setenv("LXC_NAME", name, 1)) {
407 SYSERROR("failed to set environment variable for container name");
408 }
409 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
410 SYSERROR("failed to set environment variable for config path");
411 }
412 if (setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
413 SYSERROR("failed to set environment variable for rootfs mount");
414 }
415 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
416 SYSERROR("failed to set environment variable for rootfs mount");
417 }
418 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1)) {
419 SYSERROR("failed to set environment variable for console path");
420 }
421 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1)) {
422 SYSERROR("failed to set environment variable for console log");
423 }
424 /* End of environment variable setup for hooks */
425
426 if (run_lxc_hooks(name, "pre-start", conf, handler->lxcpath, NULL)) {
427 ERROR("failed to run pre-start hooks for container '%s'.", name);
428 goto out_aborting;
429 }
430
431 /* the signal fd has to be created before forking otherwise
432 * if the child process exits before we setup the signal fd,
433 * the event will be lost and the command will be stuck */
434 handler->sigfd = setup_signal_fd(&handler->oldmask);
435 if (handler->sigfd < 0) {
436 ERROR("failed to set sigchild fd handler");
437 goto out_delete_tty;
438 }
439
440 /* do this after setting up signals since it might unblock SIGWINCH */
441 if (lxc_console_create(conf)) {
442 ERROR("failed to create console");
443 goto out_restore_sigmask;
444 }
445
446 if (ttys_shift_ids(conf) < 0) {
447 ERROR("Failed to shift tty into container");
448 goto out_restore_sigmask;
449 }
450
451 INFO("'%s' is initialized", name);
452 return handler;
453
454 out_restore_sigmask:
455 sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
456 out_delete_tty:
457 lxc_delete_tty(&conf->tty_info);
458 out_aborting:
459 lxc_set_state(name, handler, ABORTING);
460 out_close_maincmd_fd:
461 close(conf->maincmd_fd);
462 conf->maincmd_fd = -1;
463 out_free_name:
464 free(handler->name);
465 handler->name = NULL;
466 out_free:
467 free(handler);
468 return NULL;
469 }
470
471 void lxc_fini(const char *name, struct lxc_handler *handler)
472 {
473 /* The STOPPING state is there for future cleanup code
474 * which can take awhile
475 */
476 lxc_set_state(name, handler, STOPPING);
477 lxc_set_state(name, handler, STOPPED);
478
479 if (run_lxc_hooks(name, "post-stop", handler->conf, handler->lxcpath, NULL))
480 ERROR("failed to run post-stop hooks for container '%s'.", name);
481
482 /* reset mask set by setup_signal_fd */
483 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
484 WARN("failed to restore sigprocmask");
485
486 lxc_console_delete(&handler->conf->console);
487 lxc_delete_tty(&handler->conf->tty_info);
488 close(handler->conf->maincmd_fd);
489 handler->conf->maincmd_fd = -1;
490 free(handler->name);
491 if (handler->ttysock[0] != -1) {
492 close(handler->ttysock[0]);
493 close(handler->ttysock[1]);
494 }
495 cgroup_destroy(handler);
496 free(handler);
497 }
498
499 void lxc_abort(const char *name, struct lxc_handler *handler)
500 {
501 int ret, status;
502
503 lxc_set_state(name, handler, ABORTING);
504 if (handler->pid > 0)
505 kill(handler->pid, SIGKILL);
506 while ((ret = waitpid(-1, &status, 0)) > 0) ;
507 }
508
509 #include <sys/reboot.h>
510 #include <linux/reboot.h>
511
512 /*
513 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
514 * in a child pid namespace if container reboot support exists.
515 * Otherwise, it will either succeed or return -EPERM.
516 */
517 static int container_reboot_supported(void *arg)
518 {
519 int *cmd = arg;
520 int ret;
521
522 ret = reboot(*cmd);
523 if (ret == -1 && errno == EINVAL)
524 return 1;
525 return 0;
526 }
527
528 static int must_drop_cap_sys_boot(struct lxc_conf *conf)
529 {
530 FILE *f;
531 int ret, cmd, v, flags;
532 long stack_size = 4096;
533 void *stack = alloca(stack_size);
534 int status;
535 pid_t pid;
536
537 f = fopen("/proc/sys/kernel/ctrl-alt-del", "r");
538 if (!f) {
539 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
540 return 1;
541 }
542
543 ret = fscanf(f, "%d", &v);
544 fclose(f);
545 if (ret != 1) {
546 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
547 return 1;
548 }
549 cmd = v ? LINUX_REBOOT_CMD_CAD_ON : LINUX_REBOOT_CMD_CAD_OFF;
550
551 flags = CLONE_NEWPID | SIGCHLD;
552 if (!lxc_list_empty(&conf->id_map))
553 flags |= CLONE_NEWUSER;
554
555 #ifdef __ia64__
556 pid = __clone2(container_reboot_supported, stack, stack_size, flags, &cmd);
557 #else
558 stack += stack_size;
559 pid = clone(container_reboot_supported, stack, flags, &cmd);
560 #endif
561 if (pid < 0) {
562 if (flags & CLONE_NEWUSER)
563 ERROR("failed to clone (%#x): %s (includes CLONE_NEWUSER)", flags, strerror(errno));
564 else
565 ERROR("failed to clone (%#x): %s", flags, strerror(errno));
566 return -1;
567 }
568 if (wait(&status) < 0) {
569 SYSERROR("unexpected wait error: %m");
570 return -1;
571 }
572
573 if (WEXITSTATUS(status) != 1)
574 return 1;
575
576 return 0;
577 }
578
579 /*
580 * netpipe is used in the unprivileged case to transfer the ifindexes
581 * from parent to child
582 */
583 static int netpipe = -1;
584
585 static inline int count_veths(struct lxc_list *network)
586 {
587 struct lxc_list *iterator;
588 struct lxc_netdev *netdev;
589 int count = 0;
590
591 lxc_list_for_each(iterator, network) {
592 netdev = iterator->elem;
593 if (netdev->type != LXC_NET_VETH)
594 continue;
595 count++;
596 }
597 return count;
598 }
599
600 static int read_unpriv_netifindex(struct lxc_list *network)
601 {
602 struct lxc_list *iterator;
603 struct lxc_netdev *netdev;
604
605 if (netpipe == -1)
606 return 0;
607 lxc_list_for_each(iterator, network) {
608 netdev = iterator->elem;
609 if (netdev->type != LXC_NET_VETH)
610 continue;
611 if (!(netdev->name = malloc(IFNAMSIZ))) {
612 ERROR("Out of memory");
613 close(netpipe);
614 return -1;
615 }
616 if (read(netpipe, netdev->name, IFNAMSIZ) != IFNAMSIZ) {
617 close(netpipe);
618 return -1;
619 }
620 }
621 close(netpipe);
622 return 0;
623 }
624
625 static int do_start(void *data)
626 {
627 struct lxc_list *iterator;
628 struct lxc_handler *handler = data;
629
630 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL)) {
631 SYSERROR("failed to set sigprocmask");
632 return -1;
633 }
634
635 /* This prctl must be before the synchro, so if the parent
636 * dies before we set the parent death signal, we will detect
637 * its death with the synchro right after, otherwise we have
638 * a window where the parent can exit before we set the pdeath
639 * signal leading to a unsupervized container.
640 */
641 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
642 SYSERROR("failed to set pdeath signal");
643 return -1;
644 }
645
646 lxc_sync_fini_parent(handler);
647
648 /* don't leak the pinfd to the container */
649 if (handler->pinfd >= 0) {
650 close(handler->pinfd);
651 }
652
653 /* Tell the parent task it can begin to configure the
654 * container and wait for it to finish
655 */
656 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE))
657 return -1;
658
659 if (read_unpriv_netifindex(&handler->conf->network) < 0)
660 goto out_warn_father;
661
662 /*
663 * if we are in a new user namespace, become root there to have
664 * privilege over our namespace
665 */
666 if (!lxc_list_empty(&handler->conf->id_map)) {
667 NOTICE("switching to gid/uid 0 in new user namespace");
668 if (setgid(0)) {
669 SYSERROR("setgid");
670 goto out_warn_father;
671 }
672 if (setuid(0)) {
673 SYSERROR("setuid");
674 goto out_warn_father;
675 }
676 if (setgroups(0, NULL)) {
677 SYSERROR("setgroups");
678 goto out_warn_father;
679 }
680 }
681
682 if (access(handler->lxcpath, X_OK)) {
683 print_top_failing_dir(handler->lxcpath);
684 goto out_warn_father;
685 }
686
687 #if HAVE_SYS_CAPABILITY_H
688 if (handler->conf->need_utmp_watch) {
689 if (prctl(PR_CAPBSET_DROP, CAP_SYS_BOOT, 0, 0, 0)) {
690 SYSERROR("failed to remove CAP_SYS_BOOT capability");
691 goto out_warn_father;
692 }
693 DEBUG("Dropped cap_sys_boot");
694 }
695 #endif
696
697 /* Setup the container, ip, names, utsname, ... */
698 if (lxc_setup(handler)) {
699 ERROR("failed to setup the container");
700 goto out_warn_father;
701 }
702
703 /* ask father to setup cgroups and wait for him to finish */
704 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP))
705 return -1;
706
707 /* Set the label to change to when we exec(2) the container's init */
708 if (lsm_process_label_set(NULL, handler->conf, 1, 1) < 0)
709 goto out_warn_father;
710
711 /* Some init's such as busybox will set sane tty settings on stdin,
712 * stdout, stderr which it thinks is the console. We already set them
713 * the way we wanted on the real terminal, and we want init to do its
714 * setup on its console ie. the pty allocated in lxc_console_create()
715 * so make sure that that pty is stdin,stdout,stderr.
716 */
717 if (lxc_console_set_stdfds(handler) < 0)
718 goto out_warn_father;
719
720 /* If we mounted a temporary proc, then unmount it now */
721 tmp_proc_unmount(handler->conf);
722
723 if (lxc_seccomp_load(handler->conf) != 0)
724 goto out_warn_father;
725
726 if (run_lxc_hooks(handler->name, "start", handler->conf, handler->lxcpath, NULL)) {
727 ERROR("failed to run start hooks for container '%s'.", handler->name);
728 goto out_warn_father;
729 }
730
731 /* The clearenv() and putenv() calls have been moved here
732 * to allow us to use environment variables passed to the various
733 * hooks, such as the start hook above. Not all of the
734 * variables like CONFIG_PATH or ROOTFS are valid in this
735 * context but others are. */
736 if (clearenv()) {
737 SYSERROR("failed to clear environment");
738 /* don't error out though */
739 }
740
741 lxc_list_for_each(iterator, &handler->conf->environment) {
742 if (putenv((char *)iterator->elem)) {
743 SYSERROR("failed to set environment variable '%s'", (char *)iterator->elem);
744 goto out_warn_father;
745 }
746 }
747
748 if (putenv("container=lxc")) {
749 SYSERROR("failed to set environment variable 'container=lxc'");
750 goto out_warn_father;
751 }
752
753 if (handler->conf->pty_names) {
754 if (putenv(handler->conf->pty_names)) {
755 SYSERROR("failed to set environment variable for container ptys");
756 goto out_warn_father;
757 }
758 }
759
760 close(handler->sigfd);
761
762 if (handler->backgrounded) {
763 close(0);
764 close(1);
765 close(2);
766 open("/dev/zero", O_RDONLY);
767 open("/dev/null", O_RDWR);
768 open("/dev/null", O_RDWR);
769 }
770
771 /* after this call, we are in error because this
772 * ops should not return as it execs */
773 handler->ops->start(handler, handler->data);
774
775 out_warn_father:
776 /* we want the parent to know something went wrong, so any
777 * value other than what it expects is ok. */
778 lxc_sync_wake_parent(handler, LXC_SYNC_POST_CONFIGURE);
779 return -1;
780 }
781
782 static int save_phys_nics(struct lxc_conf *conf)
783 {
784 struct lxc_list *iterator;
785
786 lxc_list_for_each(iterator, &conf->network) {
787 struct lxc_netdev *netdev = iterator->elem;
788
789 if (netdev->type != LXC_NET_PHYS)
790 continue;
791 conf->saved_nics = realloc(conf->saved_nics,
792 (conf->num_savednics+1)*sizeof(struct saved_nic));
793 if (!conf->saved_nics) {
794 SYSERROR("failed to allocate memory");
795 return -1;
796 }
797 conf->saved_nics[conf->num_savednics].ifindex = netdev->ifindex;
798 conf->saved_nics[conf->num_savednics].orig_name = strdup(netdev->link);
799 if (!conf->saved_nics[conf->num_savednics].orig_name) {
800 SYSERROR("failed to allocate memory");
801 return -1;
802 }
803 INFO("stored saved_nic #%d idx %d name %s", conf->num_savednics,
804 conf->saved_nics[conf->num_savednics].ifindex,
805 conf->saved_nics[conf->num_savednics].orig_name);
806 conf->num_savednics++;
807 }
808
809 return 0;
810 }
811
812 static int recv_fd(int sock, int *fd)
813 {
814 if (lxc_abstract_unix_recv_fd(sock, fd, NULL, 0) < 0) {
815 SYSERROR("Error receiving tty fd from child");
816 return -1;
817 }
818 if (*fd == -1)
819 return -1;
820 return 0;
821 }
822
823 static int recv_ttys_from_child(struct lxc_handler *handler)
824 {
825 struct lxc_conf *conf = handler->conf;
826 int i, sock = handler->ttysock[1];
827 struct lxc_tty_info *tty_info = &conf->tty_info;
828
829 if (!conf->tty)
830 return 0;
831
832 tty_info->pty_info = malloc(sizeof(*tty_info->pty_info)*conf->tty);
833 if (!tty_info->pty_info) {
834 SYSERROR("failed to allocate pty_info");
835 return -1;
836 }
837
838 for (i = 0; i < conf->tty; i++) {
839 struct lxc_pty_info *pty_info = &tty_info->pty_info[i];
840 pty_info->busy = 0;
841 if (recv_fd(sock, &pty_info->slave) < 0 ||
842 recv_fd(sock, &pty_info->master) < 0) {
843 ERROR("Error receiving tty info from child");
844 return -1;
845 }
846 }
847 tty_info->nbtty = conf->tty;
848
849 return 0;
850 }
851
852 void resolve_clone_flags(struct lxc_handler *handler)
853 {
854 handler->clone_flags = CLONE_NEWPID | CLONE_NEWNS;
855
856 if (!lxc_list_empty(&handler->conf->id_map)) {
857 INFO("Cloning a new user namespace");
858 handler->clone_flags |= CLONE_NEWUSER;
859 }
860
861 if (handler->conf->inherit_ns_fd[LXC_NS_NET] == -1) {
862 if (!lxc_requests_empty_network(handler))
863 handler->clone_flags |= CLONE_NEWNET;
864 } else {
865 INFO("Inheriting a net namespace");
866 }
867
868 if (handler->conf->inherit_ns_fd[LXC_NS_IPC] == -1) {
869 handler->clone_flags |= CLONE_NEWIPC;
870 } else {
871 INFO("Inheriting an IPC namespace");
872 }
873
874 if (handler->conf->inherit_ns_fd[LXC_NS_UTS] == -1) {
875 handler->clone_flags |= CLONE_NEWUTS;
876 } else {
877 INFO("Inheriting a UTS namespace");
878 }
879 }
880
881 static int lxc_spawn(struct lxc_handler *handler)
882 {
883 int failed_before_rename = 0;
884 const char *name = handler->name;
885 bool cgroups_connected = false;
886 int saved_ns_fd[LXC_NS_MAX];
887 int preserve_mask = 0, i;
888 int netpipepair[2], nveths;
889
890 netpipe = -1;
891
892 for (i = 0; i < LXC_NS_MAX; i++)
893 if (handler->conf->inherit_ns_fd[i] != -1)
894 preserve_mask |= ns_info[i].clone_flag;
895
896 if (lxc_sync_init(handler))
897 return -1;
898
899 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, handler->ttysock) < 0) {
900 lxc_sync_fini(handler);
901 return -1;
902 }
903
904 resolve_clone_flags(handler);
905
906 if (handler->clone_flags & CLONE_NEWNET) {
907 if (!lxc_list_empty(&handler->conf->network)) {
908
909 /* Find gateway addresses from the link device, which is
910 * no longer accessible inside the container. Do this
911 * before creating network interfaces, since goto
912 * out_delete_net does not work before lxc_clone. */
913 if (lxc_find_gateway_addresses(handler)) {
914 ERROR("failed to find gateway addresses");
915 lxc_sync_fini(handler);
916 return -1;
917 }
918
919 /* that should be done before the clone because we will
920 * fill the netdev index and use them in the child
921 */
922 if (lxc_create_network(handler)) {
923 ERROR("failed to create the network");
924 lxc_sync_fini(handler);
925 return -1;
926 }
927 }
928
929 if (save_phys_nics(handler->conf)) {
930 ERROR("failed to save physical nic info");
931 goto out_abort;
932 }
933 }
934
935 if (!cgroup_init(handler)) {
936 ERROR("failed initializing cgroup support");
937 goto out_delete_net;
938 }
939
940 cgroups_connected = true;
941
942 if (!cgroup_create(handler)) {
943 ERROR("failed creating cgroups");
944 goto out_delete_net;
945 }
946
947 /*
948 * if the rootfs is not a blockdev, prevent the container from
949 * marking it readonly.
950 *
951 * if the container is unprivileged then skip rootfs pinning
952 */
953 if (lxc_list_empty(&handler->conf->id_map)) {
954 handler->pinfd = pin_rootfs(handler->conf->rootfs.path);
955 if (handler->pinfd == -1)
956 INFO("failed to pin the container's rootfs");
957 }
958
959 if (preserve_ns(saved_ns_fd, preserve_mask) < 0)
960 goto out_delete_net;
961 if (attach_ns(handler->conf->inherit_ns_fd) < 0)
962 goto out_delete_net;
963
964 if (am_unpriv() && (nveths = count_veths(&handler->conf->network))) {
965 if (pipe(netpipepair) < 0) {
966 SYSERROR("Error creating pipe");
967 goto out_delete_net;
968 }
969 /* store netpipe in the global var for do_start's use */
970 netpipe = netpipepair[0];
971 }
972
973 /* Create a process in a new set of namespaces */
974 handler->pid = lxc_clone(do_start, handler, handler->clone_flags);
975 if (handler->pid < 0) {
976 SYSERROR("failed to fork into a new namespace");
977 goto out_delete_net;
978 }
979
980 if (attach_ns(saved_ns_fd))
981 WARN("failed to restore saved namespaces");
982
983 lxc_sync_fini_child(handler);
984
985 if (lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE))
986 failed_before_rename = 1;
987
988 if (!cgroup_create_legacy(handler)) {
989 ERROR("failed to setup the legacy cgroups for %s", name);
990 goto out_delete_net;
991 }
992 if (!cgroup_setup_limits(handler, false)) {
993 ERROR("failed to setup the cgroup limits for '%s'", name);
994 goto out_delete_net;
995 }
996
997 if (!cgroup_enter(handler))
998 goto out_delete_net;
999
1000 if (!cgroup_chown(handler))
1001 goto out_delete_net;
1002
1003 if (failed_before_rename)
1004 goto out_delete_net;
1005
1006 /* Create the network configuration */
1007 if (handler->clone_flags & CLONE_NEWNET) {
1008 if (lxc_assign_network(&handler->conf->network, handler->pid)) {
1009 ERROR("failed to create the configured network");
1010 goto out_delete_net;
1011 }
1012 }
1013
1014 if (netpipe != -1) {
1015 struct lxc_list *iterator;
1016 struct lxc_netdev *netdev;
1017
1018 close(netpipe);
1019 lxc_list_for_each(iterator, &handler->conf->network) {
1020 netdev = iterator->elem;
1021 if (netdev->type != LXC_NET_VETH)
1022 continue;
1023 if (write(netpipepair[1], netdev->name, IFNAMSIZ) != IFNAMSIZ) {
1024 ERROR("Error writing veth name to container");
1025 goto out_delete_net;
1026 }
1027 }
1028 close(netpipepair[1]);
1029 }
1030
1031 /* map the container uids - the container became an invalid
1032 * userid the moment it was cloned with CLONE_NEWUSER - this
1033 * call doesn't change anything immediately, but allows the
1034 * container to setuid(0) (0 being mapped to something else on
1035 * the host) later to become a valid uid again */
1036 if (lxc_map_ids(&handler->conf->id_map, handler->pid)) {
1037 ERROR("failed to set up id mapping");
1038 goto out_delete_net;
1039 }
1040
1041 /* Tell the child to continue its initialization. we'll get
1042 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
1043 */
1044 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE))
1045 goto out_delete_net;
1046
1047 if (!cgroup_setup_limits(handler, true)) {
1048 ERROR("failed to setup the devices cgroup for '%s'", name);
1049 goto out_delete_net;
1050 }
1051
1052 cgroup_disconnect();
1053 cgroups_connected = false;
1054
1055 /* read tty fds allocated by child */
1056 if (recv_ttys_from_child(handler) < 0) {
1057 ERROR("failed to receive tty info from child");
1058 goto out_delete_net;
1059 }
1060
1061 /* Tell the child to complete its initialization and wait for
1062 * it to exec or return an error. (the child will never
1063 * return LXC_SYNC_POST_CGROUP+1. It will either close the
1064 * sync pipe, causing lxc_sync_barrier_child to return
1065 * success, or return a different value, causing us to error
1066 * out).
1067 */
1068 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CGROUP))
1069 return -1;
1070
1071 if (detect_shared_rootfs())
1072 umount2(handler->conf->rootfs.mount, MNT_DETACH);
1073
1074 if (handler->ops->post_start(handler, handler->data))
1075 goto out_abort;
1076
1077 if (lxc_set_state(name, handler, RUNNING)) {
1078 ERROR("failed to set state to %s",
1079 lxc_state2str(RUNNING));
1080 goto out_abort;
1081 }
1082
1083 lxc_sync_fini(handler);
1084
1085 return 0;
1086
1087 out_delete_net:
1088 if (cgroups_connected)
1089 cgroup_disconnect();
1090 if (handler->clone_flags & CLONE_NEWNET)
1091 lxc_delete_network(handler);
1092 out_abort:
1093 lxc_abort(name, handler);
1094 lxc_sync_fini(handler);
1095 if (handler->pinfd >= 0) {
1096 close(handler->pinfd);
1097 handler->pinfd = -1;
1098 }
1099
1100 return -1;
1101 }
1102
1103 int get_netns_fd(int pid)
1104 {
1105 char path[MAXPATHLEN];
1106 int ret, fd;
1107
1108 ret = snprintf(path, MAXPATHLEN, "/proc/%d/ns/net", pid);
1109 if (ret < 0 || ret >= MAXPATHLEN) {
1110 WARN("Failed to pin netns file for pid %d", pid);
1111 return -1;
1112 }
1113
1114 fd = open(path, O_RDONLY);
1115 if (fd < 0) {
1116 WARN("Failed to pin netns file %s for pid %d: %s",
1117 path, pid, strerror(errno));
1118 return -1;
1119 }
1120 return fd;
1121 }
1122
1123 int __lxc_start(const char *name, struct lxc_conf *conf,
1124 struct lxc_operations* ops, void *data, const char *lxcpath,
1125 bool backgrounded)
1126 {
1127 struct lxc_handler *handler;
1128 int err = -1;
1129 int status;
1130 int netnsfd = -1;
1131
1132 handler = lxc_init(name, conf, lxcpath);
1133 if (!handler) {
1134 ERROR("failed to initialize the container");
1135 return -1;
1136 }
1137 handler->ops = ops;
1138 handler->data = data;
1139 handler->backgrounded = backgrounded;
1140
1141 if (must_drop_cap_sys_boot(handler->conf)) {
1142 #if HAVE_SYS_CAPABILITY_H
1143 DEBUG("Dropping cap_sys_boot");
1144 #else
1145 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
1146 #endif
1147 } else {
1148 DEBUG("Not dropping cap_sys_boot or watching utmp");
1149 handler->conf->need_utmp_watch = 0;
1150 }
1151
1152 if (!attach_block_device(handler->conf)) {
1153 ERROR("Failure attaching block device");
1154 goto out_fini_nonet;
1155 }
1156
1157 if (geteuid() == 0 && !lxc_list_empty(&conf->id_map)) {
1158 /* if the backing store is a device, mount it here and now */
1159 if (rootfs_is_blockdev(conf)) {
1160 if (unshare(CLONE_NEWNS) < 0) {
1161 ERROR("Error unsharing mounts");
1162 goto out_fini_nonet;
1163 }
1164 remount_all_slave();
1165 if (do_rootfs_setup(conf, name, lxcpath) < 0) {
1166 ERROR("Error setting up rootfs mount as root before spawn");
1167 goto out_fini_nonet;
1168 }
1169 INFO("Set up container rootfs as host root");
1170 }
1171 }
1172
1173 err = lxc_spawn(handler);
1174 if (err) {
1175 ERROR("failed to spawn '%s'", name);
1176 goto out_detach_blockdev;
1177 }
1178
1179 netnsfd = get_netns_fd(handler->pid);
1180
1181 err = lxc_poll(name, handler);
1182 if (err) {
1183 ERROR("mainloop exited with an error");
1184 if (netnsfd >= 0)
1185 close(netnsfd);
1186 goto out_abort;
1187 }
1188
1189 while (waitpid(handler->pid, &status, 0) < 0 && errno == EINTR)
1190 continue;
1191
1192 /*
1193 * If the child process exited but was not signaled,
1194 * it didn't call reboot. This should mean it was an
1195 * lxc-execute which simply exited. In any case, treat
1196 * it as a 'halt'
1197 */
1198 if (WIFSIGNALED(status)) {
1199 switch(WTERMSIG(status)) {
1200 case SIGINT: /* halt */
1201 DEBUG("Container halting");
1202 break;
1203 case SIGHUP: /* reboot */
1204 DEBUG("Container rebooting");
1205 handler->conf->reboot = 1;
1206 break;
1207 case SIGSYS: /* seccomp */
1208 DEBUG("Container violated its seccomp policy");
1209 break;
1210 default:
1211 DEBUG("unknown exit status for init: %d", WTERMSIG(status));
1212 break;
1213 }
1214 }
1215
1216 lxc_rename_phys_nics_on_shutdown(netnsfd, handler->conf);
1217 if (netnsfd >= 0)
1218 close(netnsfd);
1219
1220 if (handler->pinfd >= 0) {
1221 close(handler->pinfd);
1222 handler->pinfd = -1;
1223 }
1224
1225 lxc_monitor_send_exit_code(name, status, handler->lxcpath);
1226 err = lxc_error_set_and_log(handler->pid, status);
1227 out_fini:
1228 lxc_delete_network(handler);
1229
1230 out_detach_blockdev:
1231 detach_block_device(handler->conf);
1232
1233 out_fini_nonet:
1234 lxc_fini(name, handler);
1235 return err;
1236
1237 out_abort:
1238 lxc_abort(name, handler);
1239 goto out_fini;
1240 }
1241
1242 struct start_args {
1243 char *const *argv;
1244 };
1245
1246 static int start(struct lxc_handler *handler, void* data)
1247 {
1248 struct start_args *arg = data;
1249
1250 NOTICE("exec'ing '%s'", arg->argv[0]);
1251
1252 execvp(arg->argv[0], arg->argv);
1253 SYSERROR("failed to exec %s", arg->argv[0]);
1254 return 0;
1255 }
1256
1257 static int post_start(struct lxc_handler *handler, void* data)
1258 {
1259 struct start_args *arg = data;
1260
1261 NOTICE("'%s' started with pid '%d'", arg->argv[0], handler->pid);
1262 return 0;
1263 }
1264
1265 static struct lxc_operations start_ops = {
1266 .start = start,
1267 .post_start = post_start
1268 };
1269
1270 int lxc_start(const char *name, char *const argv[], struct lxc_conf *conf,
1271 const char *lxcpath, bool backgrounded)
1272 {
1273 struct start_args start_arg = {
1274 .argv = argv,
1275 };
1276
1277 conf->need_utmp_watch = 1;
1278 return __lxc_start(name, conf, &start_ops, &start_arg, lxcpath, backgrounded);
1279 }