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