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