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