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