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