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