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