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