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