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