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