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