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