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