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