chiark / gitweb /
Link against -lcap only where required
[elogind.git] / src / nspawn.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <signal.h>
23 #include <sched.h>
24 #include <unistd.h>
25 #include <sys/types.h>
26 #include <sys/syscall.h>
27 #include <sys/mount.h>
28 #include <sys/wait.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <stdio.h>
32 #include <errno.h>
33 #include <sys/prctl.h>
34 #include <sys/capability.h>
35 #include <getopt.h>
36 #include <sys/epoll.h>
37 #include <termios.h>
38 #include <sys/signalfd.h>
39 #include <grp.h>
40
41 #include "log.h"
42 #include "util.h"
43 #include "missing.h"
44 #include "cgroup-util.h"
45 #include "sd-daemon.h"
46 #include "strv.h"
47
48 static char *arg_directory = NULL;
49 static char *arg_user = NULL;
50
51 static int help(void) {
52
53         printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
54                "Spawn a minimal namespace container for debugging, testing and building.\n\n"
55                "  -h --help            Show this help\n"
56                "  -D --directory=NAME  Root directory for the container\n"
57                "  -u --user=USER       Run the command under specified user or uid\n",
58                program_invocation_short_name);
59
60         return 0;
61 }
62
63 static int parse_argv(int argc, char *argv[]) {
64
65         static const struct option options[] = {
66                 { "help",      no_argument,       NULL, 'h' },
67                 { "directory", required_argument, NULL, 'D' },
68                 { "user",      optional_argument, NULL, 'u' },
69                 { NULL,        0,                 NULL, 0   }
70         };
71
72         int c;
73
74         assert(argc >= 0);
75         assert(argv);
76
77         while ((c = getopt_long(argc, argv, "+hD:u:", options, NULL)) >= 0) {
78
79                 switch (c) {
80
81                 case 'h':
82                         help();
83                         return 0;
84
85                 case 'D':
86                         free(arg_directory);
87                         if (!(arg_directory = strdup(optarg))) {
88                                 log_error("Failed to duplicate root directory.");
89                                 return -ENOMEM;
90                         }
91
92                         break;
93
94                 case 'u':
95                         free(arg_user);
96                         if (!(arg_user = strdup(optarg))) {
97                                 log_error("Failed to duplicate user name.");
98                                 return -ENOMEM;
99                         }
100
101                         break;
102
103                 case '?':
104                         return -EINVAL;
105
106                 default:
107                         log_error("Unknown option code %c", c);
108                         return -EINVAL;
109                 }
110         }
111
112         return 1;
113 }
114
115 static int mount_all(const char *dest) {
116
117         typedef struct MountPoint {
118                 const char *what;
119                 const char *where;
120                 const char *type;
121                 const char *options;
122                 unsigned long flags;
123                 bool fatal;
124         } MountPoint;
125
126         static const MountPoint mount_table[] = {
127                 { "proc",      "/proc",     "proc",  NULL,       MS_NOSUID|MS_NOEXEC|MS_NODEV, true  },
128                 { "/proc/sys", "/proc/sys", "bind",  NULL,       MS_BIND, true                       },   /* Bind mount first */
129                 { "/proc/sys", "/proc/sys", "bind",  NULL,       MS_BIND|MS_RDONLY|MS_REMOUNT, true  },   /* Then, make it r/o */
130                 { "/sys",      "/sys",      "bind",  NULL,       MS_BIND,                      true  },   /* Bind mount first */
131                 { "/sys",      "/sys",      "bind",  NULL,       MS_BIND|MS_RDONLY|MS_REMOUNT, true  },   /* Then, make it r/o */
132                 { "tmpfs",     "/dev",      "tmpfs", "mode=755", MS_NOSUID,                    true  },
133                 { "/dev/pts",  "/dev/pts",  "bind",  NULL,       MS_BIND,                      true  },
134                 { "tmpfs",     "/run",      "tmpfs", "mode=755", MS_NOSUID|MS_NODEV,           true  },
135 #ifdef HAVE_SELINUX
136                 { "/selinux",  "/selinux",  "bind",  NULL,       MS_BIND,                      false },  /* Bind mount first */
137                 { "/selinux",  "/selinux",  "bind",  NULL,       MS_BIND|MS_RDONLY|MS_REMOUNT, false },  /* Then, make it r/o */
138 #endif
139         };
140
141         unsigned k;
142         int r = 0;
143         char *where;
144
145         for (k = 0; k < ELEMENTSOF(mount_table); k++) {
146                 int t;
147
148                 if (asprintf(&where, "%s/%s", dest, mount_table[k].where) < 0) {
149                         log_error("Out of memory");
150
151                         if (r == 0)
152                                 r = -ENOMEM;
153
154                         break;
155                 }
156
157                 if ((t = path_is_mount_point(where)) < 0) {
158                         log_error("Failed to detect whether %s is a mount point: %s", where, strerror(-t));
159                         free(where);
160
161                         if (r == 0)
162                                 r = t;
163
164                         continue;
165                 }
166
167                 mkdir_p(where, 0755);
168
169                 if (mount(mount_table[k].what,
170                           where,
171                           mount_table[k].type,
172                           mount_table[k].flags,
173                           mount_table[k].options) < 0 &&
174                     mount_table[k].fatal) {
175
176                         log_error("mount(%s) failed: %m", where);
177
178                         if (r == 0)
179                                 r = -errno;
180                 }
181
182                 free(where);
183         }
184
185         /* Fix the timezone, if possible */
186         if (asprintf(&where, "%s/%s", dest, "/etc/localtime") >= 0) {
187                 mount("/etc/localtime", where, "bind", MS_BIND, NULL);
188                 mount("/etc/localtime", where, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
189                 free(where);
190         }
191
192         return r;
193 }
194
195 static int copy_devnodes(const char *dest, const char *console) {
196
197         static const char devnodes[] =
198                 "null\0"
199                 "zero\0"
200                 "full\0"
201                 "random\0"
202                 "urandom\0"
203                 "tty\0"
204                 "ptmx\0"
205                 "kmsg\0"
206                 "rtc0\0";
207
208         const char *d;
209         int r = 0, k;
210         mode_t u;
211         struct stat st;
212         char *from = NULL, *to = NULL;
213
214         assert(dest);
215         assert(console);
216
217         u = umask(0000);
218
219         NULSTR_FOREACH(d, devnodes) {
220                 from = to = NULL;
221
222                 asprintf(&from, "/dev/%s", d);
223                 asprintf(&to, "%s/dev/%s", dest, d);
224
225                 if (!from || !to) {
226                         log_error("Failed to allocate devnode path");
227
228                         free(from);
229                         free(to);
230
231                         from = to = NULL;
232
233                         if (r == 0)
234                                 r = -ENOMEM;
235
236                         break;
237                 }
238
239                 if (stat(from, &st) < 0) {
240
241                         if (errno != ENOENT) {
242                                 log_error("Failed to stat %s: %m", from);
243                                 if (r == 0)
244                                         r = -errno;
245                         }
246
247                 } else if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
248
249                         log_error("%s is not a char or block device, cannot copy.", from);
250                         if (r == 0)
251                                 r = -EIO;
252
253                 } else if (mknod(to, st.st_mode, st.st_rdev) < 0) {
254
255                         log_error("mknod(%s) failed: %m", dest);
256                         if (r == 0)
257                                 r = -errno;
258                 }
259
260                 free(from);
261                 free(to);
262         }
263
264         if (stat(console, &st) < 0) {
265
266                 log_error("Failed to stat %s: %m", console);
267                 if (r == 0)
268                         r = -errno;
269
270                 goto finish;
271
272         } else if (!S_ISCHR(st.st_mode)) {
273
274                 log_error("/dev/console is not a char device.");
275                 if (r == 0)
276                         r = -EIO;
277
278                 goto finish;
279         }
280
281         if (asprintf(&to, "%s/dev/console", dest) < 0) {
282
283                 log_error("Out of memory");
284                 if (r == 0)
285                         r = -ENOMEM;
286
287                  goto finish;
288         }
289
290         /* We need to bind mount the right tty to /dev/console since
291          * ptys can only exist on pts file systems. To have something
292          * to bind mount things on we create a device node first, that
293          * has the right major/minor (note that the major minor
294          * doesn't actually matter here, since we mount it over
295          * anyway). */
296
297         if (mknod(to, (st.st_mode & ~07777) | 0600, st.st_rdev) < 0)
298                 log_error("mknod for /dev/console failed: %m");
299
300         if (mount(console, to, "bind", MS_BIND, NULL) < 0) {
301                 log_error("bind mount for /dev/console failed: %m");
302
303                 if (r == 0)
304                         r = -errno;
305         }
306
307         free(to);
308
309         if ((k = chmod_and_chown(console, 0600, 0, 0)) < 0) {
310                 log_error("Failed to correct access mode for TTY: %s", strerror(-k));
311
312                 if (r == 0)
313                         r = k;
314         }
315
316 finish:
317
318         umask(u);
319
320         return r;
321 }
322
323 static int drop_capabilities(void) {
324         static const unsigned long retain[] = {
325                 CAP_CHOWN,
326                 CAP_DAC_OVERRIDE,
327                 CAP_DAC_READ_SEARCH,
328                 CAP_FOWNER,
329                 CAP_FSETID,
330                 CAP_IPC_OWNER,
331                 CAP_KILL,
332                 CAP_LEASE,
333                 CAP_LINUX_IMMUTABLE,
334                 CAP_NET_BIND_SERVICE,
335                 CAP_NET_BROADCAST,
336                 CAP_NET_RAW,
337                 CAP_SETGID,
338                 CAP_SETFCAP,
339                 CAP_SETPCAP,
340                 CAP_SETUID,
341                 CAP_SYS_ADMIN,
342                 CAP_SYS_CHROOT,
343                 CAP_SYS_NICE,
344                 CAP_SYS_PTRACE,
345                 CAP_SYS_TTY_CONFIG
346         };
347
348         unsigned long l;
349
350         for (l = 0; l <= MAX(63LU, (unsigned long) CAP_LAST_CAP); l++) {
351                 unsigned i;
352
353                 for (i = 0; i < ELEMENTSOF(retain); i++)
354                         if (retain[i] == l)
355                                 break;
356
357                 if (i < ELEMENTSOF(retain))
358                         continue;
359
360                 if (prctl(PR_CAPBSET_DROP, l) < 0) {
361
362                         /* If this capability is not known, EINVAL
363                          * will be returned, let's ignore this. */
364                         if (errno == EINVAL)
365                                 break;
366
367                         log_error("PR_CAPBSET_DROP failed: %m");
368                         return -errno;
369                 }
370         }
371
372         return 0;
373 }
374
375 static int is_os_tree(const char *path) {
376         int r;
377         char *p;
378         /* We use /bin/sh as flag file if something is an OS */
379
380         if (asprintf(&p, "%s/bin/sh", path) < 0)
381                 return -ENOMEM;
382
383         r = access(p, F_OK);
384         free(p);
385
386         return r < 0 ? 0 : 1;
387 }
388
389 #define BUFFER_SIZE 1024
390
391 static int process_pty(int master, sigset_t *mask) {
392
393         char in_buffer[BUFFER_SIZE], out_buffer[BUFFER_SIZE];
394         size_t in_buffer_full = 0, out_buffer_full = 0;
395         struct epoll_event stdin_ev, stdout_ev, master_ev, signal_ev;
396         bool stdin_readable = false, stdout_writable = false, master_readable = false, master_writable = false;
397         int ep = -1, signal_fd = -1, r;
398
399         fd_nonblock(STDIN_FILENO, 1);
400         fd_nonblock(STDOUT_FILENO, 1);
401         fd_nonblock(master, 1);
402
403         if ((signal_fd = signalfd(-1, mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
404                 log_error("signalfd(): %m");
405                 r = -errno;
406                 goto finish;
407         }
408
409         if ((ep = epoll_create1(EPOLL_CLOEXEC)) < 0) {
410                 log_error("Failed to create epoll: %m");
411                 r = -errno;
412                 goto finish;
413         }
414
415         zero(stdin_ev);
416         stdin_ev.events = EPOLLIN|EPOLLET;
417         stdin_ev.data.fd = STDIN_FILENO;
418
419         zero(stdout_ev);
420         stdout_ev.events = EPOLLOUT|EPOLLET;
421         stdout_ev.data.fd = STDOUT_FILENO;
422
423         zero(master_ev);
424         master_ev.events = EPOLLIN|EPOLLOUT|EPOLLET;
425         master_ev.data.fd = master;
426
427         zero(signal_ev);
428         signal_ev.events = EPOLLIN;
429         signal_ev.data.fd = signal_fd;
430
431         if (epoll_ctl(ep, EPOLL_CTL_ADD, STDIN_FILENO, &stdin_ev) < 0 ||
432             epoll_ctl(ep, EPOLL_CTL_ADD, STDOUT_FILENO, &stdout_ev) < 0 ||
433             epoll_ctl(ep, EPOLL_CTL_ADD, master, &master_ev) < 0 ||
434             epoll_ctl(ep, EPOLL_CTL_ADD, signal_fd, &signal_ev) < 0) {
435                 log_error("Failed to regiser fds in epoll: %m");
436                 r = -errno;
437                 goto finish;
438         }
439
440         for (;;) {
441                 struct epoll_event ev[16];
442                 ssize_t k;
443                 int i, nfds;
444
445                 if ((nfds = epoll_wait(ep, ev, ELEMENTSOF(ev), -1)) < 0) {
446
447                         if (errno == EINTR || errno == EAGAIN)
448                                 continue;
449
450                         log_error("epoll_wait(): %m");
451                         r = -errno;
452                         goto finish;
453                 }
454
455                 assert(nfds >= 1);
456
457                 for (i = 0; i < nfds; i++) {
458                         if (ev[i].data.fd == STDIN_FILENO) {
459
460                                 if (ev[i].events & (EPOLLIN|EPOLLHUP))
461                                         stdin_readable = true;
462
463                         } else if (ev[i].data.fd == STDOUT_FILENO) {
464
465                                 if (ev[i].events & (EPOLLOUT|EPOLLHUP))
466                                         stdout_writable = true;
467
468                         } else if (ev[i].data.fd == master) {
469
470                                 if (ev[i].events & (EPOLLIN|EPOLLHUP))
471                                         master_readable = true;
472
473                                 if (ev[i].events & (EPOLLOUT|EPOLLHUP))
474                                         master_writable = true;
475
476                         } else if (ev[i].data.fd == signal_fd) {
477                                 struct signalfd_siginfo sfsi;
478                                 ssize_t n;
479
480                                 if ((n = read(signal_fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
481
482                                         if (n >= 0) {
483                                                 log_error("Failed to read from signalfd: invalid block size");
484                                                 r = -EIO;
485                                                 goto finish;
486                                         }
487
488                                         if (errno != EINTR && errno != EAGAIN) {
489                                                 log_error("Failed to read from signalfd: %m");
490                                                 r = -errno;
491                                                 goto finish;
492                                         }
493                                 } else {
494
495                                         if (sfsi.ssi_signo == SIGWINCH) {
496                                                 struct winsize ws;
497
498                                                 /* The window size changed, let's forward that. */
499                                                 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
500                                                         ioctl(master, TIOCSWINSZ, &ws);
501                                         } else {
502                                                 r = 0;
503                                                 goto finish;
504                                         }
505                                 }
506                         }
507                 }
508
509                 while ((stdin_readable && in_buffer_full <= 0) ||
510                        (master_writable && in_buffer_full > 0) ||
511                        (master_readable && out_buffer_full <= 0) ||
512                        (stdout_writable && out_buffer_full > 0)) {
513
514                         if (stdin_readable && in_buffer_full < BUFFER_SIZE) {
515
516                                 if ((k = read(STDIN_FILENO, in_buffer + in_buffer_full, BUFFER_SIZE - in_buffer_full)) < 0) {
517
518                                         if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
519                                                 stdin_readable = false;
520                                         else {
521                                                 log_error("read(): %m");
522                                                 r = -errno;
523                                                 goto finish;
524                                         }
525                                 } else
526                                         in_buffer_full += (size_t) k;
527                         }
528
529                         if (master_writable && in_buffer_full > 0) {
530
531                                 if ((k = write(master, in_buffer, in_buffer_full)) < 0) {
532
533                                         if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
534                                                 master_writable = false;
535                                         else {
536                                                 log_error("write(): %m");
537                                                 r = -errno;
538                                                 goto finish;
539                                         }
540
541                                 } else {
542                                         assert(in_buffer_full >= (size_t) k);
543                                         memmove(in_buffer, in_buffer + k, in_buffer_full - k);
544                                         in_buffer_full -= k;
545                                 }
546                         }
547
548                         if (master_readable && out_buffer_full < BUFFER_SIZE) {
549
550                                 if ((k = read(master, out_buffer + out_buffer_full, BUFFER_SIZE - out_buffer_full)) < 0) {
551
552                                         if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
553                                                 master_readable = false;
554                                         else {
555                                                 log_error("read(): %m");
556                                                 r = -errno;
557                                                 goto finish;
558                                         }
559                                 }  else
560                                         out_buffer_full += (size_t) k;
561                         }
562
563                         if (stdout_writable && out_buffer_full > 0) {
564
565                                 if ((k = write(STDOUT_FILENO, out_buffer, out_buffer_full)) < 0) {
566
567                                         if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
568                                                 stdout_writable = false;
569                                         else {
570                                                 log_error("write(): %m");
571                                                 r = -errno;
572                                                 goto finish;
573                                         }
574
575                                 } else {
576                                         assert(out_buffer_full >= (size_t) k);
577                                         memmove(out_buffer, out_buffer + k, out_buffer_full - k);
578                                         out_buffer_full -= k;
579                                 }
580                         }
581                 }
582         }
583
584 finish:
585         if (ep >= 0)
586                 close_nointr_nofail(ep);
587
588         if (signal_fd >= 0)
589                 close_nointr_nofail(signal_fd);
590
591         return r;
592 }
593
594 int main(int argc, char *argv[]) {
595         pid_t pid = 0;
596         int r = EXIT_FAILURE, k;
597         char *oldcg = NULL, *newcg = NULL;
598         int master = -1;
599         const char *console = NULL;
600         struct termios saved_attr, raw_attr;
601         sigset_t mask;
602         bool saved_attr_valid = false;
603         struct winsize ws;
604
605         log_parse_environment();
606         log_open();
607
608         if ((r = parse_argv(argc, argv)) <= 0)
609                 goto finish;
610
611         if (arg_directory) {
612                 char *p;
613
614                 p = path_make_absolute_cwd(arg_directory);
615                 free(arg_directory);
616                 arg_directory = p;
617         } else
618                 arg_directory = get_current_dir_name();
619
620         if (!arg_directory) {
621                 log_error("Failed to determine path");
622                 goto finish;
623         }
624
625         path_kill_slashes(arg_directory);
626
627         if (geteuid() != 0) {
628                 log_error("Need to be root.");
629                 goto finish;
630         }
631
632         if (sd_booted() <= 0) {
633                 log_error("Not running on a systemd system.");
634                 goto finish;
635         }
636
637         if (path_equal(arg_directory, "/")) {
638                 log_error("Spawning container on root directory not supported.");
639                 goto finish;
640         }
641
642         if (is_os_tree(arg_directory) <= 0) {
643                 log_error("Directory %s doesn't look like an OS root directory. Refusing.", arg_directory);
644                 goto finish;
645         }
646
647         if ((k = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 0, &oldcg)) < 0) {
648                 log_error("Failed to determine current cgroup: %s", strerror(-k));
649                 goto finish;
650         }
651
652         if (asprintf(&newcg, "%s/nspawn-%lu", oldcg, (unsigned long) getpid()) < 0) {
653                 log_error("Failed to allocate cgroup path.");
654                 goto finish;
655         }
656
657         if ((k = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, newcg, 0)) < 0)  {
658                 log_error("Failed to create cgroup: %s", strerror(-k));
659                 goto finish;
660         }
661
662         if ((master = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NDELAY)) < 0) {
663                 log_error("Failed to acquire pseudo tty: %m");
664                 goto finish;
665         }
666
667         if (!(console = ptsname(master))) {
668                 log_error("Failed to determine tty name: %m");
669                 goto finish;
670         }
671
672         log_info("Spawning namespace container on %s (console is %s).", arg_directory, console);
673
674         if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
675                 ioctl(master, TIOCSWINSZ, &ws);
676
677         if (unlockpt(master) < 0) {
678                 log_error("Failed to unlock tty: %m");
679                 goto finish;
680         }
681
682         if (tcgetattr(STDIN_FILENO, &saved_attr) < 0) {
683                 log_error("Failed to get terminal attributes: %m");
684                 goto finish;
685         }
686
687         saved_attr_valid = true;
688
689         raw_attr = saved_attr;
690         cfmakeraw(&raw_attr);
691         raw_attr.c_lflag &= ~ECHO;
692
693         if (tcsetattr(STDIN_FILENO, TCSANOW, &raw_attr) < 0) {
694                 log_error("Failed to set terminal attributes: %m");
695                 goto finish;
696         }
697
698         assert_se(sigemptyset(&mask) == 0);
699         sigset_add_many(&mask, SIGCHLD, SIGWINCH, SIGTERM, SIGINT, -1);
700         assert_se(sigprocmask(SIG_BLOCK, &mask, NULL) == 0);
701
702         if ((pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS, NULL)) < 0) {
703                 log_error("clone() failed: %m");
704                 goto finish;
705         }
706
707         if (pid == 0) {
708                 /* child */
709
710                 const char *hn;
711                 const char *home = NULL;
712                 uid_t uid = (uid_t) -1;
713                 gid_t gid = (gid_t) -1;
714                 const char *envp[] = {
715                         "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
716                         NULL, /* TERM */
717                         NULL, /* HOME */
718                         NULL, /* USER */
719                         NULL, /* LOGNAME */
720                         NULL
721                 };
722
723                 envp[1] = strv_find_prefix(environ, "TERM=");
724
725                 close_nointr_nofail(master);
726
727                 close_nointr(STDIN_FILENO);
728                 close_nointr(STDOUT_FILENO);
729                 close_nointr(STDERR_FILENO);
730
731                 close_all_fds(NULL, 0);
732
733                 reset_all_signal_handlers();
734
735                 assert_se(sigemptyset(&mask) == 0);
736                 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
737
738                 if (setsid() < 0)
739                         goto child_fail;
740
741                 if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0)
742                         goto child_fail;
743
744                 /* Mark / as private, in case somebody marked it shared */
745                 if (mount(NULL, "/", NULL, MS_PRIVATE|MS_REC, NULL) < 0)
746                         goto child_fail;
747
748                 if (mount_all(arg_directory) < 0)
749                         goto child_fail;
750
751                 if (copy_devnodes(arg_directory, console) < 0)
752                         goto child_fail;
753
754                 if (chdir(arg_directory) < 0) {
755                         log_error("chdir(%s) failed: %m", arg_directory);
756                         goto child_fail;
757                 }
758
759                 if (open_terminal("dev/console", O_RDWR) != STDIN_FILENO ||
760                     dup2(STDIN_FILENO, STDOUT_FILENO) != STDOUT_FILENO ||
761                     dup2(STDIN_FILENO, STDERR_FILENO) != STDERR_FILENO)
762                         goto child_fail;
763
764                 if (mount(arg_directory, "/", "bind", MS_BIND|MS_MOVE, NULL) < 0) {
765                         log_error("mount(MS_MOVE) failed: %m");
766                         goto child_fail;
767                 }
768
769                 if (chroot(".") < 0) {
770                         log_error("chroot() failed: %m");
771                         goto child_fail;
772                 }
773
774                 if (chdir("/") < 0) {
775                         log_error("chdir() failed: %m");
776                         goto child_fail;
777                 }
778
779                 umask(0002);
780
781                 if (drop_capabilities() < 0)
782                         goto child_fail;
783
784                 if (arg_user) {
785
786                         if (get_user_creds((const char**)&arg_user, &uid, &gid, &home) < 0) {
787                                 log_error("get_user_creds() failed: %m");
788                                 goto child_fail;
789                         }
790
791                         if (mkdir_parents(home, 0775) < 0) {
792                                 log_error("mkdir_parents() failed: %m");
793                                 goto child_fail;
794                         }
795
796                         if (safe_mkdir(home, 0775, uid, gid) < 0) {
797                                 log_error("safe_mkdir() failed: %m");
798                                 goto child_fail;
799                         }
800
801                         if (initgroups((const char*)arg_user, gid) < 0) {
802                                 log_error("initgroups() failed: %m");
803                                 goto child_fail;
804                         }
805
806                         if (setresgid(gid, gid, gid) < 0) {
807                                 log_error("setregid() failed: %m");
808                                 goto child_fail;
809                         }
810
811                         if (setresuid(uid, uid, uid) < 0) {
812                                 log_error("setreuid() failed: %m");
813                                 goto child_fail;
814                         }
815                 }
816
817                 if ((asprintf((char**)(envp + 2), "HOME=%s", home? home: "/root") < 0) ||
818                     (asprintf((char**)(envp + 3), "USER=%s", arg_user? arg_user : "root") < 0) ||
819                     (asprintf((char**)(envp + 4), "LOGNAME=%s", arg_user? arg_user : "root") < 0)) {
820                     log_error("Out of memory");
821                     goto child_fail;
822                 }
823
824                 if ((hn = file_name_from_path(arg_directory)))
825                         sethostname(hn, strlen(hn));
826
827                 if (argc > optind)
828                         execvpe(argv[optind], argv + optind, (char**) envp);
829                 else {
830                         chdir(home ? home : "/root");
831                         execle("/bin/bash", "-bash", NULL, (char**) envp);
832                 }
833
834                 log_error("execv() failed: %m");
835
836         child_fail:
837                 _exit(EXIT_FAILURE);
838         }
839
840         if (process_pty(master, &mask) < 0)
841                 goto finish;
842
843         if (saved_attr_valid) {
844                 tcsetattr(STDIN_FILENO, TCSANOW, &saved_attr);
845                 saved_attr_valid = false;
846         }
847
848         r = wait_for_terminate_and_warn(argc > optind ? argv[optind] : "bash", pid);
849
850         if (r < 0)
851                 r = EXIT_FAILURE;
852
853 finish:
854         if (saved_attr_valid)
855                 tcsetattr(STDIN_FILENO, TCSANOW, &saved_attr);
856
857         if (master >= 0)
858                 close_nointr_nofail(master);
859
860         if (oldcg)
861                 cg_attach(SYSTEMD_CGROUP_CONTROLLER, oldcg, 0);
862
863         if (newcg)
864                 cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, newcg, true);
865
866         free(arg_directory);
867         free(oldcg);
868         free(newcg);
869
870         return r;
871 }