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