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