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