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