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