chiark / gitweb /
nspawn: improve exit warning
[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
37 #include "log.h"
38 #include "util.h"
39
40 static char *arg_directory = NULL;
41
42 static int help(void) {
43
44         printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
45                "Spawn a minimal namespace container for debugging, testing and building.\n\n"
46                "  -h --help            Show this help\n"
47                "  -D --directory=NAME  Root directory for the container\n",
48                program_invocation_short_name);
49
50         return 0;
51 }
52
53 static int parse_argv(int argc, char *argv[]) {
54
55         static const struct option options[] = {
56                 { "help",      no_argument,       NULL, 'h' },
57                 { "directory", required_argument, NULL, 'D' },
58                 { NULL,        0,                 NULL, 0   }
59         };
60
61         int c;
62
63         assert(argc >= 0);
64         assert(argv);
65
66         while ((c = getopt_long(argc, argv, "+hD:", options, NULL)) >= 0) {
67
68                 switch (c) {
69
70                 case 'h':
71                         help();
72                         return 0;
73
74                 case 'D':
75                         free(arg_directory);
76                         if (!(arg_directory = strdup(optarg))) {
77                                 log_error("Failed to duplicate root directory.");
78                                 return -ENOMEM;
79                         }
80
81                         break;
82
83                 case '?':
84                         return -EINVAL;
85
86                 default:
87                         log_error("Unknown option code %c", c);
88                         return -EINVAL;
89                 }
90         }
91
92         return 1;
93 }
94
95 static int mount_all(const char *dest) {
96
97         typedef struct MountPoint {
98                 const char *what;
99                 const char *where;
100                 const char *type;
101                 const char *options;
102                 unsigned long flags;
103         } MountPoint;
104
105         static const MountPoint mount_table[] = {
106                 { "proc",      "/proc",     "proc",   NULL,        MS_NOSUID|MS_NOEXEC|MS_NODEV },
107                 { "/proc/sys", "/proc/sys", "bind",   NULL,        MS_BIND },                      /* Bind mount first */
108                 { "/proc/sys", "/proc/sys", "bind",   NULL,        MS_BIND|MS_RDONLY|MS_REMOUNT }, /* Then, make it r/o */
109                 { "sysfs",     "/sys",      "sysfs",  NULL,        MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY },
110                 { "tmpfs",     "/dev",      "tmpfs",  "mode=755",  MS_NOSUID },
111                 { "/dev/pts",  "/dev/pts",  "bind",   NULL,        MS_BIND },
112                 { "tmpfs",     "/dev/.run", "tmpfs",  "mode=755",  MS_NOSUID|MS_NOEXEC|MS_NODEV },
113         };
114
115         unsigned k;
116         int r = 0;
117
118         for (k = 0; k < ELEMENTSOF(mount_table); k++) {
119                 char *where;
120                 int t;
121
122                 if (asprintf(&where, "%s/%s", dest, mount_table[k].where) < 0) {
123                         log_error("Out of memory");
124
125                         if (r == 0)
126                                 r = -ENOMEM;
127
128                         break;
129                 }
130
131                 if ((t = path_is_mount_point(where)) < 0) {
132                         log_error("Failed to detect whether %s is a mount point: %s", where, strerror(-t));
133                         free(where);
134
135                         if (r == 0)
136                                 r = t;
137
138                         continue;
139                 }
140
141                 mkdir_p(where, 0755);
142
143                 if (mount(mount_table[k].what,
144                           where,
145                           mount_table[k].type,
146                           mount_table[k].flags,
147                           mount_table[k].options) < 0) {
148
149                         log_error("mount(%s) failed: %m", where);
150
151                         if (r == 0)
152                                 r = -errno;
153                 }
154
155                 free(where);
156         }
157
158         return r;
159 }
160
161 static int copy_devnodes(const char *dest) {
162
163         static const char devnodes[] =
164                 "null\0"
165                 "zero\0"
166                 "full\0"
167                 "random\0"
168                 "urandom\0"
169                 "tty\0"
170                 "ptmx\0"
171                 "kmsg\0"
172                 "rtc0\0";
173
174         const char *d;
175         int r = 0, k;
176         char *tty = NULL;
177         dev_t tty_devnum;
178
179         NULSTR_FOREACH(d, devnodes) {
180                 char *from = NULL, *to = NULL;
181                 struct stat st;
182
183                 asprintf(&from, "/dev/%s", d);
184                 asprintf(&to, "%s/dev/%s", dest, d);
185
186                 if (!from || !to) {
187                         log_error("Failed to allocate devnode path");
188
189                         free(from);
190                         free(to);
191
192                         if (r == 0)
193                                 r = -ENOMEM;
194
195                         break;
196                 }
197
198                 if (stat(from, &st) < 0) {
199
200                         if (errno != ENOENT) {
201                                 log_error("Failed to stat %s: %m", from);
202
203                                 if (r == 0)
204                                         r = -errno;
205                         }
206
207                 } else {
208                         if (mknod(to, st.st_mode, st.st_rdev) < 0) {
209                                 log_error("mknod(%s) failed: %m", dest);
210
211                                 if (r == 0)
212                                         r = -errno;
213                         }
214                 }
215
216                 free(from);
217                 free(to);
218         }
219
220         if ((k = get_ctty(&tty, &tty_devnum)) < 0) {
221                 log_error("Failed to determine controlling tty: %s", strerror(-k));
222
223                 if (r == 0)
224                         r = k;
225         } else {
226                 char *from = NULL, *to = NULL;
227
228                 asprintf(&from, "/dev/%s", tty);
229                 asprintf(&to, "%s/dev/console", dest);
230
231                 if (!from || !to) {
232                         log_error("Out of memory");
233
234                         if (r == 0)
235                                 r = k;
236                 } else {
237                         /* We need to bind mount our own tty on
238                          * /dev/console, since ptys cannot be used
239                          * unless on a devpts file system. But to bind
240                          * mount it we first have to create a device
241                          * node where we can bind mount it on. This is
242                          * kinda ugly since the TTY will very likely
243                          * be owned by a user/group that does not
244                          * exist in the container. */
245
246                         if (mknod(to, S_IFCHR|0600, tty_devnum) < 0) {
247                                 log_error("mknod for /dev/console failed: %m");
248
249                                 if (r == 0)
250                                         r = -errno;
251                         }
252
253                         if (mount(from, to, "bind", MS_BIND, NULL) < 0) {
254                                 log_error("bind mount for /dev/console failed: %m");
255
256                                 if (r == 0)
257                                         r = -errno;
258                         }
259                 }
260
261                 free(from);
262                 free(to);
263         }
264
265         free(tty);
266
267         return r;
268 }
269
270 static int drop_capabilities(void) {
271         static const unsigned long retain[] = {
272                 CAP_CHOWN,
273                 CAP_DAC_OVERRIDE,
274                 CAP_DAC_READ_SEARCH,
275                 CAP_FOWNER,
276                 CAP_FSETID,
277                 CAP_IPC_OWNER,
278                 CAP_KILL,
279                 CAP_LEASE,
280                 CAP_LINUX_IMMUTABLE,
281                 CAP_NET_BIND_SERVICE,
282                 CAP_NET_BROADCAST,
283                 CAP_NET_RAW,
284                 CAP_SETGID,
285                 CAP_SETFCAP,
286                 CAP_SETPCAP,
287                 CAP_SETUID,
288                 CAP_SYS_ADMIN,
289                 CAP_SYS_CHROOT,
290                 CAP_SYS_NICE,
291                 CAP_SYS_PTRACE,
292                 CAP_SYS_TTY_CONFIG
293         };
294
295         unsigned long l;
296
297         for (l = 0; l <= MAX(63LU, (unsigned long) CAP_LAST_CAP); l ++) {
298                 unsigned i;
299
300                 for (i = 0; i < ELEMENTSOF(retain); i++)
301                         if (retain[i] == l)
302                                 break;
303
304                 if (i < ELEMENTSOF(retain))
305                         continue;
306
307                 if (prctl(PR_CAPBSET_DROP, l) < 0) {
308
309                         /* If this capability is not known, EINVAL
310                          * will be returned, let's ignore this. */
311                         if (errno == EINVAL)
312                                 continue;
313
314                         log_error("PR_CAPBSET_DROP failed: %m");
315                         return -errno;
316                 }
317         }
318
319         return 0;
320 }
321
322 static int is_os_tree(const char *path) {
323         int r;
324         char *p;
325         /* We use /bin/sh as flag file if something is an OS */
326
327         if (asprintf(&p, "%s/bin/sh", path) < 0)
328                 return -ENOMEM;
329
330         r = access(p, F_OK);
331         free(p);
332
333         return r < 0 ? 0 : 1;
334 }
335
336
337 int main(int argc, char *argv[]) {
338         pid_t pid = 0;
339         int r = EXIT_FAILURE;
340
341         log_parse_environment();
342         log_open();
343
344         if ((r = parse_argv(argc, argv)) <= 0)
345                 goto finish;
346
347         if (arg_directory) {
348                 char *p;
349
350                 p = path_make_absolute_cwd(arg_directory);
351                 free(arg_directory);
352                 arg_directory = p;
353         } else
354                 arg_directory = get_current_dir_name();
355
356         if (!arg_directory) {
357                 log_error("Failed to determine path");
358                 goto finish;
359         }
360
361         path_kill_slashes(arg_directory);
362
363         if (geteuid() != 0) {
364                 log_error("Need to be root.");
365                 goto finish;
366         }
367
368         if (path_equal(arg_directory, "/")) {
369                 log_error("Spawning container on root directory not supported.");
370                 goto finish;
371         }
372
373         if (is_os_tree(arg_directory) <= 0) {
374                 log_error("Directory %s doesn't look like an OS root directory. Refusing.", arg_directory);
375                 goto finish;
376         }
377
378         log_info("Spawning namespace container on %s.", arg_directory);
379
380         if ((pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS|CLONE_NEWNET, NULL)) < 0) {
381                 log_error("clone() failed: %m");
382                 goto finish;
383         }
384
385         if (pid == 0) {
386                 const char *hn;
387
388                 /* child */
389
390                 if (mount_all(arg_directory) < 0)
391                         goto child_fail;
392
393                 if (copy_devnodes(arg_directory) < 0)
394                         goto child_fail;
395
396                 if (chdir(arg_directory) < 0) {
397                         log_error("chdir(%s) failed: %m", arg_directory);
398                         goto child_fail;
399                 }
400                 if (mount(arg_directory, "/", "bind", MS_BIND|MS_MOVE, NULL) < 0) {
401                         log_error("mount(MS_MOVE) failed: %m");
402                         goto child_fail;
403                 }
404
405                 if (chroot(".") < 0) {
406                         log_error("chroot() failed: %m");
407                         goto child_fail;
408                 }
409
410                 if (chdir("/") < 0) {
411                         log_error("chdir() failed: %m");
412                         goto child_fail;
413                 }
414
415                 if (drop_capabilities() < 0)
416                         goto child_fail;
417
418                 if ((hn = file_name_from_path(arg_directory)))
419                         sethostname(hn, strlen(hn));
420
421                 if (argc > optind)
422                         execvp(argv[optind], argv + optind);
423                 else
424                         execl("/bin/bash", "/bin/bash", NULL);
425
426                 log_error("execv() failed: %m");
427
428         child_fail:
429                 _exit(EXIT_FAILURE);
430         }
431
432         r = wait_for_terminate_and_warn(argc > optind ? argv[optind] : "bash", pid);
433
434         if (r < 0)
435                 r = EXIT_FAILURE;
436
437 finish:
438         free(arg_directory);
439
440         if (pid > 0)
441                 kill(pid, SIGTERM);
442
443         return r;
444 }