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