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