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