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