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