]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/start.c
tree-wide: s/pts/pty/g
[mirror_lxc.git] / src / lxc / start.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #ifndef _GNU_SOURCE
4 #define _GNU_SOURCE 1
5 #endif
6 #include <dirent.h>
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <grp.h>
10 #include <poll.h>
11 #include <pthread.h>
12 #include <signal.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <sys/file.h>
17 #include <sys/mount.h>
18 #include <sys/param.h>
19 #include <sys/prctl.h>
20 #include <sys/socket.h>
21 #include <sys/stat.h>
22 #include <sys/syscall.h>
23 #include <sys/types.h>
24 #include <sys/un.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27
28 #include "af_unix.h"
29 #include "caps.h"
30 #include "cgroup.h"
31 #include "commands.h"
32 #include "commands_utils.h"
33 #include "conf.h"
34 #include "config.h"
35 #include "confile_utils.h"
36 #include "error.h"
37 #include "file_utils.h"
38 #include "list.h"
39 #include "log.h"
40 #include "lsm/lsm.h"
41 #include "lxccontainer.h"
42 #include "lxclock.h"
43 #include "lxcseccomp.h"
44 #include "macro.h"
45 #include "mainloop.h"
46 #include "memory_utils.h"
47 #include "monitor.h"
48 #include "namespace.h"
49 #include "network.h"
50 #include "process_utils.h"
51 #include "start.h"
52 #include "storage/storage.h"
53 #include "storage/storage_utils.h"
54 #include "sync.h"
55 #include "syscall_wrappers.h"
56 #include "terminal.h"
57 #include "utils.h"
58
59 #if HAVE_LIBCAP
60 #include <sys/capability.h>
61 #endif
62
63 #ifndef HAVE_STRLCPY
64 #include "include/strlcpy.h"
65 #endif
66
67 lxc_log_define(start, lxc);
68
69 extern void mod_all_rdeps(struct lxc_container *c, bool inc);
70 static bool do_destroy_container(struct lxc_handler *handler);
71 static int lxc_rmdir_onedev_wrapper(void *data);
72 static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
73 const char *name);
74
75 static void print_top_failing_dir(const char *path)
76 {
77 __do_free char *copy = NULL;
78 int ret;
79 char *e, *p, saved;
80
81 copy = must_copy_string(path);
82 p = copy;
83 e = copy + strlen(path);
84
85 while (p < e) {
86 while (p < e && *p == '/')
87 p++;
88
89 while (p < e && *p != '/')
90 p++;
91
92 saved = *p;
93 *p = '\0';
94
95 ret = access(copy, X_OK);
96 if (ret != 0) {
97 SYSERROR("Could not access %s. Please grant it x access, or add an ACL for the container " "root", copy);
98 return;
99 }
100 *p = saved;
101 }
102 }
103
104 static void lxc_put_nsfds(struct lxc_handler *handler)
105 {
106 for (int i = 0; i < LXC_NS_MAX; i++) {
107 if (handler->nsfd[i] < 0)
108 continue;
109
110 close_prot_errno_disarm(handler->nsfd[i]);
111 }
112 }
113
114 static int lxc_try_preserve_ns(const int pid, const char *ns)
115 {
116 int fd;
117
118 fd = lxc_preserve_ns(pid, ns);
119 if (fd < 0) {
120 if (errno != ENOENT)
121 return log_error_errno(-EINVAL,
122 errno, "Failed to preserve %s namespace",
123 ns);
124
125 return log_warn_errno(-EOPNOTSUPP,
126 errno, "Kernel does not support preserving %s namespaces",
127 ns);
128 }
129
130 return fd;
131 }
132
133 /* lxc_try_preserve_namespaces: open /proc/@pid/ns/@ns for each namespace
134 * specified in ns_clone_flags.
135 * Return true on success, false on failure.
136 */
137 static bool lxc_try_preserve_namespaces(struct lxc_handler *handler,
138 int ns_clone_flags, pid_t pid)
139 {
140 int i;
141
142 for (i = 0; i < LXC_NS_MAX; i++)
143 handler->nsfd[i] = -EBADF;
144
145 for (i = 0; i < LXC_NS_MAX; i++) {
146 int fd;
147
148 if ((ns_clone_flags & ns_info[i].clone_flag) == 0)
149 continue;
150
151 fd = lxc_try_preserve_ns(pid, ns_info[i].proc_name);
152 if (fd < 0) {
153 /* Do not fail to start container on kernels that do
154 * not support interacting with namespaces through
155 * /proc.
156 */
157 if (fd == -EOPNOTSUPP)
158 continue;
159
160 lxc_put_nsfds(handler);
161 return false;
162 }
163
164 handler->nsfd[i] = fd;
165 DEBUG("Preserved %s namespace via fd %d", ns_info[i].proc_name,
166 handler->nsfd[i]);
167 }
168
169 return true;
170 }
171
172 static inline bool match_stdfds(int fd)
173 {
174 return (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO);
175 }
176
177 #ifdef HAVE_DLOG
178 static bool match_dlog_fds(struct dirent *direntp)
179 {
180 char path[PATH_MAX] = {0};
181 char link[PATH_MAX] = {0};
182 ssize_t linklen;
183 int ret;
184
185 ret = snprintf(path, PATH_MAX, "/proc/self/fd/%s", direntp->d_name);
186 if (ret < 0 || ret >= PATH_MAX)
187 return log_error(false, "Failed to create file descriptor name");
188
189 linklen = readlink(path, link, PATH_MAX);
190 if (linklen < 0)
191 return log_error(false, "Failed to read link path - \"%s\"", path);
192 else if (linklen >= PATH_MAX)
193 return log_error(false, "The name of link path is too long - \"%s\"", path);
194
195 if (strcmp(link, "/dev/log_main") == 0 ||
196 strcmp(link, "/dev/log_system") == 0 ||
197 strcmp(link, "/dev/log_radio") == 0)
198 return true;
199
200 return false;
201 }
202 #endif
203
204 int lxc_check_inherited(struct lxc_conf *conf, bool closeall,
205 int *fds_to_ignore, size_t len_fds)
206 {
207 int fd, fddir;
208 size_t i;
209 DIR *dir;
210 struct dirent *direntp;
211
212 if (conf && conf->close_all_fds)
213 closeall = true;
214
215 /*
216 * Disable syslog at this point to avoid the above logging
217 * function to open a new fd and make the check_inherited function
218 * enter an infinite loop.
219 */
220 lxc_log_syslog_disable();
221
222 restart:
223 dir = opendir("/proc/self/fd");
224 if (!dir)
225 return log_warn(-1, "Failed to open directory");
226
227 fddir = dirfd(dir);
228
229 while ((direntp = readdir(dir))) {
230 int ret;
231 struct lxc_list *cur;
232 bool matched = false;
233
234 if (strcmp(direntp->d_name, ".") == 0)
235 continue;
236
237 if (strcmp(direntp->d_name, "..") == 0)
238 continue;
239
240 ret = lxc_safe_int(direntp->d_name, &fd);
241 if (ret < 0) {
242 INFO("Could not parse file descriptor for \"%s\"", direntp->d_name);
243 continue;
244 }
245
246 for (i = 0; i < len_fds; i++)
247 if (fds_to_ignore[i] == fd)
248 break;
249
250 if (fd == fddir || fd == lxc_log_fd ||
251 (i < len_fds && fd == fds_to_ignore[i]))
252 continue;
253
254 /* Keep state clients that wait on reboots. */
255 if (conf) {
256 lxc_list_for_each(cur, &conf->state_clients) {
257 struct lxc_state_client *client = cur->elem;
258
259 if (client->clientfd != fd)
260 continue;
261
262 matched = true;
263 break;
264 }
265 }
266
267 if (matched)
268 continue;
269
270 if (current_config && fd == current_config->logfd)
271 continue;
272
273 if (match_stdfds(fd))
274 continue;
275
276 #ifdef HAVE_DLOG
277 if (match_dlog_fds(direntp))
278 continue;
279
280 #endif
281 if (closeall) {
282 if (close(fd))
283 SYSINFO("Closed inherited fd %d", fd);
284 else
285 INFO("Closed inherited fd %d", fd);
286 closedir(dir);
287 goto restart;
288 }
289 WARN("Inherited fd %d", fd);
290 }
291 closedir(dir);
292
293 /*
294 * Only enable syslog at this point to avoid the above logging
295 * function to open a new fd and make the check_inherited function
296 * enter an infinite loop.
297 */
298 lxc_log_syslog_enable();
299
300 return 0;
301 }
302
303 static int setup_signal_fd(sigset_t *oldmask)
304 {
305 int ret;
306 sigset_t mask;
307 const int signals[] = {SIGBUS, SIGILL, SIGSEGV, SIGWINCH};
308
309 /* Block everything except serious error signals. */
310 ret = sigfillset(&mask);
311 if (ret < 0)
312 return -EBADF;
313
314 for (int sig = 0; sig < (sizeof(signals) / sizeof(signals[0])); sig++) {
315 ret = sigdelset(&mask, signals[sig]);
316 if (ret < 0)
317 return -EBADF;
318 }
319
320 ret = pthread_sigmask(SIG_BLOCK, &mask, oldmask);
321 if (ret < 0)
322 return log_error_errno(-EBADF, errno,
323 "Failed to set signal mask");
324
325 ret = signalfd(-1, &mask, SFD_CLOEXEC);
326 if (ret < 0)
327 return log_error_errno(-EBADF,
328 errno, "Failed to create signal file descriptor");
329
330 TRACE("Created signal file descriptor %d", ret);
331
332 return ret;
333 }
334
335 static int signal_handler(int fd, uint32_t events, void *data,
336 struct lxc_epoll_descr *descr)
337 {
338 int ret;
339 siginfo_t info;
340 struct signalfd_siginfo siginfo;
341 struct lxc_handler *hdlr = data;
342
343 ret = lxc_read_nointr(fd, &siginfo, sizeof(siginfo));
344 if (ret < 0)
345 return log_error(LXC_MAINLOOP_ERROR, "Failed to read signal info from signal file descriptor %d", fd);
346
347 if (ret != sizeof(siginfo))
348 return log_error(LXC_MAINLOOP_ERROR, "Unexpected size for struct signalfd_siginfo");
349
350 /* Check whether init is running. */
351 info.si_pid = 0;
352 ret = waitid(P_PID, hdlr->pid, &info, WEXITED | WNOWAIT | WNOHANG);
353 if (ret == 0 && info.si_pid == hdlr->pid)
354 hdlr->init_died = true;
355
356 /* Try to figure out a reasonable exit status to report. */
357 if (hdlr->init_died) {
358 switch (info.si_code) {
359 case CLD_EXITED:
360 hdlr->exit_status = info.si_status << 8;
361 break;
362 case CLD_KILLED:
363 case CLD_DUMPED:
364 case CLD_STOPPED:
365 hdlr->exit_status = info.si_status << 8 | 0x7f;
366 break;
367 case CLD_CONTINUED:
368 /* Huh? The waitid() told us it's dead *and* continued? */
369 WARN("Init %d dead and continued?", hdlr->pid);
370 hdlr->exit_status = 1;
371 break;
372 default:
373 ERROR("Unknown si_code: %d", info.si_code);
374 hdlr->exit_status = 1;
375 }
376 }
377
378 if (siginfo.ssi_signo == SIGHUP) {
379 if (hdlr->pidfd >= 0)
380 lxc_raw_pidfd_send_signal(hdlr->pidfd, SIGTERM, NULL, 0);
381 else
382 kill(hdlr->pid, SIGTERM);
383 INFO("Killing %d since terminal hung up", hdlr->pid);
384 return hdlr->init_died ? LXC_MAINLOOP_CLOSE
385 : LXC_MAINLOOP_CONTINUE;
386 }
387
388 if (siginfo.ssi_signo != SIGCHLD) {
389 if (hdlr->pidfd >= 0)
390 lxc_raw_pidfd_send_signal(hdlr->pidfd,
391 siginfo.ssi_signo, NULL, 0);
392 else
393 kill(hdlr->pid, siginfo.ssi_signo);
394 INFO("Forwarded signal %d to pid %d", siginfo.ssi_signo, hdlr->pid);
395 return hdlr->init_died ? LXC_MAINLOOP_CLOSE
396 : LXC_MAINLOOP_CONTINUE;
397 }
398
399 /* More robustness, protect ourself from a SIGCHLD sent
400 * by a process different from the container init.
401 */
402 if (siginfo.ssi_pid != hdlr->pid) {
403 NOTICE("Received %d from pid %d instead of container init %d",
404 siginfo.ssi_signo, siginfo.ssi_pid, hdlr->pid);
405 return hdlr->init_died ? LXC_MAINLOOP_CLOSE
406 : LXC_MAINLOOP_CONTINUE;
407 }
408
409 if (siginfo.ssi_code == CLD_STOPPED) {
410 INFO("Container init process was stopped");
411 return hdlr->init_died ? LXC_MAINLOOP_CLOSE
412 : LXC_MAINLOOP_CONTINUE;
413 }
414
415 if (siginfo.ssi_code == CLD_CONTINUED) {
416 INFO("Container init process was continued");
417 return hdlr->init_died ? LXC_MAINLOOP_CLOSE
418 : LXC_MAINLOOP_CONTINUE;
419 }
420
421 return log_debug(LXC_MAINLOOP_CLOSE, "Container init process %d exited", hdlr->pid);
422 }
423
424 int lxc_serve_state_clients(const char *name, struct lxc_handler *handler,
425 lxc_state_t state)
426 {
427 size_t retlen;
428 ssize_t ret;
429 struct lxc_list *cur, *next;
430 struct lxc_msg msg = {.type = lxc_msg_state, .value = state};
431
432 if (state == THAWED)
433 handler->state = RUNNING;
434 else
435 handler->state = state;
436
437 TRACE("Set container state to %s", lxc_state2str(state));
438
439 if (lxc_list_empty(&handler->conf->state_clients))
440 return log_trace(0, "No state clients registered");
441
442 retlen = strlcpy(msg.name, name, sizeof(msg.name));
443 if (retlen >= sizeof(msg.name))
444 return -E2BIG;
445
446 lxc_list_for_each_safe(cur, &handler->conf->state_clients, next) {
447 struct lxc_state_client *client = cur->elem;
448
449 if (client->states[state] == 0) {
450 TRACE("State %s not registered for state client %d",
451 lxc_state2str(state), client->clientfd);
452 continue;
453 }
454
455 TRACE("Sending state %s to state client %d",
456 lxc_state2str(state), client->clientfd);
457
458 ret = lxc_send_nointr(client->clientfd, &msg, sizeof(msg), MSG_NOSIGNAL);
459 if (ret <= 0)
460 SYSERROR("Failed to send message to client");
461
462 /* kick client from list */
463 lxc_list_del(cur);
464 close(client->clientfd);
465 free(cur->elem);
466 free(cur);
467 }
468
469 return 0;
470 }
471
472 static int lxc_serve_state_socket_pair(const char *name,
473 struct lxc_handler *handler,
474 lxc_state_t state)
475 {
476 ssize_t ret;
477
478 if (!handler->daemonize ||
479 handler->state_socket_pair[1] < 0 ||
480 state == STARTING)
481 return 0;
482
483 /* Close read end of the socket pair. */
484 close_prot_errno_disarm(handler->state_socket_pair[0]);
485
486 again:
487 ret = lxc_abstract_unix_send_credential(handler->state_socket_pair[1],
488 &(int){state}, sizeof(int));
489 if (ret < 0) {
490 SYSERROR("Failed to send state to %d", handler->state_socket_pair[1]);
491
492 if (errno == EINTR)
493 goto again;
494
495 return -1;
496 }
497
498 if (ret != sizeof(int))
499 return log_error(-1, "Message too long : %d", handler->state_socket_pair[1]);
500
501 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state),
502 handler->state_socket_pair[1]);
503
504 /* Close write end of the socket pair. */
505 close_prot_errno_disarm(handler->state_socket_pair[1]);
506
507 return 0;
508 }
509
510 int lxc_set_state(const char *name, struct lxc_handler *handler,
511 lxc_state_t state)
512 {
513 int ret;
514
515 ret = lxc_serve_state_socket_pair(name, handler, state);
516 if (ret < 0)
517 return log_error(-1, "Failed to synchronize via anonymous pair of unix sockets");
518
519 ret = lxc_serve_state_clients(name, handler, state);
520 if (ret < 0)
521 return -1;
522
523 /* This function will try to connect to the legacy lxc-monitord state
524 * server and only exists for backwards compatibility.
525 */
526 lxc_monitor_send_state(name, state, handler->lxcpath);
527
528 return 0;
529 }
530
531 int lxc_poll(const char *name, struct lxc_handler *handler)
532 {
533 int ret;
534 bool has_console = true;
535 struct lxc_epoll_descr descr, descr_console;
536
537 if (handler->conf->console.path &&
538 strcmp(handler->conf->console.path, "none") == 0)
539 has_console = false;
540
541 ret = lxc_mainloop_open(&descr);
542 if (ret < 0) {
543 ERROR("Failed to create mainloop");
544 goto out_sigfd;
545 }
546
547 if (has_console) {
548 ret = lxc_mainloop_open(&descr_console);
549 if (ret < 0) {
550 ERROR("Failed to create console mainloop");
551 goto out_mainloop;
552 }
553 }
554
555 ret = lxc_mainloop_add_handler(&descr, handler->sigfd, signal_handler, handler);
556 if (ret < 0) {
557 ERROR("Failed to add signal handler for %d to mainloop", handler->sigfd);
558 goto out_mainloop_console;
559 }
560
561 ret = lxc_seccomp_setup_proxy(&handler->conf->seccomp, &descr, handler);
562 if (ret < 0) {
563 ERROR("Failed to setup seccomp proxy");
564 goto out_mainloop_console;
565 }
566
567 if (has_console) {
568 struct lxc_terminal *console = &handler->conf->console;
569
570 ret = lxc_terminal_mainloop_add(&descr, console);
571 if (ret < 0) {
572 ERROR("Failed to add console handlers to mainloop");
573 goto out_mainloop_console;
574 }
575
576 ret = lxc_terminal_mainloop_add(&descr_console, console);
577 if (ret < 0) {
578 ERROR("Failed to add console handlers to console mainloop");
579 goto out_mainloop_console;
580 }
581
582 handler->conf->console.descr = &descr;
583 }
584
585 ret = lxc_cmd_mainloop_add(name, &descr, handler);
586 if (ret < 0) {
587 ERROR("Failed to add command handler to mainloop");
588 goto out_mainloop_console;
589 }
590
591 TRACE("Mainloop is ready");
592
593 ret = lxc_mainloop(&descr, -1);
594 close_prot_errno_disarm(descr.epfd);
595 if (ret < 0 || !handler->init_died)
596 goto out_mainloop_console;
597
598 if (has_console)
599 ret = lxc_mainloop(&descr_console, 0);
600
601 out_mainloop_console:
602 if (has_console) {
603 lxc_mainloop_close(&descr_console);
604 TRACE("Closed console mainloop");
605 }
606
607 out_mainloop:
608 lxc_mainloop_close(&descr);
609 TRACE("Closed mainloop");
610
611 out_sigfd:
612 TRACE("Closed signal file descriptor %d", handler->sigfd);
613 close_prot_errno_disarm(handler->sigfd);
614
615 return ret;
616 }
617
618 void lxc_put_handler(struct lxc_handler *handler)
619 {
620 close_prot_errno_disarm(handler->pinfd);
621 close_prot_errno_disarm(handler->pidfd);
622 close_prot_errno_disarm(handler->sigfd);
623 lxc_put_nsfds(handler);
624 if (handler->conf && handler->conf->reboot == REBOOT_NONE)
625 close_prot_errno_disarm(handler->conf->maincmd_fd);
626 close_prot_errno_disarm(handler->monitor_status_fd);
627 close_prot_errno_disarm(handler->state_socket_pair[0]);
628 close_prot_errno_disarm(handler->state_socket_pair[1]);
629 cgroup_exit(handler->cgroup_ops);
630 if (handler->conf && handler->conf->reboot == REBOOT_NONE)
631 free_disarm(handler);
632 else
633 handler->conf = NULL;
634 }
635
636 struct lxc_handler *lxc_init_handler(struct lxc_handler *old,
637 const char *name, struct lxc_conf *conf,
638 const char *lxcpath, bool daemonize)
639 {
640 int nr_keep_fds = 0;
641 int ret;
642 struct lxc_handler *handler;
643
644 if (!old)
645 handler = zalloc(sizeof(*handler));
646 else
647 handler = old;
648 if (!handler)
649 return NULL;
650
651 /* Note that am_guest_unpriv() checks the effective uid. We
652 * probably don't care if we are real root only if we are running
653 * as root so this should be fine.
654 */
655 handler->am_root = !am_guest_unpriv();
656 handler->conf = conf;
657 handler->lxcpath = lxcpath;
658 handler->init_died = false;
659 handler->data_sock[0] = -EBADF;
660 handler->data_sock[1] = -EBADF;
661 handler->monitor_status_fd = -EBADF;
662 handler->pinfd = -EBADF;
663 handler->pidfd = -EBADF;
664 handler->sigfd = -EBADF;
665 handler->state_socket_pair[0] = -EBADF;
666 handler->state_socket_pair[1] = -EBADF;
667 if (handler->conf->reboot == REBOOT_NONE)
668 lxc_list_init(&handler->conf->state_clients);
669
670 for (int i = 0; i < LXC_NS_MAX; i++)
671 handler->nsfd[i] = -EBADF;
672
673 handler->name = name;
674 if (daemonize)
675 handler->transient_pid = lxc_raw_getpid();
676 else
677 handler->transient_pid = -1;
678
679 if (daemonize && handler->conf->reboot == REBOOT_NONE) {
680 /* Create socketpair() to synchronize on daemonized startup.
681 * When the container reboots we don't need to synchronize
682 * again currently so don't open another socketpair().
683 */
684 ret = socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
685 handler->state_socket_pair);
686 if (ret < 0) {
687 ERROR("Failed to create anonymous pair of unix sockets");
688 goto on_error;
689 }
690
691 TRACE("Created anonymous pair {%d,%d} of unix sockets",
692 handler->state_socket_pair[0],
693 handler->state_socket_pair[1]);
694 handler->keep_fds[nr_keep_fds++] = handler->state_socket_pair[0];
695 handler->keep_fds[nr_keep_fds++] = handler->state_socket_pair[1];
696 }
697
698 if (handler->conf->reboot == REBOOT_NONE) {
699 handler->conf->maincmd_fd = lxc_cmd_init(name, lxcpath, "command");
700 if (handler->conf->maincmd_fd < 0) {
701 ERROR("Failed to set up command socket");
702 goto on_error;
703 }
704 handler->keep_fds[nr_keep_fds++] = handler->conf->maincmd_fd;
705 }
706
707 TRACE("Unix domain socket %d for command server is ready",
708 handler->conf->maincmd_fd);
709
710 return handler;
711
712 on_error:
713 lxc_put_handler(handler);
714
715 return NULL;
716 }
717
718 int lxc_init(const char *name, struct lxc_handler *handler)
719 {
720 __do_close int status_fd = -EBADF;
721 int ret;
722 const char *loglevel;
723 struct lxc_conf *conf = handler->conf;
724
725 handler->monitor_pid = lxc_raw_getpid();
726 status_fd = open("/proc/self/status", O_RDONLY | O_CLOEXEC);
727 if (status_fd < 0)
728 return log_error_errno(-1, errno, "Failed to open monitor status fd");
729
730 lsm_init();
731 TRACE("Initialized LSM");
732
733 /* Begin by setting the state to STARTING. */
734 ret = lxc_set_state(name, handler, STARTING);
735 if (ret < 0)
736 return log_error(-1, "Failed to set state to \"%s\"", lxc_state2str(STARTING));
737 TRACE("Set container state to \"STARTING\"");
738
739 /* Start of environment variable setup for hooks. */
740 ret = setenv("LXC_NAME", name, 1);
741 if (ret < 0)
742 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name);
743
744 if (conf->rcfile) {
745 ret = setenv("LXC_CONFIG_FILE", conf->rcfile, 1);
746 if (ret < 0)
747 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s", conf->rcfile);
748 }
749
750 if (conf->rootfs.mount) {
751 ret = setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1);
752 if (ret < 0)
753 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s", conf->rootfs.mount);
754 }
755
756 if (conf->rootfs.path) {
757 ret = setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1);
758 if (ret < 0)
759 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s", conf->rootfs.path);
760 }
761
762 if (conf->console.path) {
763 ret = setenv("LXC_CONSOLE", conf->console.path, 1);
764 if (ret < 0)
765 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s", conf->console.path);
766 }
767
768 if (conf->console.log_path) {
769 ret = setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1);
770 if (ret < 0)
771 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s", conf->console.log_path);
772 }
773
774 if (cgns_supported()) {
775 ret = setenv("LXC_CGNS_AWARE", "1", 1);
776 if (ret < 0)
777 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1");
778 }
779
780 loglevel = lxc_log_priority_to_string(lxc_log_get_level());
781 ret = setenv("LXC_LOG_LEVEL", loglevel, 1);
782 if (ret < 0)
783 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s", loglevel);
784
785 if (conf->hooks_version == 0)
786 ret = setenv("LXC_HOOK_VERSION", "0", 1);
787 else
788 ret = setenv("LXC_HOOK_VERSION", "1", 1);
789 if (ret < 0)
790 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf->hooks_version);
791 /* End of environment variable setup for hooks. */
792
793 TRACE("Set environment variables");
794
795 ret = run_lxc_hooks(name, "pre-start", conf, NULL);
796 if (ret < 0)
797 return log_error(-1, "Failed to run lxc.hook.pre-start for container \"%s\"", name);
798 TRACE("Ran pre-start hooks");
799
800 /* The signal fd has to be created before forking otherwise if the child
801 * process exits before we setup the signal fd, the event will be lost
802 * and the command will be stuck.
803 */
804 handler->sigfd = setup_signal_fd(&handler->oldmask);
805 if (handler->sigfd < 0)
806 return log_error(-1, "Failed to setup SIGCHLD fd handler.");
807 TRACE("Set up signal fd");
808
809 /* Do this after setting up signals since it might unblock SIGWINCH. */
810 ret = lxc_terminal_setup(conf);
811 if (ret < 0) {
812 ERROR("Failed to create console");
813 goto out_restore_sigmask;
814 }
815 TRACE("Created console");
816
817 ret = lxc_terminal_map_ids(conf, &conf->console);
818 if (ret < 0) {
819 ERROR("Failed to chown console");
820 goto out_delete_terminal;
821 }
822 TRACE("Chowned console");
823
824 handler->cgroup_ops = cgroup_init(handler->conf);
825 if (!handler->cgroup_ops) {
826 ERROR("Failed to initialize cgroup driver");
827 goto out_delete_terminal;
828 }
829 TRACE("Initialized cgroup driver");
830
831 ret = lxc_read_seccomp_config(conf);
832 if (ret < 0)
833 return log_error(-1, "Failed loading seccomp policy");
834 TRACE("Read seccomp policy");
835
836 ret = lsm_process_prepare(conf, handler->lxcpath);
837 if (ret < 0) {
838 ERROR("Failed to initialize LSM");
839 goto out_delete_terminal;
840 }
841 TRACE("Initialized LSM");
842
843 INFO("Container \"%s\" is initialized", name);
844 handler->monitor_status_fd = move_fd(status_fd);
845 return 0;
846
847 out_delete_terminal:
848 lxc_terminal_delete(&handler->conf->console);
849
850 out_restore_sigmask:
851 (void)pthread_sigmask(SIG_SETMASK, &handler->oldmask, NULL);
852
853 return -1;
854 }
855
856 void lxc_end(struct lxc_handler *handler)
857 {
858 int ret;
859 pid_t self;
860 struct lxc_list *cur, *next;
861 char *namespaces[LXC_NS_MAX + 1];
862 size_t namespace_count = 0;
863 const char *name = handler->name;
864 struct cgroup_ops *cgroup_ops = handler->cgroup_ops;
865
866 /* The STOPPING state is there for future cleanup code which can take
867 * awhile.
868 */
869 lxc_set_state(name, handler, STOPPING);
870
871 self = lxc_raw_getpid();
872 for (int i = 0; i < LXC_NS_MAX; i++) {
873 if (handler->nsfd[i] < 0)
874 continue;
875
876 if (handler->conf->hooks_version == 0)
877 ret = asprintf(&namespaces[namespace_count],
878 "%s:/proc/%d/fd/%d", ns_info[i].proc_name,
879 self, handler->nsfd[i]);
880 else
881 ret = asprintf(&namespaces[namespace_count],
882 "/proc/%d/fd/%d", self, handler->nsfd[i]);
883 if (ret < 0) {
884 SYSERROR("Failed to allocate memory");
885 break;
886 }
887
888 if (handler->conf->hooks_version == 0) {
889 namespace_count++;
890 continue;
891 }
892
893 ret = setenv(ns_info[i].env_name, namespaces[namespace_count], 1);
894 if (ret < 0)
895 SYSERROR("Failed to set environment variable %s=%s",
896 ns_info[i].env_name, namespaces[namespace_count]);
897 else
898 TRACE("Set environment variable %s=%s",
899 ns_info[i].env_name, namespaces[namespace_count]);
900
901 namespace_count++;
902 }
903 namespaces[namespace_count] = NULL;
904
905 if (handler->conf->reboot > REBOOT_NONE) {
906 ret = setenv("LXC_TARGET", "reboot", 1);
907 if (ret < 0)
908 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot");
909 }
910
911 if (handler->conf->reboot == REBOOT_NONE) {
912 ret = setenv("LXC_TARGET", "stop", 1);
913 if (ret < 0)
914 SYSERROR("Failed to set environment variable: LXC_TARGET=stop");
915 }
916
917 if (handler->conf->hooks_version == 0)
918 ret = run_lxc_hooks(name, "stop", handler->conf, namespaces);
919 else
920 ret = run_lxc_hooks(name, "stop", handler->conf, NULL);
921 if (ret < 0)
922 ERROR("Failed to run \"lxc.hook.stop\" hook");
923
924 while (namespace_count--)
925 free(namespaces[namespace_count]);
926
927 lsm_process_cleanup(handler->conf, handler->lxcpath);
928
929 if (cgroup_ops) {
930 cgroup_ops->payload_destroy(cgroup_ops, handler);
931 cgroup_ops->monitor_destroy(cgroup_ops, handler);
932 }
933
934 if (handler->conf->reboot == REBOOT_NONE) {
935 /* For all new state clients simply close the command socket.
936 * This will inform all state clients that the container is
937 * STOPPED and also prevents a race between a open()/close() on
938 * the command socket causing a new process to get ECONNREFUSED
939 * because we haven't yet closed the command socket.
940 */
941 close_prot_errno_disarm(handler->conf->maincmd_fd);
942 TRACE("Closed command socket");
943
944 /* This function will try to connect to the legacy lxc-monitord
945 * state server and only exists for backwards compatibility.
946 */
947 lxc_monitor_send_state(name, STOPPED, handler->lxcpath);
948
949 /* The command socket is closed so no one can acces the command
950 * socket anymore so there's no need to lock it.
951 */
952 handler->state = STOPPED;
953 TRACE("Set container state to \"STOPPED\"");
954 } else {
955 lxc_set_state(name, handler, STOPPED);
956 TRACE("Set container state to \"STOPPED\"");
957 }
958
959 /* Avoid lingering namespace references. */
960 lxc_put_nsfds(handler);
961
962 ret = run_lxc_hooks(name, "post-stop", handler->conf, NULL);
963 if (ret < 0) {
964 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name);
965 if (handler->conf->reboot > REBOOT_NONE) {
966 WARN("Container will be stopped instead of rebooted");
967 handler->conf->reboot = REBOOT_NONE;
968
969 ret = setenv("LXC_TARGET", "stop", 1);
970 if (ret < 0)
971 WARN("Failed to set environment variable: LXC_TARGET=stop");
972 }
973 }
974
975 /* Reset mask set by setup_signal_fd. */
976 ret = pthread_sigmask(SIG_SETMASK, &handler->oldmask, NULL);
977 if (ret < 0)
978 SYSWARN("Failed to restore signal mask");
979
980 lxc_terminal_delete(&handler->conf->console);
981 lxc_delete_tty(&handler->conf->ttys);
982
983 /* The command socket is now closed, no more state clients can register
984 * themselves from now on. So free the list of state clients.
985 */
986 lxc_list_for_each_safe(cur, &handler->conf->state_clients, next) {
987 struct lxc_state_client *client = cur->elem;
988
989 /* Keep state clients that want to be notified about reboots. */
990 if ((handler->conf->reboot > REBOOT_NONE) &&
991 (client->states[RUNNING] == 2))
992 continue;
993
994 /* close state client socket */
995 lxc_list_del(cur);
996 close(client->clientfd);
997 free(cur->elem);
998 free(cur);
999 }
1000
1001 if (handler->conf->ephemeral == 1 && handler->conf->reboot != REBOOT_REQ)
1002 lxc_destroy_container_on_signal(handler, name);
1003
1004 lxc_put_handler(handler);
1005 }
1006
1007 void lxc_abort(struct lxc_handler *handler)
1008 {
1009 int ret = 0;
1010 int status;
1011
1012 lxc_set_state(handler->name, handler, ABORTING);
1013
1014 if (handler->pidfd >= 0) {
1015 ret = lxc_raw_pidfd_send_signal(handler->pidfd, SIGKILL, NULL, 0);
1016 if (ret)
1017 SYSWARN("Failed to send SIGKILL via pidfd %d for process %d",
1018 handler->pidfd, handler->pid);
1019 }
1020
1021 if ((!ret || errno != ESRCH) && handler->pid > 0)
1022 if (kill(handler->pid, SIGKILL))
1023 SYSWARN("Failed to send SIGKILL to %d", handler->pid);
1024
1025 do {
1026 ret = waitpid(-1, &status, 0);
1027 } while (ret > 0);
1028 }
1029
1030 static int do_start(void *data)
1031 {
1032 struct lxc_handler *handler = data;
1033 __lxc_unused __do_close int data_sock0 = handler->data_sock[0],
1034 data_sock1 = handler->data_sock[1];
1035 __do_close int devnull_fd = -EBADF, status_fd = -EBADF;
1036 int ret;
1037 uid_t new_uid;
1038 gid_t new_gid;
1039 struct lxc_list *iterator;
1040 uid_t nsuid = 0;
1041 gid_t nsgid = 0;
1042
1043 lxc_sync_fini_parent(handler);
1044
1045 if (lxc_abstract_unix_recv_fds(data_sock1, &status_fd, 1, NULL, 0) < 0) {
1046 ERROR("Failed to receive status file descriptor to child process");
1047 goto out_warn_father;
1048 }
1049
1050 /* This prctl must be before the synchro, so if the parent dies before
1051 * we set the parent death signal, we will detect its death with the
1052 * synchro right after, otherwise we have a window where the parent can
1053 * exit before we set the pdeath signal leading to a unsupervized
1054 * container.
1055 */
1056 ret = lxc_set_death_signal(SIGKILL, handler->monitor_pid, status_fd);
1057 if (ret < 0) {
1058 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1059 goto out_warn_father;
1060 }
1061
1062 ret = lxc_ambient_caps_up();
1063 if (ret < 0) {
1064 ERROR("Failed to raise ambient capabilities");
1065 goto out_warn_father;
1066 }
1067
1068 ret = pthread_sigmask(SIG_SETMASK, &handler->oldmask, NULL);
1069 if (ret < 0) {
1070 SYSERROR("Failed to set signal mask");
1071 goto out_warn_father;
1072 }
1073
1074 /* Don't leak the pinfd to the container. */
1075 close_prot_errno_disarm(handler->pinfd);
1076
1077 ret = lxc_sync_wait_parent(handler, LXC_SYNC_STARTUP);
1078 if (ret < 0)
1079 goto out_warn_father;
1080
1081 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1082 * https://github.com/lxc/lxd/issues/1978.
1083 */
1084 if (handler->ns_unshare_flags & CLONE_NEWNET) {
1085 ret = unshare(CLONE_NEWNET);
1086 if (ret < 0) {
1087 SYSERROR("Failed to unshare CLONE_NEWNET");
1088 goto out_warn_father;
1089 }
1090 INFO("Unshared CLONE_NEWNET");
1091 }
1092
1093 /* Tell the parent task it can begin to configure the container and wait
1094 * for it to finish.
1095 */
1096 ret = lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE);
1097 if (ret < 0)
1098 goto out_error;
1099
1100 if (handler->ns_clone_flags & CLONE_NEWNET) {
1101 ret = lxc_network_recv_from_parent(handler);
1102 if (ret < 0) {
1103 ERROR("Failed to receive veth names from parent");
1104 goto out_warn_father;
1105 }
1106 }
1107
1108 /* If we are in a new user namespace, become root there to have
1109 * privilege over our namespace.
1110 */
1111 if (!lxc_list_empty(&handler->conf->id_map)) {
1112 if (!handler->conf->root_nsuid_map)
1113 nsuid = handler->conf->init_uid;
1114
1115 if (!handler->conf->root_nsgid_map)
1116 nsgid = handler->conf->init_gid;
1117
1118 /* Drop groups only after we switched to a valid gid in the new
1119 * user namespace.
1120 */
1121 if (!lxc_setgroups(0, NULL) &&
1122 (handler->am_root || errno != EPERM))
1123 goto out_warn_father;
1124
1125 if (!lxc_switch_uid_gid(nsuid, nsgid))
1126 goto out_warn_father;
1127
1128 ret = prctl(PR_SET_DUMPABLE, prctl_arg(1), prctl_arg(0),
1129 prctl_arg(0), prctl_arg(0));
1130 if (ret < 0)
1131 goto out_warn_father;
1132
1133 /* set{g,u}id() clears deathsignal */
1134 ret = lxc_set_death_signal(SIGKILL, handler->monitor_pid, status_fd);
1135 if (ret < 0) {
1136 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1137 goto out_warn_father;
1138 }
1139 }
1140
1141 ret = access(handler->lxcpath, X_OK);
1142 if (ret != 0) {
1143 print_top_failing_dir(handler->lxcpath);
1144 goto out_warn_father;
1145 }
1146
1147 /* In order to checkpoint restore, we need to have everything in the
1148 * same mount namespace. However, some containers may not have a
1149 * reasonable /dev (in particular, they may not have /dev/null), so we
1150 * can't set init's std fds to /dev/null by opening it from inside the
1151 * container.
1152 *
1153 * If that's the case, fall back to using the host's /dev/null. This
1154 * means that migration won't work, but at least we won't spew output
1155 * where it isn't wanted.
1156 */
1157 if (handler->daemonize && !handler->conf->autodev) {
1158 char path[PATH_MAX];
1159
1160 ret = snprintf(path, sizeof(path), "%s/dev/null",
1161 handler->conf->rootfs.mount);
1162 if (ret < 0 || ret >= sizeof(path))
1163 goto out_warn_father;
1164
1165 ret = access(path, F_OK);
1166 if (ret != 0) {
1167 devnull_fd = open_devnull();
1168
1169 if (devnull_fd < 0)
1170 goto out_warn_father;
1171 WARN("Using /dev/null from the host for container init's standard file descriptors. Migration will not work");
1172 }
1173 }
1174
1175 /* Ask father to setup cgroups and wait for him to finish. */
1176 ret = lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP);
1177 if (ret < 0)
1178 goto out_error;
1179
1180 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1181 * earlier we end up with a wrong view of /proc/self/cgroup. For
1182 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1183 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1184 * /proc/self/cgroup would show us:
1185 *
1186 * 8:cpuset:/lxc/c
1187 *
1188 * whereas it should actually show
1189 *
1190 * 8:cpuset:/
1191 */
1192 if (handler->ns_unshare_flags & CLONE_NEWCGROUP) {
1193 ret = unshare(CLONE_NEWCGROUP);
1194 if (ret < 0) {
1195 if (errno != EINVAL) {
1196 SYSERROR("Failed to unshare CLONE_NEWCGROUP");
1197 goto out_warn_father;
1198 }
1199
1200 handler->ns_clone_flags &= ~CLONE_NEWCGROUP;
1201 SYSINFO("Kernel does not support CLONE_NEWCGROUP");
1202 } else {
1203 INFO("Unshared CLONE_NEWCGROUP");
1204 }
1205 }
1206
1207 if (handler->ns_unshare_flags & CLONE_NEWTIME) {
1208 ret = unshare(CLONE_NEWTIME);
1209 if (ret < 0) {
1210 if (errno != EINVAL) {
1211 SYSERROR("Failed to unshare CLONE_NEWTIME");
1212 goto out_warn_father;
1213 }
1214
1215 handler->ns_clone_flags &= ~CLONE_NEWTIME;
1216 SYSINFO("Kernel does not support CLONE_NEWTIME");
1217 } else {
1218 __do_close int timens_fd = -EBADF;
1219
1220 INFO("Unshared CLONE_NEWTIME");
1221
1222 if (handler->conf->timens.s_boot)
1223 ret = timens_offset_write(CLOCK_BOOTTIME, handler->conf->timens.s_boot, 0);
1224 else if (handler->conf->timens.ns_boot)
1225 ret = timens_offset_write(CLOCK_BOOTTIME, 0, handler->conf->timens.ns_boot);
1226 if (ret) {
1227 SYSERROR("Failed to write CLONE_BOOTTIME offset");
1228 goto out_warn_father;
1229 }
1230 TRACE("Wrote CLOCK_BOOTTIME offset");
1231
1232 if (handler->conf->timens.s_monotonic)
1233 ret = timens_offset_write(CLOCK_MONOTONIC, handler->conf->timens.s_monotonic, 0);
1234 else if (handler->conf->timens.ns_monotonic)
1235 ret = timens_offset_write(CLOCK_MONOTONIC, 0, handler->conf->timens.ns_monotonic);
1236 if (ret) {
1237 SYSERROR("Failed to write CLONE_MONOTONIC offset");
1238 goto out_warn_father;
1239 }
1240 TRACE("Wrote CLOCK_MONOTONIC offset");
1241
1242 timens_fd = open("/proc/self/ns/time_for_children", O_RDONLY | O_CLOEXEC);
1243 if (timens_fd < 0) {
1244 SYSERROR("Failed to open \"/proc/self/ns/time_for_children\"");
1245 goto out_warn_father;
1246 }
1247
1248 ret = setns(timens_fd, CLONE_NEWTIME);
1249 if (ret) {
1250 SYSERROR("Failed to setns(%d(\"/proc/self/ns/time_for_children\"))", timens_fd);
1251 goto out_warn_father;
1252 }
1253 }
1254 }
1255
1256 /* Add the requested environment variables to the current environment to
1257 * allow them to be used by the various hooks, such as the start hook
1258 * below.
1259 */
1260 lxc_list_for_each(iterator, &handler->conf->environment) {
1261 ret = putenv((char *)iterator->elem);
1262 if (ret < 0) {
1263 SYSERROR("Failed to set environment variable: %s",
1264 (char *)iterator->elem);
1265 goto out_warn_father;
1266 }
1267 }
1268
1269 /* Setup the container, ip, names, utsname, ... */
1270 ret = lxc_setup(handler);
1271 if (ret < 0) {
1272 ERROR("Failed to setup container \"%s\"", handler->name);
1273 goto out_warn_father;
1274 }
1275
1276 /* Set the label to change to when we exec(2) the container's init. */
1277 ret = lsm_process_label_set(NULL, handler->conf, true);
1278 if (ret < 0)
1279 goto out_warn_father;
1280
1281 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1282 * before we aren't allowed anymore.
1283 */
1284 if (handler->conf->no_new_privs) {
1285 ret = prctl(PR_SET_NO_NEW_PRIVS, prctl_arg(1), prctl_arg(0),
1286 prctl_arg(0), prctl_arg(0));
1287 if (ret < 0) {
1288 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges");
1289 goto out_warn_father;
1290 }
1291 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges");
1292 }
1293
1294 /* Some init's such as busybox will set sane tty settings on stdin,
1295 * stdout, stderr which it thinks is the console. We already set them
1296 * the way we wanted on the real terminal, and we want init to do its
1297 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
1298 * make sure that that pty is stdin,stdout,stderr.
1299 */
1300 if (handler->conf->console.pty >= 0) {
1301 if (handler->daemonize || !handler->conf->is_execute)
1302 ret = set_stdfds(handler->conf->console.pty);
1303 else
1304 ret = lxc_terminal_set_stdfds(handler->conf->console.pty);
1305 if (ret < 0) {
1306 ERROR("Failed to redirect std{in,out,err} to pty file descriptor %d",
1307 handler->conf->console.pty);
1308 goto out_warn_father;
1309 }
1310 }
1311
1312 /* If we mounted a temporary proc, then unmount it now. */
1313 tmp_proc_unmount(handler->conf);
1314
1315 ret = lxc_seccomp_load(handler->conf);
1316 if (ret < 0)
1317 goto out_warn_father;
1318
1319 ret = lxc_seccomp_send_notifier_fd(&handler->conf->seccomp, data_sock0);
1320 if (ret < 0) {
1321 SYSERROR("Failed to send seccomp notify fd to parent");
1322 goto out_warn_father;
1323 }
1324
1325 ret = run_lxc_hooks(handler->name, "start", handler->conf, NULL);
1326 if (ret < 0) {
1327 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1328 handler->name);
1329 goto out_warn_father;
1330 }
1331
1332 close_prot_errno_disarm(handler->sigfd);
1333
1334 if (handler->conf->console.pty < 0 && handler->daemonize) {
1335 if (devnull_fd < 0) {
1336 devnull_fd = open_devnull();
1337 if (devnull_fd < 0)
1338 goto out_warn_father;
1339 }
1340
1341 ret = set_stdfds(devnull_fd);
1342 if (ret < 0) {
1343 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
1344 goto out_warn_father;
1345 }
1346 }
1347
1348 close_prot_errno_disarm(devnull_fd);
1349
1350 setsid();
1351
1352 if (handler->conf->init_cwd) {
1353 ret = chdir(handler->conf->init_cwd);
1354 if (ret < 0) {
1355 SYSERROR("Could not change directory to \"%s\"",
1356 handler->conf->init_cwd);
1357 goto out_warn_father;
1358 }
1359 }
1360
1361 ret = lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP_LIMITS);
1362 if (ret < 0)
1363 goto out_warn_father;
1364
1365 /* Reset the environment variables the user requested in a clear
1366 * environment.
1367 */
1368 ret = clearenv();
1369 /* Don't error out though. */
1370 if (ret < 0)
1371 SYSERROR("Failed to clear environment.");
1372
1373 lxc_list_for_each(iterator, &handler->conf->environment) {
1374 ret = putenv((char *)iterator->elem);
1375 if (ret < 0) {
1376 SYSERROR("Failed to set environment variable: %s",
1377 (char *)iterator->elem);
1378 goto out_warn_father;
1379 }
1380 }
1381
1382 ret = putenv("container=lxc");
1383 if (ret < 0) {
1384 SYSERROR("Failed to set environment variable: container=lxc");
1385 goto out_warn_father;
1386 }
1387
1388 if (handler->conf->ttys.tty_names) {
1389 ret = putenv(handler->conf->ttys.tty_names);
1390 if (ret < 0) {
1391 SYSERROR("Failed to set environment variable for container ptys");
1392 goto out_warn_father;
1393 }
1394 }
1395
1396 /* The container has been setup. We can now switch to an unprivileged
1397 * uid/gid.
1398 */
1399 new_uid = handler->conf->init_uid;
1400 new_gid = handler->conf->init_gid;
1401
1402 /* Avoid unnecessary syscalls. */
1403 if (new_uid == nsuid)
1404 new_uid = LXC_INVALID_UID;
1405
1406 if (new_gid == nsgid)
1407 new_gid = LXC_INVALID_GID;
1408
1409 /* Make sure that the processes STDIO is correctly owned by the user that we are switching to */
1410 ret = fix_stdio_permissions(new_uid);
1411 if (ret)
1412 WARN("Failed to ajust stdio permissions");
1413
1414 /* If we are in a new user namespace we already dropped all groups when
1415 * we switched to root in the new user namespace further above. Only
1416 * drop groups if we can, so ensure that we have necessary privilege.
1417 */
1418 if (lxc_list_empty(&handler->conf->id_map))
1419 #if HAVE_LIBCAP
1420 if (lxc_proc_cap_is_set(CAP_SETGID, CAP_EFFECTIVE))
1421 #endif
1422 if (!lxc_setgroups(0, NULL))
1423 goto out_warn_father;
1424
1425 if (!lxc_switch_uid_gid(new_uid, new_gid))
1426 goto out_warn_father;
1427
1428 ret = lxc_ambient_caps_down();
1429 if (ret < 0) {
1430 ERROR("Failed to clear ambient capabilities");
1431 goto out_warn_father;
1432 }
1433
1434 if (handler->conf->monitor_signal_pdeath != SIGKILL) {
1435 ret = lxc_set_death_signal(handler->conf->monitor_signal_pdeath,
1436 handler->monitor_pid, status_fd);
1437 if (ret < 0) {
1438 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1439 handler->conf->monitor_signal_pdeath);
1440 goto out_warn_father;
1441 }
1442 }
1443
1444 /*
1445 * After this call, we are in error because this ops should not return
1446 * as it execs.
1447 */
1448 handler->ops->start(handler, handler->data);
1449
1450 out_warn_father:
1451 /*
1452 * We want the parent to know something went wrong, so we return a
1453 * special error code.
1454 */
1455 lxc_sync_wake_parent(handler, LXC_SYNC_ERROR);
1456
1457 out_error:
1458 return -1;
1459 }
1460
1461 static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
1462 {
1463 int i;
1464 struct lxc_terminal_info *tty;
1465 int ret = -1;
1466 int sock = handler->data_sock[1];
1467 struct lxc_conf *conf = handler->conf;
1468 struct lxc_tty_info *ttys = &conf->ttys;
1469
1470 if (!conf->ttys.max)
1471 return 0;
1472
1473 ttys->tty = malloc(sizeof(*ttys->tty) * ttys->max);
1474 if (!ttys->tty)
1475 return -1;
1476
1477 for (i = 0; i < conf->ttys.max; i++) {
1478 int ttyfds[2];
1479
1480 ret = lxc_abstract_unix_recv_fds(sock, ttyfds, 2, NULL, 0);
1481 if (ret < 0)
1482 break;
1483
1484 tty = &ttys->tty[i];
1485 tty->busy = -1;
1486 tty->ptx = ttyfds[0];
1487 tty->pty = ttyfds[1];
1488 TRACE("Received pty with ptx fd %d and pty fd %d from child", tty->ptx, tty->pty);
1489 }
1490
1491 if (ret < 0)
1492 SYSERROR("Failed to receive %zu ttys from child", ttys->max);
1493 else
1494 TRACE("Received %zu ttys from child", ttys->max);
1495
1496 return ret;
1497 }
1498
1499 int resolve_clone_flags(struct lxc_handler *handler)
1500 {
1501 int i;
1502 struct lxc_conf *conf = handler->conf;
1503 bool wants_timens = conf->timens.s_boot || conf->timens.ns_boot ||
1504 conf->timens.s_monotonic || conf->timens.ns_monotonic;
1505
1506 for (i = 0; i < LXC_NS_MAX; i++) {
1507 if (conf->ns_keep) {
1508 if (!(conf->ns_keep & ns_info[i].clone_flag))
1509 handler->ns_clone_flags |= ns_info[i].clone_flag;
1510 } else if (conf->ns_clone) {
1511 if ((conf->ns_clone & ns_info[i].clone_flag))
1512 handler->ns_clone_flags |= ns_info[i].clone_flag;
1513 } else {
1514 if (i == LXC_NS_USER && lxc_list_empty(&handler->conf->id_map))
1515 continue;
1516
1517 if (i == LXC_NS_NET && lxc_requests_empty_network(handler))
1518 continue;
1519
1520 if (i == LXC_NS_CGROUP && !cgns_supported())
1521 continue;
1522
1523 if (i == LXC_NS_TIME && !wants_timens)
1524 continue;
1525
1526 handler->ns_clone_flags |= ns_info[i].clone_flag;
1527 }
1528
1529 if (!conf->ns_share[i])
1530 continue;
1531
1532 handler->ns_clone_flags &= ~ns_info[i].clone_flag;
1533 TRACE("Sharing %s namespace", ns_info[i].proc_name);
1534 }
1535
1536 if (wants_timens && (conf->ns_keep & ns_info[LXC_NS_TIME].clone_flag))
1537 return log_trace_errno(-1, EINVAL, "Requested to keep time namespace while also specifying offsets");
1538
1539 /* Deal with namespaces that are unshared. */
1540 if (handler->ns_clone_flags & CLONE_NEWTIME)
1541 handler->ns_unshare_flags |= CLONE_NEWTIME;
1542
1543 if (!pure_unified_layout(handler->cgroup_ops) && handler->ns_clone_flags & CLONE_NEWCGROUP)
1544 handler->ns_unshare_flags |= CLONE_NEWCGROUP;
1545
1546 if ((handler->ns_clone_flags & (CLONE_NEWNET | CLONE_NEWUSER)) ==
1547 (CLONE_NEWNET | CLONE_NEWUSER))
1548 handler->ns_unshare_flags |= CLONE_NEWNET;
1549
1550 /* Deal with namespaces that are spawned. */
1551 handler->ns_on_clone_flags = handler->ns_clone_flags & ~handler->ns_unshare_flags;
1552
1553 handler->clone_flags = handler->ns_on_clone_flags | CLONE_PIDFD;
1554
1555 return 0;
1556 }
1557
1558 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1559 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1560 * But since the memory between parent and child is shared on CLONE_VM this
1561 * would invalidate the getpid() cache that glibc used to maintain and so
1562 * getpid() in the child would return the parent's pid. This is all fixed in
1563 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1564 * not reset anymore.
1565 * However, if for whatever reason you - dear committer - somehow need to get the
1566 * pid of the dummy intermediate process for do_share_ns() you need to call
1567 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1568 * will be fine.
1569 */
1570 static inline int do_share_ns(void *arg)
1571 {
1572 int i, flags, ret;
1573 struct lxc_handler *handler = arg;
1574
1575 for (i = 0; i < LXC_NS_MAX; i++) {
1576 if (handler->nsfd[i] < 0)
1577 continue;
1578
1579 ret = setns(handler->nsfd[i], 0);
1580 if (ret < 0) {
1581 /*
1582 * Note that joining a user and/or mount namespace
1583 * requires the process is not multithreaded otherwise
1584 * setns() will fail here.
1585 */
1586 SYSERROR("Failed to inherit %s namespace",
1587 ns_info[i].proc_name);
1588 return -1;
1589 }
1590
1591 DEBUG("Inherited %s namespace", ns_info[i].proc_name);
1592 }
1593
1594 flags = handler->ns_on_clone_flags;
1595 flags |= CLONE_PARENT;
1596 handler->pid = lxc_raw_clone_cb(do_start, handler, CLONE_PIDFD | flags,
1597 &handler->pidfd);
1598 if (handler->pid < 0)
1599 return -1;
1600
1601 return 0;
1602 }
1603
1604 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1605 * exec()s the requested container binary.
1606 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1607 * right here should be double checked if they'd pose a security risk. (For
1608 * example, any {u}mount() operations performed here will be reflected on the
1609 * host!)
1610 */
1611 static int lxc_spawn(struct lxc_handler *handler)
1612 {
1613 __do_close int data_sock0 = -EBADF, data_sock1 = -EBADF;
1614 int i, ret;
1615 char pidstr[20];
1616 bool wants_to_map_ids;
1617 struct lxc_list *id_map;
1618 const char *name = handler->name;
1619 const char *lxcpath = handler->lxcpath;
1620 bool share_ns = false;
1621 struct lxc_conf *conf = handler->conf;
1622 struct cgroup_ops *cgroup_ops = handler->cgroup_ops;
1623
1624 id_map = &conf->id_map;
1625 wants_to_map_ids = !lxc_list_empty(id_map);
1626
1627 for (i = 0; i < LXC_NS_MAX; i++) {
1628 if (!conf->ns_share[i])
1629 continue;
1630
1631 handler->nsfd[i] = lxc_inherit_namespace(conf->ns_share[i], lxcpath, ns_info[i].proc_name);
1632 if (handler->nsfd[i] < 0)
1633 return -1;
1634
1635 share_ns = true;
1636 }
1637
1638 ret = lxc_sync_init(handler);
1639 if (ret < 0)
1640 return -1;
1641
1642 ret = socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
1643 handler->data_sock);
1644 if (ret < 0)
1645 goto out_sync_fini;
1646 data_sock0 = handler->data_sock[0];
1647 data_sock1 = handler->data_sock[1];
1648
1649 ret = resolve_clone_flags(handler);
1650 if (ret < 0)
1651 goto out_sync_fini;
1652
1653 if (handler->ns_clone_flags & CLONE_NEWNET) {
1654 ret = lxc_find_gateway_addresses(handler);
1655 if (ret) {
1656 ERROR("Failed to find gateway addresses");
1657 goto out_sync_fini;
1658 }
1659 }
1660
1661 if (!cgroup_ops->payload_create(cgroup_ops, handler)) {
1662 ERROR("Failed creating cgroups");
1663 goto out_delete_net;
1664 }
1665
1666 /* If the rootfs is not a blockdev, prevent the container from marking
1667 * it readonly.
1668 * If the container is unprivileged then skip rootfs pinning.
1669 */
1670 if (!wants_to_map_ids) {
1671 handler->pinfd = pin_rootfs(conf->rootfs.path);
1672 if (handler->pinfd == -EBADF)
1673 INFO("Failed to pin the rootfs for container \"%s\"", handler->name);
1674 }
1675
1676 /* Create a process in a new set of namespaces. */
1677 if (share_ns) {
1678 pid_t attacher_pid;
1679
1680 attacher_pid = lxc_clone(do_share_ns, handler,
1681 CLONE_VFORK | CLONE_VM | CLONE_FILES, NULL);
1682 if (attacher_pid < 0) {
1683 SYSERROR(LXC_CLONE_ERROR);
1684 goto out_delete_net;
1685 }
1686
1687 ret = wait_for_pid(attacher_pid);
1688 if (ret < 0) {
1689 SYSERROR("Intermediate process failed");
1690 goto out_delete_net;
1691 }
1692
1693 if (handler->pid < 0) {
1694 SYSERROR(LXC_CLONE_ERROR);
1695 goto out_delete_net;
1696 }
1697 } else {
1698 int cgroup_fd = -EBADF;
1699
1700 struct lxc_clone_args clone_args = {
1701 .flags = handler->clone_flags,
1702 .pidfd = ptr_to_u64(&handler->pidfd),
1703 .exit_signal = SIGCHLD,
1704 };
1705
1706 if (handler->ns_clone_flags & CLONE_NEWCGROUP) {
1707 cgroup_fd = cgroup_unified_fd(cgroup_ops);
1708 if (cgroup_fd >= 0) {
1709 handler->clone_flags |= CLONE_INTO_CGROUP;
1710 clone_args.flags |= CLONE_INTO_CGROUP;
1711 clone_args.cgroup = cgroup_fd;
1712 }
1713 }
1714
1715 /* Try to spawn directly into target cgroup. */
1716 handler->pid = lxc_clone3(&clone_args, CLONE_ARGS_SIZE_VER2);
1717 if (handler->pid < 0) {
1718 SYSTRACE("Failed to spawn container directly into target cgroup");
1719
1720 /* Kernel might simply be too old for CLONE_INTO_CGROUP. */
1721 handler->clone_flags &= ~(CLONE_INTO_CGROUP | CLONE_NEWCGROUP);
1722 handler->ns_on_clone_flags &= ~CLONE_NEWCGROUP;
1723 handler->ns_unshare_flags |= CLONE_NEWCGROUP;
1724
1725 clone_args.flags = handler->clone_flags;
1726
1727 handler->pid = lxc_clone3(&clone_args, CLONE_ARGS_SIZE_VER0);
1728 } else if (cgroup_fd >= 0) {
1729 TRACE("Spawned container directly into target cgroup via cgroup2 fd %d", cgroup_fd);
1730 }
1731
1732 /* Kernel might be too old for clone3(). */
1733 if (handler->pid < 0) {
1734 SYSTRACE("Failed to spawn container via clone3()");
1735 handler->pid = lxc_raw_legacy_clone(handler->clone_flags, &handler->pidfd);
1736 }
1737
1738 if (handler->pid < 0) {
1739 SYSERROR(LXC_CLONE_ERROR);
1740 goto out_delete_net;
1741 }
1742
1743 if (handler->pid == 0) {
1744 (void)do_start(handler);
1745 _exit(EXIT_FAILURE);
1746 }
1747 }
1748 if (handler->pidfd < 0)
1749 handler->clone_flags &= ~CLONE_PIDFD;
1750 TRACE("Cloned child process %d", handler->pid);
1751
1752 /* Verify that we can actually make use of pidfds. */
1753 if (!lxc_can_use_pidfd(handler->pidfd))
1754 close_prot_errno_disarm(handler->pidfd);
1755
1756 ret = snprintf(pidstr, 20, "%d", handler->pid);
1757 if (ret < 0 || ret >= 20)
1758 goto out_delete_net;
1759
1760 ret = setenv("LXC_PID", pidstr, 1);
1761 if (ret < 0)
1762 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr);
1763
1764 for (i = 0; i < LXC_NS_MAX; i++)
1765 if (handler->ns_on_clone_flags & ns_info[i].clone_flag)
1766 INFO("Cloned %s", ns_info[i].flag_name);
1767
1768 if (!lxc_try_preserve_namespaces(handler, handler->ns_on_clone_flags, handler->pid)) {
1769 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1770 goto out_delete_net;
1771 }
1772
1773 lxc_sync_fini_child(handler);
1774
1775 if (lxc_abstract_unix_send_fds(handler->data_sock[0], &handler->monitor_status_fd, 1, NULL, 0) < 0) {
1776 ERROR("Failed to send status file descriptor to child process");
1777 goto out_delete_net;
1778 }
1779 close_prot_errno_disarm(handler->monitor_status_fd);
1780
1781 /* Map the container uids. The container became an invalid userid the
1782 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1783 * anything immediately, but allows the container to setuid(0) (0 being
1784 * mapped to something else on the host.) later to become a valid uid
1785 * again.
1786 */
1787 if (wants_to_map_ids) {
1788 if (!handler->conf->ns_share[LXC_NS_USER] &&
1789 (handler->conf->ns_keep & CLONE_NEWUSER) == 0) {
1790 ret = lxc_map_ids(id_map, handler->pid);
1791 if (ret < 0) {
1792 ERROR("Failed to set up id mapping.");
1793 goto out_delete_net;
1794 }
1795 }
1796 }
1797
1798 ret = lxc_sync_wake_child(handler, LXC_SYNC_STARTUP);
1799 if (ret < 0)
1800 goto out_delete_net;
1801
1802 ret = lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE);
1803 if (ret < 0)
1804 goto out_delete_net;
1805
1806 if (!cgroup_ops->setup_limits_legacy(cgroup_ops, handler->conf, false)) {
1807 ERROR("Failed to setup cgroup limits for container \"%s\"", name);
1808 goto out_delete_net;
1809 }
1810
1811 if (!cgroup_ops->payload_enter(cgroup_ops, handler)) {
1812 ERROR("Failed to enter cgroups");
1813 goto out_delete_net;
1814 }
1815
1816 if (!cgroup_ops->payload_delegate_controllers(cgroup_ops)) {
1817 ERROR("Failed to delegate controllers to payload cgroup");
1818 goto out_delete_net;
1819 }
1820
1821 if (!cgroup_ops->setup_limits(cgroup_ops, handler)) {
1822 ERROR("Failed to setup cgroup limits for container \"%s\"", name);
1823 goto out_delete_net;
1824 }
1825
1826 if (!cgroup_ops->chown(cgroup_ops, handler->conf))
1827 goto out_delete_net;
1828
1829 /* If not done yet, we're now ready to preserve the network namespace */
1830 if (handler->nsfd[LXC_NS_NET] < 0) {
1831 ret = lxc_try_preserve_ns(handler->pid, "net");
1832 if (ret < 0) {
1833 if (ret != -EOPNOTSUPP) {
1834 SYSERROR("Failed to preserve net namespace");
1835 goto out_delete_net;
1836 }
1837 } else {
1838 handler->nsfd[LXC_NS_NET] = ret;
1839 DEBUG("Preserved net namespace via fd %d", ret);
1840 }
1841 }
1842 ret = lxc_netns_set_nsid(handler->nsfd[LXC_NS_NET]);
1843 if (ret < 0)
1844 SYSWARN("Failed to allocate new network namespace id");
1845 else
1846 TRACE("Allocated new network namespace id");
1847
1848 /* Create the network configuration. */
1849 if (handler->ns_clone_flags & CLONE_NEWNET) {
1850 ret = lxc_create_network(handler);
1851 if (ret < 0) {
1852 ERROR("Failed to create the network");
1853 goto out_delete_net;
1854 }
1855
1856 ret = lxc_network_send_to_child(handler);
1857 if (ret < 0) {
1858 ERROR("Failed to send veth names to child");
1859 goto out_delete_net;
1860 }
1861 }
1862
1863 if (!lxc_list_empty(&conf->procs)) {
1864 ret = setup_proc_filesystem(&conf->procs, handler->pid);
1865 if (ret < 0)
1866 goto out_delete_net;
1867 }
1868
1869 /* Tell the child to continue its initialization. We'll get
1870 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1871 */
1872 ret = lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE);
1873 if (ret < 0)
1874 goto out_delete_net;
1875
1876 if (!lxc_list_empty(&conf->limits)) {
1877 ret = setup_resource_limits(&conf->limits, handler->pid);
1878 if (ret < 0) {
1879 ERROR("Failed to setup resource limits");
1880 goto out_delete_net;
1881 }
1882 }
1883
1884 ret = lxc_sync_barrier_child(handler, LXC_SYNC_CGROUP_UNSHARE);
1885 if (ret < 0)
1886 goto out_delete_net;
1887
1888 /*
1889 * with isolation the limiting devices cgroup was already setup, so
1890 * only setup devices here if we have no namespace directory
1891 */
1892 if (!handler->conf->cgroup_meta.namespace_dir &&
1893 !cgroup_ops->setup_limits_legacy(cgroup_ops, handler->conf, true)) {
1894 ERROR("Failed to setup legacy device cgroup controller limits");
1895 goto out_delete_net;
1896 }
1897 TRACE("Set up legacy device cgroup controller limits");
1898
1899 if (!cgroup_ops->devices_activate(cgroup_ops, handler)) {
1900 ERROR("Failed to setup cgroup2 device controller limits");
1901 goto out_delete_net;
1902 }
1903 TRACE("Set up cgroup2 device controller limits");
1904
1905 if (handler->ns_unshare_flags & CLONE_NEWCGROUP) {
1906 /* Now we're ready to preserve the cgroup namespace */
1907 ret = lxc_try_preserve_ns(handler->pid, "cgroup");
1908 if (ret < 0) {
1909 if (ret != -EOPNOTSUPP) {
1910 SYSERROR("Failed to preserve cgroup namespace");
1911 goto out_delete_net;
1912 }
1913 } else {
1914 handler->nsfd[LXC_NS_CGROUP] = ret;
1915 DEBUG("Preserved cgroup namespace via fd %d", ret);
1916 }
1917 }
1918
1919 cgroup_ops->payload_finalize(cgroup_ops);
1920 TRACE("Finished setting up cgroups");
1921
1922 if (handler->ns_unshare_flags & CLONE_NEWTIME) {
1923 /* Now we're ready to preserve the cgroup namespace */
1924 ret = lxc_try_preserve_ns(handler->pid, "time");
1925 if (ret < 0) {
1926 if (ret != -EOPNOTSUPP) {
1927 SYSERROR("Failed to preserve time namespace");
1928 goto out_delete_net;
1929 }
1930 } else {
1931 handler->nsfd[LXC_NS_TIME] = ret;
1932 DEBUG("Preserved time namespace via fd %d", ret);
1933 }
1934 }
1935
1936 /* Run any host-side start hooks */
1937 ret = run_lxc_hooks(name, "start-host", conf, NULL);
1938 if (ret < 0) {
1939 ERROR("Failed to run lxc.hook.start-host");
1940 goto out_delete_net;
1941 }
1942
1943 /* Tell the child to complete its initialization and wait for it to exec
1944 * or return an error. (The child will never return
1945 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1946 * lxc_sync_barrier_child to return success, or return a different
1947 * value, causing us to error out).
1948 */
1949 ret = lxc_sync_barrier_child(handler, LXC_SYNC_READY_START);
1950 if (ret < 0)
1951 goto out_delete_net;
1952
1953 if (handler->ns_clone_flags & CLONE_NEWNET) {
1954 ret = lxc_network_recv_name_and_ifindex_from_child(handler);
1955 if (ret < 0) {
1956 ERROR("Failed to receive names and ifindices for network devices from child");
1957 goto out_delete_net;
1958 }
1959 }
1960
1961 /* Now all networks are created, network devices are moved into place,
1962 * and the correct names and ifindices in the respective namespaces have
1963 * been recorded. The corresponding structs have now all been filled. So
1964 * log them for debugging purposes.
1965 */
1966 lxc_log_configured_netdevs(conf);
1967
1968 /* Read tty fds allocated by child. */
1969 ret = lxc_recv_ttys_from_child(handler);
1970 if (ret < 0) {
1971 ERROR("Failed to receive tty info from child process");
1972 goto out_delete_net;
1973 }
1974
1975 ret = lxc_seccomp_recv_notifier_fd(&handler->conf->seccomp, data_sock1);
1976 if (ret < 0) {
1977 SYSERROR("Failed to receive seccomp notify fd from child");
1978 goto out_delete_net;
1979 }
1980
1981 ret = handler->ops->post_start(handler, handler->data);
1982 if (ret < 0)
1983 goto out_abort;
1984
1985 ret = lxc_set_state(name, handler, RUNNING);
1986 if (ret < 0) {
1987 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING));
1988 goto out_abort;
1989 }
1990
1991 lxc_sync_fini(handler);
1992
1993 return 0;
1994
1995 out_delete_net:
1996 if (handler->ns_clone_flags & CLONE_NEWNET)
1997 lxc_delete_network(handler);
1998
1999 out_abort:
2000 lxc_abort(handler);
2001
2002 out_sync_fini:
2003 lxc_sync_fini(handler);
2004 close_prot_errno_disarm(handler->pinfd);
2005
2006 return -1;
2007 }
2008
2009 int __lxc_start(struct lxc_handler *handler, struct lxc_operations *ops,
2010 void *data, const char *lxcpath, bool daemonize, int *error_num)
2011 {
2012 int ret, status;
2013 const char *name = handler->name;
2014 struct lxc_conf *conf = handler->conf;
2015 struct cgroup_ops *cgroup_ops;
2016
2017 ret = lxc_init(name, handler);
2018 if (ret < 0) {
2019 ERROR("Failed to initialize container \"%s\"", name);
2020 goto out_abort;
2021 }
2022 handler->ops = ops;
2023 handler->data = data;
2024 handler->daemonize = daemonize;
2025 cgroup_ops = handler->cgroup_ops;
2026
2027 if (!attach_block_device(handler->conf)) {
2028 ERROR("Failed to attach block device");
2029 ret = -1;
2030 goto out_abort;
2031 }
2032
2033 if (!cgroup_ops->monitor_create(cgroup_ops, handler)) {
2034 ERROR("Failed to create monitor cgroup");
2035 ret = -1;
2036 goto out_abort;
2037 }
2038
2039 if (!cgroup_ops->monitor_enter(cgroup_ops, handler)) {
2040 ERROR("Failed to enter monitor cgroup");
2041 ret = -1;
2042 goto out_abort;
2043 }
2044
2045 if (!cgroup_ops->monitor_delegate_controllers(cgroup_ops)) {
2046 ERROR("Failed to delegate controllers to monitor cgroup");
2047 ret = -1;
2048 goto out_abort;
2049 }
2050
2051 if (geteuid() == 0 && !lxc_list_empty(&conf->id_map)) {
2052 /* If the backing store is a device, mount it here and now. */
2053 if (rootfs_is_blockdev(conf)) {
2054 ret = unshare(CLONE_NEWNS);
2055 if (ret < 0) {
2056 ERROR("Failed to unshare CLONE_NEWNS");
2057 goto out_abort;
2058 }
2059 INFO("Unshared CLONE_NEWNS");
2060
2061 turn_into_dependent_mounts();
2062 ret = lxc_setup_rootfs_prepare_root(conf, name, lxcpath);
2063 if (ret < 0) {
2064 ERROR("Error setting up rootfs mount as root before spawn");
2065 goto out_abort;
2066 }
2067 INFO("Set up container rootfs as host root");
2068 }
2069 }
2070
2071 ret = lxc_spawn(handler);
2072 if (ret < 0) {
2073 ERROR("Failed to spawn container \"%s\"", name);
2074 goto out_detach_blockdev;
2075 }
2076
2077 handler->conf->reboot = REBOOT_NONE;
2078
2079 ret = lxc_poll(name, handler);
2080 if (ret) {
2081 ERROR("LXC mainloop exited with error: %d", ret);
2082 goto out_delete_network;
2083 }
2084
2085 if (!handler->init_died && handler->pid > 0) {
2086 ERROR("Child process is not killed");
2087 ret = -1;
2088 goto out_delete_network;
2089 }
2090
2091 status = lxc_wait_for_pid_status(handler->pid);
2092 if (status < 0)
2093 SYSERROR("Failed to retrieve status for %d", handler->pid);
2094
2095 /* If the child process exited but was not signaled, it didn't call
2096 * reboot. This should mean it was an lxc-execute which simply exited.
2097 * In any case, treat it as a 'halt'.
2098 */
2099 if (WIFSIGNALED(status)) {
2100 switch(WTERMSIG(status)) {
2101 case SIGINT: /* halt */
2102 DEBUG("Container \"%s\" is halting", name);
2103 break;
2104 case SIGHUP: /* reboot */
2105 DEBUG("Container \"%s\" is rebooting", name);
2106 handler->conf->reboot = REBOOT_REQ;
2107 break;
2108 case SIGSYS: /* seccomp */
2109 DEBUG("Container \"%s\" violated its seccomp policy", name);
2110 break;
2111 default:
2112 DEBUG("Unknown exit status for container \"%s\" init %d", name, WTERMSIG(status));
2113 break;
2114 }
2115 }
2116
2117 ret = lxc_restore_phys_nics_to_netns(handler);
2118 if (ret < 0)
2119 ERROR("Failed to move physical network devices back to parent network namespace");
2120
2121 close_prot_errno_disarm(handler->pinfd);
2122
2123 lxc_monitor_send_exit_code(name, status, handler->lxcpath);
2124 lxc_error_set_and_log(handler->pid, status);
2125 if (error_num)
2126 *error_num = handler->exit_status;
2127
2128 /* These are not the droids you are looking for. */
2129 __private_goto1:
2130 lxc_delete_network(handler);
2131
2132 __private_goto2:
2133 detach_block_device(handler->conf);
2134
2135 __private_goto3:
2136 lxc_end(handler);
2137
2138 return ret;
2139
2140 /* These are the droids you are looking for. */
2141 out_abort:
2142 lxc_abort(handler);
2143 goto __private_goto3;
2144
2145 out_detach_blockdev:
2146 lxc_abort(handler);
2147 goto __private_goto2;
2148
2149 out_delete_network:
2150 lxc_abort(handler);
2151 goto __private_goto1;
2152 }
2153
2154 struct start_args {
2155 char *const *argv;
2156 };
2157
2158 static int start(struct lxc_handler *handler, void* data)
2159 {
2160 struct start_args *arg = data;
2161
2162 NOTICE("Exec'ing \"%s\"", arg->argv[0]);
2163
2164 execvp(arg->argv[0], arg->argv);
2165 SYSERROR("Failed to exec \"%s\"", arg->argv[0]);
2166 return 0;
2167 }
2168
2169 static int post_start(struct lxc_handler *handler, void* data)
2170 {
2171 struct start_args *arg = data;
2172
2173 NOTICE("Started \"%s\" with pid \"%d\"", arg->argv[0], handler->pid);
2174 return 0;
2175 }
2176
2177 static struct lxc_operations start_ops = {
2178 .start = start,
2179 .post_start = post_start
2180 };
2181
2182 int lxc_start(char *const argv[], struct lxc_handler *handler,
2183 const char *lxcpath, bool daemonize, int *error_num)
2184 {
2185 struct start_args start_arg = {
2186 .argv = argv,
2187 };
2188
2189 TRACE("Doing lxc_start");
2190 return __lxc_start(handler, &start_ops, &start_arg, lxcpath, daemonize, error_num);
2191 }
2192
2193 static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
2194 const char *name)
2195 {
2196 char destroy[PATH_MAX];
2197 struct lxc_container *c;
2198 int ret = 0;
2199 bool bret = true;
2200
2201 if (handler->conf->rootfs.path && handler->conf->rootfs.mount) {
2202 bret = do_destroy_container(handler);
2203 if (!bret) {
2204 ERROR("Error destroying rootfs for container \"%s\"", name);
2205 return;
2206 }
2207 }
2208 INFO("Destroyed rootfs for container \"%s\"", name);
2209
2210 ret = snprintf(destroy, PATH_MAX, "%s/%s", handler->lxcpath, name);
2211 if (ret < 0 || ret >= PATH_MAX) {
2212 ERROR("Error destroying directory for container \"%s\"", name);
2213 return;
2214 }
2215
2216 c = lxc_container_new(name, handler->lxcpath);
2217 if (c) {
2218 if (container_disk_lock(c)) {
2219 INFO("Could not update lxc_snapshots file");
2220 lxc_container_put(c);
2221 } else {
2222 mod_all_rdeps(c, false);
2223 container_disk_unlock(c);
2224 lxc_container_put(c);
2225 }
2226 }
2227
2228 if (!handler->am_root)
2229 ret = userns_exec_full(handler->conf, lxc_rmdir_onedev_wrapper,
2230 destroy, "lxc_rmdir_onedev_wrapper");
2231 else
2232 ret = lxc_rmdir_onedev(destroy, NULL);
2233
2234 if (ret < 0) {
2235 ERROR("Error destroying directory for container \"%s\"", name);
2236 return;
2237 }
2238 INFO("Destroyed directory for container \"%s\"", name);
2239 }
2240
2241 static int lxc_rmdir_onedev_wrapper(void *data)
2242 {
2243 char *arg = (char *) data;
2244 return lxc_rmdir_onedev(arg, NULL);
2245 }
2246
2247 static bool do_destroy_container(struct lxc_handler *handler)
2248 {
2249 int ret;
2250
2251 if (!handler->am_root) {
2252 ret = userns_exec_full(handler->conf, storage_destroy_wrapper,
2253 handler->conf, "storage_destroy_wrapper");
2254 if (ret < 0)
2255 return false;
2256
2257 return true;
2258 }
2259
2260 return storage_destroy(handler->conf);
2261 }