]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/conf.c
network: fix socket handle leak
[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
2202afc9
CB
760 if (!handler->cgroup_ops->mount(handler->cgroup_ops,
761 handler,
762 conf->rootfs.path ? conf->rootfs.mount : "",
763 cg_flags)) {
0fd73091 764 SYSERROR("Failed to mount \"/sys/fs/cgroup\"");
b06b8511 765 return -1;
368bbc02
CS
766 }
767 }
768
368bbc02 769 return 0;
368bbc02
CS
770}
771
4e5440c6 772static int setup_utsname(struct utsname *utsname)
0ad19a3f 773{
0fd73091
CB
774 int ret;
775
4e5440c6
DL
776 if (!utsname)
777 return 0;
0ad19a3f 778
0fd73091
CB
779 ret = sethostname(utsname->nodename, strlen(utsname->nodename));
780 if (ret < 0) {
781 SYSERROR("Failed to set the hostname to \"%s\"", utsname->nodename);
0ad19a3f 782 return -1;
783 }
784
0fd73091 785 INFO("Set hostname to \"%s\"", utsname->nodename);
cd54d859 786
0ad19a3f 787 return 0;
788}
789
69aa6655
DE
790struct dev_symlinks {
791 const char *oldpath;
792 const char *name;
793};
794
795static const struct dev_symlinks dev_symlinks[] = {
0fd73091
CB
796 { "/proc/self/fd", "fd" },
797 { "/proc/self/fd/0", "stdin" },
798 { "/proc/self/fd/1", "stdout" },
799 { "/proc/self/fd/2", "stderr" },
69aa6655
DE
800};
801
ed8704d0 802static int lxc_setup_dev_symlinks(const struct lxc_rootfs *rootfs)
69aa6655 803{
0fd73091 804 int i, ret;
69aa6655 805 char path[MAXPATHLEN];
09227be2 806 struct stat s;
69aa6655 807
69aa6655
DE
808 for (i = 0; i < sizeof(dev_symlinks) / sizeof(dev_symlinks[0]); i++) {
809 const struct dev_symlinks *d = &dev_symlinks[i];
0fd73091
CB
810
811 ret = snprintf(path, sizeof(path), "%s/dev/%s",
812 rootfs->path ? rootfs->mount : "", d->name);
69aa6655
DE
813 if (ret < 0 || ret >= MAXPATHLEN)
814 return -1;
09227be2 815
0fd73091
CB
816 /* Stat the path first. If we don't get an error accept it as
817 * is and don't try to create it
09227be2 818 */
0fd73091
CB
819 ret = stat(path, &s);
820 if (ret == 0)
09227be2 821 continue;
09227be2 822
69aa6655
DE
823 ret = symlink(d->oldpath, path);
824 if (ret && errno != EEXIST) {
0fd73091
CB
825 if (errno == EROFS) {
826 WARN("Failed to create \"%s\". Read-only filesystem", path);
09227be2 827 } else {
0fd73091 828 SYSERROR("Failed to create \"%s\"", path);
09227be2
MW
829 return -1;
830 }
69aa6655
DE
831 }
832 }
0fd73091 833
69aa6655
DE
834 return 0;
835}
836
2187efd3 837/* Build a space-separate list of ptys to pass to systemd. */
885766f5 838static bool append_ttyname(char **pp, char *name)
b0a33c1e 839{
393903d1
SH
840 char *p;
841
842 if (!*pp) {
843 *pp = malloc(strlen(name) + strlen("container_ttys=") + 1);
844 if (!*pp)
845 return false;
0fd73091 846
393903d1
SH
847 sprintf(*pp, "container_ttys=%s", name);
848 return true;
849 }
0fd73091 850
393903d1
SH
851 p = realloc(*pp, strlen(*pp) + strlen(name) + 2);
852 if (!p)
853 return false;
0fd73091 854
393903d1
SH
855 *pp = p;
856 strcat(p, " ");
857 strcat(p, name);
0fd73091 858
393903d1
SH
859 return true;
860}
861
2187efd3 862static int lxc_setup_ttys(struct lxc_conf *conf)
393903d1 863{
9e1045e3 864 int i, ret;
0e4be3cf 865 const struct lxc_tty_info *ttys = &conf->ttys;
885766f5 866 char *ttydir = ttys->dir;
7c6ef2a2 867 char path[MAXPATHLEN], lxcpath[MAXPATHLEN];
b0a33c1e 868
e8bd4e43 869 if (!conf->rootfs.path)
bc9bd0e3
DL
870 return 0;
871
885766f5 872 for (i = 0; i < ttys->max; i++) {
0e4be3cf 873 struct lxc_terminal_info *tty = &ttys->tty[i];
b0a33c1e 874
e8bd4e43 875 ret = snprintf(path, sizeof(path), "/dev/tty%d", i + 1);
73363c61 876 if (ret < 0 || (size_t)ret >= sizeof(path))
7c6ef2a2 877 return -1;
9e1045e3 878
7c6ef2a2
SH
879 if (ttydir) {
880 /* create dev/lxc/tty%d" */
9e1045e3
CB
881 ret = snprintf(lxcpath, sizeof(lxcpath),
882 "/dev/%s/tty%d", ttydir, i + 1);
73363c61 883 if (ret < 0 || (size_t)ret >= sizeof(lxcpath))
7c6ef2a2 884 return -1;
9e1045e3 885
7c6ef2a2 886 ret = creat(lxcpath, 0660);
9e1045e3 887 if (ret < 0 && errno != EEXIST) {
73363c61 888 SYSERROR("Failed to create \"%s\"", lxcpath);
7c6ef2a2
SH
889 return -1;
890 }
4d44e274
SH
891 if (ret >= 0)
892 close(ret);
9e1045e3 893
7c6ef2a2 894 ret = unlink(path);
9e1045e3 895 if (ret < 0 && errno != ENOENT) {
73363c61 896 SYSERROR("Failed to unlink \"%s\"", path);
7c6ef2a2
SH
897 return -1;
898 }
b0a33c1e 899
2520facd 900 ret = mount(tty->name, lxcpath, "none", MS_BIND, 0);
9e1045e3 901 if (ret < 0) {
73363c61 902 WARN("Failed to bind mount \"%s\" onto \"%s\"",
2520facd 903 tty->name, path);
7c6ef2a2
SH
904 continue;
905 }
0fd73091 906 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty->name,
9e1045e3 907 path);
13954cce 908
9e1045e3
CB
909 ret = snprintf(lxcpath, sizeof(lxcpath), "%s/tty%d",
910 ttydir, i + 1);
73363c61 911 if (ret < 0 || (size_t)ret >= sizeof(lxcpath))
9ba8130c 912 return -1;
9e1045e3 913
7c6ef2a2 914 ret = symlink(lxcpath, path);
9e1045e3 915 if (ret < 0) {
73363c61 916 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
9e1045e3 917 path, lxcpath);
7c6ef2a2
SH
918 return -1;
919 }
920 } else {
9e1045e3
CB
921 /* If we populated /dev, then we need to create
922 * /dev/ttyN
923 */
924 ret = access(path, F_OK);
925 if (ret < 0) {
c6883f38 926 ret = creat(path, 0660);
9e1045e3 927 if (ret < 0) {
73363c61 928 SYSERROR("Failed to create \"%s\"", path);
c6883f38 929 /* this isn't fatal, continue */
025ed0f3 930 } else {
c6883f38 931 close(ret);
025ed0f3 932 }
c6883f38 933 }
9e1045e3 934
2520facd 935 ret = mount(tty->name, path, "none", MS_BIND, 0);
9e1045e3 936 if (ret < 0) {
2520facd 937 SYSERROR("Failed to mount '%s'->'%s'", tty->name, path);
7c6ef2a2
SH
938 continue;
939 }
9e1045e3 940
2520facd 941 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty->name,
9e1045e3 942 path);
393903d1 943 }
9e1045e3 944
885766f5 945 if (!append_ttyname(&conf->ttys.tty_names, tty->name)) {
393903d1
SH
946 ERROR("Error setting up container_ttys string");
947 return -1;
b0a33c1e 948 }
949 }
950
885766f5 951 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys->max);
b0a33c1e 952 return 0;
953}
954
2187efd3
CB
955int lxc_allocate_ttys(const char *name, struct lxc_conf *conf)
956{
2187efd3 957 int i, ret;
0fd73091 958 struct lxc_tty_info *ttys = &conf->ttys;
2187efd3
CB
959
960 /* no tty in the configuration */
885766f5 961 if (ttys->max == 0)
2187efd3
CB
962 return 0;
963
885766f5 964 ttys->tty = malloc(sizeof(*ttys->tty) * ttys->max);
0e4be3cf 965 if (!ttys->tty)
2187efd3 966 return -ENOMEM;
2187efd3 967
885766f5 968 for (i = 0; i < ttys->max; i++) {
0e4be3cf 969 struct lxc_terminal_info *tty = &ttys->tty[i];
2187efd3 970
2520facd
CB
971 ret = openpty(&tty->master, &tty->slave,
972 tty->name, NULL, NULL);
2187efd3 973 if (ret) {
0fd73091 974 SYSERROR("Failed to create tty %d", i);
885766f5 975 ttys->max = i;
0e4be3cf 976 lxc_delete_tty(ttys);
2187efd3
CB
977 return -ENOTTY;
978 }
979
0fd73091 980 DEBUG("Created tty \"%s\" with master fd %d and slave fd %d",
2520facd 981 tty->name, tty->master, tty->slave);
2187efd3
CB
982
983 /* Prevent leaking the file descriptors to the container */
2520facd 984 ret = fcntl(tty->master, F_SETFD, FD_CLOEXEC);
2187efd3 985 if (ret < 0)
0fd73091
CB
986 WARN("Failed to set FD_CLOEXEC flag on master fd %d of "
987 "tty device \"%s\": %s",
2520facd 988 tty->master, tty->name, strerror(errno));
2187efd3 989
2520facd 990 ret = fcntl(tty->slave, F_SETFD, FD_CLOEXEC);
2187efd3 991 if (ret < 0)
0fd73091
CB
992 WARN("Failed to set FD_CLOEXEC flag on slave fd %d of "
993 "tty device \"%s\": %s",
2520facd 994 tty->slave, tty->name, strerror(errno));
2187efd3 995
2520facd 996 tty->busy = 0;
2187efd3
CB
997 }
998
885766f5 999 INFO("Finished creating %zu tty devices", ttys->max);
2187efd3
CB
1000 return 0;
1001}
1002
0e4be3cf 1003void lxc_delete_tty(struct lxc_tty_info *ttys)
2187efd3
CB
1004{
1005 int i;
1006
885766f5 1007 for (i = 0; i < ttys->max; i++) {
0e4be3cf 1008 struct lxc_terminal_info *tty = &ttys->tty[i];
2187efd3 1009
2520facd
CB
1010 close(tty->master);
1011 close(tty->slave);
2187efd3
CB
1012 }
1013
0e4be3cf
CB
1014 free(ttys->tty);
1015 ttys->tty = NULL;
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
885766f5 1026 if (ttys->max == 0)
2187efd3
CB
1027 return 0;
1028
885766f5 1029 for (i = 0; i < ttys->max; i++) {
2187efd3 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)
885766f5 1045 ERROR("Failed to send %zu ttys to parent: %s", ttys->max,
2187efd3
CB
1046 strerror(errno));
1047 else
885766f5 1048 TRACE("Sent %zu ttys to parent", ttys->max);
2187efd3
CB
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
885766f5
CB
1078 if (conf->ttys.tty_names) {
1079 ret = setenv("container_ttys", conf->ttys.tty_names, 1);
2187efd3 1080 if (ret < 0)
885766f5 1081 SYSERROR("Failed to set \"container_ttys=%s\"", conf->ttys.tty_names);
2187efd3
CB
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
e528c735 1526 if (conf->pty_max <= 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
e528c735
CB
1532 ret = snprintf(devpts_mntopts, sizeof(devpts_mntopts), "%s,max=%zu",
1533 default_devpts_mntopts, conf->pty_max);
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);
395b1a3e 2702 close(fd);
2388737b 2703 if (ret != buflen) {
0fd73091
CB
2704 SYSERROR("Failed to write \"deny\" to "
2705 "\"/proc/%d/setgroups\"", pid);
2388737b
CB
2706 return -1;
2707 }
395b1a3e 2708 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid);
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);
395b1a3e 2725 close(fd);
29053180 2726 if (ret != buf_size) {
a19b974f 2727 SYSERROR("Failed to write %cid mapping to \"%s\"",
29053180 2728 idtype == ID_TYPE_UID ? 'u' : 'g', path);
29053180
CB
2729 return -1;
2730 }
29053180
CB
2731
2732 return 0;
f6d3e3e4
SH
2733}
2734
6e50e704
CB
2735/* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2736 *
2737 * @return 1 if functional binary was found
2738 * @return 0 if binary exists but is lacking privilege
2739 * @return -ENOENT if binary does not exist
2740 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
6e50e704 2741 */
df6a2945
CB
2742static int idmaptool_on_path_and_privileged(const char *binary, cap_value_t cap)
2743{
2744 char *path;
2745 int ret;
2746 struct stat st;
2747 int fret = 0;
2748
6e50e704
CB
2749 if (cap != CAP_SETUID && cap != CAP_SETGID)
2750 return -EINVAL;
2751
df6a2945
CB
2752 path = on_path(binary, NULL);
2753 if (!path)
2754 return -ENOENT;
2755
2756 ret = stat(path, &st);
2757 if (ret < 0) {
2758 fret = -errno;
2759 goto cleanup;
2760 }
2761
2762 /* Check if the binary is setuid. */
2763 if (st.st_mode & S_ISUID) {
0fd73091 2764 DEBUG("The binary \"%s\" does have the setuid bit set", path);
df6a2945
CB
2765 fret = 1;
2766 goto cleanup;
2767 }
2768
0fd73091 2769#if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
df6a2945
CB
2770 /* Check if it has the CAP_SETUID capability. */
2771 if ((cap & CAP_SETUID) &&
2772 lxc_file_cap_is_set(path, CAP_SETUID, CAP_EFFECTIVE) &&
2773 lxc_file_cap_is_set(path, CAP_SETUID, CAP_PERMITTED)) {
2774 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
0fd73091 2775 "and CAP_PERMITTED sets", path);
df6a2945
CB
2776 fret = 1;
2777 goto cleanup;
2778 }
2779
2780 /* Check if it has the CAP_SETGID capability. */
2781 if ((cap & CAP_SETGID) &&
2782 lxc_file_cap_is_set(path, CAP_SETGID, CAP_EFFECTIVE) &&
2783 lxc_file_cap_is_set(path, CAP_SETGID, CAP_PERMITTED)) {
2784 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
0fd73091 2785 "and CAP_PERMITTED sets", path);
df6a2945
CB
2786 fret = 1;
2787 goto cleanup;
2788 }
0fd73091 2789#else
69924fff
CB
2790 /* If we cannot check for file capabilities we need to give the benefit
2791 * of the doubt. Otherwise we might fail even though all the necessary
2792 * file capabilities are set.
2793 */
d6018f88 2794 DEBUG("Cannot check for file capabilites as full capability support is "
0fd73091 2795 "missing. Manual intervention needed");
d6018f88 2796 fret = 1;
0fd73091 2797#endif
df6a2945
CB
2798
2799cleanup:
2800 free(path);
2801 return fret;
2802}
2803
986ef930
CB
2804int lxc_map_ids_exec_wrapper(void *args)
2805{
2806 execl("/bin/sh", "sh", "-c", (char *)args, (char *)NULL);
2807 return -1;
2808}
2809
f6d3e3e4
SH
2810int lxc_map_ids(struct lxc_list *idmap, pid_t pid)
2811{
0fd73091 2812 int fill, left;
986ef930 2813 char u_or_g;
4bc3b759 2814 char *pos;
986ef930 2815 char cmd_output[MAXPATHLEN];
0fd73091
CB
2816 struct id_map *map;
2817 struct lxc_list *iterator;
2818 enum idtype type;
986ef930
CB
2819 /* strlen("new@idmap") = 9
2820 * +
2821 * strlen(" ") = 1
2822 * +
2823 * LXC_NUMSTRLEN64
2824 * +
2825 * strlen(" ") = 1
2826 *
2827 * We add some additional space to make sure that we really have
2828 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2829 */
0fd73091 2830 int ret = 0, gidmap = 0, uidmap = 0;
986ef930 2831 char mapbuf[9 + 1 + LXC_NUMSTRLEN64 + 1 + LXC_IDMAPLEN] = {0};
0fd73091 2832 bool had_entry = false, use_shadow = false;
df6a2945
CB
2833
2834 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2835 * ranges, then insist that root also reserve ranges in subuid. This
22038de5
SH
2836 * will protected it by preventing another user from being handed the
2837 * range by shadow.
2838 */
df6a2945 2839 uidmap = idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID);
6e50e704
CB
2840 if (uidmap == -ENOENT)
2841 WARN("newuidmap binary is missing");
2842 else if (!uidmap)
2843 WARN("newuidmap is lacking necessary privileges");
2844
df6a2945 2845 gidmap = idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID);
6e50e704
CB
2846 if (gidmap == -ENOENT)
2847 WARN("newgidmap binary is missing");
2848 else if (!gidmap)
2849 WARN("newgidmap is lacking necessary privileges");
2850
df6a2945 2851 if (uidmap > 0 && gidmap > 0) {
0fd73091 2852 DEBUG("Functional newuidmap and newgidmap binary found");
4bc3b759 2853 use_shadow = true;
df6a2945 2854 } else {
99d43365
CB
2855 /* In case unprivileged users run application containers via
2856 * execute() or a start*() there are valid cases where they may
2857 * only want to map their own {g,u}id. Let's not block them from
2858 * doing so by requiring geteuid() == 0.
2859 */
2860 DEBUG("No newuidmap and newgidmap binary found. Trying to "
0fd73091 2861 "write directly with euid %d", geteuid());
0e6e3a41 2862 }
251d0d2a 2863
986ef930
CB
2864 for (type = ID_TYPE_UID, u_or_g = 'u'; type <= ID_TYPE_GID;
2865 type++, u_or_g = 'g') {
2866 pos = mapbuf;
2867
0e6e3a41 2868 if (use_shadow)
986ef930 2869 pos += sprintf(mapbuf, "new%cidmap %d", u_or_g, pid);
4f7521b4 2870
cf3ef16d 2871 lxc_list_for_each(iterator, idmap) {
251d0d2a 2872 map = iterator->elem;
cf3ef16d
SH
2873 if (map->idtype != type)
2874 continue;
2875
4bc3b759
CB
2876 had_entry = true;
2877
986ef930 2878 left = LXC_IDMAPLEN - (pos - mapbuf);
d1838f34 2879 fill = snprintf(pos, left, "%s%lu %lu %lu%s",
4bc3b759
CB
2880 use_shadow ? " " : "", map->nsid,
2881 map->hostid, map->range,
0e6e3a41 2882 use_shadow ? "" : "\n");
a427e268
CB
2883 if (fill <= 0 || fill >= left) {
2884 /* The kernel only takes <= 4k for writes to
2885 * /proc/<pid>/{g,u}id_map
2886 */
2887 SYSERROR("Too many %cid mappings defined", u_or_g);
2888 return -1;
2889 }
4bc3b759 2890
cf3ef16d 2891 pos += fill;
251d0d2a 2892 }
cf3ef16d 2893 if (!had_entry)
4f7521b4 2894 continue;
cf3ef16d 2895
986ef930
CB
2896 /* Try to catch the ouput of new{g,u}idmap to make debugging
2897 * easier.
2898 */
2899 if (use_shadow) {
2900 ret = run_command(cmd_output, sizeof(cmd_output),
2901 lxc_map_ids_exec_wrapper,
2902 (void *)mapbuf);
2903 if (ret < 0) {
54fbbeb5
CB
2904 ERROR("new%cidmap failed to write mapping \"%s\": %s",
2905 u_or_g, cmd_output, mapbuf);
986ef930
CB
2906 return -1;
2907 }
54fbbeb5 2908 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g, mapbuf);
d1838f34 2909 } else {
986ef930 2910 ret = write_id_mapping(type, pid, mapbuf, pos - mapbuf);
54fbbeb5 2911 if (ret < 0) {
da0f9977 2912 ERROR("Failed to write mapping: %s", mapbuf);
986ef930 2913 return -1;
54fbbeb5
CB
2914 }
2915 TRACE("Wrote mapping \"%s\"", mapbuf);
d1838f34 2916 }
986ef930
CB
2917
2918 memset(mapbuf, 0, sizeof(mapbuf));
f6d3e3e4 2919 }
251d0d2a 2920
986ef930 2921 return 0;
f6d3e3e4
SH
2922}
2923
0fd73091 2924/* Return the host uid/gid to which the container root is mapped in val.
0b3a6504 2925 * Return true if id was found, false otherwise.
cf3ef16d 2926 */
2a9a80cb 2927bool get_mapped_rootid(struct lxc_conf *conf, enum idtype idtype,
4160c3a0 2928 unsigned long *val)
cf3ef16d 2929{
4160c3a0 2930 unsigned nsid;
0fd73091
CB
2931 struct id_map *map;
2932 struct lxc_list *it;
4160c3a0
CB
2933
2934 if (idtype == ID_TYPE_UID)
2935 nsid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
2936 else
2937 nsid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
cf3ef16d 2938
0fd73091 2939 lxc_list_for_each (it, &conf->id_map) {
cf3ef16d 2940 map = it->elem;
7b50c609 2941 if (map->idtype != idtype)
cf3ef16d 2942 continue;
4160c3a0 2943 if (map->nsid != nsid)
cf3ef16d 2944 continue;
2a9a80cb
SH
2945 *val = map->hostid;
2946 return true;
cf3ef16d 2947 }
4160c3a0 2948
2a9a80cb 2949 return false;
cf3ef16d
SH
2950}
2951
2133f58c 2952int mapped_hostid(unsigned id, struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 2953{
cf3ef16d 2954 struct id_map *map;
0fd73091
CB
2955 struct lxc_list *it;
2956
2957 lxc_list_for_each (it, &conf->id_map) {
cf3ef16d 2958 map = it->elem;
2133f58c 2959 if (map->idtype != idtype)
cf3ef16d 2960 continue;
0fd73091 2961
cf3ef16d 2962 if (id >= map->hostid && id < map->hostid + map->range)
57d116ab 2963 return (id - map->hostid) + map->nsid;
cf3ef16d 2964 }
0fd73091 2965
57d116ab 2966 return -1;
cf3ef16d
SH
2967}
2968
339efad9 2969int find_unmapped_nsid(struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 2970{
cf3ef16d 2971 struct id_map *map;
0fd73091 2972 struct lxc_list *it;
2133f58c 2973 unsigned int freeid = 0;
0fd73091 2974
cf3ef16d 2975again:
0fd73091 2976 lxc_list_for_each (it, &conf->id_map) {
cf3ef16d 2977 map = it->elem;
2133f58c 2978 if (map->idtype != idtype)
cf3ef16d 2979 continue;
0fd73091 2980
cf3ef16d
SH
2981 if (freeid >= map->nsid && freeid < map->nsid + map->range) {
2982 freeid = map->nsid + map->range;
2983 goto again;
2984 }
2985 }
0fd73091 2986
cf3ef16d
SH
2987 return freeid;
2988}
2989
f4f52cb5
CB
2990int chown_mapped_root_exec_wrapper(void *args)
2991{
2992 execvp("lxc-usernsexec", args);
2993 return -1;
2994}
2995
0fd73091 2996/* chown_mapped_root: for an unprivileged user with uid/gid X to
7b50c609
TS
2997 * chown a dir to subuid/subgid Y, he needs to run chown as root
2998 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
2999 * nsid Y is mapped to hostuid/hostgid X. That way, the container
3000 * root is privileged with respect to hostuid/hostgid X, allowing
3001 * him to do the chown.
f6d3e3e4 3002 */
41dc7155 3003int chown_mapped_root(const char *path, struct lxc_conf *conf)
f6d3e3e4 3004{
f4f52cb5 3005 uid_t rootuid, rootgid;
2a9a80cb 3006 unsigned long val;
f4f52cb5
CB
3007 int hostuid, hostgid, ret;
3008 struct stat sb;
3009 char map1[100], map2[100], map3[100], map4[100], map5[100];
3010 char ugid[100];
41dc7155 3011 const char *args1[] = {"lxc-usernsexec",
f4f52cb5
CB
3012 "-m", map1,
3013 "-m", map2,
3014 "-m", map3,
3015 "-m", map5,
3016 "--", "chown", ugid, path,
3017 NULL};
41dc7155 3018 const char *args2[] = {"lxc-usernsexec",
f4f52cb5
CB
3019 "-m", map1,
3020 "-m", map2,
3021 "-m", map3,
3022 "-m", map4,
3023 "-m", map5,
3024 "--", "chown", ugid, path,
3025 NULL};
3026 char cmd_output[MAXPATHLEN];
3027
3028 hostuid = geteuid();
3029 hostgid = getegid();
f6d3e3e4 3030
2a9a80cb 3031 if (!get_mapped_rootid(conf, ID_TYPE_UID, &val)) {
bc80f098 3032 ERROR("No uid mapping for container root");
c4d10a05 3033 return -1;
f6d3e3e4 3034 }
f4f52cb5 3035 rootuid = (uid_t)val;
0fd73091 3036
7b50c609 3037 if (!get_mapped_rootid(conf, ID_TYPE_GID, &val)) {
bc80f098 3038 ERROR("No gid mapping for container root");
7b50c609
TS
3039 return -1;
3040 }
f4f52cb5 3041 rootgid = (gid_t)val;
2a9a80cb 3042
f4f52cb5 3043 if (hostuid == 0) {
7b50c609 3044 if (chown(path, rootuid, rootgid) < 0) {
c4d10a05
SH
3045 ERROR("Error chowning %s", path);
3046 return -1;
3047 }
0fd73091 3048
c4d10a05
SH
3049 return 0;
3050 }
f3d7e4ca 3051
f4f52cb5 3052 if (rootuid == hostuid) {
1a0e70ac 3053 /* nothing to do */
b103ceac 3054 INFO("Container root is our uid; no need to chown");
f3d7e4ca
SH
3055 return 0;
3056 }
3057
bbdbf8f0 3058 /* save the current gid of "path" */
f4f52cb5
CB
3059 if (stat(path, &sb) < 0) {
3060 ERROR("Error stat %s", path);
f6d3e3e4
SH
3061 return -1;
3062 }
7b50c609 3063
bbdbf8f0
CB
3064 /* Update the path argument in case this was overlayfs. */
3065 args1[sizeof(args1) / sizeof(args1[0]) - 2] = path;
3066 args2[sizeof(args2) / sizeof(args2[0]) - 2] = path;
3067
f4f52cb5
CB
3068 /*
3069 * A file has to be group-owned by a gid mapped into the
3070 * container, or the container won't be privileged over it.
3071 */
3072 DEBUG("trying to chown \"%s\" to %d", path, hostgid);
3073 if (sb.st_uid == hostuid &&
3074 mapped_hostid(sb.st_gid, conf, ID_TYPE_GID) < 0 &&
3075 chown(path, -1, hostgid) < 0) {
3076 ERROR("Failed chgrping %s", path);
3077 return -1;
3078 }
f6d3e3e4 3079
1a0e70ac 3080 /* "u:0:rootuid:1" */
f4f52cb5
CB
3081 ret = snprintf(map1, 100, "u:0:%d:1", rootuid);
3082 if (ret < 0 || ret >= 100) {
3083 ERROR("Error uid printing map string");
3084 return -1;
3085 }
7b50c609 3086
1a0e70ac 3087 /* "u:hostuid:hostuid:1" */
f4f52cb5
CB
3088 ret = snprintf(map2, 100, "u:%d:%d:1", hostuid, hostuid);
3089 if (ret < 0 || ret >= 100) {
3090 ERROR("Error uid printing map string");
3091 return -1;
3092 }
c4d10a05 3093
1a0e70ac 3094 /* "g:0:rootgid:1" */
f4f52cb5
CB
3095 ret = snprintf(map3, 100, "g:0:%d:1", rootgid);
3096 if (ret < 0 || ret >= 100) {
3097 ERROR("Error gid printing map string");
3098 return -1;
3099 }
98e5ba51 3100
1a0e70ac 3101 /* "g:pathgid:rootgid+pathgid:1" */
f4f52cb5
CB
3102 ret = snprintf(map4, 100, "g:%d:%d:1", (gid_t)sb.st_gid,
3103 rootgid + (gid_t)sb.st_gid);
3104 if (ret < 0 || ret >= 100) {
3105 ERROR("Error gid printing map string");
3106 return -1;
3107 }
c4d10a05 3108
1a0e70ac 3109 /* "g:hostgid:hostgid:1" */
f4f52cb5
CB
3110 ret = snprintf(map5, 100, "g:%d:%d:1", hostgid, hostgid);
3111 if (ret < 0 || ret >= 100) {
3112 ERROR("Error gid printing map string");
3113 return -1;
3114 }
7b50c609 3115
1a0e70ac 3116 /* "0:pathgid" (chown) */
f4f52cb5
CB
3117 ret = snprintf(ugid, 100, "0:%d", (gid_t)sb.st_gid);
3118 if (ret < 0 || ret >= 100) {
3119 ERROR("Error owner printing format string for chown");
3120 return -1;
3121 }
7b50c609 3122
f4f52cb5
CB
3123 if (hostgid == sb.st_gid)
3124 ret = run_command(cmd_output, sizeof(cmd_output),
3125 chown_mapped_root_exec_wrapper,
3126 (void *)args1);
3127 else
3128 ret = run_command(cmd_output, sizeof(cmd_output),
3129 chown_mapped_root_exec_wrapper,
3130 (void *)args2);
3131 if (ret < 0)
3132 ERROR("lxc-usernsexec failed: %s", cmd_output);
7b50c609 3133
f4f52cb5 3134 return ret;
f6d3e3e4
SH
3135}
3136
943144d9
CB
3137/* NOTE: Must not be called from inside the container namespace! */
3138int lxc_create_tmp_proc_mount(struct lxc_conf *conf)
5112cd70
SH
3139{
3140 int mounted;
3141
943144d9 3142 mounted = lxc_mount_proc_if_needed(conf->rootfs.path ? conf->rootfs.mount : "");
5112cd70 3143 if (mounted == -1) {
0fd73091 3144 SYSERROR("Failed to mount proc in the container");
01958b1f 3145 /* continue only if there is no rootfs */
943144d9 3146 if (conf->rootfs.path)
01958b1f 3147 return -1;
5112cd70 3148 } else if (mounted == 1) {
943144d9 3149 conf->tmp_umount_proc = 1;
5112cd70 3150 }
943144d9 3151
5112cd70
SH
3152 return 0;
3153}
3154
3155void tmp_proc_unmount(struct lxc_conf *lxc_conf)
3156{
0fd73091
CB
3157 if (lxc_conf->tmp_umount_proc != 1)
3158 return;
3159
3160 umount("/proc");
3161 lxc_conf->tmp_umount_proc = 0;
5112cd70
SH
3162}
3163
0fd73091 3164/* Walk /proc/mounts and change any shared entries to slave. */
6a0c909a 3165void remount_all_slave(void)
e995d7a2 3166{
0fd73091 3167 FILE *f;
e995d7a2 3168 size_t len = 0;
0fd73091 3169 char *line = NULL;
e995d7a2 3170
0fd73091 3171 f = fopen("/proc/self/mountinfo", "r");
e995d7a2 3172 if (!f) {
0fd73091 3173 SYSERROR("Failed to open \"/proc/self/mountinfo\" to mark all shared");
e995d7a2
SH
3174 ERROR("Continuing container startup...");
3175 return;
3176 }
3177
3178 while (getline(&line, &len, f) != -1) {
0fd73091
CB
3179 int ret;
3180 char *opts, *target;
3181
e995d7a2
SH
3182 target = get_field(line, 4);
3183 if (!target)
3184 continue;
0fd73091 3185
e995d7a2
SH
3186 opts = get_field(target, 2);
3187 if (!opts)
3188 continue;
0fd73091 3189
e995d7a2
SH
3190 null_endofword(opts);
3191 if (!strstr(opts, "shared"))
3192 continue;
0fd73091 3193
e995d7a2 3194 null_endofword(target);
0fd73091
CB
3195 ret = mount(NULL, target, NULL, MS_SLAVE, NULL);
3196 if (ret < 0) {
3197 SYSERROR("Failed to make \"%s\" MS_SLAVE", target);
e995d7a2
SH
3198 ERROR("Continuing...");
3199 }
3200 }
3201 fclose(f);
f10fad2f 3202 free(line);
e995d7a2
SH
3203}
3204
794248d0 3205static int lxc_execute_bind_init(struct lxc_handler *handler)
2322903b
SH
3206{
3207 int ret;
794248d0
CB
3208 char *p;
3209 char path[PATH_MAX], destpath[PATH_MAX];
3210 struct lxc_conf *conf = handler->conf;
9d9c111c
SH
3211
3212 /* If init exists in the container, don't bind mount a static one */
3213 p = choose_init(conf->rootfs.mount);
3214 if (p) {
41089848
TA
3215 char *old = p;
3216
3217 p = strdup(old + strlen(conf->rootfs.mount));
3218 free(old);
3219 if (!p)
3220 return -ENOMEM;
3221
3222 INFO("Found existing init at \"%s\"", p);
3223 goto out;
9d9c111c 3224 }
2322903b
SH
3225
3226 ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static");
0fd73091 3227 if (ret < 0 || ret >= PATH_MAX)
8353b4c9 3228 return -1;
2322903b
SH
3229
3230 if (!file_exists(path)) {
0fd73091 3231 ERROR("The file \"%s\" does not exist on host", path);
8353b4c9 3232 return -1;
2322903b
SH
3233 }
3234
794248d0 3235 ret = snprintf(destpath, PATH_MAX, "%s" P_tmpdir "%s", conf->rootfs.mount, "/.lxc-init");
0fd73091 3236 if (ret < 0 || ret >= PATH_MAX)
8353b4c9 3237 return -1;
2322903b
SH
3238
3239 if (!file_exists(destpath)) {
794248d0
CB
3240 ret = mknod(destpath, S_IFREG | 0000, 0);
3241 if (ret < 0 && errno != EEXIST) {
3242 SYSERROR("Failed to create dummy \"%s\" file as bind mount target", destpath);
8353b4c9 3243 return -1;
2322903b 3244 }
2322903b
SH
3245 }
3246
592fd47a 3247 ret = safe_mount(path, destpath, "none", MS_BIND, NULL, conf->rootfs.mount);
8353b4c9 3248 if (ret < 0) {
0fd73091 3249 SYSERROR("Failed to bind mount lxc.init.static into container");
8353b4c9
CB
3250 return -1;
3251 }
3252
794248d0
CB
3253 p = strdup(destpath + strlen(conf->rootfs.mount));
3254 if (!p)
3255 return -ENOMEM;
794248d0 3256
8353b4c9 3257 INFO("Bind mounted lxc.init.static into container at \"%s\"", path);
41089848 3258out:
4b5b3a2a 3259 ((struct execute_args *)handler->data)->init_fd = -1;
41089848 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
4b5b3a2a
TA
3334static bool execveat_supported(void)
3335{
3336#ifdef __NR_execveat
3337 /*
3338 * We use the syscall here, because it was introduced in kernel 3.19,
3339 * while glibc got support for using the syscall much later, in 2.27.
3340 * We don't want to use glibc because it falls back to /proc, and the
3341 * container may not have /proc mounted depending on its configuration.
3342 */
3343 syscall(__NR_execveat, -1, "", NULL, NULL, AT_EMPTY_PATH);
3344 if (errno == ENOSYS)
3345 return false;
3346
3347 return true;
3348#else
3349 return false;
3350#endif
3351}
3352
3b988b33 3353int lxc_setup(struct lxc_handler *handler)
35120d9c 3354{
2187efd3 3355 int ret;
0fd73091 3356 const char *lxcpath = handler->lxcpath, *name = handler->name;
35120d9c 3357 struct lxc_conf *lxc_conf = handler->conf;
35120d9c 3358
8353b4c9
CB
3359 ret = do_rootfs_setup(lxc_conf, name, lxcpath);
3360 if (ret < 0) {
3361 ERROR("Failed to setup rootfs");
35120d9c
SH
3362 return -1;
3363 }
3364
28d9e29e 3365 if (handler->nsfd[LXC_NS_UTS] == -1) {
8353b4c9
CB
3366 ret = setup_utsname(lxc_conf->utsname);
3367 if (ret < 0) {
0fd73091 3368 ERROR("Failed to setup the utsname %s", name);
6c544cb3
MM
3369 return -1;
3370 }
0ad19a3f 3371 }
3372
8353b4c9
CB
3373 ret = lxc_setup_network_in_child_namespaces(lxc_conf, &lxc_conf->network);
3374 if (ret < 0) {
3375 ERROR("Failed to setup network");
95b5ffaf 3376 return -1;
0ad19a3f 3377 }
3378
8353b4c9
CB
3379 ret = lxc_network_send_name_and_ifindex_to_parent(handler);
3380 if (ret < 0) {
3381 ERROR("Failed to send network device names and ifindices to parent");
790255cf
CB
3382 return -1;
3383 }
3384
bc6928ff 3385 if (lxc_conf->autodev > 0) {
8353b4c9
CB
3386 ret = mount_autodev(name, &lxc_conf->rootfs, lxcpath);
3387 if (ret < 0) {
3388 ERROR("Failed to mount \"/dev\"");
c6883f38
SH
3389 return -1;
3390 }
3391 }
3392
8353b4c9
CB
3393 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3394 * need to wait until other stuff has finished.
368bbc02 3395 */
8353b4c9
CB
3396 ret = lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK, handler);
3397 if (ret < 0) {
3398 ERROR("Failed to setup first automatic mounts");
368bbc02
CS
3399 return -1;
3400 }
3401
8353b4c9
CB
3402 ret = setup_mount(lxc_conf, &lxc_conf->rootfs, lxc_conf->fstab, name, lxcpath);
3403 if (ret < 0) {
3404 ERROR("Failed to setup mounts");
95b5ffaf 3405 return -1;
576f946d 3406 }
3407
7b6753e7 3408 /* Make sure any start hooks are in the container */
1c1c7051
SH
3409 if (!verify_start_hooks(lxc_conf))
3410 return -1;
3411
8353b4c9 3412 if (lxc_conf->is_execute) {
4b5b3a2a
TA
3413 if (execveat_supported()) {
3414 int fd;
3415 char path[PATH_MAX];
3416
3417 ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static");
3418 if (ret < 0 || ret >= PATH_MAX) {
3419 ERROR("Path to init.lxc.static too long");
3420 return -1;
3421 }
3422
3423 fd = open(path, O_PATH | O_CLOEXEC);
3424 if (fd < 0) {
3425 SYSERROR("Unable to open lxc.init.static");
3426 return -1;
3427 }
3428
3429 ((struct execute_args *)handler->data)->init_fd = fd;
3430 ((struct execute_args *)handler->data)->init_path = NULL;
3431 } else {
3432 ret = lxc_execute_bind_init(handler);
3433 if (ret < 0) {
3434 ERROR("Failed to bind-mount the lxc init system");
3435 return -1;
3436 }
8353b4c9
CB
3437 }
3438 }
2322903b 3439
8353b4c9
CB
3440 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3441 * mounted. It is guaranteed to be mounted now either through
3442 * automatically or via fstab entries.
368bbc02 3443 */
8353b4c9
CB
3444 ret = lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK, handler);
3445 if (ret < 0) {
3446 ERROR("Failed to setup remaining automatic mounts");
368bbc02
CS
3447 return -1;
3448 }
3449
8353b4c9 3450 ret = run_lxc_hooks(name, "mount", lxc_conf, NULL);
1a2cf89d 3451 if (ret < 0) {
8353b4c9 3452 ERROR("Failed to run mount hooks");
773fb9ca
SH
3453 return -1;
3454 }
3455
bc6928ff 3456 if (lxc_conf->autodev > 0) {
8353b4c9
CB
3457 ret = run_lxc_hooks(name, "autodev", lxc_conf, NULL);
3458 if (ret < 0) {
3459 ERROR("Failed to run autodev hooks");
f7bee6c6
MW
3460 return -1;
3461 }
06749971 3462
8353b4c9
CB
3463 ret = lxc_fill_autodev(&lxc_conf->rootfs);
3464 if (ret < 0) {
3465 ERROR("Failed to populate \"/dev\"");
91c3830e
SH
3466 return -1;
3467 }
3468 }
368bbc02 3469
8353b4c9
CB
3470 if (!lxc_list_empty(&lxc_conf->mount_list)) {
3471 ret = setup_mount_entries(lxc_conf, &lxc_conf->rootfs,
3472 &lxc_conf->mount_list, name, lxcpath);
3473 if (ret < 0) {
3474 ERROR("Failed to setup mount entries");
3475 return -1;
3476 }
181437fd
YT
3477 }
3478
ed8704d0 3479 ret = lxc_setup_console(&lxc_conf->rootfs, &lxc_conf->console,
885766f5 3480 lxc_conf->ttys.dir);
ed8704d0
CB
3481 if (ret < 0) {
3482 ERROR("Failed to setup console");
95b5ffaf 3483 return -1;
6e590161 3484 }
3485
ed8704d0
CB
3486 ret = lxc_setup_dev_symlinks(&lxc_conf->rootfs);
3487 if (ret < 0) {
8353b4c9 3488 ERROR("Failed to setup \"/dev\" symlinks");
69aa6655
DE
3489 return -1;
3490 }
3491
8353b4c9
CB
3492 ret = lxc_create_tmp_proc_mount(lxc_conf);
3493 if (ret < 0) {
3494 ERROR("Failed to \"/proc\" LSMs");
e075f5d9 3495 return -1;
e075f5d9 3496 }
e075f5d9 3497
8353b4c9
CB
3498 ret = setup_pivot_root(&lxc_conf->rootfs);
3499 if (ret < 0) {
3500 ERROR("Failed to pivot root into rootfs");
95b5ffaf 3501 return -1;
ed502555 3502 }
3503
8353b4c9
CB
3504 ret = lxc_setup_devpts(lxc_conf);
3505 if (ret < 0) {
3506 ERROR("Failed to setup new devpts instance");
95b5ffaf 3507 return -1;
3c26f34e 3508 }
3509
2187efd3
CB
3510 ret = lxc_create_ttys(handler);
3511 if (ret < 0)
e8bd4e43 3512 return -1;
e8bd4e43 3513
8353b4c9
CB
3514 ret = setup_personality(lxc_conf->personality);
3515 if (ret < 0) {
3516 ERROR("Failed to set personality");
cccc74b5
DL
3517 return -1;
3518 }
3519
8353b4c9
CB
3520 /* Set sysctl value to a path under /proc/sys as determined from the
3521 * key. For e.g. net.ipv4.ip_forward translated to
3522 * /proc/sys/net/ipv4/ip_forward.
7edd0540
L
3523 */
3524 if (!lxc_list_empty(&lxc_conf->sysctls)) {
3525 ret = setup_sysctl_parameters(&lxc_conf->sysctls);
8353b4c9
CB
3526 if (ret < 0) {
3527 ERROR("Failed to setup sysctl parameters");
7edd0540 3528 return -1;
8353b4c9 3529 }
7edd0540
L
3530 }
3531
97a8f74f
SG
3532 if (!lxc_list_empty(&lxc_conf->keepcaps)) {
3533 if (!lxc_list_empty(&lxc_conf->caps)) {
8353b4c9
CB
3534 ERROR("Container requests lxc.cap.drop and "
3535 "lxc.cap.keep: either use lxc.cap.drop or "
3536 "lxc.cap.keep, not both");
f6d3e3e4
SH
3537 return -1;
3538 }
8353b4c9 3539
97a8f74f 3540 if (dropcaps_except(&lxc_conf->keepcaps)) {
8353b4c9 3541 ERROR("Failed to keep capabilities");
97a8f74f
SG
3542 return -1;
3543 }
3544 } else if (setup_caps(&lxc_conf->caps)) {
8353b4c9 3545 ERROR("Failed to drop capabilities");
97a8f74f 3546 return -1;
81810dd1
DL
3547 }
3548
8353b4c9 3549 NOTICE("The container \"%s\" is set up", name);
cd54d859 3550
0ad19a3f 3551 return 0;
3552}
26ddeedd 3553
3f60c2f7 3554int run_lxc_hooks(const char *name, char *hookname, struct lxc_conf *conf,
14a7b0f9 3555 char *argv[])
26ddeedd 3556{
26ddeedd 3557 struct lxc_list *it;
3f60c2f7 3558 int which = -1;
26ddeedd 3559
3f60c2f7 3560 if (strcmp(hookname, "pre-start") == 0)
26ddeedd 3561 which = LXCHOOK_PRESTART;
3f60c2f7 3562 else if (strcmp(hookname, "start-host") == 0)
08dd2805 3563 which = LXCHOOK_START_HOST;
3f60c2f7 3564 else if (strcmp(hookname, "pre-mount") == 0)
5ea6163a 3565 which = LXCHOOK_PREMOUNT;
3f60c2f7 3566 else if (strcmp(hookname, "mount") == 0)
26ddeedd 3567 which = LXCHOOK_MOUNT;
3f60c2f7 3568 else if (strcmp(hookname, "autodev") == 0)
f7bee6c6 3569 which = LXCHOOK_AUTODEV;
3f60c2f7 3570 else if (strcmp(hookname, "start") == 0)
26ddeedd 3571 which = LXCHOOK_START;
3f60c2f7 3572 else if (strcmp(hookname, "stop") == 0)
52492063 3573 which = LXCHOOK_STOP;
3f60c2f7 3574 else if (strcmp(hookname, "post-stop") == 0)
26ddeedd 3575 which = LXCHOOK_POSTSTOP;
3f60c2f7 3576 else if (strcmp(hookname, "clone") == 0)
148e91f5 3577 which = LXCHOOK_CLONE;
3f60c2f7 3578 else if (strcmp(hookname, "destroy") == 0)
37cf711b 3579 which = LXCHOOK_DESTROY;
26ddeedd
SH
3580 else
3581 return -1;
3f60c2f7 3582
0fd73091 3583 lxc_list_for_each (it, &conf->hooks[which]) {
26ddeedd 3584 int ret;
3f60c2f7
CB
3585 char *hook = it->elem;
3586
3587 ret = run_script_argv(name, conf->hooks_version, "lxc", hook,
14a7b0f9 3588 hookname, argv);
3f60c2f7
CB
3589 if (ret < 0)
3590 return -1;
26ddeedd 3591 }
3f60c2f7 3592
26ddeedd
SH
3593 return 0;
3594}
72d0e1cb 3595
72d0e1cb
SG
3596int lxc_clear_config_caps(struct lxc_conf *c)
3597{
1a0e70ac 3598 struct lxc_list *it, *next;
72d0e1cb 3599
0fd73091 3600 lxc_list_for_each_safe (it, &c->caps, next) {
72d0e1cb
SG
3601 lxc_list_del(it);
3602 free(it->elem);
3603 free(it);
3604 }
0fd73091 3605
72d0e1cb
SG
3606 return 0;
3607}
3608
c7e345ae
CB
3609static int lxc_free_idmap(struct lxc_list *id_map)
3610{
27c27d73
SH
3611 struct lxc_list *it, *next;
3612
0fd73091 3613 lxc_list_for_each_safe (it, id_map, next) {
27c27d73
SH
3614 lxc_list_del(it);
3615 free(it->elem);
3616 free(it);
3617 }
c7e345ae 3618
27c27d73
SH
3619 return 0;
3620}
3621
4355ab5f
SH
3622int lxc_clear_idmaps(struct lxc_conf *c)
3623{
3624 return lxc_free_idmap(&c->id_map);
3625}
3626
1fb86a7c
SH
3627int lxc_clear_config_keepcaps(struct lxc_conf *c)
3628{
0fd73091 3629 struct lxc_list *it, *next;
1fb86a7c 3630
0fd73091 3631 lxc_list_for_each_safe (it, &c->keepcaps, next) {
1fb86a7c
SH
3632 lxc_list_del(it);
3633 free(it->elem);
3634 free(it);
3635 }
0fd73091 3636
1fb86a7c
SH
3637 return 0;
3638}
3639
54860ed0 3640int lxc_clear_cgroups(struct lxc_conf *c, const char *key, int version)
72d0e1cb 3641{
54860ed0 3642 char *global_token, *namespaced_token;
ab1a6cac 3643 size_t namespaced_token_len;
54860ed0 3644 struct lxc_list *it, *next, *list;
ab1a6cac 3645 const char *k = key;
54860ed0 3646 bool all = false;
72d0e1cb 3647
54860ed0
CB
3648 if (version == CGROUP2_SUPER_MAGIC) {
3649 global_token = "lxc.cgroup2";
3650 namespaced_token = "lxc.cgroup2.";
0fd73091 3651 namespaced_token_len = sizeof("lxc.cgroup2.") - 1;
54860ed0
CB
3652 list = &c->cgroup2;
3653 } else if (version == CGROUP_SUPER_MAGIC) {
3654 global_token = "lxc.cgroup";
3655 namespaced_token = "lxc.cgroup.";
0fd73091 3656 namespaced_token_len = sizeof("lxc.cgroup.") - 1;
54860ed0
CB
3657 list = &c->cgroup;
3658 } else {
ab1a6cac 3659 return -EINVAL;
54860ed0
CB
3660 }
3661
3662 if (strcmp(key, global_token) == 0)
72d0e1cb 3663 all = true;
54860ed0 3664 else if (strncmp(key, namespaced_token, sizeof(namespaced_token) - 1) == 0)
ab1a6cac 3665 k += namespaced_token_len;
a6390f01 3666 else
ab1a6cac 3667 return -EINVAL;
72d0e1cb 3668
0fd73091 3669 lxc_list_for_each_safe (it, list, next) {
72d0e1cb 3670 struct lxc_cgroup *cg = it->elem;
54860ed0 3671
72d0e1cb
SG
3672 if (!all && strcmp(cg->subsystem, k) != 0)
3673 continue;
54860ed0 3674
72d0e1cb
SG
3675 lxc_list_del(it);
3676 free(cg->subsystem);
3677 free(cg->value);
3678 free(cg);
3679 free(it);
3680 }
e409b214 3681
72d0e1cb
SG
3682 return 0;
3683}
3684
c6d09e15
WB
3685int lxc_clear_limits(struct lxc_conf *c, const char *key)
3686{
3687 struct lxc_list *it, *next;
c6d09e15 3688 const char *k = NULL;
0fd73091 3689 bool all = false;
c6d09e15 3690
b668653c 3691 if (strcmp(key, "lxc.limit") == 0 || strcmp(key, "lxc.prlimit") == 0)
c6d09e15 3692 all = true;
b668653c
CB
3693 else if (strncmp(key, "lxc.limit.", sizeof("lxc.limit.") - 1) == 0)
3694 k = key + sizeof("lxc.limit.") - 1;
3695 else if (strncmp(key, "lxc.prlimit.", sizeof("lxc.prlimit.") - 1) == 0)
3696 k = key + sizeof("lxc.prlimit.") - 1;
c6d09e15
WB
3697 else
3698 return -1;
3699
0fd73091 3700 lxc_list_for_each_safe (it, &c->limits, next) {
c6d09e15 3701 struct lxc_limit *lim = it->elem;
0fd73091 3702
c6d09e15
WB
3703 if (!all && strcmp(lim->resource, k) != 0)
3704 continue;
0fd73091 3705
c6d09e15
WB
3706 lxc_list_del(it);
3707 free(lim->resource);
3708 free(lim);
3709 free(it);
3710 }
b668653c 3711
c6d09e15
WB
3712 return 0;
3713}
3714
7edd0540
L
3715int lxc_clear_sysctls(struct lxc_conf *c, const char *key)
3716{
3717 struct lxc_list *it, *next;
7edd0540 3718 const char *k = NULL;
0fd73091 3719 bool all = false;
7edd0540
L
3720
3721 if (strcmp(key, "lxc.sysctl") == 0)
3722 all = true;
3723 else if (strncmp(key, "lxc.sysctl.", sizeof("lxc.sysctl.") - 1) == 0)
3724 k = key + sizeof("lxc.sysctl.") - 1;
3725 else
3726 return -1;
3727
0fd73091 3728 lxc_list_for_each_safe (it, &c->sysctls, next) {
7edd0540 3729 struct lxc_sysctl *elem = it->elem;
0fd73091 3730
7edd0540
L
3731 if (!all && strcmp(elem->key, k) != 0)
3732 continue;
0fd73091 3733
7edd0540
L
3734 lxc_list_del(it);
3735 free(elem->key);
3736 free(elem->value);
3737 free(elem);
3738 free(it);
3739 }
0fd73091 3740
7edd0540
L
3741 return 0;
3742}
3743
61d7a733
YT
3744int lxc_clear_procs(struct lxc_conf *c, const char *key)
3745{
0fd73091 3746 struct lxc_list *it, *next;
61d7a733 3747 const char *k = NULL;
0fd73091 3748 bool all = false;
61d7a733
YT
3749
3750 if (strcmp(key, "lxc.proc") == 0)
3751 all = true;
3752 else if (strncmp(key, "lxc.proc.", sizeof("lxc.proc.") - 1) == 0)
3753 k = key + sizeof("lxc.proc.") - 1;
3754 else
3755 return -1;
3756
0fd73091 3757 lxc_list_for_each_safe (it, &c->procs, next) {
61d7a733 3758 struct lxc_proc *proc = it->elem;
0fd73091 3759
61d7a733
YT
3760 if (!all && strcmp(proc->filename, k) != 0)
3761 continue;
0fd73091 3762
61d7a733
YT
3763 lxc_list_del(it);
3764 free(proc->filename);
3765 free(proc->value);
3766 free(proc);
3767 free(it);
3768 }
3769
3770 return 0;
3771}
3772
ee1e7aa0
SG
3773int lxc_clear_groups(struct lxc_conf *c)
3774{
0fd73091 3775 struct lxc_list *it, *next;
ee1e7aa0 3776
0fd73091 3777 lxc_list_for_each_safe (it, &c->groups, next) {
ee1e7aa0
SG
3778 lxc_list_del(it);
3779 free(it->elem);
3780 free(it);
3781 }
0fd73091 3782
ee1e7aa0
SG
3783 return 0;
3784}
3785
ab799c0b
SG
3786int lxc_clear_environment(struct lxc_conf *c)
3787{
0fd73091 3788 struct lxc_list *it, *next;
ab799c0b 3789
0fd73091 3790 lxc_list_for_each_safe (it, &c->environment, next) {
ab799c0b
SG
3791 lxc_list_del(it);
3792 free(it->elem);
3793 free(it);
3794 }
0fd73091 3795
ab799c0b
SG
3796 return 0;
3797}
3798
72d0e1cb
SG
3799int lxc_clear_mount_entries(struct lxc_conf *c)
3800{
0fd73091 3801 struct lxc_list *it, *next;
72d0e1cb 3802
0fd73091 3803 lxc_list_for_each_safe (it, &c->mount_list, next) {
72d0e1cb
SG
3804 lxc_list_del(it);
3805 free(it->elem);
3806 free(it);
3807 }
0fd73091 3808
72d0e1cb
SG
3809 return 0;
3810}
3811
b099e9e9
SH
3812int lxc_clear_automounts(struct lxc_conf *c)
3813{
3814 c->auto_mounts = 0;
3815 return 0;
3816}
3817
12a50cc6 3818int lxc_clear_hooks(struct lxc_conf *c, const char *key)
72d0e1cb 3819{
72d0e1cb 3820 int i;
0fd73091
CB
3821 struct lxc_list *it, *next;
3822 const char *k = NULL;
3823 bool all = false, done = false;
72d0e1cb 3824
17ed13a3
SH
3825 if (strcmp(key, "lxc.hook") == 0)
3826 all = true;
0fd73091
CB
3827 else if (strncmp(key, "lxc.hook.", sizeof("lxc.hook.") - 1) == 0)
3828 k = key + sizeof("lxc.hook.") - 1;
a6390f01
WB
3829 else
3830 return -1;
17ed13a3 3831
0fd73091 3832 for (i = 0; i < NUM_LXC_HOOKS; i++) {
17ed13a3 3833 if (all || strcmp(k, lxchook_names[i]) == 0) {
0fd73091 3834 lxc_list_for_each_safe (it, &c->hooks[i], next) {
17ed13a3
SH
3835 lxc_list_del(it);
3836 free(it->elem);
3837 free(it);
3838 }
0fd73091 3839
17ed13a3 3840 done = true;
72d0e1cb
SG
3841 }
3842 }
17ed13a3
SH
3843
3844 if (!done) {
3845 ERROR("Invalid hook key: %s", key);
3846 return -1;
3847 }
0fd73091 3848
72d0e1cb
SG
3849 return 0;
3850}
8eb5694b 3851
4184c3e1
SH
3852static inline void lxc_clear_aliens(struct lxc_conf *conf)
3853{
0fd73091 3854 struct lxc_list *it, *next;
4184c3e1 3855
0fd73091 3856 lxc_list_for_each_safe (it, &conf->aliens, next) {
4184c3e1
SH
3857 lxc_list_del(it);
3858 free(it->elem);
3859 free(it);
3860 }
3861}
3862
c7b15d1e 3863void lxc_clear_includes(struct lxc_conf *conf)
f979ac15 3864{
0fd73091 3865 struct lxc_list *it, *next;
f979ac15 3866
0fd73091 3867 lxc_list_for_each_safe (it, &conf->includes, next) {
f979ac15
SH
3868 lxc_list_del(it);
3869 free(it->elem);
3870 free(it);
3871 }
3872}
3873
8eb5694b
SH
3874void lxc_conf_free(struct lxc_conf *conf)
3875{
3876 if (!conf)
3877 return;
0fd73091 3878
858377e4
SH
3879 if (current_config == conf)
3880 current_config = NULL;
aed105d5 3881 lxc_terminal_conf_free(&conf->console);
f10fad2f 3882 free(conf->rootfs.mount);
b3b8c97f 3883 free(conf->rootfs.bdev_type);
f10fad2f
ME
3884 free(conf->rootfs.options);
3885 free(conf->rootfs.path);
f10fad2f 3886 free(conf->logfile);
858377e4
SH
3887 if (conf->logfd != -1)
3888 close(conf->logfd);
f10fad2f 3889 free(conf->utsname);
885766f5
CB
3890 free(conf->ttys.dir);
3891 free(conf->ttys.tty_names);
f10fad2f
ME
3892 free(conf->fstab);
3893 free(conf->rcfile);
5cda27c1 3894 free(conf->execute_cmd);
f10fad2f 3895 free(conf->init_cmd);
3c491553 3896 free(conf->init_cwd);
6b0d5538 3897 free(conf->unexpanded_config);
76d0127f 3898 free(conf->syslog);
c302b476 3899 lxc_free_networks(&conf->network);
f10fad2f
ME
3900 free(conf->lsm_aa_profile);
3901 free(conf->lsm_se_context);
769872f9 3902 lxc_seccomp_free(conf);
8eb5694b 3903 lxc_clear_config_caps(conf);
1fb86a7c 3904 lxc_clear_config_keepcaps(conf);
54860ed0
CB
3905 lxc_clear_cgroups(conf, "lxc.cgroup", CGROUP_SUPER_MAGIC);
3906 lxc_clear_cgroups(conf, "lxc.cgroup2", CGROUP2_SUPER_MAGIC);
17ed13a3 3907 lxc_clear_hooks(conf, "lxc.hook");
8eb5694b 3908 lxc_clear_mount_entries(conf);
27c27d73 3909 lxc_clear_idmaps(conf);
ee1e7aa0 3910 lxc_clear_groups(conf);
f979ac15 3911 lxc_clear_includes(conf);
761d81ca 3912 lxc_clear_aliens(conf);
ab799c0b 3913 lxc_clear_environment(conf);
240d4b74 3914 lxc_clear_limits(conf, "lxc.prlimit");
7edd0540 3915 lxc_clear_sysctls(conf, "lxc.sysctl");
61d7a733 3916 lxc_clear_procs(conf, "lxc.proc");
43654d34
CB
3917 free(conf->cgroup_meta.dir);
3918 free(conf->cgroup_meta.controllers);
8eb5694b
SH
3919 free(conf);
3920}
4355ab5f
SH
3921
3922struct userns_fn_data {
3923 int (*fn)(void *);
c9b7c33e 3924 const char *fn_name;
4355ab5f
SH
3925 void *arg;
3926 int p[2];
3927};
3928
3929static int run_userns_fn(void *data)
3930{
4355ab5f 3931 char c;
0fd73091 3932 struct userns_fn_data *d = data;
4355ab5f 3933
f8aa4bf3 3934 /* Close write end of the pipe. */
4355ab5f 3935 close(d->p[1]);
f8aa4bf3
CB
3936
3937 /* Wait for parent to finish establishing a new mapping in the user
3938 * namespace we are executing in.
3939 */
4355ab5f
SH
3940 if (read(d->p[0], &c, 1) != 1)
3941 return -1;
f8aa4bf3
CB
3942
3943 /* Close read end of the pipe. */
4355ab5f 3944 close(d->p[0]);
f8aa4bf3 3945
c9b7c33e
CB
3946 if (d->fn_name)
3947 TRACE("calling function \"%s\"", d->fn_name);
0fd73091 3948
f8aa4bf3 3949 /* Call function to run. */
4355ab5f
SH
3950 return d->fn(d->arg);
3951}
3952
db7cfe23
CB
3953static struct id_map *mapped_nsid_add(struct lxc_conf *conf, unsigned id,
3954 enum idtype idtype)
3955{
3956 struct id_map *map, *retmap;
3957
3958 map = find_mapped_nsid_entry(conf, id, idtype);
3959 if (!map)
3960 return NULL;
3961
3962 retmap = malloc(sizeof(*retmap));
3963 if (!retmap)
3964 return NULL;
3965
3966 memcpy(retmap, map, sizeof(*retmap));
3967 return retmap;
3968}
3969
c4333195
CB
3970static struct id_map *find_mapped_hostid_entry(struct lxc_conf *conf,
3971 unsigned id, enum idtype idtype)
f8aa4bf3 3972{
f8aa4bf3 3973 struct id_map *map;
0fd73091 3974 struct lxc_list *it;
f8aa4bf3
CB
3975 struct id_map *retmap = NULL;
3976
0fd73091 3977 lxc_list_for_each (it, &conf->id_map) {
f8aa4bf3
CB
3978 map = it->elem;
3979 if (map->idtype != idtype)
3980 continue;
3981
3982 if (id >= map->hostid && id < map->hostid + map->range) {
3983 retmap = map;
3984 break;
3985 }
3986 }
3987
f8aa4bf3
CB
3988 return retmap;
3989}
3990
0fd73091 3991/* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
f8aa4bf3 3992 * existing one or establish a new one.
4355ab5f 3993 */
0fd73091
CB
3994static struct id_map *mapped_hostid_add(struct lxc_conf *conf, uid_t id,
3995 enum idtype type)
4355ab5f 3996{
28a2d9e7 3997 int hostid_mapped;
c4333195
CB
3998 struct id_map *entry = NULL, *tmp = NULL;
3999
4000 entry = malloc(sizeof(*entry));
4001 if (!entry)
4002 return NULL;
f8aa4bf3 4003
28a2d9e7 4004 /* Reuse existing mapping. */
c4333195
CB
4005 tmp = find_mapped_hostid_entry(conf, id, type);
4006 if (tmp)
4007 return memcpy(entry, tmp, sizeof(*entry));
f8aa4bf3 4008
28a2d9e7
CB
4009 /* Find new mapping. */
4010 hostid_mapped = find_unmapped_nsid(conf, type);
4011 if (hostid_mapped < 0) {
c4333195
CB
4012 DEBUG("Failed to find free mapping for id %d", id);
4013 free(entry);
28a2d9e7 4014 return NULL;
f8aa4bf3 4015 }
f8aa4bf3 4016
28a2d9e7
CB
4017 entry->idtype = type;
4018 entry->nsid = hostid_mapped;
4019 entry->hostid = (unsigned long)id;
4020 entry->range = 1;
4355ab5f 4021
28a2d9e7 4022 return entry;
4355ab5f
SH
4023}
4024
dcf0ffdf 4025struct lxc_list *get_minimal_idmap(struct lxc_conf *conf)
4355ab5f 4026{
f8aa4bf3 4027 uid_t euid, egid;
4160c3a0
CB
4028 uid_t nsuid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
4029 gid_t nsgid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
f8aa4bf3 4030 struct lxc_list *idmap = NULL, *tmplist = NULL;
28a2d9e7
CB
4031 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
4032 *host_uid_map = NULL, *host_gid_map = NULL;
4355ab5f 4033
db7cfe23 4034 /* Find container root mappings. */
4160c3a0 4035 container_root_uid = mapped_nsid_add(conf, nsuid, ID_TYPE_UID);
db7cfe23 4036 if (!container_root_uid) {
dcf0ffdf 4037 DEBUG("Failed to find mapping for namespace uid %d", 0);
db7cfe23 4038 goto on_error;
f8aa4bf3 4039 }
dcf0ffdf
CB
4040 euid = geteuid();
4041 if (euid >= container_root_uid->hostid &&
4042 euid < (container_root_uid->hostid + container_root_uid->range))
db7cfe23 4043 host_uid_map = container_root_uid;
f8aa4bf3 4044
4160c3a0 4045 container_root_gid = mapped_nsid_add(conf, nsgid, ID_TYPE_GID);
db7cfe23 4046 if (!container_root_gid) {
dcf0ffdf 4047 DEBUG("Failed to find mapping for namespace gid %d", 0);
f8aa4bf3
CB
4048 goto on_error;
4049 }
dcf0ffdf
CB
4050 egid = getegid();
4051 if (egid >= container_root_gid->hostid &&
4052 egid < (container_root_gid->hostid + container_root_gid->range))
db7cfe23 4053 host_gid_map = container_root_gid;
f8aa4bf3
CB
4054
4055 /* Check whether the {g,u}id of the user has a mapping. */
954b7d9b 4056 if (!host_uid_map)
c4333195 4057 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
28a2d9e7 4058 if (!host_uid_map) {
db7cfe23 4059 DEBUG("Failed to find mapping for uid %d", euid);
f8aa4bf3
CB
4060 goto on_error;
4061 }
4062
dcf0ffdf
CB
4063 if (!host_gid_map)
4064 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
28a2d9e7 4065 if (!host_gid_map) {
db7cfe23 4066 DEBUG("Failed to find mapping for gid %d", egid);
28a2d9e7
CB
4067 goto on_error;
4068 }
4069
4070 /* Allocate new {g,u}id map list. */
4071 idmap = malloc(sizeof(*idmap));
4072 if (!idmap)
4073 goto on_error;
4074 lxc_list_init(idmap);
4075
f8aa4bf3
CB
4076 /* Add container root to the map. */
4077 tmplist = malloc(sizeof(*tmplist));
4078 if (!tmplist)
4079 goto on_error;
4080 lxc_list_add_elem(tmplist, container_root_uid);
4081 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 4082
1d90e064 4083 if (host_uid_map && (host_uid_map != container_root_uid)) {
28a2d9e7
CB
4084 /* idmap will now keep track of that memory. */
4085 container_root_uid = NULL;
4086
4087 /* Add container root to the map. */
4088 tmplist = malloc(sizeof(*tmplist));
4089 if (!tmplist)
4090 goto on_error;
4091 lxc_list_add_elem(tmplist, host_uid_map);
4092 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 4093 }
1d90e064
CB
4094 /* idmap will now keep track of that memory. */
4095 container_root_uid = NULL;
4096 /* idmap will now keep track of that memory. */
4097 host_uid_map = NULL;
f8aa4bf3
CB
4098
4099 tmplist = malloc(sizeof(*tmplist));
4100 if (!tmplist)
4101 goto on_error;
4102 lxc_list_add_elem(tmplist, container_root_gid);
4103 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 4104
1d90e064 4105 if (host_gid_map && (host_gid_map != container_root_gid)) {
28a2d9e7
CB
4106 /* idmap will now keep track of that memory. */
4107 container_root_gid = NULL;
4108
4109 tmplist = malloc(sizeof(*tmplist));
4110 if (!tmplist)
4111 goto on_error;
4112 lxc_list_add_elem(tmplist, host_gid_map);
4113 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 4114 }
1d90e064
CB
4115 /* idmap will now keep track of that memory. */
4116 container_root_gid = NULL;
4117 /* idmap will now keep track of that memory. */
4118 host_gid_map = NULL;
f8aa4bf3 4119
dcf0ffdf
CB
4120 TRACE("Allocated minimal idmapping");
4121 return idmap;
4122
4123on_error:
4dc41f99 4124 if (idmap) {
dcf0ffdf 4125 lxc_free_idmap(idmap);
4dc41f99
SX
4126 free(idmap);
4127 }
dcf0ffdf
CB
4128 if (container_root_uid)
4129 free(container_root_uid);
4130 if (container_root_gid)
4131 free(container_root_gid);
4132 if (host_uid_map && (host_uid_map != container_root_uid))
4133 free(host_uid_map);
4134 if (host_gid_map && (host_gid_map != container_root_gid))
4135 free(host_gid_map);
4136
4137 return NULL;
4138}
4139
4140/* Run a function in a new user namespace.
4141 * The caller's euid/egid will be mapped if it is not already.
4142 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4143 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4144 * This means we require only to establish a mapping from:
4145 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4146 * - the container root -> some sub{g,u}id
4147 * The former we add, if the user did not specifiy a mapping. The latter we
4148 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
4149 * there to start the container in the first place.
4150 */
4151int userns_exec_1(struct lxc_conf *conf, int (*fn)(void *), void *data,
4152 const char *fn_name)
4153{
4154 pid_t pid;
dcf0ffdf 4155 int p[2];
0fd73091 4156 struct userns_fn_data d;
dcf0ffdf 4157 struct lxc_list *idmap;
0fd73091
CB
4158 int ret = -1, status = -1;
4159 char c = '1';
dcf0ffdf 4160
2b2655a8
CB
4161 if (!conf)
4162 return -EINVAL;
4163
dcf0ffdf
CB
4164 idmap = get_minimal_idmap(conf);
4165 if (!idmap)
4166 return -1;
4167
4168 ret = pipe(p);
4169 if (ret < 0) {
4170 SYSERROR("Failed to create pipe");
4171 return -1;
4172 }
4173 d.fn = fn;
4174 d.fn_name = fn_name;
4175 d.arg = data;
4176 d.p[0] = p[0];
4177 d.p[1] = p[1];
4178
4179 /* Clone child in new user namespace. */
4180 pid = lxc_raw_clone_cb(run_userns_fn, &d, CLONE_NEWUSER);
4181 if (pid < 0) {
0fd73091 4182 ERROR("Failed to clone process in new user namespace");
dcf0ffdf
CB
4183 goto on_error;
4184 }
4185
4186 close(p[0]);
4187 p[0] = -1;
4188
4b73005c
CB
4189 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE ||
4190 conf->loglevel == LXC_LOG_LEVEL_TRACE) {
dcf0ffdf 4191 struct id_map *map;
0fd73091 4192 struct lxc_list *it;
dcf0ffdf 4193
0fd73091 4194 lxc_list_for_each (it, idmap) {
f8aa4bf3 4195 map = it->elem;
dcf0ffdf 4196 TRACE("Establishing %cid mapping for \"%d\" in new "
f8aa4bf3 4197 "user namespace: nsuid %lu - hostid %lu - range "
0fd73091
CB
4198 "%lu",
4199 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
4200 map->nsid, map->hostid, map->range);
f8aa4bf3 4201 }
4355ab5f
SH
4202 }
4203
f8aa4bf3 4204 /* Set up {g,u}id mapping for user namespace of child process. */
4355ab5f 4205 ret = lxc_map_ids(idmap, pid);
f8aa4bf3 4206 if (ret < 0) {
0fd73091 4207 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
f8aa4bf3 4208 goto on_error;
4355ab5f
SH
4209 }
4210
f8aa4bf3 4211 /* Tell child to proceed. */
4355ab5f 4212 if (write(p[1], &c, 1) != 1) {
dcf0ffdf 4213 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
f8aa4bf3 4214 goto on_error;
4355ab5f
SH
4215 }
4216
686dd5d1 4217on_error:
4355ab5f
SH
4218 if (p[0] != -1)
4219 close(p[0]);
4220 close(p[1]);
f8aa4bf3 4221
ee1b16bc
TA
4222 /* Wait for child to finish. */
4223 if (pid > 0)
4224 status = wait_for_pid(pid);
4225
686dd5d1
CB
4226 if (status < 0)
4227 ret = -1;
4228
f8aa4bf3 4229 return ret;
4355ab5f 4230}
97e9cfa0 4231
415a8851
CB
4232int userns_exec_full(struct lxc_conf *conf, int (*fn)(void *), void *data,
4233 const char *fn_name)
4234{
4235 pid_t pid;
4236 uid_t euid, egid;
415a8851
CB
4237 int p[2];
4238 struct id_map *map;
4239 struct lxc_list *cur;
0fd73091 4240 struct userns_fn_data d;
415a8851 4241 int ret = -1;
0fd73091 4242 char c = '1';
415a8851
CB
4243 struct lxc_list *idmap = NULL, *tmplist = NULL;
4244 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
4245 *host_uid_map = NULL, *host_gid_map = NULL;
4246
2b2655a8
CB
4247 if (!conf)
4248 return -EINVAL;
4249
415a8851
CB
4250 ret = pipe(p);
4251 if (ret < 0) {
4252 SYSERROR("opening pipe");
4253 return -1;
4254 }
4255 d.fn = fn;
4256 d.fn_name = fn_name;
4257 d.arg = data;
4258 d.p[0] = p[0];
4259 d.p[1] = p[1];
4260
4261 /* Clone child in new user namespace. */
4262 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER);
4263 if (pid < 0) {
0fd73091 4264 ERROR("Failed to clone process in new user namespace");
415a8851
CB
4265 goto on_error;
4266 }
4267
4268 close(p[0]);
4269 p[0] = -1;
4270
4271 euid = geteuid();
4272 egid = getegid();
4273
4274 /* Allocate new {g,u}id map list. */
4275 idmap = malloc(sizeof(*idmap));
4276 if (!idmap)
4277 goto on_error;
4278 lxc_list_init(idmap);
4279
4280 /* Find container root. */
0fd73091 4281 lxc_list_for_each (cur, &conf->id_map) {
415a8851
CB
4282 struct id_map *tmpmap;
4283
4284 tmplist = malloc(sizeof(*tmplist));
4285 if (!tmplist)
4286 goto on_error;
4287
4288 tmpmap = malloc(sizeof(*tmpmap));
4289 if (!tmpmap) {
4290 free(tmplist);
4291 goto on_error;
4292 }
4293
4294 memset(tmpmap, 0, sizeof(*tmpmap));
4295 memcpy(tmpmap, cur->elem, sizeof(*tmpmap));
4296 tmplist->elem = tmpmap;
4297
4298 lxc_list_add_tail(idmap, tmplist);
4299
4300 map = cur->elem;
4301
4302 if (map->idtype == ID_TYPE_UID)
4303 if (euid >= map->hostid && euid < map->hostid + map->range)
4304 host_uid_map = map;
4305
4306 if (map->idtype == ID_TYPE_GID)
4307 if (egid >= map->hostid && egid < map->hostid + map->range)
4308 host_gid_map = map;
4309
4310 if (map->nsid != 0)
4311 continue;
4312
4313 if (map->idtype == ID_TYPE_UID)
4314 if (container_root_uid == NULL)
4315 container_root_uid = map;
4316
4317 if (map->idtype == ID_TYPE_GID)
4318 if (container_root_gid == NULL)
4319 container_root_gid = map;
4320 }
4321
4322 if (!container_root_uid || !container_root_gid) {
4323 ERROR("No mapping for container root found");
4324 goto on_error;
4325 }
4326
4327 /* Check whether the {g,u}id of the user has a mapping. */
4328 if (!host_uid_map)
c4333195 4329 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
415a8851
CB
4330 else
4331 host_uid_map = container_root_uid;
4332
4333 if (!host_gid_map)
c4333195 4334 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
415a8851
CB
4335 else
4336 host_gid_map = container_root_gid;
4337
4338 if (!host_uid_map) {
4339 DEBUG("Failed to find mapping for uid %d", euid);
4340 goto on_error;
4341 }
4342
4343 if (!host_gid_map) {
4344 DEBUG("Failed to find mapping for gid %d", egid);
4345 goto on_error;
4346 }
4347
4348 if (host_uid_map && (host_uid_map != container_root_uid)) {
4349 /* Add container root to the map. */
4350 tmplist = malloc(sizeof(*tmplist));
4351 if (!tmplist)
4352 goto on_error;
4353 lxc_list_add_elem(tmplist, host_uid_map);
4354 lxc_list_add_tail(idmap, tmplist);
4355 }
4356 /* idmap will now keep track of that memory. */
4357 host_uid_map = NULL;
4358
4359 if (host_gid_map && (host_gid_map != container_root_gid)) {
4360 tmplist = malloc(sizeof(*tmplist));
4361 if (!tmplist)
4362 goto on_error;
4363 lxc_list_add_elem(tmplist, host_gid_map);
4364 lxc_list_add_tail(idmap, tmplist);
4365 }
4366 /* idmap will now keep track of that memory. */
4367 host_gid_map = NULL;
4368
4369 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE ||
4370 conf->loglevel == LXC_LOG_LEVEL_TRACE) {
0fd73091 4371 lxc_list_for_each (cur, idmap) {
415a8851
CB
4372 map = cur->elem;
4373 TRACE("establishing %cid mapping for \"%d\" in new "
4374 "user namespace: nsuid %lu - hostid %lu - range "
4375 "%lu",
4376 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
4377 map->nsid, map->hostid, map->range);
4378 }
4379 }
4380
4381 /* Set up {g,u}id mapping for user namespace of child process. */
4382 ret = lxc_map_ids(idmap, pid);
4383 if (ret < 0) {
0fd73091 4384 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid);
415a8851
CB
4385 goto on_error;
4386 }
4387
4388 /* Tell child to proceed. */
4389 if (write(p[1], &c, 1) != 1) {
0fd73091 4390 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
415a8851
CB
4391 goto on_error;
4392 }
4393
686dd5d1 4394on_error:
ee1b16bc
TA
4395 if (p[0] != -1)
4396 close(p[0]);
4397 close(p[1]);
4398
415a8851 4399 /* Wait for child to finish. */
686dd5d1
CB
4400 if (pid > 0)
4401 ret = wait_for_pid(pid);
415a8851 4402
415a8851
CB
4403 if (idmap)
4404 lxc_free_idmap(idmap);
4405 if (host_uid_map && (host_uid_map != container_root_uid))
4406 free(host_uid_map);
4407 if (host_gid_map && (host_gid_map != container_root_gid))
4408 free(host_gid_map);
4409
415a8851
CB
4410 return ret;
4411}
4412
a96a8e8c 4413/* not thread-safe, do not use from api without first forking */
0fd73091 4414static char *getuname(void)
97e9cfa0 4415{
a96a8e8c 4416 struct passwd *result;
97e9cfa0 4417
a96a8e8c
SH
4418 result = getpwuid(geteuid());
4419 if (!result)
97e9cfa0
SH
4420 return NULL;
4421
a96a8e8c 4422 return strdup(result->pw_name);
97e9cfa0
SH
4423}
4424
a96a8e8c 4425/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
4426static char *getgname(void)
4427{
a96a8e8c 4428 struct group *result;
97e9cfa0 4429
a96a8e8c
SH
4430 result = getgrgid(getegid());
4431 if (!result)
97e9cfa0
SH
4432 return NULL;
4433
a96a8e8c 4434 return strdup(result->gr_name);
97e9cfa0
SH
4435}
4436
a96a8e8c 4437/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
4438void suggest_default_idmap(void)
4439{
0fd73091 4440 char *uname, *gname;
97e9cfa0
SH
4441 FILE *f;
4442 unsigned int uid = 0, urange = 0, gid = 0, grange = 0;
97e9cfa0 4443 size_t len = 0;
0fd73091 4444 char *line = NULL;
97e9cfa0 4445
0fd73091
CB
4446 uname = getuname();
4447 if (!uname)
97e9cfa0
SH
4448 return;
4449
0fd73091
CB
4450 gname = getgname();
4451 if (!gname) {
97e9cfa0
SH
4452 free(uname);
4453 return;
4454 }
4455
4456 f = fopen(subuidfile, "r");
4457 if (!f) {
4458 ERROR("Your system is not configured with subuids");
4459 free(gname);
4460 free(uname);
4461 return;
4462 }
0fd73091 4463
97e9cfa0 4464 while (getline(&line, &len, f) != -1) {
0fd73091 4465 char *p, *p2;
b7930180 4466 size_t no_newline = 0;
0fd73091
CB
4467
4468 p = strchr(line, ':');
97e9cfa0
SH
4469 if (*line == '#')
4470 continue;
4471 if (!p)
4472 continue;
4473 *p = '\0';
4474 p++;
0fd73091 4475
97e9cfa0
SH
4476 if (strcmp(line, uname))
4477 continue;
0fd73091 4478
97e9cfa0
SH
4479 p2 = strchr(p, ':');
4480 if (!p2)
4481 continue;
4482 *p2 = '\0';
4483 p2++;
4484 if (!*p2)
4485 continue;
b7930180
CB
4486 no_newline = strcspn(p2, "\n");
4487 p2[no_newline] = '\0';
4488
b7b2fde4 4489 if (lxc_safe_uint(p, &uid) < 0)
0fd73091 4490 WARN("Could not parse UID");
b7b2fde4 4491 if (lxc_safe_uint(p2, &urange) < 0)
0fd73091 4492 WARN("Could not parse UID range");
97e9cfa0
SH
4493 }
4494 fclose(f);
4495
6be7389a 4496 f = fopen(subgidfile, "r");
97e9cfa0
SH
4497 if (!f) {
4498 ERROR("Your system is not configured with subgids");
4499 free(gname);
4500 free(uname);
4501 return;
4502 }
0fd73091 4503
97e9cfa0 4504 while (getline(&line, &len, f) != -1) {
0fd73091 4505 char *p, *p2;
b7930180 4506 size_t no_newline = 0;
0fd73091
CB
4507
4508 p = strchr(line, ':');
97e9cfa0
SH
4509 if (*line == '#')
4510 continue;
4511 if (!p)
4512 continue;
4513 *p = '\0';
4514 p++;
0fd73091 4515
97e9cfa0
SH
4516 if (strcmp(line, uname))
4517 continue;
0fd73091 4518
97e9cfa0
SH
4519 p2 = strchr(p, ':');
4520 if (!p2)
4521 continue;
4522 *p2 = '\0';
4523 p2++;
4524 if (!*p2)
4525 continue;
b7930180
CB
4526 no_newline = strcspn(p2, "\n");
4527 p2[no_newline] = '\0';
4528
b7b2fde4 4529 if (lxc_safe_uint(p, &gid) < 0)
0fd73091 4530 WARN("Could not parse GID");
b7b2fde4 4531 if (lxc_safe_uint(p2, &grange) < 0)
0fd73091 4532 WARN("Could not parse GID range");
97e9cfa0
SH
4533 }
4534 fclose(f);
4535
f10fad2f 4536 free(line);
97e9cfa0
SH
4537
4538 if (!urange || !grange) {
4539 ERROR("You do not have subuids or subgids allocated");
4540 ERROR("Unprivileged containers require subuids and subgids");
fbd4a4d1 4541 free(uname);
1e7cd2f7 4542 free(gname);
97e9cfa0
SH
4543 return;
4544 }
4545
4546 ERROR("You must either run as root, or define uid mappings");
4547 ERROR("To pass uid mappings to lxc-create, you could create");
4548 ERROR("~/.config/lxc/default.conf:");
4549 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG);
bdcbb6b3
CB
4550 ERROR("lxc.idmap = u 0 %u %u", uid, urange);
4551 ERROR("lxc.idmap = g 0 %u %u", gid, grange);
97e9cfa0
SH
4552
4553 free(gname);
4554 free(uname);
4555}
aaf26830 4556
a7307747
SH
4557static void free_cgroup_settings(struct lxc_list *result)
4558{
4559 struct lxc_list *iterator, *next;
4560
0fd73091 4561 lxc_list_for_each_safe (iterator, result, next) {
a7307747
SH
4562 lxc_list_del(iterator);
4563 free(iterator);
4564 }
4565 free(result);
4566}
4567
0fd73091 4568/* Return the list of cgroup_settings sorted according to the following rules
aaf26830
KT
4569 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4570 */
0fd73091 4571struct lxc_list *sort_cgroup_settings(struct lxc_list *cgroup_settings)
aaf26830
KT
4572{
4573 struct lxc_list *result;
aaf26830 4574 struct lxc_cgroup *cg = NULL;
0fd73091 4575 struct lxc_list *it = NULL, *item = NULL, *memsw_limit = NULL;
aaf26830
KT
4576
4577 result = malloc(sizeof(*result));
0fd73091 4578 if (!result)
fac7c663 4579 return NULL;
aaf26830
KT
4580 lxc_list_init(result);
4581
0fd73091
CB
4582 /* Iterate over the cgroup settings and copy them to the output list. */
4583 lxc_list_for_each (it, cgroup_settings) {
aaf26830 4584 item = malloc(sizeof(*item));
fac7c663 4585 if (!item) {
a7307747 4586 free_cgroup_settings(result);
fac7c663
KT
4587 return NULL;
4588 }
0fd73091 4589
aaf26830
KT
4590 item->elem = it->elem;
4591 cg = it->elem;
4592 if (strcmp(cg->subsystem, "memory.memsw.limit_in_bytes") == 0) {
4593 /* Store the memsw_limit location */
4594 memsw_limit = item;
0fd73091
CB
4595 } else if (strcmp(cg->subsystem, "memory.limit_in_bytes") == 0 &&
4596 memsw_limit != NULL) {
4597 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4598 * before lxc.cgroup.memory.limit_in_bytes, swap these
4599 * two items */
aaf26830
KT
4600 item->elem = memsw_limit->elem;
4601 memsw_limit->elem = it->elem;
4602 }
4603 lxc_list_add_tail(result, item);
4604 }
4605
4606 return result;
a7307747 4607}