]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/start.c
start: generalize lxc_check_inherited()
[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 #define _GNU_SOURCE
25 #include "config.h"
26
27 #include <alloca.h>
28 #include <dirent.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <grp.h>
32 #include <poll.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <sys/file.h>
39 #include <sys/mount.h>
40 #include <sys/param.h>
41 #include <sys/prctl.h>
42 #include <sys/socket.h>
43 #include <sys/stat.h>
44 #include <sys/syscall.h>
45 #include <sys/types.h>
46 #include <sys/un.h>
47 #include <sys/wait.h>
48
49 #if HAVE_LIBCAP
50 #include <sys/capability.h>
51 #endif
52
53 #ifndef HAVE_DECL_PR_CAPBSET_DROP
54 #define PR_CAPBSET_DROP 24
55 #endif
56
57 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
58 #define PR_SET_NO_NEW_PRIVS 38
59 #endif
60
61 #ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
62 #define PR_GET_NO_NEW_PRIVS 39
63 #endif
64
65 #include "af_unix.h"
66 #include "bdev.h"
67 #include "caps.h"
68 #include "cgroup.h"
69 #include "commands.h"
70 #include "conf.h"
71 #include "console.h"
72 #include "error.h"
73 #include "log.h"
74 #include "lxccontainer.h"
75 #include "lxclock.h"
76 #include "lxcseccomp.h"
77 #include "lxcutmp.h"
78 #include "mainloop.h"
79 #include "monitor.h"
80 #include "namespace.h"
81 #include "start.h"
82 #include "storage_utils.h"
83 #include "sync.h"
84 #include "utils.h"
85 #include "lsm/lsm.h"
86
87 lxc_log_define(lxc_start, lxc);
88
89 extern void mod_all_rdeps(struct lxc_container *c, bool inc);
90 static bool do_destroy_container(struct lxc_conf *conf);
91 static int lxc_rmdir_onedev_wrapper(void *data);
92 static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
93 const char *name);
94
95 static void print_top_failing_dir(const char *path)
96 {
97 size_t len = strlen(path);
98 char *copy = alloca(len + 1), *p, *e, saved;
99 strcpy(copy, path);
100
101 p = copy;
102 e = copy + len;
103 while (p < e) {
104 while (p < e && *p == '/')
105 p++;
106 while (p < e && *p != '/')
107 p++;
108 saved = *p;
109 *p = '\0';
110 if (access(copy, X_OK)) {
111 SYSERROR("Could not access %s. Please grant it x "
112 "access, or add an ACL for the container "
113 "root.", copy);
114 return;
115 }
116 *p = saved;
117 }
118 }
119
120 static void close_ns(int ns_fd[LXC_NS_MAX])
121 {
122 int i;
123
124 for (i = 0; i < LXC_NS_MAX; i++) {
125 if (ns_fd[i] > -1) {
126 close(ns_fd[i]);
127 ns_fd[i] = -1;
128 }
129 }
130 }
131
132 /* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
133 * in clone_flags.
134 * Return true on success, false on failure.
135 */
136 static bool preserve_ns(int ns_fd[LXC_NS_MAX], int clone_flags, pid_t pid)
137 {
138 int i, ret;
139
140 for (i = 0; i < LXC_NS_MAX; i++)
141 ns_fd[i] = -1;
142
143 ret = lxc_preserve_ns(pid, "");
144 if (ret < 0) {
145 SYSERROR("Kernel does not support attaching to namespaces.");
146 return false;
147 } else {
148 close(ret);
149 }
150
151 for (i = 0; i < LXC_NS_MAX; i++) {
152 if ((clone_flags & ns_info[i].clone_flag) == 0)
153 continue;
154 ns_fd[i] = lxc_preserve_ns(pid, ns_info[i].proc_name);
155 if (ns_fd[i] < 0)
156 goto error;
157 }
158
159 return true;
160
161 error:
162 if (errno == ENOENT)
163 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info[i].proc_name);
164 else
165 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info[i].proc_name, strerror(errno));
166 close_ns(ns_fd);
167 return false;
168 }
169
170 static int attach_ns(const int ns_fd[LXC_NS_MAX]) {
171 int i;
172
173 for (i = 0; i < LXC_NS_MAX; i++) {
174 if (ns_fd[i] < 0)
175 continue;
176
177 if (setns(ns_fd[i], 0) != 0)
178 goto error;
179 }
180 return 0;
181
182 error:
183 SYSERROR("Failed to attach %s namespace.", ns_info[i].proc_name);
184 return -1;
185 }
186
187 static int match_fd(int fd)
188 {
189 return (fd == 0 || fd == 1 || fd == 2);
190 }
191
192 int lxc_check_inherited(struct lxc_conf *conf, bool closeall,
193 int *fds_to_ignore, size_t len_fds)
194 {
195 struct dirent *direntp;
196 int fd, fddir;
197 size_t i;
198 DIR *dir;
199
200 if (conf && conf->close_all_fds)
201 closeall = true;
202
203 restart:
204 dir = opendir("/proc/self/fd");
205 if (!dir) {
206 WARN("Failed to open directory: %s.", strerror(errno));
207 return -1;
208 }
209
210 fddir = dirfd(dir);
211
212 while ((direntp = readdir(dir))) {
213 if (!direntp)
214 break;
215
216 if (!strcmp(direntp->d_name, "."))
217 continue;
218
219 if (!strcmp(direntp->d_name, ".."))
220 continue;
221
222 if (lxc_safe_int(direntp->d_name, &fd) < 0) {
223 INFO("Could not parse file descriptor for: %s", direntp->d_name);
224 continue;
225 }
226
227 for (i = 0; i < len_fds; i++)
228 if (fds_to_ignore[i] == fd)
229 break;
230
231 if (fd == fddir || fd == lxc_log_fd ||
232 (i < len_fds && fd == fds_to_ignore[i]))
233 continue;
234
235 if (current_config && fd == current_config->logfd)
236 continue;
237
238 if (match_fd(fd))
239 continue;
240
241 if (closeall) {
242 close(fd);
243 closedir(dir);
244 INFO("Closed inherited fd: %d.", fd);
245 goto restart;
246 }
247 WARN("Inherited fd: %d.", fd);
248 }
249
250 /* Only enable syslog at this point to avoid the above logging function
251 * to open a new fd and make the check_inherited function enter an
252 * infinite loop.
253 */
254 lxc_log_enable_syslog();
255
256 closedir(dir); /* cannot fail */
257 return 0;
258 }
259
260 static int setup_signal_fd(sigset_t *oldmask)
261 {
262 sigset_t mask;
263 int fd;
264
265 /* Block everything except serious error signals. */
266 if (sigfillset(&mask) ||
267 sigdelset(&mask, SIGILL) ||
268 sigdelset(&mask, SIGSEGV) ||
269 sigdelset(&mask, SIGBUS) ||
270 sigdelset(&mask, SIGWINCH) ||
271 sigprocmask(SIG_BLOCK, &mask, oldmask)) {
272 SYSERROR("Failed to set signal mask.");
273 return -1;
274 }
275
276 fd = signalfd(-1, &mask, 0);
277 if (fd < 0) {
278 SYSERROR("Failed to create signal file descriptor.");
279 return -1;
280 }
281
282 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
283 SYSERROR("Failed to set FD_CLOEXEC on the signal file descriptor: %d.", fd);
284 close(fd);
285 return -1;
286 }
287
288 DEBUG("Set SIGCHLD handler with file descriptor: %d.", fd);
289
290 return fd;
291 }
292
293 static int signal_handler(int fd, uint32_t events, void *data,
294 struct lxc_epoll_descr *descr)
295 {
296 struct signalfd_siginfo siginfo;
297 siginfo_t info;
298 int ret;
299 pid_t *pid = data;
300 bool init_died = false;
301
302 ret = read(fd, &siginfo, sizeof(siginfo));
303 if (ret < 0) {
304 ERROR("Failed to read signal info from signal file descriptor: %d.", fd);
305 return -1;
306 }
307
308 if (ret != sizeof(siginfo)) {
309 ERROR("Unexpected size for siginfo struct.");
310 return -1;
311 }
312
313 /* Check whether init is running. */
314 info.si_pid = 0;
315 ret = waitid(P_PID, *pid, &info, WEXITED | WNOWAIT | WNOHANG);
316 if (ret == 0 && info.si_pid == *pid)
317 init_died = true;
318
319 if (siginfo.ssi_signo != SIGCHLD) {
320 kill(*pid, siginfo.ssi_signo);
321 INFO("Forwarded signal %d to pid %d.", siginfo.ssi_signo, *pid);
322 return init_died ? 1 : 0;
323 }
324
325 if (siginfo.ssi_code == CLD_STOPPED) {
326 INFO("Container init process was stopped.");
327 return init_died ? 1 : 0;
328 } else if (siginfo.ssi_code == CLD_CONTINUED) {
329 INFO("Container init process was continued.");
330 return init_died ? 1 : 0;
331 }
332
333 /* More robustness, protect ourself from a SIGCHLD sent
334 * by a process different from the container init.
335 */
336 if (siginfo.ssi_pid != *pid) {
337 NOTICE("Received SIGCHLD from pid %d instead of container init %d.", siginfo.ssi_pid, *pid);
338 return init_died ? 1 : 0;
339 }
340
341 DEBUG("Container init process %d exited.", *pid);
342 return 1;
343 }
344
345 int lxc_set_state(const char *name, struct lxc_handler *handler,
346 lxc_state_t state)
347 {
348 ssize_t ret;
349 struct lxc_list *cur, *next;
350 struct state_client *client;
351 struct lxc_msg msg = {.type = lxc_msg_state, .value = state};
352
353 process_lock();
354 /* Only set state under process lock held so that we don't cause
355 * lxc_cmd_state_server() to miss a state.
356 */
357 handler->state = state;
358 TRACE("set container state to %s", lxc_state2str(state));
359
360 if (lxc_list_empty(&handler->state_clients)) {
361 TRACE("no state clients registered");
362 process_unlock();
363 lxc_monitor_send_state(name, state, handler->lxcpath);
364 return 0;
365 }
366
367 strncpy(msg.name, name, sizeof(msg.name));
368 msg.name[sizeof(msg.name) - 1] = 0;
369
370 lxc_list_for_each_safe(cur, &handler->state_clients, next) {
371 client = cur->elem;
372
373 if (!client->states[state]) {
374 TRACE("state %s not registered for state client %d",
375 lxc_state2str(state), client->clientfd);
376 continue;
377 }
378
379 TRACE("sending state %s to state client %d",
380 lxc_state2str(state), client->clientfd);
381
382 again:
383 ret = send(client->clientfd, &msg, sizeof(msg), 0);
384 if (ret < 0) {
385 if (errno == EINTR)
386 goto again;
387
388 ERROR("failed to send message to client");
389 }
390
391 /* kick client from list */
392 close(client->clientfd);
393 lxc_list_del(cur);
394 free(cur->elem);
395 free(cur);
396 }
397 process_unlock();
398
399 /* This function will try to connect to the legacy lxc-monitord state
400 * server and only exists for backwards compatibility.
401 */
402 lxc_monitor_send_state(name, state, handler->lxcpath);
403
404 return 0;
405 }
406
407 int lxc_poll(const char *name, struct lxc_handler *handler)
408 {
409 int sigfd = handler->sigfd;
410 int pid = handler->pid;
411 struct lxc_epoll_descr descr;
412
413 if (lxc_mainloop_open(&descr)) {
414 ERROR("Failed to create LXC mainloop.");
415 goto out_sigfd;
416 }
417
418 if (lxc_mainloop_add_handler(&descr, sigfd, signal_handler, &pid)) {
419 ERROR("Failed to add signal handler with file descriptor %d to LXC mainloop.", sigfd);
420 goto out_mainloop_open;
421 }
422
423 if (lxc_console_mainloop_add(&descr, handler->conf)) {
424 ERROR("Failed to add console handler to LXC mainloop.");
425 goto out_mainloop_open;
426 }
427
428 if (lxc_cmd_mainloop_add(name, &descr, handler)) {
429 ERROR("Failed to add command handler to LXC mainloop.");
430 goto out_mainloop_open;
431 }
432
433 if (handler->conf->need_utmp_watch) {
434 #if HAVE_LIBCAP
435 if (lxc_utmp_mainloop_add(&descr, handler)) {
436 ERROR("Failed to add utmp handler to LXC mainloop.");
437 goto out_mainloop_open;
438 }
439 #else
440 DEBUG("Not starting utmp handler as CAP_SYS_BOOT cannot be dropped without capabilities support.");
441 #endif
442 }
443 TRACE("lxc mainloop is ready");
444
445 return lxc_mainloop(&descr, -1);
446
447 out_mainloop_open:
448 lxc_mainloop_close(&descr);
449
450 out_sigfd:
451 close(sigfd);
452
453 return -1;
454 }
455
456 void lxc_free_handler(struct lxc_handler *handler)
457 {
458 if (handler->conf && handler->conf->maincmd_fd)
459 close(handler->conf->maincmd_fd);
460
461 if (handler->name)
462 free(handler->name);
463
464 handler->conf = NULL;
465 free(handler);
466 }
467
468 struct lxc_handler *lxc_init_handler(const char *name, struct lxc_conf *conf,
469 const char *lxcpath)
470 {
471 int i;
472 struct lxc_handler *handler;
473
474 handler = malloc(sizeof(*handler));
475 if (!handler) {
476 ERROR("failed to allocate memory");
477 return NULL;
478 }
479
480 memset(handler, 0, sizeof(*handler));
481
482 handler->ttysock[0] = handler->ttysock[1] = -1;
483 handler->conf = conf;
484 handler->lxcpath = lxcpath;
485 handler->pinfd = -1;
486 lxc_list_init(&handler->state_clients);
487
488 for (i = 0; i < LXC_NS_MAX; i++)
489 handler->nsfd[i] = -1;
490
491 handler->name = strdup(name);
492 if (!handler->name) {
493 ERROR("failed to allocate memory");
494 goto on_error;
495 }
496
497 if (lxc_cmd_init(name, handler, lxcpath)) {
498 ERROR("failed to set up command socket");
499 goto on_error;
500 }
501
502 TRACE("unix domain socket %d for command server is ready",
503 handler->conf->maincmd_fd);
504
505 return handler;
506
507 on_error:
508 lxc_free_handler(handler);
509
510 return NULL;
511 }
512
513 int lxc_init(const char *name, struct lxc_handler *handler)
514 {
515 struct lxc_conf *conf = handler->conf;
516
517 lsm_init();
518 TRACE("initialized LSM");
519
520 if (lxc_read_seccomp_config(conf) != 0) {
521 ERROR("Failed loading seccomp policy.");
522 goto out_close_maincmd_fd;
523 }
524 TRACE("read seccomp policy");
525
526 /* Begin by setting the state to STARTING. */
527 if (lxc_set_state(name, handler, STARTING)) {
528 ERROR("Failed to set state for container \"%s\" to \"%s\".", name, lxc_state2str(STARTING));
529 goto out_close_maincmd_fd;
530 }
531 TRACE("set container state to \"STARTING\"");
532
533 /* Start of environment variable setup for hooks. */
534 if (name && setenv("LXC_NAME", name, 1))
535 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name);
536
537 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
538 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf->rcfile);
539
540 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1))
541 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf->rootfs.mount);
542
543 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
544 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf->rootfs.path);
545
546 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1))
547 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf->console.path);
548
549 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1))
550 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf->console.log_path);
551
552 if (setenv("LXC_CGNS_AWARE", "1", 1))
553 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
554 /* End of environment variable setup for hooks. */
555
556 TRACE("set environment variables");
557
558 if (run_lxc_hooks(name, "pre-start", conf, handler->lxcpath, NULL)) {
559 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name);
560 goto out_aborting;
561 }
562 TRACE("ran pre-start hooks");
563
564 /* The signal fd has to be created before forking otherwise if the child
565 * process exits before we setup the signal fd, the event will be lost
566 * and the command will be stuck.
567 */
568 handler->sigfd = setup_signal_fd(&handler->oldmask);
569 if (handler->sigfd < 0) {
570 ERROR("Failed to setup SIGCHLD fd handler.");
571 goto out_delete_tty;
572 }
573 TRACE("set up signal fd");
574
575 /* Do this after setting up signals since it might unblock SIGWINCH. */
576 if (lxc_console_create(conf)) {
577 ERROR("Failed to create console for container \"%s\".", name);
578 goto out_restore_sigmask;
579 }
580 TRACE("created console");
581
582 if (lxc_ttys_shift_ids(conf) < 0) {
583 ERROR("Failed to shift tty into container.");
584 goto out_restore_sigmask;
585 }
586 TRACE("shifted tty ids");
587
588 INFO("container \"%s\" is initialized", name);
589 return 0;
590
591 out_restore_sigmask:
592 sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
593 out_delete_tty:
594 lxc_delete_tty(&conf->tty_info);
595 out_aborting:
596 lxc_set_state(name, handler, ABORTING);
597 out_close_maincmd_fd:
598 close(conf->maincmd_fd);
599 conf->maincmd_fd = -1;
600 return -1;
601 }
602
603 void lxc_fini(const char *name, struct lxc_handler *handler)
604 {
605 int i, rc;
606 struct lxc_list *cur, *next;
607 pid_t self = getpid();
608 char *namespaces[LXC_NS_MAX + 1];
609 size_t namespace_count = 0;
610
611 /* The STOPPING state is there for future cleanup code which can take
612 * awhile.
613 */
614 lxc_set_state(name, handler, STOPPING);
615
616 for (i = 0; i < LXC_NS_MAX; i++) {
617 if (handler->nsfd[i] != -1) {
618 rc = asprintf(&namespaces[namespace_count], "%s:/proc/%d/fd/%d",
619 ns_info[i].proc_name, self, handler->nsfd[i]);
620 if (rc == -1) {
621 SYSERROR("Failed to allocate memory.");
622 break;
623 }
624 ++namespace_count;
625 }
626 }
627 namespaces[namespace_count] = NULL;
628
629 if (handler->conf->reboot && setenv("LXC_TARGET", "reboot", 1))
630 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
631
632 if (!handler->conf->reboot && setenv("LXC_TARGET", "stop", 1))
633 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
634
635 if (run_lxc_hooks(name, "stop", handler->conf, handler->lxcpath, namespaces))
636 ERROR("Failed to run lxc.hook.stop for container \"%s\".", name);
637
638 while (namespace_count--)
639 free(namespaces[namespace_count]);
640 for (i = 0; i < LXC_NS_MAX; i++) {
641 if (handler->nsfd[i] != -1) {
642 close(handler->nsfd[i]);
643 handler->nsfd[i] = -1;
644 }
645 }
646
647 if (handler->netnsfd >= 0) {
648 close(handler->netnsfd);
649 handler->netnsfd = -1;
650 }
651
652 lxc_set_state(name, handler, STOPPED);
653
654 if (run_lxc_hooks(name, "post-stop", handler->conf, handler->lxcpath, NULL)) {
655 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name);
656 if (handler->conf->reboot) {
657 WARN("Container will be stopped instead of rebooted.");
658 handler->conf->reboot = 0;
659 if (setenv("LXC_TARGET", "stop", 1))
660 WARN("Failed to set environment variable: LXC_TARGET=stop.");
661 }
662 }
663
664 /* Reset mask set by setup_signal_fd. */
665 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
666 WARN("Failed to restore signal mask.");
667
668 lxc_console_delete(&handler->conf->console);
669 lxc_delete_tty(&handler->conf->tty_info);
670
671 /* close the command socket */
672 close(handler->conf->maincmd_fd);
673 handler->conf->maincmd_fd = -1;
674
675 /* The command socket is now closed, no more state clients can register
676 * themselves from now on. So free the list of state clients.
677 */
678 lxc_list_for_each_safe(cur, &handler->state_clients, next) {
679 struct state_client *client = cur->elem;
680 /* close state client socket */
681 close(client->clientfd);
682 lxc_list_del(cur);
683 free(cur->elem);
684 free(cur);
685 }
686
687 free(handler->name);
688 if (handler->ttysock[0] != -1) {
689 close(handler->ttysock[0]);
690 close(handler->ttysock[1]);
691 }
692
693 if (handler->conf->ephemeral == 1 && handler->conf->reboot != 1)
694 lxc_destroy_container_on_signal(handler, name);
695
696 cgroup_destroy(handler);
697 free(handler);
698 }
699
700 void lxc_abort(const char *name, struct lxc_handler *handler)
701 {
702 int ret, status;
703
704 lxc_set_state(name, handler, ABORTING);
705 if (handler->pid > 0)
706 kill(handler->pid, SIGKILL);
707 while ((ret = waitpid(-1, &status, 0)) > 0) {
708 ;
709 }
710 }
711
712 #include <sys/reboot.h>
713 #include <linux/reboot.h>
714
715 /* reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL in a child pid namespace
716 * if container reboot support exists. Otherwise, it will either succeed or
717 * return -EPERM.
718 */
719 static int container_reboot_supported(void *arg)
720 {
721 int *cmd = arg;
722 int ret;
723
724 ret = reboot(*cmd);
725 if (ret == -1 && errno == EINVAL)
726 return 1;
727 return 0;
728 }
729
730 static int must_drop_cap_sys_boot(struct lxc_conf *conf)
731 {
732 FILE *f;
733 int ret, cmd, v, flags;
734 long stack_size = 4096;
735 void *stack = alloca(stack_size);
736 int status;
737 pid_t pid;
738
739 f = fopen("/proc/sys/kernel/ctrl-alt-del", "r");
740 if (!f) {
741 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
742 return 1;
743 }
744
745 ret = fscanf(f, "%d", &v);
746 fclose(f);
747 if (ret != 1) {
748 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del.");
749 return 1;
750 }
751 cmd = v ? LINUX_REBOOT_CMD_CAD_ON : LINUX_REBOOT_CMD_CAD_OFF;
752
753 flags = CLONE_NEWPID | SIGCHLD;
754 if (!lxc_list_empty(&conf->id_map))
755 flags |= CLONE_NEWUSER;
756
757 #ifdef __ia64__
758 pid = __clone2(container_reboot_supported, stack, stack_size, flags, &cmd);
759 #else
760 stack += stack_size;
761 pid = clone(container_reboot_supported, stack, flags, &cmd);
762 #endif
763 if (pid < 0) {
764 if (flags & CLONE_NEWUSER)
765 ERROR("Failed to clone (%#x): %s (includes CLONE_NEWUSER).", flags, strerror(errno));
766 else
767 ERROR("Failed to clone (%#x): %s.", flags, strerror(errno));
768 return -1;
769 }
770 if (wait(&status) < 0) {
771 SYSERROR("Unexpected wait error: %s.", strerror(errno));
772 return -1;
773 }
774
775 if (WEXITSTATUS(status) != 1)
776 return 1;
777
778 return 0;
779 }
780
781 /* netpipe is used in the unprivileged case to transfer the ifindexes from
782 * parent to child
783 */
784 static int netpipe = -1;
785
786 static inline int count_veths(struct lxc_list *network)
787 {
788 struct lxc_list *iterator;
789 struct lxc_netdev *netdev;
790 int count = 0;
791
792 lxc_list_for_each(iterator, network) {
793 netdev = iterator->elem;
794 if (netdev->type != LXC_NET_VETH)
795 continue;
796 count++;
797 }
798 return count;
799 }
800
801 static int read_unpriv_netifindex(struct lxc_list *network)
802 {
803 struct lxc_list *iterator;
804 struct lxc_netdev *netdev;
805
806 if (netpipe == -1)
807 return 0;
808 lxc_list_for_each(iterator, network) {
809 netdev = iterator->elem;
810 if (netdev->type != LXC_NET_VETH)
811 continue;
812 if (!(netdev->name = malloc(IFNAMSIZ))) {
813 ERROR("Out of memory.");
814 close(netpipe);
815 return -1;
816 }
817 if (read(netpipe, netdev->name, IFNAMSIZ) != IFNAMSIZ) {
818 close(netpipe);
819 return -1;
820 }
821 }
822 close(netpipe);
823 return 0;
824 }
825
826 static int do_start(void *data)
827 {
828 struct lxc_list *iterator;
829 struct lxc_handler *handler = data;
830 int devnull_fd = -1, ret;
831 char path[PATH_MAX];
832
833 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL)) {
834 SYSERROR("Failed to set signal mask.");
835 return -1;
836 }
837
838 /* This prctl must be before the synchro, so if the parent dies before
839 * we set the parent death signal, we will detect its death with the
840 * synchro right after, otherwise we have a window where the parent can
841 * exit before we set the pdeath signal leading to a unsupervized
842 * container.
843 */
844 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
845 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL.");
846 return -1;
847 }
848
849 lxc_sync_fini_parent(handler);
850
851 /* Don't leak the pinfd to the container. */
852 if (handler->pinfd >= 0) {
853 close(handler->pinfd);
854 }
855
856 if (lxc_sync_wait_parent(handler, LXC_SYNC_STARTUP))
857 return -1;
858
859 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
860 * https://github.com/lxc/lxd/issues/1978.
861 */
862 if ((handler->clone_flags & (CLONE_NEWNET | CLONE_NEWUSER)) ==
863 (CLONE_NEWNET | CLONE_NEWUSER)) {
864 ret = unshare(CLONE_NEWNET);
865 if (ret < 0) {
866 SYSERROR("Failed to unshare CLONE_NEWNET.");
867 goto out_warn_father;
868 }
869 INFO("Unshared CLONE_NEWNET.");
870 }
871
872 /* Tell the parent task it can begin to configure the container and wait
873 * for it to finish.
874 */
875 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE))
876 return -1;
877
878 if (read_unpriv_netifindex(&handler->conf->network) < 0)
879 goto out_warn_father;
880
881 /* If we are in a new user namespace, become root there to have
882 * privilege over our namespace.
883 */
884 if (!lxc_list_empty(&handler->conf->id_map)) {
885 if (lxc_switch_uid_gid(0, 0) < 0)
886 goto out_warn_father;
887
888 /* Drop groups only after we switched to a valid gid in the new
889 * user namespace.
890 */
891 if (lxc_setgroups(0, NULL) < 0)
892 goto out_warn_father;
893 }
894
895 if (access(handler->lxcpath, X_OK)) {
896 print_top_failing_dir(handler->lxcpath);
897 goto out_warn_father;
898 }
899
900 #if HAVE_LIBCAP
901 if (handler->conf->need_utmp_watch) {
902 if (prctl(PR_CAPBSET_DROP, CAP_SYS_BOOT, 0, 0, 0)) {
903 SYSERROR("Failed to remove the CAP_SYS_BOOT capability.");
904 goto out_warn_father;
905 }
906 DEBUG("Dropped the CAP_SYS_BOOT capability.");
907 }
908 #endif
909
910 ret = snprintf(path, sizeof(path), "%s/dev/null", handler->conf->rootfs.mount);
911 if (ret < 0 || ret >= sizeof(path))
912 goto out_warn_father;
913
914 /* In order to checkpoint restore, we need to have everything in the
915 * same mount namespace. However, some containers may not have a
916 * reasonable /dev (in particular, they may not have /dev/null), so we
917 * can't set init's std fds to /dev/null by opening it from inside the
918 * container.
919 *
920 * If that's the case, fall back to using the host's /dev/null. This
921 * means that migration won't work, but at least we won't spew output
922 * where it isn't wanted.
923 */
924 if (handler->backgrounded && !handler->conf->autodev && access(path, F_OK) < 0) {
925 devnull_fd = open_devnull();
926
927 if (devnull_fd < 0)
928 goto out_warn_father;
929 WARN("Using /dev/null from the host for container init's "
930 "standard file descriptors. Migration will not work.");
931 }
932
933 /* Setup the container, ip, names, utsname, ... */
934 if (lxc_setup(handler)) {
935 ERROR("Failed to setup container \"%s\".", handler->name);
936 goto out_warn_father;
937 }
938
939 /* Ask father to setup cgroups and wait for him to finish. */
940 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP))
941 goto out_error;
942
943 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
944 * earlier we end up with a wrong view of /proc/self/cgroup. For
945 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
946 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
947 * /proc/self/cgroup would show us:
948 *
949 * 8:cpuset:/lxc/c
950 *
951 * whereas it should actually show
952 *
953 * 8:cpuset:/
954 */
955 if (cgns_supported()) {
956 if (unshare(CLONE_NEWCGROUP) < 0) {
957 INFO("Failed to unshare CLONE_NEWCGROUP.");
958 goto out_warn_father;
959 }
960 INFO("Unshared CLONE_NEWCGROUP.");
961 }
962
963 /* Set the label to change to when we exec(2) the container's init. */
964 if (lsm_process_label_set(NULL, handler->conf, 1, 1) < 0)
965 goto out_warn_father;
966
967 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
968 * before we aren't allowed anymore.
969 */
970 if (handler->conf->no_new_privs) {
971 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
972 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
973 goto out_warn_father;
974 }
975 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
976 }
977
978 /* Some init's such as busybox will set sane tty settings on stdin,
979 * stdout, stderr which it thinks is the console. We already set them
980 * the way we wanted on the real terminal, and we want init to do its
981 * setup on its console ie. the pty allocated in lxc_console_create() so
982 * make sure that that pty is stdin,stdout,stderr.
983 */
984 if (lxc_console_set_stdfds(handler->conf->console.slave) < 0)
985 goto out_warn_father;
986
987 /* If we mounted a temporary proc, then unmount it now. */
988 tmp_proc_unmount(handler->conf);
989
990 if (lxc_seccomp_load(handler->conf) != 0)
991 goto out_warn_father;
992
993 if (run_lxc_hooks(handler->name, "start", handler->conf, handler->lxcpath, NULL)) {
994 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler->name);
995 goto out_warn_father;
996 }
997
998 /* The container has been setup. We can now switch to an unprivileged
999 * uid/gid.
1000 */
1001 if (handler->conf->is_execute) {
1002 bool have_cap_setgid;
1003 uid_t new_uid = handler->conf->init_uid;
1004 gid_t new_gid = handler->conf->init_gid;
1005
1006 /* If we are in a new user namespace we already dropped all
1007 * groups when we switched to root in the new user namespace
1008 * further above. Only drop groups if we can, so ensure that we
1009 * have necessary privilege.
1010 */
1011 #if HAVE_LIBCAP
1012 have_cap_setgid = lxc_proc_cap_is_set(CAP_SETGID, CAP_EFFECTIVE);
1013 #else
1014 have_cap_setgid = false;
1015 #endif
1016 if (lxc_list_empty(&handler->conf->id_map) && have_cap_setgid) {
1017 if (lxc_setgroups(0, NULL) < 0)
1018 goto out_warn_father;
1019 }
1020
1021 if (lxc_switch_uid_gid(new_uid, new_gid) < 0)
1022 goto out_warn_father;
1023 }
1024
1025 /* The clearenv() and putenv() calls have been moved here to allow us to
1026 * use environment variables passed to the various hooks, such as the
1027 * start hook above. Not all of the variables like CONFIG_PATH or ROOTFS
1028 * are valid in this context but others are.
1029 */
1030 if (clearenv()) {
1031 SYSERROR("Failed to clear environment.");
1032 /* Don't error out though. */
1033 }
1034
1035 lxc_list_for_each(iterator, &handler->conf->environment) {
1036 if (putenv((char *)iterator->elem)) {
1037 SYSERROR("Failed to set environment variable: %s.", (char *)iterator->elem);
1038 goto out_warn_father;
1039 }
1040 }
1041
1042 if (putenv("container=lxc")) {
1043 SYSERROR("Failed to set environment variable: container=lxc.");
1044 goto out_warn_father;
1045 }
1046
1047 if (handler->conf->pty_names) {
1048 if (putenv(handler->conf->pty_names)) {
1049 SYSERROR("Failed to set environment variable for container ptys.");
1050 goto out_warn_father;
1051 }
1052 }
1053
1054 close(handler->sigfd);
1055
1056 if (devnull_fd < 0) {
1057 devnull_fd = open_devnull();
1058
1059 if (devnull_fd < 0)
1060 goto out_warn_father;
1061 }
1062
1063 if (handler->backgrounded && set_stdfds(devnull_fd))
1064 goto out_warn_father;
1065
1066 if (devnull_fd >= 0) {
1067 close(devnull_fd);
1068 devnull_fd = -1;
1069 }
1070
1071 setsid();
1072
1073 /* After this call, we are in error because this ops should not return
1074 * as it execs.
1075 */
1076 handler->ops->start(handler, handler->data);
1077
1078 out_warn_father:
1079 /* We want the parent to know something went wrong, so we return a
1080 * special error code.
1081 */
1082 lxc_sync_wake_parent(handler, LXC_SYNC_ERROR);
1083
1084 out_error:
1085 if (devnull_fd >= 0)
1086 close(devnull_fd);
1087
1088 return -1;
1089 }
1090
1091 static int save_phys_nics(struct lxc_conf *conf)
1092 {
1093 struct lxc_list *iterator;
1094 int am_root = (getuid() == 0);
1095
1096 if (!am_root)
1097 return 0;
1098
1099 lxc_list_for_each(iterator, &conf->network) {
1100 struct lxc_netdev *netdev = iterator->elem;
1101
1102 if (netdev->type != LXC_NET_PHYS)
1103 continue;
1104 conf->saved_nics = realloc(conf->saved_nics,
1105 (conf->num_savednics+1)*sizeof(struct saved_nic));
1106 if (!conf->saved_nics)
1107 return -1;
1108 conf->saved_nics[conf->num_savednics].ifindex = netdev->ifindex;
1109 conf->saved_nics[conf->num_savednics].orig_name = strdup(netdev->link);
1110 if (!conf->saved_nics[conf->num_savednics].orig_name)
1111 return -1;
1112 INFO("Stored saved_nic #%d idx %d name %s.", conf->num_savednics,
1113 conf->saved_nics[conf->num_savednics].ifindex,
1114 conf->saved_nics[conf->num_savednics].orig_name);
1115 conf->num_savednics++;
1116 }
1117
1118 return 0;
1119 }
1120
1121 static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
1122 {
1123 int i;
1124 int *ttyfds;
1125 struct lxc_pty_info *pty_info;
1126 int ret = -1;
1127 int sock = handler->ttysock[1];
1128 struct lxc_conf *conf = handler->conf;
1129 struct lxc_tty_info *tty_info = &conf->tty_info;
1130 size_t num_ttyfds = (2 * conf->tty);
1131
1132 if (!conf->tty)
1133 return 0;
1134
1135 tty_info->pty_info = malloc(sizeof(*tty_info->pty_info) * conf->tty);
1136 if (!tty_info->pty_info)
1137 return -1;
1138
1139 ttyfds = malloc(num_ttyfds * sizeof(int));
1140 if (!ttyfds)
1141 return -1;
1142
1143 ret = lxc_abstract_unix_recv_fds(sock, ttyfds, num_ttyfds, NULL, 0);
1144 for (i = 0; (ret >= 0 && *ttyfds != -1) && (i < num_ttyfds); i++) {
1145 pty_info = &tty_info->pty_info[i / 2];
1146 pty_info->busy = 0;
1147 pty_info->slave = ttyfds[i++];
1148 pty_info->master = ttyfds[i];
1149 TRACE("received pty with master fd %d and slave fd %d from "
1150 "parent", pty_info->master, pty_info->slave);
1151 }
1152
1153 tty_info->nbtty = conf->tty;
1154
1155 free(ttyfds);
1156
1157 if (ret < 0)
1158 ERROR("failed to receive %d ttys from child: %s", conf->tty,
1159 strerror(errno));
1160 else
1161 TRACE("received %d ttys from child", conf->tty);
1162
1163 return ret;
1164 }
1165
1166 void resolve_clone_flags(struct lxc_handler *handler)
1167 {
1168 handler->clone_flags = CLONE_NEWPID | CLONE_NEWNS;
1169
1170 if (!lxc_list_empty(&handler->conf->id_map))
1171 handler->clone_flags |= CLONE_NEWUSER;
1172
1173 if (handler->conf->inherit_ns_fd[LXC_NS_NET] == -1) {
1174 if (!lxc_requests_empty_network(handler))
1175 handler->clone_flags |= CLONE_NEWNET;
1176 } else {
1177 INFO("Inheriting a NET namespace.");
1178 }
1179
1180 if (handler->conf->inherit_ns_fd[LXC_NS_IPC] == -1)
1181 handler->clone_flags |= CLONE_NEWIPC;
1182 else
1183 INFO("Inheriting an IPC namespace.");
1184
1185 if (handler->conf->inherit_ns_fd[LXC_NS_UTS] == -1)
1186 handler->clone_flags |= CLONE_NEWUTS;
1187 else
1188 INFO("Inheriting a UTS namespace.");
1189 }
1190
1191 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1192 * exec()s the requested container binary.
1193 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1194 * right here should be double checked if they'd pose a security risk. (For
1195 * example, any {u}mount() operations performed here will be reflected on the
1196 * host!)
1197 */
1198 static int lxc_spawn(struct lxc_handler *handler)
1199 {
1200 int failed_before_rename = 0;
1201 const char *name = handler->name;
1202 bool cgroups_connected = false;
1203 int saved_ns_fd[LXC_NS_MAX];
1204 int preserve_mask = 0, i, flags;
1205 int netpipepair[2], nveths;
1206 bool wants_to_map_ids;
1207 struct lxc_list *id_map;
1208
1209 netpipe = -1;
1210 id_map = &handler->conf->id_map;
1211 wants_to_map_ids = !lxc_list_empty(id_map);
1212
1213 for (i = 0; i < LXC_NS_MAX; i++)
1214 if (handler->conf->inherit_ns_fd[i] != -1)
1215 preserve_mask |= ns_info[i].clone_flag;
1216
1217 if (lxc_sync_init(handler))
1218 return -1;
1219
1220 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, handler->ttysock) < 0) {
1221 lxc_sync_fini(handler);
1222 return -1;
1223 }
1224
1225 resolve_clone_flags(handler);
1226
1227 if (handler->clone_flags & CLONE_NEWNET) {
1228 if (!lxc_list_empty(&handler->conf->network)) {
1229
1230 /* Find gateway addresses from the link device, which is
1231 * no longer accessible inside the container. Do this
1232 * before creating network interfaces, since goto
1233 * out_delete_net does not work before lxc_clone.
1234 */
1235 if (lxc_find_gateway_addresses(handler)) {
1236 ERROR("Failed to find gateway addresses.");
1237 lxc_sync_fini(handler);
1238 return -1;
1239 }
1240
1241 /* That should be done before the clone because we will
1242 * fill the netdev index and use them in the child.
1243 */
1244 if (lxc_setup_networks_in_parent_namespaces(handler)) {
1245 ERROR("Failed to create the network.");
1246 lxc_sync_fini(handler);
1247 return -1;
1248 }
1249 }
1250
1251 if (save_phys_nics(handler->conf)) {
1252 ERROR("Failed to save physical nic info.");
1253 goto out_abort;
1254 }
1255 }
1256
1257 if (!cgroup_init(handler)) {
1258 ERROR("Failed initializing cgroup support.");
1259 goto out_delete_net;
1260 }
1261
1262 cgroups_connected = true;
1263
1264 if (!cgroup_create(handler)) {
1265 ERROR("Failed creating cgroups.");
1266 goto out_delete_net;
1267 }
1268
1269 /* If the rootfs is not a blockdev, prevent the container from marking
1270 * it readonly.
1271 * If the container is unprivileged then skip rootfs pinning.
1272 */
1273 if (!wants_to_map_ids) {
1274 handler->pinfd = pin_rootfs(handler->conf->rootfs.path);
1275 if (handler->pinfd == -1)
1276 INFO("Failed to pin the rootfs for container \"%s\".", handler->name);
1277 }
1278
1279 if (!preserve_ns(saved_ns_fd, preserve_mask, getpid()))
1280 goto out_delete_net;
1281
1282 if (attach_ns(handler->conf->inherit_ns_fd) < 0)
1283 goto out_delete_net;
1284
1285 if (am_unpriv() && (nveths = count_veths(&handler->conf->network))) {
1286 if (pipe(netpipepair) < 0) {
1287 SYSERROR("Failed to create pipe.");
1288 goto out_delete_net;
1289 }
1290 /* Store netpipe in the global var for do_start's use. */
1291 netpipe = netpipepair[0];
1292 }
1293
1294 /* Create a process in a new set of namespaces. */
1295 flags = handler->clone_flags;
1296 if (handler->clone_flags & CLONE_NEWUSER) {
1297 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1298 * clone a new user namespace first and only later unshare our
1299 * network namespace to ensure that network devices ownership is
1300 * set up correctly.
1301 */
1302 flags &= ~CLONE_NEWNET;
1303 }
1304 handler->pid = lxc_clone(do_start, handler, flags);
1305 if (handler->pid < 0) {
1306 SYSERROR("Failed to clone a new set of namespaces.");
1307 goto out_delete_net;
1308 }
1309 for (i = 0; i < LXC_NS_MAX; i++)
1310 if (flags & ns_info[i].clone_flag)
1311 INFO("Cloned %s.", ns_info[i].flag_name);
1312
1313 if (!preserve_ns(handler->nsfd, handler->clone_flags | preserve_mask, handler->pid))
1314 INFO("Failed to preserve namespace for lxc.hook.stop.");
1315
1316 if (attach_ns(saved_ns_fd))
1317 WARN("Failed to restore saved namespaces.");
1318
1319 lxc_sync_fini_child(handler);
1320
1321 /* Map the container uids. The container became an invalid userid the
1322 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1323 * anything immediately, but allows the container to setuid(0) (0 being
1324 * mapped to something else on the host.) later to become a valid uid
1325 * again.
1326 */
1327 if (wants_to_map_ids && lxc_map_ids(id_map, handler->pid)) {
1328 ERROR("Failed to set up id mapping.");
1329 goto out_delete_net;
1330 }
1331
1332 if (lxc_sync_wake_child(handler, LXC_SYNC_STARTUP)) {
1333 failed_before_rename = 1;
1334 goto out_delete_net;
1335 }
1336
1337 if (lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE)) {
1338 failed_before_rename = 1;
1339 goto out_delete_net;
1340 }
1341
1342 if (!cgroup_create_legacy(handler)) {
1343 ERROR("Failed to setup legacy cgroups for container \"%s\".", name);
1344 goto out_delete_net;
1345 }
1346 if (!cgroup_setup_limits(handler, false)) {
1347 ERROR("Failed to setup cgroup limits for container \"%s\".", name);
1348 goto out_delete_net;
1349 }
1350
1351 if (!cgroup_enter(handler))
1352 goto out_delete_net;
1353
1354 if (!cgroup_chown(handler))
1355 goto out_delete_net;
1356
1357 if (failed_before_rename)
1358 goto out_delete_net;
1359
1360 /* Create the network configuration. */
1361 if (handler->clone_flags & CLONE_NEWNET) {
1362 if (lxc_assign_network(handler->lxcpath, handler->name,
1363 &handler->conf->network, handler->pid)) {
1364 ERROR("Failed to create the configured network.");
1365 goto out_delete_net;
1366 }
1367 }
1368
1369 if (netpipe != -1) {
1370 struct lxc_list *iterator;
1371 struct lxc_netdev *netdev;
1372
1373 close(netpipe);
1374 lxc_list_for_each(iterator, &handler->conf->network) {
1375 netdev = iterator->elem;
1376 if (netdev->type != LXC_NET_VETH)
1377 continue;
1378 if (write(netpipepair[1], netdev->name, IFNAMSIZ) != IFNAMSIZ) {
1379 ERROR("Error writing veth name to container.");
1380 goto out_delete_net;
1381 }
1382 }
1383 close(netpipepair[1]);
1384 }
1385
1386 /* Tell the child to continue its initialization. We'll get
1387 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1388 */
1389 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE))
1390 goto out_delete_net;
1391
1392 if (!lxc_list_empty(&handler->conf->limits) && setup_resource_limits(&handler->conf->limits, handler->pid)) {
1393 ERROR("failed to setup resource limits for '%s'", name);
1394 goto out_delete_net;
1395 }
1396
1397 if (!cgroup_setup_limits(handler, true)) {
1398 ERROR("Failed to setup the devices cgroup for container \"%s\".", name);
1399 goto out_delete_net;
1400 }
1401
1402 cgroup_disconnect();
1403 cgroups_connected = false;
1404
1405 /* Read tty fds allocated by child. */
1406 if (lxc_recv_ttys_from_child(handler) < 0) {
1407 ERROR("Failed to receive tty info from child process.");
1408 goto out_delete_net;
1409 }
1410
1411 /* Tell the child to complete its initialization and wait for it to exec
1412 * or return an error. (The child will never return
1413 * LXC_SYNC_POST_CGROUP+1. It will either close the sync pipe, causing
1414 * lxc_sync_barrier_child to return success, or return a different
1415 * value, causing us to error out).
1416 */
1417 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CGROUP))
1418 return -1;
1419
1420 if (handler->ops->post_start(handler, handler->data))
1421 goto out_abort;
1422
1423 if (lxc_set_state(name, handler, RUNNING)) {
1424 ERROR("Failed to set state for container \"%s\" to \"%s\".", name,
1425 lxc_state2str(RUNNING));
1426 goto out_abort;
1427 }
1428
1429 lxc_sync_fini(handler);
1430 handler->netnsfd = lxc_preserve_ns(handler->pid, "net");
1431
1432 return 0;
1433
1434 out_delete_net:
1435 if (cgroups_connected)
1436 cgroup_disconnect();
1437 if (handler->clone_flags & CLONE_NEWNET)
1438 lxc_delete_network(handler);
1439 out_abort:
1440 lxc_abort(name, handler);
1441 lxc_sync_fini(handler);
1442 if (handler->pinfd >= 0) {
1443 close(handler->pinfd);
1444 handler->pinfd = -1;
1445 }
1446
1447 return -1;
1448 }
1449
1450 int __lxc_start(const char *name, struct lxc_handler *handler,
1451 struct lxc_operations* ops, void *data, const char *lxcpath,
1452 bool backgrounded)
1453 {
1454 int status;
1455 int err = -1;
1456 bool removed_all_netdevs = true;
1457 struct lxc_conf *conf = handler->conf;
1458
1459 if (lxc_init(name, handler) < 0) {
1460 ERROR("Failed to initialize container \"%s\".", name);
1461 return -1;
1462 }
1463 handler->ops = ops;
1464 handler->data = data;
1465 handler->backgrounded = backgrounded;
1466 handler->netnsfd = -1;
1467
1468 if (must_drop_cap_sys_boot(handler->conf)) {
1469 #if HAVE_LIBCAP
1470 DEBUG("Dropping CAP_SYS_BOOT capability.");
1471 #else
1472 DEBUG("Not dropping CAP_SYS_BOOT capability as capabilities aren't supported.");
1473 #endif
1474 } else {
1475 DEBUG("Not dropping CAP_SYS_BOOT or watching utmp.");
1476 handler->conf->need_utmp_watch = 0;
1477 }
1478
1479 if (!attach_block_device(handler->conf)) {
1480 ERROR("Failed to attach block device.");
1481 goto out_fini_nonet;
1482 }
1483
1484 if (geteuid() == 0 && !lxc_list_empty(&conf->id_map)) {
1485 /* If the backing store is a device, mount it here and now. */
1486 if (rootfs_is_blockdev(conf)) {
1487 if (unshare(CLONE_NEWNS) < 0) {
1488 ERROR("Failed to unshare CLONE_NEWNS.");
1489 goto out_fini_nonet;
1490 }
1491 INFO("Unshared CLONE_NEWNS.");
1492
1493 remount_all_slave();
1494 if (do_rootfs_setup(conf, name, lxcpath) < 0) {
1495 ERROR("Error setting up rootfs mount as root before spawn.");
1496 goto out_fini_nonet;
1497 }
1498 INFO("Set up container rootfs as host root.");
1499 }
1500 }
1501
1502 err = lxc_spawn(handler);
1503 if (err) {
1504 ERROR("Failed to spawn container \"%s\".", name);
1505 goto out_detach_blockdev;
1506 }
1507
1508 handler->conf->reboot = 0;
1509
1510 err = lxc_poll(name, handler);
1511 if (err) {
1512 ERROR("LXC mainloop exited with error: %d.", err);
1513 if (handler->netnsfd >= 0) {
1514 close(handler->netnsfd);
1515 handler->netnsfd = -1;
1516 }
1517 goto out_abort;
1518 }
1519
1520 while (waitpid(handler->pid, &status, 0) < 0 && errno == EINTR)
1521 continue;
1522
1523 /* If the child process exited but was not signaled, it didn't call
1524 * reboot. This should mean it was an lxc-execute which simply exited.
1525 * In any case, treat it as a 'halt'.
1526 */
1527 if (WIFSIGNALED(status)) {
1528 switch(WTERMSIG(status)) {
1529 case SIGINT: /* halt */
1530 DEBUG("Container \"%s\" is halting.", name);
1531 break;
1532 case SIGHUP: /* reboot */
1533 DEBUG("Container \"%s\" is rebooting.", name);
1534 handler->conf->reboot = 1;
1535 break;
1536 case SIGSYS: /* seccomp */
1537 DEBUG("Container \"%s\" violated its seccomp policy.", name);
1538 break;
1539 default:
1540 DEBUG("Unknown exit status for container \"%s\" init %d.", name, WTERMSIG(status));
1541 break;
1542 }
1543 }
1544
1545 DEBUG("Pushing physical nics back to host namespace");
1546 lxc_restore_phys_nics_to_netns(handler->netnsfd, handler->conf);
1547
1548 DEBUG("Tearing down virtual network devices used by container \"%s\".", name);
1549 removed_all_netdevs = lxc_delete_network(handler);
1550
1551 if (handler->pinfd >= 0) {
1552 close(handler->pinfd);
1553 handler->pinfd = -1;
1554 }
1555
1556 lxc_monitor_send_exit_code(name, status, handler->lxcpath);
1557 err = lxc_error_set_and_log(handler->pid, status);
1558 out_fini:
1559 if (!removed_all_netdevs) {
1560 DEBUG("Failed tearing down network devices used by container. Trying again!");
1561 removed_all_netdevs = lxc_delete_network(handler);
1562 if (!removed_all_netdevs)
1563 DEBUG("Failed tearing down network devices used by container. Not trying again!");
1564 }
1565
1566 out_detach_blockdev:
1567 detach_block_device(handler->conf);
1568
1569 out_fini_nonet:
1570 lxc_fini(name, handler);
1571 return err;
1572
1573 out_abort:
1574 lxc_abort(name, handler);
1575 goto out_fini;
1576 }
1577
1578 struct start_args {
1579 char *const *argv;
1580 };
1581
1582 static int start(struct lxc_handler *handler, void* data)
1583 {
1584 struct start_args *arg = data;
1585
1586 NOTICE("Exec'ing \"%s\".", arg->argv[0]);
1587
1588 execvp(arg->argv[0], arg->argv);
1589 SYSERROR("Failed to exec \"%s\".", arg->argv[0]);
1590 return 0;
1591 }
1592
1593 static int post_start(struct lxc_handler *handler, void* data)
1594 {
1595 struct start_args *arg = data;
1596
1597 NOTICE("Started \"%s\" with pid \"%d\".", arg->argv[0], handler->pid);
1598 return 0;
1599 }
1600
1601 static struct lxc_operations start_ops = {
1602 .start = start,
1603 .post_start = post_start
1604 };
1605
1606 int lxc_start(const char *name, char *const argv[], struct lxc_handler *handler,
1607 const char *lxcpath, bool backgrounded)
1608 {
1609 struct start_args start_arg = {
1610 .argv = argv,
1611 };
1612
1613 handler->conf->need_utmp_watch = 1;
1614 return __lxc_start(name, handler, &start_ops, &start_arg, lxcpath, backgrounded);
1615 }
1616
1617 static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
1618 const char *name)
1619 {
1620 char destroy[MAXPATHLEN];
1621 bool bret = true;
1622 int ret = 0;
1623 struct lxc_container *c;
1624 if (handler->conf->rootfs.path && handler->conf->rootfs.mount) {
1625 bret = do_destroy_container(handler->conf);
1626 if (!bret) {
1627 ERROR("Error destroying rootfs for container \"%s\".", name);
1628 return;
1629 }
1630 }
1631 INFO("Destroyed rootfs for container \"%s\".", name);
1632
1633 ret = snprintf(destroy, MAXPATHLEN, "%s/%s", handler->lxcpath, name);
1634 if (ret < 0 || ret >= MAXPATHLEN) {
1635 ERROR("Error destroying directory for container \"%s\".", name);
1636 return;
1637 }
1638
1639 c = lxc_container_new(name, handler->lxcpath);
1640 if (c) {
1641 if (container_disk_lock(c)) {
1642 INFO("Could not update lxc_snapshots file.");
1643 lxc_container_put(c);
1644 } else {
1645 mod_all_rdeps(c, false);
1646 container_disk_unlock(c);
1647 lxc_container_put(c);
1648 }
1649 }
1650
1651 if (am_unpriv())
1652 ret = userns_exec_1(handler->conf, lxc_rmdir_onedev_wrapper,
1653 destroy, "lxc_rmdir_onedev_wrapper");
1654 else
1655 ret = lxc_rmdir_onedev(destroy, NULL);
1656
1657 if (ret < 0) {
1658 ERROR("Error destroying directory for container \"%s\".", name);
1659 return;
1660 }
1661 INFO("Destroyed directory for container \"%s\".", name);
1662 }
1663
1664 static int lxc_rmdir_onedev_wrapper(void *data)
1665 {
1666 char *arg = (char *) data;
1667 return lxc_rmdir_onedev(arg, NULL);
1668 }
1669
1670 static bool do_destroy_container(struct lxc_conf *conf) {
1671 if (am_unpriv()) {
1672 if (userns_exec_1(conf, bdev_destroy_wrapper, conf,
1673 "bdev_destroy_wrapper") < 0)
1674 return false;
1675 return true;
1676 }
1677 return bdev_destroy(conf);
1678 }