]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/start.c
Merge pull request #2092 from lifeng68/modify_console_create
[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;
552
553 if (has_console)
554 ret = lxc_mainloop(&descr_console, 0);
555
556
557 out_mainloop:
558 lxc_mainloop_close(&descr);
559 TRACE("Closed mainloop");
560
561 out_mainloop_console:
562 if (has_console) {
563 lxc_mainloop_close(&descr_console);
564 TRACE("Closed console mainloop");
565 }
566
567 out_sigfd:
568 close(handler->sigfd);
569 TRACE("Closed signal file descriptor %d", handler->sigfd);
570 handler->sigfd = -EBADF;
571
572 return ret;
573 }
574
575 void lxc_zero_handler(struct lxc_handler *handler)
576 {
577 int i;
578
579 memset(handler, 0, sizeof(struct lxc_handler));
580
581 handler->clone_flags = -1;
582
583 handler->pinfd = -1;
584
585 handler->sigfd = -1;
586
587 for (i = 0; i < LXC_NS_MAX; i++)
588 handler->nsfd[i] = -1;
589
590 handler->data_sock[0] = -1;
591 handler->data_sock[1] = -1;
592
593 handler->state_socket_pair[0] = -1;
594 handler->state_socket_pair[1] = -1;
595
596 handler->sync_sock[0] = -1;
597 handler->sync_sock[1] = -1;
598 }
599
600 static void lxc_put_nsfds(struct lxc_handler *handler)
601 {
602 int i;
603
604 for (i = 0; i < LXC_NS_MAX; i++) {
605 if (handler->nsfd[i] < 0)
606 continue;
607
608 close(handler->nsfd[i]);
609 handler->nsfd[i] = -EBADF;
610 }
611 }
612
613 void lxc_free_handler(struct lxc_handler *handler)
614 {
615 if (handler->pinfd >= 0)
616 close(handler->pinfd);
617
618 if (handler->sigfd >= 0)
619 close(handler->sigfd);
620
621 lxc_put_nsfds(handler);
622
623 if (handler->conf && handler->conf->reboot == 0)
624 if (handler->conf->maincmd_fd)
625 close(handler->conf->maincmd_fd);
626
627 if (handler->state_socket_pair[0] >= 0)
628 close(handler->state_socket_pair[0]);
629
630 if (handler->state_socket_pair[1] >= 0)
631 close(handler->state_socket_pair[1]);
632
633 handler->conf = NULL;
634 free(handler);
635 handler = NULL;
636 }
637
638 struct lxc_handler *lxc_init_handler(const char *name, struct lxc_conf *conf,
639 const char *lxcpath, bool daemonize)
640 {
641 int i, ret;
642 struct lxc_handler *handler;
643
644 handler = malloc(sizeof(*handler));
645 if (!handler) {
646 ERROR("failed to allocate memory");
647 return NULL;
648 }
649
650 memset(handler, 0, sizeof(*handler));
651
652 /* Note that am_unpriv() checks the effective uid. We probably don't
653 * care if we are real root only if we are running as root so this
654 * should be fine.
655 */
656 handler->am_root = !am_unpriv();
657 handler->data_sock[0] = handler->data_sock[1] = -1;
658 handler->conf = conf;
659 handler->lxcpath = lxcpath;
660 handler->pinfd = -1;
661 handler->sigfd = -EBADF;
662 handler->init_died = false;
663 handler->state_socket_pair[0] = handler->state_socket_pair[1] = -1;
664 if (handler->conf->reboot == 0)
665 lxc_list_init(&handler->conf->state_clients);
666
667 for (i = 0; i < LXC_NS_MAX; i++)
668 handler->nsfd[i] = -1;
669
670 handler->name = name;
671
672 if (daemonize && !handler->conf->reboot) {
673 /* Create socketpair() to synchronize on daemonized startup.
674 * When the container reboots we don't need to synchronize again
675 * currently so don't open another socketpair().
676 */
677 ret = socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
678 handler->state_socket_pair);
679 if (ret < 0) {
680 ERROR("Failed to create anonymous pair of unix sockets");
681 goto on_error;
682 }
683 TRACE("Created anonymous pair {%d,%d} of unix sockets",
684 handler->state_socket_pair[0],
685 handler->state_socket_pair[1]);
686 }
687
688 if (handler->conf->reboot == 0) {
689 handler->conf->maincmd_fd = lxc_cmd_init(name, lxcpath, "command");
690 if (handler->conf->maincmd_fd < 0) {
691 ERROR("Failed to set up command socket");
692 goto on_error;
693 }
694 }
695 TRACE("Unix domain socket %d for command server is ready",
696 handler->conf->maincmd_fd);
697
698 return handler;
699
700 on_error:
701 lxc_free_handler(handler);
702
703 return NULL;
704 }
705
706 int lxc_init(const char *name, struct lxc_handler *handler)
707 {
708 int ret;
709 const char *loglevel;
710 struct lxc_conf *conf = handler->conf;
711
712 lsm_init();
713 TRACE("initialized LSM");
714
715 if (lxc_read_seccomp_config(conf) != 0) {
716 ERROR("Failed loading seccomp policy.");
717 goto out_close_maincmd_fd;
718 }
719 TRACE("read seccomp policy");
720
721 /* Begin by setting the state to STARTING. */
722 if (lxc_set_state(name, handler, STARTING)) {
723 ERROR("Failed to set state for container \"%s\" to \"%s\".", name, lxc_state2str(STARTING));
724 goto out_close_maincmd_fd;
725 }
726 TRACE("set container state to \"STARTING\"");
727
728 /* Start of environment variable setup for hooks. */
729 if (name && setenv("LXC_NAME", name, 1))
730 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name);
731
732 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
733 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf->rcfile);
734
735 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1))
736 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf->rootfs.mount);
737
738 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
739 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf->rootfs.path);
740
741 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1))
742 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf->console.path);
743
744 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1))
745 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf->console.log_path);
746
747 if (setenv("LXC_CGNS_AWARE", "1", 1))
748 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
749
750 loglevel = lxc_log_priority_to_string(lxc_log_get_level());
751 if (setenv("LXC_LOG_LEVEL", loglevel, 1))
752 SYSERROR("Failed to set environment variable LXC_LOG_LEVEL=%s", loglevel);
753
754 if (conf->hooks_version == 0)
755 ret = setenv("LXC_HOOK_VERSION", "0", 1);
756 else
757 ret = setenv("LXC_HOOK_VERSION", "1", 1);
758 if (ret < 0)
759 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf->hooks_version);
760 /* End of environment variable setup for hooks. */
761
762 TRACE("set environment variables");
763
764 if (run_lxc_hooks(name, "pre-start", conf, NULL)) {
765 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name);
766 goto out_aborting;
767 }
768 TRACE("ran pre-start hooks");
769
770 /* The signal fd has to be created before forking otherwise if the child
771 * process exits before we setup the signal fd, the event will be lost
772 * and the command will be stuck.
773 */
774 handler->sigfd = setup_signal_fd(&handler->oldmask);
775 if (handler->sigfd < 0) {
776 ERROR("Failed to setup SIGCHLD fd handler.");
777 goto out_delete_tty;
778 }
779 TRACE("set up signal fd");
780
781 /* Do this after setting up signals since it might unblock SIGWINCH. */
782 ret = lxc_console_create(conf);
783 if (ret < 0) {
784 ERROR("Failed to create console");
785 goto out_restore_sigmask;
786 }
787 TRACE("Created console");
788
789 ret = lxc_pty_map_ids(conf, &conf->console);
790 if (ret < 0) {
791 ERROR("Failed to shift tty into container.");
792 goto out_restore_sigmask;
793 }
794 TRACE("shifted tty ids");
795
796 INFO("container \"%s\" is initialized", name);
797 return 0;
798
799 out_restore_sigmask:
800 sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
801 out_delete_tty:
802 lxc_delete_tty(&conf->tty_info);
803 out_aborting:
804 lxc_set_state(name, handler, ABORTING);
805 out_close_maincmd_fd:
806 close(conf->maincmd_fd);
807 conf->maincmd_fd = -1;
808 return -1;
809 }
810
811 void lxc_fini(const char *name, struct lxc_handler *handler)
812 {
813 int i, rc;
814 pid_t self;
815 struct lxc_list *cur, *next;
816 char *namespaces[LXC_NS_MAX + 1];
817 size_t namespace_count = 0;
818
819 /* The STOPPING state is there for future cleanup code which can take
820 * awhile.
821 */
822 lxc_set_state(name, handler, STOPPING);
823
824 self = lxc_raw_getpid();
825 for (i = 0; i < LXC_NS_MAX; i++) {
826 if (handler->nsfd[i] < 0)
827 continue;
828
829 if (handler->conf->hooks_version == 0)
830 rc = asprintf(&namespaces[namespace_count],
831 "%s:/proc/%d/fd/%d", ns_info[i].proc_name,
832 self, handler->nsfd[i]);
833 else
834 rc = asprintf(&namespaces[namespace_count],
835 "/proc/%d/fd/%d", self, handler->nsfd[i]);
836 if (rc == -1) {
837 SYSERROR("Failed to allocate memory.");
838 break;
839 }
840
841 if (handler->conf->hooks_version == 0) {
842 namespace_count++;
843 continue;
844 }
845
846 rc = setenv(ns_info[i].env_name, namespaces[namespace_count], 1);
847 if (rc < 0)
848 SYSERROR("Failed to set environment variable %s=%s",
849 ns_info[i].env_name, namespaces[namespace_count]);
850 else
851 TRACE("Set environment variable %s=%s",
852 ns_info[i].env_name, namespaces[namespace_count]);
853
854 namespace_count++;
855 }
856 namespaces[namespace_count] = NULL;
857
858 if (handler->conf->reboot && setenv("LXC_TARGET", "reboot", 1))
859 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
860
861 if (!handler->conf->reboot && setenv("LXC_TARGET", "stop", 1))
862 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
863
864 if (handler->conf->hooks_version == 0)
865 rc = run_lxc_hooks(name, "stop", handler->conf, namespaces);
866 else
867 rc = run_lxc_hooks(name, "stop", handler->conf, NULL);
868
869 while (namespace_count--)
870 free(namespaces[namespace_count]);
871
872 cgroup_destroy(handler);
873
874 if (handler->conf->reboot == 0) {
875 /* For all new state clients simply close the command socket.
876 * This will inform all state clients that the container is
877 * STOPPED and also prevents a race between a open()/close() on
878 * the command socket causing a new process to get ECONNREFUSED
879 * because we haven't yet closed the command socket.
880 */
881 close(handler->conf->maincmd_fd);
882 handler->conf->maincmd_fd = -1;
883 TRACE("Closed command socket");
884
885 /* This function will try to connect to the legacy lxc-monitord
886 * state server and only exists for backwards compatibility.
887 */
888 lxc_monitor_send_state(name, STOPPED, handler->lxcpath);
889
890 /* The command socket is closed so no one can acces the command
891 * socket anymore so there's no need to lock it.
892 */
893 handler->state = STOPPED;
894 TRACE("Set container state to \"STOPPED\"");
895 } else {
896 lxc_set_state(name, handler, STOPPED);
897 }
898
899 if (run_lxc_hooks(name, "post-stop", handler->conf, NULL)) {
900 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name);
901 if (handler->conf->reboot) {
902 WARN("Container will be stopped instead of rebooted.");
903 handler->conf->reboot = 0;
904 if (setenv("LXC_TARGET", "stop", 1))
905 WARN("Failed to set environment variable: LXC_TARGET=stop.");
906 }
907 }
908
909 /* Reset mask set by setup_signal_fd. */
910 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
911 WARN("Failed to restore signal mask.");
912
913 lxc_console_delete(&handler->conf->console);
914 lxc_delete_tty(&handler->conf->tty_info);
915
916 /* The command socket is now closed, no more state clients can register
917 * themselves from now on. So free the list of state clients.
918 */
919 lxc_list_for_each_safe(cur, &handler->conf->state_clients, next) {
920 struct lxc_state_client *client = cur->elem;
921
922 /* Keep state clients that want to be notified about reboots. */
923 if ((handler->conf->reboot > 0) && (client->states[RUNNING] == 2))
924 continue;
925
926 /* close state client socket */
927 close(client->clientfd);
928 lxc_list_del(cur);
929 free(cur->elem);
930 free(cur);
931 }
932
933 if (handler->conf->ephemeral == 1 && handler->conf->reboot != 1)
934 lxc_destroy_container_on_signal(handler, name);
935
936 lxc_free_handler(handler);
937 }
938
939 void lxc_abort(const char *name, struct lxc_handler *handler)
940 {
941 int ret, status;
942
943 lxc_set_state(name, handler, ABORTING);
944 if (handler->pid > 0)
945 kill(handler->pid, SIGKILL);
946 while ((ret = waitpid(-1, &status, 0)) > 0) {
947 ;
948 }
949 }
950
951 static int lxc_set_death_signal(int signal)
952 {
953 int ret;
954 pid_t ppid;
955
956 ret = prctl(PR_SET_PDEATHSIG, signal, 0, 0, 0);
957
958 /* Check whether we have been orphaned. */
959 ppid = (pid_t)syscall(SYS_getppid);
960 if (ppid == 1) {
961 pid_t self;
962
963 self = lxc_raw_getpid();
964 ret = kill(self, SIGKILL);
965 if (ret < 0)
966 return -1;
967 }
968
969 if (ret < 0) {
970 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal);
971 return -1;
972 }
973
974 return 0;
975 }
976
977 static int do_start(void *data)
978 {
979 int ret;
980 struct lxc_list *iterator;
981 char path[PATH_MAX];
982 struct lxc_handler *handler = data;
983 bool have_cap_setgid;
984 uid_t new_uid;
985 gid_t new_gid;
986 int devnull_fd = -1;
987
988 lxc_sync_fini_parent(handler);
989
990 /* This prctl must be before the synchro, so if the parent dies before
991 * we set the parent death signal, we will detect its death with the
992 * synchro right after, otherwise we have a window where the parent can
993 * exit before we set the pdeath signal leading to a unsupervized
994 * container.
995 */
996 ret = lxc_set_death_signal(SIGKILL);
997 if (ret < 0) {
998 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
999 goto out_warn_father;
1000 }
1001
1002 ret = sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
1003 if (ret < 0) {
1004 SYSERROR("Failed to set signal mask");
1005 goto out_warn_father;
1006 }
1007
1008 /* Don't leak the pinfd to the container. */
1009 if (handler->pinfd >= 0)
1010 close(handler->pinfd);
1011
1012 ret = lxc_sync_wait_parent(handler, LXC_SYNC_STARTUP);
1013 if (ret < 0)
1014 goto out_warn_father;
1015
1016 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1017 * https://github.com/lxc/lxd/issues/1978.
1018 */
1019 if ((handler->clone_flags & (CLONE_NEWNET | CLONE_NEWUSER)) ==
1020 (CLONE_NEWNET | CLONE_NEWUSER)) {
1021 ret = unshare(CLONE_NEWNET);
1022 if (ret < 0) {
1023 SYSERROR("Failed to unshare CLONE_NEWNET.");
1024 goto out_warn_father;
1025 }
1026 INFO("Unshared CLONE_NEWNET.");
1027 }
1028
1029 /* Tell the parent task it can begin to configure the container and wait
1030 * for it to finish.
1031 */
1032 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE))
1033 return -1;
1034
1035 if (lxc_network_recv_veth_names_from_parent(handler) < 0) {
1036 ERROR("Failed to receive veth names from parent");
1037 goto out_warn_father;
1038 }
1039
1040 /* If we are in a new user namespace, become root there to have
1041 * privilege over our namespace.
1042 */
1043 if (!lxc_list_empty(&handler->conf->id_map)) {
1044 uid_t nsuid = (handler->conf->root_nsuid_map != NULL)
1045 ? 0
1046 : handler->conf->init_uid;
1047 gid_t nsgid = (handler->conf->root_nsgid_map != NULL)
1048 ? 0
1049 : handler->conf->init_gid;
1050
1051 ret = lxc_switch_uid_gid(nsuid, nsgid);
1052 if (ret < 0)
1053 goto out_warn_father;
1054
1055 /* Drop groups only after we switched to a valid gid in the new
1056 * user namespace.
1057 */
1058 ret = lxc_setgroups(0, NULL);
1059 if (ret < 0 && (handler->am_root || errno != EPERM))
1060 goto out_warn_father;
1061
1062 if (!handler->am_root) {
1063 ret = prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1064 if (ret < 0)
1065 goto out_warn_father;
1066 }
1067
1068 /* set{g,u}id() clears deathsignal */
1069 ret = lxc_set_death_signal(SIGKILL);
1070 if (ret < 0) {
1071 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1072 goto out_warn_father;
1073 }
1074 }
1075
1076 if (access(handler->lxcpath, X_OK)) {
1077 print_top_failing_dir(handler->lxcpath);
1078 goto out_warn_father;
1079 }
1080
1081 ret = snprintf(path, sizeof(path), "%s/dev/null", handler->conf->rootfs.mount);
1082 if (ret < 0 || ret >= sizeof(path))
1083 goto out_warn_father;
1084
1085 /* In order to checkpoint restore, we need to have everything in the
1086 * same mount namespace. However, some containers may not have a
1087 * reasonable /dev (in particular, they may not have /dev/null), so we
1088 * can't set init's std fds to /dev/null by opening it from inside the
1089 * container.
1090 *
1091 * If that's the case, fall back to using the host's /dev/null. This
1092 * means that migration won't work, but at least we won't spew output
1093 * where it isn't wanted.
1094 */
1095 if (handler->backgrounded && !handler->conf->autodev && access(path, F_OK) < 0) {
1096 devnull_fd = open_devnull();
1097
1098 if (devnull_fd < 0)
1099 goto out_warn_father;
1100 WARN("Using /dev/null from the host for container init's "
1101 "standard file descriptors. Migration will not work.");
1102 }
1103
1104 /* Ask father to setup cgroups and wait for him to finish. */
1105 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP))
1106 goto out_error;
1107
1108 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1109 * earlier we end up with a wrong view of /proc/self/cgroup. For
1110 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1111 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1112 * /proc/self/cgroup would show us:
1113 *
1114 * 8:cpuset:/lxc/c
1115 *
1116 * whereas it should actually show
1117 *
1118 * 8:cpuset:/
1119 */
1120 if (handler->clone_flags & CLONE_NEWCGROUP) {
1121 if (unshare(CLONE_NEWCGROUP) < 0) {
1122 INFO("Failed to unshare CLONE_NEWCGROUP.");
1123 goto out_warn_father;
1124 }
1125 INFO("Unshared CLONE_NEWCGROUP.");
1126 }
1127
1128 /* Add the requested environment variables to the current environment to
1129 * allow them to be used by the various hooks, such as the start hook
1130 * above.
1131 */
1132 lxc_list_for_each(iterator, &handler->conf->environment) {
1133 if (putenv((char *)iterator->elem)) {
1134 SYSERROR("Failed to set environment variable: %s.", (char *)iterator->elem);
1135 goto out_warn_father;
1136 }
1137 }
1138
1139 /* Setup the container, ip, names, utsname, ... */
1140 ret = lxc_setup(handler);
1141 close(handler->data_sock[1]);
1142 close(handler->data_sock[0]);
1143 if (ret < 0) {
1144 ERROR("Failed to setup container \"%s\".", handler->name);
1145 goto out_warn_father;
1146 }
1147
1148 /* Set the label to change to when we exec(2) the container's init. */
1149 if (lsm_process_label_set(NULL, handler->conf, 1, 1) < 0)
1150 goto out_warn_father;
1151
1152 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
1153 * before we aren't allowed anymore.
1154 */
1155 if (handler->conf->no_new_privs) {
1156 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1157 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
1158 goto out_warn_father;
1159 }
1160 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
1161 }
1162
1163 /* Some init's such as busybox will set sane tty settings on stdin,
1164 * stdout, stderr which it thinks is the console. We already set them
1165 * the way we wanted on the real terminal, and we want init to do its
1166 * setup on its console ie. the pty allocated in lxc_console_create() so
1167 * make sure that that pty is stdin,stdout,stderr.
1168 */
1169 if (handler->conf->console.slave >= 0) {
1170 if (handler->backgrounded || handler->conf->is_execute == 0)
1171 ret = set_stdfds(handler->conf->console.slave);
1172 else
1173 ret = lxc_console_set_stdfds(handler->conf->console.slave);
1174 if (ret < 0) {
1175 ERROR("Failed to redirect std{in,out,err} to pty file "
1176 "descriptor %d",
1177 handler->conf->console.slave);
1178 goto out_warn_father;
1179 }
1180 }
1181
1182 /* If we mounted a temporary proc, then unmount it now. */
1183 tmp_proc_unmount(handler->conf);
1184
1185 if (lxc_seccomp_load(handler->conf) != 0)
1186 goto out_warn_father;
1187
1188 if (run_lxc_hooks(handler->name, "start", handler->conf, NULL)) {
1189 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler->name);
1190 goto out_warn_father;
1191 }
1192
1193 close(handler->sigfd);
1194
1195 if (devnull_fd < 0) {
1196 devnull_fd = open_devnull();
1197
1198 if (devnull_fd < 0)
1199 goto out_warn_father;
1200 }
1201
1202 if (handler->conf->console.slave < 0 && handler->backgrounded)
1203 if (set_stdfds(devnull_fd) < 0) {
1204 ERROR("Failed to redirect std{in,out,err} to "
1205 "\"/dev/null\"");
1206 goto out_warn_father;
1207 }
1208
1209 if (devnull_fd >= 0) {
1210 close(devnull_fd);
1211 devnull_fd = -1;
1212 }
1213
1214 setsid();
1215
1216 if (handler->conf->init_cwd && chdir(handler->conf->init_cwd)) {
1217 SYSERROR("Could not change directory to \"%s\"", handler->conf->init_cwd);
1218 goto out_warn_father;
1219 }
1220
1221 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP_LIMITS))
1222 goto out_warn_father;
1223
1224 /* Reset the environment variables the user requested in a clear
1225 * environment.
1226 */
1227 if (clearenv()) {
1228 SYSERROR("Failed to clear environment.");
1229 /* Don't error out though. */
1230 }
1231
1232 lxc_list_for_each(iterator, &handler->conf->environment) {
1233 if (putenv((char *)iterator->elem)) {
1234 SYSERROR("Failed to set environment variable: %s.", (char *)iterator->elem);
1235 goto out_warn_father;
1236 }
1237 }
1238
1239 if (putenv("container=lxc")) {
1240 SYSERROR("Failed to set environment variable: container=lxc.");
1241 goto out_warn_father;
1242 }
1243
1244 if (handler->conf->pty_names) {
1245 if (putenv(handler->conf->pty_names)) {
1246 SYSERROR("Failed to set environment variable for container ptys.");
1247 goto out_warn_father;
1248 }
1249 }
1250
1251 /* The container has been setup. We can now switch to an unprivileged
1252 * uid/gid.
1253 */
1254 new_uid = handler->conf->init_uid;
1255 new_gid = handler->conf->init_gid;
1256
1257 /* If we are in a new user namespace we already dropped all
1258 * groups when we switched to root in the new user namespace
1259 * further above. Only drop groups if we can, so ensure that we
1260 * have necessary privilege.
1261 */
1262 #if HAVE_LIBCAP
1263 have_cap_setgid = lxc_proc_cap_is_set(CAP_SETGID, CAP_EFFECTIVE);
1264 #else
1265 have_cap_setgid = false;
1266 #endif
1267 if (lxc_list_empty(&handler->conf->id_map) && have_cap_setgid) {
1268 if (lxc_setgroups(0, NULL) < 0)
1269 goto out_warn_father;
1270 }
1271
1272 if (lxc_switch_uid_gid(new_uid, new_gid) < 0)
1273 goto out_warn_father;
1274
1275 /* After this call, we are in error because this ops should not return
1276 * as it execs.
1277 */
1278 handler->ops->start(handler, handler->data);
1279
1280 out_warn_father:
1281 /* We want the parent to know something went wrong, so we return a
1282 * special error code.
1283 */
1284 lxc_sync_wake_parent(handler, LXC_SYNC_ERROR);
1285
1286 out_error:
1287 if (devnull_fd >= 0)
1288 close(devnull_fd);
1289
1290 return -1;
1291 }
1292
1293 static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
1294 {
1295 int i;
1296 struct lxc_pty_info *pty_info;
1297 int ret = -1;
1298 int sock = handler->data_sock[1];
1299 struct lxc_conf *conf = handler->conf;
1300 struct lxc_tty_info *tty_info = &conf->tty_info;
1301
1302 if (!conf->tty)
1303 return 0;
1304
1305 tty_info->pty_info = malloc(sizeof(*tty_info->pty_info) * conf->tty);
1306 if (!tty_info->pty_info)
1307 return -1;
1308
1309 for (i = 0; i < conf->tty; i++) {
1310 int ttyfds[2];
1311
1312 ret = lxc_abstract_unix_recv_fds(sock, ttyfds, 2, NULL, 0);
1313 if (ret < 0)
1314 break;
1315
1316 pty_info = &tty_info->pty_info[i];
1317 pty_info->busy = 0;
1318 pty_info->master = ttyfds[0];
1319 pty_info->slave = ttyfds[1];
1320 TRACE("Received pty with master fd %d and slave fd %d from "
1321 "parent", pty_info->master, pty_info->slave);
1322 }
1323 if (ret < 0)
1324 ERROR("Failed to receive %d ttys from child: %s", conf->tty,
1325 strerror(errno));
1326 else
1327 TRACE("Received %d ttys from child", conf->tty);
1328
1329 tty_info->nbtty = conf->tty;
1330
1331 return ret;
1332 }
1333
1334 int resolve_clone_flags(struct lxc_handler *handler)
1335 {
1336 handler->clone_flags = CLONE_NEWNS;
1337
1338 if (!handler->conf->inherit_ns[LXC_NS_USER]) {
1339 if (!lxc_list_empty(&handler->conf->id_map))
1340 handler->clone_flags |= CLONE_NEWUSER;
1341 } else {
1342 INFO("Inheriting user namespace");
1343 }
1344
1345 if (!handler->conf->inherit_ns[LXC_NS_NET]) {
1346 if (!lxc_requests_empty_network(handler))
1347 handler->clone_flags |= CLONE_NEWNET;
1348 } else {
1349 INFO("Inheriting net namespace");
1350 }
1351
1352 if (!handler->conf->inherit_ns[LXC_NS_IPC])
1353 handler->clone_flags |= CLONE_NEWIPC;
1354 else
1355 INFO("Inheriting ipc namespace");
1356
1357 if (!handler->conf->inherit_ns[LXC_NS_UTS])
1358 handler->clone_flags |= CLONE_NEWUTS;
1359 else
1360 INFO("Inheriting uts namespace");
1361
1362 if (!handler->conf->inherit_ns[LXC_NS_PID])
1363 handler->clone_flags |= CLONE_NEWPID;
1364 else
1365 INFO("Inheriting pid namespace");
1366
1367 if (cgns_supported()) {
1368 if (!handler->conf->inherit_ns[LXC_NS_CGROUP])
1369 handler->clone_flags |= CLONE_NEWCGROUP;
1370 else
1371 INFO("Inheriting cgroup namespace");
1372 } else if (handler->conf->inherit_ns[LXC_NS_CGROUP]) {
1373 return -EINVAL;
1374 }
1375
1376 return 0;
1377 }
1378
1379 /* Note that this function is used with clone(CLONE_VM). Some glibc versions
1380 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1381 * But since the memory between parent and child is shared on CLONE_VM this
1382 * would invalidate the getpid() cache that glibc used to maintain and so
1383 * getpid() in the child would return the parent's pid. This is all fixed in
1384 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1385 * not reset anymore.
1386 * However, if for whatever reason you - dear commiter - somehow need to get the
1387 * pid of the dummy intermediate process for do_share_ns() you need to call
1388 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1389 * will be fine.
1390 */
1391 static inline int do_share_ns(void *arg)
1392 {
1393 int i, flags, ret;
1394 struct lxc_handler *handler = arg;
1395
1396 for (i = 0; i < LXC_NS_MAX; i++) {
1397 if (handler->nsfd[i] < 0)
1398 continue;
1399
1400 ret = setns(handler->nsfd[i], 0);
1401 if (ret < 0)
1402 return -1;
1403
1404 DEBUG("Inherited %s namespace", ns_info[i].proc_name);
1405 }
1406
1407 flags = handler->on_clone_flags;
1408 flags |= CLONE_PARENT;
1409 handler->pid = lxc_raw_clone_cb(do_start, handler, flags);
1410 if (handler->pid < 0)
1411 return -1;
1412
1413 return 0;
1414 }
1415
1416 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1417 * exec()s the requested container binary.
1418 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1419 * right here should be double checked if they'd pose a security risk. (For
1420 * example, any {u}mount() operations performed here will be reflected on the
1421 * host!)
1422 */
1423 static int lxc_spawn(struct lxc_handler *handler)
1424 {
1425 int i, ret;
1426 char pidstr[20];
1427 bool wants_to_map_ids;
1428 struct lxc_list *id_map;
1429 const char *name = handler->name;
1430 const char *lxcpath = handler->lxcpath;
1431 bool cgroups_connected = false, share_ns = false;
1432 struct lxc_conf *conf = handler->conf;
1433
1434 id_map = &conf->id_map;
1435 wants_to_map_ids = !lxc_list_empty(id_map);
1436
1437 for (i = 0; i < LXC_NS_MAX; i++) {
1438 if (!conf->inherit_ns[i])
1439 continue;
1440
1441 handler->nsfd[i] = lxc_inherit_namespace(conf->inherit_ns[i], lxcpath, ns_info[i].proc_name);
1442 if (handler->nsfd[i] < 0)
1443 return -1;
1444
1445 share_ns = true;
1446 }
1447
1448 if (lxc_sync_init(handler))
1449 return -1;
1450
1451 ret = socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
1452 handler->data_sock);
1453 if (ret < 0) {
1454 lxc_sync_fini(handler);
1455 return -1;
1456 }
1457
1458 ret = resolve_clone_flags(handler);
1459 if (ret < 0) {
1460 lxc_sync_fini(handler);
1461 return -1;
1462 }
1463
1464 if (handler->clone_flags & CLONE_NEWNET) {
1465 if (!lxc_list_empty(&conf->network)) {
1466
1467 /* Find gateway addresses from the link device, which is
1468 * no longer accessible inside the container. Do this
1469 * before creating network interfaces, since goto
1470 * out_delete_net does not work before lxc_clone.
1471 */
1472 if (lxc_find_gateway_addresses(handler)) {
1473 ERROR("Failed to find gateway addresses.");
1474 lxc_sync_fini(handler);
1475 return -1;
1476 }
1477
1478 /* That should be done before the clone because we will
1479 * fill the netdev index and use them in the child.
1480 */
1481 if (lxc_create_network_priv(handler)) {
1482 ERROR("Failed to create the network.");
1483 lxc_sync_fini(handler);
1484 return -1;
1485 }
1486 }
1487 }
1488
1489 if (!cgroup_init(handler)) {
1490 ERROR("Failed initializing cgroup support.");
1491 goto out_delete_net;
1492 }
1493
1494 cgroups_connected = true;
1495
1496 if (!cgroup_create(handler)) {
1497 ERROR("Failed creating cgroups.");
1498 goto out_delete_net;
1499 }
1500
1501 /* If the rootfs is not a blockdev, prevent the container from marking
1502 * it readonly.
1503 * If the container is unprivileged then skip rootfs pinning.
1504 */
1505 if (!wants_to_map_ids) {
1506 handler->pinfd = pin_rootfs(conf->rootfs.path);
1507 if (handler->pinfd == -1)
1508 INFO("Failed to pin the rootfs for container \"%s\".", handler->name);
1509 }
1510
1511 /* Create a process in a new set of namespaces. */
1512 handler->on_clone_flags = handler->clone_flags;
1513 if (handler->clone_flags & CLONE_NEWUSER) {
1514 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1515 * clone a new user namespace first and only later unshare our
1516 * network namespace to ensure that network devices ownership is
1517 * set up correctly.
1518 */
1519 handler->on_clone_flags &= ~CLONE_NEWNET;
1520 }
1521 /* The cgroup namespace gets unshare()ed not clone()ed. */
1522 handler->on_clone_flags &= ~CLONE_NEWCGROUP;
1523
1524 if (share_ns) {
1525 pid_t attacher_pid;
1526
1527 attacher_pid = lxc_clone(do_share_ns, handler, CLONE_VFORK | CLONE_VM | CLONE_FILES);
1528 if (attacher_pid < 0) {
1529 SYSERROR(LXC_CLONE_ERROR);
1530 goto out_delete_net;
1531 }
1532
1533 ret = wait_for_pid(attacher_pid);
1534 if (ret < 0) {
1535 SYSERROR("Intermediate process failed");
1536 goto out_delete_net;
1537 }
1538 } else {
1539 handler->pid = lxc_raw_clone_cb(do_start, handler, handler->on_clone_flags);
1540 }
1541 if (handler->pid < 0) {
1542 SYSERROR(LXC_CLONE_ERROR);
1543 goto out_delete_net;
1544 }
1545 TRACE("Cloned child process %d", handler->pid);
1546
1547 for (i = 0; i < LXC_NS_MAX; i++)
1548 if (handler->on_clone_flags & ns_info[i].clone_flag)
1549 INFO("Cloned %s", ns_info[i].flag_name);
1550
1551 if (!preserve_ns(handler->nsfd, handler->on_clone_flags, handler->pid)) {
1552 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1553 goto out_delete_net;
1554 }
1555
1556 lxc_sync_fini_child(handler);
1557
1558 /* Map the container uids. The container became an invalid userid the
1559 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1560 * anything immediately, but allows the container to setuid(0) (0 being
1561 * mapped to something else on the host.) later to become a valid uid
1562 * again.
1563 */
1564 if (wants_to_map_ids) {
1565 if (!handler->conf->inherit_ns[LXC_NS_USER]) {
1566 ret = lxc_map_ids(id_map, handler->pid);
1567 if (ret < 0) {
1568 ERROR("Failed to set up id mapping.");
1569 goto out_delete_net;
1570 }
1571 }
1572 }
1573
1574 if (lxc_sync_wake_child(handler, LXC_SYNC_STARTUP))
1575 goto out_delete_net;
1576
1577 if (lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE))
1578 goto out_delete_net;
1579
1580 if (!cgroup_create_legacy(handler)) {
1581 ERROR("Failed to setup legacy cgroups for container \"%s\".", name);
1582 goto out_delete_net;
1583 }
1584 if (!cgroup_setup_limits(handler, false)) {
1585 ERROR("Failed to setup cgroup limits for container \"%s\".", name);
1586 goto out_delete_net;
1587 }
1588
1589 if (!cgroup_enter(handler))
1590 goto out_delete_net;
1591
1592 if (!cgroup_chown(handler))
1593 goto out_delete_net;
1594
1595 /* Now we're ready to preserve the network namespace */
1596 ret = lxc_preserve_ns(handler->pid, "net");
1597 if (ret < 0) {
1598 ERROR("%s - Failed to preserve net namespace", strerror(errno));
1599 goto out_delete_net;
1600 }
1601 handler->nsfd[LXC_NS_NET] = ret;
1602 DEBUG("Preserved net namespace via fd %d", ret);
1603
1604 /* Create the network configuration. */
1605 if (handler->clone_flags & CLONE_NEWNET) {
1606 if (lxc_network_move_created_netdev_priv(handler->lxcpath,
1607 handler->name,
1608 &conf->network,
1609 handler->pid)) {
1610 ERROR("Failed to create the configured network.");
1611 goto out_delete_net;
1612 }
1613
1614 if (lxc_create_network_unpriv(handler->lxcpath, handler->name,
1615 &conf->network,
1616 handler->pid)) {
1617 ERROR("Failed to create the configured network.");
1618 goto out_delete_net;
1619 }
1620 }
1621
1622 if (lxc_network_send_veth_names_to_child(handler) < 0) {
1623 ERROR("Failed to send veth names to child");
1624 goto out_delete_net;
1625 }
1626
1627 if (!lxc_list_empty(&conf->procs)) {
1628 ret = setup_proc_filesystem(&conf->procs, handler->pid);
1629 if (ret < 0)
1630 goto out_delete_net;
1631 }
1632
1633 /* Tell the child to continue its initialization. We'll get
1634 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1635 */
1636 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE))
1637 goto out_delete_net;
1638
1639 if (!lxc_list_empty(&conf->limits) && setup_resource_limits(&conf->limits, handler->pid)) {
1640 ERROR("failed to setup resource limits for '%s'", name);
1641 goto out_delete_net;
1642 }
1643
1644 if (lxc_sync_barrier_child(handler, LXC_SYNC_CGROUP_UNSHARE))
1645 goto out_delete_net;
1646
1647 if (!cgroup_setup_limits(handler, true)) {
1648 ERROR("Failed to setup the devices cgroup for container \"%s\".", name);
1649 goto out_delete_net;
1650 }
1651 TRACE("Set up cgroup device limits");
1652
1653 cgroup_disconnect();
1654 cgroups_connected = false;
1655
1656 if (handler->clone_flags & CLONE_NEWCGROUP) {
1657 /* Now we're ready to preserve the cgroup namespace */
1658 ret = lxc_preserve_ns(handler->pid, "cgroup");
1659 if (ret < 0) {
1660 ERROR("%s - Failed to preserve cgroup namespace", strerror(errno));
1661 goto out_delete_net;
1662 }
1663 handler->nsfd[LXC_NS_CGROUP] = ret;
1664 DEBUG("Preserved cgroup namespace via fd %d", ret);
1665 }
1666
1667 snprintf(pidstr, 20, "%d", handler->pid);
1668 if (setenv("LXC_PID", pidstr, 1))
1669 SYSERROR("Failed to set environment variable: LXC_PID=%s.", pidstr);
1670
1671 /* Run any host-side start hooks */
1672 if (run_lxc_hooks(name, "start-host", conf, NULL)) {
1673 ERROR("Failed to run lxc.hook.start-host for container \"%s\".", name);
1674 return -1;
1675 }
1676
1677 /* Tell the child to complete its initialization and wait for it to exec
1678 * or return an error. (The child will never return
1679 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
1680 * lxc_sync_barrier_child to return success, or return a different
1681 * value, causing us to error out).
1682 */
1683 if (lxc_sync_barrier_child(handler, LXC_SYNC_READY_START))
1684 return -1;
1685
1686 if (lxc_network_recv_name_and_ifindex_from_child(handler) < 0) {
1687 ERROR("Failed to receive names and ifindices for network "
1688 "devices from child");
1689 goto out_delete_net;
1690 }
1691
1692 /* Now all networks are created, network devices are moved into place,
1693 * and the correct names and ifindeces in the respective namespaces have
1694 * been recorded. The corresponding structs have now all been filled. So
1695 * log them for debugging purposes.
1696 */
1697 lxc_log_configured_netdevs(conf);
1698
1699 /* Read tty fds allocated by child. */
1700 if (lxc_recv_ttys_from_child(handler) < 0) {
1701 ERROR("Failed to receive tty info from child process.");
1702 goto out_delete_net;
1703 }
1704
1705 if (handler->ops->post_start(handler, handler->data))
1706 goto out_abort;
1707
1708 if (lxc_set_state(name, handler, RUNNING)) {
1709 ERROR("Failed to set state for container \"%s\" to \"%s\".", name,
1710 lxc_state2str(RUNNING));
1711 goto out_abort;
1712 }
1713
1714 lxc_sync_fini(handler);
1715
1716 return 0;
1717
1718 out_delete_net:
1719 if (cgroups_connected)
1720 cgroup_disconnect();
1721
1722 if (handler->clone_flags & CLONE_NEWNET)
1723 lxc_delete_network(handler);
1724
1725 out_abort:
1726 lxc_abort(name, handler);
1727 lxc_sync_fini(handler);
1728 if (handler->pinfd >= 0) {
1729 close(handler->pinfd);
1730 handler->pinfd = -1;
1731 }
1732
1733 return -1;
1734 }
1735
1736 int __lxc_start(const char *name, struct lxc_handler *handler,
1737 struct lxc_operations* ops, void *data, const char *lxcpath,
1738 bool backgrounded)
1739 {
1740 int status;
1741 int err = -1;
1742 struct lxc_conf *conf = handler->conf;
1743
1744 if (lxc_init(name, handler) < 0) {
1745 ERROR("Failed to initialize container \"%s\".", name);
1746 return -1;
1747 }
1748 handler->ops = ops;
1749 handler->data = data;
1750 handler->backgrounded = backgrounded;
1751
1752 if (!attach_block_device(handler->conf)) {
1753 ERROR("Failed to attach block device.");
1754 goto out_fini_nonet;
1755 }
1756
1757 if (geteuid() == 0 && !lxc_list_empty(&conf->id_map)) {
1758 /* If the backing store is a device, mount it here and now. */
1759 if (rootfs_is_blockdev(conf)) {
1760 if (unshare(CLONE_NEWNS) < 0) {
1761 ERROR("Failed to unshare CLONE_NEWNS.");
1762 goto out_fini_nonet;
1763 }
1764 INFO("Unshared CLONE_NEWNS.");
1765
1766 remount_all_slave();
1767 if (do_rootfs_setup(conf, name, lxcpath) < 0) {
1768 ERROR("Error setting up rootfs mount as root before spawn.");
1769 goto out_fini_nonet;
1770 }
1771 INFO("Set up container rootfs as host root.");
1772 }
1773 }
1774
1775 err = lxc_spawn(handler);
1776 if (err) {
1777 ERROR("Failed to spawn container \"%s\".", name);
1778 goto out_detach_blockdev;
1779 }
1780 /* close parent side of data socket */
1781 close(handler->data_sock[0]);
1782 handler->data_sock[0] = -1;
1783 close(handler->data_sock[1]);
1784 handler->data_sock[1] = -1;
1785
1786 handler->conf->reboot = 0;
1787
1788 err = lxc_poll(name, handler);
1789 if (err) {
1790 ERROR("LXC mainloop exited with error: %d.", err);
1791 goto out_abort;
1792 }
1793
1794 while (waitpid(handler->pid, &status, 0) < 0 && errno == EINTR)
1795 continue;
1796
1797 /* If the child process exited but was not signaled, it didn't call
1798 * reboot. This should mean it was an lxc-execute which simply exited.
1799 * In any case, treat it as a 'halt'.
1800 */
1801 if (WIFSIGNALED(status)) {
1802 switch(WTERMSIG(status)) {
1803 case SIGINT: /* halt */
1804 DEBUG("Container \"%s\" is halting.", name);
1805 break;
1806 case SIGHUP: /* reboot */
1807 DEBUG("Container \"%s\" is rebooting.", name);
1808 handler->conf->reboot = 1;
1809 break;
1810 case SIGSYS: /* seccomp */
1811 DEBUG("Container \"%s\" violated its seccomp policy.", name);
1812 break;
1813 default:
1814 DEBUG("Unknown exit status for container \"%s\" init %d.", name, WTERMSIG(status));
1815 break;
1816 }
1817 }
1818
1819 err = lxc_restore_phys_nics_to_netns(handler);
1820 if (err < 0)
1821 ERROR("Failed to move physical network devices back to parent "
1822 "network namespace");
1823
1824 if (handler->pinfd >= 0) {
1825 close(handler->pinfd);
1826 handler->pinfd = -1;
1827 }
1828
1829 lxc_monitor_send_exit_code(name, status, handler->lxcpath);
1830 lxc_error_set_and_log(handler->pid, status);
1831
1832 out_fini:
1833 lxc_delete_network(handler);
1834
1835 out_detach_blockdev:
1836 detach_block_device(handler->conf);
1837
1838 out_fini_nonet:
1839 lxc_fini(name, handler);
1840 return err;
1841
1842 out_abort:
1843 lxc_abort(name, handler);
1844 goto out_fini;
1845 }
1846
1847 struct start_args {
1848 char *const *argv;
1849 };
1850
1851 static int start(struct lxc_handler *handler, void* data)
1852 {
1853 struct start_args *arg = data;
1854
1855 NOTICE("Exec'ing \"%s\".", arg->argv[0]);
1856
1857 execvp(arg->argv[0], arg->argv);
1858 SYSERROR("Failed to exec \"%s\".", arg->argv[0]);
1859 return 0;
1860 }
1861
1862 static int post_start(struct lxc_handler *handler, void* data)
1863 {
1864 struct start_args *arg = data;
1865
1866 NOTICE("Started \"%s\" with pid \"%d\".", arg->argv[0], handler->pid);
1867 return 0;
1868 }
1869
1870 static struct lxc_operations start_ops = {
1871 .start = start,
1872 .post_start = post_start
1873 };
1874
1875 int lxc_start(const char *name, char *const argv[], struct lxc_handler *handler,
1876 const char *lxcpath, bool backgrounded)
1877 {
1878 struct start_args start_arg = {
1879 .argv = argv,
1880 };
1881
1882 return __lxc_start(name, handler, &start_ops, &start_arg, lxcpath, backgrounded);
1883 }
1884
1885 static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
1886 const char *name)
1887 {
1888 char destroy[MAXPATHLEN];
1889 bool bret = true;
1890 int ret = 0;
1891 struct lxc_container *c;
1892 if (handler->conf->rootfs.path && handler->conf->rootfs.mount) {
1893 bret = do_destroy_container(handler);
1894 if (!bret) {
1895 ERROR("Error destroying rootfs for container \"%s\".", name);
1896 return;
1897 }
1898 }
1899 INFO("Destroyed rootfs for container \"%s\".", name);
1900
1901 ret = snprintf(destroy, MAXPATHLEN, "%s/%s", handler->lxcpath, name);
1902 if (ret < 0 || ret >= MAXPATHLEN) {
1903 ERROR("Error destroying directory for container \"%s\".", name);
1904 return;
1905 }
1906
1907 c = lxc_container_new(name, handler->lxcpath);
1908 if (c) {
1909 if (container_disk_lock(c)) {
1910 INFO("Could not update lxc_snapshots file.");
1911 lxc_container_put(c);
1912 } else {
1913 mod_all_rdeps(c, false);
1914 container_disk_unlock(c);
1915 lxc_container_put(c);
1916 }
1917 }
1918
1919 if (!handler->am_root)
1920 ret = userns_exec_full(handler->conf, lxc_rmdir_onedev_wrapper,
1921 destroy, "lxc_rmdir_onedev_wrapper");
1922 else
1923 ret = lxc_rmdir_onedev(destroy, NULL);
1924
1925 if (ret < 0) {
1926 ERROR("Error destroying directory for container \"%s\".", name);
1927 return;
1928 }
1929 INFO("Destroyed directory for container \"%s\".", name);
1930 }
1931
1932 static int lxc_rmdir_onedev_wrapper(void *data)
1933 {
1934 char *arg = (char *) data;
1935 return lxc_rmdir_onedev(arg, NULL);
1936 }
1937
1938 static bool do_destroy_container(struct lxc_handler *handler) {
1939 int ret;
1940
1941 if (!handler->am_root) {
1942 ret = userns_exec_full(handler->conf, storage_destroy_wrapper,
1943 handler->conf, "storage_destroy_wrapper");
1944 if (ret < 0)
1945 return false;
1946
1947 return true;
1948 }
1949
1950 return storage_destroy(handler->conf);
1951 }