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