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