]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/conf.c
commands: allow waiting for all states
[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 1743 INFO("Failed to mount \"%s\" on \"%s\" (optional): %s",
0103eb53 1744 fsname ? fsname : "(null)", target, strerror(errno));
1fc64d22
SG
1745 return 0;
1746 }
0ac4b28a 1747
0103eb53
CB
1748 SYSERROR("Failed to mount \"%s\" on \"%s\"",
1749 fsname ? fsname : "(null)", target);
0ac4b28a 1750 return -1;
911324ef
DL
1751 }
1752
1753 if ((mountflags & MS_REMOUNT) || (mountflags & MS_BIND)) {
7c5b6e7c 1754 unsigned long rqd_flags = 0;
0ac4b28a
CB
1755
1756 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
0103eb53 1757 "options", fsname ? fsname : "(none)", target ? target : "(none)");
0ac4b28a 1758
7c5b6e7c
AS
1759 if (mountflags & MS_RDONLY)
1760 rqd_flags |= MS_RDONLY;
614305f3 1761#ifdef HAVE_STATVFS
0103eb53 1762 if (fsname && 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 1800 INFO("Failed to mount \"%s\" on \"%s\" "
0103eb53
CB
1801 "(optional): %s",
1802 fsname ? fsname : "(null)", target,
0ac4b28a 1803 strerror(errno));
1fc64d22
SG
1804 return 0;
1805 }
0ac4b28a 1806
0103eb53
CB
1807 SYSERROR("Failed to mount \"%s\" on \"%s\"",
1808 fsname ? fsname : "(null)", target);
0ac4b28a 1809 return -1;
911324ef
DL
1810 }
1811 }
1812
614305f3 1813#ifdef HAVE_STATVFS
6fd5e769 1814skipremount:
614305f3 1815#endif
0103eb53
CB
1816 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
1817 fsname ? fsname : "(null)", target, fstype);
911324ef
DL
1818
1819 return 0;
1820}
1821
c5e30de4 1822/* Remove "optional", "create=dir", and "create=file" from mntopt */
4e4ca161
SH
1823static void cull_mntent_opt(struct mntent *mntent)
1824{
1825 int i;
c5e30de4
CB
1826 char *list[] = {"create=dir", "create=file", "optional", NULL};
1827
1828 for (i = 0; list[i]; i++) {
1829 char *p, *p2;
1830
1831 p = strstr(mntent->mnt_opts, list[i]);
1832 if (!p)
4e4ca161 1833 continue;
c5e30de4 1834
4e4ca161
SH
1835 p2 = strchr(p, ',');
1836 if (!p2) {
1837 /* no more mntopts, so just chop it here */
1838 *p = '\0';
1839 continue;
1840 }
c5e30de4
CB
1841
1842 memmove(p, p2 + 1, strlen(p2 + 1) + 1);
4e4ca161
SH
1843 }
1844}
1845
4d5b72a1 1846static int mount_entry_create_dir_file(const struct mntent *mntent,
749f98d9
CB
1847 const char *path,
1848 const struct lxc_rootfs *rootfs,
1849 const char *lxc_name,
1850 const char *lxc_path)
0ad19a3f 1851{
608e3567 1852 int ret = 0;
911324ef 1853
749f98d9
CB
1854 if (!strncmp(mntent->mnt_type, "overlay", 7))
1855 ret = ovl_mkdir(mntent, rootfs, lxc_name, lxc_path);
1856 else if (!strncmp(mntent->mnt_type, "aufs", 4))
1857 ret = aufs_mkdir(mntent, rootfs, lxc_name, lxc_path);
1858 if (ret < 0)
1859 return -1;
6e46cc0d 1860
34cfffb3 1861 if (hasmntopt(mntent, "create=dir")) {
749f98d9
CB
1862 ret = mkdir_p(path, 0755);
1863 if (ret < 0 && errno != EEXIST) {
1864 SYSERROR("Failed to create directory \"%s\"", path);
1865 return -1;
34cfffb3
SG
1866 }
1867 }
1868
4d5b72a1 1869 if (hasmntopt(mntent, "create=file") && access(path, F_OK)) {
749f98d9
CB
1870 int fd;
1871 char *p1, *p2;
1872
1873 p1 = strdup(path);
1874 if (!p1)
1875 return -1;
1876
1877 p2 = dirname(p1);
1878
1879 ret = mkdir_p(p2, 0755);
1880 free(p1);
1881 if (ret < 0 && errno != EEXIST) {
1882 SYSERROR("Failed to create directory \"%s\"", path);
1883 return -1;
6e46cc0d 1884 }
749f98d9
CB
1885
1886 fd = open(path, O_CREAT, 0644);
1887 if (fd < 0)
1888 return -1;
1889 close(fd);
34cfffb3 1890 }
749f98d9
CB
1891
1892 return 0;
4d5b72a1
NC
1893}
1894
ec50007f
CB
1895/* rootfs, lxc_name, and lxc_path can be NULL when the container is created
1896 * without a rootfs. */
db4aba38 1897static inline int mount_entry_on_generic(struct mntent *mntent,
d8b712bc
CB
1898 const char *path,
1899 const struct lxc_rootfs *rootfs,
1900 const char *lxc_name,
1901 const char *lxc_path)
4d5b72a1 1902{
d8b712bc 1903 int ret;
4d5b72a1
NC
1904 unsigned long mntflags;
1905 char *mntdata;
d8b712bc 1906 bool dev, optional;
ec50007f 1907 char *rootfs_path = NULL;
d8b712bc
CB
1908
1909 optional = hasmntopt(mntent, "optional") != NULL;
1910 dev = hasmntopt(mntent, "dev") != NULL;
1911
ec50007f
CB
1912 if (rootfs && rootfs->path)
1913 rootfs_path = rootfs->mount;
1914
d8b712bc
CB
1915 ret = mount_entry_create_dir_file(mntent, path, rootfs, lxc_name,
1916 lxc_path);
1917 if (ret < 0) {
1918 if (optional)
1919 return 0;
608e3567 1920
d8b712bc
CB
1921 return -1;
1922 }
4e4ca161
SH
1923 cull_mntent_opt(mntent);
1924
d8b712bc
CB
1925 ret = parse_mntopts(mntent->mnt_opts, &mntflags, &mntdata);
1926 if (ret < 0)
a17b1e65 1927 return -1;
a17b1e65 1928
6e46cc0d 1929 ret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type, mntflags,
ae7a770e 1930 mntdata, optional, dev, rootfs_path);
68c152ef 1931
911324ef 1932 free(mntdata);
911324ef
DL
1933 return ret;
1934}
1935
db4aba38
NC
1936static inline int mount_entry_on_systemfs(struct mntent *mntent)
1937{
1433c9f9 1938 int ret;
07667a6a 1939 char path[MAXPATHLEN];
1433c9f9
CB
1940
1941 /* For containers created without a rootfs all mounts are treated as
07667a6a
CB
1942 * absolute paths starting at / on the host.
1943 */
1433c9f9
CB
1944 if (mntent->mnt_dir[0] != '/')
1945 ret = snprintf(path, sizeof(path), "/%s", mntent->mnt_dir);
1946 else
1947 ret = snprintf(path, sizeof(path), "%s", mntent->mnt_dir);
07667a6a 1948 if (ret < 0 || ret >= sizeof(path))
1433c9f9 1949 return -1;
1433c9f9
CB
1950
1951 return mount_entry_on_generic(mntent, path, NULL, NULL, NULL);
db4aba38
NC
1952}
1953
4e4ca161 1954static int mount_entry_on_absolute_rootfs(struct mntent *mntent,
80a881b2 1955 const struct lxc_rootfs *rootfs,
0a2dddd4
CB
1956 const char *lxc_name,
1957 const char *lxc_path)
911324ef 1958{
bdd2b34c 1959 int offset;
013bd428 1960 char *aux;
67e571de 1961 const char *lxcpath;
bdd2b34c
CB
1962 char path[MAXPATHLEN];
1963 int ret = 0;
0ad19a3f 1964
593e8478 1965 lxcpath = lxc_global_config_value("lxc.lxcpath");
bdd2b34c 1966 if (!lxcpath)
2a59a681 1967 return -1;
2a59a681 1968
bdd2b34c
CB
1969 /* If rootfs->path is a blockdev path, allow container fstab to use
1970 * <lxcpath>/<name>/rootfs" as the target prefix.
1971 */
1972 ret = snprintf(path, MAXPATHLEN, "%s/%s/rootfs", lxcpath, lxc_name);
1973 if (ret < 0 || ret >= MAXPATHLEN)
80a881b2
SH
1974 goto skipvarlib;
1975
1976 aux = strstr(mntent->mnt_dir, path);
1977 if (aux) {
1978 offset = strlen(path);
1979 goto skipabs;
1980 }
1981
1982skipvarlib:
013bd428
DL
1983 aux = strstr(mntent->mnt_dir, rootfs->path);
1984 if (!aux) {
bdd2b34c 1985 WARN("Ignoring mount point \"%s\"", mntent->mnt_dir);
db4aba38 1986 return ret;
013bd428 1987 }
80a881b2
SH
1988 offset = strlen(rootfs->path);
1989
1990skipabs:
bdd2b34c
CB
1991 ret = snprintf(path, MAXPATHLEN, "%s/%s", rootfs->mount, aux + offset);
1992 if (ret < 0 || ret >= MAXPATHLEN)
a17b1e65 1993 return -1;
a17b1e65 1994
0a2dddd4 1995 return mount_entry_on_generic(mntent, path, rootfs, lxc_name, lxc_path);
911324ef 1996}
d330fe7b 1997
4e4ca161 1998static int mount_entry_on_relative_rootfs(struct mntent *mntent,
0a2dddd4
CB
1999 const struct lxc_rootfs *rootfs,
2000 const char *lxc_name,
2001 const char *lxc_path)
911324ef
DL
2002{
2003 char path[MAXPATHLEN];
911324ef 2004 int ret;
d330fe7b 2005
34cfffb3 2006 /* relative to root mount point */
6e46cc0d 2007 ret = snprintf(path, sizeof(path), "%s/%s", rootfs->mount, mntent->mnt_dir);
1433c9f9 2008 if (ret < 0 || ret >= sizeof(path)) {
9ba8130c
SH
2009 ERROR("path name too long");
2010 return -1;
2011 }
911324ef 2012
0a2dddd4 2013 return mount_entry_on_generic(mntent, path, rootfs, lxc_name, lxc_path);
911324ef
DL
2014}
2015
06749971
CB
2016/* This logs a NOTICE() when a user specifies mounts that would conflict with
2017 * devices liblxc sets up automatically.
2018 */
2019static void log_notice_on_conflict(const struct lxc_conf *conf, const char *src,
2020 const char *dest)
2021{
2022 char *clean_mnt_fsname, *clean_mnt_dir, *tmp;
2023 bool needs_warning = false;
2024
2025 clean_mnt_fsname = lxc_deslashify(src);
2026 if (!clean_mnt_fsname)
2027 return;
2028
2029 clean_mnt_dir = lxc_deslashify(dest);
2030 if (!clean_mnt_dir) {
2031 free(clean_mnt_fsname);
2032 return;
2033 }
2034
2035 tmp = clean_mnt_dir;
2036 if (*tmp == '/')
2037 tmp++;
2038
2039 if (strncmp(src, "/dev", 4) || strncmp(tmp, "dev", 3)) {
2040 free(clean_mnt_dir);
2041 free(clean_mnt_fsname);
2042 return;
2043 }
2044
2045 if (!conf->autodev && !conf->pts && !conf->tty &&
2046 (!conf->console.path || !strcmp(conf->console.path, "none"))) {
2047 free(clean_mnt_dir);
2048 free(clean_mnt_fsname);
2049 return;
2050 }
2051
2052 if (!strcmp(tmp, "dev") && conf->autodev > 0)
2053 needs_warning = true;
2054 else if (!strcmp(tmp, "dev/pts") && (conf->autodev > 0 || conf->pts > 0))
2055 needs_warning = true;
2056 else if (!strcmp(tmp, "dev/ptmx") && (conf->autodev > 0 || conf->pts > 0))
2057 needs_warning = true;
2058 else if (!strcmp(tmp, "dev/pts/ptmx") && (conf->autodev > 0 || conf->pts > 0))
2059 needs_warning = true;
2060 else if (!strcmp(tmp, "dev/null") && conf->autodev > 0)
2061 needs_warning = true;
2062 else if (!strcmp(tmp, "dev/zero") && conf->autodev > 0)
2063 needs_warning = true;
2064 else if (!strcmp(tmp, "dev/full") && conf->autodev > 0)
2065 needs_warning = true;
2066 else if (!strcmp(tmp, "dev/urandom") && conf->autodev > 0)
2067 needs_warning = true;
2068 else if (!strcmp(tmp, "dev/random") && conf->autodev > 0)
2069 needs_warning = true;
2070 else if (!strcmp(tmp, "dev/tty") && conf->autodev > 0)
2071 needs_warning = true;
2072 else if (!strncmp(tmp, "dev/tty", 7) && (conf->autodev > 0 || conf->tty > 0))
2073 needs_warning = true;
2074
2075 if (needs_warning)
2076 NOTICE("Requesting to mount \"%s\" on \"%s\" while requesting "
2077 "automatic device setup under \"/dev\"",
2078 clean_mnt_fsname, clean_mnt_dir);
2079
2080 free(clean_mnt_dir);
2081 free(clean_mnt_fsname);
2082}
2083
2084static int mount_file_entries(const struct lxc_conf *conf,
2085 const struct lxc_rootfs *rootfs, FILE *file,
1ae3c19f 2086 const char *lxc_name, const char *lxc_path)
911324ef 2087{
aaf901be
AM
2088 struct mntent mntent;
2089 char buf[4096];
911324ef 2090 int ret = -1;
e76b8764 2091
aaf901be 2092 while (getmntent_r(file, &mntent, buf, sizeof(buf))) {
06749971
CB
2093 log_notice_on_conflict(conf, mntent.mnt_fsname, mntent.mnt_dir);
2094
1ae3c19f
CB
2095 if (!rootfs->path)
2096 ret = mount_entry_on_systemfs(&mntent);
2097 else if (mntent.mnt_dir[0] != '/')
2098 ret = mount_entry_on_relative_rootfs(&mntent, rootfs,
2099 lxc_name, lxc_path);
2100 else
2101 ret = mount_entry_on_absolute_rootfs(&mntent, rootfs,
2102 lxc_name, lxc_path);
2103 if (ret < 0)
2104 return -1;
0ad19a3f 2105 }
2106 ret = 0;
cd54d859 2107
1ae3c19f 2108 INFO("Set up mount entries");
e7938e9e
MN
2109 return ret;
2110}
2111
06749971
CB
2112static int setup_mount(const struct lxc_conf *conf,
2113 const struct lxc_rootfs *rootfs, const char *fstab,
42dff448 2114 const char *lxc_name, const char *lxc_path)
e7938e9e 2115{
42dff448 2116 FILE *f;
e7938e9e
MN
2117 int ret;
2118
2119 if (!fstab)
2120 return 0;
2121
42dff448
CB
2122 f = setmntent(fstab, "r");
2123 if (!f) {
2124 SYSERROR("Failed to open \"%s\"", fstab);
e7938e9e
MN
2125 return -1;
2126 }
2127
06749971 2128 ret = mount_file_entries(conf, rootfs, f, lxc_name, lxc_path);
42dff448
CB
2129 if (ret < 0)
2130 ERROR("Failed to set up mount entries");
e7938e9e 2131
42dff448 2132 endmntent(f);
0ad19a3f 2133 return ret;
2134}
2135
5ef5c9a3 2136FILE *make_anonymous_mount_file(struct lxc_list *mount)
e7938e9e 2137{
5ef5c9a3 2138 int ret;
e7938e9e 2139 char *mount_entry;
5ef5c9a3 2140 struct lxc_list *iterator;
6bd04140 2141 FILE *f;
5ef5c9a3
CB
2142 int fd = -1;
2143
2144 fd = memfd_create("lxc_mount_file", MFD_CLOEXEC);
2145 if (fd < 0) {
2146 if (errno != ENOSYS)
2147 return NULL;
6bd04140
CB
2148 f = tmpfile();
2149 TRACE("Created temporary mount file");
5ef5c9a3 2150 } else {
6bd04140
CB
2151 f = fdopen(fd, "r+");
2152 TRACE("Created anonymous mount file");
5ef5c9a3 2153 }
e7938e9e 2154
6bd04140
CB
2155 if (!f) {
2156 SYSERROR("Could not create mount file");
5ef5c9a3
CB
2157 if (fd != -1)
2158 close(fd);
9fc7f8c0 2159 return NULL;
e7938e9e
MN
2160 }
2161
2162 lxc_list_for_each(iterator, mount) {
2163 mount_entry = iterator->elem;
6bd04140 2164 ret = fprintf(f, "%s\n", mount_entry);
5ef5c9a3 2165 if (ret < strlen(mount_entry))
6bd04140 2166 WARN("Could not write mount entry to mount file");
5ef5c9a3
CB
2167 }
2168
6bd04140
CB
2169 ret = fseek(f, 0, SEEK_SET);
2170 if (ret < 0) {
2171 SYSERROR("Failed to seek mount file");
2172 fclose(f);
5ef5c9a3 2173 return NULL;
e7938e9e
MN
2174 }
2175
6bd04140 2176 return f;
9fc7f8c0
TA
2177}
2178
06749971
CB
2179static int setup_mount_entries(const struct lxc_conf *conf,
2180 const struct lxc_rootfs *rootfs,
5ef5c9a3
CB
2181 struct lxc_list *mount, const char *lxc_name,
2182 const char *lxc_path)
9fc7f8c0 2183{
19b5d755 2184 FILE *f;
9fc7f8c0
TA
2185 int ret;
2186
19b5d755
CB
2187 f = make_anonymous_mount_file(mount);
2188 if (!f)
9fc7f8c0 2189 return -1;
e7938e9e 2190
06749971 2191 ret = mount_file_entries(conf, rootfs, f, lxc_name, lxc_path);
e7938e9e 2192
19b5d755 2193 fclose(f);
e7938e9e
MN
2194 return ret;
2195}
2196
bab88e68
CS
2197static int parse_cap(const char *cap)
2198{
2199 char *ptr = NULL;
84760c11 2200 size_t i;
2201 int capid = -1;
bab88e68 2202
7035407c
DE
2203 if (!strcmp(cap, "none"))
2204 return -2;
2205
bab88e68
CS
2206 for (i = 0; i < sizeof(caps_opt)/sizeof(caps_opt[0]); i++) {
2207
2208 if (strcmp(cap, caps_opt[i].name))
2209 continue;
2210
2211 capid = caps_opt[i].value;
2212 break;
2213 }
2214
2215 if (capid < 0) {
2216 /* try to see if it's numeric, so the user may specify
2217 * capabilities that the running kernel knows about but
2218 * we don't */
2219 errno = 0;
2220 capid = strtol(cap, &ptr, 10);
2221 if (!ptr || *ptr != '\0' || errno != 0)
2222 /* not a valid number */
2223 capid = -1;
2224 else if (capid > lxc_caps_last_cap())
2225 /* we have a number but it's not a valid
2226 * capability */
2227 capid = -1;
2228 }
2229
2230 return capid;
2231}
2232
0769b82a
CS
2233int in_caplist(int cap, struct lxc_list *caps)
2234{
2235 struct lxc_list *iterator;
2236 int capid;
2237
2238 lxc_list_for_each(iterator, caps) {
2239 capid = parse_cap(iterator->elem);
2240 if (capid == cap)
2241 return 1;
2242 }
2243
2244 return 0;
2245}
2246
81810dd1
DL
2247static int setup_caps(struct lxc_list *caps)
2248{
2249 struct lxc_list *iterator;
2250 char *drop_entry;
bab88e68 2251 int capid;
81810dd1
DL
2252
2253 lxc_list_for_each(iterator, caps) {
2254
2255 drop_entry = iterator->elem;
2256
bab88e68 2257 capid = parse_cap(drop_entry);
d55bc1ad 2258
81810dd1 2259 if (capid < 0) {
1e11be34
DL
2260 ERROR("unknown capability %s", drop_entry);
2261 return -1;
81810dd1
DL
2262 }
2263
2264 DEBUG("drop capability '%s' (%d)", drop_entry, capid);
2265
2266 if (prctl(PR_CAPBSET_DROP, capid, 0, 0, 0)) {
3ec1648d
SH
2267 SYSERROR("failed to remove %s capability", drop_entry);
2268 return -1;
2269 }
81810dd1
DL
2270
2271 }
2272
1fb86a7c
SH
2273 DEBUG("capabilities have been setup");
2274
2275 return 0;
2276}
2277
2278static int dropcaps_except(struct lxc_list *caps)
2279{
2280 struct lxc_list *iterator;
2281 char *keep_entry;
1fb86a7c
SH
2282 int i, capid;
2283 int numcaps = lxc_caps_last_cap() + 1;
959aee9c 2284 INFO("found %d capabilities", numcaps);
1fb86a7c 2285
2caf9a97
SH
2286 if (numcaps <= 0 || numcaps > 200)
2287 return -1;
2288
1a0e70ac 2289 /* caplist[i] is 1 if we keep capability i */
1fb86a7c
SH
2290 int *caplist = alloca(numcaps * sizeof(int));
2291 memset(caplist, 0, numcaps * sizeof(int));
2292
2293 lxc_list_for_each(iterator, caps) {
2294
2295 keep_entry = iterator->elem;
2296
bab88e68 2297 capid = parse_cap(keep_entry);
1fb86a7c 2298
7035407c
DE
2299 if (capid == -2)
2300 continue;
2301
1fb86a7c
SH
2302 if (capid < 0) {
2303 ERROR("unknown capability %s", keep_entry);
2304 return -1;
2305 }
2306
8255688a 2307 DEBUG("keep capability '%s' (%d)", keep_entry, capid);
1fb86a7c
SH
2308
2309 caplist[capid] = 1;
2310 }
2311 for (i=0; i<numcaps; i++) {
2312 if (caplist[i])
2313 continue;
2314 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0)) {
3ec1648d
SH
2315 SYSERROR("failed to remove capability %d", i);
2316 return -1;
2317 }
1fb86a7c
SH
2318 }
2319
2320 DEBUG("capabilities have been setup");
81810dd1
DL
2321
2322 return 0;
2323}
2324
c6d09e15
WB
2325static int parse_resource(const char *res) {
2326 size_t i;
2327 int resid = -1;
2328
2329 for (i = 0; i < sizeof(limit_opt)/sizeof(limit_opt[0]); ++i) {
2330 if (strcmp(res, limit_opt[i].name) == 0)
2331 return limit_opt[i].value;
2332 }
2333
2334 /* try to see if it's numeric, so the user may specify
2335 * resources that the running kernel knows about but
2336 * we don't */
2337 if (lxc_safe_int(res, &resid) == 0)
2338 return resid;
2339 return -1;
2340}
2341
2342int setup_resource_limits(struct lxc_list *limits, pid_t pid) {
2343 struct lxc_list *it;
2344 struct lxc_limit *lim;
2345 int resid;
2346
2347 lxc_list_for_each(it, limits) {
2348 lim = it->elem;
2349
2350 resid = parse_resource(lim->resource);
2351 if (resid < 0) {
2352 ERROR("unknown resource %s", lim->resource);
2353 return -1;
2354 }
2355
f48b5fd8 2356#if HAVE_PRLIMIT || HAVE_PRLIMIT64
c6d09e15
WB
2357 if (prlimit(pid, resid, &lim->limit, NULL) != 0) {
2358 ERROR("failed to set limit %s: %s", lim->resource, strerror(errno));
2359 return -1;
2360 }
f48b5fd8
FF
2361#else
2362 ERROR("Cannot set limit %s as prlimit is missing", lim->resource);
2363 return -1;
2364#endif
c6d09e15
WB
2365 }
2366 return 0;
2367}
2368
ae9242c8
SH
2369static char *default_rootfs_mount = LXCROOTFSMOUNT;
2370
7b379ab3 2371struct lxc_conf *lxc_conf_init(void)
089cd8b8 2372{
7b379ab3 2373 struct lxc_conf *new;
26ddeedd 2374 int i;
7b379ab3 2375
13277ec4 2376 new = malloc(sizeof(*new));
7b379ab3 2377 if (!new) {
13277ec4 2378 ERROR("lxc_conf_init : %s", strerror(errno));
7b379ab3
MN
2379 return NULL;
2380 }
2381 memset(new, 0, sizeof(*new));
2382
4b73005c 2383 new->loglevel = LXC_LOG_LEVEL_NOTSET;
cccc74b5 2384 new->personality = -1;
124fa0a8 2385 new->autodev = 1;
3a784510
CB
2386 new->console.buffer_log_file = NULL;
2387 new->console.buffer_log_file_fd = -1;
2388 new->console.buffer_size = 0;
596a818d
DE
2389 new->console.log_path = NULL;
2390 new->console.log_fd = -1;
28a4b0e5 2391 new->console.path = NULL;
63376d7d 2392 new->console.peer = -1;
b5159817
DE
2393 new->console.peerpty.busy = -1;
2394 new->console.peerpty.master = -1;
2395 new->console.peerpty.slave = -1;
63376d7d
DL
2396 new->console.master = -1;
2397 new->console.slave = -1;
2398 new->console.name[0] = '\0';
732375f5 2399 memset(&new->console.ringbuf, 0, sizeof(struct lxc_ringbuf));
d2e30e99 2400 new->maincmd_fd = -1;
76a26f55 2401 new->nbd_idx = -1;
54c30e29 2402 new->rootfs.mount = strdup(default_rootfs_mount);
53f3f048 2403 if (!new->rootfs.mount) {
13277ec4 2404 ERROR("lxc_conf_init : %s", strerror(errno));
53f3f048
SH
2405 free(new);
2406 return NULL;
2407 }
858377e4 2408 new->logfd = -1;
7b379ab3
MN
2409 lxc_list_init(&new->cgroup);
2410 lxc_list_init(&new->network);
2411 lxc_list_init(&new->mount_list);
81810dd1 2412 lxc_list_init(&new->caps);
1fb86a7c 2413 lxc_list_init(&new->keepcaps);
f6d3e3e4 2414 lxc_list_init(&new->id_map);
f979ac15 2415 lxc_list_init(&new->includes);
4184c3e1 2416 lxc_list_init(&new->aliens);
7c661726 2417 lxc_list_init(&new->environment);
c6d09e15 2418 lxc_list_init(&new->limits);
28d9e29e 2419 for (i = 0; i < NUM_LXC_HOOKS; i++)
26ddeedd 2420 lxc_list_init(&new->hooks[i]);
ee1e7aa0 2421 lxc_list_init(&new->groups);
fe4de9a6
DE
2422 new->lsm_aa_profile = NULL;
2423 new->lsm_se_context = NULL;
5112cd70 2424 new->tmp_umount_proc = 0;
7b379ab3 2425
72bb04e4
PT
2426 /* if running in a new user namespace, init and COMMAND
2427 * default to running as UID/GID 0 when using lxc-execute */
2428 new->init_uid = 0;
2429 new->init_gid = 0;
43654d34 2430 memset(&new->cgroup_meta, 0, sizeof(struct lxc_cgroup));
28d9e29e 2431 memset(&new->inherit_ns, 0, sizeof(char *) * LXC_NS_MAX);
72bb04e4 2432
7b379ab3 2433 return new;
089cd8b8
DL
2434}
2435
344c9d81 2436int write_id_mapping(enum idtype idtype, pid_t pid, const char *buf,
251d0d2a 2437 size_t buf_size)
f6d3e3e4 2438{
29053180
CB
2439 char path[MAXPATHLEN];
2440 int fd, ret;
f6d3e3e4 2441
29053180
CB
2442 ret = snprintf(path, MAXPATHLEN, "/proc/%d/%cid_map", pid,
2443 idtype == ID_TYPE_UID ? 'u' : 'g');
2444 if (ret < 0 || ret >= MAXPATHLEN) {
2445 ERROR("failed to create path \"%s\"", path);
f6d3e3e4
SH
2446 return -E2BIG;
2447 }
29053180
CB
2448
2449 fd = open(path, O_WRONLY);
2450 if (fd < 0) {
2451 SYSERROR("failed to open \"%s\"", path);
2452 return -1;
f6d3e3e4 2453 }
29053180
CB
2454
2455 errno = 0;
2456 ret = lxc_write_nointr(fd, buf, buf_size);
2457 if (ret != buf_size) {
2458 SYSERROR("failed to write %cid mapping to \"%s\"",
2459 idtype == ID_TYPE_UID ? 'u' : 'g', path);
2460 close(fd);
2461 return -1;
2462 }
2463 close(fd);
2464
2465 return 0;
f6d3e3e4
SH
2466}
2467
6e50e704
CB
2468/* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2469 *
2470 * @return 1 if functional binary was found
2471 * @return 0 if binary exists but is lacking privilege
2472 * @return -ENOENT if binary does not exist
2473 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2474 *
2475 */
df6a2945
CB
2476static int idmaptool_on_path_and_privileged(const char *binary, cap_value_t cap)
2477{
2478 char *path;
2479 int ret;
2480 struct stat st;
2481 int fret = 0;
2482
6e50e704
CB
2483 if (cap != CAP_SETUID && cap != CAP_SETGID)
2484 return -EINVAL;
2485
df6a2945
CB
2486 path = on_path(binary, NULL);
2487 if (!path)
2488 return -ENOENT;
2489
2490 ret = stat(path, &st);
2491 if (ret < 0) {
2492 fret = -errno;
2493 goto cleanup;
2494 }
2495
2496 /* Check if the binary is setuid. */
2497 if (st.st_mode & S_ISUID) {
2498 DEBUG("The binary \"%s\" does have the setuid bit set.", path);
2499 fret = 1;
2500 goto cleanup;
2501 }
2502
69924fff 2503 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
df6a2945
CB
2504 /* Check if it has the CAP_SETUID capability. */
2505 if ((cap & CAP_SETUID) &&
2506 lxc_file_cap_is_set(path, CAP_SETUID, CAP_EFFECTIVE) &&
2507 lxc_file_cap_is_set(path, CAP_SETUID, CAP_PERMITTED)) {
2508 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2509 "and CAP_PERMITTED sets.", path);
2510 fret = 1;
2511 goto cleanup;
2512 }
2513
2514 /* Check if it has the CAP_SETGID capability. */
2515 if ((cap & CAP_SETGID) &&
2516 lxc_file_cap_is_set(path, CAP_SETGID, CAP_EFFECTIVE) &&
2517 lxc_file_cap_is_set(path, CAP_SETGID, CAP_PERMITTED)) {
2518 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2519 "and CAP_PERMITTED sets.", path);
2520 fret = 1;
2521 goto cleanup;
2522 }
d6018f88 2523 #else
69924fff
CB
2524 /* If we cannot check for file capabilities we need to give the benefit
2525 * of the doubt. Otherwise we might fail even though all the necessary
2526 * file capabilities are set.
2527 */
d6018f88
CB
2528 DEBUG("Cannot check for file capabilites as full capability support is "
2529 "missing. Manual intervention needed.");
2530 fret = 1;
df6a2945
CB
2531 #endif
2532
2533cleanup:
2534 free(path);
2535 return fret;
2536}
2537
986ef930
CB
2538int lxc_map_ids_exec_wrapper(void *args)
2539{
2540 execl("/bin/sh", "sh", "-c", (char *)args, (char *)NULL);
2541 return -1;
2542}
2543
f6d3e3e4
SH
2544int lxc_map_ids(struct lxc_list *idmap, pid_t pid)
2545{
f6d3e3e4 2546 struct id_map *map;
4bc3b759 2547 struct lxc_list *iterator;
251d0d2a 2548 enum idtype type;
986ef930 2549 char u_or_g;
4bc3b759 2550 char *pos;
99d43365 2551 int fill, left;
986ef930
CB
2552 char cmd_output[MAXPATHLEN];
2553 /* strlen("new@idmap") = 9
2554 * +
2555 * strlen(" ") = 1
2556 * +
2557 * LXC_NUMSTRLEN64
2558 * +
2559 * strlen(" ") = 1
2560 *
2561 * We add some additional space to make sure that we really have
2562 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2563 */
2564 char mapbuf[9 + 1 + LXC_NUMSTRLEN64 + 1 + LXC_IDMAPLEN] = {0};
2565 int ret = 0, uidmap = 0, gidmap = 0;
2566 bool use_shadow = false, had_entry = false;
df6a2945
CB
2567
2568 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2569 * ranges, then insist that root also reserve ranges in subuid. This
22038de5
SH
2570 * will protected it by preventing another user from being handed the
2571 * range by shadow.
2572 */
df6a2945 2573 uidmap = idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID);
6e50e704
CB
2574 if (uidmap == -ENOENT)
2575 WARN("newuidmap binary is missing");
2576 else if (!uidmap)
2577 WARN("newuidmap is lacking necessary privileges");
2578
df6a2945 2579 gidmap = idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID);
6e50e704
CB
2580 if (gidmap == -ENOENT)
2581 WARN("newgidmap binary is missing");
2582 else if (!gidmap)
2583 WARN("newgidmap is lacking necessary privileges");
2584
df6a2945
CB
2585 if (uidmap > 0 && gidmap > 0) {
2586 DEBUG("Functional newuidmap and newgidmap binary found.");
4bc3b759 2587 use_shadow = true;
df6a2945 2588 } else {
99d43365
CB
2589 /* In case unprivileged users run application containers via
2590 * execute() or a start*() there are valid cases where they may
2591 * only want to map their own {g,u}id. Let's not block them from
2592 * doing so by requiring geteuid() == 0.
2593 */
2594 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2595 "write directly with euid %d.", geteuid());
0e6e3a41 2596 }
251d0d2a 2597
986ef930
CB
2598 for (type = ID_TYPE_UID, u_or_g = 'u'; type <= ID_TYPE_GID;
2599 type++, u_or_g = 'g') {
2600 pos = mapbuf;
2601
0e6e3a41 2602 if (use_shadow)
986ef930 2603 pos += sprintf(mapbuf, "new%cidmap %d", u_or_g, pid);
4f7521b4 2604
cf3ef16d 2605 lxc_list_for_each(iterator, idmap) {
251d0d2a 2606 map = iterator->elem;
cf3ef16d
SH
2607 if (map->idtype != type)
2608 continue;
2609
4bc3b759
CB
2610 had_entry = true;
2611
986ef930 2612 left = LXC_IDMAPLEN - (pos - mapbuf);
d1838f34 2613 fill = snprintf(pos, left, "%s%lu %lu %lu%s",
4bc3b759
CB
2614 use_shadow ? " " : "", map->nsid,
2615 map->hostid, map->range,
0e6e3a41 2616 use_shadow ? "" : "\n");
a427e268
CB
2617 if (fill <= 0 || fill >= left) {
2618 /* The kernel only takes <= 4k for writes to
2619 * /proc/<pid>/{g,u}id_map
2620 */
2621 SYSERROR("Too many %cid mappings defined", u_or_g);
2622 return -1;
2623 }
4bc3b759 2624
cf3ef16d 2625 pos += fill;
251d0d2a 2626 }
cf3ef16d 2627 if (!had_entry)
4f7521b4 2628 continue;
cf3ef16d 2629
986ef930
CB
2630 /* Try to catch the ouput of new{g,u}idmap to make debugging
2631 * easier.
2632 */
2633 if (use_shadow) {
2634 ret = run_command(cmd_output, sizeof(cmd_output),
2635 lxc_map_ids_exec_wrapper,
2636 (void *)mapbuf);
2637 if (ret < 0) {
54fbbeb5
CB
2638 ERROR("new%cidmap failed to write mapping \"%s\": %s",
2639 u_or_g, cmd_output, mapbuf);
986ef930
CB
2640 return -1;
2641 }
54fbbeb5 2642 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g, mapbuf);
d1838f34 2643 } else {
986ef930 2644 ret = write_id_mapping(type, pid, mapbuf, pos - mapbuf);
54fbbeb5 2645 if (ret < 0) {
da0f9977 2646 ERROR("Failed to write mapping: %s", mapbuf);
986ef930 2647 return -1;
54fbbeb5
CB
2648 }
2649 TRACE("Wrote mapping \"%s\"", mapbuf);
d1838f34 2650 }
986ef930
CB
2651
2652 memset(mapbuf, 0, sizeof(mapbuf));
f6d3e3e4 2653 }
251d0d2a 2654
986ef930 2655 return 0;
f6d3e3e4
SH
2656}
2657
cf3ef16d 2658/*
7b50c609
TS
2659 * return the host uid/gid to which the container root is mapped in
2660 * *val.
0b3a6504 2661 * Return true if id was found, false otherwise.
cf3ef16d 2662 */
2a9a80cb 2663bool get_mapped_rootid(struct lxc_conf *conf, enum idtype idtype,
3ec1648d 2664 unsigned long *val)
cf3ef16d
SH
2665{
2666 struct lxc_list *it;
2667 struct id_map *map;
2668
2669 lxc_list_for_each(it, &conf->id_map) {
2670 map = it->elem;
7b50c609 2671 if (map->idtype != idtype)
cf3ef16d
SH
2672 continue;
2673 if (map->nsid != 0)
2674 continue;
2a9a80cb
SH
2675 *val = map->hostid;
2676 return true;
cf3ef16d 2677 }
2a9a80cb 2678 return false;
cf3ef16d
SH
2679}
2680
2133f58c 2681int mapped_hostid(unsigned id, struct lxc_conf *conf, enum idtype idtype)
cf3ef16d
SH
2682{
2683 struct lxc_list *it;
2684 struct id_map *map;
2685 lxc_list_for_each(it, &conf->id_map) {
2686 map = it->elem;
2133f58c 2687 if (map->idtype != idtype)
cf3ef16d
SH
2688 continue;
2689 if (id >= map->hostid && id < map->hostid + map->range)
57d116ab 2690 return (id - map->hostid) + map->nsid;
cf3ef16d 2691 }
57d116ab 2692 return -1;
cf3ef16d
SH
2693}
2694
339efad9 2695int find_unmapped_nsid(struct lxc_conf *conf, enum idtype idtype)
cf3ef16d
SH
2696{
2697 struct lxc_list *it;
2698 struct id_map *map;
2133f58c 2699 unsigned int freeid = 0;
cf3ef16d
SH
2700again:
2701 lxc_list_for_each(it, &conf->id_map) {
2702 map = it->elem;
2133f58c 2703 if (map->idtype != idtype)
cf3ef16d
SH
2704 continue;
2705 if (freeid >= map->nsid && freeid < map->nsid + map->range) {
2706 freeid = map->nsid + map->range;
2707 goto again;
2708 }
2709 }
2710 return freeid;
2711}
2712
f4f52cb5
CB
2713int chown_mapped_root_exec_wrapper(void *args)
2714{
2715 execvp("lxc-usernsexec", args);
2716 return -1;
2717}
2718
f6d3e3e4 2719/*
7b50c609
TS
2720 * chown_mapped_root: for an unprivileged user with uid/gid X to
2721 * chown a dir to subuid/subgid Y, he needs to run chown as root
2722 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
2723 * nsid Y is mapped to hostuid/hostgid X. That way, the container
2724 * root is privileged with respect to hostuid/hostgid X, allowing
2725 * him to do the chown.
f6d3e3e4 2726 */
c4d10a05 2727int chown_mapped_root(char *path, struct lxc_conf *conf)
f6d3e3e4 2728{
f4f52cb5 2729 uid_t rootuid, rootgid;
2a9a80cb 2730 unsigned long val;
f4f52cb5
CB
2731 int hostuid, hostgid, ret;
2732 struct stat sb;
2733 char map1[100], map2[100], map3[100], map4[100], map5[100];
2734 char ugid[100];
2735 char *args1[] = {"lxc-usernsexec",
2736 "-m", map1,
2737 "-m", map2,
2738 "-m", map3,
2739 "-m", map5,
2740 "--", "chown", ugid, path,
2741 NULL};
2742 char *args2[] = {"lxc-usernsexec",
2743 "-m", map1,
2744 "-m", map2,
2745 "-m", map3,
2746 "-m", map4,
2747 "-m", map5,
2748 "--", "chown", ugid, path,
2749 NULL};
2750 char cmd_output[MAXPATHLEN];
2751
2752 hostuid = geteuid();
2753 hostgid = getegid();
f6d3e3e4 2754
2a9a80cb 2755 if (!get_mapped_rootid(conf, ID_TYPE_UID, &val)) {
bc80f098 2756 ERROR("No uid mapping for container root");
c4d10a05 2757 return -1;
f6d3e3e4 2758 }
f4f52cb5 2759 rootuid = (uid_t)val;
7b50c609 2760 if (!get_mapped_rootid(conf, ID_TYPE_GID, &val)) {
bc80f098 2761 ERROR("No gid mapping for container root");
7b50c609
TS
2762 return -1;
2763 }
f4f52cb5 2764 rootgid = (gid_t)val;
2a9a80cb 2765
f4f52cb5 2766 if (hostuid == 0) {
7b50c609 2767 if (chown(path, rootuid, rootgid) < 0) {
c4d10a05
SH
2768 ERROR("Error chowning %s", path);
2769 return -1;
2770 }
2771 return 0;
2772 }
f3d7e4ca 2773
f4f52cb5 2774 if (rootuid == hostuid) {
1a0e70ac 2775 /* nothing to do */
b103ceac 2776 INFO("Container root is our uid; no need to chown");
f3d7e4ca
SH
2777 return 0;
2778 }
2779
bbdbf8f0 2780 /* save the current gid of "path" */
f4f52cb5
CB
2781 if (stat(path, &sb) < 0) {
2782 ERROR("Error stat %s", path);
f6d3e3e4
SH
2783 return -1;
2784 }
7b50c609 2785
bbdbf8f0
CB
2786 /* Update the path argument in case this was overlayfs. */
2787 args1[sizeof(args1) / sizeof(args1[0]) - 2] = path;
2788 args2[sizeof(args2) / sizeof(args2[0]) - 2] = path;
2789
f4f52cb5
CB
2790 /*
2791 * A file has to be group-owned by a gid mapped into the
2792 * container, or the container won't be privileged over it.
2793 */
2794 DEBUG("trying to chown \"%s\" to %d", path, hostgid);
2795 if (sb.st_uid == hostuid &&
2796 mapped_hostid(sb.st_gid, conf, ID_TYPE_GID) < 0 &&
2797 chown(path, -1, hostgid) < 0) {
2798 ERROR("Failed chgrping %s", path);
2799 return -1;
2800 }
f6d3e3e4 2801
1a0e70ac 2802 /* "u:0:rootuid:1" */
f4f52cb5
CB
2803 ret = snprintf(map1, 100, "u:0:%d:1", rootuid);
2804 if (ret < 0 || ret >= 100) {
2805 ERROR("Error uid printing map string");
2806 return -1;
2807 }
7b50c609 2808
1a0e70ac 2809 /* "u:hostuid:hostuid:1" */
f4f52cb5
CB
2810 ret = snprintf(map2, 100, "u:%d:%d:1", hostuid, hostuid);
2811 if (ret < 0 || ret >= 100) {
2812 ERROR("Error uid printing map string");
2813 return -1;
2814 }
c4d10a05 2815
1a0e70ac 2816 /* "g:0:rootgid:1" */
f4f52cb5
CB
2817 ret = snprintf(map3, 100, "g:0:%d:1", rootgid);
2818 if (ret < 0 || ret >= 100) {
2819 ERROR("Error gid printing map string");
2820 return -1;
2821 }
98e5ba51 2822
1a0e70ac 2823 /* "g:pathgid:rootgid+pathgid:1" */
f4f52cb5
CB
2824 ret = snprintf(map4, 100, "g:%d:%d:1", (gid_t)sb.st_gid,
2825 rootgid + (gid_t)sb.st_gid);
2826 if (ret < 0 || ret >= 100) {
2827 ERROR("Error gid printing map string");
2828 return -1;
2829 }
c4d10a05 2830
1a0e70ac 2831 /* "g:hostgid:hostgid:1" */
f4f52cb5
CB
2832 ret = snprintf(map5, 100, "g:%d:%d:1", hostgid, hostgid);
2833 if (ret < 0 || ret >= 100) {
2834 ERROR("Error gid printing map string");
2835 return -1;
2836 }
7b50c609 2837
1a0e70ac 2838 /* "0:pathgid" (chown) */
f4f52cb5
CB
2839 ret = snprintf(ugid, 100, "0:%d", (gid_t)sb.st_gid);
2840 if (ret < 0 || ret >= 100) {
2841 ERROR("Error owner printing format string for chown");
2842 return -1;
2843 }
7b50c609 2844
f4f52cb5
CB
2845 if (hostgid == sb.st_gid)
2846 ret = run_command(cmd_output, sizeof(cmd_output),
2847 chown_mapped_root_exec_wrapper,
2848 (void *)args1);
2849 else
2850 ret = run_command(cmd_output, sizeof(cmd_output),
2851 chown_mapped_root_exec_wrapper,
2852 (void *)args2);
2853 if (ret < 0)
2854 ERROR("lxc-usernsexec failed: %s", cmd_output);
7b50c609 2855
f4f52cb5 2856 return ret;
f6d3e3e4
SH
2857}
2858
54117de5 2859int lxc_ttys_shift_ids(struct lxc_conf *c)
f6d3e3e4 2860{
c4d10a05 2861 if (lxc_list_empty(&c->id_map))
f6d3e3e4 2862 return 0;
c4d10a05 2863
54117de5
CB
2864 if (!strcmp(c->console.name, ""))
2865 return 0;
2866
2867 if (chown_mapped_root(c->console.name, c) < 0) {
2868 ERROR("failed to chown console \"%s\"", c->console.name);
c4d10a05
SH
2869 return -1;
2870 }
2871
54117de5
CB
2872 TRACE("chowned console \"%s\"", c->console.name);
2873
f6d3e3e4
SH
2874 return 0;
2875}
2876
943144d9
CB
2877/* NOTE: Must not be called from inside the container namespace! */
2878int lxc_create_tmp_proc_mount(struct lxc_conf *conf)
5112cd70
SH
2879{
2880 int mounted;
2881
943144d9 2882 mounted = lxc_mount_proc_if_needed(conf->rootfs.path ? conf->rootfs.mount : "");
5112cd70 2883 if (mounted == -1) {
943144d9 2884 SYSERROR("failed to mount /proc in the container");
01958b1f 2885 /* continue only if there is no rootfs */
943144d9 2886 if (conf->rootfs.path)
01958b1f 2887 return -1;
5112cd70 2888 } else if (mounted == 1) {
943144d9 2889 conf->tmp_umount_proc = 1;
5112cd70 2890 }
943144d9 2891
5112cd70
SH
2892 return 0;
2893}
2894
2895void tmp_proc_unmount(struct lxc_conf *lxc_conf)
2896{
2897 if (lxc_conf->tmp_umount_proc == 1) {
2898 umount("/proc");
2899 lxc_conf->tmp_umount_proc = 0;
2900 }
2901}
2902
6a0c909a 2903void remount_all_slave(void)
e995d7a2
SH
2904{
2905 /* walk /proc/mounts and change any shared entries to slave */
2906 FILE *f = fopen("/proc/self/mountinfo", "r");
2907 char *line = NULL;
2908 size_t len = 0;
2909
2910 if (!f) {
2911 SYSERROR("Failed to open /proc/self/mountinfo to mark all shared");
2912 ERROR("Continuing container startup...");
2913 return;
2914 }
2915
2916 while (getline(&line, &len, f) != -1) {
2917 char *target, *opts;
2918 target = get_field(line, 4);
2919 if (!target)
2920 continue;
2921 opts = get_field(target, 2);
2922 if (!opts)
2923 continue;
2924 null_endofword(opts);
2925 if (!strstr(opts, "shared"))
2926 continue;
2927 null_endofword(target);
2928 if (mount(NULL, target, NULL, MS_SLAVE, NULL)) {
2929 SYSERROR("Failed to make %s rslave", target);
2930 ERROR("Continuing...");
2931 }
2932 }
2933 fclose(f);
f10fad2f 2934 free(line);
e995d7a2
SH
2935}
2936
2322903b
SH
2937void lxc_execute_bind_init(struct lxc_conf *conf)
2938{
2939 int ret;
9d9c111c
SH
2940 char path[PATH_MAX], destpath[PATH_MAX], *p;
2941
2942 /* If init exists in the container, don't bind mount a static one */
2943 p = choose_init(conf->rootfs.mount);
2944 if (p) {
2945 free(p);
2946 return;
2947 }
2322903b
SH
2948
2949 ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static");
2950 if (ret < 0 || ret >= PATH_MAX) {
2951 WARN("Path name too long searching for lxc.init.static");
2952 return;
2953 }
2954
2955 if (!file_exists(path)) {
2956 INFO("%s does not exist on host", path);
2957 return;
2958 }
2959
2960 ret = snprintf(destpath, PATH_MAX, "%s%s", conf->rootfs.mount, "/init.lxc.static");
2961 if (ret < 0 || ret >= PATH_MAX) {
2962 WARN("Path name too long for container's lxc.init.static");
2963 return;
2964 }
2965
2966 if (!file_exists(destpath)) {
2967 FILE * pathfile = fopen(destpath, "wb");
2968 if (!pathfile) {
2969 SYSERROR("Failed to create mount target '%s'", destpath);
2970 return;
2971 }
2972 fclose(pathfile);
2973 }
2974
592fd47a 2975 ret = safe_mount(path, destpath, "none", MS_BIND, NULL, conf->rootfs.mount);
2322903b
SH
2976 if (ret < 0)
2977 SYSERROR("Failed to bind lxc.init.static into container");
2978 INFO("lxc.init.static bound into container at %s", path);
2979}
2980
35120d9c
SH
2981/*
2982 * This does the work of remounting / if it is shared, calling the
2983 * container pre-mount hooks, and mounting the rootfs.
2984 */
2985int do_rootfs_setup(struct lxc_conf *conf, const char *name, const char *lxcpath)
0ad19a3f 2986{
35120d9c
SH
2987 if (conf->rootfs_setup) {
2988 /*
2989 * rootfs was set up in another namespace. bind-mount it
2990 * to give us a mount in our own ns so we can pivot_root to it
2991 */
2992 const char *path = conf->rootfs.mount;
2993 if (mount(path, path, "rootfs", MS_BIND, NULL) < 0) {
2994 ERROR("Failed to bind-mount container / onto itself");
145832ba 2995 return -1;
35120d9c 2996 }
145832ba 2997 return 0;
35120d9c 2998 }
d4ef7c50 2999
e995d7a2
SH
3000 remount_all_slave();
3001
35120d9c
SH
3002 if (run_lxc_hooks(name, "pre-mount", conf, lxcpath, NULL)) {
3003 ERROR("failed to run pre-mount hooks for container '%s'.", name);
3004 return -1;
3005 }
3006
9aa76a17 3007 if (lxc_setup_rootfs(conf)) {
35120d9c
SH
3008 ERROR("failed to setup rootfs for '%s'", name);
3009 return -1;
3010 }
3011
3012 conf->rootfs_setup = true;
3013 return 0;
3014}
3015
1c1c7051
SH
3016static bool verify_start_hooks(struct lxc_conf *conf)
3017{
3018 struct lxc_list *it;
3019 char path[MAXPATHLEN];
3020 lxc_list_for_each(it, &conf->hooks[LXCHOOK_START]) {
3021 char *hookname = it->elem;
3022 struct stat st;
3023 int ret;
3024
3025 ret = snprintf(path, MAXPATHLEN, "%s%s",
7b6753e7 3026 conf->rootfs.path ? conf->rootfs.mount : "", hookname);
1c1c7051
SH
3027 if (ret < 0 || ret >= MAXPATHLEN)
3028 return false;
3029 ret = stat(path, &st);
3030 if (ret) {
7b6753e7 3031 SYSERROR("Start hook %s not found in container",
1c1c7051
SH
3032 hookname);
3033 return false;
3034 }
6a0c909a 3035 return true;
1c1c7051
SH
3036 }
3037
3038 return true;
3039}
3040
3b988b33 3041int lxc_setup(struct lxc_handler *handler)
35120d9c 3042{
2187efd3 3043 int ret;
35120d9c
SH
3044 const char *name = handler->name;
3045 struct lxc_conf *lxc_conf = handler->conf;
3046 const char *lxcpath = handler->lxcpath;
35120d9c
SH
3047
3048 if (do_rootfs_setup(lxc_conf, name, lxcpath) < 0) {
3049 ERROR("Error setting up rootfs mount after spawn");
3050 return -1;
3051 }
3052
28d9e29e 3053 if (handler->nsfd[LXC_NS_UTS] == -1) {
6c544cb3
MM
3054 if (setup_utsname(lxc_conf->utsname)) {
3055 ERROR("failed to setup the utsname for '%s'", name);
3056 return -1;
3057 }
0ad19a3f 3058 }
3059
811ef482 3060 if (lxc_setup_network_in_child_namespaces(lxc_conf, &lxc_conf->network)) {
36eb9bde 3061 ERROR("failed to setup the network for '%s'", name);
95b5ffaf 3062 return -1;
0ad19a3f 3063 }
3064
790255cf
CB
3065 if (lxc_network_send_name_and_ifindex_to_parent(handler) < 0) {
3066 ERROR("Failed to network device names and ifindices to parent");
3067 return -1;
3068 }
3069
bc6928ff 3070 if (lxc_conf->autodev > 0) {
14221cbb 3071 if (mount_autodev(name, &lxc_conf->rootfs, lxcpath)) {
91c3830e 3072 ERROR("failed to mount /dev in the container");
c6883f38
SH
3073 return -1;
3074 }
3075 }
3076
368bbc02
CS
3077 /* do automatic mounts (mainly /proc and /sys), but exclude
3078 * those that need to wait until other stuff has finished
3079 */
4fb3cba5 3080 if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK, handler) < 0) {
368bbc02
CS
3081 ERROR("failed to setup the automatic mounts for '%s'", name);
3082 return -1;
3083 }
3084
06749971 3085 if (setup_mount(lxc_conf, &lxc_conf->rootfs, lxc_conf->fstab, name, lxcpath)) {
36eb9bde 3086 ERROR("failed to setup the mounts for '%s'", name);
95b5ffaf 3087 return -1;
576f946d 3088 }
3089
06749971 3090 if (!lxc_list_empty(&lxc_conf->mount_list) && setup_mount_entries(lxc_conf, &lxc_conf->rootfs, &lxc_conf->mount_list, name, lxcpath)) {
e7938e9e
MN
3091 ERROR("failed to setup the mount entries for '%s'", name);
3092 return -1;
3093 }
3094
7b6753e7 3095 /* Make sure any start hooks are in the container */
1c1c7051
SH
3096 if (!verify_start_hooks(lxc_conf))
3097 return -1;
3098
2322903b
SH
3099 if (lxc_conf->is_execute)
3100 lxc_execute_bind_init(lxc_conf);
3101
368bbc02
CS
3102 /* now mount only cgroup, if wanted;
3103 * before, /sys could not have been mounted
3104 * (is either mounted automatically or via fstab entries)
3105 */
4fb3cba5 3106 if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK, handler) < 0) {
368bbc02
CS
3107 ERROR("failed to setup the automatic mounts for '%s'", name);
3108 return -1;
3109 }
3110
283678ed 3111 if (run_lxc_hooks(name, "mount", lxc_conf, lxcpath, NULL)) {
773fb9ca
SH
3112 ERROR("failed to run mount hooks for container '%s'.", name);
3113 return -1;
3114 }
3115
bc6928ff 3116 if (lxc_conf->autodev > 0) {
283678ed 3117 if (run_lxc_hooks(name, "autodev", lxc_conf, lxcpath, NULL)) {
f7bee6c6
MW
3118 ERROR("failed to run autodev hooks for container '%s'.", name);
3119 return -1;
3120 }
06749971 3121
27245ff7 3122 if (lxc_fill_autodev(&lxc_conf->rootfs)) {
91c3830e
SH
3123 ERROR("failed to populate /dev in the container");
3124 return -1;
3125 }
3126 }
368bbc02 3127
ed8704d0
CB
3128 ret = lxc_setup_console(&lxc_conf->rootfs, &lxc_conf->console,
3129 lxc_conf->ttydir);
3130 if (ret < 0) {
3131 ERROR("Failed to setup console");
95b5ffaf 3132 return -1;
6e590161 3133 }
3134
ed8704d0
CB
3135 ret = lxc_setup_dev_symlinks(&lxc_conf->rootfs);
3136 if (ret < 0) {
3137 ERROR("Failed to setup /dev symlinks");
69aa6655
DE
3138 return -1;
3139 }
3140
5112cd70 3141 /* mount /proc if it's not already there */
943144d9 3142 if (lxc_create_tmp_proc_mount(lxc_conf) < 0) {
fe4de9a6 3143 ERROR("failed to LSM mount proc for '%s'", name);
e075f5d9 3144 return -1;
e075f5d9 3145 }
e075f5d9 3146
ac778708 3147 if (setup_pivot_root(&lxc_conf->rootfs)) {
36eb9bde 3148 ERROR("failed to set rootfs for '%s'", name);
95b5ffaf 3149 return -1;
ed502555 3150 }
3151
70761e5e 3152 if (lxc_setup_devpts(lxc_conf->pts)) {
36eb9bde 3153 ERROR("failed to setup the new pts instance");
95b5ffaf 3154 return -1;
3c26f34e 3155 }
3156
2187efd3
CB
3157 ret = lxc_create_ttys(handler);
3158 if (ret < 0)
e8bd4e43 3159 return -1;
e8bd4e43 3160
cccc74b5
DL
3161 if (setup_personality(lxc_conf->personality)) {
3162 ERROR("failed to setup personality");
3163 return -1;
3164 }
3165
97a8f74f
SG
3166 if (!lxc_list_empty(&lxc_conf->keepcaps)) {
3167 if (!lxc_list_empty(&lxc_conf->caps)) {
7389ca26 3168 ERROR("Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both.");
f6d3e3e4
SH
3169 return -1;
3170 }
97a8f74f
SG
3171 if (dropcaps_except(&lxc_conf->keepcaps)) {
3172 ERROR("failed to keep requested caps");
3173 return -1;
3174 }
3175 } else if (setup_caps(&lxc_conf->caps)) {
3176 ERROR("failed to drop capabilities");
3177 return -1;
81810dd1
DL
3178 }
3179
f4152036 3180 NOTICE("Container \"%s\" is set up", name);
cd54d859 3181
0ad19a3f 3182 return 0;
3183}
26ddeedd 3184
283678ed
SH
3185int run_lxc_hooks(const char *name, char *hook, struct lxc_conf *conf,
3186 const char *lxcpath, char *argv[])
26ddeedd
SH
3187{
3188 int which = -1;
3189 struct lxc_list *it;
3190
3191 if (strcmp(hook, "pre-start") == 0)
3192 which = LXCHOOK_PRESTART;
08dd2805
SH
3193 else if (strcmp(hook, "start-host") == 0)
3194 which = LXCHOOK_START_HOST;
5ea6163a
SH
3195 else if (strcmp(hook, "pre-mount") == 0)
3196 which = LXCHOOK_PREMOUNT;
26ddeedd
SH
3197 else if (strcmp(hook, "mount") == 0)
3198 which = LXCHOOK_MOUNT;
f7bee6c6
MW
3199 else if (strcmp(hook, "autodev") == 0)
3200 which = LXCHOOK_AUTODEV;
26ddeedd
SH
3201 else if (strcmp(hook, "start") == 0)
3202 which = LXCHOOK_START;
52492063
WB
3203 else if (strcmp(hook, "stop") == 0)
3204 which = LXCHOOK_STOP;
26ddeedd
SH
3205 else if (strcmp(hook, "post-stop") == 0)
3206 which = LXCHOOK_POSTSTOP;
148e91f5
SH
3207 else if (strcmp(hook, "clone") == 0)
3208 which = LXCHOOK_CLONE;
37cf711b
SY
3209 else if (strcmp(hook, "destroy") == 0)
3210 which = LXCHOOK_DESTROY;
26ddeedd
SH
3211 else
3212 return -1;
3213 lxc_list_for_each(it, &conf->hooks[which]) {
3214 int ret;
3215 char *hookname = it->elem;
283678ed 3216 ret = run_script_argv(name, "lxc", hookname, hook, lxcpath, argv);
26ddeedd
SH
3217 if (ret)
3218 return ret;
3219 }
3220 return 0;
3221}
72d0e1cb 3222
72d0e1cb
SG
3223int lxc_clear_config_caps(struct lxc_conf *c)
3224{
1a0e70ac 3225 struct lxc_list *it, *next;
72d0e1cb 3226
9ebb03ad 3227 lxc_list_for_each_safe(it, &c->caps, next) {
72d0e1cb
SG
3228 lxc_list_del(it);
3229 free(it->elem);
3230 free(it);
3231 }
3232 return 0;
3233}
3234
74a3920a 3235static int lxc_free_idmap(struct lxc_list *id_map) {
27c27d73
SH
3236 struct lxc_list *it, *next;
3237
4355ab5f 3238 lxc_list_for_each_safe(it, id_map, next) {
27c27d73
SH
3239 lxc_list_del(it);
3240 free(it->elem);
3241 free(it);
3242 }
3243 return 0;
3244}
3245
4355ab5f
SH
3246int lxc_clear_idmaps(struct lxc_conf *c)
3247{
3248 return lxc_free_idmap(&c->id_map);
3249}
3250
1fb86a7c
SH
3251int lxc_clear_config_keepcaps(struct lxc_conf *c)
3252{
3253 struct lxc_list *it,*next;
3254
3255 lxc_list_for_each_safe(it, &c->keepcaps, next) {
3256 lxc_list_del(it);
3257 free(it->elem);
3258 free(it);
3259 }
3260 return 0;
3261}
3262
12a50cc6 3263int lxc_clear_cgroups(struct lxc_conf *c, const char *key)
72d0e1cb 3264{
9ebb03ad 3265 struct lxc_list *it,*next;
72d0e1cb 3266 bool all = false;
a6390f01 3267 const char *k = NULL;
72d0e1cb
SG
3268
3269 if (strcmp(key, "lxc.cgroup") == 0)
3270 all = true;
a6390f01
WB
3271 else if (strncmp(key, "lxc.cgroup.", sizeof("lxc.cgroup.")-1) == 0)
3272 k = key + sizeof("lxc.cgroup.")-1;
3273 else
3274 return -1;
72d0e1cb 3275
9ebb03ad 3276 lxc_list_for_each_safe(it, &c->cgroup, next) {
72d0e1cb
SG
3277 struct lxc_cgroup *cg = it->elem;
3278 if (!all && strcmp(cg->subsystem, k) != 0)
3279 continue;
3280 lxc_list_del(it);
3281 free(cg->subsystem);
3282 free(cg->value);
3283 free(cg);
3284 free(it);
3285 }
3286 return 0;
3287}
3288
c6d09e15
WB
3289int lxc_clear_limits(struct lxc_conf *c, const char *key)
3290{
3291 struct lxc_list *it, *next;
3292 bool all = false;
3293 const char *k = NULL;
3294
240d4b74 3295 if (strcmp(key, "lxc.limit") == 0
3296 || strcmp(key, "lxc.prlimit"))
c6d09e15
WB
3297 all = true;
3298 else if (strncmp(key, "lxc.limit.", sizeof("lxc.limit.")-1) == 0)
3299 k = key + sizeof("lxc.limit.")-1;
240d4b74 3300 else if (strncmp(key, "lxc.prlimit.", sizeof("lxc.prlimit.")-1) == 0)
3301 k = key + sizeof("lxc.prlimit.")-1;
c6d09e15
WB
3302 else
3303 return -1;
3304
3305 lxc_list_for_each_safe(it, &c->limits, next) {
3306 struct lxc_limit *lim = it->elem;
3307 if (!all && strcmp(lim->resource, k) != 0)
3308 continue;
3309 lxc_list_del(it);
3310 free(lim->resource);
3311 free(lim);
3312 free(it);
3313 }
3314 return 0;
3315}
3316
ee1e7aa0
SG
3317int lxc_clear_groups(struct lxc_conf *c)
3318{
3319 struct lxc_list *it,*next;
3320
3321 lxc_list_for_each_safe(it, &c->groups, next) {
3322 lxc_list_del(it);
3323 free(it->elem);
3324 free(it);
3325 }
3326 return 0;
3327}
3328
ab799c0b
SG
3329int lxc_clear_environment(struct lxc_conf *c)
3330{
3331 struct lxc_list *it,*next;
3332
3333 lxc_list_for_each_safe(it, &c->environment, next) {
3334 lxc_list_del(it);
3335 free(it->elem);
3336 free(it);
3337 }
3338 return 0;
3339}
3340
72d0e1cb
SG
3341int lxc_clear_mount_entries(struct lxc_conf *c)
3342{
9ebb03ad 3343 struct lxc_list *it,*next;
72d0e1cb 3344
9ebb03ad 3345 lxc_list_for_each_safe(it, &c->mount_list, next) {
72d0e1cb
SG
3346 lxc_list_del(it);
3347 free(it->elem);
3348 free(it);
3349 }
3350 return 0;
3351}
3352
b099e9e9
SH
3353int lxc_clear_automounts(struct lxc_conf *c)
3354{
3355 c->auto_mounts = 0;
3356 return 0;
3357}
3358
12a50cc6 3359int lxc_clear_hooks(struct lxc_conf *c, const char *key)
72d0e1cb 3360{
9ebb03ad 3361 struct lxc_list *it,*next;
17ed13a3 3362 bool all = false, done = false;
a6390f01 3363 const char *k = NULL;
72d0e1cb
SG
3364 int i;
3365
17ed13a3
SH
3366 if (strcmp(key, "lxc.hook") == 0)
3367 all = true;
a6390f01
WB
3368 else if (strncmp(key, "lxc.hook.", sizeof("lxc.hook.")-1) == 0)
3369 k = key + sizeof("lxc.hook.")-1;
3370 else
3371 return -1;
17ed13a3 3372
72d0e1cb 3373 for (i=0; i<NUM_LXC_HOOKS; i++) {
17ed13a3 3374 if (all || strcmp(k, lxchook_names[i]) == 0) {
9ebb03ad 3375 lxc_list_for_each_safe(it, &c->hooks[i], next) {
17ed13a3
SH
3376 lxc_list_del(it);
3377 free(it->elem);
3378 free(it);
3379 }
3380 done = true;
72d0e1cb
SG
3381 }
3382 }
17ed13a3
SH
3383
3384 if (!done) {
3385 ERROR("Invalid hook key: %s", key);
3386 return -1;
3387 }
72d0e1cb
SG
3388 return 0;
3389}
8eb5694b 3390
4184c3e1
SH
3391static inline void lxc_clear_aliens(struct lxc_conf *conf)
3392{
3393 struct lxc_list *it,*next;
3394
3395 lxc_list_for_each_safe(it, &conf->aliens, next) {
3396 lxc_list_del(it);
3397 free(it->elem);
3398 free(it);
3399 }
3400}
3401
c7b15d1e 3402void lxc_clear_includes(struct lxc_conf *conf)
f979ac15
SH
3403{
3404 struct lxc_list *it,*next;
3405
3406 lxc_list_for_each_safe(it, &conf->includes, next) {
3407 lxc_list_del(it);
3408 free(it->elem);
3409 free(it);
3410 }
3411}
3412
8eb5694b
SH
3413void lxc_conf_free(struct lxc_conf *conf)
3414{
3415 if (!conf)
3416 return;
858377e4
SH
3417 if (current_config == conf)
3418 current_config = NULL;
3a784510 3419 free(conf->console.buffer_log_file);
f10fad2f
ME
3420 free(conf->console.log_path);
3421 free(conf->console.path);
28f3b1cd 3422 if (conf->console.buffer_size > 0 && conf->console.ringbuf.addr)
732375f5 3423 lxc_ringbuf_release(&conf->console.ringbuf);
f10fad2f 3424 free(conf->rootfs.mount);
b3b8c97f 3425 free(conf->rootfs.bdev_type);
f10fad2f
ME
3426 free(conf->rootfs.options);
3427 free(conf->rootfs.path);
f10fad2f 3428 free(conf->logfile);
858377e4
SH
3429 if (conf->logfd != -1)
3430 close(conf->logfd);
f10fad2f
ME
3431 free(conf->utsname);
3432 free(conf->ttydir);
3433 free(conf->fstab);
3434 free(conf->rcfile);
5cda27c1 3435 free(conf->execute_cmd);
f10fad2f 3436 free(conf->init_cmd);
3c491553 3437 free(conf->init_cwd);
6b0d5538 3438 free(conf->unexpanded_config);
393903d1 3439 free(conf->pty_names);
76d0127f 3440 free(conf->syslog);
c302b476 3441 lxc_free_networks(&conf->network);
f10fad2f
ME
3442 free(conf->lsm_aa_profile);
3443 free(conf->lsm_se_context);
769872f9 3444 lxc_seccomp_free(conf);
8eb5694b 3445 lxc_clear_config_caps(conf);
1fb86a7c 3446 lxc_clear_config_keepcaps(conf);
8eb5694b 3447 lxc_clear_cgroups(conf, "lxc.cgroup");
17ed13a3 3448 lxc_clear_hooks(conf, "lxc.hook");
8eb5694b 3449 lxc_clear_mount_entries(conf);
27c27d73 3450 lxc_clear_idmaps(conf);
ee1e7aa0 3451 lxc_clear_groups(conf);
f979ac15 3452 lxc_clear_includes(conf);
761d81ca 3453 lxc_clear_aliens(conf);
ab799c0b 3454 lxc_clear_environment(conf);
240d4b74 3455 lxc_clear_limits(conf, "lxc.prlimit");
43654d34
CB
3456 free(conf->cgroup_meta.dir);
3457 free(conf->cgroup_meta.controllers);
8eb5694b
SH
3458 free(conf);
3459}
4355ab5f
SH
3460
3461struct userns_fn_data {
3462 int (*fn)(void *);
c9b7c33e 3463 const char *fn_name;
4355ab5f
SH
3464 void *arg;
3465 int p[2];
3466};
3467
3468static int run_userns_fn(void *data)
3469{
3470 struct userns_fn_data *d = data;
3471 char c;
4355ab5f 3472
f8aa4bf3 3473 /* Close write end of the pipe. */
4355ab5f 3474 close(d->p[1]);
f8aa4bf3
CB
3475
3476 /* Wait for parent to finish establishing a new mapping in the user
3477 * namespace we are executing in.
3478 */
4355ab5f
SH
3479 if (read(d->p[0], &c, 1) != 1)
3480 return -1;
f8aa4bf3
CB
3481
3482 /* Close read end of the pipe. */
4355ab5f 3483 close(d->p[0]);
f8aa4bf3 3484
c9b7c33e
CB
3485 if (d->fn_name)
3486 TRACE("calling function \"%s\"", d->fn_name);
f8aa4bf3 3487 /* Call function to run. */
4355ab5f
SH
3488 return d->fn(d->arg);
3489}
3490
339efad9 3491static struct id_map *mapped_hostid_entry(struct lxc_conf *conf, unsigned id,
f8aa4bf3
CB
3492 enum idtype idtype)
3493{
3494 struct lxc_list *it;
3495 struct id_map *map;
3496 struct id_map *retmap = NULL;
3497
3498 lxc_list_for_each(it, &conf->id_map) {
3499 map = it->elem;
3500 if (map->idtype != idtype)
3501 continue;
3502
3503 if (id >= map->hostid && id < map->hostid + map->range) {
3504 retmap = map;
3505 break;
3506 }
3507 }
3508
3509 if (!retmap)
3510 return NULL;
3511
3512 retmap = malloc(sizeof(*retmap));
3513 if (!retmap)
3514 return NULL;
3515
3516 memcpy(retmap, map, sizeof(*retmap));
3517 return retmap;
3518}
3519
4355ab5f 3520/*
f8aa4bf3
CB
3521 * Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
3522 * existing one or establish a new one.
4355ab5f 3523 */
28a2d9e7 3524static struct id_map *idmap_add(struct lxc_conf *conf, uid_t id, enum idtype type)
4355ab5f 3525{
28a2d9e7 3526 int hostid_mapped;
f8aa4bf3 3527 struct id_map *entry = NULL;
f8aa4bf3 3528
28a2d9e7
CB
3529 /* Reuse existing mapping. */
3530 entry = mapped_hostid_entry(conf, id, type);
3531 if (entry)
3532 return entry;
f8aa4bf3 3533
28a2d9e7
CB
3534 /* Find new mapping. */
3535 hostid_mapped = find_unmapped_nsid(conf, type);
3536 if (hostid_mapped < 0) {
3537 DEBUG("failed to find free mapping for id %d", id);
3538 return NULL;
f8aa4bf3 3539 }
f8aa4bf3 3540
28a2d9e7
CB
3541 entry = malloc(sizeof(*entry));
3542 if (!entry)
3543 return NULL;
4355ab5f 3544
28a2d9e7
CB
3545 entry->idtype = type;
3546 entry->nsid = hostid_mapped;
3547 entry->hostid = (unsigned long)id;
3548 entry->range = 1;
4355ab5f 3549
28a2d9e7 3550 return entry;
4355ab5f
SH
3551}
3552
f8aa4bf3
CB
3553/* Run a function in a new user namespace.
3554 * The caller's euid/egid will be mapped if it is not already.
3555 * Afaict, userns_exec_1() is only used to operate based on privileges for the
3556 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
3557 * This means we require only to establish a mapping from:
3558 * - the container root {g,u}id as seen from the host > user's host {g,u}id
3559 * - the container root -> some sub{g,u}id
3560 * The former we add, if the user did not specifiy a mapping. The latter we
3561 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
3562 * there to start the container in the first place.
4355ab5f 3563 */
c9b7c33e
CB
3564int userns_exec_1(struct lxc_conf *conf, int (*fn)(void *), void *data,
3565 const char *fn_name)
4355ab5f 3566{
f8aa4bf3
CB
3567 pid_t pid;
3568 uid_t euid, egid;
4355ab5f 3569 struct userns_fn_data d;
4355ab5f 3570 int p[2];
f8aa4bf3
CB
3571 struct lxc_list *it;
3572 struct id_map *map;
3573 char c = '1';
686dd5d1 3574 int ret = -1, status = -1;
f8aa4bf3 3575 struct lxc_list *idmap = NULL, *tmplist = NULL;
28a2d9e7
CB
3576 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
3577 *host_uid_map = NULL, *host_gid_map = NULL;
4355ab5f 3578
4355ab5f 3579 ret = pipe(p);
4355ab5f
SH
3580 if (ret < 0) {
3581 SYSERROR("opening pipe");
3582 return -1;
3583 }
3584 d.fn = fn;
c9b7c33e 3585 d.fn_name = fn_name;
4355ab5f
SH
3586 d.arg = data;
3587 d.p[0] = p[0];
3588 d.p[1] = p[1];
f8aa4bf3
CB
3589
3590 /* Clone child in new user namespace. */
4355ab5f 3591 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER);
f8aa4bf3
CB
3592 if (pid < 0) {
3593 ERROR("failed to clone child process in new user namespace");
3594 goto on_error;
3595 }
3596
4355ab5f 3597 close(p[0]);
4355ab5f
SH
3598 p[0] = -1;
3599
954b7d9b
CB
3600 euid = geteuid();
3601 egid = getegid();
3602
f8aa4bf3
CB
3603 /* Find container root. */
3604 lxc_list_for_each(it, &conf->id_map) {
3605 map = it->elem;
3606
3607 if (map->nsid != 0)
3608 continue;
3609
3610 if (map->idtype == ID_TYPE_UID && container_root_uid == NULL) {
3611 container_root_uid = malloc(sizeof(*container_root_uid));
3612 if (!container_root_uid)
3613 goto on_error;
3614 container_root_uid->idtype = map->idtype;
3615 container_root_uid->hostid = map->hostid;
3616 container_root_uid->nsid = 0;
3617 container_root_uid->range = map->range;
954b7d9b
CB
3618
3619 /* Check if container root mapping contains a mapping
3620 * for user's uid.
3621 */
3622 if (euid >= map->hostid && euid < map->hostid + map->range)
3623 host_uid_map = container_root_uid;
f8aa4bf3
CB
3624 } else if (map->idtype == ID_TYPE_GID && container_root_gid == NULL) {
3625 container_root_gid = malloc(sizeof(*container_root_gid));
3626 if (!container_root_gid)
3627 goto on_error;
3628 container_root_gid->idtype = map->idtype;
3629 container_root_gid->hostid = map->hostid;
3630 container_root_gid->nsid = 0;
3631 container_root_gid->range = map->range;
954b7d9b
CB
3632
3633 /* Check if container root mapping contains a mapping
3634 * for user's gid.
3635 */
3636 if (egid >= map->hostid && egid < map->hostid + map->range)
3637 host_gid_map = container_root_gid;
f8aa4bf3
CB
3638 }
3639
3640 /* Found container root. */
3641 if (container_root_uid && container_root_gid)
3642 break;
3643 }
3644
3645 /* This is actually checked earlier but it can't hurt. */
3646 if (!container_root_uid || !container_root_gid) {
3647 ERROR("no mapping for container root found");
3648 goto on_error;
3649 }
3650
3651 /* Check whether the {g,u}id of the user has a mapping. */
954b7d9b 3652 if (!host_uid_map)
28a2d9e7
CB
3653 host_uid_map = idmap_add(conf, euid, ID_TYPE_UID);
3654
954b7d9b 3655 if (!host_gid_map)
28a2d9e7
CB
3656 host_gid_map = idmap_add(conf, egid, ID_TYPE_GID);
3657
3658 if (!host_uid_map) {
3659 DEBUG("failed to find mapping for uid %d", euid);
f8aa4bf3
CB
3660 goto on_error;
3661 }
3662
28a2d9e7
CB
3663 if (!host_gid_map) {
3664 DEBUG("failed to find mapping for gid %d", egid);
3665 goto on_error;
3666 }
3667
3668 /* Allocate new {g,u}id map list. */
3669 idmap = malloc(sizeof(*idmap));
3670 if (!idmap)
3671 goto on_error;
3672 lxc_list_init(idmap);
3673
f8aa4bf3
CB
3674 /* Add container root to the map. */
3675 tmplist = malloc(sizeof(*tmplist));
3676 if (!tmplist)
3677 goto on_error;
3678 lxc_list_add_elem(tmplist, container_root_uid);
3679 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 3680
1d90e064 3681 if (host_uid_map && (host_uid_map != container_root_uid)) {
28a2d9e7
CB
3682 /* idmap will now keep track of that memory. */
3683 container_root_uid = NULL;
3684
3685 /* Add container root to the map. */
3686 tmplist = malloc(sizeof(*tmplist));
3687 if (!tmplist)
3688 goto on_error;
3689 lxc_list_add_elem(tmplist, host_uid_map);
3690 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 3691 }
1d90e064
CB
3692 /* idmap will now keep track of that memory. */
3693 container_root_uid = NULL;
3694 /* idmap will now keep track of that memory. */
3695 host_uid_map = NULL;
f8aa4bf3
CB
3696
3697 tmplist = malloc(sizeof(*tmplist));
3698 if (!tmplist)
3699 goto on_error;
3700 lxc_list_add_elem(tmplist, container_root_gid);
3701 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 3702
1d90e064 3703 if (host_gid_map && (host_gid_map != container_root_gid)) {
28a2d9e7
CB
3704 /* idmap will now keep track of that memory. */
3705 container_root_gid = NULL;
3706
3707 tmplist = malloc(sizeof(*tmplist));
3708 if (!tmplist)
3709 goto on_error;
3710 lxc_list_add_elem(tmplist, host_gid_map);
3711 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 3712 }
1d90e064
CB
3713 /* idmap will now keep track of that memory. */
3714 container_root_gid = NULL;
3715 /* idmap will now keep track of that memory. */
3716 host_gid_map = NULL;
f8aa4bf3 3717
4b73005c
CB
3718 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE ||
3719 conf->loglevel == LXC_LOG_LEVEL_TRACE) {
f8aa4bf3
CB
3720 lxc_list_for_each(it, idmap) {
3721 map = it->elem;
3722 TRACE("establishing %cid mapping for \"%d\" in new "
3723 "user namespace: nsuid %lu - hostid %lu - range "
3724 "%lu",
3725 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
3726 map->nsid, map->hostid, map->range);
3727 }
4355ab5f
SH
3728 }
3729
f8aa4bf3 3730 /* Set up {g,u}id mapping for user namespace of child process. */
4355ab5f 3731 ret = lxc_map_ids(idmap, pid);
f8aa4bf3
CB
3732 if (ret < 0) {
3733 ERROR("error setting up {g,u}id mappings for child process "
415a8851 3734 "\"%d\"", pid);
f8aa4bf3 3735 goto on_error;
4355ab5f
SH
3736 }
3737
f8aa4bf3 3738 /* Tell child to proceed. */
4355ab5f 3739 if (write(p[1], &c, 1) != 1) {
f8aa4bf3
CB
3740 SYSERROR("failed telling child process \"%d\" to proceed", pid);
3741 goto on_error;
4355ab5f
SH
3742 }
3743
686dd5d1 3744on_error:
f8aa4bf3 3745 /* Wait for child to finish. */
686dd5d1
CB
3746 if (pid > 0)
3747 status = wait_for_pid(pid);
3139aead 3748
1d90e064
CB
3749 if (idmap)
3750 lxc_free_idmap(idmap);
3751 if (container_root_uid)
3752 free(container_root_uid);
3753 if (container_root_gid)
3754 free(container_root_gid);
3755 if (host_uid_map && (host_uid_map != container_root_uid))
3756 free(host_uid_map);
3757 if (host_gid_map && (host_gid_map != container_root_gid))
3758 free(host_gid_map);
3139aead 3759
4355ab5f
SH
3760 if (p[0] != -1)
3761 close(p[0]);
3762 close(p[1]);
f8aa4bf3 3763
686dd5d1
CB
3764 if (status < 0)
3765 ret = -1;
3766
f8aa4bf3 3767 return ret;
4355ab5f 3768}
97e9cfa0 3769
415a8851
CB
3770int userns_exec_full(struct lxc_conf *conf, int (*fn)(void *), void *data,
3771 const char *fn_name)
3772{
3773 pid_t pid;
3774 uid_t euid, egid;
3775 struct userns_fn_data d;
3776 int p[2];
3777 struct id_map *map;
3778 struct lxc_list *cur;
3779 char c = '1';
3780 int ret = -1;
3781 struct lxc_list *idmap = NULL, *tmplist = NULL;
3782 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
3783 *host_uid_map = NULL, *host_gid_map = NULL;
3784
3785 ret = pipe(p);
3786 if (ret < 0) {
3787 SYSERROR("opening pipe");
3788 return -1;
3789 }
3790 d.fn = fn;
3791 d.fn_name = fn_name;
3792 d.arg = data;
3793 d.p[0] = p[0];
3794 d.p[1] = p[1];
3795
3796 /* Clone child in new user namespace. */
3797 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER);
3798 if (pid < 0) {
3799 ERROR("failed to clone child process in new user namespace");
3800 goto on_error;
3801 }
3802
3803 close(p[0]);
3804 p[0] = -1;
3805
3806 euid = geteuid();
3807 egid = getegid();
3808
3809 /* Allocate new {g,u}id map list. */
3810 idmap = malloc(sizeof(*idmap));
3811 if (!idmap)
3812 goto on_error;
3813 lxc_list_init(idmap);
3814
3815 /* Find container root. */
3816 lxc_list_for_each(cur, &conf->id_map) {
3817 struct id_map *tmpmap;
3818
3819 tmplist = malloc(sizeof(*tmplist));
3820 if (!tmplist)
3821 goto on_error;
3822
3823 tmpmap = malloc(sizeof(*tmpmap));
3824 if (!tmpmap) {
3825 free(tmplist);
3826 goto on_error;
3827 }
3828
3829 memset(tmpmap, 0, sizeof(*tmpmap));
3830 memcpy(tmpmap, cur->elem, sizeof(*tmpmap));
3831 tmplist->elem = tmpmap;
3832
3833 lxc_list_add_tail(idmap, tmplist);
3834
3835 map = cur->elem;
3836
3837 if (map->idtype == ID_TYPE_UID)
3838 if (euid >= map->hostid && euid < map->hostid + map->range)
3839 host_uid_map = map;
3840
3841 if (map->idtype == ID_TYPE_GID)
3842 if (egid >= map->hostid && egid < map->hostid + map->range)
3843 host_gid_map = map;
3844
3845 if (map->nsid != 0)
3846 continue;
3847
3848 if (map->idtype == ID_TYPE_UID)
3849 if (container_root_uid == NULL)
3850 container_root_uid = map;
3851
3852 if (map->idtype == ID_TYPE_GID)
3853 if (container_root_gid == NULL)
3854 container_root_gid = map;
3855 }
3856
3857 if (!container_root_uid || !container_root_gid) {
3858 ERROR("No mapping for container root found");
3859 goto on_error;
3860 }
3861
3862 /* Check whether the {g,u}id of the user has a mapping. */
3863 if (!host_uid_map)
3864 host_uid_map = idmap_add(conf, euid, ID_TYPE_UID);
3865 else
3866 host_uid_map = container_root_uid;
3867
3868 if (!host_gid_map)
3869 host_gid_map = idmap_add(conf, egid, ID_TYPE_GID);
3870 else
3871 host_gid_map = container_root_gid;
3872
3873 if (!host_uid_map) {
3874 DEBUG("Failed to find mapping for uid %d", euid);
3875 goto on_error;
3876 }
3877
3878 if (!host_gid_map) {
3879 DEBUG("Failed to find mapping for gid %d", egid);
3880 goto on_error;
3881 }
3882
3883 if (host_uid_map && (host_uid_map != container_root_uid)) {
3884 /* Add container root to the map. */
3885 tmplist = malloc(sizeof(*tmplist));
3886 if (!tmplist)
3887 goto on_error;
3888 lxc_list_add_elem(tmplist, host_uid_map);
3889 lxc_list_add_tail(idmap, tmplist);
3890 }
3891 /* idmap will now keep track of that memory. */
3892 host_uid_map = NULL;
3893
3894 if (host_gid_map && (host_gid_map != container_root_gid)) {
3895 tmplist = malloc(sizeof(*tmplist));
3896 if (!tmplist)
3897 goto on_error;
3898 lxc_list_add_elem(tmplist, host_gid_map);
3899 lxc_list_add_tail(idmap, tmplist);
3900 }
3901 /* idmap will now keep track of that memory. */
3902 host_gid_map = NULL;
3903
3904 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE ||
3905 conf->loglevel == LXC_LOG_LEVEL_TRACE) {
3906 lxc_list_for_each(cur, idmap) {
3907 map = cur->elem;
3908 TRACE("establishing %cid mapping for \"%d\" in new "
3909 "user namespace: nsuid %lu - hostid %lu - range "
3910 "%lu",
3911 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
3912 map->nsid, map->hostid, map->range);
3913 }
3914 }
3915
3916 /* Set up {g,u}id mapping for user namespace of child process. */
3917 ret = lxc_map_ids(idmap, pid);
3918 if (ret < 0) {
3919 ERROR("error setting up {g,u}id mappings for child process "
3920 "\"%d\"", pid);
3921 goto on_error;
3922 }
3923
3924 /* Tell child to proceed. */
3925 if (write(p[1], &c, 1) != 1) {
3926 SYSERROR("failed telling child process \"%d\" to proceed", pid);
3927 goto on_error;
3928 }
3929
686dd5d1 3930on_error:
415a8851 3931 /* Wait for child to finish. */
686dd5d1
CB
3932 if (pid > 0)
3933 ret = wait_for_pid(pid);
415a8851 3934
415a8851
CB
3935 if (idmap)
3936 lxc_free_idmap(idmap);
3937 if (host_uid_map && (host_uid_map != container_root_uid))
3938 free(host_uid_map);
3939 if (host_gid_map && (host_gid_map != container_root_gid))
3940 free(host_gid_map);
3941
3942 if (p[0] != -1)
3943 close(p[0]);
3944 close(p[1]);
3945
3946 return ret;
3947}
3948
a96a8e8c 3949/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
3950static char* getuname(void)
3951{
a96a8e8c 3952 struct passwd *result;
97e9cfa0 3953
a96a8e8c
SH
3954 result = getpwuid(geteuid());
3955 if (!result)
97e9cfa0
SH
3956 return NULL;
3957
a96a8e8c 3958 return strdup(result->pw_name);
97e9cfa0
SH
3959}
3960
a96a8e8c 3961/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
3962static char *getgname(void)
3963{
a96a8e8c 3964 struct group *result;
97e9cfa0 3965
a96a8e8c
SH
3966 result = getgrgid(getegid());
3967 if (!result)
97e9cfa0
SH
3968 return NULL;
3969
a96a8e8c 3970 return strdup(result->gr_name);
97e9cfa0
SH
3971}
3972
a96a8e8c 3973/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
3974void suggest_default_idmap(void)
3975{
3976 FILE *f;
3977 unsigned int uid = 0, urange = 0, gid = 0, grange = 0;
3978 char *line = NULL;
3979 char *uname, *gname;
3980 size_t len = 0;
3981
3982 if (!(uname = getuname()))
3983 return;
3984
3985 if (!(gname = getgname())) {
3986 free(uname);
3987 return;
3988 }
3989
3990 f = fopen(subuidfile, "r");
3991 if (!f) {
3992 ERROR("Your system is not configured with subuids");
3993 free(gname);
3994 free(uname);
3995 return;
3996 }
3997 while (getline(&line, &len, f) != -1) {
b7930180 3998 size_t no_newline = 0;
97e9cfa0
SH
3999 char *p = strchr(line, ':'), *p2;
4000 if (*line == '#')
4001 continue;
4002 if (!p)
4003 continue;
4004 *p = '\0';
4005 p++;
4006 if (strcmp(line, uname))
4007 continue;
4008 p2 = strchr(p, ':');
4009 if (!p2)
4010 continue;
4011 *p2 = '\0';
4012 p2++;
4013 if (!*p2)
4014 continue;
b7930180
CB
4015 no_newline = strcspn(p2, "\n");
4016 p2[no_newline] = '\0';
4017
b7b2fde4
CB
4018 if (lxc_safe_uint(p, &uid) < 0)
4019 WARN("Could not parse UID.");
4020 if (lxc_safe_uint(p2, &urange) < 0)
4021 WARN("Could not parse UID range.");
97e9cfa0
SH
4022 }
4023 fclose(f);
4024
6be7389a 4025 f = fopen(subgidfile, "r");
97e9cfa0
SH
4026 if (!f) {
4027 ERROR("Your system is not configured with subgids");
4028 free(gname);
4029 free(uname);
4030 return;
4031 }
4032 while (getline(&line, &len, f) != -1) {
b7930180 4033 size_t no_newline = 0;
97e9cfa0
SH
4034 char *p = strchr(line, ':'), *p2;
4035 if (*line == '#')
4036 continue;
4037 if (!p)
4038 continue;
4039 *p = '\0';
4040 p++;
4041 if (strcmp(line, uname))
4042 continue;
4043 p2 = strchr(p, ':');
4044 if (!p2)
4045 continue;
4046 *p2 = '\0';
4047 p2++;
4048 if (!*p2)
4049 continue;
b7930180
CB
4050 no_newline = strcspn(p2, "\n");
4051 p2[no_newline] = '\0';
4052
b7b2fde4
CB
4053 if (lxc_safe_uint(p, &gid) < 0)
4054 WARN("Could not parse GID.");
4055 if (lxc_safe_uint(p2, &grange) < 0)
4056 WARN("Could not parse GID range.");
97e9cfa0
SH
4057 }
4058 fclose(f);
4059
f10fad2f 4060 free(line);
97e9cfa0
SH
4061
4062 if (!urange || !grange) {
4063 ERROR("You do not have subuids or subgids allocated");
4064 ERROR("Unprivileged containers require subuids and subgids");
4065 return;
4066 }
4067
4068 ERROR("You must either run as root, or define uid mappings");
4069 ERROR("To pass uid mappings to lxc-create, you could create");
4070 ERROR("~/.config/lxc/default.conf:");
4071 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG);
bdcbb6b3
CB
4072 ERROR("lxc.idmap = u 0 %u %u", uid, urange);
4073 ERROR("lxc.idmap = g 0 %u %u", gid, grange);
97e9cfa0
SH
4074
4075 free(gname);
4076 free(uname);
4077}
aaf26830 4078
a7307747
SH
4079static void free_cgroup_settings(struct lxc_list *result)
4080{
4081 struct lxc_list *iterator, *next;
4082
4083 lxc_list_for_each_safe(iterator, result, next) {
4084 lxc_list_del(iterator);
4085 free(iterator);
4086 }
4087 free(result);
4088}
4089
aaf26830
KT
4090/*
4091 * Return the list of cgroup_settings sorted according to the following rules
4092 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4093 */
4094struct lxc_list *sort_cgroup_settings(struct lxc_list* cgroup_settings)
4095{
4096 struct lxc_list *result;
4097 struct lxc_list *memsw_limit = NULL;
4098 struct lxc_list *it = NULL;
4099 struct lxc_cgroup *cg = NULL;
4100 struct lxc_list *item = NULL;
4101
4102 result = malloc(sizeof(*result));
fac7c663
KT
4103 if (!result) {
4104 ERROR("failed to allocate memory to sort cgroup settings");
4105 return NULL;
4106 }
aaf26830
KT
4107 lxc_list_init(result);
4108
4109 /*Iterate over the cgroup settings and copy them to the output list*/
4110 lxc_list_for_each(it, cgroup_settings) {
4111 item = malloc(sizeof(*item));
fac7c663
KT
4112 if (!item) {
4113 ERROR("failed to allocate memory to sort cgroup settings");
a7307747 4114 free_cgroup_settings(result);
fac7c663
KT
4115 return NULL;
4116 }
aaf26830
KT
4117 item->elem = it->elem;
4118 cg = it->elem;
4119 if (strcmp(cg->subsystem, "memory.memsw.limit_in_bytes") == 0) {
4120 /* Store the memsw_limit location */
4121 memsw_limit = item;
4122 } else if (strcmp(cg->subsystem, "memory.limit_in_bytes") == 0 && memsw_limit != NULL) {
4d5b72a1 4123 /* lxc.cgroup.memory.memsw.limit_in_bytes is found before
aaf26830
KT
4124 * lxc.cgroup.memory.limit_in_bytes, swap these two items */
4125 item->elem = memsw_limit->elem;
4126 memsw_limit->elem = it->elem;
4127 }
4128 lxc_list_add_tail(result, item);
4129 }
4130
4131 return result;
a7307747 4132}