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