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