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