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