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