]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/start.c
lxccontainer: use userns_exec_full()
[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>
f3787121
CB
35#include <signal.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <unistd.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>
ff218c25 50
e37dda71 51#if HAVE_LIBCAP
495d2046
SG
52#include <sys/capability.h>
53#endif
54
955e2a02 55#ifndef HAVE_DECL_PR_CAPBSET_DROP
656994bb
MH
56#define PR_CAPBSET_DROP 24
57#endif
58
955e2a02
CB
59#ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
60#define PR_SET_NO_NEW_PRIVS 38
61#endif
62
63#ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
64#define PR_GET_NO_NEW_PRIVS 39
65#endif
66
f3787121
CB
67#include "af_unix.h"
68#include "caps.h"
563f2f2c 69#include "cgroup.h"
f3787121 70#include "commands.h"
bbf5cf35 71#include "commands_utils.h"
f3787121 72#include "conf.h"
74c6e2b0 73#include "confile_utils.h"
f3787121 74#include "console.h"
e2bcd7db 75#include "error.h"
f3787121 76#include "log.h"
f2d5a09d 77#include "lxccontainer.h"
f3787121
CB
78#include "lxclock.h"
79#include "lxcseccomp.h"
f3787121 80#include "mainloop.h"
63376d7d 81#include "monitor.h"
f549edcc 82#include "namespace.h"
811ef482 83#include "network.h"
f3787121 84#include "start.h"
28d832c4 85#include "storage.h"
f2d5a09d 86#include "storage_utils.h"
f3787121
CB
87#include "sync.h"
88#include "utils.h"
fe4de9a6 89#include "lsm/lsm.h"
36eb9bde
CLG
90
91lxc_log_define(lxc_start, lxc);
92
f01f7975 93extern void mod_all_rdeps(struct lxc_container *c, bool inc);
790255cf 94static bool do_destroy_container(struct lxc_handler *handler);
28272964
CB
95static int lxc_rmdir_onedev_wrapper(void *data);
96static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
97 const char *name);
98
c8154066
SH
99static void print_top_failing_dir(const char *path)
100{
101 size_t len = strlen(path);
f3787121 102 char *copy = alloca(len + 1), *p, *e, saved;
c8154066
SH
103 strcpy(copy, path);
104
105 p = copy;
106 e = copy + len;
107 while (p < e) {
f3787121
CB
108 while (p < e && *p == '/')
109 p++;
110 while (p < e && *p != '/')
111 p++;
c8154066
SH
112 saved = *p;
113 *p = '\0';
114 if (access(copy, X_OK)) {
408da065
CB
115 SYSERROR("Could not access %s. Please grant it x "
116 "access, or add an ACL for the container "
117 "root.", copy);
c8154066
SH
118 return;
119 }
120 *p = saved;
121 }
122}
123
408da065
CB
124static void close_ns(int ns_fd[LXC_NS_MAX])
125{
9f30a190
MM
126 int i;
127
9f30a190
MM
128 for (i = 0; i < LXC_NS_MAX; i++) {
129 if (ns_fd[i] > -1) {
130 close(ns_fd[i]);
131 ns_fd[i] = -1;
132 }
133 }
9f30a190
MM
134}
135
4d8ac866 136/* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
62d05d9b 137 * in clone_flags.
4d8ac866 138 * Return true on success, false on failure.
62d05d9b 139 */
4d8ac866 140static bool preserve_ns(int ns_fd[LXC_NS_MAX], int clone_flags, pid_t pid)
f3787121 141{
62d05d9b 142 int i, ret;
9f30a190 143
9f30a190
MM
144 for (i = 0; i < LXC_NS_MAX; i++)
145 ns_fd[i] = -1;
146
4d8ac866
CB
147 ret = lxc_preserve_ns(pid, "");
148 if (ret < 0) {
149 SYSERROR("Kernel does not support attaching to namespaces.");
62d05d9b 150 return false;
4d8ac866
CB
151 } else {
152 close(ret);
cd43d2d1
SH
153 }
154
9f30a190
MM
155 for (i = 0; i < LXC_NS_MAX; i++) {
156 if ((clone_flags & ns_info[i].clone_flag) == 0)
157 continue;
4d8ac866 158 ns_fd[i] = lxc_preserve_ns(pid, ns_info[i].proc_name);
9f30a190
MM
159 if (ns_fd[i] < 0)
160 goto error;
161 }
162
62d05d9b 163 return true;
9f30a190
MM
164
165error:
4d8ac866
CB
166 if (errno == ENOENT)
167 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info[i].proc_name);
168 else
169 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info[i].proc_name, strerror(errno));
9f30a190 170 close_ns(ns_fd);
62d05d9b 171 return false;
9f30a190
MM
172}
173
174static int attach_ns(const int ns_fd[LXC_NS_MAX]) {
175 int i;
176
177 for (i = 0; i < LXC_NS_MAX; i++) {
178 if (ns_fd[i] < 0)
179 continue;
180
181 if (setns(ns_fd[i], 0) != 0)
182 goto error;
183 }
184 return 0;
185
186error:
408da065 187 SYSERROR("Failed to attach %s namespace.", ns_info[i].proc_name);
9f30a190
MM
188 return -1;
189}
190
80090207
CLG
191static int match_fd(int fd)
192{
193 return (fd == 0 || fd == 1 || fd == 2);
194}
195
47a46cf1
CB
196int lxc_check_inherited(struct lxc_conf *conf, bool closeall,
197 int *fds_to_ignore, size_t len_fds)
80090207 198{
74f96976 199 struct dirent *direntp;
80090207 200 int fd, fddir;
47a46cf1 201 size_t i;
80090207 202 DIR *dir;
80090207 203
d2cf4c37
SH
204 if (conf && conf->close_all_fds)
205 closeall = true;
206
b119f362 207restart:
80090207
CLG
208 dir = opendir("/proc/self/fd");
209 if (!dir) {
13277ec4 210 WARN("Failed to open directory: %s.", strerror(errno));
80090207
CLG
211 return -1;
212 }
213
214 fddir = dirfd(dir);
215
74f96976 216 while ((direntp = readdir(dir))) {
80090207
CLG
217 if (!direntp)
218 break;
219
220 if (!strcmp(direntp->d_name, "."))
221 continue;
222
223 if (!strcmp(direntp->d_name, ".."))
224 continue;
225
d4cff0d2
CB
226 if (lxc_safe_int(direntp->d_name, &fd) < 0) {
227 INFO("Could not parse file descriptor for: %s", direntp->d_name);
228 continue;
229 }
80090207 230
47a46cf1
CB
231 for (i = 0; i < len_fds; i++)
232 if (fds_to_ignore[i] == fd)
233 break;
234
235 if (fd == fddir || fd == lxc_log_fd ||
236 (i < len_fds && fd == fds_to_ignore[i]))
80090207
CLG
237 continue;
238
858377e4
SH
239 if (current_config && fd == current_config->logfd)
240 continue;
241
80090207
CLG
242 if (match_fd(fd))
243 continue;
80090207 244
d2cf4c37 245 if (closeall) {
b119f362
SH
246 close(fd);
247 closedir(dir);
408da065 248 INFO("Closed inherited fd: %d.", fd);
b119f362
SH
249 goto restart;
250 }
408da065 251 WARN("Inherited fd: %d.", fd);
80090207
CLG
252 }
253
408da065 254 /* Only enable syslog at this point to avoid the above logging function
64c57ea1
BD
255 * to open a new fd and make the check_inherited function enter an
256 * infinite loop.
257 */
258 lxc_log_enable_syslog();
259
92c7f629
GK
260 closedir(dir); /* cannot fail */
261 return 0;
80090207
CLG
262}
263
83ee7875 264static int setup_signal_fd(sigset_t *oldmask)
b0a33c1e 265{
266 sigset_t mask;
267 int fd;
268
408da065 269 /* Block everything except serious error signals. */
f3304a29
FW
270 if (sigfillset(&mask) ||
271 sigdelset(&mask, SIGILL) ||
272 sigdelset(&mask, SIGSEGV) ||
273 sigdelset(&mask, SIGBUS) ||
b5159817 274 sigdelset(&mask, SIGWINCH) ||
f3304a29 275 sigprocmask(SIG_BLOCK, &mask, oldmask)) {
408da065 276 SYSERROR("Failed to set signal mask.");
b0a33c1e 277 return -1;
278 }
279
280 fd = signalfd(-1, &mask, 0);
281 if (fd < 0) {
408da065 282 SYSERROR("Failed to create signal file descriptor.");
b0a33c1e 283 return -1;
284 }
285
286 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
408da065 287 SYSERROR("Failed to set FD_CLOEXEC on the signal file descriptor: %d.", fd);
b0a33c1e 288 close(fd);
289 return -1;
290 }
291
408da065 292 DEBUG("Set SIGCHLD handler with file descriptor: %d.", fd);
1ac470c0 293
b0a33c1e 294 return fd;
295}
296
84c92abd 297static int signal_handler(int fd, uint32_t events, void *data,
f3787121 298 struct lxc_epoll_descr *descr)
b0a33c1e 299{
15cd25fd 300 struct signalfd_siginfo siginfo;
80507ee8 301 siginfo_t info;
15cd25fd 302 int ret;
82d89dce 303 pid_t *pid = data;
80507ee8 304 bool init_died = false;
15cd25fd
DL
305
306 ret = read(fd, &siginfo, sizeof(siginfo));
307 if (ret < 0) {
408da065 308 ERROR("Failed to read signal info from signal file descriptor: %d.", fd);
15cd25fd
DL
309 return -1;
310 }
311
312 if (ret != sizeof(siginfo)) {
408da065 313 ERROR("Unexpected size for siginfo struct.");
15cd25fd
DL
314 return -1;
315 }
316
408da065 317 /* Check whether init is running. */
80507ee8
SH
318 info.si_pid = 0;
319 ret = waitid(P_PID, *pid, &info, WEXITED | WNOWAIT | WNOHANG);
408da065 320 if (ret == 0 && info.si_pid == *pid)
80507ee8 321 init_died = true;
80507ee8 322
f3304a29
FW
323 if (siginfo.ssi_signo != SIGCHLD) {
324 kill(*pid, siginfo.ssi_signo);
408da065 325 INFO("Forwarded signal %d to pid %d.", siginfo.ssi_signo, *pid);
80507ee8 326 return init_died ? 1 : 0;
f3304a29
FW
327 }
328
408da065
CB
329 if (siginfo.ssi_code == CLD_STOPPED) {
330 INFO("Container init process was stopped.");
331 return init_died ? 1 : 0;
332 } else if (siginfo.ssi_code == CLD_CONTINUED) {
333 INFO("Container init process was continued.");
80507ee8 334 return init_died ? 1 : 0;
15cd25fd 335 }
1ac470c0 336
408da065
CB
337 /* More robustness, protect ourself from a SIGCHLD sent
338 * by a process different from the container init.
82d89dce
DL
339 */
340 if (siginfo.ssi_pid != *pid) {
af4c0f05 341 NOTICE("Received SIGCHLD from pid %d instead of container init %d.", siginfo.ssi_pid, *pid);
80507ee8 342 return init_died ? 1 : 0;
82d89dce
DL
343 }
344
408da065 345 DEBUG("Container init process %d exited.", *pid);
b0a33c1e 346 return 1;
347}
348
5e5576a4
CB
349static int lxc_serve_state_clients(const char *name,
350 struct lxc_handler *handler,
351 lxc_state_t state)
66aeffc7 352{
dbc9832d
CB
353 ssize_t ret;
354 struct lxc_list *cur, *next;
355 struct state_client *client;
356 struct lxc_msg msg = {.type = lxc_msg_state, .value = state};
357
358 process_lock();
5e5576a4 359
dbc9832d 360 /* Only set state under process lock held so that we don't cause
54446942 361 * lxc_cmd_add_state_client() to miss a state.
dbc9832d 362 */
66aeffc7 363 handler->state = state;
dbc9832d
CB
364 TRACE("set container state to %s", lxc_state2str(state));
365
366 if (lxc_list_empty(&handler->state_clients)) {
367 TRACE("no state clients registered");
368 process_unlock();
65ee1673 369 lxc_monitor_send_state(name, state, handler->lxcpath);
dbc9832d
CB
370 return 0;
371 }
372
373 strncpy(msg.name, name, sizeof(msg.name));
374 msg.name[sizeof(msg.name) - 1] = 0;
375
376 lxc_list_for_each_safe(cur, &handler->state_clients, next) {
377 client = cur->elem;
378
379 if (!client->states[state]) {
380 TRACE("state %s not registered for state client %d",
381 lxc_state2str(state), client->clientfd);
382 continue;
383 }
384
385 TRACE("sending state %s to state client %d",
386 lxc_state2str(state), client->clientfd);
387
388 again:
389 ret = send(client->clientfd, &msg, sizeof(msg), 0);
ee8377bd
CB
390 if (ret <= 0) {
391 if (errno == EINTR) {
392 TRACE("Caught EINTR; retrying");
dbc9832d 393 goto again;
ee8377bd 394 }
dbc9832d
CB
395
396 ERROR("failed to send message to client");
397 }
398
399 /* kick client from list */
400 close(client->clientfd);
401 lxc_list_del(cur);
402 free(cur->elem);
403 free(cur);
404 }
405 process_unlock();
406
5e5576a4
CB
407 return 0;
408}
409
410static int lxc_serve_state_socket_pair(const char *name,
411 struct lxc_handler *handler,
412 lxc_state_t state)
413{
414 ssize_t ret;
415
416 if (!handler->backgrounded ||
417 handler->state_socket_pair[1] < 0 ||
418 state == STARTING)
419 return 0;
420
421 /* Close read end of the socket pair. */
422 close(handler->state_socket_pair[0]);
423 handler->state_socket_pair[0] = -1;
424
ee8377bd 425again:
5e5576a4
CB
426 ret = lxc_abstract_unix_send_credential(handler->state_socket_pair[1],
427 &(int){state}, sizeof(int));
ee8377bd
CB
428 if (ret != sizeof(int)) {
429 if (errno == EINTR)
430 goto again;
5e5576a4
CB
431 SYSERROR("Failed to send state to %d",
432 handler->state_socket_pair[1]);
ee8377bd
CB
433 return -1;
434 }
5e5576a4
CB
435
436 TRACE("Sent container state \"%s\" to %d", lxc_state2str(state),
437 handler->state_socket_pair[1]);
438
439 /* Close write end of the socket pair. */
440 close(handler->state_socket_pair[1]);
441 handler->state_socket_pair[1] = -1;
442
443 return 0;
444}
445
446int lxc_set_state(const char *name, struct lxc_handler *handler,
447 lxc_state_t state)
448{
449 int ret;
450
451 ret = lxc_serve_state_socket_pair(name, handler, state);
452 if (ret < 0) {
453 ERROR("Failed to synchronize via anonymous pair of unix sockets");
454 return -1;
455 }
456
457 ret = lxc_serve_state_clients(name, handler, state);
458 if (ret < 0)
459 return -1;
460
dbc9832d
CB
461 /* This function will try to connect to the legacy lxc-monitord state
462 * server and only exists for backwards compatibility.
463 */
9123e471 464 lxc_monitor_send_state(name, state, handler->lxcpath);
dbc9832d 465
66aeffc7
DL
466 return 0;
467}
468
735f2c6e 469int lxc_poll(const char *name, struct lxc_handler *handler)
b0a33c1e 470{
ca5f7926
DL
471 int sigfd = handler->sigfd;
472 int pid = handler->pid;
b0a33c1e 473 struct lxc_epoll_descr descr;
474
a9e61274 475 if (lxc_mainloop_open(&descr)) {
408da065 476 ERROR("Failed to create LXC mainloop.");
50c8bf05 477 goto out_sigfd;
b0a33c1e 478 }
479
83ee7875 480 if (lxc_mainloop_add_handler(&descr, sigfd, signal_handler, &pid)) {
408da065 481 ERROR("Failed to add signal handler with file descriptor %d to LXC mainloop.", sigfd);
b0a33c1e 482 goto out_mainloop_open;
483 }
484
da41561c 485 if (lxc_console_mainloop_add(&descr, handler->conf)) {
408da065 486 ERROR("Failed to add console handler to LXC mainloop.");
63376d7d
DL
487 goto out_mainloop_open;
488 }
489
ef6e34ee 490 if (lxc_cmd_mainloop_add(name, &descr, handler)) {
408da065 491 ERROR("Failed to add command handler to LXC mainloop.");
96fa1ff0 492 goto out_mainloop_open;
563f2f2c
DL
493 }
494
3f903c04 495 TRACE("lxc mainloop is ready");
b0a33c1e 496
e51d4895 497 return lxc_mainloop(&descr, -1);
b0a33c1e 498
499out_mainloop_open:
500 lxc_mainloop_close(&descr);
408da065 501
b0a33c1e 502out_sigfd:
503 close(sigfd);
408da065 504
c3e13372 505 return -1;
b0a33c1e 506}
507
f2e07cb6
CB
508void lxc_free_handler(struct lxc_handler *handler)
509{
510 if (handler->conf && handler->conf->maincmd_fd)
511 close(handler->conf->maincmd_fd);
512
5e5576a4
CB
513 if (handler->state_socket_pair[0] >= 0)
514 close(handler->state_socket_pair[0]);
515
516 if (handler->state_socket_pair[1] >= 0)
517 close(handler->state_socket_pair[1]);
518
f2e07cb6
CB
519 if (handler->name)
520 free(handler->name);
521
522 handler->conf = NULL;
523 free(handler);
524}
525
aa460476 526struct lxc_handler *lxc_init_handler(const char *name, struct lxc_conf *conf,
5e5576a4 527 const char *lxcpath, bool daemonize)
59eb99ba 528{
5e5576a4 529 int i, ret;
3a0f472d
DL
530 struct lxc_handler *handler;
531
532 handler = malloc(sizeof(*handler));
aa460476
CB
533 if (!handler) {
534 ERROR("failed to allocate memory");
3a0f472d 535 return NULL;
aa460476 536 }
59eb99ba
DL
537
538 memset(handler, 0, sizeof(*handler));
539
790255cf
CB
540 /* Note that am_unpriv() checks the effective uid. We probably don't
541 * care if we are real root only if we are running as root so this
542 * should be fine.
543 */
d0fbc7ba 544 handler->am_root = !am_unpriv();
c6012571 545 handler->data_sock[0] = handler->data_sock[1] = -1;
fae349da 546 handler->conf = conf;
9123e471 547 handler->lxcpath = lxcpath;
5c068da9 548 handler->pinfd = -1;
5e5576a4 549 handler->state_socket_pair[0] = handler->state_socket_pair[1] = -1;
dbc9832d 550 lxc_list_init(&handler->state_clients);
fae349da 551
b6b2b194
WB
552 for (i = 0; i < LXC_NS_MAX; i++)
553 handler->nsfd[i] = -1;
554
3bdf52d7
DL
555 handler->name = strdup(name);
556 if (!handler->name) {
aa460476 557 ERROR("failed to allocate memory");
f2e07cb6 558 goto on_error;
3bdf52d7
DL
559 }
560
5e5576a4
CB
561 if (daemonize && !handler->conf->reboot) {
562 /* Create socketpair() to synchronize on daemonized startup.
563 * When the container reboots we don't need to synchronize again
564 * currently so don't open another socketpair().
565 */
566 ret = socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
567 handler->state_socket_pair);
568 if (ret < 0) {
569 ERROR("Failed to create anonymous pair of unix sockets");
570 goto on_error;
571 }
572 TRACE("Created anonymous pair {%d,%d} of unix sockets",
573 handler->state_socket_pair[0],
574 handler->state_socket_pair[1]);
575 }
576
aa460476
CB
577 if (lxc_cmd_init(name, handler, lxcpath)) {
578 ERROR("failed to set up command socket");
f2e07cb6 579 goto on_error;
aa460476
CB
580 }
581
582 TRACE("unix domain socket %d for command server is ready",
583 handler->conf->maincmd_fd);
584
585 return handler;
586
f2e07cb6
CB
587on_error:
588 lxc_free_handler(handler);
aa460476
CB
589
590 return NULL;
591}
592
593int lxc_init(const char *name, struct lxc_handler *handler)
594{
595 struct lxc_conf *conf = handler->conf;
596
597 lsm_init();
598 TRACE("initialized LSM");
d2e30e99 599
8f2c3a70 600 if (lxc_read_seccomp_config(conf) != 0) {
408da065 601 ERROR("Failed loading seccomp policy.");
d2e30e99 602 goto out_close_maincmd_fd;
8f2c3a70 603 }
dbc9832d 604 TRACE("read seccomp policy");
8f2c3a70 605
408da065 606 /* Begin by setting the state to STARTING. */
25c2aca5 607 if (lxc_set_state(name, handler, STARTING)) {
408da065 608 ERROR("Failed to set state for container \"%s\" to \"%s\".", name, lxc_state2str(STARTING));
051151de 609 goto out_close_maincmd_fd;
0ad19a3f 610 }
dbc9832d 611 TRACE("set container state to \"STARTING\"");
0ad19a3f 612
408da065
CB
613 /* Start of environment variable setup for hooks. */
614 if (name && setenv("LXC_NAME", name, 1))
615 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name);
616
617 if (conf->rcfile && setenv("LXC_CONFIG_FILE", conf->rcfile, 1))
618 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf->rcfile);
619
620 if (conf->rootfs.mount && setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1))
621 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf->rootfs.mount);
622
623 if (conf->rootfs.path && setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1))
624 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf->rootfs.path);
625
626 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1))
627 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf->console.path);
628
629 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1))
630 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf->console.log_path);
631
632 if (setenv("LXC_CGNS_AWARE", "1", 1))
633 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
634 /* End of environment variable setup for hooks. */
f7bee6c6 635
dbc9832d
CB
636 TRACE("set environment variables");
637
283678ed 638 if (run_lxc_hooks(name, "pre-start", conf, handler->lxcpath, NULL)) {
408da065 639 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name);
773fb9ca
SH
640 goto out_aborting;
641 }
dbc9832d 642 TRACE("ran pre-start hooks");
26ddeedd 643
408da065
CB
644 /* The signal fd has to be created before forking otherwise if the child
645 * process exits before we setup the signal fd, the event will be lost
646 * and the command will be stuck.
647 */
83ee7875 648 handler->sigfd = setup_signal_fd(&handler->oldmask);
59eb99ba 649 if (handler->sigfd < 0) {
408da065 650 ERROR("Failed to setup SIGCHLD fd handler.");
b5159817
DE
651 goto out_delete_tty;
652 }
dbc9832d 653 TRACE("set up signal fd");
b5159817 654
408da065 655 /* Do this after setting up signals since it might unblock SIGWINCH. */
b5159817 656 if (lxc_console_create(conf)) {
408da065 657 ERROR("Failed to create console for container \"%s\".", name);
b5159817 658 goto out_restore_sigmask;
b0a33c1e 659 }
dbc9832d 660 TRACE("created console");
b0a33c1e 661
54117de5 662 if (lxc_ttys_shift_ids(conf) < 0) {
408da065 663 ERROR("Failed to shift tty into container.");
c4d10a05
SH
664 goto out_restore_sigmask;
665 }
dbc9832d 666 TRACE("shifted tty ids");
c4d10a05 667
dbc9832d 668 INFO("container \"%s\" is initialized", name);
aa460476 669 return 0;
59eb99ba 670
b5159817
DE
671out_restore_sigmask:
672 sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
59eb99ba 673out_delete_tty:
fae349da 674 lxc_delete_tty(&conf->tty_info);
59eb99ba 675out_aborting:
25c2aca5 676 lxc_set_state(name, handler, ABORTING);
d2e30e99
DE
677out_close_maincmd_fd:
678 close(conf->maincmd_fd);
679 conf->maincmd_fd = -1;
aa460476 680 return -1;
59eb99ba
DL
681}
682
3b72c4a0 683void lxc_fini(const char *name, struct lxc_handler *handler)
59eb99ba 684{
b3286b62 685 int i, rc;
dbc9832d 686 struct lxc_list *cur, *next;
b3286b62 687 pid_t self = getpid();
dbc9832d 688 char *namespaces[LXC_NS_MAX + 1];
b3286b62 689 size_t namespace_count = 0;
b6b2b194 690
408da065
CB
691 /* The STOPPING state is there for future cleanup code which can take
692 * awhile.
59eb99ba 693 */
25c2aca5 694 lxc_set_state(name, handler, STOPPING);
b6b2b194 695
b3286b62
WB
696 for (i = 0; i < LXC_NS_MAX; i++) {
697 if (handler->nsfd[i] != -1) {
698 rc = asprintf(&namespaces[namespace_count], "%s:/proc/%d/fd/%d",
699 ns_info[i].proc_name, self, handler->nsfd[i]);
700 if (rc == -1) {
408da065 701 SYSERROR("Failed to allocate memory.");
b3286b62
WB
702 break;
703 }
704 ++namespace_count;
705 }
706 }
707 namespaces[namespace_count] = NULL;
c154af98 708
408da065
CB
709 if (handler->conf->reboot && setenv("LXC_TARGET", "reboot", 1))
710 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
711
712 if (!handler->conf->reboot && setenv("LXC_TARGET", "stop", 1))
713 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
c154af98 714
b3286b62 715 if (run_lxc_hooks(name, "stop", handler->conf, handler->lxcpath, namespaces))
408da065 716 ERROR("Failed to run lxc.hook.stop for container \"%s\".", name);
c154af98 717
b3286b62
WB
718 while (namespace_count--)
719 free(namespaces[namespace_count]);
b6b2b194
WB
720 for (i = 0; i < LXC_NS_MAX; i++) {
721 if (handler->nsfd[i] != -1) {
722 close(handler->nsfd[i]);
723 handler->nsfd[i] = -1;
724 }
725 }
738d0deb
CB
726
727 if (handler->netnsfd >= 0) {
728 close(handler->netnsfd);
729 handler->netnsfd = -1;
730 }
731
4288b79f
CB
732 cgroup_destroy(handler);
733
25c2aca5 734 lxc_set_state(name, handler, STOPPED);
59eb99ba 735
4288b79f
CB
736 /* close command socket */
737 close(handler->conf->maincmd_fd);
738 handler->conf->maincmd_fd = -1;
739
f3787121 740 if (run_lxc_hooks(name, "post-stop", handler->conf, handler->lxcpath, NULL)) {
408da065 741 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name);
f3787121
CB
742 if (handler->conf->reboot) {
743 WARN("Container will be stopped instead of rebooted.");
744 handler->conf->reboot = 0;
408da065
CB
745 if (setenv("LXC_TARGET", "stop", 1))
746 WARN("Failed to set environment variable: LXC_TARGET=stop.");
f3787121
CB
747 }
748 }
26ddeedd 749
408da065 750 /* Reset mask set by setup_signal_fd. */
8f64a3f6 751 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
408da065 752 WARN("Failed to restore signal mask.");
8f64a3f6 753
b5159817 754 lxc_console_delete(&handler->conf->console);
b2431939 755 lxc_delete_tty(&handler->conf->tty_info);
dbc9832d 756
dbc9832d
CB
757 /* The command socket is now closed, no more state clients can register
758 * themselves from now on. So free the list of state clients.
759 */
760 lxc_list_for_each_safe(cur, &handler->state_clients, next) {
761 struct state_client *client = cur->elem;
762 /* close state client socket */
763 close(client->clientfd);
764 lxc_list_del(cur);
765 free(cur->elem);
766 free(cur);
767 }
768
c6012571
CB
769 if (handler->data_sock[0] != -1) {
770 close(handler->data_sock[0]);
771 close(handler->data_sock[1]);
e8bd4e43 772 }
2c5f2ede
CB
773
774 if (handler->conf->ephemeral == 1 && handler->conf->reboot != 1)
28272964 775 lxc_destroy_container_on_signal(handler, name);
2c5f2ede 776
4288b79f 777 free(handler->name);
b2431939 778 free(handler);
59eb99ba
DL
779}
780
735f2c6e 781void lxc_abort(const char *name, struct lxc_handler *handler)
59eb99ba 782{
73e608b2
SH
783 int ret, status;
784
25c2aca5 785 lxc_set_state(name, handler, ABORTING);
7d9fb3e9
DL
786 if (handler->pid > 0)
787 kill(handler->pid, SIGKILL);
408da065
CB
788 while ((ret = waitpid(-1, &status, 0)) > 0) {
789 ;
790 }
59eb99ba
DL
791}
792
ffe1e01a 793static int do_start(void *data)
50e98013 794{
7c661726 795 struct lxc_list *iterator;
23c53af9 796 struct lxc_handler *handler = data;
7a55c157
TA
797 int devnull_fd = -1, ret;
798 char path[PATH_MAX];
50e98013
DL
799
800 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL)) {
408da065 801 SYSERROR("Failed to set signal mask.");
9d7f9e52 802 return -1;
50e98013
DL
803 }
804
408da065
CB
805 /* This prctl must be before the synchro, so if the parent dies before
806 * we set the parent death signal, we will detect its death with the
807 * synchro right after, otherwise we have a window where the parent can
808 * exit before we set the pdeath signal leading to a unsupervized
809 * container.
743ecd2e
DL
810 */
811 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
408da065 812 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL.");
743ecd2e
DL
813 return -1;
814 }
815
3c22086f 816 lxc_sync_fini_parent(handler);
50e98013 817
408da065 818 /* Don't leak the pinfd to the container. */
025ed0f3 819 if (handler->pinfd >= 0) {
0d03360a 820 close(handler->pinfd);
025ed0f3 821 }
2b0e17e4 822
5b1e83cb
SH
823 if (lxc_sync_wait_parent(handler, LXC_SYNC_STARTUP))
824 return -1;
825
408da065
CB
826 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
827 * https://github.com/lxc/lxd/issues/1978.
828 */
5b1e83cb 829 if ((handler->clone_flags & (CLONE_NEWNET | CLONE_NEWUSER)) ==
408da065 830 (CLONE_NEWNET | CLONE_NEWUSER)) {
5b1e83cb
SH
831 ret = unshare(CLONE_NEWNET);
832 if (ret < 0) {
408da065 833 SYSERROR("Failed to unshare CLONE_NEWNET.");
5b1e83cb
SH
834 goto out_warn_father;
835 }
408da065 836 INFO("Unshared CLONE_NEWNET.");
5b1e83cb
SH
837 }
838
408da065
CB
839 /* Tell the parent task it can begin to configure the container and wait
840 * for it to finish.
3c22086f
CLG
841 */
842 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE))
9d7f9e52 843 return -1;
50e98013 844
7ab1ba02
CB
845 if (lxc_network_recv_veth_names_from_parent(handler) < 0) {
846 ERROR("Failed to receive veth names from parent");
658979c5 847 goto out_warn_father;
7ab1ba02 848 }
658979c5 849
408da065 850 /* If we are in a new user namespace, become root there to have
d08f8d2f 851 * privilege over our namespace.
f6d3e3e4
SH
852 */
853 if (!lxc_list_empty(&handler->conf->id_map)) {
d08f8d2f 854 if (lxc_switch_uid_gid(0, 0) < 0)
f6d3e3e4 855 goto out_warn_father;
d08f8d2f
CB
856
857 /* Drop groups only after we switched to a valid gid in the new
858 * user namespace.
859 */
860 if (lxc_setgroups(0, NULL) < 0)
c476bdce 861 goto out_warn_father;
f6d3e3e4
SH
862 }
863
99b71824 864 if (access(handler->lxcpath, X_OK)) {
c8154066
SH
865 print_top_failing_dir(handler->lxcpath);
866 goto out_warn_father;
867 }
868
a91cde21 869 ret = snprintf(path, sizeof(path), "%s/dev/null", handler->conf->rootfs.mount);
408da065 870 if (ret < 0 || ret >= sizeof(path))
7a55c157 871 goto out_warn_father;
7a55c157
TA
872
873 /* In order to checkpoint restore, we need to have everything in the
874 * same mount namespace. However, some containers may not have a
875 * reasonable /dev (in particular, they may not have /dev/null), so we
876 * can't set init's std fds to /dev/null by opening it from inside the
877 * container.
878 *
879 * If that's the case, fall back to using the host's /dev/null. This
880 * means that migration won't work, but at least we won't spew output
881 * where it isn't wanted.
882 */
883 if (handler->backgrounded && !handler->conf->autodev && access(path, F_OK) < 0) {
c44de748
AM
884 devnull_fd = open_devnull();
885
886 if (devnull_fd < 0)
887 goto out_warn_father;
408da065
CB
888 WARN("Using /dev/null from the host for container init's "
889 "standard file descriptors. Migration will not work.");
c44de748
AM
890 }
891
408da065 892 /* Ask father to setup cgroups and wait for him to finish. */
544a48a0 893 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP))
c44de748 894 goto out_error;
544a48a0 895
deefdf8a
CB
896 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
897 * earlier we end up with a wrong view of /proc/self/cgroup. For
898 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
899 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
900 * /proc/self/cgroup would show us:
901 *
902 * 8:cpuset:/lxc/c
903 *
904 * whereas it should actually show
905 *
906 * 8:cpuset:/
907 */
908 if (cgns_supported()) {
909 if (unshare(CLONE_NEWCGROUP) < 0) {
910 INFO("Failed to unshare CLONE_NEWCGROUP.");
911 goto out_warn_father;
912 }
913 INFO("Unshared CLONE_NEWCGROUP.");
914 }
915
f4152036 916 /* Setup the container, ip, names, utsname, ... */
7729f8e5
CB
917 ret = lxc_setup(handler);
918 close(handler->data_sock[0]);
919 close(handler->data_sock[1]);
920 if (ret < 0) {
f4152036
CB
921 ERROR("Failed to setup container \"%s\".", handler->name);
922 goto out_warn_father;
923 }
924
408da065 925 /* Set the label to change to when we exec(2) the container's init. */
7aff4f43 926 if (lsm_process_label_set(NULL, handler->conf, 1, 1) < 0)
e075f5d9 927 goto out_warn_father;
5112cd70 928
029cdff5 929 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
408da065
CB
930 * before we aren't allowed anymore.
931 */
029cdff5
CB
932 if (handler->conf->no_new_privs) {
933 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
934 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
935 goto out_warn_father;
936 }
937 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
938 }
939
0d9acb99
DE
940 /* Some init's such as busybox will set sane tty settings on stdin,
941 * stdout, stderr which it thinks is the console. We already set them
942 * the way we wanted on the real terminal, and we want init to do its
408da065
CB
943 * setup on its console ie. the pty allocated in lxc_console_create() so
944 * make sure that that pty is stdin,stdout,stderr.
0d9acb99 945 */
c5b93afb
LF
946 if (handler->conf->console.slave >= 0)
947 if (set_stdfds(handler->conf->console.slave) < 0) {
948 ERROR("Failed to redirect std{in,out,err} to pty file "
949 "descriptor %d",
950 handler->conf->console.slave);
951 goto out_warn_father;
952 }
0d9acb99 953
408da065 954 /* If we mounted a temporary proc, then unmount it now. */
5112cd70 955 tmp_proc_unmount(handler->conf);
e075f5d9 956
8f2c3a70
SH
957 if (lxc_seccomp_load(handler->conf) != 0)
958 goto out_warn_father;
959
283678ed 960 if (run_lxc_hooks(handler->name, "start", handler->conf, handler->lxcpath, NULL)) {
408da065 961 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler->name);
773fb9ca
SH
962 goto out_warn_father;
963 }
fc25b815 964
d08f8d2f
CB
965 /* The container has been setup. We can now switch to an unprivileged
966 * uid/gid.
967 */
968 if (handler->conf->is_execute) {
87bf0db0
CB
969 bool have_cap_setgid;
970 uid_t new_uid = handler->conf->init_uid;
971 gid_t new_gid = handler->conf->init_gid;
d08f8d2f
CB
972
973 /* If we are in a new user namespace we already dropped all
974 * groups when we switched to root in the new user namespace
975 * further above. Only drop groups if we can, so ensure that we
976 * have necessary privilege.
977 */
e37dda71 978 #if HAVE_LIBCAP
207c4c71 979 have_cap_setgid = lxc_proc_cap_is_set(CAP_SETGID, CAP_EFFECTIVE);
df11e022
BN
980 #else
981 have_cap_setgid = false;
982 #endif
87bf0db0 983 if (lxc_list_empty(&handler->conf->id_map) && have_cap_setgid) {
d08f8d2f
CB
984 if (lxc_setgroups(0, NULL) < 0)
985 goto out_warn_father;
986 }
987
988 if (lxc_switch_uid_gid(new_uid, new_gid) < 0)
989 goto out_warn_father;
990 }
991
408da065
CB
992 /* The clearenv() and putenv() calls have been moved here to allow us to
993 * use environment variables passed to the various hooks, such as the
994 * start hook above. Not all of the variables like CONFIG_PATH or ROOTFS
995 * are valid in this context but others are.
996 */
f7bee6c6 997 if (clearenv()) {
408da065
CB
998 SYSERROR("Failed to clear environment.");
999 /* Don't error out though. */
f7bee6c6
MW
1000 }
1001
7c661726
MP
1002 lxc_list_for_each(iterator, &handler->conf->environment) {
1003 if (putenv((char *)iterator->elem)) {
408da065 1004 SYSERROR("Failed to set environment variable: %s.", (char *)iterator->elem);
7c661726
MP
1005 goto out_warn_father;
1006 }
1007 }
1008
f7bee6c6 1009 if (putenv("container=lxc")) {
408da065 1010 SYSERROR("Failed to set environment variable: container=lxc.");
c4ea60df 1011 goto out_warn_father;
f7bee6c6
MW
1012 }
1013
393903d1
SH
1014 if (handler->conf->pty_names) {
1015 if (putenv(handler->conf->pty_names)) {
408da065 1016 SYSERROR("Failed to set environment variable for container ptys.");
393903d1
SH
1017 goto out_warn_father;
1018 }
1019 }
1020
773fb9ca 1021 close(handler->sigfd);
26ddeedd 1022
7a55c157
TA
1023 if (devnull_fd < 0) {
1024 devnull_fd = open_devnull();
1025
1026 if (devnull_fd < 0)
1027 goto out_warn_father;
1028 }
1029
c5b93afb
LF
1030 if (handler->conf->console.slave < 0 && handler->backgrounded)
1031 if (set_stdfds(devnull_fd) < 0) {
1032 ERROR("Failed to redirect std{in,out,err} to "
1033 "\"/dev/null\"");
1034 goto out_warn_father;
1035 }
507cee36 1036
c44de748
AM
1037 if (devnull_fd >= 0) {
1038 close(devnull_fd);
1039 devnull_fd = -1;
1040 }
1041
8c9a7665
TA
1042 setsid();
1043
f4152036
CB
1044 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP_LIMITS))
1045 goto out_warn_father;
1046
408da065
CB
1047 /* After this call, we are in error because this ops should not return
1048 * as it execs.
1049 */
c4ea60df 1050 handler->ops->start(handler, handler->data);
50e98013
DL
1051
1052out_warn_father:
408da065
CB
1053 /* We want the parent to know something went wrong, so we return a
1054 * special error code.
1055 */
d1ccb562 1056 lxc_sync_wake_parent(handler, LXC_SYNC_ERROR);
c44de748
AM
1057
1058out_error:
1059 if (devnull_fd >= 0)
1060 close(devnull_fd);
1061
50e98013
DL
1062 return -1;
1063}
1064
ae467c54 1065static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
e8bd4e43 1066{
ae467c54 1067 int i;
ae467c54
CB
1068 struct lxc_pty_info *pty_info;
1069 int ret = -1;
c6012571 1070 int sock = handler->data_sock[1];
e8bd4e43 1071 struct lxc_conf *conf = handler->conf;
e8bd4e43
SH
1072 struct lxc_tty_info *tty_info = &conf->tty_info;
1073
1074 if (!conf->tty)
1075 return 0;
1076
408da065
CB
1077 tty_info->pty_info = malloc(sizeof(*tty_info->pty_info) * conf->tty);
1078 if (!tty_info->pty_info)
e8bd4e43 1079 return -1;
e8bd4e43 1080
672c1e58
CB
1081 for (i = 0; i < conf->tty; i++) {
1082 int ttyfds[2];
1083
1084 ret = lxc_abstract_unix_recv_fds(sock, ttyfds, 2, NULL, 0);
1085 if (ret < 0)
1086 break;
ae467c54 1087
672c1e58 1088 pty_info = &tty_info->pty_info[i];
e8bd4e43 1089 pty_info->busy = 0;
672c1e58
CB
1090 pty_info->master = ttyfds[0];
1091 pty_info->slave = ttyfds[1];
1092 TRACE("Received pty with master fd %d and slave fd %d from "
ae467c54 1093 "parent", pty_info->master, pty_info->slave);
e8bd4e43 1094 }
ae467c54 1095 if (ret < 0)
672c1e58 1096 ERROR("Failed to receive %d ttys from child: %s", conf->tty,
ae467c54
CB
1097 strerror(errno));
1098 else
672c1e58
CB
1099 TRACE("Received %d ttys from child", conf->tty);
1100
1101 tty_info->nbtty = conf->tty;
ae467c54
CB
1102
1103 return ret;
e8bd4e43
SH
1104}
1105
f813849c
TA
1106void resolve_clone_flags(struct lxc_handler *handler)
1107{
1108 handler->clone_flags = CLONE_NEWPID | CLONE_NEWNS;
1109
408da065 1110 if (!lxc_list_empty(&handler->conf->id_map))
f813849c 1111 handler->clone_flags |= CLONE_NEWUSER;
f813849c
TA
1112
1113 if (handler->conf->inherit_ns_fd[LXC_NS_NET] == -1) {
408da065 1114 if (!lxc_requests_empty_network(handler))
f813849c
TA
1115 handler->clone_flags |= CLONE_NEWNET;
1116 } else {
198cbbaa 1117 INFO("Inheriting a NET namespace.");
f813849c
TA
1118 }
1119
408da065 1120 if (handler->conf->inherit_ns_fd[LXC_NS_IPC] == -1)
f813849c 1121 handler->clone_flags |= CLONE_NEWIPC;
408da065 1122 else
198cbbaa 1123 INFO("Inheriting an IPC namespace.");
f813849c 1124
408da065 1125 if (handler->conf->inherit_ns_fd[LXC_NS_UTS] == -1)
f813849c 1126 handler->clone_flags |= CLONE_NEWUTS;
408da065 1127 else
198cbbaa 1128 INFO("Inheriting a UTS namespace.");
f813849c
TA
1129}
1130
480588e6
CB
1131/* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1132 * exec()s the requested container binary.
1133 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1134 * right here should be double checked if they'd pose a security risk. (For
1135 * example, any {u}mount() operations performed here will be reflected on the
1136 * host!)
1137 */
74a3920a 1138static int lxc_spawn(struct lxc_handler *handler)
59eb99ba 1139{
7ab1ba02 1140 int i, flags, ret;
ffe1e01a 1141 const char *name = handler->name;
57927bf2 1142 bool wants_to_map_ids;
7ab1ba02 1143 int saved_ns_fd[LXC_NS_MAX];
57927bf2 1144 struct lxc_list *id_map;
d0b915aa
CB
1145 int failed_before_rename = 0, preserve_mask = 0;
1146 bool cgroups_connected = false;
9f30a190 1147
57927bf2
CB
1148 id_map = &handler->conf->id_map;
1149 wants_to_map_ids = !lxc_list_empty(id_map);
2f2623ec 1150
9f30a190 1151 for (i = 0; i < LXC_NS_MAX; i++)
6c544cb3 1152 if (handler->conf->inherit_ns_fd[i] != -1)
9f30a190 1153 preserve_mask |= ns_info[i].clone_flag;
50e98013 1154
3c22086f 1155 if (lxc_sync_init(handler))
9d7f9e52 1156 return -1;
0ad19a3f 1157
b9f522c5 1158 ret = socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
790255cf 1159 handler->data_sock);
c6012571 1160 if (ret < 0) {
e8bd4e43
SH
1161 lxc_sync_fini(handler);
1162 return -1;
1163 }
1164
f813849c 1165 resolve_clone_flags(handler);
9f30a190 1166
f813849c 1167 if (handler->clone_flags & CLONE_NEWNET) {
26b797f3
SH
1168 if (!lxc_list_empty(&handler->conf->network)) {
1169
9f30a190
MM
1170 /* Find gateway addresses from the link device, which is
1171 * no longer accessible inside the container. Do this
1172 * before creating network interfaces, since goto
408da065
CB
1173 * out_delete_net does not work before lxc_clone.
1174 */
9f30a190 1175 if (lxc_find_gateway_addresses(handler)) {
408da065 1176 ERROR("Failed to find gateway addresses.");
9f30a190
MM
1177 lxc_sync_fini(handler);
1178 return -1;
1179 }
1180
408da065
CB
1181 /* That should be done before the clone because we will
1182 * fill the netdev index and use them in the child.
9f30a190 1183 */
811ef482 1184 if (lxc_create_network_priv(handler)) {
408da065 1185 ERROR("Failed to create the network.");
9f30a190
MM
1186 lxc_sync_fini(handler);
1187 return -1;
1188 }
19a26f82 1189 }
82d5ae15
DL
1190 }
1191
d4ef7c50 1192 if (!cgroup_init(handler)) {
408da065 1193 ERROR("Failed initializing cgroup support.");
33ad9f1a
CS
1194 goto out_delete_net;
1195 }
1196
7e4dfe0b
SH
1197 cgroups_connected = true;
1198
d4ef7c50 1199 if (!cgroup_create(handler)) {
408da065 1200 ERROR("Failed creating cgroups.");
47d8fb3b
CS
1201 goto out_delete_net;
1202 }
1203
408da065
CB
1204 /* If the rootfs is not a blockdev, prevent the container from marking
1205 * it readonly.
1206 * If the container is unprivileged then skip rootfs pinning.
0c547523 1207 */
0ee35059 1208 if (!wants_to_map_ids) {
5e32a990
ÇO
1209 handler->pinfd = pin_rootfs(handler->conf->rootfs.path);
1210 if (handler->pinfd == -1)
408da065 1211 INFO("Failed to pin the rootfs for container \"%s\".", handler->name);
5e32a990 1212 }
0c547523 1213
4d8ac866 1214 if (!preserve_ns(saved_ns_fd, preserve_mask, getpid()))
cd43d2d1 1215 goto out_delete_net;
4d8ac866 1216
cd43d2d1
SH
1217 if (attach_ns(handler->conf->inherit_ns_fd) < 0)
1218 goto out_delete_net;
9f30a190 1219
408da065 1220 /* Create a process in a new set of namespaces. */
5b1e83cb 1221 flags = handler->clone_flags;
408da065
CB
1222 if (handler->clone_flags & CLONE_NEWUSER) {
1223 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1224 * clone a new user namespace first and only later unshare our
1225 * network namespace to ensure that network devices ownership is
1226 * set up correctly.
1227 */
5b1e83cb 1228 flags &= ~CLONE_NEWNET;
408da065 1229 }
9fac8fbb 1230 handler->pid = lxc_clone(do_start, handler, flags);
59eb99ba 1231 if (handler->pid < 0) {
408da065 1232 SYSERROR("Failed to clone a new set of namespaces.");
7fef7a06 1233 goto out_delete_net;
0ad19a3f 1234 }
1bd8d726 1235
9662e444
CB
1236 for (i = 0; i < LXC_NS_MAX; i++)
1237 if (flags & ns_info[i].clone_flag)
1238 INFO("Cloned %s.", ns_info[i].flag_name);
0ad19a3f 1239
4d8ac866
CB
1240 if (!preserve_ns(handler->nsfd, handler->clone_flags | preserve_mask, handler->pid))
1241 INFO("Failed to preserve namespace for lxc.hook.stop.");
b6b2b194 1242
cd43d2d1 1243 if (attach_ns(saved_ns_fd))
408da065 1244 WARN("Failed to restore saved namespaces.");
9f30a190 1245
3c22086f
CLG
1246 lxc_sync_fini_child(handler);
1247
408da065
CB
1248 /* Map the container uids. The container became an invalid userid the
1249 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1250 * anything immediately, but allows the container to setuid(0) (0 being
1251 * mapped to something else on the host.) later to become a valid uid
1252 * again.
1253 */
57927bf2 1254 if (wants_to_map_ids && lxc_map_ids(id_map, handler->pid)) {
408da065 1255 ERROR("Failed to set up id mapping.");
5b1e83cb
SH
1256 goto out_delete_net;
1257 }
1258
1259 if (lxc_sync_wake_child(handler, LXC_SYNC_STARTUP)) {
99a6af52 1260 failed_before_rename = 1;
5b1e83cb
SH
1261 goto out_delete_net;
1262 }
1263
1264 if (lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE)) {
1265 failed_before_rename = 1;
1266 goto out_delete_net;
1267 }
0ad19a3f 1268
d4ef7c50 1269 if (!cgroup_create_legacy(handler)) {
408da065 1270 ERROR("Failed to setup legacy cgroups for container \"%s\".", name);
ae5c8b8e 1271 goto out_delete_net;
33ad9f1a 1272 }
9daf6f5d 1273 if (!cgroup_setup_limits(handler, false)) {
408da065 1274 ERROR("Failed to setup cgroup limits for container \"%s\".", name);
6031a6e5
DE
1275 goto out_delete_net;
1276 }
1277
d4ef7c50 1278 if (!cgroup_enter(handler))
7fef7a06 1279 goto out_delete_net;
218d4250 1280
0996e18a
SH
1281 if (!cgroup_chown(handler))
1282 goto out_delete_net;
1283
99a6af52
MN
1284 if (failed_before_rename)
1285 goto out_delete_net;
1286
1bd8d726
CB
1287 handler->netnsfd = lxc_preserve_ns(handler->pid, "net");
1288 if (handler->netnsfd < 0) {
1289 ERROR("Failed to preserve network namespace");
1290 goto out_delete_net;
1291 }
1292
408da065 1293 /* Create the network configuration. */
d5088cf2 1294 if (handler->clone_flags & CLONE_NEWNET) {
74c6e2b0
CB
1295 if (lxc_network_move_created_netdev_priv(handler->lxcpath,
1296 handler->name,
1297 &handler->conf->network,
1298 handler->pid)) {
408da065 1299 ERROR("Failed to create the configured network.");
7fef7a06 1300 goto out_delete_net;
82d5ae15 1301 }
74c6e2b0
CB
1302
1303 if (lxc_create_network_unpriv(handler->lxcpath, handler->name,
1304 &handler->conf->network,
1305 handler->pid)) {
1306 ERROR("Failed to create the configured network.");
1307 goto out_delete_net;
1308 }
0ad19a3f 1309 }
1310
7ab1ba02
CB
1311 if (lxc_network_send_veth_names_to_child(handler) < 0) {
1312 ERROR("Failed to send veth names to child");
1313 goto out_delete_net;
658979c5
SH
1314 }
1315
408da065
CB
1316 /* Tell the child to continue its initialization. We'll get
1317 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
3c22086f
CLG
1318 */
1319 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE))
544a48a0
SH
1320 goto out_delete_net;
1321
c6d09e15
WB
1322 if (!lxc_list_empty(&handler->conf->limits) && setup_resource_limits(&handler->conf->limits, handler->pid)) {
1323 ERROR("failed to setup resource limits for '%s'", name);
84ff3af7 1324 goto out_delete_net;
c6d09e15
WB
1325 }
1326
f4152036
CB
1327 if (lxc_sync_barrier_child(handler, LXC_SYNC_CGROUP_UNSHARE))
1328 goto out_delete_net;
1329
9daf6f5d 1330 if (!cgroup_setup_limits(handler, true)) {
408da065 1331 ERROR("Failed to setup the devices cgroup for container \"%s\".", name);
b98f7d6e 1332 goto out_delete_net;
544a48a0 1333 }
f4152036 1334 TRACE("Set up cgroup device limits");
544a48a0 1335
73d28d42 1336 cgroup_disconnect();
7e4dfe0b 1337 cgroups_connected = false;
73d28d42 1338
408da065
CB
1339 /* Tell the child to complete its initialization and wait for it to exec
1340 * or return an error. (The child will never return
1341 * LXC_SYNC_POST_CGROUP+1. It will either close the sync pipe, causing
1342 * lxc_sync_barrier_child to return success, or return a different
1343 * value, causing us to error out).
544a48a0
SH
1344 */
1345 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CGROUP))
3c22086f 1346 return -1;
0ad19a3f 1347
790255cf
CB
1348 if (lxc_network_recv_name_and_ifindex_from_child(handler) < 0) {
1349 ERROR("Failed to receive names and ifindices for network "
1350 "devices from child");
1351 goto out_delete_net;
1352 }
1353
1354 /* Now all networks are created, network devices are moved into place,
1355 * and the correct names and ifindeces in the respective namespaces have
1356 * been recorded. The corresponding structs have now all been filled. So
1357 * log them for debugging purposes.
1358 */
1359 lxc_log_configured_netdevs(handler->conf);
1360
f4152036
CB
1361 /* Read tty fds allocated by child. */
1362 if (lxc_recv_ttys_from_child(handler) < 0) {
1363 ERROR("Failed to receive tty info from child process.");
1364 goto out_delete_net;
1365 }
1366
23c53af9 1367 if (handler->ops->post_start(handler, handler->data))
e6126dbe
MN
1368 goto out_abort;
1369
25c2aca5 1370 if (lxc_set_state(name, handler, RUNNING)) {
408da065
CB
1371 ERROR("Failed to set state for container \"%s\" to \"%s\".", name,
1372 lxc_state2str(RUNNING));
59eb99ba 1373 goto out_abort;
3f21c114 1374 }
22ebac19 1375
3c22086f 1376 lxc_sync_fini(handler);
0c547523 1377
e6126dbe 1378 return 0;
1ac470c0 1379
7fef7a06 1380out_delete_net:
7e4dfe0b
SH
1381 if (cgroups_connected)
1382 cgroup_disconnect();
1bd8d726
CB
1383
1384 if (handler->clone_flags & CLONE_NEWNET) {
1385 DEBUG("Tearing down network devices");
1386 if (!lxc_delete_network_priv(handler))
1387 DEBUG("Failed tearing down network devices");
1388
1389 if (!lxc_delete_network_unpriv(handler))
1390 DEBUG("Failed tearing down network devices");
1391 }
1392
59eb99ba
DL
1393out_abort:
1394 lxc_abort(name, handler);
3c22086f 1395 lxc_sync_fini(handler);
5c068da9
SH
1396 if (handler->pinfd >= 0) {
1397 close(handler->pinfd);
1398 handler->pinfd = -1;
1399 }
1400
1bd8d726
CB
1401 if (handler->netnsfd >= 0) {
1402 close(handler->netnsfd);
1403 handler->netnsfd = -1;
1404 }
1405
b79fcd86 1406 return -1;
59eb99ba 1407}
0ad19a3f 1408
aa460476 1409int __lxc_start(const char *name, struct lxc_handler *handler,
507cee36
TA
1410 struct lxc_operations* ops, void *data, const char *lxcpath,
1411 bool backgrounded)
59eb99ba 1412{
59eb99ba 1413 int status;
aa460476 1414 int err = -1;
aa460476 1415 struct lxc_conf *conf = handler->conf;
80090207 1416
aa460476 1417 if (lxc_init(name, handler) < 0) {
408da065 1418 ERROR("Failed to initialize container \"%s\".", name);
66aeffc7 1419 return -1;
0ad19a3f 1420 }
ee70bf78
CLG
1421 handler->ops = ops;
1422 handler->data = data;
507cee36 1423 handler->backgrounded = backgrounded;
738d0deb 1424 handler->netnsfd = -1;
e6126dbe 1425
76a26f55 1426 if (!attach_block_device(handler->conf)) {
408da065 1427 ERROR("Failed to attach block device.");
76a26f55
SH
1428 goto out_fini_nonet;
1429 }
1430
35120d9c 1431 if (geteuid() == 0 && !lxc_list_empty(&conf->id_map)) {
408da065 1432 /* If the backing store is a device, mount it here and now. */
35120d9c
SH
1433 if (rootfs_is_blockdev(conf)) {
1434 if (unshare(CLONE_NEWNS) < 0) {
408da065 1435 ERROR("Failed to unshare CLONE_NEWNS.");
35120d9c
SH
1436 goto out_fini_nonet;
1437 }
408da065
CB
1438 INFO("Unshared CLONE_NEWNS.");
1439
6a0c909a 1440 remount_all_slave();
35120d9c 1441 if (do_rootfs_setup(conf, name, lxcpath) < 0) {
408da065 1442 ERROR("Error setting up rootfs mount as root before spawn.");
35120d9c
SH
1443 goto out_fini_nonet;
1444 }
408da065 1445 INFO("Set up container rootfs as host root.");
35120d9c
SH
1446 }
1447 }
1448
23c53af9 1449 err = lxc_spawn(handler);
59eb99ba 1450 if (err) {
408da065 1451 ERROR("Failed to spawn container \"%s\".", name);
76a26f55 1452 goto out_detach_blockdev;
0ad19a3f 1453 }
1454
8bee8851
WB
1455 handler->conf->reboot = 0;
1456
3a0f472d 1457 err = lxc_poll(name, handler);
e043236e 1458 if (err) {
408da065 1459 ERROR("LXC mainloop exited with error: %d.", err);
59eb99ba
DL
1460 goto out_abort;
1461 }
0ad19a3f 1462
3a0f472d 1463 while (waitpid(handler->pid, &status, 0) < 0 && errno == EINTR)
1bc5cc8c 1464 continue;
e043236e 1465
408da065
CB
1466 /* If the child process exited but was not signaled, it didn't call
1467 * reboot. This should mean it was an lxc-execute which simply exited.
1468 * In any case, treat it as a 'halt'.
8b004f07 1469 */
d028235d 1470 if (WIFSIGNALED(status)) {
8b004f07
SH
1471 switch(WTERMSIG(status)) {
1472 case SIGINT: /* halt */
408da065 1473 DEBUG("Container \"%s\" is halting.", name);
8b004f07
SH
1474 break;
1475 case SIGHUP: /* reboot */
408da065 1476 DEBUG("Container \"%s\" is rebooting.", name);
8b004f07
SH
1477 handler->conf->reboot = 1;
1478 break;
c2b9bd9e 1479 case SIGSYS: /* seccomp */
408da065 1480 DEBUG("Container \"%s\" violated its seccomp policy.", name);
c2b9bd9e 1481 break;
8b004f07 1482 default:
408da065 1483 DEBUG("Unknown exit status for container \"%s\" init %d.", name, WTERMSIG(status));
8b004f07
SH
1484 break;
1485 }
d028235d 1486 }
828695d9 1487
b809f232
CB
1488 err = lxc_restore_phys_nics_to_netns(handler);
1489 if (err < 0)
1490 ERROR("Failed to move physical network devices back to parent "
1491 "network namespace");
ce5782df 1492
5c068da9
SH
1493 if (handler->pinfd >= 0) {
1494 close(handler->pinfd);
1495 handler->pinfd = -1;
1496 }
1497
1787abca 1498 lxc_monitor_send_exit_code(name, status, handler->lxcpath);
3a0f472d 1499 err = lxc_error_set_and_log(handler->pid, status);
1bd8d726 1500
9d7f9e52 1501out_fini:
1bd8d726
CB
1502 DEBUG("Tearing down network devices");
1503 if (!lxc_delete_network_priv(handler))
1504 DEBUG("Failed tearing down network devices");
1505
1506 if (!lxc_delete_network_unpriv(handler))
1507 DEBUG("Failed tearing down network devices");
1508
1509 if (handler->netnsfd >= 0) {
1510 close(handler->netnsfd);
1511 handler->netnsfd = -1;
358daf49 1512 }
74a2b586 1513
76a26f55
SH
1514out_detach_blockdev:
1515 detach_block_device(handler->conf);
1516
74a2b586 1517out_fini_nonet:
3a0f472d 1518 lxc_fini(name, handler);
0ad19a3f 1519 return err;
1520
59eb99ba 1521out_abort:
3a0f472d 1522 lxc_abort(name, handler);
9d7f9e52 1523 goto out_fini;
0ad19a3f 1524}
ee70bf78
CLG
1525
1526struct start_args {
1527 char *const *argv;
1528};
1529
1530static int start(struct lxc_handler *handler, void* data)
1531{
1532 struct start_args *arg = data;
1533
408da065 1534 NOTICE("Exec'ing \"%s\".", arg->argv[0]);
ee70bf78
CLG
1535
1536 execvp(arg->argv[0], arg->argv);
408da065 1537 SYSERROR("Failed to exec \"%s\".", arg->argv[0]);
ee70bf78
CLG
1538 return 0;
1539}
1540
1541static int post_start(struct lxc_handler *handler, void* data)
1542{
1543 struct start_args *arg = data;
1544
408da065 1545 NOTICE("Started \"%s\" with pid \"%d\".", arg->argv[0], handler->pid);
ee70bf78
CLG
1546 return 0;
1547}
1548
1549static struct lxc_operations start_ops = {
1550 .start = start,
1551 .post_start = post_start
1552};
1553
aa460476 1554int lxc_start(const char *name, char *const argv[], struct lxc_handler *handler,
507cee36 1555 const char *lxcpath, bool backgrounded)
ee70bf78
CLG
1556{
1557 struct start_args start_arg = {
1558 .argv = argv,
1559 };
1560
aa460476 1561 return __lxc_start(name, handler, &start_ops, &start_arg, lxcpath, backgrounded);
ee70bf78 1562}
28272964
CB
1563
1564static void lxc_destroy_container_on_signal(struct lxc_handler *handler,
1565 const char *name)
1566{
1567 char destroy[MAXPATHLEN];
1568 bool bret = true;
1569 int ret = 0;
f01f7975 1570 struct lxc_container *c;
df31363a 1571 if (handler->conf->rootfs.path && handler->conf->rootfs.mount) {
790255cf 1572 bret = do_destroy_container(handler);
28272964 1573 if (!bret) {
408da065 1574 ERROR("Error destroying rootfs for container \"%s\".", name);
28272964
CB
1575 return;
1576 }
1577 }
408da065 1578 INFO("Destroyed rootfs for container \"%s\".", name);
28272964
CB
1579
1580 ret = snprintf(destroy, MAXPATHLEN, "%s/%s", handler->lxcpath, name);
1581 if (ret < 0 || ret >= MAXPATHLEN) {
408da065 1582 ERROR("Error destroying directory for container \"%s\".", name);
28272964
CB
1583 return;
1584 }
1585
f01f7975
CB
1586 c = lxc_container_new(name, handler->lxcpath);
1587 if (c) {
1588 if (container_disk_lock(c)) {
408da065 1589 INFO("Could not update lxc_snapshots file.");
f01f7975
CB
1590 lxc_container_put(c);
1591 } else {
1592 mod_all_rdeps(c, false);
1593 container_disk_unlock(c);
1594 lxc_container_put(c);
1595 }
1596 }
1597
d0fbc7ba 1598 if (!handler->am_root)
c9b7c33e
CB
1599 ret = userns_exec_1(handler->conf, lxc_rmdir_onedev_wrapper,
1600 destroy, "lxc_rmdir_onedev_wrapper");
28272964
CB
1601 else
1602 ret = lxc_rmdir_onedev(destroy, NULL);
1603
1604 if (ret < 0) {
408da065 1605 ERROR("Error destroying directory for container \"%s\".", name);
28272964
CB
1606 return;
1607 }
408da065 1608 INFO("Destroyed directory for container \"%s\".", name);
28272964
CB
1609}
1610
1611static int lxc_rmdir_onedev_wrapper(void *data)
1612{
1613 char *arg = (char *) data;
1614 return lxc_rmdir_onedev(arg, NULL);
1615}
1616
790255cf 1617static bool do_destroy_container(struct lxc_handler *handler) {
d0fbc7ba 1618 if (!handler->am_root) {
790255cf
CB
1619 if (userns_exec_1(handler->conf, storage_destroy_wrapper,
1620 handler->conf, "storage_destroy_wrapper") < 0)
d028235d 1621 return false;
10bc1861 1622
d028235d
SG
1623 return true;
1624 }
10bc1861 1625
790255cf 1626 return storage_destroy(handler->conf);
28272964 1627}