]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/start.c
commands: add TRACE()ers
[mirror_lxc.git] / src / lxc / start.c
CommitLineData
0ad19a3f 1/*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
9afe19d6 7 * Daniel Lezcano <daniel.lezcano at free.fr>
0ad19a3f 8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
250b1eec 21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0ad19a3f 22 */
23
f3787121 24#define _GNU_SOURCE
f549edcc
GK
25#include "config.h"
26
f3787121 27#include <alloca.h>
0ad19a3f 28#include <dirent.h>
29#include <errno.h>
b0a33c1e 30#include <fcntl.h>
c476bdce 31#include <grp.h>
37515ebd 32#include <poll.h>
f3787121
CB
33#include <signal.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37#include <unistd.h>
0ad19a3f 38#include <sys/file.h>
f4d507d5 39#include <sys/mount.h>
f3787121 40#include <sys/param.h>
0ad19a3f 41#include <sys/prctl.h>
f3787121
CB
42#include <sys/socket.h>
43#include <sys/stat.h>
44#include <sys/syscall.h>
ddceb1f9 45#include <sys/types.h>
b0a33c1e 46#include <sys/un.h>
f3787121 47#include <sys/wait.h>
ff218c25 48
e37dda71 49#if HAVE_LIBCAP
495d2046
SG
50#include <sys/capability.h>
51#endif
52
955e2a02 53#ifndef HAVE_DECL_PR_CAPBSET_DROP
656994bb
MH
54#define PR_CAPBSET_DROP 24
55#endif
56
955e2a02
CB
57#ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
58#define PR_SET_NO_NEW_PRIVS 38
59#endif
60
61#ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
62#define PR_GET_NO_NEW_PRIVS 39
63#endif
64
f3787121 65#include "af_unix.h"
d8e48992 66#include "bdev.h"
f3787121 67#include "caps.h"
563f2f2c 68#include "cgroup.h"
f3787121
CB
69#include "commands.h"
70#include "conf.h"
71#include "console.h"
e2bcd7db 72#include "error.h"
f3787121
CB
73#include "log.h"
74#include "lxclock.h"
75#include "lxcseccomp.h"
565c2d76 76#include "lxcutmp.h"
f3787121 77#include "mainloop.h"
63376d7d 78#include "monitor.h"
f549edcc 79#include "namespace.h"
f3787121
CB
80#include "start.h"
81#include "sync.h"
82#include "utils.h"
fe4de9a6 83#include "lsm/lsm.h"
36eb9bde
CLG
84
85lxc_log_define(lxc_start, lxc);
86
f01f7975 87extern void mod_all_rdeps(struct lxc_container *c, bool inc);
28272964
CB
88static bool do_destroy_container(struct lxc_conf *conf);
89static int lxc_rmdir_onedev_wrapper(void *data);
90static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
91 const char *name);
92
c8154066
SH
93static void print_top_failing_dir(const char *path)
94{
95 size_t len = strlen(path);
f3787121 96 char *copy = alloca(len + 1), *p, *e, saved;
c8154066
SH
97 strcpy(copy, path);
98
99 p = copy;
100 e = copy + len;
101 while (p < e) {
f3787121
CB
102 while (p < e && *p == '/')
103 p++;
104 while (p < e && *p != '/')
105 p++;
c8154066
SH
106 saved = *p;
107 *p = '\0';
108 if (access(copy, X_OK)) {
408da065
CB
109 SYSERROR("Could not access %s. Please grant it x "
110 "access, or add an ACL for the container "
111 "root.", copy);
c8154066
SH
112 return;
113 }
114 *p = saved;
115 }
116}
117
408da065
CB
118static void close_ns(int ns_fd[LXC_NS_MAX])
119{
9f30a190
MM
120 int i;
121
9f30a190
MM
122 for (i = 0; i < LXC_NS_MAX; i++) {
123 if (ns_fd[i] > -1) {
124 close(ns_fd[i]);
125 ns_fd[i] = -1;
126 }
127 }
9f30a190
MM
128}
129
4d8ac866 130/* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
62d05d9b 131 * in clone_flags.
4d8ac866 132 * Return true on success, false on failure.
62d05d9b 133 */
4d8ac866 134static bool preserve_ns(int ns_fd[LXC_NS_MAX], int clone_flags, pid_t pid)
f3787121 135{
62d05d9b 136 int i, ret;
9f30a190 137
9f30a190
MM
138 for (i = 0; i < LXC_NS_MAX; i++)
139 ns_fd[i] = -1;
140
4d8ac866
CB
141 ret = lxc_preserve_ns(pid, "");
142 if (ret < 0) {
143 SYSERROR("Kernel does not support attaching to namespaces.");
62d05d9b 144 return false;
4d8ac866
CB
145 } else {
146 close(ret);
cd43d2d1
SH
147 }
148
9f30a190
MM
149 for (i = 0; i < LXC_NS_MAX; i++) {
150 if ((clone_flags & ns_info[i].clone_flag) == 0)
151 continue;
4d8ac866 152 ns_fd[i] = lxc_preserve_ns(pid, ns_info[i].proc_name);
9f30a190
MM
153 if (ns_fd[i] < 0)
154 goto error;
155 }
156
62d05d9b 157 return true;
9f30a190
MM
158
159error:
4d8ac866
CB
160 if (errno == ENOENT)
161 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info[i].proc_name);
162 else
163 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info[i].proc_name, strerror(errno));
9f30a190 164 close_ns(ns_fd);
62d05d9b 165 return false;
9f30a190
MM
166}
167
168static int attach_ns(const int ns_fd[LXC_NS_MAX]) {
169 int i;
170
171 for (i = 0; i < LXC_NS_MAX; i++) {
172 if (ns_fd[i] < 0)
173 continue;
174
175 if (setns(ns_fd[i], 0) != 0)
176 goto error;
177 }
178 return 0;
179
180error:
408da065 181 SYSERROR("Failed to attach %s namespace.", ns_info[i].proc_name);
9f30a190
MM
182 return -1;
183}
184
80090207
CLG
185static int match_fd(int fd)
186{
187 return (fd == 0 || fd == 1 || fd == 2);
188}
189
408da065
CB
190/* Check for any fds we need to close.
191 * - If fd_to_ignore != -1, then if we find that fd open we will ignore it.
192 * - By default we warn about open fds we find.
193 * - If closeall is true, we will close open fds.
194 * - If lxc-start was passed "-C", then conf->close_all_fds will be true, in
195 * which case we also close all open fds.
196 * - A daemonized container will always pass closeall=true.
d2cf4c37
SH
197 */
198int lxc_check_inherited(struct lxc_conf *conf, bool closeall, int fd_to_ignore)
80090207 199{
74f96976 200 struct dirent *direntp;
80090207
CLG
201 int fd, fddir;
202 DIR *dir;
80090207 203
d2cf4c37
SH
204 if (conf && conf->close_all_fds)
205 closeall = true;
206
b119f362 207restart:
80090207
CLG
208 dir = opendir("/proc/self/fd");
209 if (!dir) {
408da065 210 WARN("Failed to open directory: %m.");
80090207
CLG
211 return -1;
212 }
213
214 fddir = dirfd(dir);
215
74f96976 216 while ((direntp = readdir(dir))) {
80090207
CLG
217 if (!direntp)
218 break;
219
220 if (!strcmp(direntp->d_name, "."))
221 continue;
222
223 if (!strcmp(direntp->d_name, ".."))
224 continue;
225
d4cff0d2
CB
226 if (lxc_safe_int(direntp->d_name, &fd) < 0) {
227 INFO("Could not parse file descriptor for: %s", direntp->d_name);
228 continue;
229 }
80090207 230
f2faa8fa 231 if (fd == fddir || fd == lxc_log_fd || fd == fd_to_ignore)
80090207
CLG
232 continue;
233
858377e4
SH
234 if (current_config && fd == current_config->logfd)
235 continue;
236
80090207
CLG
237 if (match_fd(fd))
238 continue;
80090207 239
d2cf4c37 240 if (closeall) {
b119f362
SH
241 close(fd);
242 closedir(dir);
408da065 243 INFO("Closed inherited fd: %d.", fd);
b119f362
SH
244 goto restart;
245 }
408da065 246 WARN("Inherited fd: %d.", fd);
80090207
CLG
247 }
248
408da065 249 /* Only enable syslog at this point to avoid the above logging function
64c57ea1
BD
250 * to open a new fd and make the check_inherited function enter an
251 * infinite loop.
252 */
253 lxc_log_enable_syslog();
254
92c7f629
GK
255 closedir(dir); /* cannot fail */
256 return 0;
80090207
CLG
257}
258
83ee7875 259static int setup_signal_fd(sigset_t *oldmask)
b0a33c1e 260{
261 sigset_t mask;
262 int fd;
263
408da065 264 /* Block everything except serious error signals. */
f3304a29
FW
265 if (sigfillset(&mask) ||
266 sigdelset(&mask, SIGILL) ||
267 sigdelset(&mask, SIGSEGV) ||
268 sigdelset(&mask, SIGBUS) ||
b5159817 269 sigdelset(&mask, SIGWINCH) ||
f3304a29 270 sigprocmask(SIG_BLOCK, &mask, oldmask)) {
408da065 271 SYSERROR("Failed to set signal mask.");
b0a33c1e 272 return -1;
273 }
274
275 fd = signalfd(-1, &mask, 0);
276 if (fd < 0) {
408da065 277 SYSERROR("Failed to create signal file descriptor.");
b0a33c1e 278 return -1;
279 }
280
281 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
408da065 282 SYSERROR("Failed to set FD_CLOEXEC on the signal file descriptor: %d.", fd);
b0a33c1e 283 close(fd);
284 return -1;
285 }
286
408da065 287 DEBUG("Set SIGCHLD handler with file descriptor: %d.", fd);
1ac470c0 288
b0a33c1e 289 return fd;
290}
291
84c92abd 292static int signal_handler(int fd, uint32_t events, void *data,
f3787121 293 struct lxc_epoll_descr *descr)
b0a33c1e 294{
15cd25fd 295 struct signalfd_siginfo siginfo;
80507ee8 296 siginfo_t info;
15cd25fd 297 int ret;
82d89dce 298 pid_t *pid = data;
80507ee8 299 bool init_died = false;
15cd25fd
DL
300
301 ret = read(fd, &siginfo, sizeof(siginfo));
302 if (ret < 0) {
408da065 303 ERROR("Failed to read signal info from signal file descriptor: %d.", fd);
15cd25fd
DL
304 return -1;
305 }
306
307 if (ret != sizeof(siginfo)) {
408da065 308 ERROR("Unexpected size for siginfo struct.");
15cd25fd
DL
309 return -1;
310 }
311
408da065 312 /* Check whether init is running. */
80507ee8
SH
313 info.si_pid = 0;
314 ret = waitid(P_PID, *pid, &info, WEXITED | WNOWAIT | WNOHANG);
408da065 315 if (ret == 0 && info.si_pid == *pid)
80507ee8 316 init_died = true;
80507ee8 317
f3304a29
FW
318 if (siginfo.ssi_signo != SIGCHLD) {
319 kill(*pid, siginfo.ssi_signo);
408da065 320 INFO("Forwarded signal %d to pid %d.", siginfo.ssi_signo, *pid);
80507ee8 321 return init_died ? 1 : 0;
f3304a29
FW
322 }
323
408da065
CB
324 if (siginfo.ssi_code == CLD_STOPPED) {
325 INFO("Container init process was stopped.");
326 return init_died ? 1 : 0;
327 } else if (siginfo.ssi_code == CLD_CONTINUED) {
328 INFO("Container init process was continued.");
80507ee8 329 return init_died ? 1 : 0;
15cd25fd 330 }
1ac470c0 331
408da065
CB
332 /* More robustness, protect ourself from a SIGCHLD sent
333 * by a process different from the container init.
82d89dce
DL
334 */
335 if (siginfo.ssi_pid != *pid) {
af4c0f05 336 NOTICE("Received SIGCHLD from pid %d instead of container init %d.", siginfo.ssi_pid, *pid);
80507ee8 337 return init_died ? 1 : 0;
82d89dce
DL
338 }
339
408da065 340 DEBUG("Container init process %d exited.", *pid);
b0a33c1e 341 return 1;
342}
343
735f2c6e 344int lxc_set_state(const char *name, struct lxc_handler *handler, lxc_state_t state)
66aeffc7
DL
345{
346 handler->state = state;
9123e471 347 lxc_monitor_send_state(name, state, handler->lxcpath);
66aeffc7
DL
348 return 0;
349}
350
735f2c6e 351int lxc_poll(const char *name, struct lxc_handler *handler)
b0a33c1e 352{
ca5f7926
DL
353 int sigfd = handler->sigfd;
354 int pid = handler->pid;
b0a33c1e 355 struct lxc_epoll_descr descr;
356
a9e61274 357 if (lxc_mainloop_open(&descr)) {
408da065 358 ERROR("Failed to create LXC mainloop.");
50c8bf05 359 goto out_sigfd;
b0a33c1e 360 }
361
83ee7875 362 if (lxc_mainloop_add_handler(&descr, sigfd, signal_handler, &pid)) {
408da065 363 ERROR("Failed to add signal handler with file descriptor %d to LXC mainloop.", sigfd);
b0a33c1e 364 goto out_mainloop_open;
365 }
366
da41561c 367 if (lxc_console_mainloop_add(&descr, handler->conf)) {
408da065 368 ERROR("Failed to add console handler to LXC mainloop.");
63376d7d
DL
369 goto out_mainloop_open;
370 }
371
ef6e34ee 372 if (lxc_cmd_mainloop_add(name, &descr, handler)) {
408da065 373 ERROR("Failed to add command handler to LXC mainloop.");
96fa1ff0 374 goto out_mainloop_open;
563f2f2c
DL
375 }
376
828695d9 377 if (handler->conf->need_utmp_watch) {
e37dda71 378 #if HAVE_LIBCAP
828695d9 379 if (lxc_utmp_mainloop_add(&descr, handler)) {
408da065 380 ERROR("Failed to add utmp handler to LXC mainloop.");
828695d9
SH
381 goto out_mainloop_open;
382 }
495d2046 383 #else
408da065 384 DEBUG("Not starting utmp handler as CAP_SYS_BOOT cannot be dropped without capabilities support.");
495d2046 385 #endif
563f2f2c 386 }
3f903c04 387 TRACE("lxc mainloop is ready");
b0a33c1e 388
e51d4895 389 return lxc_mainloop(&descr, -1);
b0a33c1e 390
391out_mainloop_open:
392 lxc_mainloop_close(&descr);
408da065 393
b0a33c1e 394out_sigfd:
395 close(sigfd);
408da065 396
c3e13372 397 return -1;
b0a33c1e 398}
399
aa460476
CB
400struct lxc_handler *lxc_init_handler(const char *name, struct lxc_conf *conf,
401 const char *lxcpath)
59eb99ba 402{
b6b2b194 403 int i;
3a0f472d
DL
404 struct lxc_handler *handler;
405
406 handler = malloc(sizeof(*handler));
aa460476
CB
407 if (!handler) {
408 ERROR("failed to allocate memory");
3a0f472d 409 return NULL;
aa460476 410 }
59eb99ba
DL
411
412 memset(handler, 0, sizeof(*handler));
413
e8bd4e43 414 handler->ttysock[0] = handler->ttysock[1] = -1;
fae349da 415 handler->conf = conf;
9123e471 416 handler->lxcpath = lxcpath;
5c068da9 417 handler->pinfd = -1;
fae349da 418
b6b2b194
WB
419 for (i = 0; i < LXC_NS_MAX; i++)
420 handler->nsfd[i] = -1;
421
3bdf52d7
DL
422 handler->name = strdup(name);
423 if (!handler->name) {
aa460476
CB
424 ERROR("failed to allocate memory");
425 goto do_partial_cleanup;
3bdf52d7
DL
426 }
427
aa460476
CB
428 if (lxc_cmd_init(name, handler, lxcpath)) {
429 ERROR("failed to set up command socket");
430 goto do_full_cleanup;
431 }
432
433 TRACE("unix domain socket %d for command server is ready",
434 handler->conf->maincmd_fd);
435
436 return handler;
437
438do_full_cleanup:
439 free(handler->name);
440
441do_partial_cleanup:
442 free(handler);
443
444 return NULL;
445}
446
447int lxc_init(const char *name, struct lxc_handler *handler)
448{
449 struct lxc_conf *conf = handler->conf;
450
451 lsm_init();
452 TRACE("initialized LSM");
d2e30e99 453
8f2c3a70 454 if (lxc_read_seccomp_config(conf) != 0) {
408da065 455 ERROR("Failed loading seccomp policy.");
d2e30e99 456 goto out_close_maincmd_fd;
8f2c3a70
SH
457 }
458
408da065 459 /* Begin by setting the state to STARTING. */
25c2aca5 460 if (lxc_set_state(name, handler, STARTING)) {
408da065 461 ERROR("Failed to set state for container \"%s\" to \"%s\".", name, lxc_state2str(STARTING));
051151de 462 goto out_close_maincmd_fd;
0ad19a3f 463 }
464
408da065
CB
465 /* Start of environment variable setup for hooks. */
466 if (name && setenv("LXC_NAME", name, 1))
467 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name);
468
469 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
470 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf->rcfile);
471
472 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1))
473 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf->rootfs.mount);
474
475 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
476 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf->rootfs.path);
477
478 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1))
479 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf->console.path);
480
481 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1))
482 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf->console.log_path);
483
484 if (setenv("LXC_CGNS_AWARE", "1", 1))
485 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
486 /* End of environment variable setup for hooks. */
f7bee6c6 487
283678ed 488 if (run_lxc_hooks(name, "pre-start", conf, handler->lxcpath, NULL)) {
408da065 489 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name);
773fb9ca
SH
490 goto out_aborting;
491 }
26ddeedd 492
408da065
CB
493 /* The signal fd has to be created before forking otherwise if the child
494 * process exits before we setup the signal fd, the event will be lost
495 * and the command will be stuck.
496 */
83ee7875 497 handler->sigfd = setup_signal_fd(&handler->oldmask);
59eb99ba 498 if (handler->sigfd < 0) {
408da065 499 ERROR("Failed to setup SIGCHLD fd handler.");
b5159817
DE
500 goto out_delete_tty;
501 }
502
408da065 503 /* Do this after setting up signals since it might unblock SIGWINCH. */
b5159817 504 if (lxc_console_create(conf)) {
408da065 505 ERROR("Failed to create console for container \"%s\".", name);
b5159817 506 goto out_restore_sigmask;
b0a33c1e 507 }
508
54117de5 509 if (lxc_ttys_shift_ids(conf) < 0) {
408da065 510 ERROR("Failed to shift tty into container.");
c4d10a05
SH
511 goto out_restore_sigmask;
512 }
513
408da065 514 INFO("Container \"%s\" is initialized.", name);
aa460476 515 return 0;
59eb99ba 516
b5159817
DE
517out_restore_sigmask:
518 sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
59eb99ba 519out_delete_tty:
fae349da 520 lxc_delete_tty(&conf->tty_info);
59eb99ba 521out_aborting:
25c2aca5 522 lxc_set_state(name, handler, ABORTING);
d2e30e99
DE
523out_close_maincmd_fd:
524 close(conf->maincmd_fd);
525 conf->maincmd_fd = -1;
aa460476 526 return -1;
59eb99ba
DL
527}
528
3b72c4a0 529void lxc_fini(const char *name, struct lxc_handler *handler)
59eb99ba 530{
b3286b62
WB
531 int i, rc;
532 pid_t self = getpid();
533 char *namespaces[LXC_NS_MAX+1];
534 size_t namespace_count = 0;
b6b2b194 535
408da065
CB
536 /* The STOPPING state is there for future cleanup code which can take
537 * awhile.
59eb99ba 538 */
25c2aca5 539 lxc_set_state(name, handler, STOPPING);
b6b2b194 540
b3286b62
WB
541 for (i = 0; i < LXC_NS_MAX; i++) {
542 if (handler->nsfd[i] != -1) {
543 rc = asprintf(&namespaces[namespace_count], "%s:/proc/%d/fd/%d",
544 ns_info[i].proc_name, self, handler->nsfd[i]);
545 if (rc == -1) {
408da065 546 SYSERROR("Failed to allocate memory.");
b3286b62
WB
547 break;
548 }
549 ++namespace_count;
550 }
551 }
552 namespaces[namespace_count] = NULL;
c154af98 553
408da065
CB
554 if (handler->conf->reboot && setenv("LXC_TARGET", "reboot", 1))
555 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
556
557 if (!handler->conf->reboot && setenv("LXC_TARGET", "stop", 1))
558 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
c154af98 559
b3286b62 560 if (run_lxc_hooks(name, "stop", handler->conf, handler->lxcpath, namespaces))
408da065 561 ERROR("Failed to run lxc.hook.stop for container \"%s\".", name);
c154af98 562
b3286b62
WB
563 while (namespace_count--)
564 free(namespaces[namespace_count]);
b6b2b194
WB
565 for (i = 0; i < LXC_NS_MAX; i++) {
566 if (handler->nsfd[i] != -1) {
567 close(handler->nsfd[i]);
568 handler->nsfd[i] = -1;
569 }
570 }
738d0deb
CB
571
572 if (handler->netnsfd >= 0) {
573 close(handler->netnsfd);
574 handler->netnsfd = -1;
575 }
576
25c2aca5 577 lxc_set_state(name, handler, STOPPED);
59eb99ba 578
f3787121 579 if (run_lxc_hooks(name, "post-stop", handler->conf, handler->lxcpath, NULL)) {
408da065 580 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name);
f3787121
CB
581 if (handler->conf->reboot) {
582 WARN("Container will be stopped instead of rebooted.");
583 handler->conf->reboot = 0;
408da065
CB
584 if (setenv("LXC_TARGET", "stop", 1))
585 WARN("Failed to set environment variable: LXC_TARGET=stop.");
f3787121
CB
586 }
587 }
26ddeedd 588
408da065 589 /* Reset mask set by setup_signal_fd. */
8f64a3f6 590 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
408da065 591 WARN("Failed to restore signal mask.");
8f64a3f6 592
b5159817 593 lxc_console_delete(&handler->conf->console);
b2431939 594 lxc_delete_tty(&handler->conf->tty_info);
d2e30e99
DE
595 close(handler->conf->maincmd_fd);
596 handler->conf->maincmd_fd = -1;
3bdf52d7 597 free(handler->name);
e8bd4e43
SH
598 if (handler->ttysock[0] != -1) {
599 close(handler->ttysock[0]);
600 close(handler->ttysock[1]);
601 }
2c5f2ede
CB
602
603 if (handler->conf->ephemeral == 1 && handler->conf->reboot != 1)
28272964 604 lxc_destroy_container_on_signal(handler, name);
2c5f2ede 605
d4ef7c50 606 cgroup_destroy(handler);
b2431939 607 free(handler);
59eb99ba
DL
608}
609
735f2c6e 610void lxc_abort(const char *name, struct lxc_handler *handler)
59eb99ba 611{
73e608b2
SH
612 int ret, status;
613
25c2aca5 614 lxc_set_state(name, handler, ABORTING);
7d9fb3e9
DL
615 if (handler->pid > 0)
616 kill(handler->pid, SIGKILL);
408da065
CB
617 while ((ret = waitpid(-1, &status, 0)) > 0) {
618 ;
619 }
59eb99ba
DL
620}
621
828695d9
SH
622#include <sys/reboot.h>
623#include <linux/reboot.h>
624
408da065
CB
625/* reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL in a child pid namespace
626 * if container reboot support exists. Otherwise, it will either succeed or
627 * return -EPERM.
e2fa1520
SH
628 */
629static int container_reboot_supported(void *arg)
828695d9 630{
d028235d 631 int *cmd = arg;
828695d9 632 int ret;
828695d9 633
d028235d 634 ret = reboot(*cmd);
e2fa1520
SH
635 if (ret == -1 && errno == EINVAL)
636 return 1;
637 return 0;
638}
639
b60ed720 640static int must_drop_cap_sys_boot(struct lxc_conf *conf)
e2fa1520 641{
025ed0f3 642 FILE *f;
b60ed720 643 int ret, cmd, v, flags;
d028235d
SG
644 long stack_size = 4096;
645 void *stack = alloca(stack_size);
646 int status;
647 pid_t pid;
e2fa1520 648
025ed0f3 649 f = fopen("/proc/sys/kernel/ctrl-alt-del", "r");
e2fa1520
SH
650 if (!f) {
651 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
828695d9 652 return 1;
e2fa1520 653 }
828695d9
SH
654
655 ret = fscanf(f, "%d", &v);
656 fclose(f);
e2fa1520 657 if (ret != 1) {
408da065 658 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del.");
828695d9 659 return 1;
e2fa1520
SH
660 }
661 cmd = v ? LINUX_REBOOT_CMD_CAD_ON : LINUX_REBOOT_CMD_CAD_OFF;
662
b60ed720
SH
663 flags = CLONE_NEWPID | SIGCHLD;
664 if (!lxc_list_empty(&conf->id_map))
665 flags |= CLONE_NEWUSER;
666
7f145a6d 667#ifdef __ia64__
959aee9c 668 pid = __clone2(container_reboot_supported, stack, stack_size, flags, &cmd);
7f145a6d 669#else
959aee9c
SG
670 stack += stack_size;
671 pid = clone(container_reboot_supported, stack, flags, &cmd);
7f145a6d 672#endif
959aee9c 673 if (pid < 0) {
c08220e9 674 if (flags & CLONE_NEWUSER)
408da065 675 ERROR("Failed to clone (%#x): %s (includes CLONE_NEWUSER).", flags, strerror(errno));
c08220e9 676 else
408da065 677 ERROR("Failed to clone (%#x): %s.", flags, strerror(errno));
959aee9c
SG
678 return -1;
679 }
680 if (wait(&status) < 0) {
408da065 681 SYSERROR("Unexpected wait error: %m.");
959aee9c
SG
682 return -1;
683 }
e2fa1520
SH
684
685 if (WEXITSTATUS(status) != 1)
828695d9 686 return 1;
e2fa1520 687
828695d9
SH
688 return 0;
689}
690
408da065
CB
691/* netpipe is used in the unprivileged case to transfer the ifindexes from
692 * parent to child
658979c5
SH
693 */
694static int netpipe = -1;
695
696static inline int count_veths(struct lxc_list *network)
697{
698 struct lxc_list *iterator;
699 struct lxc_netdev *netdev;
700 int count = 0;
701
702 lxc_list_for_each(iterator, network) {
703 netdev = iterator->elem;
704 if (netdev->type != LXC_NET_VETH)
705 continue;
706 count++;
707 }
708 return count;
709}
710
711static int read_unpriv_netifindex(struct lxc_list *network)
712{
713 struct lxc_list *iterator;
714 struct lxc_netdev *netdev;
715
716 if (netpipe == -1)
717 return 0;
718 lxc_list_for_each(iterator, network) {
719 netdev = iterator->elem;
720 if (netdev->type != LXC_NET_VETH)
721 continue;
722 if (!(netdev->name = malloc(IFNAMSIZ))) {
408da065 723 ERROR("Out of memory.");
658979c5
SH
724 close(netpipe);
725 return -1;
726 }
727 if (read(netpipe, netdev->name, IFNAMSIZ) != IFNAMSIZ) {
728 close(netpipe);
729 return -1;
730 }
731 }
732 close(netpipe);
733 return 0;
734}
735
ffe1e01a 736static int do_start(void *data)
50e98013 737{
7c661726 738 struct lxc_list *iterator;
23c53af9 739 struct lxc_handler *handler = data;
7a55c157
TA
740 int devnull_fd = -1, ret;
741 char path[PATH_MAX];
50e98013
DL
742
743 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL)) {
408da065 744 SYSERROR("Failed to set signal mask.");
9d7f9e52 745 return -1;
50e98013
DL
746 }
747
408da065
CB
748 /* This prctl must be before the synchro, so if the parent dies before
749 * we set the parent death signal, we will detect its death with the
750 * synchro right after, otherwise we have a window where the parent can
751 * exit before we set the pdeath signal leading to a unsupervized
752 * container.
743ecd2e
DL
753 */
754 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
408da065 755 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL.");
743ecd2e
DL
756 return -1;
757 }
758
3c22086f 759 lxc_sync_fini_parent(handler);
50e98013 760
408da065 761 /* Don't leak the pinfd to the container. */
025ed0f3 762 if (handler->pinfd >= 0) {
0d03360a 763 close(handler->pinfd);
025ed0f3 764 }
2b0e17e4 765
5b1e83cb
SH
766 if (lxc_sync_wait_parent(handler, LXC_SYNC_STARTUP))
767 return -1;
768
408da065
CB
769 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
770 * https://github.com/lxc/lxd/issues/1978.
771 */
5b1e83cb 772 if ((handler->clone_flags & (CLONE_NEWNET | CLONE_NEWUSER)) ==
408da065 773 (CLONE_NEWNET | CLONE_NEWUSER)) {
5b1e83cb
SH
774 ret = unshare(CLONE_NEWNET);
775 if (ret < 0) {
408da065 776 SYSERROR("Failed to unshare CLONE_NEWNET.");
5b1e83cb
SH
777 goto out_warn_father;
778 }
408da065 779 INFO("Unshared CLONE_NEWNET.");
5b1e83cb
SH
780 }
781
408da065
CB
782 /* Tell the parent task it can begin to configure the container and wait
783 * for it to finish.
3c22086f
CLG
784 */
785 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE))
9d7f9e52 786 return -1;
50e98013 787
658979c5
SH
788 if (read_unpriv_netifindex(&handler->conf->network) < 0)
789 goto out_warn_father;
790
408da065 791 /* If we are in a new user namespace, become root there to have
d08f8d2f 792 * privilege over our namespace.
f6d3e3e4
SH
793 */
794 if (!lxc_list_empty(&handler->conf->id_map)) {
d08f8d2f 795 if (lxc_switch_uid_gid(0, 0) < 0)
f6d3e3e4 796 goto out_warn_father;
d08f8d2f
CB
797
798 /* Drop groups only after we switched to a valid gid in the new
799 * user namespace.
800 */
801 if (lxc_setgroups(0, NULL) < 0)
c476bdce 802 goto out_warn_father;
f6d3e3e4
SH
803 }
804
99b71824 805 if (access(handler->lxcpath, X_OK)) {
c8154066
SH
806 print_top_failing_dir(handler->lxcpath);
807 goto out_warn_father;
808 }
809
e37dda71 810 #if HAVE_LIBCAP
69182a31 811 if (handler->conf->need_utmp_watch) {
828695d9 812 if (prctl(PR_CAPBSET_DROP, CAP_SYS_BOOT, 0, 0, 0)) {
408da065 813 SYSERROR("Failed to remove the CAP_SYS_BOOT capability.");
c4ea60df 814 goto out_warn_father;
828695d9 815 }
408da065 816 DEBUG("Dropped the CAP_SYS_BOOT capability.");
e2fa1520 817 }
495d2046 818 #endif
e2fa1520 819
a91cde21 820 ret = snprintf(path, sizeof(path), "%s/dev/null", handler->conf->rootfs.mount);
408da065 821 if (ret < 0 || ret >= sizeof(path))
7a55c157 822 goto out_warn_father;
7a55c157
TA
823
824 /* In order to checkpoint restore, we need to have everything in the
825 * same mount namespace. However, some containers may not have a
826 * reasonable /dev (in particular, they may not have /dev/null), so we
827 * can't set init's std fds to /dev/null by opening it from inside the
828 * container.
829 *
830 * If that's the case, fall back to using the host's /dev/null. This
831 * means that migration won't work, but at least we won't spew output
832 * where it isn't wanted.
833 */
834 if (handler->backgrounded && !handler->conf->autodev && access(path, F_OK) < 0) {
c44de748
AM
835 devnull_fd = open_devnull();
836
837 if (devnull_fd < 0)
838 goto out_warn_father;
408da065
CB
839 WARN("Using /dev/null from the host for container init's "
840 "standard file descriptors. Migration will not work.");
c44de748
AM
841 }
842
e2fa1520 843 /* Setup the container, ip, names, utsname, ... */
d4ef7c50 844 if (lxc_setup(handler)) {
408da065 845 ERROR("Failed to setup container \"%s\".", handler->name);
e2fa1520
SH
846 goto out_warn_father;
847 }
50e98013 848
408da065 849 /* Ask father to setup cgroups and wait for him to finish. */
544a48a0 850 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP))
c44de748 851 goto out_error;
544a48a0 852
deefdf8a
CB
853 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
854 * earlier we end up with a wrong view of /proc/self/cgroup. For
855 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
856 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
857 * /proc/self/cgroup would show us:
858 *
859 * 8:cpuset:/lxc/c
860 *
861 * whereas it should actually show
862 *
863 * 8:cpuset:/
864 */
865 if (cgns_supported()) {
866 if (unshare(CLONE_NEWCGROUP) < 0) {
867 INFO("Failed to unshare CLONE_NEWCGROUP.");
868 goto out_warn_father;
869 }
870 INFO("Unshared CLONE_NEWCGROUP.");
871 }
872
408da065 873 /* Set the label to change to when we exec(2) the container's init. */
7aff4f43 874 if (lsm_process_label_set(NULL, handler->conf, 1, 1) < 0)
e075f5d9 875 goto out_warn_father;
5112cd70 876
029cdff5 877 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
408da065
CB
878 * before we aren't allowed anymore.
879 */
029cdff5
CB
880 if (handler->conf->no_new_privs) {
881 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
882 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
883 goto out_warn_father;
884 }
885 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
886 }
887
0d9acb99
DE
888 /* Some init's such as busybox will set sane tty settings on stdin,
889 * stdout, stderr which it thinks is the console. We already set them
890 * the way we wanted on the real terminal, and we want init to do its
408da065
CB
891 * setup on its console ie. the pty allocated in lxc_console_create() so
892 * make sure that that pty is stdin,stdout,stderr.
0d9acb99 893 */
39a78bbe 894 if (lxc_console_set_stdfds(handler->conf->console.slave) < 0)
0d9acb99
DE
895 goto out_warn_father;
896
408da065 897 /* If we mounted a temporary proc, then unmount it now. */
5112cd70 898 tmp_proc_unmount(handler->conf);
e075f5d9 899
8f2c3a70
SH
900 if (lxc_seccomp_load(handler->conf) != 0)
901 goto out_warn_father;
902
283678ed 903 if (run_lxc_hooks(handler->name, "start", handler->conf, handler->lxcpath, NULL)) {
408da065 904 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler->name);
773fb9ca
SH
905 goto out_warn_father;
906 }
fc25b815 907
d08f8d2f
CB
908 /* The container has been setup. We can now switch to an unprivileged
909 * uid/gid.
910 */
911 if (handler->conf->is_execute) {
87bf0db0
CB
912 bool have_cap_setgid;
913 uid_t new_uid = handler->conf->init_uid;
914 gid_t new_gid = handler->conf->init_gid;
d08f8d2f
CB
915
916 /* If we are in a new user namespace we already dropped all
917 * groups when we switched to root in the new user namespace
918 * further above. Only drop groups if we can, so ensure that we
919 * have necessary privilege.
920 */
e37dda71 921 #if HAVE_LIBCAP
207c4c71 922 have_cap_setgid = lxc_proc_cap_is_set(CAP_SETGID, CAP_EFFECTIVE);
df11e022
BN
923 #else
924 have_cap_setgid = false;
925 #endif
87bf0db0 926 if (lxc_list_empty(&handler->conf->id_map) && have_cap_setgid) {
d08f8d2f
CB
927 if (lxc_setgroups(0, NULL) < 0)
928 goto out_warn_father;
929 }
930
931 if (lxc_switch_uid_gid(new_uid, new_gid) < 0)
932 goto out_warn_father;
933 }
934
408da065
CB
935 /* The clearenv() and putenv() calls have been moved here to allow us to
936 * use environment variables passed to the various hooks, such as the
937 * start hook above. Not all of the variables like CONFIG_PATH or ROOTFS
938 * are valid in this context but others are.
939 */
f7bee6c6 940 if (clearenv()) {
408da065
CB
941 SYSERROR("Failed to clear environment.");
942 /* Don't error out though. */
f7bee6c6
MW
943 }
944
7c661726
MP
945 lxc_list_for_each(iterator, &handler->conf->environment) {
946 if (putenv((char *)iterator->elem)) {
408da065 947 SYSERROR("Failed to set environment variable: %s.", (char *)iterator->elem);
7c661726
MP
948 goto out_warn_father;
949 }
950 }
951
f7bee6c6 952 if (putenv("container=lxc")) {
408da065 953 SYSERROR("Failed to set environment variable: container=lxc.");
c4ea60df 954 goto out_warn_father;
f7bee6c6
MW
955 }
956
393903d1
SH
957 if (handler->conf->pty_names) {
958 if (putenv(handler->conf->pty_names)) {
408da065 959 SYSERROR("Failed to set environment variable for container ptys.");
393903d1
SH
960 goto out_warn_father;
961 }
962 }
963
773fb9ca 964 close(handler->sigfd);
26ddeedd 965
7a55c157
TA
966 if (devnull_fd < 0) {
967 devnull_fd = open_devnull();
968
969 if (devnull_fd < 0)
970 goto out_warn_father;
971 }
972
c44de748 973 if (handler->backgrounded && set_stdfds(devnull_fd))
69aeabac 974 goto out_warn_father;
507cee36 975
c44de748
AM
976 if (devnull_fd >= 0) {
977 close(devnull_fd);
978 devnull_fd = -1;
979 }
980
8c9a7665
TA
981 setsid();
982
408da065
CB
983 /* After this call, we are in error because this ops should not return
984 * as it execs.
985 */
c4ea60df 986 handler->ops->start(handler, handler->data);
50e98013
DL
987
988out_warn_father:
408da065
CB
989 /* We want the parent to know something went wrong, so we return a
990 * special error code.
991 */
d1ccb562 992 lxc_sync_wake_parent(handler, LXC_SYNC_ERROR);
c44de748
AM
993
994out_error:
995 if (devnull_fd >= 0)
996 close(devnull_fd);
997
50e98013
DL
998 return -1;
999}
1000
74a3920a 1001static int save_phys_nics(struct lxc_conf *conf)
7b35f3d6
SH
1002{
1003 struct lxc_list *iterator;
40f2f8a2 1004 int am_root = (getuid() == 0);
7b35f3d6 1005
40f2f8a2
LQ
1006 if (!am_root)
1007 return 0;
2c5f2ede 1008
7b35f3d6
SH
1009 lxc_list_for_each(iterator, &conf->network) {
1010 struct lxc_netdev *netdev = iterator->elem;
1011
1012 if (netdev->type != LXC_NET_PHYS)
1013 continue;
1014 conf->saved_nics = realloc(conf->saved_nics,
1015 (conf->num_savednics+1)*sizeof(struct saved_nic));
408da065 1016 if (!conf->saved_nics)
7b35f3d6 1017 return -1;
7b35f3d6
SH
1018 conf->saved_nics[conf->num_savednics].ifindex = netdev->ifindex;
1019 conf->saved_nics[conf->num_savednics].orig_name = strdup(netdev->link);
408da065 1020 if (!conf->saved_nics[conf->num_savednics].orig_name)
7b35f3d6 1021 return -1;
408da065 1022 INFO("Stored saved_nic #%d idx %d name %s.", conf->num_savednics,
7b35f3d6
SH
1023 conf->saved_nics[conf->num_savednics].ifindex,
1024 conf->saved_nics[conf->num_savednics].orig_name);
1025 conf->num_savednics++;
1026 }
1027
1028 return 0;
1029}
1030
ae467c54 1031static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
e8bd4e43 1032{
ae467c54
CB
1033 int i;
1034 int *ttyfds;
1035 struct lxc_pty_info *pty_info;
1036 int ret = -1;
f07fa8df 1037 int sock = handler->ttysock[1];
e8bd4e43 1038 struct lxc_conf *conf = handler->conf;
e8bd4e43 1039 struct lxc_tty_info *tty_info = &conf->tty_info;
ae467c54 1040 size_t num_ttyfds = (2 * conf->tty);
e8bd4e43
SH
1041
1042 if (!conf->tty)
1043 return 0;
1044
408da065
CB
1045 tty_info->pty_info = malloc(sizeof(*tty_info->pty_info) * conf->tty);
1046 if (!tty_info->pty_info)
e8bd4e43 1047 return -1;
e8bd4e43 1048
ae467c54
CB
1049 ttyfds = malloc(num_ttyfds * sizeof(int));
1050 if (!ttyfds)
1051 return -1;
1052
1053 ret = lxc_abstract_unix_recv_fds(sock, ttyfds, num_ttyfds, NULL, 0);
1054 for (i = 0; (ret >= 0 && *ttyfds != -1) && (i < num_ttyfds); i++) {
1055 pty_info = &tty_info->pty_info[i / 2];
e8bd4e43 1056 pty_info->busy = 0;
ae467c54
CB
1057 pty_info->slave = ttyfds[i++];
1058 pty_info->master = ttyfds[i];
1059 TRACE("received pty with master fd %d and slave fd %d from "
1060 "parent", pty_info->master, pty_info->slave);
e8bd4e43 1061 }
ae467c54 1062
e8bd4e43
SH
1063 tty_info->nbtty = conf->tty;
1064
ae467c54
CB
1065 free(ttyfds);
1066
1067 if (ret < 0)
1068 ERROR("failed to receive %d ttys from child: %s", conf->tty,
1069 strerror(errno));
1070 else
1071 TRACE("received %d ttys from child", conf->tty);
1072
1073 return ret;
e8bd4e43
SH
1074}
1075
f813849c
TA
1076void resolve_clone_flags(struct lxc_handler *handler)
1077{
1078 handler->clone_flags = CLONE_NEWPID | CLONE_NEWNS;
1079
408da065 1080 if (!lxc_list_empty(&handler->conf->id_map))
f813849c 1081 handler->clone_flags |= CLONE_NEWUSER;
f813849c
TA
1082
1083 if (handler->conf->inherit_ns_fd[LXC_NS_NET] == -1) {
408da065 1084 if (!lxc_requests_empty_network(handler))
f813849c
TA
1085 handler->clone_flags |= CLONE_NEWNET;
1086 } else {
198cbbaa 1087 INFO("Inheriting a NET namespace.");
f813849c
TA
1088 }
1089
408da065 1090 if (handler->conf->inherit_ns_fd[LXC_NS_IPC] == -1)
f813849c 1091 handler->clone_flags |= CLONE_NEWIPC;
408da065 1092 else
198cbbaa 1093 INFO("Inheriting an IPC namespace.");
f813849c 1094
408da065 1095 if (handler->conf->inherit_ns_fd[LXC_NS_UTS] == -1)
f813849c 1096 handler->clone_flags |= CLONE_NEWUTS;
408da065 1097 else
198cbbaa 1098 INFO("Inheriting a UTS namespace.");
f813849c
TA
1099}
1100
480588e6
CB
1101/* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1102 * exec()s the requested container binary.
1103 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1104 * right here should be double checked if they'd pose a security risk. (For
1105 * example, any {u}mount() operations performed here will be reflected on the
1106 * host!)
1107 */
74a3920a 1108static int lxc_spawn(struct lxc_handler *handler)
59eb99ba 1109{
b98f7d6e 1110 int failed_before_rename = 0;
ffe1e01a 1111 const char *name = handler->name;
7e4dfe0b 1112 bool cgroups_connected = false;
9f30a190 1113 int saved_ns_fd[LXC_NS_MAX];
5b1e83cb 1114 int preserve_mask = 0, i, flags;
658979c5 1115 int netpipepair[2], nveths;
57927bf2
CB
1116 bool wants_to_map_ids;
1117 struct lxc_list *id_map;
9f30a190 1118
2f2623ec 1119 netpipe = -1;
57927bf2
CB
1120 id_map = &handler->conf->id_map;
1121 wants_to_map_ids = !lxc_list_empty(id_map);
2f2623ec 1122
9f30a190 1123 for (i = 0; i < LXC_NS_MAX; i++)
6c544cb3 1124 if (handler->conf->inherit_ns_fd[i] != -1)
9f30a190 1125 preserve_mask |= ns_info[i].clone_flag;
50e98013 1126
3c22086f 1127 if (lxc_sync_init(handler))
9d7f9e52 1128 return -1;
0ad19a3f 1129
e8bd4e43
SH
1130 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, handler->ttysock) < 0) {
1131 lxc_sync_fini(handler);
1132 return -1;
1133 }
1134
f813849c 1135 resolve_clone_flags(handler);
9f30a190 1136
f813849c 1137 if (handler->clone_flags & CLONE_NEWNET) {
26b797f3
SH
1138 if (!lxc_list_empty(&handler->conf->network)) {
1139
9f30a190
MM
1140 /* Find gateway addresses from the link device, which is
1141 * no longer accessible inside the container. Do this
1142 * before creating network interfaces, since goto
408da065
CB
1143 * out_delete_net does not work before lxc_clone.
1144 */
9f30a190 1145 if (lxc_find_gateway_addresses(handler)) {
408da065 1146 ERROR("Failed to find gateway addresses.");
9f30a190
MM
1147 lxc_sync_fini(handler);
1148 return -1;
1149 }
1150
408da065
CB
1151 /* That should be done before the clone because we will
1152 * fill the netdev index and use them in the child.
9f30a190
MM
1153 */
1154 if (lxc_create_network(handler)) {
408da065 1155 ERROR("Failed to create the network.");
9f30a190
MM
1156 lxc_sync_fini(handler);
1157 return -1;
1158 }
19a26f82
MK
1159 }
1160
9f30a190 1161 if (save_phys_nics(handler->conf)) {
408da065 1162 ERROR("Failed to save physical nic info.");
9f30a190 1163 goto out_abort;
82d5ae15
DL
1164 }
1165 }
1166
d4ef7c50 1167 if (!cgroup_init(handler)) {
408da065 1168 ERROR("Failed initializing cgroup support.");
33ad9f1a
CS
1169 goto out_delete_net;
1170 }
1171
7e4dfe0b
SH
1172 cgroups_connected = true;
1173
d4ef7c50 1174 if (!cgroup_create(handler)) {
408da065 1175 ERROR("Failed creating cgroups.");
47d8fb3b
CS
1176 goto out_delete_net;
1177 }
1178
408da065
CB
1179 /* If the rootfs is not a blockdev, prevent the container from marking
1180 * it readonly.
1181 * If the container is unprivileged then skip rootfs pinning.
0c547523 1182 */
0ee35059 1183 if (!wants_to_map_ids) {
5e32a990
ÇO
1184 handler->pinfd = pin_rootfs(handler->conf->rootfs.path);
1185 if (handler->pinfd == -1)
408da065 1186 INFO("Failed to pin the rootfs for container \"%s\".", handler->name);
5e32a990 1187 }
0c547523 1188
4d8ac866 1189 if (!preserve_ns(saved_ns_fd, preserve_mask, getpid()))
cd43d2d1 1190 goto out_delete_net;
4d8ac866 1191
cd43d2d1
SH
1192 if (attach_ns(handler->conf->inherit_ns_fd) < 0)
1193 goto out_delete_net;
9f30a190 1194
658979c5
SH
1195 if (am_unpriv() && (nveths = count_veths(&handler->conf->network))) {
1196 if (pipe(netpipepair) < 0) {
408da065 1197 SYSERROR("Failed to create pipe.");
658979c5
SH
1198 goto out_delete_net;
1199 }
408da065 1200 /* Store netpipe in the global var for do_start's use. */
658979c5
SH
1201 netpipe = netpipepair[0];
1202 }
1203
408da065 1204 /* Create a process in a new set of namespaces. */
5b1e83cb 1205 flags = handler->clone_flags;
408da065
CB
1206 if (handler->clone_flags & CLONE_NEWUSER) {
1207 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1208 * clone a new user namespace first and only later unshare our
1209 * network namespace to ensure that network devices ownership is
1210 * set up correctly.
1211 */
5b1e83cb 1212 flags &= ~CLONE_NEWNET;
408da065 1213 }
9fac8fbb 1214 handler->pid = lxc_clone(do_start, handler, flags);
59eb99ba 1215 if (handler->pid < 0) {
408da065 1216 SYSERROR("Failed to clone a new set of namespaces.");
7fef7a06 1217 goto out_delete_net;
0ad19a3f 1218 }
9662e444
CB
1219 for (i = 0; i < LXC_NS_MAX; i++)
1220 if (flags & ns_info[i].clone_flag)
1221 INFO("Cloned %s.", ns_info[i].flag_name);
0ad19a3f 1222
4d8ac866
CB
1223 if (!preserve_ns(handler->nsfd, handler->clone_flags | preserve_mask, handler->pid))
1224 INFO("Failed to preserve namespace for lxc.hook.stop.");
b6b2b194 1225
cd43d2d1 1226 if (attach_ns(saved_ns_fd))
408da065 1227 WARN("Failed to restore saved namespaces.");
9f30a190 1228
3c22086f
CLG
1229 lxc_sync_fini_child(handler);
1230
408da065
CB
1231 /* Map the container uids. The container became an invalid userid the
1232 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1233 * anything immediately, but allows the container to setuid(0) (0 being
1234 * mapped to something else on the host.) later to become a valid uid
1235 * again.
1236 */
57927bf2 1237 if (wants_to_map_ids && lxc_map_ids(id_map, handler->pid)) {
408da065 1238 ERROR("Failed to set up id mapping.");
5b1e83cb
SH
1239 goto out_delete_net;
1240 }
1241
1242 if (lxc_sync_wake_child(handler, LXC_SYNC_STARTUP)) {
99a6af52 1243 failed_before_rename = 1;
5b1e83cb
SH
1244 goto out_delete_net;
1245 }
1246
1247 if (lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE)) {
1248 failed_before_rename = 1;
1249 goto out_delete_net;
1250 }
0ad19a3f 1251
d4ef7c50 1252 if (!cgroup_create_legacy(handler)) {
408da065 1253 ERROR("Failed to setup legacy cgroups for container \"%s\".", name);
ae5c8b8e 1254 goto out_delete_net;
33ad9f1a 1255 }
9daf6f5d 1256 if (!cgroup_setup_limits(handler, false)) {
408da065 1257 ERROR("Failed to setup cgroup limits for container \"%s\".", name);
6031a6e5
DE
1258 goto out_delete_net;
1259 }
1260
d4ef7c50 1261 if (!cgroup_enter(handler))
7fef7a06 1262 goto out_delete_net;
218d4250 1263
0996e18a
SH
1264 if (!cgroup_chown(handler))
1265 goto out_delete_net;
1266
99a6af52
MN
1267 if (failed_before_rename)
1268 goto out_delete_net;
1269
408da065 1270 /* Create the network configuration. */
d5088cf2 1271 if (handler->clone_flags & CLONE_NEWNET) {
c43cbc04 1272 if (lxc_assign_network(handler->lxcpath, handler->name,
408da065
CB
1273 &handler->conf->network, handler->pid)) {
1274 ERROR("Failed to create the configured network.");
7fef7a06 1275 goto out_delete_net;
82d5ae15 1276 }
0ad19a3f 1277 }
1278
658979c5
SH
1279 if (netpipe != -1) {
1280 struct lxc_list *iterator;
1281 struct lxc_netdev *netdev;
1282
1283 close(netpipe);
1284 lxc_list_for_each(iterator, &handler->conf->network) {
1285 netdev = iterator->elem;
1286 if (netdev->type != LXC_NET_VETH)
1287 continue;
1288 if (write(netpipepair[1], netdev->name, IFNAMSIZ) != IFNAMSIZ) {
408da065 1289 ERROR("Error writing veth name to container.");
658979c5
SH
1290 goto out_delete_net;
1291 }
1292 }
1293 close(netpipepair[1]);
1294 }
1295
408da065
CB
1296 /* Tell the child to continue its initialization. We'll get
1297 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
3c22086f
CLG
1298 */
1299 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE))
544a48a0
SH
1300 goto out_delete_net;
1301
c6d09e15
WB
1302 if (!lxc_list_empty(&handler->conf->limits) && setup_resource_limits(&handler->conf->limits, handler->pid)) {
1303 ERROR("failed to setup resource limits for '%s'", name);
84ff3af7 1304 goto out_delete_net;
c6d09e15
WB
1305 }
1306
9daf6f5d 1307 if (!cgroup_setup_limits(handler, true)) {
408da065 1308 ERROR("Failed to setup the devices cgroup for container \"%s\".", name);
b98f7d6e 1309 goto out_delete_net;
544a48a0
SH
1310 }
1311
73d28d42 1312 cgroup_disconnect();
7e4dfe0b 1313 cgroups_connected = false;
73d28d42 1314
408da065 1315 /* Read tty fds allocated by child. */
ae467c54 1316 if (lxc_recv_ttys_from_child(handler) < 0) {
408da065 1317 ERROR("Failed to receive tty info from child process.");
e8bd4e43
SH
1318 goto out_delete_net;
1319 }
1320
408da065
CB
1321 /* Tell the child to complete its initialization and wait for it to exec
1322 * or return an error. (The child will never return
1323 * LXC_SYNC_POST_CGROUP+1. It will either close the sync pipe, causing
1324 * lxc_sync_barrier_child to return success, or return a different
1325 * value, causing us to error out).
544a48a0
SH
1326 */
1327 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CGROUP))
3c22086f 1328 return -1;
0ad19a3f 1329
23c53af9 1330 if (handler->ops->post_start(handler, handler->data))
e6126dbe
MN
1331 goto out_abort;
1332
25c2aca5 1333 if (lxc_set_state(name, handler, RUNNING)) {
408da065
CB
1334 ERROR("Failed to set state for container \"%s\" to \"%s\".", name,
1335 lxc_state2str(RUNNING));
59eb99ba 1336 goto out_abort;
3f21c114 1337 }
22ebac19 1338
3c22086f 1339 lxc_sync_fini(handler);
738d0deb 1340 handler->netnsfd = lxc_preserve_ns(handler->pid, "net");
0c547523 1341
e6126dbe 1342 return 0;
1ac470c0 1343
7fef7a06 1344out_delete_net:
7e4dfe0b
SH
1345 if (cgroups_connected)
1346 cgroup_disconnect();
d5088cf2 1347 if (handler->clone_flags & CLONE_NEWNET)
74a2b586 1348 lxc_delete_network(handler);
59eb99ba
DL
1349out_abort:
1350 lxc_abort(name, handler);
3c22086f 1351 lxc_sync_fini(handler);
5c068da9
SH
1352 if (handler->pinfd >= 0) {
1353 close(handler->pinfd);
1354 handler->pinfd = -1;
1355 }
1356
b79fcd86 1357 return -1;
59eb99ba 1358}
0ad19a3f 1359
aa460476 1360int __lxc_start(const char *name, struct lxc_handler *handler,
507cee36
TA
1361 struct lxc_operations* ops, void *data, const char *lxcpath,
1362 bool backgrounded)
59eb99ba 1363{
59eb99ba 1364 int status;
aa460476 1365 int err = -1;
358daf49 1366 bool removed_all_netdevs = true;
aa460476 1367 struct lxc_conf *conf = handler->conf;
80090207 1368
aa460476 1369 if (lxc_init(name, handler) < 0) {
408da065 1370 ERROR("Failed to initialize container \"%s\".", name);
66aeffc7 1371 return -1;
0ad19a3f 1372 }
ee70bf78
CLG
1373 handler->ops = ops;
1374 handler->data = data;
507cee36 1375 handler->backgrounded = backgrounded;
738d0deb 1376 handler->netnsfd = -1;
e6126dbe 1377
b60ed720 1378 if (must_drop_cap_sys_boot(handler->conf)) {
e37dda71 1379 #if HAVE_LIBCAP
408da065 1380 DEBUG("Dropping CAP_SYS_BOOT capability.");
495d2046 1381 #else
408da065 1382 DEBUG("Not dropping CAP_SYS_BOOT capability as capabilities aren't supported.");
495d2046 1383 #endif
69182a31 1384 } else {
408da065 1385 DEBUG("Not dropping CAP_SYS_BOOT or watching utmp.");
69182a31
SH
1386 handler->conf->need_utmp_watch = 0;
1387 }
1388
76a26f55 1389 if (!attach_block_device(handler->conf)) {
408da065 1390 ERROR("Failed to attach block device.");
76a26f55
SH
1391 goto out_fini_nonet;
1392 }
1393
35120d9c 1394 if (geteuid() == 0 && !lxc_list_empty(&conf->id_map)) {
408da065 1395 /* If the backing store is a device, mount it here and now. */
35120d9c
SH
1396 if (rootfs_is_blockdev(conf)) {
1397 if (unshare(CLONE_NEWNS) < 0) {
408da065 1398 ERROR("Failed to unshare CLONE_NEWNS.");
35120d9c
SH
1399 goto out_fini_nonet;
1400 }
408da065
CB
1401 INFO("Unshared CLONE_NEWNS.");
1402
6a0c909a 1403 remount_all_slave();
35120d9c 1404 if (do_rootfs_setup(conf, name, lxcpath) < 0) {
408da065 1405 ERROR("Error setting up rootfs mount as root before spawn.");
35120d9c
SH
1406 goto out_fini_nonet;
1407 }
408da065 1408 INFO("Set up container rootfs as host root.");
35120d9c
SH
1409 }
1410 }
1411
23c53af9 1412 err = lxc_spawn(handler);
59eb99ba 1413 if (err) {
408da065 1414 ERROR("Failed to spawn container \"%s\".", name);
76a26f55 1415 goto out_detach_blockdev;
0ad19a3f 1416 }
1417
8bee8851
WB
1418 handler->conf->reboot = 0;
1419
3a0f472d 1420 err = lxc_poll(name, handler);
e043236e 1421 if (err) {
408da065 1422 ERROR("LXC mainloop exited with error: %d.", err);
738d0deb
CB
1423 if (handler->netnsfd >= 0) {
1424 close(handler->netnsfd);
1425 handler->netnsfd = -1;
1426 }
59eb99ba
DL
1427 goto out_abort;
1428 }
0ad19a3f 1429
3a0f472d 1430 while (waitpid(handler->pid, &status, 0) < 0 && errno == EINTR)
1bc5cc8c 1431 continue;
e043236e 1432
408da065
CB
1433 /* If the child process exited but was not signaled, it didn't call
1434 * reboot. This should mean it was an lxc-execute which simply exited.
1435 * In any case, treat it as a 'halt'.
8b004f07 1436 */
d028235d 1437 if (WIFSIGNALED(status)) {
8b004f07
SH
1438 switch(WTERMSIG(status)) {
1439 case SIGINT: /* halt */
408da065 1440 DEBUG("Container \"%s\" is halting.", name);
8b004f07
SH
1441 break;
1442 case SIGHUP: /* reboot */
408da065 1443 DEBUG("Container \"%s\" is rebooting.", name);
8b004f07
SH
1444 handler->conf->reboot = 1;
1445 break;
c2b9bd9e 1446 case SIGSYS: /* seccomp */
408da065 1447 DEBUG("Container \"%s\" violated its seccomp policy.", name);
c2b9bd9e 1448 break;
8b004f07 1449 default:
408da065 1450 DEBUG("Unknown exit status for container \"%s\" init %d.", name, WTERMSIG(status));
8b004f07
SH
1451 break;
1452 }
d028235d 1453 }
828695d9 1454
ce5782df 1455 DEBUG("Pushing physical nics back to host namespace");
738d0deb 1456 lxc_restore_phys_nics_to_netns(handler->netnsfd, handler->conf);
ce5782df 1457
408da065 1458 DEBUG("Tearing down virtual network devices used by container \"%s\".", name);
358daf49 1459 removed_all_netdevs = lxc_delete_network(handler);
ce5782df 1460
5c068da9
SH
1461 if (handler->pinfd >= 0) {
1462 close(handler->pinfd);
1463 handler->pinfd = -1;
1464 }
1465
1787abca 1466 lxc_monitor_send_exit_code(name, status, handler->lxcpath);
3a0f472d 1467 err = lxc_error_set_and_log(handler->pid, status);
9d7f9e52 1468out_fini:
358daf49 1469 if (!removed_all_netdevs) {
408da065 1470 DEBUG("Failed tearing down network devices used by container. Trying again!");
358daf49
CB
1471 removed_all_netdevs = lxc_delete_network(handler);
1472 if (!removed_all_netdevs)
1473 DEBUG("Failed tearing down network devices used by container. Not trying again!");
1474 }
74a2b586 1475
76a26f55
SH
1476out_detach_blockdev:
1477 detach_block_device(handler->conf);
1478
74a2b586 1479out_fini_nonet:
3a0f472d 1480 lxc_fini(name, handler);
0ad19a3f 1481 return err;
1482
59eb99ba 1483out_abort:
3a0f472d 1484 lxc_abort(name, handler);
9d7f9e52 1485 goto out_fini;
0ad19a3f 1486}
ee70bf78
CLG
1487
1488struct start_args {
1489 char *const *argv;
1490};
1491
1492static int start(struct lxc_handler *handler, void* data)
1493{
1494 struct start_args *arg = data;
1495
408da065 1496 NOTICE("Exec'ing \"%s\".", arg->argv[0]);
ee70bf78
CLG
1497
1498 execvp(arg->argv[0], arg->argv);
408da065 1499 SYSERROR("Failed to exec \"%s\".", arg->argv[0]);
ee70bf78
CLG
1500 return 0;
1501}
1502
1503static int post_start(struct lxc_handler *handler, void* data)
1504{
1505 struct start_args *arg = data;
1506
408da065 1507 NOTICE("Started \"%s\" with pid \"%d\".", arg->argv[0], handler->pid);
ee70bf78
CLG
1508 return 0;
1509}
1510
1511static struct lxc_operations start_ops = {
1512 .start = start,
1513 .post_start = post_start
1514};
1515
aa460476 1516int lxc_start(const char *name, char *const argv[], struct lxc_handler *handler,
507cee36 1517 const char *lxcpath, bool backgrounded)
ee70bf78
CLG
1518{
1519 struct start_args start_arg = {
1520 .argv = argv,
1521 };
1522
aa460476
CB
1523 handler->conf->need_utmp_watch = 1;
1524 return __lxc_start(name, handler, &start_ops, &start_arg, lxcpath, backgrounded);
ee70bf78 1525}
28272964
CB
1526
1527static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
1528 const char *name)
1529{
1530 char destroy[MAXPATHLEN];
1531 bool bret = true;
1532 int ret = 0;
f01f7975 1533 struct lxc_container *c;
df31363a 1534 if (handler->conf->rootfs.path && handler->conf->rootfs.mount) {
28272964
CB
1535 bret = do_destroy_container(handler->conf);
1536 if (!bret) {
408da065 1537 ERROR("Error destroying rootfs for container \"%s\".", name);
28272964
CB
1538 return;
1539 }
1540 }
408da065 1541 INFO("Destroyed rootfs for container \"%s\".", name);
28272964
CB
1542
1543 ret = snprintf(destroy, MAXPATHLEN, "%s/%s", handler->lxcpath, name);
1544 if (ret < 0 || ret >= MAXPATHLEN) {
408da065 1545 ERROR("Error destroying directory for container \"%s\".", name);
28272964
CB
1546 return;
1547 }
1548
f01f7975
CB
1549 c = lxc_container_new(name, handler->lxcpath);
1550 if (c) {
1551 if (container_disk_lock(c)) {
408da065 1552 INFO("Could not update lxc_snapshots file.");
f01f7975
CB
1553 lxc_container_put(c);
1554 } else {
1555 mod_all_rdeps(c, false);
1556 container_disk_unlock(c);
1557 lxc_container_put(c);
1558 }
1559 }
1560
28272964 1561 if (am_unpriv())
c9b7c33e
CB
1562 ret = userns_exec_1(handler->conf, lxc_rmdir_onedev_wrapper,
1563 destroy, "lxc_rmdir_onedev_wrapper");
28272964
CB
1564 else
1565 ret = lxc_rmdir_onedev(destroy, NULL);
1566
1567 if (ret < 0) {
408da065 1568 ERROR("Error destroying directory for container \"%s\".", name);
28272964
CB
1569 return;
1570 }
408da065 1571 INFO("Destroyed directory for container \"%s\".", name);
28272964
CB
1572}
1573
1574static int lxc_rmdir_onedev_wrapper(void *data)
1575{
1576 char *arg = (char *) data;
1577 return lxc_rmdir_onedev(arg, NULL);
1578}
1579
1580static bool do_destroy_container(struct lxc_conf *conf) {
d028235d 1581 if (am_unpriv()) {
c9b7c33e
CB
1582 if (userns_exec_1(conf, bdev_destroy_wrapper, conf,
1583 "bdev_destroy_wrapper") < 0)
d028235d
SG
1584 return false;
1585 return true;
1586 }
1587 return bdev_destroy(conf);
28272964 1588}