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