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