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