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