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