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