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