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