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