]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/start.c
lxc-oracle: export upstart environment variable for maygetty
[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>
0ad19a3f 8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
250b1eec 21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0ad19a3f 22 */
23
f549edcc
GK
24#include "config.h"
25
0ad19a3f 26#include <stdio.h>
0ad19a3f 27#include <string.h>
28#include <stdlib.h>
29#include <dirent.h>
30#include <errno.h>
31#include <unistd.h>
32#include <signal.h>
b0a33c1e 33#include <fcntl.h>
c476bdce 34#include <grp.h>
37515ebd 35#include <poll.h>
0ad19a3f 36#include <sys/param.h>
37#include <sys/file.h>
f4d507d5 38#include <sys/mount.h>
b4f8660e 39#include <sys/stat.h>
0ad19a3f 40#include <sys/types.h>
8173e600 41#include <sys/socket.h>
0ad19a3f 42#include <sys/prctl.h>
ddceb1f9 43#include <sys/types.h>
0ad19a3f 44#include <sys/wait.h>
b0a33c1e 45#include <sys/un.h>
8173e600 46#include <sys/syscall.h>
ff218c25 47
495d2046
SG
48#if HAVE_SYS_CAPABILITY_H
49#include <sys/capability.h>
50#endif
51
656994bb
MH
52#if !HAVE_DECL_PR_CAPBSET_DROP
53#define PR_CAPBSET_DROP 24
54#endif
55
63376d7d
DL
56#include "start.h"
57#include "conf.h"
58#include "log.h"
563f2f2c 59#include "cgroup.h"
e2bcd7db 60#include "error.h"
b0a33c1e 61#include "af_unix.h"
62#include "mainloop.h"
63376d7d 63#include "utils.h"
565c2d76 64#include "lxcutmp.h"
63376d7d 65#include "monitor.h"
96fa1ff0 66#include "commands.h"
63376d7d 67#include "console.h"
3c22086f 68#include "sync.h"
f549edcc 69#include "namespace.h"
0d0527a9 70#include "lxcseccomp.h"
8173e600 71#include "caps.h"
fe4de9a6 72#include "lsm/lsm.h"
36eb9bde
CLG
73
74lxc_log_define(lxc_start, lxc);
75
9f30a190
MM
76const struct ns_info ns_info[LXC_NS_MAX] = {
77 [LXC_NS_MNT] = {"mnt", CLONE_NEWNS},
78 [LXC_NS_PID] = {"pid", CLONE_NEWPID},
79 [LXC_NS_UTS] = {"uts", CLONE_NEWUTS},
80 [LXC_NS_IPC] = {"ipc", CLONE_NEWIPC},
81 [LXC_NS_USER] = {"user", CLONE_NEWUSER},
82 [LXC_NS_NET] = {"net", CLONE_NEWNET}
83};
84
c8154066
SH
85static void print_top_failing_dir(const char *path)
86{
87 size_t len = strlen(path);
88 char *copy = alloca(len+1), *p, *e, saved;
89 strcpy(copy, path);
90
91 p = copy;
92 e = copy + len;
93 while (p < e) {
94 while (p < e && *p == '/') p++;
95 while (p < e && *p != '/') p++;
c8154066
SH
96 saved = *p;
97 *p = '\0';
98 if (access(copy, X_OK)) {
99 SYSERROR("could not access %s. Please grant it 'x' " \
100 "access, or add an ACL for the container root.",
101 copy);
102 return;
103 }
104 *p = saved;
105 }
106}
107
9f30a190
MM
108static void close_ns(int ns_fd[LXC_NS_MAX]) {
109 int i;
110
9f30a190
MM
111 for (i = 0; i < LXC_NS_MAX; i++) {
112 if (ns_fd[i] > -1) {
113 close(ns_fd[i]);
114 ns_fd[i] = -1;
115 }
116 }
9f30a190
MM
117}
118
119static int preserve_ns(int ns_fd[LXC_NS_MAX], int clone_flags) {
120 int i, saved_errno;
121 char path[MAXPATHLEN];
122
9f30a190
MM
123 for (i = 0; i < LXC_NS_MAX; i++)
124 ns_fd[i] = -1;
125
cd43d2d1
SH
126 if (access("/proc/self/ns", X_OK)) {
127 WARN("Kernel does not support attach; preserve_ns ignored");
128 return 0;
129 }
130
9f30a190
MM
131 for (i = 0; i < LXC_NS_MAX; i++) {
132 if ((clone_flags & ns_info[i].clone_flag) == 0)
133 continue;
134 snprintf(path, MAXPATHLEN, "/proc/self/ns/%s", ns_info[i].proc_name);
9f30a190 135 ns_fd[i] = open(path, O_RDONLY | O_CLOEXEC);
9f30a190
MM
136 if (ns_fd[i] < 0)
137 goto error;
138 }
139
140 return 0;
141
142error:
143 saved_errno = errno;
144 close_ns(ns_fd);
145 errno = saved_errno;
146 SYSERROR("failed to open '%s'", path);
147 return -1;
148}
149
150static int attach_ns(const int ns_fd[LXC_NS_MAX]) {
151 int i;
152
153 for (i = 0; i < LXC_NS_MAX; i++) {
154 if (ns_fd[i] < 0)
155 continue;
156
157 if (setns(ns_fd[i], 0) != 0)
158 goto error;
159 }
160 return 0;
161
162error:
163 SYSERROR("failed to set namespace '%s'", ns_info[i].proc_name);
164 return -1;
165}
166
80090207
CLG
167static int match_fd(int fd)
168{
169 return (fd == 0 || fd == 1 || fd == 2);
170}
171
b119f362 172int lxc_check_inherited(struct lxc_conf *conf, int fd_to_ignore)
80090207
CLG
173{
174 struct dirent dirent, *direntp;
175 int fd, fddir;
176 DIR *dir;
80090207 177
b119f362 178restart:
80090207
CLG
179 dir = opendir("/proc/self/fd");
180 if (!dir) {
181 WARN("failed to open directory: %m");
182 return -1;
183 }
184
185 fddir = dirfd(dir);
186
187 while (!readdir_r(dir, &dirent, &direntp)) {
80090207
CLG
188 if (!direntp)
189 break;
190
191 if (!strcmp(direntp->d_name, "."))
192 continue;
193
194 if (!strcmp(direntp->d_name, ".."))
195 continue;
196
197 fd = atoi(direntp->d_name);
198
f2faa8fa 199 if (fd == fddir || fd == lxc_log_fd || fd == fd_to_ignore)
80090207
CLG
200 continue;
201
202 if (match_fd(fd))
203 continue;
80090207 204
b119f362
SH
205 if (conf->close_all_fds) {
206 close(fd);
207 closedir(dir);
208 INFO("closed inherited fd %d", fd);
209 goto restart;
210 }
92c7f629 211 WARN("inherited fd %d", fd);
80090207
CLG
212 }
213
92c7f629
GK
214 closedir(dir); /* cannot fail */
215 return 0;
80090207
CLG
216}
217
83ee7875 218static int setup_signal_fd(sigset_t *oldmask)
b0a33c1e 219{
220 sigset_t mask;
221 int fd;
222
f3304a29
FW
223 /* Block everything except serious error signals */
224 if (sigfillset(&mask) ||
225 sigdelset(&mask, SIGILL) ||
226 sigdelset(&mask, SIGSEGV) ||
227 sigdelset(&mask, SIGBUS) ||
b5159817 228 sigdelset(&mask, SIGWINCH) ||
f3304a29
FW
229 sigprocmask(SIG_BLOCK, &mask, oldmask)) {
230 SYSERROR("failed to set signal mask");
b0a33c1e 231 return -1;
232 }
233
234 fd = signalfd(-1, &mask, 0);
235 if (fd < 0) {
36eb9bde 236 SYSERROR("failed to create the signal fd");
b0a33c1e 237 return -1;
238 }
239
240 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
36eb9bde 241 SYSERROR("failed to set sigfd to close-on-exec");
b0a33c1e 242 close(fd);
243 return -1;
244 }
245
1ac470c0
DL
246 DEBUG("sigchild handler set");
247
b0a33c1e 248 return fd;
249}
250
84c92abd 251static int signal_handler(int fd, uint32_t events, void *data,
b0a33c1e 252 struct lxc_epoll_descr *descr)
253{
15cd25fd 254 struct signalfd_siginfo siginfo;
80507ee8 255 siginfo_t info;
15cd25fd 256 int ret;
82d89dce 257 pid_t *pid = data;
80507ee8 258 bool init_died = false;
15cd25fd
DL
259
260 ret = read(fd, &siginfo, sizeof(siginfo));
261 if (ret < 0) {
f3304a29 262 ERROR("failed to read signal info");
15cd25fd
DL
263 return -1;
264 }
265
266 if (ret != sizeof(siginfo)) {
267 ERROR("unexpected siginfo size");
268 return -1;
269 }
270
80507ee8
SH
271 // check whether init is running
272 info.si_pid = 0;
273 ret = waitid(P_PID, *pid, &info, WEXITED | WNOWAIT | WNOHANG);
274 if (ret == 0 && info.si_pid == *pid) {
275 init_died = true;
276 }
277
f3304a29
FW
278 if (siginfo.ssi_signo != SIGCHLD) {
279 kill(*pid, siginfo.ssi_signo);
280 INFO("forwarded signal %d to pid %d", siginfo.ssi_signo, *pid);
80507ee8 281 return init_died ? 1 : 0;
f3304a29
FW
282 }
283
15cd25fd
DL
284 if (siginfo.ssi_code == CLD_STOPPED ||
285 siginfo.ssi_code == CLD_CONTINUED) {
286 INFO("container init process was stopped/continued");
80507ee8 287 return init_died ? 1 : 0;
15cd25fd 288 }
1ac470c0 289
82d89dce
DL
290 /* more robustness, protect ourself from a SIGCHLD sent
291 * by a process different from the container init
292 */
293 if (siginfo.ssi_pid != *pid) {
294 WARN("invalid pid for SIGCHLD");
80507ee8 295 return init_died ? 1 : 0;
82d89dce
DL
296 }
297
15cd25fd 298 DEBUG("container init process exited");
b0a33c1e 299 return 1;
300}
301
74a3920a 302static int lxc_set_state(const char *name, struct lxc_handler *handler, lxc_state_t state)
66aeffc7
DL
303{
304 handler->state = state;
9123e471 305 lxc_monitor_send_state(name, state, handler->lxcpath);
66aeffc7
DL
306 return 0;
307}
308
74a3920a 309static int lxc_poll(const char *name, struct lxc_handler *handler)
b0a33c1e 310{
ca5f7926
DL
311 int sigfd = handler->sigfd;
312 int pid = handler->pid;
b0a33c1e 313 struct lxc_epoll_descr descr;
314
a9e61274 315 if (lxc_mainloop_open(&descr)) {
36eb9bde 316 ERROR("failed to create mainloop");
50c8bf05 317 goto out_sigfd;
b0a33c1e 318 }
319
83ee7875 320 if (lxc_mainloop_add_handler(&descr, sigfd, signal_handler, &pid)) {
36eb9bde 321 ERROR("failed to add handler for the signal");
b0a33c1e 322 goto out_mainloop_open;
323 }
324
63376d7d
DL
325 if (lxc_console_mainloop_add(&descr, handler)) {
326 ERROR("failed to add console handler to mainloop");
327 goto out_mainloop_open;
328 }
329
ef6e34ee 330 if (lxc_cmd_mainloop_add(name, &descr, handler)) {
563f2f2c 331 ERROR("failed to add command handler to mainloop");
96fa1ff0 332 goto out_mainloop_open;
563f2f2c
DL
333 }
334
828695d9 335 if (handler->conf->need_utmp_watch) {
495d2046 336 #if HAVE_SYS_CAPABILITY_H
828695d9
SH
337 if (lxc_utmp_mainloop_add(&descr, handler)) {
338 ERROR("failed to add utmp handler to mainloop");
339 goto out_mainloop_open;
340 }
495d2046 341 #else
959aee9c 342 DEBUG("not starting utmp handler as cap_sys_boot cannot be dropped without capabilities support");
495d2046 343 #endif
563f2f2c 344 }
b0a33c1e 345
e51d4895 346 return lxc_mainloop(&descr, -1);
b0a33c1e 347
348out_mainloop_open:
349 lxc_mainloop_close(&descr);
b0a33c1e 350out_sigfd:
351 close(sigfd);
c3e13372 352 return -1;
b0a33c1e 353}
354
13f5be62 355struct lxc_handler *lxc_init(const char *name, struct lxc_conf *conf, const char *lxcpath)
59eb99ba 356{
3a0f472d
DL
357 struct lxc_handler *handler;
358
359 handler = malloc(sizeof(*handler));
360 if (!handler)
361 return NULL;
59eb99ba
DL
362
363 memset(handler, 0, sizeof(*handler));
364
fae349da 365 handler->conf = conf;
9123e471 366 handler->lxcpath = lxcpath;
5c068da9 367 handler->pinfd = -1;
fae349da 368
fe4de9a6
DE
369 lsm_init();
370
3bdf52d7
DL
371 handler->name = strdup(name);
372 if (!handler->name) {
373 ERROR("failed to allocate memory");
374 goto out_free;
375 }
376
ef6e34ee 377 if (lxc_cmd_init(name, handler, lxcpath))
d2e30e99
DE
378 goto out_free_name;
379
8f2c3a70
SH
380 if (lxc_read_seccomp_config(conf) != 0) {
381 ERROR("failed loading seccomp policy");
d2e30e99 382 goto out_close_maincmd_fd;
8f2c3a70
SH
383 }
384
051151de 385 /* Begin by setting the state to STARTING */
25c2aca5 386 if (lxc_set_state(name, handler, STARTING)) {
59eb99ba 387 ERROR("failed to set state '%s'", lxc_state2str(STARTING));
051151de 388 goto out_close_maincmd_fd;
0ad19a3f 389 }
390
f7bee6c6
MW
391 /* Start of environment variable setup for hooks */
392 if (setenv("LXC_NAME", name, 1)) {
393 SYSERROR("failed to set environment variable for container name");
394 }
395 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
396 SYSERROR("failed to set environment variable for config path");
397 }
398 if (setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
399 SYSERROR("failed to set environment variable for rootfs mount");
400 }
401 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
402 SYSERROR("failed to set environment variable for rootfs mount");
403 }
404 if (conf->console.path && setenv("LXC_CONSOLE", conf->console.path, 1)) {
405 SYSERROR("failed to set environment variable for console path");
406 }
407 if (conf->console.log_path && setenv("LXC_CONSOLE_LOGPATH", conf->console.log_path, 1)) {
408 SYSERROR("failed to set environment variable for console log");
409 }
410 /* End of environment variable setup for hooks */
411
283678ed 412 if (run_lxc_hooks(name, "pre-start", conf, handler->lxcpath, NULL)) {
773fb9ca
SH
413 ERROR("failed to run pre-start hooks for container '%s'.", name);
414 goto out_aborting;
415 }
26ddeedd 416
fae349da 417 if (lxc_create_tty(name, conf)) {
36eb9bde 418 ERROR("failed to create the ttys");
59eb99ba 419 goto out_aborting;
b0a33c1e 420 }
421
422 /* the signal fd has to be created before forking otherwise
423 * if the child process exits before we setup the signal fd,
424 * the event will be lost and the command will be stuck */
83ee7875 425 handler->sigfd = setup_signal_fd(&handler->oldmask);
59eb99ba 426 if (handler->sigfd < 0) {
36eb9bde 427 ERROR("failed to set sigchild fd handler");
b5159817
DE
428 goto out_delete_tty;
429 }
430
431 /* do this after setting up signals since it might unblock SIGWINCH */
432 if (lxc_console_create(conf)) {
433 ERROR("failed to create console");
434 goto out_restore_sigmask;
b0a33c1e 435 }
436
c4d10a05
SH
437 if (ttys_shift_ids(conf) < 0) {
438 ERROR("Failed to shift tty into container");
439 goto out_restore_sigmask;
440 }
441
c3e13372 442 INFO("'%s' is initialized", name);
3a0f472d 443 return handler;
59eb99ba 444
b5159817
DE
445out_restore_sigmask:
446 sigprocmask(SIG_SETMASK, &handler->oldmask, NULL);
59eb99ba 447out_delete_tty:
fae349da 448 lxc_delete_tty(&conf->tty_info);
59eb99ba 449out_aborting:
25c2aca5 450 lxc_set_state(name, handler, ABORTING);
d2e30e99
DE
451out_close_maincmd_fd:
452 close(conf->maincmd_fd);
453 conf->maincmd_fd = -1;
3bdf52d7
DL
454out_free_name:
455 free(handler->name);
456 handler->name = NULL;
3a0f472d
DL
457out_free:
458 free(handler);
c3e13372 459 return NULL;
59eb99ba
DL
460}
461
ae5c8b8e 462static void lxc_fini(const char *name, struct lxc_handler *handler)
59eb99ba
DL
463{
464 /* The STOPPING state is there for future cleanup code
465 * which can take awhile
466 */
25c2aca5
MN
467 lxc_set_state(name, handler, STOPPING);
468 lxc_set_state(name, handler, STOPPED);
59eb99ba 469
283678ed 470 if (run_lxc_hooks(name, "post-stop", handler->conf, handler->lxcpath, NULL))
773fb9ca 471 ERROR("failed to run post-stop hooks for container '%s'.", name);
26ddeedd 472
83ee7875 473 /* reset mask set by setup_signal_fd */
8f64a3f6
MN
474 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL))
475 WARN("failed to restore sigprocmask");
476
b5159817 477 lxc_console_delete(&handler->conf->console);
b2431939 478 lxc_delete_tty(&handler->conf->tty_info);
d2e30e99
DE
479 close(handler->conf->maincmd_fd);
480 handler->conf->maincmd_fd = -1;
3bdf52d7 481 free(handler->name);
d4ef7c50 482 cgroup_destroy(handler);
b2431939 483 free(handler);
59eb99ba
DL
484}
485
74a3920a 486static void lxc_abort(const char *name, struct lxc_handler *handler)
59eb99ba 487{
73e608b2
SH
488 int ret, status;
489
25c2aca5 490 lxc_set_state(name, handler, ABORTING);
7d9fb3e9
DL
491 if (handler->pid > 0)
492 kill(handler->pid, SIGKILL);
73e608b2 493 while ((ret = waitpid(-1, &status, 0)) > 0) ;
59eb99ba
DL
494}
495
828695d9
SH
496#include <sys/reboot.h>
497#include <linux/reboot.h>
498
e2fa1520
SH
499/*
500 * reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL
501 * in a child pid namespace if container reboot support exists.
502 * Otherwise, it will either succeed or return -EPERM.
503 */
504static int container_reboot_supported(void *arg)
828695d9 505{
e2fa1520 506 int *cmd = arg;
828695d9 507 int ret;
828695d9 508
e2fa1520
SH
509 ret = reboot(*cmd);
510 if (ret == -1 && errno == EINVAL)
511 return 1;
512 return 0;
513}
514
b60ed720 515static int must_drop_cap_sys_boot(struct lxc_conf *conf)
e2fa1520 516{
025ed0f3 517 FILE *f;
b60ed720 518 int ret, cmd, v, flags;
e2fa1520 519 long stack_size = 4096;
7f145a6d 520 void *stack = alloca(stack_size);
e2fa1520
SH
521 int status;
522 pid_t pid;
523
025ed0f3 524 f = fopen("/proc/sys/kernel/ctrl-alt-del", "r");
e2fa1520
SH
525 if (!f) {
526 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
828695d9 527 return 1;
e2fa1520 528 }
828695d9
SH
529
530 ret = fscanf(f, "%d", &v);
531 fclose(f);
e2fa1520
SH
532 if (ret != 1) {
533 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del");
828695d9 534 return 1;
e2fa1520
SH
535 }
536 cmd = v ? LINUX_REBOOT_CMD_CAD_ON : LINUX_REBOOT_CMD_CAD_OFF;
537
b60ed720
SH
538 flags = CLONE_NEWPID | SIGCHLD;
539 if (!lxc_list_empty(&conf->id_map))
540 flags |= CLONE_NEWUSER;
541
7f145a6d 542#ifdef __ia64__
959aee9c 543 pid = __clone2(container_reboot_supported, stack, stack_size, flags, &cmd);
7f145a6d 544#else
959aee9c
SG
545 stack += stack_size;
546 pid = clone(container_reboot_supported, stack, flags, &cmd);
7f145a6d 547#endif
959aee9c
SG
548 if (pid < 0) {
549 SYSERROR("failed to clone");
550 return -1;
551 }
552 if (wait(&status) < 0) {
553 SYSERROR("unexpected wait error: %m");
554 return -1;
555 }
e2fa1520
SH
556
557 if (WEXITSTATUS(status) != 1)
828695d9 558 return 1;
e2fa1520 559
828695d9
SH
560 return 0;
561}
562
658979c5
SH
563/*
564 * netpipe is used in the unprivileged case to transfer the ifindexes
565 * from parent to child
566 */
567static int netpipe = -1;
568
569static inline int count_veths(struct lxc_list *network)
570{
571 struct lxc_list *iterator;
572 struct lxc_netdev *netdev;
573 int count = 0;
574
575 lxc_list_for_each(iterator, network) {
576 netdev = iterator->elem;
577 if (netdev->type != LXC_NET_VETH)
578 continue;
579 count++;
580 }
581 return count;
582}
583
584static int read_unpriv_netifindex(struct lxc_list *network)
585{
586 struct lxc_list *iterator;
587 struct lxc_netdev *netdev;
588
589 if (netpipe == -1)
590 return 0;
591 lxc_list_for_each(iterator, network) {
592 netdev = iterator->elem;
593 if (netdev->type != LXC_NET_VETH)
594 continue;
595 if (!(netdev->name = malloc(IFNAMSIZ))) {
596 ERROR("Out of memory");
597 close(netpipe);
598 return -1;
599 }
600 if (read(netpipe, netdev->name, IFNAMSIZ) != IFNAMSIZ) {
601 close(netpipe);
602 return -1;
603 }
604 }
605 close(netpipe);
606 return 0;
607}
608
ffe1e01a 609static int do_start(void *data)
50e98013 610{
23c53af9 611 struct lxc_handler *handler = data;
e0b6898a 612 const char *lsm_label = NULL;
50e98013
DL
613
614 if (sigprocmask(SIG_SETMASK, &handler->oldmask, NULL)) {
615 SYSERROR("failed to set sigprocmask");
9d7f9e52 616 return -1;
50e98013
DL
617 }
618
743ecd2e
DL
619 /* This prctl must be before the synchro, so if the parent
620 * dies before we set the parent death signal, we will detect
621 * its death with the synchro right after, otherwise we have
622 * a window where the parent can exit before we set the pdeath
623 * signal leading to a unsupervized container.
624 */
625 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
626 SYSERROR("failed to set pdeath signal");
627 return -1;
628 }
629
3c22086f 630 lxc_sync_fini_parent(handler);
50e98013 631
2b0e17e4 632 /* don't leak the pinfd to the container */
025ed0f3 633 if (handler->pinfd >= 0) {
0d03360a 634 close(handler->pinfd);
025ed0f3 635 }
2b0e17e4 636
3c22086f
CLG
637 /* Tell the parent task it can begin to configure the
638 * container and wait for it to finish
639 */
640 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CONFIGURE))
9d7f9e52 641 return -1;
50e98013 642
658979c5
SH
643 if (read_unpriv_netifindex(&handler->conf->network) < 0)
644 goto out_warn_father;
645
f6d3e3e4
SH
646 /*
647 * if we are in a new user namespace, become root there to have
648 * privilege over our namespace
649 */
650 if (!lxc_list_empty(&handler->conf->id_map)) {
651 NOTICE("switching to gid/uid 0 in new user namespace");
652 if (setgid(0)) {
653 SYSERROR("setgid");
654 goto out_warn_father;
655 }
656 if (setuid(0)) {
657 SYSERROR("setuid");
658 goto out_warn_father;
659 }
c476bdce
SH
660 if (setgroups(0, NULL)) {
661 SYSERROR("setgroups");
662 goto out_warn_father;
663 }
f6d3e3e4
SH
664 }
665
99b71824 666 if (access(handler->lxcpath, X_OK)) {
c8154066
SH
667 print_top_failing_dir(handler->lxcpath);
668 goto out_warn_father;
669 }
670
495d2046 671 #if HAVE_SYS_CAPABILITY_H
69182a31 672 if (handler->conf->need_utmp_watch) {
828695d9
SH
673 if (prctl(PR_CAPBSET_DROP, CAP_SYS_BOOT, 0, 0, 0)) {
674 SYSERROR("failed to remove CAP_SYS_BOOT capability");
c4ea60df 675 goto out_warn_father;
828695d9 676 }
959aee9c 677 DEBUG("Dropped cap_sys_boot");
e2fa1520 678 }
495d2046 679 #endif
e2fa1520
SH
680
681 /* Setup the container, ip, names, utsname, ... */
d4ef7c50 682 if (lxc_setup(handler)) {
e2fa1520
SH
683 ERROR("failed to setup the container");
684 goto out_warn_father;
685 }
50e98013 686
544a48a0
SH
687 /* ask father to setup cgroups and wait for him to finish */
688 if (lxc_sync_barrier_parent(handler, LXC_SYNC_CGROUP))
689 return -1;
690
72863294 691 /* Set the label to change to when we exec(2) the container's init */
e0b6898a
DE
692 if (!strcmp(lsm_name(), "AppArmor"))
693 lsm_label = handler->conf->lsm_aa_profile;
694 else if (!strcmp(lsm_name(), "SELinux"))
695 lsm_label = handler->conf->lsm_se_context;
696 if (lsm_process_label_set(lsm_label, 1, 1) < 0)
e075f5d9 697 goto out_warn_father;
5112cd70 698
0d9acb99
DE
699 /* Some init's such as busybox will set sane tty settings on stdin,
700 * stdout, stderr which it thinks is the console. We already set them
701 * the way we wanted on the real terminal, and we want init to do its
702 * setup on its console ie. the pty allocated in lxc_console_create()
703 * so make sure that that pty is stdin,stdout,stderr.
704 */
705 if (lxc_console_set_stdfds(handler) < 0)
706 goto out_warn_father;
707
5112cd70
SH
708 /* If we mounted a temporary proc, then unmount it now */
709 tmp_proc_unmount(handler->conf);
e075f5d9 710
8f2c3a70
SH
711 if (lxc_seccomp_load(handler->conf) != 0)
712 goto out_warn_father;
713
283678ed 714 if (run_lxc_hooks(handler->name, "start", handler->conf, handler->lxcpath, NULL)) {
773fb9ca
SH
715 ERROR("failed to run start hooks for container '%s'.", handler->name);
716 goto out_warn_father;
717 }
fc25b815 718
f7bee6c6
MW
719 /* The clearenv() and putenv() calls have been moved here
720 * to allow us to use enviroment variables passed to the various
721 * hooks, such as the start hook above. Not all of the
722 * variables like CONFIG_PATH or ROOTFS are valid in this
723 * context but others are. */
724 if (clearenv()) {
725 SYSERROR("failed to clear environment");
726 /* don't error out though */
727 }
728
729 if (putenv("container=lxc")) {
730 SYSERROR("failed to set environment variable");
c4ea60df 731 goto out_warn_father;
f7bee6c6
MW
732 }
733
773fb9ca 734 close(handler->sigfd);
26ddeedd 735
e6126dbe
MN
736 /* after this call, we are in error because this
737 * ops should not return as it execs */
c4ea60df 738 handler->ops->start(handler, handler->data);
50e98013
DL
739
740out_warn_father:
544a48a0
SH
741 /* we want the parent to know something went wrong, so any
742 * value other than what it expects is ok. */
3c22086f 743 lxc_sync_wake_parent(handler, LXC_SYNC_POST_CONFIGURE);
50e98013
DL
744 return -1;
745}
746
74a3920a 747static int save_phys_nics(struct lxc_conf *conf)
7b35f3d6
SH
748{
749 struct lxc_list *iterator;
750
751 lxc_list_for_each(iterator, &conf->network) {
752 struct lxc_netdev *netdev = iterator->elem;
753
754 if (netdev->type != LXC_NET_PHYS)
755 continue;
756 conf->saved_nics = realloc(conf->saved_nics,
757 (conf->num_savednics+1)*sizeof(struct saved_nic));
758 if (!conf->saved_nics) {
759 SYSERROR("failed to allocate memory");
760 return -1;
761 }
762 conf->saved_nics[conf->num_savednics].ifindex = netdev->ifindex;
763 conf->saved_nics[conf->num_savednics].orig_name = strdup(netdev->link);
764 if (!conf->saved_nics[conf->num_savednics].orig_name) {
765 SYSERROR("failed to allocate memory");
766 return -1;
767 }
959aee9c 768 INFO("stored saved_nic #%d idx %d name %s", conf->num_savednics,
7b35f3d6
SH
769 conf->saved_nics[conf->num_savednics].ifindex,
770 conf->saved_nics[conf->num_savednics].orig_name);
771 conf->num_savednics++;
772 }
773
774 return 0;
775}
776
74a3920a 777static int lxc_spawn(struct lxc_handler *handler)
59eb99ba 778{
b98f7d6e 779 int failed_before_rename = 0;
ffe1e01a 780 const char *name = handler->name;
7e4dfe0b 781 bool cgroups_connected = false;
9f30a190
MM
782 int saved_ns_fd[LXC_NS_MAX];
783 int preserve_mask = 0, i;
658979c5 784 int netpipepair[2], nveths;
9f30a190 785
2f2623ec
SH
786 netpipe = -1;
787
9f30a190 788 for (i = 0; i < LXC_NS_MAX; i++)
6c544cb3 789 if (handler->conf->inherit_ns_fd[i] != -1)
9f30a190 790 preserve_mask |= ns_info[i].clone_flag;
50e98013 791
3c22086f 792 if (lxc_sync_init(handler))
9d7f9e52 793 return -1;
0ad19a3f 794
6c544cb3 795 handler->clone_flags = CLONE_NEWPID|CLONE_NEWNS;
f6d3e3e4
SH
796 if (!lxc_list_empty(&handler->conf->id_map)) {
797 INFO("Cloning a new user namespace");
798 handler->clone_flags |= CLONE_NEWUSER;
799 }
0ad19a3f 800
9f30a190 801 if (handler->conf->inherit_ns_fd[LXC_NS_NET] == -1) {
26b797f3 802 if (!lxc_requests_empty_network(handler))
9f30a190
MM
803 handler->clone_flags |= CLONE_NEWNET;
804
26b797f3
SH
805 if (!lxc_list_empty(&handler->conf->network)) {
806
9f30a190
MM
807 /* Find gateway addresses from the link device, which is
808 * no longer accessible inside the container. Do this
809 * before creating network interfaces, since goto
810 * out_delete_net does not work before lxc_clone. */
811 if (lxc_find_gateway_addresses(handler)) {
812 ERROR("failed to find gateway addresses");
813 lxc_sync_fini(handler);
814 return -1;
815 }
816
817 /* that should be done before the clone because we will
818 * fill the netdev index and use them in the child
819 */
820 if (lxc_create_network(handler)) {
38521a3b 821 ERROR("failed to create the network");
9f30a190
MM
822 lxc_sync_fini(handler);
823 return -1;
824 }
19a26f82
MK
825 }
826
9f30a190
MM
827 if (save_phys_nics(handler->conf)) {
828 ERROR("failed to save physical nic info");
829 goto out_abort;
82d5ae15 830 }
9f30a190
MM
831 } else {
832 INFO("Inheriting a net namespace");
82d5ae15
DL
833 }
834
3c93577b
MM
835 if (handler->conf->inherit_ns_fd[LXC_NS_IPC] == -1) {
836 handler->clone_flags |= CLONE_NEWIPC;
837 } else {
838 INFO("Inheriting an IPC namespace");
7b35f3d6
SH
839 }
840
6c544cb3
MM
841 if (handler->conf->inherit_ns_fd[LXC_NS_UTS] == -1) {
842 handler->clone_flags |= CLONE_NEWUTS;
843 } else {
844 INFO("Inheriting a UTS namespace");
845 }
846
7b35f3d6 847
d4ef7c50
SH
848 if (!cgroup_init(handler)) {
849 ERROR("failed initializing cgroup support");
33ad9f1a
CS
850 goto out_delete_net;
851 }
852
7e4dfe0b
SH
853 cgroups_connected = true;
854
d4ef7c50
SH
855 if (!cgroup_create(handler)) {
856 ERROR("failed creating cgroups");
47d8fb3b
CS
857 goto out_delete_net;
858 }
859
0c547523
SH
860 /*
861 * if the rootfs is not a blockdev, prevent the container from
862 * marking it readonly.
5e32a990
ÇO
863 *
864 * if the container is unprivileged then skip rootfs pinning
0c547523 865 */
5e32a990
ÇO
866 if (lxc_list_empty(&handler->conf->id_map)) {
867 handler->pinfd = pin_rootfs(handler->conf->rootfs.path);
868 if (handler->pinfd == -1)
869 INFO("failed to pin the container's rootfs");
870 }
0c547523 871
cd43d2d1
SH
872 if (preserve_ns(saved_ns_fd, preserve_mask) < 0)
873 goto out_delete_net;
874 if (attach_ns(handler->conf->inherit_ns_fd) < 0)
875 goto out_delete_net;
9f30a190 876
658979c5
SH
877 if (am_unpriv() && (nveths = count_veths(&handler->conf->network))) {
878 if (pipe(netpipepair) < 0) {
879 SYSERROR("Error creating pipe");
880 goto out_delete_net;
881 }
882 /* store netpipe in the global var for do_start's use */
883 netpipe = netpipepair[0];
884 }
885
0ad19a3f 886 /* Create a process in a new set of namespaces */
d5088cf2 887 handler->pid = lxc_clone(do_start, handler, handler->clone_flags);
59eb99ba 888 if (handler->pid < 0) {
36eb9bde 889 SYSERROR("failed to fork into a new namespace");
7fef7a06 890 goto out_delete_net;
0ad19a3f 891 }
892
cd43d2d1
SH
893 if (attach_ns(saved_ns_fd))
894 WARN("failed to restore saved namespaces");
9f30a190 895
3c22086f
CLG
896 lxc_sync_fini_child(handler);
897
898 if (lxc_sync_wait_child(handler, LXC_SYNC_CONFIGURE))
99a6af52 899 failed_before_rename = 1;
0ad19a3f 900
d4ef7c50
SH
901 if (!cgroup_create_legacy(handler)) {
902 ERROR("failed to setup the legacy cgroups for %s", name);
ae5c8b8e 903 goto out_delete_net;
33ad9f1a 904 }
9daf6f5d
SH
905 if (!cgroup_setup_limits(handler, false)) {
906 ERROR("failed to setup the cgroup limits for '%s'", name);
6031a6e5
DE
907 goto out_delete_net;
908 }
909
d4ef7c50 910 if (!cgroup_enter(handler))
7fef7a06 911 goto out_delete_net;
218d4250 912
0996e18a
SH
913 if (!cgroup_chown(handler))
914 goto out_delete_net;
915
99a6af52
MN
916 if (failed_before_rename)
917 goto out_delete_net;
918
0ad19a3f 919 /* Create the network configuration */
d5088cf2 920 if (handler->clone_flags & CLONE_NEWNET) {
fae349da 921 if (lxc_assign_network(&handler->conf->network, handler->pid)) {
82d5ae15 922 ERROR("failed to create the configured network");
7fef7a06 923 goto out_delete_net;
82d5ae15 924 }
0ad19a3f 925 }
926
658979c5
SH
927 if (netpipe != -1) {
928 struct lxc_list *iterator;
929 struct lxc_netdev *netdev;
930
931 close(netpipe);
932 lxc_list_for_each(iterator, &handler->conf->network) {
933 netdev = iterator->elem;
934 if (netdev->type != LXC_NET_VETH)
935 continue;
936 if (write(netpipepair[1], netdev->name, IFNAMSIZ) != IFNAMSIZ) {
937 ERROR("Error writing veth name to container");
938 goto out_delete_net;
939 }
940 }
941 close(netpipepair[1]);
942 }
943
f6d3e3e4
SH
944 /* map the container uids - the container became an invalid
945 * userid the moment it was cloned with CLONE_NEWUSER - this
946 * call doesn't change anything immediately, but allows the
947 * container to setuid(0) (0 being mapped to something else on
948 * the host) later to become a valid uid again */
949 if (lxc_map_ids(&handler->conf->id_map, handler->pid)) {
950 ERROR("failed to set up id mapping");
951 goto out_delete_net;
952 }
953
544a48a0
SH
954 /* Tell the child to continue its initialization. we'll get
955 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups
3c22086f
CLG
956 */
957 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CONFIGURE))
544a48a0
SH
958 goto out_delete_net;
959
9daf6f5d 960 if (!cgroup_setup_limits(handler, true)) {
b98f7d6e
SH
961 ERROR("failed to setup the devices cgroup for '%s'", name);
962 goto out_delete_net;
544a48a0
SH
963 }
964
73d28d42 965 cgroup_disconnect();
7e4dfe0b 966 cgroups_connected = false;
73d28d42 967
544a48a0
SH
968 /* Tell the child to complete its initialization and wait for
969 * it to exec or return an error. (the child will never
970 * return LXC_SYNC_POST_CGROUP+1. It will either close the
971 * sync pipe, causing lxc_sync_barrier_child to return
972 * success, or return a different value, causing us to error
973 * out).
974 */
975 if (lxc_sync_barrier_child(handler, LXC_SYNC_POST_CGROUP))
3c22086f 976 return -1;
0ad19a3f 977
cc28d0b0
SH
978 if (detect_shared_rootfs())
979 umount2(handler->conf->rootfs.mount, MNT_DETACH);
980
23c53af9 981 if (handler->ops->post_start(handler, handler->data))
e6126dbe
MN
982 goto out_abort;
983
25c2aca5 984 if (lxc_set_state(name, handler, RUNNING)) {
59eb99ba
DL
985 ERROR("failed to set state to %s",
986 lxc_state2str(RUNNING));
987 goto out_abort;
3f21c114 988 }
22ebac19 989
3c22086f 990 lxc_sync_fini(handler);
0c547523 991
e6126dbe 992 return 0;
1ac470c0 993
7fef7a06 994out_delete_net:
7e4dfe0b
SH
995 if (cgroups_connected)
996 cgroup_disconnect();
d5088cf2 997 if (handler->clone_flags & CLONE_NEWNET)
74a2b586 998 lxc_delete_network(handler);
59eb99ba
DL
999out_abort:
1000 lxc_abort(name, handler);
3c22086f 1001 lxc_sync_fini(handler);
5c068da9
SH
1002 if (handler->pinfd >= 0) {
1003 close(handler->pinfd);
1004 handler->pinfd = -1;
1005 }
1006
b79fcd86 1007 return -1;
59eb99ba 1008}
0ad19a3f 1009
2af6bd1b
SH
1010int get_netns_fd(int pid)
1011{
1012 char path[MAXPATHLEN];
1013 int ret, fd;
1014
1015 ret = snprintf(path, MAXPATHLEN, "/proc/%d/ns/net", pid);
1016 if (ret < 0 || ret >= MAXPATHLEN) {
1017 WARN("Failed to pin netns file for pid %d", pid);
1018 return -1;
1019 }
1020
1021 fd = open(path, O_RDONLY);
1022 if (fd < 0) {
1023 WARN("Failed to pin netns file %s for pid %d: %s",
1024 path, pid, strerror(errno));
1025 return -1;
1026 }
1027 return fd;
1028}
1029
ee70bf78 1030int __lxc_start(const char *name, struct lxc_conf *conf,
13f5be62 1031 struct lxc_operations* ops, void *data, const char *lxcpath)
59eb99ba 1032{
3a0f472d 1033 struct lxc_handler *handler;
e043236e 1034 int err = -1;
59eb99ba 1035 int status;
2af6bd1b 1036 int netnsfd = -1;
80090207 1037
13f5be62 1038 handler = lxc_init(name, conf, lxcpath);
3a0f472d 1039 if (!handler) {
59eb99ba 1040 ERROR("failed to initialize the container");
66aeffc7 1041 return -1;
0ad19a3f 1042 }
ee70bf78
CLG
1043 handler->ops = ops;
1044 handler->data = data;
e6126dbe 1045
b60ed720 1046 if (must_drop_cap_sys_boot(handler->conf)) {
495d2046 1047 #if HAVE_SYS_CAPABILITY_H
959aee9c 1048 DEBUG("Dropping cap_sys_boot");
495d2046 1049 #else
959aee9c 1050 DEBUG("Can't drop cap_sys_boot as capabilities aren't supported");
495d2046 1051 #endif
69182a31 1052 } else {
959aee9c 1053 DEBUG("Not dropping cap_sys_boot or watching utmp");
69182a31
SH
1054 handler->conf->need_utmp_watch = 0;
1055 }
1056
23c53af9 1057 err = lxc_spawn(handler);
59eb99ba 1058 if (err) {
ee70bf78 1059 ERROR("failed to spawn '%s'", name);
74a2b586 1060 goto out_fini_nonet;
0ad19a3f 1061 }
1062
2af6bd1b
SH
1063 netnsfd = get_netns_fd(handler->pid);
1064
3a0f472d 1065 err = lxc_poll(name, handler);
e043236e 1066 if (err) {
59eb99ba 1067 ERROR("mainloop exited with an error");
4b2f98f5
SH
1068 if (netnsfd >= 0)
1069 close(netnsfd);
59eb99ba
DL
1070 goto out_abort;
1071 }
0ad19a3f 1072
3a0f472d 1073 while (waitpid(handler->pid, &status, 0) < 0 && errno == EINTR)
1bc5cc8c 1074 continue;
e043236e 1075
8b004f07
SH
1076 /*
1077 * If the child process exited but was not signaled,
1078 * it didn't call reboot. This should mean it was an
1079 * lxc-execute which simply exited. In any case, treat
1080 * it as a 'halt'
1081 */
1082 if (WIFSIGNALED(status)) {
1083 switch(WTERMSIG(status)) {
1084 case SIGINT: /* halt */
1085 DEBUG("Container halting");
1086 break;
1087 case SIGHUP: /* reboot */
1088 DEBUG("Container rebooting");
1089 handler->conf->reboot = 1;
1090 break;
c2b9bd9e
SH
1091 case SIGSYS: /* seccomp */
1092 DEBUG("Container violated its seccomp policy");
1093 break;
8b004f07 1094 default:
959aee9c 1095 DEBUG("unknown exit status for init: %d", WTERMSIG(status));
8b004f07
SH
1096 break;
1097 }
828695d9
SH
1098 }
1099
2af6bd1b 1100 lxc_rename_phys_nics_on_shutdown(netnsfd, handler->conf);
4b2f98f5
SH
1101 if (netnsfd >= 0)
1102 close(netnsfd);
7b35f3d6 1103
5c068da9
SH
1104 if (handler->pinfd >= 0) {
1105 close(handler->pinfd);
1106 handler->pinfd = -1;
1107 }
1108
3a0f472d 1109 err = lxc_error_set_and_log(handler->pid, status);
9d7f9e52 1110out_fini:
74a2b586
JK
1111 lxc_delete_network(handler);
1112
1113out_fini_nonet:
3a0f472d 1114 lxc_fini(name, handler);
0ad19a3f 1115 return err;
1116
59eb99ba 1117out_abort:
3a0f472d 1118 lxc_abort(name, handler);
9d7f9e52 1119 goto out_fini;
0ad19a3f 1120}
ee70bf78
CLG
1121
1122struct start_args {
1123 char *const *argv;
1124};
1125
1126static int start(struct lxc_handler *handler, void* data)
1127{
1128 struct start_args *arg = data;
1129
1130 NOTICE("exec'ing '%s'", arg->argv[0]);
1131
1132 execvp(arg->argv[0], arg->argv);
1133 SYSERROR("failed to exec %s", arg->argv[0]);
1134 return 0;
1135}
1136
1137static int post_start(struct lxc_handler *handler, void* data)
1138{
1139 struct start_args *arg = data;
1140
1141 NOTICE("'%s' started with pid '%d'", arg->argv[0], handler->pid);
1142 return 0;
1143}
1144
1145static struct lxc_operations start_ops = {
1146 .start = start,
1147 .post_start = post_start
1148};
1149
13f5be62
SH
1150int lxc_start(const char *name, char *const argv[], struct lxc_conf *conf,
1151 const char *lxcpath)
ee70bf78
CLG
1152{
1153 struct start_args start_arg = {
1154 .argv = argv,
1155 };
1156
71a606ee
ÇO
1157 if (lxc_check_inherited(conf, -1))
1158 return -1;
1159
828695d9 1160 conf->need_utmp_watch = 1;
13f5be62 1161 return __lxc_start(name, conf, &start_ops, &start_arg, lxcpath);
ee70bf78 1162}