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