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