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