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