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