]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/conf.c
Merge pull request #1908 from Cypresslin/fix-overlayfs
[mirror_lxc.git] / src / lxc / conf.c
1 /*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
7 * Daniel Lezcano <daniel.lezcano at free.fr>
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24 #define _GNU_SOURCE
25 #include "config.h"
26
27 #include <dirent.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <grp.h>
31 #include <inttypes.h>
32 #include <libgen.h>
33 #include <pwd.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39 #include <unistd.h>
40 #include <arpa/inet.h>
41 #include <linux/loop.h>
42 #include <net/if.h>
43 #include <netinet/in.h>
44 #include <sys/mman.h>
45 #include <sys/mount.h>
46 #include <sys/param.h>
47 #include <sys/prctl.h>
48 #include <sys/stat.h>
49 #include <sys/socket.h>
50 #include <sys/sysmacros.h>
51 #include <sys/syscall.h>
52 #include <sys/types.h>
53 #include <sys/utsname.h>
54 #include <sys/wait.h>
55
56 /* makedev() */
57 #ifdef MAJOR_IN_MKDEV
58 # include <sys/mkdev.h>
59 #endif
60
61 #ifdef HAVE_STATVFS
62 #include <sys/statvfs.h>
63 #endif
64
65 #if HAVE_PTY_H
66 #include <pty.h>
67 #else
68 #include <../include/openpty.h>
69 #endif
70
71 #include "af_unix.h"
72 #include "caps.h" /* for lxc_caps_last_cap() */
73 #include "cgroup.h"
74 #include "conf.h"
75 #include "confile_utils.h"
76 #include "error.h"
77 #include "log.h"
78 #include "lxclock.h"
79 #include "lxcseccomp.h"
80 #include "namespace.h"
81 #include "network.h"
82 #include "parse.h"
83 #include "ringbuf.h"
84 #include "storage.h"
85 #include "storage/aufs.h"
86 #include "storage/overlay.h"
87 #include "utils.h"
88 #include "lsm/lsm.h"
89
90 #if HAVE_LIBCAP
91 #include <sys/capability.h>
92 #endif
93
94 #if HAVE_SYS_PERSONALITY_H
95 #include <sys/personality.h>
96 #endif
97
98 #if IS_BIONIC
99 #include <../include/lxcmntent.h>
100 #else
101 #include <mntent.h>
102 #endif
103
104 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
105 #include <../include/prlimit.h>
106 #endif
107
108 lxc_log_define(lxc_conf, lxc);
109
110 #if HAVE_LIBCAP
111 #ifndef CAP_SETFCAP
112 #define CAP_SETFCAP 31
113 #endif
114
115 #ifndef CAP_MAC_OVERRIDE
116 #define CAP_MAC_OVERRIDE 32
117 #endif
118
119 #ifndef CAP_MAC_ADMIN
120 #define CAP_MAC_ADMIN 33
121 #endif
122 #endif
123
124 #ifndef PR_CAPBSET_DROP
125 #define PR_CAPBSET_DROP 24
126 #endif
127
128 #ifndef LO_FLAGS_AUTOCLEAR
129 #define LO_FLAGS_AUTOCLEAR 4
130 #endif
131
132 #ifndef CAP_SETUID
133 #define CAP_SETUID 7
134 #endif
135
136 #ifndef CAP_SETGID
137 #define CAP_SETGID 6
138 #endif
139
140 /* needed for cgroup automount checks, regardless of whether we
141 * have included linux/capability.h or not */
142 #ifndef CAP_SYS_ADMIN
143 #define CAP_SYS_ADMIN 21
144 #endif
145
146 /* Define pivot_root() if missing from the C library */
147 #ifndef HAVE_PIVOT_ROOT
148 static int pivot_root(const char * new_root, const char * put_old)
149 {
150 #ifdef __NR_pivot_root
151 return syscall(__NR_pivot_root, new_root, put_old);
152 #else
153 errno = ENOSYS;
154 return -1;
155 #endif
156 }
157 #else
158 extern int pivot_root(const char * new_root, const char * put_old);
159 #endif
160
161 /* Define sethostname() if missing from the C library */
162 #ifndef HAVE_SETHOSTNAME
163 static int sethostname(const char * name, size_t len)
164 {
165 #ifdef __NR_sethostname
166 return syscall(__NR_sethostname, name, len);
167 #else
168 errno = ENOSYS;
169 return -1;
170 #endif
171 }
172 #endif
173
174 #ifndef MS_PRIVATE
175 #define MS_PRIVATE (1<<18)
176 #endif
177
178 #ifndef MS_LAZYTIME
179 #define MS_LAZYTIME (1<<25)
180 #endif
181
182 char *lxchook_names[NUM_LXC_HOOKS] = {"pre-start", "pre-mount", "mount",
183 "autodev", "start", "stop",
184 "post-stop", "clone", "destroy",
185 "start-host"};
186
187 struct mount_opt {
188 char *name;
189 int clear;
190 int flag;
191 };
192
193 struct caps_opt {
194 char *name;
195 int value;
196 };
197
198 struct limit_opt {
199 char *name;
200 int value;
201 };
202
203 /*
204 * The lxc_conf of the container currently being worked on in an
205 * API call
206 * This is used in the error calls
207 */
208 #ifdef HAVE_TLS
209 __thread struct lxc_conf *current_config;
210 #else
211 struct lxc_conf *current_config;
212 #endif
213
214 static struct mount_opt mount_opt[] = {
215 { "async", 1, MS_SYNCHRONOUS },
216 { "atime", 1, MS_NOATIME },
217 { "bind", 0, MS_BIND },
218 { "defaults", 0, 0 },
219 { "dev", 1, MS_NODEV },
220 { "diratime", 1, MS_NODIRATIME },
221 { "dirsync", 0, MS_DIRSYNC },
222 { "exec", 1, MS_NOEXEC },
223 { "lazytime", 0, MS_LAZYTIME },
224 { "mand", 0, MS_MANDLOCK },
225 { "noatime", 0, MS_NOATIME },
226 { "nodev", 0, MS_NODEV },
227 { "nodiratime", 0, MS_NODIRATIME },
228 { "noexec", 0, MS_NOEXEC },
229 { "nomand", 1, MS_MANDLOCK },
230 { "norelatime", 1, MS_RELATIME },
231 { "nostrictatime", 1, MS_STRICTATIME },
232 { "nosuid", 0, MS_NOSUID },
233 { "rbind", 0, MS_BIND|MS_REC },
234 { "relatime", 0, MS_RELATIME },
235 { "remount", 0, MS_REMOUNT },
236 { "ro", 0, MS_RDONLY },
237 { "rw", 1, MS_RDONLY },
238 { "strictatime", 0, MS_STRICTATIME },
239 { "suid", 1, MS_NOSUID },
240 { "sync", 0, MS_SYNCHRONOUS },
241 { NULL, 0, 0 },
242 };
243
244 #if HAVE_LIBCAP
245 static struct caps_opt caps_opt[] = {
246 { "chown", CAP_CHOWN },
247 { "dac_override", CAP_DAC_OVERRIDE },
248 { "dac_read_search", CAP_DAC_READ_SEARCH },
249 { "fowner", CAP_FOWNER },
250 { "fsetid", CAP_FSETID },
251 { "kill", CAP_KILL },
252 { "setgid", CAP_SETGID },
253 { "setuid", CAP_SETUID },
254 { "setpcap", CAP_SETPCAP },
255 { "linux_immutable", CAP_LINUX_IMMUTABLE },
256 { "net_bind_service", CAP_NET_BIND_SERVICE },
257 { "net_broadcast", CAP_NET_BROADCAST },
258 { "net_admin", CAP_NET_ADMIN },
259 { "net_raw", CAP_NET_RAW },
260 { "ipc_lock", CAP_IPC_LOCK },
261 { "ipc_owner", CAP_IPC_OWNER },
262 { "sys_module", CAP_SYS_MODULE },
263 { "sys_rawio", CAP_SYS_RAWIO },
264 { "sys_chroot", CAP_SYS_CHROOT },
265 { "sys_ptrace", CAP_SYS_PTRACE },
266 { "sys_pacct", CAP_SYS_PACCT },
267 { "sys_admin", CAP_SYS_ADMIN },
268 { "sys_boot", CAP_SYS_BOOT },
269 { "sys_nice", CAP_SYS_NICE },
270 { "sys_resource", CAP_SYS_RESOURCE },
271 { "sys_time", CAP_SYS_TIME },
272 { "sys_tty_config", CAP_SYS_TTY_CONFIG },
273 { "mknod", CAP_MKNOD },
274 { "lease", CAP_LEASE },
275 #ifdef CAP_AUDIT_READ
276 { "audit_read", CAP_AUDIT_READ },
277 #endif
278 #ifdef CAP_AUDIT_WRITE
279 { "audit_write", CAP_AUDIT_WRITE },
280 #endif
281 #ifdef CAP_AUDIT_CONTROL
282 { "audit_control", CAP_AUDIT_CONTROL },
283 #endif
284 { "setfcap", CAP_SETFCAP },
285 { "mac_override", CAP_MAC_OVERRIDE },
286 { "mac_admin", CAP_MAC_ADMIN },
287 #ifdef CAP_SYSLOG
288 { "syslog", CAP_SYSLOG },
289 #endif
290 #ifdef CAP_WAKE_ALARM
291 { "wake_alarm", CAP_WAKE_ALARM },
292 #endif
293 #ifdef CAP_BLOCK_SUSPEND
294 { "block_suspend", CAP_BLOCK_SUSPEND },
295 #endif
296 };
297 #else
298 static struct caps_opt caps_opt[] = {};
299 #endif
300
301 static struct limit_opt limit_opt[] = {
302 #ifdef RLIMIT_AS
303 { "as", RLIMIT_AS },
304 #endif
305 #ifdef RLIMIT_CORE
306 { "core", RLIMIT_CORE },
307 #endif
308 #ifdef RLIMIT_CPU
309 { "cpu", RLIMIT_CPU },
310 #endif
311 #ifdef RLIMIT_DATA
312 { "data", RLIMIT_DATA },
313 #endif
314 #ifdef RLIMIT_FSIZE
315 { "fsize", RLIMIT_FSIZE },
316 #endif
317 #ifdef RLIMIT_LOCKS
318 { "locks", RLIMIT_LOCKS },
319 #endif
320 #ifdef RLIMIT_MEMLOCK
321 { "memlock", RLIMIT_MEMLOCK },
322 #endif
323 #ifdef RLIMIT_MSGQUEUE
324 { "msgqueue", RLIMIT_MSGQUEUE },
325 #endif
326 #ifdef RLIMIT_NICE
327 { "nice", RLIMIT_NICE },
328 #endif
329 #ifdef RLIMIT_NOFILE
330 { "nofile", RLIMIT_NOFILE },
331 #endif
332 #ifdef RLIMIT_NPROC
333 { "nproc", RLIMIT_NPROC },
334 #endif
335 #ifdef RLIMIT_RSS
336 { "rss", RLIMIT_RSS },
337 #endif
338 #ifdef RLIMIT_RTPRIO
339 { "rtprio", RLIMIT_RTPRIO },
340 #endif
341 #ifdef RLIMIT_RTTIME
342 { "rttime", RLIMIT_RTTIME },
343 #endif
344 #ifdef RLIMIT_SIGPENDING
345 { "sigpending", RLIMIT_SIGPENDING },
346 #endif
347 #ifdef RLIMIT_STACK
348 { "stack", RLIMIT_STACK },
349 #endif
350 };
351
352 static int run_buffer(char *buffer)
353 {
354 struct lxc_popen_FILE *f;
355 char *output;
356 int ret;
357
358 f = lxc_popen(buffer);
359 if (!f) {
360 SYSERROR("Failed to popen() %s.", buffer);
361 return -1;
362 }
363
364 output = malloc(LXC_LOG_BUFFER_SIZE);
365 if (!output) {
366 ERROR("Failed to allocate memory for %s.", buffer);
367 lxc_pclose(f);
368 return -1;
369 }
370
371 while (fgets(output, LXC_LOG_BUFFER_SIZE, f->f))
372 DEBUG("Script %s with output: %s.", buffer, output);
373
374 free(output);
375
376 ret = lxc_pclose(f);
377 if (ret == -1) {
378 SYSERROR("Script exited with error.");
379 return -1;
380 } else if (WIFEXITED(ret) && WEXITSTATUS(ret) != 0) {
381 ERROR("Script exited with status %d.", WEXITSTATUS(ret));
382 return -1;
383 } else if (WIFSIGNALED(ret)) {
384 ERROR("Script terminated by signal %d.", WTERMSIG(ret));
385 return -1;
386 }
387
388 return 0;
389 }
390
391 static int run_script_argv(const char *name, const char *section,
392 const char *script, const char *hook,
393 const char *lxcpath, char **argsin)
394 {
395 int ret, i;
396 char *buffer;
397 size_t size = 0;
398
399 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
400 script, name, section);
401
402 for (i = 0; argsin && argsin[i]; i++)
403 size += strlen(argsin[i]) + 1;
404
405 size += strlen(hook) + 1;
406
407 size += strlen(script);
408 size += strlen(name);
409 size += strlen(section);
410 size += 3;
411
412 if (size > INT_MAX)
413 return -1;
414
415 buffer = alloca(size);
416 if (!buffer) {
417 ERROR("Failed to allocate memory.");
418 return -1;
419 }
420
421 ret =
422 snprintf(buffer, size, "%s %s %s %s", script, name, section, hook);
423 if (ret < 0 || (size_t)ret >= size) {
424 ERROR("Script name too long.");
425 return -1;
426 }
427
428 for (i = 0; argsin && argsin[i]; i++) {
429 int len = size - ret;
430 int rc;
431 rc = snprintf(buffer + ret, len, " %s", argsin[i]);
432 if (rc < 0 || rc >= len) {
433 ERROR("Script args too long.");
434 return -1;
435 }
436 ret += rc;
437 }
438
439 return run_buffer(buffer);
440 }
441
442 int run_script(const char *name, const char *section, const char *script, ...)
443 {
444 int ret;
445 char *buffer, *p;
446 size_t size = 0;
447 va_list ap;
448
449 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
450 script, name, section);
451
452 va_start(ap, script);
453 while ((p = va_arg(ap, char *)))
454 size += strlen(p) + 1;
455 va_end(ap);
456
457 size += strlen(script);
458 size += strlen(name);
459 size += strlen(section);
460 size += 3;
461
462 if (size > INT_MAX)
463 return -1;
464
465 buffer = alloca(size);
466 if (!buffer) {
467 ERROR("Failed to allocate memory.");
468 return -1;
469 }
470
471 ret = snprintf(buffer, size, "%s %s %s", script, name, section);
472 if (ret < 0 || ret >= size) {
473 ERROR("Script name too long.");
474 return -1;
475 }
476
477 va_start(ap, script);
478 while ((p = va_arg(ap, char *))) {
479 int len = size - ret;
480 int rc;
481 rc = snprintf(buffer + ret, len, " %s", p);
482 if (rc < 0 || rc >= len) {
483 ERROR("Script args too long.");
484 return -1;
485 }
486 ret += rc;
487 }
488 va_end(ap);
489
490 return run_buffer(buffer);
491 }
492
493 /*
494 * pin_rootfs
495 * if rootfs is a directory, then open ${rootfs}/lxc.hold for writing for
496 * the duration of the container run, to prevent the container from marking
497 * the underlying fs readonly on shutdown. unlink the file immediately so
498 * no name pollution is happens
499 * return -1 on error.
500 * return -2 if nothing needed to be pinned.
501 * return an open fd (>=0) if we pinned it.
502 */
503 int pin_rootfs(const char *rootfs)
504 {
505 char absrootfs[MAXPATHLEN];
506 char absrootfspin[MAXPATHLEN];
507 struct stat s;
508 int ret, fd;
509
510 if (rootfs == NULL || strlen(rootfs) == 0)
511 return -2;
512
513 if (!realpath(rootfs, absrootfs))
514 return -2;
515
516 if (access(absrootfs, F_OK))
517 return -1;
518
519 if (stat(absrootfs, &s))
520 return -1;
521
522 if (!S_ISDIR(s.st_mode))
523 return -2;
524
525 ret = snprintf(absrootfspin, MAXPATHLEN, "%s/lxc.hold", absrootfs);
526 if (ret >= MAXPATHLEN)
527 return -1;
528
529 fd = open(absrootfspin, O_CREAT | O_RDWR, S_IWUSR|S_IRUSR);
530 if (fd < 0)
531 return fd;
532 (void)unlink(absrootfspin);
533 return fd;
534 }
535
536 /*
537 * If we are asking to remount something, make sure that any
538 * NOEXEC etc are honored.
539 */
540 unsigned long add_required_remount_flags(const char *s, const char *d,
541 unsigned long flags)
542 {
543 #ifdef HAVE_STATVFS
544 struct statvfs sb;
545 unsigned long required_flags = 0;
546
547 if (!(flags & MS_REMOUNT))
548 return flags;
549
550 if (!s)
551 s = d;
552
553 if (!s)
554 return flags;
555 if (statvfs(s, &sb) < 0)
556 return flags;
557
558 if (sb.f_flag & MS_NOSUID)
559 required_flags |= MS_NOSUID;
560 if (sb.f_flag & MS_NODEV)
561 required_flags |= MS_NODEV;
562 if (sb.f_flag & MS_RDONLY)
563 required_flags |= MS_RDONLY;
564 if (sb.f_flag & MS_NOEXEC)
565 required_flags |= MS_NOEXEC;
566
567 return flags | required_flags;
568 #else
569 return flags;
570 #endif
571 }
572
573 static int lxc_mount_auto_mounts(struct lxc_conf *conf, int flags, struct lxc_handler *handler)
574 {
575 int r;
576 int i;
577 static struct {
578 int match_mask;
579 int match_flag;
580 const char *source;
581 const char *destination;
582 const char *fstype;
583 unsigned long flags;
584 const char *options;
585 } default_mounts[] = {
586 /* Read-only bind-mounting... In older kernels, doing that required
587 * to do one MS_BIND mount and then MS_REMOUNT|MS_RDONLY the same
588 * one. According to mount(2) manpage, MS_BIND honors MS_RDONLY from
589 * kernel 2.6.26 onwards. However, this apparently does not work on
590 * kernel 3.8. Unfortunately, on that very same kernel, doing the
591 * same trick as above doesn't seem to work either, there one needs
592 * to ALSO specify MS_BIND for the remount, otherwise the entire
593 * fs is remounted read-only or the mount fails because it's busy...
594 * MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for kernels as low as
595 * 2.6.32...
596 */
597 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL },
598 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
599 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys/net", "%r/proc/tty", NULL, MS_BIND, NULL },
600 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys", "%r/proc/sys", NULL, MS_BIND, NULL },
601 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL },
602 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/tty", "%r/proc/sys/net", NULL, MS_MOVE, NULL },
603 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL, MS_BIND, NULL },
604 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sysrq-trigger", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL },
605 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_RW, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL },
606 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RW, "sysfs", "%r/sys", "sysfs", 0, NULL },
607 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RO, "sysfs", "%r/sys", "sysfs", MS_RDONLY, NULL },
608 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys", "sysfs", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL },
609 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys", "%r/sys", NULL, MS_BIND, NULL },
610 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, NULL, "%r/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL },
611 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL },
612 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys/devices/virtual/net/devices/virtual/net", "%r/sys/devices/virtual/net", NULL, MS_BIND, NULL },
613 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, NULL, "%r/sys/devices/virtual/net", NULL, MS_REMOUNT|MS_BIND|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL },
614 { 0, 0, NULL, NULL, NULL, 0, NULL }
615 };
616
617 for (i = 0; default_mounts[i].match_mask; i++) {
618 if ((flags & default_mounts[i].match_mask) == default_mounts[i].match_flag) {
619 char *source = NULL;
620 char *destination = NULL;
621 int saved_errno;
622 unsigned long mflags;
623
624 if (default_mounts[i].source) {
625 /* will act like strdup if %r is not present */
626 source = lxc_string_replace("%r", conf->rootfs.path ? conf->rootfs.mount : "", default_mounts[i].source);
627 if (!source) {
628 SYSERROR("memory allocation error");
629 return -1;
630 }
631 }
632 if (!default_mounts[i].destination) {
633 ERROR("BUG: auto mounts destination %d was NULL", i);
634 free(source);
635 return -1;
636 }
637 /* will act like strdup if %r is not present */
638 destination = lxc_string_replace("%r", conf->rootfs.path ? conf->rootfs.mount : "", default_mounts[i].destination);
639 if (!destination) {
640 saved_errno = errno;
641 SYSERROR("memory allocation error");
642 free(source);
643 errno = saved_errno;
644 return -1;
645 }
646 mflags = add_required_remount_flags(source, destination,
647 default_mounts[i].flags);
648 r = safe_mount(source, destination, default_mounts[i].fstype, mflags, default_mounts[i].options, conf->rootfs.path ? conf->rootfs.mount : NULL);
649 saved_errno = errno;
650 if (r < 0 && errno == ENOENT) {
651 INFO("Mount source or target for %s on %s doesn't exist. Skipping.", source, destination);
652 r = 0;
653 }
654 else if (r < 0)
655 SYSERROR("error mounting %s on %s flags %lu", source, destination, mflags);
656
657 free(source);
658 free(destination);
659 if (r < 0) {
660 errno = saved_errno;
661 return -1;
662 }
663 }
664 }
665
666 if (flags & LXC_AUTO_CGROUP_MASK) {
667 int cg_flags;
668
669 cg_flags = flags & LXC_AUTO_CGROUP_MASK;
670 /* If the type of cgroup mount was not specified, it depends on the
671 * container's capabilities as to what makes sense: if we have
672 * CAP_SYS_ADMIN, the read-only part can be remounted read-write
673 * anyway, so we may as well default to read-write; then the admin
674 * will not be given a false sense of security. (And if they really
675 * want mixed r/o r/w, then they can explicitly specify :mixed.)
676 * OTOH, if the container lacks CAP_SYS_ADMIN, do only default to
677 * :mixed, because then the container can't remount it read-write. */
678 if (cg_flags == LXC_AUTO_CGROUP_NOSPEC || cg_flags == LXC_AUTO_CGROUP_FULL_NOSPEC) {
679 int has_sys_admin = 0;
680
681 if (!lxc_list_empty(&conf->keepcaps))
682 has_sys_admin = in_caplist(CAP_SYS_ADMIN, &conf->keepcaps);
683 else
684 has_sys_admin = !in_caplist(CAP_SYS_ADMIN, &conf->caps);
685
686 if (cg_flags == LXC_AUTO_CGROUP_NOSPEC)
687 cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_RW : LXC_AUTO_CGROUP_MIXED;
688 else
689 cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_FULL_RW : LXC_AUTO_CGROUP_FULL_MIXED;
690 }
691
692 if (!cgroup_mount(conf->rootfs.path ? conf->rootfs.mount : "", handler, cg_flags)) {
693 SYSERROR("error mounting /sys/fs/cgroup");
694 return -1;
695 }
696 }
697
698 return 0;
699 }
700
701 static int setup_utsname(struct utsname *utsname)
702 {
703 if (!utsname)
704 return 0;
705
706 if (sethostname(utsname->nodename, strlen(utsname->nodename))) {
707 SYSERROR("failed to set the hostname to '%s'", utsname->nodename);
708 return -1;
709 }
710
711 INFO("'%s' hostname has been setup", utsname->nodename);
712
713 return 0;
714 }
715
716 struct dev_symlinks {
717 const char *oldpath;
718 const char *name;
719 };
720
721 static const struct dev_symlinks dev_symlinks[] = {
722 {"/proc/self/fd", "fd"},
723 {"/proc/self/fd/0", "stdin"},
724 {"/proc/self/fd/1", "stdout"},
725 {"/proc/self/fd/2", "stderr"},
726 };
727
728 static int lxc_setup_dev_symlinks(const struct lxc_rootfs *rootfs)
729 {
730 char path[MAXPATHLEN];
731 int ret,i;
732 struct stat s;
733
734
735 for (i = 0; i < sizeof(dev_symlinks) / sizeof(dev_symlinks[0]); i++) {
736 const struct dev_symlinks *d = &dev_symlinks[i];
737 ret = snprintf(path, sizeof(path), "%s/dev/%s", rootfs->path ? rootfs->mount : "", d->name);
738 if (ret < 0 || ret >= MAXPATHLEN)
739 return -1;
740
741 /*
742 * Stat the path first. If we don't get an error
743 * accept it as is and don't try to create it
744 */
745 if (!stat(path, &s)) {
746 continue;
747 }
748
749 ret = symlink(d->oldpath, path);
750
751 if (ret && errno != EEXIST) {
752 if ( errno == EROFS ) {
753 WARN("Warning: Read Only file system while creating %s", path);
754 } else {
755 SYSERROR("Error creating %s", path);
756 return -1;
757 }
758 }
759 }
760 return 0;
761 }
762
763 /* Build a space-separate list of ptys to pass to systemd. */
764 static bool append_ptyname(char **pp, char *name)
765 {
766 char *p;
767
768 if (!*pp) {
769 *pp = malloc(strlen(name) + strlen("container_ttys=") + 1);
770 if (!*pp)
771 return false;
772 sprintf(*pp, "container_ttys=%s", name);
773 return true;
774 }
775 p = realloc(*pp, strlen(*pp) + strlen(name) + 2);
776 if (!p)
777 return false;
778 *pp = p;
779 strcat(p, " ");
780 strcat(p, name);
781 return true;
782 }
783
784 static int lxc_setup_ttys(struct lxc_conf *conf)
785 {
786 int i, ret;
787 const struct lxc_tty_info *tty_info = &conf->tty_info;
788 char *ttydir = conf->ttydir;
789 char path[MAXPATHLEN], lxcpath[MAXPATHLEN];
790
791 if (!conf->rootfs.path)
792 return 0;
793
794 for (i = 0; i < tty_info->nbtty; i++) {
795 struct lxc_pty_info *pty_info = &tty_info->pty_info[i];
796
797 ret = snprintf(path, sizeof(path), "/dev/tty%d", i + 1);
798 if (ret < 0 || (size_t)ret >= sizeof(path))
799 return -1;
800
801 if (ttydir) {
802 /* create dev/lxc/tty%d" */
803 ret = snprintf(lxcpath, sizeof(lxcpath),
804 "/dev/%s/tty%d", ttydir, i + 1);
805 if (ret < 0 || (size_t)ret >= sizeof(lxcpath))
806 return -1;
807
808 ret = creat(lxcpath, 0660);
809 if (ret < 0 && errno != EEXIST) {
810 SYSERROR("Failed to create \"%s\"", lxcpath);
811 return -1;
812 }
813 if (ret >= 0)
814 close(ret);
815
816 ret = unlink(path);
817 if (ret < 0 && errno != ENOENT) {
818 SYSERROR("Failed to unlink \"%s\"", path);
819 return -1;
820 }
821
822 ret = mount(pty_info->name, lxcpath, "none", MS_BIND, 0);
823 if (ret < 0) {
824 WARN("Failed to bind mount \"%s\" onto \"%s\"",
825 pty_info->name, path);
826 continue;
827 }
828 DEBUG("bind mounted \"%s\" onto \"%s\"", pty_info->name,
829 path);
830
831 ret = snprintf(lxcpath, sizeof(lxcpath), "%s/tty%d",
832 ttydir, i + 1);
833 if (ret < 0 || (size_t)ret >= sizeof(lxcpath))
834 return -1;
835
836 ret = symlink(lxcpath, path);
837 if (ret < 0) {
838 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
839 path, lxcpath);
840 return -1;
841 }
842 } else {
843 /* If we populated /dev, then we need to create
844 * /dev/ttyN
845 */
846 ret = access(path, F_OK);
847 if (ret < 0) {
848 ret = creat(path, 0660);
849 if (ret < 0) {
850 SYSERROR("Failed to create \"%s\"", path);
851 /* this isn't fatal, continue */
852 } else {
853 close(ret);
854 }
855 }
856
857 ret = mount(pty_info->name, path, "none", MS_BIND, 0);
858 if (ret < 0) {
859 SYSERROR("Failed to mount '%s'->'%s'", pty_info->name, path);
860 continue;
861 }
862
863 DEBUG("Bind mounted \"%s\" onto \"%s\"", pty_info->name,
864 path);
865 }
866
867 if (!append_ptyname(&conf->pty_names, pty_info->name)) {
868 ERROR("Error setting up container_ttys string");
869 return -1;
870 }
871 }
872
873 INFO("Finished setting up %d /dev/tty<N> device(s)", tty_info->nbtty);
874 return 0;
875 }
876
877 int lxc_allocate_ttys(const char *name, struct lxc_conf *conf)
878 {
879 struct lxc_tty_info *tty_info = &conf->tty_info;
880 int i, ret;
881
882 /* no tty in the configuration */
883 if (!conf->tty)
884 return 0;
885
886 tty_info->pty_info = malloc(sizeof(*tty_info->pty_info) * conf->tty);
887 if (!tty_info->pty_info) {
888 SYSERROR("failed to allocate struct *pty_info");
889 return -ENOMEM;
890 }
891
892 for (i = 0; i < conf->tty; i++) {
893 struct lxc_pty_info *pty_info = &tty_info->pty_info[i];
894
895 process_lock();
896 ret = openpty(&pty_info->master, &pty_info->slave,
897 pty_info->name, NULL, NULL);
898 process_unlock();
899 if (ret) {
900 SYSERROR("failed to create pty device number %d", i);
901 tty_info->nbtty = i;
902 lxc_delete_tty(tty_info);
903 return -ENOTTY;
904 }
905
906 DEBUG("allocated pty \"%s\" with master fd %d and slave fd %d",
907 pty_info->name, pty_info->master, pty_info->slave);
908
909 /* Prevent leaking the file descriptors to the container */
910 ret = fcntl(pty_info->master, F_SETFD, FD_CLOEXEC);
911 if (ret < 0)
912 WARN("failed to set FD_CLOEXEC flag on master fd %d of "
913 "pty device \"%s\": %s",
914 pty_info->master, pty_info->name, strerror(errno));
915
916 ret = fcntl(pty_info->slave, F_SETFD, FD_CLOEXEC);
917 if (ret < 0)
918 WARN("failed to set FD_CLOEXEC flag on slave fd %d of "
919 "pty device \"%s\": %s",
920 pty_info->slave, pty_info->name, strerror(errno));
921
922 pty_info->busy = 0;
923 }
924
925 tty_info->nbtty = conf->tty;
926
927 INFO("finished allocating %d pts devices", conf->tty);
928 return 0;
929 }
930
931 void lxc_delete_tty(struct lxc_tty_info *tty_info)
932 {
933 int i;
934
935 for (i = 0; i < tty_info->nbtty; i++) {
936 struct lxc_pty_info *pty_info = &tty_info->pty_info[i];
937
938 close(pty_info->master);
939 close(pty_info->slave);
940 }
941
942 free(tty_info->pty_info);
943 tty_info->pty_info = NULL;
944 tty_info->nbtty = 0;
945 }
946
947 static int lxc_send_ttys_to_parent(struct lxc_handler *handler)
948 {
949 int i;
950 struct lxc_conf *conf = handler->conf;
951 struct lxc_tty_info *tty_info = &conf->tty_info;
952 int sock = handler->data_sock[0];
953 int ret = -1;
954
955 if (!conf->tty)
956 return 0;
957
958 for (i = 0; i < conf->tty; i++) {
959 int ttyfds[2];
960 struct lxc_pty_info *pty_info = &tty_info->pty_info[i];
961
962 ttyfds[0] = pty_info->master;
963 ttyfds[1] = pty_info->slave;
964
965 ret = lxc_abstract_unix_send_fds(sock, ttyfds, 2, NULL, 0);
966 if (ret < 0)
967 break;
968
969 TRACE("Send pty \"%s\" with master fd %d and slave fd %d to "
970 "parent", pty_info->name, pty_info->master, pty_info->slave);
971 }
972
973 if (ret < 0)
974 ERROR("Failed to send %d ttys to parent: %s", conf->tty,
975 strerror(errno));
976 else
977 TRACE("Sent %d ttys to parent", conf->tty);
978
979 return ret;
980 }
981
982 static int lxc_create_ttys(struct lxc_handler *handler)
983 {
984 int ret = -1;
985 struct lxc_conf *conf = handler->conf;
986
987 ret = lxc_allocate_ttys(handler->name, conf);
988 if (ret < 0) {
989 ERROR("Failed to allocate ttys");
990 goto on_error;
991 }
992
993 ret = lxc_send_ttys_to_parent(handler);
994 if (ret < 0) {
995 ERROR("Failed to send ttys to parent");
996 goto on_error;
997 }
998
999 if (!conf->is_execute) {
1000 ret = lxc_setup_ttys(conf);
1001 if (ret < 0) {
1002 ERROR("Failed to setup ttys");
1003 goto on_error;
1004 }
1005 }
1006
1007 if (conf->pty_names) {
1008 ret = setenv("container_ttys", conf->pty_names, 1);
1009 if (ret < 0)
1010 SYSERROR("Failed to set \"container_ttys=%s\"", conf->pty_names);
1011 }
1012
1013 ret = 0;
1014
1015 on_error:
1016 lxc_delete_tty(&conf->tty_info);
1017
1018 return ret;
1019 }
1020
1021 static int setup_rootfs_pivot_root(const char *rootfs)
1022 {
1023 int oldroot = -1, newroot = -1;
1024
1025 oldroot = open("/", O_DIRECTORY | O_RDONLY);
1026 if (oldroot < 0) {
1027 SYSERROR("Error opening old-/ for fchdir");
1028 return -1;
1029 }
1030 newroot = open(rootfs, O_DIRECTORY | O_RDONLY);
1031 if (newroot < 0) {
1032 SYSERROR("Error opening new-/ for fchdir");
1033 goto fail;
1034 }
1035
1036 /* change into new root fs */
1037 if (fchdir(newroot)) {
1038 SYSERROR("can't chdir to new rootfs '%s'", rootfs);
1039 goto fail;
1040 }
1041
1042 /* pivot_root into our new root fs */
1043 if (pivot_root(".", ".")) {
1044 SYSERROR("pivot_root syscall failed");
1045 goto fail;
1046 }
1047
1048 /*
1049 * at this point the old-root is mounted on top of our new-root
1050 * To unmounted it we must not be chdir'd into it, so escape back
1051 * to old-root
1052 */
1053 if (fchdir(oldroot) < 0) {
1054 SYSERROR("Error entering oldroot");
1055 goto fail;
1056 }
1057 if (umount2(".", MNT_DETACH) < 0) {
1058 SYSERROR("Error detaching old root");
1059 goto fail;
1060 }
1061
1062 if (fchdir(newroot) < 0) {
1063 SYSERROR("Error re-entering newroot");
1064 goto fail;
1065 }
1066
1067 close(oldroot);
1068 close(newroot);
1069
1070 DEBUG("pivot_root syscall to '%s' successful", rootfs);
1071
1072 return 0;
1073
1074 fail:
1075 if (oldroot != -1)
1076 close(oldroot);
1077 if (newroot != -1)
1078 close(newroot);
1079 return -1;
1080 }
1081
1082 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1083 * error, log it but don't fail yet.
1084 */
1085 static int mount_autodev(const char *name, const struct lxc_rootfs *rootfs,
1086 const char *lxcpath)
1087 {
1088 int ret;
1089 size_t clen;
1090 char *path;
1091
1092 INFO("Preparing \"/dev\"");
1093
1094 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1095 clen = (rootfs->path ? strlen(rootfs->mount) : 0) + 9;
1096 path = alloca(clen);
1097
1098 ret = snprintf(path, clen, "%s/dev", rootfs->path ? rootfs->mount : "");
1099 if (ret < 0 || (size_t)ret >= clen)
1100 return -1;
1101
1102 if (!dir_exists(path)) {
1103 WARN("\"/dev\" directory does not exist. Proceeding without "
1104 "autodev being set up");
1105 return 0;
1106 }
1107
1108 ret = safe_mount("none", path, "tmpfs", 0, "size=500000,mode=755",
1109 rootfs->path ? rootfs->mount : NULL);
1110 if (ret < 0) {
1111 SYSERROR("Failed to mount tmpfs on \"%s\"", path);
1112 return -1;
1113 }
1114 INFO("Mounted tmpfs on \"%s\"", path);
1115
1116 ret = snprintf(path, clen, "%s/dev/pts", rootfs->path ? rootfs->mount : "");
1117 if (ret < 0 || (size_t)ret >= clen)
1118 return -1;
1119
1120 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1121 * If not, then create it and exit if that fails...
1122 */
1123 if (!dir_exists(path)) {
1124 ret = mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
1125 if (ret < 0) {
1126 SYSERROR("Failed to create directory \"%s\"", path);
1127 return -1;
1128 }
1129 }
1130
1131 INFO("Prepared \"/dev\"");
1132 return 0;
1133 }
1134
1135 struct lxc_devs {
1136 const char *name;
1137 mode_t mode;
1138 int maj;
1139 int min;
1140 };
1141
1142 static const struct lxc_devs lxc_devs[] = {
1143 { "null", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 3 },
1144 { "zero", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 5 },
1145 { "full", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 7 },
1146 { "urandom", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 9 },
1147 { "random", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 8 },
1148 { "tty", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 5, 0 },
1149 };
1150
1151 static int lxc_fill_autodev(const struct lxc_rootfs *rootfs)
1152 {
1153 int ret;
1154 char path[MAXPATHLEN];
1155 int i;
1156 mode_t cmask;
1157
1158 ret = snprintf(path, MAXPATHLEN, "%s/dev",
1159 rootfs->path ? rootfs->mount : "");
1160 if (ret < 0 || ret >= MAXPATHLEN)
1161 return -1;
1162
1163 /* ignore, just don't try to fill in */
1164 if (!dir_exists(path))
1165 return 0;
1166
1167 INFO("Populating \"/dev\"");
1168
1169 cmask = umask(S_IXUSR | S_IXGRP | S_IXOTH);
1170 for (i = 0; i < sizeof(lxc_devs) / sizeof(lxc_devs[0]); i++) {
1171 const struct lxc_devs *d = &lxc_devs[i];
1172
1173 ret = snprintf(path, MAXPATHLEN, "%s/dev/%s",
1174 rootfs->path ? rootfs->mount : "", d->name);
1175 if (ret < 0 || ret >= MAXPATHLEN)
1176 return -1;
1177
1178 ret = mknod(path, d->mode, makedev(d->maj, d->min));
1179 if (ret < 0) {
1180 FILE *pathfile;
1181 char hostpath[MAXPATHLEN];
1182
1183 if (errno == EEXIST) {
1184 DEBUG("\"%s\" device already existed", path);
1185 continue;
1186 }
1187
1188 /* Unprivileged containers cannot create devices, so
1189 * bind mount the device from the host.
1190 */
1191 ret = snprintf(hostpath, MAXPATHLEN, "/dev/%s", d->name);
1192 if (ret < 0 || ret >= MAXPATHLEN)
1193 return -1;
1194
1195 pathfile = fopen(path, "wb");
1196 if (!pathfile) {
1197 SYSERROR("Failed to create file \"%s\"", path);
1198 return -1;
1199 }
1200 fclose(pathfile);
1201
1202 ret = safe_mount(hostpath, path, 0, MS_BIND, NULL,
1203 rootfs->path ? rootfs->mount : NULL);
1204 if (ret < 0) {
1205 SYSERROR("Failed to bind mount \"%s\" from "
1206 "host into container",
1207 d->name);
1208 return -1;
1209 }
1210 DEBUG("Bind mounted \"%s\" onto \"%s\"", hostpath,
1211 path);
1212 } else {
1213 DEBUG("Created device node \"%s\"", path);
1214 }
1215 }
1216 umask(cmask);
1217
1218 INFO("Populated \"/dev\"");
1219 return 0;
1220 }
1221
1222 static int lxc_setup_rootfs(struct lxc_conf *conf)
1223 {
1224 int ret;
1225 struct lxc_storage *bdev;
1226 const struct lxc_rootfs *rootfs;
1227
1228 rootfs = &conf->rootfs;
1229 if (!rootfs->path) {
1230 if (mount("", "/", NULL, MS_SLAVE | MS_REC, 0)) {
1231 SYSERROR("Failed to make / rslave.");
1232 return -1;
1233 }
1234 return 0;
1235 }
1236
1237 if (access(rootfs->mount, F_OK)) {
1238 SYSERROR("Failed to access to \"%s\". Check it is present.",
1239 rootfs->mount);
1240 return -1;
1241 }
1242
1243 bdev = storage_init(conf, rootfs->path, rootfs->mount, rootfs->options);
1244 if (!bdev) {
1245 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1246 rootfs->path, rootfs->mount,
1247 rootfs->options ? rootfs->options : "(null)");
1248 return -1;
1249 }
1250
1251 ret = bdev->ops->mount(bdev);
1252 storage_put(bdev);
1253 if (ret < 0) {
1254 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1255 rootfs->path, rootfs->mount,
1256 rootfs->options ? rootfs->options : "(null)");
1257 return -1;
1258 }
1259
1260 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\".",
1261 rootfs->path, rootfs->mount,
1262 rootfs->options ? rootfs->options : "(null)");
1263
1264 return 0;
1265 }
1266
1267 int prepare_ramfs_root(char *root)
1268 {
1269 char buf[LXC_LINELEN], *p;
1270 char nroot[PATH_MAX];
1271 FILE *f;
1272 int i;
1273 char *p2;
1274
1275 if (realpath(root, nroot) == NULL)
1276 return -errno;
1277
1278 if (chdir("/") == -1)
1279 return -errno;
1280
1281 /*
1282 * We could use here MS_MOVE, but in userns this mount is
1283 * locked and can't be moved.
1284 */
1285 if (mount(root, "/", NULL, MS_REC | MS_BIND, NULL) < 0) {
1286 SYSERROR("Failed to move %s into /", root);
1287 return -errno;
1288 }
1289
1290 if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) < 0) {
1291 SYSERROR("Failed to make . rprivate");
1292 return -errno;
1293 }
1294
1295 /*
1296 * The following code cleans up inhereted mounts which are not
1297 * required for CT.
1298 *
1299 * The mountinfo file shows not all mounts, if a few points have been
1300 * unmounted between read operations from the mountinfo. So we need to
1301 * read mountinfo a few times.
1302 *
1303 * This loop can be skipped if a container uses unserns, because all
1304 * inherited mounts are locked and we should live with all this trash.
1305 */
1306 while (1) {
1307 int progress = 0;
1308
1309 f = fopen("./proc/self/mountinfo", "r");
1310 if (!f) {
1311 SYSERROR("Unable to open /proc/self/mountinfo");
1312 return -1;
1313 }
1314 while (fgets(buf, LXC_LINELEN, f)) {
1315 for (p = buf, i=0; p && i < 4; i++)
1316 p = strchr(p+1, ' ');
1317 if (!p)
1318 continue;
1319 p2 = strchr(p+1, ' ');
1320 if (!p2)
1321 continue;
1322
1323 *p2 = '\0';
1324 *p = '.';
1325
1326 if (strcmp(p + 1, "/") == 0)
1327 continue;
1328 if (strcmp(p + 1, "/proc") == 0)
1329 continue;
1330
1331 if (umount2(p, MNT_DETACH) == 0)
1332 progress++;
1333 }
1334 fclose(f);
1335 if (!progress)
1336 break;
1337 }
1338
1339 /* This also can be skipped if a container uses unserns */
1340 umount2("./proc", MNT_DETACH);
1341
1342 /* It is weird, but chdir("..") moves us in a new root */
1343 if (chdir("..") == -1) {
1344 SYSERROR("Unable to change working directory");
1345 return -1;
1346 }
1347
1348 if (chroot(".") == -1) {
1349 SYSERROR("Unable to chroot");
1350 return -1;
1351 }
1352
1353 return 0;
1354 }
1355
1356 static int setup_pivot_root(const struct lxc_rootfs *rootfs)
1357 {
1358 if (!rootfs->path) {
1359 DEBUG("container does not have a rootfs, so not doing pivot root");
1360 return 0;
1361 }
1362
1363 if (detect_ramfs_rootfs()) {
1364 DEBUG("detected that container is on ramfs");
1365 if (prepare_ramfs_root(rootfs->mount)) {
1366 ERROR("failed to prepare minimal ramfs root");
1367 return -1;
1368 }
1369
1370 DEBUG("prepared ramfs root for container");
1371 return 0;
1372 }
1373
1374 if (setup_rootfs_pivot_root(rootfs->mount) < 0) {
1375 ERROR("failed to pivot root");
1376 return -1;
1377 }
1378
1379 DEBUG("finished pivot root");
1380 return 0;
1381 }
1382
1383 static int lxc_setup_devpts(int num_pts)
1384 {
1385 int ret;
1386 const char *default_devpts_mntopts = "newinstance,ptmxmode=0666,mode=0620,gid=5";
1387 char devpts_mntopts[256];
1388
1389 if (!num_pts) {
1390 DEBUG("no new devpts instance will be mounted since no pts "
1391 "devices are requested");
1392 return 0;
1393 }
1394
1395 ret = snprintf(devpts_mntopts, sizeof(devpts_mntopts), "%s,max=%d",
1396 default_devpts_mntopts, num_pts);
1397 if (ret < 0 || (size_t)ret >= sizeof(devpts_mntopts))
1398 return -1;
1399
1400 /* Unmount old devpts instance. */
1401 ret = access("/dev/pts/ptmx", F_OK);
1402 if (!ret) {
1403 ret = umount("/dev/pts");
1404 if (ret < 0) {
1405 SYSERROR("failed to unmount old devpts instance");
1406 return -1;
1407 }
1408 DEBUG("unmounted old /dev/pts instance");
1409 }
1410
1411 /* Create mountpoint for devpts instance. */
1412 ret = mkdir("/dev/pts", 0755);
1413 if (ret < 0 && errno != EEXIST) {
1414 SYSERROR("failed to create the \"/dev/pts\" directory");
1415 return -1;
1416 }
1417
1418 /* Mount new devpts instance. */
1419 ret = mount("devpts", "/dev/pts", "devpts", MS_MGC_VAL, devpts_mntopts);
1420 if (ret < 0) {
1421 SYSERROR("failed to mount new devpts instance");
1422 return -1;
1423 }
1424 DEBUG("mount new devpts instance with options \"%s\"", devpts_mntopts);
1425
1426 /* Remove any pre-existing /dev/ptmx file. */
1427 ret = access("/dev/ptmx", F_OK);
1428 if (!ret) {
1429 ret = remove("/dev/ptmx");
1430 if (ret < 0) {
1431 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1432 return -1;
1433 }
1434 DEBUG("removed existing \"/dev/ptmx\"");
1435 }
1436
1437 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1438 ret = open("/dev/ptmx", O_CREAT, 0666);
1439 if (ret < 0) {
1440 SYSERROR("failed to create dummy \"/dev/ptmx\" file as bind mount target");
1441 return -1;
1442 }
1443 close(ret);
1444 DEBUG("created dummy \"/dev/ptmx\" file as bind mount target");
1445
1446 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1447 ret = mount("/dev/pts/ptmx", "/dev/ptmx", NULL, MS_BIND, NULL);
1448 if (!ret) {
1449 DEBUG("bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1450 return 0;
1451 } else {
1452 /* Fallthrough and try to create a symlink. */
1453 ERROR("failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1454 }
1455
1456 /* Remove the dummy /dev/ptmx file we created above. */
1457 ret = remove("/dev/ptmx");
1458 if (ret < 0) {
1459 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1460 return -1;
1461 }
1462
1463 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1464 ret = symlink("/dev/pts/ptmx", "/dev/ptmx");
1465 if (ret < 0) {
1466 SYSERROR("failed to create symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1467 return -1;
1468 }
1469 DEBUG("created symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1470
1471 return 0;
1472 }
1473
1474 static int setup_personality(int persona)
1475 {
1476 #if HAVE_SYS_PERSONALITY_H
1477 if (persona == -1)
1478 return 0;
1479
1480 if (personality(persona) < 0) {
1481 SYSERROR("failed to set personality to '0x%x'", persona);
1482 return -1;
1483 }
1484
1485 INFO("set personality to '0x%x'", persona);
1486 #endif
1487
1488 return 0;
1489 }
1490
1491 static int lxc_setup_dev_console(const struct lxc_rootfs *rootfs,
1492 const struct lxc_console *console)
1493 {
1494 char path[MAXPATHLEN];
1495 int ret, fd;
1496
1497 if (console->path && !strcmp(console->path, "none"))
1498 return 0;
1499
1500 ret = snprintf(path, sizeof(path), "%s/dev/console", rootfs->mount);
1501 if (ret < 0 || (size_t)ret >= sizeof(path))
1502 return -1;
1503
1504 /* When we are asked to setup a console we remove any previous
1505 * /dev/console bind-mounts.
1506 */
1507 if (file_exists(path)) {
1508 ret = lxc_unstack_mountpoint(path, false);
1509 if (ret < 0) {
1510 ERROR("failed to unmount \"%s\": %s", path, strerror(errno));
1511 return -ret;
1512 } else {
1513 DEBUG("cleared all (%d) mounts from \"%s\"", ret, path);
1514 }
1515
1516 ret = unlink(path);
1517 if (ret < 0) {
1518 SYSERROR("error unlinking %s", path);
1519 return -errno;
1520 }
1521 }
1522
1523 /* For unprivileged containers autodev or automounts will already have
1524 * taken care of creating /dev/console.
1525 */
1526 fd = open(path, O_CREAT | O_EXCL, S_IXUSR | S_IXGRP | S_IXOTH);
1527 if (fd < 0) {
1528 if (errno != EEXIST) {
1529 SYSERROR("failed to create console");
1530 return -errno;
1531 }
1532 } else {
1533 close(fd);
1534 }
1535
1536 if (chmod(console->name, S_IXUSR | S_IXGRP | S_IXOTH)) {
1537 SYSERROR("failed to set mode '0%o' to '%s'", S_IXUSR | S_IXGRP | S_IXOTH, console->name);
1538 return -errno;
1539 }
1540
1541 if (safe_mount(console->name, path, "none", MS_BIND, 0, rootfs->mount) < 0) {
1542 ERROR("failed to mount '%s' on '%s'", console->name, path);
1543 return -1;
1544 }
1545
1546 DEBUG("mounted pts device \"%s\" onto \"%s\"", console->name, path);
1547 return 0;
1548 }
1549
1550 static int lxc_setup_ttydir_console(const struct lxc_rootfs *rootfs,
1551 const struct lxc_console *console,
1552 char *ttydir)
1553 {
1554 int ret;
1555 char path[MAXPATHLEN], lxcpath[MAXPATHLEN];
1556
1557 /* create rootfs/dev/<ttydir> directory */
1558 ret = snprintf(path, sizeof(path), "%s/dev/%s", rootfs->mount, ttydir);
1559 if (ret < 0 || (size_t)ret >= sizeof(path))
1560 return -1;
1561
1562 ret = mkdir(path, 0755);
1563 if (ret && errno != EEXIST) {
1564 SYSERROR("failed with errno %d to create %s", errno, path);
1565 return -errno;
1566 }
1567 DEBUG("Created directory for console and tty devices at \"%s\"", path);
1568
1569 ret = snprintf(lxcpath, sizeof(lxcpath), "%s/dev/%s/console", rootfs->mount, ttydir);
1570 if (ret < 0 || (size_t)ret >= sizeof(lxcpath))
1571 return -1;
1572
1573 ret = creat(lxcpath, 0660);
1574 if (ret == -1 && errno != EEXIST) {
1575 SYSERROR("error %d creating %s", errno, lxcpath);
1576 return -errno;
1577 }
1578 if (ret >= 0)
1579 close(ret);
1580
1581 ret = snprintf(path, sizeof(path), "%s/dev/console", rootfs->mount);
1582 if (ret < 0 || (size_t)ret >= sizeof(lxcpath))
1583 return -1;
1584
1585 /* When we are asked to setup a console we remove any previous
1586 * /dev/console bind-mounts.
1587 */
1588 if (console->path && !strcmp(console->path, "none")) {
1589 struct stat st;
1590 ret = stat(path, &st);
1591 if (ret < 0) {
1592 if (errno == ENOENT)
1593 return 0;
1594 SYSERROR("failed stat() \"%s\"", path);
1595 return -errno;
1596 }
1597
1598 /* /dev/console must be character device with major number 5 and
1599 * minor number 1. If not, give benefit of the doubt and assume
1600 * the user has mounted something else right there on purpose.
1601 */
1602 if (((st.st_mode & S_IFMT) != S_IFCHR) || major(st.st_rdev) != 5 || minor(st.st_rdev) != 1)
1603 return 0;
1604
1605 /* In case the user requested a bind-mount for /dev/console and
1606 * requests a ttydir we move the mount to the
1607 * /dev/<ttydir/console.
1608 * Note, we only move the uppermost mount and clear all other
1609 * mounts underneath for safety.
1610 * If it is a character device created via mknod() we simply
1611 * rename it.
1612 */
1613 ret = safe_mount(path, lxcpath, "none", MS_MOVE, NULL, rootfs->mount);
1614 if (ret < 0) {
1615 if (errno != EINVAL) {
1616 ERROR("failed to MS_MOVE \"%s\" to \"%s\": %s", path, lxcpath, strerror(errno));
1617 return -errno;
1618 }
1619 /* path was not a mountpoint */
1620 ret = rename(path, lxcpath);
1621 if (ret < 0) {
1622 ERROR("failed to rename \"%s\" to \"%s\": %s", path, lxcpath, strerror(errno));
1623 return -errno;
1624 }
1625 DEBUG("renamed \"%s\" to \"%s\"", path, lxcpath);
1626 } else {
1627 DEBUG("moved mount \"%s\" to \"%s\"", path, lxcpath);
1628 }
1629
1630 /* Clear all remaining bind-mounts. */
1631 ret = lxc_unstack_mountpoint(path, false);
1632 if (ret < 0) {
1633 ERROR("failed to unmount \"%s\": %s", path, strerror(errno));
1634 return -ret;
1635 } else {
1636 DEBUG("cleared all (%d) mounts from \"%s\"", ret, path);
1637 }
1638 } else {
1639 if (file_exists(path)) {
1640 ret = lxc_unstack_mountpoint(path, false);
1641 if (ret < 0) {
1642 ERROR("failed to unmount \"%s\": %s", path, strerror(errno));
1643 return -ret;
1644 } else {
1645 DEBUG("cleared all (%d) mounts from \"%s\"", ret, path);
1646 }
1647 }
1648
1649 if (safe_mount(console->name, lxcpath, "none", MS_BIND, 0, rootfs->mount) < 0) {
1650 ERROR("failed to mount '%s' on '%s'", console->name, lxcpath);
1651 return -1;
1652 }
1653 DEBUG("mounted \"%s\" onto \"%s\"", console->name, lxcpath);
1654 }
1655
1656 /* create symlink from rootfs /dev/console to '<ttydir>/console' */
1657 ret = snprintf(lxcpath, sizeof(lxcpath), "%s/console", ttydir);
1658 if (ret < 0 || (size_t)ret >= sizeof(lxcpath))
1659 return -1;
1660
1661 ret = unlink(path);
1662 if (ret && errno != ENOENT) {
1663 SYSERROR("error unlinking %s", path);
1664 return -errno;
1665 }
1666
1667 ret = symlink(lxcpath, path);
1668 if (ret < 0) {
1669 SYSERROR("failed to create symlink for console from \"%s\" to \"%s\"", lxcpath, path);
1670 return -1;
1671 }
1672
1673 DEBUG("console has been setup under \"%s\" and symlinked to \"%s\"", lxcpath, path);
1674 return 0;
1675 }
1676
1677 static int lxc_setup_console(const struct lxc_rootfs *rootfs,
1678 const struct lxc_console *console, char *ttydir)
1679 {
1680 /* We don't have a rootfs, /dev/console will be shared. */
1681 if (!rootfs->path) {
1682 DEBUG("/dev/console will be shared with the host");
1683 return 0;
1684 }
1685
1686 if (!ttydir)
1687 return lxc_setup_dev_console(rootfs, console);
1688
1689 return lxc_setup_ttydir_console(rootfs, console, ttydir);
1690 }
1691
1692 static void parse_mntopt(char *opt, unsigned long *flags, char **data)
1693 {
1694 struct mount_opt *mo;
1695
1696 /* If opt is found in mount_opt, set or clear flags.
1697 * Otherwise append it to data. */
1698
1699 for (mo = &mount_opt[0]; mo->name != NULL; mo++) {
1700 if (!strncmp(opt, mo->name, strlen(mo->name))) {
1701 if (mo->clear)
1702 *flags &= ~mo->flag;
1703 else
1704 *flags |= mo->flag;
1705 return;
1706 }
1707 }
1708
1709 if (strlen(*data))
1710 strcat(*data, ",");
1711 strcat(*data, opt);
1712 }
1713
1714 int parse_mntopts(const char *mntopts, unsigned long *mntflags,
1715 char **mntdata)
1716 {
1717 char *s, *data;
1718 char *p, *saveptr = NULL;
1719
1720 *mntdata = NULL;
1721 *mntflags = 0L;
1722
1723 if (!mntopts)
1724 return 0;
1725
1726 s = strdup(mntopts);
1727 if (!s) {
1728 SYSERROR("failed to allocate memory");
1729 return -1;
1730 }
1731
1732 data = malloc(strlen(s) + 1);
1733 if (!data) {
1734 SYSERROR("failed to allocate memory");
1735 free(s);
1736 return -1;
1737 }
1738 *data = 0;
1739
1740 for (p = strtok_r(s, ",", &saveptr); p != NULL;
1741 p = strtok_r(NULL, ",", &saveptr))
1742 parse_mntopt(p, mntflags, &data);
1743
1744 if (*data)
1745 *mntdata = data;
1746 else
1747 free(data);
1748 free(s);
1749
1750 return 0;
1751 }
1752
1753 static void null_endofword(char *word)
1754 {
1755 while (*word && *word != ' ' && *word != '\t')
1756 word++;
1757 *word = '\0';
1758 }
1759
1760 /*
1761 * skip @nfields spaces in @src
1762 */
1763 static char *get_field(char *src, int nfields)
1764 {
1765 char *p = src;
1766 int i;
1767
1768 for (i = 0; i < nfields; i++) {
1769 while (*p && *p != ' ' && *p != '\t')
1770 p++;
1771 if (!*p)
1772 break;
1773 p++;
1774 }
1775 return p;
1776 }
1777
1778 static int mount_entry(const char *fsname, const char *target,
1779 const char *fstype, unsigned long mountflags,
1780 const char *data, int optional, int dev,
1781 const char *rootfs)
1782 {
1783 int ret;
1784 #ifdef HAVE_STATVFS
1785 struct statvfs sb;
1786 #endif
1787
1788 ret = safe_mount(fsname, target, fstype, mountflags & ~MS_REMOUNT, data,
1789 rootfs);
1790 if (ret < 0) {
1791 if (optional) {
1792 INFO("Failed to mount \"%s\" on \"%s\" (optional): %s",
1793 fsname, target, strerror(errno));
1794 return 0;
1795 }
1796
1797 SYSERROR("Failed to mount \"%s\" on \"%s\"", fsname, target);
1798 return -1;
1799 }
1800
1801 if ((mountflags & MS_REMOUNT) || (mountflags & MS_BIND)) {
1802 unsigned long rqd_flags = 0;
1803
1804 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
1805 "options",
1806 fsname ? fsname : "(none)", target ? target : "(none)");
1807
1808 if (mountflags & MS_RDONLY)
1809 rqd_flags |= MS_RDONLY;
1810 #ifdef HAVE_STATVFS
1811 if (statvfs(fsname, &sb) == 0) {
1812 unsigned long required_flags = rqd_flags;
1813
1814 if (sb.f_flag & MS_NOSUID)
1815 required_flags |= MS_NOSUID;
1816
1817 if (sb.f_flag & MS_NODEV && !dev)
1818 required_flags |= MS_NODEV;
1819
1820 if (sb.f_flag & MS_RDONLY)
1821 required_flags |= MS_RDONLY;
1822
1823 if (sb.f_flag & MS_NOEXEC)
1824 required_flags |= MS_NOEXEC;
1825
1826 DEBUG("Flags for \"%s\" were %lu, required extra flags "
1827 "are %lu", fsname, sb.f_flag, required_flags);
1828
1829 /* If this was a bind mount request, and required_flags
1830 * does not have any flags which are not already in
1831 * mountflags, then skip the remount.
1832 */
1833 if (!(mountflags & MS_REMOUNT)) {
1834 if (!(required_flags & ~mountflags) &&
1835 rqd_flags == 0) {
1836 DEBUG("Mountflags already were %lu, "
1837 "skipping remount", mountflags);
1838 goto skipremount;
1839 }
1840 }
1841
1842 mountflags |= required_flags;
1843 }
1844 #endif
1845
1846 ret = mount(fsname, target, fstype, mountflags | MS_REMOUNT, data);
1847 if (ret < 0) {
1848 if (optional) {
1849 INFO("Failed to mount \"%s\" on \"%s\" "
1850 "(optional): %s", fsname, target,
1851 strerror(errno));
1852 return 0;
1853 }
1854
1855 SYSERROR("Failed to mount \"%s\" on \"%s\"", fsname, target);
1856 return -1;
1857 }
1858 }
1859
1860 #ifdef HAVE_STATVFS
1861 skipremount:
1862 #endif
1863 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"", fsname,
1864 target, fstype);
1865
1866 return 0;
1867 }
1868
1869 /* Remove "optional", "create=dir", and "create=file" from mntopt */
1870 static void cull_mntent_opt(struct mntent *mntent)
1871 {
1872 int i;
1873 char *list[] = {"create=dir", "create=file", "optional", NULL};
1874
1875 for (i = 0; list[i]; i++) {
1876 char *p, *p2;
1877
1878 p = strstr(mntent->mnt_opts, list[i]);
1879 if (!p)
1880 continue;
1881
1882 p2 = strchr(p, ',');
1883 if (!p2) {
1884 /* no more mntopts, so just chop it here */
1885 *p = '\0';
1886 continue;
1887 }
1888
1889 memmove(p, p2 + 1, strlen(p2 + 1) + 1);
1890 }
1891 }
1892
1893 static int mount_entry_create_dir_file(const struct mntent *mntent,
1894 const char *path,
1895 const struct lxc_rootfs *rootfs,
1896 const char *lxc_name,
1897 const char *lxc_path)
1898 {
1899 int ret = 0;
1900
1901 if (!strncmp(mntent->mnt_type, "overlay", 7))
1902 ret = ovl_mkdir(mntent, rootfs, lxc_name, lxc_path);
1903 else if (!strncmp(mntent->mnt_type, "aufs", 4))
1904 ret = aufs_mkdir(mntent, rootfs, lxc_name, lxc_path);
1905 if (ret < 0)
1906 return -1;
1907
1908 if (hasmntopt(mntent, "create=dir")) {
1909 ret = mkdir_p(path, 0755);
1910 if (ret < 0 && errno != EEXIST) {
1911 SYSERROR("Failed to create directory \"%s\"", path);
1912 return -1;
1913 }
1914 }
1915
1916 if (hasmntopt(mntent, "create=file") && access(path, F_OK)) {
1917 int fd;
1918 char *p1, *p2;
1919
1920 p1 = strdup(path);
1921 if (!p1)
1922 return -1;
1923
1924 p2 = dirname(p1);
1925
1926 ret = mkdir_p(p2, 0755);
1927 free(p1);
1928 if (ret < 0 && errno != EEXIST) {
1929 SYSERROR("Failed to create directory \"%s\"", path);
1930 return -1;
1931 }
1932
1933 fd = open(path, O_CREAT, 0644);
1934 if (fd < 0)
1935 return -1;
1936 close(fd);
1937 }
1938
1939 return 0;
1940 }
1941
1942 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
1943 * without a rootfs. */
1944 static inline int mount_entry_on_generic(struct mntent *mntent,
1945 const char *path,
1946 const struct lxc_rootfs *rootfs,
1947 const char *lxc_name,
1948 const char *lxc_path)
1949 {
1950 int ret;
1951 unsigned long mntflags;
1952 char *mntdata;
1953 bool dev, optional;
1954 char *rootfs_path = NULL;
1955
1956 optional = hasmntopt(mntent, "optional") != NULL;
1957 dev = hasmntopt(mntent, "dev") != NULL;
1958
1959 if (rootfs && rootfs->path)
1960 rootfs_path = rootfs->mount;
1961
1962 ret = mount_entry_create_dir_file(mntent, path, rootfs, lxc_name,
1963 lxc_path);
1964 if (ret < 0) {
1965 if (optional)
1966 return 0;
1967
1968 return -1;
1969 }
1970 cull_mntent_opt(mntent);
1971
1972 ret = parse_mntopts(mntent->mnt_opts, &mntflags, &mntdata);
1973 if (ret < 0)
1974 return -1;
1975
1976 ret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type, mntflags,
1977 mntdata, optional, dev, rootfs_path);
1978
1979 free(mntdata);
1980 return ret;
1981 }
1982
1983 static inline int mount_entry_on_systemfs(struct mntent *mntent)
1984 {
1985 int ret;
1986 char path[MAXPATHLEN];
1987
1988 /* For containers created without a rootfs all mounts are treated as
1989 * absolute paths starting at / on the host.
1990 */
1991 if (mntent->mnt_dir[0] != '/')
1992 ret = snprintf(path, sizeof(path), "/%s", mntent->mnt_dir);
1993 else
1994 ret = snprintf(path, sizeof(path), "%s", mntent->mnt_dir);
1995 if (ret < 0 || ret >= sizeof(path))
1996 return -1;
1997
1998 return mount_entry_on_generic(mntent, path, NULL, NULL, NULL);
1999 }
2000
2001 static int mount_entry_on_absolute_rootfs(struct mntent *mntent,
2002 const struct lxc_rootfs *rootfs,
2003 const char *lxc_name,
2004 const char *lxc_path)
2005 {
2006 int offset;
2007 char *aux;
2008 const char *lxcpath;
2009 char path[MAXPATHLEN];
2010 int ret = 0;
2011
2012 lxcpath = lxc_global_config_value("lxc.lxcpath");
2013 if (!lxcpath)
2014 return -1;
2015
2016 /* If rootfs->path is a blockdev path, allow container fstab to use
2017 * <lxcpath>/<name>/rootfs" as the target prefix.
2018 */
2019 ret = snprintf(path, MAXPATHLEN, "%s/%s/rootfs", lxcpath, lxc_name);
2020 if (ret < 0 || ret >= MAXPATHLEN)
2021 goto skipvarlib;
2022
2023 aux = strstr(mntent->mnt_dir, path);
2024 if (aux) {
2025 offset = strlen(path);
2026 goto skipabs;
2027 }
2028
2029 skipvarlib:
2030 aux = strstr(mntent->mnt_dir, rootfs->path);
2031 if (!aux) {
2032 WARN("Ignoring mount point \"%s\"", mntent->mnt_dir);
2033 return ret;
2034 }
2035 offset = strlen(rootfs->path);
2036
2037 skipabs:
2038 ret = snprintf(path, MAXPATHLEN, "%s/%s", rootfs->mount, aux + offset);
2039 if (ret < 0 || ret >= MAXPATHLEN)
2040 return -1;
2041
2042 return mount_entry_on_generic(mntent, path, rootfs, lxc_name, lxc_path);
2043 }
2044
2045 static int mount_entry_on_relative_rootfs(struct mntent *mntent,
2046 const struct lxc_rootfs *rootfs,
2047 const char *lxc_name,
2048 const char *lxc_path)
2049 {
2050 char path[MAXPATHLEN];
2051 int ret;
2052
2053 /* relative to root mount point */
2054 ret = snprintf(path, sizeof(path), "%s/%s", rootfs->mount, mntent->mnt_dir);
2055 if (ret < 0 || ret >= sizeof(path)) {
2056 ERROR("path name too long");
2057 return -1;
2058 }
2059
2060 return mount_entry_on_generic(mntent, path, rootfs, lxc_name, lxc_path);
2061 }
2062
2063 /* This logs a NOTICE() when a user specifies mounts that would conflict with
2064 * devices liblxc sets up automatically.
2065 */
2066 static void log_notice_on_conflict(const struct lxc_conf *conf, const char *src,
2067 const char *dest)
2068 {
2069 char *clean_mnt_fsname, *clean_mnt_dir, *tmp;
2070 bool needs_warning = false;
2071
2072 clean_mnt_fsname = lxc_deslashify(src);
2073 if (!clean_mnt_fsname)
2074 return;
2075
2076 clean_mnt_dir = lxc_deslashify(dest);
2077 if (!clean_mnt_dir) {
2078 free(clean_mnt_fsname);
2079 return;
2080 }
2081
2082 tmp = clean_mnt_dir;
2083 if (*tmp == '/')
2084 tmp++;
2085
2086 if (strncmp(src, "/dev", 4) || strncmp(tmp, "dev", 3)) {
2087 free(clean_mnt_dir);
2088 free(clean_mnt_fsname);
2089 return;
2090 }
2091
2092 if (!conf->autodev && !conf->pts && !conf->tty &&
2093 (!conf->console.path || !strcmp(conf->console.path, "none"))) {
2094 free(clean_mnt_dir);
2095 free(clean_mnt_fsname);
2096 return;
2097 }
2098
2099 if (!strcmp(tmp, "dev") && conf->autodev > 0)
2100 needs_warning = true;
2101 else if (!strcmp(tmp, "dev/pts") && (conf->autodev > 0 || conf->pts > 0))
2102 needs_warning = true;
2103 else if (!strcmp(tmp, "dev/ptmx") && (conf->autodev > 0 || conf->pts > 0))
2104 needs_warning = true;
2105 else if (!strcmp(tmp, "dev/pts/ptmx") && (conf->autodev > 0 || conf->pts > 0))
2106 needs_warning = true;
2107 else if (!strcmp(tmp, "dev/null") && conf->autodev > 0)
2108 needs_warning = true;
2109 else if (!strcmp(tmp, "dev/zero") && conf->autodev > 0)
2110 needs_warning = true;
2111 else if (!strcmp(tmp, "dev/full") && conf->autodev > 0)
2112 needs_warning = true;
2113 else if (!strcmp(tmp, "dev/urandom") && conf->autodev > 0)
2114 needs_warning = true;
2115 else if (!strcmp(tmp, "dev/random") && conf->autodev > 0)
2116 needs_warning = true;
2117 else if (!strcmp(tmp, "dev/tty") && conf->autodev > 0)
2118 needs_warning = true;
2119 else if (!strncmp(tmp, "dev/tty", 7) && (conf->autodev > 0 || conf->tty > 0))
2120 needs_warning = true;
2121
2122 if (needs_warning)
2123 NOTICE("Requesting to mount \"%s\" on \"%s\" while requesting "
2124 "automatic device setup under \"/dev\"",
2125 clean_mnt_fsname, clean_mnt_dir);
2126
2127 free(clean_mnt_dir);
2128 free(clean_mnt_fsname);
2129 }
2130
2131 static int mount_file_entries(const struct lxc_conf *conf,
2132 const struct lxc_rootfs *rootfs, FILE *file,
2133 const char *lxc_name, const char *lxc_path)
2134 {
2135 struct mntent mntent;
2136 char buf[4096];
2137 int ret = -1;
2138
2139 while (getmntent_r(file, &mntent, buf, sizeof(buf))) {
2140 log_notice_on_conflict(conf, mntent.mnt_fsname, mntent.mnt_dir);
2141
2142 if (!rootfs->path)
2143 ret = mount_entry_on_systemfs(&mntent);
2144 else if (mntent.mnt_dir[0] != '/')
2145 ret = mount_entry_on_relative_rootfs(&mntent, rootfs,
2146 lxc_name, lxc_path);
2147 else
2148 ret = mount_entry_on_absolute_rootfs(&mntent, rootfs,
2149 lxc_name, lxc_path);
2150 if (ret < 0)
2151 return -1;
2152 }
2153 ret = 0;
2154
2155 INFO("Set up mount entries");
2156 return ret;
2157 }
2158
2159 static int setup_mount(const struct lxc_conf *conf,
2160 const struct lxc_rootfs *rootfs, const char *fstab,
2161 const char *lxc_name, const char *lxc_path)
2162 {
2163 FILE *f;
2164 int ret;
2165
2166 if (!fstab)
2167 return 0;
2168
2169 f = setmntent(fstab, "r");
2170 if (!f) {
2171 SYSERROR("Failed to open \"%s\"", fstab);
2172 return -1;
2173 }
2174
2175 ret = mount_file_entries(conf, rootfs, f, lxc_name, lxc_path);
2176 if (ret < 0)
2177 ERROR("Failed to set up mount entries");
2178
2179 endmntent(f);
2180 return ret;
2181 }
2182
2183 FILE *make_anonymous_mount_file(struct lxc_list *mount)
2184 {
2185 int ret;
2186 char *mount_entry;
2187 struct lxc_list *iterator;
2188 FILE *f;
2189 int fd = -1;
2190
2191 fd = memfd_create("lxc_mount_file", MFD_CLOEXEC);
2192 if (fd < 0) {
2193 if (errno != ENOSYS)
2194 return NULL;
2195 f = tmpfile();
2196 TRACE("Created temporary mount file");
2197 } else {
2198 f = fdopen(fd, "r+");
2199 TRACE("Created anonymous mount file");
2200 }
2201
2202 if (!f) {
2203 SYSERROR("Could not create mount file");
2204 if (fd != -1)
2205 close(fd);
2206 return NULL;
2207 }
2208
2209 lxc_list_for_each(iterator, mount) {
2210 mount_entry = iterator->elem;
2211 ret = fprintf(f, "%s\n", mount_entry);
2212 if (ret < strlen(mount_entry))
2213 WARN("Could not write mount entry to mount file");
2214 }
2215
2216 ret = fseek(f, 0, SEEK_SET);
2217 if (ret < 0) {
2218 SYSERROR("Failed to seek mount file");
2219 fclose(f);
2220 return NULL;
2221 }
2222
2223 return f;
2224 }
2225
2226 static int setup_mount_entries(const struct lxc_conf *conf,
2227 const struct lxc_rootfs *rootfs,
2228 struct lxc_list *mount, const char *lxc_name,
2229 const char *lxc_path)
2230 {
2231 FILE *f;
2232 int ret;
2233
2234 f = make_anonymous_mount_file(mount);
2235 if (!f)
2236 return -1;
2237
2238 ret = mount_file_entries(conf, rootfs, f, lxc_name, lxc_path);
2239
2240 fclose(f);
2241 return ret;
2242 }
2243
2244 static int parse_cap(const char *cap)
2245 {
2246 char *ptr = NULL;
2247 size_t i;
2248 int capid = -1;
2249
2250 if (!strcmp(cap, "none"))
2251 return -2;
2252
2253 for (i = 0; i < sizeof(caps_opt)/sizeof(caps_opt[0]); i++) {
2254
2255 if (strcmp(cap, caps_opt[i].name))
2256 continue;
2257
2258 capid = caps_opt[i].value;
2259 break;
2260 }
2261
2262 if (capid < 0) {
2263 /* try to see if it's numeric, so the user may specify
2264 * capabilities that the running kernel knows about but
2265 * we don't */
2266 errno = 0;
2267 capid = strtol(cap, &ptr, 10);
2268 if (!ptr || *ptr != '\0' || errno != 0)
2269 /* not a valid number */
2270 capid = -1;
2271 else if (capid > lxc_caps_last_cap())
2272 /* we have a number but it's not a valid
2273 * capability */
2274 capid = -1;
2275 }
2276
2277 return capid;
2278 }
2279
2280 int in_caplist(int cap, struct lxc_list *caps)
2281 {
2282 struct lxc_list *iterator;
2283 int capid;
2284
2285 lxc_list_for_each(iterator, caps) {
2286 capid = parse_cap(iterator->elem);
2287 if (capid == cap)
2288 return 1;
2289 }
2290
2291 return 0;
2292 }
2293
2294 static int setup_caps(struct lxc_list *caps)
2295 {
2296 struct lxc_list *iterator;
2297 char *drop_entry;
2298 int capid;
2299
2300 lxc_list_for_each(iterator, caps) {
2301
2302 drop_entry = iterator->elem;
2303
2304 capid = parse_cap(drop_entry);
2305
2306 if (capid < 0) {
2307 ERROR("unknown capability %s", drop_entry);
2308 return -1;
2309 }
2310
2311 DEBUG("drop capability '%s' (%d)", drop_entry, capid);
2312
2313 if (prctl(PR_CAPBSET_DROP, capid, 0, 0, 0)) {
2314 SYSERROR("failed to remove %s capability", drop_entry);
2315 return -1;
2316 }
2317
2318 }
2319
2320 DEBUG("capabilities have been setup");
2321
2322 return 0;
2323 }
2324
2325 static int dropcaps_except(struct lxc_list *caps)
2326 {
2327 struct lxc_list *iterator;
2328 char *keep_entry;
2329 int i, capid;
2330 int numcaps = lxc_caps_last_cap() + 1;
2331 INFO("found %d capabilities", numcaps);
2332
2333 if (numcaps <= 0 || numcaps > 200)
2334 return -1;
2335
2336 /* caplist[i] is 1 if we keep capability i */
2337 int *caplist = alloca(numcaps * sizeof(int));
2338 memset(caplist, 0, numcaps * sizeof(int));
2339
2340 lxc_list_for_each(iterator, caps) {
2341
2342 keep_entry = iterator->elem;
2343
2344 capid = parse_cap(keep_entry);
2345
2346 if (capid == -2)
2347 continue;
2348
2349 if (capid < 0) {
2350 ERROR("unknown capability %s", keep_entry);
2351 return -1;
2352 }
2353
2354 DEBUG("keep capability '%s' (%d)", keep_entry, capid);
2355
2356 caplist[capid] = 1;
2357 }
2358 for (i=0; i<numcaps; i++) {
2359 if (caplist[i])
2360 continue;
2361 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0)) {
2362 SYSERROR("failed to remove capability %d", i);
2363 return -1;
2364 }
2365 }
2366
2367 DEBUG("capabilities have been setup");
2368
2369 return 0;
2370 }
2371
2372 static int parse_resource(const char *res) {
2373 size_t i;
2374 int resid = -1;
2375
2376 for (i = 0; i < sizeof(limit_opt)/sizeof(limit_opt[0]); ++i) {
2377 if (strcmp(res, limit_opt[i].name) == 0)
2378 return limit_opt[i].value;
2379 }
2380
2381 /* try to see if it's numeric, so the user may specify
2382 * resources that the running kernel knows about but
2383 * we don't */
2384 if (lxc_safe_int(res, &resid) == 0)
2385 return resid;
2386 return -1;
2387 }
2388
2389 int setup_resource_limits(struct lxc_list *limits, pid_t pid) {
2390 struct lxc_list *it;
2391 struct lxc_limit *lim;
2392 int resid;
2393
2394 lxc_list_for_each(it, limits) {
2395 lim = it->elem;
2396
2397 resid = parse_resource(lim->resource);
2398 if (resid < 0) {
2399 ERROR("unknown resource %s", lim->resource);
2400 return -1;
2401 }
2402
2403 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2404 if (prlimit(pid, resid, &lim->limit, NULL) != 0) {
2405 ERROR("failed to set limit %s: %s", lim->resource, strerror(errno));
2406 return -1;
2407 }
2408 #else
2409 ERROR("Cannot set limit %s as prlimit is missing", lim->resource);
2410 return -1;
2411 #endif
2412 }
2413 return 0;
2414 }
2415
2416 static char *default_rootfs_mount = LXCROOTFSMOUNT;
2417
2418 struct lxc_conf *lxc_conf_init(void)
2419 {
2420 struct lxc_conf *new;
2421 int i;
2422
2423 new = malloc(sizeof(*new));
2424 if (!new) {
2425 ERROR("lxc_conf_init : %s", strerror(errno));
2426 return NULL;
2427 }
2428 memset(new, 0, sizeof(*new));
2429
2430 new->loglevel = LXC_LOG_LEVEL_NOTSET;
2431 new->personality = -1;
2432 new->autodev = 1;
2433 new->console.log_path = NULL;
2434 new->console.log_fd = -1;
2435 new->console.log_size = 0;
2436 new->console.path = NULL;
2437 new->console.peer = -1;
2438 new->console.peerpty.busy = -1;
2439 new->console.peerpty.master = -1;
2440 new->console.peerpty.slave = -1;
2441 new->console.master = -1;
2442 new->console.slave = -1;
2443 new->console.name[0] = '\0';
2444 memset(&new->console.ringbuf, 0, sizeof(struct lxc_ringbuf));
2445 new->maincmd_fd = -1;
2446 new->nbd_idx = -1;
2447 new->rootfs.mount = strdup(default_rootfs_mount);
2448 if (!new->rootfs.mount) {
2449 ERROR("lxc_conf_init : %s", strerror(errno));
2450 free(new);
2451 return NULL;
2452 }
2453 new->logfd = -1;
2454 lxc_list_init(&new->cgroup);
2455 lxc_list_init(&new->network);
2456 lxc_list_init(&new->mount_list);
2457 lxc_list_init(&new->caps);
2458 lxc_list_init(&new->keepcaps);
2459 lxc_list_init(&new->id_map);
2460 lxc_list_init(&new->includes);
2461 lxc_list_init(&new->aliens);
2462 lxc_list_init(&new->environment);
2463 lxc_list_init(&new->limits);
2464 for (i = 0; i < NUM_LXC_HOOKS; i++)
2465 lxc_list_init(&new->hooks[i]);
2466 lxc_list_init(&new->groups);
2467 new->lsm_aa_profile = NULL;
2468 new->lsm_se_context = NULL;
2469 new->tmp_umount_proc = 0;
2470
2471 /* if running in a new user namespace, init and COMMAND
2472 * default to running as UID/GID 0 when using lxc-execute */
2473 new->init_uid = 0;
2474 new->init_gid = 0;
2475 memset(&new->cgroup_meta, 0, sizeof(struct lxc_cgroup));
2476 memset(&new->inherit_ns, 0, sizeof(char *) * LXC_NS_MAX);
2477
2478 return new;
2479 }
2480
2481 static int write_id_mapping(enum idtype idtype, pid_t pid, const char *buf,
2482 size_t buf_size)
2483 {
2484 char path[MAXPATHLEN];
2485 int fd, ret;
2486
2487 ret = snprintf(path, MAXPATHLEN, "/proc/%d/%cid_map", pid,
2488 idtype == ID_TYPE_UID ? 'u' : 'g');
2489 if (ret < 0 || ret >= MAXPATHLEN) {
2490 ERROR("failed to create path \"%s\"", path);
2491 return -E2BIG;
2492 }
2493
2494 fd = open(path, O_WRONLY);
2495 if (fd < 0) {
2496 SYSERROR("failed to open \"%s\"", path);
2497 return -1;
2498 }
2499
2500 errno = 0;
2501 ret = lxc_write_nointr(fd, buf, buf_size);
2502 if (ret != buf_size) {
2503 SYSERROR("failed to write %cid mapping to \"%s\"",
2504 idtype == ID_TYPE_UID ? 'u' : 'g', path);
2505 close(fd);
2506 return -1;
2507 }
2508 close(fd);
2509
2510 return 0;
2511 }
2512
2513 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2514 *
2515 * @return 1 if functional binary was found
2516 * @return 0 if binary exists but is lacking privilege
2517 * @return -ENOENT if binary does not exist
2518 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2519 *
2520 */
2521 static int idmaptool_on_path_and_privileged(const char *binary, cap_value_t cap)
2522 {
2523 char *path;
2524 int ret;
2525 struct stat st;
2526 int fret = 0;
2527
2528 if (cap != CAP_SETUID && cap != CAP_SETGID)
2529 return -EINVAL;
2530
2531 path = on_path(binary, NULL);
2532 if (!path)
2533 return -ENOENT;
2534
2535 ret = stat(path, &st);
2536 if (ret < 0) {
2537 fret = -errno;
2538 goto cleanup;
2539 }
2540
2541 /* Check if the binary is setuid. */
2542 if (st.st_mode & S_ISUID) {
2543 DEBUG("The binary \"%s\" does have the setuid bit set.", path);
2544 fret = 1;
2545 goto cleanup;
2546 }
2547
2548 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2549 /* Check if it has the CAP_SETUID capability. */
2550 if ((cap & CAP_SETUID) &&
2551 lxc_file_cap_is_set(path, CAP_SETUID, CAP_EFFECTIVE) &&
2552 lxc_file_cap_is_set(path, CAP_SETUID, CAP_PERMITTED)) {
2553 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2554 "and CAP_PERMITTED sets.", path);
2555 fret = 1;
2556 goto cleanup;
2557 }
2558
2559 /* Check if it has the CAP_SETGID capability. */
2560 if ((cap & CAP_SETGID) &&
2561 lxc_file_cap_is_set(path, CAP_SETGID, CAP_EFFECTIVE) &&
2562 lxc_file_cap_is_set(path, CAP_SETGID, CAP_PERMITTED)) {
2563 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2564 "and CAP_PERMITTED sets.", path);
2565 fret = 1;
2566 goto cleanup;
2567 }
2568 #else
2569 /* If we cannot check for file capabilities we need to give the benefit
2570 * of the doubt. Otherwise we might fail even though all the necessary
2571 * file capabilities are set.
2572 */
2573 DEBUG("Cannot check for file capabilites as full capability support is "
2574 "missing. Manual intervention needed.");
2575 fret = 1;
2576 #endif
2577
2578 cleanup:
2579 free(path);
2580 return fret;
2581 }
2582
2583 int lxc_map_ids_exec_wrapper(void *args)
2584 {
2585 execl("/bin/sh", "sh", "-c", (char *)args, (char *)NULL);
2586 return -1;
2587 }
2588
2589 int lxc_map_ids(struct lxc_list *idmap, pid_t pid)
2590 {
2591 struct id_map *map;
2592 struct lxc_list *iterator;
2593 enum idtype type;
2594 char u_or_g;
2595 char *pos;
2596 int fill, left;
2597 char cmd_output[MAXPATHLEN];
2598 /* strlen("new@idmap") = 9
2599 * +
2600 * strlen(" ") = 1
2601 * +
2602 * LXC_NUMSTRLEN64
2603 * +
2604 * strlen(" ") = 1
2605 *
2606 * We add some additional space to make sure that we really have
2607 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2608 */
2609 char mapbuf[9 + 1 + LXC_NUMSTRLEN64 + 1 + LXC_IDMAPLEN] = {0};
2610 int ret = 0, uidmap = 0, gidmap = 0;
2611 bool use_shadow = false, had_entry = false;
2612
2613 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2614 * ranges, then insist that root also reserve ranges in subuid. This
2615 * will protected it by preventing another user from being handed the
2616 * range by shadow.
2617 */
2618 uidmap = idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID);
2619 if (uidmap == -ENOENT)
2620 WARN("newuidmap binary is missing");
2621 else if (!uidmap)
2622 WARN("newuidmap is lacking necessary privileges");
2623
2624 gidmap = idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID);
2625 if (gidmap == -ENOENT)
2626 WARN("newgidmap binary is missing");
2627 else if (!gidmap)
2628 WARN("newgidmap is lacking necessary privileges");
2629
2630 if (uidmap > 0 && gidmap > 0) {
2631 DEBUG("Functional newuidmap and newgidmap binary found.");
2632 use_shadow = true;
2633 } else {
2634 /* In case unprivileged users run application containers via
2635 * execute() or a start*() there are valid cases where they may
2636 * only want to map their own {g,u}id. Let's not block them from
2637 * doing so by requiring geteuid() == 0.
2638 */
2639 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2640 "write directly with euid %d.", geteuid());
2641 }
2642
2643 for (type = ID_TYPE_UID, u_or_g = 'u'; type <= ID_TYPE_GID;
2644 type++, u_or_g = 'g') {
2645 pos = mapbuf;
2646
2647 if (use_shadow)
2648 pos += sprintf(mapbuf, "new%cidmap %d", u_or_g, pid);
2649
2650 lxc_list_for_each(iterator, idmap) {
2651 map = iterator->elem;
2652 if (map->idtype != type)
2653 continue;
2654
2655 had_entry = true;
2656
2657 left = LXC_IDMAPLEN - (pos - mapbuf);
2658 fill = snprintf(pos, left, "%s%lu %lu %lu%s",
2659 use_shadow ? " " : "", map->nsid,
2660 map->hostid, map->range,
2661 use_shadow ? "" : "\n");
2662 if (fill <= 0 || fill >= left) {
2663 /* The kernel only takes <= 4k for writes to
2664 * /proc/<pid>/{g,u}id_map
2665 */
2666 SYSERROR("Too many %cid mappings defined", u_or_g);
2667 return -1;
2668 }
2669
2670 pos += fill;
2671 }
2672 if (!had_entry)
2673 continue;
2674
2675 /* Try to catch the ouput of new{g,u}idmap to make debugging
2676 * easier.
2677 */
2678 if (use_shadow) {
2679 ret = run_command(cmd_output, sizeof(cmd_output),
2680 lxc_map_ids_exec_wrapper,
2681 (void *)mapbuf);
2682 if (ret < 0) {
2683 ERROR("new%cidmap failed to write mapping \"%s\": %s",
2684 u_or_g, cmd_output, mapbuf);
2685 return -1;
2686 }
2687 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g, mapbuf);
2688 } else {
2689 ret = write_id_mapping(type, pid, mapbuf, pos - mapbuf);
2690 if (ret < 0) {
2691 ERROR("Failed to write mapping: %s", mapbuf);
2692 return -1;
2693 }
2694 TRACE("Wrote mapping \"%s\"", mapbuf);
2695 }
2696
2697 memset(mapbuf, 0, sizeof(mapbuf));
2698 }
2699
2700 return 0;
2701 }
2702
2703 /*
2704 * return the host uid/gid to which the container root is mapped in
2705 * *val.
2706 * Return true if id was found, false otherwise.
2707 */
2708 bool get_mapped_rootid(struct lxc_conf *conf, enum idtype idtype,
2709 unsigned long *val)
2710 {
2711 struct lxc_list *it;
2712 struct id_map *map;
2713
2714 lxc_list_for_each(it, &conf->id_map) {
2715 map = it->elem;
2716 if (map->idtype != idtype)
2717 continue;
2718 if (map->nsid != 0)
2719 continue;
2720 *val = map->hostid;
2721 return true;
2722 }
2723 return false;
2724 }
2725
2726 int mapped_hostid(unsigned id, struct lxc_conf *conf, enum idtype idtype)
2727 {
2728 struct lxc_list *it;
2729 struct id_map *map;
2730 lxc_list_for_each(it, &conf->id_map) {
2731 map = it->elem;
2732 if (map->idtype != idtype)
2733 continue;
2734 if (id >= map->hostid && id < map->hostid + map->range)
2735 return (id - map->hostid) + map->nsid;
2736 }
2737 return -1;
2738 }
2739
2740 int find_unmapped_nsid(struct lxc_conf *conf, enum idtype idtype)
2741 {
2742 struct lxc_list *it;
2743 struct id_map *map;
2744 unsigned int freeid = 0;
2745 again:
2746 lxc_list_for_each(it, &conf->id_map) {
2747 map = it->elem;
2748 if (map->idtype != idtype)
2749 continue;
2750 if (freeid >= map->nsid && freeid < map->nsid + map->range) {
2751 freeid = map->nsid + map->range;
2752 goto again;
2753 }
2754 }
2755 return freeid;
2756 }
2757
2758 int chown_mapped_root_exec_wrapper(void *args)
2759 {
2760 execvp("lxc-usernsexec", args);
2761 return -1;
2762 }
2763
2764 /*
2765 * chown_mapped_root: for an unprivileged user with uid/gid X to
2766 * chown a dir to subuid/subgid Y, he needs to run chown as root
2767 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
2768 * nsid Y is mapped to hostuid/hostgid X. That way, the container
2769 * root is privileged with respect to hostuid/hostgid X, allowing
2770 * him to do the chown.
2771 */
2772 int chown_mapped_root(char *path, struct lxc_conf *conf)
2773 {
2774 uid_t rootuid, rootgid;
2775 unsigned long val;
2776 int hostuid, hostgid, ret;
2777 struct stat sb;
2778 char map1[100], map2[100], map3[100], map4[100], map5[100];
2779 char ugid[100];
2780 char *args1[] = {"lxc-usernsexec",
2781 "-m", map1,
2782 "-m", map2,
2783 "-m", map3,
2784 "-m", map5,
2785 "--", "chown", ugid, path,
2786 NULL};
2787 char *args2[] = {"lxc-usernsexec",
2788 "-m", map1,
2789 "-m", map2,
2790 "-m", map3,
2791 "-m", map4,
2792 "-m", map5,
2793 "--", "chown", ugid, path,
2794 NULL};
2795 char cmd_output[MAXPATHLEN];
2796
2797 hostuid = geteuid();
2798 hostgid = getegid();
2799
2800 if (!get_mapped_rootid(conf, ID_TYPE_UID, &val)) {
2801 ERROR("No uid mapping for container root");
2802 return -1;
2803 }
2804 rootuid = (uid_t)val;
2805 if (!get_mapped_rootid(conf, ID_TYPE_GID, &val)) {
2806 ERROR("No gid mapping for container root");
2807 return -1;
2808 }
2809 rootgid = (gid_t)val;
2810
2811 if (hostuid == 0) {
2812 if (chown(path, rootuid, rootgid) < 0) {
2813 ERROR("Error chowning %s", path);
2814 return -1;
2815 }
2816 return 0;
2817 }
2818
2819 if (rootuid == hostuid) {
2820 /* nothing to do */
2821 INFO("Container root is our uid; no need to chown");
2822 return 0;
2823 }
2824
2825 /* save the current gid of "path" */
2826 if (stat(path, &sb) < 0) {
2827 ERROR("Error stat %s", path);
2828 return -1;
2829 }
2830
2831 /* Update the path argument in case this was overlayfs. */
2832 args1[sizeof(args1) / sizeof(args1[0]) - 2] = path;
2833 args2[sizeof(args2) / sizeof(args2[0]) - 2] = path;
2834
2835 /*
2836 * A file has to be group-owned by a gid mapped into the
2837 * container, or the container won't be privileged over it.
2838 */
2839 DEBUG("trying to chown \"%s\" to %d", path, hostgid);
2840 if (sb.st_uid == hostuid &&
2841 mapped_hostid(sb.st_gid, conf, ID_TYPE_GID) < 0 &&
2842 chown(path, -1, hostgid) < 0) {
2843 ERROR("Failed chgrping %s", path);
2844 return -1;
2845 }
2846
2847 /* "u:0:rootuid:1" */
2848 ret = snprintf(map1, 100, "u:0:%d:1", rootuid);
2849 if (ret < 0 || ret >= 100) {
2850 ERROR("Error uid printing map string");
2851 return -1;
2852 }
2853
2854 /* "u:hostuid:hostuid:1" */
2855 ret = snprintf(map2, 100, "u:%d:%d:1", hostuid, hostuid);
2856 if (ret < 0 || ret >= 100) {
2857 ERROR("Error uid printing map string");
2858 return -1;
2859 }
2860
2861 /* "g:0:rootgid:1" */
2862 ret = snprintf(map3, 100, "g:0:%d:1", rootgid);
2863 if (ret < 0 || ret >= 100) {
2864 ERROR("Error gid printing map string");
2865 return -1;
2866 }
2867
2868 /* "g:pathgid:rootgid+pathgid:1" */
2869 ret = snprintf(map4, 100, "g:%d:%d:1", (gid_t)sb.st_gid,
2870 rootgid + (gid_t)sb.st_gid);
2871 if (ret < 0 || ret >= 100) {
2872 ERROR("Error gid printing map string");
2873 return -1;
2874 }
2875
2876 /* "g:hostgid:hostgid:1" */
2877 ret = snprintf(map5, 100, "g:%d:%d:1", hostgid, hostgid);
2878 if (ret < 0 || ret >= 100) {
2879 ERROR("Error gid printing map string");
2880 return -1;
2881 }
2882
2883 /* "0:pathgid" (chown) */
2884 ret = snprintf(ugid, 100, "0:%d", (gid_t)sb.st_gid);
2885 if (ret < 0 || ret >= 100) {
2886 ERROR("Error owner printing format string for chown");
2887 return -1;
2888 }
2889
2890 if (hostgid == sb.st_gid)
2891 ret = run_command(cmd_output, sizeof(cmd_output),
2892 chown_mapped_root_exec_wrapper,
2893 (void *)args1);
2894 else
2895 ret = run_command(cmd_output, sizeof(cmd_output),
2896 chown_mapped_root_exec_wrapper,
2897 (void *)args2);
2898 if (ret < 0)
2899 ERROR("lxc-usernsexec failed: %s", cmd_output);
2900
2901 return ret;
2902 }
2903
2904 int lxc_ttys_shift_ids(struct lxc_conf *c)
2905 {
2906 if (lxc_list_empty(&c->id_map))
2907 return 0;
2908
2909 if (!strcmp(c->console.name, ""))
2910 return 0;
2911
2912 if (chown_mapped_root(c->console.name, c) < 0) {
2913 ERROR("failed to chown console \"%s\"", c->console.name);
2914 return -1;
2915 }
2916
2917 TRACE("chowned console \"%s\"", c->console.name);
2918
2919 return 0;
2920 }
2921
2922 /* NOTE: Must not be called from inside the container namespace! */
2923 int lxc_create_tmp_proc_mount(struct lxc_conf *conf)
2924 {
2925 int mounted;
2926
2927 mounted = lxc_mount_proc_if_needed(conf->rootfs.path ? conf->rootfs.mount : "");
2928 if (mounted == -1) {
2929 SYSERROR("failed to mount /proc in the container");
2930 /* continue only if there is no rootfs */
2931 if (conf->rootfs.path)
2932 return -1;
2933 } else if (mounted == 1) {
2934 conf->tmp_umount_proc = 1;
2935 }
2936
2937 return 0;
2938 }
2939
2940 void tmp_proc_unmount(struct lxc_conf *lxc_conf)
2941 {
2942 if (lxc_conf->tmp_umount_proc == 1) {
2943 umount("/proc");
2944 lxc_conf->tmp_umount_proc = 0;
2945 }
2946 }
2947
2948 void remount_all_slave(void)
2949 {
2950 /* walk /proc/mounts and change any shared entries to slave */
2951 FILE *f = fopen("/proc/self/mountinfo", "r");
2952 char *line = NULL;
2953 size_t len = 0;
2954
2955 if (!f) {
2956 SYSERROR("Failed to open /proc/self/mountinfo to mark all shared");
2957 ERROR("Continuing container startup...");
2958 return;
2959 }
2960
2961 while (getline(&line, &len, f) != -1) {
2962 char *target, *opts;
2963 target = get_field(line, 4);
2964 if (!target)
2965 continue;
2966 opts = get_field(target, 2);
2967 if (!opts)
2968 continue;
2969 null_endofword(opts);
2970 if (!strstr(opts, "shared"))
2971 continue;
2972 null_endofword(target);
2973 if (mount(NULL, target, NULL, MS_SLAVE, NULL)) {
2974 SYSERROR("Failed to make %s rslave", target);
2975 ERROR("Continuing...");
2976 }
2977 }
2978 fclose(f);
2979 free(line);
2980 }
2981
2982 void lxc_execute_bind_init(struct lxc_conf *conf)
2983 {
2984 int ret;
2985 char path[PATH_MAX], destpath[PATH_MAX], *p;
2986
2987 /* If init exists in the container, don't bind mount a static one */
2988 p = choose_init(conf->rootfs.mount);
2989 if (p) {
2990 free(p);
2991 return;
2992 }
2993
2994 ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static");
2995 if (ret < 0 || ret >= PATH_MAX) {
2996 WARN("Path name too long searching for lxc.init.static");
2997 return;
2998 }
2999
3000 if (!file_exists(path)) {
3001 INFO("%s does not exist on host", path);
3002 return;
3003 }
3004
3005 ret = snprintf(destpath, PATH_MAX, "%s%s", conf->rootfs.mount, "/init.lxc.static");
3006 if (ret < 0 || ret >= PATH_MAX) {
3007 WARN("Path name too long for container's lxc.init.static");
3008 return;
3009 }
3010
3011 if (!file_exists(destpath)) {
3012 FILE * pathfile = fopen(destpath, "wb");
3013 if (!pathfile) {
3014 SYSERROR("Failed to create mount target '%s'", destpath);
3015 return;
3016 }
3017 fclose(pathfile);
3018 }
3019
3020 ret = safe_mount(path, destpath, "none", MS_BIND, NULL, conf->rootfs.mount);
3021 if (ret < 0)
3022 SYSERROR("Failed to bind lxc.init.static into container");
3023 INFO("lxc.init.static bound into container at %s", path);
3024 }
3025
3026 /*
3027 * This does the work of remounting / if it is shared, calling the
3028 * container pre-mount hooks, and mounting the rootfs.
3029 */
3030 int do_rootfs_setup(struct lxc_conf *conf, const char *name, const char *lxcpath)
3031 {
3032 if (conf->rootfs_setup) {
3033 /*
3034 * rootfs was set up in another namespace. bind-mount it
3035 * to give us a mount in our own ns so we can pivot_root to it
3036 */
3037 const char *path = conf->rootfs.mount;
3038 if (mount(path, path, "rootfs", MS_BIND, NULL) < 0) {
3039 ERROR("Failed to bind-mount container / onto itself");
3040 return -1;
3041 }
3042 return 0;
3043 }
3044
3045 remount_all_slave();
3046
3047 if (run_lxc_hooks(name, "pre-mount", conf, lxcpath, NULL)) {
3048 ERROR("failed to run pre-mount hooks for container '%s'.", name);
3049 return -1;
3050 }
3051
3052 if (lxc_setup_rootfs(conf)) {
3053 ERROR("failed to setup rootfs for '%s'", name);
3054 return -1;
3055 }
3056
3057 conf->rootfs_setup = true;
3058 return 0;
3059 }
3060
3061 static bool verify_start_hooks(struct lxc_conf *conf)
3062 {
3063 struct lxc_list *it;
3064 char path[MAXPATHLEN];
3065 lxc_list_for_each(it, &conf->hooks[LXCHOOK_START]) {
3066 char *hookname = it->elem;
3067 struct stat st;
3068 int ret;
3069
3070 ret = snprintf(path, MAXPATHLEN, "%s%s",
3071 conf->rootfs.path ? conf->rootfs.mount : "", hookname);
3072 if (ret < 0 || ret >= MAXPATHLEN)
3073 return false;
3074 ret = stat(path, &st);
3075 if (ret) {
3076 SYSERROR("Start hook %s not found in container",
3077 hookname);
3078 return false;
3079 }
3080 return true;
3081 }
3082
3083 return true;
3084 }
3085
3086 int lxc_setup(struct lxc_handler *handler)
3087 {
3088 int ret;
3089 const char *name = handler->name;
3090 struct lxc_conf *lxc_conf = handler->conf;
3091 const char *lxcpath = handler->lxcpath;
3092
3093 if (do_rootfs_setup(lxc_conf, name, lxcpath) < 0) {
3094 ERROR("Error setting up rootfs mount after spawn");
3095 return -1;
3096 }
3097
3098 if (handler->nsfd[LXC_NS_UTS] == -1) {
3099 if (setup_utsname(lxc_conf->utsname)) {
3100 ERROR("failed to setup the utsname for '%s'", name);
3101 return -1;
3102 }
3103 }
3104
3105 if (lxc_setup_network_in_child_namespaces(lxc_conf, &lxc_conf->network)) {
3106 ERROR("failed to setup the network for '%s'", name);
3107 return -1;
3108 }
3109
3110 if (lxc_network_send_name_and_ifindex_to_parent(handler) < 0) {
3111 ERROR("Failed to network device names and ifindices to parent");
3112 return -1;
3113 }
3114
3115 if (lxc_conf->autodev > 0) {
3116 if (mount_autodev(name, &lxc_conf->rootfs, lxcpath)) {
3117 ERROR("failed to mount /dev in the container");
3118 return -1;
3119 }
3120 }
3121
3122 /* do automatic mounts (mainly /proc and /sys), but exclude
3123 * those that need to wait until other stuff has finished
3124 */
3125 if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK, handler) < 0) {
3126 ERROR("failed to setup the automatic mounts for '%s'", name);
3127 return -1;
3128 }
3129
3130 if (setup_mount(lxc_conf, &lxc_conf->rootfs, lxc_conf->fstab, name, lxcpath)) {
3131 ERROR("failed to setup the mounts for '%s'", name);
3132 return -1;
3133 }
3134
3135 if (!lxc_list_empty(&lxc_conf->mount_list) && setup_mount_entries(lxc_conf, &lxc_conf->rootfs, &lxc_conf->mount_list, name, lxcpath)) {
3136 ERROR("failed to setup the mount entries for '%s'", name);
3137 return -1;
3138 }
3139
3140 /* Make sure any start hooks are in the container */
3141 if (!verify_start_hooks(lxc_conf))
3142 return -1;
3143
3144 if (lxc_conf->is_execute)
3145 lxc_execute_bind_init(lxc_conf);
3146
3147 /* now mount only cgroup, if wanted;
3148 * before, /sys could not have been mounted
3149 * (is either mounted automatically or via fstab entries)
3150 */
3151 if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK, handler) < 0) {
3152 ERROR("failed to setup the automatic mounts for '%s'", name);
3153 return -1;
3154 }
3155
3156 if (run_lxc_hooks(name, "mount", lxc_conf, lxcpath, NULL)) {
3157 ERROR("failed to run mount hooks for container '%s'.", name);
3158 return -1;
3159 }
3160
3161 if (lxc_conf->autodev > 0) {
3162 if (run_lxc_hooks(name, "autodev", lxc_conf, lxcpath, NULL)) {
3163 ERROR("failed to run autodev hooks for container '%s'.", name);
3164 return -1;
3165 }
3166
3167 if (lxc_fill_autodev(&lxc_conf->rootfs)) {
3168 ERROR("failed to populate /dev in the container");
3169 return -1;
3170 }
3171 }
3172
3173 ret = lxc_setup_console(&lxc_conf->rootfs, &lxc_conf->console,
3174 lxc_conf->ttydir);
3175 if (ret < 0) {
3176 ERROR("Failed to setup console");
3177 return -1;
3178 }
3179
3180 ret = lxc_setup_dev_symlinks(&lxc_conf->rootfs);
3181 if (ret < 0) {
3182 ERROR("Failed to setup /dev symlinks");
3183 return -1;
3184 }
3185
3186 /* mount /proc if it's not already there */
3187 if (lxc_create_tmp_proc_mount(lxc_conf) < 0) {
3188 ERROR("failed to LSM mount proc for '%s'", name);
3189 return -1;
3190 }
3191
3192 if (setup_pivot_root(&lxc_conf->rootfs)) {
3193 ERROR("failed to set rootfs for '%s'", name);
3194 return -1;
3195 }
3196
3197 if (lxc_setup_devpts(lxc_conf->pts)) {
3198 ERROR("failed to setup the new pts instance");
3199 return -1;
3200 }
3201
3202 ret = lxc_create_ttys(handler);
3203 if (ret < 0)
3204 return -1;
3205
3206 if (setup_personality(lxc_conf->personality)) {
3207 ERROR("failed to setup personality");
3208 return -1;
3209 }
3210
3211 if (!lxc_list_empty(&lxc_conf->keepcaps)) {
3212 if (!lxc_list_empty(&lxc_conf->caps)) {
3213 ERROR("Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both.");
3214 return -1;
3215 }
3216 if (dropcaps_except(&lxc_conf->keepcaps)) {
3217 ERROR("failed to keep requested caps");
3218 return -1;
3219 }
3220 } else if (setup_caps(&lxc_conf->caps)) {
3221 ERROR("failed to drop capabilities");
3222 return -1;
3223 }
3224
3225 NOTICE("Container \"%s\" is set up", name);
3226
3227 return 0;
3228 }
3229
3230 int run_lxc_hooks(const char *name, char *hook, struct lxc_conf *conf,
3231 const char *lxcpath, char *argv[])
3232 {
3233 int which = -1;
3234 struct lxc_list *it;
3235
3236 if (strcmp(hook, "pre-start") == 0)
3237 which = LXCHOOK_PRESTART;
3238 else if (strcmp(hook, "start-host") == 0)
3239 which = LXCHOOK_START_HOST;
3240 else if (strcmp(hook, "pre-mount") == 0)
3241 which = LXCHOOK_PREMOUNT;
3242 else if (strcmp(hook, "mount") == 0)
3243 which = LXCHOOK_MOUNT;
3244 else if (strcmp(hook, "autodev") == 0)
3245 which = LXCHOOK_AUTODEV;
3246 else if (strcmp(hook, "start") == 0)
3247 which = LXCHOOK_START;
3248 else if (strcmp(hook, "stop") == 0)
3249 which = LXCHOOK_STOP;
3250 else if (strcmp(hook, "post-stop") == 0)
3251 which = LXCHOOK_POSTSTOP;
3252 else if (strcmp(hook, "clone") == 0)
3253 which = LXCHOOK_CLONE;
3254 else if (strcmp(hook, "destroy") == 0)
3255 which = LXCHOOK_DESTROY;
3256 else
3257 return -1;
3258 lxc_list_for_each(it, &conf->hooks[which]) {
3259 int ret;
3260 char *hookname = it->elem;
3261 ret = run_script_argv(name, "lxc", hookname, hook, lxcpath, argv);
3262 if (ret)
3263 return ret;
3264 }
3265 return 0;
3266 }
3267
3268 int lxc_clear_config_caps(struct lxc_conf *c)
3269 {
3270 struct lxc_list *it, *next;
3271
3272 lxc_list_for_each_safe(it, &c->caps, next) {
3273 lxc_list_del(it);
3274 free(it->elem);
3275 free(it);
3276 }
3277 return 0;
3278 }
3279
3280 static int lxc_free_idmap(struct lxc_list *id_map) {
3281 struct lxc_list *it, *next;
3282
3283 lxc_list_for_each_safe(it, id_map, next) {
3284 lxc_list_del(it);
3285 free(it->elem);
3286 free(it);
3287 }
3288 return 0;
3289 }
3290
3291 int lxc_clear_idmaps(struct lxc_conf *c)
3292 {
3293 return lxc_free_idmap(&c->id_map);
3294 }
3295
3296 int lxc_clear_config_keepcaps(struct lxc_conf *c)
3297 {
3298 struct lxc_list *it,*next;
3299
3300 lxc_list_for_each_safe(it, &c->keepcaps, next) {
3301 lxc_list_del(it);
3302 free(it->elem);
3303 free(it);
3304 }
3305 return 0;
3306 }
3307
3308 int lxc_clear_cgroups(struct lxc_conf *c, const char *key)
3309 {
3310 struct lxc_list *it,*next;
3311 bool all = false;
3312 const char *k = NULL;
3313
3314 if (strcmp(key, "lxc.cgroup") == 0)
3315 all = true;
3316 else if (strncmp(key, "lxc.cgroup.", sizeof("lxc.cgroup.")-1) == 0)
3317 k = key + sizeof("lxc.cgroup.")-1;
3318 else
3319 return -1;
3320
3321 lxc_list_for_each_safe(it, &c->cgroup, next) {
3322 struct lxc_cgroup *cg = it->elem;
3323 if (!all && strcmp(cg->subsystem, k) != 0)
3324 continue;
3325 lxc_list_del(it);
3326 free(cg->subsystem);
3327 free(cg->value);
3328 free(cg);
3329 free(it);
3330 }
3331 return 0;
3332 }
3333
3334 int lxc_clear_limits(struct lxc_conf *c, const char *key)
3335 {
3336 struct lxc_list *it, *next;
3337 bool all = false;
3338 const char *k = NULL;
3339
3340 if (strcmp(key, "lxc.limit") == 0
3341 || strcmp(key, "lxc.prlimit"))
3342 all = true;
3343 else if (strncmp(key, "lxc.limit.", sizeof("lxc.limit.")-1) == 0)
3344 k = key + sizeof("lxc.limit.")-1;
3345 else if (strncmp(key, "lxc.prlimit.", sizeof("lxc.prlimit.")-1) == 0)
3346 k = key + sizeof("lxc.prlimit.")-1;
3347 else
3348 return -1;
3349
3350 lxc_list_for_each_safe(it, &c->limits, next) {
3351 struct lxc_limit *lim = it->elem;
3352 if (!all && strcmp(lim->resource, k) != 0)
3353 continue;
3354 lxc_list_del(it);
3355 free(lim->resource);
3356 free(lim);
3357 free(it);
3358 }
3359 return 0;
3360 }
3361
3362 int lxc_clear_groups(struct lxc_conf *c)
3363 {
3364 struct lxc_list *it,*next;
3365
3366 lxc_list_for_each_safe(it, &c->groups, next) {
3367 lxc_list_del(it);
3368 free(it->elem);
3369 free(it);
3370 }
3371 return 0;
3372 }
3373
3374 int lxc_clear_environment(struct lxc_conf *c)
3375 {
3376 struct lxc_list *it,*next;
3377
3378 lxc_list_for_each_safe(it, &c->environment, next) {
3379 lxc_list_del(it);
3380 free(it->elem);
3381 free(it);
3382 }
3383 return 0;
3384 }
3385
3386 int lxc_clear_mount_entries(struct lxc_conf *c)
3387 {
3388 struct lxc_list *it,*next;
3389
3390 lxc_list_for_each_safe(it, &c->mount_list, next) {
3391 lxc_list_del(it);
3392 free(it->elem);
3393 free(it);
3394 }
3395 return 0;
3396 }
3397
3398 int lxc_clear_automounts(struct lxc_conf *c)
3399 {
3400 c->auto_mounts = 0;
3401 return 0;
3402 }
3403
3404 int lxc_clear_hooks(struct lxc_conf *c, const char *key)
3405 {
3406 struct lxc_list *it,*next;
3407 bool all = false, done = false;
3408 const char *k = NULL;
3409 int i;
3410
3411 if (strcmp(key, "lxc.hook") == 0)
3412 all = true;
3413 else if (strncmp(key, "lxc.hook.", sizeof("lxc.hook.")-1) == 0)
3414 k = key + sizeof("lxc.hook.")-1;
3415 else
3416 return -1;
3417
3418 for (i=0; i<NUM_LXC_HOOKS; i++) {
3419 if (all || strcmp(k, lxchook_names[i]) == 0) {
3420 lxc_list_for_each_safe(it, &c->hooks[i], next) {
3421 lxc_list_del(it);
3422 free(it->elem);
3423 free(it);
3424 }
3425 done = true;
3426 }
3427 }
3428
3429 if (!done) {
3430 ERROR("Invalid hook key: %s", key);
3431 return -1;
3432 }
3433 return 0;
3434 }
3435
3436 static inline void lxc_clear_aliens(struct lxc_conf *conf)
3437 {
3438 struct lxc_list *it,*next;
3439
3440 lxc_list_for_each_safe(it, &conf->aliens, next) {
3441 lxc_list_del(it);
3442 free(it->elem);
3443 free(it);
3444 }
3445 }
3446
3447 void lxc_clear_includes(struct lxc_conf *conf)
3448 {
3449 struct lxc_list *it,*next;
3450
3451 lxc_list_for_each_safe(it, &conf->includes, next) {
3452 lxc_list_del(it);
3453 free(it->elem);
3454 free(it);
3455 }
3456 }
3457
3458 void lxc_conf_free(struct lxc_conf *conf)
3459 {
3460 if (!conf)
3461 return;
3462 if (current_config == conf)
3463 current_config = NULL;
3464 free(conf->console.log_path);
3465 free(conf->console.path);
3466 if (conf->console.log_size > 0 && conf->console.ringbuf.addr)
3467 lxc_ringbuf_release(&conf->console.ringbuf);
3468 free(conf->rootfs.mount);
3469 free(conf->rootfs.bdev_type);
3470 free(conf->rootfs.options);
3471 free(conf->rootfs.path);
3472 free(conf->logfile);
3473 if (conf->logfd != -1)
3474 close(conf->logfd);
3475 free(conf->utsname);
3476 free(conf->ttydir);
3477 free(conf->fstab);
3478 free(conf->rcfile);
3479 free(conf->execute_cmd);
3480 free(conf->init_cmd);
3481 free(conf->unexpanded_config);
3482 free(conf->pty_names);
3483 free(conf->syslog);
3484 lxc_free_networks(&conf->network);
3485 free(conf->lsm_aa_profile);
3486 free(conf->lsm_se_context);
3487 lxc_seccomp_free(conf);
3488 lxc_clear_config_caps(conf);
3489 lxc_clear_config_keepcaps(conf);
3490 lxc_clear_cgroups(conf, "lxc.cgroup");
3491 lxc_clear_hooks(conf, "lxc.hook");
3492 lxc_clear_mount_entries(conf);
3493 lxc_clear_idmaps(conf);
3494 lxc_clear_groups(conf);
3495 lxc_clear_includes(conf);
3496 lxc_clear_aliens(conf);
3497 lxc_clear_environment(conf);
3498 lxc_clear_limits(conf, "lxc.prlimit");
3499 free(conf->cgroup_meta.dir);
3500 free(conf->cgroup_meta.controllers);
3501 free(conf);
3502 }
3503
3504 struct userns_fn_data {
3505 int (*fn)(void *);
3506 const char *fn_name;
3507 void *arg;
3508 int p[2];
3509 };
3510
3511 static int run_userns_fn(void *data)
3512 {
3513 struct userns_fn_data *d = data;
3514 char c;
3515
3516 /* Close write end of the pipe. */
3517 close(d->p[1]);
3518
3519 /* Wait for parent to finish establishing a new mapping in the user
3520 * namespace we are executing in.
3521 */
3522 if (read(d->p[0], &c, 1) != 1)
3523 return -1;
3524
3525 /* Close read end of the pipe. */
3526 close(d->p[0]);
3527
3528 if (d->fn_name)
3529 TRACE("calling function \"%s\"", d->fn_name);
3530 /* Call function to run. */
3531 return d->fn(d->arg);
3532 }
3533
3534 static struct id_map *mapped_hostid_entry(struct lxc_conf *conf, unsigned id,
3535 enum idtype idtype)
3536 {
3537 struct lxc_list *it;
3538 struct id_map *map;
3539 struct id_map *retmap = NULL;
3540
3541 lxc_list_for_each(it, &conf->id_map) {
3542 map = it->elem;
3543 if (map->idtype != idtype)
3544 continue;
3545
3546 if (id >= map->hostid && id < map->hostid + map->range) {
3547 retmap = map;
3548 break;
3549 }
3550 }
3551
3552 if (!retmap)
3553 return NULL;
3554
3555 retmap = malloc(sizeof(*retmap));
3556 if (!retmap)
3557 return NULL;
3558
3559 memcpy(retmap, map, sizeof(*retmap));
3560 return retmap;
3561 }
3562
3563 /*
3564 * Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
3565 * existing one or establish a new one.
3566 */
3567 static struct id_map *idmap_add(struct lxc_conf *conf, uid_t id, enum idtype type)
3568 {
3569 int hostid_mapped;
3570 struct id_map *entry = NULL;
3571
3572 /* Reuse existing mapping. */
3573 entry = mapped_hostid_entry(conf, id, type);
3574 if (entry)
3575 return entry;
3576
3577 /* Find new mapping. */
3578 hostid_mapped = find_unmapped_nsid(conf, type);
3579 if (hostid_mapped < 0) {
3580 DEBUG("failed to find free mapping for id %d", id);
3581 return NULL;
3582 }
3583
3584 entry = malloc(sizeof(*entry));
3585 if (!entry)
3586 return NULL;
3587
3588 entry->idtype = type;
3589 entry->nsid = hostid_mapped;
3590 entry->hostid = (unsigned long)id;
3591 entry->range = 1;
3592
3593 return entry;
3594 }
3595
3596 /* Run a function in a new user namespace.
3597 * The caller's euid/egid will be mapped if it is not already.
3598 * Afaict, userns_exec_1() is only used to operate based on privileges for the
3599 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
3600 * This means we require only to establish a mapping from:
3601 * - the container root {g,u}id as seen from the host > user's host {g,u}id
3602 * - the container root -> some sub{g,u}id
3603 * The former we add, if the user did not specifiy a mapping. The latter we
3604 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
3605 * there to start the container in the first place.
3606 */
3607 int userns_exec_1(struct lxc_conf *conf, int (*fn)(void *), void *data,
3608 const char *fn_name)
3609 {
3610 pid_t pid;
3611 uid_t euid, egid;
3612 struct userns_fn_data d;
3613 int p[2];
3614 struct lxc_list *it;
3615 struct id_map *map;
3616 char c = '1';
3617 int ret = -1, status = -1;
3618 struct lxc_list *idmap = NULL, *tmplist = NULL;
3619 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
3620 *host_uid_map = NULL, *host_gid_map = NULL;
3621
3622 ret = pipe(p);
3623 if (ret < 0) {
3624 SYSERROR("opening pipe");
3625 return -1;
3626 }
3627 d.fn = fn;
3628 d.fn_name = fn_name;
3629 d.arg = data;
3630 d.p[0] = p[0];
3631 d.p[1] = p[1];
3632
3633 /* Clone child in new user namespace. */
3634 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER);
3635 if (pid < 0) {
3636 ERROR("failed to clone child process in new user namespace");
3637 goto on_error;
3638 }
3639
3640 close(p[0]);
3641 p[0] = -1;
3642
3643 euid = geteuid();
3644 egid = getegid();
3645
3646 /* Find container root. */
3647 lxc_list_for_each(it, &conf->id_map) {
3648 map = it->elem;
3649
3650 if (map->nsid != 0)
3651 continue;
3652
3653 if (map->idtype == ID_TYPE_UID && container_root_uid == NULL) {
3654 container_root_uid = malloc(sizeof(*container_root_uid));
3655 if (!container_root_uid)
3656 goto on_error;
3657 container_root_uid->idtype = map->idtype;
3658 container_root_uid->hostid = map->hostid;
3659 container_root_uid->nsid = 0;
3660 container_root_uid->range = map->range;
3661
3662 /* Check if container root mapping contains a mapping
3663 * for user's uid.
3664 */
3665 if (euid >= map->hostid && euid < map->hostid + map->range)
3666 host_uid_map = container_root_uid;
3667 } else if (map->idtype == ID_TYPE_GID && container_root_gid == NULL) {
3668 container_root_gid = malloc(sizeof(*container_root_gid));
3669 if (!container_root_gid)
3670 goto on_error;
3671 container_root_gid->idtype = map->idtype;
3672 container_root_gid->hostid = map->hostid;
3673 container_root_gid->nsid = 0;
3674 container_root_gid->range = map->range;
3675
3676 /* Check if container root mapping contains a mapping
3677 * for user's gid.
3678 */
3679 if (egid >= map->hostid && egid < map->hostid + map->range)
3680 host_gid_map = container_root_gid;
3681 }
3682
3683 /* Found container root. */
3684 if (container_root_uid && container_root_gid)
3685 break;
3686 }
3687
3688 /* This is actually checked earlier but it can't hurt. */
3689 if (!container_root_uid || !container_root_gid) {
3690 ERROR("no mapping for container root found");
3691 goto on_error;
3692 }
3693
3694 /* Check whether the {g,u}id of the user has a mapping. */
3695 if (!host_uid_map)
3696 host_uid_map = idmap_add(conf, euid, ID_TYPE_UID);
3697
3698 if (!host_gid_map)
3699 host_gid_map = idmap_add(conf, egid, ID_TYPE_GID);
3700
3701 if (!host_uid_map) {
3702 DEBUG("failed to find mapping for uid %d", euid);
3703 goto on_error;
3704 }
3705
3706 if (!host_gid_map) {
3707 DEBUG("failed to find mapping for gid %d", egid);
3708 goto on_error;
3709 }
3710
3711 /* Allocate new {g,u}id map list. */
3712 idmap = malloc(sizeof(*idmap));
3713 if (!idmap)
3714 goto on_error;
3715 lxc_list_init(idmap);
3716
3717 /* Add container root to the map. */
3718 tmplist = malloc(sizeof(*tmplist));
3719 if (!tmplist)
3720 goto on_error;
3721 lxc_list_add_elem(tmplist, container_root_uid);
3722 lxc_list_add_tail(idmap, tmplist);
3723
3724 if (host_uid_map && (host_uid_map != container_root_uid)) {
3725 /* idmap will now keep track of that memory. */
3726 container_root_uid = NULL;
3727
3728 /* Add container root to the map. */
3729 tmplist = malloc(sizeof(*tmplist));
3730 if (!tmplist)
3731 goto on_error;
3732 lxc_list_add_elem(tmplist, host_uid_map);
3733 lxc_list_add_tail(idmap, tmplist);
3734 }
3735 /* idmap will now keep track of that memory. */
3736 container_root_uid = NULL;
3737 /* idmap will now keep track of that memory. */
3738 host_uid_map = NULL;
3739
3740 tmplist = malloc(sizeof(*tmplist));
3741 if (!tmplist)
3742 goto on_error;
3743 lxc_list_add_elem(tmplist, container_root_gid);
3744 lxc_list_add_tail(idmap, tmplist);
3745
3746 if (host_gid_map && (host_gid_map != container_root_gid)) {
3747 /* idmap will now keep track of that memory. */
3748 container_root_gid = NULL;
3749
3750 tmplist = malloc(sizeof(*tmplist));
3751 if (!tmplist)
3752 goto on_error;
3753 lxc_list_add_elem(tmplist, host_gid_map);
3754 lxc_list_add_tail(idmap, tmplist);
3755 }
3756 /* idmap will now keep track of that memory. */
3757 container_root_gid = NULL;
3758 /* idmap will now keep track of that memory. */
3759 host_gid_map = NULL;
3760
3761 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE ||
3762 conf->loglevel == LXC_LOG_LEVEL_TRACE) {
3763 lxc_list_for_each(it, idmap) {
3764 map = it->elem;
3765 TRACE("establishing %cid mapping for \"%d\" in new "
3766 "user namespace: nsuid %lu - hostid %lu - range "
3767 "%lu",
3768 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
3769 map->nsid, map->hostid, map->range);
3770 }
3771 }
3772
3773 /* Set up {g,u}id mapping for user namespace of child process. */
3774 ret = lxc_map_ids(idmap, pid);
3775 if (ret < 0) {
3776 ERROR("error setting up {g,u}id mappings for child process "
3777 "\"%d\"", pid);
3778 goto on_error;
3779 }
3780
3781 /* Tell child to proceed. */
3782 if (write(p[1], &c, 1) != 1) {
3783 SYSERROR("failed telling child process \"%d\" to proceed", pid);
3784 goto on_error;
3785 }
3786
3787 on_error:
3788 /* Wait for child to finish. */
3789 if (pid > 0)
3790 status = wait_for_pid(pid);
3791
3792 if (idmap)
3793 lxc_free_idmap(idmap);
3794 if (container_root_uid)
3795 free(container_root_uid);
3796 if (container_root_gid)
3797 free(container_root_gid);
3798 if (host_uid_map && (host_uid_map != container_root_uid))
3799 free(host_uid_map);
3800 if (host_gid_map && (host_gid_map != container_root_gid))
3801 free(host_gid_map);
3802
3803 if (p[0] != -1)
3804 close(p[0]);
3805 close(p[1]);
3806
3807 if (status < 0)
3808 ret = -1;
3809
3810 return ret;
3811 }
3812
3813 int userns_exec_full(struct lxc_conf *conf, int (*fn)(void *), void *data,
3814 const char *fn_name)
3815 {
3816 pid_t pid;
3817 uid_t euid, egid;
3818 struct userns_fn_data d;
3819 int p[2];
3820 struct id_map *map;
3821 struct lxc_list *cur;
3822 char c = '1';
3823 int ret = -1;
3824 struct lxc_list *idmap = NULL, *tmplist = NULL;
3825 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
3826 *host_uid_map = NULL, *host_gid_map = NULL;
3827
3828 ret = pipe(p);
3829 if (ret < 0) {
3830 SYSERROR("opening pipe");
3831 return -1;
3832 }
3833 d.fn = fn;
3834 d.fn_name = fn_name;
3835 d.arg = data;
3836 d.p[0] = p[0];
3837 d.p[1] = p[1];
3838
3839 /* Clone child in new user namespace. */
3840 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER);
3841 if (pid < 0) {
3842 ERROR("failed to clone child process in new user namespace");
3843 goto on_error;
3844 }
3845
3846 close(p[0]);
3847 p[0] = -1;
3848
3849 euid = geteuid();
3850 egid = getegid();
3851
3852 /* Allocate new {g,u}id map list. */
3853 idmap = malloc(sizeof(*idmap));
3854 if (!idmap)
3855 goto on_error;
3856 lxc_list_init(idmap);
3857
3858 /* Find container root. */
3859 lxc_list_for_each(cur, &conf->id_map) {
3860 struct id_map *tmpmap;
3861
3862 tmplist = malloc(sizeof(*tmplist));
3863 if (!tmplist)
3864 goto on_error;
3865
3866 tmpmap = malloc(sizeof(*tmpmap));
3867 if (!tmpmap) {
3868 free(tmplist);
3869 goto on_error;
3870 }
3871
3872 memset(tmpmap, 0, sizeof(*tmpmap));
3873 memcpy(tmpmap, cur->elem, sizeof(*tmpmap));
3874 tmplist->elem = tmpmap;
3875
3876 lxc_list_add_tail(idmap, tmplist);
3877
3878 map = cur->elem;
3879
3880 if (map->idtype == ID_TYPE_UID)
3881 if (euid >= map->hostid && euid < map->hostid + map->range)
3882 host_uid_map = map;
3883
3884 if (map->idtype == ID_TYPE_GID)
3885 if (egid >= map->hostid && egid < map->hostid + map->range)
3886 host_gid_map = map;
3887
3888 if (map->nsid != 0)
3889 continue;
3890
3891 if (map->idtype == ID_TYPE_UID)
3892 if (container_root_uid == NULL)
3893 container_root_uid = map;
3894
3895 if (map->idtype == ID_TYPE_GID)
3896 if (container_root_gid == NULL)
3897 container_root_gid = map;
3898 }
3899
3900 if (!container_root_uid || !container_root_gid) {
3901 ERROR("No mapping for container root found");
3902 goto on_error;
3903 }
3904
3905 /* Check whether the {g,u}id of the user has a mapping. */
3906 if (!host_uid_map)
3907 host_uid_map = idmap_add(conf, euid, ID_TYPE_UID);
3908 else
3909 host_uid_map = container_root_uid;
3910
3911 if (!host_gid_map)
3912 host_gid_map = idmap_add(conf, egid, ID_TYPE_GID);
3913 else
3914 host_gid_map = container_root_gid;
3915
3916 if (!host_uid_map) {
3917 DEBUG("Failed to find mapping for uid %d", euid);
3918 goto on_error;
3919 }
3920
3921 if (!host_gid_map) {
3922 DEBUG("Failed to find mapping for gid %d", egid);
3923 goto on_error;
3924 }
3925
3926 if (host_uid_map && (host_uid_map != container_root_uid)) {
3927 /* Add container root to the map. */
3928 tmplist = malloc(sizeof(*tmplist));
3929 if (!tmplist)
3930 goto on_error;
3931 lxc_list_add_elem(tmplist, host_uid_map);
3932 lxc_list_add_tail(idmap, tmplist);
3933 }
3934 /* idmap will now keep track of that memory. */
3935 host_uid_map = NULL;
3936
3937 if (host_gid_map && (host_gid_map != container_root_gid)) {
3938 tmplist = malloc(sizeof(*tmplist));
3939 if (!tmplist)
3940 goto on_error;
3941 lxc_list_add_elem(tmplist, host_gid_map);
3942 lxc_list_add_tail(idmap, tmplist);
3943 }
3944 /* idmap will now keep track of that memory. */
3945 host_gid_map = NULL;
3946
3947 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE ||
3948 conf->loglevel == LXC_LOG_LEVEL_TRACE) {
3949 lxc_list_for_each(cur, idmap) {
3950 map = cur->elem;
3951 TRACE("establishing %cid mapping for \"%d\" in new "
3952 "user namespace: nsuid %lu - hostid %lu - range "
3953 "%lu",
3954 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
3955 map->nsid, map->hostid, map->range);
3956 }
3957 }
3958
3959 /* Set up {g,u}id mapping for user namespace of child process. */
3960 ret = lxc_map_ids(idmap, pid);
3961 if (ret < 0) {
3962 ERROR("error setting up {g,u}id mappings for child process "
3963 "\"%d\"", pid);
3964 goto on_error;
3965 }
3966
3967 /* Tell child to proceed. */
3968 if (write(p[1], &c, 1) != 1) {
3969 SYSERROR("failed telling child process \"%d\" to proceed", pid);
3970 goto on_error;
3971 }
3972
3973 on_error:
3974 /* Wait for child to finish. */
3975 if (pid > 0)
3976 ret = wait_for_pid(pid);
3977
3978 if (idmap)
3979 lxc_free_idmap(idmap);
3980 if (host_uid_map && (host_uid_map != container_root_uid))
3981 free(host_uid_map);
3982 if (host_gid_map && (host_gid_map != container_root_gid))
3983 free(host_gid_map);
3984
3985 if (p[0] != -1)
3986 close(p[0]);
3987 close(p[1]);
3988
3989 return ret;
3990 }
3991
3992 /* not thread-safe, do not use from api without first forking */
3993 static char* getuname(void)
3994 {
3995 struct passwd *result;
3996
3997 result = getpwuid(geteuid());
3998 if (!result)
3999 return NULL;
4000
4001 return strdup(result->pw_name);
4002 }
4003
4004 /* not thread-safe, do not use from api without first forking */
4005 static char *getgname(void)
4006 {
4007 struct group *result;
4008
4009 result = getgrgid(getegid());
4010 if (!result)
4011 return NULL;
4012
4013 return strdup(result->gr_name);
4014 }
4015
4016 /* not thread-safe, do not use from api without first forking */
4017 void suggest_default_idmap(void)
4018 {
4019 FILE *f;
4020 unsigned int uid = 0, urange = 0, gid = 0, grange = 0;
4021 char *line = NULL;
4022 char *uname, *gname;
4023 size_t len = 0;
4024
4025 if (!(uname = getuname()))
4026 return;
4027
4028 if (!(gname = getgname())) {
4029 free(uname);
4030 return;
4031 }
4032
4033 f = fopen(subuidfile, "r");
4034 if (!f) {
4035 ERROR("Your system is not configured with subuids");
4036 free(gname);
4037 free(uname);
4038 return;
4039 }
4040 while (getline(&line, &len, f) != -1) {
4041 size_t no_newline = 0;
4042 char *p = strchr(line, ':'), *p2;
4043 if (*line == '#')
4044 continue;
4045 if (!p)
4046 continue;
4047 *p = '\0';
4048 p++;
4049 if (strcmp(line, uname))
4050 continue;
4051 p2 = strchr(p, ':');
4052 if (!p2)
4053 continue;
4054 *p2 = '\0';
4055 p2++;
4056 if (!*p2)
4057 continue;
4058 no_newline = strcspn(p2, "\n");
4059 p2[no_newline] = '\0';
4060
4061 if (lxc_safe_uint(p, &uid) < 0)
4062 WARN("Could not parse UID.");
4063 if (lxc_safe_uint(p2, &urange) < 0)
4064 WARN("Could not parse UID range.");
4065 }
4066 fclose(f);
4067
4068 f = fopen(subgidfile, "r");
4069 if (!f) {
4070 ERROR("Your system is not configured with subgids");
4071 free(gname);
4072 free(uname);
4073 return;
4074 }
4075 while (getline(&line, &len, f) != -1) {
4076 size_t no_newline = 0;
4077 char *p = strchr(line, ':'), *p2;
4078 if (*line == '#')
4079 continue;
4080 if (!p)
4081 continue;
4082 *p = '\0';
4083 p++;
4084 if (strcmp(line, uname))
4085 continue;
4086 p2 = strchr(p, ':');
4087 if (!p2)
4088 continue;
4089 *p2 = '\0';
4090 p2++;
4091 if (!*p2)
4092 continue;
4093 no_newline = strcspn(p2, "\n");
4094 p2[no_newline] = '\0';
4095
4096 if (lxc_safe_uint(p, &gid) < 0)
4097 WARN("Could not parse GID.");
4098 if (lxc_safe_uint(p2, &grange) < 0)
4099 WARN("Could not parse GID range.");
4100 }
4101 fclose(f);
4102
4103 free(line);
4104
4105 if (!urange || !grange) {
4106 ERROR("You do not have subuids or subgids allocated");
4107 ERROR("Unprivileged containers require subuids and subgids");
4108 return;
4109 }
4110
4111 ERROR("You must either run as root, or define uid mappings");
4112 ERROR("To pass uid mappings to lxc-create, you could create");
4113 ERROR("~/.config/lxc/default.conf:");
4114 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG);
4115 ERROR("lxc.idmap = u 0 %u %u", uid, urange);
4116 ERROR("lxc.idmap = g 0 %u %u", gid, grange);
4117
4118 free(gname);
4119 free(uname);
4120 }
4121
4122 static void free_cgroup_settings(struct lxc_list *result)
4123 {
4124 struct lxc_list *iterator, *next;
4125
4126 lxc_list_for_each_safe(iterator, result, next) {
4127 lxc_list_del(iterator);
4128 free(iterator);
4129 }
4130 free(result);
4131 }
4132
4133 /*
4134 * Return the list of cgroup_settings sorted according to the following rules
4135 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4136 */
4137 struct lxc_list *sort_cgroup_settings(struct lxc_list* cgroup_settings)
4138 {
4139 struct lxc_list *result;
4140 struct lxc_list *memsw_limit = NULL;
4141 struct lxc_list *it = NULL;
4142 struct lxc_cgroup *cg = NULL;
4143 struct lxc_list *item = NULL;
4144
4145 result = malloc(sizeof(*result));
4146 if (!result) {
4147 ERROR("failed to allocate memory to sort cgroup settings");
4148 return NULL;
4149 }
4150 lxc_list_init(result);
4151
4152 /*Iterate over the cgroup settings and copy them to the output list*/
4153 lxc_list_for_each(it, cgroup_settings) {
4154 item = malloc(sizeof(*item));
4155 if (!item) {
4156 ERROR("failed to allocate memory to sort cgroup settings");
4157 free_cgroup_settings(result);
4158 return NULL;
4159 }
4160 item->elem = it->elem;
4161 cg = it->elem;
4162 if (strcmp(cg->subsystem, "memory.memsw.limit_in_bytes") == 0) {
4163 /* Store the memsw_limit location */
4164 memsw_limit = item;
4165 } else if (strcmp(cg->subsystem, "memory.limit_in_bytes") == 0 && memsw_limit != NULL) {
4166 /* lxc.cgroup.memory.memsw.limit_in_bytes is found before
4167 * lxc.cgroup.memory.limit_in_bytes, swap these two items */
4168 item->elem = memsw_limit->elem;
4169 memsw_limit->elem = it->elem;
4170 }
4171 lxc_list_add_tail(result, item);
4172 }
4173
4174 return result;
4175 }