2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
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.
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.
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
40 #include <arpa/inet.h>
41 #include <linux/loop.h>
43 #include <netinet/in.h>
45 #include <sys/mount.h>
46 #include <sys/param.h>
47 #include <sys/prctl.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>
58 # include <sys/mkdev.h>
62 #include <sys/statvfs.h>
68 #include <../include/openpty.h>
71 #ifdef HAVE_LINUX_MEMFD_H
72 #include <linux/memfd.h>
76 #include "caps.h" /* for lxc_caps_last_cap() */
79 #include "confile_utils.h"
83 #include "lxcseccomp.h"
84 #include "namespace.h"
88 #include "storage/aufs.h"
89 #include "storage/overlay.h"
94 #include <sys/capability.h>
97 #if HAVE_SYS_PERSONALITY_H
98 #include <sys/personality.h>
102 #include <../include/lxcmntent.h>
104 #include <../include/prlimit.h>
110 lxc_log_define(lxc_conf
, lxc
);
114 #define CAP_SETFCAP 31
117 #ifndef CAP_MAC_OVERRIDE
118 #define CAP_MAC_OVERRIDE 32
121 #ifndef CAP_MAC_ADMIN
122 #define CAP_MAC_ADMIN 33
126 #ifndef PR_CAPBSET_DROP
127 #define PR_CAPBSET_DROP 24
130 #ifndef LO_FLAGS_AUTOCLEAR
131 #define LO_FLAGS_AUTOCLEAR 4
142 /* needed for cgroup automount checks, regardless of whether we
143 * have included linux/capability.h or not */
144 #ifndef CAP_SYS_ADMIN
145 #define CAP_SYS_ADMIN 21
148 /* Define pivot_root() if missing from the C library */
149 #ifndef HAVE_PIVOT_ROOT
150 static int pivot_root(const char * new_root
, const char * put_old
)
152 #ifdef __NR_pivot_root
153 return syscall(__NR_pivot_root
, new_root
, put_old
);
160 extern int pivot_root(const char * new_root
, const char * put_old
);
163 /* Define sethostname() if missing from the C library */
164 #ifndef HAVE_SETHOSTNAME
165 static int sethostname(const char * name
, size_t len
)
167 #ifdef __NR_sethostname
168 return syscall(__NR_sethostname
, name
, len
);
177 #define MS_PRIVATE (1<<18)
181 #define MS_LAZYTIME (1<<25)
186 #define MFD_CLOEXEC 0x0001U
189 #ifndef MFD_ALLOW_SEALING
190 #define MFD_ALLOW_SEALING 0x0002U
193 #ifndef HAVE_MEMFD_CREATE
194 static int memfd_create(const char *name
, unsigned int flags
) {
195 #ifndef __NR_memfd_create
197 #define __NR_memfd_create 356
198 #elif defined __x86_64__
199 #define __NR_memfd_create 319
200 #elif defined __arm__
201 #define __NR_memfd_create 385
202 #elif defined __aarch64__
203 #define __NR_memfd_create 279
204 #elif defined __s390__
205 #define __NR_memfd_create 350
206 #elif defined __powerpc__
207 #define __NR_memfd_create 360
208 #elif defined __sparc__
209 #define __NR_memfd_create 348
210 #elif defined __blackfin__
211 #define __NR_memfd_create 390
212 #elif defined __ia64__
213 #define __NR_memfd_create 1340
214 #elif defined _MIPS_SIM
215 #if _MIPS_SIM == _MIPS_SIM_ABI32
216 #define __NR_memfd_create 4354
218 #if _MIPS_SIM == _MIPS_SIM_NABI32
219 #define __NR_memfd_create 6318
221 #if _MIPS_SIM == _MIPS_SIM_ABI64
222 #define __NR_memfd_create 5314
226 #ifdef __NR_memfd_create
227 return syscall(__NR_memfd_create
, name
, flags
);
234 extern int memfd_create(const char *name
, unsigned int flags
);
237 char *lxchook_names
[NUM_LXC_HOOKS
] = {"pre-start", "pre-mount", "mount",
238 "autodev", "start", "stop",
239 "post-stop", "clone", "destroy"};
258 * The lxc_conf of the container currently being worked on in an
260 * This is used in the error calls
263 __thread
struct lxc_conf
*current_config
;
265 struct lxc_conf
*current_config
;
268 /* Declare this here, since we don't want to reshuffle the whole file. */
269 static int in_caplist(int cap
, struct lxc_list
*caps
);
271 static struct mount_opt mount_opt
[] = {
272 { "async", 1, MS_SYNCHRONOUS
},
273 { "atime", 1, MS_NOATIME
},
274 { "bind", 0, MS_BIND
},
275 { "defaults", 0, 0 },
276 { "dev", 1, MS_NODEV
},
277 { "diratime", 1, MS_NODIRATIME
},
278 { "dirsync", 0, MS_DIRSYNC
},
279 { "exec", 1, MS_NOEXEC
},
280 { "lazytime", 0, MS_LAZYTIME
},
281 { "mand", 0, MS_MANDLOCK
},
282 { "noatime", 0, MS_NOATIME
},
283 { "nodev", 0, MS_NODEV
},
284 { "nodiratime", 0, MS_NODIRATIME
},
285 { "noexec", 0, MS_NOEXEC
},
286 { "nomand", 1, MS_MANDLOCK
},
287 { "norelatime", 1, MS_RELATIME
},
288 { "nostrictatime", 1, MS_STRICTATIME
},
289 { "nosuid", 0, MS_NOSUID
},
290 { "rbind", 0, MS_BIND
|MS_REC
},
291 { "relatime", 0, MS_RELATIME
},
292 { "remount", 0, MS_REMOUNT
},
293 { "ro", 0, MS_RDONLY
},
294 { "rw", 1, MS_RDONLY
},
295 { "strictatime", 0, MS_STRICTATIME
},
296 { "suid", 1, MS_NOSUID
},
297 { "sync", 0, MS_SYNCHRONOUS
},
302 static struct caps_opt caps_opt
[] = {
303 { "chown", CAP_CHOWN
},
304 { "dac_override", CAP_DAC_OVERRIDE
},
305 { "dac_read_search", CAP_DAC_READ_SEARCH
},
306 { "fowner", CAP_FOWNER
},
307 { "fsetid", CAP_FSETID
},
308 { "kill", CAP_KILL
},
309 { "setgid", CAP_SETGID
},
310 { "setuid", CAP_SETUID
},
311 { "setpcap", CAP_SETPCAP
},
312 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
313 { "net_bind_service", CAP_NET_BIND_SERVICE
},
314 { "net_broadcast", CAP_NET_BROADCAST
},
315 { "net_admin", CAP_NET_ADMIN
},
316 { "net_raw", CAP_NET_RAW
},
317 { "ipc_lock", CAP_IPC_LOCK
},
318 { "ipc_owner", CAP_IPC_OWNER
},
319 { "sys_module", CAP_SYS_MODULE
},
320 { "sys_rawio", CAP_SYS_RAWIO
},
321 { "sys_chroot", CAP_SYS_CHROOT
},
322 { "sys_ptrace", CAP_SYS_PTRACE
},
323 { "sys_pacct", CAP_SYS_PACCT
},
324 { "sys_admin", CAP_SYS_ADMIN
},
325 { "sys_boot", CAP_SYS_BOOT
},
326 { "sys_nice", CAP_SYS_NICE
},
327 { "sys_resource", CAP_SYS_RESOURCE
},
328 { "sys_time", CAP_SYS_TIME
},
329 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
330 { "mknod", CAP_MKNOD
},
331 { "lease", CAP_LEASE
},
332 #ifdef CAP_AUDIT_READ
333 { "audit_read", CAP_AUDIT_READ
},
335 #ifdef CAP_AUDIT_WRITE
336 { "audit_write", CAP_AUDIT_WRITE
},
338 #ifdef CAP_AUDIT_CONTROL
339 { "audit_control", CAP_AUDIT_CONTROL
},
341 { "setfcap", CAP_SETFCAP
},
342 { "mac_override", CAP_MAC_OVERRIDE
},
343 { "mac_admin", CAP_MAC_ADMIN
},
345 { "syslog", CAP_SYSLOG
},
347 #ifdef CAP_WAKE_ALARM
348 { "wake_alarm", CAP_WAKE_ALARM
},
350 #ifdef CAP_BLOCK_SUSPEND
351 { "block_suspend", CAP_BLOCK_SUSPEND
},
355 static struct caps_opt caps_opt
[] = {};
358 static struct limit_opt limit_opt
[] = {
363 { "core", RLIMIT_CORE
},
366 { "cpu", RLIMIT_CPU
},
369 { "data", RLIMIT_DATA
},
372 { "fsize", RLIMIT_FSIZE
},
375 { "locks", RLIMIT_LOCKS
},
377 #ifdef RLIMIT_MEMLOCK
378 { "memlock", RLIMIT_MEMLOCK
},
380 #ifdef RLIMIT_MSGQUEUE
381 { "msgqueue", RLIMIT_MSGQUEUE
},
384 { "nice", RLIMIT_NICE
},
387 { "nofile", RLIMIT_NOFILE
},
390 { "nproc", RLIMIT_NPROC
},
393 { "rss", RLIMIT_RSS
},
396 { "rtprio", RLIMIT_RTPRIO
},
399 { "rttime", RLIMIT_RTTIME
},
401 #ifdef RLIMIT_SIGPENDING
402 { "sigpending", RLIMIT_SIGPENDING
},
405 { "stack", RLIMIT_STACK
},
409 static int run_buffer(char *buffer
)
411 struct lxc_popen_FILE
*f
;
415 f
= lxc_popen(buffer
);
417 SYSERROR("Failed to popen() %s.", buffer
);
421 output
= malloc(LXC_LOG_BUFFER_SIZE
);
423 ERROR("Failed to allocate memory for %s.", buffer
);
428 while (fgets(output
, LXC_LOG_BUFFER_SIZE
, f
->f
))
429 DEBUG("Script %s with output: %s.", buffer
, output
);
435 SYSERROR("Script exited with error.");
437 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
438 ERROR("Script exited with status %d.", WEXITSTATUS(ret
));
440 } else if (WIFSIGNALED(ret
)) {
441 ERROR("Script terminated by signal %d.", WTERMSIG(ret
));
448 static int run_script_argv(const char *name
, const char *section
,
449 const char *script
, const char *hook
,
450 const char *lxcpath
, char **argsin
)
456 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
457 script
, name
, section
);
459 for (i
= 0; argsin
&& argsin
[i
]; i
++)
460 size
+= strlen(argsin
[i
]) + 1;
462 size
+= strlen(hook
) + 1;
464 size
+= strlen(script
);
465 size
+= strlen(name
);
466 size
+= strlen(section
);
472 buffer
= alloca(size
);
474 ERROR("Failed to allocate memory.");
479 snprintf(buffer
, size
, "%s %s %s %s", script
, name
, section
, hook
);
480 if (ret
< 0 || (size_t)ret
>= size
) {
481 ERROR("Script name too long.");
485 for (i
= 0; argsin
&& argsin
[i
]; i
++) {
486 int len
= size
- ret
;
488 rc
= snprintf(buffer
+ ret
, len
, " %s", argsin
[i
]);
489 if (rc
< 0 || rc
>= len
) {
490 ERROR("Script args too long.");
496 return run_buffer(buffer
);
499 int run_script(const char *name
, const char *section
, const char *script
, ...)
506 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
507 script
, name
, section
);
509 va_start(ap
, script
);
510 while ((p
= va_arg(ap
, char *)))
511 size
+= strlen(p
) + 1;
514 size
+= strlen(script
);
515 size
+= strlen(name
);
516 size
+= strlen(section
);
522 buffer
= alloca(size
);
524 ERROR("Failed to allocate memory.");
528 ret
= snprintf(buffer
, size
, "%s %s %s", script
, name
, section
);
529 if (ret
< 0 || ret
>= size
) {
530 ERROR("Script name too long.");
534 va_start(ap
, script
);
535 while ((p
= va_arg(ap
, char *))) {
536 int len
= size
- ret
;
538 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
539 if (rc
< 0 || rc
>= len
) {
540 ERROR("Script args too long.");
547 return run_buffer(buffer
);
552 * if rootfs is a directory, then open ${rootfs}/lxc.hold for writing for
553 * the duration of the container run, to prevent the container from marking
554 * the underlying fs readonly on shutdown. unlink the file immediately so
555 * no name pollution is happens
556 * return -1 on error.
557 * return -2 if nothing needed to be pinned.
558 * return an open fd (>=0) if we pinned it.
560 int pin_rootfs(const char *rootfs
)
562 char absrootfs
[MAXPATHLEN
];
563 char absrootfspin
[MAXPATHLEN
];
567 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
570 if (!realpath(rootfs
, absrootfs
))
573 if (access(absrootfs
, F_OK
))
576 if (stat(absrootfs
, &s
))
579 if (!S_ISDIR(s
.st_mode
))
582 ret
= snprintf(absrootfspin
, MAXPATHLEN
, "%s/lxc.hold", absrootfs
);
583 if (ret
>= MAXPATHLEN
)
586 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
|S_IRUSR
);
589 (void)unlink(absrootfspin
);
594 * If we are asking to remount something, make sure that any
595 * NOEXEC etc are honored.
597 unsigned long add_required_remount_flags(const char *s
, const char *d
,
602 unsigned long required_flags
= 0;
604 if (!(flags
& MS_REMOUNT
))
612 if (statvfs(s
, &sb
) < 0)
615 if (sb
.f_flag
& MS_NOSUID
)
616 required_flags
|= MS_NOSUID
;
617 if (sb
.f_flag
& MS_NODEV
)
618 required_flags
|= MS_NODEV
;
619 if (sb
.f_flag
& MS_RDONLY
)
620 required_flags
|= MS_RDONLY
;
621 if (sb
.f_flag
& MS_NOEXEC
)
622 required_flags
|= MS_NOEXEC
;
624 return flags
| required_flags
;
630 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
638 const char *destination
;
642 } default_mounts
[] = {
643 /* Read-only bind-mounting... In older kernels, doing that required
644 * to do one MS_BIND mount and then MS_REMOUNT|MS_RDONLY the same
645 * one. According to mount(2) manpage, MS_BIND honors MS_RDONLY from
646 * kernel 2.6.26 onwards. However, this apparently does not work on
647 * kernel 3.8. Unfortunately, on that very same kernel, doing the
648 * same trick as above doesn't seem to work either, there one needs
649 * to ALSO specify MS_BIND for the remount, otherwise the entire
650 * fs is remounted read-only or the mount fails because it's busy...
651 * MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for kernels as low as
654 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
655 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
656 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
657 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
658 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
659 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
660 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
661 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
662 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
663 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
664 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
665 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
666 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
667 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
668 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
669 { 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
},
670 { 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
},
671 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
674 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
675 if ((flags
& default_mounts
[i
].match_mask
) == default_mounts
[i
].match_flag
) {
677 char *destination
= NULL
;
679 unsigned long mflags
;
681 if (default_mounts
[i
].source
) {
682 /* will act like strdup if %r is not present */
683 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
685 SYSERROR("memory allocation error");
689 if (!default_mounts
[i
].destination
) {
690 ERROR("BUG: auto mounts destination %d was NULL", i
);
694 /* will act like strdup if %r is not present */
695 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
698 SYSERROR("memory allocation error");
703 mflags
= add_required_remount_flags(source
, destination
,
704 default_mounts
[i
].flags
);
705 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
, mflags
, default_mounts
[i
].options
, conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
707 if (r
< 0 && errno
== ENOENT
) {
708 INFO("Mount source or target for %s on %s doesn't exist. Skipping.", source
, destination
);
712 SYSERROR("error mounting %s on %s flags %lu", source
, destination
, mflags
);
723 if (flags
& LXC_AUTO_CGROUP_MASK
) {
726 cg_flags
= flags
& LXC_AUTO_CGROUP_MASK
;
727 /* If the type of cgroup mount was not specified, it depends on the
728 * container's capabilities as to what makes sense: if we have
729 * CAP_SYS_ADMIN, the read-only part can be remounted read-write
730 * anyway, so we may as well default to read-write; then the admin
731 * will not be given a false sense of security. (And if they really
732 * want mixed r/o r/w, then they can explicitly specify :mixed.)
733 * OTOH, if the container lacks CAP_SYS_ADMIN, do only default to
734 * :mixed, because then the container can't remount it read-write. */
735 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
736 int has_sys_admin
= 0;
738 if (!lxc_list_empty(&conf
->keepcaps
))
739 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
741 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
743 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
744 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
746 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
749 if (!cgroup_mount(conf
->rootfs
.path
? conf
->rootfs
.mount
: "", handler
, cg_flags
)) {
750 SYSERROR("error mounting /sys/fs/cgroup");
758 static int setup_utsname(struct utsname
*utsname
)
763 if (sethostname(utsname
->nodename
, strlen(utsname
->nodename
))) {
764 SYSERROR("failed to set the hostname to '%s'", utsname
->nodename
);
768 INFO("'%s' hostname has been setup", utsname
->nodename
);
773 struct dev_symlinks
{
778 static const struct dev_symlinks dev_symlinks
[] = {
779 {"/proc/self/fd", "fd"},
780 {"/proc/self/fd/0", "stdin"},
781 {"/proc/self/fd/1", "stdout"},
782 {"/proc/self/fd/2", "stderr"},
785 static int setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
787 char path
[MAXPATHLEN
];
792 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
793 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
794 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs
->path
? rootfs
->mount
: "", d
->name
);
795 if (ret
< 0 || ret
>= MAXPATHLEN
)
799 * Stat the path first. If we don't get an error
800 * accept it as is and don't try to create it
802 if (!stat(path
, &s
)) {
806 ret
= symlink(d
->oldpath
, path
);
808 if (ret
&& errno
!= EEXIST
) {
809 if ( errno
== EROFS
) {
810 WARN("Warning: Read Only file system while creating %s", path
);
812 SYSERROR("Error creating %s", path
);
821 * Build a space-separate list of ptys to pass to systemd.
823 static bool append_ptyname(char **pp
, char *name
)
828 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
831 sprintf(*pp
, "container_ttys=%s", name
);
834 p
= realloc(*pp
, strlen(*pp
) + strlen(name
) + 2);
843 static int lxc_setup_tty(struct lxc_conf
*conf
)
846 const struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
847 char *ttydir
= conf
->ttydir
;
848 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
850 if (!conf
->rootfs
.path
)
853 for (i
= 0; i
< tty_info
->nbtty
; i
++) {
854 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
856 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
857 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
858 ERROR("pathname too long for ttys");
863 /* create dev/lxc/tty%d" */
864 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
865 "/dev/%s/tty%d", ttydir
, i
+ 1);
866 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
)) {
867 ERROR("pathname too long for ttys");
871 ret
= creat(lxcpath
, 0660);
872 if (ret
< 0 && errno
!= EEXIST
) {
873 SYSERROR("failed to create \"%s\"", lxcpath
);
880 if (ret
< 0 && errno
!= ENOENT
) {
881 SYSERROR("failed to unlink \"%s\"", path
);
885 ret
= mount(pty_info
->name
, lxcpath
, "none", MS_BIND
, 0);
887 WARN("failed to bind mount \"%s\" onto \"%s\"",
888 pty_info
->name
, path
);
891 DEBUG("bind mounted \"%s\" onto \"%s\"", pty_info
->name
,
894 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
896 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
)) {
897 ERROR("tty pathname too long");
901 ret
= symlink(lxcpath
, path
);
903 SYSERROR("failed to create symlink \"%s\" -> \"%s\"",
908 /* If we populated /dev, then we need to create
911 ret
= access(path
, F_OK
);
913 ret
= creat(path
, 0660);
915 SYSERROR("failed to create \"%s\"", path
);
916 /* this isn't fatal, continue */
922 ret
= mount(pty_info
->name
, path
, "none", MS_BIND
, 0);
924 SYSERROR("failed to mount '%s'->'%s'", pty_info
->name
, path
);
928 DEBUG("bind mounted \"%s\" onto \"%s\"", pty_info
->name
,
932 if (!append_ptyname(&conf
->pty_names
, pty_info
->name
)) {
933 ERROR("Error setting up container_ttys string");
938 INFO("finished setting up %d /dev/tty<N> device(s)", tty_info
->nbtty
);
942 static int setup_rootfs_pivot_root(const char *rootfs
)
944 int oldroot
= -1, newroot
= -1;
946 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
948 SYSERROR("Error opening old-/ for fchdir");
951 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
);
953 SYSERROR("Error opening new-/ for fchdir");
957 /* change into new root fs */
958 if (fchdir(newroot
)) {
959 SYSERROR("can't chdir to new rootfs '%s'", rootfs
);
963 /* pivot_root into our new root fs */
964 if (pivot_root(".", ".")) {
965 SYSERROR("pivot_root syscall failed");
970 * at this point the old-root is mounted on top of our new-root
971 * To unmounted it we must not be chdir'd into it, so escape back
974 if (fchdir(oldroot
) < 0) {
975 SYSERROR("Error entering oldroot");
978 if (umount2(".", MNT_DETACH
) < 0) {
979 SYSERROR("Error detaching old root");
983 if (fchdir(newroot
) < 0) {
984 SYSERROR("Error re-entering newroot");
991 DEBUG("pivot_root syscall to '%s' successful", rootfs
);
1003 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1004 * error, log it but don't fail yet.
1006 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1007 const char *lxcpath
)
1013 INFO("Preparing \"/dev\"");
1015 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1016 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1017 path
= alloca(clen
);
1019 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1020 if (ret
< 0 || (size_t)ret
>= clen
)
1023 if (!dir_exists(path
)) {
1024 WARN("\"/dev\" directory does not exist. Proceeding without "
1025 "autodev being set up");
1029 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1030 rootfs
->path
? rootfs
->mount
: NULL
);
1032 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1035 INFO("Mounted tmpfs on \"%s\"", path
);
1037 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1038 if (ret
< 0 || (size_t)ret
>= clen
)
1041 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1042 * If not, then create it and exit if that fails...
1044 if (!dir_exists(path
)) {
1045 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1047 SYSERROR("Failed to create directory \"%s\"", path
);
1052 INFO("Prepared \"/dev\"");
1063 static const struct lxc_devs lxc_devs
[] = {
1064 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1065 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1066 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1067 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1068 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1069 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1072 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1075 char path
[MAXPATHLEN
];
1079 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev",
1080 rootfs
->path
? rootfs
->mount
: "");
1081 if (ret
< 0 || ret
>= MAXPATHLEN
)
1084 /* ignore, just don't try to fill in */
1085 if (!dir_exists(path
))
1088 INFO("Populating \"/dev\"");
1090 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1091 for (i
= 0; i
< sizeof(lxc_devs
) / sizeof(lxc_devs
[0]); i
++) {
1092 const struct lxc_devs
*d
= &lxc_devs
[i
];
1094 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev/%s",
1095 rootfs
->path
? rootfs
->mount
: "", d
->name
);
1096 if (ret
< 0 || ret
>= MAXPATHLEN
)
1099 ret
= mknod(path
, d
->mode
, makedev(d
->maj
, d
->min
));
1102 char hostpath
[MAXPATHLEN
];
1104 if (errno
== EEXIST
) {
1105 DEBUG("\"%s\" device already existed", path
);
1109 /* Unprivileged containers cannot create devices, so
1110 * bind mount the device from the host.
1112 ret
= snprintf(hostpath
, MAXPATHLEN
, "/dev/%s", d
->name
);
1113 if (ret
< 0 || ret
>= MAXPATHLEN
)
1116 pathfile
= fopen(path
, "wb");
1118 SYSERROR("Failed to create file \"%s\"", path
);
1123 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1124 rootfs
->path
? rootfs
->mount
: NULL
);
1126 SYSERROR("Failed to bind mount \"%s\" from "
1127 "host into container",
1131 DEBUG("Bind mounted \"%s\" onto \"%s\"", hostpath
,
1134 DEBUG("Created device node \"%s\"", path
);
1139 INFO("Populated \"/dev\"");
1143 static int lxc_setup_rootfs(struct lxc_conf
*conf
)
1146 struct lxc_storage
*bdev
;
1147 const struct lxc_rootfs
*rootfs
;
1149 rootfs
= &conf
->rootfs
;
1150 if (!rootfs
->path
) {
1151 if (mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0)) {
1152 SYSERROR("Failed to make / rslave.");
1158 if (access(rootfs
->mount
, F_OK
)) {
1159 SYSERROR("Failed to access to \"%s\". Check it is present.",
1164 bdev
= storage_init(conf
, rootfs
->path
, rootfs
->mount
, rootfs
->options
);
1166 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1167 rootfs
->path
, rootfs
->mount
,
1168 rootfs
->options
? rootfs
->options
: "(null)");
1172 ret
= bdev
->ops
->mount(bdev
);
1175 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1176 rootfs
->path
, rootfs
->mount
,
1177 rootfs
->options
? rootfs
->options
: "(null)");
1181 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\".",
1182 rootfs
->path
, rootfs
->mount
,
1183 rootfs
->options
? rootfs
->options
: "(null)");
1188 int prepare_ramfs_root(char *root
)
1190 char buf
[LXC_LINELEN
], *p
;
1191 char nroot
[PATH_MAX
];
1196 if (realpath(root
, nroot
) == NULL
)
1199 if (chdir("/") == -1)
1203 * We could use here MS_MOVE, but in userns this mount is
1204 * locked and can't be moved.
1206 if (mount(root
, "/", NULL
, MS_REC
| MS_BIND
, NULL
) < 0) {
1207 SYSERROR("Failed to move %s into /", root
);
1211 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
) < 0) {
1212 SYSERROR("Failed to make . rprivate");
1217 * The following code cleans up inhereted mounts which are not
1220 * The mountinfo file shows not all mounts, if a few points have been
1221 * unmounted between read operations from the mountinfo. So we need to
1222 * read mountinfo a few times.
1224 * This loop can be skipped if a container uses unserns, because all
1225 * inherited mounts are locked and we should live with all this trash.
1230 f
= fopen("./proc/self/mountinfo", "r");
1232 SYSERROR("Unable to open /proc/self/mountinfo");
1235 while (fgets(buf
, LXC_LINELEN
, f
)) {
1236 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1237 p
= strchr(p
+1, ' ');
1240 p2
= strchr(p
+1, ' ');
1247 if (strcmp(p
+ 1, "/") == 0)
1249 if (strcmp(p
+ 1, "/proc") == 0)
1252 if (umount2(p
, MNT_DETACH
) == 0)
1260 /* This also can be skipped if a container uses unserns */
1261 umount2("./proc", MNT_DETACH
);
1263 /* It is weird, but chdir("..") moves us in a new root */
1264 if (chdir("..") == -1) {
1265 SYSERROR("Unable to change working directory");
1269 if (chroot(".") == -1) {
1270 SYSERROR("Unable to chroot");
1277 static int setup_pivot_root(const struct lxc_rootfs
*rootfs
)
1279 if (!rootfs
->path
) {
1280 DEBUG("container does not have a rootfs, so not doing pivot root");
1284 if (detect_ramfs_rootfs()) {
1285 DEBUG("detected that container is on ramfs");
1286 if (prepare_ramfs_root(rootfs
->mount
)) {
1287 ERROR("failed to prepare minimal ramfs root");
1291 DEBUG("prepared ramfs root for container");
1295 if (setup_rootfs_pivot_root(rootfs
->mount
) < 0) {
1296 ERROR("failed to pivot root");
1300 DEBUG("finished pivot root");
1304 static int lxc_setup_devpts(int num_pts
)
1307 const char *default_devpts_mntopts
= "newinstance,ptmxmode=0666,mode=0620,gid=5";
1308 char devpts_mntopts
[256];
1311 DEBUG("no new devpts instance will be mounted since no pts "
1312 "devices are requested");
1316 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%d",
1317 default_devpts_mntopts
, num_pts
);
1318 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1321 /* Unmount old devpts instance. */
1322 ret
= access("/dev/pts/ptmx", F_OK
);
1324 ret
= umount("/dev/pts");
1326 SYSERROR("failed to unmount old devpts instance");
1329 DEBUG("unmounted old /dev/pts instance");
1332 /* Create mountpoint for devpts instance. */
1333 ret
= mkdir("/dev/pts", 0755);
1334 if (ret
< 0 && errno
!= EEXIST
) {
1335 SYSERROR("failed to create the \"/dev/pts\" directory");
1339 /* Mount new devpts instance. */
1340 ret
= mount("devpts", "/dev/pts", "devpts", MS_MGC_VAL
, devpts_mntopts
);
1342 SYSERROR("failed to mount new devpts instance");
1345 DEBUG("mount new devpts instance with options \"%s\"", devpts_mntopts
);
1347 /* Remove any pre-existing /dev/ptmx file. */
1348 ret
= access("/dev/ptmx", F_OK
);
1350 ret
= remove("/dev/ptmx");
1352 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1355 DEBUG("removed existing \"/dev/ptmx\"");
1358 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1359 ret
= open("/dev/ptmx", O_CREAT
, 0666);
1361 SYSERROR("failed to create dummy \"/dev/ptmx\" file as bind mount target");
1365 DEBUG("created dummy \"/dev/ptmx\" file as bind mount target");
1367 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1368 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1370 DEBUG("bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1373 /* Fallthrough and try to create a symlink. */
1374 ERROR("failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1377 /* Remove the dummy /dev/ptmx file we created above. */
1378 ret
= remove("/dev/ptmx");
1380 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1384 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1385 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1387 SYSERROR("failed to create symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1390 DEBUG("created symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1395 static int setup_personality(int persona
)
1397 #if HAVE_SYS_PERSONALITY_H
1401 if (personality(persona
) < 0) {
1402 SYSERROR("failed to set personality to '0x%x'", persona
);
1406 INFO("set personality to '0x%x'", persona
);
1412 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1413 const struct lxc_console
*console
)
1415 char path
[MAXPATHLEN
];
1418 if (console
->path
&& !strcmp(console
->path
, "none"))
1421 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs
->mount
);
1422 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1425 /* When we are asked to setup a console we remove any previous
1426 * /dev/console bind-mounts.
1428 if (file_exists(path
)) {
1429 ret
= lxc_unstack_mountpoint(path
, false);
1431 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1434 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1439 SYSERROR("error unlinking %s", path
);
1444 /* For unprivileged containers autodev or automounts will already have
1445 * taken care of creating /dev/console.
1447 fd
= open(path
, O_CREAT
| O_EXCL
, S_IXUSR
| S_IXGRP
| S_IXOTH
);
1449 if (errno
!= EEXIST
) {
1450 SYSERROR("failed to create console");
1457 if (chmod(console
->name
, S_IXUSR
| S_IXGRP
| S_IXOTH
)) {
1458 SYSERROR("failed to set mode '0%o' to '%s'", S_IXUSR
| S_IXGRP
| S_IXOTH
, console
->name
);
1462 if (safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs
->mount
) < 0) {
1463 ERROR("failed to mount '%s' on '%s'", console
->name
, path
);
1467 DEBUG("mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1471 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1472 const struct lxc_console
*console
,
1476 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
1478 /* create rootfs/dev/<ttydir> directory */
1479 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs
->mount
, ttydir
);
1480 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1483 ret
= mkdir(path
, 0755);
1484 if (ret
&& errno
!= EEXIST
) {
1485 SYSERROR("failed with errno %d to create %s", errno
, path
);
1488 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1490 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs
->mount
, ttydir
);
1491 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1494 ret
= creat(lxcpath
, 0660);
1495 if (ret
== -1 && errno
!= EEXIST
) {
1496 SYSERROR("error %d creating %s", errno
, lxcpath
);
1502 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs
->mount
);
1503 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1506 /* When we are asked to setup a console we remove any previous
1507 * /dev/console bind-mounts.
1509 if (console
->path
&& !strcmp(console
->path
, "none")) {
1511 ret
= stat(path
, &st
);
1513 if (errno
== ENOENT
)
1515 SYSERROR("failed stat() \"%s\"", path
);
1519 /* /dev/console must be character device with major number 5 and
1520 * minor number 1. If not, give benefit of the doubt and assume
1521 * the user has mounted something else right there on purpose.
1523 if (((st
.st_mode
& S_IFMT
) != S_IFCHR
) || major(st
.st_rdev
) != 5 || minor(st
.st_rdev
) != 1)
1526 /* In case the user requested a bind-mount for /dev/console and
1527 * requests a ttydir we move the mount to the
1528 * /dev/<ttydir/console.
1529 * Note, we only move the uppermost mount and clear all other
1530 * mounts underneath for safety.
1531 * If it is a character device created via mknod() we simply
1534 ret
= safe_mount(path
, lxcpath
, "none", MS_MOVE
, NULL
, rootfs
->mount
);
1536 if (errno
!= EINVAL
) {
1537 ERROR("failed to MS_MOVE \"%s\" to \"%s\": %s", path
, lxcpath
, strerror(errno
));
1540 /* path was not a mountpoint */
1541 ret
= rename(path
, lxcpath
);
1543 ERROR("failed to rename \"%s\" to \"%s\": %s", path
, lxcpath
, strerror(errno
));
1546 DEBUG("renamed \"%s\" to \"%s\"", path
, lxcpath
);
1548 DEBUG("moved mount \"%s\" to \"%s\"", path
, lxcpath
);
1551 /* Clear all remaining bind-mounts. */
1552 ret
= lxc_unstack_mountpoint(path
, false);
1554 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1557 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1560 if (file_exists(path
)) {
1561 ret
= lxc_unstack_mountpoint(path
, false);
1563 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1566 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1570 if (safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs
->mount
) < 0) {
1571 ERROR("failed to mount '%s' on '%s'", console
->name
, lxcpath
);
1574 DEBUG("mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1577 /* create symlink from rootfs /dev/console to '<ttydir>/console' */
1578 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/console", ttydir
);
1579 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1583 if (ret
&& errno
!= ENOENT
) {
1584 SYSERROR("error unlinking %s", path
);
1588 ret
= symlink(lxcpath
, path
);
1590 SYSERROR("failed to create symlink for console from \"%s\" to \"%s\"", lxcpath
, path
);
1594 DEBUG("console has been setup under \"%s\" and symlinked to \"%s\"", lxcpath
, path
);
1598 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1599 const struct lxc_console
*console
, char *ttydir
)
1601 /* We don't have a rootfs, /dev/console will be shared. */
1602 if (!rootfs
->path
) {
1603 DEBUG("/dev/console will be shared with the host");
1608 return lxc_setup_dev_console(rootfs
, console
);
1610 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1613 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
)
1615 struct mount_opt
*mo
;
1617 /* If opt is found in mount_opt, set or clear flags.
1618 * Otherwise append it to data. */
1620 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1621 if (!strncmp(opt
, mo
->name
, strlen(mo
->name
))) {
1623 *flags
&= ~mo
->flag
;
1635 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
,
1639 char *p
, *saveptr
= NULL
;
1647 s
= strdup(mntopts
);
1649 SYSERROR("failed to allocate memory");
1653 data
= malloc(strlen(s
) + 1);
1655 SYSERROR("failed to allocate memory");
1661 for (p
= strtok_r(s
, ",", &saveptr
); p
!= NULL
;
1662 p
= strtok_r(NULL
, ",", &saveptr
))
1663 parse_mntopt(p
, mntflags
, &data
);
1674 static void null_endofword(char *word
)
1676 while (*word
&& *word
!= ' ' && *word
!= '\t')
1682 * skip @nfields spaces in @src
1684 static char *get_field(char *src
, int nfields
)
1689 for (i
= 0; i
< nfields
; i
++) {
1690 while (*p
&& *p
!= ' ' && *p
!= '\t')
1699 static int mount_entry(const char *fsname
, const char *target
,
1700 const char *fstype
, unsigned long mountflags
,
1701 const char *data
, int optional
, int dev
,
1709 ret
= safe_mount(fsname
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
1713 INFO("Failed to mount \"%s\" on \"%s\" (optional): %s",
1714 fsname
, target
, strerror(errno
));
1718 SYSERROR("Failed to mount \"%s\" on \"%s\"", fsname
, target
);
1722 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
1723 unsigned long rqd_flags
= 0;
1725 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
1727 fsname
? fsname
: "(none)", target
? target
: "(none)");
1729 if (mountflags
& MS_RDONLY
)
1730 rqd_flags
|= MS_RDONLY
;
1732 if (statvfs(fsname
, &sb
) == 0) {
1733 unsigned long required_flags
= rqd_flags
;
1735 if (sb
.f_flag
& MS_NOSUID
)
1736 required_flags
|= MS_NOSUID
;
1738 if (sb
.f_flag
& MS_NODEV
&& !dev
)
1739 required_flags
|= MS_NODEV
;
1741 if (sb
.f_flag
& MS_RDONLY
)
1742 required_flags
|= MS_RDONLY
;
1744 if (sb
.f_flag
& MS_NOEXEC
)
1745 required_flags
|= MS_NOEXEC
;
1747 DEBUG("Flags for \"%s\" were %lu, required extra flags "
1748 "are %lu", fsname
, sb
.f_flag
, required_flags
);
1750 /* If this was a bind mount request, and required_flags
1751 * does not have any flags which are not already in
1752 * mountflags, then skip the remount.
1754 if (!(mountflags
& MS_REMOUNT
)) {
1755 if (!(required_flags
& ~mountflags
) &&
1757 DEBUG("Mountflags already were %lu, "
1758 "skipping remount", mountflags
);
1763 mountflags
|= required_flags
;
1767 ret
= mount(fsname
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
1770 INFO("Failed to mount \"%s\" on \"%s\" "
1771 "(optional): %s", fsname
, target
,
1776 SYSERROR("Failed to mount \"%s\" on \"%s\"", fsname
, target
);
1784 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"", fsname
,
1790 /* Remove "optional", "create=dir", and "create=file" from mntopt */
1791 static void cull_mntent_opt(struct mntent
*mntent
)
1794 char *list
[] = {"create=dir", "create=file", "optional", NULL
};
1796 for (i
= 0; list
[i
]; i
++) {
1799 p
= strstr(mntent
->mnt_opts
, list
[i
]);
1803 p2
= strchr(p
, ',');
1805 /* no more mntopts, so just chop it here */
1810 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
1814 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
1816 const struct lxc_rootfs
*rootfs
,
1817 const char *lxc_name
,
1818 const char *lxc_path
)
1822 if (!strncmp(mntent
->mnt_type
, "overlay", 7))
1823 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
1824 else if (!strncmp(mntent
->mnt_type
, "aufs", 4))
1825 ret
= aufs_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
1829 if (hasmntopt(mntent
, "create=dir")) {
1830 ret
= mkdir_p(path
, 0755);
1831 if (ret
< 0 && errno
!= EEXIST
) {
1832 SYSERROR("Failed to create directory \"%s\"", path
);
1837 if (hasmntopt(mntent
, "create=file") && access(path
, F_OK
)) {
1847 ret
= mkdir_p(p2
, 0755);
1849 if (ret
< 0 && errno
!= EEXIST
) {
1850 SYSERROR("Failed to create directory \"%s\"", path
);
1854 fd
= open(path
, O_CREAT
, 0644);
1863 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
1864 * without a rootfs. */
1865 static inline int mount_entry_on_generic(struct mntent
*mntent
,
1867 const struct lxc_rootfs
*rootfs
,
1868 const char *lxc_name
,
1869 const char *lxc_path
)
1872 unsigned long mntflags
;
1875 char *rootfs_path
= NULL
;
1877 optional
= hasmntopt(mntent
, "optional") != NULL
;
1878 dev
= hasmntopt(mntent
, "dev") != NULL
;
1880 if (rootfs
&& rootfs
->path
)
1881 rootfs_path
= rootfs
->mount
;
1883 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
1891 cull_mntent_opt(mntent
);
1893 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
1897 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
1898 mntdata
, optional
, dev
, rootfs_path
);
1904 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
1907 char path
[MAXPATHLEN
];
1909 /* For containers created without a rootfs all mounts are treated as
1910 * absolute paths starting at / on the host.
1912 if (mntent
->mnt_dir
[0] != '/')
1913 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
1915 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
1916 if (ret
< 0 || ret
>= sizeof(path
))
1919 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
1922 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
1923 const struct lxc_rootfs
*rootfs
,
1924 const char *lxc_name
,
1925 const char *lxc_path
)
1929 const char *lxcpath
;
1930 char path
[MAXPATHLEN
];
1933 lxcpath
= lxc_global_config_value("lxc.lxcpath");
1937 /* If rootfs->path is a blockdev path, allow container fstab to use
1938 * <lxcpath>/<name>/rootfs" as the target prefix.
1940 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, lxc_name
);
1941 if (ret
< 0 || ret
>= MAXPATHLEN
)
1944 aux
= strstr(mntent
->mnt_dir
, path
);
1946 offset
= strlen(path
);
1951 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
1953 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
1956 offset
= strlen(rootfs
->path
);
1959 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", rootfs
->mount
, aux
+ offset
);
1960 if (ret
< 0 || ret
>= MAXPATHLEN
)
1963 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
1966 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
1967 const struct lxc_rootfs
*rootfs
,
1968 const char *lxc_name
,
1969 const char *lxc_path
)
1971 char path
[MAXPATHLEN
];
1974 /* relative to root mount point */
1975 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
1976 if (ret
< 0 || ret
>= sizeof(path
)) {
1977 ERROR("path name too long");
1981 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
1984 /* This logs a NOTICE() when a user specifies mounts that would conflict with
1985 * devices liblxc sets up automatically.
1987 static void log_notice_on_conflict(const struct lxc_conf
*conf
, const char *src
,
1990 char *clean_mnt_fsname
, *clean_mnt_dir
, *tmp
;
1991 bool needs_warning
= false;
1993 clean_mnt_fsname
= lxc_deslashify(src
);
1994 if (!clean_mnt_fsname
)
1997 clean_mnt_dir
= lxc_deslashify(dest
);
1998 if (!clean_mnt_dir
) {
1999 free(clean_mnt_fsname
);
2003 tmp
= clean_mnt_dir
;
2007 if (strncmp(src
, "/dev", 4) || strncmp(tmp
, "dev", 3)) {
2008 free(clean_mnt_dir
);
2009 free(clean_mnt_fsname
);
2013 if (!conf
->autodev
&& !conf
->pts
&& !conf
->tty
&&
2014 (!conf
->console
.path
|| !strcmp(conf
->console
.path
, "none"))) {
2015 free(clean_mnt_dir
);
2016 free(clean_mnt_fsname
);
2020 if (!strcmp(tmp
, "dev") && conf
->autodev
> 0)
2021 needs_warning
= true;
2022 else if (!strcmp(tmp
, "dev/pts") && (conf
->autodev
> 0 || conf
->pts
> 0))
2023 needs_warning
= true;
2024 else if (!strcmp(tmp
, "dev/ptmx") && (conf
->autodev
> 0 || conf
->pts
> 0))
2025 needs_warning
= true;
2026 else if (!strcmp(tmp
, "dev/pts/ptmx") && (conf
->autodev
> 0 || conf
->pts
> 0))
2027 needs_warning
= true;
2028 else if (!strcmp(tmp
, "dev/null") && conf
->autodev
> 0)
2029 needs_warning
= true;
2030 else if (!strcmp(tmp
, "dev/zero") && conf
->autodev
> 0)
2031 needs_warning
= true;
2032 else if (!strcmp(tmp
, "dev/full") && conf
->autodev
> 0)
2033 needs_warning
= true;
2034 else if (!strcmp(tmp
, "dev/urandom") && conf
->autodev
> 0)
2035 needs_warning
= true;
2036 else if (!strcmp(tmp
, "dev/random") && conf
->autodev
> 0)
2037 needs_warning
= true;
2038 else if (!strcmp(tmp
, "dev/tty") && conf
->autodev
> 0)
2039 needs_warning
= true;
2040 else if (!strncmp(tmp
, "dev/tty", 7) && (conf
->autodev
> 0 || conf
->tty
> 0))
2041 needs_warning
= true;
2044 NOTICE("Requesting to mount \"%s\" on \"%s\" while requesting "
2045 "automatic device setup under \"/dev\"",
2046 clean_mnt_fsname
, clean_mnt_dir
);
2048 free(clean_mnt_dir
);
2049 free(clean_mnt_fsname
);
2052 static int mount_file_entries(const struct lxc_conf
*conf
,
2053 const struct lxc_rootfs
*rootfs
, FILE *file
,
2054 const char *lxc_name
, const char *lxc_path
)
2056 struct mntent mntent
;
2060 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2061 log_notice_on_conflict(conf
, mntent
.mnt_fsname
, mntent
.mnt_dir
);
2064 ret
= mount_entry_on_systemfs(&mntent
);
2065 else if (mntent
.mnt_dir
[0] != '/')
2066 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2067 lxc_name
, lxc_path
);
2069 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2070 lxc_name
, lxc_path
);
2076 INFO("Set up mount entries");
2080 static int setup_mount(const struct lxc_conf
*conf
,
2081 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2082 const char *lxc_name
, const char *lxc_path
)
2090 f
= setmntent(fstab
, "r");
2092 SYSERROR("Failed to open \"%s\"", fstab
);
2096 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2098 ERROR("Failed to set up mount entries");
2104 FILE *make_anonymous_mount_file(struct lxc_list
*mount
)
2108 struct lxc_list
*iterator
;
2112 fd
= memfd_create("lxc_mount_file", MFD_CLOEXEC
);
2114 if (errno
!= ENOSYS
)
2117 TRACE("Created temporary mount file");
2119 f
= fdopen(fd
, "r+");
2120 TRACE("Created anonymous mount file");
2124 SYSERROR("Could not create mount file");
2130 lxc_list_for_each(iterator
, mount
) {
2131 mount_entry
= iterator
->elem
;
2132 ret
= fprintf(f
, "%s\n", mount_entry
);
2133 if (ret
< strlen(mount_entry
))
2134 WARN("Could not write mount entry to mount file");
2137 ret
= fseek(f
, 0, SEEK_SET
);
2139 SYSERROR("Failed to seek mount file");
2147 static int setup_mount_entries(const struct lxc_conf
*conf
,
2148 const struct lxc_rootfs
*rootfs
,
2149 struct lxc_list
*mount
, const char *lxc_name
,
2150 const char *lxc_path
)
2155 f
= make_anonymous_mount_file(mount
);
2159 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2165 static int parse_cap(const char *cap
)
2171 if (!strcmp(cap
, "none"))
2174 for (i
= 0; i
< sizeof(caps_opt
)/sizeof(caps_opt
[0]); i
++) {
2176 if (strcmp(cap
, caps_opt
[i
].name
))
2179 capid
= caps_opt
[i
].value
;
2184 /* try to see if it's numeric, so the user may specify
2185 * capabilities that the running kernel knows about but
2188 capid
= strtol(cap
, &ptr
, 10);
2189 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2190 /* not a valid number */
2192 else if (capid
> lxc_caps_last_cap())
2193 /* we have a number but it's not a valid
2201 int in_caplist(int cap
, struct lxc_list
*caps
)
2203 struct lxc_list
*iterator
;
2206 lxc_list_for_each(iterator
, caps
) {
2207 capid
= parse_cap(iterator
->elem
);
2215 static int setup_caps(struct lxc_list
*caps
)
2217 struct lxc_list
*iterator
;
2221 lxc_list_for_each(iterator
, caps
) {
2223 drop_entry
= iterator
->elem
;
2225 capid
= parse_cap(drop_entry
);
2228 ERROR("unknown capability %s", drop_entry
);
2232 DEBUG("drop capability '%s' (%d)", drop_entry
, capid
);
2234 if (prctl(PR_CAPBSET_DROP
, capid
, 0, 0, 0)) {
2235 SYSERROR("failed to remove %s capability", drop_entry
);
2241 DEBUG("capabilities have been setup");
2246 static int dropcaps_except(struct lxc_list
*caps
)
2248 struct lxc_list
*iterator
;
2251 int numcaps
= lxc_caps_last_cap() + 1;
2252 INFO("found %d capabilities", numcaps
);
2254 if (numcaps
<= 0 || numcaps
> 200)
2257 /* caplist[i] is 1 if we keep capability i */
2258 int *caplist
= alloca(numcaps
* sizeof(int));
2259 memset(caplist
, 0, numcaps
* sizeof(int));
2261 lxc_list_for_each(iterator
, caps
) {
2263 keep_entry
= iterator
->elem
;
2265 capid
= parse_cap(keep_entry
);
2271 ERROR("unknown capability %s", keep_entry
);
2275 DEBUG("keep capability '%s' (%d)", keep_entry
, capid
);
2279 for (i
=0; i
<numcaps
; i
++) {
2282 if (prctl(PR_CAPBSET_DROP
, i
, 0, 0, 0)) {
2283 SYSERROR("failed to remove capability %d", i
);
2288 DEBUG("capabilities have been setup");
2293 static int parse_resource(const char *res
) {
2297 for (i
= 0; i
< sizeof(limit_opt
)/sizeof(limit_opt
[0]); ++i
) {
2298 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2299 return limit_opt
[i
].value
;
2302 /* try to see if it's numeric, so the user may specify
2303 * resources that the running kernel knows about but
2305 if (lxc_safe_int(res
, &resid
) == 0)
2310 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
) {
2311 struct lxc_list
*it
;
2312 struct lxc_limit
*lim
;
2315 lxc_list_for_each(it
, limits
) {
2318 resid
= parse_resource(lim
->resource
);
2320 ERROR("unknown resource %s", lim
->resource
);
2324 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2325 ERROR("failed to set limit %s: %s", lim
->resource
, strerror(errno
));
2332 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2334 struct lxc_conf
*lxc_conf_init(void)
2336 struct lxc_conf
*new;
2339 new = malloc(sizeof(*new));
2341 ERROR("lxc_conf_init : %s", strerror(errno
));
2344 memset(new, 0, sizeof(*new));
2346 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2347 new->personality
= -1;
2349 new->console
.log_path
= NULL
;
2350 new->console
.log_fd
= -1;
2351 new->console
.path
= NULL
;
2352 new->console
.peer
= -1;
2353 new->console
.peerpty
.busy
= -1;
2354 new->console
.peerpty
.master
= -1;
2355 new->console
.peerpty
.slave
= -1;
2356 new->console
.master
= -1;
2357 new->console
.slave
= -1;
2358 new->console
.name
[0] = '\0';
2359 new->maincmd_fd
= -1;
2361 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2362 if (!new->rootfs
.mount
) {
2363 ERROR("lxc_conf_init : %s", strerror(errno
));
2368 lxc_list_init(&new->cgroup
);
2369 lxc_list_init(&new->network
);
2370 lxc_list_init(&new->mount_list
);
2371 lxc_list_init(&new->caps
);
2372 lxc_list_init(&new->keepcaps
);
2373 lxc_list_init(&new->id_map
);
2374 lxc_list_init(&new->includes
);
2375 lxc_list_init(&new->aliens
);
2376 lxc_list_init(&new->environment
);
2377 lxc_list_init(&new->limits
);
2378 for (i
=0; i
<NUM_LXC_HOOKS
; i
++)
2379 lxc_list_init(&new->hooks
[i
]);
2380 lxc_list_init(&new->groups
);
2381 new->lsm_aa_profile
= NULL
;
2382 new->lsm_se_context
= NULL
;
2383 new->tmp_umount_proc
= 0;
2385 for (i
= 0; i
< LXC_NS_MAX
; i
++)
2386 new->inherit_ns_fd
[i
] = -1;
2388 /* if running in a new user namespace, init and COMMAND
2389 * default to running as UID/GID 0 when using lxc-execute */
2392 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2397 static int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2400 char path
[MAXPATHLEN
];
2403 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/%cid_map", pid
,
2404 idtype
== ID_TYPE_UID
? 'u' : 'g');
2405 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2406 ERROR("failed to create path \"%s\"", path
);
2410 fd
= open(path
, O_WRONLY
);
2412 SYSERROR("failed to open \"%s\"", path
);
2417 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2418 if (ret
!= buf_size
) {
2419 SYSERROR("failed to write %cid mapping to \"%s\"",
2420 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2429 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2431 * @return 1 if functional binary was found
2432 * @return 0 if binary exists but is lacking privilege
2433 * @return -ENOENT if binary does not exist
2434 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2437 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2444 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2447 path
= on_path(binary
, NULL
);
2451 ret
= stat(path
, &st
);
2457 /* Check if the binary is setuid. */
2458 if (st
.st_mode
& S_ISUID
) {
2459 DEBUG("The binary \"%s\" does have the setuid bit set.", path
);
2464 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2465 /* Check if it has the CAP_SETUID capability. */
2466 if ((cap
& CAP_SETUID
) &&
2467 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2468 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2469 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2470 "and CAP_PERMITTED sets.", path
);
2475 /* Check if it has the CAP_SETGID capability. */
2476 if ((cap
& CAP_SETGID
) &&
2477 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2478 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2479 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2480 "and CAP_PERMITTED sets.", path
);
2485 /* If we cannot check for file capabilities we need to give the benefit
2486 * of the doubt. Otherwise we might fail even though all the necessary
2487 * file capabilities are set.
2489 DEBUG("Cannot check for file capabilites as full capability support is "
2490 "missing. Manual intervention needed.");
2499 int lxc_map_ids_exec_wrapper(void *args
)
2501 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2505 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2508 struct lxc_list
*iterator
;
2513 char cmd_output
[MAXPATHLEN
];
2514 /* strlen("new@idmap") = 9
2522 * We add some additional space to make sure that we really have
2523 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2525 char mapbuf
[9 + 1 + LXC_NUMSTRLEN64
+ 1 + LXC_IDMAPLEN
] = {0};
2526 int ret
= 0, uidmap
= 0, gidmap
= 0;
2527 bool use_shadow
= false, had_entry
= false;
2529 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2530 * ranges, then insist that root also reserve ranges in subuid. This
2531 * will protected it by preventing another user from being handed the
2534 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2535 if (uidmap
== -ENOENT
)
2536 WARN("newuidmap binary is missing");
2538 WARN("newuidmap is lacking necessary privileges");
2540 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2541 if (gidmap
== -ENOENT
)
2542 WARN("newgidmap binary is missing");
2544 WARN("newgidmap is lacking necessary privileges");
2546 if (uidmap
> 0 && gidmap
> 0) {
2547 DEBUG("Functional newuidmap and newgidmap binary found.");
2550 /* In case unprivileged users run application containers via
2551 * execute() or a start*() there are valid cases where they may
2552 * only want to map their own {g,u}id. Let's not block them from
2553 * doing so by requiring geteuid() == 0.
2555 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2556 "write directly with euid %d.", geteuid());
2559 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
2560 type
++, u_or_g
= 'g') {
2564 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
2566 lxc_list_for_each(iterator
, idmap
) {
2567 /* The kernel only takes <= 4k for writes to
2568 * /proc/<nr>/[ug]id_map
2570 map
= iterator
->elem
;
2571 if (map
->idtype
!= type
)
2576 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
2577 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
2578 use_shadow
? " " : "", map
->nsid
,
2579 map
->hostid
, map
->range
,
2580 use_shadow
? "" : "\n");
2581 if (fill
<= 0 || fill
>= left
)
2582 SYSERROR("Too many {g,u}id mappings defined.");
2589 /* Try to catch the ouput of new{g,u}idmap to make debugging
2593 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2594 lxc_map_ids_exec_wrapper
,
2597 ERROR("new%cidmap failed to write mapping: %s",
2598 u_or_g
, cmd_output
);
2602 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
2607 memset(mapbuf
, 0, sizeof(mapbuf
));
2614 * return the host uid/gid to which the container root is mapped in
2616 * Return true if id was found, false otherwise.
2618 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
2621 struct lxc_list
*it
;
2624 lxc_list_for_each(it
, &conf
->id_map
) {
2626 if (map
->idtype
!= idtype
)
2636 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
2638 struct lxc_list
*it
;
2640 lxc_list_for_each(it
, &conf
->id_map
) {
2642 if (map
->idtype
!= idtype
)
2644 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
2645 return (id
- map
->hostid
) + map
->nsid
;
2650 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
2652 struct lxc_list
*it
;
2654 unsigned int freeid
= 0;
2656 lxc_list_for_each(it
, &conf
->id_map
) {
2658 if (map
->idtype
!= idtype
)
2660 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
2661 freeid
= map
->nsid
+ map
->range
;
2668 int lxc_create_tty(const char *name
, struct lxc_conf
*conf
)
2670 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
2673 /* no tty in the configuration */
2677 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
) * conf
->tty
);
2678 if (!tty_info
->pty_info
) {
2679 SYSERROR("failed to allocate struct *pty_info");
2683 for (i
= 0; i
< conf
->tty
; i
++) {
2684 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
2687 ret
= openpty(&pty_info
->master
, &pty_info
->slave
,
2688 pty_info
->name
, NULL
, NULL
);
2691 SYSERROR("failed to create pty device number %d", i
);
2692 tty_info
->nbtty
= i
;
2693 lxc_delete_tty(tty_info
);
2697 DEBUG("allocated pty \"%s\" with master fd %d and slave fd %d",
2698 pty_info
->name
, pty_info
->master
, pty_info
->slave
);
2700 /* Prevent leaking the file descriptors to the container */
2701 ret
= fcntl(pty_info
->master
, F_SETFD
, FD_CLOEXEC
);
2703 WARN("failed to set FD_CLOEXEC flag on master fd %d of "
2704 "pty device \"%s\": %s",
2705 pty_info
->master
, pty_info
->name
, strerror(errno
));
2707 ret
= fcntl(pty_info
->slave
, F_SETFD
, FD_CLOEXEC
);
2709 WARN("failed to set FD_CLOEXEC flag on slave fd %d of "
2710 "pty device \"%s\": %s",
2711 pty_info
->slave
, pty_info
->name
, strerror(errno
));
2716 tty_info
->nbtty
= conf
->tty
;
2718 INFO("finished allocating %d pts devices", conf
->tty
);
2722 void lxc_delete_tty(struct lxc_tty_info
*tty_info
)
2726 for (i
= 0; i
< tty_info
->nbtty
; i
++) {
2727 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
2729 close(pty_info
->master
);
2730 close(pty_info
->slave
);
2733 free(tty_info
->pty_info
);
2734 tty_info
->pty_info
= NULL
;
2735 tty_info
->nbtty
= 0;
2739 int chown_mapped_root_exec_wrapper(void *args
)
2741 execvp("lxc-usernsexec", args
);
2746 * chown_mapped_root: for an unprivileged user with uid/gid X to
2747 * chown a dir to subuid/subgid Y, he needs to run chown as root
2748 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
2749 * nsid Y is mapped to hostuid/hostgid X. That way, the container
2750 * root is privileged with respect to hostuid/hostgid X, allowing
2751 * him to do the chown.
2753 int chown_mapped_root(char *path
, struct lxc_conf
*conf
)
2755 uid_t rootuid
, rootgid
;
2757 int hostuid
, hostgid
, ret
;
2759 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
2761 char *args1
[] = {"lxc-usernsexec",
2766 "--", "chown", ugid
, path
,
2768 char *args2
[] = {"lxc-usernsexec",
2774 "--", "chown", ugid
, path
,
2776 char cmd_output
[MAXPATHLEN
];
2778 hostuid
= geteuid();
2779 hostgid
= getegid();
2781 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
2782 ERROR("No uid mapping for container root");
2785 rootuid
= (uid_t
)val
;
2786 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
2787 ERROR("No gid mapping for container root");
2790 rootgid
= (gid_t
)val
;
2793 if (chown(path
, rootuid
, rootgid
) < 0) {
2794 ERROR("Error chowning %s", path
);
2800 if (rootuid
== hostuid
) {
2802 INFO("Container root is our uid; no need to chown");
2806 /* save the current gid of "path" */
2807 if (stat(path
, &sb
) < 0) {
2808 ERROR("Error stat %s", path
);
2812 /* Update the path argument in case this was overlayfs. */
2813 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
2814 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
2817 * A file has to be group-owned by a gid mapped into the
2818 * container, or the container won't be privileged over it.
2820 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
2821 if (sb
.st_uid
== hostuid
&&
2822 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
2823 chown(path
, -1, hostgid
) < 0) {
2824 ERROR("Failed chgrping %s", path
);
2828 /* "u:0:rootuid:1" */
2829 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
2830 if (ret
< 0 || ret
>= 100) {
2831 ERROR("Error uid printing map string");
2835 /* "u:hostuid:hostuid:1" */
2836 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
2837 if (ret
< 0 || ret
>= 100) {
2838 ERROR("Error uid printing map string");
2842 /* "g:0:rootgid:1" */
2843 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
2844 if (ret
< 0 || ret
>= 100) {
2845 ERROR("Error gid printing map string");
2849 /* "g:pathgid:rootgid+pathgid:1" */
2850 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
2851 rootgid
+ (gid_t
)sb
.st_gid
);
2852 if (ret
< 0 || ret
>= 100) {
2853 ERROR("Error gid printing map string");
2857 /* "g:hostgid:hostgid:1" */
2858 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
2859 if (ret
< 0 || ret
>= 100) {
2860 ERROR("Error gid printing map string");
2864 /* "0:pathgid" (chown) */
2865 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
2866 if (ret
< 0 || ret
>= 100) {
2867 ERROR("Error owner printing format string for chown");
2871 if (hostgid
== sb
.st_gid
)
2872 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2873 chown_mapped_root_exec_wrapper
,
2876 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2877 chown_mapped_root_exec_wrapper
,
2880 ERROR("lxc-usernsexec failed: %s", cmd_output
);
2885 int lxc_ttys_shift_ids(struct lxc_conf
*c
)
2887 if (lxc_list_empty(&c
->id_map
))
2890 if (!strcmp(c
->console
.name
, ""))
2893 if (chown_mapped_root(c
->console
.name
, c
) < 0) {
2894 ERROR("failed to chown console \"%s\"", c
->console
.name
);
2898 TRACE("chowned console \"%s\"", c
->console
.name
);
2903 /* NOTE: Must not be called from inside the container namespace! */
2904 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
2908 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
2909 if (mounted
== -1) {
2910 SYSERROR("failed to mount /proc in the container");
2911 /* continue only if there is no rootfs */
2912 if (conf
->rootfs
.path
)
2914 } else if (mounted
== 1) {
2915 conf
->tmp_umount_proc
= 1;
2921 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
2923 if (lxc_conf
->tmp_umount_proc
== 1) {
2925 lxc_conf
->tmp_umount_proc
= 0;
2929 void remount_all_slave(void)
2931 /* walk /proc/mounts and change any shared entries to slave */
2932 FILE *f
= fopen("/proc/self/mountinfo", "r");
2937 SYSERROR("Failed to open /proc/self/mountinfo to mark all shared");
2938 ERROR("Continuing container startup...");
2942 while (getline(&line
, &len
, f
) != -1) {
2943 char *target
, *opts
;
2944 target
= get_field(line
, 4);
2947 opts
= get_field(target
, 2);
2950 null_endofword(opts
);
2951 if (!strstr(opts
, "shared"))
2953 null_endofword(target
);
2954 if (mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
)) {
2955 SYSERROR("Failed to make %s rslave", target
);
2956 ERROR("Continuing...");
2963 void lxc_execute_bind_init(struct lxc_conf
*conf
)
2966 char path
[PATH_MAX
], destpath
[PATH_MAX
], *p
;
2968 /* If init exists in the container, don't bind mount a static one */
2969 p
= choose_init(conf
->rootfs
.mount
);
2975 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
2976 if (ret
< 0 || ret
>= PATH_MAX
) {
2977 WARN("Path name too long searching for lxc.init.static");
2981 if (!file_exists(path
)) {
2982 INFO("%s does not exist on host", path
);
2986 ret
= snprintf(destpath
, PATH_MAX
, "%s%s", conf
->rootfs
.mount
, "/init.lxc.static");
2987 if (ret
< 0 || ret
>= PATH_MAX
) {
2988 WARN("Path name too long for container's lxc.init.static");
2992 if (!file_exists(destpath
)) {
2993 FILE * pathfile
= fopen(destpath
, "wb");
2995 SYSERROR("Failed to create mount target '%s'", destpath
);
3001 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3003 SYSERROR("Failed to bind lxc.init.static into container");
3004 INFO("lxc.init.static bound into container at %s", path
);
3008 * This does the work of remounting / if it is shared, calling the
3009 * container pre-mount hooks, and mounting the rootfs.
3011 int do_rootfs_setup(struct lxc_conf
*conf
, const char *name
, const char *lxcpath
)
3013 if (conf
->rootfs_setup
) {
3015 * rootfs was set up in another namespace. bind-mount it
3016 * to give us a mount in our own ns so we can pivot_root to it
3018 const char *path
= conf
->rootfs
.mount
;
3019 if (mount(path
, path
, "rootfs", MS_BIND
, NULL
) < 0) {
3020 ERROR("Failed to bind-mount container / onto itself");
3026 remount_all_slave();
3028 if (run_lxc_hooks(name
, "pre-mount", conf
, lxcpath
, NULL
)) {
3029 ERROR("failed to run pre-mount hooks for container '%s'.", name
);
3033 if (lxc_setup_rootfs(conf
)) {
3034 ERROR("failed to setup rootfs for '%s'", name
);
3038 conf
->rootfs_setup
= true;
3042 static bool verify_start_hooks(struct lxc_conf
*conf
)
3044 struct lxc_list
*it
;
3045 char path
[MAXPATHLEN
];
3046 lxc_list_for_each(it
, &conf
->hooks
[LXCHOOK_START
]) {
3047 char *hookname
= it
->elem
;
3051 ret
= snprintf(path
, MAXPATHLEN
, "%s%s",
3052 conf
->rootfs
.path
? conf
->rootfs
.mount
: "", hookname
);
3053 if (ret
< 0 || ret
>= MAXPATHLEN
)
3055 ret
= stat(path
, &st
);
3057 SYSERROR("Start hook %s not found in container",
3067 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
3070 struct lxc_conf
*conf
= handler
->conf
;
3071 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
3072 int sock
= handler
->data_sock
[0];
3078 for (i
= 0; i
< conf
->tty
; i
++) {
3080 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
3082 ttyfds
[0] = pty_info
->master
;
3083 ttyfds
[1] = pty_info
->slave
;
3085 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
3089 TRACE("Send pty \"%s\" with master fd %d and slave fd %d to "
3090 "parent", pty_info
->name
, pty_info
->master
, pty_info
->slave
);
3094 ERROR("Failed to send %d ttys to parent: %s", conf
->tty
,
3097 TRACE("Sent %d ttys to parent", conf
->tty
);
3099 close(handler
->data_sock
[0]);
3100 close(handler
->data_sock
[1]);
3101 lxc_delete_tty(tty_info
);
3106 int lxc_setup(struct lxc_handler
*handler
)
3108 const char *name
= handler
->name
;
3109 struct lxc_conf
*lxc_conf
= handler
->conf
;
3110 const char *lxcpath
= handler
->lxcpath
;
3112 if (do_rootfs_setup(lxc_conf
, name
, lxcpath
) < 0) {
3113 ERROR("Error setting up rootfs mount after spawn");
3117 if (lxc_conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1) {
3118 if (setup_utsname(lxc_conf
->utsname
)) {
3119 ERROR("failed to setup the utsname for '%s'", name
);
3124 if (lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
)) {
3125 ERROR("failed to setup the network for '%s'", name
);
3129 if (lxc_network_send_name_and_ifindex_to_parent(handler
) < 0) {
3130 ERROR("Failed to network device names and ifindices to parent");
3134 if (lxc_conf
->autodev
> 0) {
3135 if (mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
)) {
3136 ERROR("failed to mount /dev in the container");
3141 /* do automatic mounts (mainly /proc and /sys), but exclude
3142 * those that need to wait until other stuff has finished
3144 if (lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
) < 0) {
3145 ERROR("failed to setup the automatic mounts for '%s'", name
);
3149 if (setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
)) {
3150 ERROR("failed to setup the mounts for '%s'", name
);
3154 if (!lxc_list_empty(&lxc_conf
->mount_list
) && setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
, &lxc_conf
->mount_list
, name
, lxcpath
)) {
3155 ERROR("failed to setup the mount entries for '%s'", name
);
3159 /* Make sure any start hooks are in the container */
3160 if (!verify_start_hooks(lxc_conf
))
3163 if (lxc_conf
->is_execute
)
3164 lxc_execute_bind_init(lxc_conf
);
3166 /* now mount only cgroup, if wanted;
3167 * before, /sys could not have been mounted
3168 * (is either mounted automatically or via fstab entries)
3170 if (lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
) < 0) {
3171 ERROR("failed to setup the automatic mounts for '%s'", name
);
3175 if (run_lxc_hooks(name
, "mount", lxc_conf
, lxcpath
, NULL
)) {
3176 ERROR("failed to run mount hooks for container '%s'.", name
);
3180 if (lxc_conf
->autodev
> 0) {
3181 if (run_lxc_hooks(name
, "autodev", lxc_conf
, lxcpath
, NULL
)) {
3182 ERROR("failed to run autodev hooks for container '%s'.", name
);
3186 if (lxc_fill_autodev(&lxc_conf
->rootfs
)) {
3187 ERROR("failed to populate /dev in the container");
3192 if (!lxc_conf
->is_execute
&& lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
, lxc_conf
->ttydir
)) {
3193 ERROR("failed to setup the console for '%s'", name
);
3197 if (!lxc_conf
->is_execute
&& setup_dev_symlinks(&lxc_conf
->rootfs
)) {
3198 ERROR("failed to setup /dev symlinks for '%s'", name
);
3202 /* mount /proc if it's not already there */
3203 if (lxc_create_tmp_proc_mount(lxc_conf
) < 0) {
3204 ERROR("failed to LSM mount proc for '%s'", name
);
3208 if (setup_pivot_root(&lxc_conf
->rootfs
)) {
3209 ERROR("failed to set rootfs for '%s'", name
);
3213 if (lxc_setup_devpts(lxc_conf
->pts
)) {
3214 ERROR("failed to setup the new pts instance");
3218 if (lxc_create_tty(name
, lxc_conf
)) {
3219 ERROR("failed to create the ttys");
3223 if (lxc_send_ttys_to_parent(handler
) < 0) {
3224 ERROR("failure sending console info to parent");
3228 if (!lxc_conf
->is_execute
&& lxc_setup_tty(lxc_conf
)) {
3229 ERROR("failed to setup the ttys for '%s'", name
);
3233 if (lxc_conf
->pty_names
&& setenv("container_ttys", lxc_conf
->pty_names
, 1))
3234 SYSERROR("failed to set environment variable for container ptys");
3237 if (setup_personality(lxc_conf
->personality
)) {
3238 ERROR("failed to setup personality");
3242 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3243 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3244 ERROR("Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both.");
3247 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3248 ERROR("failed to keep requested caps");
3251 } else if (setup_caps(&lxc_conf
->caps
)) {
3252 ERROR("failed to drop capabilities");
3256 NOTICE("Container \"%s\" is set up", name
);
3261 int run_lxc_hooks(const char *name
, char *hook
, struct lxc_conf
*conf
,
3262 const char *lxcpath
, char *argv
[])
3265 struct lxc_list
*it
;
3267 if (strcmp(hook
, "pre-start") == 0)
3268 which
= LXCHOOK_PRESTART
;
3269 else if (strcmp(hook
, "pre-mount") == 0)
3270 which
= LXCHOOK_PREMOUNT
;
3271 else if (strcmp(hook
, "mount") == 0)
3272 which
= LXCHOOK_MOUNT
;
3273 else if (strcmp(hook
, "autodev") == 0)
3274 which
= LXCHOOK_AUTODEV
;
3275 else if (strcmp(hook
, "start") == 0)
3276 which
= LXCHOOK_START
;
3277 else if (strcmp(hook
, "stop") == 0)
3278 which
= LXCHOOK_STOP
;
3279 else if (strcmp(hook
, "post-stop") == 0)
3280 which
= LXCHOOK_POSTSTOP
;
3281 else if (strcmp(hook
, "clone") == 0)
3282 which
= LXCHOOK_CLONE
;
3283 else if (strcmp(hook
, "destroy") == 0)
3284 which
= LXCHOOK_DESTROY
;
3287 lxc_list_for_each(it
, &conf
->hooks
[which
]) {
3289 char *hookname
= it
->elem
;
3290 ret
= run_script_argv(name
, "lxc", hookname
, hook
, lxcpath
, argv
);
3297 int lxc_clear_config_caps(struct lxc_conf
*c
)
3299 struct lxc_list
*it
, *next
;
3301 lxc_list_for_each_safe(it
, &c
->caps
, next
) {
3309 static int lxc_free_idmap(struct lxc_list
*id_map
) {
3310 struct lxc_list
*it
, *next
;
3312 lxc_list_for_each_safe(it
, id_map
, next
) {
3320 int lxc_clear_idmaps(struct lxc_conf
*c
)
3322 return lxc_free_idmap(&c
->id_map
);
3325 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3327 struct lxc_list
*it
,*next
;
3329 lxc_list_for_each_safe(it
, &c
->keepcaps
, next
) {
3337 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
)
3339 struct lxc_list
*it
,*next
;
3341 const char *k
= NULL
;
3343 if (strcmp(key
, "lxc.cgroup") == 0)
3345 else if (strncmp(key
, "lxc.cgroup.", sizeof("lxc.cgroup.")-1) == 0)
3346 k
= key
+ sizeof("lxc.cgroup.")-1;
3350 lxc_list_for_each_safe(it
, &c
->cgroup
, next
) {
3351 struct lxc_cgroup
*cg
= it
->elem
;
3352 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3355 free(cg
->subsystem
);
3363 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3365 struct lxc_list
*it
, *next
;
3367 const char *k
= NULL
;
3369 if (strcmp(key
, "lxc.limit") == 0
3370 || strcmp(key
, "lxc.prlimit"))
3372 else if (strncmp(key
, "lxc.limit.", sizeof("lxc.limit.")-1) == 0)
3373 k
= key
+ sizeof("lxc.limit.")-1;
3374 else if (strncmp(key
, "lxc.prlimit.", sizeof("lxc.prlimit.")-1) == 0)
3375 k
= key
+ sizeof("lxc.prlimit.")-1;
3379 lxc_list_for_each_safe(it
, &c
->limits
, next
) {
3380 struct lxc_limit
*lim
= it
->elem
;
3381 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3384 free(lim
->resource
);
3391 int lxc_clear_groups(struct lxc_conf
*c
)
3393 struct lxc_list
*it
,*next
;
3395 lxc_list_for_each_safe(it
, &c
->groups
, next
) {
3403 int lxc_clear_environment(struct lxc_conf
*c
)
3405 struct lxc_list
*it
,*next
;
3407 lxc_list_for_each_safe(it
, &c
->environment
, next
) {
3415 int lxc_clear_mount_entries(struct lxc_conf
*c
)
3417 struct lxc_list
*it
,*next
;
3419 lxc_list_for_each_safe(it
, &c
->mount_list
, next
) {
3427 int lxc_clear_automounts(struct lxc_conf
*c
)
3433 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
3435 struct lxc_list
*it
,*next
;
3436 bool all
= false, done
= false;
3437 const char *k
= NULL
;
3440 if (strcmp(key
, "lxc.hook") == 0)
3442 else if (strncmp(key
, "lxc.hook.", sizeof("lxc.hook.")-1) == 0)
3443 k
= key
+ sizeof("lxc.hook.")-1;
3447 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3448 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
3449 lxc_list_for_each_safe(it
, &c
->hooks
[i
], next
) {
3459 ERROR("Invalid hook key: %s", key
);
3465 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
3467 struct lxc_list
*it
,*next
;
3469 lxc_list_for_each_safe(it
, &conf
->aliens
, next
) {
3476 void lxc_clear_includes(struct lxc_conf
*conf
)
3478 struct lxc_list
*it
,*next
;
3480 lxc_list_for_each_safe(it
, &conf
->includes
, next
) {
3487 void lxc_conf_free(struct lxc_conf
*conf
)
3491 if (current_config
== conf
)
3492 current_config
= NULL
;
3493 free(conf
->console
.log_path
);
3494 free(conf
->console
.path
);
3495 free(conf
->rootfs
.mount
);
3496 free(conf
->rootfs
.bdev_type
);
3497 free(conf
->rootfs
.options
);
3498 free(conf
->rootfs
.path
);
3499 free(conf
->logfile
);
3500 if (conf
->logfd
!= -1)
3502 free(conf
->utsname
);
3506 free(conf
->init_cmd
);
3507 free(conf
->unexpanded_config
);
3508 free(conf
->pty_names
);
3510 lxc_free_networks(&conf
->network
);
3511 free(conf
->lsm_aa_profile
);
3512 free(conf
->lsm_se_context
);
3513 lxc_seccomp_free(conf
);
3514 lxc_clear_config_caps(conf
);
3515 lxc_clear_config_keepcaps(conf
);
3516 lxc_clear_cgroups(conf
, "lxc.cgroup");
3517 lxc_clear_hooks(conf
, "lxc.hook");
3518 lxc_clear_mount_entries(conf
);
3519 lxc_clear_idmaps(conf
);
3520 lxc_clear_groups(conf
);
3521 lxc_clear_includes(conf
);
3522 lxc_clear_aliens(conf
);
3523 lxc_clear_environment(conf
);
3524 lxc_clear_limits(conf
, "lxc.prlimit");
3525 free(conf
->cgroup_meta
.dir
);
3526 free(conf
->cgroup_meta
.controllers
);
3530 struct userns_fn_data
{
3532 const char *fn_name
;
3537 static int run_userns_fn(void *data
)
3539 struct userns_fn_data
*d
= data
;
3542 /* Close write end of the pipe. */
3545 /* Wait for parent to finish establishing a new mapping in the user
3546 * namespace we are executing in.
3548 if (read(d
->p
[0], &c
, 1) != 1)
3551 /* Close read end of the pipe. */
3555 TRACE("calling function \"%s\"", d
->fn_name
);
3556 /* Call function to run. */
3557 return d
->fn(d
->arg
);
3560 static struct id_map
*mapped_hostid_entry(struct lxc_conf
*conf
, unsigned id
,
3563 struct lxc_list
*it
;
3565 struct id_map
*retmap
= NULL
;
3567 lxc_list_for_each(it
, &conf
->id_map
) {
3569 if (map
->idtype
!= idtype
)
3572 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
3581 retmap
= malloc(sizeof(*retmap
));
3585 memcpy(retmap
, map
, sizeof(*retmap
));
3590 * Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
3591 * existing one or establish a new one.
3593 static struct id_map
*idmap_add(struct lxc_conf
*conf
, uid_t id
, enum idtype type
)
3596 struct id_map
*entry
= NULL
;
3598 /* Reuse existing mapping. */
3599 entry
= mapped_hostid_entry(conf
, id
, type
);
3603 /* Find new mapping. */
3604 hostid_mapped
= find_unmapped_nsid(conf
, type
);
3605 if (hostid_mapped
< 0) {
3606 DEBUG("failed to find free mapping for id %d", id
);
3610 entry
= malloc(sizeof(*entry
));
3614 entry
->idtype
= type
;
3615 entry
->nsid
= hostid_mapped
;
3616 entry
->hostid
= (unsigned long)id
;
3622 /* Run a function in a new user namespace.
3623 * The caller's euid/egid will be mapped if it is not already.
3624 * Afaict, userns_exec_1() is only used to operate based on privileges for the
3625 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
3626 * This means we require only to establish a mapping from:
3627 * - the container root {g,u}id as seen from the host > user's host {g,u}id
3628 * - the container root -> some sub{g,u}id
3629 * The former we add, if the user did not specifiy a mapping. The latter we
3630 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
3631 * there to start the container in the first place.
3633 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
3634 const char *fn_name
)
3638 struct userns_fn_data d
;
3640 struct lxc_list
*it
;
3644 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
3645 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
3646 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
3650 SYSERROR("opening pipe");
3654 d
.fn_name
= fn_name
;
3659 /* Clone child in new user namespace. */
3660 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
3662 ERROR("failed to clone child process in new user namespace");
3669 /* Find container root. */
3670 lxc_list_for_each(it
, &conf
->id_map
) {
3676 if (map
->idtype
== ID_TYPE_UID
&& container_root_uid
== NULL
) {
3677 container_root_uid
= malloc(sizeof(*container_root_uid
));
3678 if (!container_root_uid
)
3680 container_root_uid
->idtype
= map
->idtype
;
3681 container_root_uid
->hostid
= map
->hostid
;
3682 container_root_uid
->nsid
= 0;
3683 container_root_uid
->range
= map
->range
;
3684 } else if (map
->idtype
== ID_TYPE_GID
&& container_root_gid
== NULL
) {
3685 container_root_gid
= malloc(sizeof(*container_root_gid
));
3686 if (!container_root_gid
)
3688 container_root_gid
->idtype
= map
->idtype
;
3689 container_root_gid
->hostid
= map
->hostid
;
3690 container_root_gid
->nsid
= 0;
3691 container_root_gid
->range
= map
->range
;
3694 /* Found container root. */
3695 if (container_root_uid
&& container_root_gid
)
3699 /* This is actually checked earlier but it can't hurt. */
3700 if (!container_root_uid
|| !container_root_gid
) {
3701 ERROR("no mapping for container root found");
3705 host_uid_map
= container_root_uid
;
3706 host_gid_map
= container_root_gid
;
3708 /* Check whether the {g,u}id of the user has a mapping. */
3711 if (euid
!= container_root_uid
->hostid
)
3712 host_uid_map
= idmap_add(conf
, euid
, ID_TYPE_UID
);
3714 if (egid
!= container_root_gid
->hostid
)
3715 host_gid_map
= idmap_add(conf
, egid
, ID_TYPE_GID
);
3717 if (!host_uid_map
) {
3718 DEBUG("failed to find mapping for uid %d", euid
);
3722 if (!host_gid_map
) {
3723 DEBUG("failed to find mapping for gid %d", egid
);
3727 /* Allocate new {g,u}id map list. */
3728 idmap
= malloc(sizeof(*idmap
));
3731 lxc_list_init(idmap
);
3733 /* Add container root to the map. */
3734 tmplist
= malloc(sizeof(*tmplist
));
3737 lxc_list_add_elem(tmplist
, container_root_uid
);
3738 lxc_list_add_tail(idmap
, tmplist
);
3740 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
3741 /* idmap will now keep track of that memory. */
3742 container_root_uid
= NULL
;
3744 /* Add container root to the map. */
3745 tmplist
= malloc(sizeof(*tmplist
));
3748 lxc_list_add_elem(tmplist
, host_uid_map
);
3749 lxc_list_add_tail(idmap
, tmplist
);
3751 /* idmap will now keep track of that memory. */
3752 container_root_uid
= NULL
;
3753 /* idmap will now keep track of that memory. */
3754 host_uid_map
= NULL
;
3756 tmplist
= malloc(sizeof(*tmplist
));
3759 lxc_list_add_elem(tmplist
, container_root_gid
);
3760 lxc_list_add_tail(idmap
, tmplist
);
3762 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
3763 /* idmap will now keep track of that memory. */
3764 container_root_gid
= NULL
;
3766 tmplist
= malloc(sizeof(*tmplist
));
3769 lxc_list_add_elem(tmplist
, host_gid_map
);
3770 lxc_list_add_tail(idmap
, tmplist
);
3772 /* idmap will now keep track of that memory. */
3773 container_root_gid
= NULL
;
3774 /* idmap will now keep track of that memory. */
3775 host_gid_map
= NULL
;
3777 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
3778 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
3779 lxc_list_for_each(it
, idmap
) {
3781 TRACE("establishing %cid mapping for \"%d\" in new "
3782 "user namespace: nsuid %lu - hostid %lu - range "
3784 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
3785 map
->nsid
, map
->hostid
, map
->range
);
3789 /* Set up {g,u}id mapping for user namespace of child process. */
3790 ret
= lxc_map_ids(idmap
, pid
);
3792 ERROR("error setting up {g,u}id mappings for child process "
3798 /* Tell child to proceed. */
3799 if (write(p
[1], &c
, 1) != 1) {
3800 SYSERROR("failed telling child process \"%d\" to proceed", pid
);
3804 /* Wait for child to finish. */
3805 ret
= wait_for_pid(pid
);
3809 lxc_free_idmap(idmap
);
3810 if (container_root_uid
)
3811 free(container_root_uid
);
3812 if (container_root_gid
)
3813 free(container_root_gid
);
3814 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
3816 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
3826 /* not thread-safe, do not use from api without first forking */
3827 static char* getuname(void)
3829 struct passwd
*result
;
3831 result
= getpwuid(geteuid());
3835 return strdup(result
->pw_name
);
3838 /* not thread-safe, do not use from api without first forking */
3839 static char *getgname(void)
3841 struct group
*result
;
3843 result
= getgrgid(getegid());
3847 return strdup(result
->gr_name
);
3850 /* not thread-safe, do not use from api without first forking */
3851 void suggest_default_idmap(void)
3854 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
3856 char *uname
, *gname
;
3859 if (!(uname
= getuname()))
3862 if (!(gname
= getgname())) {
3867 f
= fopen(subuidfile
, "r");
3869 ERROR("Your system is not configured with subuids");
3874 while (getline(&line
, &len
, f
) != -1) {
3875 size_t no_newline
= 0;
3876 char *p
= strchr(line
, ':'), *p2
;
3883 if (strcmp(line
, uname
))
3885 p2
= strchr(p
, ':');
3892 no_newline
= strcspn(p2
, "\n");
3893 p2
[no_newline
] = '\0';
3895 if (lxc_safe_uint(p
, &uid
) < 0)
3896 WARN("Could not parse UID.");
3897 if (lxc_safe_uint(p2
, &urange
) < 0)
3898 WARN("Could not parse UID range.");
3902 f
= fopen(subgidfile
, "r");
3904 ERROR("Your system is not configured with subgids");
3909 while (getline(&line
, &len
, f
) != -1) {
3910 size_t no_newline
= 0;
3911 char *p
= strchr(line
, ':'), *p2
;
3918 if (strcmp(line
, uname
))
3920 p2
= strchr(p
, ':');
3927 no_newline
= strcspn(p2
, "\n");
3928 p2
[no_newline
] = '\0';
3930 if (lxc_safe_uint(p
, &gid
) < 0)
3931 WARN("Could not parse GID.");
3932 if (lxc_safe_uint(p2
, &grange
) < 0)
3933 WARN("Could not parse GID range.");
3939 if (!urange
|| !grange
) {
3940 ERROR("You do not have subuids or subgids allocated");
3941 ERROR("Unprivileged containers require subuids and subgids");
3945 ERROR("You must either run as root, or define uid mappings");
3946 ERROR("To pass uid mappings to lxc-create, you could create");
3947 ERROR("~/.config/lxc/default.conf:");
3948 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
3949 ERROR("lxc.id_map = u 0 %u %u", uid
, urange
);
3950 ERROR("lxc.id_map = g 0 %u %u", gid
, grange
);
3956 static void free_cgroup_settings(struct lxc_list
*result
)
3958 struct lxc_list
*iterator
, *next
;
3960 lxc_list_for_each_safe(iterator
, result
, next
) {
3961 lxc_list_del(iterator
);
3968 * Return the list of cgroup_settings sorted according to the following rules
3969 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
3971 struct lxc_list
*sort_cgroup_settings(struct lxc_list
* cgroup_settings
)
3973 struct lxc_list
*result
;
3974 struct lxc_list
*memsw_limit
= NULL
;
3975 struct lxc_list
*it
= NULL
;
3976 struct lxc_cgroup
*cg
= NULL
;
3977 struct lxc_list
*item
= NULL
;
3979 result
= malloc(sizeof(*result
));
3981 ERROR("failed to allocate memory to sort cgroup settings");
3984 lxc_list_init(result
);
3986 /*Iterate over the cgroup settings and copy them to the output list*/
3987 lxc_list_for_each(it
, cgroup_settings
) {
3988 item
= malloc(sizeof(*item
));
3990 ERROR("failed to allocate memory to sort cgroup settings");
3991 free_cgroup_settings(result
);
3994 item
->elem
= it
->elem
;
3996 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
3997 /* Store the memsw_limit location */
3999 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 && memsw_limit
!= NULL
) {
4000 /* lxc.cgroup.memory.memsw.limit_in_bytes is found before
4001 * lxc.cgroup.memory.limit_in_bytes, swap these two items */
4002 item
->elem
= memsw_limit
->elem
;
4003 memsw_limit
->elem
= it
->elem
;
4005 lxc_list_add_tail(result
, item
);