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