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