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