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