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