]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/conf.c
Merge branch 'duguhaotian-new' into lxc/master
[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 }
90f20466 400 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname);
3f60c2f7
CB
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,
5285689c 578 unsigned long flags)
e2a7e8dc 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;
86530b0a 1568 char *rootfs_path = rootfs->path ? rootfs->mount : "";
52e35957 1569
8b1b1210
CB
1570 if (console->path && !strcmp(console->path, "none"))
1571 return 0;
1572
86530b0a 1573 ret = snprintf(path, sizeof(path), "%s/dev/console", rootfs_path);
3d7d929a 1574 if (ret < 0 || (size_t)ret >= sizeof(path))
7c6ef2a2 1575 return -1;
52e35957 1576
8b1b1210
CB
1577 /* When we are asked to setup a console we remove any previous
1578 * /dev/console bind-mounts.
1579 */
a7ba3c7f
CB
1580 if (file_exists(path)) {
1581 ret = lxc_unstack_mountpoint(path, false);
1582 if (ret < 0) {
86530b0a 1583 ERROR("Failed to unmount \"%s\": %s", path, strerror(errno));
a7ba3c7f
CB
1584 return -ret;
1585 } else {
86530b0a 1586 DEBUG("Cleared all (%d) mounts from \"%s\"", ret, path);
a7ba3c7f 1587 }
8b1b1210
CB
1588 }
1589
1590 /* For unprivileged containers autodev or automounts will already have
1591 * taken care of creating /dev/console.
1592 */
0728ebf4
TA
1593 fd = open(path, O_CREAT | O_EXCL, S_IXUSR | S_IXGRP | S_IXOTH);
1594 if (fd < 0) {
1595 if (errno != EEXIST) {
86530b0a 1596 SYSERROR("Failed to create console");
3d7d929a 1597 return -errno;
0728ebf4
TA
1598 }
1599 } else {
1600 close(fd);
52e35957
DL
1601 }
1602
86530b0a
L
1603 ret = chmod(console->name, S_IXUSR | S_IXGRP | S_IXOTH);
1604 if (ret < 0) {
1605 SYSERROR("Failed to set mode '0%o' to '%s'", S_IXUSR | S_IXGRP | S_IXOTH, console->name);
3d7d929a 1606 return -errno;
63376d7d 1607 }
13954cce 1608
86530b0a
L
1609 ret = safe_mount(console->name, path, "none", MS_BIND, 0, rootfs_path);
1610 if (ret < 0) {
1611 ERROR("Failed to mount '%s' on '%s'", console->name, path);
6e590161 1612 return -1;
1613 }
1614
86530b0a 1615 DEBUG("Mounted pts device \"%s\" onto \"%s\"", console->name, path);
7c6ef2a2
SH
1616 return 0;
1617}
1618
3d7d929a
CB
1619static int lxc_setup_ttydir_console(const struct lxc_rootfs *rootfs,
1620 const struct lxc_console *console,
1621 char *ttydir)
7c6ef2a2 1622{
3dc035f1 1623 int ret, fd;
3d7d929a 1624 char path[MAXPATHLEN], lxcpath[MAXPATHLEN];
86530b0a 1625 char *rootfs_path = rootfs->path ? rootfs->mount : "";
7c6ef2a2 1626
3dc035f1
L
1627 if (console->path && !strcmp(console->path, "none"))
1628 return 0;
1629
7c6ef2a2 1630 /* create rootfs/dev/<ttydir> directory */
86530b0a 1631 ret = snprintf(path, sizeof(path), "%s/dev/%s", rootfs_path, ttydir);
3d7d929a 1632 if (ret < 0 || (size_t)ret >= sizeof(path))
7c6ef2a2 1633 return -1;
3d7d929a 1634
7c6ef2a2
SH
1635 ret = mkdir(path, 0755);
1636 if (ret && errno != EEXIST) {
86530b0a 1637 SYSERROR("Failed with errno %d to create %s", errno, path);
3d7d929a 1638 return -errno;
7c6ef2a2 1639 }
4742cd9a 1640 DEBUG("Created directory for console and tty devices at \"%s\"", path);
7c6ef2a2 1641
86530b0a 1642 ret = snprintf(lxcpath, sizeof(lxcpath), "%s/dev/%s/console", rootfs_path, ttydir);
3d7d929a
CB
1643 if (ret < 0 || (size_t)ret >= sizeof(lxcpath))
1644 return -1;
1645
7c6ef2a2 1646 ret = creat(lxcpath, 0660);
3d7d929a 1647 if (ret == -1 && errno != EEXIST) {
86530b0a 1648 SYSERROR("Error %d creating %s", errno, lxcpath);
3d7d929a 1649 return -errno;
7c6ef2a2 1650 }
4d44e274
SH
1651 if (ret >= 0)
1652 close(ret);
7c6ef2a2 1653
86530b0a 1654 ret = snprintf(path, sizeof(path), "%s/dev/console", rootfs_path);
3dc035f1 1655 if (ret < 0 || (size_t)ret >= sizeof(path))
7c6ef2a2 1656 return -1;
2a12fefd 1657
3dc035f1 1658 if (file_exists(path)) {
a7ba3c7f 1659 ret = lxc_unstack_mountpoint(path, false);
2a12fefd 1660 if (ret < 0) {
86530b0a 1661 ERROR("Failed to unmount \"%s\": %s", path, strerror(errno));
a7ba3c7f
CB
1662 return -ret;
1663 } else {
86530b0a 1664 DEBUG("Cleared all (%d) mounts from \"%s\"", ret, path);
a7ba3c7f 1665 }
3dc035f1 1666 }
2a12fefd 1667
3dc035f1
L
1668 fd = open(path, O_CREAT | O_EXCL, S_IXUSR | S_IXGRP | S_IXOTH);
1669 if (fd < 0) {
1670 if (errno != EEXIST) {
86530b0a 1671 SYSERROR("Failed to create console");
3dc035f1 1672 return -errno;
2a12fefd 1673 }
3dc035f1
L
1674 } else {
1675 close(fd);
7c6ef2a2
SH
1676 }
1677
86530b0a
L
1678 ret = chmod(console->name, S_IXUSR | S_IXGRP | S_IXOTH);
1679 if (ret < 0) {
1680 SYSERROR("Failed to set mode '0%o' to '%s'", S_IXUSR | S_IXGRP | S_IXOTH, console->name);
2a12fefd
CB
1681 return -errno;
1682 }
1683
3dc035f1 1684 /* bind mount console->name to '/dev/<ttydir>/console' */
86530b0a
L
1685 ret = safe_mount(console->name, lxcpath, "none", MS_BIND, 0, rootfs_path);
1686 if (ret < 0) {
1687 ERROR("Failed to mount '%s' on '%s'", console->name, lxcpath);
7c6ef2a2
SH
1688 return -1;
1689 }
86530b0a 1690 DEBUG("Mounted \"%s\" onto \"%s\"", console->name, lxcpath);
3dc035f1
L
1691
1692 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
86530b0a
L
1693 ret = safe_mount(lxcpath, path, "none", MS_BIND, 0, rootfs_path);
1694 if (ret < 0) {
1695 ERROR("Failed to mount '%s' on '%s'", console->name, lxcpath);
3dc035f1
L
1696 return -1;
1697 }
86530b0a 1698 DEBUG("Mounted \"%s\" onto \"%s\"", console->name, lxcpath);
3dc035f1 1699
86530b0a 1700 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath, path);
7c6ef2a2 1701
6e590161 1702 return 0;
1703}
1704
3d7d929a
CB
1705static int lxc_setup_console(const struct lxc_rootfs *rootfs,
1706 const struct lxc_console *console, char *ttydir)
7c6ef2a2 1707{
3d7d929a 1708
7c6ef2a2 1709 if (!ttydir)
3d7d929a 1710 return lxc_setup_dev_console(rootfs, console);
7c6ef2a2 1711
3d7d929a 1712 return lxc_setup_ttydir_console(rootfs, console, ttydir);
7c6ef2a2
SH
1713}
1714
998ac676
RT
1715static void parse_mntopt(char *opt, unsigned long *flags, char **data)
1716{
1717 struct mount_opt *mo;
1718
1719 /* If opt is found in mount_opt, set or clear flags.
1720 * Otherwise append it to data. */
1721
1722 for (mo = &mount_opt[0]; mo->name != NULL; mo++) {
1723 if (!strncmp(opt, mo->name, strlen(mo->name))) {
1724 if (mo->clear)
1725 *flags &= ~mo->flag;
1726 else
1727 *flags |= mo->flag;
1728 return;
1729 }
1730 }
1731
1732 if (strlen(*data))
1733 strcat(*data, ",");
1734 strcat(*data, opt);
1735}
1736
a17b1e65 1737int parse_mntopts(const char *mntopts, unsigned long *mntflags,
998ac676
RT
1738 char **mntdata)
1739{
1740 char *s, *data;
1741 char *p, *saveptr = NULL;
1742
911324ef 1743 *mntdata = NULL;
91656ce5 1744 *mntflags = 0L;
911324ef
DL
1745
1746 if (!mntopts)
998ac676
RT
1747 return 0;
1748
911324ef 1749 s = strdup(mntopts);
998ac676 1750 if (!s) {
36eb9bde 1751 SYSERROR("failed to allocate memory");
998ac676
RT
1752 return -1;
1753 }
1754
1755 data = malloc(strlen(s) + 1);
1756 if (!data) {
36eb9bde 1757 SYSERROR("failed to allocate memory");
998ac676
RT
1758 free(s);
1759 return -1;
1760 }
1761 *data = 0;
1762
1763 for (p = strtok_r(s, ",", &saveptr); p != NULL;
1764 p = strtok_r(NULL, ",", &saveptr))
1765 parse_mntopt(p, mntflags, &data);
1766
1767 if (*data)
1768 *mntdata = data;
1769 else
1770 free(data);
1771 free(s);
1772
1773 return 0;
1774}
1775
6fd5e769
SH
1776static void null_endofword(char *word)
1777{
1778 while (*word && *word != ' ' && *word != '\t')
1779 word++;
1780 *word = '\0';
1781}
1782
1783/*
1784 * skip @nfields spaces in @src
1785 */
1786static char *get_field(char *src, int nfields)
1787{
1788 char *p = src;
1789 int i;
1790
1791 for (i = 0; i < nfields; i++) {
1792 while (*p && *p != ' ' && *p != '\t')
1793 p++;
1794 if (!*p)
1795 break;
1796 p++;
1797 }
1798 return p;
1799}
1800
911324ef
DL
1801static int mount_entry(const char *fsname, const char *target,
1802 const char *fstype, unsigned long mountflags,
d6bec4ab
YT
1803 const char *data, bool optional, bool dev,
1804 bool relative, const char *rootfs)
911324ef 1805{
0ac4b28a 1806 int ret;
181437fd
YT
1807 char srcbuf[MAXPATHLEN];
1808 const char *srcpath = fsname;
614305f3 1809#ifdef HAVE_STATVFS
2938f7c8 1810 struct statvfs sb;
614305f3 1811#endif
2938f7c8 1812
181437fd
YT
1813 if (relative) {
1814 ret = snprintf(srcbuf, MAXPATHLEN, "%s/%s", rootfs ? rootfs : "/", fsname ? fsname : "");
1815 if (ret < 0 || ret >= MAXPATHLEN) {
1816 ERROR("source path is too long");
1817 return -1;
1818 }
1819 srcpath = srcbuf;
1820 }
1821
1822 ret = safe_mount(srcpath, target, fstype, mountflags & ~MS_REMOUNT, data,
0ac4b28a
CB
1823 rootfs);
1824 if (ret < 0) {
1fc64d22 1825 if (optional) {
0ac4b28a 1826 INFO("Failed to mount \"%s\" on \"%s\" (optional): %s",
181437fd 1827 srcpath ? srcpath : "(null)", target, strerror(errno));
1fc64d22
SG
1828 return 0;
1829 }
0ac4b28a 1830
0103eb53 1831 SYSERROR("Failed to mount \"%s\" on \"%s\"",
181437fd 1832 srcpath ? srcpath : "(null)", target);
0ac4b28a 1833 return -1;
911324ef
DL
1834 }
1835
1836 if ((mountflags & MS_REMOUNT) || (mountflags & MS_BIND)) {
7c5b6e7c 1837 unsigned long rqd_flags = 0;
0ac4b28a
CB
1838
1839 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
181437fd 1840 "options", srcpath ? srcpath : "(none)", target ? target : "(none)");
0ac4b28a 1841
7c5b6e7c
AS
1842 if (mountflags & MS_RDONLY)
1843 rqd_flags |= MS_RDONLY;
614305f3 1844#ifdef HAVE_STATVFS
181437fd 1845 if (srcpath && statvfs(srcpath, &sb) == 0) {
7c5b6e7c 1846 unsigned long required_flags = rqd_flags;
0ac4b28a 1847
2938f7c8
SH
1848 if (sb.f_flag & MS_NOSUID)
1849 required_flags |= MS_NOSUID;
0ac4b28a 1850
ae7a770e 1851 if (sb.f_flag & MS_NODEV && !dev)
2938f7c8 1852 required_flags |= MS_NODEV;
0ac4b28a 1853
2938f7c8
SH
1854 if (sb.f_flag & MS_RDONLY)
1855 required_flags |= MS_RDONLY;
0ac4b28a 1856
2938f7c8
SH
1857 if (sb.f_flag & MS_NOEXEC)
1858 required_flags |= MS_NOEXEC;
0ac4b28a
CB
1859
1860 DEBUG("Flags for \"%s\" were %lu, required extra flags "
181437fd 1861 "are %lu", srcpath, sb.f_flag, required_flags);
0ac4b28a
CB
1862
1863 /* If this was a bind mount request, and required_flags
2938f7c8 1864 * does not have any flags which are not already in
0ac4b28a 1865 * mountflags, then skip the remount.
2938f7c8
SH
1866 */
1867 if (!(mountflags & MS_REMOUNT)) {
0ac4b28a
CB
1868 if (!(required_flags & ~mountflags) &&
1869 rqd_flags == 0) {
1870 DEBUG("Mountflags already were %lu, "
1871 "skipping remount", mountflags);
2938f7c8
SH
1872 goto skipremount;
1873 }
1874 }
0ac4b28a 1875
2938f7c8 1876 mountflags |= required_flags;
6fd5e769 1877 }
614305f3 1878#endif
911324ef 1879
181437fd 1880 ret = mount(srcpath, target, fstype, mountflags | MS_REMOUNT, data);
0ac4b28a 1881 if (ret < 0) {
1fc64d22 1882 if (optional) {
0ac4b28a 1883 INFO("Failed to mount \"%s\" on \"%s\" "
0103eb53 1884 "(optional): %s",
181437fd 1885 srcpath ? srcpath : "(null)", target,
0ac4b28a 1886 strerror(errno));
1fc64d22
SG
1887 return 0;
1888 }
0ac4b28a 1889
0103eb53 1890 SYSERROR("Failed to mount \"%s\" on \"%s\"",
181437fd 1891 srcpath ? srcpath : "(null)", target);
0ac4b28a 1892 return -1;
911324ef
DL
1893 }
1894 }
1895
614305f3 1896#ifdef HAVE_STATVFS
6fd5e769 1897skipremount:
614305f3 1898#endif
0103eb53 1899 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
181437fd 1900 srcpath ? srcpath : "(null)", target, fstype);
911324ef
DL
1901
1902 return 0;
1903}
1904
c5e30de4 1905/* Remove "optional", "create=dir", and "create=file" from mntopt */
4e4ca161
SH
1906static void cull_mntent_opt(struct mntent *mntent)
1907{
1908 int i;
181437fd 1909 char *list[] = {"create=dir", "create=file", "optional", "relative", NULL};
c5e30de4
CB
1910
1911 for (i = 0; list[i]; i++) {
1912 char *p, *p2;
1913
1914 p = strstr(mntent->mnt_opts, list[i]);
1915 if (!p)
4e4ca161 1916 continue;
c5e30de4 1917
4e4ca161
SH
1918 p2 = strchr(p, ',');
1919 if (!p2) {
1920 /* no more mntopts, so just chop it here */
1921 *p = '\0';
1922 continue;
1923 }
c5e30de4
CB
1924
1925 memmove(p, p2 + 1, strlen(p2 + 1) + 1);
4e4ca161
SH
1926 }
1927}
1928
4d5b72a1 1929static int mount_entry_create_dir_file(const struct mntent *mntent,
749f98d9
CB
1930 const char *path,
1931 const struct lxc_rootfs *rootfs,
1932 const char *lxc_name,
1933 const char *lxc_path)
0ad19a3f 1934{
608e3567 1935 int ret = 0;
911324ef 1936
749f98d9
CB
1937 if (!strncmp(mntent->mnt_type, "overlay", 7))
1938 ret = ovl_mkdir(mntent, rootfs, lxc_name, lxc_path);
1939 else if (!strncmp(mntent->mnt_type, "aufs", 4))
1940 ret = aufs_mkdir(mntent, rootfs, lxc_name, lxc_path);
1941 if (ret < 0)
1942 return -1;
6e46cc0d 1943
34cfffb3 1944 if (hasmntopt(mntent, "create=dir")) {
749f98d9
CB
1945 ret = mkdir_p(path, 0755);
1946 if (ret < 0 && errno != EEXIST) {
1947 SYSERROR("Failed to create directory \"%s\"", path);
1948 return -1;
34cfffb3
SG
1949 }
1950 }
1951
4d5b72a1 1952 if (hasmntopt(mntent, "create=file") && access(path, F_OK)) {
749f98d9
CB
1953 int fd;
1954 char *p1, *p2;
1955
1956 p1 = strdup(path);
1957 if (!p1)
1958 return -1;
1959
1960 p2 = dirname(p1);
1961
1962 ret = mkdir_p(p2, 0755);
1963 free(p1);
1964 if (ret < 0 && errno != EEXIST) {
1965 SYSERROR("Failed to create directory \"%s\"", path);
1966 return -1;
6e46cc0d 1967 }
749f98d9
CB
1968
1969 fd = open(path, O_CREAT, 0644);
1970 if (fd < 0)
1971 return -1;
1972 close(fd);
34cfffb3 1973 }
749f98d9
CB
1974
1975 return 0;
4d5b72a1
NC
1976}
1977
ec50007f
CB
1978/* rootfs, lxc_name, and lxc_path can be NULL when the container is created
1979 * without a rootfs. */
db4aba38 1980static inline int mount_entry_on_generic(struct mntent *mntent,
d8b712bc
CB
1981 const char *path,
1982 const struct lxc_rootfs *rootfs,
1983 const char *lxc_name,
1984 const char *lxc_path)
4d5b72a1 1985{
d8b712bc 1986 int ret;
4d5b72a1
NC
1987 unsigned long mntflags;
1988 char *mntdata;
181437fd 1989 bool dev, optional, relative;
ec50007f 1990 char *rootfs_path = NULL;
d8b712bc
CB
1991
1992 optional = hasmntopt(mntent, "optional") != NULL;
1993 dev = hasmntopt(mntent, "dev") != NULL;
181437fd 1994 relative = hasmntopt(mntent, "relative") != NULL;
d8b712bc 1995
ec50007f
CB
1996 if (rootfs && rootfs->path)
1997 rootfs_path = rootfs->mount;
1998
d8b712bc
CB
1999 ret = mount_entry_create_dir_file(mntent, path, rootfs, lxc_name,
2000 lxc_path);
2001 if (ret < 0) {
2002 if (optional)
2003 return 0;
608e3567 2004
d8b712bc
CB
2005 return -1;
2006 }
4e4ca161
SH
2007 cull_mntent_opt(mntent);
2008
d8b712bc
CB
2009 ret = parse_mntopts(mntent->mnt_opts, &mntflags, &mntdata);
2010 if (ret < 0)
a17b1e65 2011 return -1;
a17b1e65 2012
6e46cc0d 2013 ret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type, mntflags,
181437fd 2014 mntdata, optional, dev, relative, rootfs_path);
68c152ef 2015
911324ef 2016 free(mntdata);
911324ef
DL
2017 return ret;
2018}
2019
db4aba38
NC
2020static inline int mount_entry_on_systemfs(struct mntent *mntent)
2021{
1433c9f9 2022 int ret;
07667a6a 2023 char path[MAXPATHLEN];
1433c9f9
CB
2024
2025 /* For containers created without a rootfs all mounts are treated as
07667a6a
CB
2026 * absolute paths starting at / on the host.
2027 */
1433c9f9
CB
2028 if (mntent->mnt_dir[0] != '/')
2029 ret = snprintf(path, sizeof(path), "/%s", mntent->mnt_dir);
2030 else
2031 ret = snprintf(path, sizeof(path), "%s", mntent->mnt_dir);
07667a6a 2032 if (ret < 0 || ret >= sizeof(path))
1433c9f9 2033 return -1;
1433c9f9
CB
2034
2035 return mount_entry_on_generic(mntent, path, NULL, NULL, NULL);
db4aba38
NC
2036}
2037
4e4ca161 2038static int mount_entry_on_absolute_rootfs(struct mntent *mntent,
80a881b2 2039 const struct lxc_rootfs *rootfs,
0a2dddd4
CB
2040 const char *lxc_name,
2041 const char *lxc_path)
911324ef 2042{
bdd2b34c 2043 int offset;
013bd428 2044 char *aux;
67e571de 2045 const char *lxcpath;
bdd2b34c
CB
2046 char path[MAXPATHLEN];
2047 int ret = 0;
0ad19a3f 2048
593e8478 2049 lxcpath = lxc_global_config_value("lxc.lxcpath");
bdd2b34c 2050 if (!lxcpath)
2a59a681 2051 return -1;
2a59a681 2052
bdd2b34c
CB
2053 /* If rootfs->path is a blockdev path, allow container fstab to use
2054 * <lxcpath>/<name>/rootfs" as the target prefix.
2055 */
2056 ret = snprintf(path, MAXPATHLEN, "%s/%s/rootfs", lxcpath, lxc_name);
2057 if (ret < 0 || ret >= MAXPATHLEN)
80a881b2
SH
2058 goto skipvarlib;
2059
2060 aux = strstr(mntent->mnt_dir, path);
2061 if (aux) {
2062 offset = strlen(path);
2063 goto skipabs;
2064 }
2065
2066skipvarlib:
013bd428
DL
2067 aux = strstr(mntent->mnt_dir, rootfs->path);
2068 if (!aux) {
bdd2b34c 2069 WARN("Ignoring mount point \"%s\"", mntent->mnt_dir);
db4aba38 2070 return ret;
013bd428 2071 }
80a881b2
SH
2072 offset = strlen(rootfs->path);
2073
2074skipabs:
bdd2b34c
CB
2075 ret = snprintf(path, MAXPATHLEN, "%s/%s", rootfs->mount, aux + offset);
2076 if (ret < 0 || ret >= MAXPATHLEN)
a17b1e65 2077 return -1;
a17b1e65 2078
0a2dddd4 2079 return mount_entry_on_generic(mntent, path, rootfs, lxc_name, lxc_path);
911324ef 2080}
d330fe7b 2081
4e4ca161 2082static int mount_entry_on_relative_rootfs(struct mntent *mntent,
0a2dddd4
CB
2083 const struct lxc_rootfs *rootfs,
2084 const char *lxc_name,
2085 const char *lxc_path)
911324ef
DL
2086{
2087 char path[MAXPATHLEN];
911324ef 2088 int ret;
d330fe7b 2089
34cfffb3 2090 /* relative to root mount point */
6e46cc0d 2091 ret = snprintf(path, sizeof(path), "%s/%s", rootfs->mount, mntent->mnt_dir);
1433c9f9 2092 if (ret < 0 || ret >= sizeof(path)) {
9ba8130c
SH
2093 ERROR("path name too long");
2094 return -1;
2095 }
911324ef 2096
0a2dddd4 2097 return mount_entry_on_generic(mntent, path, rootfs, lxc_name, lxc_path);
911324ef
DL
2098}
2099
06749971
CB
2100/* This logs a NOTICE() when a user specifies mounts that would conflict with
2101 * devices liblxc sets up automatically.
2102 */
2103static void log_notice_on_conflict(const struct lxc_conf *conf, const char *src,
2104 const char *dest)
2105{
2106 char *clean_mnt_fsname, *clean_mnt_dir, *tmp;
2107 bool needs_warning = false;
2108
2109 clean_mnt_fsname = lxc_deslashify(src);
2110 if (!clean_mnt_fsname)
2111 return;
2112
2113 clean_mnt_dir = lxc_deslashify(dest);
2114 if (!clean_mnt_dir) {
2115 free(clean_mnt_fsname);
2116 return;
2117 }
2118
2119 tmp = clean_mnt_dir;
2120 if (*tmp == '/')
2121 tmp++;
2122
2123 if (strncmp(src, "/dev", 4) || strncmp(tmp, "dev", 3)) {
2124 free(clean_mnt_dir);
2125 free(clean_mnt_fsname);
2126 return;
2127 }
2128
2129 if (!conf->autodev && !conf->pts && !conf->tty &&
2130 (!conf->console.path || !strcmp(conf->console.path, "none"))) {
2131 free(clean_mnt_dir);
2132 free(clean_mnt_fsname);
2133 return;
2134 }
2135
2136 if (!strcmp(tmp, "dev") && conf->autodev > 0)
2137 needs_warning = true;
2138 else if (!strcmp(tmp, "dev/pts") && (conf->autodev > 0 || conf->pts > 0))
2139 needs_warning = true;
2140 else if (!strcmp(tmp, "dev/ptmx") && (conf->autodev > 0 || conf->pts > 0))
2141 needs_warning = true;
2142 else if (!strcmp(tmp, "dev/pts/ptmx") && (conf->autodev > 0 || conf->pts > 0))
2143 needs_warning = true;
2144 else if (!strcmp(tmp, "dev/null") && conf->autodev > 0)
2145 needs_warning = true;
2146 else if (!strcmp(tmp, "dev/zero") && conf->autodev > 0)
2147 needs_warning = true;
2148 else if (!strcmp(tmp, "dev/full") && conf->autodev > 0)
2149 needs_warning = true;
2150 else if (!strcmp(tmp, "dev/urandom") && conf->autodev > 0)
2151 needs_warning = true;
2152 else if (!strcmp(tmp, "dev/random") && conf->autodev > 0)
2153 needs_warning = true;
2154 else if (!strcmp(tmp, "dev/tty") && conf->autodev > 0)
2155 needs_warning = true;
2156 else if (!strncmp(tmp, "dev/tty", 7) && (conf->autodev > 0 || conf->tty > 0))
2157 needs_warning = true;
2158
2159 if (needs_warning)
2160 NOTICE("Requesting to mount \"%s\" on \"%s\" while requesting "
2161 "automatic device setup under \"/dev\"",
2162 clean_mnt_fsname, clean_mnt_dir);
2163
2164 free(clean_mnt_dir);
2165 free(clean_mnt_fsname);
2166}
2167
2168static int mount_file_entries(const struct lxc_conf *conf,
2169 const struct lxc_rootfs *rootfs, FILE *file,
1ae3c19f 2170 const char *lxc_name, const char *lxc_path)
911324ef 2171{
aaf901be
AM
2172 struct mntent mntent;
2173 char buf[4096];
911324ef 2174 int ret = -1;
e76b8764 2175
aaf901be 2176 while (getmntent_r(file, &mntent, buf, sizeof(buf))) {
06749971
CB
2177 log_notice_on_conflict(conf, mntent.mnt_fsname, mntent.mnt_dir);
2178
1ae3c19f
CB
2179 if (!rootfs->path)
2180 ret = mount_entry_on_systemfs(&mntent);
2181 else if (mntent.mnt_dir[0] != '/')
2182 ret = mount_entry_on_relative_rootfs(&mntent, rootfs,
2183 lxc_name, lxc_path);
2184 else
2185 ret = mount_entry_on_absolute_rootfs(&mntent, rootfs,
2186 lxc_name, lxc_path);
2187 if (ret < 0)
2188 return -1;
0ad19a3f 2189 }
2190 ret = 0;
cd54d859 2191
1ae3c19f 2192 INFO("Set up mount entries");
e7938e9e
MN
2193 return ret;
2194}
2195
06749971
CB
2196static int setup_mount(const struct lxc_conf *conf,
2197 const struct lxc_rootfs *rootfs, const char *fstab,
42dff448 2198 const char *lxc_name, const char *lxc_path)
e7938e9e 2199{
42dff448 2200 FILE *f;
e7938e9e
MN
2201 int ret;
2202
2203 if (!fstab)
2204 return 0;
2205
42dff448
CB
2206 f = setmntent(fstab, "r");
2207 if (!f) {
2208 SYSERROR("Failed to open \"%s\"", fstab);
e7938e9e
MN
2209 return -1;
2210 }
2211
06749971 2212 ret = mount_file_entries(conf, rootfs, f, lxc_name, lxc_path);
42dff448
CB
2213 if (ret < 0)
2214 ERROR("Failed to set up mount entries");
e7938e9e 2215
42dff448 2216 endmntent(f);
0ad19a3f 2217 return ret;
2218}
2219
5ef5c9a3 2220FILE *make_anonymous_mount_file(struct lxc_list *mount)
e7938e9e 2221{
5ef5c9a3 2222 int ret;
e7938e9e 2223 char *mount_entry;
5ef5c9a3 2224 struct lxc_list *iterator;
6bd04140 2225 FILE *f;
5ef5c9a3
CB
2226 int fd = -1;
2227
2228 fd = memfd_create("lxc_mount_file", MFD_CLOEXEC);
2229 if (fd < 0) {
2230 if (errno != ENOSYS)
2231 return NULL;
6bd04140
CB
2232 f = tmpfile();
2233 TRACE("Created temporary mount file");
5ef5c9a3 2234 } else {
6bd04140
CB
2235 f = fdopen(fd, "r+");
2236 TRACE("Created anonymous mount file");
5ef5c9a3 2237 }
e7938e9e 2238
6bd04140
CB
2239 if (!f) {
2240 SYSERROR("Could not create mount file");
5ef5c9a3
CB
2241 if (fd != -1)
2242 close(fd);
9fc7f8c0 2243 return NULL;
e7938e9e
MN
2244 }
2245
2246 lxc_list_for_each(iterator, mount) {
2247 mount_entry = iterator->elem;
6bd04140 2248 ret = fprintf(f, "%s\n", mount_entry);
5ef5c9a3 2249 if (ret < strlen(mount_entry))
6bd04140 2250 WARN("Could not write mount entry to mount file");
5ef5c9a3
CB
2251 }
2252
6bd04140
CB
2253 ret = fseek(f, 0, SEEK_SET);
2254 if (ret < 0) {
2255 SYSERROR("Failed to seek mount file");
2256 fclose(f);
5ef5c9a3 2257 return NULL;
e7938e9e
MN
2258 }
2259
6bd04140 2260 return f;
9fc7f8c0
TA
2261}
2262
06749971
CB
2263static int setup_mount_entries(const struct lxc_conf *conf,
2264 const struct lxc_rootfs *rootfs,
5ef5c9a3
CB
2265 struct lxc_list *mount, const char *lxc_name,
2266 const char *lxc_path)
9fc7f8c0 2267{
19b5d755 2268 FILE *f;
9fc7f8c0
TA
2269 int ret;
2270
19b5d755
CB
2271 f = make_anonymous_mount_file(mount);
2272 if (!f)
9fc7f8c0 2273 return -1;
e7938e9e 2274
06749971 2275 ret = mount_file_entries(conf, rootfs, f, lxc_name, lxc_path);
e7938e9e 2276
19b5d755 2277 fclose(f);
e7938e9e
MN
2278 return ret;
2279}
2280
bab88e68
CS
2281static int parse_cap(const char *cap)
2282{
2283 char *ptr = NULL;
84760c11 2284 size_t i;
2285 int capid = -1;
bab88e68 2286
7035407c
DE
2287 if (!strcmp(cap, "none"))
2288 return -2;
2289
bab88e68
CS
2290 for (i = 0; i < sizeof(caps_opt)/sizeof(caps_opt[0]); i++) {
2291
2292 if (strcmp(cap, caps_opt[i].name))
2293 continue;
2294
2295 capid = caps_opt[i].value;
2296 break;
2297 }
2298
2299 if (capid < 0) {
2300 /* try to see if it's numeric, so the user may specify
2301 * capabilities that the running kernel knows about but
2302 * we don't */
2303 errno = 0;
2304 capid = strtol(cap, &ptr, 10);
2305 if (!ptr || *ptr != '\0' || errno != 0)
2306 /* not a valid number */
2307 capid = -1;
2308 else if (capid > lxc_caps_last_cap())
2309 /* we have a number but it's not a valid
2310 * capability */
2311 capid = -1;
2312 }
2313
2314 return capid;
2315}
2316
0769b82a
CS
2317int in_caplist(int cap, struct lxc_list *caps)
2318{
2319 struct lxc_list *iterator;
2320 int capid;
2321
2322 lxc_list_for_each(iterator, caps) {
2323 capid = parse_cap(iterator->elem);
2324 if (capid == cap)
2325 return 1;
2326 }
2327
2328 return 0;
2329}
2330
81810dd1
DL
2331static int setup_caps(struct lxc_list *caps)
2332{
2333 struct lxc_list *iterator;
2334 char *drop_entry;
bab88e68 2335 int capid;
81810dd1
DL
2336
2337 lxc_list_for_each(iterator, caps) {
2338
2339 drop_entry = iterator->elem;
2340
bab88e68 2341 capid = parse_cap(drop_entry);
d55bc1ad 2342
81810dd1 2343 if (capid < 0) {
1e11be34
DL
2344 ERROR("unknown capability %s", drop_entry);
2345 return -1;
81810dd1
DL
2346 }
2347
2348 DEBUG("drop capability '%s' (%d)", drop_entry, capid);
2349
2350 if (prctl(PR_CAPBSET_DROP, capid, 0, 0, 0)) {
3ec1648d
SH
2351 SYSERROR("failed to remove %s capability", drop_entry);
2352 return -1;
2353 }
81810dd1
DL
2354
2355 }
2356
1fb86a7c
SH
2357 DEBUG("capabilities have been setup");
2358
2359 return 0;
2360}
2361
2362static int dropcaps_except(struct lxc_list *caps)
2363{
2364 struct lxc_list *iterator;
2365 char *keep_entry;
1fb86a7c
SH
2366 int i, capid;
2367 int numcaps = lxc_caps_last_cap() + 1;
959aee9c 2368 INFO("found %d capabilities", numcaps);
1fb86a7c 2369
2caf9a97
SH
2370 if (numcaps <= 0 || numcaps > 200)
2371 return -1;
2372
1a0e70ac 2373 /* caplist[i] is 1 if we keep capability i */
1fb86a7c
SH
2374 int *caplist = alloca(numcaps * sizeof(int));
2375 memset(caplist, 0, numcaps * sizeof(int));
2376
2377 lxc_list_for_each(iterator, caps) {
2378
2379 keep_entry = iterator->elem;
2380
bab88e68 2381 capid = parse_cap(keep_entry);
1fb86a7c 2382
7035407c
DE
2383 if (capid == -2)
2384 continue;
2385
1fb86a7c
SH
2386 if (capid < 0) {
2387 ERROR("unknown capability %s", keep_entry);
2388 return -1;
2389 }
2390
8255688a 2391 DEBUG("keep capability '%s' (%d)", keep_entry, capid);
1fb86a7c
SH
2392
2393 caplist[capid] = 1;
2394 }
2395 for (i=0; i<numcaps; i++) {
2396 if (caplist[i])
2397 continue;
2398 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0)) {
3ec1648d
SH
2399 SYSERROR("failed to remove capability %d", i);
2400 return -1;
2401 }
1fb86a7c
SH
2402 }
2403
2404 DEBUG("capabilities have been setup");
81810dd1
DL
2405
2406 return 0;
2407}
2408
c6d09e15
WB
2409static int parse_resource(const char *res) {
2410 size_t i;
2411 int resid = -1;
2412
2413 for (i = 0; i < sizeof(limit_opt)/sizeof(limit_opt[0]); ++i) {
2414 if (strcmp(res, limit_opt[i].name) == 0)
2415 return limit_opt[i].value;
2416 }
2417
2418 /* try to see if it's numeric, so the user may specify
2419 * resources that the running kernel knows about but
2420 * we don't */
2421 if (lxc_safe_int(res, &resid) == 0)
2422 return resid;
2423 return -1;
2424}
2425
2426int setup_resource_limits(struct lxc_list *limits, pid_t pid) {
2427 struct lxc_list *it;
2428 struct lxc_limit *lim;
2429 int resid;
2430
2431 lxc_list_for_each(it, limits) {
2432 lim = it->elem;
2433
2434 resid = parse_resource(lim->resource);
2435 if (resid < 0) {
2436 ERROR("unknown resource %s", lim->resource);
2437 return -1;
2438 }
2439
f48b5fd8 2440#if HAVE_PRLIMIT || HAVE_PRLIMIT64
c6d09e15
WB
2441 if (prlimit(pid, resid, &lim->limit, NULL) != 0) {
2442 ERROR("failed to set limit %s: %s", lim->resource, strerror(errno));
2443 return -1;
2444 }
f48b5fd8
FF
2445#else
2446 ERROR("Cannot set limit %s as prlimit is missing", lim->resource);
2447 return -1;
2448#endif
c6d09e15
WB
2449 }
2450 return 0;
2451}
2452
7edd0540
L
2453int setup_sysctl_parameters(struct lxc_list *sysctls)
2454{
2455 struct lxc_list *it;
2456 struct lxc_sysctl *elem;
2457 char *tmp = NULL;
2458 char filename[MAXPATHLEN] = {0};
2459 int ret = 0;
2460
2461 lxc_list_for_each(it, sysctls) {
2462 elem = it->elem;
2463 tmp = lxc_string_replace(".", "/", elem->key);
2464 if (!tmp) {
2465 ERROR("Failed to replace key %s", elem->key);
2466 return -1;
2467 }
2468
2469 ret = snprintf(filename, sizeof(filename), "/proc/sys/%s", tmp);
2470 free(tmp);
2471 if (ret < 0 || (size_t)ret >= sizeof(filename)) {
2472 ERROR("Error setting up sysctl parameters path");
2473 return -1;
2474 }
2475
2476 ret = lxc_write_to_file(filename, elem->value, strlen(elem->value), false);
2477 if (ret < 0) {
2478 ERROR("Failed to setup sysctl parameters %s to %s", elem->key, elem->value);
2479 return -1;
2480 }
2481 }
2482 return 0;
2483}
2484
61d7a733
YT
2485int setup_proc_filesystem(struct lxc_list *procs, pid_t pid)
2486{
2487 struct lxc_list *it;
2488 struct lxc_proc *elem;
2489 char *tmp = NULL;
2490 char filename[MAXPATHLEN] = {0};
2491 int ret = 0;
2492
2493 lxc_list_for_each(it, procs) {
2494 elem = it->elem;
2495 tmp = lxc_string_replace(".", "/", elem->filename);
2496 if (!tmp) {
2497 ERROR("Failed to replace key %s", elem->filename);
2498 return -1;
2499 }
2500
2501 ret = snprintf(filename, sizeof(filename), "/proc/%d/%s", pid, tmp);
2502 free(tmp);
2503 if (ret < 0 || (size_t)ret >= sizeof(filename)) {
2504 ERROR("Error setting up proc filesystem path");
2505 return -1;
2506 }
2507
2508 ret = lxc_write_to_file(filename, elem->value, strlen(elem->value), false);
2509 if (ret < 0) {
2510 ERROR("Failed to setup proc filesystem %s to %s", elem->filename, elem->value);
2511 return -1;
2512 }
2513 }
2514 return 0;
2515}
2516
ae9242c8
SH
2517static char *default_rootfs_mount = LXCROOTFSMOUNT;
2518
7b379ab3 2519struct lxc_conf *lxc_conf_init(void)
089cd8b8 2520{
7b379ab3 2521 struct lxc_conf *new;
26ddeedd 2522 int i;
7b379ab3 2523
13277ec4 2524 new = malloc(sizeof(*new));
7b379ab3 2525 if (!new) {
13277ec4 2526 ERROR("lxc_conf_init : %s", strerror(errno));
7b379ab3
MN
2527 return NULL;
2528 }
2529 memset(new, 0, sizeof(*new));
2530
4b73005c 2531 new->loglevel = LXC_LOG_LEVEL_NOTSET;
cccc74b5 2532 new->personality = -1;
124fa0a8 2533 new->autodev = 1;
3a784510
CB
2534 new->console.buffer_log_file = NULL;
2535 new->console.buffer_log_file_fd = -1;
2536 new->console.buffer_size = 0;
596a818d
DE
2537 new->console.log_path = NULL;
2538 new->console.log_fd = -1;
28a4b0e5 2539 new->console.path = NULL;
63376d7d 2540 new->console.peer = -1;
b5159817
DE
2541 new->console.peerpty.busy = -1;
2542 new->console.peerpty.master = -1;
2543 new->console.peerpty.slave = -1;
63376d7d
DL
2544 new->console.master = -1;
2545 new->console.slave = -1;
2546 new->console.name[0] = '\0';
732375f5 2547 memset(&new->console.ringbuf, 0, sizeof(struct lxc_ringbuf));
d2e30e99 2548 new->maincmd_fd = -1;
76a26f55 2549 new->nbd_idx = -1;
54c30e29 2550 new->rootfs.mount = strdup(default_rootfs_mount);
53f3f048 2551 if (!new->rootfs.mount) {
13277ec4 2552 ERROR("lxc_conf_init : %s", strerror(errno));
53f3f048
SH
2553 free(new);
2554 return NULL;
2555 }
858377e4 2556 new->logfd = -1;
7b379ab3 2557 lxc_list_init(&new->cgroup);
54860ed0 2558 lxc_list_init(&new->cgroup2);
7b379ab3
MN
2559 lxc_list_init(&new->network);
2560 lxc_list_init(&new->mount_list);
81810dd1 2561 lxc_list_init(&new->caps);
1fb86a7c 2562 lxc_list_init(&new->keepcaps);
f6d3e3e4 2563 lxc_list_init(&new->id_map);
46ad64ab
CB
2564 new->root_nsuid_map = NULL;
2565 new->root_nsgid_map = NULL;
f979ac15 2566 lxc_list_init(&new->includes);
4184c3e1 2567 lxc_list_init(&new->aliens);
7c661726 2568 lxc_list_init(&new->environment);
c6d09e15 2569 lxc_list_init(&new->limits);
7edd0540 2570 lxc_list_init(&new->sysctls);
61d7a733 2571 lxc_list_init(&new->procs);
44ae0fb6 2572 new->hooks_version = 0;
28d9e29e 2573 for (i = 0; i < NUM_LXC_HOOKS; i++)
26ddeedd 2574 lxc_list_init(&new->hooks[i]);
ee1e7aa0 2575 lxc_list_init(&new->groups);
d39b10eb 2576 lxc_list_init(&new->state_clients);
fe4de9a6
DE
2577 new->lsm_aa_profile = NULL;
2578 new->lsm_se_context = NULL;
5112cd70 2579 new->tmp_umount_proc = 0;
7b379ab3 2580
72bb04e4
PT
2581 /* if running in a new user namespace, init and COMMAND
2582 * default to running as UID/GID 0 when using lxc-execute */
2583 new->init_uid = 0;
2584 new->init_gid = 0;
43654d34 2585 memset(&new->cgroup_meta, 0, sizeof(struct lxc_cgroup));
b074bbf1 2586 memset(&new->ns_share, 0, sizeof(char *) * LXC_NS_MAX);
72bb04e4 2587
7b379ab3 2588 return new;
089cd8b8
DL
2589}
2590
344c9d81 2591int write_id_mapping(enum idtype idtype, pid_t pid, const char *buf,
a19b974f 2592 size_t buf_size)
f6d3e3e4 2593{
29053180
CB
2594 char path[MAXPATHLEN];
2595 int fd, ret;
f6d3e3e4 2596
a19b974f
CB
2597 if (geteuid() != 0 && idtype == ID_TYPE_GID) {
2598 size_t buflen;
2599
2600 ret = snprintf(path, MAXPATHLEN, "/proc/%d/setgroups", pid);
2601 if (ret < 0 || ret >= MAXPATHLEN) {
2602 ERROR("Failed to create string");
2603 return -E2BIG;
2604 }
2605
2606 fd = open(path, O_WRONLY);
2607 if (fd < 0 && errno != ENOENT) {
2608 SYSERROR("Failed to open \"%s\"", path);
2609 return -1;
2610 }
2611
2388737b
CB
2612 if (fd >= 0) {
2613 buflen = sizeof("deny\n") - 1;
2614 errno = 0;
2615 ret = lxc_write_nointr(fd, "deny\n", buflen);
2616 if (ret != buflen) {
2617 SYSERROR("Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid);
2618 close(fd);
2619 return -1;
2620 }
a19b974f 2621 close(fd);
a19b974f 2622 }
a19b974f
CB
2623 }
2624
29053180
CB
2625 ret = snprintf(path, MAXPATHLEN, "/proc/%d/%cid_map", pid,
2626 idtype == ID_TYPE_UID ? 'u' : 'g');
2627 if (ret < 0 || ret >= MAXPATHLEN) {
a19b974f 2628 ERROR("Failed to create string");
f6d3e3e4
SH
2629 return -E2BIG;
2630 }
29053180
CB
2631
2632 fd = open(path, O_WRONLY);
2633 if (fd < 0) {
a19b974f 2634 SYSERROR("Failed to open \"%s\"", path);
29053180 2635 return -1;
f6d3e3e4 2636 }
29053180
CB
2637
2638 errno = 0;
2639 ret = lxc_write_nointr(fd, buf, buf_size);
2640 if (ret != buf_size) {
a19b974f 2641 SYSERROR("Failed to write %cid mapping to \"%s\"",
29053180
CB
2642 idtype == ID_TYPE_UID ? 'u' : 'g', path);
2643 close(fd);
2644 return -1;
2645 }
2646 close(fd);
2647
2648 return 0;
f6d3e3e4
SH
2649}
2650
6e50e704
CB
2651/* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2652 *
2653 * @return 1 if functional binary was found
2654 * @return 0 if binary exists but is lacking privilege
2655 * @return -ENOENT if binary does not exist
2656 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2657 *
2658 */
df6a2945
CB
2659static int idmaptool_on_path_and_privileged(const char *binary, cap_value_t cap)
2660{
2661 char *path;
2662 int ret;
2663 struct stat st;
2664 int fret = 0;
2665
6e50e704
CB
2666 if (cap != CAP_SETUID && cap != CAP_SETGID)
2667 return -EINVAL;
2668
df6a2945
CB
2669 path = on_path(binary, NULL);
2670 if (!path)
2671 return -ENOENT;
2672
2673 ret = stat(path, &st);
2674 if (ret < 0) {
2675 fret = -errno;
2676 goto cleanup;
2677 }
2678
2679 /* Check if the binary is setuid. */
2680 if (st.st_mode & S_ISUID) {
2681 DEBUG("The binary \"%s\" does have the setuid bit set.", path);
2682 fret = 1;
2683 goto cleanup;
2684 }
2685
69924fff 2686 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
df6a2945
CB
2687 /* Check if it has the CAP_SETUID capability. */
2688 if ((cap & CAP_SETUID) &&
2689 lxc_file_cap_is_set(path, CAP_SETUID, CAP_EFFECTIVE) &&
2690 lxc_file_cap_is_set(path, CAP_SETUID, CAP_PERMITTED)) {
2691 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2692 "and CAP_PERMITTED sets.", path);
2693 fret = 1;
2694 goto cleanup;
2695 }
2696
2697 /* Check if it has the CAP_SETGID capability. */
2698 if ((cap & CAP_SETGID) &&
2699 lxc_file_cap_is_set(path, CAP_SETGID, CAP_EFFECTIVE) &&
2700 lxc_file_cap_is_set(path, CAP_SETGID, CAP_PERMITTED)) {
2701 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2702 "and CAP_PERMITTED sets.", path);
2703 fret = 1;
2704 goto cleanup;
2705 }
d6018f88 2706 #else
69924fff
CB
2707 /* If we cannot check for file capabilities we need to give the benefit
2708 * of the doubt. Otherwise we might fail even though all the necessary
2709 * file capabilities are set.
2710 */
d6018f88
CB
2711 DEBUG("Cannot check for file capabilites as full capability support is "
2712 "missing. Manual intervention needed.");
2713 fret = 1;
df6a2945
CB
2714 #endif
2715
2716cleanup:
2717 free(path);
2718 return fret;
2719}
2720
986ef930
CB
2721int lxc_map_ids_exec_wrapper(void *args)
2722{
2723 execl("/bin/sh", "sh", "-c", (char *)args, (char *)NULL);
2724 return -1;
2725}
2726
f6d3e3e4
SH
2727int lxc_map_ids(struct lxc_list *idmap, pid_t pid)
2728{
f6d3e3e4 2729 struct id_map *map;
4bc3b759 2730 struct lxc_list *iterator;
251d0d2a 2731 enum idtype type;
986ef930 2732 char u_or_g;
4bc3b759 2733 char *pos;
99d43365 2734 int fill, left;
986ef930
CB
2735 char cmd_output[MAXPATHLEN];
2736 /* strlen("new@idmap") = 9
2737 * +
2738 * strlen(" ") = 1
2739 * +
2740 * LXC_NUMSTRLEN64
2741 * +
2742 * strlen(" ") = 1
2743 *
2744 * We add some additional space to make sure that we really have
2745 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2746 */
2747 char mapbuf[9 + 1 + LXC_NUMSTRLEN64 + 1 + LXC_IDMAPLEN] = {0};
2748 int ret = 0, uidmap = 0, gidmap = 0;
2749 bool use_shadow = false, had_entry = false;
df6a2945
CB
2750
2751 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2752 * ranges, then insist that root also reserve ranges in subuid. This
22038de5
SH
2753 * will protected it by preventing another user from being handed the
2754 * range by shadow.
2755 */
df6a2945 2756 uidmap = idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID);
6e50e704
CB
2757 if (uidmap == -ENOENT)
2758 WARN("newuidmap binary is missing");
2759 else if (!uidmap)
2760 WARN("newuidmap is lacking necessary privileges");
2761
df6a2945 2762 gidmap = idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID);
6e50e704
CB
2763 if (gidmap == -ENOENT)
2764 WARN("newgidmap binary is missing");
2765 else if (!gidmap)
2766 WARN("newgidmap is lacking necessary privileges");
2767
df6a2945
CB
2768 if (uidmap > 0 && gidmap > 0) {
2769 DEBUG("Functional newuidmap and newgidmap binary found.");
4bc3b759 2770 use_shadow = true;
df6a2945 2771 } else {
99d43365
CB
2772 /* In case unprivileged users run application containers via
2773 * execute() or a start*() there are valid cases where they may
2774 * only want to map their own {g,u}id. Let's not block them from
2775 * doing so by requiring geteuid() == 0.
2776 */
2777 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2778 "write directly with euid %d.", geteuid());
0e6e3a41 2779 }
251d0d2a 2780
986ef930
CB
2781 for (type = ID_TYPE_UID, u_or_g = 'u'; type <= ID_TYPE_GID;
2782 type++, u_or_g = 'g') {
2783 pos = mapbuf;
2784
0e6e3a41 2785 if (use_shadow)
986ef930 2786 pos += sprintf(mapbuf, "new%cidmap %d", u_or_g, pid);
4f7521b4 2787
cf3ef16d 2788 lxc_list_for_each(iterator, idmap) {
251d0d2a 2789 map = iterator->elem;
cf3ef16d
SH
2790 if (map->idtype != type)
2791 continue;
2792
4bc3b759
CB
2793 had_entry = true;
2794
986ef930 2795 left = LXC_IDMAPLEN - (pos - mapbuf);
d1838f34 2796 fill = snprintf(pos, left, "%s%lu %lu %lu%s",
4bc3b759
CB
2797 use_shadow ? " " : "", map->nsid,
2798 map->hostid, map->range,
0e6e3a41 2799 use_shadow ? "" : "\n");
a427e268
CB
2800 if (fill <= 0 || fill >= left) {
2801 /* The kernel only takes <= 4k for writes to
2802 * /proc/<pid>/{g,u}id_map
2803 */
2804 SYSERROR("Too many %cid mappings defined", u_or_g);
2805 return -1;
2806 }
4bc3b759 2807
cf3ef16d 2808 pos += fill;
251d0d2a 2809 }
cf3ef16d 2810 if (!had_entry)
4f7521b4 2811 continue;
cf3ef16d 2812
986ef930
CB
2813 /* Try to catch the ouput of new{g,u}idmap to make debugging
2814 * easier.
2815 */
2816 if (use_shadow) {
2817 ret = run_command(cmd_output, sizeof(cmd_output),
2818 lxc_map_ids_exec_wrapper,
2819 (void *)mapbuf);
2820 if (ret < 0) {
54fbbeb5
CB
2821 ERROR("new%cidmap failed to write mapping \"%s\": %s",
2822 u_or_g, cmd_output, mapbuf);
986ef930
CB
2823 return -1;
2824 }
54fbbeb5 2825 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g, mapbuf);
d1838f34 2826 } else {
986ef930 2827 ret = write_id_mapping(type, pid, mapbuf, pos - mapbuf);
54fbbeb5 2828 if (ret < 0) {
da0f9977 2829 ERROR("Failed to write mapping: %s", mapbuf);
986ef930 2830 return -1;
54fbbeb5
CB
2831 }
2832 TRACE("Wrote mapping \"%s\"", mapbuf);
d1838f34 2833 }
986ef930
CB
2834
2835 memset(mapbuf, 0, sizeof(mapbuf));
f6d3e3e4 2836 }
251d0d2a 2837
986ef930 2838 return 0;
f6d3e3e4
SH
2839}
2840
cf3ef16d 2841/*
7b50c609
TS
2842 * return the host uid/gid to which the container root is mapped in
2843 * *val.
0b3a6504 2844 * Return true if id was found, false otherwise.
cf3ef16d 2845 */
2a9a80cb 2846bool get_mapped_rootid(struct lxc_conf *conf, enum idtype idtype,
4160c3a0 2847 unsigned long *val)
cf3ef16d
SH
2848{
2849 struct lxc_list *it;
2850 struct id_map *map;
4160c3a0
CB
2851 unsigned nsid;
2852
2853 if (idtype == ID_TYPE_UID)
2854 nsid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
2855 else
2856 nsid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
cf3ef16d
SH
2857
2858 lxc_list_for_each(it, &conf->id_map) {
2859 map = it->elem;
7b50c609 2860 if (map->idtype != idtype)
cf3ef16d 2861 continue;
4160c3a0 2862 if (map->nsid != nsid)
cf3ef16d 2863 continue;
2a9a80cb
SH
2864 *val = map->hostid;
2865 return true;
cf3ef16d 2866 }
4160c3a0 2867
2a9a80cb 2868 return false;
cf3ef16d
SH
2869}
2870
2133f58c 2871int mapped_hostid(unsigned id, struct lxc_conf *conf, enum idtype idtype)
cf3ef16d
SH
2872{
2873 struct lxc_list *it;
2874 struct id_map *map;
2875 lxc_list_for_each(it, &conf->id_map) {
2876 map = it->elem;
2133f58c 2877 if (map->idtype != idtype)
cf3ef16d
SH
2878 continue;
2879 if (id >= map->hostid && id < map->hostid + map->range)
57d116ab 2880 return (id - map->hostid) + map->nsid;
cf3ef16d 2881 }
57d116ab 2882 return -1;
cf3ef16d
SH
2883}
2884
339efad9 2885int find_unmapped_nsid(struct lxc_conf *conf, enum idtype idtype)
cf3ef16d
SH
2886{
2887 struct lxc_list *it;
2888 struct id_map *map;
2133f58c 2889 unsigned int freeid = 0;
cf3ef16d
SH
2890again:
2891 lxc_list_for_each(it, &conf->id_map) {
2892 map = it->elem;
2133f58c 2893 if (map->idtype != idtype)
cf3ef16d
SH
2894 continue;
2895 if (freeid >= map->nsid && freeid < map->nsid + map->range) {
2896 freeid = map->nsid + map->range;
2897 goto again;
2898 }
2899 }
2900 return freeid;
2901}
2902
f4f52cb5
CB
2903int chown_mapped_root_exec_wrapper(void *args)
2904{
2905 execvp("lxc-usernsexec", args);
2906 return -1;
2907}
2908
f6d3e3e4 2909/*
7b50c609
TS
2910 * chown_mapped_root: for an unprivileged user with uid/gid X to
2911 * chown a dir to subuid/subgid Y, he needs to run chown as root
2912 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
2913 * nsid Y is mapped to hostuid/hostgid X. That way, the container
2914 * root is privileged with respect to hostuid/hostgid X, allowing
2915 * him to do the chown.
f6d3e3e4 2916 */
41dc7155 2917int chown_mapped_root(const char *path, struct lxc_conf *conf)
f6d3e3e4 2918{
f4f52cb5 2919 uid_t rootuid, rootgid;
2a9a80cb 2920 unsigned long val;
f4f52cb5
CB
2921 int hostuid, hostgid, ret;
2922 struct stat sb;
2923 char map1[100], map2[100], map3[100], map4[100], map5[100];
2924 char ugid[100];
41dc7155 2925 const char *args1[] = {"lxc-usernsexec",
f4f52cb5
CB
2926 "-m", map1,
2927 "-m", map2,
2928 "-m", map3,
2929 "-m", map5,
2930 "--", "chown", ugid, path,
2931 NULL};
41dc7155 2932 const char *args2[] = {"lxc-usernsexec",
f4f52cb5
CB
2933 "-m", map1,
2934 "-m", map2,
2935 "-m", map3,
2936 "-m", map4,
2937 "-m", map5,
2938 "--", "chown", ugid, path,
2939 NULL};
2940 char cmd_output[MAXPATHLEN];
2941
2942 hostuid = geteuid();
2943 hostgid = getegid();
f6d3e3e4 2944
2a9a80cb 2945 if (!get_mapped_rootid(conf, ID_TYPE_UID, &val)) {
bc80f098 2946 ERROR("No uid mapping for container root");
c4d10a05 2947 return -1;
f6d3e3e4 2948 }
f4f52cb5 2949 rootuid = (uid_t)val;
7b50c609 2950 if (!get_mapped_rootid(conf, ID_TYPE_GID, &val)) {
bc80f098 2951 ERROR("No gid mapping for container root");
7b50c609
TS
2952 return -1;
2953 }
f4f52cb5 2954 rootgid = (gid_t)val;
2a9a80cb 2955
f4f52cb5 2956 if (hostuid == 0) {
7b50c609 2957 if (chown(path, rootuid, rootgid) < 0) {
c4d10a05
SH
2958 ERROR("Error chowning %s", path);
2959 return -1;
2960 }
2961 return 0;
2962 }
f3d7e4ca 2963
f4f52cb5 2964 if (rootuid == hostuid) {
1a0e70ac 2965 /* nothing to do */
b103ceac 2966 INFO("Container root is our uid; no need to chown");
f3d7e4ca
SH
2967 return 0;
2968 }
2969
bbdbf8f0 2970 /* save the current gid of "path" */
f4f52cb5
CB
2971 if (stat(path, &sb) < 0) {
2972 ERROR("Error stat %s", path);
f6d3e3e4
SH
2973 return -1;
2974 }
7b50c609 2975
bbdbf8f0
CB
2976 /* Update the path argument in case this was overlayfs. */
2977 args1[sizeof(args1) / sizeof(args1[0]) - 2] = path;
2978 args2[sizeof(args2) / sizeof(args2[0]) - 2] = path;
2979
f4f52cb5
CB
2980 /*
2981 * A file has to be group-owned by a gid mapped into the
2982 * container, or the container won't be privileged over it.
2983 */
2984 DEBUG("trying to chown \"%s\" to %d", path, hostgid);
2985 if (sb.st_uid == hostuid &&
2986 mapped_hostid(sb.st_gid, conf, ID_TYPE_GID) < 0 &&
2987 chown(path, -1, hostgid) < 0) {
2988 ERROR("Failed chgrping %s", path);
2989 return -1;
2990 }
f6d3e3e4 2991
1a0e70ac 2992 /* "u:0:rootuid:1" */
f4f52cb5
CB
2993 ret = snprintf(map1, 100, "u:0:%d:1", rootuid);
2994 if (ret < 0 || ret >= 100) {
2995 ERROR("Error uid printing map string");
2996 return -1;
2997 }
7b50c609 2998
1a0e70ac 2999 /* "u:hostuid:hostuid:1" */
f4f52cb5
CB
3000 ret = snprintf(map2, 100, "u:%d:%d:1", hostuid, hostuid);
3001 if (ret < 0 || ret >= 100) {
3002 ERROR("Error uid printing map string");
3003 return -1;
3004 }
c4d10a05 3005
1a0e70ac 3006 /* "g:0:rootgid:1" */
f4f52cb5
CB
3007 ret = snprintf(map3, 100, "g:0:%d:1", rootgid);
3008 if (ret < 0 || ret >= 100) {
3009 ERROR("Error gid printing map string");
3010 return -1;
3011 }
98e5ba51 3012
1a0e70ac 3013 /* "g:pathgid:rootgid+pathgid:1" */
f4f52cb5
CB
3014 ret = snprintf(map4, 100, "g:%d:%d:1", (gid_t)sb.st_gid,
3015 rootgid + (gid_t)sb.st_gid);
3016 if (ret < 0 || ret >= 100) {
3017 ERROR("Error gid printing map string");
3018 return -1;
3019 }
c4d10a05 3020
1a0e70ac 3021 /* "g:hostgid:hostgid:1" */
f4f52cb5
CB
3022 ret = snprintf(map5, 100, "g:%d:%d:1", hostgid, hostgid);
3023 if (ret < 0 || ret >= 100) {
3024 ERROR("Error gid printing map string");
3025 return -1;
3026 }
7b50c609 3027
1a0e70ac 3028 /* "0:pathgid" (chown) */
f4f52cb5
CB
3029 ret = snprintf(ugid, 100, "0:%d", (gid_t)sb.st_gid);
3030 if (ret < 0 || ret >= 100) {
3031 ERROR("Error owner printing format string for chown");
3032 return -1;
3033 }
7b50c609 3034
f4f52cb5
CB
3035 if (hostgid == sb.st_gid)
3036 ret = run_command(cmd_output, sizeof(cmd_output),
3037 chown_mapped_root_exec_wrapper,
3038 (void *)args1);
3039 else
3040 ret = run_command(cmd_output, sizeof(cmd_output),
3041 chown_mapped_root_exec_wrapper,
3042 (void *)args2);
3043 if (ret < 0)
3044 ERROR("lxc-usernsexec failed: %s", cmd_output);
7b50c609 3045
f4f52cb5 3046 return ret;
f6d3e3e4
SH
3047}
3048
943144d9
CB
3049/* NOTE: Must not be called from inside the container namespace! */
3050int lxc_create_tmp_proc_mount(struct lxc_conf *conf)
5112cd70
SH
3051{
3052 int mounted;
3053
943144d9 3054 mounted = lxc_mount_proc_if_needed(conf->rootfs.path ? conf->rootfs.mount : "");
5112cd70 3055 if (mounted == -1) {
943144d9 3056 SYSERROR("failed to mount /proc in the container");
01958b1f 3057 /* continue only if there is no rootfs */
943144d9 3058 if (conf->rootfs.path)
01958b1f 3059 return -1;
5112cd70 3060 } else if (mounted == 1) {
943144d9 3061 conf->tmp_umount_proc = 1;
5112cd70 3062 }
943144d9 3063
5112cd70
SH
3064 return 0;
3065}
3066
3067void tmp_proc_unmount(struct lxc_conf *lxc_conf)
3068{
3069 if (lxc_conf->tmp_umount_proc == 1) {
3070 umount("/proc");
3071 lxc_conf->tmp_umount_proc = 0;
3072 }
3073}
3074
6a0c909a 3075void remount_all_slave(void)
e995d7a2
SH
3076{
3077 /* walk /proc/mounts and change any shared entries to slave */
3078 FILE *f = fopen("/proc/self/mountinfo", "r");
3079 char *line = NULL;
3080 size_t len = 0;
3081
3082 if (!f) {
3083 SYSERROR("Failed to open /proc/self/mountinfo to mark all shared");
3084 ERROR("Continuing container startup...");
3085 return;
3086 }
3087
3088 while (getline(&line, &len, f) != -1) {
3089 char *target, *opts;
3090 target = get_field(line, 4);
3091 if (!target)
3092 continue;
3093 opts = get_field(target, 2);
3094 if (!opts)
3095 continue;
3096 null_endofword(opts);
3097 if (!strstr(opts, "shared"))
3098 continue;
3099 null_endofword(target);
3100 if (mount(NULL, target, NULL, MS_SLAVE, NULL)) {
3101 SYSERROR("Failed to make %s rslave", target);
3102 ERROR("Continuing...");
3103 }
3104 }
3105 fclose(f);
f10fad2f 3106 free(line);
e995d7a2
SH
3107}
3108
2322903b
SH
3109void lxc_execute_bind_init(struct lxc_conf *conf)
3110{
3111 int ret;
9d9c111c
SH
3112 char path[PATH_MAX], destpath[PATH_MAX], *p;
3113
3114 /* If init exists in the container, don't bind mount a static one */
3115 p = choose_init(conf->rootfs.mount);
3116 if (p) {
3117 free(p);
3118 return;
3119 }
2322903b
SH
3120
3121 ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static");
3122 if (ret < 0 || ret >= PATH_MAX) {
3123 WARN("Path name too long searching for lxc.init.static");
3124 return;
3125 }
3126
3127 if (!file_exists(path)) {
3128 INFO("%s does not exist on host", path);
3129 return;
3130 }
3131
3132 ret = snprintf(destpath, PATH_MAX, "%s%s", conf->rootfs.mount, "/init.lxc.static");
3133 if (ret < 0 || ret >= PATH_MAX) {
3134 WARN("Path name too long for container's lxc.init.static");
3135 return;
3136 }
3137
3138 if (!file_exists(destpath)) {
3139 FILE * pathfile = fopen(destpath, "wb");
3140 if (!pathfile) {
3141 SYSERROR("Failed to create mount target '%s'", destpath);
3142 return;
3143 }
3144 fclose(pathfile);
3145 }
3146
592fd47a 3147 ret = safe_mount(path, destpath, "none", MS_BIND, NULL, conf->rootfs.mount);
2322903b
SH
3148 if (ret < 0)
3149 SYSERROR("Failed to bind lxc.init.static into container");
3150 INFO("lxc.init.static bound into container at %s", path);
3151}
3152
35120d9c
SH
3153/*
3154 * This does the work of remounting / if it is shared, calling the
3155 * container pre-mount hooks, and mounting the rootfs.
3156 */
3157int do_rootfs_setup(struct lxc_conf *conf, const char *name, const char *lxcpath)
0ad19a3f 3158{
35120d9c
SH
3159 if (conf->rootfs_setup) {
3160 /*
3161 * rootfs was set up in another namespace. bind-mount it
3162 * to give us a mount in our own ns so we can pivot_root to it
3163 */
3164 const char *path = conf->rootfs.mount;
3165 if (mount(path, path, "rootfs", MS_BIND, NULL) < 0) {
3166 ERROR("Failed to bind-mount container / onto itself");
145832ba 3167 return -1;
35120d9c 3168 }
145832ba 3169 return 0;
35120d9c 3170 }
d4ef7c50 3171
e995d7a2
SH
3172 remount_all_slave();
3173
14a7b0f9 3174 if (run_lxc_hooks(name, "pre-mount", conf, NULL)) {
35120d9c
SH
3175 ERROR("failed to run pre-mount hooks for container '%s'.", name);
3176 return -1;
3177 }
3178
9aa76a17 3179 if (lxc_setup_rootfs(conf)) {
35120d9c
SH
3180 ERROR("failed to setup rootfs for '%s'", name);
3181 return -1;
3182 }
3183
3184 conf->rootfs_setup = true;
3185 return 0;
3186}
3187
1c1c7051
SH
3188static bool verify_start_hooks(struct lxc_conf *conf)
3189{
3190 struct lxc_list *it;
3191 char path[MAXPATHLEN];
3192 lxc_list_for_each(it, &conf->hooks[LXCHOOK_START]) {
3193 char *hookname = it->elem;
3194 struct stat st;
3195 int ret;
3196
3197 ret = snprintf(path, MAXPATHLEN, "%s%s",
7b6753e7 3198 conf->rootfs.path ? conf->rootfs.mount : "", hookname);
1c1c7051
SH
3199 if (ret < 0 || ret >= MAXPATHLEN)
3200 return false;
3201 ret = stat(path, &st);
3202 if (ret) {
7b6753e7 3203 SYSERROR("Start hook %s not found in container",
1c1c7051
SH
3204 hookname);
3205 return false;
3206 }
6a0c909a 3207 return true;
1c1c7051
SH
3208 }
3209
3210 return true;
3211}
3212
3b988b33 3213int lxc_setup(struct lxc_handler *handler)
35120d9c 3214{
2187efd3 3215 int ret;
35120d9c
SH
3216 const char *name = handler->name;
3217 struct lxc_conf *lxc_conf = handler->conf;
3218 const char *lxcpath = handler->lxcpath;
35120d9c
SH
3219
3220 if (do_rootfs_setup(lxc_conf, name, lxcpath) < 0) {
3221 ERROR("Error setting up rootfs mount after spawn");
3222 return -1;
3223 }
3224
28d9e29e 3225 if (handler->nsfd[LXC_NS_UTS] == -1) {
6c544cb3
MM
3226 if (setup_utsname(lxc_conf->utsname)) {
3227 ERROR("failed to setup the utsname for '%s'", name);
3228 return -1;
3229 }
0ad19a3f 3230 }
3231
811ef482 3232 if (lxc_setup_network_in_child_namespaces(lxc_conf, &lxc_conf->network)) {
36eb9bde 3233 ERROR("failed to setup the network for '%s'", name);
95b5ffaf 3234 return -1;
0ad19a3f 3235 }
3236
790255cf
CB
3237 if (lxc_network_send_name_and_ifindex_to_parent(handler) < 0) {
3238 ERROR("Failed to network device names and ifindices to parent");
3239 return -1;
3240 }
3241
bc6928ff 3242 if (lxc_conf->autodev > 0) {
14221cbb 3243 if (mount_autodev(name, &lxc_conf->rootfs, lxcpath)) {
91c3830e 3244 ERROR("failed to mount /dev in the container");
c6883f38
SH
3245 return -1;
3246 }
3247 }
3248
368bbc02
CS
3249 /* do automatic mounts (mainly /proc and /sys), but exclude
3250 * those that need to wait until other stuff has finished
3251 */
4fb3cba5 3252 if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK, handler) < 0) {
368bbc02
CS
3253 ERROR("failed to setup the automatic mounts for '%s'", name);
3254 return -1;
3255 }
3256
06749971 3257 if (setup_mount(lxc_conf, &lxc_conf->rootfs, lxc_conf->fstab, name, lxcpath)) {
36eb9bde 3258 ERROR("failed to setup the mounts for '%s'", name);
95b5ffaf 3259 return -1;
576f946d 3260 }
3261
7b6753e7 3262 /* Make sure any start hooks are in the container */
1c1c7051
SH
3263 if (!verify_start_hooks(lxc_conf))
3264 return -1;
3265
2322903b
SH
3266 if (lxc_conf->is_execute)
3267 lxc_execute_bind_init(lxc_conf);
3268
368bbc02
CS
3269 /* now mount only cgroup, if wanted;
3270 * before, /sys could not have been mounted
3271 * (is either mounted automatically or via fstab entries)
3272 */
4fb3cba5 3273 if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK, handler) < 0) {
368bbc02
CS
3274 ERROR("failed to setup the automatic mounts for '%s'", name);
3275 return -1;
3276 }
3277
14a7b0f9 3278 if (run_lxc_hooks(name, "mount", lxc_conf, NULL)) {
773fb9ca
SH
3279 ERROR("failed to run mount hooks for container '%s'.", name);
3280 return -1;
3281 }
3282
bc6928ff 3283 if (lxc_conf->autodev > 0) {
14a7b0f9 3284 if (run_lxc_hooks(name, "autodev", lxc_conf, NULL)) {
f7bee6c6
MW
3285 ERROR("failed to run autodev hooks for container '%s'.", name);
3286 return -1;
3287 }
06749971 3288
27245ff7 3289 if (lxc_fill_autodev(&lxc_conf->rootfs)) {
91c3830e
SH
3290 ERROR("failed to populate /dev in the container");
3291 return -1;
3292 }
3293 }
368bbc02 3294
181437fd
YT
3295 if (!lxc_list_empty(&lxc_conf->mount_list) && setup_mount_entries(lxc_conf, &lxc_conf->rootfs, &lxc_conf->mount_list, name, lxcpath)) {
3296 ERROR("failed to setup the mount entries for '%s'", name);
3297 return -1;
3298 }
3299
ed8704d0
CB
3300 ret = lxc_setup_console(&lxc_conf->rootfs, &lxc_conf->console,
3301 lxc_conf->ttydir);
3302 if (ret < 0) {
3303 ERROR("Failed to setup console");
95b5ffaf 3304 return -1;
6e590161 3305 }
3306
ed8704d0
CB
3307 ret = lxc_setup_dev_symlinks(&lxc_conf->rootfs);
3308 if (ret < 0) {
3309 ERROR("Failed to setup /dev symlinks");
69aa6655
DE
3310 return -1;
3311 }
3312
5112cd70 3313 /* mount /proc if it's not already there */
943144d9 3314 if (lxc_create_tmp_proc_mount(lxc_conf) < 0) {
fe4de9a6 3315 ERROR("failed to LSM mount proc for '%s'", name);
e075f5d9 3316 return -1;
e075f5d9 3317 }
e075f5d9 3318
ac778708 3319 if (setup_pivot_root(&lxc_conf->rootfs)) {
36eb9bde 3320 ERROR("failed to set rootfs for '%s'", name);
95b5ffaf 3321 return -1;
ed502555 3322 }
3323
f4900711 3324 if (lxc_setup_devpts(lxc_conf)) {
36eb9bde 3325 ERROR("failed to setup the new pts instance");
95b5ffaf 3326 return -1;
3c26f34e 3327 }
3328
2187efd3
CB
3329 ret = lxc_create_ttys(handler);
3330 if (ret < 0)
e8bd4e43 3331 return -1;
e8bd4e43 3332
cccc74b5
DL
3333 if (setup_personality(lxc_conf->personality)) {
3334 ERROR("failed to setup personality");
3335 return -1;
3336 }
3337
7edd0540
L
3338 /* set sysctl value to a path under /proc/sys as determined from the key.
3339 * For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
3340 */
3341 if (!lxc_list_empty(&lxc_conf->sysctls)) {
3342 ret = setup_sysctl_parameters(&lxc_conf->sysctls);
3343 if (ret < 0)
3344 return -1;
3345 }
3346
97a8f74f
SG
3347 if (!lxc_list_empty(&lxc_conf->keepcaps)) {
3348 if (!lxc_list_empty(&lxc_conf->caps)) {
7389ca26 3349 ERROR("Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both.");
f6d3e3e4
SH
3350 return -1;
3351 }
97a8f74f
SG
3352 if (dropcaps_except(&lxc_conf->keepcaps)) {
3353 ERROR("failed to keep requested caps");
3354 return -1;
3355 }
3356 } else if (setup_caps(&lxc_conf->caps)) {
3357 ERROR("failed to drop capabilities");
3358 return -1;
81810dd1
DL
3359 }
3360
f4152036 3361 NOTICE("Container \"%s\" is set up", name);
cd54d859 3362
0ad19a3f 3363 return 0;
3364}
26ddeedd 3365
3f60c2f7 3366int run_lxc_hooks(const char *name, char *hookname, struct lxc_conf *conf,
14a7b0f9 3367 char *argv[])
26ddeedd 3368{
26ddeedd 3369 struct lxc_list *it;
3f60c2f7 3370 int which = -1;
26ddeedd 3371
3f60c2f7 3372 if (strcmp(hookname, "pre-start") == 0)
26ddeedd 3373 which = LXCHOOK_PRESTART;
3f60c2f7 3374 else if (strcmp(hookname, "start-host") == 0)
08dd2805 3375 which = LXCHOOK_START_HOST;
3f60c2f7 3376 else if (strcmp(hookname, "pre-mount") == 0)
5ea6163a 3377 which = LXCHOOK_PREMOUNT;
3f60c2f7 3378 else if (strcmp(hookname, "mount") == 0)
26ddeedd 3379 which = LXCHOOK_MOUNT;
3f60c2f7 3380 else if (strcmp(hookname, "autodev") == 0)
f7bee6c6 3381 which = LXCHOOK_AUTODEV;
3f60c2f7 3382 else if (strcmp(hookname, "start") == 0)
26ddeedd 3383 which = LXCHOOK_START;
3f60c2f7 3384 else if (strcmp(hookname, "stop") == 0)
52492063 3385 which = LXCHOOK_STOP;
3f60c2f7 3386 else if (strcmp(hookname, "post-stop") == 0)
26ddeedd 3387 which = LXCHOOK_POSTSTOP;
3f60c2f7 3388 else if (strcmp(hookname, "clone") == 0)
148e91f5 3389 which = LXCHOOK_CLONE;
3f60c2f7 3390 else if (strcmp(hookname, "destroy") == 0)
37cf711b 3391 which = LXCHOOK_DESTROY;
26ddeedd
SH
3392 else
3393 return -1;
3f60c2f7 3394
26ddeedd
SH
3395 lxc_list_for_each(it, &conf->hooks[which]) {
3396 int ret;
3f60c2f7
CB
3397 char *hook = it->elem;
3398
3399 ret = run_script_argv(name, conf->hooks_version, "lxc", hook,
14a7b0f9 3400 hookname, argv);
3f60c2f7
CB
3401 if (ret < 0)
3402 return -1;
26ddeedd 3403 }
3f60c2f7 3404
26ddeedd
SH
3405 return 0;
3406}
72d0e1cb 3407
72d0e1cb
SG
3408int lxc_clear_config_caps(struct lxc_conf *c)
3409{
1a0e70ac 3410 struct lxc_list *it, *next;
72d0e1cb 3411
9ebb03ad 3412 lxc_list_for_each_safe(it, &c->caps, next) {
72d0e1cb
SG
3413 lxc_list_del(it);
3414 free(it->elem);
3415 free(it);
3416 }
3417 return 0;
3418}
3419
c7e345ae
CB
3420static int lxc_free_idmap(struct lxc_list *id_map)
3421{
27c27d73
SH
3422 struct lxc_list *it, *next;
3423
4355ab5f 3424 lxc_list_for_each_safe(it, id_map, next) {
27c27d73
SH
3425 lxc_list_del(it);
3426 free(it->elem);
3427 free(it);
3428 }
c7e345ae 3429
27c27d73
SH
3430 return 0;
3431}
3432
4355ab5f
SH
3433int lxc_clear_idmaps(struct lxc_conf *c)
3434{
3435 return lxc_free_idmap(&c->id_map);
3436}
3437
1fb86a7c
SH
3438int lxc_clear_config_keepcaps(struct lxc_conf *c)
3439{
3440 struct lxc_list *it,*next;
3441
3442 lxc_list_for_each_safe(it, &c->keepcaps, next) {
3443 lxc_list_del(it);
3444 free(it->elem);
3445 free(it);
3446 }
3447 return 0;
3448}
3449
54860ed0 3450int lxc_clear_cgroups(struct lxc_conf *c, const char *key, int version)
72d0e1cb 3451{
54860ed0
CB
3452 char *global_token, *namespaced_token;
3453 struct lxc_list *it, *next, *list;
a6390f01 3454 const char *k = NULL;
54860ed0 3455 bool all = false;
72d0e1cb 3456
54860ed0
CB
3457 if (version == CGROUP2_SUPER_MAGIC) {
3458 global_token = "lxc.cgroup2";
3459 namespaced_token = "lxc.cgroup2.";
3460 list = &c->cgroup2;
3461 } else if (version == CGROUP_SUPER_MAGIC) {
3462 global_token = "lxc.cgroup";
3463 namespaced_token = "lxc.cgroup.";
3464 list = &c->cgroup;
3465 } else {
3466 return -1;
3467 }
3468
3469 if (strcmp(key, global_token) == 0)
72d0e1cb 3470 all = true;
54860ed0
CB
3471 else if (strncmp(key, namespaced_token, sizeof(namespaced_token) - 1) == 0)
3472 k = key + sizeof(namespaced_token) - 1;
a6390f01
WB
3473 else
3474 return -1;
72d0e1cb 3475
54860ed0 3476 lxc_list_for_each_safe(it, list, next) {
72d0e1cb 3477 struct lxc_cgroup *cg = it->elem;
54860ed0 3478
72d0e1cb
SG
3479 if (!all && strcmp(cg->subsystem, k) != 0)
3480 continue;
54860ed0 3481
72d0e1cb
SG
3482 lxc_list_del(it);
3483 free(cg->subsystem);
3484 free(cg->value);
3485 free(cg);
3486 free(it);
3487 }
e409b214 3488
72d0e1cb
SG
3489 return 0;
3490}
3491
c6d09e15
WB
3492int lxc_clear_limits(struct lxc_conf *c, const char *key)
3493{
3494 struct lxc_list *it, *next;
3495 bool all = false;
3496 const char *k = NULL;
3497
b668653c 3498 if (strcmp(key, "lxc.limit") == 0 || strcmp(key, "lxc.prlimit") == 0)
c6d09e15 3499 all = true;
b668653c
CB
3500 else if (strncmp(key, "lxc.limit.", sizeof("lxc.limit.") - 1) == 0)
3501 k = key + sizeof("lxc.limit.") - 1;
3502 else if (strncmp(key, "lxc.prlimit.", sizeof("lxc.prlimit.") - 1) == 0)
3503 k = key + sizeof("lxc.prlimit.") - 1;
c6d09e15
WB
3504 else
3505 return -1;
3506
3507 lxc_list_for_each_safe(it, &c->limits, next) {
3508 struct lxc_limit *lim = it->elem;
3509 if (!all && strcmp(lim->resource, k) != 0)
3510 continue;
3511 lxc_list_del(it);
3512 free(lim->resource);
3513 free(lim);
3514 free(it);
3515 }
b668653c 3516
c6d09e15
WB
3517 return 0;
3518}
3519
7edd0540
L
3520int lxc_clear_sysctls(struct lxc_conf *c, const char *key)
3521{
3522 struct lxc_list *it, *next;
3523 bool all = false;
3524 const char *k = NULL;
3525
3526 if (strcmp(key, "lxc.sysctl") == 0)
3527 all = true;
3528 else if (strncmp(key, "lxc.sysctl.", sizeof("lxc.sysctl.") - 1) == 0)
3529 k = key + sizeof("lxc.sysctl.") - 1;
3530 else
3531 return -1;
3532
3533 lxc_list_for_each_safe(it, &c->sysctls, next) {
3534 struct lxc_sysctl *elem = it->elem;
3535 if (!all && strcmp(elem->key, k) != 0)
3536 continue;
3537 lxc_list_del(it);
3538 free(elem->key);
3539 free(elem->value);
3540 free(elem);
3541 free(it);
3542 }
3543 return 0;
3544}
3545
61d7a733
YT
3546int lxc_clear_procs(struct lxc_conf *c, const char *key)
3547{
3548 struct lxc_list *it,*next;
3549 bool all = false;
3550 const char *k = NULL;
3551
3552 if (strcmp(key, "lxc.proc") == 0)
3553 all = true;
3554 else if (strncmp(key, "lxc.proc.", sizeof("lxc.proc.") - 1) == 0)
3555 k = key + sizeof("lxc.proc.") - 1;
3556 else
3557 return -1;
3558
3559 lxc_list_for_each_safe(it, &c->procs, next) {
3560 struct lxc_proc *proc = it->elem;
3561 if (!all && strcmp(proc->filename, k) != 0)
3562 continue;
3563 lxc_list_del(it);
3564 free(proc->filename);
3565 free(proc->value);
3566 free(proc);
3567 free(it);
3568 }
3569
3570 return 0;
3571}
3572
ee1e7aa0
SG
3573int lxc_clear_groups(struct lxc_conf *c)
3574{
3575 struct lxc_list *it,*next;
3576
3577 lxc_list_for_each_safe(it, &c->groups, next) {
3578 lxc_list_del(it);
3579 free(it->elem);
3580 free(it);
3581 }
3582 return 0;
3583}
3584
ab799c0b
SG
3585int lxc_clear_environment(struct lxc_conf *c)
3586{
3587 struct lxc_list *it,*next;
3588
3589 lxc_list_for_each_safe(it, &c->environment, next) {
3590 lxc_list_del(it);
3591 free(it->elem);
3592 free(it);
3593 }
3594 return 0;
3595}
3596
72d0e1cb
SG
3597int lxc_clear_mount_entries(struct lxc_conf *c)
3598{
9ebb03ad 3599 struct lxc_list *it,*next;
72d0e1cb 3600
9ebb03ad 3601 lxc_list_for_each_safe(it, &c->mount_list, next) {
72d0e1cb
SG
3602 lxc_list_del(it);
3603 free(it->elem);
3604 free(it);
3605 }
3606 return 0;
3607}
3608
b099e9e9
SH
3609int lxc_clear_automounts(struct lxc_conf *c)
3610{
3611 c->auto_mounts = 0;
3612 return 0;
3613}
3614
12a50cc6 3615int lxc_clear_hooks(struct lxc_conf *c, const char *key)
72d0e1cb 3616{
9ebb03ad 3617 struct lxc_list *it,*next;
17ed13a3 3618 bool all = false, done = false;
a6390f01 3619 const char *k = NULL;
72d0e1cb
SG
3620 int i;
3621
17ed13a3
SH
3622 if (strcmp(key, "lxc.hook") == 0)
3623 all = true;
a6390f01
WB
3624 else if (strncmp(key, "lxc.hook.", sizeof("lxc.hook.")-1) == 0)
3625 k = key + sizeof("lxc.hook.")-1;
3626 else
3627 return -1;
17ed13a3 3628
72d0e1cb 3629 for (i=0; i<NUM_LXC_HOOKS; i++) {
17ed13a3 3630 if (all || strcmp(k, lxchook_names[i]) == 0) {
9ebb03ad 3631 lxc_list_for_each_safe(it, &c->hooks[i], next) {
17ed13a3
SH
3632 lxc_list_del(it);
3633 free(it->elem);
3634 free(it);
3635 }
3636 done = true;
72d0e1cb
SG
3637 }
3638 }
17ed13a3
SH
3639
3640 if (!done) {
3641 ERROR("Invalid hook key: %s", key);
3642 return -1;
3643 }
72d0e1cb
SG
3644 return 0;
3645}
8eb5694b 3646
4184c3e1
SH
3647static inline void lxc_clear_aliens(struct lxc_conf *conf)
3648{
3649 struct lxc_list *it,*next;
3650
3651 lxc_list_for_each_safe(it, &conf->aliens, next) {
3652 lxc_list_del(it);
3653 free(it->elem);
3654 free(it);
3655 }
3656}
3657
c7b15d1e 3658void lxc_clear_includes(struct lxc_conf *conf)
f979ac15
SH
3659{
3660 struct lxc_list *it,*next;
3661
3662 lxc_list_for_each_safe(it, &conf->includes, next) {
3663 lxc_list_del(it);
3664 free(it->elem);
3665 free(it);
3666 }
3667}
3668
8eb5694b
SH
3669void lxc_conf_free(struct lxc_conf *conf)
3670{
3671 if (!conf)
3672 return;
858377e4
SH
3673 if (current_config == conf)
3674 current_config = NULL;
e98affda 3675 lxc_pty_conf_free(&conf->console);
f10fad2f 3676 free(conf->rootfs.mount);
b3b8c97f 3677 free(conf->rootfs.bdev_type);
f10fad2f
ME
3678 free(conf->rootfs.options);
3679 free(conf->rootfs.path);
f10fad2f 3680 free(conf->logfile);
858377e4
SH
3681 if (conf->logfd != -1)
3682 close(conf->logfd);
f10fad2f
ME
3683 free(conf->utsname);
3684 free(conf->ttydir);
3685 free(conf->fstab);
3686 free(conf->rcfile);
5cda27c1 3687 free(conf->execute_cmd);
f10fad2f 3688 free(conf->init_cmd);
3c491553 3689 free(conf->init_cwd);
6b0d5538 3690 free(conf->unexpanded_config);
393903d1 3691 free(conf->pty_names);
76d0127f 3692 free(conf->syslog);
c302b476 3693 lxc_free_networks(&conf->network);
f10fad2f
ME
3694 free(conf->lsm_aa_profile);
3695 free(conf->lsm_se_context);
769872f9 3696 lxc_seccomp_free(conf);
8eb5694b 3697 lxc_clear_config_caps(conf);
1fb86a7c 3698 lxc_clear_config_keepcaps(conf);
54860ed0
CB
3699 lxc_clear_cgroups(conf, "lxc.cgroup", CGROUP_SUPER_MAGIC);
3700 lxc_clear_cgroups(conf, "lxc.cgroup2", CGROUP2_SUPER_MAGIC);
17ed13a3 3701 lxc_clear_hooks(conf, "lxc.hook");
8eb5694b 3702 lxc_clear_mount_entries(conf);
27c27d73 3703 lxc_clear_idmaps(conf);
ee1e7aa0 3704 lxc_clear_groups(conf);
f979ac15 3705 lxc_clear_includes(conf);
761d81ca 3706 lxc_clear_aliens(conf);
ab799c0b 3707 lxc_clear_environment(conf);
240d4b74 3708 lxc_clear_limits(conf, "lxc.prlimit");
7edd0540 3709 lxc_clear_sysctls(conf, "lxc.sysctl");
61d7a733 3710 lxc_clear_procs(conf, "lxc.proc");
43654d34
CB
3711 free(conf->cgroup_meta.dir);
3712 free(conf->cgroup_meta.controllers);
8eb5694b
SH
3713 free(conf);
3714}
4355ab5f
SH
3715
3716struct userns_fn_data {
3717 int (*fn)(void *);
c9b7c33e 3718 const char *fn_name;
4355ab5f
SH
3719 void *arg;
3720 int p[2];
3721};
3722
3723static int run_userns_fn(void *data)
3724{
3725 struct userns_fn_data *d = data;
3726 char c;
4355ab5f 3727
f8aa4bf3 3728 /* Close write end of the pipe. */
4355ab5f 3729 close(d->p[1]);
f8aa4bf3
CB
3730
3731 /* Wait for parent to finish establishing a new mapping in the user
3732 * namespace we are executing in.
3733 */
4355ab5f
SH
3734 if (read(d->p[0], &c, 1) != 1)
3735 return -1;
f8aa4bf3
CB
3736
3737 /* Close read end of the pipe. */
4355ab5f 3738 close(d->p[0]);
f8aa4bf3 3739
c9b7c33e
CB
3740 if (d->fn_name)
3741 TRACE("calling function \"%s\"", d->fn_name);
f8aa4bf3 3742 /* Call function to run. */
4355ab5f
SH
3743 return d->fn(d->arg);
3744}
3745
db7cfe23
CB
3746static struct id_map *mapped_nsid_add(struct lxc_conf *conf, unsigned id,
3747 enum idtype idtype)
3748{
3749 struct id_map *map, *retmap;
3750
3751 map = find_mapped_nsid_entry(conf, id, idtype);
3752 if (!map)
3753 return NULL;
3754
3755 retmap = malloc(sizeof(*retmap));
3756 if (!retmap)
3757 return NULL;
3758
3759 memcpy(retmap, map, sizeof(*retmap));
3760 return retmap;
3761}
3762
c4333195
CB
3763static struct id_map *find_mapped_hostid_entry(struct lxc_conf *conf,
3764 unsigned id, enum idtype idtype)
f8aa4bf3
CB
3765{
3766 struct lxc_list *it;
3767 struct id_map *map;
3768 struct id_map *retmap = NULL;
3769
3770 lxc_list_for_each(it, &conf->id_map) {
3771 map = it->elem;
3772 if (map->idtype != idtype)
3773 continue;
3774
3775 if (id >= map->hostid && id < map->hostid + map->range) {
3776 retmap = map;
3777 break;
3778 }
3779 }
3780
f8aa4bf3
CB
3781 return retmap;
3782}
3783
4355ab5f 3784/*
f8aa4bf3
CB
3785 * Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
3786 * existing one or establish a new one.
4355ab5f 3787 */
c4333195 3788static struct id_map *mapped_hostid_add(struct lxc_conf *conf, uid_t id, enum idtype type)
4355ab5f 3789{
28a2d9e7 3790 int hostid_mapped;
c4333195
CB
3791 struct id_map *entry = NULL, *tmp = NULL;
3792
3793 entry = malloc(sizeof(*entry));
3794 if (!entry)
3795 return NULL;
f8aa4bf3 3796
28a2d9e7 3797 /* Reuse existing mapping. */
c4333195
CB
3798 tmp = find_mapped_hostid_entry(conf, id, type);
3799 if (tmp)
3800 return memcpy(entry, tmp, sizeof(*entry));
f8aa4bf3 3801
28a2d9e7
CB
3802 /* Find new mapping. */
3803 hostid_mapped = find_unmapped_nsid(conf, type);
3804 if (hostid_mapped < 0) {
c4333195
CB
3805 DEBUG("Failed to find free mapping for id %d", id);
3806 free(entry);
28a2d9e7 3807 return NULL;
f8aa4bf3 3808 }
f8aa4bf3 3809
28a2d9e7
CB
3810 entry->idtype = type;
3811 entry->nsid = hostid_mapped;
3812 entry->hostid = (unsigned long)id;
3813 entry->range = 1;
4355ab5f 3814
28a2d9e7 3815 return entry;
4355ab5f
SH
3816}
3817
dcf0ffdf 3818struct lxc_list *get_minimal_idmap(struct lxc_conf *conf)
4355ab5f 3819{
f8aa4bf3 3820 uid_t euid, egid;
4160c3a0
CB
3821 uid_t nsuid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
3822 gid_t nsgid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
f8aa4bf3 3823 struct lxc_list *idmap = NULL, *tmplist = NULL;
28a2d9e7
CB
3824 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
3825 *host_uid_map = NULL, *host_gid_map = NULL;
4355ab5f 3826
db7cfe23 3827 /* Find container root mappings. */
4160c3a0 3828 container_root_uid = mapped_nsid_add(conf, nsuid, ID_TYPE_UID);
db7cfe23 3829 if (!container_root_uid) {
dcf0ffdf 3830 DEBUG("Failed to find mapping for namespace uid %d", 0);
db7cfe23 3831 goto on_error;
f8aa4bf3 3832 }
dcf0ffdf
CB
3833 euid = geteuid();
3834 if (euid >= container_root_uid->hostid &&
3835 euid < (container_root_uid->hostid + container_root_uid->range))
db7cfe23 3836 host_uid_map = container_root_uid;
f8aa4bf3 3837
4160c3a0 3838 container_root_gid = mapped_nsid_add(conf, nsgid, ID_TYPE_GID);
db7cfe23 3839 if (!container_root_gid) {
dcf0ffdf 3840 DEBUG("Failed to find mapping for namespace gid %d", 0);
f8aa4bf3
CB
3841 goto on_error;
3842 }
dcf0ffdf
CB
3843 egid = getegid();
3844 if (egid >= container_root_gid->hostid &&
3845 egid < (container_root_gid->hostid + container_root_gid->range))
db7cfe23 3846 host_gid_map = container_root_gid;
f8aa4bf3
CB
3847
3848 /* Check whether the {g,u}id of the user has a mapping. */
954b7d9b 3849 if (!host_uid_map)
c4333195 3850 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
28a2d9e7 3851 if (!host_uid_map) {
db7cfe23 3852 DEBUG("Failed to find mapping for uid %d", euid);
f8aa4bf3
CB
3853 goto on_error;
3854 }
3855
dcf0ffdf
CB
3856 if (!host_gid_map)
3857 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
28a2d9e7 3858 if (!host_gid_map) {
db7cfe23 3859 DEBUG("Failed to find mapping for gid %d", egid);
28a2d9e7
CB
3860 goto on_error;
3861 }
3862
3863 /* Allocate new {g,u}id map list. */
3864 idmap = malloc(sizeof(*idmap));
3865 if (!idmap)
3866 goto on_error;
3867 lxc_list_init(idmap);
3868
f8aa4bf3
CB
3869 /* Add container root to the map. */
3870 tmplist = malloc(sizeof(*tmplist));
3871 if (!tmplist)
3872 goto on_error;
3873 lxc_list_add_elem(tmplist, container_root_uid);
3874 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 3875
1d90e064 3876 if (host_uid_map && (host_uid_map != container_root_uid)) {
28a2d9e7
CB
3877 /* idmap will now keep track of that memory. */
3878 container_root_uid = NULL;
3879
3880 /* Add container root to the map. */
3881 tmplist = malloc(sizeof(*tmplist));
3882 if (!tmplist)
3883 goto on_error;
3884 lxc_list_add_elem(tmplist, host_uid_map);
3885 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 3886 }
1d90e064
CB
3887 /* idmap will now keep track of that memory. */
3888 container_root_uid = NULL;
3889 /* idmap will now keep track of that memory. */
3890 host_uid_map = NULL;
f8aa4bf3
CB
3891
3892 tmplist = malloc(sizeof(*tmplist));
3893 if (!tmplist)
3894 goto on_error;
3895 lxc_list_add_elem(tmplist, container_root_gid);
3896 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 3897
1d90e064 3898 if (host_gid_map && (host_gid_map != container_root_gid)) {
28a2d9e7
CB
3899 /* idmap will now keep track of that memory. */
3900 container_root_gid = NULL;
3901
3902 tmplist = malloc(sizeof(*tmplist));
3903 if (!tmplist)
3904 goto on_error;
3905 lxc_list_add_elem(tmplist, host_gid_map);
3906 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 3907 }
1d90e064
CB
3908 /* idmap will now keep track of that memory. */
3909 container_root_gid = NULL;
3910 /* idmap will now keep track of that memory. */
3911 host_gid_map = NULL;
f8aa4bf3 3912
dcf0ffdf
CB
3913 TRACE("Allocated minimal idmapping");
3914 return idmap;
3915
3916on_error:
3917 if (idmap)
3918 lxc_free_idmap(idmap);
3919 if (container_root_uid)
3920 free(container_root_uid);
3921 if (container_root_gid)
3922 free(container_root_gid);
3923 if (host_uid_map && (host_uid_map != container_root_uid))
3924 free(host_uid_map);
3925 if (host_gid_map && (host_gid_map != container_root_gid))
3926 free(host_gid_map);
3927
3928 return NULL;
3929}
3930
3931/* Run a function in a new user namespace.
3932 * The caller's euid/egid will be mapped if it is not already.
3933 * Afaict, userns_exec_1() is only used to operate based on privileges for the
3934 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
3935 * This means we require only to establish a mapping from:
3936 * - the container root {g,u}id as seen from the host > user's host {g,u}id
3937 * - the container root -> some sub{g,u}id
3938 * The former we add, if the user did not specifiy a mapping. The latter we
3939 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
3940 * there to start the container in the first place.
3941 */
3942int userns_exec_1(struct lxc_conf *conf, int (*fn)(void *), void *data,
3943 const char *fn_name)
3944{
3945 pid_t pid;
3946 struct userns_fn_data d;
3947 int p[2];
3948 char c = '1';
3949 int ret = -1, status = -1;
3950 struct lxc_list *idmap;
3951
3952 idmap = get_minimal_idmap(conf);
3953 if (!idmap)
3954 return -1;
3955
3956 ret = pipe(p);
3957 if (ret < 0) {
3958 SYSERROR("Failed to create pipe");
3959 return -1;
3960 }
3961 d.fn = fn;
3962 d.fn_name = fn_name;
3963 d.arg = data;
3964 d.p[0] = p[0];
3965 d.p[1] = p[1];
3966
3967 /* Clone child in new user namespace. */
3968 pid = lxc_raw_clone_cb(run_userns_fn, &d, CLONE_NEWUSER);
3969 if (pid < 0) {
3970 ERROR("failed to clone child process in new user namespace");
3971 goto on_error;
3972 }
3973
3974 close(p[0]);
3975 p[0] = -1;
3976
4b73005c
CB
3977 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE ||
3978 conf->loglevel == LXC_LOG_LEVEL_TRACE) {
dcf0ffdf
CB
3979 struct lxc_list *it;
3980 struct id_map *map;
3981
f8aa4bf3
CB
3982 lxc_list_for_each(it, idmap) {
3983 map = it->elem;
dcf0ffdf 3984 TRACE("Establishing %cid mapping for \"%d\" in new "
f8aa4bf3 3985 "user namespace: nsuid %lu - hostid %lu - range "
dcf0ffdf
CB
3986 "%lu", (map->idtype == ID_TYPE_UID) ? 'u' : 'g',
3987 pid, map->nsid, map->hostid, map->range);
f8aa4bf3 3988 }
4355ab5f
SH
3989 }
3990
f8aa4bf3 3991 /* Set up {g,u}id mapping for user namespace of child process. */
4355ab5f 3992 ret = lxc_map_ids(idmap, pid);
f8aa4bf3 3993 if (ret < 0) {
dcf0ffdf 3994 ERROR("Error setting up {g,u}id mappings for child process "
415a8851 3995 "\"%d\"", pid);
f8aa4bf3 3996 goto on_error;
4355ab5f
SH
3997 }
3998
f8aa4bf3 3999 /* Tell child to proceed. */
4355ab5f 4000 if (write(p[1], &c, 1) != 1) {
dcf0ffdf 4001 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
f8aa4bf3 4002 goto on_error;
4355ab5f
SH
4003 }
4004
686dd5d1 4005on_error:
f8aa4bf3 4006 /* Wait for child to finish. */
686dd5d1
CB
4007 if (pid > 0)
4008 status = wait_for_pid(pid);
3139aead 4009
4355ab5f
SH
4010 if (p[0] != -1)
4011 close(p[0]);
4012 close(p[1]);
f8aa4bf3 4013
686dd5d1
CB
4014 if (status < 0)
4015 ret = -1;
4016
f8aa4bf3 4017 return ret;
4355ab5f 4018}
97e9cfa0 4019
415a8851
CB
4020int userns_exec_full(struct lxc_conf *conf, int (*fn)(void *), void *data,
4021 const char *fn_name)
4022{
4023 pid_t pid;
4024 uid_t euid, egid;
4025 struct userns_fn_data d;
4026 int p[2];
4027 struct id_map *map;
4028 struct lxc_list *cur;
4029 char c = '1';
4030 int ret = -1;
4031 struct lxc_list *idmap = NULL, *tmplist = NULL;
4032 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
4033 *host_uid_map = NULL, *host_gid_map = NULL;
4034
4035 ret = pipe(p);
4036 if (ret < 0) {
4037 SYSERROR("opening pipe");
4038 return -1;
4039 }
4040 d.fn = fn;
4041 d.fn_name = fn_name;
4042 d.arg = data;
4043 d.p[0] = p[0];
4044 d.p[1] = p[1];
4045
4046 /* Clone child in new user namespace. */
4047 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER);
4048 if (pid < 0) {
4049 ERROR("failed to clone child process in new user namespace");
4050 goto on_error;
4051 }
4052
4053 close(p[0]);
4054 p[0] = -1;
4055
4056 euid = geteuid();
4057 egid = getegid();
4058
4059 /* Allocate new {g,u}id map list. */
4060 idmap = malloc(sizeof(*idmap));
4061 if (!idmap)
4062 goto on_error;
4063 lxc_list_init(idmap);
4064
4065 /* Find container root. */
4066 lxc_list_for_each(cur, &conf->id_map) {
4067 struct id_map *tmpmap;
4068
4069 tmplist = malloc(sizeof(*tmplist));
4070 if (!tmplist)
4071 goto on_error;
4072
4073 tmpmap = malloc(sizeof(*tmpmap));
4074 if (!tmpmap) {
4075 free(tmplist);
4076 goto on_error;
4077 }
4078
4079 memset(tmpmap, 0, sizeof(*tmpmap));
4080 memcpy(tmpmap, cur->elem, sizeof(*tmpmap));
4081 tmplist->elem = tmpmap;
4082
4083 lxc_list_add_tail(idmap, tmplist);
4084
4085 map = cur->elem;
4086
4087 if (map->idtype == ID_TYPE_UID)
4088 if (euid >= map->hostid && euid < map->hostid + map->range)
4089 host_uid_map = map;
4090
4091 if (map->idtype == ID_TYPE_GID)
4092 if (egid >= map->hostid && egid < map->hostid + map->range)
4093 host_gid_map = map;
4094
4095 if (map->nsid != 0)
4096 continue;
4097
4098 if (map->idtype == ID_TYPE_UID)
4099 if (container_root_uid == NULL)
4100 container_root_uid = map;
4101
4102 if (map->idtype == ID_TYPE_GID)
4103 if (container_root_gid == NULL)
4104 container_root_gid = map;
4105 }
4106
4107 if (!container_root_uid || !container_root_gid) {
4108 ERROR("No mapping for container root found");
4109 goto on_error;
4110 }
4111
4112 /* Check whether the {g,u}id of the user has a mapping. */
4113 if (!host_uid_map)
c4333195 4114 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
415a8851
CB
4115 else
4116 host_uid_map = container_root_uid;
4117
4118 if (!host_gid_map)
c4333195 4119 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
415a8851
CB
4120 else
4121 host_gid_map = container_root_gid;
4122
4123 if (!host_uid_map) {
4124 DEBUG("Failed to find mapping for uid %d", euid);
4125 goto on_error;
4126 }
4127
4128 if (!host_gid_map) {
4129 DEBUG("Failed to find mapping for gid %d", egid);
4130 goto on_error;
4131 }
4132
4133 if (host_uid_map && (host_uid_map != container_root_uid)) {
4134 /* Add container root to the map. */
4135 tmplist = malloc(sizeof(*tmplist));
4136 if (!tmplist)
4137 goto on_error;
4138 lxc_list_add_elem(tmplist, host_uid_map);
4139 lxc_list_add_tail(idmap, tmplist);
4140 }
4141 /* idmap will now keep track of that memory. */
4142 host_uid_map = NULL;
4143
4144 if (host_gid_map && (host_gid_map != container_root_gid)) {
4145 tmplist = malloc(sizeof(*tmplist));
4146 if (!tmplist)
4147 goto on_error;
4148 lxc_list_add_elem(tmplist, host_gid_map);
4149 lxc_list_add_tail(idmap, tmplist);
4150 }
4151 /* idmap will now keep track of that memory. */
4152 host_gid_map = NULL;
4153
4154 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE ||
4155 conf->loglevel == LXC_LOG_LEVEL_TRACE) {
4156 lxc_list_for_each(cur, idmap) {
4157 map = cur->elem;
4158 TRACE("establishing %cid mapping for \"%d\" in new "
4159 "user namespace: nsuid %lu - hostid %lu - range "
4160 "%lu",
4161 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
4162 map->nsid, map->hostid, map->range);
4163 }
4164 }
4165
4166 /* Set up {g,u}id mapping for user namespace of child process. */
4167 ret = lxc_map_ids(idmap, pid);
4168 if (ret < 0) {
4169 ERROR("error setting up {g,u}id mappings for child process "
4170 "\"%d\"", pid);
4171 goto on_error;
4172 }
4173
4174 /* Tell child to proceed. */
4175 if (write(p[1], &c, 1) != 1) {
4176 SYSERROR("failed telling child process \"%d\" to proceed", pid);
4177 goto on_error;
4178 }
4179
686dd5d1 4180on_error:
415a8851 4181 /* Wait for child to finish. */
686dd5d1
CB
4182 if (pid > 0)
4183 ret = wait_for_pid(pid);
415a8851 4184
415a8851
CB
4185 if (idmap)
4186 lxc_free_idmap(idmap);
4187 if (host_uid_map && (host_uid_map != container_root_uid))
4188 free(host_uid_map);
4189 if (host_gid_map && (host_gid_map != container_root_gid))
4190 free(host_gid_map);
4191
4192 if (p[0] != -1)
4193 close(p[0]);
4194 close(p[1]);
4195
4196 return ret;
4197}
4198
a96a8e8c 4199/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
4200static char* getuname(void)
4201{
a96a8e8c 4202 struct passwd *result;
97e9cfa0 4203
a96a8e8c
SH
4204 result = getpwuid(geteuid());
4205 if (!result)
97e9cfa0
SH
4206 return NULL;
4207
a96a8e8c 4208 return strdup(result->pw_name);
97e9cfa0
SH
4209}
4210
a96a8e8c 4211/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
4212static char *getgname(void)
4213{
a96a8e8c 4214 struct group *result;
97e9cfa0 4215
a96a8e8c
SH
4216 result = getgrgid(getegid());
4217 if (!result)
97e9cfa0
SH
4218 return NULL;
4219
a96a8e8c 4220 return strdup(result->gr_name);
97e9cfa0
SH
4221}
4222
a96a8e8c 4223/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
4224void suggest_default_idmap(void)
4225{
4226 FILE *f;
4227 unsigned int uid = 0, urange = 0, gid = 0, grange = 0;
4228 char *line = NULL;
4229 char *uname, *gname;
4230 size_t len = 0;
4231
4232 if (!(uname = getuname()))
4233 return;
4234
4235 if (!(gname = getgname())) {
4236 free(uname);
4237 return;
4238 }
4239
4240 f = fopen(subuidfile, "r");
4241 if (!f) {
4242 ERROR("Your system is not configured with subuids");
4243 free(gname);
4244 free(uname);
4245 return;
4246 }
4247 while (getline(&line, &len, f) != -1) {
b7930180 4248 size_t no_newline = 0;
97e9cfa0
SH
4249 char *p = strchr(line, ':'), *p2;
4250 if (*line == '#')
4251 continue;
4252 if (!p)
4253 continue;
4254 *p = '\0';
4255 p++;
4256 if (strcmp(line, uname))
4257 continue;
4258 p2 = strchr(p, ':');
4259 if (!p2)
4260 continue;
4261 *p2 = '\0';
4262 p2++;
4263 if (!*p2)
4264 continue;
b7930180
CB
4265 no_newline = strcspn(p2, "\n");
4266 p2[no_newline] = '\0';
4267
b7b2fde4
CB
4268 if (lxc_safe_uint(p, &uid) < 0)
4269 WARN("Could not parse UID.");
4270 if (lxc_safe_uint(p2, &urange) < 0)
4271 WARN("Could not parse UID range.");
97e9cfa0
SH
4272 }
4273 fclose(f);
4274
6be7389a 4275 f = fopen(subgidfile, "r");
97e9cfa0
SH
4276 if (!f) {
4277 ERROR("Your system is not configured with subgids");
4278 free(gname);
4279 free(uname);
4280 return;
4281 }
4282 while (getline(&line, &len, f) != -1) {
b7930180 4283 size_t no_newline = 0;
97e9cfa0
SH
4284 char *p = strchr(line, ':'), *p2;
4285 if (*line == '#')
4286 continue;
4287 if (!p)
4288 continue;
4289 *p = '\0';
4290 p++;
4291 if (strcmp(line, uname))
4292 continue;
4293 p2 = strchr(p, ':');
4294 if (!p2)
4295 continue;
4296 *p2 = '\0';
4297 p2++;
4298 if (!*p2)
4299 continue;
b7930180
CB
4300 no_newline = strcspn(p2, "\n");
4301 p2[no_newline] = '\0';
4302
b7b2fde4
CB
4303 if (lxc_safe_uint(p, &gid) < 0)
4304 WARN("Could not parse GID.");
4305 if (lxc_safe_uint(p2, &grange) < 0)
4306 WARN("Could not parse GID range.");
97e9cfa0
SH
4307 }
4308 fclose(f);
4309
f10fad2f 4310 free(line);
97e9cfa0
SH
4311
4312 if (!urange || !grange) {
4313 ERROR("You do not have subuids or subgids allocated");
4314 ERROR("Unprivileged containers require subuids and subgids");
4315 return;
4316 }
4317
4318 ERROR("You must either run as root, or define uid mappings");
4319 ERROR("To pass uid mappings to lxc-create, you could create");
4320 ERROR("~/.config/lxc/default.conf:");
4321 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG);
bdcbb6b3
CB
4322 ERROR("lxc.idmap = u 0 %u %u", uid, urange);
4323 ERROR("lxc.idmap = g 0 %u %u", gid, grange);
97e9cfa0
SH
4324
4325 free(gname);
4326 free(uname);
4327}
aaf26830 4328
a7307747
SH
4329static void free_cgroup_settings(struct lxc_list *result)
4330{
4331 struct lxc_list *iterator, *next;
4332
4333 lxc_list_for_each_safe(iterator, result, next) {
4334 lxc_list_del(iterator);
4335 free(iterator);
4336 }
4337 free(result);
4338}
4339
aaf26830
KT
4340/*
4341 * Return the list of cgroup_settings sorted according to the following rules
4342 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4343 */
4344struct lxc_list *sort_cgroup_settings(struct lxc_list* cgroup_settings)
4345{
4346 struct lxc_list *result;
4347 struct lxc_list *memsw_limit = NULL;
4348 struct lxc_list *it = NULL;
4349 struct lxc_cgroup *cg = NULL;
4350 struct lxc_list *item = NULL;
4351
4352 result = malloc(sizeof(*result));
fac7c663
KT
4353 if (!result) {
4354 ERROR("failed to allocate memory to sort cgroup settings");
4355 return NULL;
4356 }
aaf26830
KT
4357 lxc_list_init(result);
4358
4359 /*Iterate over the cgroup settings and copy them to the output list*/
4360 lxc_list_for_each(it, cgroup_settings) {
4361 item = malloc(sizeof(*item));
fac7c663
KT
4362 if (!item) {
4363 ERROR("failed to allocate memory to sort cgroup settings");
a7307747 4364 free_cgroup_settings(result);
fac7c663
KT
4365 return NULL;
4366 }
aaf26830
KT
4367 item->elem = it->elem;
4368 cg = it->elem;
4369 if (strcmp(cg->subsystem, "memory.memsw.limit_in_bytes") == 0) {
4370 /* Store the memsw_limit location */
4371 memsw_limit = item;
4372 } else if (strcmp(cg->subsystem, "memory.limit_in_bytes") == 0 && memsw_limit != NULL) {
4d5b72a1 4373 /* lxc.cgroup.memory.memsw.limit_in_bytes is found before
aaf26830
KT
4374 * lxc.cgroup.memory.limit_in_bytes, swap these two items */
4375 item->elem = memsw_limit->elem;
4376 memsw_limit->elem = it->elem;
4377 }
4378 lxc_list_add_tail(result, item);
4379 }
4380
4381 return result;
a7307747 4382}