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