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