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