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