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