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