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