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