]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/start.c
Fix user namespace pdeathsig handling
[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
d38dd64a
CB
26#ifndef _GNU_SOURCE
27#define _GNU_SOURCE 1
28#endif
0ad19a3f 29#include <dirent.h>
30#include <errno.h>
b0a33c1e 31#include <fcntl.h>
c476bdce 32#include <grp.h>
37515ebd 33#include <poll.h>
b467714b 34#include <pthread.h>
f3787121
CB
35#include <signal.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
0ad19a3f 39#include <sys/file.h>
f4d507d5 40#include <sys/mount.h>
f3787121 41#include <sys/param.h>
0ad19a3f 42#include <sys/prctl.h>
f3787121
CB
43#include <sys/socket.h>
44#include <sys/stat.h>
45#include <sys/syscall.h>
ddceb1f9 46#include <sys/types.h>
b0a33c1e 47#include <sys/un.h>
f3787121 48#include <sys/wait.h>
d38dd64a 49#include <unistd.h>
495d2046 50
f3787121
CB
51#include "af_unix.h"
52#include "caps.h"
563f2f2c 53#include "cgroup.h"
f3787121 54#include "commands.h"
bbf5cf35 55#include "commands_utils.h"
f3787121 56#include "conf.h"
d38dd64a 57#include "config.h"
74c6e2b0 58#include "confile_utils.h"
e2bcd7db 59#include "error.h"
7fbb15ec 60#include "file_utils.h"
1cc8bd4b 61#include "list.h"
f3787121 62#include "log.h"
d38dd64a 63#include "lsm/lsm.h"
f2d5a09d 64#include "lxccontainer.h"
f3787121
CB
65#include "lxclock.h"
66#include "lxcseccomp.h"
3ef9b3d3 67#include "macro.h"
f3787121 68#include "mainloop.h"
4ffeaf27 69#include "memory_utils.h"
63376d7d 70#include "monitor.h"
f549edcc 71#include "namespace.h"
811ef482 72#include "network.h"
38e5c2db 73#include "raw_syscalls.h"
f3787121 74#include "start.h"
6be5397b
CB
75#include "storage/storage.h"
76#include "storage/storage_utils.h"
0ed9b1bc 77#include "sync.h"
59524108 78#include "syscall_wrappers.h"
0ed9b1bc
CB
79#include "terminal.h"
80#include "utils.h"
36eb9bde 81
d38dd64a
CB
82#if HAVE_LIBCAP
83#include <sys/capability.h>
84#endif
85
9de31d5a
CB
86#ifndef HAVE_STRLCPY
87#include "include/strlcpy.h"
88#endif
89
ac2cecc4 90lxc_log_define(start, lxc);
36eb9bde 91
f01f7975 92extern void mod_all_rdeps(struct lxc_container *c, bool inc);
790255cf 93static bool do_destroy_container(struct lxc_handler *handler);
28272964
CB
94static int lxc_rmdir_onedev_wrapper(void *data);
95static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
96 const char *name);
97
c8154066
SH
98static void print_top_failing_dir(const char *path)
99{
dcd9a847 100 __do_free char *copy = NULL;
9e5f5f2f 101 int ret;
4ffeaf27 102 char *e, *p, saved;
cbb9c7c7 103
4ffeaf27 104 copy = must_copy_string(path);
c8154066 105 p = copy;
4ffeaf27 106 e = copy + strlen(path);
cbb9c7c7 107
c8154066 108 while (p < e) {
f3787121
CB
109 while (p < e && *p == '/')
110 p++;
9e5f5f2f 111
f3787121
CB
112 while (p < e && *p != '/')
113 p++;
9e5f5f2f 114
c8154066
SH
115 saved = *p;
116 *p = '\0';
9e5f5f2f
CB
117
118 ret = access(copy, X_OK);
119 if (ret != 0) {
408da065
CB
120 SYSERROR("Could not access %s. Please grant it x "
121 "access, or add an ACL for the container "
9e5f5f2f 122 "root", copy);
c8154066
SH
123 return;
124 }
125 *p = saved;
126 }
127}
128
5032bf39 129static void lxc_put_nsfds(struct lxc_handler *handler)
408da065 130{
9f30a190
MM
131 int i;
132
9f30a190 133 for (i = 0; i < LXC_NS_MAX; i++) {
5032bf39 134 if (handler->nsfd[i] < 0)
39cd919c
CB
135 continue;
136
5032bf39
CB
137 close(handler->nsfd[i]);
138 handler->nsfd[i] = -EBADF;
9f30a190 139 }
9f30a190
MM
140}
141
4cb53844
CB
142static int lxc_try_preserve_ns(const int pid, const char *ns)
143{
144 int fd;
145
146 fd = lxc_preserve_ns(pid, ns);
147 if (fd < 0) {
148 if (errno != ENOENT) {
149 SYSERROR("Failed to preserve %s namespace", ns);
150 return -EINVAL;
151 }
152
a24c5678 153 SYSWARN("Kernel does not support preserving %s namespaces", ns);
4cb53844
CB
154 return -EOPNOTSUPP;
155 }
156
157 return fd;
158}
159
160/* lxc_try_preserve_namespaces: open /proc/@pid/ns/@ns for each namespace
161 * specified in ns_clone_flags.
4d8ac866 162 * Return true on success, false on failure.
62d05d9b 163 */
4cb53844
CB
164static bool lxc_try_preserve_namespaces(struct lxc_handler *handler,
165 int ns_clone_flags, pid_t pid)
f3787121 166{
9fef3355 167 int i;
9f30a190 168
9f30a190 169 for (i = 0; i < LXC_NS_MAX; i++)
5032bf39 170 handler->nsfd[i] = -EBADF;
cd43d2d1 171
9f30a190 172 for (i = 0; i < LXC_NS_MAX; i++) {
4cb53844
CB
173 int fd;
174
becad0ec 175 if ((ns_clone_flags & ns_info[i].clone_flag) == 0)
9f30a190 176 continue;
28d9e29e 177
4cb53844
CB
178 fd = lxc_try_preserve_ns(pid, ns_info[i].proc_name);
179 if (fd < 0) {
4cb53844
CB
180 /* Do not fail to start container on kernels that do
181 * not support interacting with namespaces through
182 * /proc.
183 */
184 if (fd == -EOPNOTSUPP)
185 continue;
fa3a5b22 186
4cb53844
CB
187 lxc_put_nsfds(handler);
188 return false;
189 }
190
191 handler->nsfd[i] = fd;
192 DEBUG("Preserved %s namespace via fd %d", ns_info[i].proc_name,
193 handler->nsfd[i]);
9f30a190
MM
194 }
195
62d05d9b 196 return true;
9f30a190
MM
197}
198
ec1dc633 199static inline bool match_stdfds(int fd)
80090207 200{
ec1dc633 201 return (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO);
80090207
CLG
202}
203
4c03724e 204#ifdef HAVE_DLOG
205static bool match_dlog_fds(struct dirent *direntp)
206{
207 char path[PATH_MAX] = {0};
208 char link[PATH_MAX] = {0};
209 ssize_t linklen;
210 int ret;
211
212 ret = snprintf(path, PATH_MAX, "/proc/self/fd/%s", direntp->d_name);
213 if (ret < 0 || ret >= PATH_MAX) {
214 ERROR("Failed to create file descriptor name");
215 return false;
216 }
217
218 linklen = readlink(path, link, PATH_MAX);
219 if (linklen < 0) {
220 SYSERROR("Failed to read link path - \"%s\"", path);
221 return false;
222 } else if (linklen >= PATH_MAX) {
223 ERROR("The name of link path is too long - \"%s\"", path);
224 return false;
225 }
226
227 if (strcmp(link, "/dev/log_main") == 0 ||
228 strcmp(link, "/dev/log_system") == 0 ||
229 strcmp(link, "/dev/log_radio") == 0)
230 return true;
231
232 return false;
233}
234#endif
235
47a46cf1
CB
236int lxc_check_inherited(struct lxc_conf *conf, bool closeall,
237 int *fds_to_ignore, size_t len_fds)
80090207 238{
80090207 239 int fd, fddir;
47a46cf1 240 size_t i;
80090207 241 DIR *dir;
a5a70219 242 struct dirent *direntp;
80090207 243
d2cf4c37
SH
244 if (conf && conf->close_all_fds)
245 closeall = true;
246
b119f362 247restart:
80090207
CLG
248 dir = opendir("/proc/self/fd");
249 if (!dir) {
a24c5678 250 SYSWARN("Failed to open directory");
80090207
CLG
251 return -1;
252 }
253
254 fddir = dirfd(dir);
255
74f96976 256 while ((direntp = readdir(dir))) {
a5a70219 257 int ret;
d39b10eb
CB
258 struct lxc_list *cur;
259 bool matched = false;
260
a5a70219 261 if (strcmp(direntp->d_name, ".") == 0)
80090207
CLG
262 continue;
263
a5a70219 264 if (strcmp(direntp->d_name, "..") == 0)
80090207
CLG
265 continue;
266
a5a70219
CB
267 ret = lxc_safe_int(direntp->d_name, &fd);
268 if (ret < 0) {
269 INFO("Could not parse file descriptor for \"%s\"", direntp->d_name);
d4cff0d2
CB
270 continue;
271 }
80090207 272
47a46cf1
CB
273 for (i = 0; i < len_fds; i++)
274 if (fds_to_ignore[i] == fd)
275 break;
276
277 if (fd == fddir || fd == lxc_log_fd ||
278 (i < len_fds && fd == fds_to_ignore[i]))
80090207
CLG
279 continue;
280
d39b10eb 281 /* Keep state clients that wait on reboots. */
3ee9e4fb
CB
282 if (conf) {
283 lxc_list_for_each(cur, &conf->state_clients) {
284 struct lxc_state_client *client = cur->elem;
d39b10eb 285
3ee9e4fb
CB
286 if (client->clientfd != fd)
287 continue;
d39b10eb 288
3ee9e4fb
CB
289 matched = true;
290 break;
291 }
d39b10eb
CB
292 }
293
294 if (matched)
295 continue;
296
858377e4
SH
297 if (current_config && fd == current_config->logfd)
298 continue;
299
ec1dc633 300 if (match_stdfds(fd))
80090207 301 continue;
80090207 302
1d5e5f26 303#ifdef HAVE_DLOG
304 if (match_dlog_fds(direntp))
305 continue;
306
307#endif
d2cf4c37 308 if (closeall) {
b119f362
SH
309 close(fd);
310 closedir(dir);
28d9e29e 311 INFO("Closed inherited fd %d", fd);
b119f362
SH
312 goto restart;
313 }
28d9e29e 314 WARN("Inherited fd %d", fd);
80090207
CLG
315 }
316
408da065 317 /* Only enable syslog at this point to avoid the above logging function
64c57ea1
BD
318 * to open a new fd and make the check_inherited function enter an
319 * infinite loop.
320 */
321 lxc_log_enable_syslog();
322
92c7f629
GK
323 closedir(dir); /* cannot fail */
324 return 0;
80090207
CLG
325}
326
83ee7875 327static int setup_signal_fd(sigset_t *oldmask)
b0a33c1e 328{
7288dfb6 329 int ret;
b0a33c1e 330 sigset_t mask;
7288dfb6 331 const int signals[] = {SIGBUS, SIGILL, SIGSEGV, SIGWINCH};
b0a33c1e 332
408da065 333 /* Block everything except serious error signals. */
df0795b1
CB
334 ret = sigfillset(&mask);
335 if (ret < 0)
336 return -EBADF;
337
9b10bef5 338 for (int sig = 0; sig < (sizeof(signals) / sizeof(signals[0])); sig++) {
df0795b1
CB
339 ret = sigdelset(&mask, signals[sig]);
340 if (ret < 0)
341 return -EBADF;
b0a33c1e 342 }
343
b467714b 344 ret = pthread_sigmask(SIG_BLOCK, &mask, oldmask);
df0795b1
CB
345 if (ret < 0) {
346 SYSERROR("Failed to set signal mask");
347 return -EBADF;
b0a33c1e 348 }
349
df0795b1
CB
350 ret = signalfd(-1, &mask, SFD_CLOEXEC);
351 if (ret < 0) {
352 SYSERROR("Failed to create signal file descriptor");
353 return -EBADF;
b0a33c1e 354 }
355
df0795b1 356 TRACE("Created signal file descriptor %d", ret);
1ac470c0 357
df0795b1 358 return ret;
b0a33c1e 359}
360
84c92abd 361static int signal_handler(int fd, uint32_t events, void *data,
f3787121 362 struct lxc_epoll_descr *descr)
b0a33c1e 363{
15cd25fd 364 int ret;
3c319edb
CB
365 siginfo_t info;
366 struct signalfd_siginfo siginfo;
367 struct lxc_handler *hdlr = data;
15cd25fd 368
489f39be 369 ret = lxc_read_nointr(fd, &siginfo, sizeof(siginfo));
15cd25fd 370 if (ret < 0) {
6e94162a 371 ERROR("Failed to read signal info from signal file descriptor %d", fd);
b2a48508 372 return LXC_MAINLOOP_ERROR;
15cd25fd
DL
373 }
374
375 if (ret != sizeof(siginfo)) {
6e94162a
CB
376 ERROR("Unexpected size for struct signalfd_siginfo");
377 return -EINVAL;
15cd25fd
DL
378 }
379
408da065 380 /* Check whether init is running. */
80507ee8 381 info.si_pid = 0;
3c319edb
CB
382 ret = waitid(P_PID, hdlr->pid, &info, WEXITED | WNOWAIT | WNOHANG);
383 if (ret == 0 && info.si_pid == hdlr->pid)
384 hdlr->init_died = true;
80507ee8 385
cd5177e9
TA
386 /* Try to figure out a reasonable exit status to report. */
387 if (hdlr->init_died) {
388 switch (info.si_code) {
389 case CLD_EXITED:
390 hdlr->exit_status = info.si_status << 8;
391 break;
392 case CLD_KILLED:
393 case CLD_DUMPED:
394 case CLD_STOPPED:
395 hdlr->exit_status = info.si_status << 8 | 0x7f;
396 break;
397 case CLD_CONTINUED:
398 /* Huh? The waitid() told us it's dead *and* continued? */
399 WARN("Init %d dead and continued?", hdlr->pid);
400 hdlr->exit_status = 1;
401 break;
402 default:
20993a97 403 ERROR("Unknown si_code: %d", info.si_code);
55e1311e 404 hdlr->exit_status = 1;
cd5177e9
TA
405 }
406 }
407
d4b5d7a8
TA
408 if (siginfo.ssi_signo == SIGHUP) {
409 kill(hdlr->pid, SIGTERM);
410 INFO("Killing %d since terminal hung up", hdlr->pid);
9b10bef5
CB
411 return hdlr->init_died ? LXC_MAINLOOP_CLOSE
412 : LXC_MAINLOOP_CONTINUE;
d4b5d7a8
TA
413 }
414
9cb94384
TA
415 if (siginfo.ssi_signo != SIGCHLD) {
416 kill(hdlr->pid, siginfo.ssi_signo);
417 INFO("Forwarded signal %d to pid %d", siginfo.ssi_signo, hdlr->pid);
9b10bef5
CB
418 return hdlr->init_died ? LXC_MAINLOOP_CLOSE
419 : LXC_MAINLOOP_CONTINUE;
9cb94384
TA
420 }
421
3a9e949f
TA
422 /* More robustness, protect ourself from a SIGCHLD sent
423 * by a process different from the container init.
424 */
425 if (siginfo.ssi_pid != hdlr->pid) {
6e94162a
CB
426 NOTICE("Received %d from pid %d instead of container init %d",
427 siginfo.ssi_signo, siginfo.ssi_pid, hdlr->pid);
9b10bef5
CB
428 return hdlr->init_died ? LXC_MAINLOOP_CLOSE
429 : LXC_MAINLOOP_CONTINUE;
3a9e949f
TA
430 }
431
408da065 432 if (siginfo.ssi_code == CLD_STOPPED) {
6e94162a 433 INFO("Container init process was stopped");
9b10bef5
CB
434 return hdlr->init_died ? LXC_MAINLOOP_CLOSE
435 : LXC_MAINLOOP_CONTINUE;
436 }
437
438 if (siginfo.ssi_code == CLD_CONTINUED) {
6e94162a 439 INFO("Container init process was continued");
9b10bef5
CB
440 return hdlr->init_died ? LXC_MAINLOOP_CLOSE
441 : LXC_MAINLOOP_CONTINUE;
15cd25fd 442 }
1ac470c0 443
6e94162a 444 DEBUG("Container init process %d exited", hdlr->pid);
9b10bef5 445
3c319edb 446 return LXC_MAINLOOP_CLOSE;
b0a33c1e 447}
448
974a8aba
CB
449int lxc_serve_state_clients(const char *name, struct lxc_handler *handler,
450 lxc_state_t state)
66aeffc7 451{
9de31d5a 452 size_t retlen;
dbc9832d
CB
453 ssize_t ret;
454 struct lxc_list *cur, *next;
dbc9832d
CB
455 struct lxc_msg msg = {.type = lxc_msg_state, .value = state};
456
974a8aba
CB
457 if (state == THAWED)
458 handler->state = RUNNING;
459 else
460 handler->state = state;
461
9dfa4041 462 TRACE("Set container state to %s", lxc_state2str(state));
dbc9832d 463
d39b10eb 464 if (lxc_list_empty(&handler->conf->state_clients)) {
9dfa4041 465 TRACE("No state clients registered");
dbc9832d
CB
466 return 0;
467 }
468
9de31d5a
CB
469 retlen = strlcpy(msg.name, name, sizeof(msg.name));
470 if (retlen >= sizeof(msg.name))
471 return -E2BIG;
dbc9832d 472
d39b10eb 473 lxc_list_for_each_safe(cur, &handler->conf->state_clients, next) {
d85617bc 474 struct lxc_state_client *client = cur->elem;
dbc9832d 475
d39b10eb 476 if (client->states[state] == 0) {
9dfa4041 477 TRACE("State %s not registered for state client %d",
dbc9832d
CB
478 lxc_state2str(state), client->clientfd);
479 continue;
480 }
481
9dfa4041 482 TRACE("Sending state %s to state client %d",
dbc9832d
CB
483 lxc_state2str(state), client->clientfd);
484
7fbb15ec
CB
485 ret = lxc_send_nointr(client->clientfd, &msg, sizeof(msg), MSG_NOSIGNAL);
486 if (ret <= 0)
6d1400b5 487 SYSERROR("Failed to send message to client");
dbc9832d
CB
488
489 /* kick client from list */
dbc9832d 490 lxc_list_del(cur);
300d1cb4 491 close(client->clientfd);
dbc9832d
CB
492 free(cur->elem);
493 free(cur);
494 }
dbc9832d 495
5e5576a4
CB
496 return 0;
497}
498
499static int lxc_serve_state_socket_pair(const char *name,
500 struct lxc_handler *handler,
501 lxc_state_t state)
502{
503 ssize_t ret;
504
bb955810 505 if (!handler->daemonize ||
5e5576a4
CB
506 handler->state_socket_pair[1] < 0 ||
507 state == STARTING)
508 return 0;
509
510 /* Close read end of the socket pair. */
511 close(handler->state_socket_pair[0]);
512 handler->state_socket_pair[0] = -1;
513
ee8377bd 514again:
5e5576a4
CB
515 ret = lxc_abstract_unix_send_credential(handler->state_socket_pair[1],
516 &(int){state}, sizeof(int));
9044b79e 517 if (ret < 0) {
518 SYSERROR("Failed to send state to %d", handler->state_socket_pair[1]);
519
ee8377bd
CB
520 if (errno == EINTR)
521 goto again;
9044b79e 522
523 return -1;
524 }
525
526 if (ret != sizeof(int)) {
527 ERROR("Message too long : %d", handler->state_socket_pair[1]);
ee8377bd
CB
528 return -1;
529 }
5e5576a4
CB
530
531 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state),
532 handler->state_socket_pair[1]);
533
534 /* Close write end of the socket pair. */
535 close(handler->state_socket_pair[1]);
536 handler->state_socket_pair[1] = -1;
537
538 return 0;
539}
540
541int lxc_set_state(const char *name, struct lxc_handler *handler,
542 lxc_state_t state)
543{
544 int ret;
545
546 ret = lxc_serve_state_socket_pair(name, handler, state);
547 if (ret < 0) {
548 ERROR("Failed to synchronize via anonymous pair of unix sockets");
549 return -1;
550 }
551
552 ret = lxc_serve_state_clients(name, handler, state);
553 if (ret < 0)
554 return -1;
555
dbc9832d
CB
556 /* This function will try to connect to the legacy lxc-monitord state
557 * server and only exists for backwards compatibility.
558 */
9123e471 559 lxc_monitor_send_state(name, state, handler->lxcpath);
dbc9832d 560
66aeffc7
DL
561 return 0;
562}
563
735f2c6e 564int lxc_poll(const char *name, struct lxc_handler *handler)
b0a33c1e 565{
3c319edb 566 int ret;
86530b0a 567 bool has_console = true;
3c319edb 568 struct lxc_epoll_descr descr, descr_console;
b0a33c1e 569
03760215
CB
570 if (handler->conf->console.path &&
571 strcmp(handler->conf->console.path, "none") == 0)
86530b0a
L
572 has_console = false;
573
3c319edb
CB
574 ret = lxc_mainloop_open(&descr);
575 if (ret < 0) {
576 ERROR("Failed to create mainloop");
50c8bf05 577 goto out_sigfd;
b0a33c1e 578 }
579
30a33fbd
CB
580 if (has_console) {
581 ret = lxc_mainloop_open(&descr_console);
582 if (ret < 0) {
583 ERROR("Failed to create console mainloop");
584 goto out_mainloop;
585 }
3c319edb
CB
586 }
587
1cc8bd4b 588 ret = lxc_mainloop_add_handler(&descr, handler->sigfd, signal_handler, handler);
3c319edb 589 if (ret < 0) {
1cc8bd4b 590 ERROR("Failed to add signal handler for %d to mainloop", handler->sigfd);
3c319edb 591 goto out_mainloop_console;
b0a33c1e 592 }
593
30a33fbd 594 if (has_console) {
dcad02f8 595 struct lxc_terminal *console = &handler->conf->console;
63376d7d 596
093bce5f 597 ret = lxc_terminal_mainloop_add(&descr, console);
30a33fbd
CB
598 if (ret < 0) {
599 ERROR("Failed to add console handlers to mainloop");
600 goto out_mainloop_console;
601 }
602
093bce5f 603 ret = lxc_terminal_mainloop_add(&descr_console, console);
30a33fbd
CB
604 if (ret < 0) {
605 ERROR("Failed to add console handlers to console mainloop");
606 goto out_mainloop_console;
607 }
a54585ad
L
608
609 handler->conf->console.descr = &descr;
563f2f2c
DL
610 }
611
3c319edb
CB
612 ret = lxc_cmd_mainloop_add(name, &descr, handler);
613 if (ret < 0) {
614 ERROR("Failed to add command handler to mainloop");
615 goto out_mainloop_console;
616 }
b0a33c1e 617
3c319edb 618 TRACE("Mainloop is ready");
b0a33c1e 619
3c319edb 620 ret = lxc_mainloop(&descr, -1);
1cc8bd4b
CB
621 close(descr.epfd);
622 descr.epfd = -EBADF;
623 if (ret < 0 || !handler->init_died)
42b09f94 624 goto out_mainloop_console;
1cc8bd4b 625
30a33fbd
CB
626 if (has_console)
627 ret = lxc_mainloop(&descr_console, 0);
628
3c319edb 629out_mainloop_console:
30a33fbd
CB
630 if (has_console) {
631 lxc_mainloop_close(&descr_console);
632 TRACE("Closed console mainloop");
633 }
3c319edb 634
42b09f94
CB
635out_mainloop:
636 lxc_mainloop_close(&descr);
637 TRACE("Closed mainloop");
638
b0a33c1e 639out_sigfd:
1cc8bd4b
CB
640 close(handler->sigfd);
641 TRACE("Closed signal file descriptor %d", handler->sigfd);
642 handler->sigfd = -EBADF;
408da065 643
1cc8bd4b 644 return ret;
b0a33c1e 645}
646
41784e4e
CB
647void lxc_zero_handler(struct lxc_handler *handler)
648{
649 int i;
650
651 memset(handler, 0, sizeof(struct lxc_handler));
652
41784e4e
CB
653 handler->pinfd = -1;
654
655 handler->sigfd = -1;
656
657 for (i = 0; i < LXC_NS_MAX; i++)
658 handler->nsfd[i] = -1;
659
660 handler->data_sock[0] = -1;
661 handler->data_sock[1] = -1;
662
663 handler->state_socket_pair[0] = -1;
664 handler->state_socket_pair[1] = -1;
665
666 handler->sync_sock[0] = -1;
667 handler->sync_sock[1] = -1;
668}
669
f2e07cb6
CB
670void lxc_free_handler(struct lxc_handler *handler)
671{
1cc8bd4b
CB
672 if (handler->pinfd >= 0)
673 close(handler->pinfd);
674
675 if (handler->sigfd >= 0)
676 close(handler->sigfd);
677
678 lxc_put_nsfds(handler);
679
80308d07 680 if (handler->conf && handler->conf->reboot == REBOOT_NONE)
0d0d3655 681 if (handler->conf->maincmd_fd >= 0)
9044b79e 682 lxc_abstract_unix_close(handler->conf->maincmd_fd);
f2e07cb6 683
5e5576a4
CB
684 if (handler->state_socket_pair[0] >= 0)
685 close(handler->state_socket_pair[0]);
686
687 if (handler->state_socket_pair[1] >= 0)
688 close(handler->state_socket_pair[1]);
689
9b10bef5
CB
690 if (handler->cgroup_ops)
691 cgroup_exit(handler->cgroup_ops);
692
f2e07cb6
CB
693 handler->conf = NULL;
694 free(handler);
1cc8bd4b 695 handler = NULL;
f2e07cb6
CB
696}
697
aa460476 698struct lxc_handler *lxc_init_handler(const char *name, struct lxc_conf *conf,
5e5576a4 699 const char *lxcpath, bool daemonize)
59eb99ba 700{
5e5576a4 701 int i, ret;
3a0f472d
DL
702 struct lxc_handler *handler;
703
704 handler = malloc(sizeof(*handler));
fdecbc9c 705 if (!handler)
3a0f472d 706 return NULL;
9044b79e 707
59eb99ba
DL
708 memset(handler, 0, sizeof(*handler));
709
fdecbc9c
CB
710 /* Note that am_guest_unpriv() checks the effective uid. We
711 * probably don't care if we are real root only if we are running
712 * as root so this should be fine.
790255cf 713 */
e0010464 714 handler->am_root = !am_guest_unpriv();
c6012571 715 handler->data_sock[0] = handler->data_sock[1] = -1;
fae349da 716 handler->conf = conf;
9123e471 717 handler->lxcpath = lxcpath;
5c068da9 718 handler->pinfd = -1;
1cc8bd4b
CB
719 handler->sigfd = -EBADF;
720 handler->init_died = false;
5e5576a4 721 handler->state_socket_pair[0] = handler->state_socket_pair[1] = -1;
80308d07 722 if (handler->conf->reboot == REBOOT_NONE)
d39b10eb 723 lxc_list_init(&handler->conf->state_clients);
fae349da 724
b6b2b194
WB
725 for (i = 0; i < LXC_NS_MAX; i++)
726 handler->nsfd[i] = -1;
727
f0ecc19d 728 handler->name = name;
3bdf52d7 729
80308d07 730 if (daemonize && handler->conf->reboot == REBOOT_NONE) {
5e5576a4 731 /* Create socketpair() to synchronize on daemonized startup.
fdecbc9c
CB
732 * When the container reboots we don't need to synchronize
733 * again currently so don't open another socketpair().
5e5576a4
CB
734 */
735 ret = socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
736 handler->state_socket_pair);
737 if (ret < 0) {
738 ERROR("Failed to create anonymous pair of unix sockets");
739 goto on_error;
740 }
9044b79e 741
5e5576a4
CB
742 TRACE("Created anonymous pair {%d,%d} of unix sockets",
743 handler->state_socket_pair[0],
744 handler->state_socket_pair[1]);
745 }
746
80308d07 747 if (handler->conf->reboot == REBOOT_NONE) {
d39b10eb
CB
748 handler->conf->maincmd_fd = lxc_cmd_init(name, lxcpath, "command");
749 if (handler->conf->maincmd_fd < 0) {
750 ERROR("Failed to set up command socket");
751 goto on_error;
752 }
aa460476 753 }
9044b79e 754
9dfa4041 755 TRACE("Unix domain socket %d for command server is ready",
aa460476
CB
756 handler->conf->maincmd_fd);
757
758 return handler;
759
f2e07cb6
CB
760on_error:
761 lxc_free_handler(handler);
aa460476
CB
762
763 return NULL;
764}
765
766int lxc_init(const char *name, struct lxc_handler *handler)
767{
a2c09be0 768 int ret;
4a03ded4 769 const char *loglevel;
aa460476
CB
770 struct lxc_conf *conf = handler->conf;
771
434c8e15
CB
772 handler->monitor_pid = lxc_raw_getpid();
773
aa460476 774 lsm_init();
2170b263 775 TRACE("Initialized LSM");
d2e30e99 776
2170b263
CB
777 ret = lxc_read_seccomp_config(conf);
778 if (ret < 0) {
779 ERROR("Failed loading seccomp policy");
d2e30e99 780 goto out_close_maincmd_fd;
8f2c3a70 781 }
2170b263 782 TRACE("Read seccomp policy");
8f2c3a70 783
408da065 784 /* Begin by setting the state to STARTING. */
2170b263
CB
785 ret = lxc_set_state(name, handler, STARTING);
786 if (ret < 0) {
787 ERROR("Failed to set state to \"%s\"", lxc_state2str(STARTING));
051151de 788 goto out_close_maincmd_fd;
0ad19a3f 789 }
46800e77 790 TRACE("Set container state to \"STARTING\"");
0ad19a3f 791
408da065 792 /* Start of environment variable setup for hooks. */
24c2a48d
CB
793 ret = setenv("LXC_NAME", name, 1);
794 if (ret < 0)
795 SYSERROR("Failed to set environment variable: LXC_NAME=%s", name);
408da065 796
2170b263
CB
797 if (conf->rcfile) {
798 ret = setenv("LXC_CONFIG_FILE", conf->rcfile, 1);
799 if (ret < 0)
800 SYSERROR("Failed to set environment variable: "
801 "LXC_CONFIG_FILE=%s", conf->rcfile);
802 }
408da065 803
2170b263
CB
804 if (conf->rootfs.mount) {
805 ret = setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1);
806 if (ret < 0)
807 SYSERROR("Failed to set environment variable: "
808 "LXC_ROOTFS_MOUNT=%s", conf->rootfs.mount);
809 }
408da065 810
2170b263
CB
811 if (conf->rootfs.path) {
812 ret = setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1);
813 if (ret < 0)
814 SYSERROR("Failed to set environment variable: "
815 "LXC_ROOTFS_PATH=%s", conf->rootfs.path);
816 }
408da065 817
2170b263
CB
818 if (conf->console.path) {
819 ret = setenv("LXC_CONSOLE", conf->console.path, 1);
820 if (ret < 0)
821 SYSERROR("Failed to set environment variable: "
822 "LXC_CONSOLE=%s", conf->console.path);
823 }
408da065 824
2170b263
CB
825 if (conf->console.log_path) {
826 ret = setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1);
827 if (ret < 0)
828 SYSERROR("Failed to set environment variable: "
829 "LXC_CONSOLE_LOGPATH=%s", conf->console.log_path);
830 }
408da065 831
2170b263
CB
832 if (cgns_supported()) {
833 ret = setenv("LXC_CGNS_AWARE", "1", 1);
834 if (ret < 0)
835 SYSERROR("Failed to set environment variable "
836 "LXC_CGNS_AWARE=1");
837 }
b8f88d9b 838
4a03ded4 839 loglevel = lxc_log_priority_to_string(lxc_log_get_level());
2170b263
CB
840 ret = setenv("LXC_LOG_LEVEL", loglevel, 1);
841 if (ret < 0)
842 SYSERROR("Set environment variable LXC_LOG_LEVEL=%s",
843 loglevel);
a2c09be0
CB
844
845 if (conf->hooks_version == 0)
846 ret = setenv("LXC_HOOK_VERSION", "0", 1);
847 else
848 ret = setenv("LXC_HOOK_VERSION", "1", 1);
849 if (ret < 0)
850 SYSERROR("Failed to set environment variable LXC_HOOK_VERSION=%u", conf->hooks_version);
408da065 851 /* End of environment variable setup for hooks. */
f7bee6c6 852
2170b263 853 TRACE("Set environment variables");
dbc9832d 854
2170b263
CB
855 ret = run_lxc_hooks(name, "pre-start", conf, NULL);
856 if (ret < 0) {
857 ERROR("Failed to run lxc.hook.pre-start for container \"%s\"", name);
773fb9ca
SH
858 goto out_aborting;
859 }
2170b263 860 TRACE("Ran pre-start hooks");
26ddeedd 861
408da065
CB
862 /* The signal fd has to be created before forking otherwise if the child
863 * process exits before we setup the signal fd, the event will be lost
864 * and the command will be stuck.
865 */
83ee7875 866 handler->sigfd = setup_signal_fd(&handler->oldmask);
59eb99ba 867 if (handler->sigfd < 0) {
408da065 868 ERROR("Failed to setup SIGCHLD fd handler.");
b5159817
DE
869 goto out_delete_tty;
870 }
2170b263 871 TRACE("Set up signal fd");
b5159817 872
408da065 873 /* Do this after setting up signals since it might unblock SIGWINCH. */
564e31c4 874 ret = lxc_terminal_setup(conf);
4d1ffb0a
CB
875 if (ret < 0) {
876 ERROR("Failed to create console");
b5159817 877 goto out_restore_sigmask;
b0a33c1e 878 }
4d1ffb0a 879 TRACE("Created console");
b0a33c1e 880
2f835b4b 881 ret = lxc_terminal_map_ids(conf, &conf->console);
7cfeddd7 882 if (ret < 0) {
2170b263 883 ERROR("Failed to chown console");
5b74eb3c 884 goto out_delete_terminal;
c4d10a05 885 }
2170b263 886 TRACE("Chowned console");
c4d10a05 887
5a087e05 888 handler->cgroup_ops = cgroup_init(handler->conf);
2202afc9
CB
889 if (!handler->cgroup_ops) {
890 ERROR("Failed to initialize cgroup driver");
5b74eb3c 891 goto out_delete_terminal;
2202afc9
CB
892 }
893 TRACE("Initialized cgroup driver");
894
1800f924
WB
895 ret = lsm_process_prepare(conf, handler->lxcpath);
896 if (ret < 0) {
897 ERROR("Failed to initialize LSM");
898 goto out_destroy_cgroups;
899 }
900 TRACE("Initialized LSM");
901
2170b263 902 INFO("Container \"%s\" is initialized", name);
aa460476 903 return 0;
59eb99ba 904
1800f924 905out_destroy_cgroups:
434c8e15
CB
906 handler->cgroup_ops->payload_destroy(handler->cgroup_ops, handler);
907 handler->cgroup_ops->monitor_destroy(handler->cgroup_ops, handler);
1800f924 908
5b74eb3c
CB
909out_delete_terminal:
910 lxc_terminal_delete(&handler->conf->console);
ea918412 911
b5159817 912out_restore_sigmask:
4c496daa 913 (void)pthread_sigmask(SIG_SETMASK, &handler->oldmask, NULL);
ea918412 914
59eb99ba 915out_delete_tty:
0e4be3cf 916 lxc_delete_tty(&conf->ttys);
ea918412 917
59eb99ba 918out_aborting:
4c496daa 919 (void)lxc_set_state(name, handler, ABORTING);
ea918412 920
d2e30e99 921out_close_maincmd_fd:
9044b79e 922 lxc_abstract_unix_close(conf->maincmd_fd);
d2e30e99 923 conf->maincmd_fd = -1;
aa460476 924 return -1;
59eb99ba
DL
925}
926
3b72c4a0 927void lxc_fini(const char *name, struct lxc_handler *handler)
59eb99ba 928{
c097467f 929 int i, ret;
18b3b9c1 930 pid_t self;
dbc9832d 931 struct lxc_list *cur, *next;
dbc9832d 932 char *namespaces[LXC_NS_MAX + 1];
b3286b62 933 size_t namespace_count = 0;
2202afc9 934 struct cgroup_ops *cgroup_ops = handler->cgroup_ops;
b6b2b194 935
408da065
CB
936 /* The STOPPING state is there for future cleanup code which can take
937 * awhile.
59eb99ba 938 */
25c2aca5 939 lxc_set_state(name, handler, STOPPING);
b6b2b194 940
0059379f 941 self = lxc_raw_getpid();
b3286b62 942 for (i = 0; i < LXC_NS_MAX; i++) {
18b3b9c1
CB
943 if (handler->nsfd[i] < 0)
944 continue;
945
946 if (handler->conf->hooks_version == 0)
c097467f 947 ret = asprintf(&namespaces[namespace_count],
18b3b9c1
CB
948 "%s:/proc/%d/fd/%d", ns_info[i].proc_name,
949 self, handler->nsfd[i]);
950 else
c097467f 951 ret = asprintf(&namespaces[namespace_count],
18b3b9c1 952 "/proc/%d/fd/%d", self, handler->nsfd[i]);
c097467f
CB
953 if (ret == -1) {
954 SYSERROR("Failed to allocate memory");
18b3b9c1 955 break;
b3286b62 956 }
18b3b9c1
CB
957
958 if (handler->conf->hooks_version == 0) {
959 namespace_count++;
960 continue;
961 }
962
c097467f
CB
963 ret = setenv(ns_info[i].env_name, namespaces[namespace_count], 1);
964 if (ret < 0)
18b3b9c1
CB
965 SYSERROR("Failed to set environment variable %s=%s",
966 ns_info[i].env_name, namespaces[namespace_count]);
967 else
968 TRACE("Set environment variable %s=%s",
969 ns_info[i].env_name, namespaces[namespace_count]);
970
971 namespace_count++;
b3286b62
WB
972 }
973 namespaces[namespace_count] = NULL;
c154af98 974
80308d07 975 if (handler->conf->reboot > REBOOT_NONE) {
c097467f
CB
976 ret = setenv("LXC_TARGET", "reboot", 1);
977 if (ret < 0)
978 SYSERROR("Failed to set environment variable: "
979 "LXC_TARGET=reboot");
980 }
408da065 981
80308d07 982 if (handler->conf->reboot == REBOOT_NONE) {
c097467f
CB
983 ret = setenv("LXC_TARGET", "stop", 1);
984 if (ret < 0)
985 SYSERROR("Failed to set environment variable: "
986 "LXC_TARGET=stop");
987 }
c154af98 988
18b3b9c1 989 if (handler->conf->hooks_version == 0)
c097467f 990 ret = run_lxc_hooks(name, "stop", handler->conf, namespaces);
18b3b9c1 991 else
c097467f
CB
992 ret = run_lxc_hooks(name, "stop", handler->conf, NULL);
993 if (ret < 0)
994 ERROR("Failed to run \"lxc.hook.stop\" hook");
c154af98 995
b3286b62
WB
996 while (namespace_count--)
997 free(namespaces[namespace_count]);
28d9e29e 998
1800f924
WB
999 lsm_process_cleanup(handler->conf, handler->lxcpath);
1000
434c8e15
CB
1001 cgroup_ops->payload_destroy(cgroup_ops, handler);
1002 cgroup_ops->monitor_destroy(cgroup_ops, handler);
4288b79f 1003
80308d07 1004 if (handler->conf->reboot == REBOOT_NONE) {
f893d898
CB
1005 /* For all new state clients simply close the command socket.
1006 * This will inform all state clients that the container is
1007 * STOPPED and also prevents a race between a open()/close() on
1008 * the command socket causing a new process to get ECONNREFUSED
1009 * because we haven't yet closed the command socket.
1010 */
9044b79e 1011 lxc_abstract_unix_close(handler->conf->maincmd_fd);
d39b10eb 1012 handler->conf->maincmd_fd = -1;
c3184275
CB
1013 TRACE("Closed command socket");
1014
1015 /* This function will try to connect to the legacy lxc-monitord
1016 * state server and only exists for backwards compatibility.
1017 */
1018 lxc_monitor_send_state(name, STOPPED, handler->lxcpath);
1019
1020 /* The command socket is closed so no one can acces the command
1021 * socket anymore so there's no need to lock it.
1022 */
1023 handler->state = STOPPED;
1024 TRACE("Set container state to \"STOPPED\"");
f893d898
CB
1025 } else {
1026 lxc_set_state(name, handler, STOPPED);
d39b10eb 1027 }
4288b79f 1028
048493a3
CB
1029 /* Avoid lingering namespace references. */
1030 lxc_put_nsfds(handler);
1031
46800e77
CB
1032 ret = run_lxc_hooks(name, "post-stop", handler->conf, NULL);
1033 if (ret < 0) {
c097467f 1034 ERROR("Failed to run lxc.hook.post-stop for container \"%s\"", name);
80308d07 1035 if (handler->conf->reboot > REBOOT_NONE) {
c097467f 1036 WARN("Container will be stopped instead of rebooted");
80308d07 1037 handler->conf->reboot = REBOOT_NONE;
c097467f
CB
1038
1039 ret = setenv("LXC_TARGET", "stop", 1);
1040 if (ret < 0)
1041 WARN("Failed to set environment variable: "
1042 "LXC_TARGET=stop");
f3787121
CB
1043 }
1044 }
26ddeedd 1045
408da065 1046 /* Reset mask set by setup_signal_fd. */
b467714b 1047 ret = pthread_sigmask(SIG_SETMASK, &handler->oldmask, NULL);
c097467f 1048 if (ret < 0)
a24c5678 1049 SYSWARN("Failed to restore signal mask");
8f64a3f6 1050
2aac071b 1051 lxc_terminal_delete(&handler->conf->console);
0e4be3cf 1052 lxc_delete_tty(&handler->conf->ttys);
dbc9832d 1053
dbc9832d
CB
1054 /* The command socket is now closed, no more state clients can register
1055 * themselves from now on. So free the list of state clients.
1056 */
d39b10eb
CB
1057 lxc_list_for_each_safe(cur, &handler->conf->state_clients, next) {
1058 struct lxc_state_client *client = cur->elem;
1059
1060 /* Keep state clients that want to be notified about reboots. */
80308d07
CB
1061 if ((handler->conf->reboot > REBOOT_NONE) &&
1062 (client->states[RUNNING] == 2))
d39b10eb
CB
1063 continue;
1064
dbc9832d 1065 /* close state client socket */
dbc9832d 1066 lxc_list_del(cur);
c097467f 1067 close(client->clientfd);
dbc9832d
CB
1068 free(cur->elem);
1069 free(cur);
1070 }
1071
80308d07 1072 if (handler->conf->ephemeral == 1 && handler->conf->reboot != REBOOT_REQ)
28272964 1073 lxc_destroy_container_on_signal(handler, name);
2c5f2ede 1074
1cc8bd4b 1075 lxc_free_handler(handler);
59eb99ba
DL
1076}
1077
735f2c6e 1078void lxc_abort(const char *name, struct lxc_handler *handler)
59eb99ba 1079{
73e608b2
SH
1080 int ret, status;
1081
25c2aca5 1082 lxc_set_state(name, handler, ABORTING);
0e4f9d51
CB
1083
1084 if (handler->pid > 0) {
1085 ret = kill(handler->pid, SIGKILL);
1086 if (ret < 0)
1087 SYSERROR("Failed to send SIGKILL to %d", handler->pid);
1088 }
1089
408da065
CB
1090 while ((ret = waitpid(-1, &status, 0)) > 0) {
1091 ;
1092 }
59eb99ba
DL
1093}
1094
ffe1e01a 1095static int do_start(void *data)
50e98013 1096{
8bf3abfb 1097 int ret;
7a55c157 1098 char path[PATH_MAX];
928b1f04
YT
1099 uid_t new_uid;
1100 gid_t new_gid;
e96a536c 1101 struct lxc_list *iterator;
964581c2
CB
1102 uid_t nsuid = 0;
1103 gid_t nsgid = 0;
5af9369b 1104 int devnull_fd = -1;
e96a536c 1105 struct lxc_handler *handler = data;
50e98013 1106
18225d19 1107 lxc_sync_fini_parent(handler);
50e98013 1108
408da065
CB
1109 /* This prctl must be before the synchro, so if the parent dies before
1110 * we set the parent death signal, we will detect its death with the
1111 * synchro right after, otherwise we have a window where the parent can
1112 * exit before we set the pdeath signal leading to a unsupervized
1113 * container.
743ecd2e 1114 */
b765aa88 1115 ret = lxc_set_death_signal(SIGKILL, handler->monitor_pid);
912314fc
CB
1116 if (ret < 0) {
1117 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
18225d19 1118 goto out_warn_father;
743ecd2e
DL
1119 }
1120
611ddd34
CB
1121 ret = lxc_ambient_caps_up();
1122 if (ret < 0) {
6f5e532f 1123 ERROR("Failed to raise ambient capabilities");
611ddd34
CB
1124 goto out_warn_father;
1125 }
1126
b467714b 1127 ret = pthread_sigmask(SIG_SETMASK, &handler->oldmask, NULL);
18225d19
CB
1128 if (ret < 0) {
1129 SYSERROR("Failed to set signal mask");
1130 goto out_warn_father;
1131 }
50e98013 1132
408da065 1133 /* Don't leak the pinfd to the container. */
d39b10eb 1134 if (handler->pinfd >= 0)
0d03360a 1135 close(handler->pinfd);
2b0e17e4 1136
18225d19
CB
1137 ret = lxc_sync_wait_parent(handler, LXC_SYNC_STARTUP);
1138 if (ret < 0)
1139 goto out_warn_father;
5b1e83cb 1140
408da065
CB
1141 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
1142 * https://github.com/lxc/lxd/issues/1978.
1143 */
becad0ec 1144 if ((handler->ns_clone_flags & (CLONE_NEWNET | CLONE_NEWUSER)) ==
408da065 1145 (CLONE_NEWNET | CLONE_NEWUSER)) {
5b1e83cb
SH
1146 ret = unshare(CLONE_NEWNET);
1147 if (ret < 0) {
e96a536c 1148 SYSERROR("Failed to unshare CLONE_NEWNET");
5b1e83cb
SH
1149 goto out_warn_father;
1150 }
e96a536c 1151 INFO("Unshared CLONE_NEWNET");
5b1e83cb
SH
1152 }
1153
408da065
CB
1154 /* Tell the parent task it can begin to configure the container and wait
1155 * for it to finish.
3c22086f 1156 */
e96a536c
CB
1157 ret = lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE);
1158 if (ret < 0)
611ddd34 1159 goto out_error;
50e98013 1160
e96a536c
CB
1161 ret = lxc_network_recv_veth_names_from_parent(handler);
1162 if (ret < 0) {
7ab1ba02 1163 ERROR("Failed to receive veth names from parent");
658979c5 1164 goto out_warn_father;
7ab1ba02 1165 }
658979c5 1166
408da065 1167 /* If we are in a new user namespace, become root there to have
d08f8d2f 1168 * privilege over our namespace.
f6d3e3e4
SH
1169 */
1170 if (!lxc_list_empty(&handler->conf->id_map)) {
964581c2
CB
1171 if (!handler->conf->root_nsuid_map)
1172 nsuid = handler->conf->init_uid;
1173
1174 if (!handler->conf->root_nsgid_map)
1175 nsgid = handler->conf->init_gid;
4160c3a0 1176
464c4611 1177 if (!lxc_switch_uid_gid(nsuid, nsgid))
f6d3e3e4 1178 goto out_warn_father;
d08f8d2f
CB
1179
1180 /* Drop groups only after we switched to a valid gid in the new
1181 * user namespace.
1182 */
8af07f82
CB
1183 if (!lxc_setgroups(0, NULL) &&
1184 (handler->am_root || errno != EPERM))
c476bdce 1185 goto out_warn_father;
4b826b1f 1186
b81689a1
CB
1187 ret = prctl(PR_SET_DUMPABLE, prctl_arg(1), prctl_arg(0),
1188 prctl_arg(0), prctl_arg(0));
d7883725
CB
1189 if (ret < 0)
1190 goto out_warn_father;
912314fc
CB
1191
1192 /* set{g,u}id() clears deathsignal */
f08a5cc4 1193 ret = lxc_set_death_signal(SIGKILL, handler->monitor_pid);
912314fc
CB
1194 if (ret < 0) {
1195 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL");
1196 goto out_warn_father;
1197 }
f6d3e3e4
SH
1198 }
1199
e96a536c
CB
1200 ret = access(handler->lxcpath, X_OK);
1201 if (ret != 0) {
c8154066
SH
1202 print_top_failing_dir(handler->lxcpath);
1203 goto out_warn_father;
1204 }
1205
e96a536c
CB
1206 ret = snprintf(path, sizeof(path), "%s/dev/null",
1207 handler->conf->rootfs.mount);
408da065 1208 if (ret < 0 || ret >= sizeof(path))
7a55c157 1209 goto out_warn_father;
7a55c157
TA
1210
1211 /* In order to checkpoint restore, we need to have everything in the
1212 * same mount namespace. However, some containers may not have a
1213 * reasonable /dev (in particular, they may not have /dev/null), so we
1214 * can't set init's std fds to /dev/null by opening it from inside the
1215 * container.
1216 *
1217 * If that's the case, fall back to using the host's /dev/null. This
1218 * means that migration won't work, but at least we won't spew output
1219 * where it isn't wanted.
1220 */
bb955810 1221 if (handler->daemonize && !handler->conf->autodev) {
e96a536c
CB
1222 ret = access(path, F_OK);
1223 if (ret != 0) {
1224 devnull_fd = open_devnull();
c44de748 1225
e96a536c
CB
1226 if (devnull_fd < 0)
1227 goto out_warn_father;
1228 WARN("Using /dev/null from the host for container "
1229 "init's standard file descriptors. Migration will "
1230 "not work");
1231 }
c44de748
AM
1232 }
1233
408da065 1234 /* Ask father to setup cgroups and wait for him to finish. */
e96a536c
CB
1235 ret = lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP);
1236 if (ret < 0)
c44de748 1237 goto out_error;
544a48a0 1238
deefdf8a
CB
1239 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
1240 * earlier we end up with a wrong view of /proc/self/cgroup. For
1241 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
1242 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
1243 * /proc/self/cgroup would show us:
1244 *
1245 * 8:cpuset:/lxc/c
1246 *
1247 * whereas it should actually show
1248 *
1249 * 8:cpuset:/
1250 */
becad0ec 1251 if (handler->ns_clone_flags & CLONE_NEWCGROUP) {
e96a536c
CB
1252 ret = unshare(CLONE_NEWCGROUP);
1253 if (ret < 0) {
bca7c59c
CB
1254 if (errno != EINVAL) {
1255 SYSERROR("Failed to unshare CLONE_NEWCGROUP");
1256 goto out_warn_father;
1257 }
1258
1259 handler->ns_clone_flags &= ~CLONE_NEWCGROUP;
1260 SYSINFO("Kernel does not support CLONE_NEWCGROUP");
1261 } else {
1262 INFO("Unshared CLONE_NEWCGROUP");
deefdf8a 1263 }
deefdf8a
CB
1264 }
1265
149857af
CB
1266 /* Add the requested environment variables to the current environment to
1267 * allow them to be used by the various hooks, such as the start hook
1268 * above.
98ff08ca 1269 */
98ff08ca 1270 lxc_list_for_each(iterator, &handler->conf->environment) {
e96a536c
CB
1271 ret = putenv((char *)iterator->elem);
1272 if (ret < 0) {
1273 SYSERROR("Failed to set environment variable: %s",
1274 (char *)iterator->elem);
98ff08ca
CB
1275 goto out_warn_father;
1276 }
1277 }
1278
f4152036 1279 /* Setup the container, ip, names, utsname, ... */
3b988b33 1280 ret = lxc_setup(handler);
7729f8e5 1281 close(handler->data_sock[1]);
8bf3abfb 1282 close(handler->data_sock[0]);
7729f8e5 1283 if (ret < 0) {
e96a536c 1284 ERROR("Failed to setup container \"%s\"", handler->name);
f4152036
CB
1285 goto out_warn_father;
1286 }
1287
408da065 1288 /* Set the label to change to when we exec(2) the container's init. */
1800f924 1289 ret = lsm_process_label_set(NULL, handler->conf, true);
e96a536c 1290 if (ret < 0)
e075f5d9 1291 goto out_warn_father;
5112cd70 1292
029cdff5 1293 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
408da065
CB
1294 * before we aren't allowed anymore.
1295 */
029cdff5 1296 if (handler->conf->no_new_privs) {
b81689a1
CB
1297 ret = prctl(PR_SET_NO_NEW_PRIVS, prctl_arg(1), prctl_arg(0),
1298 prctl_arg(0), prctl_arg(0));
e96a536c
CB
1299 if (ret < 0) {
1300 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block "
1301 "execve() gainable privileges");
029cdff5
CB
1302 goto out_warn_father;
1303 }
e96a536c
CB
1304 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable "
1305 "privileges");
029cdff5
CB
1306 }
1307
0d9acb99
DE
1308 /* Some init's such as busybox will set sane tty settings on stdin,
1309 * stdout, stderr which it thinks is the console. We already set them
1310 * the way we wanted on the real terminal, and we want init to do its
564e31c4 1311 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
408da065 1312 * make sure that that pty is stdin,stdout,stderr.
0d9acb99 1313 */
5d113f65 1314 if (handler->conf->console.slave >= 0) {
bb955810 1315 if (handler->daemonize || !handler->conf->is_execute)
5d113f65
CB
1316 ret = set_stdfds(handler->conf->console.slave);
1317 else
ae6d3913 1318 ret = lxc_terminal_set_stdfds(handler->conf->console.slave);
5d113f65 1319 if (ret < 0) {
c5b93afb 1320 ERROR("Failed to redirect std{in,out,err} to pty file "
e96a536c 1321 "descriptor %d", handler->conf->console.slave);
c5b93afb
LF
1322 goto out_warn_father;
1323 }
5d113f65 1324 }
0d9acb99 1325
408da065 1326 /* If we mounted a temporary proc, then unmount it now. */
5112cd70 1327 tmp_proc_unmount(handler->conf);
e075f5d9 1328
e96a536c
CB
1329 ret = lxc_seccomp_load(handler->conf);
1330 if (ret < 0)
8f2c3a70
SH
1331 goto out_warn_father;
1332
e96a536c
CB
1333 ret = run_lxc_hooks(handler->name, "start", handler->conf, NULL);
1334 if (ret < 0) {
1335 ERROR("Failed to run lxc.hook.start for container \"%s\"",
1336 handler->name);
773fb9ca
SH
1337 goto out_warn_father;
1338 }
fc25b815 1339
773fb9ca 1340 close(handler->sigfd);
26ddeedd 1341
bb955810 1342 if (handler->conf->console.slave < 0 && handler->daemonize) {
f4c177c3
CB
1343 if (devnull_fd < 0) {
1344 devnull_fd = open_devnull();
1345 if (devnull_fd < 0)
1346 goto out_warn_father;
1347 }
1348
e96a536c
CB
1349 ret = set_stdfds(devnull_fd);
1350 if (ret < 0) {
1351 ERROR("Failed to redirect std{in,out,err} to \"/dev/null\"");
c5b93afb
LF
1352 goto out_warn_father;
1353 }
e96a536c 1354 }
507cee36 1355
c44de748
AM
1356 if (devnull_fd >= 0) {
1357 close(devnull_fd);
1358 devnull_fd = -1;
1359 }
1360
8c9a7665
TA
1361 setsid();
1362
e96a536c
CB
1363 if (handler->conf->init_cwd) {
1364 ret = chdir(handler->conf->init_cwd);
1365 if (ret < 0) {
1366 SYSERROR("Could not change directory to \"%s\"",
1367 handler->conf->init_cwd);
1368 goto out_warn_father;
1369 }
3c491553
L
1370 }
1371
e96a536c
CB
1372 ret = lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP_LIMITS);
1373 if (ret < 0)
f4152036
CB
1374 goto out_warn_father;
1375
149857af
CB
1376 /* Reset the environment variables the user requested in a clear
1377 * environment.
1378 */
e96a536c
CB
1379 ret = clearenv();
1380 /* Don't error out though. */
1381 if (ret < 0)
149857af 1382 SYSERROR("Failed to clear environment.");
149857af
CB
1383
1384 lxc_list_for_each(iterator, &handler->conf->environment) {
e96a536c
CB
1385 ret = putenv((char *)iterator->elem);
1386 if (ret < 0) {
1387 SYSERROR("Failed to set environment variable: %s",
1388 (char *)iterator->elem);
149857af
CB
1389 goto out_warn_father;
1390 }
1391 }
1392
e96a536c
CB
1393 ret = putenv("container=lxc");
1394 if (ret < 0) {
1395 SYSERROR("Failed to set environment variable: container=lxc");
98ff08ca
CB
1396 goto out_warn_father;
1397 }
1398
885766f5
CB
1399 if (handler->conf->ttys.tty_names) {
1400 ret = putenv(handler->conf->ttys.tty_names);
e96a536c
CB
1401 if (ret < 0) {
1402 SYSERROR("Failed to set environment variable for container ptys");
98ff08ca
CB
1403 goto out_warn_father;
1404 }
1405 }
1406
76bdf299
CB
1407 /* The container has been setup. We can now switch to an unprivileged
1408 * uid/gid.
1409 */
928b1f04
YT
1410 new_uid = handler->conf->init_uid;
1411 new_gid = handler->conf->init_gid;
76bdf299 1412
964581c2
CB
1413 /* Avoid unnecessary syscalls. */
1414 if (new_uid == nsuid)
1415 new_uid = LXC_INVALID_UID;
1416
1417 if (new_gid == nsgid)
1418 new_gid = LXC_INVALID_GID;
1419
464c4611 1420 if (!lxc_switch_uid_gid(new_uid, new_gid))
928b1f04
YT
1421 goto out_warn_father;
1422
8af07f82
CB
1423 /* If we are in a new user namespace we already dropped all groups when
1424 * we switched to root in the new user namespace further above. Only
1425 * drop groups if we can, so ensure that we have necessary privilege.
1426 */
1427 if (lxc_list_empty(&handler->conf->id_map))
1428 #if HAVE_LIBCAP
1429 if (lxc_proc_cap_is_set(CAP_SETGID, CAP_EFFECTIVE))
1430 #endif
1431 if (!lxc_setgroups(0, NULL))
1432 goto out_warn_father;
1433
611ddd34
CB
1434 ret = lxc_ambient_caps_down();
1435 if (ret < 0) {
6f5e532f 1436 ERROR("Failed to clear ambient capabilities");
611ddd34
CB
1437 goto out_warn_father;
1438 }
1439
258f8051 1440 if (handler->conf->monitor_signal_pdeath != SIGKILL) {
c7f493ae 1441 ret = lxc_set_death_signal(handler->conf->monitor_signal_pdeath, 0);
258f8051
CB
1442 if (ret < 0) {
1443 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d",
1444 handler->conf->monitor_signal_pdeath);
1445 goto out_warn_father;
1446 }
1447 }
1448
408da065
CB
1449 /* After this call, we are in error because this ops should not return
1450 * as it execs.
1451 */
c4ea60df 1452 handler->ops->start(handler, handler->data);
50e98013
DL
1453
1454out_warn_father:
408da065
CB
1455 /* We want the parent to know something went wrong, so we return a
1456 * special error code.
1457 */
d1ccb562 1458 lxc_sync_wake_parent(handler, LXC_SYNC_ERROR);
c44de748
AM
1459
1460out_error:
1461 if (devnull_fd >= 0)
1462 close(devnull_fd);
1463
50e98013
DL
1464 return -1;
1465}
1466
ae467c54 1467static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
e8bd4e43 1468{
ae467c54 1469 int i;
2520facd 1470 struct lxc_terminal_info *tty;
ae467c54 1471 int ret = -1;
c6012571 1472 int sock = handler->data_sock[1];
e8bd4e43 1473 struct lxc_conf *conf = handler->conf;
0e4be3cf 1474 struct lxc_tty_info *ttys = &conf->ttys;
e8bd4e43 1475
885766f5 1476 if (!conf->ttys.max)
e8bd4e43
SH
1477 return 0;
1478
885766f5 1479 ttys->tty = malloc(sizeof(*ttys->tty) * ttys->max);
0e4be3cf 1480 if (!ttys->tty)
e8bd4e43 1481 return -1;
e8bd4e43 1482
885766f5 1483 for (i = 0; i < conf->ttys.max; i++) {
672c1e58
CB
1484 int ttyfds[2];
1485
1486 ret = lxc_abstract_unix_recv_fds(sock, ttyfds, 2, NULL, 0);
1487 if (ret < 0)
1488 break;
ae467c54 1489
0e4be3cf 1490 tty = &ttys->tty[i];
2520facd
CB
1491 tty->busy = 0;
1492 tty->master = ttyfds[0];
1493 tty->slave = ttyfds[1];
672c1e58 1494 TRACE("Received pty with master fd %d and slave fd %d from "
2520facd 1495 "parent", tty->master, tty->slave);
e8bd4e43 1496 }
6d1400b5 1497
ae467c54 1498 if (ret < 0)
6d1400b5 1499 SYSERROR("Failed to receive %zu ttys from child", ttys->max);
ae467c54 1500 else
885766f5 1501 TRACE("Received %zu ttys from child", ttys->max);
ae467c54
CB
1502
1503 return ret;
e8bd4e43
SH
1504}
1505
5af9369b 1506int resolve_clone_flags(struct lxc_handler *handler)
f813849c 1507{
8bc8c715
CB
1508 int i;
1509 struct lxc_conf *conf = handler->conf;
f813849c 1510
8bc8c715 1511 for (i = 0; i < LXC_NS_MAX; i++) {
f7a0c6ee
CB
1512 if (conf->ns_keep) {
1513 if (!(conf->ns_keep & ns_info[i].clone_flag))
becad0ec 1514 handler->ns_clone_flags |= ns_info[i].clone_flag;
f7a0c6ee
CB
1515 } else if (conf->ns_clone) {
1516 if ((conf->ns_clone & ns_info[i].clone_flag))
becad0ec 1517 handler->ns_clone_flags |= ns_info[i].clone_flag;
8bc8c715
CB
1518 } else {
1519 if (i == LXC_NS_USER && lxc_list_empty(&handler->conf->id_map))
1520 continue;
1521
1522 if (i == LXC_NS_NET && lxc_requests_empty_network(handler))
1523 continue;
1524
7bd05339
CB
1525 if (i == LXC_NS_CGROUP && !cgns_supported())
1526 continue;
1527
becad0ec 1528 handler->ns_clone_flags |= ns_info[i].clone_flag;
8bc8c715 1529 }
03df7ab5 1530
8bc8c715
CB
1531 if (!conf->ns_share[i])
1532 continue;
5af9369b 1533
becad0ec 1534 handler->ns_clone_flags &= ~ns_info[i].clone_flag;
8bc8c715 1535 TRACE("Sharing %s namespace", ns_info[i].proc_name);
5af9369b
CB
1536 }
1537
1538 return 0;
f813849c
TA
1539}
1540
8deca6c9
CB
1541/* Note that this function is used with clone(CLONE_VM). Some glibc versions
1542 * used to reset the pid/tid to -1 when CLONE_VM was used without CLONE_THREAD.
1543 * But since the memory between parent and child is shared on CLONE_VM this
1544 * would invalidate the getpid() cache that glibc used to maintain and so
1545 * getpid() in the child would return the parent's pid. This is all fixed in
1546 * newer glibc versions where the getpid() cache is removed and the pid/tid is
1547 * not reset anymore.
b35ddc5b 1548 * However, if for whatever reason you - dear committer - somehow need to get the
8deca6c9 1549 * pid of the dummy intermediate process for do_share_ns() you need to call
0059379f
CB
1550 * lxc_raw_getpid(). The next lxc_raw_clone() call does not employ CLONE_VM and
1551 * will be fine.
8deca6c9
CB
1552 */
1553static inline int do_share_ns(void *arg)
fa3a5b22 1554{
8deca6c9 1555 int i, flags, ret;
fa3a5b22
CB
1556 struct lxc_handler *handler = arg;
1557
8deca6c9
CB
1558 for (i = 0; i < LXC_NS_MAX; i++) {
1559 if (handler->nsfd[i] < 0)
1560 continue;
fa3a5b22 1561
8deca6c9 1562 ret = setns(handler->nsfd[i], 0);
c0b48eff
CB
1563 if (ret < 0) {
1564 /*
1565 * Note that joining a user and/or mount namespace
1566 * requires the process is not multithreaded otherwise
1567 * setns() will fail here.
1568 */
1569 SYSERROR("Failed to inherit %s namespace",
1570 ns_info[i].proc_name);
8deca6c9 1571 return -1;
c0b48eff 1572 }
fa3a5b22 1573
8deca6c9 1574 DEBUG("Inherited %s namespace", ns_info[i].proc_name);
fa3a5b22
CB
1575 }
1576
becad0ec 1577 flags = handler->ns_on_clone_flags;
8deca6c9 1578 flags |= CLONE_PARENT;
ac2ba696 1579 handler->pid = lxc_raw_clone_cb(do_start, handler, flags);
8deca6c9 1580 if (handler->pid < 0)
fa3a5b22
CB
1581 return -1;
1582
8deca6c9 1583 return 0;
fa3a5b22
CB
1584}
1585
480588e6
CB
1586/* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1587 * exec()s the requested container binary.
1588 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1589 * right here should be double checked if they'd pose a security risk. (For
1590 * example, any {u}mount() operations performed here will be reflected on the
1591 * host!)
1592 */
74a3920a 1593static int lxc_spawn(struct lxc_handler *handler)
59eb99ba 1594{
8deca6c9 1595 int i, ret;
08dd2805 1596 char pidstr[20];
57927bf2
CB
1597 bool wants_to_map_ids;
1598 struct lxc_list *id_map;
6e5fc7a5 1599 const char *name = handler->name;
28d9e29e 1600 const char *lxcpath = handler->lxcpath;
2202afc9 1601 bool share_ns = false;
28d9e29e 1602 struct lxc_conf *conf = handler->conf;
2202afc9 1603 struct cgroup_ops *cgroup_ops = handler->cgroup_ops;
9f30a190 1604
28d9e29e 1605 id_map = &conf->id_map;
57927bf2 1606 wants_to_map_ids = !lxc_list_empty(id_map);
2f2623ec 1607
28d9e29e 1608 for (i = 0; i < LXC_NS_MAX; i++) {
b074bbf1 1609 if (!conf->ns_share[i])
28d9e29e
CB
1610 continue;
1611
b074bbf1 1612 handler->nsfd[i] = lxc_inherit_namespace(conf->ns_share[i], lxcpath, ns_info[i].proc_name);
28d9e29e
CB
1613 if (handler->nsfd[i] < 0)
1614 return -1;
fa3a5b22 1615
8deca6c9 1616 share_ns = true;
28d9e29e 1617 }
50e98013 1618
cfc62c60
CB
1619 ret = lxc_sync_init(handler);
1620 if (ret < 0)
9d7f9e52 1621 return -1;
0ad19a3f 1622
b9f522c5 1623 ret = socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
790255cf 1624 handler->data_sock);
95ef0d7c
CB
1625 if (ret < 0)
1626 goto out_sync_fini;
e8bd4e43 1627
5af9369b 1628 ret = resolve_clone_flags(handler);
95ef0d7c
CB
1629 if (ret < 0)
1630 goto out_sync_fini;
9f30a190 1631
becad0ec 1632 if (handler->ns_clone_flags & CLONE_NEWNET) {
28d9e29e 1633 if (!lxc_list_empty(&conf->network)) {
26b797f3 1634
9f30a190
MM
1635 /* Find gateway addresses from the link device, which is
1636 * no longer accessible inside the container. Do this
1637 * before creating network interfaces, since goto
408da065
CB
1638 * out_delete_net does not work before lxc_clone.
1639 */
cfc62c60
CB
1640 ret = lxc_find_gateway_addresses(handler);
1641 if (ret < 0) {
1642 ERROR("Failed to find gateway addresses");
95ef0d7c 1643 goto out_sync_fini;
9f30a190
MM
1644 }
1645
408da065
CB
1646 /* That should be done before the clone because we will
1647 * fill the netdev index and use them in the child.
9f30a190 1648 */
cfc62c60
CB
1649 ret = lxc_create_network_priv(handler);
1650 if (ret < 0) {
1651 ERROR("Failed to create the network");
78852a0c 1652 goto out_delete_net;
9f30a190 1653 }
19a26f82 1654 }
82d5ae15
DL
1655 }
1656
e8b181f5 1657 if (!cgroup_ops->payload_create(cgroup_ops, handler)) {
cfc62c60 1658 ERROR("Failed creating cgroups");
47d8fb3b
CS
1659 goto out_delete_net;
1660 }
1661
408da065
CB
1662 /* If the rootfs is not a blockdev, prevent the container from marking
1663 * it readonly.
1664 * If the container is unprivileged then skip rootfs pinning.
0c547523 1665 */
0ee35059 1666 if (!wants_to_map_ids) {
28d9e29e 1667 handler->pinfd = pin_rootfs(conf->rootfs.path);
5e32a990 1668 if (handler->pinfd == -1)
cfc62c60 1669 INFO("Failed to pin the rootfs for container \"%s\"", handler->name);
5e32a990 1670 }
0c547523 1671
408da065 1672 /* Create a process in a new set of namespaces. */
becad0ec
CB
1673 handler->ns_on_clone_flags = handler->ns_clone_flags;
1674 if (handler->ns_clone_flags & CLONE_NEWUSER) {
408da065
CB
1675 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1676 * clone a new user namespace first and only later unshare our
1677 * network namespace to ensure that network devices ownership is
1678 * set up correctly.
1679 */
becad0ec 1680 handler->ns_on_clone_flags &= ~CLONE_NEWNET;
408da065 1681 }
5af9369b 1682 /* The cgroup namespace gets unshare()ed not clone()ed. */
becad0ec 1683 handler->ns_on_clone_flags &= ~CLONE_NEWCGROUP;
732375f5 1684
4e232466
CB
1685 if (share_ns) {
1686 pid_t attacher_pid;
1687
cfc62c60
CB
1688 attacher_pid = lxc_clone(do_share_ns, handler,
1689 CLONE_VFORK | CLONE_VM | CLONE_FILES);
4e232466
CB
1690 if (attacher_pid < 0) {
1691 SYSERROR(LXC_CLONE_ERROR);
1692 goto out_delete_net;
1693 }
1694
1695 ret = wait_for_pid(attacher_pid);
1696 if (ret < 0) {
1697 SYSERROR("Intermediate process failed");
1698 goto out_delete_net;
1699 }
1700 } else {
cfc62c60 1701 handler->pid = lxc_raw_clone_cb(do_start, handler,
becad0ec 1702 handler->ns_on_clone_flags);
4e232466
CB
1703 }
1704 if (handler->pid < 0) {
1705 SYSERROR(LXC_CLONE_ERROR);
7fef7a06 1706 goto out_delete_net;
0ad19a3f 1707 }
fa3a5b22 1708 TRACE("Cloned child process %d", handler->pid);
1bd8d726 1709
9662e444 1710 for (i = 0; i < LXC_NS_MAX; i++)
becad0ec 1711 if (handler->ns_on_clone_flags & ns_info[i].clone_flag)
28d9e29e 1712 INFO("Cloned %s", ns_info[i].flag_name);
0ad19a3f 1713
4cb53844 1714 if (!lxc_try_preserve_namespaces(handler, handler->ns_on_clone_flags, handler->pid)) {
28d9e29e
CB
1715 ERROR("Failed to preserve cloned namespaces for lxc.hook.stop");
1716 goto out_delete_net;
1717 }
b6b2b194 1718
3c22086f
CLG
1719 lxc_sync_fini_child(handler);
1720
408da065
CB
1721 /* Map the container uids. The container became an invalid userid the
1722 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1723 * anything immediately, but allows the container to setuid(0) (0 being
1724 * mapped to something else on the host.) later to become a valid uid
1725 * again.
1726 */
fa3a5b22 1727 if (wants_to_map_ids) {
df3c5314 1728 if (!handler->conf->ns_share[LXC_NS_USER] &&
46186acd 1729 (handler->conf->ns_keep & CLONE_NEWUSER) == 0) {
fa3a5b22
CB
1730 ret = lxc_map_ids(id_map, handler->pid);
1731 if (ret < 0) {
1732 ERROR("Failed to set up id mapping.");
1733 goto out_delete_net;
1734 }
1735 }
5b1e83cb
SH
1736 }
1737
cfc62c60
CB
1738 ret = lxc_sync_wake_child(handler, LXC_SYNC_STARTUP);
1739 if (ret < 0)
5b1e83cb 1740 goto out_delete_net;
5b1e83cb 1741
cfc62c60
CB
1742 ret = lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE);
1743 if (ret < 0)
5b1e83cb 1744 goto out_delete_net;
0ad19a3f 1745
2202afc9 1746 if (!cgroup_ops->setup_limits(cgroup_ops, handler->conf, false)) {
cfc62c60 1747 ERROR("Failed to setup cgroup limits for container \"%s\"", name);
6031a6e5
DE
1748 goto out_delete_net;
1749 }
1750
e8b181f5 1751 if (!cgroup_ops->payload_enter(cgroup_ops, handler->pid))
7fef7a06 1752 goto out_delete_net;
218d4250 1753
2202afc9 1754 if (!cgroup_ops->chown(cgroup_ops, handler->conf))
0996e18a
SH
1755 goto out_delete_net;
1756
fa3a5b22 1757 /* Now we're ready to preserve the network namespace */
4cb53844 1758 ret = lxc_try_preserve_ns(handler->pid, "net");
fa3a5b22 1759 if (ret < 0) {
4cb53844 1760 if (ret != -EOPNOTSUPP) {
6d1400b5 1761 SYSERROR("Failed to preserve net namespace");
4cb53844
CB
1762 goto out_delete_net;
1763 }
1764 } else {
1765 handler->nsfd[LXC_NS_NET] = ret;
1766 DEBUG("Preserved net namespace via fd %d", ret);
1cd95214
CB
1767
1768 ret = lxc_netns_set_nsid(handler->nsfd[LXC_NS_NET]);
bfcedc7e 1769 if (ret < 0)
4752343f 1770 SYSWARN("Failed to allocate new network namespace id");
bfcedc7e 1771 else
b7986d0d 1772 TRACE("Allocated new network namespace id");
fa3a5b22 1773 }
fa3a5b22 1774
408da065 1775 /* Create the network configuration. */
becad0ec 1776 if (handler->ns_clone_flags & CLONE_NEWNET) {
cfc62c60
CB
1777 ret = lxc_network_move_created_netdev_priv(handler->lxcpath,
1778 handler->name,
1779 &conf->network,
1780 handler->pid);
1781 if (ret < 0) {
1782 ERROR("Failed to create the configured network");
7fef7a06 1783 goto out_delete_net;
82d5ae15 1784 }
74c6e2b0 1785
cfc62c60 1786 ret = lxc_create_network_unpriv(handler->lxcpath, handler->name,
4d781681 1787 &conf->network, handler->pid, conf->hooks_version);
cfc62c60
CB
1788 if (ret < 0) {
1789 ERROR("Failed to create the configured network");
74c6e2b0
CB
1790 goto out_delete_net;
1791 }
0ad19a3f 1792 }
1793
cfc62c60
CB
1794 ret = lxc_network_send_veth_names_to_child(handler);
1795 if (ret < 0) {
7ab1ba02
CB
1796 ERROR("Failed to send veth names to child");
1797 goto out_delete_net;
658979c5
SH
1798 }
1799
61d7a733
YT
1800 if (!lxc_list_empty(&conf->procs)) {
1801 ret = setup_proc_filesystem(&conf->procs, handler->pid);
1802 if (ret < 0)
1803 goto out_delete_net;
1804 }
1805
408da065
CB
1806 /* Tell the child to continue its initialization. We'll get
1807 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
3c22086f 1808 */
cfc62c60
CB
1809 ret = lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE);
1810 if (ret < 0)
544a48a0
SH
1811 goto out_delete_net;
1812
cfc62c60
CB
1813 if (!lxc_list_empty(&conf->limits)) {
1814 ret = setup_resource_limits(&conf->limits, handler->pid);
1815 if (ret < 0) {
1816 ERROR("Failed to setup resource limits");
1817 goto out_delete_net;
1818 }
c6d09e15
WB
1819 }
1820
cfc62c60
CB
1821 ret = lxc_sync_barrier_child(handler, LXC_SYNC_CGROUP_UNSHARE);
1822 if (ret < 0)
f4152036
CB
1823 goto out_delete_net;
1824
2202afc9 1825 if (!cgroup_ops->setup_limits(cgroup_ops, handler->conf, true)) {
cfc62c60 1826 ERROR("Failed to setup legacy device cgroup controller limits");
b98f7d6e 1827 goto out_delete_net;
544a48a0 1828 }
cfc62c60 1829 TRACE("Set up legacy device cgroup controller limits");
544a48a0 1830
becad0ec 1831 if (handler->ns_clone_flags & CLONE_NEWCGROUP) {
8bf3abfb 1832 /* Now we're ready to preserve the cgroup namespace */
4cb53844 1833 ret = lxc_try_preserve_ns(handler->pid, "cgroup");
8bf3abfb 1834 if (ret < 0) {
4cb53844 1835 if (ret != -EOPNOTSUPP) {
6d1400b5 1836 SYSERROR("Failed to preserve cgroup namespace");
4cb53844
CB
1837 goto out_delete_net;
1838 }
1839 } else {
1840 handler->nsfd[LXC_NS_CGROUP] = ret;
1841 DEBUG("Preserved cgroup namespace via fd %d", ret);
8bf3abfb 1842 }
8bf3abfb
CB
1843 }
1844
5b7f756a
CB
1845 ret = snprintf(pidstr, 20, "%d", handler->pid);
1846 if (ret < 0 || ret >= 20)
1847 goto out_delete_net;
1848
cfc62c60
CB
1849 ret = setenv("LXC_PID", pidstr, 1);
1850 if (ret < 0)
1851 SYSERROR("Failed to set environment variable: LXC_PID=%s", pidstr);
08dd2805
SH
1852
1853 /* Run any host-side start hooks */
cfc62c60
CB
1854 ret = run_lxc_hooks(name, "start-host", conf, NULL);
1855 if (ret < 0) {
1856 ERROR("Failed to run lxc.hook.start-host");
341ed84c 1857 goto out_delete_net;
08dd2805
SH
1858 }
1859
408da065
CB
1860 /* Tell the child to complete its initialization and wait for it to exec
1861 * or return an error. (The child will never return
08dd2805 1862 * LXC_SYNC_READY_START+1. It will either close the sync pipe, causing
408da065
CB
1863 * lxc_sync_barrier_child to return success, or return a different
1864 * value, causing us to error out).
544a48a0 1865 */
cfc62c60
CB
1866 ret = lxc_sync_barrier_child(handler, LXC_SYNC_READY_START);
1867 if (ret < 0)
341ed84c 1868 goto out_delete_net;
0ad19a3f 1869
cfc62c60
CB
1870 ret = lxc_network_recv_name_and_ifindex_from_child(handler);
1871 if (ret < 0) {
790255cf
CB
1872 ERROR("Failed to receive names and ifindices for network "
1873 "devices from child");
1874 goto out_delete_net;
1875 }
1876
1877 /* Now all networks are created, network devices are moved into place,
ad2ddfcd 1878 * and the correct names and ifindices in the respective namespaces have
790255cf
CB
1879 * been recorded. The corresponding structs have now all been filled. So
1880 * log them for debugging purposes.
1881 */
28d9e29e 1882 lxc_log_configured_netdevs(conf);
790255cf 1883
f4152036 1884 /* Read tty fds allocated by child. */
cfc62c60
CB
1885 ret = lxc_recv_ttys_from_child(handler);
1886 if (ret < 0) {
1887 ERROR("Failed to receive tty info from child process");
f4152036
CB
1888 goto out_delete_net;
1889 }
1890
cfc62c60
CB
1891 ret = handler->ops->post_start(handler, handler->data);
1892 if (ret < 0)
e6126dbe
MN
1893 goto out_abort;
1894
cfc62c60
CB
1895 ret = lxc_set_state(name, handler, RUNNING);
1896 if (ret < 0) {
1897 ERROR("Failed to set state to \"%s\"", lxc_state2str(RUNNING));
59eb99ba 1898 goto out_abort;
3f21c114 1899 }
22ebac19 1900
3c22086f 1901 lxc_sync_fini(handler);
0c547523 1902
e6126dbe 1903 return 0;
1ac470c0 1904
7fef7a06 1905out_delete_net:
becad0ec 1906 if (handler->ns_clone_flags & CLONE_NEWNET)
bb84beda 1907 lxc_delete_network(handler);
1bd8d726 1908
59eb99ba
DL
1909out_abort:
1910 lxc_abort(name, handler);
95ef0d7c
CB
1911
1912out_sync_fini:
3c22086f 1913 lxc_sync_fini(handler);
5c068da9
SH
1914 if (handler->pinfd >= 0) {
1915 close(handler->pinfd);
1916 handler->pinfd = -1;
1917 }
1918
b79fcd86 1919 return -1;
59eb99ba 1920}
0ad19a3f 1921
aa460476 1922int __lxc_start(const char *name, struct lxc_handler *handler,
507cee36 1923 struct lxc_operations* ops, void *data, const char *lxcpath,
bb955810 1924 bool daemonize, int *error_num)
59eb99ba 1925{
c30e9b19 1926 int ret, status;
aa460476 1927 struct lxc_conf *conf = handler->conf;
72068e74 1928 struct cgroup_ops *cgroup_ops;
80090207 1929
c30e9b19
CB
1930 ret = lxc_init(name, handler);
1931 if (ret < 0) {
1932 ERROR("Failed to initialize container \"%s\"", name);
66aeffc7 1933 return -1;
0ad19a3f 1934 }
ee70bf78
CLG
1935 handler->ops = ops;
1936 handler->data = data;
bb955810 1937 handler->daemonize = daemonize;
72068e74 1938 cgroup_ops = handler->cgroup_ops;
e6126dbe 1939
76a26f55 1940 if (!attach_block_device(handler->conf)) {
c30e9b19 1941 ERROR("Failed to attach block device");
575ea467 1942 ret = -1;
76a26f55
SH
1943 goto out_fini_nonet;
1944 }
1945
72068e74
CB
1946 if (!cgroup_ops->monitor_create(cgroup_ops, handler)) {
1947 ERROR("Failed to create monitor cgroup");
575ea467 1948 ret = -1;
eeef32bb
CB
1949 goto out_fini_nonet;
1950 }
1951
434c8e15 1952 if (!cgroup_ops->monitor_enter(cgroup_ops, handler->monitor_pid)) {
eeef32bb 1953 ERROR("Failed to enter monitor cgroup");
575ea467 1954 ret = -1;
72068e74
CB
1955 goto out_fini_nonet;
1956 }
1957
35120d9c 1958 if (geteuid() == 0 && !lxc_list_empty(&conf->id_map)) {
408da065 1959 /* If the backing store is a device, mount it here and now. */
35120d9c 1960 if (rootfs_is_blockdev(conf)) {
c30e9b19
CB
1961 ret = unshare(CLONE_NEWNS);
1962 if (ret < 0) {
1963 ERROR("Failed to unshare CLONE_NEWNS");
35120d9c
SH
1964 goto out_fini_nonet;
1965 }
c30e9b19 1966 INFO("Unshared CLONE_NEWNS");
408da065 1967
6a0c909a 1968 remount_all_slave();
8ce1abc2 1969 ret = lxc_setup_rootfs_prepare_root(conf, name, lxcpath);
c30e9b19
CB
1970 if (ret < 0) {
1971 ERROR("Error setting up rootfs mount as root before spawn");
35120d9c
SH
1972 goto out_fini_nonet;
1973 }
c30e9b19 1974 INFO("Set up container rootfs as host root");
35120d9c
SH
1975 }
1976 }
1977
c30e9b19
CB
1978 ret = lxc_spawn(handler);
1979 if (ret < 0) {
1980 ERROR("Failed to spawn container \"%s\"", name);
76a26f55 1981 goto out_detach_blockdev;
0ad19a3f 1982 }
a9e1109e
CB
1983 /* close parent side of data socket */
1984 close(handler->data_sock[0]);
1985 handler->data_sock[0] = -1;
1986 close(handler->data_sock[1]);
1987 handler->data_sock[1] = -1;
0ad19a3f 1988
80308d07 1989 handler->conf->reboot = REBOOT_NONE;
8bee8851 1990
c30e9b19
CB
1991 ret = lxc_poll(name, handler);
1992 if (ret) {
1993 ERROR("LXC mainloop exited with error: %d", ret);
59eb99ba
DL
1994 goto out_abort;
1995 }
0ad19a3f 1996
321db026
DJ
1997 if (!handler->init_died && handler->pid > 0) {
1998 ERROR("Child process is not killed");
575ea467 1999 ret = -1;
321db026
DJ
2000 goto out_abort;
2001 }
2002
c30e9b19
CB
2003 status = lxc_wait_for_pid_status(handler->pid);
2004 if (status < 0)
2005 SYSERROR("Failed to retrieve status for %d", handler->pid);
e043236e 2006
408da065
CB
2007 /* If the child process exited but was not signaled, it didn't call
2008 * reboot. This should mean it was an lxc-execute which simply exited.
2009 * In any case, treat it as a 'halt'.
8b004f07 2010 */
d028235d 2011 if (WIFSIGNALED(status)) {
8b004f07
SH
2012 switch(WTERMSIG(status)) {
2013 case SIGINT: /* halt */
c30e9b19 2014 DEBUG("Container \"%s\" is halting", name);
8b004f07
SH
2015 break;
2016 case SIGHUP: /* reboot */
c30e9b19 2017 DEBUG("Container \"%s\" is rebooting", name);
80308d07 2018 handler->conf->reboot = REBOOT_REQ;
8b004f07 2019 break;
c2b9bd9e 2020 case SIGSYS: /* seccomp */
c30e9b19 2021 DEBUG("Container \"%s\" violated its seccomp policy", name);
c2b9bd9e 2022 break;
8b004f07 2023 default:
c30e9b19 2024 DEBUG("Unknown exit status for container \"%s\" init %d", name, WTERMSIG(status));
8b004f07
SH
2025 break;
2026 }
d028235d 2027 }
828695d9 2028
c30e9b19
CB
2029 ret = lxc_restore_phys_nics_to_netns(handler);
2030 if (ret < 0)
b809f232
CB
2031 ERROR("Failed to move physical network devices back to parent "
2032 "network namespace");
ce5782df 2033
5c068da9
SH
2034 if (handler->pinfd >= 0) {
2035 close(handler->pinfd);
2036 handler->pinfd = -1;
2037 }
2038
1787abca 2039 lxc_monitor_send_exit_code(name, status, handler->lxcpath);
eb808539 2040 lxc_error_set_and_log(handler->pid, status);
a3b4f3d6
TA
2041 if (error_num)
2042 *error_num = handler->exit_status;
1bd8d726 2043
9d7f9e52 2044out_fini:
bb84beda 2045 lxc_delete_network(handler);
74a2b586 2046
76a26f55
SH
2047out_detach_blockdev:
2048 detach_block_device(handler->conf);
2049
74a2b586 2050out_fini_nonet:
3a0f472d 2051 lxc_fini(name, handler);
c30e9b19 2052 return ret;
0ad19a3f 2053
59eb99ba 2054out_abort:
3a0f472d 2055 lxc_abort(name, handler);
9d7f9e52 2056 goto out_fini;
0ad19a3f 2057}
ee70bf78
CLG
2058
2059struct start_args {
2060 char *const *argv;
2061};
2062
2063static int start(struct lxc_handler *handler, void* data)
2064{
2065 struct start_args *arg = data;
2066
984984e4 2067 NOTICE("Exec'ing \"%s\"", arg->argv[0]);
ee70bf78
CLG
2068
2069 execvp(arg->argv[0], arg->argv);
984984e4 2070 SYSERROR("Failed to exec \"%s\"", arg->argv[0]);
ee70bf78
CLG
2071 return 0;
2072}
2073
2074static int post_start(struct lxc_handler *handler, void* data)
2075{
2076 struct start_args *arg = data;
2077
4c8e880e 2078 NOTICE("Started \"%s\" with pid \"%d\"", arg->argv[0], handler->pid);
ee70bf78
CLG
2079 return 0;
2080}
2081
2082static struct lxc_operations start_ops = {
2083 .start = start,
2084 .post_start = post_start
2085};
2086
aa460476 2087int lxc_start(const char *name, char *const argv[], struct lxc_handler *handler,
bb955810 2088 const char *lxcpath, bool daemonize, int *error_num)
ee70bf78
CLG
2089{
2090 struct start_args start_arg = {
2091 .argv = argv,
2092 };
2093
b2efeb0b 2094 TRACE("Doing lxc_start");
bb955810 2095 return __lxc_start(name, handler, &start_ops, &start_arg, lxcpath, daemonize, error_num);
ee70bf78 2096}
28272964
CB
2097
2098static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
2099 const char *name)
2100{
245100a0 2101 char destroy[PATH_MAX];
f01f7975 2102 struct lxc_container *c;
ae3beac9
CB
2103 int ret = 0;
2104 bool bret = true;
2105
df31363a 2106 if (handler->conf->rootfs.path && handler->conf->rootfs.mount) {
790255cf 2107 bret = do_destroy_container(handler);
28272964 2108 if (!bret) {
ae3beac9 2109 ERROR("Error destroying rootfs for container \"%s\"", name);
28272964
CB
2110 return;
2111 }
2112 }
ae3beac9 2113 INFO("Destroyed rootfs for container \"%s\"", name);
28272964 2114
245100a0
CB
2115 ret = snprintf(destroy, PATH_MAX, "%s/%s", handler->lxcpath, name);
2116 if (ret < 0 || ret >= PATH_MAX) {
ae3beac9 2117 ERROR("Error destroying directory for container \"%s\"", name);
28272964
CB
2118 return;
2119 }
2120
f01f7975
CB
2121 c = lxc_container_new(name, handler->lxcpath);
2122 if (c) {
2123 if (container_disk_lock(c)) {
ae3beac9 2124 INFO("Could not update lxc_snapshots file");
f01f7975
CB
2125 lxc_container_put(c);
2126 } else {
2127 mod_all_rdeps(c, false);
2128 container_disk_unlock(c);
2129 lxc_container_put(c);
2130 }
2131 }
2132
d0fbc7ba 2133 if (!handler->am_root)
94b0a3ac
CB
2134 ret = userns_exec_full(handler->conf, lxc_rmdir_onedev_wrapper,
2135 destroy, "lxc_rmdir_onedev_wrapper");
28272964
CB
2136 else
2137 ret = lxc_rmdir_onedev(destroy, NULL);
2138
2139 if (ret < 0) {
ae3beac9 2140 ERROR("Error destroying directory for container \"%s\"", name);
28272964
CB
2141 return;
2142 }
ae3beac9 2143 INFO("Destroyed directory for container \"%s\"", name);
28272964
CB
2144}
2145
2146static int lxc_rmdir_onedev_wrapper(void *data)
2147{
2148 char *arg = (char *) data;
2149 return lxc_rmdir_onedev(arg, NULL);
2150}
2151
134df645
CB
2152static bool do_destroy_container(struct lxc_handler *handler)
2153{
94b0a3ac
CB
2154 int ret;
2155
d0fbc7ba 2156 if (!handler->am_root) {
94b0a3ac
CB
2157 ret = userns_exec_full(handler->conf, storage_destroy_wrapper,
2158 handler->conf, "storage_destroy_wrapper");
2159 if (ret < 0)
d028235d 2160 return false;
10bc1861 2161
d028235d
SG
2162 return true;
2163 }
10bc1861 2164
790255cf 2165 return storage_destroy(handler->conf);
28272964 2166}