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