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