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