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