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