]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/start.c
console: adapt lxc_console_mainloop_add()
[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"
1cc8bd4b 76#include "list.h"
f3787121 77#include "log.h"
f2d5a09d 78#include "lxccontainer.h"
f3787121
CB
79#include "lxclock.h"
80#include "lxcseccomp.h"
f3787121 81#include "mainloop.h"
63376d7d 82#include "monitor.h"
f549edcc 83#include "namespace.h"
811ef482 84#include "network.h"
f3787121 85#include "start.h"
28d832c4 86#include "storage.h"
f2d5a09d 87#include "storage_utils.h"
f3787121
CB
88#include "sync.h"
89#include "utils.h"
fe4de9a6 90#include "lsm/lsm.h"
36eb9bde
CLG
91
92lxc_log_define(lxc_start, lxc);
93
f01f7975 94extern void mod_all_rdeps(struct lxc_container *c, bool inc);
790255cf 95static bool do_destroy_container(struct lxc_handler *handler);
28272964
CB
96static int lxc_rmdir_onedev_wrapper(void *data);
97static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
98 const char *name);
99
c8154066
SH
100static void print_top_failing_dir(const char *path)
101{
102 size_t len = strlen(path);
f3787121 103 char *copy = alloca(len + 1), *p, *e, saved;
c8154066
SH
104 strcpy(copy, path);
105
106 p = copy;
107 e = copy + len;
108 while (p < e) {
f3787121
CB
109 while (p < e && *p == '/')
110 p++;
111 while (p < e && *p != '/')
112 p++;
c8154066
SH
113 saved = *p;
114 *p = '\0';
115 if (access(copy, X_OK)) {
408da065
CB
116 SYSERROR("Could not access %s. Please grant it x "
117 "access, or add an ACL for the container "
118 "root.", copy);
c8154066
SH
119 return;
120 }
121 *p = saved;
122 }
123}
124
408da065
CB
125static void close_ns(int ns_fd[LXC_NS_MAX])
126{
9f30a190
MM
127 int i;
128
9f30a190
MM
129 for (i = 0; i < LXC_NS_MAX; i++) {
130 if (ns_fd[i] > -1) {
131 close(ns_fd[i]);
132 ns_fd[i] = -1;
133 }
134 }
9f30a190
MM
135}
136
4d8ac866 137/* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
62d05d9b 138 * in clone_flags.
4d8ac866 139 * Return true on success, false on failure.
62d05d9b 140 */
4d8ac866 141static bool preserve_ns(int ns_fd[LXC_NS_MAX], int clone_flags, pid_t pid)
f3787121 142{
62d05d9b 143 int i, ret;
9f30a190 144
9f30a190
MM
145 for (i = 0; i < LXC_NS_MAX; i++)
146 ns_fd[i] = -1;
147
4d8ac866
CB
148 ret = lxc_preserve_ns(pid, "");
149 if (ret < 0) {
150 SYSERROR("Kernel does not support attaching to namespaces.");
62d05d9b 151 return false;
4d8ac866
CB
152 } else {
153 close(ret);
cd43d2d1
SH
154 }
155
9f30a190
MM
156 for (i = 0; i < LXC_NS_MAX; i++) {
157 if ((clone_flags & ns_info[i].clone_flag) == 0)
158 continue;
28d9e29e 159
4d8ac866 160 ns_fd[i] = lxc_preserve_ns(pid, ns_info[i].proc_name);
9f30a190
MM
161 if (ns_fd[i] < 0)
162 goto error;
fa3a5b22
CB
163
164 DEBUG("Preserved %s namespace via fd %d", ns_info[i].proc_name, ns_fd[i]);
9f30a190
MM
165 }
166
62d05d9b 167 return true;
9f30a190
MM
168
169error:
4d8ac866
CB
170 if (errno == ENOENT)
171 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info[i].proc_name);
172 else
173 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info[i].proc_name, strerror(errno));
9f30a190 174 close_ns(ns_fd);
62d05d9b 175 return false;
9f30a190
MM
176}
177
80090207
CLG
178static int match_fd(int fd)
179{
180 return (fd == 0 || fd == 1 || fd == 2);
181}
182
47a46cf1
CB
183int lxc_check_inherited(struct lxc_conf *conf, bool closeall,
184 int *fds_to_ignore, size_t len_fds)
80090207 185{
74f96976 186 struct dirent *direntp;
80090207 187 int fd, fddir;
47a46cf1 188 size_t i;
80090207 189 DIR *dir;
80090207 190
d2cf4c37
SH
191 if (conf && conf->close_all_fds)
192 closeall = true;
193
b119f362 194restart:
80090207
CLG
195 dir = opendir("/proc/self/fd");
196 if (!dir) {
13277ec4 197 WARN("Failed to open directory: %s.", strerror(errno));
80090207
CLG
198 return -1;
199 }
200
201 fddir = dirfd(dir);
202
74f96976 203 while ((direntp = readdir(dir))) {
d39b10eb
CB
204 struct lxc_list *cur;
205 bool matched = false;
206
80090207
CLG
207 if (!strcmp(direntp->d_name, "."))
208 continue;
209
210 if (!strcmp(direntp->d_name, ".."))
211 continue;
212
d4cff0d2
CB
213 if (lxc_safe_int(direntp->d_name, &fd) < 0) {
214 INFO("Could not parse file descriptor for: %s", direntp->d_name);
215 continue;
216 }
80090207 217
47a46cf1
CB
218 for (i = 0; i < len_fds; i++)
219 if (fds_to_ignore[i] == fd)
220 break;
221
222 if (fd == fddir || fd == lxc_log_fd ||
223 (i < len_fds && fd == fds_to_ignore[i]))
80090207
CLG
224 continue;
225
d39b10eb 226 /* Keep state clients that wait on reboots. */
3ee9e4fb
CB
227 if (conf) {
228 lxc_list_for_each(cur, &conf->state_clients) {
229 struct lxc_state_client *client = cur->elem;
d39b10eb 230
3ee9e4fb
CB
231 if (client->clientfd != fd)
232 continue;
d39b10eb 233
3ee9e4fb
CB
234 matched = true;
235 break;
236 }
d39b10eb
CB
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 int ret;
3c319edb
CB
304 siginfo_t info;
305 struct signalfd_siginfo siginfo;
306 struct lxc_handler *hdlr = data;
15cd25fd
DL
307
308 ret = read(fd, &siginfo, sizeof(siginfo));
309 if (ret < 0) {
408da065 310 ERROR("Failed to read signal info from signal file descriptor: %d.", fd);
15cd25fd
DL
311 return -1;
312 }
313
314 if (ret != sizeof(siginfo)) {
408da065 315 ERROR("Unexpected size for siginfo struct.");
15cd25fd
DL
316 return -1;
317 }
318
408da065 319 /* Check whether init is running. */
80507ee8 320 info.si_pid = 0;
3c319edb
CB
321 ret = waitid(P_PID, hdlr->pid, &info, WEXITED | WNOWAIT | WNOHANG);
322 if (ret == 0 && info.si_pid == hdlr->pid)
323 hdlr->init_died = true;
80507ee8 324
f3304a29 325 if (siginfo.ssi_signo != SIGCHLD) {
3c319edb
CB
326 kill(hdlr->pid, siginfo.ssi_signo);
327 INFO("Forwarded signal %d to pid %d.", siginfo.ssi_signo, hdlr->pid);
328 return hdlr->init_died ? LXC_MAINLOOP_CLOSE : 0;
f3304a29
FW
329 }
330
408da065
CB
331 if (siginfo.ssi_code == CLD_STOPPED) {
332 INFO("Container init process was stopped.");
3c319edb 333 return hdlr->init_died ? LXC_MAINLOOP_CLOSE : 0;
408da065
CB
334 } else if (siginfo.ssi_code == CLD_CONTINUED) {
335 INFO("Container init process was continued.");
3c319edb 336 return hdlr->init_died ? LXC_MAINLOOP_CLOSE : 0;
15cd25fd 337 }
1ac470c0 338
408da065
CB
339 /* More robustness, protect ourself from a SIGCHLD sent
340 * by a process different from the container init.
82d89dce 341 */
3c319edb
CB
342 if (siginfo.ssi_pid != hdlr->pid) {
343 NOTICE("Received SIGCHLD from pid %d instead of container init %d.", siginfo.ssi_pid, hdlr->pid);
344 return hdlr->init_died ? LXC_MAINLOOP_CLOSE : 0;
82d89dce
DL
345 }
346
3c319edb
CB
347 DEBUG("Container init process %d exited.", hdlr->pid);
348 return LXC_MAINLOOP_CLOSE;
b0a33c1e 349}
350
5e5576a4
CB
351static int lxc_serve_state_clients(const char *name,
352 struct lxc_handler *handler,
353 lxc_state_t state)
66aeffc7 354{
dbc9832d
CB
355 ssize_t ret;
356 struct lxc_list *cur, *next;
d39b10eb 357 struct lxc_state_client *client;
dbc9832d
CB
358 struct lxc_msg msg = {.type = lxc_msg_state, .value = state};
359
bc631984 360 process_lock();
66aeffc7 361 handler->state = state;
9dfa4041 362 TRACE("Set container state to %s", lxc_state2str(state));
dbc9832d 363
d39b10eb 364 if (lxc_list_empty(&handler->conf->state_clients)) {
9dfa4041 365 TRACE("No state clients registered");
dbc9832d 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
d39b10eb 374 lxc_list_for_each_safe(cur, &handler->conf->state_clients, next) {
dbc9832d
CB
375 client = cur->elem;
376
d39b10eb 377 if (client->states[state] == 0) {
9dfa4041 378 TRACE("State %s not registered for state client %d",
dbc9832d
CB
379 lxc_state2str(state), client->clientfd);
380 continue;
381 }
382
9dfa4041 383 TRACE("Sending state %s to state client %d",
dbc9832d
CB
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 393
9dfa4041
CB
394 ERROR("%s - Failed to send message to client",
395 strerror(errno));
dbc9832d
CB
396 }
397
398 /* kick client from list */
399 close(client->clientfd);
400 lxc_list_del(cur);
401 free(cur->elem);
402 free(cur);
403 }
404 process_unlock();
405
5e5576a4
CB
406 return 0;
407}
408
409static int lxc_serve_state_socket_pair(const char *name,
410 struct lxc_handler *handler,
411 lxc_state_t state)
412{
413 ssize_t ret;
414
415 if (!handler->backgrounded ||
416 handler->state_socket_pair[1] < 0 ||
417 state == STARTING)
418 return 0;
419
420 /* Close read end of the socket pair. */
421 close(handler->state_socket_pair[0]);
422 handler->state_socket_pair[0] = -1;
423
ee8377bd 424again:
5e5576a4
CB
425 ret = lxc_abstract_unix_send_credential(handler->state_socket_pair[1],
426 &(int){state}, sizeof(int));
ee8377bd
CB
427 if (ret != sizeof(int)) {
428 if (errno == EINTR)
429 goto again;
5e5576a4
CB
430 SYSERROR("Failed to send state to %d",
431 handler->state_socket_pair[1]);
ee8377bd
CB
432 return -1;
433 }
5e5576a4
CB
434
435 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state),
436 handler->state_socket_pair[1]);
437
438 /* Close write end of the socket pair. */
439 close(handler->state_socket_pair[1]);
440 handler->state_socket_pair[1] = -1;
441
442 return 0;
443}
444
445int lxc_set_state(const char *name, struct lxc_handler *handler,
446 lxc_state_t state)
447{
448 int ret;
449
450 ret = lxc_serve_state_socket_pair(name, handler, state);
451 if (ret < 0) {
452 ERROR("Failed to synchronize via anonymous pair of unix sockets");
453 return -1;
454 }
455
456 ret = lxc_serve_state_clients(name, handler, state);
457 if (ret < 0)
458 return -1;
459
dbc9832d
CB
460 /* This function will try to connect to the legacy lxc-monitord state
461 * server and only exists for backwards compatibility.
462 */
9123e471 463 lxc_monitor_send_state(name, state, handler->lxcpath);
dbc9832d 464
66aeffc7
DL
465 return 0;
466}
467
735f2c6e 468int lxc_poll(const char *name, struct lxc_handler *handler)
b0a33c1e 469{
3c319edb 470 int ret;
30a33fbd 471 bool has_console = (handler->conf->rootfs.path != NULL);
3c319edb 472 struct lxc_epoll_descr descr, descr_console;
b0a33c1e 473
3c319edb
CB
474 ret = lxc_mainloop_open(&descr);
475 if (ret < 0) {
476 ERROR("Failed to create mainloop");
50c8bf05 477 goto out_sigfd;
b0a33c1e 478 }
479
30a33fbd
CB
480 if (has_console) {
481 ret = lxc_mainloop_open(&descr_console);
482 if (ret < 0) {
483 ERROR("Failed to create console mainloop");
484 goto out_mainloop;
485 }
3c319edb
CB
486 }
487
1cc8bd4b 488 ret = lxc_mainloop_add_handler(&descr, handler->sigfd, signal_handler, handler);
3c319edb 489 if (ret < 0) {
1cc8bd4b 490 ERROR("Failed to add signal handler for %d to mainloop", handler->sigfd);
3c319edb 491 goto out_mainloop_console;
b0a33c1e 492 }
493
30a33fbd
CB
494 if (has_console) {
495 struct lxc_console *console = &handler->conf->console;
63376d7d 496
30a33fbd
CB
497 ret = lxc_console_mainloop_add(&descr, console);
498 if (ret < 0) {
499 ERROR("Failed to add console handlers to mainloop");
500 goto out_mainloop_console;
501 }
502
503 ret = lxc_console_mainloop_add(&descr_console, console);
504 if (ret < 0) {
505 ERROR("Failed to add console handlers to console mainloop");
506 goto out_mainloop_console;
507 }
563f2f2c
DL
508 }
509
3c319edb
CB
510 ret = lxc_cmd_mainloop_add(name, &descr, handler);
511 if (ret < 0) {
512 ERROR("Failed to add command handler to mainloop");
513 goto out_mainloop_console;
514 }
b0a33c1e 515
3c319edb 516 TRACE("Mainloop is ready");
b0a33c1e 517
3c319edb 518 ret = lxc_mainloop(&descr, -1);
1cc8bd4b
CB
519 close(descr.epfd);
520 descr.epfd = -EBADF;
521 if (ret < 0 || !handler->init_died)
522 goto out_mainloop;
523
30a33fbd
CB
524 if (has_console)
525 ret = lxc_mainloop(&descr_console, 0);
526
3c319edb
CB
527
528out_mainloop:
b0a33c1e 529 lxc_mainloop_close(&descr);
1cc8bd4b 530 TRACE("Closed mainloop");
408da065 531
3c319edb 532out_mainloop_console:
30a33fbd
CB
533 if (has_console) {
534 lxc_mainloop_close(&descr_console);
535 TRACE("Closed console mainloop");
536 }
3c319edb 537
b0a33c1e 538out_sigfd:
1cc8bd4b
CB
539 close(handler->sigfd);
540 TRACE("Closed signal file descriptor %d", handler->sigfd);
541 handler->sigfd = -EBADF;
408da065 542
1cc8bd4b 543 return ret;
b0a33c1e 544}
545
41784e4e
CB
546void lxc_zero_handler(struct lxc_handler *handler)
547{
548 int i;
549
550 memset(handler, 0, sizeof(struct lxc_handler));
551
552 handler->clone_flags = -1;
553
554 handler->pinfd = -1;
555
556 handler->sigfd = -1;
557
558 for (i = 0; i < LXC_NS_MAX; i++)
559 handler->nsfd[i] = -1;
560
561 handler->data_sock[0] = -1;
562 handler->data_sock[1] = -1;
563
564 handler->state_socket_pair[0] = -1;
565 handler->state_socket_pair[1] = -1;
566
567 handler->sync_sock[0] = -1;
568 handler->sync_sock[1] = -1;
569}
570
1cc8bd4b
CB
571static void lxc_put_nsfds(struct lxc_handler *handler)
572{
573 int i;
574
575 for (i = 0; i < LXC_NS_MAX; i++) {
576 if (handler->nsfd[i] < 0)
577 continue;
578
579 close(handler->nsfd[i]);
580 handler->nsfd[i] = -EBADF;
581 }
582}
583
f2e07cb6
CB
584void lxc_free_handler(struct lxc_handler *handler)
585{
1cc8bd4b
CB
586 if (handler->pinfd >= 0)
587 close(handler->pinfd);
588
589 if (handler->sigfd >= 0)
590 close(handler->sigfd);
591
592 lxc_put_nsfds(handler);
593
594 if (handler->conf && handler->conf->reboot == 0)
595 if (handler->conf->maincmd_fd)
596 close(handler->conf->maincmd_fd);
f2e07cb6 597
5e5576a4
CB
598 if (handler->state_socket_pair[0] >= 0)
599 close(handler->state_socket_pair[0]);
600
601 if (handler->state_socket_pair[1] >= 0)
602 close(handler->state_socket_pair[1]);
603
f2e07cb6
CB
604 handler->conf = NULL;
605 free(handler);
1cc8bd4b 606 handler = NULL;
f2e07cb6
CB
607}
608
aa460476 609struct lxc_handler *lxc_init_handler(const char *name, struct lxc_conf *conf,
5e5576a4 610 const char *lxcpath, bool daemonize)
59eb99ba 611{
5e5576a4 612 int i, ret;
3a0f472d
DL
613 struct lxc_handler *handler;
614
615 handler = malloc(sizeof(*handler));
aa460476
CB
616 if (!handler) {
617 ERROR("failed to allocate memory");
3a0f472d 618 return NULL;
aa460476 619 }
59eb99ba
DL
620
621 memset(handler, 0, sizeof(*handler));
622
790255cf
CB
623 /* Note that am_unpriv() checks the effective uid. We probably don't
624 * care if we are real root only if we are running as root so this
625 * should be fine.
626 */
d0fbc7ba 627 handler->am_root = !am_unpriv();
c6012571 628 handler->data_sock[0] = handler->data_sock[1] = -1;
fae349da 629 handler->conf = conf;
9123e471 630 handler->lxcpath = lxcpath;
5c068da9 631 handler->pinfd = -1;
1cc8bd4b
CB
632 handler->sigfd = -EBADF;
633 handler->init_died = false;
5e5576a4 634 handler->state_socket_pair[0] = handler->state_socket_pair[1] = -1;
d39b10eb
CB
635 if (handler->conf->reboot == 0)
636 lxc_list_init(&handler->conf->state_clients);
fae349da 637
b6b2b194
WB
638 for (i = 0; i < LXC_NS_MAX; i++)
639 handler->nsfd[i] = -1;
640
f0ecc19d 641 handler->name = name;
3bdf52d7 642
5e5576a4
CB
643 if (daemonize && !handler->conf->reboot) {
644 /* Create socketpair() to synchronize on daemonized startup.
645 * When the container reboots we don't need to synchronize again
646 * currently so don't open another socketpair().
647 */
648 ret = socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
649 handler->state_socket_pair);
650 if (ret < 0) {
651 ERROR("Failed to create anonymous pair of unix sockets");
652 goto on_error;
653 }
654 TRACE("Created anonymous pair {%d,%d} of unix sockets",
655 handler->state_socket_pair[0],
656 handler->state_socket_pair[1]);
657 }
658
d39b10eb
CB
659 if (handler->conf->reboot == 0) {
660 handler->conf->maincmd_fd = lxc_cmd_init(name, lxcpath, "command");
661 if (handler->conf->maincmd_fd < 0) {
662 ERROR("Failed to set up command socket");
663 goto on_error;
664 }
aa460476 665 }
9dfa4041 666 TRACE("Unix domain socket %d for command server is ready",
aa460476
CB
667 handler->conf->maincmd_fd);
668
669 return handler;
670
f2e07cb6
CB
671on_error:
672 lxc_free_handler(handler);
aa460476
CB
673
674 return NULL;
675}
676
677int lxc_init(const char *name, struct lxc_handler *handler)
678{
a2c09be0 679 int ret;
4a03ded4 680 const char *loglevel;
aa460476
CB
681 struct lxc_conf *conf = handler->conf;
682
683 lsm_init();
684 TRACE("initialized LSM");
d2e30e99 685
8f2c3a70 686 if (lxc_read_seccomp_config(conf) != 0) {
408da065 687 ERROR("Failed loading seccomp policy.");
d2e30e99 688 goto out_close_maincmd_fd;
8f2c3a70 689 }
dbc9832d 690 TRACE("read seccomp policy");
8f2c3a70 691
408da065 692 /* Begin by setting the state to STARTING. */
25c2aca5 693 if (lxc_set_state(name, handler, STARTING)) {
408da065 694 ERROR("Failed to set state for container \"%s\" to \"%s\".", name, lxc_state2str(STARTING));
051151de 695 goto out_close_maincmd_fd;
0ad19a3f 696 }
dbc9832d 697 TRACE("set container state to \"STARTING\"");
0ad19a3f 698
408da065
CB
699 /* Start of environment variable setup for hooks. */
700 if (name && setenv("LXC_NAME", name, 1))
701 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name);
702
703 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
704 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf->rcfile);
705
706 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1))
707 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf->rootfs.mount);
708
709 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
710 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf->rootfs.path);
711
712 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1))
713 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf->console.path);
714
715 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1))
716 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf->console.log_path);
717
718 if (setenv("LXC_CGNS_AWARE", "1", 1))
719 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
b8f88d9b 720
4a03ded4
CB
721 loglevel = lxc_log_priority_to_string(lxc_log_get_level());
722 if (setenv("LXC_LOG_LEVEL", loglevel, 1))
723 SYSERROR("Failed to set environment variable LXC_LOG_LEVEL=%s", loglevel);
a2c09be0
CB
724
725 if (conf->hooks_version == 0)
726 ret = setenv("LXC_HOOK_VERSION", "0", 1);
727 else
728 ret = setenv("LXC_HOOK_VERSION", "1", 1);
729 if (ret < 0)
730 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf->hooks_version);
408da065 731 /* End of environment variable setup for hooks. */
f7bee6c6 732
dbc9832d
CB
733 TRACE("set environment variables");
734
14a7b0f9 735 if (run_lxc_hooks(name, "pre-start", conf, NULL)) {
408da065 736 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name);
773fb9ca
SH
737 goto out_aborting;
738 }
dbc9832d 739 TRACE("ran pre-start hooks");
26ddeedd 740
408da065
CB
741 /* The signal fd has to be created before forking otherwise if the child
742 * process exits before we setup the signal fd, the event will be lost
743 * and the command will be stuck.
744 */
83ee7875 745 handler->sigfd = setup_signal_fd(&handler->oldmask);
59eb99ba 746 if (handler->sigfd < 0) {
408da065 747 ERROR("Failed to setup SIGCHLD fd handler.");
b5159817
DE
748 goto out_delete_tty;
749 }
dbc9832d 750 TRACE("set up signal fd");
b5159817 751
408da065 752 /* Do this after setting up signals since it might unblock SIGWINCH. */
4d1ffb0a
CB
753 ret = lxc_console_create(conf);
754 if (ret < 0) {
755 ERROR("Failed to create console");
b5159817 756 goto out_restore_sigmask;
b0a33c1e 757 }
4d1ffb0a 758 TRACE("Created console");
b0a33c1e 759
54117de5 760 if (lxc_ttys_shift_ids(conf) < 0) {
408da065 761 ERROR("Failed to shift tty into container.");
c4d10a05
SH
762 goto out_restore_sigmask;
763 }
dbc9832d 764 TRACE("shifted tty ids");
c4d10a05 765
dbc9832d 766 INFO("container \"%s\" is initialized", name);
aa460476 767 return 0;
59eb99ba 768
b5159817
DE
769out_restore_sigmask:
770 sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
59eb99ba 771out_delete_tty:
fae349da 772 lxc_delete_tty(&conf->tty_info);
59eb99ba 773out_aborting:
25c2aca5 774 lxc_set_state(name, handler, ABORTING);
d2e30e99
DE
775out_close_maincmd_fd:
776 close(conf->maincmd_fd);
777 conf->maincmd_fd = -1;
aa460476 778 return -1;
59eb99ba
DL
779}
780
3b72c4a0 781void lxc_fini(const char *name, struct lxc_handler *handler)
59eb99ba 782{
b3286b62 783 int i, rc;
18b3b9c1 784 pid_t self;
dbc9832d 785 struct lxc_list *cur, *next;
dbc9832d 786 char *namespaces[LXC_NS_MAX + 1];
b3286b62 787 size_t namespace_count = 0;
b6b2b194 788
408da065
CB
789 /* The STOPPING state is there for future cleanup code which can take
790 * awhile.
59eb99ba 791 */
25c2aca5 792 lxc_set_state(name, handler, STOPPING);
b6b2b194 793
0059379f 794 self = lxc_raw_getpid();
b3286b62 795 for (i = 0; i < LXC_NS_MAX; i++) {
18b3b9c1
CB
796 if (handler->nsfd[i] < 0)
797 continue;
798
799 if (handler->conf->hooks_version == 0)
800 rc = asprintf(&namespaces[namespace_count],
801 "%s:/proc/%d/fd/%d", ns_info[i].proc_name,
802 self, handler->nsfd[i]);
803 else
804 rc = asprintf(&namespaces[namespace_count],
805 "/proc/%d/fd/%d", self, handler->nsfd[i]);
806 if (rc == -1) {
807 SYSERROR("Failed to allocate memory.");
808 break;
b3286b62 809 }
18b3b9c1
CB
810
811 if (handler->conf->hooks_version == 0) {
812 namespace_count++;
813 continue;
814 }
815
816 rc = setenv(ns_info[i].env_name, namespaces[namespace_count], 1);
817 if (rc < 0)
818 SYSERROR("Failed to set environment variable %s=%s",
819 ns_info[i].env_name, namespaces[namespace_count]);
820 else
821 TRACE("Set environment variable %s=%s",
822 ns_info[i].env_name, namespaces[namespace_count]);
823
824 namespace_count++;
b3286b62
WB
825 }
826 namespaces[namespace_count] = NULL;
c154af98 827
408da065
CB
828 if (handler->conf->reboot && setenv("LXC_TARGET", "reboot", 1))
829 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
830
831 if (!handler->conf->reboot && setenv("LXC_TARGET", "stop", 1))
832 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
c154af98 833
18b3b9c1 834 if (handler->conf->hooks_version == 0)
14a7b0f9 835 rc = run_lxc_hooks(name, "stop", handler->conf, namespaces);
18b3b9c1 836 else
14a7b0f9 837 rc = run_lxc_hooks(name, "stop", handler->conf, NULL);
c154af98 838
b3286b62
WB
839 while (namespace_count--)
840 free(namespaces[namespace_count]);
28d9e29e 841
4288b79f
CB
842 cgroup_destroy(handler);
843
d39b10eb 844 if (handler->conf->reboot == 0) {
f893d898
CB
845 /* For all new state clients simply close the command socket.
846 * This will inform all state clients that the container is
847 * STOPPED and also prevents a race between a open()/close() on
848 * the command socket causing a new process to get ECONNREFUSED
849 * because we haven't yet closed the command socket.
850 */
d39b10eb
CB
851 close(handler->conf->maincmd_fd);
852 handler->conf->maincmd_fd = -1;
c3184275
CB
853 TRACE("Closed command socket");
854
855 /* This function will try to connect to the legacy lxc-monitord
856 * state server and only exists for backwards compatibility.
857 */
858 lxc_monitor_send_state(name, STOPPED, handler->lxcpath);
859
860 /* The command socket is closed so no one can acces the command
861 * socket anymore so there's no need to lock it.
862 */
863 handler->state = STOPPED;
864 TRACE("Set container state to \"STOPPED\"");
f893d898
CB
865 } else {
866 lxc_set_state(name, handler, STOPPED);
d39b10eb 867 }
4288b79f 868
14a7b0f9 869 if (run_lxc_hooks(name, "post-stop", handler->conf, NULL)) {
408da065 870 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name);
f3787121
CB
871 if (handler->conf->reboot) {
872 WARN("Container will be stopped instead of rebooted.");
873 handler->conf->reboot = 0;
408da065
CB
874 if (setenv("LXC_TARGET", "stop", 1))
875 WARN("Failed to set environment variable: LXC_TARGET=stop.");
f3787121
CB
876 }
877 }
26ddeedd 878
408da065 879 /* Reset mask set by setup_signal_fd. */
8f64a3f6 880 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
408da065 881 WARN("Failed to restore signal mask.");
8f64a3f6 882
b5159817 883 lxc_console_delete(&handler->conf->console);
b2431939 884 lxc_delete_tty(&handler->conf->tty_info);
dbc9832d 885
dbc9832d
CB
886 /* The command socket is now closed, no more state clients can register
887 * themselves from now on. So free the list of state clients.
888 */
d39b10eb
CB
889 lxc_list_for_each_safe(cur, &handler->conf->state_clients, next) {
890 struct lxc_state_client *client = cur->elem;
891
892 /* Keep state clients that want to be notified about reboots. */
893 if ((handler->conf->reboot > 0) && (client->states[RUNNING] == 2))
894 continue;
895
dbc9832d
CB
896 /* close state client socket */
897 close(client->clientfd);
898 lxc_list_del(cur);
899 free(cur->elem);
900 free(cur);
901 }
902
2c5f2ede 903 if (handler->conf->ephemeral == 1 && handler->conf->reboot != 1)
28272964 904 lxc_destroy_container_on_signal(handler, name);
2c5f2ede 905
1cc8bd4b 906 lxc_free_handler(handler);
59eb99ba
DL
907}
908
735f2c6e 909void lxc_abort(const char *name, struct lxc_handler *handler)
59eb99ba 910{
73e608b2
SH
911 int ret, status;
912
25c2aca5 913 lxc_set_state(name, handler, ABORTING);
7d9fb3e9
DL
914 if (handler->pid > 0)
915 kill(handler->pid, SIGKILL);
408da065
CB
916 while ((ret = waitpid(-1, &status, 0)) > 0) {
917 ;
918 }
59eb99ba
DL
919}
920
18225d19
CB
921static int lxc_set_death_signal(int signal)
922{
923 int ret;
924 pid_t ppid;
925
926 ret = prctl(PR_SET_PDEATHSIG, signal, 0, 0, 0);
927
928 /* Check whether we have been orphaned. */
929 ppid = (pid_t)syscall(SYS_getppid);
930 if (ppid == 1) {
931 pid_t self;
932
933 self = lxc_raw_getpid();
934 ret = kill(self, SIGKILL);
935 if (ret < 0)
936 return -1;
937 }
938
939 if (ret < 0) {
940 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal);
941 return -1;
942 }
943
944 return 0;
945}
946
ffe1e01a 947static int do_start(void *data)
50e98013 948{
8bf3abfb 949 int ret;
7c661726 950 struct lxc_list *iterator;
7a55c157 951 char path[PATH_MAX];
fa3a5b22 952 struct lxc_handler *handler = data;
928b1f04
YT
953 bool have_cap_setgid;
954 uid_t new_uid;
955 gid_t new_gid;
5af9369b 956 int devnull_fd = -1;
50e98013 957
18225d19 958 lxc_sync_fini_parent(handler);
50e98013 959
408da065
CB
960 /* This prctl must be before the synchro, so if the parent dies before
961 * we set the parent death signal, we will detect its death with the
962 * synchro right after, otherwise we have a window where the parent can
963 * exit before we set the pdeath signal leading to a unsupervized
964 * container.
743ecd2e 965 */
18225d19 966 ret = lxc_set_death_signal(SIGKILL);
912314fc
CB
967 if (ret < 0) {
968 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
18225d19 969 goto out_warn_father;
743ecd2e
DL
970 }
971
18225d19
CB
972 ret = sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
973 if (ret < 0) {
974 SYSERROR("Failed to set signal mask");
975 goto out_warn_father;
976 }
50e98013 977
408da065 978 /* Don't leak the pinfd to the container. */
d39b10eb 979 if (handler->pinfd >= 0)
0d03360a 980 close(handler->pinfd);
2b0e17e4 981
18225d19
CB
982 ret = lxc_sync_wait_parent(handler, LXC_SYNC_STARTUP);
983 if (ret < 0)
984 goto out_warn_father;
5b1e83cb 985
408da065
CB
986 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
987 * https://github.com/lxc/lxd/issues/1978.
988 */
5b1e83cb 989 if ((handler->clone_flags & (CLONE_NEWNET | CLONE_NEWUSER)) ==
408da065 990 (CLONE_NEWNET | CLONE_NEWUSER)) {
5b1e83cb
SH
991 ret = unshare(CLONE_NEWNET);
992 if (ret < 0) {
408da065 993 SYSERROR("Failed to unshare CLONE_NEWNET.");
5b1e83cb
SH
994 goto out_warn_father;
995 }
408da065 996 INFO("Unshared CLONE_NEWNET.");
5b1e83cb
SH
997 }
998
408da065
CB
999 /* Tell the parent task it can begin to configure the container and wait
1000 * for it to finish.
3c22086f
CLG
1001 */
1002 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE))
9d7f9e52 1003 return -1;
50e98013 1004
7ab1ba02
CB
1005 if (lxc_network_recv_veth_names_from_parent(handler) < 0) {
1006 ERROR("Failed to receive veth names from parent");
658979c5 1007 goto out_warn_father;
7ab1ba02 1008 }
658979c5 1009
408da065 1010 /* If we are in a new user namespace, become root there to have
d08f8d2f 1011 * privilege over our namespace.
f6d3e3e4
SH
1012 */
1013 if (!lxc_list_empty(&handler->conf->id_map)) {
4160c3a0
CB
1014 uid_t nsuid = (handler->conf->root_nsuid_map != NULL)
1015 ? 0
1016 : handler->conf->init_uid;
1017 gid_t nsgid = (handler->conf->root_nsgid_map != NULL)
1018 ? 0
1019 : handler->conf->init_gid;
1020
1021 ret = lxc_switch_uid_gid(nsuid, nsgid);
4b826b1f 1022 if (ret < 0)
f6d3e3e4 1023 goto out_warn_father;
d08f8d2f
CB
1024
1025 /* Drop groups only after we switched to a valid gid in the new
1026 * user namespace.
1027 */
4b826b1f 1028 ret = lxc_setgroups(0, NULL);
a19b974f 1029 if (ret < 0 && (handler->am_root || errno != EPERM))
c476bdce 1030 goto out_warn_father;
4b826b1f
CB
1031
1032 if (!handler->am_root) {
1033 ret = prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1034 if (ret < 0)
1035 goto out_warn_father;
1036 }
912314fc
CB
1037
1038 /* set{g,u}id() clears deathsignal */
18225d19 1039 ret = lxc_set_death_signal(SIGKILL);
912314fc
CB
1040 if (ret < 0) {
1041 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1042 goto out_warn_father;
1043 }
f6d3e3e4
SH
1044 }
1045
99b71824 1046 if (access(handler->lxcpath, X_OK)) {
c8154066
SH
1047 print_top_failing_dir(handler->lxcpath);
1048 goto out_warn_father;
1049 }
1050
a91cde21 1051 ret = snprintf(path, sizeof(path), "%s/dev/null", handler->conf->rootfs.mount);
408da065 1052 if (ret < 0 || ret >= sizeof(path))
7a55c157 1053 goto out_warn_father;
7a55c157
TA
1054
1055 /* In order to checkpoint restore, we need to have everything in the
1056 * same mount namespace. However, some containers may not have a
1057 * reasonable /dev (in particular, they may not have /dev/null), so we
1058 * can't set init's std fds to /dev/null by opening it from inside the
1059 * container.
1060 *
1061 * If that's the case, fall back to using the host's /dev/null. This
1062 * means that migration won't work, but at least we won't spew output
1063 * where it isn't wanted.
1064 */
1065 if (handler->backgrounded && !handler->conf->autodev && access(path, F_OK) < 0) {
c44de748
AM
1066 devnull_fd = open_devnull();
1067
1068 if (devnull_fd < 0)
1069 goto out_warn_father;
408da065
CB
1070 WARN("Using /dev/null from the host for container init's "
1071 "standard file descriptors. Migration will not work.");
c44de748
AM
1072 }
1073
408da065 1074 /* Ask father to setup cgroups and wait for him to finish. */
544a48a0 1075 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP))
c44de748 1076 goto out_error;
544a48a0 1077
deefdf8a
CB
1078 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1079 * earlier we end up with a wrong view of /proc/self/cgroup. For
1080 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1081 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1082 * /proc/self/cgroup would show us:
1083 *
1084 * 8:cpuset:/lxc/c
1085 *
1086 * whereas it should actually show
1087 *
1088 * 8:cpuset:/
1089 */
5af9369b 1090 if (handler->clone_flags & CLONE_NEWCGROUP) {
deefdf8a
CB
1091 if (unshare(CLONE_NEWCGROUP) < 0) {
1092 INFO("Failed to unshare CLONE_NEWCGROUP.");
1093 goto out_warn_father;
1094 }
1095 INFO("Unshared CLONE_NEWCGROUP.");
1096 }
1097
149857af
CB
1098 /* Add the requested environment variables to the current environment to
1099 * allow them to be used by the various hooks, such as the start hook
1100 * above.
98ff08ca 1101 */
98ff08ca
CB
1102 lxc_list_for_each(iterator, &handler->conf->environment) {
1103 if (putenv((char *)iterator->elem)) {
1104 SYSERROR("Failed to set environment variable: %s.", (char *)iterator->elem);
1105 goto out_warn_father;
1106 }
1107 }
1108
f4152036 1109 /* Setup the container, ip, names, utsname, ... */
3b988b33 1110 ret = lxc_setup(handler);
7729f8e5 1111 close(handler->data_sock[1]);
8bf3abfb 1112 close(handler->data_sock[0]);
7729f8e5 1113 if (ret < 0) {
f4152036
CB
1114 ERROR("Failed to setup container \"%s\".", handler->name);
1115 goto out_warn_father;
1116 }
1117
408da065 1118 /* Set the label to change to when we exec(2) the container's init. */
7aff4f43 1119 if (lsm_process_label_set(NULL, handler->conf, 1, 1) < 0)
e075f5d9 1120 goto out_warn_father;
5112cd70 1121
029cdff5 1122 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
408da065
CB
1123 * before we aren't allowed anymore.
1124 */
029cdff5
CB
1125 if (handler->conf->no_new_privs) {
1126 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1127 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
1128 goto out_warn_father;
1129 }
1130 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
1131 }
1132
0d9acb99
DE
1133 /* Some init's such as busybox will set sane tty settings on stdin,
1134 * stdout, stderr which it thinks is the console. We already set them
1135 * the way we wanted on the real terminal, and we want init to do its
408da065
CB
1136 * setup on its console ie. the pty allocated in lxc_console_create() so
1137 * make sure that that pty is stdin,stdout,stderr.
0d9acb99 1138 */
5d113f65
CB
1139 if (handler->conf->console.slave >= 0) {
1140 if (handler->backgrounded || handler->conf->is_execute == 0)
1141 ret = set_stdfds(handler->conf->console.slave);
1142 else
1143 ret = lxc_console_set_stdfds(handler->conf->console.slave);
1144 if (ret < 0) {
c5b93afb
LF
1145 ERROR("Failed to redirect std{in,out,err} to pty file "
1146 "descriptor %d",
1147 handler->conf->console.slave);
1148 goto out_warn_father;
1149 }
5d113f65 1150 }
0d9acb99 1151
408da065 1152 /* If we mounted a temporary proc, then unmount it now. */
5112cd70 1153 tmp_proc_unmount(handler->conf);
e075f5d9 1154
8f2c3a70
SH
1155 if (lxc_seccomp_load(handler->conf) != 0)
1156 goto out_warn_father;
1157
14a7b0f9 1158 if (run_lxc_hooks(handler->name, "start", handler->conf, NULL)) {
408da065 1159 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler->name);
773fb9ca
SH
1160 goto out_warn_father;
1161 }
fc25b815 1162
773fb9ca 1163 close(handler->sigfd);
26ddeedd 1164
7a55c157
TA
1165 if (devnull_fd < 0) {
1166 devnull_fd = open_devnull();
1167
1168 if (devnull_fd < 0)
1169 goto out_warn_father;
1170 }
1171
c5b93afb
LF
1172 if (handler->conf->console.slave < 0 && handler->backgrounded)
1173 if (set_stdfds(devnull_fd) < 0) {
1174 ERROR("Failed to redirect std{in,out,err} to "
1175 "\"/dev/null\"");
1176 goto out_warn_father;
1177 }
507cee36 1178
c44de748
AM
1179 if (devnull_fd >= 0) {
1180 close(devnull_fd);
1181 devnull_fd = -1;
1182 }
1183
8c9a7665
TA
1184 setsid();
1185
3c491553
L
1186 if (handler->conf->init_cwd && chdir(handler->conf->init_cwd)) {
1187 SYSERROR("Could not change directory to \"%s\"", handler->conf->init_cwd);
1188 goto out_warn_father;
1189 }
1190
f4152036
CB
1191 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP_LIMITS))
1192 goto out_warn_father;
1193
149857af
CB
1194 /* Reset the environment variables the user requested in a clear
1195 * environment.
1196 */
1197 if (clearenv()) {
1198 SYSERROR("Failed to clear environment.");
1199 /* Don't error out though. */
1200 }
1201
1202 lxc_list_for_each(iterator, &handler->conf->environment) {
1203 if (putenv((char *)iterator->elem)) {
1204 SYSERROR("Failed to set environment variable: %s.", (char *)iterator->elem);
1205 goto out_warn_father;
1206 }
1207 }
1208
98ff08ca
CB
1209 if (putenv("container=lxc")) {
1210 SYSERROR("Failed to set environment variable: container=lxc.");
1211 goto out_warn_father;
1212 }
1213
1214 if (handler->conf->pty_names) {
1215 if (putenv(handler->conf->pty_names)) {
1216 SYSERROR("Failed to set environment variable for container ptys.");
1217 goto out_warn_father;
1218 }
1219 }
1220
76bdf299
CB
1221 /* The container has been setup. We can now switch to an unprivileged
1222 * uid/gid.
1223 */
928b1f04
YT
1224 new_uid = handler->conf->init_uid;
1225 new_gid = handler->conf->init_gid;
76bdf299 1226
928b1f04
YT
1227 /* If we are in a new user namespace we already dropped all
1228 * groups when we switched to root in the new user namespace
1229 * further above. Only drop groups if we can, so ensure that we
1230 * have necessary privilege.
1231 */
1232 #if HAVE_LIBCAP
1233 have_cap_setgid = lxc_proc_cap_is_set(CAP_SETGID, CAP_EFFECTIVE);
1234 #else
1235 have_cap_setgid = false;
1236 #endif
1237 if (lxc_list_empty(&handler->conf->id_map) && have_cap_setgid) {
1238 if (lxc_setgroups(0, NULL) < 0)
76bdf299
CB
1239 goto out_warn_father;
1240 }
1241
928b1f04
YT
1242 if (lxc_switch_uid_gid(new_uid, new_gid) < 0)
1243 goto out_warn_father;
1244
408da065
CB
1245 /* After this call, we are in error because this ops should not return
1246 * as it execs.
1247 */
c4ea60df 1248 handler->ops->start(handler, handler->data);
50e98013
DL
1249
1250out_warn_father:
408da065
CB
1251 /* We want the parent to know something went wrong, so we return a
1252 * special error code.
1253 */
d1ccb562 1254 lxc_sync_wake_parent(handler, LXC_SYNC_ERROR);
c44de748
AM
1255
1256out_error:
1257 if (devnull_fd >= 0)
1258 close(devnull_fd);
1259
50e98013
DL
1260 return -1;
1261}
1262
ae467c54 1263static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
e8bd4e43 1264{
ae467c54 1265 int i;
ae467c54
CB
1266 struct lxc_pty_info *pty_info;
1267 int ret = -1;
c6012571 1268 int sock = handler->data_sock[1];
e8bd4e43 1269 struct lxc_conf *conf = handler->conf;
e8bd4e43
SH
1270 struct lxc_tty_info *tty_info = &conf->tty_info;
1271
1272 if (!conf->tty)
1273 return 0;
1274
408da065
CB
1275 tty_info->pty_info = malloc(sizeof(*tty_info->pty_info) * conf->tty);
1276 if (!tty_info->pty_info)
e8bd4e43 1277 return -1;
e8bd4e43 1278
672c1e58
CB
1279 for (i = 0; i < conf->tty; i++) {
1280 int ttyfds[2];
1281
1282 ret = lxc_abstract_unix_recv_fds(sock, ttyfds, 2, NULL, 0);
1283 if (ret < 0)
1284 break;
ae467c54 1285
672c1e58 1286 pty_info = &tty_info->pty_info[i];
e8bd4e43 1287 pty_info->busy = 0;
672c1e58
CB
1288 pty_info->master = ttyfds[0];
1289 pty_info->slave = ttyfds[1];
1290 TRACE("Received pty with master fd %d and slave fd %d from "
ae467c54 1291 "parent", pty_info->master, pty_info->slave);
e8bd4e43 1292 }
ae467c54 1293 if (ret < 0)
672c1e58 1294 ERROR("Failed to receive %d ttys from child: %s", conf->tty,
ae467c54
CB
1295 strerror(errno));
1296 else
672c1e58
CB
1297 TRACE("Received %d ttys from child", conf->tty);
1298
1299 tty_info->nbtty = conf->tty;
ae467c54
CB
1300
1301 return ret;
e8bd4e43
SH
1302}
1303
5af9369b 1304int resolve_clone_flags(struct lxc_handler *handler)
f813849c 1305{
03df7ab5 1306 handler->clone_flags = CLONE_NEWNS;
f813849c 1307
fa3a5b22
CB
1308 if (!handler->conf->inherit_ns[LXC_NS_USER]) {
1309 if (!lxc_list_empty(&handler->conf->id_map))
1310 handler->clone_flags |= CLONE_NEWUSER;
1311 } else {
1312 INFO("Inheriting user namespace");
1313 }
f813849c 1314
28d9e29e 1315 if (!handler->conf->inherit_ns[LXC_NS_NET]) {
408da065 1316 if (!lxc_requests_empty_network(handler))
f813849c
TA
1317 handler->clone_flags |= CLONE_NEWNET;
1318 } else {
28d9e29e 1319 INFO("Inheriting net namespace");
f813849c
TA
1320 }
1321
28d9e29e 1322 if (!handler->conf->inherit_ns[LXC_NS_IPC])
f813849c 1323 handler->clone_flags |= CLONE_NEWIPC;
408da065 1324 else
28d9e29e 1325 INFO("Inheriting ipc namespace");
f813849c 1326
28d9e29e 1327 if (!handler->conf->inherit_ns[LXC_NS_UTS])
f813849c 1328 handler->clone_flags |= CLONE_NEWUTS;
408da065 1329 else
28d9e29e 1330 INFO("Inheriting uts namespace");
03df7ab5 1331
28d9e29e 1332 if (!handler->conf->inherit_ns[LXC_NS_PID])
03df7ab5
L
1333 handler->clone_flags |= CLONE_NEWPID;
1334 else
28d9e29e 1335 INFO("Inheriting pid namespace");
5af9369b
CB
1336
1337 if (cgns_supported()) {
1338 if (!handler->conf->inherit_ns[LXC_NS_CGROUP])
1339 handler->clone_flags |= CLONE_NEWCGROUP;
1340 else
1341 INFO("Inheriting cgroup namespace");
1342 } else if (handler->conf->inherit_ns[LXC_NS_CGROUP]) {
1343 return -EINVAL;
1344 }
1345
1346 return 0;
f813849c
TA
1347}
1348
8deca6c9
CB
1349/* Note that this function is used with clone(CLONE_VM). Some glibc versions
1350 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1351 * But since the memory between parent and child is shared on CLONE_VM this
1352 * would invalidate the getpid() cache that glibc used to maintain and so
1353 * getpid() in the child would return the parent's pid. This is all fixed in
1354 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1355 * not reset anymore.
1356 * However, if for whatever reason you - dear commiter - somehow need to get the
1357 * pid of the dummy intermediate process for do_share_ns() you need to call
0059379f
CB
1358 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1359 * will be fine.
8deca6c9
CB
1360 */
1361static inline int do_share_ns(void *arg)
fa3a5b22 1362{
8deca6c9 1363 int i, flags, ret;
fa3a5b22
CB
1364 struct lxc_handler *handler = arg;
1365
8deca6c9
CB
1366 for (i = 0; i < LXC_NS_MAX; i++) {
1367 if (handler->nsfd[i] < 0)
1368 continue;
fa3a5b22 1369
8deca6c9 1370 ret = setns(handler->nsfd[i], 0);
fa3a5b22 1371 if (ret < 0)
8deca6c9 1372 return -1;
fa3a5b22 1373
8deca6c9 1374 DEBUG("Inherited %s namespace", ns_info[i].proc_name);
fa3a5b22
CB
1375 }
1376
8deca6c9
CB
1377 flags = handler->on_clone_flags;
1378 flags |= CLONE_PARENT;
ac2ba696 1379 handler->pid = lxc_raw_clone_cb(do_start, handler, flags);
8deca6c9 1380 if (handler->pid < 0)
fa3a5b22
CB
1381 return -1;
1382
8deca6c9 1383 return 0;
fa3a5b22
CB
1384}
1385
480588e6
CB
1386/* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1387 * exec()s the requested container binary.
1388 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1389 * right here should be double checked if they'd pose a security risk. (For
1390 * example, any {u}mount() operations performed here will be reflected on the
1391 * host!)
1392 */
74a3920a 1393static int lxc_spawn(struct lxc_handler *handler)
59eb99ba 1394{
8deca6c9 1395 int i, ret;
08dd2805 1396 char pidstr[20];
57927bf2
CB
1397 bool wants_to_map_ids;
1398 struct lxc_list *id_map;
6e5fc7a5 1399 const char *name = handler->name;
28d9e29e 1400 const char *lxcpath = handler->lxcpath;
8deca6c9 1401 bool cgroups_connected = false, share_ns = false;
28d9e29e 1402 struct lxc_conf *conf = handler->conf;
9f30a190 1403
28d9e29e 1404 id_map = &conf->id_map;
57927bf2 1405 wants_to_map_ids = !lxc_list_empty(id_map);
2f2623ec 1406
28d9e29e
CB
1407 for (i = 0; i < LXC_NS_MAX; i++) {
1408 if (!conf->inherit_ns[i])
1409 continue;
1410
28d9e29e
CB
1411 handler->nsfd[i] = lxc_inherit_namespace(conf->inherit_ns[i], lxcpath, ns_info[i].proc_name);
1412 if (handler->nsfd[i] < 0)
1413 return -1;
fa3a5b22 1414
8deca6c9 1415 share_ns = true;
28d9e29e 1416 }
50e98013 1417
3c22086f 1418 if (lxc_sync_init(handler))
9d7f9e52 1419 return -1;
0ad19a3f 1420
b9f522c5 1421 ret = socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
790255cf 1422 handler->data_sock);
c6012571 1423 if (ret < 0) {
e8bd4e43
SH
1424 lxc_sync_fini(handler);
1425 return -1;
1426 }
1427
5af9369b
CB
1428 ret = resolve_clone_flags(handler);
1429 if (ret < 0) {
1430 lxc_sync_fini(handler);
1431 return -1;
1432 }
9f30a190 1433
f813849c 1434 if (handler->clone_flags & CLONE_NEWNET) {
28d9e29e 1435 if (!lxc_list_empty(&conf->network)) {
26b797f3 1436
9f30a190
MM
1437 /* Find gateway addresses from the link device, which is
1438 * no longer accessible inside the container. Do this
1439 * before creating network interfaces, since goto
408da065
CB
1440 * out_delete_net does not work before lxc_clone.
1441 */
9f30a190 1442 if (lxc_find_gateway_addresses(handler)) {
408da065 1443 ERROR("Failed to find gateway addresses.");
9f30a190
MM
1444 lxc_sync_fini(handler);
1445 return -1;
1446 }
1447
408da065
CB
1448 /* That should be done before the clone because we will
1449 * fill the netdev index and use them in the child.
9f30a190 1450 */
811ef482 1451 if (lxc_create_network_priv(handler)) {
408da065 1452 ERROR("Failed to create the network.");
9f30a190
MM
1453 lxc_sync_fini(handler);
1454 return -1;
1455 }
19a26f82 1456 }
82d5ae15
DL
1457 }
1458
d4ef7c50 1459 if (!cgroup_init(handler)) {
408da065 1460 ERROR("Failed initializing cgroup support.");
33ad9f1a
CS
1461 goto out_delete_net;
1462 }
1463
7e4dfe0b
SH
1464 cgroups_connected = true;
1465
d4ef7c50 1466 if (!cgroup_create(handler)) {
408da065 1467 ERROR("Failed creating cgroups.");
47d8fb3b
CS
1468 goto out_delete_net;
1469 }
1470
408da065
CB
1471 /* If the rootfs is not a blockdev, prevent the container from marking
1472 * it readonly.
1473 * If the container is unprivileged then skip rootfs pinning.
0c547523 1474 */
0ee35059 1475 if (!wants_to_map_ids) {
28d9e29e 1476 handler->pinfd = pin_rootfs(conf->rootfs.path);
5e32a990 1477 if (handler->pinfd == -1)
408da065 1478 INFO("Failed to pin the rootfs for container \"%s\".", handler->name);
5e32a990 1479 }
0c547523 1480
408da065 1481 /* Create a process in a new set of namespaces. */
8deca6c9 1482 handler->on_clone_flags = handler->clone_flags;
408da065
CB
1483 if (handler->clone_flags & CLONE_NEWUSER) {
1484 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1485 * clone a new user namespace first and only later unshare our
1486 * network namespace to ensure that network devices ownership is
1487 * set up correctly.
1488 */
8deca6c9 1489 handler->on_clone_flags &= ~CLONE_NEWNET;
408da065 1490 }
5af9369b
CB
1491 /* The cgroup namespace gets unshare()ed not clone()ed. */
1492 handler->on_clone_flags &= ~CLONE_NEWCGROUP;
732375f5 1493
4e232466
CB
1494 if (share_ns) {
1495 pid_t attacher_pid;
1496
1497 attacher_pid = lxc_clone(do_share_ns, handler, CLONE_VFORK | CLONE_VM | CLONE_FILES);
1498 if (attacher_pid < 0) {
1499 SYSERROR(LXC_CLONE_ERROR);
1500 goto out_delete_net;
1501 }
1502
1503 ret = wait_for_pid(attacher_pid);
1504 if (ret < 0) {
1505 SYSERROR("Intermediate process failed");
1506 goto out_delete_net;
1507 }
1508 } else {
ac2ba696 1509 handler->pid = lxc_raw_clone_cb(do_start, handler, handler->on_clone_flags);
4e232466
CB
1510 }
1511 if (handler->pid < 0) {
1512 SYSERROR(LXC_CLONE_ERROR);
7fef7a06 1513 goto out_delete_net;
0ad19a3f 1514 }
fa3a5b22 1515 TRACE("Cloned child process %d", handler->pid);
1bd8d726 1516
9662e444 1517 for (i = 0; i < LXC_NS_MAX; i++)
8deca6c9 1518 if (handler->on_clone_flags & ns_info[i].clone_flag)
28d9e29e 1519 INFO("Cloned %s", ns_info[i].flag_name);
0ad19a3f 1520
8bf3abfb 1521 if (!preserve_ns(handler->nsfd, handler->on_clone_flags, handler->pid)) {
28d9e29e
CB
1522 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1523 goto out_delete_net;
1524 }
b6b2b194 1525
3c22086f
CLG
1526 lxc_sync_fini_child(handler);
1527
408da065
CB
1528 /* Map the container uids. The container became an invalid userid the
1529 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1530 * anything immediately, but allows the container to setuid(0) (0 being
1531 * mapped to something else on the host.) later to become a valid uid
1532 * again.
1533 */
fa3a5b22
CB
1534 if (wants_to_map_ids) {
1535 if (!handler->conf->inherit_ns[LXC_NS_USER]) {
1536 ret = lxc_map_ids(id_map, handler->pid);
1537 if (ret < 0) {
1538 ERROR("Failed to set up id mapping.");
1539 goto out_delete_net;
1540 }
1541 }
5b1e83cb
SH
1542 }
1543
9e2bdae4 1544 if (lxc_sync_wake_child(handler, LXC_SYNC_STARTUP))
5b1e83cb 1545 goto out_delete_net;
5b1e83cb 1546
9e2bdae4 1547 if (lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE))
5b1e83cb 1548 goto out_delete_net;
0ad19a3f 1549
d4ef7c50 1550 if (!cgroup_create_legacy(handler)) {
408da065 1551 ERROR("Failed to setup legacy cgroups for container \"%s\".", name);
ae5c8b8e 1552 goto out_delete_net;
33ad9f1a 1553 }
9daf6f5d 1554 if (!cgroup_setup_limits(handler, false)) {
408da065 1555 ERROR("Failed to setup cgroup limits for container \"%s\".", name);
6031a6e5
DE
1556 goto out_delete_net;
1557 }
1558
d4ef7c50 1559 if (!cgroup_enter(handler))
7fef7a06 1560 goto out_delete_net;
218d4250 1561
0996e18a
SH
1562 if (!cgroup_chown(handler))
1563 goto out_delete_net;
1564
fa3a5b22
CB
1565 /* Now we're ready to preserve the network namespace */
1566 ret = lxc_preserve_ns(handler->pid, "net");
1567 if (ret < 0) {
1568 ERROR("%s - Failed to preserve net namespace", strerror(errno));
1569 goto out_delete_net;
1570 }
1571 handler->nsfd[LXC_NS_NET] = ret;
1572 DEBUG("Preserved net namespace via fd %d", ret);
1573
408da065 1574 /* Create the network configuration. */
d5088cf2 1575 if (handler->clone_flags & CLONE_NEWNET) {
74c6e2b0
CB
1576 if (lxc_network_move_created_netdev_priv(handler->lxcpath,
1577 handler->name,
28d9e29e 1578 &conf->network,
74c6e2b0 1579 handler->pid)) {
408da065 1580 ERROR("Failed to create the configured network.");
7fef7a06 1581 goto out_delete_net;
82d5ae15 1582 }
74c6e2b0
CB
1583
1584 if (lxc_create_network_unpriv(handler->lxcpath, handler->name,
28d9e29e 1585 &conf->network,
74c6e2b0
CB
1586 handler->pid)) {
1587 ERROR("Failed to create the configured network.");
1588 goto out_delete_net;
1589 }
0ad19a3f 1590 }
1591
7ab1ba02
CB
1592 if (lxc_network_send_veth_names_to_child(handler) < 0) {
1593 ERROR("Failed to send veth names to child");
1594 goto out_delete_net;
658979c5
SH
1595 }
1596
61d7a733
YT
1597 if (!lxc_list_empty(&conf->procs)) {
1598 ret = setup_proc_filesystem(&conf->procs, handler->pid);
1599 if (ret < 0)
1600 goto out_delete_net;
1601 }
1602
408da065
CB
1603 /* Tell the child to continue its initialization. We'll get
1604 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
3c22086f
CLG
1605 */
1606 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE))
544a48a0
SH
1607 goto out_delete_net;
1608
28d9e29e 1609 if (!lxc_list_empty(&conf->limits) && setup_resource_limits(&conf->limits, handler->pid)) {
c6d09e15 1610 ERROR("failed to setup resource limits for '%s'", name);
84ff3af7 1611 goto out_delete_net;
c6d09e15
WB
1612 }
1613
f4152036
CB
1614 if (lxc_sync_barrier_child(handler, LXC_SYNC_CGROUP_UNSHARE))
1615 goto out_delete_net;
1616
9daf6f5d 1617 if (!cgroup_setup_limits(handler, true)) {
408da065 1618 ERROR("Failed to setup the devices cgroup for container \"%s\".", name);
b98f7d6e 1619 goto out_delete_net;
544a48a0 1620 }
f4152036 1621 TRACE("Set up cgroup device limits");
544a48a0 1622
73d28d42 1623 cgroup_disconnect();
7e4dfe0b 1624 cgroups_connected = false;
73d28d42 1625
8bf3abfb
CB
1626 if (handler->clone_flags & CLONE_NEWCGROUP) {
1627 /* Now we're ready to preserve the cgroup namespace */
1628 ret = lxc_preserve_ns(handler->pid, "cgroup");
1629 if (ret < 0) {
1630 ERROR("%s - Failed to preserve cgroup namespace", strerror(errno));
1631 goto out_delete_net;
1632 }
1633 handler->nsfd[LXC_NS_CGROUP] = ret;
1634 DEBUG("Preserved cgroup namespace via fd %d", ret);
1635 }
1636
08dd2805
SH
1637 snprintf(pidstr, 20, "%d", handler->pid);
1638 if (setenv("LXC_PID", pidstr, 1))
1639 SYSERROR("Failed to set environment variable: LXC_PID=%s.", pidstr);
1640
1641 /* Run any host-side start hooks */
14a7b0f9 1642 if (run_lxc_hooks(name, "start-host", conf, NULL)) {
08dd2805
SH
1643 ERROR("Failed to run lxc.hook.start-host for container \"%s\".", name);
1644 return -1;
1645 }
1646
408da065
CB
1647 /* Tell the child to complete its initialization and wait for it to exec
1648 * or return an error. (The child will never return
08dd2805 1649 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
408da065
CB
1650 * lxc_sync_barrier_child to return success, or return a different
1651 * value, causing us to error out).
544a48a0 1652 */
08dd2805 1653 if (lxc_sync_barrier_child(handler, LXC_SYNC_READY_START))
3c22086f 1654 return -1;
0ad19a3f 1655
790255cf
CB
1656 if (lxc_network_recv_name_and_ifindex_from_child(handler) < 0) {
1657 ERROR("Failed to receive names and ifindices for network "
1658 "devices from child");
1659 goto out_delete_net;
1660 }
1661
1662 /* Now all networks are created, network devices are moved into place,
1663 * and the correct names and ifindeces in the respective namespaces have
1664 * been recorded. The corresponding structs have now all been filled. So
1665 * log them for debugging purposes.
1666 */
28d9e29e 1667 lxc_log_configured_netdevs(conf);
790255cf 1668
f4152036
CB
1669 /* Read tty fds allocated by child. */
1670 if (lxc_recv_ttys_from_child(handler) < 0) {
1671 ERROR("Failed to receive tty info from child process.");
1672 goto out_delete_net;
1673 }
1674
23c53af9 1675 if (handler->ops->post_start(handler, handler->data))
e6126dbe
MN
1676 goto out_abort;
1677
25c2aca5 1678 if (lxc_set_state(name, handler, RUNNING)) {
408da065
CB
1679 ERROR("Failed to set state for container \"%s\" to \"%s\".", name,
1680 lxc_state2str(RUNNING));
59eb99ba 1681 goto out_abort;
3f21c114 1682 }
22ebac19 1683
3c22086f 1684 lxc_sync_fini(handler);
0c547523 1685
e6126dbe 1686 return 0;
1ac470c0 1687
7fef7a06 1688out_delete_net:
7e4dfe0b
SH
1689 if (cgroups_connected)
1690 cgroup_disconnect();
1bd8d726 1691
bb84beda
CB
1692 if (handler->clone_flags & CLONE_NEWNET)
1693 lxc_delete_network(handler);
1bd8d726 1694
59eb99ba
DL
1695out_abort:
1696 lxc_abort(name, handler);
3c22086f 1697 lxc_sync_fini(handler);
5c068da9
SH
1698 if (handler->pinfd >= 0) {
1699 close(handler->pinfd);
1700 handler->pinfd = -1;
1701 }
1702
b79fcd86 1703 return -1;
59eb99ba 1704}
0ad19a3f 1705
aa460476 1706int __lxc_start(const char *name, struct lxc_handler *handler,
507cee36
TA
1707 struct lxc_operations* ops, void *data, const char *lxcpath,
1708 bool backgrounded)
59eb99ba 1709{
59eb99ba 1710 int status;
aa460476 1711 int err = -1;
aa460476 1712 struct lxc_conf *conf = handler->conf;
80090207 1713
aa460476 1714 if (lxc_init(name, handler) < 0) {
408da065 1715 ERROR("Failed to initialize container \"%s\".", name);
66aeffc7 1716 return -1;
0ad19a3f 1717 }
ee70bf78
CLG
1718 handler->ops = ops;
1719 handler->data = data;
507cee36 1720 handler->backgrounded = backgrounded;
e6126dbe 1721
76a26f55 1722 if (!attach_block_device(handler->conf)) {
408da065 1723 ERROR("Failed to attach block device.");
76a26f55
SH
1724 goto out_fini_nonet;
1725 }
1726
35120d9c 1727 if (geteuid() == 0 && !lxc_list_empty(&conf->id_map)) {
408da065 1728 /* If the backing store is a device, mount it here and now. */
35120d9c
SH
1729 if (rootfs_is_blockdev(conf)) {
1730 if (unshare(CLONE_NEWNS) < 0) {
408da065 1731 ERROR("Failed to unshare CLONE_NEWNS.");
35120d9c
SH
1732 goto out_fini_nonet;
1733 }
408da065
CB
1734 INFO("Unshared CLONE_NEWNS.");
1735
6a0c909a 1736 remount_all_slave();
35120d9c 1737 if (do_rootfs_setup(conf, name, lxcpath) < 0) {
408da065 1738 ERROR("Error setting up rootfs mount as root before spawn.");
35120d9c
SH
1739 goto out_fini_nonet;
1740 }
408da065 1741 INFO("Set up container rootfs as host root.");
35120d9c
SH
1742 }
1743 }
1744
23c53af9 1745 err = lxc_spawn(handler);
59eb99ba 1746 if (err) {
408da065 1747 ERROR("Failed to spawn container \"%s\".", name);
76a26f55 1748 goto out_detach_blockdev;
0ad19a3f 1749 }
a9e1109e
CB
1750 /* close parent side of data socket */
1751 close(handler->data_sock[0]);
1752 handler->data_sock[0] = -1;
1753 close(handler->data_sock[1]);
1754 handler->data_sock[1] = -1;
0ad19a3f 1755
8bee8851
WB
1756 handler->conf->reboot = 0;
1757
3a0f472d 1758 err = lxc_poll(name, handler);
e043236e 1759 if (err) {
408da065 1760 ERROR("LXC mainloop exited with error: %d.", err);
59eb99ba
DL
1761 goto out_abort;
1762 }
0ad19a3f 1763
3a0f472d 1764 while (waitpid(handler->pid, &status, 0) < 0 && errno == EINTR)
1bc5cc8c 1765 continue;
e043236e 1766
408da065
CB
1767 /* If the child process exited but was not signaled, it didn't call
1768 * reboot. This should mean it was an lxc-execute which simply exited.
1769 * In any case, treat it as a 'halt'.
8b004f07 1770 */
d028235d 1771 if (WIFSIGNALED(status)) {
8b004f07
SH
1772 switch(WTERMSIG(status)) {
1773 case SIGINT: /* halt */
408da065 1774 DEBUG("Container \"%s\" is halting.", name);
8b004f07
SH
1775 break;
1776 case SIGHUP: /* reboot */
408da065 1777 DEBUG("Container \"%s\" is rebooting.", name);
8b004f07
SH
1778 handler->conf->reboot = 1;
1779 break;
c2b9bd9e 1780 case SIGSYS: /* seccomp */
408da065 1781 DEBUG("Container \"%s\" violated its seccomp policy.", name);
c2b9bd9e 1782 break;
8b004f07 1783 default:
408da065 1784 DEBUG("Unknown exit status for container \"%s\" init %d.", name, WTERMSIG(status));
8b004f07
SH
1785 break;
1786 }
d028235d 1787 }
828695d9 1788
b809f232
CB
1789 err = lxc_restore_phys_nics_to_netns(handler);
1790 if (err < 0)
1791 ERROR("Failed to move physical network devices back to parent "
1792 "network namespace");
ce5782df 1793
5c068da9
SH
1794 if (handler->pinfd >= 0) {
1795 close(handler->pinfd);
1796 handler->pinfd = -1;
1797 }
1798
1787abca 1799 lxc_monitor_send_exit_code(name, status, handler->lxcpath);
3a0f472d 1800 err = lxc_error_set_and_log(handler->pid, status);
1bd8d726 1801
9d7f9e52 1802out_fini:
bb84beda 1803 lxc_delete_network(handler);
74a2b586 1804
76a26f55
SH
1805out_detach_blockdev:
1806 detach_block_device(handler->conf);
1807
74a2b586 1808out_fini_nonet:
3a0f472d 1809 lxc_fini(name, handler);
0ad19a3f 1810 return err;
1811
59eb99ba 1812out_abort:
3a0f472d 1813 lxc_abort(name, handler);
9d7f9e52 1814 goto out_fini;
0ad19a3f 1815}
ee70bf78
CLG
1816
1817struct start_args {
1818 char *const *argv;
1819};
1820
1821static int start(struct lxc_handler *handler, void* data)
1822{
1823 struct start_args *arg = data;
1824
408da065 1825 NOTICE("Exec'ing \"%s\".", arg->argv[0]);
ee70bf78
CLG
1826
1827 execvp(arg->argv[0], arg->argv);
408da065 1828 SYSERROR("Failed to exec \"%s\".", arg->argv[0]);
ee70bf78
CLG
1829 return 0;
1830}
1831
1832static int post_start(struct lxc_handler *handler, void* data)
1833{
1834 struct start_args *arg = data;
1835
408da065 1836 NOTICE("Started \"%s\" with pid \"%d\".", arg->argv[0], handler->pid);
ee70bf78
CLG
1837 return 0;
1838}
1839
1840static struct lxc_operations start_ops = {
1841 .start = start,
1842 .post_start = post_start
1843};
1844
aa460476 1845int lxc_start(const char *name, char *const argv[], struct lxc_handler *handler,
507cee36 1846 const char *lxcpath, bool backgrounded)
ee70bf78
CLG
1847{
1848 struct start_args start_arg = {
1849 .argv = argv,
1850 };
1851
aa460476 1852 return __lxc_start(name, handler, &start_ops, &start_arg, lxcpath, backgrounded);
ee70bf78 1853}
28272964
CB
1854
1855static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
1856 const char *name)
1857{
1858 char destroy[MAXPATHLEN];
1859 bool bret = true;
1860 int ret = 0;
f01f7975 1861 struct lxc_container *c;
df31363a 1862 if (handler->conf->rootfs.path && handler->conf->rootfs.mount) {
790255cf 1863 bret = do_destroy_container(handler);
28272964 1864 if (!bret) {
408da065 1865 ERROR("Error destroying rootfs for container \"%s\".", name);
28272964
CB
1866 return;
1867 }
1868 }
408da065 1869 INFO("Destroyed rootfs for container \"%s\".", name);
28272964
CB
1870
1871 ret = snprintf(destroy, MAXPATHLEN, "%s/%s", handler->lxcpath, name);
1872 if (ret < 0 || ret >= MAXPATHLEN) {
408da065 1873 ERROR("Error destroying directory for container \"%s\".", name);
28272964
CB
1874 return;
1875 }
1876
f01f7975
CB
1877 c = lxc_container_new(name, handler->lxcpath);
1878 if (c) {
1879 if (container_disk_lock(c)) {
408da065 1880 INFO("Could not update lxc_snapshots file.");
f01f7975
CB
1881 lxc_container_put(c);
1882 } else {
1883 mod_all_rdeps(c, false);
1884 container_disk_unlock(c);
1885 lxc_container_put(c);
1886 }
1887 }
1888
d0fbc7ba 1889 if (!handler->am_root)
94b0a3ac
CB
1890 ret = userns_exec_full(handler->conf, lxc_rmdir_onedev_wrapper,
1891 destroy, "lxc_rmdir_onedev_wrapper");
28272964
CB
1892 else
1893 ret = lxc_rmdir_onedev(destroy, NULL);
1894
1895 if (ret < 0) {
408da065 1896 ERROR("Error destroying directory for container \"%s\".", name);
28272964
CB
1897 return;
1898 }
408da065 1899 INFO("Destroyed directory for container \"%s\".", name);
28272964
CB
1900}
1901
1902static int lxc_rmdir_onedev_wrapper(void *data)
1903{
1904 char *arg = (char *) data;
1905 return lxc_rmdir_onedev(arg, NULL);
1906}
1907
790255cf 1908static bool do_destroy_container(struct lxc_handler *handler) {
94b0a3ac
CB
1909 int ret;
1910
d0fbc7ba 1911 if (!handler->am_root) {
94b0a3ac
CB
1912 ret = userns_exec_full(handler->conf, storage_destroy_wrapper,
1913 handler->conf, "storage_destroy_wrapper");
1914 if (ret < 0)
d028235d 1915 return false;
10bc1861 1916
d028235d
SG
1917 return true;
1918 }
10bc1861 1919
790255cf 1920 return storage_destroy(handler->conf);
28272964 1921}