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