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