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