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