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