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