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