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