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