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