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