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