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