]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/conf.c
conf: log failure to create tty mountpoint
[mirror_lxc.git] / src / lxc / conf.c
CommitLineData
cc73685d 1/* SPDX-License-Identifier: LGPL-2.1+ */
1d52bdf7 2
d38dd64a
CB
3#ifndef _GNU_SOURCE
4#define _GNU_SOURCE 1
5#endif
9d257a2a 6#include <arpa/inet.h>
8f3e280e
CB
7#include <dirent.h>
8#include <errno.h>
9#include <fcntl.h>
10#include <grp.h>
11#include <inttypes.h>
12#include <libgen.h>
9d257a2a
CB
13#include <linux/loop.h>
14#include <net/if.h>
15#include <netinet/in.h>
8f3e280e
CB
16#include <pwd.h>
17#include <stdarg.h>
1b82d721 18#include <stdbool.h>
0ad19a3f 19#include <stdio.h>
0ad19a3f 20#include <stdlib.h>
0ad19a3f 21#include <string.h>
8f3e280e
CB
22#include <sys/mman.h>
23#include <sys/mount.h>
24#include <sys/param.h>
25#include <sys/prctl.h>
6a49f05e 26#include <sys/sendfile.h>
8f3e280e 27#include <sys/socket.h>
9d257a2a 28#include <sys/stat.h>
2d76d1d7 29#include <sys/syscall.h>
9d257a2a 30#include <sys/sysmacros.h>
97e9cfa0 31#include <sys/types.h>
8f3e280e
CB
32#include <sys/utsname.h>
33#include <sys/wait.h>
9d257a2a
CB
34#include <time.h>
35#include <unistd.h>
1d52bdf7 36
d38dd64a
CB
37#include "af_unix.h"
38#include "caps.h"
5f126977 39#include "cgroups/cgroup.h"
52ce8504 40#include "compiler.h"
d38dd64a
CB
41#include "conf.h"
42#include "config.h"
43#include "confile.h"
44#include "confile_utils.h"
45#include "error.h"
46#include "log.h"
47#include "lsm/lsm.h"
48#include "lxclock.h"
49#include "lxcseccomp.h"
50#include "macro.h"
2f443e88 51#include "memory_utils.h"
7f88a1a2 52#include "mount_utils.h"
d38dd64a
CB
53#include "namespace.h"
54#include "network.h"
55#include "parse.h"
f40988c7 56#include "process_utils.h"
d38dd64a
CB
57#include "ringbuf.h"
58#include "start.h"
5f126977 59#include "storage/storage.h"
d38dd64a 60#include "storage/overlay.h"
1b82d721 61#include "sync.h"
6b3d24d7 62#include "syscall_wrappers.h"
d38dd64a
CB
63#include "terminal.h"
64#include "utils.h"
20502652 65#include "uuid.h"
d38dd64a 66
af6824fc 67#ifdef MAJOR_IN_MKDEV
9d257a2a 68#include <sys/mkdev.h>
af6824fc 69#endif
af6824fc 70
614305f3 71#ifdef HAVE_STATVFS
2938f7c8 72#include <sys/statvfs.h>
614305f3 73#endif
e827ff7e 74
35eb5cdc 75#if HAVE_OPENPTY
b0a33c1e 76#include <pty.h>
e827ff7e
SG
77#else
78#include <../include/openpty.h>
79#endif
0ad19a3f 80
9d257a2a
CB
81#if HAVE_LIBCAP
82#include <sys/capability.h>
83#endif
84
f1e05b90
DJ
85#ifndef HAVE_STRLCAT
86#include "include/strlcat.h"
87#endif
88
9d257a2a
CB
89#if IS_BIONIC
90#include <../include/lxcmntent.h>
91#else
92#include <mntent.h>
93#endif
94
95#if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
96#include <../include/prlimit.h>
97#endif
98
f6815906
CB
99#ifndef HAVE_STRLCPY
100#include "include/strlcpy.h"
101#endif
102
60933dae
CB
103#ifndef HAVE_STRCHRNUL
104#include "include/strchrnul.h"
105#endif
106
ac2cecc4 107lxc_log_define(conf, lxc);
e5bda9ee 108
52ce8504
CB
109/*
110 * The lxc_conf of the container currently being worked on in an API call.
0fd73091
CB
111 * This is used in the error calls.
112 */
d7f19646 113thread_local struct lxc_conf *current_config;
8912711c 114
0fd73091
CB
115char *lxchook_names[NUM_LXC_HOOKS] = {
116 "pre-start",
117 "pre-mount",
118 "mount",
119 "autodev",
120 "start",
121 "stop",
122 "post-stop",
123 "clone",
124 "destroy",
125 "start-host"
126};
72d0e1cb 127
998ac676
RT
128struct mount_opt {
129 char *name;
130 int clear;
1b82d721
CB
131 bool recursive;
132 __u64 flag;
1e4bce2c 133 int legacy_flag;
998ac676
RT
134};
135
81810dd1
DL
136struct caps_opt {
137 char *name;
138 int value;
139};
140
c6d09e15
WB
141struct limit_opt {
142 char *name;
143 int value;
144};
145
998ac676 146static struct mount_opt mount_opt[] = {
1b82d721
CB
147 { "atime", 1, false, MOUNT_ATTR_NOATIME, MS_NOATIME },
148 { "dev", 1, false, MOUNT_ATTR_NODEV, MS_NODEV },
149 { "diratime", 1, false, MOUNT_ATTR_NODIRATIME, MS_NODIRATIME },
150 { "exec", 1, false, MOUNT_ATTR_NOEXEC, MS_NOEXEC },
151 { "noatime", 0, false, MOUNT_ATTR_NOATIME, MS_NOATIME },
152 { "nodev", 0, false, MOUNT_ATTR_NODEV, MS_NODEV },
153 { "nodiratime", 0, false, MOUNT_ATTR_NODIRATIME, MS_NODIRATIME },
154 { "noexec", 0, false, MOUNT_ATTR_NOEXEC, MS_NOEXEC },
155 { "norelatime", 1, false, MOUNT_ATTR_RELATIME, MS_RELATIME },
156 { "nostrictatime", 1, false, MOUNT_ATTR_STRICTATIME, MS_STRICTATIME },
157 { "nosuid", 0, false, MOUNT_ATTR_NOSUID, MS_NOSUID },
158 { "relatime", 0, false, MOUNT_ATTR_RELATIME, MS_RELATIME },
159 { "ro", 0, false, MOUNT_ATTR_RDONLY, MS_RDONLY },
160 { "rw", 1, false, MOUNT_ATTR_RDONLY, MS_RDONLY },
161 { "strictatime", 0, false, MOUNT_ATTR_STRICTATIME, MS_STRICTATIME },
162 { "suid", 1, false, MOUNT_ATTR_NOSUID, MS_NOSUID },
163
164 { "bind", 0, false, 0, MS_BIND },
165 { "defaults", 0, false, 0, 0 },
166 { "rbind", 0, true, 0, MS_BIND | MS_REC },
167
168 { "sync", 0, false, ~0, MS_SYNCHRONOUS },
169 { "async", 1, false, ~0, MS_SYNCHRONOUS },
170 { "dirsync", 0, false, ~0, MS_DIRSYNC },
171 { "lazytime", 0, false, ~0, MS_LAZYTIME },
172 { "mand", 0, false, ~0, MS_MANDLOCK },
173 { "nomand", 1, false, ~0, MS_MANDLOCK },
174 { "remount", 0, false, ~0, MS_REMOUNT },
175
176 { NULL, 0, false, ~0, ~0 },
998ac676
RT
177};
178
d840039e 179static struct mount_opt propagation_opt[] = {
1b82d721
CB
180 { "private", 0, false, MS_PRIVATE, MS_PRIVATE },
181 { "shared", 0, false, MS_SHARED, MS_SHARED },
182 { "slave", 0, false, MS_SLAVE, MS_SLAVE },
183 { "unbindable", 0, false, MS_UNBINDABLE, MS_UNBINDABLE },
184 { "rprivate", 0, true, MS_PRIVATE, MS_PRIVATE | MS_REC },
185 { "rshared", 0, true, MS_SHARED, MS_SHARED | MS_REC },
186 { "rslave", 0, true, MS_SLAVE, MS_SLAVE | MS_REC },
187 { "runbindable", 0, true, MS_UNBINDABLE, MS_UNBINDABLE | MS_REC },
188 { NULL, 0, 0 },
d840039e
YT
189};
190
81810dd1 191static struct caps_opt caps_opt[] = {
8560cd36 192#if HAVE_LIBCAP
7b4cd468
CB
193 { "chown", CAP_CHOWN },
194 { "dac_override", CAP_DAC_OVERRIDE },
195 { "dac_read_search", CAP_DAC_READ_SEARCH },
196 { "fowner", CAP_FOWNER },
197 { "fsetid", CAP_FSETID },
198 { "kill", CAP_KILL },
199 { "setgid", CAP_SETGID },
200 { "setuid", CAP_SETUID },
201 { "setpcap", CAP_SETPCAP },
202 { "linux_immutable", CAP_LINUX_IMMUTABLE },
203 { "net_bind_service", CAP_NET_BIND_SERVICE },
204 { "net_broadcast", CAP_NET_BROADCAST },
205 { "net_admin", CAP_NET_ADMIN },
206 { "net_raw", CAP_NET_RAW },
207 { "ipc_lock", CAP_IPC_LOCK },
208 { "ipc_owner", CAP_IPC_OWNER },
209 { "sys_module", CAP_SYS_MODULE },
210 { "sys_rawio", CAP_SYS_RAWIO },
211 { "sys_chroot", CAP_SYS_CHROOT },
212 { "sys_ptrace", CAP_SYS_PTRACE },
213 { "sys_pacct", CAP_SYS_PACCT },
214 { "sys_admin", CAP_SYS_ADMIN },
215 { "sys_boot", CAP_SYS_BOOT },
216 { "sys_nice", CAP_SYS_NICE },
217 { "sys_resource", CAP_SYS_RESOURCE },
218 { "sys_time", CAP_SYS_TIME },
219 { "sys_tty_config", CAP_SYS_TTY_CONFIG },
220 { "mknod", CAP_MKNOD },
221 { "lease", CAP_LEASE },
222 { "audit_write", CAP_AUDIT_WRITE },
223 { "audit_control", CAP_AUDIT_CONTROL },
224 { "setfcap", CAP_SETFCAP },
225 { "mac_override", CAP_MAC_OVERRIDE },
226 { "mac_admin", CAP_MAC_ADMIN },
227 { "syslog", CAP_SYSLOG },
228 { "wake_alarm", CAP_WAKE_ALARM },
229 { "block_suspend", CAP_BLOCK_SUSPEND },
230 { "audit_read", CAP_AUDIT_READ },
231 { "perfmon", CAP_PERFMON },
232 { "bpf", CAP_BPF },
233 { "checkpoint_restore", CAP_CHECKPOINT_RESTORE },
2b54359b 234#endif
8560cd36 235};
81810dd1 236
c6d09e15
WB
237static struct limit_opt limit_opt[] = {
238#ifdef RLIMIT_AS
239 { "as", RLIMIT_AS },
240#endif
241#ifdef RLIMIT_CORE
242 { "core", RLIMIT_CORE },
243#endif
244#ifdef RLIMIT_CPU
245 { "cpu", RLIMIT_CPU },
246#endif
247#ifdef RLIMIT_DATA
248 { "data", RLIMIT_DATA },
249#endif
250#ifdef RLIMIT_FSIZE
251 { "fsize", RLIMIT_FSIZE },
252#endif
253#ifdef RLIMIT_LOCKS
254 { "locks", RLIMIT_LOCKS },
255#endif
256#ifdef RLIMIT_MEMLOCK
257 { "memlock", RLIMIT_MEMLOCK },
258#endif
259#ifdef RLIMIT_MSGQUEUE
260 { "msgqueue", RLIMIT_MSGQUEUE },
261#endif
262#ifdef RLIMIT_NICE
263 { "nice", RLIMIT_NICE },
264#endif
265#ifdef RLIMIT_NOFILE
266 { "nofile", RLIMIT_NOFILE },
267#endif
268#ifdef RLIMIT_NPROC
269 { "nproc", RLIMIT_NPROC },
270#endif
271#ifdef RLIMIT_RSS
272 { "rss", RLIMIT_RSS },
273#endif
274#ifdef RLIMIT_RTPRIO
275 { "rtprio", RLIMIT_RTPRIO },
276#endif
277#ifdef RLIMIT_RTTIME
278 { "rttime", RLIMIT_RTTIME },
279#endif
280#ifdef RLIMIT_SIGPENDING
281 { "sigpending", RLIMIT_SIGPENDING },
282#endif
283#ifdef RLIMIT_STACK
284 { "stack", RLIMIT_STACK },
285#endif
286};
287
91c3830e
SH
288static int run_buffer(char *buffer)
289{
cc6a0e78 290 __do_free char *output = NULL;
55022530 291 __do_lxc_pclose struct lxc_popen_FILE *f = NULL;
ebf3a6af 292 int fd, ret;
91c3830e 293
ebec9176 294 f = lxc_popen(buffer);
55022530
CB
295 if (!f)
296 return log_error_errno(-1, errno, "Failed to popen() %s", buffer);
91c3830e 297
b8e43ef0 298 output = zalloc(LXC_LOG_BUFFER_SIZE);
55022530
CB
299 if (!output)
300 return log_error_errno(-1, ENOMEM, "Failed to allocate memory for %s", buffer);
91c3830e 301
ebf3a6af 302 fd = fileno(f->f);
55022530
CB
303 if (fd < 0)
304 return log_error_errno(-1, errno, "Failed to retrieve underlying file descriptor");
ebf3a6af
CB
305
306 for (int i = 0; i < 10; i++) {
307 ssize_t bytes_read;
308
309 bytes_read = lxc_read_nointr(fd, output, LXC_LOG_BUFFER_SIZE - 1);
310 if (bytes_read > 0) {
311 output[bytes_read] = '\0';
312 DEBUG("Script %s produced output: %s", buffer, output);
313 continue;
314 }
315
316 break;
317 }
91c3830e 318
55022530
CB
319 ret = lxc_pclose(move_ptr(f));
320 if (ret == -1)
321 return log_error_errno(-1, errno, "Script exited with error");
322 else if (WIFEXITED(ret) && WEXITSTATUS(ret) != 0)
323 return log_error(-1, "Script exited with status %d", WEXITSTATUS(ret));
324 else if (WIFSIGNALED(ret))
325 return log_error(-1, "Script terminated by signal %d", WTERMSIG(ret));
91c3830e
SH
326
327 return 0;
328}
329
14a7b0f9
CB
330int run_script_argv(const char *name, unsigned int hook_version,
331 const char *section, const char *script,
586b1ce7 332 const char *hookname, char **argv)
148e91f5 333{
e1a94937 334 __do_free char *buffer = NULL;
3f60c2f7 335 int buf_pos, i, ret;
d08e5708 336 size_t size = 0;
148e91f5 337
3f60c2f7 338 if (hook_version == 0)
55022530
CB
339 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
340 script, name, section);
3f60c2f7
CB
341 else
342 INFO("Executing script \"%s\" for container \"%s\"", script, name);
148e91f5 343
586b1ce7
CB
344 for (i = 0; argv && argv[i]; i++)
345 size += strlen(argv[i]) + 1;
148e91f5 346
6333c915
CB
347 size += STRLITERALLEN("exec");
348 size++;
148e91f5 349 size += strlen(script);
3f60c2f7
CB
350 size++;
351
148e91f5 352 if (size > INT_MAX)
3f60c2f7 353 return -EFBIG;
148e91f5 354
3f60c2f7 355 if (hook_version == 0) {
d08e5708
CB
356 size += strlen(hookname);
357 size++;
358
359 size += strlen(name);
360 size++;
361
362 size += strlen(section);
363 size++;
364
365 if (size > INT_MAX)
366 return -EFBIG;
327cce76 367 }
3f60c2f7 368
b8e43ef0 369 buffer = zalloc(size);
6f8d00d2
CB
370 if (!buffer)
371 return -ENOMEM;
372
327cce76 373 if (hook_version == 0)
9bcde680 374 buf_pos = strnprintf(buffer, size, "exec %s %s %s %s", script, name, section, hookname);
327cce76 375 else
9bcde680
CB
376 buf_pos = strnprintf(buffer, size, "exec %s", script);
377 if (buf_pos < 0)
55022530 378 return log_error_errno(-1, errno, "Failed to create command line for script \"%s\"", script);
3f60c2f7 379
327cce76 380 if (hook_version == 1) {
3f60c2f7
CB
381 ret = setenv("LXC_HOOK_TYPE", hookname, 1);
382 if (ret < 0) {
55022530 383 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_HOOK_TYPE=%s", hookname);
3f60c2f7 384 }
90f20466 385 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname);
3f60c2f7
CB
386
387 ret = setenv("LXC_HOOK_SECTION", section, 1);
55022530
CB
388 if (ret < 0)
389 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_HOOK_SECTION=%s", section);
3f60c2f7 390 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section);
14a7b0f9 391
71528742 392 if (strequal(section, "net")) {
14a7b0f9
CB
393 char *parent;
394
586b1ce7 395 if (!argv || !argv[0])
e1a94937 396 return -1;
14a7b0f9 397
586b1ce7 398 ret = setenv("LXC_NET_TYPE", argv[0], 1);
55022530
CB
399 if (ret < 0)
400 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_NET_TYPE=%s", argv[0]);
586b1ce7 401 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv[0]);
14a7b0f9 402
586b1ce7 403 parent = argv[1] ? argv[1] : "";
14a7b0f9 404
71528742 405 if (strequal(argv[0], "macvlan")) {
14a7b0f9 406 ret = setenv("LXC_NET_PARENT", parent, 1);
55022530
CB
407 if (ret < 0)
408 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_NET_PARENT=%s", parent);
14a7b0f9 409 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent);
71528742 410 } else if (strequal(argv[0], "phys")) {
14a7b0f9 411 ret = setenv("LXC_NET_PARENT", parent, 1);
55022530
CB
412 if (ret < 0)
413 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_NET_PARENT=%s", parent);
14a7b0f9 414 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent);
71528742 415 } else if (strequal(argv[0], "veth")) {
586b1ce7 416 char *peer = argv[2] ? argv[2] : "";
14a7b0f9
CB
417
418 ret = setenv("LXC_NET_PEER", peer, 1);
55022530
CB
419 if (ret < 0)
420 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_NET_PEER=%s", peer);
14a7b0f9
CB
421 TRACE("Set environment variable: LXC_NET_PEER=%s", peer);
422
423 ret = setenv("LXC_NET_PARENT", parent, 1);
55022530
CB
424 if (ret < 0)
425 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_NET_PARENT=%s", parent);
14a7b0f9
CB
426 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent);
427 }
428 }
148e91f5
SH
429 }
430
586b1ce7 431 for (i = 0; argv && argv[i]; i++) {
3f60c2f7
CB
432 size_t len = size - buf_pos;
433
9bcde680
CB
434 ret = strnprintf(buffer + buf_pos, len, " %s", argv[i]);
435 if (ret < 0)
55022530 436 return log_error_errno(-1, errno, "Failed to create command line for script \"%s\"", script);
3f60c2f7 437 buf_pos += ret;
148e91f5
SH
438 }
439
e1a94937 440 return run_buffer(buffer);
148e91f5
SH
441}
442
811ef482 443int run_script(const char *name, const char *section, const char *script, ...)
e3b4c4c4 444{
2f443e88 445 __do_free char *buffer = NULL;
abbfd20b 446 int ret;
2f443e88 447 char *p;
abbfd20b 448 va_list ap;
0fd73091 449 size_t size = 0;
751d9dcd 450
0fd73091 451 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
751d9dcd 452 script, name, section);
e3b4c4c4 453
abbfd20b
DL
454 va_start(ap, script);
455 while ((p = va_arg(ap, char *)))
95642a10 456 size += strlen(p) + 1;
abbfd20b
DL
457 va_end(ap);
458
6333c915 459 size += STRLITERALLEN("exec");
abbfd20b
DL
460 size += strlen(script);
461 size += strlen(name);
462 size += strlen(section);
6d1a5f93 463 size += 4;
abbfd20b 464
95642a10
MS
465 if (size > INT_MAX)
466 return -1;
467
2f443e88 468 buffer = must_realloc(NULL, size);
9bcde680
CB
469 ret = strnprintf(buffer, size, "exec %s %s %s", script, name, section);
470 if (ret < 0)
9ba8130c 471 return -1;
751d9dcd 472
abbfd20b 473 va_start(ap, script);
9ba8130c 474 while ((p = va_arg(ap, char *))) {
062b72c6 475 int len = size - ret;
9ba8130c 476 int rc;
9bcde680
CB
477 rc = strnprintf(buffer + ret, len, " %s", p);
478 if (rc < 0) {
7b5a2435 479 va_end(ap);
9ba8130c 480 return -1;
7b5a2435 481 }
9ba8130c
SH
482 ret += rc;
483 }
abbfd20b 484 va_end(ap);
751d9dcd 485
91c3830e 486 return run_buffer(buffer);
e3b4c4c4
ST
487}
488
4e86cad3
CB
489int lxc_storage_prepare(struct lxc_conf *conf)
490{
491 int ret;
492 struct lxc_rootfs *rootfs = &conf->rootfs;
493
494 if (!rootfs->path) {
495 ret = mount("", "/", NULL, MS_SLAVE | MS_REC, 0);
496 if (ret < 0)
497 return log_error_errno(-1, errno, "Failed to recursively turn root mount tree into dependent mount");
498
499 rootfs->dfd_mnt = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
500 if (rootfs->dfd_mnt < 0)
501 return -errno;
502
503 return 0;
504 }
505
506 ret = access(rootfs->mount, F_OK);
507 if (ret != 0)
508 return log_error_errno(-1, errno, "Failed to access to \"%s\". Check it is present",
509 rootfs->mount);
510
511 rootfs->storage = storage_init(conf);
512 if (!rootfs->storage)
513 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
514 rootfs->path, rootfs->mount,
515 rootfs->options ? rootfs->options : "(null)");
516
517 return 0;
518}
519
520void lxc_storage_put(struct lxc_conf *conf)
521{
522 storage_put(conf->rootfs.storage);
523 conf->rootfs.storage = NULL;
524}
525
79ff643d 526/* lxc_rootfs_prepare
63fc76c3 527 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
b7ed4bf0
CS
528 * the duration of the container run, to prevent the container from marking
529 * the underlying fs readonly on shutdown. unlink the file immediately so
63fc76c3
GJ
530 * no name pollution is happens.
531 * don't unlink on NFS to avoid random named stale handles.
0c547523 532 */
239f29c9 533int lxc_rootfs_init(struct lxc_conf *conf, bool userns)
0c547523 534{
1b82d721 535 __do_close int dfd_path = -EBADF, fd_pin = -EBADF;
79ff643d
CB
536 int ret;
537 struct stat st;
538 struct statfs stfs;
4e86cad3
CB
539 struct lxc_rootfs *rootfs = &conf->rootfs;
540
541 ret = lxc_storage_prepare(conf);
542 if (ret)
543 return syserror_set(-EINVAL, "Failed to prepare rootfs storage");
0c547523 544
e26cf563 545 if (!is_empty_string(rootfs->mnt_opts.userns_path)) {
657ed14a
CB
546 if (!rootfs->path)
547 return syserror_set(-EINVAL, "Idmapped rootfs currently only supported with separate rootfs for container");
548
549 if (rootfs->bdev_type && !strequal(rootfs->bdev_type, "dir"))
550 return syserror_set(-EINVAL, "Idmapped rootfs currently only supports the \"dir\" storage driver");
e26cf563
CB
551 }
552
c119f018
CB
553 if (!rootfs->path)
554 return log_trace(0, "Not pinning because container does not have a rootfs");
e99ee0de 555
c119f018
CB
556 if (userns)
557 return log_trace(0, "Not pinning because container runs in user namespace");
79ff643d 558
c119f018
CB
559 if (rootfs->bdev_type) {
560 if (strequal(rootfs->bdev_type, "overlay") ||
561 strequal(rootfs->bdev_type, "overlayfs"))
562 return log_trace_errno(0, EINVAL, "Not pinning on stacking filesystem");
0c547523 563
c119f018
CB
564 if (strequal(rootfs->bdev_type, "zfs"))
565 return log_trace_errno(0, EINVAL, "Not pinning on ZFS filesystem");
e26cf563 566 }
79ff643d 567
c119f018
CB
568 dfd_path = open_at(-EBADF, rootfs->path, PROTECT_OPATH_FILE, 0, 0);
569 if (dfd_path < 0)
570 return syserror("Failed to open \"%s\"", rootfs->path);
571
79ff643d 572 ret = fstat(dfd_path, &st);
957c4704 573 if (ret < 0)
79ff643d 574 return log_trace_errno(-errno, errno, "Failed to retrieve file status");
0c547523 575
79ff643d
CB
576 if (!S_ISDIR(st.st_mode))
577 return log_trace_errno(0, ENOTDIR, "Not pinning because file descriptor is not a directory");
0c547523 578
79ff643d
CB
579 fd_pin = open_at(dfd_path, ".lxc_keep",
580 PROTECT_OPEN | O_CREAT,
581 PROTECT_LOOKUP_BENEATH,
582 S_IWUSR | S_IRUSR);
e859a5ee
WM
583 if (fd_pin < 0) {
584 if (errno == EROFS) {
585 return log_trace_errno(0, EROFS, "Not pinning on read-only filesystem");
586 }
e26cf563 587 return syserror("Failed to pin rootfs");
e859a5ee 588 }
0c547523 589
79ff643d 590 TRACE("Pinned rootfs %d(.lxc_keep)", fd_pin);
0fd73091 591
79ff643d
CB
592 ret = fstatfs(fd_pin, &stfs);
593 if (ret < 0) {
594 SYSWARN("Failed to retrieve filesystem status");
595 goto out;
596 }
63fc76c3 597
79ff643d
CB
598 if (stfs.f_type == NFS_SUPER_MAGIC) {
599 DEBUG("Not unlinking pinned file on NFS");
600 goto out;
601 }
63fc76c3 602
79ff643d
CB
603 if (unlinkat(dfd_path, ".lxc_keep", 0))
604 SYSTRACE("Failed to unlink rootfs pinning file %d(.lxc_keep)", dfd_path);
605 else
606 TRACE("Unlinked pinned file %d(.lxc_keep)", dfd_path);
0fd73091 607
79ff643d
CB
608out:
609 rootfs->fd_path_pin = move_fd(fd_pin);
610 return 0;
0c547523
SH
611}
612
4b875ef9
CB
613int lxc_rootfs_prepare_parent(struct lxc_handler *handler)
614{
615 __do_close int dfd_idmapped = -EBADF, fd_userns = -EBADF;
616 struct lxc_rootfs *rootfs = &handler->conf->rootfs;
617 struct lxc_storage *storage = rootfs->storage;
618 int ret;
619 const char *path_source;
620
621 if (lxc_list_empty(&handler->conf->id_map))
622 return 0;
623
624 if (is_empty_string(rootfs->mnt_opts.userns_path))
625 return 0;
626
627 if (handler->conf->rootfs_setup)
628 return 0;
629
630 if (rootfs_is_blockdev(handler->conf))
631 return syserror_set(-EOPNOTSUPP, "Idmapped mounts on block-backed storage not yet supported");
632
633 if (!can_use_bind_mounts())
634 return syserror_set(-EOPNOTSUPP, "Kernel does not support the new mount api");
635
1b82d721 636 if (strequal(rootfs->mnt_opts.userns_path, "container"))
4b875ef9
CB
637 fd_userns = dup_cloexec(handler->nsfd[LXC_NS_USER]);
638 else
639 fd_userns = open_at(-EBADF, rootfs->mnt_opts.userns_path,
640 PROTECT_OPEN_WITH_TRAILING_SYMLINKS, 0, 0);
641 if (fd_userns < 0)
642 return syserror("Failed to open user namespace");
643
644 path_source = lxc_storage_get_path(storage->src, storage->type);
645
646 dfd_idmapped = create_detached_idmapped_mount(path_source, fd_userns, true);
647 if (dfd_idmapped < 0)
648 return syserror("Failed to create detached idmapped mount");
649
650 ret = lxc_abstract_unix_send_fds(handler->data_sock[0], &dfd_idmapped, 1, NULL, 0);
651 if (ret < 0)
652 return syserror("Failed to send detached idmapped mount fd");
653
654 TRACE("Created detached idmapped mount %d", dfd_idmapped);
655 return 0;
656}
657
6b741397
CB
658static int add_shmount_to_list(struct lxc_conf *conf)
659{
6b5a54cd 660 char new_mount[PATH_MAX];
0d190408 661 /* Offset for the leading '/' since the path_cont
6b741397
CB
662 * is absolute inside the container.
663 */
664 int offset = 1, ret = -1;
0d190408 665
9bcde680 666 ret = strnprintf(new_mount, sizeof(new_mount),
6b741397
CB
667 "%s %s none bind,create=dir 0 0", conf->shmount.path_host,
668 conf->shmount.path_cont + offset);
9bcde680 669 if (ret < 0)
0d190408
LT
670 return -1;
671
6b741397 672 return add_elem_to_mount_list(new_mount, conf);
0d190408
LT
673}
674
6d25a524 675static int lxc_mount_auto_mounts(struct lxc_handler *handler, int flags)
368bbc02 676{
7b371c1e 677 int i, ret;
b06b8511
CS
678 static struct {
679 int match_mask;
680 int match_flag;
681 const char *source;
682 const char *destination;
683 const char *fstype;
684 unsigned long flags;
685 const char *options;
e8b9c9ec 686 bool requires_cap_net_admin;
b06b8511 687 } default_mounts[] = {
0fd73091
CB
688 /* Read-only bind-mounting... In older kernels, doing that
689 * required to do one MS_BIND mount and then
690 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
691 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
692 * onwards. However, this apparently does not work on kernel
693 * 3.8. Unfortunately, on that very same kernel, doing the same
694 * trick as above doesn't seem to work either, there one needs
695 * to ALSO specify MS_BIND for the remount, otherwise the
696 * entire fs is remounted read-only or the mount fails because
697 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
698 * kernels as low as 2.6.32...
368bbc02 699 */
5d1bf4c4 700 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL, false },
592fd47a 701 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
cb4889ab 702 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys/net", "%r/proc/tty", NULL, MS_BIND, NULL, true, },
5d1bf4c4
CB
703 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys", "%r/proc/sys", NULL, MS_BIND, NULL, false },
704 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL, false },
705 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/tty", "%r/proc/sys/net", NULL, MS_MOVE, NULL, true },
706 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL, MS_BIND, NULL, false },
707 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sysrq-trigger", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL, false },
708 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_RW, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL, false },
709 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RW, "sysfs", "%r/sys", "sysfs", 0, NULL, false },
710 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RO, "sysfs", "%r/sys", "sysfs", MS_RDONLY, NULL, false },
cb4889ab
CB
711 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys", "sysfs", MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL, false },
712 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys/devices/virtual/net", "%r/sys/devices/virtual/net", NULL, MS_BIND, NULL, false },
713 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, NULL, "%r/sys/devices/virtual/net", NULL, MS_REMOUNT|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL, false },
5d1bf4c4 714 { 0, 0, NULL, NULL, NULL, 0, NULL, false }
b06b8511 715 };
6d25a524 716 struct lxc_conf *conf = handler->conf;
e25af1bc
CB
717 struct lxc_rootfs *rootfs = &conf->rootfs;
718 bool has_cap_net_admin;
368bbc02 719
f4bea7cc 720 if (flags & LXC_AUTO_PROC_MASK) {
f6c5aab0
CB
721 if (rootfs->path) {
722 /*
723 * Only unmount procfs if we have a separate rootfs so
724 * we can still access it in safe_mount() below.
725 */
726 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/proc",
727 rootfs->path ? rootfs->mount : "");
728 if (ret < 0)
729 return ret_errno(EIO);
95258e34 730
f6c5aab0
CB
731 ret = umount2(rootfs->buf, MNT_DETACH);
732 if (ret)
733 SYSDEBUG("Tried to ensure procfs is unmounted");
734 }
95258e34 735
ea57e424 736 ret = mkdirat(rootfs->dfd_mnt, "proc" , S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
f4bea7cc 737 if (ret < 0 && errno != EEXIST)
0d33a382 738 return syserror("Failed to create procfs mountpoint under %d", rootfs->dfd_mnt);
c119f018
CB
739
740 TRACE("Created procfs mountpoint under %d", rootfs->dfd_mnt);
f4bea7cc
CB
741 }
742
743 if (flags & LXC_AUTO_SYS_MASK) {
f6c5aab0
CB
744 if (rootfs->path) {
745 /*
746 * Only unmount sysfs if we have a separate rootfs so
747 * we can still access it in safe_mount() below.
748 */
749 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/sys",
750 rootfs->path ? rootfs->mount : "");
751 if (ret < 0)
752 return ret_errno(EIO);
95258e34 753
f6c5aab0
CB
754 ret = umount2(rootfs->buf, MNT_DETACH);
755 if (ret)
756 SYSDEBUG("Tried to ensure sysfs is unmounted");
757 }
95258e34 758
ea57e424 759 ret = mkdirat(rootfs->dfd_mnt, "sys" , S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
f4bea7cc 760 if (ret < 0 && errno != EEXIST)
0d33a382 761 return syserror("Failed to create sysfs mountpoint under %d", rootfs->dfd_mnt);
c119f018
CB
762
763 TRACE("Created sysfs mountpoint under %d", rootfs->dfd_mnt);
f4bea7cc
CB
764 }
765
e25af1bc 766 has_cap_net_admin = lxc_wants_cap(CAP_NET_ADMIN, conf);
d84b26bc 767 for (i = 0; default_mounts[i].match_mask; i++) {
8db92302 768 __do_free char *destination = NULL, *source = NULL;
cb4889ab 769 unsigned long mflags = default_mounts[i].flags;
96f306e6 770
0fd73091
CB
771 if ((flags & default_mounts[i].match_mask) != default_mounts[i].match_flag)
772 continue;
773
774 if (default_mounts[i].source) {
cc4fd506 775 /* will act like strdup if %r is not present */
e25af1bc 776 source = lxc_string_replace("%r", rootfs->path ? rootfs->mount : "", default_mounts[i].source);
0fd73091 777 if (!source)
75fca1ac 778 return syserror_set(-ENOMEM, "Failed to create source path");
0fd73091 779 }
f24a52d5 780
55022530 781 if (!default_mounts[i].destination)
75fca1ac 782 return syserror_set(-EINVAL, "BUG: auto mounts destination %d was NULL", i);
0fd73091 783
e8b9c9ec 784 if (!has_cap_net_admin && default_mounts[i].requires_cap_net_admin) {
785 TRACE("Container does not have CAP_NET_ADMIN. Skipping \"%s\" mount", default_mounts[i].source ?: "(null)");
786 continue;
787 }
788
0fd73091 789 /* will act like strdup if %r is not present */
e25af1bc 790 destination = lxc_string_replace("%r", rootfs->path ? rootfs->mount : "", default_mounts[i].destination);
55022530 791 if (!destination)
75fca1ac 792 return syserror_set(-ENOMEM, "Failed to create target path");
0fd73091 793
cb4889ab
CB
794 ret = safe_mount(source, destination,
795 default_mounts[i].fstype,
796 mflags,
797 default_mounts[i].options,
75fca1ac 798 rootfs->path ? rootfs->mount : NULL);
7b371c1e 799 if (ret < 0) {
75fca1ac
CB
800 if (errno != ENOENT)
801 return syserror("Failed to mount \"%s\" on \"%s\" with flags %lu", source, destination, mflags);
802
803 INFO("Mount source or target for \"%s\" on \"%s\" does not exist. Skipping", source, destination);
804 continue;
368bbc02 805 }
cb4889ab
CB
806
807 if (mflags & MS_REMOUNT)
808 TRACE("Remounted automount \"%s\" on \"%s\" %s with flags %lu", source, destination, (mflags & MS_RDONLY) ? "read-only" : "read-write", mflags);
809 else
810 TRACE("Mounted automount \"%s\" on \"%s\" %s with flags %lu", source, destination, (mflags & MS_RDONLY) ? "read-only" : "read-write", mflags);
368bbc02
CS
811 }
812
b06b8511 813 if (flags & LXC_AUTO_CGROUP_MASK) {
0769b82a
CS
814 int cg_flags;
815
3f69fb12 816 cg_flags = flags & (LXC_AUTO_CGROUP_MASK & ~LXC_AUTO_CGROUP_FORCE);
0fd73091
CB
817 /* If the type of cgroup mount was not specified, it depends on
818 * the container's capabilities as to what makes sense: if we
819 * have CAP_SYS_ADMIN, the read-only part can be remounted
820 * read-write anyway, so we may as well default to read-write;
821 * then the admin will not be given a false sense of security.
822 * (And if they really want mixed r/o r/w, then they can
823 * explicitly specify :mixed.) OTOH, if the container lacks
824 * CAP_SYS_ADMIN, do only default to :mixed, because then the
825 * container can't remount it read-write.
826 */
9394b6dc 827 if ((cg_flags == LXC_AUTO_CGROUP_NOSPEC) || (cg_flags == LXC_AUTO_CGROUP_FULL_NOSPEC)) {
0769b82a 828 int has_sys_admin = 0;
b0ee5983
CB
829
830 if (!lxc_list_empty(&conf->keepcaps))
0769b82a 831 has_sys_admin = in_caplist(CAP_SYS_ADMIN, &conf->keepcaps);
b0ee5983 832 else
0769b82a 833 has_sys_admin = !in_caplist(CAP_SYS_ADMIN, &conf->caps);
b0ee5983
CB
834
835 if (cg_flags == LXC_AUTO_CGROUP_NOSPEC)
0769b82a 836 cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_RW : LXC_AUTO_CGROUP_MIXED;
b0ee5983 837 else
0769b82a 838 cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_FULL_RW : LXC_AUTO_CGROUP_FULL_MIXED;
0769b82a 839 }
0fd73091 840
3f69fb12 841 if (flags & LXC_AUTO_CGROUP_FORCE)
0fd73091
CB
842 cg_flags |= LXC_AUTO_CGROUP_FORCE;
843
ab8cd5d9 844 if (!handler->cgroup_ops->mount(handler->cgroup_ops, handler, cg_flags))
55022530 845 return log_error_errno(-1, errno, "Failed to mount \"/sys/fs/cgroup\"");
368bbc02
CS
846 }
847
0d190408 848 if (flags & LXC_AUTO_SHMOUNTS_MASK) {
7b371c1e 849 ret = add_shmount_to_list(conf);
55022530
CB
850 if (ret < 0)
851 return log_error(-1, "Failed to add shmount entry to container config");
0d190408
LT
852 }
853
368bbc02 854 return 0;
368bbc02
CS
855}
856
4e5440c6 857static int setup_utsname(struct utsname *utsname)
0ad19a3f 858{
0fd73091
CB
859 int ret;
860
4e5440c6
DL
861 if (!utsname)
862 return 0;
0ad19a3f 863
0fd73091 864 ret = sethostname(utsname->nodename, strlen(utsname->nodename));
55022530
CB
865 if (ret < 0)
866 return log_error_errno(-1, errno, "Failed to set the hostname to \"%s\"",
867 utsname->nodename);
0ad19a3f 868
0fd73091 869 INFO("Set hostname to \"%s\"", utsname->nodename);
cd54d859 870
0ad19a3f 871 return 0;
872}
873
69aa6655
DE
874struct dev_symlinks {
875 const char *oldpath;
876 const char *name;
877};
878
879static const struct dev_symlinks dev_symlinks[] = {
0fd73091
CB
880 { "/proc/self/fd", "fd" },
881 { "/proc/self/fd/0", "stdin" },
882 { "/proc/self/fd/1", "stdout" },
883 { "/proc/self/fd/2", "stderr" },
69aa6655
DE
884};
885
ed8704d0 886static int lxc_setup_dev_symlinks(const struct lxc_rootfs *rootfs)
69aa6655 887{
79019997
CB
888 for (int i = 0; i < sizeof(dev_symlinks) / sizeof(dev_symlinks[0]); i++) {
889 int ret;
890 struct stat s;
69aa6655 891 const struct dev_symlinks *d = &dev_symlinks[i];
0fd73091 892
79019997
CB
893 /*
894 * Stat the path first. If we don't get an error accept it as
0fd73091 895 * is and don't try to create it
09227be2 896 */
a5a08920 897 ret = fstatat(rootfs->dfd_dev, d->name, &s, 0);
0fd73091 898 if (ret == 0)
09227be2 899 continue;
09227be2 900
a5a08920 901 ret = symlinkat(d->oldpath, rootfs->dfd_dev, d->name);
79019997
CB
902 if (ret) {
903 switch (errno) {
904 case EROFS:
905 WARN("Failed to create \"%s\" on read-only filesystem", d->name);
906 __fallthrough;
907 case EEXIST:
908 break;
909 default:
910 return log_error_errno(-errno, errno, "Failed to create \"%s\"", d->name);
911 }
69aa6655
DE
912 }
913 }
0fd73091 914
69aa6655
DE
915 return 0;
916}
917
2187efd3 918/* Build a space-separate list of ptys to pass to systemd. */
885766f5 919static bool append_ttyname(char **pp, char *name)
b0a33c1e 920{
393903d1 921 char *p;
f1e05b90 922 size_t size;
393903d1
SH
923
924 if (!*pp) {
b8e43ef0 925 *pp = zalloc(strlen(name) + strlen("container_ttys=") + 1);
393903d1
SH
926 if (!*pp)
927 return false;
0fd73091 928
393903d1
SH
929 sprintf(*pp, "container_ttys=%s", name);
930 return true;
931 }
0fd73091 932
f1e05b90
DJ
933 size = strlen(*pp) + strlen(name) + 2;
934 p = realloc(*pp, size);
393903d1
SH
935 if (!p)
936 return false;
0fd73091 937
393903d1 938 *pp = p;
f1e05b90
DJ
939 (void)strlcat(p, " ", size);
940 (void)strlcat(p, name, size);
0fd73091 941
393903d1
SH
942 return true;
943}
944
128655e7
PM
945static int open_ttymnt_at(int dfd, const char *path)
946{
947 int fd;
948
777827cb
CB
949 fd = open_at(dfd, path,
950 PROTECT_OPEN | O_CREAT | O_EXCL,
951 PROTECT_LOOKUP_BENEATH,
952 0);
953 if (fd < 0) {
954 if (!IN_SET(errno, ENXIO, EEXIST))
955 return syserror("Failed to create \"%d/\%s\"", dfd, path);
956
957 SYSINFO("Failed to create \"%d/\%s\"", dfd, path);
958 fd = open_at(dfd, path,
959 PROTECT_OPATH_FILE,
960 PROTECT_LOOKUP_BENEATH,
961 0);
962 }
128655e7
PM
963
964 return fd;
965}
966
2187efd3 967static int lxc_setup_ttys(struct lxc_conf *conf)
393903d1 968{
7369e6bf
CB
969 int ret;
970 struct lxc_rootfs *rootfs = &conf->rootfs;
0e4be3cf 971 const struct lxc_tty_info *ttys = &conf->ttys;
885766f5 972 char *ttydir = ttys->dir;
b0a33c1e 973
e8bd4e43 974 if (!conf->rootfs.path)
bc9bd0e3
DL
975 return 0;
976
7369e6bf
CB
977 for (int i = 0; i < ttys->max; i++) {
978 __do_close int fd_to = -EBADF;
0e4be3cf 979 struct lxc_terminal_info *tty = &ttys->tty[i];
b0a33c1e 980
7c6ef2a2 981 if (ttydir) {
7369e6bf 982 char *tty_name, *tty_path;
9e1045e3 983
9bcde680 984 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf),
7369e6bf 985 "/dev/%s/tty%d", ttydir, i + 1);
9bcde680 986 if (ret < 0)
7369e6bf
CB
987 return ret_errno(-EIO);
988
989 tty_path = &rootfs->buf[STRLITERALLEN("/dev/")];
990 tty_name = tty_path + strlen(ttydir) + 1;
991
992 /* create bind-mount target */
128655e7 993 fd_to = open_ttymnt_at(rootfs->dfd_dev, tty_path);
7369e6bf
CB
994 if (fd_to < 0)
995 return log_error_errno(-errno, errno,
996 "Failed to create tty mount target %d(%s)",
997 rootfs->dfd_dev, tty_path);
998
999 ret = unlinkat(rootfs->dfd_dev, tty_name, 0);
1000 if (ret < 0 && errno != ENOENT)
1001 return log_error_errno(-errno, errno,
1002 "Failed to unlink %d(%s)",
1003 rootfs->dfd_dev, tty_name);
1004
84f8f9e4 1005 if (can_use_mount_api())
7369e6bf
CB
1006 ret = fd_bind_mount(tty->pty, "",
1007 PROTECT_OPATH_FILE,
1008 PROTECT_LOOKUP_BENEATH_XDEV,
1009 fd_to, "",
1010 PROTECT_OPATH_FILE,
1011 PROTECT_LOOKUP_BENEATH_XDEV, 0,
1012 false);
84f8f9e4
CB
1013 else
1014 ret = mount_fd(tty->pty, fd_to, "none", MS_BIND, 0);
7369e6bf
CB
1015 if (ret < 0)
1016 return log_error_errno(-errno, errno,
1017 "Failed to bind mount \"%s\" onto \"%s\"",
1018 tty->name, rootfs->buf);
1019 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty->name, rootfs->buf);
9e1045e3 1020
7369e6bf 1021 ret = symlinkat(tty_path, rootfs->dfd_dev, tty_name);
55022530 1022 if (ret < 0)
7369e6bf
CB
1023 return log_error_errno(-errno, errno,
1024 "Failed to create symlink \"%d(%s)\" -> \"%d(%s)\"",
1025 rootfs->dfd_dev, tty_name,
1026 rootfs->dfd_dev, tty_path);
7c6ef2a2 1027 } else {
9bcde680
CB
1028 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "tty%d", i + 1);
1029 if (ret < 0)
7369e6bf
CB
1030 return ret_errno(-EIO);
1031
1032 /* If we populated /dev, then we need to create /dev/tty<idx>. */
128655e7 1033 fd_to = open_ttymnt_at(rootfs->dfd_dev, rootfs->buf);
7369e6bf
CB
1034 if (fd_to < 0)
1035 return log_error_errno(-errno, errno,
1036 "Failed to create tty mount target %d(%s)",
1037 rootfs->dfd_dev, rootfs->buf);
1038
84f8f9e4 1039 if (can_use_mount_api())
7369e6bf
CB
1040 ret = fd_bind_mount(tty->pty, "",
1041 PROTECT_OPATH_FILE,
1042 PROTECT_LOOKUP_BENEATH_XDEV,
1043 fd_to, "",
1044 PROTECT_OPATH_FILE,
1045 PROTECT_LOOKUP_BENEATH, 0,
1046 false);
84f8f9e4
CB
1047 else
1048 ret = mount_fd(tty->pty, fd_to, "none", MS_BIND, 0);
7369e6bf
CB
1049 if (ret < 0)
1050 return log_error_errno(-errno, errno,
1051 "Failed to bind mount \"%s\" onto \"%s\"",
1052 tty->name, rootfs->buf);
1053 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty->name, rootfs->buf);
393903d1 1054 }
9e1045e3 1055
55022530
CB
1056 if (!append_ttyname(&conf->ttys.tty_names, tty->name))
1057 return log_error(-1, "Error setting up container_ttys string");
b0a33c1e 1058 }
1059
885766f5 1060 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys->max);
b0a33c1e 1061 return 0;
1062}
1063
9d0e129b
CB
1064define_cleanup_function(struct lxc_tty_info *, lxc_delete_tty);
1065
59eac805 1066static int lxc_allocate_ttys(struct lxc_conf *conf)
2187efd3 1067{
9d0e129b 1068 call_cleaner(lxc_delete_tty) struct lxc_tty_info *ttys = &conf->ttys;
fca23691 1069 int ret;
2187efd3
CB
1070
1071 /* no tty in the configuration */
885766f5 1072 if (ttys->max == 0)
2187efd3
CB
1073 return 0;
1074
9d0e129b
CB
1075 ttys->tty = zalloc(sizeof(struct lxc_terminal_info) * ttys->max);
1076 if (!ttys->tty)
2187efd3 1077 return -ENOMEM;
2187efd3 1078
7369e6bf 1079 for (size_t i = 0; i < conf->ttys.max; i++) {
d926c261 1080 int pty_nr = -1;
9d0e129b 1081 struct lxc_terminal_info *tty = &ttys->tty[i];
2187efd3 1082
4dcf0c43 1083 ret = lxc_devpts_terminal(conf->devpts_fd, &tty->ptx,
18129d94 1084 &tty->pty, &pty_nr, false);
77a39805 1085 if (ret < 0) {
7369e6bf 1086 conf->ttys.max = i;
6a2ca1b4 1087 return syserror_set(-ENOTTY, "Failed to create tty %zu", i);
2187efd3 1088 }
d926c261
CB
1089 DEBUG("Created tty with ptx fd %d and pty fd %d and index %d",
1090 tty->ptx, tty->pty, pty_nr);
7581d645 1091 tty->busy = -1;
2187efd3
CB
1092 }
1093
885766f5 1094 INFO("Finished creating %zu tty devices", ttys->max);
9d0e129b 1095 move_ptr(ttys);
2187efd3
CB
1096 return 0;
1097}
1098
0e4be3cf 1099void lxc_delete_tty(struct lxc_tty_info *ttys)
2187efd3 1100{
b35f8f7e 1101 if (!ttys || !ttys->tty)
386e6768
CB
1102 return;
1103
55022530 1104 for (int i = 0; i < ttys->max; i++) {
0e4be3cf 1105 struct lxc_terminal_info *tty = &ttys->tty[i];
36a94ce8 1106 close_prot_errno_disarm(tty->ptx);
41808e20 1107 close_prot_errno_disarm(tty->pty);
2187efd3
CB
1108 }
1109
55022530 1110 free_disarm(ttys->tty);
2187efd3
CB
1111}
1112
1b82d721 1113static int __lxc_send_ttys_to_parent(struct lxc_handler *handler)
2187efd3
CB
1114{
1115 int i;
0fd73091 1116 int ret = -1;
2187efd3 1117 struct lxc_conf *conf = handler->conf;
0e4be3cf 1118 struct lxc_tty_info *ttys = &conf->ttys;
2187efd3 1119 int sock = handler->data_sock[0];
2187efd3 1120
885766f5 1121 if (ttys->max == 0)
2187efd3
CB
1122 return 0;
1123
885766f5 1124 for (i = 0; i < ttys->max; i++) {
2187efd3 1125 int ttyfds[2];
0e4be3cf 1126 struct lxc_terminal_info *tty = &ttys->tty[i];
2187efd3 1127
36a94ce8 1128 ttyfds[0] = tty->ptx;
41808e20 1129 ttyfds[1] = tty->pty;
2187efd3
CB
1130
1131 ret = lxc_abstract_unix_send_fds(sock, ttyfds, 2, NULL, 0);
1132 if (ret < 0)
1133 break;
1134
41808e20
CB
1135 TRACE("Sent tty \"%s\" with ptx fd %d and pty fd %d to parent",
1136 tty->name, tty->ptx, tty->pty);
2187efd3
CB
1137 }
1138
1139 if (ret < 0)
6d1400b5 1140 SYSERROR("Failed to send %zu ttys to parent", ttys->max);
2187efd3 1141 else
885766f5 1142 TRACE("Sent %zu ttys to parent", ttys->max);
2187efd3
CB
1143
1144 return ret;
1145}
1146
1147static int lxc_create_ttys(struct lxc_handler *handler)
1148{
1149 int ret = -1;
1150 struct lxc_conf *conf = handler->conf;
1151
663014ee 1152 ret = lxc_allocate_ttys(conf);
2187efd3
CB
1153 if (ret < 0) {
1154 ERROR("Failed to allocate ttys");
1155 goto on_error;
1156 }
1157
2187efd3
CB
1158 if (!conf->is_execute) {
1159 ret = lxc_setup_ttys(conf);
1160 if (ret < 0) {
1161 ERROR("Failed to setup ttys");
1162 goto on_error;
1163 }
1164 }
1165
885766f5
CB
1166 if (conf->ttys.tty_names) {
1167 ret = setenv("container_ttys", conf->ttys.tty_names, 1);
1b82d721 1168 if (ret < 0) {
885766f5 1169 SYSERROR("Failed to set \"container_ttys=%s\"", conf->ttys.tty_names);
1b82d721
CB
1170 goto on_error;
1171 }
2187efd3
CB
1172 }
1173
1b82d721 1174 return 0;
2187efd3
CB
1175
1176on_error:
0e4be3cf 1177 lxc_delete_tty(&conf->ttys);
2187efd3 1178
1b82d721
CB
1179 return -1;
1180}
1181
111ed96e 1182static int lxc_send_ttys_to_parent(struct lxc_handler *handler)
1b82d721
CB
1183{
1184 int ret = -1;
1185
1186 ret = __lxc_send_ttys_to_parent(handler);
1187 lxc_delete_tty(&handler->conf->ttys);
2187efd3
CB
1188 return ret;
1189}
1190
7133b912
CB
1191/* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1192 * error, log it but don't fail yet.
91c3830e 1193 */
7133b912 1194static int mount_autodev(const char *name, const struct lxc_rootfs *rootfs,
63012bdd 1195 int autodevtmpfssize, const char *lxcpath)
91c3830e 1196{
bfbfeedf 1197 __do_close int fd_fs = -EBADF;
ee8eeba8 1198 const char *path = rootfs->path ? rootfs->mount : NULL;
bfbfeedf 1199 size_t tmpfs_size = (autodevtmpfssize != 0) ? autodevtmpfssize : 500000;
91c3830e 1200 int ret;
87e0e273 1201 mode_t cur_mask;
63012bdd 1202 char mount_options[128];
91c3830e 1203
7133b912 1204 INFO("Preparing \"/dev\"");
bc6928ff 1205
87e0e273 1206 cur_mask = umask(S_IXUSR | S_IXGRP | S_IXOTH);
ea57e424 1207 ret = mkdirat(rootfs->dfd_mnt, "dev" , S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
87e0e273
CB
1208 if (ret < 0 && errno != EEXIST) {
1209 SYSERROR("Failed to create \"/dev\" directory");
1210 ret = -errno;
1211 goto reset_umask;
bc6928ff 1212 }
87da4ec3 1213
de7f9f33 1214 if (can_use_mount_api()) {
635e7bac
CB
1215 fd_fs = fs_prepare("tmpfs", -EBADF, "", 0, 0);
1216 if (fd_fs < 0)
1217 return log_error_errno(-errno, errno, "Failed to prepare filesystem context for tmpfs");
ee8eeba8 1218
bfbfeedf
CB
1219 sprintf(mount_options, "%zu", tmpfs_size);
1220
1221 ret = fs_set_property(fd_fs, "mode", "0755");
1222 if (ret < 0)
1223 return log_error_errno(-errno, errno, "Failed to mount tmpfs onto %d(dev)", fd_fs);
1224
1225 ret = fs_set_property(fd_fs, "size", mount_options);
1226 if (ret < 0)
1227 return log_error_errno(-errno, errno, "Failed to mount tmpfs onto %d(dev)", fd_fs);
1228
89606dfb
CB
1229 ret = fs_attach(fd_fs, rootfs->dfd_mnt, "dev",
1230 PROTECT_OPATH_DIRECTORY,
1231 PROTECT_LOOKUP_BENEATH_XDEV, 0);
635e7bac
CB
1232 } else {
1233 __do_free char *fallback_path = NULL;
1234
1235 sprintf(mount_options, "size=%zu,mode=755", tmpfs_size);
1236 DEBUG("Using mount options: %s", mount_options);
1237
1238 if (path) {
1239 fallback_path = must_make_path(path, "/dev", NULL);
1240 ret = safe_mount("none", fallback_path, "tmpfs", 0, mount_options, path);
1241 } else {
1242 ret = safe_mount("none", "dev", "tmpfs", 0, mount_options, NULL);
1243 }
87e0e273 1244 }
bfbfeedf
CB
1245 if (ret < 0) {
1246 SYSERROR("Failed to mount tmpfs on \"%s\"", path);
1247 goto reset_umask;
1248 }
1249
7133b912 1250 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
bc6928ff
MW
1251 * If not, then create it and exit if that fails...
1252 */
ea57e424 1253 ret = mkdirat(rootfs->dfd_mnt, "dev/pts", S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
87e0e273 1254 if (ret < 0 && errno != EEXIST) {
bfbfeedf 1255 SYSERROR("Failed to create directory \"dev/pts\"");
87e0e273
CB
1256 ret = -errno;
1257 goto reset_umask;
91c3830e
SH
1258 }
1259
87e0e273
CB
1260 ret = 0;
1261
1262reset_umask:
1263 (void)umask(cur_mask);
1264
7133b912 1265 INFO("Prepared \"/dev\"");
87e0e273 1266 return ret;
91c3830e
SH
1267}
1268
5e73416f 1269struct lxc_device_node {
74a3920a 1270 const char *name;
5e73416f
CB
1271 const mode_t mode;
1272 const int maj;
1273 const int min;
c6883f38
SH
1274};
1275
5e73416f 1276static const struct lxc_device_node lxc_devices[] = {
06749971 1277 { "full", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 7 },
5e73416f 1278 { "null", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 3 },
06749971
CB
1279 { "random", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 8 },
1280 { "tty", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 5, 0 },
5e73416f
CB
1281 { "urandom", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 9 },
1282 { "zero", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 5 },
c6883f38
SH
1283};
1284
5067e4dd
CB
1285
1286enum {
1287 LXC_DEVNODE_BIND,
1288 LXC_DEVNODE_MKNOD,
1289 LXC_DEVNODE_PARTIAL,
1290 LXC_DEVNODE_OPEN,
1291};
1292
887ae844 1293static int lxc_fill_autodev(struct lxc_rootfs *rootfs)
c6883f38 1294{
5e73416f 1295 int i, ret;
3a32201c 1296 mode_t cmask;
5067e4dd 1297 int use_mknod = LXC_DEVNODE_MKNOD;
c6883f38 1298
a5a08920 1299 if (rootfs->dfd_dev < 0)
81498328 1300 return log_info(0, "No /dev directory found, skipping setup");
d43d5191 1301
3999be0a
CB
1302 INFO("Populating \"/dev\"");
1303
3a32201c 1304 cmask = umask(S_IXUSR | S_IXGRP | S_IXOTH);
5e73416f 1305 for (i = 0; i < sizeof(lxc_devices) / sizeof(lxc_devices[0]); i++) {
5e73416f 1306 const struct lxc_device_node *device = &lxc_devices[i];
0728ebf4 1307
5067e4dd 1308 if (use_mknod >= LXC_DEVNODE_MKNOD) {
a5a08920 1309 ret = mknodat(rootfs->dfd_dev, device->name, device->mode, makedev(device->maj, device->min));
5e73416f 1310 if (ret == 0 || (ret < 0 && errno == EEXIST)) {
d43d5191 1311 DEBUG("Created device node \"%s\"", device->name);
5067e4dd 1312 } else if (ret < 0) {
55022530 1313 if (errno != EPERM)
d43d5191 1314 return log_error_errno(-1, errno, "Failed to create device node \"%s\"", device->name);
0bbf8572 1315
5067e4dd 1316 use_mknod = LXC_DEVNODE_BIND;
9cb4d183 1317 }
3999be0a 1318
5067e4dd
CB
1319 /* Device nodes are fully useable. */
1320 if (use_mknod == LXC_DEVNODE_OPEN)
1321 continue;
1322
1323 if (use_mknod == LXC_DEVNODE_MKNOD) {
d43d5191 1324 __do_close int fd = -EBADF;
5067e4dd
CB
1325 /* See
1326 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1327 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1328 */
a5a08920 1329 fd = open_at(rootfs->dfd_dev, device->name, PROTECT_OPEN, PROTECT_LOOKUP_BENEATH, 0);
d43d5191 1330 if (fd >= 0) {
5067e4dd
CB
1331 /* Device nodes are fully useable. */
1332 use_mknod = LXC_DEVNODE_OPEN;
1333 continue;
1334 }
1335
d43d5191 1336 SYSTRACE("Failed to open \"%s\" device", device->name);
5067e4dd
CB
1337 /* Device nodes are only partially useable. */
1338 use_mknod = LXC_DEVNODE_PARTIAL;
1339 }
5e73416f
CB
1340 }
1341
5067e4dd
CB
1342 if (use_mknod != LXC_DEVNODE_PARTIAL) {
1343 /* If we are dealing with partially functional device
1344 * nodes the prio mknod() call will have created the
1345 * device node so we can use it as a bind-mount target.
1346 */
a5a08920 1347 ret = mknodat(rootfs->dfd_dev, device->name, S_IFREG | 0000, 0);
55022530 1348 if (ret < 0 && errno != EEXIST)
d43d5191 1349 return log_error_errno(-1, errno, "Failed to create file \"%s\"", device->name);
5e73416f
CB
1350 }
1351
1352 /* Fallback to bind-mounting the device from the host. */
9bcde680
CB
1353 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "dev/%s", device->name);
1354 if (ret < 0)
b41ff502 1355 return ret_errno(EIO);
5e73416f 1356
de7f9f33 1357 if (can_use_mount_api()) {
887ae844 1358 ret = fd_bind_mount(rootfs->dfd_host, rootfs->buf,
635e7bac
CB
1359 PROTECT_OPATH_FILE,
1360 PROTECT_LOOKUP_BENEATH_XDEV,
1361 rootfs->dfd_dev, device->name,
1362 PROTECT_OPATH_FILE,
1363 PROTECT_LOOKUP_BENEATH, 0, false);
1364 } else {
927ea337
CB
1365 char path[PATH_MAX];
1366
9bcde680
CB
1367 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/dev/%s", device->name);
1368 if (ret < 0)
927ea337
CB
1369 return ret_errno(EIO);
1370
9bcde680
CB
1371 ret = strnprintf(path, sizeof(path), "%s/dev/%s", get_rootfs_mnt(rootfs), device->name);
1372 if (ret < 0)
927ea337
CB
1373 return log_error(-1, "Failed to create device path for %s", device->name);
1374
887ae844 1375 ret = safe_mount(rootfs->buf, path, 0, MS_BIND, NULL, get_rootfs_mnt(rootfs));
927ea337 1376 if (ret < 0)
887ae844 1377 return log_error_errno(-1, errno, "Failed to bind mount host device node \"%s\" to \"%s\"", rootfs->buf, path);
927ea337 1378
887ae844 1379 DEBUG("Bind mounted host device node \"%s\" to \"%s\"", rootfs->buf, path);
927ea337 1380 continue;
d43d5191 1381 }
887ae844 1382 DEBUG("Bind mounted host device %d(%s) to %d(%s)", rootfs->dfd_host, rootfs->buf, rootfs->dfd_dev, device->name);
c6883f38 1383 }
5e73416f 1384 (void)umask(cmask);
c6883f38 1385
3999be0a 1386 INFO("Populated \"/dev\"");
c6883f38
SH
1387 return 0;
1388}
1389
4e86cad3 1390static int lxc_mount_rootfs(struct lxc_rootfs *rootfs)
0ad19a3f 1391{
9aa76a17 1392 int ret;
cc28d0b0 1393
a0f379bf 1394 if (!rootfs->path) {
0fd73091 1395 ret = mount("", "/", NULL, MS_SLAVE | MS_REC, 0);
55022530 1396 if (ret < 0)
9e61fb1f 1397 return log_error_errno(-1, errno, "Failed to recursively turn root mount tree into dependent mount");
0fd73091 1398
ea57e424
CB
1399 rootfs->dfd_mnt = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
1400 if (rootfs->dfd_mnt < 0)
31f8b2fd
CB
1401 return -errno;
1402
c119f018 1403 return log_trace(0, "Container doesn't use separate rootfs. Opened host's rootfs");
a0f379bf 1404 }
0ad19a3f 1405
0fd73091 1406 ret = access(rootfs->mount, F_OK);
55022530
CB
1407 if (ret != 0)
1408 return log_error_errno(-1, errno, "Failed to access to \"%s\". Check it is present",
1409 rootfs->mount);
b1789442 1410
4e86cad3 1411 ret = rootfs->storage->ops->mount(rootfs->storage);
55022530
CB
1412 if (ret < 0)
1413 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1414 rootfs->path, rootfs->mount,
1415 rootfs->options ? rootfs->options : "(null)");
0ad19a3f 1416
0fd73091 1417 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
91c3e281
CB
1418 rootfs->path, rootfs->mount,
1419 rootfs->options ? rootfs->options : "(null)");
9aa76a17 1420
ea57e424
CB
1421 rootfs->dfd_mnt = open_at(-EBADF, rootfs->mount, PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE_XDEV, 0);
1422 if (rootfs->dfd_mnt < 0)
31f8b2fd
CB
1423 return -errno;
1424
c119f018 1425 return log_trace(0, "Container uses separate rootfs. Opened container's rootfs");
ac778708
DL
1426}
1427
59eac805 1428static int lxc_chroot(const struct lxc_rootfs *rootfs)
91e93c71 1429{
b8d88764 1430 __do_free char *nroot = NULL;
0fd73091 1431 int i, ret;
8ce1abc2 1432 char *root = rootfs->mount;
91e93c71 1433
74e7b662 1434 nroot = realpath(root, NULL);
55022530
CB
1435 if (!nroot)
1436 return log_error_errno(-1, errno, "Failed to resolve \"%s\"", root);
91e93c71 1437
0fd73091 1438 ret = chdir("/");
b8d88764 1439 if (ret < 0)
0fd73091 1440 return -1;
91e93c71 1441
0fd73091
CB
1442 /* We could use here MS_MOVE, but in userns this mount is locked and
1443 * can't be moved.
91e93c71 1444 */
8ce1abc2 1445 ret = mount(nroot, "/", NULL, MS_REC | MS_BIND, NULL);
55022530
CB
1446 if (ret < 0)
1447 return log_error_errno(-1, errno, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot);
91e93c71 1448
0fd73091 1449 ret = mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL);
55022530
CB
1450 if (ret < 0)
1451 return log_error_errno(-1, errno, "Failed to remount \"/\"");
91e93c71 1452
aa899945 1453 /* The following code cleans up inherited mounts which are not required
0fd73091 1454 * for CT.
91e93c71
AV
1455 *
1456 * The mountinfo file shows not all mounts, if a few points have been
1457 * unmounted between read operations from the mountinfo. So we need to
1458 * read mountinfo a few times.
1459 *
7ded5fa7 1460 * This loop can be skipped if a container uses userns, because all
91e93c71
AV
1461 * inherited mounts are locked and we should live with all this trash.
1462 */
0fd73091 1463 for (;;) {
4fdd1f72 1464 __do_fclose FILE *f = NULL;
f3d38164
CB
1465 __do_free char *line = NULL;
1466 char *slider1, *slider2;
91e93c71 1467 int progress = 0;
f3d38164 1468 size_t len = 0;
91e93c71 1469
4110345b 1470 f = fopen("./proc/self/mountinfo", "re");
55022530
CB
1471 if (!f)
1472 return log_error_errno(-1, errno, "Failed to open \"/proc/self/mountinfo\"");
0fd73091 1473
f3d38164
CB
1474 while (getline(&line, &len, f) > 0) {
1475 for (slider1 = line, i = 0; slider1 && i < 4; i++)
1476 slider1 = strchr(slider1 + 1, ' ');
0fd73091 1477
f3d38164 1478 if (!slider1)
91e93c71 1479 continue;
0fd73091 1480
f3d38164
CB
1481 slider2 = strchr(slider1 + 1, ' ');
1482 if (!slider2)
91e93c71
AV
1483 continue;
1484
f3d38164
CB
1485 *slider2 = '\0';
1486 *slider1 = '.';
91e93c71 1487
71528742 1488 if (strequal(slider1 + 1, "/"))
91e93c71 1489 continue;
0fd73091 1490
71528742 1491 if (strequal(slider1 + 1, "/proc"))
91e93c71
AV
1492 continue;
1493
f3d38164 1494 ret = umount2(slider1, MNT_DETACH);
0fd73091 1495 if (ret == 0)
91e93c71
AV
1496 progress++;
1497 }
0fd73091 1498
91e93c71
AV
1499 if (!progress)
1500 break;
1501 }
1502
7ded5fa7 1503 /* This also can be skipped if a container uses userns. */
0fd73091 1504 (void)umount2("./proc", MNT_DETACH);
91e93c71
AV
1505
1506 /* It is weird, but chdir("..") moves us in a new root */
0fd73091 1507 ret = chdir("..");
55022530
CB
1508 if (ret < 0)
1509 return log_error_errno(-1, errno, "Failed to chdir(\"..\")");
91e93c71 1510
0fd73091 1511 ret = chroot(".");
55022530
CB
1512 if (ret < 0)
1513 return log_error_errno(-1, errno, "Failed to chroot(\".\")");
91e93c71
AV
1514
1515 return 0;
1516}
1517
8ce1abc2
CB
1518/* (The following explanation is copied verbatim from the kernel.)
1519 *
1520 * pivot_root Semantics:
1521 * Moves the root file system of the current process to the directory put_old,
1522 * makes new_root as the new root file system of the current process, and sets
1523 * root/cwd of all processes which had them on the current root to new_root.
1524 *
1525 * Restrictions:
1526 * The new_root and put_old must be directories, and must not be on the
1527 * same file system as the current process root. The put_old must be
1528 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1529 * pointed to by put_old must yield the same directory as new_root. No other
1530 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1531 *
1532 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1533 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1534 * in this situation.
1535 *
1536 * Notes:
1537 * - we don't move root/cwd if they are not at the root (reason: if something
1538 * cared enough to change them, it's probably wrong to force them elsewhere)
1539 * - it's okay to pick a root that isn't the root of a file system, e.g.
1540 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1541 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1542 * first.
1543 */
7f50ec8b 1544static int lxc_pivot_root(const struct lxc_rootfs *rootfs)
ac778708 1545{
7f50ec8b 1546 __do_close int fd_oldroot = -EBADF;
b0d7aac4 1547 int ret;
0fd73091 1548
7f50ec8b
CB
1549 fd_oldroot = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
1550 if (fd_oldroot < 0)
55022530 1551 return log_error_errno(-1, errno, "Failed to open old root directory");
ac778708 1552
8ce1abc2 1553 /* change into new root fs */
ea57e424 1554 ret = fchdir(rootfs->dfd_mnt);
55022530 1555 if (ret < 0)
7f50ec8b 1556 return log_error_errno(-errno, errno, "Failed to change into new root directory \"%s\"", rootfs->mount);
39c7b795 1557
8ce1abc2
CB
1558 /* pivot_root into our new root fs */
1559 ret = pivot_root(".", ".");
55022530 1560 if (ret < 0)
7f50ec8b 1561 return log_error_errno(-errno, errno, "Failed to pivot into new root directory \"%s\"", rootfs->mount);
39c7b795 1562
8ce1abc2
CB
1563 /* At this point the old-root is mounted on top of our new-root. To
1564 * unmounted it we must not be chdir'd into it, so escape back to
1565 * old-root.
1566 */
7f50ec8b 1567 ret = fchdir(fd_oldroot);
55022530 1568 if (ret < 0)
7f50ec8b 1569 return log_error_errno(-errno, errno, "Failed to enter old root directory");
c69bd12f 1570
7f50ec8b
CB
1571 /*
1572 * Make fd_oldroot a depedent mount to make sure our umounts don't
1573 * propagate to the host.
8ce1abc2
CB
1574 */
1575 ret = mount("", ".", "", MS_SLAVE | MS_REC, NULL);
55022530 1576 if (ret < 0)
7f50ec8b 1577 return log_error_errno(-errno, errno, "Failed to recursively turn old root mount tree into dependent mount");
8ce1abc2
CB
1578
1579 ret = umount2(".", MNT_DETACH);
55022530 1580 if (ret < 0)
7f50ec8b 1581 return log_error_errno(-errno, errno, "Failed to detach old root directory");
8ce1abc2 1582
ea57e424 1583 ret = fchdir(rootfs->dfd_mnt);
55022530 1584 if (ret < 0)
7f50ec8b 1585 return log_error_errno(-errno, errno, "Failed to re-enter new root directory \"%s\"", rootfs->mount);
8ce1abc2 1586
7f50ec8b 1587 TRACE("Changed into new rootfs \"%s\"", rootfs->mount);
b0d7aac4 1588 return 0;
0ad19a3f 1589}
1590
8ce1abc2
CB
1591static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs *rootfs)
1592{
55022530
CB
1593 if (!rootfs->path)
1594 return log_debug(0, "Container does not have a rootfs");
8ce1abc2
CB
1595
1596 if (detect_ramfs_rootfs())
1597 return lxc_chroot(rootfs);
1598
7f50ec8b 1599 return lxc_pivot_root(rootfs);
0ad19a3f 1600}
1601
7581a82f 1602static const struct id_map *find_mapped_nsid_entry(const struct lxc_conf *conf,
8ce1abc2
CB
1603 unsigned id,
1604 enum idtype idtype)
f4900711
CB
1605{
1606 struct lxc_list *it;
1607 struct id_map *map;
1608 struct id_map *retmap = NULL;
1609
dcf0ffdf
CB
1610 /* Shortcut for container's root mappings. */
1611 if (id == 0) {
1612 if (idtype == ID_TYPE_UID)
1613 return conf->root_nsuid_map;
1614
1615 if (idtype == ID_TYPE_GID)
1616 return conf->root_nsgid_map;
1617 }
1618
f4900711
CB
1619 lxc_list_for_each(it, &conf->id_map) {
1620 map = it->elem;
1621 if (map->idtype != idtype)
1622 continue;
1623
1624 if (id >= map->nsid && id < map->nsid + map->range) {
1625 retmap = map;
1626 break;
1627 }
1628 }
1629
1630 return retmap;
1631}
1632
42c0d056 1633static int lxc_recv_devpts_from_child(struct lxc_handler *handler)
68f3899e
CB
1634{
1635 int ret;
1636
1637 if (handler->conf->pty_max <= 0)
1638 return 0;
1639
d17c815d
CB
1640 ret = lxc_abstract_unix_recv_one_fd(handler->data_sock[1],
1641 &handler->conf->devpts_fd,
1642 &handler->conf->devpts_fd,
1643 sizeof(handler->conf->devpts_fd));
68f3899e
CB
1644 if (ret < 0)
1645 return log_error_errno(-1, errno, "Failed to receive devpts fd from child");
1646
1647 TRACE("Received devpts file descriptor %d from child", handler->conf->devpts_fd);
1648 return 0;
1649}
1650
96a980e1 1651static int lxc_setup_devpts_child(struct lxc_handler *handler)
289b707b 1652{
96a980e1 1653 __do_close int devpts_fd = -EBADF, fd_fs = -EBADF;
289b707b 1654 struct lxc_conf *conf = handler->conf;
f30fc74d 1655 struct lxc_rootfs *rootfs = &conf->rootfs;
289b707b
CB
1656 int ret;
1657
289b707b
CB
1658 if (conf->pty_max <= 0)
1659 return log_debug(0, "No new devpts instance will be mounted since no pts devices are requested");
1660
f30fc74d
CB
1661 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf),
1662 "/proc/self/fd/%d/pts", rootfs->dfd_dev);
1663 if (ret < 0)
1664 return syserror("Failed to create path");
1665
1666 (void)umount2(rootfs->buf, MNT_DETACH);
1667
1668 /* Create mountpoint for devpts instance. */
1669 ret = mkdirat(rootfs->dfd_dev, "pts", 0755);
1670 if (ret < 0 && errno != EEXIST)
1671 return log_error_errno(-1, errno, "Failed to create \"/dev/pts\" directory");
1672
96a980e1
CB
1673 if (can_use_mount_api()) {
1674 fd_fs = fs_prepare("devpts", -EBADF, "", 0, 0);
1675 if (fd_fs < 0)
1676 return syserror("Failed to prepare filesystem context for devpts");
289b707b 1677
96a980e1
CB
1678 ret = fs_set_property(fd_fs, "source", "devpts");
1679 if (ret < 0)
1680 SYSTRACE("Failed to set \"source=devpts\" on devpts filesystem context %d", fd_fs);
289b707b 1681
96a980e1
CB
1682 ret = fs_set_property(fd_fs, "gid", "5");
1683 if (ret < 0)
1684 SYSTRACE("Failed to set \"gid=5\" on devpts filesystem context %d", fd_fs);
289b707b 1685
96a980e1
CB
1686 ret = fs_set_flag(fd_fs, "newinstance");
1687 if (ret < 0)
1688 return syserror("Failed to set \"newinstance\" property on devpts filesystem context %d", fd_fs);
289b707b 1689
96a980e1
CB
1690 ret = fs_set_property(fd_fs, "ptmxmode", "0666");
1691 if (ret < 0)
1692 return syserror("Failed to set \"ptmxmode=0666\" property on devpts filesystem context %d", fd_fs);
289b707b 1693
96a980e1
CB
1694 ret = fs_set_property(fd_fs, "mode", "0620");
1695 if (ret < 0)
1696 return syserror("Failed to set \"mode=0620\" property on devpts filesystem context %d", fd_fs);
289b707b 1697
96a980e1
CB
1698 ret = fs_set_property(fd_fs, "max", fdstr(conf->pty_max));
1699 if (ret < 0)
1700 return syserror("Failed to set \"max=%zu\" property on devpts filesystem context %d", conf->pty_max, fd_fs);
f30fc74d 1701
96a980e1
CB
1702 ret = fsconfig(fd_fs, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
1703 if (ret < 0)
1704 return syserror("Failed to finalize filesystem context %d", fd_fs);
289b707b 1705
96a980e1
CB
1706 devpts_fd = fsmount(fd_fs, FSMOUNT_CLOEXEC, MOUNT_ATTR_NOSUID | MOUNT_ATTR_NOEXEC);
1707 if (devpts_fd < 0)
1708 return syserror("Failed to create new mount for filesystem context %d", fd_fs);
1709 TRACE("Created detached devpts mount %d", devpts_fd);
77890c6d 1710
96a980e1
CB
1711 ret = move_mount(devpts_fd, "", rootfs->dfd_dev, "pts", MOVE_MOUNT_F_EMPTY_PATH);
1712 if (ret)
1713 return syserror("Failed to attach devpts mount %d to %d/pts", conf->devpts_fd, rootfs->dfd_dev);
3c26f34e 1714
96a980e1
CB
1715 DEBUG("Attached detached devpts mount %d to %d/pts", devpts_fd, rootfs->dfd_dev);
1716 } else {
1717 char **opts;
1718 char devpts_mntopts[256];
1719 char *mntopt_sets[5];
1720 char default_devpts_mntopts[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
7e40254a 1721
f30fc74d
CB
1722 /*
1723 * Fallback codepath in case the new mount API can't be used to
1724 * create detached mounts.
1725 */
1726
289b707b
CB
1727 ret = strnprintf(devpts_mntopts, sizeof(devpts_mntopts), "%s,max=%zu",
1728 default_devpts_mntopts, conf->pty_max);
1729 if (ret < 0)
1730 return -1;
3c26f34e 1731
289b707b
CB
1732 /* Create mountpoint for devpts instance. */
1733 ret = mkdirat(rootfs->dfd_dev, "pts", 0755);
1734 if (ret < 0 && errno != EEXIST)
1735 return log_error_errno(-1, errno, "Failed to create \"/dev/pts\" directory");
ce155c60 1736
289b707b
CB
1737 /* gid=5 && max= */
1738 mntopt_sets[0] = devpts_mntopts;
ce155c60 1739
289b707b
CB
1740 /* !gid=5 && max= */
1741 mntopt_sets[1] = devpts_mntopts + STRLITERALLEN("gid=5") + 1;
ce155c60 1742
289b707b
CB
1743 /* gid=5 && !max= */
1744 mntopt_sets[2] = default_devpts_mntopts;
ce155c60 1745
289b707b
CB
1746 /* !gid=5 && !max= */
1747 mntopt_sets[3] = default_devpts_mntopts + STRLITERALLEN("gid=5") + 1;
ce155c60 1748
289b707b
CB
1749 /* end */
1750 mntopt_sets[4] = NULL;
70761e5e 1751
289b707b
CB
1752 for (ret = -1, opts = mntopt_sets; opts && *opts; opts++) {
1753 /* mount new devpts instance */
8b0ccdaa
CB
1754 ret = mount_at(rootfs->dfd_dev, "", 0,
1755 rootfs->dfd_dev, "pts", PROTECT_LOOKUP_BENEATH,
1756 "devpts", MS_NOSUID | MS_NOEXEC, *opts);
289b707b
CB
1757 if (ret == 0)
1758 break;
1759 }
289b707b
CB
1760 if (ret < 0)
1761 return log_error_errno(-1, errno, "Failed to mount new devpts instance");
1762
1763 devpts_fd = open_at(rootfs->dfd_dev, "pts", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_BENEATH_XDEV, 0);
1764 if (devpts_fd < 0) {
1765 devpts_fd = -EBADF;
1766 TRACE("Failed to create detached devpts mount");
1767 }
1768
289b707b
CB
1769 DEBUG("Mounted new devpts instance with options \"%s\"", *opts);
1770 }
96a980e1 1771 handler->conf->devpts_fd = move_fd(devpts_fd);
f797f05e 1772
d5cb35d6 1773 /* Remove any pre-existing /dev/ptmx file. */
a5a08920 1774 ret = unlinkat(rootfs->dfd_dev, "ptmx", 0);
b29e05d6 1775 if (ret < 0) {
55022530
CB
1776 if (errno != ENOENT)
1777 return log_error_errno(-1, errno, "Failed to remove existing \"/dev/ptmx\" file");
b29e05d6 1778 } else {
0fd73091 1779 DEBUG("Removed existing \"/dev/ptmx\" file");
3c26f34e 1780 }
1781
8de0119d 1782 /* Create placeholder /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
a5a08920 1783 ret = mknodat(rootfs->dfd_dev, "ptmx", S_IFREG | 0000, 0);
55022530 1784 if (ret < 0 && errno != EEXIST)
8de0119d
CB
1785 return log_error_errno(-1, errno, "Failed to create \"/dev/ptmx\" file as bind mount target");
1786 DEBUG("Created \"/dev/ptmx\" file as bind mount target");
77890c6d 1787
d27ae999 1788 /* Main option: use a bind-mount to please AppArmor */
8b0ccdaa
CB
1789 ret = mount_at(rootfs->dfd_dev, "pts/ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS & ~RESOLVE_NO_XDEV),
1790 rootfs->dfd_dev, "ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS & ~RESOLVE_NO_XDEV),
1791 NULL, MS_BIND, NULL);
55022530
CB
1792 if (!ret)
1793 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1794 else
d5cb35d6 1795 /* Fallthrough and try to create a symlink. */
0fd73091 1796 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
d5cb35d6 1797
8de0119d 1798 /* Remove the placeholder /dev/ptmx file we created above. */
a5a08920 1799 ret = unlinkat(rootfs->dfd_dev, "ptmx", 0);
55022530
CB
1800 if (ret < 0)
1801 return log_error_errno(-1, errno, "Failed to remove existing \"/dev/ptmx\"");
d5cb35d6
CB
1802
1803 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
06853427 1804 ret = symlinkat("/dev/pts/ptmx", rootfs->dfd_dev, "dev/ptmx");
55022530
CB
1805 if (ret < 0)
1806 return log_error_errno(-1, errno, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
cd54d859 1807
185b9ee9 1808 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
3c26f34e 1809 return 0;
1810}
1811
111ed96e 1812static int lxc_send_devpts_to_parent(struct lxc_handler *handler)
1b82d721
CB
1813{
1814 int ret;
1815
1816 if (handler->conf->pty_max <= 0)
1817 return log_debug(0, "No devpts file descriptor will be sent since no pts devices are requested");
1818
1819 ret = lxc_abstract_unix_send_fds(handler->data_sock[0], &handler->conf->devpts_fd, 1, NULL, 0);
1820 if (ret < 0)
1821 SYSERROR("Failed to send devpts file descriptor %d to parent", handler->conf->devpts_fd);
1822 else
1823 TRACE("Sent devpts file descriptor %d to parent", handler->conf->devpts_fd);
1824
1825 close_prot_errno_disarm(handler->conf->devpts_fd);
1826
1827 return 0;
1828}
1829
64a04c84 1830static int setup_personality(personality_t persona)
cccc74b5 1831{
0fd73091
CB
1832 int ret;
1833
9c601e1f
CB
1834 if (persona == LXC_ARCH_UNCHANGED)
1835 return log_debug(0, "Retaining original personality");
cccc74b5 1836
64a04c84 1837 ret = lxc_personality(persona);
55022530 1838 if (ret < 0)
9c601e1f 1839 return syserror("Failed to set personality to \"0lx%lx\"", persona);
cccc74b5 1840
38608992 1841 INFO("Set personality to \"0lx%lx\"", persona);
cccc74b5
DL
1842 return 0;
1843}
1844
9f77617b 1845static int bind_mount_console(int fd_devpts, struct lxc_rootfs *rootfs,
d94a7f09 1846 struct lxc_terminal *console, int fd_to)
37c74fd1
CB
1847{
1848 __do_close int fd_pty = -EBADF;
1849
1850 if (is_empty_string(console->name))
1851 return ret_errno(EINVAL);
1852
1853 /*
1854 * When the pty fd stashed in console->pty has been retrieved via the
1855 * TIOCGPTPEER ioctl() to avoid dangerous path-based lookups when
1856 * allocating new pty devices we can't reopen it through openat2() or
1857 * created a detached mount through open_tree() from it. This means we
1858 * would need to mount using the path stased in console->name which is
1859 * unsafe. We could be mounting a device that isn't identical to the
1860 * one we've already safely opened and stashed in console->pty.
1861 * So, what we do is we open an O_PATH file descriptor for
1862 * console->name and verify that the opened fd and the fd we stashed in
1863 * console->pty refer to the same device. If they do we can go on and
1864 * created a detached mount based on the newly opened O_PATH file
1865 * descriptor and then safely mount.
1866 */
9f77617b 1867 fd_pty = open_at_same(console->pty, fd_devpts, fdstr(console->pty_nr),
d94a7f09 1868 PROTECT_OPATH_FILE, PROTECT_LOOKUP_ABSOLUTE_XDEV, 0);
37c74fd1 1869 if (fd_pty < 0)
d94a7f09 1870 return syserror("Failed to open \"%s\"", console->name);
37c74fd1
CB
1871
1872 /*
1873 * Note, there are intentionally no open or lookup restrictions since
1874 * we're operating directly on the fd.
1875 */
d94a7f09
CB
1876 if (can_use_mount_api())
1877 return fd_bind_mount(fd_pty, "", 0, 0, fd_to, "", 0, 0, 0, false);
1878
1879 return mount_fd(fd_pty, fd_to, "none", MS_BIND, 0);
37c74fd1
CB
1880}
1881
9f77617b 1882static int lxc_setup_dev_console(int fd_devpts, struct lxc_rootfs *rootfs,
d94a7f09 1883 struct lxc_terminal *console)
6e590161 1884{
af0cf9b7 1885 __do_close int fd_console = -EBADF;
882671aa 1886 int ret;
52e35957 1887
cf68ffd9
CB
1888 /*
1889 * When we are asked to setup a console we remove any previous
8b1b1210
CB
1890 * /dev/console bind-mounts.
1891 */
a5a08920 1892 if (exists_file_at(rootfs->dfd_dev, "console")) {
af0cf9b7
CB
1893 char *rootfs_path = rootfs->path ? rootfs->mount : "";
1894
9bcde680
CB
1895 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/dev/console", rootfs_path);
1896 if (ret < 0)
953db219
CB
1897 return -1;
1898
58b38111 1899 ret = lxc_unstack_mountpoint(rootfs->buf, false);
55022530 1900 if (ret < 0)
58b38111 1901 return log_error_errno(-ret, errno, "Failed to unmount \"%s\"", rootfs->buf);
55022530 1902 else
58b38111 1903 DEBUG("Cleared all (%d) mounts from \"%s\"", ret, rootfs->buf);
8b1b1210
CB
1904 }
1905
cf68ffd9
CB
1906 /*
1907 * For unprivileged containers autodev or automounts will already have
8b1b1210
CB
1908 * taken care of creating /dev/console.
1909 */
d94a7f09
CB
1910 fd_console = open_at(rootfs->dfd_dev,
1911 "console",
1912 PROTECT_OPEN | O_CREAT,
1913 PROTECT_LOOKUP_BENEATH,
1914 0000);
af0cf9b7 1915 if (fd_console < 0)
d94a7f09 1916 return syserror("Failed to create \"%d/console\"", rootfs->dfd_dev);
52e35957 1917
1dd71c90 1918 ret = fchmod(console->pty, 0620);
55022530 1919 if (ret < 0)
d94a7f09 1920 return syserror("Failed to change console mode");
13954cce 1921
9f77617b 1922 ret = bind_mount_console(fd_devpts, rootfs, console, fd_console);
37c74fd1 1923 if (ret < 0)
d94a7f09
CB
1924 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
1925 console->pty, console->name, fd_console);
6e590161 1926
d94a7f09 1927 TRACE("Setup console \"%s\"", console->name);
7c6ef2a2
SH
1928 return 0;
1929}
1930
9f77617b 1931static int lxc_setup_ttydir_console(int fd_devpts, struct lxc_rootfs *rootfs,
d94a7f09 1932 struct lxc_terminal *console,
37c74fd1 1933 char *ttydir)
7c6ef2a2 1934{
d94a7f09
CB
1935 __do_close int fd_ttydir = -EBADF, fd_dev_console = -EBADF,
1936 fd_reg_console = -EBADF, fd_reg_ttydir_console = -EBADF;
3b7e332f 1937 int ret;
7c6ef2a2 1938
f6370f2a
CB
1939 /* create dev/<ttydir> */
1940 ret = mkdirat(rootfs->dfd_dev, ttydir, 0755);
1941 if (ret < 0 && errno != EEXIST)
1942 return syserror("Failed to create \"%d/%s\"", rootfs->dfd_dev, ttydir);
d94a7f09
CB
1943
1944 fd_ttydir = open_at(rootfs->dfd_dev,
1945 ttydir,
1946 PROTECT_OPATH_DIRECTORY,
1947 PROTECT_LOOKUP_BENEATH,
1948 0);
1949 if (fd_ttydir < 0)
1950 return syserror("Failed to open \"%d/%s\"", rootfs->dfd_dev, ttydir);
7c6ef2a2 1951
f6370f2a 1952 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/console", ttydir);
9bcde680 1953 if (ret < 0)
3d7d929a
CB
1954 return -1;
1955
f6370f2a 1956 /* create dev/<ttydir>/console */
d94a7f09
CB
1957 fd_reg_ttydir_console = open_at(fd_ttydir,
1958 "console",
1959 PROTECT_OPEN | O_CREAT,
1960 PROTECT_LOOKUP_BENEATH,
1961 0000);
1962 if (fd_reg_ttydir_console < 0)
1963 return syserror("Failed to create \"%d/console\"", fd_ttydir);
2a12fefd 1964
f6370f2a 1965 if (file_exists(rootfs->buf)) {
d94a7f09
CB
1966 char *rootfs_path = rootfs->path ? rootfs->mount : "";
1967
1968 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/dev/console", rootfs_path);
1969 if (ret < 0)
1970 return -1;
1971
f6370f2a 1972 ret = lxc_unstack_mountpoint(rootfs->buf, false);
55022530 1973 if (ret < 0)
f6370f2a 1974 return log_error_errno(-ret, errno, "Failed to unmount \"%s\"", rootfs->buf);
55022530 1975 else
f6370f2a 1976 DEBUG("Cleared all (%d) mounts from \"%s\"", ret, rootfs->buf);
3dc035f1 1977 }
2a12fefd 1978
d94a7f09
CB
1979 /* create dev/console */
1980 fd_reg_console = open_at(rootfs->dfd_dev,
1981 "console",
1982 PROTECT_OPEN | O_CREAT,
1983 PROTECT_LOOKUP_BENEATH,
1984 0000);
1985 if (fd_reg_console < 0)
1986 return syserror("Failed to create \"%d/console\"", rootfs->dfd_dev);
7c6ef2a2 1987
1dd71c90 1988 ret = fchmod(console->pty, 0620);
55022530 1989 if (ret < 0)
d94a7f09 1990 return syserror("Failed to change console mode");
2a12fefd 1991
d94a7f09 1992 /* bind mount console to '/dev/<ttydir>/console' */
9f77617b 1993 ret = bind_mount_console(fd_devpts, rootfs, console, fd_reg_ttydir_console);
55022530 1994 if (ret < 0)
d94a7f09
CB
1995 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
1996 console->pty, console->name, fd_reg_ttydir_console);
1997
1998 fd_dev_console = open_at_same(console->pty,
1999 fd_ttydir,
2000 "console",
2001 PROTECT_OPATH_FILE,
2002 PROTECT_LOOKUP_BENEATH_XDEV,
2003 0);
2004 if (fd_dev_console < 0)
2005 return syserror("Failed to open \"%d/console\"", fd_ttydir);
2006
2007 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
2008 if (can_use_mount_api())
2009 ret = fd_bind_mount(fd_dev_console,
2010 "",
2011 PROTECT_OPATH_FILE,
2012 PROTECT_LOOKUP_BENEATH_XDEV,
2013 fd_reg_console,
2014 "",
2015 PROTECT_OPATH_FILE,
2016 PROTECT_LOOKUP_BENEATH,
2017 0,
2018 false);
2019 else
2020 ret = mount_fd(fd_dev_console, fd_reg_console, "none", MS_BIND, 0);
55022530 2021 if (ret < 0)
d94a7f09
CB
2022 return syserror("Failed to mount \"%d\" on \"%d\"",
2023 fd_dev_console, fd_reg_console);
3dc035f1 2024
d94a7f09 2025 TRACE("Setup console \"%s\"", console->name);
6e590161 2026 return 0;
2027}
2028
f3dff080
CB
2029static int lxc_setup_console(const struct lxc_handler *handler,
2030 struct lxc_rootfs *rootfs,
37c74fd1 2031 struct lxc_terminal *console, char *ttydir)
7c6ef2a2 2032{
9f77617b
CB
2033 __do_close int fd_devpts_host = -EBADF;
2034 int fd_devpts = handler->conf->devpts_fd;
2035 int ret = -1;
3d7d929a 2036
37c74fd1
CB
2037 if (!wants_console(console))
2038 return log_trace(0, "Skipping console setup");
7c6ef2a2 2039
9f77617b
CB
2040 if (console->pty < 0) {
2041 /*
2042 * Allocate a console from the container's devpts instance. We
2043 * have checked on the host that we have enough pty devices
2044 * available.
2045 */
2046 ret = lxc_devpts_terminal(handler->conf->devpts_fd, &console->ptx,
18129d94 2047 &console->pty, &console->pty_nr, false);
9f77617b
CB
2048 if (ret < 0)
2049 return syserror("Failed to allocate console from container's devpts instance");
2050
2051 ret = strnprintf(console->name, sizeof(console->name),
2052 "/dev/pts/%d", console->pty_nr);
2053 if (ret < 0)
2054 return syserror("Failed to create console path");
2055 } else {
2056 /*
2057 * We're using a console from the host's devpts instance. Open
2058 * it again so we can later verify that the console we're
2059 * supposed to use is still the same as the one we opened on
2060 * the host.
2061 */
2062 fd_devpts_host = open_at(rootfs->dfd_host,
2063 "dev/pts",
2064 PROTECT_OPATH_DIRECTORY,
2065 PROTECT_LOOKUP_BENEATH_XDEV,
2066 0);
2067 if (fd_devpts_host < 0)
2068 return syserror("Failed to open host devpts");
2069
2070 fd_devpts = fd_devpts_host;
2071 }
2072
37c74fd1 2073 if (ttydir)
9f77617b 2074 ret = lxc_setup_ttydir_console(fd_devpts, rootfs, console, ttydir);
37c74fd1 2075 else
9f77617b 2076 ret = lxc_setup_dev_console(fd_devpts, rootfs, console);
87dfb724
CB
2077 if (ret < 0)
2078 return syserror("Failed to setup console");
2079
f3dff080
CB
2080 /*
2081 * Some init's such as busybox will set sane tty settings on stdin,
2082 * stdout, stderr which it thinks is the console. We already set them
2083 * the way we wanted on the real terminal, and we want init to do its
2084 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
2085 * make sure that that pty is stdin,stdout,stderr.
2086 */
9f77617b 2087 if (console->pty >= 0) {
f3dff080 2088 if (handler->daemonize || !handler->conf->is_execute)
9f77617b 2089 ret = set_stdfds(console->pty);
f3dff080 2090 else
9f77617b 2091 ret = lxc_terminal_set_stdfds(console->pty);
f3dff080 2092 if (ret < 0)
9f77617b
CB
2093 return syserror("Failed to redirect std{in,out,err} to pty file descriptor %d", console->pty);
2094
2095 /*
2096 * If the console has been allocated from the host's devpts
2097 * we're done and we don't need to send fds to the parent.
2098 */
2099 if (fd_devpts_host >= 0)
2100 lxc_terminal_delete(console);
f3dff080
CB
2101 }
2102
37c74fd1 2103 return ret;
7c6ef2a2
SH
2104}
2105
a08bfbe3 2106static int parse_mntopt(char *opt, unsigned long *flags, char **data, size_t size)
998ac676 2107{
a08bfbe3 2108 ssize_t ret;
998ac676 2109
85c2de39
MB
2110 /* If '=' is contained in opt, the option must go into data. */
2111 if (!strchr(opt, '=')) {
a08bfbe3
CB
2112 /*
2113 * If opt is found in mount_opt, set or clear flags.
2114 * Otherwise append it to data.
2115 */
85c2de39 2116 size_t opt_len = strlen(opt);
a08bfbe3 2117 for (struct mount_opt *mo = &mount_opt[0]; mo->name != NULL; mo++) {
85c2de39 2118 size_t mo_name_len = strlen(mo->name);
a08bfbe3 2119
eed95eb0 2120 if (opt_len == mo_name_len && strnequal(opt, mo->name, mo_name_len)) {
85c2de39 2121 if (mo->clear)
1e4bce2c 2122 *flags &= ~mo->legacy_flag;
85c2de39 2123 else
1e4bce2c 2124 *flags |= mo->legacy_flag;
a08bfbe3 2125 return 0;
85c2de39 2126 }
998ac676
RT
2127 }
2128 }
2129
a08bfbe3
CB
2130 if (strlen(*data)) {
2131 ret = strlcat(*data, ",", size);
2132 if (ret < 0)
2133 return log_error_errno(ret, errno, "Failed to append \",\" to %s", *data);
2134 }
2135
2136 ret = strlcat(*data, opt, size);
2137 if (ret < 0)
2138 return log_error_errno(ret, errno, "Failed to append \"%s\" to %s", opt, *data);
efed99a4 2139
a08bfbe3 2140 return 0;
998ac676
RT
2141}
2142
d94eb390 2143int parse_mntopts_legacy(const char *mntopts, unsigned long *mntflags, char **mntdata)
998ac676 2144{
a08bfbe3
CB
2145 __do_free char *mntopts_new = NULL, *mntopts_dup = NULL;
2146 char *mntopt_cur = NULL;
efed99a4 2147 size_t size;
998ac676 2148
a08bfbe3
CB
2149 if (*mntdata || *mntflags)
2150 return ret_errno(EINVAL);
911324ef
DL
2151
2152 if (!mntopts)
998ac676
RT
2153 return 0;
2154
a08bfbe3
CB
2155 mntopts_dup = strdup(mntopts);
2156 if (!mntopts_dup)
2157 return ret_errno(ENOMEM);
998ac676 2158
a08bfbe3
CB
2159 size = strlen(mntopts_dup) + 1;
2160 mntopts_new = zalloc(size);
2161 if (!mntopts_new)
2162 return ret_errno(ENOMEM);
998ac676 2163
a08bfbe3
CB
2164 lxc_iterate_parts(mntopt_cur, mntopts_dup, ",")
2165 if (parse_mntopt(mntopt_cur, mntflags, &mntopts_new, size) < 0)
2166 return ret_errno(EINVAL);
998ac676 2167
a08bfbe3
CB
2168 if (*mntopts_new)
2169 *mntdata = move_ptr(mntopts_new);
998ac676
RT
2170
2171 return 0;
2172}
2173
1b82d721
CB
2174static int parse_vfs_attr(struct lxc_mount_options *opts, char *opt, size_t size)
2175{
2176 /*
2177 * If opt is found in mount_opt, set or clear flags.
2178 * Otherwise append it to data.
2179 */
2180 for (struct mount_opt *mo = &mount_opt[0]; mo->name != NULL; mo++) {
2181 if (!strnequal(opt, mo->name, strlen(mo->name)))
2182 continue;
2183
2184 /* This is a recursive bind-mount. */
2185 if (strequal(mo->name, "rbind")) {
2186 opts->recursive = 1;
2187 opts->bind = 1;
2188 return 0;
2189 }
2190
2191 /* This is a bind-mount. */
2192 if (strequal(mo->name, "bind")) {
2193 opts->bind = 1;
2194 return 0;
2195 }
2196
2197 if (mo->flag == ~0)
2198 return log_info(0, "Ignoring %s mount option", mo->name);
2199
2200 if (mo->clear) {
2201 opts->attr.attr_clr |= mo->flag;
2202 TRACE("Lowering %s", mo->name);
2203 } else {
2204 opts->attr.attr_set |= mo->flag;
2205 TRACE("Raising %s", mo->name);
2206 }
2207
2208 return 0;
2209 }
2210
2211 for (struct mount_opt *mo = &mount_opt[0]; mo->name != NULL; mo++) {
2212 if (!strnequal(opt, mo->name, strlen(mo->name)))
2213 continue;
2214
2215 /* TODO: Handle recursive propagation requests. */
2216 opts->attr.propagation = mo->flag;
2217 return 0;
2218 }
2219
2220 return 0;
2221}
2222
2223static int parse_mount_attrs(struct lxc_mount_options *opts, const char *mntopts)
2224{
2225 __do_free char *mntopts_new = NULL, *mntopts_dup = NULL;
380fcc08 2226 char *end = NULL, *mntopt_cur = NULL;
1b82d721
CB
2227 int ret;
2228 size_t size;
2229
2230 if (!opts)
2231 return ret_errno(EINVAL);
2232
2233 if (!mntopts)
2234 return 0;
2235
2236 mntopts_dup = strdup(mntopts);
2237 if (!mntopts_dup)
2238 return ret_errno(ENOMEM);
2239
2240 size = strlen(mntopts_dup) + 1;
2241 mntopts_new = zalloc(size);
2242 if (!mntopts_new)
2243 return ret_errno(ENOMEM);
2244
2245 lxc_iterate_parts(mntopt_cur, mntopts_dup, ",") {
1b82d721
CB
2246 /* This is a filesystem specific option. */
2247 if (strchr(mntopt_cur, '=')) {
2248 if (!end) {
2249 end = stpcpy(mntopts_new, mntopt_cur);
2250 } else {
2251 end = stpcpy(end, ",");
2252 end = stpcpy(end, mntopt_cur);
2253 }
2254
2255 continue;
2256 }
2257
2258 /* This is a generic vfs option. */
2259 ret = parse_vfs_attr(opts, mntopt_cur, size);
2260 if (ret < 0)
2261 return syserror("Failed to parse mount attributes: \"%s\"", mntopt_cur);
2262 }
2263
2264 if (*mntopts_new)
2265 opts->data = move_ptr(mntopts_new);
2266
2267 return 0;
2268}
2269
d840039e
YT
2270static void parse_propagationopt(char *opt, unsigned long *flags)
2271{
2272 struct mount_opt *mo;
2273
2274 /* If opt is found in propagation_opt, set or clear flags. */
d840039e 2275 for (mo = &propagation_opt[0]; mo->name != NULL; mo++) {
eed95eb0 2276 if (!strnequal(opt, mo->name, strlen(mo->name)))
0fd73091
CB
2277 continue;
2278
2279 if (mo->clear)
1e4bce2c 2280 *flags &= ~mo->legacy_flag;
0fd73091 2281 else
1e4bce2c 2282 *flags |= mo->legacy_flag;
0fd73091
CB
2283
2284 return;
d840039e
YT
2285 }
2286}
2287
8ce1abc2 2288int parse_propagationopts(const char *mntopts, unsigned long *pflags)
d840039e 2289{
dfd2e059
CB
2290 __do_free char *s = NULL;
2291 char *p;
d840039e
YT
2292
2293 if (!mntopts)
2294 return 0;
2295
2296 s = strdup(mntopts);
55022530
CB
2297 if (!s)
2298 return log_error_errno(-ENOMEM, errno, "Failed to allocate memory");
d840039e 2299
0fd73091 2300 *pflags = 0L;
8db9d26f 2301 lxc_iterate_parts(p, s, ",")
d840039e 2302 parse_propagationopt(p, pflags);
0fd73091 2303
d840039e
YT
2304 return 0;
2305}
2306
6fd5e769
SH
2307static void null_endofword(char *word)
2308{
2309 while (*word && *word != ' ' && *word != '\t')
2310 word++;
2311 *word = '\0';
2312}
2313
0fd73091 2314/* skip @nfields spaces in @src */
6fd5e769
SH
2315static char *get_field(char *src, int nfields)
2316{
6fd5e769 2317 int i;
0fd73091 2318 char *p = src;
6fd5e769
SH
2319
2320 for (i = 0; i < nfields; i++) {
2321 while (*p && *p != ' ' && *p != '\t')
2322 p++;
0fd73091 2323
6fd5e769
SH
2324 if (!*p)
2325 break;
0fd73091 2326
6fd5e769
SH
2327 p++;
2328 }
0fd73091 2329
6fd5e769
SH
2330 return p;
2331}
2332
911324ef
DL
2333static int mount_entry(const char *fsname, const char *target,
2334 const char *fstype, unsigned long mountflags,
d840039e
YT
2335 unsigned long pflags, const char *data, bool optional,
2336 bool dev, bool relative, const char *rootfs)
911324ef 2337{
0ac4b28a 2338 int ret;
6b5a54cd 2339 char srcbuf[PATH_MAX];
181437fd 2340 const char *srcpath = fsname;
614305f3 2341#ifdef HAVE_STATVFS
2938f7c8 2342 struct statvfs sb;
614305f3 2343#endif
2938f7c8 2344
181437fd 2345 if (relative) {
9bcde680
CB
2346 ret = strnprintf(srcbuf, sizeof(srcbuf), "%s/%s", rootfs ? rootfs : "/", fsname ? fsname : "");
2347 if (ret < 0)
55022530 2348 return log_error_errno(-1, errno, "source path is too long");
181437fd
YT
2349 srcpath = srcbuf;
2350 }
2351
2352 ret = safe_mount(srcpath, target, fstype, mountflags & ~MS_REMOUNT, data,
0ac4b28a
CB
2353 rootfs);
2354 if (ret < 0) {
55022530
CB
2355 if (optional)
2356 return log_info_errno(0, errno, "Failed to mount \"%s\" on \"%s\" (optional)",
2357 srcpath ? srcpath : "(null)", target);
0ac4b28a 2358
55022530
CB
2359 return log_error_errno(-1, errno, "Failed to mount \"%s\" on \"%s\"",
2360 srcpath ? srcpath : "(null)", target);
911324ef
DL
2361 }
2362
2363 if ((mountflags & MS_REMOUNT) || (mountflags & MS_BIND)) {
0ac4b28a 2364
55022530
CB
2365 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
2366 srcpath ? srcpath : "(none)", target ? target : "(none)");
0ac4b28a 2367
614305f3 2368#ifdef HAVE_STATVFS
181437fd 2369 if (srcpath && statvfs(srcpath, &sb) == 0) {
94bef7e4
TA
2370 unsigned long required_flags = 0;
2371
2938f7c8
SH
2372 if (sb.f_flag & MS_NOSUID)
2373 required_flags |= MS_NOSUID;
0ac4b28a 2374
ae7a770e 2375 if (sb.f_flag & MS_NODEV && !dev)
2938f7c8 2376 required_flags |= MS_NODEV;
0ac4b28a 2377
2938f7c8
SH
2378 if (sb.f_flag & MS_RDONLY)
2379 required_flags |= MS_RDONLY;
0ac4b28a 2380
2938f7c8
SH
2381 if (sb.f_flag & MS_NOEXEC)
2382 required_flags |= MS_NOEXEC;
0ac4b28a 2383
55022530
CB
2384 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
2385 srcpath, sb.f_flag, required_flags);
0ac4b28a
CB
2386
2387 /* If this was a bind mount request, and required_flags
2938f7c8 2388 * does not have any flags which are not already in
0ac4b28a 2389 * mountflags, then skip the remount.
2938f7c8 2390 */
94bef7e4
TA
2391 if (!(mountflags & MS_REMOUNT) &&
2392 (!(required_flags & ~mountflags) && !(mountflags & MS_RDONLY))) {
15f3e22b
CB
2393 DEBUG("Mountflags already were %lu, skipping remount", mountflags);
2394 goto skipremount;
2938f7c8 2395 }
0ac4b28a 2396
2938f7c8 2397 mountflags |= required_flags;
6fd5e769 2398 }
614305f3 2399#endif
911324ef 2400
181437fd 2401 ret = mount(srcpath, target, fstype, mountflags | MS_REMOUNT, data);
0ac4b28a 2402 if (ret < 0) {
55022530
CB
2403 if (optional)
2404 return log_info_errno(0, errno, "Failed to mount \"%s\" on \"%s\" (optional)",
2405 srcpath ? srcpath : "(null)",
2406 target);
2407
2408 return log_error_errno(-1, errno, "Failed to mount \"%s\" on \"%s\"",
2409 srcpath ? srcpath : "(null)",
2410 target);
911324ef
DL
2411 }
2412 }
2413
a3ed9b81 2414#ifdef HAVE_STATVFS
2415skipremount:
2416#endif
d840039e
YT
2417 if (pflags) {
2418 ret = mount(NULL, target, NULL, pflags, NULL);
2419 if (ret < 0) {
55022530
CB
2420 if (optional)
2421 return log_info_errno(0, errno, "Failed to change mount propagation for \"%s\" (optional)", target);
2422 else
2423 return log_error_errno(-1, errno, "Failed to change mount propagation for \"%s\" (optional)", target);
d840039e
YT
2424 }
2425 DEBUG("Changed mount propagation for \"%s\"", target);
2426 }
2427
0103eb53 2428 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
181437fd 2429 srcpath ? srcpath : "(null)", target, fstype);
911324ef
DL
2430
2431 return 0;
2432}
2433
0b932f9d
CB
2434const char *lxc_mount_options_info[LXC_MOUNT_MAX] = {
2435 "create=dir",
2436 "create=file",
2437 "optional",
2438 "relative",
f6815906 2439 "idmap=",
0b932f9d
CB
2440};
2441
c5e30de4 2442/* Remove "optional", "create=dir", and "create=file" from mntopt */
1b82d721 2443int parse_lxc_mount_attrs(struct lxc_mount_options *opts, char *mnt_opts)
4e4ca161 2444{
0b932f9d 2445 for (size_t i = LXC_MOUNT_CREATE_DIR; i < LXC_MOUNT_MAX; i++) {
8e05f350 2446 __do_close int fd_userns = -EBADF;
0b932f9d 2447 const char *opt_name = lxc_mount_options_info[i];
f6815906 2448 size_t len;
d97d9e9f 2449 char *idmap_path, *opt, *opt_next;
c5e30de4 2450
d97d9e9f
CB
2451 opt = strstr(mnt_opts, opt_name);
2452 if (!opt)
4e4ca161 2453 continue;
c5e30de4 2454
0b932f9d
CB
2455 switch (i) {
2456 case LXC_MOUNT_CREATE_DIR:
2457 opts->create_dir = 1;
2458 break;
2459 case LXC_MOUNT_CREATE_FILE:
2460 opts->create_file = 1;
2461 break;
2462 case LXC_MOUNT_OPTIONAL:
2463 opts->optional = 1;
2464 break;
2465 case LXC_MOUNT_RELATIVE:
2466 opts->relative = 1;
2467 break;
f6815906 2468 case LXC_MOUNT_IDMAP:
d97d9e9f
CB
2469 opt_next = opt;
2470 opt_next += STRLITERALLEN("idmap=");
2471 idmap_path = strchrnul(opt_next, ',');
2e5c468a 2472 len = idmap_path - opt_next + 1;
f6815906 2473
f6815906 2474 if (len >= sizeof(opts->userns_path))
16fcdacc
CB
2475 return syserror_set(-EIO, "Excessive idmap path length for \"idmap=<path>\" LXC specific mount option");
2476
1b82d721 2477 strlcpy(opts->userns_path, opt_next, len);
2e5c468a 2478
16fcdacc
CB
2479 if (is_empty_string(opts->userns_path))
2480 return syserror_set(-EINVAL, "Missing idmap path for \"idmap=<path>\" LXC specific mount option");
2481
1b82d721 2482 if (!strequal(opts->userns_path, "container")) {
4b875ef9
CB
2483 fd_userns = open(opts->userns_path, O_RDONLY | O_NOCTTY | O_CLOEXEC);
2484 if (fd_userns < 0)
1b82d721 2485 return syserror("Failed to open user namespace %s", opts->userns_path);
4b875ef9 2486 }
e26cf563
CB
2487
2488 TRACE("Parse LXC specific mount option %d->\"idmap=%s\"", fd_userns, opts->userns_path);
f6815906 2489 break;
0b932f9d 2490 default:
16fcdacc 2491 return syserror_set(-EINVAL, "Unknown LXC specific mount option");
4e4ca161 2492 }
c5e30de4 2493
d97d9e9f
CB
2494 opt_next = strchr(opt, ',');
2495 if (!opt_next)
2496 *opt = '\0'; /* no more mntopts, so just chop it here */
0b932f9d 2497 else
d97d9e9f 2498 memmove(opt, opt_next + 1, strlen(opt_next + 1) + 1);
4e4ca161 2499 }
16fcdacc
CB
2500
2501 return 0;
4e4ca161
SH
2502}
2503
4d5b72a1 2504static int mount_entry_create_dir_file(const struct mntent *mntent,
749f98d9
CB
2505 const char *path,
2506 const struct lxc_rootfs *rootfs,
0fd73091 2507 const char *lxc_name, const char *lxc_path)
0ad19a3f 2508{
7a76eeaa 2509 __do_free char *p1 = NULL;
3b7e332f 2510 int ret;
7a76eeaa 2511 char *p2;
911324ef 2512
eed95eb0 2513 if (strnequal(mntent->mnt_type, "overlay", 7)) {
749f98d9 2514 ret = ovl_mkdir(mntent, rootfs, lxc_name, lxc_path);
12e6ab5d
CB
2515 if (ret < 0)
2516 return -1;
2517 }
6e46cc0d 2518
34cfffb3 2519 if (hasmntopt(mntent, "create=dir")) {
749f98d9 2520 ret = mkdir_p(path, 0755);
55022530
CB
2521 if (ret < 0 && errno != EEXIST)
2522 return log_error_errno(-1, errno, "Failed to create directory \"%s\"", path);
34cfffb3
SG
2523 }
2524
0fd73091
CB
2525 if (!hasmntopt(mntent, "create=file"))
2526 return 0;
749f98d9 2527
0fd73091
CB
2528 ret = access(path, F_OK);
2529 if (ret == 0)
2530 return 0;
749f98d9 2531
0fd73091
CB
2532 p1 = strdup(path);
2533 if (!p1)
2534 return -1;
749f98d9 2535
0fd73091 2536 p2 = dirname(p1);
749f98d9 2537
0fd73091 2538 ret = mkdir_p(p2, 0755);
55022530
CB
2539 if (ret < 0 && errno != EEXIST)
2540 return log_error_errno(-1, errno, "Failed to create directory \"%s\"", path);
749f98d9 2541
3b7e332f
CB
2542 ret = mknod(path, S_IFREG | 0000, 0);
2543 if (ret < 0 && errno != EEXIST)
2544 return -errno;
0fd73091 2545
749f98d9 2546 return 0;
4d5b72a1
NC
2547}
2548
ec50007f
CB
2549/* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2550 * without a rootfs. */
db4aba38 2551static inline int mount_entry_on_generic(struct mntent *mntent,
d8b712bc
CB
2552 const char *path,
2553 const struct lxc_rootfs *rootfs,
2554 const char *lxc_name,
2555 const char *lxc_path)
4d5b72a1 2556{
fd214f37 2557 __do_free char *mntdata = NULL;
a08bfbe3
CB
2558 unsigned long mntflags = 0, pflags = 0;
2559 char *rootfs_path = NULL;
d8b712bc 2560 int ret;
181437fd 2561 bool dev, optional, relative;
0b932f9d 2562 struct lxc_mount_options opts = {};
d8b712bc
CB
2563
2564 optional = hasmntopt(mntent, "optional") != NULL;
2565 dev = hasmntopt(mntent, "dev") != NULL;
181437fd 2566 relative = hasmntopt(mntent, "relative") != NULL;
d8b712bc 2567
ec50007f
CB
2568 if (rootfs && rootfs->path)
2569 rootfs_path = rootfs->mount;
2570
d8b712bc
CB
2571 ret = mount_entry_create_dir_file(mntent, path, rootfs, lxc_name,
2572 lxc_path);
2573 if (ret < 0) {
2574 if (optional)
2575 return 0;
608e3567 2576
d8b712bc
CB
2577 return -1;
2578 }
16fcdacc 2579
1b82d721 2580 ret = parse_lxc_mount_attrs(&opts, mntent->mnt_opts);
16fcdacc
CB
2581 if (ret < 0)
2582 return ret;
4e4ca161 2583
1b82d721
CB
2584 /*
2585 * Idmapped mount entries will be setup by the parent for us. Note that
2586 * we rely on mount_entry_create_dir_file() above to have already
2587 * created the target path for us. So the parent can just open the
2588 * target and send us the target fd.
2589 */
2590 errno = EOPNOTSUPP;
fa8e75f0 2591 if (!is_empty_string(opts.userns_path))
1b82d721 2592 return systrace_ret(0, "Skipping idmapped mount entry");
fa8e75f0 2593
d840039e
YT
2594 ret = parse_propagationopts(mntent->mnt_opts, &pflags);
2595 if (ret < 0)
2596 return -1;
2597
d94eb390 2598 ret = parse_mntopts_legacy(mntent->mnt_opts, &mntflags, &mntdata);
d8b712bc 2599 if (ret < 0)
a08bfbe3 2600 return ret;
a17b1e65 2601
6e46cc0d 2602 ret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type, mntflags,
d840039e 2603 pflags, mntdata, optional, dev, relative, rootfs_path);
68c152ef 2604
911324ef
DL
2605 return ret;
2606}
2607
8183f09e
CB
2608static inline int mount_entry_on_systemfs(struct lxc_rootfs *rootfs,
2609 struct mntent *mntent)
db4aba38 2610{
1433c9f9
CB
2611 int ret;
2612
2613 /* For containers created without a rootfs all mounts are treated as
07667a6a
CB
2614 * absolute paths starting at / on the host.
2615 */
1433c9f9 2616 if (mntent->mnt_dir[0] != '/')
9bcde680 2617 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/%s", mntent->mnt_dir);
1433c9f9 2618 else
9bcde680
CB
2619 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s", mntent->mnt_dir);
2620 if (ret < 0)
1433c9f9 2621 return -1;
1433c9f9 2622
8183f09e 2623 return mount_entry_on_generic(mntent, rootfs->buf, NULL, NULL, NULL);
db4aba38
NC
2624}
2625
4e4ca161 2626static int mount_entry_on_absolute_rootfs(struct mntent *mntent,
9c0fd29a 2627 struct lxc_rootfs *rootfs,
0a2dddd4
CB
2628 const char *lxc_name,
2629 const char *lxc_path)
911324ef 2630{
bdd2b34c 2631 int offset;
013bd428 2632 char *aux;
67e571de 2633 const char *lxcpath;
bdd2b34c 2634 int ret = 0;
0ad19a3f 2635
593e8478 2636 lxcpath = lxc_global_config_value("lxc.lxcpath");
bdd2b34c 2637 if (!lxcpath)
2a59a681 2638 return -1;
2a59a681 2639
bdd2b34c
CB
2640 /* If rootfs->path is a blockdev path, allow container fstab to use
2641 * <lxcpath>/<name>/rootfs" as the target prefix.
2642 */
9bcde680
CB
2643 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s/rootfs", lxcpath, lxc_name);
2644 if (ret < 0)
80a881b2
SH
2645 goto skipvarlib;
2646
9c0fd29a 2647 aux = strstr(mntent->mnt_dir, rootfs->buf);
80a881b2 2648 if (aux) {
9c0fd29a 2649 offset = strlen(rootfs->buf);
80a881b2
SH
2650 goto skipabs;
2651 }
2652
2653skipvarlib:
013bd428 2654 aux = strstr(mntent->mnt_dir, rootfs->path);
55022530
CB
2655 if (!aux)
2656 return log_warn(ret, "Ignoring mount point \"%s\"", mntent->mnt_dir);
80a881b2
SH
2657 offset = strlen(rootfs->path);
2658
2659skipabs:
9bcde680
CB
2660 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s", rootfs->mount, aux + offset);
2661 if (ret < 0)
a17b1e65 2662 return -1;
a17b1e65 2663
9c0fd29a 2664 return mount_entry_on_generic(mntent, rootfs->buf, rootfs, lxc_name, lxc_path);
911324ef 2665}
d330fe7b 2666
4e4ca161 2667static int mount_entry_on_relative_rootfs(struct mntent *mntent,
4806d3b9 2668 struct lxc_rootfs *rootfs,
0a2dddd4
CB
2669 const char *lxc_name,
2670 const char *lxc_path)
911324ef 2671{
911324ef 2672 int ret;
d330fe7b 2673
34cfffb3 2674 /* relative to root mount point */
9bcde680
CB
2675 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s", rootfs->mount, mntent->mnt_dir);
2676 if (ret < 0)
9ba8130c 2677 return -1;
911324ef 2678
4806d3b9 2679 return mount_entry_on_generic(mntent, rootfs->buf, rootfs, lxc_name, lxc_path);
911324ef
DL
2680}
2681
8183f09e 2682static int mount_file_entries(struct lxc_rootfs *rootfs, FILE *file,
1ae3c19f 2683 const char *lxc_name, const char *lxc_path)
911324ef 2684{
9d03d857 2685 char buf[PATH_MAX];
0fd73091 2686 struct mntent mntent;
e76b8764 2687
aaf901be 2688 while (getmntent_r(file, &mntent, buf, sizeof(buf))) {
9d03d857
CB
2689 int ret;
2690
1ae3c19f 2691 if (!rootfs->path)
8183f09e 2692 ret = mount_entry_on_systemfs(rootfs, &mntent);
1ae3c19f
CB
2693 else if (mntent.mnt_dir[0] != '/')
2694 ret = mount_entry_on_relative_rootfs(&mntent, rootfs,
2695 lxc_name, lxc_path);
2696 else
2697 ret = mount_entry_on_absolute_rootfs(&mntent, rootfs,
9d03d857 2698 lxc_name, lxc_path);
1ae3c19f
CB
2699 if (ret < 0)
2700 return -1;
0ad19a3f 2701 }
cd54d859 2702
55022530
CB
2703 if (!feof(file) || ferror(file))
2704 return log_error(-1, "Failed to parse mount entries");
9d03d857
CB
2705
2706 return 0;
e7938e9e
MN
2707}
2708
55022530
CB
2709static inline void __auto_endmntent__(FILE **f)
2710{
2711 if (*f)
2712 endmntent(*f);
2713}
2714
2715#define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2716
48e5dcc8 2717static int setup_mount_fstab(struct lxc_rootfs *rootfs, const char *fstab,
8183f09e 2718 const char *lxc_name, const char *lxc_path)
e7938e9e 2719{
55022530 2720 __do_endmntent FILE *f = NULL;
e7938e9e
MN
2721 int ret;
2722
2723 if (!fstab)
2724 return 0;
2725
55022530
CB
2726 f = setmntent(fstab, "re");
2727 if (!f)
2728 return log_error_errno(-1, errno, "Failed to open \"%s\"", fstab);
e7938e9e 2729
a7c6e830 2730 ret = mount_file_entries(rootfs, f, lxc_name, lxc_path);
42dff448
CB
2731 if (ret < 0)
2732 ERROR("Failed to set up mount entries");
e7938e9e 2733
0ad19a3f 2734 return ret;
2735}
2736
1800f924
WB
2737/*
2738 * In order for nested containers to be able to mount /proc and /sys they need
2739 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2740 * (like lxcfs).
2741 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2742 * apparmor rule to deny access to them. This is mostly for convenience: The
2743 * container's root user can mount them anyway and thus has access to the two
2744 * file systems. But a non-root user in the container should not be allowed to
2745 * access them as a side effect without explicitly allowing it.
2746 */
2747static const char nesting_helpers[] =
dc691e34
CB
2748"proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2749"sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
1800f924
WB
2750
2751FILE *make_anonymous_mount_file(struct lxc_list *mount,
2752 bool include_nesting_helpers)
e7938e9e 2753{
f62cf1d4 2754 __do_close int fd = -EBADF;
4110345b 2755 FILE *f;
5ef5c9a3 2756 int ret;
e7938e9e 2757 char *mount_entry;
5ef5c9a3 2758 struct lxc_list *iterator;
5ef5c9a3 2759
0fd73091 2760 fd = memfd_create(".lxc_mount_file", MFD_CLOEXEC);
5ef5c9a3 2761 if (fd < 0) {
a324e7eb
CB
2762 char template[] = P_tmpdir "/.lxc_mount_file_XXXXXX";
2763
5ef5c9a3
CB
2764 if (errno != ENOSYS)
2765 return NULL;
a324e7eb
CB
2766
2767 fd = lxc_make_tmpfile(template, true);
55022530
CB
2768 if (fd < 0)
2769 return log_error_errno(NULL, errno, "Could not create temporary mount file");
0fd73091 2770
6bd04140 2771 TRACE("Created temporary mount file");
5ef5c9a3 2772 }
e7938e9e 2773
0fd73091
CB
2774 lxc_list_for_each (iterator, mount) {
2775 size_t len;
2776
e7938e9e 2777 mount_entry = iterator->elem;
0fd73091 2778 len = strlen(mount_entry);
5ef5c9a3 2779
489f39be 2780 ret = lxc_write_nointr(fd, mount_entry, len);
0fd73091 2781 if (ret != len)
79bcf5ee 2782 return NULL;
0fd73091 2783
489f39be 2784 ret = lxc_write_nointr(fd, "\n", 1);
0fd73091 2785 if (ret != 1)
79bcf5ee 2786 return NULL;
e7938e9e
MN
2787 }
2788
1800f924
WB
2789 if (include_nesting_helpers) {
2790 ret = lxc_write_nointr(fd, nesting_helpers,
6333c915
CB
2791 STRARRAYLEN(nesting_helpers));
2792 if (ret != STRARRAYLEN(nesting_helpers))
79bcf5ee 2793 return NULL;
1800f924
WB
2794 }
2795
0fd73091
CB
2796 ret = lseek(fd, 0, SEEK_SET);
2797 if (ret < 0)
79bcf5ee 2798 return NULL;
0fd73091 2799
4110345b
CB
2800 f = fdopen(fd, "re+");
2801 if (f)
2802 move_fd(fd); /* Transfer ownership of fd. */
2803 return f;
9fc7f8c0
TA
2804}
2805
06749971 2806static int setup_mount_entries(const struct lxc_conf *conf,
48e5dcc8
CB
2807 struct lxc_rootfs *rootfs, struct lxc_list *mount,
2808 const char *lxc_name, const char *lxc_path)
9fc7f8c0 2809{
c85ced65 2810 __do_fclose FILE *f = NULL;
9fc7f8c0 2811
1800f924 2812 f = make_anonymous_mount_file(mount, conf->lsm_aa_allow_nesting);
19b5d755 2813 if (!f)
9fc7f8c0 2814 return -1;
e7938e9e 2815
a7c6e830 2816 return mount_file_entries(rootfs, f, lxc_name, lxc_path);
e7938e9e
MN
2817}
2818
1b82d721
CB
2819static int __lxc_idmapped_mounts_child(struct lxc_handler *handler, FILE *f)
2820{
2821 struct lxc_conf *conf = handler->conf;
2822 struct lxc_rootfs *rootfs = &conf->rootfs;
5a782dca 2823 int mnt_seq = 0;
1b82d721
CB
2824 int ret;
2825 char buf[PATH_MAX];
2826 struct mntent mntent;
2827
2828 while (getmntent_r(f, &mntent, buf, sizeof(buf))) {
2829 __do_close int fd_from = -EBADF, fd_to = -EBADF,
2830 fd_userns = -EBADF;
2831 __do_free char *__data = NULL;
5a782dca 2832 int cur_mnt_seq = -1;
1b82d721
CB
2833 struct lxc_mount_options opts = {};
2834 int dfd_from;
2835 const char *source_relative, *target_relative;
2836
2837 ret = parse_lxc_mount_attrs(&opts, mntent.mnt_opts);
2838 if (ret < 0)
2839 return syserror("Failed to parse LXC specific mount options");
2840 __data = opts.data;
2841
2842 ret = parse_mount_attrs(&opts, mntent.mnt_opts);
2843 if (ret < 0)
2844 return syserror("Failed to parse mount options");
2845
2846 /* No idmapped mount entry so skip it. */
2847 if (is_empty_string(opts.userns_path))
2848 continue;
2849
2850 if (!can_use_bind_mounts())
2851 return syserror_set(-EINVAL, "Kernel does not support idmapped mounts");
2852
2853 if (!opts.bind)
2854 return syserror_set(-EINVAL, "Only bind mounts can currently be idmapped");
2855
2856 /* We don't support new filesystem mounts yet. */
2857 if (!is_empty_string(mntent.mnt_type) &&
2858 !strequal(mntent.mnt_type, "none"))
2859 return syserror_set(-EINVAL, "Only bind mounts can currently be idmapped");
2860
2861 /* Someone specified additional mount options for a bind-mount. */
2862 if (!is_empty_string(opts.data))
2863 return syserror_set(-EINVAL, "Bind mounts don't support non-generic mount options");
2864
2865 /*
2866 * The source path is supposed to be taken relative to the
2867 * container's rootfs mount or - if the container does not have
2868 * a separate rootfs - to the host's /.
2869 */
2870 source_relative = deabs(mntent.mnt_fsname);
2871 if (opts.relative || !rootfs->path)
2872 dfd_from = rootfs->dfd_mnt;
2873 else
2874 dfd_from = rootfs->dfd_host;
2875 fd_from = open_tree(dfd_from, source_relative,
2876 OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC |
2877 (opts.recursive ? AT_RECURSIVE : 0));
2878 if (fd_from < 0)
2879 return syserror("Failed to create detached %smount of %d/%s",
2880 opts.recursive ? "recursive " : "",
2881 dfd_from, source_relative);
2882
2883 if (strequal(opts.userns_path, "container"))
2884 fd_userns = openat(dfd_from, "proc/self/ns/user", O_RDONLY | O_CLOEXEC);
2885 else
2886 fd_userns = open_at(-EBADF, opts.userns_path,
2887 PROTECT_OPEN_WITH_TRAILING_SYMLINKS, 0, 0);
2888 if (fd_userns < 0) {
2889 if (opts.optional) {
2890 TRACE("Skipping optional idmapped mount");
2891 continue;
2892 }
2893
2894 return syserror("Failed to open user namespace \"%s\" for detached %smount of %d/%s",
2895 opts.userns_path, opts.recursive ? "recursive " : "",
2896 dfd_from, source_relative);
2897 }
2898
2899 ret = __lxc_abstract_unix_send_two_fds(handler->data_sock[0],
2900 fd_from, fd_userns,
2901 &opts, sizeof(opts));
2902 if (ret <= 0) {
2903 if (opts.optional) {
2904 TRACE("Skipping optional idmapped mount");
2905 continue;
2906 }
2907
2908 return syserror("Failed to send file descriptor %d for detached %smount of %d/%s and file descriptor %d of user namespace \"%s\" to parent",
2909 fd_from, opts.recursive ? "recursive " : "",
2910 dfd_from, source_relative, fd_userns,
2911 opts.userns_path);
2912 }
2913
5a782dca
CB
2914 ret = lxc_abstract_unix_rcv_credential(handler->data_sock[0],
2915 &cur_mnt_seq,
2916 sizeof(cur_mnt_seq));
1b82d721
CB
2917 if (ret <= 0) {
2918 if (opts.optional) {
2919 TRACE("Skipping optional idmapped mount");
2920 continue;
2921 }
2922
2923 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
2924 opts.recursive ? "recursive " : "",
2925 dfd_from, source_relative, fd_userns);
2926 }
2927
5a782dca
CB
2928 if (mnt_seq != cur_mnt_seq)
2929 return syserror("Expected mount sequence number and mount sequence number from parent mismatch: %d != %d",
2930 mnt_seq, cur_mnt_seq);
2931 mnt_seq++;
2932
1b82d721
CB
2933 /* Set remaining mount options. */
2934 ret = mount_setattr(fd_from, "", AT_EMPTY_PATH |
2935 (opts.recursive ? AT_RECURSIVE : 0),
2936 &opts.attr, sizeof(opts.attr));
2937 if (ret < 0) {
2938 if (opts.optional) {
2939 TRACE("Skipping optional idmapped mount");
2940 continue;
2941 }
2942
2943 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
2944 opts.recursive ? "recursive " : "",
2945 dfd_from, source_relative, fd_userns);
2946 }
2947
2948 /*
2949 * In contrast to the legacy mount codepath we will simplify
2950 * our lifes and just always treat the target mountpoint to be
2951 * relative to the container's rootfs mountpoint or - if the
2952 * container does not have a separate rootfs - to the host's /.
2953 */
2954
2955 target_relative = deabs(mntent.mnt_dir);
2956 if (rootfs->path)
2957 dfd_from = rootfs->dfd_mnt;
2958 else
2959 dfd_from = rootfs->dfd_host;
2960 fd_to = open_at(dfd_from, target_relative, PROTECT_OPATH_FILE, PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS, 0);
2961 if (fd_to < 0) {
2962 if (opts.optional) {
2963 TRACE("Skipping optional idmapped mount");
2964 continue;
2965 }
2966
2967 return syserror("Failed to open target mountpoint %d/%s for detached idmapped %smount %d:%d/%s",
2968 dfd_from, target_relative,
2969 opts.recursive ? "recursive " : "",
2970 fd_userns, dfd_from, source_relative);
2971 }
2972
2973 ret = move_detached_mount(fd_from, fd_to, "", 0, 0);
2974 if (ret) {
2975 if (opts.optional) {
2976 TRACE("Skipping optional idmapped mount");
2977 continue;
2978 }
2979
2980 return syserror("Failed to attach detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
2981 opts.recursive ? "recursive " : "",
2982 fd_userns, dfd_from, source_relative, dfd_from, target_relative);
2983 }
2984
2985 TRACE("Attached detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
2986 opts.recursive ? "recursive " : "", fd_userns, dfd_from,
2987 source_relative, dfd_from, target_relative);
2988 }
2989
2990 if (!feof(f) || ferror(f))
2991 return syserror_set(-EINVAL, "Failed to parse mount entries");
2992
2993 return 0;
2994}
2995
2996static int lxc_idmapped_mounts_child(struct lxc_handler *handler)
2997{
2998 __do_fclose FILE *f_entries = NULL;
2999 int fret = -1;
3000 struct lxc_conf *conf = handler->conf;
3001 const char *fstab = conf->fstab;
3002 struct lxc_list *mount = &conf->mount_list;
3003 int ret;
3004
3005 f_entries = make_anonymous_mount_file(mount, conf->lsm_aa_allow_nesting);
3006 if (!f_entries) {
3007 SYSERROR("Failed to create anonymous mount file");
3008 goto out;
3009 }
3010
3011 ret = __lxc_idmapped_mounts_child(handler, f_entries);
3012 if (ret) {
3013 SYSERROR("Failed to setup idmapped mount entries");
3014 goto out;
3015 }
3016
3017 TRACE("Finished setting up idmapped mounts");
3018
3019 if (fstab) {
3020 __do_endmntent FILE *f_fstab = NULL;
3021
3022 f_fstab = setmntent(fstab, "re");
3023 if (!f_fstab) {
3024 SYSERROR("Failed to open fstab format file \"%s\"", fstab);
3025 goto out;
3026 }
3027
3028 ret = __lxc_idmapped_mounts_child(handler, f_fstab);
3029 if (ret) {
3030 SYSERROR("Failed to setup idmapped mount entries specified in fstab");
3031 goto out;
3032 }
3033
3034 TRACE("Finished setting up idmapped mounts specified in fstab");
3035 }
3036
3037 fret = 0;
3038
3039out:
3040 ret = lxc_abstract_unix_send_credential(handler->data_sock[0], NULL, 0);
3041 if (ret < 0)
caaa223b 3042 return syserror("Failed to inform parent that we are done setting up mounts");
1b82d721
CB
3043
3044 return fret;
3045}
3046
bab88e68
CS
3047static int parse_cap(const char *cap)
3048{
84760c11 3049 size_t i;
3050 int capid = -1;
0fd73091
CB
3051 size_t end = sizeof(caps_opt) / sizeof(caps_opt[0]);
3052 char *ptr = NULL;
bab88e68 3053
71528742 3054 if (strequal(cap, "none"))
7035407c
DE
3055 return -2;
3056
8560cd36 3057 for (i = 0; i < end; i++) {
71528742 3058 if (!strequal(cap, caps_opt[i].name))
bab88e68
CS
3059 continue;
3060
3061 capid = caps_opt[i].value;
3062 break;
3063 }
3064
3065 if (capid < 0) {
0fd73091
CB
3066 /* Try to see if it's numeric, so the user may specify
3067 * capabilities that the running kernel knows about but we
3068 * don't
3069 */
bab88e68
CS
3070 errno = 0;
3071 capid = strtol(cap, &ptr, 10);
3072 if (!ptr || *ptr != '\0' || errno != 0)
3073 /* not a valid number */
3074 capid = -1;
3075 else if (capid > lxc_caps_last_cap())
3076 /* we have a number but it's not a valid
3077 * capability */
3078 capid = -1;
3079 }
3080
3081 return capid;
3082}
3083
0769b82a
CS
3084int in_caplist(int cap, struct lxc_list *caps)
3085{
0769b82a 3086 int capid;
0fd73091 3087 struct lxc_list *iterator;
0769b82a 3088
0fd73091 3089 lxc_list_for_each (iterator, caps) {
0769b82a
CS
3090 capid = parse_cap(iterator->elem);
3091 if (capid == cap)
3092 return 1;
3093 }
3094
3095 return 0;
3096}
3097
81810dd1
DL
3098static int setup_caps(struct lxc_list *caps)
3099{
bab88e68 3100 int capid;
0fd73091
CB
3101 char *drop_entry;
3102 struct lxc_list *iterator;
81810dd1 3103
0fd73091
CB
3104 lxc_list_for_each (iterator, caps) {
3105 int ret;
81810dd1
DL
3106
3107 drop_entry = iterator->elem;
3108
bab88e68 3109 capid = parse_cap(drop_entry);
55022530
CB
3110 if (capid < 0)
3111 return log_error(-1, "unknown capability %s", drop_entry);
81810dd1 3112
b81689a1
CB
3113 ret = prctl(PR_CAPBSET_DROP, prctl_arg(capid), prctl_arg(0),
3114 prctl_arg(0), prctl_arg(0));
55022530
CB
3115 if (ret < 0)
3116 return log_error_errno(-1, errno, "Failed to remove %s capability", drop_entry);
0fd73091 3117 DEBUG("Dropped %s (%d) capability", drop_entry, capid);
81810dd1
DL
3118 }
3119
0fd73091 3120 DEBUG("Capabilities have been setup");
1fb86a7c
SH
3121 return 0;
3122}
3123
3124static int dropcaps_except(struct lxc_list *caps)
3125{
2f443e88 3126 __do_free int *caplist = NULL;
0fd73091 3127 int i, capid, numcaps;
1fb86a7c 3128 char *keep_entry;
0fd73091 3129 struct lxc_list *iterator;
1fb86a7c 3130
0fd73091 3131 numcaps = lxc_caps_last_cap() + 1;
2caf9a97
SH
3132 if (numcaps <= 0 || numcaps > 200)
3133 return -1;
0fd73091 3134 TRACE("Found %d capabilities", numcaps);
2caf9a97 3135
1a0e70ac 3136 /* caplist[i] is 1 if we keep capability i */
2f443e88 3137 caplist = must_realloc(NULL, numcaps * sizeof(int));
1fb86a7c
SH
3138 memset(caplist, 0, numcaps * sizeof(int));
3139
0fd73091 3140 lxc_list_for_each (iterator, caps) {
1fb86a7c
SH
3141 keep_entry = iterator->elem;
3142
bab88e68 3143 capid = parse_cap(keep_entry);
7035407c
DE
3144 if (capid == -2)
3145 continue;
3146
55022530
CB
3147 if (capid < 0)
3148 return log_error(-1, "Unknown capability %s", keep_entry);
1fb86a7c 3149
0fd73091 3150 DEBUG("Keep capability %s (%d)", keep_entry, capid);
1fb86a7c
SH
3151 caplist[capid] = 1;
3152 }
0fd73091
CB
3153
3154 for (i = 0; i < numcaps; i++) {
3155 int ret;
3156
1fb86a7c
SH
3157 if (caplist[i])
3158 continue;
0fd73091 3159
b81689a1
CB
3160 ret = prctl(PR_CAPBSET_DROP, prctl_arg(i), prctl_arg(0),
3161 prctl_arg(0), prctl_arg(0));
55022530
CB
3162 if (ret < 0)
3163 return log_error_errno(-1, errno, "Failed to remove capability %d", i);
1fb86a7c
SH
3164 }
3165
0fd73091 3166 DEBUG("Capabilities have been setup");
81810dd1
DL
3167 return 0;
3168}
3169
0fd73091
CB
3170static int parse_resource(const char *res)
3171{
3172 int ret;
c6d09e15
WB
3173 size_t i;
3174 int resid = -1;
3175
0fd73091 3176 for (i = 0; i < sizeof(limit_opt) / sizeof(limit_opt[0]); ++i)
71528742 3177 if (strequal(res, limit_opt[i].name))
c6d09e15 3178 return limit_opt[i].value;
c6d09e15 3179
0fd73091 3180 /* Try to see if it's numeric, so the user may specify
c6d09e15 3181 * resources that the running kernel knows about but
0fd73091
CB
3182 * we don't.
3183 */
3184 ret = lxc_safe_int(res, &resid);
3185 if (ret < 0)
3186 return -1;
3187
3188 return resid;
c6d09e15
WB
3189}
3190
0fd73091
CB
3191int setup_resource_limits(struct lxc_list *limits, pid_t pid)
3192{
3193 int resid;
c6d09e15
WB
3194 struct lxc_list *it;
3195 struct lxc_limit *lim;
c6d09e15 3196
0fd73091 3197 lxc_list_for_each (it, limits) {
c6d09e15
WB
3198 lim = it->elem;
3199
3200 resid = parse_resource(lim->resource);
55022530
CB
3201 if (resid < 0)
3202 return log_error(-1, "Unknown resource %s", lim->resource);
c6d09e15 3203
f48b5fd8 3204#if HAVE_PRLIMIT || HAVE_PRLIMIT64
55022530
CB
3205 if (prlimit(pid, resid, &lim->limit, NULL) != 0)
3206 return log_error_errno(-1, errno, "Failed to set limit %s", lim->resource);
2de12765
CB
3207
3208 TRACE("Setup \"%s\" limit", lim->resource);
f48b5fd8 3209#else
55022530 3210 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim->resource);
f48b5fd8 3211#endif
c6d09e15 3212 }
0fd73091 3213
c6d09e15
WB
3214 return 0;
3215}
3216
7edd0540
L
3217int setup_sysctl_parameters(struct lxc_list *sysctls)
3218{
e6f76452 3219 __do_free char *tmp = NULL;
7edd0540
L
3220 struct lxc_list *it;
3221 struct lxc_sysctl *elem;
0fd73091 3222 int ret = 0;
6b5a54cd 3223 char filename[PATH_MAX] = {0};
7edd0540 3224
0fd73091 3225 lxc_list_for_each (it, sysctls) {
7edd0540
L
3226 elem = it->elem;
3227 tmp = lxc_string_replace(".", "/", elem->key);
55022530
CB
3228 if (!tmp)
3229 return log_error(-1, "Failed to replace key %s", elem->key);
7edd0540 3230
9bcde680
CB
3231 ret = strnprintf(filename, sizeof(filename), "/proc/sys/%s", tmp);
3232 if (ret < 0)
55022530 3233 return log_error(-1, "Error setting up sysctl parameters path");
7edd0540 3234
0fd73091 3235 ret = lxc_write_to_file(filename, elem->value,
7cea5905 3236 strlen(elem->value), false, 0666);
55022530
CB
3237 if (ret < 0)
3238 return log_error_errno(-1, errno, "Failed to setup sysctl parameters %s to %s",
3239 elem->key, elem->value);
7edd0540 3240 }
0fd73091 3241
7edd0540
L
3242 return 0;
3243}
3244
61d7a733
YT
3245int setup_proc_filesystem(struct lxc_list *procs, pid_t pid)
3246{
0c669152 3247 __do_free char *tmp = NULL;
61d7a733
YT
3248 struct lxc_list *it;
3249 struct lxc_proc *elem;
0fd73091 3250 int ret = 0;
6b5a54cd 3251 char filename[PATH_MAX] = {0};
61d7a733 3252
0fd73091 3253 lxc_list_for_each (it, procs) {
61d7a733
YT
3254 elem = it->elem;
3255 tmp = lxc_string_replace(".", "/", elem->filename);
55022530
CB
3256 if (!tmp)
3257 return log_error(-1, "Failed to replace key %s", elem->filename);
61d7a733 3258
9bcde680
CB
3259 ret = strnprintf(filename, sizeof(filename), "/proc/%d/%s", pid, tmp);
3260 if (ret < 0)
55022530 3261 return log_error(-1, "Error setting up proc filesystem path");
61d7a733 3262
0fd73091 3263 ret = lxc_write_to_file(filename, elem->value,
7cea5905 3264 strlen(elem->value), false, 0666);
55022530
CB
3265 if (ret < 0)
3266 return log_error_errno(-1, errno, "Failed to setup proc filesystem %s to %s", elem->filename, elem->value);
61d7a733 3267 }
0fd73091 3268
61d7a733
YT
3269 return 0;
3270}
3271
ae9242c8
SH
3272static char *default_rootfs_mount = LXCROOTFSMOUNT;
3273
7b379ab3 3274struct lxc_conf *lxc_conf_init(void)
089cd8b8 3275{
26ddeedd 3276 int i;
0fd73091 3277 struct lxc_conf *new;
7b379ab3 3278
b8e43ef0 3279 new = zalloc(sizeof(*new));
0fd73091 3280 if (!new)
7b379ab3 3281 return NULL;
7b379ab3 3282
4b73005c 3283 new->loglevel = LXC_LOG_LEVEL_NOTSET;
9c601e1f 3284 new->personality = LXC_ARCH_UNCHANGED;
124fa0a8 3285 new->autodev = 1;
3a784510 3286 new->console.buffer_size = 0;
596a818d
DE
3287 new->console.log_path = NULL;
3288 new->console.log_fd = -1;
861813e5 3289 new->console.log_size = 0;
28a4b0e5 3290 new->console.path = NULL;
63376d7d 3291 new->console.peer = -1;
fb87aa6a 3292 new->console.proxy.busy = -1;
36a94ce8 3293 new->console.proxy.ptx = -1;
41808e20 3294 new->console.proxy.pty = -1;
f3dff080
CB
3295 new->console.ptx = -EBADF;
3296 new->console.pty = -EBADF;
d926c261 3297 new->console.pty_nr = -1;
63376d7d 3298 new->console.name[0] = '\0';
7294a26d 3299 new->devpts_fd = -EBADF;
732375f5 3300 memset(&new->console.ringbuf, 0, sizeof(struct lxc_ringbuf));
d2e30e99 3301 new->maincmd_fd = -1;
258f8051 3302 new->monitor_signal_pdeath = SIGKILL;
76a26f55 3303 new->nbd_idx = -1;
54c30e29 3304 new->rootfs.mount = strdup(default_rootfs_mount);
53f3f048 3305 if (!new->rootfs.mount) {
53f3f048
SH
3306 free(new);
3307 return NULL;
3308 }
6e54330c 3309 new->rootfs.managed = true;
ea57e424 3310 new->rootfs.dfd_mnt = -EBADF;
a5a08920 3311 new->rootfs.dfd_dev = -EBADF;
ea11a215 3312 new->rootfs.dfd_host = -EBADF;
79ff643d 3313 new->rootfs.fd_path_pin = -EBADF;
4b875ef9 3314 new->rootfs.dfd_idmapped = -EBADF;
858377e4 3315 new->logfd = -1;
7b379ab3 3316 lxc_list_init(&new->cgroup);
54860ed0 3317 lxc_list_init(&new->cgroup2);
a134099d
CB
3318 /* Block ("allowlist") all devices by default. */
3319 new->bpf_devices.list_type = LXC_BPF_DEVICE_CGROUP_ALLOWLIST;
3320 lxc_list_init(&(new->bpf_devices).device_item);
7b379ab3
MN
3321 lxc_list_init(&new->network);
3322 lxc_list_init(&new->mount_list);
81810dd1 3323 lxc_list_init(&new->caps);
1fb86a7c 3324 lxc_list_init(&new->keepcaps);
f6d3e3e4 3325 lxc_list_init(&new->id_map);
46ad64ab
CB
3326 new->root_nsuid_map = NULL;
3327 new->root_nsgid_map = NULL;
f979ac15 3328 lxc_list_init(&new->includes);
4184c3e1 3329 lxc_list_init(&new->aliens);
7c661726 3330 lxc_list_init(&new->environment);
c6d09e15 3331 lxc_list_init(&new->limits);
7edd0540 3332 lxc_list_init(&new->sysctls);
61d7a733 3333 lxc_list_init(&new->procs);
44ae0fb6 3334 new->hooks_version = 0;
28d9e29e 3335 for (i = 0; i < NUM_LXC_HOOKS; i++)
26ddeedd 3336 lxc_list_init(&new->hooks[i]);
ee1e7aa0 3337 lxc_list_init(&new->groups);
d39b10eb 3338 lxc_list_init(&new->state_clients);
fe4de9a6 3339 new->lsm_aa_profile = NULL;
1800f924 3340 lxc_list_init(&new->lsm_aa_raw);
fe4de9a6 3341 new->lsm_se_context = NULL;
4fef78bc 3342 new->lsm_se_keyring_context = NULL;
8f818a84 3343 new->keyring_disable_session = false;
952b5031 3344 new->transient_procfs_mnt = false;
7a41e857
LT
3345 new->shmount.path_host = NULL;
3346 new->shmount.path_cont = NULL;
7b379ab3 3347
72bb04e4
PT
3348 /* if running in a new user namespace, init and COMMAND
3349 * default to running as UID/GID 0 when using lxc-execute */
3350 new->init_uid = 0;
3351 new->init_gid = 0;
c71f64cb 3352 memset(&new->init_groups, 0, sizeof(lxc_groups_t));
43654d34 3353 memset(&new->cgroup_meta, 0, sizeof(struct lxc_cgroup));
b074bbf1 3354 memset(&new->ns_share, 0, sizeof(char *) * LXC_NS_MAX);
70fd7fc9 3355 memset(&new->timens, 0, sizeof(struct timens_offsets));
c3e3c21a 3356 seccomp_conf_init(new);
72bb04e4 3357
7b379ab3 3358 return new;
089cd8b8
DL
3359}
3360
344c9d81 3361int write_id_mapping(enum idtype idtype, pid_t pid, const char *buf,
a19b974f 3362 size_t buf_size)
f6d3e3e4 3363{
f62cf1d4 3364 __do_close int fd = -EBADF;
76bcd422 3365 int ret;
6b5a54cd 3366 char path[PATH_MAX];
f6d3e3e4 3367
a19b974f 3368 if (geteuid() != 0 && idtype == ID_TYPE_GID) {
f62cf1d4 3369 __do_close int setgroups_fd = -EBADF;
a19b974f 3370
9bcde680
CB
3371 ret = strnprintf(path, sizeof(path), "/proc/%d/setgroups", pid);
3372 if (ret < 0)
a19b974f 3373 return -E2BIG;
a19b974f 3374
76bcd422 3375 setgroups_fd = open(path, O_WRONLY);
55022530
CB
3376 if (setgroups_fd < 0 && errno != ENOENT)
3377 return log_error_errno(-1, errno, "Failed to open \"%s\"", path);
a19b974f 3378
76bcd422
CB
3379 if (setgroups_fd >= 0) {
3380 ret = lxc_write_nointr(setgroups_fd, "deny\n",
3381 STRLITERALLEN("deny\n"));
55022530
CB
3382 if (ret != STRLITERALLEN("deny\n"))
3383 return log_error_errno(-1, errno, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid);
395b1a3e 3384 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid);
a19b974f 3385 }
a19b974f
CB
3386 }
3387
9bcde680 3388 ret = strnprintf(path, sizeof(path), "/proc/%d/%cid_map", pid,
29053180 3389 idtype == ID_TYPE_UID ? 'u' : 'g');
9bcde680 3390 if (ret < 0)
f6d3e3e4 3391 return -E2BIG;
29053180 3392
55022530
CB
3393 fd = open(path, O_WRONLY | O_CLOEXEC);
3394 if (fd < 0)
3395 return log_error_errno(-1, errno, "Failed to open \"%s\"", path);
29053180 3396
29053180 3397 ret = lxc_write_nointr(fd, buf, buf_size);
55022530
CB
3398 if (ret != buf_size)
3399 return log_error_errno(-1, errno, "Failed to write %cid mapping to \"%s\"",
3400 idtype == ID_TYPE_UID ? 'u' : 'g', path);
29053180
CB
3401
3402 return 0;
f6d3e3e4
SH
3403}
3404
6e50e704
CB
3405/* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
3406 *
3407 * @return 1 if functional binary was found
3408 * @return 0 if binary exists but is lacking privilege
3409 * @return -ENOENT if binary does not exist
3410 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
6e50e704 3411 */
df6a2945
CB
3412static int idmaptool_on_path_and_privileged(const char *binary, cap_value_t cap)
3413{
48411df2 3414 __do_free char *path = NULL;
df6a2945
CB
3415 int ret;
3416 struct stat st;
df6a2945 3417
6e50e704 3418 if (cap != CAP_SETUID && cap != CAP_SETGID)
83cb7362 3419 return ret_errno(EINVAL);
6e50e704 3420
df6a2945
CB
3421 path = on_path(binary, NULL);
3422 if (!path)
83cb7362 3423 return ret_errno(ENOENT);
df6a2945
CB
3424
3425 ret = stat(path, &st);
3275932b 3426 if (ret < 0)
83cb7362 3427 return -errno;
df6a2945
CB
3428
3429 /* Check if the binary is setuid. */
55022530
CB
3430 if (st.st_mode & S_ISUID)
3431 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path);
df6a2945 3432
0fd73091 3433#if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
df6a2945
CB
3434 /* Check if it has the CAP_SETUID capability. */
3435 if ((cap & CAP_SETUID) &&
3436 lxc_file_cap_is_set(path, CAP_SETUID, CAP_EFFECTIVE) &&
55022530
CB
3437 lxc_file_cap_is_set(path, CAP_SETUID, CAP_PERMITTED))
3438 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path);
df6a2945
CB
3439
3440 /* Check if it has the CAP_SETGID capability. */
3441 if ((cap & CAP_SETGID) &&
3442 lxc_file_cap_is_set(path, CAP_SETGID, CAP_EFFECTIVE) &&
55022530
CB
3443 lxc_file_cap_is_set(path, CAP_SETGID, CAP_PERMITTED))
3444 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path);
a864a2e1
CB
3445
3446 return 0;
0fd73091 3447#else
83cb7362
CB
3448 /*
3449 * If we cannot check for file capabilities we need to give the benefit
69924fff
CB
3450 * of the doubt. Otherwise we might fail even though all the necessary
3451 * file capabilities are set.
3452 */
55022530 3453 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
3275932b 3454 return 1;
a864a2e1 3455#endif
df6a2945
CB
3456}
3457
59eac805 3458static int lxc_map_ids_exec_wrapper(void *args)
986ef930
CB
3459{
3460 execl("/bin/sh", "sh", "-c", (char *)args, (char *)NULL);
3461 return -1;
3462}
3463
86c78011
CB
3464static struct id_map *find_mapped_hostid_entry(const struct lxc_list *idmap,
3465 unsigned id, enum idtype idtype);
3466
f6d3e3e4
SH
3467int lxc_map_ids(struct lxc_list *idmap, pid_t pid)
3468{
0fd73091 3469 int fill, left;
986ef930 3470 char u_or_g;
4bc3b759 3471 char *pos;
6b5a54cd 3472 char cmd_output[PATH_MAX];
0fd73091
CB
3473 struct id_map *map;
3474 struct lxc_list *iterator;
3475 enum idtype type;
0fd73091 3476 int ret = 0, gidmap = 0, uidmap = 0;
c6ba8981
CB
3477 char mapbuf[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
3478 INTTYPE_TO_STRLEN(pid_t) + STRLITERALLEN(" ") +
3479 LXC_IDMAPLEN] = {0};
86c78011 3480 bool had_entry = false, maps_host_root = false, use_shadow = false;
c724025c
JC
3481 int hostuid, hostgid;
3482
3483 hostuid = geteuid();
3484 hostgid = getegid();
df6a2945 3485
86c78011
CB
3486 /*
3487 * Check whether caller wants to map host root.
3488 * Due to a security fix newer kernels require CAP_SETFCAP when mapping
3489 * host root into the child userns as you would be able to write fscaps
3490 * that would be valid in the ancestor userns. Mapping host root should
3491 * rarely be the case but LXC is being clever in a bunch of cases.
3492 */
3493 if (find_mapped_hostid_entry(idmap, 0, ID_TYPE_UID))
3494 maps_host_root = true;
3495
df6a2945
CB
3496 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
3497 * ranges, then insist that root also reserve ranges in subuid. This
22038de5
SH
3498 * will protected it by preventing another user from being handed the
3499 * range by shadow.
3500 */
df6a2945 3501 uidmap = idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID);
6e50e704
CB
3502 if (uidmap == -ENOENT)
3503 WARN("newuidmap binary is missing");
3504 else if (!uidmap)
3505 WARN("newuidmap is lacking necessary privileges");
3506
df6a2945 3507 gidmap = idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID);
6e50e704
CB
3508 if (gidmap == -ENOENT)
3509 WARN("newgidmap binary is missing");
3510 else if (!gidmap)
3511 WARN("newgidmap is lacking necessary privileges");
3512
86c78011
CB
3513 if (maps_host_root) {
3514 INFO("Caller maps host root. Writing mapping directly");
3515 } else if (uidmap > 0 && gidmap > 0) {
0fd73091 3516 DEBUG("Functional newuidmap and newgidmap binary found");
4bc3b759 3517 use_shadow = true;
df6a2945 3518 } else {
99d43365
CB
3519 /* In case unprivileged users run application containers via
3520 * execute() or a start*() there are valid cases where they may
3521 * only want to map their own {g,u}id. Let's not block them from
3522 * doing so by requiring geteuid() == 0.
3523 */
3524 DEBUG("No newuidmap and newgidmap binary found. Trying to "
c724025c
JC
3525 "write directly with euid %d", hostuid);
3526 }
3527
3528 /* Check if we really need to use newuidmap and newgidmap.
f48e8071 3529 * If the user is only remapping their own {g,u}id, we don't need it.
c724025c
JC
3530 */
3531 if (use_shadow && lxc_list_len(idmap) == 2) {
3532 use_shadow = false;
3533 lxc_list_for_each(iterator, idmap) {
3534 map = iterator->elem;
3535 if (map->idtype == ID_TYPE_UID && map->range == 1 &&
3536 map->nsid == hostuid && map->hostid == hostuid)
3537 continue;
3538 if (map->idtype == ID_TYPE_GID && map->range == 1 &&
3539 map->nsid == hostgid && map->hostid == hostgid)
3540 continue;
3541 use_shadow = true;
3542 break;
3543 }
0e6e3a41 3544 }
251d0d2a 3545
986ef930
CB
3546 for (type = ID_TYPE_UID, u_or_g = 'u'; type <= ID_TYPE_GID;
3547 type++, u_or_g = 'g') {
3548 pos = mapbuf;
3549
0e6e3a41 3550 if (use_shadow)
986ef930 3551 pos += sprintf(mapbuf, "new%cidmap %d", u_or_g, pid);
4f7521b4 3552
cf3ef16d 3553 lxc_list_for_each(iterator, idmap) {
251d0d2a 3554 map = iterator->elem;
cf3ef16d
SH
3555 if (map->idtype != type)
3556 continue;
3557
4bc3b759
CB
3558 had_entry = true;
3559
986ef930 3560 left = LXC_IDMAPLEN - (pos - mapbuf);
9bcde680 3561 fill = strnprintf(pos, left, "%s%lu %lu %lu%s",
4bc3b759
CB
3562 use_shadow ? " " : "", map->nsid,
3563 map->hostid, map->range,
0e6e3a41 3564 use_shadow ? "" : "\n");
55022530
CB
3565 /*
3566 * The kernel only takes <= 4k for writes to
3567 * /proc/<pid>/{g,u}id_map
3568 */
9bcde680 3569 if (fill <= 0)
55022530 3570 return log_error_errno(-1, errno, "Too many %cid mappings defined", u_or_g);
4bc3b759 3571
cf3ef16d 3572 pos += fill;
251d0d2a 3573 }
cf3ef16d 3574 if (!had_entry)
4f7521b4 3575 continue;
cf3ef16d 3576
d85813cd 3577 /* Try to catch the output of new{g,u}idmap to make debugging
986ef930
CB
3578 * easier.
3579 */
3580 if (use_shadow) {
3581 ret = run_command(cmd_output, sizeof(cmd_output),
3582 lxc_map_ids_exec_wrapper,
3583 (void *)mapbuf);
55022530
CB
3584 if (ret < 0)
3585 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g, cmd_output, mapbuf);
54fbbeb5 3586 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g, mapbuf);
d1838f34 3587 } else {
986ef930 3588 ret = write_id_mapping(type, pid, mapbuf, pos - mapbuf);
55022530
CB
3589 if (ret < 0)
3590 return log_error(-1, "Failed to write mapping: %s", mapbuf);
54fbbeb5 3591 TRACE("Wrote mapping \"%s\"", mapbuf);
d1838f34 3592 }
986ef930
CB
3593
3594 memset(mapbuf, 0, sizeof(mapbuf));
f6d3e3e4 3595 }
251d0d2a 3596
986ef930 3597 return 0;
f6d3e3e4
SH
3598}
3599
234998b4
CB
3600/*
3601 * Return the host uid/gid to which the container root is mapped in val.
0b3a6504 3602 * Return true if id was found, false otherwise.
cf3ef16d 3603 */
234998b4 3604static id_t get_mapped_rootid(const struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 3605{
4160c3a0 3606 unsigned nsid;
0fd73091
CB
3607 struct id_map *map;
3608 struct lxc_list *it;
4160c3a0
CB
3609
3610 if (idtype == ID_TYPE_UID)
3611 nsid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
3612 else
3613 nsid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
cf3ef16d 3614
0fd73091 3615 lxc_list_for_each (it, &conf->id_map) {
cf3ef16d 3616 map = it->elem;
7b50c609 3617 if (map->idtype != idtype)
cf3ef16d 3618 continue;
4160c3a0 3619 if (map->nsid != nsid)
cf3ef16d 3620 continue;
234998b4 3621 return map->hostid;
cf3ef16d 3622 }
4160c3a0 3623
234998b4
CB
3624 if (idtype == ID_TYPE_UID)
3625 return LXC_INVALID_UID;
3626
3627 return LXC_INVALID_GID;
cf3ef16d
SH
3628}
3629
facdf925 3630int mapped_hostid(unsigned id, const struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 3631{
cf3ef16d 3632 struct id_map *map;
0fd73091
CB
3633 struct lxc_list *it;
3634
3635 lxc_list_for_each (it, &conf->id_map) {
cf3ef16d 3636 map = it->elem;
2133f58c 3637 if (map->idtype != idtype)
cf3ef16d 3638 continue;
0fd73091 3639
cf3ef16d 3640 if (id >= map->hostid && id < map->hostid + map->range)
57d116ab 3641 return (id - map->hostid) + map->nsid;
cf3ef16d 3642 }
0fd73091 3643
57d116ab 3644 return -1;
cf3ef16d
SH
3645}
3646
7581a82f 3647int find_unmapped_nsid(const struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 3648{
cf3ef16d 3649 struct id_map *map;
0fd73091 3650 struct lxc_list *it;
2133f58c 3651 unsigned int freeid = 0;
0fd73091 3652
cf3ef16d 3653again:
0fd73091 3654 lxc_list_for_each (it, &conf->id_map) {
cf3ef16d 3655 map = it->elem;
2133f58c 3656 if (map->idtype != idtype)
cf3ef16d 3657 continue;
0fd73091 3658
cf3ef16d
SH
3659 if (freeid >= map->nsid && freeid < map->nsid + map->range) {
3660 freeid = map->nsid + map->range;
3661 goto again;
3662 }
3663 }
0fd73091 3664
cf3ef16d
SH
3665 return freeid;
3666}
3667
e1b9d6af
CB
3668/*
3669 * Mount a proc under @rootfs if proc self points to a pid other than
3670 * my own. This is needed to have a known-good proc mount for setting
3671 * up LSMs both at container startup and attach.
3672 *
e1b9d6af
CB
3673 * NOTE: not to be called from inside the container namespace!
3674 */
952b5031 3675static int lxc_transient_proc(struct lxc_rootfs *rootfs)
e1b9d6af 3676{
952b5031
CB
3677 __do_close int fd_proc = -EBADF;
3678 int link_to_pid, link_len, pid_self, ret;
3679 char link[INTTYPE_TO_STRLEN(pid_t) + 1];
e1b9d6af 3680
ea57e424 3681 link_len = readlinkat(rootfs->dfd_mnt, "proc/self", link, sizeof(link));
952b5031 3682 if (link_len < 0) {
ea57e424 3683 ret = mkdirat(rootfs->dfd_mnt, "proc", 0000);
952b5031 3684 if (ret < 0 && errno != EEXIST)
ea57e424 3685 return log_error_errno(-errno, errno, "Failed to create %d(proc)", rootfs->dfd_mnt);
e1b9d6af 3686
952b5031
CB
3687 goto domount;
3688 } else if (link_len >= sizeof(link)) {
3689 return log_error_errno(-EIO, EIO, "Truncated link target");
e1b9d6af 3690 }
952b5031 3691 link[link_len] = '\0';
e1b9d6af 3692
952b5031
CB
3693 pid_self = lxc_raw_getpid();
3694 INFO("Caller's PID is %d; /proc/self points to %s", pid_self, link);
e1b9d6af 3695
952b5031
CB
3696 ret = lxc_safe_int(link, &link_to_pid);
3697 if (ret)
3698 return log_error_errno(-ret, ret, "Failed to parse %s", link);
e1b9d6af 3699
952b5031
CB
3700 /* Correct procfs is already mounted. */
3701 if (link_to_pid == pid_self)
3702 return log_trace(0, "Correct procfs instance mounted");
e1b9d6af 3703
ea57e424 3704 fd_proc = open_at(rootfs->dfd_mnt, "proc", PROTECT_OPATH_DIRECTORY,
952b5031
CB
3705 PROTECT_LOOKUP_BENEATH_XDEV, 0);
3706 if (fd_proc < 0)
3707 return log_error_errno(-errno, errno, "Failed to open transient procfs mountpoint");
e1b9d6af 3708
9bcde680
CB
3709 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/proc/self/fd/%d", fd_proc);
3710 if (ret < 0)
952b5031 3711 return ret_errno(EIO);
e1b9d6af 3712
952b5031 3713 ret = umount2(rootfs->buf, MNT_DETACH);
e1b9d6af 3714 if (ret < 0)
952b5031 3715 SYSWARN("Failed to umount \"%s\" with MNT_DETACH", rootfs->buf);
e1b9d6af
CB
3716
3717domount:
3718 /* rootfs is NULL */
952b5031
CB
3719 if (!rootfs->path) {
3720 ret = mount("proc", rootfs->buf, "proc", 0, NULL);
3721 } else {
ea57e424 3722 ret = safe_mount_beneath_at(rootfs->dfd_mnt, "none", "proc", "proc", 0, NULL);
952b5031 3723 if (ret < 0) {
9bcde680
CB
3724 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/proc", rootfs->path ? rootfs->mount : "");
3725 if (ret < 0)
952b5031
CB
3726 return ret_errno(EIO);
3727
3728 ret = safe_mount("proc", rootfs->buf, "proc", 0, NULL, rootfs->mount);
3729 }
3730 }
e1b9d6af 3731 if (ret < 0)
952b5031 3732 return log_error_errno(-1, errno, "Failed to mount temporary procfs");
e1b9d6af 3733
952b5031 3734 INFO("Created transient procfs mount");
e1b9d6af
CB
3735 return 1;
3736}
3737
943144d9 3738/* NOTE: Must not be called from inside the container namespace! */
59eac805 3739static int lxc_create_tmp_proc_mount(struct lxc_conf *conf)
5112cd70
SH
3740{
3741 int mounted;
3742
952b5031 3743 mounted = lxc_transient_proc(&conf->rootfs);
5112cd70 3744 if (mounted == -1) {
01958b1f 3745 /* continue only if there is no rootfs */
943144d9 3746 if (conf->rootfs.path)
952b5031 3747 return log_error_errno(-EPERM, EPERM, "Failed to create transient procfs mount");
5112cd70 3748 } else if (mounted == 1) {
952b5031 3749 conf->transient_procfs_mnt = true;
5112cd70 3750 }
943144d9 3751
5112cd70
SH
3752 return 0;
3753}
3754
3755void tmp_proc_unmount(struct lxc_conf *lxc_conf)
3756{
952b5031
CB
3757 if (lxc_conf->transient_procfs_mnt) {
3758 (void)umount2("/proc", MNT_DETACH);
3759 lxc_conf->transient_procfs_mnt = false;
3760 }
5112cd70
SH
3761}
3762
9e61fb1f 3763/* Walk /proc/mounts and change any shared entries to dependent mounts. */
ed41e764 3764static void turn_into_dependent_mounts(const struct lxc_rootfs *rootfs)
e995d7a2 3765{
7969675f 3766 __do_free char *line = NULL;
003be47b 3767 __do_fclose FILE *f = NULL;
f62cf1d4 3768 __do_close int memfd = -EBADF, mntinfo_fd = -EBADF;
e995d7a2 3769 size_t len = 0;
a39fc34b
CB
3770 ssize_t copied;
3771 int ret;
e995d7a2 3772
ed41e764
CB
3773 mntinfo_fd = open_at(rootfs->dfd_host, "proc/self/mountinfo", PROTECT_OPEN,
3774 (PROTECT_LOOKUP_BENEATH_XDEV & ~RESOLVE_NO_SYMLINKS), 0);
fea3b91d 3775 if (mntinfo_fd < 0) {
ed41e764 3776 SYSERROR("Failed to open %d/proc/self/mountinfo", rootfs->dfd_host);
6a49f05e 3777 return;
fea3b91d 3778 }
6a49f05e
CB
3779
3780 memfd = memfd_create(".lxc_mountinfo", MFD_CLOEXEC);
3781 if (memfd < 0) {
3782 char template[] = P_tmpdir "/.lxc_mountinfo_XXXXXX";
3783
3784 if (errno != ENOSYS) {
fea3b91d 3785 SYSERROR("Failed to create temporary in-memory file");
6a49f05e
CB
3786 return;
3787 }
3788
3789 memfd = lxc_make_tmpfile(template, true);
fea3b91d 3790 if (memfd < 0) {
fea3b91d
DJ
3791 WARN("Failed to create temporary file");
3792 return;
3793 }
6a49f05e
CB
3794 }
3795
a39fc34b 3796 copied = fd_to_fd(mntinfo_fd, memfd);
6a49f05e 3797 if (copied < 0) {
fea3b91d 3798 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
6a49f05e
CB
3799 return;
3800 }
6a49f05e 3801
6a49f05e
CB
3802 ret = lseek(memfd, 0, SEEK_SET);
3803 if (ret < 0) {
fea3b91d 3804 SYSERROR("Failed to reset file descriptor offset");
6a49f05e
CB
3805 return;
3806 }
3807
4110345b 3808 f = fdopen(memfd, "re");
e995d7a2 3809 if (!f) {
003be47b 3810 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
e995d7a2
SH
3811 return;
3812 }
3813
003be47b
CB
3814 /*
3815 * After a successful fdopen() memfd will be closed when calling
3816 * fclose(f). Calling close(memfd) afterwards is undefined.
3817 */
3818 move_fd(memfd);
3819
e995d7a2 3820 while (getline(&line, &len, f) != -1) {
0fd73091
CB
3821 char *opts, *target;
3822
e995d7a2
SH
3823 target = get_field(line, 4);
3824 if (!target)
3825 continue;
0fd73091 3826
e995d7a2
SH
3827 opts = get_field(target, 2);
3828 if (!opts)
3829 continue;
0fd73091 3830
e995d7a2
SH
3831 null_endofword(opts);
3832 if (!strstr(opts, "shared"))
3833 continue;
0fd73091 3834
e995d7a2 3835 null_endofword(target);
0fd73091
CB
3836 ret = mount(NULL, target, NULL, MS_SLAVE, NULL);
3837 if (ret < 0) {
9e61fb1f 3838 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
6a49f05e 3839 continue;
e995d7a2
SH
3840 }
3841 }
9e61fb1f 3842 TRACE("Turned all mount table entries into dependent mount");
e995d7a2
SH
3843}
3844
0fd73091
CB
3845/* This does the work of remounting / if it is shared, calling the container
3846 * pre-mount hooks, and mounting the rootfs.
35120d9c 3847 */
8ce1abc2
CB
3848int lxc_setup_rootfs_prepare_root(struct lxc_conf *conf, const char *name,
3849 const char *lxcpath)
0ad19a3f 3850{
0fd73091
CB
3851 int ret;
3852
ea11a215
CB
3853 conf->rootfs.dfd_host = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
3854 if (conf->rootfs.dfd_host < 0)
a370f16b
CB
3855 return log_error_errno(-errno, errno, "Failed to open \"/\"");
3856
ed41e764
CB
3857 turn_into_dependent_mounts(&conf->rootfs);
3858
35120d9c 3859 if (conf->rootfs_setup) {
35120d9c 3860 const char *path = conf->rootfs.mount;
0fd73091 3861
ed41e764
CB
3862 /*
3863 * The rootfs was set up in another namespace. bind-mount it to
0fd73091
CB
3864 * give us a mount in our own ns so we can pivot_root to it
3865 */
3866 ret = mount(path, path, "rootfs", MS_BIND, NULL);
55022530
CB
3867 if (ret < 0)
3868 return log_error(-1, "Failed to bind mount container / onto itself");
0fd73091 3869
ea57e424
CB
3870 conf->rootfs.dfd_mnt = openat(-EBADF, path, O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_PATH | O_NOCTTY);
3871 if (conf->rootfs.dfd_mnt < 0)
26ea5533
CB
3872 return log_error_errno(-errno, errno, "Failed to open file descriptor for container rootfs");
3873
55022530 3874 return log_trace(0, "Bind mounted container / onto itself");
35120d9c 3875 }
d4ef7c50 3876
0fd73091 3877 ret = run_lxc_hooks(name, "pre-mount", conf, NULL);
55022530
CB
3878 if (ret < 0)
3879 return log_error(-1, "Failed to run pre-mount hooks");
35120d9c 3880
4e86cad3 3881 ret = lxc_mount_rootfs(&conf->rootfs);
55022530
CB
3882 if (ret < 0)
3883 return log_error(-1, "Failed to setup rootfs for");
35120d9c
SH
3884
3885 conf->rootfs_setup = true;
3886 return 0;
3887}
3888
1c1c7051
SH
3889static bool verify_start_hooks(struct lxc_conf *conf)
3890{
6b5a54cd 3891 char path[PATH_MAX];
0fd73091
CB
3892 struct lxc_list *it;
3893
3894 lxc_list_for_each (it, &conf->hooks[LXCHOOK_START]) {
1c1c7051 3895 int ret;
0fd73091 3896 char *hookname = it->elem;
1c1c7051 3897
9bcde680 3898 ret = strnprintf(path, sizeof(path), "%s%s",
0fd73091
CB
3899 conf->rootfs.path ? conf->rootfs.mount : "",
3900 hookname);
9bcde680 3901 if (ret < 0)
1c1c7051 3902 return false;
0fd73091 3903
75193660 3904 ret = access(path, X_OK);
55022530
CB
3905 if (ret < 0)
3906 return log_error_errno(false, errno, "Start hook \"%s\" not found in container", hookname);
0fd73091 3907
6a0c909a 3908 return true;
1c1c7051
SH
3909 }
3910
3911 return true;
3912}
3913
20502652
CB
3914static int lxc_setup_boot_id(void)
3915{
3916 int ret;
3917 const char *boot_id_path = "/proc/sys/kernel/random/boot_id";
3918 const char *mock_boot_id_path = "/dev/.lxc-boot-id";
3919 lxc_id128_t n;
3920
3921 if (access(boot_id_path, F_OK))
3922 return 0;
3923
3924 memset(&n, 0, sizeof(n));
3925 if (lxc_id128_randomize(&n)) {
3926 SYSERROR("Failed to generate random data for uuid");
3927 return -1;
3928 }
3929
3930 ret = lxc_id128_write(mock_boot_id_path, n);
3931 if (ret < 0) {
3932 SYSERROR("Failed to write uuid to %s", mock_boot_id_path);
3933 return -1;
3934 }
3935
3936 ret = chmod(mock_boot_id_path, 0444);
3937 if (ret < 0) {
3938 SYSERROR("Failed to chown %s", mock_boot_id_path);
3939 (void)unlink(mock_boot_id_path);
3940 return -1;
3941 }
3942
3943 ret = mount(mock_boot_id_path, boot_id_path, NULL, MS_BIND, NULL);
3944 if (ret < 0) {
3945 SYSERROR("Failed to mount %s to %s", mock_boot_id_path,
3946 boot_id_path);
3947 (void)unlink(mock_boot_id_path);
3948 return -1;
3949 }
3950
3951 ret = mount(NULL, boot_id_path, NULL,
3952 (MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NOEXEC |
3953 MS_NODEV),
3954 NULL);
3955 if (ret < 0) {
3956 SYSERROR("Failed to remount %s read-only", boot_id_path);
3957 (void)unlink(mock_boot_id_path);
3958 return -1;
3959 }
3960
3961 return 0;
3962}
3963
af04d847 3964static int lxc_setup_keyring(struct lsm_ops *lsm_ops, const struct lxc_conf *conf)
d701d729
CB
3965{
3966 key_serial_t keyring;
3967 int ret = 0;
3968
3969 if (conf->lsm_se_keyring_context)
af04d847 3970 ret = lsm_ops->keyring_label_set(lsm_ops, conf->lsm_se_keyring_context);
d701d729 3971 else if (conf->lsm_se_context)
af04d847 3972 ret = lsm_ops->keyring_label_set(lsm_ops, conf->lsm_se_context);
d701d729
CB
3973 if (ret < 0)
3974 return log_error_errno(-1, errno, "Failed to set keyring context");
3975
3976 /*
3977 * Try to allocate a new session keyring for the container to prevent
3978 * information leaks.
3979 */
3980 keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, prctl_arg(0),
3981 prctl_arg(0), prctl_arg(0), prctl_arg(0));
3982 if (keyring < 0) {
3983 switch (errno) {
3984 case ENOSYS:
3985 DEBUG("The keyctl() syscall is not supported or blocked");
3986 break;
3987 case EACCES:
3988 __fallthrough;
3989 case EPERM:
3990 DEBUG("Failed to access kernel keyring. Continuing...");
3991 break;
3992 default:
3993 SYSERROR("Failed to create kernel keyring");
3994 break;
3995 }
3996 }
3997
3998 return ret;
3999}
4000
4b875ef9
CB
4001static int lxc_rootfs_prepare_child(struct lxc_handler *handler)
4002{
4003 struct lxc_rootfs *rootfs = &handler->conf->rootfs;
4004 int dfd_idmapped = -EBADF;
4005 int ret;
4006
4007 if (lxc_list_empty(&handler->conf->id_map))
4008 return 0;
4009
4010 if (is_empty_string(rootfs->mnt_opts.userns_path))
4011 return 0;
4012
4013 if (handler->conf->rootfs_setup)
4014 return 0;
4015
4016 ret = lxc_abstract_unix_recv_one_fd(handler->data_sock[1], &dfd_idmapped, NULL, 0);
4017 if (ret < 0)
4018 return syserror("Failed to receive idmapped mount fd");
4019
4020 rootfs->dfd_idmapped = dfd_idmapped;
4021 TRACE("Received detached idmapped mount %d", rootfs->dfd_idmapped);
4022 return 0;
4023}
4024
1b82d721
CB
4025int lxc_idmapped_mounts_parent(struct lxc_handler *handler)
4026{
5a782dca
CB
4027 int mnt_seq = 0;
4028
1b82d721
CB
4029 for (;;) {
4030 __do_close int fd_from = -EBADF, fd_userns = -EBADF;
4031 struct lxc_mount_attr attr = {};
4032 struct lxc_mount_options opts = {};
4033 ssize_t ret;
4034
4035 ret = __lxc_abstract_unix_recv_two_fds(handler->data_sock[1],
4036 &fd_from, &fd_userns,
4037 &opts, sizeof(opts));
4038 if (ret < 0)
4039 return syserror("Failed to receive idmapped mount file descriptors from child");
4040
4041 if (fd_from < 0 || fd_userns < 0)
4042 return log_trace(0, "Finished receiving idmapped mount file descriptors from child");
4043
4044 attr.attr_set = MOUNT_ATTR_IDMAP;
4045 attr.userns_fd = fd_userns;
4046 ret = mount_setattr(fd_from, "",
4047 AT_EMPTY_PATH |
4048 (opts.recursive ? AT_RECURSIVE : 0),
4049 &attr, sizeof(attr));
4050 if (ret)
4051 return syserror("Failed to idmap detached %smount %d to %d",
4052 opts.recursive ? "recursive " : "",
4053 fd_from, fd_userns);
4054
5a782dca
CB
4055 ret = lxc_abstract_unix_send_credential(handler->data_sock[1],
4056 &mnt_seq,
4057 sizeof(mnt_seq));
1b82d721
CB
4058 if (ret < 0)
4059 return syserror("Parent failed to notify child that detached %smount %d was idmapped to user namespace %d",
4060 opts.recursive ? "recursive " : "",
4061 fd_from, fd_userns);
4062
4063 TRACE("Parent idmapped detached %smount %d to user namespace %d",
4064 opts.recursive ? "recursive " : "", fd_from, fd_userns);
5a782dca 4065 mnt_seq++;
1b82d721
CB
4066 }
4067}
4068
493ae3fe
CB
4069static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
4070{
b35f8f7e 4071 call_cleaner(lxc_delete_tty) struct lxc_tty_info *info_new = &(struct lxc_tty_info){};
493ae3fe
CB
4072 int sock = handler->data_sock[1];
4073 struct lxc_conf *conf = handler->conf;
b35f8f7e
CB
4074 struct lxc_tty_info *tty_info = &conf->ttys;
4075 size_t ttys_max = tty_info->max;
4076 struct lxc_terminal_info *terminal_info;
4077 int ret;
493ae3fe 4078
b35f8f7e 4079 if (!ttys_max)
493ae3fe
CB
4080 return 0;
4081
b35f8f7e
CB
4082 info_new->tty = malloc(sizeof(*(info_new->tty)) * ttys_max);
4083 if (!info_new->tty)
4084 return ret_errno(ENOMEM);
493ae3fe 4085
b35f8f7e
CB
4086 for (int i = 0; i < ttys_max; i++) {
4087 terminal_info = &info_new->tty[i];
4088 terminal_info->busy = -1;
4089 terminal_info->ptx = -EBADF;
4090 terminal_info->pty = -EBADF;
4091 }
493ae3fe 4092
b35f8f7e
CB
4093 for (int i = 0; i < ttys_max; i++) {
4094 int ptx = -EBADF, pty = -EBADF;
4095
4096 ret = lxc_abstract_unix_recv_two_fds(sock, &ptx, &pty);
493ae3fe 4097 if (ret < 0)
b35f8f7e 4098 return syserror("Failed to receive %zu ttys from child", ttys_max);
493ae3fe 4099
b35f8f7e
CB
4100 terminal_info = &info_new->tty[i];
4101 terminal_info->ptx = ptx;
4102 terminal_info->pty = pty;
4103 TRACE("Received pty with ptx fd %d and pty fd %d from child",
4104 terminal_info->ptx, terminal_info->pty);
493ae3fe
CB
4105 }
4106
b35f8f7e
CB
4107 tty_info->tty = move_ptr(info_new->tty);
4108 TRACE("Received %zu ttys from child", ttys_max);
4109 return 0;
493ae3fe
CB
4110}
4111
9f77617b
CB
4112static int lxc_send_console_to_parent(struct lxc_handler *handler)
4113{
4114 struct lxc_terminal *console = &handler->conf->console;
4115 int ret;
4116
4117 if (!wants_console(console))
4118 return 0;
4119
4120 /* We've already allocated a console from the host's devpts instance. */
4121 if (console->pty < 0)
4122 return 0;
4123
4124 ret = __lxc_abstract_unix_send_two_fds(handler->data_sock[0],
4125 console->ptx, console->pty,
4126 console,
4127 sizeof(struct lxc_terminal));
4128 if (ret < 0)
4129 return syserror("Fail to send console to parent");
4130
4131 TRACE("Sent console to parent");
4132 return 0;
4133}
4134
4135static int lxc_recv_console_from_child(struct lxc_handler *handler)
4136{
4137 __do_close int fd_ptx = -EBADF, fd_pty = -EBADF;
4138 struct lxc_terminal *console = &handler->conf->console;
4139 int ret;
4140
4141 if (!wants_console(console))
4142 return 0;
4143
4144 /* We've already allocated a console from the host's devpts instance. */
4145 if (console->pty >= 0)
4146 return 0;
4147
4148 ret = __lxc_abstract_unix_recv_two_fds(handler->data_sock[1],
4149 &fd_ptx, &fd_pty,
4150 console,
4151 sizeof(struct lxc_terminal));
4152 if (ret < 0)
4153 return syserror("Fail to receive console from child");
4154
4155 console->ptx = move_fd(fd_ptx);
4156 console->pty = move_fd(fd_pty);
4157
4158 TRACE("Received console from child");
4159 return 0;
4160}
4161
493ae3fe
CB
4162int lxc_sync_fds_parent(struct lxc_handler *handler)
4163{
4164 int ret;
4165
4166 ret = lxc_seccomp_recv_notifier_fd(&handler->conf->seccomp, handler->data_sock[1]);
4167 if (ret < 0)
4168 return syserror_ret(ret, "Failed to receive seccomp notify fd from child");
4169
42c0d056 4170 ret = lxc_recv_devpts_from_child(handler);
493ae3fe
CB
4171 if (ret < 0)
4172 return syserror_ret(ret, "Failed to receive devpts fd from child");
4173
4174 /* Read tty fds allocated by child. */
4175 ret = lxc_recv_ttys_from_child(handler);
4176 if (ret < 0)
4177 return syserror_ret(ret, "Failed to receive tty info from child process");
4178
4179 if (handler->ns_clone_flags & CLONE_NEWNET) {
4180 ret = lxc_network_recv_name_and_ifindex_from_child(handler);
4181 if (ret < 0)
4182 return syserror_ret(ret, "Failed to receive names and ifindices for network devices from child");
4183 }
4184
9f77617b
CB
4185 ret = lxc_recv_console_from_child(handler);
4186 if (ret < 0)
4187 return syserror_ret(ret, "Failed to receive console from child");
4188
493ae3fe
CB
4189 TRACE("Finished syncing file descriptors with child");
4190 return 0;
4191}
4192
111ed96e
CB
4193int lxc_sync_fds_child(struct lxc_handler *handler)
4194{
4195 int ret;
4196
4197 ret = lxc_seccomp_send_notifier_fd(&handler->conf->seccomp, handler->data_sock[0]);
4198 if (ret < 0)
4199 return syserror_ret(ret, "Failed to send seccomp notify fd to parent");
4200
4201 ret = lxc_send_devpts_to_parent(handler);
4202 if (ret < 0)
4203 return syserror_ret(ret, "Failed to send seccomp devpts fd to parent");
4204
4205 ret = lxc_send_ttys_to_parent(handler);
4206 if (ret < 0)
4207 return syserror_ret(ret, "Failed to send tty file descriptors to parent");
4208
4209 if (handler->ns_clone_flags & CLONE_NEWNET) {
4210 ret = lxc_network_send_name_and_ifindex_to_parent(handler);
4211 if (ret < 0)
4212 return syserror_ret(ret, "Failed to send network device names and ifindices to parent");
4213 }
4214
9f77617b
CB
4215 ret = lxc_send_console_to_parent(handler);
4216 if (ret < 0)
4217 return syserror_ret(ret, "Failed to send console to parent");
4218
111ed96e
CB
4219 TRACE("Finished syncing file descriptors with parent");
4220 return 0;
4221}
4222
3b988b33 4223int lxc_setup(struct lxc_handler *handler)
35120d9c 4224{
2187efd3 4225 int ret;
0fd73091 4226 const char *lxcpath = handler->lxcpath, *name = handler->name;
35120d9c 4227 struct lxc_conf *lxc_conf = handler->conf;
35120d9c 4228
4b875ef9
CB
4229 ret = lxc_rootfs_prepare_child(handler);
4230 if (ret < 0)
4231 return syserror("Failed to prepare rootfs");
4232
8ce1abc2 4233 ret = lxc_setup_rootfs_prepare_root(lxc_conf, name, lxcpath);
55022530
CB
4234 if (ret < 0)
4235 return log_error(-1, "Failed to setup rootfs");
35120d9c 4236
b87ee312 4237 if (handler->nsfd[LXC_NS_UTS] == -EBADF) {
8353b4c9 4238 ret = setup_utsname(lxc_conf->utsname);
55022530
CB
4239 if (ret < 0)
4240 return log_error(-1, "Failed to setup the utsname %s", name);
0ad19a3f 4241 }
4242
8f818a84 4243 if (!lxc_conf->keyring_disable_session) {
d701d729 4244 ret = lxc_setup_keyring(handler->lsm_ops, lxc_conf);
8f818a84 4245 if (ret < 0)
d701d729 4246 return log_error(-1, "Failed to setup container keyring");
8f818a84 4247 }
b25291da 4248
e389f2af 4249 if (handler->ns_clone_flags & CLONE_NEWNET) {
6bc4165d
CB
4250 ret = lxc_network_recv_from_parent(handler);
4251 if (ret < 0)
4252 return log_error(-1, "Failed to receive veth names from parent");
4253
e389f2af
CB
4254 ret = lxc_setup_network_in_child_namespaces(lxc_conf,
4255 &lxc_conf->network);
55022530
CB
4256 if (ret < 0)
4257 return log_error(-1, "Failed to setup network");
790255cf
CB
4258 }
4259
bc6928ff 4260 if (lxc_conf->autodev > 0) {
63012bdd 4261 ret = mount_autodev(name, &lxc_conf->rootfs, lxc_conf->autodevtmpfssize, lxcpath);
55022530
CB
4262 if (ret < 0)
4263 return log_error(-1, "Failed to mount \"/dev\"");
c6883f38
SH
4264 }
4265
8353b4c9
CB
4266 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
4267 * need to wait until other stuff has finished.
368bbc02 4268 */
6d25a524 4269 ret = lxc_mount_auto_mounts(handler, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK);
55022530
CB
4270 if (ret < 0)
4271 return log_error(-1, "Failed to setup first automatic mounts");
368bbc02 4272
48e5dcc8 4273 ret = setup_mount_fstab(&lxc_conf->rootfs, lxc_conf->fstab, name, lxcpath);
55022530
CB
4274 if (ret < 0)
4275 return log_error(-1, "Failed to setup mounts");
576f946d 4276
c631115d
FA
4277 if (!lxc_list_empty(&lxc_conf->mount_list)) {
4278 ret = setup_mount_entries(lxc_conf, &lxc_conf->rootfs,
4279 &lxc_conf->mount_list, name, lxcpath);
55022530
CB
4280 if (ret < 0)
4281 return log_error(-1, "Failed to setup mount entries");
c631115d
FA
4282 }
4283
1b82d721
CB
4284 if (!lxc_sync_wake_parent(handler, START_SYNC_IDMAPPED_MOUNTS))
4285 return -1;
4286
4287 ret = lxc_idmapped_mounts_child(handler);
4288 if (ret)
4289 return syserror("Failed to attached detached idmapped mounts");
4290
1f0a3b6e
CB
4291 lxc_conf->rootfs.dfd_dev = open_at(lxc_conf->rootfs.dfd_mnt, "dev",
4292 PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_BENEATH_XDEV, 0);
4293 if (lxc_conf->rootfs.dfd_dev < 0 && errno != ENOENT)
4294 return log_error_errno(-errno, errno, "Failed to open \"/dev\"");
4295
8353b4c9
CB
4296 /* Now mount only cgroups, if wanted. Before, /sys could not have been
4297 * mounted. It is guaranteed to be mounted now either through
4298 * automatically or via fstab entries.
368bbc02 4299 */
6d25a524 4300 ret = lxc_mount_auto_mounts(handler, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK);
55022530
CB
4301 if (ret < 0)
4302 return log_error(-1, "Failed to setup remaining automatic mounts");
368bbc02 4303
8353b4c9 4304 ret = run_lxc_hooks(name, "mount", lxc_conf, NULL);
55022530
CB
4305 if (ret < 0)
4306 return log_error(-1, "Failed to run mount hooks");
773fb9ca 4307
bc6928ff 4308 if (lxc_conf->autodev > 0) {
8353b4c9 4309 ret = run_lxc_hooks(name, "autodev", lxc_conf, NULL);
55022530
CB
4310 if (ret < 0)
4311 return log_error(-1, "Failed to run autodev hooks");
06749971 4312
8353b4c9 4313 ret = lxc_fill_autodev(&lxc_conf->rootfs);
55022530
CB
4314 if (ret < 0)
4315 return log_error(-1, "Failed to populate \"/dev\"");
91c3830e 4316 }
368bbc02 4317
75193660 4318 /* Make sure any start hooks are in the container */
55022530
CB
4319 if (!verify_start_hooks(lxc_conf))
4320 return log_error(-1, "Failed to verify start hooks");
75193660 4321
cf68ffd9
CB
4322 ret = lxc_create_tmp_proc_mount(lxc_conf);
4323 if (ret < 0)
3dd3fc31 4324 return log_error(-1, "Failed to mount transient procfs instance for LSMs");
cf68ffd9 4325
96a980e1 4326 ret = lxc_setup_devpts_child(handler);
289b707b
CB
4327 if (ret < 0)
4328 return log_error(-1, "Failed to prepare new devpts instance");
4329
f3dff080 4330 ret = lxc_setup_console(handler, &lxc_conf->rootfs, &lxc_conf->console,
37c74fd1 4331 lxc_conf->ttys.dir);
55022530
CB
4332 if (ret < 0)
4333 return log_error(-1, "Failed to setup console");
6e590161 4334
6a2ca1b4
CB
4335 ret = lxc_create_ttys(handler);
4336 if (ret < 0)
4337 return log_error(-1, "Failed to create ttys");
4338
ed8704d0 4339 ret = lxc_setup_dev_symlinks(&lxc_conf->rootfs);
55022530
CB
4340 if (ret < 0)
4341 return log_error(-1, "Failed to setup \"/dev\" symlinks");
69aa6655 4342
8ce1abc2 4343 ret = lxc_setup_rootfs_switch_root(&lxc_conf->rootfs);
55022530
CB
4344 if (ret < 0)
4345 return log_error(-1, "Failed to pivot root into rootfs");
ed502555 4346
20502652
CB
4347 /* Setting the boot-id is best-effort for now. */
4348 if (lxc_conf->autodev > 0)
4349 (void)lxc_setup_boot_id();
4350
8353b4c9 4351 ret = setup_personality(lxc_conf->personality);
55022530 4352 if (ret < 0)
9c601e1f 4353 return syserror("Failed to set personality");
cccc74b5 4354
8353b4c9
CB
4355 /* Set sysctl value to a path under /proc/sys as determined from the
4356 * key. For e.g. net.ipv4.ip_forward translated to
4357 * /proc/sys/net/ipv4/ip_forward.
7edd0540
L
4358 */
4359 if (!lxc_list_empty(&lxc_conf->sysctls)) {
4360 ret = setup_sysctl_parameters(&lxc_conf->sysctls);
55022530
CB
4361 if (ret < 0)
4362 return log_error(-1, "Failed to setup sysctl parameters");
7edd0540
L
4363 }
4364
97a8f74f 4365 if (!lxc_list_empty(&lxc_conf->keepcaps)) {
55022530
CB
4366 if (!lxc_list_empty(&lxc_conf->caps))
4367 return log_error(-1, "Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both");
8353b4c9 4368
55022530
CB
4369 if (dropcaps_except(&lxc_conf->keepcaps))
4370 return log_error(-1, "Failed to keep capabilities");
97a8f74f 4371 } else if (setup_caps(&lxc_conf->caps)) {
55022530 4372 return log_error(-1, "Failed to drop capabilities");
81810dd1
DL
4373 }
4374
79ff643d 4375 put_lxc_rootfs(&handler->conf->rootfs, true);
8353b4c9 4376 NOTICE("The container \"%s\" is set up", name);
cd54d859 4377
0ad19a3f 4378 return 0;
4379}
26ddeedd 4380
3f60c2f7 4381int run_lxc_hooks(const char *name, char *hookname, struct lxc_conf *conf,
14a7b0f9 4382 char *argv[])
26ddeedd 4383{
26ddeedd 4384 struct lxc_list *it;
3ea957c6
RK
4385 int which;
4386
4387 for (which = 0; which < NUM_LXC_HOOKS; which ++) {
71528742 4388 if (strequal(hookname, lxchook_names[which]))
3ea957c6
RK
4389 break;
4390 }
4391
4392 if (which >= NUM_LXC_HOOKS)
26ddeedd 4393 return -1;
3f60c2f7 4394
0fd73091 4395 lxc_list_for_each (it, &conf->hooks[which]) {
26ddeedd 4396 int ret;
3f60c2f7
CB
4397 char *hook = it->elem;
4398
4399 ret = run_script_argv(name, conf->hooks_version, "lxc", hook,
14a7b0f9 4400 hookname, argv);
3f60c2f7
CB
4401 if (ret < 0)
4402 return -1;
26ddeedd 4403 }
3f60c2f7 4404
26ddeedd
SH
4405 return 0;
4406}
72d0e1cb 4407
72d0e1cb
SG
4408int lxc_clear_config_caps(struct lxc_conf *c)
4409{
1a0e70ac 4410 struct lxc_list *it, *next;
72d0e1cb 4411
0fd73091 4412 lxc_list_for_each_safe (it, &c->caps, next) {
72d0e1cb
SG
4413 lxc_list_del(it);
4414 free(it->elem);
4415 free(it);
4416 }
0fd73091 4417
cc36133d 4418 lxc_list_init(&c->caps);
72d0e1cb
SG
4419 return 0;
4420}
4421
c7e345ae
CB
4422static int lxc_free_idmap(struct lxc_list *id_map)
4423{
27c27d73
SH
4424 struct lxc_list *it, *next;
4425
46bc6f2a 4426 lxc_list_for_each_safe(it, id_map, next) {
27c27d73
SH
4427 lxc_list_del(it);
4428 free(it->elem);
4429 free(it);
4430 }
c7e345ae 4431
cc36133d 4432 lxc_list_init(id_map);
27c27d73
SH
4433 return 0;
4434}
7e621263
CB
4435
4436static int __lxc_free_idmap(struct lxc_list *id_map)
4437{
4438 lxc_free_idmap(id_map);
4439 free(id_map);
4440 return 0;
4441}
4442define_cleanup_function(struct lxc_list *, __lxc_free_idmap);
27c27d73 4443
4355ab5f
SH
4444int lxc_clear_idmaps(struct lxc_conf *c)
4445{
4446 return lxc_free_idmap(&c->id_map);
4447}
4448
1fb86a7c
SH
4449int lxc_clear_config_keepcaps(struct lxc_conf *c)
4450{
0fd73091 4451 struct lxc_list *it, *next;
1fb86a7c 4452
0fd73091 4453 lxc_list_for_each_safe (it, &c->keepcaps, next) {
1fb86a7c
SH
4454 lxc_list_del(it);
4455 free(it->elem);
4456 free(it);
4457 }
0fd73091 4458
cc36133d 4459 lxc_list_init(&c->keepcaps);
1fb86a7c
SH
4460 return 0;
4461}
4462
a3ed9b81 4463int lxc_clear_namespace(struct lxc_conf *c)
4464{
ced5587c
CB
4465 for (int i = 0; i < LXC_NS_MAX; i++)
4466 free_disarm(c->ns_share[i]);
4467
a3ed9b81 4468 return 0;
4469}
4470
54860ed0 4471int lxc_clear_cgroups(struct lxc_conf *c, const char *key, int version)
72d0e1cb 4472{
54860ed0 4473 char *global_token, *namespaced_token;
ab1a6cac 4474 size_t namespaced_token_len;
54860ed0 4475 struct lxc_list *it, *next, *list;
ab1a6cac 4476 const char *k = key;
54860ed0 4477 bool all = false;
72d0e1cb 4478
54860ed0 4479 if (version == CGROUP2_SUPER_MAGIC) {
d6c06927
CB
4480 global_token = "lxc.cgroup2";
4481 namespaced_token = "lxc.cgroup2.";
4482 namespaced_token_len = STRLITERALLEN("lxc.cgroup2.");
54860ed0
CB
4483 list = &c->cgroup2;
4484 } else if (version == CGROUP_SUPER_MAGIC) {
d6c06927
CB
4485 global_token = "lxc.cgroup";
4486 namespaced_token = "lxc.cgroup.";
4487 namespaced_token_len = STRLITERALLEN("lxc.cgroup.");
54860ed0
CB
4488 list = &c->cgroup;
4489 } else {
d6c06927 4490 return ret_errno(EINVAL);
54860ed0
CB
4491 }
4492
71528742 4493 if (strequal(key, global_token))
72d0e1cb 4494 all = true;
eed95eb0 4495 else if (strnequal(key, namespaced_token, namespaced_token_len))
ab1a6cac 4496 k += namespaced_token_len;
a6390f01 4497 else
d6c06927 4498 return ret_errno(EINVAL);
72d0e1cb 4499
ced5587c 4500 lxc_list_for_each_safe(it, list, next) {
72d0e1cb 4501 struct lxc_cgroup *cg = it->elem;
54860ed0 4502
71528742 4503 if (!all && !strequal(cg->subsystem, k))
72d0e1cb 4504 continue;
54860ed0 4505
72d0e1cb
SG
4506 lxc_list_del(it);
4507 free(cg->subsystem);
4508 free(cg->value);
4509 free(cg);
4510 free(it);
4511 }
e409b214 4512
cc36133d
CB
4513 if (all)
4514 lxc_list_init(list);
4515
72d0e1cb
SG
4516 return 0;
4517}
4518
a7744f12 4519static inline void lxc_clear_cgroups_devices(struct lxc_conf *conf)
4bfb655e 4520{
a7744f12 4521 lxc_clear_cgroup2_devices(&conf->bpf_devices);
4bfb655e
CB
4522}
4523
c6d09e15
WB
4524int lxc_clear_limits(struct lxc_conf *c, const char *key)
4525{
4526 struct lxc_list *it, *next;
c6d09e15 4527 const char *k = NULL;
0fd73091 4528 bool all = false;
c6d09e15 4529
71528742 4530 if (strequal(key, "lxc.limit") || strequal(key, "lxc.prlimit"))
c6d09e15 4531 all = true;
eed95eb0 4532 else if (strnequal(key, "lxc.limit.", STRLITERALLEN("lxc.limit.")))
6333c915 4533 k = key + STRLITERALLEN("lxc.limit.");
eed95eb0 4534 else if (strnequal(key, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")))
6333c915 4535 k = key + STRLITERALLEN("lxc.prlimit.");
c6d09e15 4536 else
786467cb 4537 return ret_errno(EINVAL);
c6d09e15 4538
0fd73091 4539 lxc_list_for_each_safe (it, &c->limits, next) {
c6d09e15 4540 struct lxc_limit *lim = it->elem;
0fd73091 4541
71528742 4542 if (!all && !strequal(lim->resource, k))
c6d09e15 4543 continue;
0fd73091 4544
c6d09e15 4545 lxc_list_del(it);
786467cb
CB
4546
4547 free_disarm(lim->resource);
c6d09e15 4548 free(lim);
59bc24cd 4549 free(it);
c6d09e15 4550 }
b668653c 4551
786467cb
CB
4552 if (all)
4553 lxc_list_init(&c->limits);
4554
c6d09e15
WB
4555 return 0;
4556}
4557
7edd0540
L
4558int lxc_clear_sysctls(struct lxc_conf *c, const char *key)
4559{
4560 struct lxc_list *it, *next;
7edd0540 4561 const char *k = NULL;
0fd73091 4562 bool all = false;
7edd0540 4563
71528742 4564 if (strequal(key, "lxc.sysctl"))
7edd0540 4565 all = true;
eed95eb0 4566 else if (strnequal(key, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")))
6333c915 4567 k = key + STRLITERALLEN("lxc.sysctl.");
7edd0540
L
4568 else
4569 return -1;
4570
4a2c9b40 4571 lxc_list_for_each_safe(it, &c->sysctls, next) {
7edd0540 4572 struct lxc_sysctl *elem = it->elem;
0fd73091 4573
71528742 4574 if (!all && !strequal(elem->key, k))
7edd0540 4575 continue;
0fd73091 4576
7edd0540
L
4577 lxc_list_del(it);
4578 free(elem->key);
4579 free(elem->value);
4580 free(elem);
4581 free(it);
4582 }
0fd73091 4583
4a2c9b40
CB
4584 if (all)
4585 lxc_list_init(&c->sysctls);
4586
7edd0540
L
4587 return 0;
4588}
4589
61d7a733
YT
4590int lxc_clear_procs(struct lxc_conf *c, const char *key)
4591{
0fd73091 4592 struct lxc_list *it, *next;
61d7a733 4593 const char *k = NULL;
0fd73091 4594 bool all = false;
61d7a733 4595
71528742 4596 if (strequal(key, "lxc.proc"))
61d7a733 4597 all = true;
eed95eb0 4598 else if (strnequal(key, "lxc.proc.", STRLITERALLEN("lxc.proc.")))
6333c915 4599 k = key + STRLITERALLEN("lxc.proc.");
61d7a733
YT
4600 else
4601 return -1;
4602
ced5587c 4603 lxc_list_for_each_safe(it, &c->procs, next) {
61d7a733 4604 struct lxc_proc *proc = it->elem;
0fd73091 4605
71528742 4606 if (!all && !strequal(proc->filename, k))
61d7a733 4607 continue;
0fd73091 4608
61d7a733
YT
4609 lxc_list_del(it);
4610 free(proc->filename);
4611 free(proc->value);
4612 free(proc);
4613 free(it);
4614 }
4615
cc36133d
CB
4616 if (all)
4617 lxc_list_init(&c->procs);
4618
61d7a733
YT
4619 return 0;
4620}
4621
ee1e7aa0
SG
4622int lxc_clear_groups(struct lxc_conf *c)
4623{
0fd73091 4624 struct lxc_list *it, *next;
ee1e7aa0 4625
0fd73091 4626 lxc_list_for_each_safe (it, &c->groups, next) {
ee1e7aa0
SG
4627 lxc_list_del(it);
4628 free(it->elem);
4629 free(it);
4630 }
0fd73091 4631
cc36133d 4632 lxc_list_init(&c->groups);
ee1e7aa0
SG
4633 return 0;
4634}
4635
ab799c0b
SG
4636int lxc_clear_environment(struct lxc_conf *c)
4637{
0fd73091 4638 struct lxc_list *it, *next;
ab799c0b 4639
0fd73091 4640 lxc_list_for_each_safe (it, &c->environment, next) {
ab799c0b
SG
4641 lxc_list_del(it);
4642 free(it->elem);
4643 free(it);
4644 }
0fd73091 4645
cc36133d 4646 lxc_list_init(&c->environment);
ab799c0b
SG
4647 return 0;
4648}
4649
72d0e1cb
SG
4650int lxc_clear_mount_entries(struct lxc_conf *c)
4651{
0fd73091 4652 struct lxc_list *it, *next;
72d0e1cb 4653
0fd73091 4654 lxc_list_for_each_safe (it, &c->mount_list, next) {
72d0e1cb
SG
4655 lxc_list_del(it);
4656 free(it->elem);
4657 free(it);
4658 }
0fd73091 4659
cc36133d 4660 lxc_list_init(&c->mount_list);
72d0e1cb
SG
4661 return 0;
4662}
4663
b099e9e9
SH
4664int lxc_clear_automounts(struct lxc_conf *c)
4665{
4666 c->auto_mounts = 0;
4667 return 0;
4668}
4669
12a50cc6 4670int lxc_clear_hooks(struct lxc_conf *c, const char *key)
72d0e1cb 4671{
0fd73091
CB
4672 struct lxc_list *it, *next;
4673 const char *k = NULL;
4674 bool all = false, done = false;
72d0e1cb 4675
71528742 4676 if (strequal(key, "lxc.hook"))
17ed13a3 4677 all = true;
eed95eb0 4678 else if (strnequal(key, "lxc.hook.", STRLITERALLEN("lxc.hook.")))
6333c915 4679 k = key + STRLITERALLEN("lxc.hook.");
a6390f01
WB
4680 else
4681 return -1;
17ed13a3 4682
ced5587c 4683 for (int i = 0; i < NUM_LXC_HOOKS; i++) {
71528742 4684 if (all || strequal(k, lxchook_names[i])) {
0fd73091 4685 lxc_list_for_each_safe (it, &c->hooks[i], next) {
17ed13a3
SH
4686 lxc_list_del(it);
4687 free(it->elem);
4688 free(it);
4689 }
cc36133d 4690 lxc_list_init(&c->hooks[i]);
0fd73091 4691
17ed13a3 4692 done = true;
72d0e1cb
SG
4693 }
4694 }
17ed13a3 4695
55022530
CB
4696 if (!done)
4697 return log_error(-1, "Invalid hook key: %s", key);
0fd73091 4698
72d0e1cb
SG
4699 return 0;
4700}
8eb5694b 4701
4184c3e1
SH
4702static inline void lxc_clear_aliens(struct lxc_conf *conf)
4703{
0fd73091 4704 struct lxc_list *it, *next;
4184c3e1 4705
0fd73091 4706 lxc_list_for_each_safe (it, &conf->aliens, next) {
4184c3e1
SH
4707 lxc_list_del(it);
4708 free(it->elem);
4709 free(it);
4710 }
cc36133d
CB
4711
4712 lxc_list_init(&conf->aliens);
4184c3e1
SH
4713}
4714
c7b15d1e 4715void lxc_clear_includes(struct lxc_conf *conf)
f979ac15 4716{
0fd73091 4717 struct lxc_list *it, *next;
f979ac15 4718
ced5587c 4719 lxc_list_for_each_safe(it, &conf->includes, next) {
f979ac15
SH
4720 lxc_list_del(it);
4721 free(it->elem);
4722 free(it);
4723 }
cc36133d
CB
4724
4725 lxc_list_init(&conf->includes);
f979ac15
SH
4726}
4727
1800f924
WB
4728int lxc_clear_apparmor_raw(struct lxc_conf *c)
4729{
4730 struct lxc_list *it, *next;
4731
4732 lxc_list_for_each_safe (it, &c->lsm_aa_raw, next) {
4733 lxc_list_del(it);
4734 free(it->elem);
4735 free(it);
4736 }
4737
cc36133d 4738 lxc_list_init(&c->lsm_aa_raw);
1800f924
WB
4739 return 0;
4740}
4741
8eb5694b
SH
4742void lxc_conf_free(struct lxc_conf *conf)
4743{
4744 if (!conf)
4745 return;
0fd73091 4746
858377e4
SH
4747 if (current_config == conf)
4748 current_config = NULL;
aed105d5 4749 lxc_terminal_conf_free(&conf->console);
f10fad2f 4750 free(conf->rootfs.mount);
b3b8c97f 4751 free(conf->rootfs.bdev_type);
f10fad2f
ME
4752 free(conf->rootfs.options);
4753 free(conf->rootfs.path);
79ff643d 4754 put_lxc_rootfs(&conf->rootfs, true);
f10fad2f 4755 free(conf->logfile);
858377e4
SH
4756 if (conf->logfd != -1)
4757 close(conf->logfd);
f10fad2f 4758 free(conf->utsname);
885766f5
CB
4759 free(conf->ttys.dir);
4760 free(conf->ttys.tty_names);
f10fad2f
ME
4761 free(conf->fstab);
4762 free(conf->rcfile);
5cda27c1 4763 free(conf->execute_cmd);
f10fad2f 4764 free(conf->init_cmd);
bf31b337 4765 free(conf->init_groups.list);
3c491553 4766 free(conf->init_cwd);
6b0d5538 4767 free(conf->unexpanded_config);
76d0127f 4768 free(conf->syslog);
c302b476 4769 lxc_free_networks(&conf->network);
f10fad2f 4770 free(conf->lsm_aa_profile);
1800f924 4771 free(conf->lsm_aa_profile_computed);
f10fad2f 4772 free(conf->lsm_se_context);
1ed59e6d 4773 free(conf->lsm_se_keyring_context);
c3e3c21a 4774 lxc_seccomp_free(&conf->seccomp);
8eb5694b 4775 lxc_clear_config_caps(conf);
1fb86a7c 4776 lxc_clear_config_keepcaps(conf);
54860ed0
CB
4777 lxc_clear_cgroups(conf, "lxc.cgroup", CGROUP_SUPER_MAGIC);
4778 lxc_clear_cgroups(conf, "lxc.cgroup2", CGROUP2_SUPER_MAGIC);
a7744f12 4779 lxc_clear_cgroups_devices(conf);
17ed13a3 4780 lxc_clear_hooks(conf, "lxc.hook");
8eb5694b 4781 lxc_clear_mount_entries(conf);
27c27d73 4782 lxc_clear_idmaps(conf);
ee1e7aa0 4783 lxc_clear_groups(conf);
f979ac15 4784 lxc_clear_includes(conf);
761d81ca 4785 lxc_clear_aliens(conf);
ab799c0b 4786 lxc_clear_environment(conf);
240d4b74 4787 lxc_clear_limits(conf, "lxc.prlimit");
7edd0540 4788 lxc_clear_sysctls(conf, "lxc.sysctl");
61d7a733 4789 lxc_clear_procs(conf, "lxc.proc");
1800f924 4790 lxc_clear_apparmor_raw(conf);
a3ed9b81 4791 lxc_clear_namespace(conf);
43654d34 4792 free(conf->cgroup_meta.dir);
a900cbaf 4793 free(conf->cgroup_meta.monitor_dir);
eb60b564 4794 free(conf->cgroup_meta.monitor_pivot_dir);
a900cbaf
WB
4795 free(conf->cgroup_meta.container_dir);
4796 free(conf->cgroup_meta.namespace_dir);
43654d34 4797 free(conf->cgroup_meta.controllers);
7a41e857
LT
4798 free(conf->shmount.path_host);
4799 free(conf->shmount.path_cont);
8eb5694b
SH
4800 free(conf);
4801}
4355ab5f
SH
4802
4803struct userns_fn_data {
4804 int (*fn)(void *);
c9b7c33e 4805 const char *fn_name;
4355ab5f
SH
4806 void *arg;
4807 int p[2];
4808};
4809
4810static int run_userns_fn(void *data)
4811{
766c5b6d 4812 struct userns_fn_data *d = data;
adaffdd7 4813 int ret;
4355ab5f 4814 char c;
4355ab5f 4815
766c5b6d 4816 close_prot_errno_disarm(d->p[1]);
f8aa4bf3 4817
766c5b6d
CB
4818 /*
4819 * Wait for parent to finish establishing a new mapping in the user
f8aa4bf3
CB
4820 * namespace we are executing in.
4821 */
adaffdd7 4822 ret = lxc_read_nointr(d->p[0], &c, 1);
766c5b6d 4823 close_prot_errno_disarm(d->p[0]);
adaffdd7
CB
4824 if (ret != 1)
4825 return -1;
f8aa4bf3 4826
c9b7c33e 4827 if (d->fn_name)
adaffdd7 4828 TRACE("Calling function \"%s\"", d->fn_name);
0fd73091 4829
f8aa4bf3 4830 /* Call function to run. */
4355ab5f
SH
4831 return d->fn(d->arg);
4832}
4833
7581a82f 4834static struct id_map *mapped_nsid_add(const struct lxc_conf *conf, unsigned id,
db7cfe23
CB
4835 enum idtype idtype)
4836{
5173b710
CB
4837 const struct id_map *map;
4838 struct id_map *retmap;
db7cfe23
CB
4839
4840 map = find_mapped_nsid_entry(conf, id, idtype);
4841 if (!map)
4842 return NULL;
4843
b8e43ef0 4844 retmap = zalloc(sizeof(*retmap));
db7cfe23
CB
4845 if (!retmap)
4846 return NULL;
4847
4848 memcpy(retmap, map, sizeof(*retmap));
4849 return retmap;
4850}
4851
86c78011 4852static struct id_map *find_mapped_hostid_entry(const struct lxc_list *idmap,
c4333195 4853 unsigned id, enum idtype idtype)
f8aa4bf3 4854{
f8aa4bf3 4855 struct id_map *map;
0fd73091 4856 struct lxc_list *it;
f8aa4bf3
CB
4857 struct id_map *retmap = NULL;
4858
86c78011 4859 lxc_list_for_each (it, idmap) {
f8aa4bf3
CB
4860 map = it->elem;
4861 if (map->idtype != idtype)
4862 continue;
4863
4864 if (id >= map->hostid && id < map->hostid + map->range) {
4865 retmap = map;
4866 break;
4867 }
4868 }
4869
f8aa4bf3
CB
4870 return retmap;
4871}
4872
0fd73091 4873/* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
f8aa4bf3 4874 * existing one or establish a new one.
4355ab5f 4875 */
7581a82f 4876static struct id_map *mapped_hostid_add(const struct lxc_conf *conf, uid_t id,
0fd73091 4877 enum idtype type)
4355ab5f 4878{
55022530 4879 __do_free struct id_map *entry = NULL;
28a2d9e7 4880 int hostid_mapped;
55022530 4881 struct id_map *tmp = NULL;
c4333195 4882
b8e43ef0 4883 entry = zalloc(sizeof(*entry));
c4333195
CB
4884 if (!entry)
4885 return NULL;
f8aa4bf3 4886
28a2d9e7 4887 /* Reuse existing mapping. */
86c78011 4888 tmp = find_mapped_hostid_entry(&conf->id_map, id, type);
1758c195
CB
4889 if (tmp) {
4890 memcpy(entry, tmp, sizeof(*entry));
4891 } else {
4892 /* Find new mapping. */
4893 hostid_mapped = find_unmapped_nsid(conf, type);
4894 if (hostid_mapped < 0)
4895 return log_debug(NULL, "Failed to find free mapping for id %d", id);
4896
4897 entry->idtype = type;
4898 entry->nsid = hostid_mapped;
4899 entry->hostid = (unsigned long)id;
4900 entry->range = 1;
4901 }
4355ab5f 4902
55022530 4903 return move_ptr(entry);
4355ab5f
SH
4904}
4905
dbfcdf86
CB
4906static struct lxc_list *get_minimal_idmap(const struct lxc_conf *conf,
4907 uid_t *resuid, gid_t *resgid)
4355ab5f 4908{
00d6cfe2
CB
4909 __do_free struct id_map *container_root_uid = NULL,
4910 *container_root_gid = NULL,
4911 *host_uid_map = NULL, *host_gid_map = NULL;
4912 __do_free struct lxc_list *idmap = NULL;
f8aa4bf3 4913 uid_t euid, egid;
4160c3a0
CB
4914 uid_t nsuid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
4915 gid_t nsgid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
00d6cfe2 4916 struct lxc_list *tmplist = NULL;
4355ab5f 4917
db7cfe23 4918 /* Find container root mappings. */
4160c3a0 4919 container_root_uid = mapped_nsid_add(conf, nsuid, ID_TYPE_UID);
55022530
CB
4920 if (!container_root_uid)
4921 return log_debug(NULL, "Failed to find mapping for namespace uid %d", 0);
dcf0ffdf
CB
4922 euid = geteuid();
4923 if (euid >= container_root_uid->hostid &&
4924 euid < (container_root_uid->hostid + container_root_uid->range))
2c996219 4925 host_uid_map = move_ptr(container_root_uid);
f8aa4bf3 4926
4160c3a0 4927 container_root_gid = mapped_nsid_add(conf, nsgid, ID_TYPE_GID);
55022530
CB
4928 if (!container_root_gid)
4929 return log_debug(NULL, "Failed to find mapping for namespace gid %d", 0);
dcf0ffdf
CB
4930 egid = getegid();
4931 if (egid >= container_root_gid->hostid &&
4932 egid < (container_root_gid->hostid + container_root_gid->range))
2c996219 4933 host_gid_map = move_ptr(container_root_gid);
f8aa4bf3
CB
4934
4935 /* Check whether the {g,u}id of the user has a mapping. */
954b7d9b 4936 if (!host_uid_map)
c4333195 4937 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
55022530
CB
4938 if (!host_uid_map)
4939 return log_debug(NULL, "Failed to find mapping for uid %d", euid);
f8aa4bf3 4940
dcf0ffdf
CB
4941 if (!host_gid_map)
4942 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
55022530
CB
4943 if (!host_gid_map)
4944 return log_debug(NULL, "Failed to find mapping for gid %d", egid);
28a2d9e7
CB
4945
4946 /* Allocate new {g,u}id map list. */
b8e43ef0 4947 idmap = lxc_list_new();
28a2d9e7 4948 if (!idmap)
00d6cfe2 4949 return NULL;
28a2d9e7 4950
f8aa4bf3 4951 /* Add container root to the map. */
b8e43ef0 4952 tmplist = lxc_list_new();
f8aa4bf3 4953 if (!tmplist)
00d6cfe2 4954 return NULL;
47649d5b
CB
4955 /* idmap will now keep track of that memory. */
4956 lxc_list_add_elem(tmplist, move_ptr(host_uid_map));
f8aa4bf3 4957 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 4958
2c996219 4959 if (container_root_uid) {
28a2d9e7 4960 /* Add container root to the map. */
b8e43ef0 4961 tmplist = lxc_list_new();
28a2d9e7 4962 if (!tmplist)
00d6cfe2 4963 return NULL;
47649d5b
CB
4964 /* idmap will now keep track of that memory. */
4965 lxc_list_add_elem(tmplist, move_ptr(container_root_uid));
28a2d9e7 4966 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 4967 }
f8aa4bf3 4968
b8e43ef0 4969 tmplist = lxc_list_new();
f8aa4bf3 4970 if (!tmplist)
00d6cfe2 4971 return NULL;
47649d5b
CB
4972 /* idmap will now keep track of that memory. */
4973 lxc_list_add_elem(tmplist, move_ptr(host_gid_map));
f8aa4bf3 4974 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 4975
2c996219 4976 if (container_root_gid) {
b8e43ef0 4977 tmplist = lxc_list_new();
28a2d9e7 4978 if (!tmplist)
00d6cfe2 4979 return NULL;
47649d5b
CB
4980 /* idmap will now keep track of that memory. */
4981 lxc_list_add_elem(tmplist, move_ptr(container_root_gid));
28a2d9e7 4982 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 4983 }
f8aa4bf3 4984
dbfcdf86
CB
4985 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid, nsgid);
4986
4987 if (resuid)
4988 *resuid = nsuid;
4989 if (resgid)
4990 *resgid = nsgid;
00d6cfe2 4991 return move_ptr(idmap);
dcf0ffdf
CB
4992}
4993
766c5b6d
CB
4994/*
4995 * Run a function in a new user namespace.
dcf0ffdf
CB
4996 * The caller's euid/egid will be mapped if it is not already.
4997 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4998 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4999 * This means we require only to establish a mapping from:
5000 * - the container root {g,u}id as seen from the host > user's host {g,u}id
5001 * - the container root -> some sub{g,u}id
915e3dbd 5002 * The former we add, if the user did not specify a mapping. The latter we
6f3fd27f 5003 * retrieve from the container's configured {g,u}id mappings as it must have been
dcf0ffdf
CB
5004 * there to start the container in the first place.
5005 */
7581a82f 5006int userns_exec_1(const struct lxc_conf *conf, int (*fn)(void *), void *data,
dcf0ffdf
CB
5007 const char *fn_name)
5008{
7e621263 5009 call_cleaner(__lxc_free_idmap) struct lxc_list *idmap = NULL;
0fd73091
CB
5010 int ret = -1, status = -1;
5011 char c = '1';
46bc6f2a
CB
5012 struct userns_fn_data d = {
5013 .arg = data,
5014 .fn = fn,
5015 .fn_name = fn_name,
5016 };
766c5b6d
CB
5017 pid_t pid;
5018 int pipe_fds[2];
dcf0ffdf 5019
2b2655a8
CB
5020 if (!conf)
5021 return -EINVAL;
5022
dbfcdf86 5023 idmap = get_minimal_idmap(conf, NULL, NULL);
dcf0ffdf 5024 if (!idmap)
766c5b6d 5025 return ret_errno(ENOENT);
dcf0ffdf 5026
766c5b6d
CB
5027 ret = pipe2(pipe_fds, O_CLOEXEC);
5028 if (ret < 0)
5029 return -errno;
5030
766c5b6d
CB
5031 d.p[0] = pipe_fds[0];
5032 d.p[1] = pipe_fds[1];
dcf0ffdf
CB
5033
5034 /* Clone child in new user namespace. */
a59440be 5035 pid = lxc_raw_clone_cb(run_userns_fn, &d, CLONE_NEWUSER, NULL);
dcf0ffdf 5036 if (pid < 0) {
0fd73091 5037 ERROR("Failed to clone process in new user namespace");
dcf0ffdf
CB
5038 goto on_error;
5039 }
5040
766c5b6d 5041 close_prot_errno_disarm(pipe_fds[0]);
dcf0ffdf 5042
62fef886 5043 if (lxc_log_trace()) {
dcf0ffdf 5044 struct id_map *map;
0fd73091 5045 struct lxc_list *it;
dcf0ffdf 5046
766c5b6d 5047 lxc_list_for_each(it, idmap) {
f8aa4bf3 5048 map = it->elem;
766c5b6d
CB
5049 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5050 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
f8aa4bf3 5051 }
4355ab5f
SH
5052 }
5053
f8aa4bf3 5054 /* Set up {g,u}id mapping for user namespace of child process. */
4355ab5f 5055 ret = lxc_map_ids(idmap, pid);
f8aa4bf3 5056 if (ret < 0) {
0fd73091 5057 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
f8aa4bf3 5058 goto on_error;
4355ab5f
SH
5059 }
5060
f8aa4bf3 5061 /* Tell child to proceed. */
766c5b6d 5062 if (lxc_write_nointr(pipe_fds[1], &c, 1) != 1) {
dcf0ffdf 5063 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
f8aa4bf3 5064 goto on_error;
4355ab5f
SH
5065 }
5066
686dd5d1 5067on_error:
766c5b6d
CB
5068 close_prot_errno_disarm(pipe_fds[0]);
5069 close_prot_errno_disarm(pipe_fds[1]);
f8aa4bf3 5070
ee1b16bc
TA
5071 /* Wait for child to finish. */
5072 if (pid > 0)
5073 status = wait_for_pid(pid);
5074
686dd5d1
CB
5075 if (status < 0)
5076 ret = -1;
5077
f8aa4bf3 5078 return ret;
4355ab5f 5079}
97e9cfa0 5080
d1783ef4
CB
5081int userns_exec_minimal(const struct lxc_conf *conf,
5082 int (*fn_parent)(void *), void *fn_parent_data,
5083 int (*fn_child)(void *), void *fn_child_data)
edf88289 5084{
7e621263 5085 call_cleaner(__lxc_free_idmap) struct lxc_list *idmap = NULL;
dbfcdf86
CB
5086 uid_t resuid = LXC_INVALID_UID;
5087 gid_t resgid = LXC_INVALID_GID;
edf88289 5088 char c = '1';
dbfcdf86 5089 ssize_t ret;
edf88289
CB
5090 pid_t pid;
5091 int sock_fds[2];
5092
d1783ef4 5093 if (!conf || !fn_child)
dbfcdf86 5094 return ret_errno(EINVAL);
edf88289 5095
dbfcdf86 5096 idmap = get_minimal_idmap(conf, &resuid, &resgid);
edf88289
CB
5097 if (!idmap)
5098 return ret_errno(ENOENT);
5099
5100 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sock_fds);
5101 if (ret < 0)
5102 return -errno;
5103
5104 pid = fork();
5105 if (pid < 0) {
dbfcdf86 5106 SYSERROR("Failed to create new process");
edf88289
CB
5107 goto on_error;
5108 }
5109
5110 if (pid == 0) {
5111 close_prot_errno_disarm(sock_fds[1]);
5112
5113 ret = unshare(CLONE_NEWUSER);
dbfcdf86
CB
5114 if (ret < 0) {
5115 SYSERROR("Failed to unshare new user namespace");
edf88289 5116 _exit(EXIT_FAILURE);
dbfcdf86 5117 }
edf88289 5118
dbfcdf86
CB
5119 ret = lxc_write_nointr(sock_fds[0], &c, 1);
5120 if (ret != 1)
edf88289
CB
5121 _exit(EXIT_FAILURE);
5122
5123 ret = lxc_read_nointr(sock_fds[0], &c, 1);
5124 if (ret != 1)
5125 _exit(EXIT_FAILURE);
5126
5127 close_prot_errno_disarm(sock_fds[0]);
5128
8917c382 5129 if (!lxc_drop_groups() && errno != EPERM)
edf88289
CB
5130 _exit(EXIT_FAILURE);
5131
dbfcdf86
CB
5132 ret = setresgid(resgid, resgid, resgid);
5133 if (ret < 0) {
5134 SYSERROR("Failed to setresgid(%d, %d, %d)",
5135 resgid, resgid, resgid);
edf88289 5136 _exit(EXIT_FAILURE);
dbfcdf86
CB
5137 }
5138
5139 ret = setresuid(resuid, resuid, resuid);
5140 if (ret < 0) {
5141 SYSERROR("Failed to setresuid(%d, %d, %d)",
5142 resuid, resuid, resuid);
5143 _exit(EXIT_FAILURE);
5144 }
edf88289 5145
d1783ef4 5146 ret = fn_child(fn_child_data);
dbfcdf86
CB
5147 if (ret) {
5148 SYSERROR("Running function in new user namespace failed");
edf88289 5149 _exit(EXIT_FAILURE);
dbfcdf86 5150 }
edf88289
CB
5151
5152 _exit(EXIT_SUCCESS);
5153 }
5154
5155 close_prot_errno_disarm(sock_fds[0]);
5156
62fef886 5157 if (lxc_log_trace()) {
edf88289
CB
5158 struct id_map *map;
5159 struct lxc_list *it;
5160
5161 lxc_list_for_each(it, idmap) {
5162 map = it->elem;
5163 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5164 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
5165 }
5166 }
5167
5168 ret = lxc_read_nointr(sock_fds[1], &c, 1);
5169 if (ret != 1) {
5170 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid);
5171 goto on_error;
5172 }
5173
5174 /* Set up {g,u}id mapping for user namespace of child process. */
5175 ret = lxc_map_ids(idmap, pid);
5176 if (ret < 0) {
5177 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
5178 goto on_error;
5179 }
5180
5181 /* Tell child to proceed. */
5182 ret = lxc_write_nointr(sock_fds[1], &c, 1);
5183 if (ret != 1) {
5184 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
5185 goto on_error;
5186 }
5187
d1783ef4
CB
5188 if (fn_parent && fn_parent(fn_parent_data)) {
5189 SYSERROR("Running parent function failed");
5190 _exit(EXIT_FAILURE);
5191 }
5192
edf88289
CB
5193on_error:
5194 close_prot_errno_disarm(sock_fds[0]);
5195 close_prot_errno_disarm(sock_fds[1]);
5196
5197 /* Wait for child to finish. */
dbfcdf86
CB
5198 if (pid < 0)
5199 return -1;
edf88289 5200
dbfcdf86 5201 return wait_for_pid(pid);
edf88289
CB
5202}
5203
415a8851
CB
5204int userns_exec_full(struct lxc_conf *conf, int (*fn)(void *), void *data,
5205 const char *fn_name)
5206{
5207 pid_t pid;
5208 uid_t euid, egid;
415a8851
CB
5209 int p[2];
5210 struct id_map *map;
5211 struct lxc_list *cur;
0fd73091 5212 struct userns_fn_data d;
415a8851 5213 int ret = -1;
0fd73091 5214 char c = '1';
415a8851
CB
5215 struct lxc_list *idmap = NULL, *tmplist = NULL;
5216 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
5217 *host_uid_map = NULL, *host_gid_map = NULL;
5218
2b2655a8
CB
5219 if (!conf)
5220 return -EINVAL;
5221
979f9e34 5222 ret = pipe2(p, O_CLOEXEC);
415a8851
CB
5223 if (ret < 0) {
5224 SYSERROR("opening pipe");
5225 return -1;
5226 }
5227 d.fn = fn;
5228 d.fn_name = fn_name;
5229 d.arg = data;
5230 d.p[0] = p[0];
5231 d.p[1] = p[1];
5232
5233 /* Clone child in new user namespace. */
33258b95 5234 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER, NULL);
415a8851 5235 if (pid < 0) {
0fd73091 5236 ERROR("Failed to clone process in new user namespace");
415a8851
CB
5237 goto on_error;
5238 }
5239
5240 close(p[0]);
5241 p[0] = -1;
5242
5243 euid = geteuid();
5244 egid = getegid();
5245
5246 /* Allocate new {g,u}id map list. */
b8e43ef0 5247 idmap = lxc_list_new();
415a8851
CB
5248 if (!idmap)
5249 goto on_error;
415a8851
CB
5250
5251 /* Find container root. */
0fd73091 5252 lxc_list_for_each (cur, &conf->id_map) {
415a8851
CB
5253 struct id_map *tmpmap;
5254
b8e43ef0 5255 tmplist = lxc_list_new();
415a8851
CB
5256 if (!tmplist)
5257 goto on_error;
5258
b8e43ef0 5259 tmpmap = zalloc(sizeof(*tmpmap));
415a8851
CB
5260 if (!tmpmap) {
5261 free(tmplist);
5262 goto on_error;
5263 }
5264
5265 memset(tmpmap, 0, sizeof(*tmpmap));
5266 memcpy(tmpmap, cur->elem, sizeof(*tmpmap));
5267 tmplist->elem = tmpmap;
5268
5269 lxc_list_add_tail(idmap, tmplist);
5270
5271 map = cur->elem;
5272
5273 if (map->idtype == ID_TYPE_UID)
5274 if (euid >= map->hostid && euid < map->hostid + map->range)
5275 host_uid_map = map;
5276
5277 if (map->idtype == ID_TYPE_GID)
5278 if (egid >= map->hostid && egid < map->hostid + map->range)
5279 host_gid_map = map;
5280
5281 if (map->nsid != 0)
5282 continue;
5283
5284 if (map->idtype == ID_TYPE_UID)
5285 if (container_root_uid == NULL)
5286 container_root_uid = map;
5287
5288 if (map->idtype == ID_TYPE_GID)
5289 if (container_root_gid == NULL)
5290 container_root_gid = map;
5291 }
5292
5293 if (!container_root_uid || !container_root_gid) {
5294 ERROR("No mapping for container root found");
5295 goto on_error;
5296 }
5297
5298 /* Check whether the {g,u}id of the user has a mapping. */
5299 if (!host_uid_map)
c4333195 5300 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
415a8851
CB
5301 else
5302 host_uid_map = container_root_uid;
5303
5304 if (!host_gid_map)
c4333195 5305 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
415a8851
CB
5306 else
5307 host_gid_map = container_root_gid;
5308
5309 if (!host_uid_map) {
5310 DEBUG("Failed to find mapping for uid %d", euid);
5311 goto on_error;
5312 }
5313
5314 if (!host_gid_map) {
5315 DEBUG("Failed to find mapping for gid %d", egid);
5316 goto on_error;
5317 }
5318
5319 if (host_uid_map && (host_uid_map != container_root_uid)) {
5320 /* Add container root to the map. */
b8e43ef0 5321 tmplist = lxc_list_new();
415a8851
CB
5322 if (!tmplist)
5323 goto on_error;
5324 lxc_list_add_elem(tmplist, host_uid_map);
5325 lxc_list_add_tail(idmap, tmplist);
5326 }
5327 /* idmap will now keep track of that memory. */
5328 host_uid_map = NULL;
5329
5330 if (host_gid_map && (host_gid_map != container_root_gid)) {
b8e43ef0 5331 tmplist = lxc_list_new();
415a8851
CB
5332 if (!tmplist)
5333 goto on_error;
5334 lxc_list_add_elem(tmplist, host_gid_map);
5335 lxc_list_add_tail(idmap, tmplist);
5336 }
5337 /* idmap will now keep track of that memory. */
5338 host_gid_map = NULL;
5339
62fef886 5340 if (lxc_log_trace()) {
0fd73091 5341 lxc_list_for_each (cur, idmap) {
415a8851
CB
5342 map = cur->elem;
5343 TRACE("establishing %cid mapping for \"%d\" in new "
5344 "user namespace: nsuid %lu - hostid %lu - range "
5345 "%lu",
5346 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
5347 map->nsid, map->hostid, map->range);
5348 }
5349 }
5350
5351 /* Set up {g,u}id mapping for user namespace of child process. */
5352 ret = lxc_map_ids(idmap, pid);
5353 if (ret < 0) {
0fd73091 5354 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid);
415a8851
CB
5355 goto on_error;
5356 }
5357
5358 /* Tell child to proceed. */
489f39be 5359 if (lxc_write_nointr(p[1], &c, 1) != 1) {
0fd73091 5360 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
415a8851
CB
5361 goto on_error;
5362 }
5363
686dd5d1 5364on_error:
ee1b16bc
TA
5365 if (p[0] != -1)
5366 close(p[0]);
5367 close(p[1]);
5368
415a8851 5369 /* Wait for child to finish. */
686dd5d1
CB
5370 if (pid > 0)
5371 ret = wait_for_pid(pid);
415a8851 5372
7e621263
CB
5373 if (idmap)
5374 __lxc_free_idmap(idmap);
80758b4b 5375
415a8851
CB
5376 if (host_uid_map && (host_uid_map != container_root_uid))
5377 free(host_uid_map);
5378 if (host_gid_map && (host_gid_map != container_root_gid))
5379 free(host_gid_map);
5380
415a8851
CB
5381 return ret;
5382}
5383
234998b4
CB
5384static int add_idmap_entry(struct lxc_list *idmap, enum idtype idtype,
5385 unsigned long nsid, unsigned long hostid,
5386 unsigned long range)
5387{
5388 __do_free struct id_map *new_idmap = NULL;
5389 __do_free struct lxc_list *new_list = NULL;
5390
5391 new_idmap = zalloc(sizeof(*new_idmap));
5392 if (!new_idmap)
5393 return ret_errno(ENOMEM);
5394
5395 new_idmap->idtype = idtype;
5396 new_idmap->hostid = hostid;
5397 new_idmap->nsid = nsid;
5398 new_idmap->range = range;
5399
5400 new_list = zalloc(sizeof(*new_list));
5401 if (!new_list)
5402 return ret_errno(ENOMEM);
5403
5404 new_list->elem = move_ptr(new_idmap);
5405 lxc_list_add_tail(idmap, move_ptr(new_list));
5406
5407 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
5408 idtype == ID_TYPE_UID ? 'u' : 'g', nsid, hostid, range);
5409 return 0;
5410}
5411
5412int userns_exec_mapped_root(const char *path, int path_fd,
5413 const struct lxc_conf *conf)
5414{
7e621263 5415 call_cleaner(__lxc_free_idmap) struct lxc_list *idmap = NULL;
234998b4
CB
5416 __do_close int fd = -EBADF;
5417 int target_fd = -EBADF;
5418 char c = '1';
5419 ssize_t ret;
5420 pid_t pid;
5421 int sock_fds[2];
5422 uid_t container_host_uid, hostuid;
5423 gid_t container_host_gid, hostgid;
5424 struct stat st;
5425
5426 if (!conf || (!path && path_fd < 0))
5427 return ret_errno(EINVAL);
5428
5429 if (!path)
5430 path = "(null)";
5431
5432 container_host_uid = get_mapped_rootid(conf, ID_TYPE_UID);
5433 if (!uid_valid(container_host_uid))
5434 return log_error(-1, "No uid mapping for container root");
5435
5436 container_host_gid = get_mapped_rootid(conf, ID_TYPE_GID);
5437 if (!gid_valid(container_host_gid))
5438 return log_error(-1, "No gid mapping for container root");
5439
cf68ffd9 5440 if (path_fd < 0) {
a72c68f7 5441 fd = open(path, O_CLOEXEC | O_NOCTTY);
234998b4
CB
5442 if (fd < 0)
5443 return log_error_errno(-errno, errno, "Failed to open \"%s\"", path);
5444 target_fd = fd;
5445 } else {
5446 target_fd = path_fd;
5447 }
5448
5449 hostuid = geteuid();
5450 /* We are root so chown directly. */
5451 if (hostuid == 0) {
5452 ret = fchown(target_fd, container_host_uid, container_host_gid);
5453 if (ret)
5454 return log_error_errno(-errno, errno,
5455 "Failed to fchown(%d(%s), %d, %d)",
5456 target_fd, path, container_host_uid,
5457 container_host_gid);
5458 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd, path,
5459 container_host_uid, container_host_gid);
5460 }
5461
5462 /* The container's root host id matches */
5463 if (container_host_uid == hostuid)
5464 return log_info(0, "Container root id is mapped to our uid");
5465
5466 /* Get the current ids of our target. */
5467 ret = fstat(target_fd, &st);
5468 if (ret)
5469 return log_error_errno(-errno, errno, "Failed to stat \"%s\"", path);
5470
5471 hostgid = getegid();
5472 if (st.st_uid == hostuid && mapped_hostid(st.st_gid, conf, ID_TYPE_GID) < 0) {
5473 ret = fchown(target_fd, -1, hostgid);
5474 if (ret)
5475 return log_error_errno(-errno, errno,
5476 "Failed to fchown(%d(%s), -1, %d)",
5477 target_fd, path, hostgid);
2e8013f9 5478 TRACE("Chowned %d(%s) to -1:%d", target_fd, path, hostgid);
234998b4
CB
5479 }
5480
b8e43ef0 5481 idmap = lxc_list_new();
234998b4
CB
5482 if (!idmap)
5483 return -ENOMEM;
234998b4
CB
5484
5485 /* "u:0:rootuid:1" */
5486 ret = add_idmap_entry(idmap, ID_TYPE_UID, 0, container_host_uid, 1);
5487 if (ret < 0)
5488 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5489
5490 /* "u:hostuid:hostuid:1" */
5491 ret = add_idmap_entry(idmap, ID_TYPE_UID, hostuid, hostuid, 1);
5492 if (ret < 0)
5493 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5494
5495 /* "g:0:rootgid:1" */
5496 ret = add_idmap_entry(idmap, ID_TYPE_GID, 0, container_host_gid, 1);
5497 if (ret < 0)
5498 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5499
5500 /* "g:hostgid:hostgid:1" */
5501 ret = add_idmap_entry(idmap, ID_TYPE_GID, hostgid, hostgid, 1);
5502 if (ret < 0)
5503 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5504
5505 if (hostgid != st.st_gid) {
5506 /* "g:pathgid:rootgid+pathgid:1" */
5507 ret = add_idmap_entry(idmap, ID_TYPE_GID, st.st_gid,
5508 container_host_gid + (gid_t)st.st_gid, 1);
5509 if (ret < 0)
5510 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5511 }
5512
5513 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sock_fds);
5514 if (ret < 0)
5515 return -errno;
5516
5517 pid = fork();
5518 if (pid < 0) {
5519 SYSERROR("Failed to create new process");
5520 goto on_error;
5521 }
5522
5523 if (pid == 0) {
5524 close_prot_errno_disarm(sock_fds[1]);
5525
5526 ret = unshare(CLONE_NEWUSER);
5527 if (ret < 0) {
5528 SYSERROR("Failed to unshare new user namespace");
5529 _exit(EXIT_FAILURE);
5530 }
5531
5532 ret = lxc_write_nointr(sock_fds[0], &c, 1);
5533 if (ret != 1)
5534 _exit(EXIT_FAILURE);
5535
5536 ret = lxc_read_nointr(sock_fds[0], &c, 1);
5537 if (ret != 1)
5538 _exit(EXIT_FAILURE);
5539
5540 close_prot_errno_disarm(sock_fds[0]);
5541
5542 if (!lxc_switch_uid_gid(0, 0))
5543 _exit(EXIT_FAILURE);
5544
8917c382 5545 if (!lxc_drop_groups())
234998b4
CB
5546 _exit(EXIT_FAILURE);
5547
8053a085 5548 ret = fchown(target_fd, 0, st.st_gid);
234998b4 5549 if (ret) {
8ea93a0f 5550 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd, path, st.st_gid);
234998b4
CB
5551 _exit(EXIT_FAILURE);
5552 }
5553
2e8013f9 5554 TRACE("Chowned %d(%s) to 0:%d", target_fd, path, st.st_gid);
234998b4
CB
5555 _exit(EXIT_SUCCESS);
5556 }
5557
5558 close_prot_errno_disarm(sock_fds[0]);
5559
62fef886 5560 if (lxc_log_trace()) {
234998b4
CB
5561 struct id_map *map;
5562 struct lxc_list *it;
5563
5564 lxc_list_for_each(it, idmap) {
5565 map = it->elem;
5566 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5567 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
5568 }
5569 }
5570
5571 ret = lxc_read_nointr(sock_fds[1], &c, 1);
5572 if (ret != 1) {
5573 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid);
5574 goto on_error;
5575 }
5576
5577 /* Set up {g,u}id mapping for user namespace of child process. */
5578 ret = lxc_map_ids(idmap, pid);
5579 if (ret < 0) {
5580 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
5581 goto on_error;
5582 }
5583
5584 /* Tell child to proceed. */
5585 ret = lxc_write_nointr(sock_fds[1], &c, 1);
5586 if (ret != 1) {
5587 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
5588 goto on_error;
5589 }
5590
5591on_error:
5592 close_prot_errno_disarm(sock_fds[0]);
5593 close_prot_errno_disarm(sock_fds[1]);
5594
5595 /* Wait for child to finish. */
5596 if (pid < 0)
5597 return -1;
5598
5599 return wait_for_pid(pid);
5600}
5601
a96a8e8c 5602/* not thread-safe, do not use from api without first forking */
0fd73091 5603static char *getuname(void)
97e9cfa0 5604{
4f410b2a 5605 __do_free char *buf = NULL;
cb7aa5e8
DJ
5606 struct passwd pwent;
5607 struct passwd *pwentp = NULL;
cb7aa5e8
DJ
5608 size_t bufsize;
5609 int ret;
97e9cfa0 5610
cb7aa5e8
DJ
5611 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
5612 if (bufsize == -1)
5613 bufsize = 1024;
5614
b8e43ef0 5615 buf = zalloc(bufsize);
cb7aa5e8 5616 if (!buf)
97e9cfa0
SH
5617 return NULL;
5618
cb7aa5e8
DJ
5619 ret = getpwuid_r(geteuid(), &pwent, buf, bufsize, &pwentp);
5620 if (!pwentp) {
5621 if (ret == 0)
5622 WARN("Could not find matched password record.");
5623
55022530 5624 return log_error(NULL, "Failed to get password record - %u", geteuid());
cb7aa5e8
DJ
5625 }
5626
4f410b2a 5627 return strdup(pwent.pw_name);
97e9cfa0
SH
5628}
5629
a96a8e8c 5630/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
5631static char *getgname(void)
5632{
4f410b2a 5633 __do_free char *buf = NULL;
3de9fb4c
DJ
5634 struct group grent;
5635 struct group *grentp = NULL;
3de9fb4c
DJ
5636 size_t bufsize;
5637 int ret;
5638
5639 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
5640 if (bufsize == -1)
5641 bufsize = 1024;
5642
b8e43ef0 5643 buf = zalloc(bufsize);
3de9fb4c
DJ
5644 if (!buf)
5645 return NULL;
5646
5647 ret = getgrgid_r(getegid(), &grent, buf, bufsize, &grentp);
5648 if (!grentp) {
5649 if (ret == 0)
5650 WARN("Could not find matched group record");
97e9cfa0 5651
55022530 5652 return log_error(NULL, "Failed to get group record - %u", getegid());
3de9fb4c
DJ
5653 }
5654
4f410b2a 5655 return strdup(grent.gr_name);
97e9cfa0
SH
5656}
5657
a96a8e8c 5658/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
5659void suggest_default_idmap(void)
5660{
3a6e3bf5 5661 __do_free char *gname = NULL, *line = NULL, *uname = NULL;
4aae564f 5662 __do_fclose FILE *subuid_f = NULL, *subgid_f = NULL;
97e9cfa0 5663 unsigned int uid = 0, urange = 0, gid = 0, grange = 0;
97e9cfa0
SH
5664 size_t len = 0;
5665
0fd73091
CB
5666 uname = getuname();
5667 if (!uname)
97e9cfa0
SH
5668 return;
5669
0fd73091 5670 gname = getgname();
3a6e3bf5 5671 if (!gname)
97e9cfa0 5672 return;
97e9cfa0 5673
4110345b 5674 subuid_f = fopen(subuidfile, "re");
4aae564f 5675 if (!subuid_f) {
97e9cfa0 5676 ERROR("Your system is not configured with subuids");
97e9cfa0
SH
5677 return;
5678 }
0fd73091 5679
4aae564f 5680 while (getline(&line, &len, subuid_f) != -1) {
0fd73091 5681 char *p, *p2;
b7930180 5682 size_t no_newline = 0;
0fd73091
CB
5683
5684 p = strchr(line, ':');
97e9cfa0
SH
5685 if (*line == '#')
5686 continue;
5687 if (!p)
5688 continue;
5689 *p = '\0';
5690 p++;
0fd73091 5691
71528742 5692 if (!strequal(line, uname))
97e9cfa0 5693 continue;
0fd73091 5694
97e9cfa0
SH
5695 p2 = strchr(p, ':');
5696 if (!p2)
5697 continue;
5698 *p2 = '\0';
5699 p2++;
5700 if (!*p2)
5701 continue;
b7930180
CB
5702 no_newline = strcspn(p2, "\n");
5703 p2[no_newline] = '\0';
5704
b7b2fde4 5705 if (lxc_safe_uint(p, &uid) < 0)
0fd73091 5706 WARN("Could not parse UID");
b7b2fde4 5707 if (lxc_safe_uint(p2, &urange) < 0)
0fd73091 5708 WARN("Could not parse UID range");
97e9cfa0 5709 }
97e9cfa0 5710
4110345b 5711 subgid_f = fopen(subgidfile, "re");
4aae564f 5712 if (!subgid_f) {
97e9cfa0 5713 ERROR("Your system is not configured with subgids");
97e9cfa0
SH
5714 return;
5715 }
0fd73091 5716
4aae564f 5717 while (getline(&line, &len, subgid_f) != -1) {
0fd73091 5718 char *p, *p2;
b7930180 5719 size_t no_newline = 0;
0fd73091
CB
5720
5721 p = strchr(line, ':');
97e9cfa0
SH
5722 if (*line == '#')
5723 continue;
5724 if (!p)
5725 continue;
5726 *p = '\0';
5727 p++;
0fd73091 5728
71528742 5729 if (!strequal(line, uname))
97e9cfa0 5730 continue;
0fd73091 5731
97e9cfa0
SH
5732 p2 = strchr(p, ':');
5733 if (!p2)
5734 continue;
5735 *p2 = '\0';
5736 p2++;
5737 if (!*p2)
5738 continue;
b7930180
CB
5739 no_newline = strcspn(p2, "\n");
5740 p2[no_newline] = '\0';
5741
b7b2fde4 5742 if (lxc_safe_uint(p, &gid) < 0)
0fd73091 5743 WARN("Could not parse GID");
b7b2fde4 5744 if (lxc_safe_uint(p2, &grange) < 0)
0fd73091 5745 WARN("Could not parse GID range");
97e9cfa0 5746 }
97e9cfa0 5747
97e9cfa0
SH
5748 if (!urange || !grange) {
5749 ERROR("You do not have subuids or subgids allocated");
5750 ERROR("Unprivileged containers require subuids and subgids");
5751 return;
5752 }
5753
5754 ERROR("You must either run as root, or define uid mappings");
5755 ERROR("To pass uid mappings to lxc-create, you could create");
5756 ERROR("~/.config/lxc/default.conf:");
5757 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG);
bdcbb6b3
CB
5758 ERROR("lxc.idmap = u 0 %u %u", uid, urange);
5759 ERROR("lxc.idmap = g 0 %u %u", gid, grange);
97e9cfa0 5760}
aaf26830 5761
a7307747
SH
5762static void free_cgroup_settings(struct lxc_list *result)
5763{
5764 struct lxc_list *iterator, *next;
5765
0fd73091 5766 lxc_list_for_each_safe (iterator, result, next) {
a7307747 5767 lxc_list_del(iterator);
55022530 5768 free_disarm(iterator);
a7307747 5769 }
55022530 5770 free_disarm(result);
a7307747
SH
5771}
5772
0fd73091 5773/* Return the list of cgroup_settings sorted according to the following rules
aaf26830
KT
5774 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
5775 */
0fd73091 5776struct lxc_list *sort_cgroup_settings(struct lxc_list *cgroup_settings)
aaf26830
KT
5777{
5778 struct lxc_list *result;
aaf26830 5779 struct lxc_cgroup *cg = NULL;
0fd73091 5780 struct lxc_list *it = NULL, *item = NULL, *memsw_limit = NULL;
aaf26830 5781
b8e43ef0 5782 result = lxc_list_new();
0fd73091 5783 if (!result)
fac7c663 5784 return NULL;
aaf26830
KT
5785 lxc_list_init(result);
5786
0fd73091
CB
5787 /* Iterate over the cgroup settings and copy them to the output list. */
5788 lxc_list_for_each (it, cgroup_settings) {
b8e43ef0 5789 item = zalloc(sizeof(*item));
fac7c663 5790 if (!item) {
a7307747 5791 free_cgroup_settings(result);
fac7c663
KT
5792 return NULL;
5793 }
0fd73091 5794
aaf26830
KT
5795 item->elem = it->elem;
5796 cg = it->elem;
71528742 5797 if (strequal(cg->subsystem, "memory.memsw.limit_in_bytes")) {
aaf26830
KT
5798 /* Store the memsw_limit location */
5799 memsw_limit = item;
71528742 5800 } else if (strequal(cg->subsystem, "memory.limit_in_bytes") &&
0fd73091
CB
5801 memsw_limit != NULL) {
5802 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
5803 * before lxc.cgroup.memory.limit_in_bytes, swap these
5804 * two items */
aaf26830
KT
5805 item->elem = memsw_limit->elem;
5806 memsw_limit->elem = it->elem;
5807 }
5808 lxc_list_add_tail(result, item);
5809 }
5810
5811 return result;
a7307747 5812}