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>
72 #include "caps.h" /* for lxc_caps_last_cap() */
75 #include "confile_utils.h"
79 #include "lxcseccomp.h"
80 #include "namespace.h"
85 #include "storage/aufs.h"
86 #include "storage/overlay.h"
91 #include <sys/capability.h>
94 #if HAVE_SYS_PERSONALITY_H
95 #include <sys/personality.h>
99 #include <../include/lxcmntent.h>
104 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
105 #include <../include/prlimit.h>
108 lxc_log_define(lxc_conf
, lxc
);
110 /* Define pivot_root() if missing from the C library */
111 #ifndef HAVE_PIVOT_ROOT
112 static int pivot_root(const char * new_root
, const char * put_old
)
114 #ifdef __NR_pivot_root
115 return syscall(__NR_pivot_root
, new_root
, put_old
);
122 extern int pivot_root(const char * new_root
, const char * put_old
);
126 #define MS_PRIVATE (1<<18)
130 #define MS_LAZYTIME (1<<25)
133 char *lxchook_names
[NUM_LXC_HOOKS
] = {"pre-start", "pre-mount", "mount",
134 "autodev", "start", "stop",
135 "post-stop", "clone", "destroy",
155 * The lxc_conf of the container currently being worked on in an
157 * This is used in the error calls
160 __thread
struct lxc_conf
*current_config
;
162 struct lxc_conf
*current_config
;
165 static struct mount_opt mount_opt
[] = {
166 { "async", 1, MS_SYNCHRONOUS
},
167 { "atime", 1, MS_NOATIME
},
168 { "bind", 0, MS_BIND
},
169 { "defaults", 0, 0 },
170 { "dev", 1, MS_NODEV
},
171 { "diratime", 1, MS_NODIRATIME
},
172 { "dirsync", 0, MS_DIRSYNC
},
173 { "exec", 1, MS_NOEXEC
},
174 { "lazytime", 0, MS_LAZYTIME
},
175 { "mand", 0, MS_MANDLOCK
},
176 { "noatime", 0, MS_NOATIME
},
177 { "nodev", 0, MS_NODEV
},
178 { "nodiratime", 0, MS_NODIRATIME
},
179 { "noexec", 0, MS_NOEXEC
},
180 { "nomand", 1, MS_MANDLOCK
},
181 { "norelatime", 1, MS_RELATIME
},
182 { "nostrictatime", 1, MS_STRICTATIME
},
183 { "nosuid", 0, MS_NOSUID
},
184 { "rbind", 0, MS_BIND
|MS_REC
},
185 { "relatime", 0, MS_RELATIME
},
186 { "remount", 0, MS_REMOUNT
},
187 { "ro", 0, MS_RDONLY
},
188 { "rw", 1, MS_RDONLY
},
189 { "strictatime", 0, MS_STRICTATIME
},
190 { "suid", 1, MS_NOSUID
},
191 { "sync", 0, MS_SYNCHRONOUS
},
196 static struct caps_opt caps_opt
[] = {
197 { "chown", CAP_CHOWN
},
198 { "dac_override", CAP_DAC_OVERRIDE
},
199 { "dac_read_search", CAP_DAC_READ_SEARCH
},
200 { "fowner", CAP_FOWNER
},
201 { "fsetid", CAP_FSETID
},
202 { "kill", CAP_KILL
},
203 { "setgid", CAP_SETGID
},
204 { "setuid", CAP_SETUID
},
205 { "setpcap", CAP_SETPCAP
},
206 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
207 { "net_bind_service", CAP_NET_BIND_SERVICE
},
208 { "net_broadcast", CAP_NET_BROADCAST
},
209 { "net_admin", CAP_NET_ADMIN
},
210 { "net_raw", CAP_NET_RAW
},
211 { "ipc_lock", CAP_IPC_LOCK
},
212 { "ipc_owner", CAP_IPC_OWNER
},
213 { "sys_module", CAP_SYS_MODULE
},
214 { "sys_rawio", CAP_SYS_RAWIO
},
215 { "sys_chroot", CAP_SYS_CHROOT
},
216 { "sys_ptrace", CAP_SYS_PTRACE
},
217 { "sys_pacct", CAP_SYS_PACCT
},
218 { "sys_admin", CAP_SYS_ADMIN
},
219 { "sys_boot", CAP_SYS_BOOT
},
220 { "sys_nice", CAP_SYS_NICE
},
221 { "sys_resource", CAP_SYS_RESOURCE
},
222 { "sys_time", CAP_SYS_TIME
},
223 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
224 { "mknod", CAP_MKNOD
},
225 { "lease", CAP_LEASE
},
226 #ifdef CAP_AUDIT_READ
227 { "audit_read", CAP_AUDIT_READ
},
229 #ifdef CAP_AUDIT_WRITE
230 { "audit_write", CAP_AUDIT_WRITE
},
232 #ifdef CAP_AUDIT_CONTROL
233 { "audit_control", CAP_AUDIT_CONTROL
},
235 { "setfcap", CAP_SETFCAP
},
236 { "mac_override", CAP_MAC_OVERRIDE
},
237 { "mac_admin", CAP_MAC_ADMIN
},
239 { "syslog", CAP_SYSLOG
},
241 #ifdef CAP_WAKE_ALARM
242 { "wake_alarm", CAP_WAKE_ALARM
},
244 #ifdef CAP_BLOCK_SUSPEND
245 { "block_suspend", CAP_BLOCK_SUSPEND
},
249 static struct caps_opt caps_opt
[] = {};
252 static struct limit_opt limit_opt
[] = {
257 { "core", RLIMIT_CORE
},
260 { "cpu", RLIMIT_CPU
},
263 { "data", RLIMIT_DATA
},
266 { "fsize", RLIMIT_FSIZE
},
269 { "locks", RLIMIT_LOCKS
},
271 #ifdef RLIMIT_MEMLOCK
272 { "memlock", RLIMIT_MEMLOCK
},
274 #ifdef RLIMIT_MSGQUEUE
275 { "msgqueue", RLIMIT_MSGQUEUE
},
278 { "nice", RLIMIT_NICE
},
281 { "nofile", RLIMIT_NOFILE
},
284 { "nproc", RLIMIT_NPROC
},
287 { "rss", RLIMIT_RSS
},
290 { "rtprio", RLIMIT_RTPRIO
},
293 { "rttime", RLIMIT_RTTIME
},
295 #ifdef RLIMIT_SIGPENDING
296 { "sigpending", RLIMIT_SIGPENDING
},
299 { "stack", RLIMIT_STACK
},
303 static int run_buffer(char *buffer
)
305 struct lxc_popen_FILE
*f
;
309 f
= lxc_popen(buffer
);
311 SYSERROR("Failed to popen() %s.", buffer
);
315 output
= malloc(LXC_LOG_BUFFER_SIZE
);
317 ERROR("Failed to allocate memory for %s.", buffer
);
322 while (fgets(output
, LXC_LOG_BUFFER_SIZE
, f
->f
))
323 DEBUG("Script %s with output: %s.", buffer
, output
);
329 SYSERROR("Script exited with error.");
331 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
332 ERROR("Script exited with status %d.", WEXITSTATUS(ret
));
334 } else if (WIFSIGNALED(ret
)) {
335 ERROR("Script terminated by signal %d.", WTERMSIG(ret
));
342 static int run_script_argv(const char *name
, const char *section
,
343 const char *script
, const char *hook
,
344 const char *lxcpath
, char **argsin
)
350 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
351 script
, name
, section
);
353 for (i
= 0; argsin
&& argsin
[i
]; i
++)
354 size
+= strlen(argsin
[i
]) + 1;
356 size
+= strlen(hook
) + 1;
358 size
+= strlen(script
);
359 size
+= strlen(name
);
360 size
+= strlen(section
);
366 buffer
= alloca(size
);
368 ERROR("Failed to allocate memory.");
373 snprintf(buffer
, size
, "%s %s %s %s", script
, name
, section
, hook
);
374 if (ret
< 0 || (size_t)ret
>= size
) {
375 ERROR("Script name too long.");
379 for (i
= 0; argsin
&& argsin
[i
]; i
++) {
380 int len
= size
- ret
;
382 rc
= snprintf(buffer
+ ret
, len
, " %s", argsin
[i
]);
383 if (rc
< 0 || rc
>= len
) {
384 ERROR("Script args too long.");
390 return run_buffer(buffer
);
393 int run_script(const char *name
, const char *section
, const char *script
, ...)
400 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
401 script
, name
, section
);
403 va_start(ap
, script
);
404 while ((p
= va_arg(ap
, char *)))
405 size
+= strlen(p
) + 1;
408 size
+= strlen(script
);
409 size
+= strlen(name
);
410 size
+= strlen(section
);
416 buffer
= alloca(size
);
418 ERROR("Failed to allocate memory.");
422 ret
= snprintf(buffer
, size
, "%s %s %s", script
, name
, section
);
423 if (ret
< 0 || ret
>= size
) {
424 ERROR("Script name too long.");
428 va_start(ap
, script
);
429 while ((p
= va_arg(ap
, char *))) {
430 int len
= size
- ret
;
432 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
433 if (rc
< 0 || rc
>= len
) {
434 ERROR("Script args too long.");
441 return run_buffer(buffer
);
446 * if rootfs is a directory, then open ${rootfs}/lxc.hold for writing for
447 * the duration of the container run, to prevent the container from marking
448 * the underlying fs readonly on shutdown. unlink the file immediately so
449 * no name pollution is happens
450 * return -1 on error.
451 * return -2 if nothing needed to be pinned.
452 * return an open fd (>=0) if we pinned it.
454 int pin_rootfs(const char *rootfs
)
456 char absrootfs
[MAXPATHLEN
];
457 char absrootfspin
[MAXPATHLEN
];
461 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
464 if (!realpath(rootfs
, absrootfs
))
467 if (access(absrootfs
, F_OK
))
470 if (stat(absrootfs
, &s
))
473 if (!S_ISDIR(s
.st_mode
))
476 ret
= snprintf(absrootfspin
, MAXPATHLEN
, "%s/lxc.hold", absrootfs
);
477 if (ret
>= MAXPATHLEN
)
480 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
|S_IRUSR
);
483 (void)unlink(absrootfspin
);
488 * If we are asking to remount something, make sure that any
489 * NOEXEC etc are honored.
491 unsigned long add_required_remount_flags(const char *s
, const char *d
,
496 unsigned long required_flags
= 0;
498 if (!(flags
& MS_REMOUNT
))
506 if (statvfs(s
, &sb
) < 0)
509 if (sb
.f_flag
& MS_NOSUID
)
510 required_flags
|= MS_NOSUID
;
511 if (sb
.f_flag
& MS_NODEV
)
512 required_flags
|= MS_NODEV
;
513 if (sb
.f_flag
& MS_RDONLY
)
514 required_flags
|= MS_RDONLY
;
515 if (sb
.f_flag
& MS_NOEXEC
)
516 required_flags
|= MS_NOEXEC
;
518 return flags
| required_flags
;
524 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
532 const char *destination
;
536 } default_mounts
[] = {
537 /* Read-only bind-mounting... In older kernels, doing that required
538 * to do one MS_BIND mount and then MS_REMOUNT|MS_RDONLY the same
539 * one. According to mount(2) manpage, MS_BIND honors MS_RDONLY from
540 * kernel 2.6.26 onwards. However, this apparently does not work on
541 * kernel 3.8. Unfortunately, on that very same kernel, doing the
542 * same trick as above doesn't seem to work either, there one needs
543 * to ALSO specify MS_BIND for the remount, otherwise the entire
544 * fs is remounted read-only or the mount fails because it's busy...
545 * MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for kernels as low as
548 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
549 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
550 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
551 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
552 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
553 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
554 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
555 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
556 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
557 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
558 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
559 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
560 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
561 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
562 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
563 { 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
},
564 { 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
},
565 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
568 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
569 if ((flags
& default_mounts
[i
].match_mask
) == default_mounts
[i
].match_flag
) {
571 char *destination
= NULL
;
573 unsigned long mflags
;
575 if (default_mounts
[i
].source
) {
576 /* will act like strdup if %r is not present */
577 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
579 SYSERROR("memory allocation error");
583 if (!default_mounts
[i
].destination
) {
584 ERROR("BUG: auto mounts destination %d was NULL", i
);
588 /* will act like strdup if %r is not present */
589 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
592 SYSERROR("memory allocation error");
597 mflags
= add_required_remount_flags(source
, destination
,
598 default_mounts
[i
].flags
);
599 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
, mflags
, default_mounts
[i
].options
, conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
601 if (r
< 0 && errno
== ENOENT
) {
602 INFO("Mount source or target for %s on %s doesn't exist. Skipping.", source
, destination
);
606 SYSERROR("error mounting %s on %s flags %lu", source
, destination
, mflags
);
617 if (flags
& LXC_AUTO_CGROUP_MASK
) {
620 cg_flags
= flags
& LXC_AUTO_CGROUP_MASK
;
621 /* If the type of cgroup mount was not specified, it depends on the
622 * container's capabilities as to what makes sense: if we have
623 * CAP_SYS_ADMIN, the read-only part can be remounted read-write
624 * anyway, so we may as well default to read-write; then the admin
625 * will not be given a false sense of security. (And if they really
626 * want mixed r/o r/w, then they can explicitly specify :mixed.)
627 * OTOH, if the container lacks CAP_SYS_ADMIN, do only default to
628 * :mixed, because then the container can't remount it read-write. */
629 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
630 int has_sys_admin
= 0;
632 if (!lxc_list_empty(&conf
->keepcaps
))
633 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
635 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
637 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
638 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
640 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
643 if (!cgroup_mount(conf
->rootfs
.path
? conf
->rootfs
.mount
: "", handler
, cg_flags
)) {
644 SYSERROR("error mounting /sys/fs/cgroup");
652 static int setup_utsname(struct utsname
*utsname
)
657 if (sethostname(utsname
->nodename
, strlen(utsname
->nodename
))) {
658 SYSERROR("failed to set the hostname to '%s'", utsname
->nodename
);
662 INFO("'%s' hostname has been setup", utsname
->nodename
);
667 struct dev_symlinks
{
672 static const struct dev_symlinks dev_symlinks
[] = {
673 {"/proc/self/fd", "fd"},
674 {"/proc/self/fd/0", "stdin"},
675 {"/proc/self/fd/1", "stdout"},
676 {"/proc/self/fd/2", "stderr"},
679 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
681 char path
[MAXPATHLEN
];
686 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
687 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
688 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs
->path
? rootfs
->mount
: "", d
->name
);
689 if (ret
< 0 || ret
>= MAXPATHLEN
)
693 * Stat the path first. If we don't get an error
694 * accept it as is and don't try to create it
696 if (!stat(path
, &s
)) {
700 ret
= symlink(d
->oldpath
, path
);
702 if (ret
&& errno
!= EEXIST
) {
703 if ( errno
== EROFS
) {
704 WARN("Warning: Read Only file system while creating %s", path
);
706 SYSERROR("Error creating %s", path
);
714 /* Build a space-separate list of ptys to pass to systemd. */
715 static bool append_ptyname(char **pp
, char *name
)
720 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
723 sprintf(*pp
, "container_ttys=%s", name
);
726 p
= realloc(*pp
, strlen(*pp
) + strlen(name
) + 2);
735 static int lxc_setup_ttys(struct lxc_conf
*conf
)
738 const struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
739 char *ttydir
= conf
->ttydir
;
740 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
742 if (!conf
->rootfs
.path
)
745 for (i
= 0; i
< tty_info
->nbtty
; i
++) {
746 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
748 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
749 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
753 /* create dev/lxc/tty%d" */
754 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
755 "/dev/%s/tty%d", ttydir
, i
+ 1);
756 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
759 ret
= creat(lxcpath
, 0660);
760 if (ret
< 0 && errno
!= EEXIST
) {
761 SYSERROR("Failed to create \"%s\"", lxcpath
);
768 if (ret
< 0 && errno
!= ENOENT
) {
769 SYSERROR("Failed to unlink \"%s\"", path
);
773 ret
= mount(pty_info
->name
, lxcpath
, "none", MS_BIND
, 0);
775 WARN("Failed to bind mount \"%s\" onto \"%s\"",
776 pty_info
->name
, path
);
779 DEBUG("bind mounted \"%s\" onto \"%s\"", pty_info
->name
,
782 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
784 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
787 ret
= symlink(lxcpath
, path
);
789 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
794 /* If we populated /dev, then we need to create
797 ret
= access(path
, F_OK
);
799 ret
= creat(path
, 0660);
801 SYSERROR("Failed to create \"%s\"", path
);
802 /* this isn't fatal, continue */
808 ret
= mount(pty_info
->name
, path
, "none", MS_BIND
, 0);
810 SYSERROR("Failed to mount '%s'->'%s'", pty_info
->name
, path
);
814 DEBUG("Bind mounted \"%s\" onto \"%s\"", pty_info
->name
,
818 if (!append_ptyname(&conf
->pty_names
, pty_info
->name
)) {
819 ERROR("Error setting up container_ttys string");
824 INFO("Finished setting up %d /dev/tty<N> device(s)", tty_info
->nbtty
);
828 int lxc_allocate_ttys(const char *name
, struct lxc_conf
*conf
)
830 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
833 /* no tty in the configuration */
837 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
) * conf
->tty
);
838 if (!tty_info
->pty_info
) {
839 SYSERROR("failed to allocate struct *pty_info");
843 for (i
= 0; i
< conf
->tty
; i
++) {
844 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
847 ret
= openpty(&pty_info
->master
, &pty_info
->slave
,
848 pty_info
->name
, NULL
, NULL
);
851 SYSERROR("failed to create pty device number %d", i
);
853 lxc_delete_tty(tty_info
);
857 DEBUG("allocated pty \"%s\" with master fd %d and slave fd %d",
858 pty_info
->name
, pty_info
->master
, pty_info
->slave
);
860 /* Prevent leaking the file descriptors to the container */
861 ret
= fcntl(pty_info
->master
, F_SETFD
, FD_CLOEXEC
);
863 WARN("failed to set FD_CLOEXEC flag on master fd %d of "
864 "pty device \"%s\": %s",
865 pty_info
->master
, pty_info
->name
, strerror(errno
));
867 ret
= fcntl(pty_info
->slave
, F_SETFD
, FD_CLOEXEC
);
869 WARN("failed to set FD_CLOEXEC flag on slave fd %d of "
870 "pty device \"%s\": %s",
871 pty_info
->slave
, pty_info
->name
, strerror(errno
));
876 tty_info
->nbtty
= conf
->tty
;
878 INFO("finished allocating %d pts devices", conf
->tty
);
882 void lxc_delete_tty(struct lxc_tty_info
*tty_info
)
886 for (i
= 0; i
< tty_info
->nbtty
; i
++) {
887 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
889 close(pty_info
->master
);
890 close(pty_info
->slave
);
893 free(tty_info
->pty_info
);
894 tty_info
->pty_info
= NULL
;
898 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
901 struct lxc_conf
*conf
= handler
->conf
;
902 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
903 int sock
= handler
->data_sock
[0];
909 for (i
= 0; i
< conf
->tty
; i
++) {
911 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
913 ttyfds
[0] = pty_info
->master
;
914 ttyfds
[1] = pty_info
->slave
;
916 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
920 TRACE("Send pty \"%s\" with master fd %d and slave fd %d to "
921 "parent", pty_info
->name
, pty_info
->master
, pty_info
->slave
);
925 ERROR("Failed to send %d ttys to parent: %s", conf
->tty
,
928 TRACE("Sent %d ttys to parent", conf
->tty
);
933 static int lxc_create_ttys(struct lxc_handler
*handler
)
936 struct lxc_conf
*conf
= handler
->conf
;
938 ret
= lxc_allocate_ttys(handler
->name
, conf
);
940 ERROR("Failed to allocate ttys");
944 ret
= lxc_send_ttys_to_parent(handler
);
946 ERROR("Failed to send ttys to parent");
950 if (!conf
->is_execute
) {
951 ret
= lxc_setup_ttys(conf
);
953 ERROR("Failed to setup ttys");
958 if (conf
->pty_names
) {
959 ret
= setenv("container_ttys", conf
->pty_names
, 1);
961 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->pty_names
);
967 lxc_delete_tty(&conf
->tty_info
);
972 static int setup_rootfs_pivot_root(const char *rootfs
)
974 int oldroot
= -1, newroot
= -1;
976 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
978 SYSERROR("Error opening old-/ for fchdir");
981 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
);
983 SYSERROR("Error opening new-/ for fchdir");
987 /* change into new root fs */
988 if (fchdir(newroot
)) {
989 SYSERROR("can't chdir to new rootfs '%s'", rootfs
);
993 /* pivot_root into our new root fs */
994 if (pivot_root(".", ".")) {
995 SYSERROR("pivot_root syscall failed");
1000 * at this point the old-root is mounted on top of our new-root
1001 * To unmounted it we must not be chdir'd into it, so escape back
1004 if (fchdir(oldroot
) < 0) {
1005 SYSERROR("Error entering oldroot");
1008 if (umount2(".", MNT_DETACH
) < 0) {
1009 SYSERROR("Error detaching old root");
1013 if (fchdir(newroot
) < 0) {
1014 SYSERROR("Error re-entering newroot");
1021 DEBUG("pivot_root syscall to '%s' successful", rootfs
);
1033 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1034 * error, log it but don't fail yet.
1036 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1037 const char *lxcpath
)
1043 INFO("Preparing \"/dev\"");
1045 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1046 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1047 path
= alloca(clen
);
1049 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1050 if (ret
< 0 || (size_t)ret
>= clen
)
1053 if (!dir_exists(path
)) {
1054 WARN("\"/dev\" directory does not exist. Proceeding without "
1055 "autodev being set up");
1059 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1060 rootfs
->path
? rootfs
->mount
: NULL
);
1062 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1065 INFO("Mounted tmpfs on \"%s\"", path
);
1067 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1068 if (ret
< 0 || (size_t)ret
>= clen
)
1071 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1072 * If not, then create it and exit if that fails...
1074 if (!dir_exists(path
)) {
1075 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1077 SYSERROR("Failed to create directory \"%s\"", path
);
1082 INFO("Prepared \"/dev\"");
1093 static const struct lxc_devs lxc_devs
[] = {
1094 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1095 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1096 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1097 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1098 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1099 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1102 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1105 char path
[MAXPATHLEN
];
1109 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev",
1110 rootfs
->path
? rootfs
->mount
: "");
1111 if (ret
< 0 || ret
>= MAXPATHLEN
)
1114 /* ignore, just don't try to fill in */
1115 if (!dir_exists(path
))
1118 INFO("Populating \"/dev\"");
1120 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1121 for (i
= 0; i
< sizeof(lxc_devs
) / sizeof(lxc_devs
[0]); i
++) {
1122 const struct lxc_devs
*d
= &lxc_devs
[i
];
1124 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev/%s",
1125 rootfs
->path
? rootfs
->mount
: "", d
->name
);
1126 if (ret
< 0 || ret
>= MAXPATHLEN
)
1129 ret
= mknod(path
, d
->mode
, makedev(d
->maj
, d
->min
));
1132 char hostpath
[MAXPATHLEN
];
1134 if (errno
== EEXIST
) {
1135 DEBUG("\"%s\" device already existed", path
);
1139 /* Unprivileged containers cannot create devices, so
1140 * bind mount the device from the host.
1142 ret
= snprintf(hostpath
, MAXPATHLEN
, "/dev/%s", d
->name
);
1143 if (ret
< 0 || ret
>= MAXPATHLEN
)
1146 pathfile
= fopen(path
, "wb");
1148 SYSERROR("Failed to create file \"%s\"", path
);
1153 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1154 rootfs
->path
? rootfs
->mount
: NULL
);
1156 SYSERROR("Failed to bind mount \"%s\" from "
1157 "host into container",
1161 DEBUG("Bind mounted \"%s\" onto \"%s\"", hostpath
,
1164 DEBUG("Created device node \"%s\"", path
);
1169 INFO("Populated \"/dev\"");
1173 static int lxc_setup_rootfs(struct lxc_conf
*conf
)
1176 struct lxc_storage
*bdev
;
1177 const struct lxc_rootfs
*rootfs
;
1179 rootfs
= &conf
->rootfs
;
1180 if (!rootfs
->path
) {
1181 if (mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0)) {
1182 SYSERROR("Failed to make / rslave.");
1188 if (access(rootfs
->mount
, F_OK
)) {
1189 SYSERROR("Failed to access to \"%s\". Check it is present.",
1194 bdev
= storage_init(conf
, rootfs
->path
, rootfs
->mount
, rootfs
->options
);
1196 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1197 rootfs
->path
, rootfs
->mount
,
1198 rootfs
->options
? rootfs
->options
: "(null)");
1202 ret
= bdev
->ops
->mount(bdev
);
1205 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1206 rootfs
->path
, rootfs
->mount
,
1207 rootfs
->options
? rootfs
->options
: "(null)");
1211 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\".",
1212 rootfs
->path
, rootfs
->mount
,
1213 rootfs
->options
? rootfs
->options
: "(null)");
1218 int prepare_ramfs_root(char *root
)
1220 char buf
[LXC_LINELEN
], *p
;
1221 char nroot
[PATH_MAX
];
1226 if (realpath(root
, nroot
) == NULL
)
1229 if (chdir("/") == -1)
1233 * We could use here MS_MOVE, but in userns this mount is
1234 * locked and can't be moved.
1236 if (mount(root
, "/", NULL
, MS_REC
| MS_BIND
, NULL
) < 0) {
1237 SYSERROR("Failed to move %s into /", root
);
1241 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
) < 0) {
1242 SYSERROR("Failed to make . rprivate");
1247 * The following code cleans up inhereted mounts which are not
1250 * The mountinfo file shows not all mounts, if a few points have been
1251 * unmounted between read operations from the mountinfo. So we need to
1252 * read mountinfo a few times.
1254 * This loop can be skipped if a container uses unserns, because all
1255 * inherited mounts are locked and we should live with all this trash.
1260 f
= fopen("./proc/self/mountinfo", "r");
1262 SYSERROR("Unable to open /proc/self/mountinfo");
1265 while (fgets(buf
, LXC_LINELEN
, f
)) {
1266 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1267 p
= strchr(p
+1, ' ');
1270 p2
= strchr(p
+1, ' ');
1277 if (strcmp(p
+ 1, "/") == 0)
1279 if (strcmp(p
+ 1, "/proc") == 0)
1282 if (umount2(p
, MNT_DETACH
) == 0)
1290 /* This also can be skipped if a container uses unserns */
1291 umount2("./proc", MNT_DETACH
);
1293 /* It is weird, but chdir("..") moves us in a new root */
1294 if (chdir("..") == -1) {
1295 SYSERROR("Unable to change working directory");
1299 if (chroot(".") == -1) {
1300 SYSERROR("Unable to chroot");
1307 static int setup_pivot_root(const struct lxc_rootfs
*rootfs
)
1309 if (!rootfs
->path
) {
1310 DEBUG("container does not have a rootfs, so not doing pivot root");
1314 if (detect_ramfs_rootfs()) {
1315 DEBUG("detected that container is on ramfs");
1316 if (prepare_ramfs_root(rootfs
->mount
)) {
1317 ERROR("failed to prepare minimal ramfs root");
1321 DEBUG("prepared ramfs root for container");
1325 if (setup_rootfs_pivot_root(rootfs
->mount
) < 0) {
1326 ERROR("failed to pivot root");
1330 DEBUG("finished pivot root");
1334 static int lxc_setup_devpts(int num_pts
)
1337 const char *default_devpts_mntopts
= "newinstance,ptmxmode=0666,mode=0620,gid=5";
1338 char devpts_mntopts
[256];
1341 DEBUG("no new devpts instance will be mounted since no pts "
1342 "devices are requested");
1346 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%d",
1347 default_devpts_mntopts
, num_pts
);
1348 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1351 /* Unmount old devpts instance. */
1352 ret
= access("/dev/pts/ptmx", F_OK
);
1354 ret
= umount("/dev/pts");
1356 SYSERROR("failed to unmount old devpts instance");
1359 DEBUG("unmounted old /dev/pts instance");
1362 /* Create mountpoint for devpts instance. */
1363 ret
= mkdir("/dev/pts", 0755);
1364 if (ret
< 0 && errno
!= EEXIST
) {
1365 SYSERROR("failed to create the \"/dev/pts\" directory");
1369 /* Mount new devpts instance. */
1370 ret
= mount("devpts", "/dev/pts", "devpts", MS_MGC_VAL
, devpts_mntopts
);
1372 SYSERROR("failed to mount new devpts instance");
1375 DEBUG("mount new devpts instance with options \"%s\"", devpts_mntopts
);
1377 /* Remove any pre-existing /dev/ptmx file. */
1378 ret
= access("/dev/ptmx", F_OK
);
1380 ret
= remove("/dev/ptmx");
1382 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1385 DEBUG("removed existing \"/dev/ptmx\"");
1388 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1389 ret
= open("/dev/ptmx", O_CREAT
, 0666);
1391 SYSERROR("failed to create dummy \"/dev/ptmx\" file as bind mount target");
1395 DEBUG("created dummy \"/dev/ptmx\" file as bind mount target");
1397 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1398 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1400 DEBUG("bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1403 /* Fallthrough and try to create a symlink. */
1404 ERROR("failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1407 /* Remove the dummy /dev/ptmx file we created above. */
1408 ret
= remove("/dev/ptmx");
1410 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1414 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1415 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1417 SYSERROR("failed to create symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1420 DEBUG("created symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1425 static int setup_personality(int persona
)
1427 #if HAVE_SYS_PERSONALITY_H
1431 if (personality(persona
) < 0) {
1432 SYSERROR("failed to set personality to '0x%x'", persona
);
1436 INFO("set personality to '0x%x'", persona
);
1442 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1443 const struct lxc_console
*console
)
1445 char path
[MAXPATHLEN
];
1448 if (console
->path
&& !strcmp(console
->path
, "none"))
1451 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs
->mount
);
1452 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1455 /* When we are asked to setup a console we remove any previous
1456 * /dev/console bind-mounts.
1458 if (file_exists(path
)) {
1459 ret
= lxc_unstack_mountpoint(path
, false);
1461 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1464 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1469 SYSERROR("error unlinking %s", path
);
1474 /* For unprivileged containers autodev or automounts will already have
1475 * taken care of creating /dev/console.
1477 fd
= open(path
, O_CREAT
| O_EXCL
, S_IXUSR
| S_IXGRP
| S_IXOTH
);
1479 if (errno
!= EEXIST
) {
1480 SYSERROR("failed to create console");
1487 if (chmod(console
->name
, S_IXUSR
| S_IXGRP
| S_IXOTH
)) {
1488 SYSERROR("failed to set mode '0%o' to '%s'", S_IXUSR
| S_IXGRP
| S_IXOTH
, console
->name
);
1492 if (safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs
->mount
) < 0) {
1493 ERROR("failed to mount '%s' on '%s'", console
->name
, path
);
1497 DEBUG("mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1501 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1502 const struct lxc_console
*console
,
1506 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
1508 /* create rootfs/dev/<ttydir> directory */
1509 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs
->mount
, ttydir
);
1510 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1513 ret
= mkdir(path
, 0755);
1514 if (ret
&& errno
!= EEXIST
) {
1515 SYSERROR("failed with errno %d to create %s", errno
, path
);
1518 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1520 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs
->mount
, ttydir
);
1521 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1524 ret
= creat(lxcpath
, 0660);
1525 if (ret
== -1 && errno
!= EEXIST
) {
1526 SYSERROR("error %d creating %s", errno
, lxcpath
);
1532 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs
->mount
);
1533 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1536 /* When we are asked to setup a console we remove any previous
1537 * /dev/console bind-mounts.
1539 if (console
->path
&& !strcmp(console
->path
, "none")) {
1541 ret
= stat(path
, &st
);
1543 if (errno
== ENOENT
)
1545 SYSERROR("failed stat() \"%s\"", path
);
1549 /* /dev/console must be character device with major number 5 and
1550 * minor number 1. If not, give benefit of the doubt and assume
1551 * the user has mounted something else right there on purpose.
1553 if (((st
.st_mode
& S_IFMT
) != S_IFCHR
) || major(st
.st_rdev
) != 5 || minor(st
.st_rdev
) != 1)
1556 /* In case the user requested a bind-mount for /dev/console and
1557 * requests a ttydir we move the mount to the
1558 * /dev/<ttydir/console.
1559 * Note, we only move the uppermost mount and clear all other
1560 * mounts underneath for safety.
1561 * If it is a character device created via mknod() we simply
1564 ret
= safe_mount(path
, lxcpath
, "none", MS_MOVE
, NULL
, rootfs
->mount
);
1566 if (errno
!= EINVAL
) {
1567 ERROR("failed to MS_MOVE \"%s\" to \"%s\": %s", path
, lxcpath
, strerror(errno
));
1570 /* path was not a mountpoint */
1571 ret
= rename(path
, lxcpath
);
1573 ERROR("failed to rename \"%s\" to \"%s\": %s", path
, lxcpath
, strerror(errno
));
1576 DEBUG("renamed \"%s\" to \"%s\"", path
, lxcpath
);
1578 DEBUG("moved mount \"%s\" to \"%s\"", path
, lxcpath
);
1581 /* Clear all remaining bind-mounts. */
1582 ret
= lxc_unstack_mountpoint(path
, false);
1584 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1587 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1590 if (file_exists(path
)) {
1591 ret
= lxc_unstack_mountpoint(path
, false);
1593 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1596 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1600 if (safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs
->mount
) < 0) {
1601 ERROR("failed to mount '%s' on '%s'", console
->name
, lxcpath
);
1604 DEBUG("mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1607 /* create symlink from rootfs /dev/console to '<ttydir>/console' */
1608 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/console", ttydir
);
1609 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1613 if (ret
&& errno
!= ENOENT
) {
1614 SYSERROR("error unlinking %s", path
);
1618 ret
= symlink(lxcpath
, path
);
1620 SYSERROR("failed to create symlink for console from \"%s\" to \"%s\"", lxcpath
, path
);
1624 DEBUG("console has been setup under \"%s\" and symlinked to \"%s\"", lxcpath
, path
);
1628 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1629 const struct lxc_console
*console
, char *ttydir
)
1631 /* We don't have a rootfs, /dev/console will be shared. */
1632 if (!rootfs
->path
) {
1633 DEBUG("/dev/console will be shared with the host");
1638 return lxc_setup_dev_console(rootfs
, console
);
1640 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1643 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
)
1645 struct mount_opt
*mo
;
1647 /* If opt is found in mount_opt, set or clear flags.
1648 * Otherwise append it to data. */
1650 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1651 if (!strncmp(opt
, mo
->name
, strlen(mo
->name
))) {
1653 *flags
&= ~mo
->flag
;
1665 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
,
1669 char *p
, *saveptr
= NULL
;
1677 s
= strdup(mntopts
);
1679 SYSERROR("failed to allocate memory");
1683 data
= malloc(strlen(s
) + 1);
1685 SYSERROR("failed to allocate memory");
1691 for (p
= strtok_r(s
, ",", &saveptr
); p
!= NULL
;
1692 p
= strtok_r(NULL
, ",", &saveptr
))
1693 parse_mntopt(p
, mntflags
, &data
);
1704 static void null_endofword(char *word
)
1706 while (*word
&& *word
!= ' ' && *word
!= '\t')
1712 * skip @nfields spaces in @src
1714 static char *get_field(char *src
, int nfields
)
1719 for (i
= 0; i
< nfields
; i
++) {
1720 while (*p
&& *p
!= ' ' && *p
!= '\t')
1729 static int mount_entry(const char *fsname
, const char *target
,
1730 const char *fstype
, unsigned long mountflags
,
1731 const char *data
, int optional
, int dev
,
1739 ret
= safe_mount(fsname
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
1743 INFO("Failed to mount \"%s\" on \"%s\" (optional): %s",
1744 fsname
, target
, strerror(errno
));
1748 SYSERROR("Failed to mount \"%s\" on \"%s\"", fsname
, target
);
1752 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
1753 unsigned long rqd_flags
= 0;
1755 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
1757 fsname
? fsname
: "(none)", target
? target
: "(none)");
1759 if (mountflags
& MS_RDONLY
)
1760 rqd_flags
|= MS_RDONLY
;
1762 if (statvfs(fsname
, &sb
) == 0) {
1763 unsigned long required_flags
= rqd_flags
;
1765 if (sb
.f_flag
& MS_NOSUID
)
1766 required_flags
|= MS_NOSUID
;
1768 if (sb
.f_flag
& MS_NODEV
&& !dev
)
1769 required_flags
|= MS_NODEV
;
1771 if (sb
.f_flag
& MS_RDONLY
)
1772 required_flags
|= MS_RDONLY
;
1774 if (sb
.f_flag
& MS_NOEXEC
)
1775 required_flags
|= MS_NOEXEC
;
1777 DEBUG("Flags for \"%s\" were %lu, required extra flags "
1778 "are %lu", fsname
, sb
.f_flag
, required_flags
);
1780 /* If this was a bind mount request, and required_flags
1781 * does not have any flags which are not already in
1782 * mountflags, then skip the remount.
1784 if (!(mountflags
& MS_REMOUNT
)) {
1785 if (!(required_flags
& ~mountflags
) &&
1787 DEBUG("Mountflags already were %lu, "
1788 "skipping remount", mountflags
);
1793 mountflags
|= required_flags
;
1797 ret
= mount(fsname
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
1800 INFO("Failed to mount \"%s\" on \"%s\" "
1801 "(optional): %s", fsname
, target
,
1806 SYSERROR("Failed to mount \"%s\" on \"%s\"", fsname
, target
);
1814 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"", fsname
,
1820 /* Remove "optional", "create=dir", and "create=file" from mntopt */
1821 static void cull_mntent_opt(struct mntent
*mntent
)
1824 char *list
[] = {"create=dir", "create=file", "optional", NULL
};
1826 for (i
= 0; list
[i
]; i
++) {
1829 p
= strstr(mntent
->mnt_opts
, list
[i
]);
1833 p2
= strchr(p
, ',');
1835 /* no more mntopts, so just chop it here */
1840 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
1844 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
1846 const struct lxc_rootfs
*rootfs
,
1847 const char *lxc_name
,
1848 const char *lxc_path
)
1852 if (!strncmp(mntent
->mnt_type
, "overlay", 7))
1853 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
1854 else if (!strncmp(mntent
->mnt_type
, "aufs", 4))
1855 ret
= aufs_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
1859 if (hasmntopt(mntent
, "create=dir")) {
1860 ret
= mkdir_p(path
, 0755);
1861 if (ret
< 0 && errno
!= EEXIST
) {
1862 SYSERROR("Failed to create directory \"%s\"", path
);
1867 if (hasmntopt(mntent
, "create=file") && access(path
, F_OK
)) {
1877 ret
= mkdir_p(p2
, 0755);
1879 if (ret
< 0 && errno
!= EEXIST
) {
1880 SYSERROR("Failed to create directory \"%s\"", path
);
1884 fd
= open(path
, O_CREAT
, 0644);
1893 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
1894 * without a rootfs. */
1895 static inline int mount_entry_on_generic(struct mntent
*mntent
,
1897 const struct lxc_rootfs
*rootfs
,
1898 const char *lxc_name
,
1899 const char *lxc_path
)
1902 unsigned long mntflags
;
1905 char *rootfs_path
= NULL
;
1907 optional
= hasmntopt(mntent
, "optional") != NULL
;
1908 dev
= hasmntopt(mntent
, "dev") != NULL
;
1910 if (rootfs
&& rootfs
->path
)
1911 rootfs_path
= rootfs
->mount
;
1913 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
1921 cull_mntent_opt(mntent
);
1923 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
1927 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
1928 mntdata
, optional
, dev
, rootfs_path
);
1934 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
1937 char path
[MAXPATHLEN
];
1939 /* For containers created without a rootfs all mounts are treated as
1940 * absolute paths starting at / on the host.
1942 if (mntent
->mnt_dir
[0] != '/')
1943 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
1945 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
1946 if (ret
< 0 || ret
>= sizeof(path
))
1949 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
1952 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
1953 const struct lxc_rootfs
*rootfs
,
1954 const char *lxc_name
,
1955 const char *lxc_path
)
1959 const char *lxcpath
;
1960 char path
[MAXPATHLEN
];
1963 lxcpath
= lxc_global_config_value("lxc.lxcpath");
1967 /* If rootfs->path is a blockdev path, allow container fstab to use
1968 * <lxcpath>/<name>/rootfs" as the target prefix.
1970 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, lxc_name
);
1971 if (ret
< 0 || ret
>= MAXPATHLEN
)
1974 aux
= strstr(mntent
->mnt_dir
, path
);
1976 offset
= strlen(path
);
1981 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
1983 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
1986 offset
= strlen(rootfs
->path
);
1989 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", rootfs
->mount
, aux
+ offset
);
1990 if (ret
< 0 || ret
>= MAXPATHLEN
)
1993 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
1996 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
1997 const struct lxc_rootfs
*rootfs
,
1998 const char *lxc_name
,
1999 const char *lxc_path
)
2001 char path
[MAXPATHLEN
];
2004 /* relative to root mount point */
2005 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2006 if (ret
< 0 || ret
>= sizeof(path
)) {
2007 ERROR("path name too long");
2011 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2014 /* This logs a NOTICE() when a user specifies mounts that would conflict with
2015 * devices liblxc sets up automatically.
2017 static void log_notice_on_conflict(const struct lxc_conf
*conf
, const char *src
,
2020 char *clean_mnt_fsname
, *clean_mnt_dir
, *tmp
;
2021 bool needs_warning
= false;
2023 clean_mnt_fsname
= lxc_deslashify(src
);
2024 if (!clean_mnt_fsname
)
2027 clean_mnt_dir
= lxc_deslashify(dest
);
2028 if (!clean_mnt_dir
) {
2029 free(clean_mnt_fsname
);
2033 tmp
= clean_mnt_dir
;
2037 if (strncmp(src
, "/dev", 4) || strncmp(tmp
, "dev", 3)) {
2038 free(clean_mnt_dir
);
2039 free(clean_mnt_fsname
);
2043 if (!conf
->autodev
&& !conf
->pts
&& !conf
->tty
&&
2044 (!conf
->console
.path
|| !strcmp(conf
->console
.path
, "none"))) {
2045 free(clean_mnt_dir
);
2046 free(clean_mnt_fsname
);
2050 if (!strcmp(tmp
, "dev") && conf
->autodev
> 0)
2051 needs_warning
= true;
2052 else if (!strcmp(tmp
, "dev/pts") && (conf
->autodev
> 0 || conf
->pts
> 0))
2053 needs_warning
= true;
2054 else if (!strcmp(tmp
, "dev/ptmx") && (conf
->autodev
> 0 || conf
->pts
> 0))
2055 needs_warning
= true;
2056 else if (!strcmp(tmp
, "dev/pts/ptmx") && (conf
->autodev
> 0 || conf
->pts
> 0))
2057 needs_warning
= true;
2058 else if (!strcmp(tmp
, "dev/null") && conf
->autodev
> 0)
2059 needs_warning
= true;
2060 else if (!strcmp(tmp
, "dev/zero") && conf
->autodev
> 0)
2061 needs_warning
= true;
2062 else if (!strcmp(tmp
, "dev/full") && conf
->autodev
> 0)
2063 needs_warning
= true;
2064 else if (!strcmp(tmp
, "dev/urandom") && conf
->autodev
> 0)
2065 needs_warning
= true;
2066 else if (!strcmp(tmp
, "dev/random") && conf
->autodev
> 0)
2067 needs_warning
= true;
2068 else if (!strcmp(tmp
, "dev/tty") && conf
->autodev
> 0)
2069 needs_warning
= true;
2070 else if (!strncmp(tmp
, "dev/tty", 7) && (conf
->autodev
> 0 || conf
->tty
> 0))
2071 needs_warning
= true;
2074 NOTICE("Requesting to mount \"%s\" on \"%s\" while requesting "
2075 "automatic device setup under \"/dev\"",
2076 clean_mnt_fsname
, clean_mnt_dir
);
2078 free(clean_mnt_dir
);
2079 free(clean_mnt_fsname
);
2082 static int mount_file_entries(const struct lxc_conf
*conf
,
2083 const struct lxc_rootfs
*rootfs
, FILE *file
,
2084 const char *lxc_name
, const char *lxc_path
)
2086 struct mntent mntent
;
2090 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2091 log_notice_on_conflict(conf
, mntent
.mnt_fsname
, mntent
.mnt_dir
);
2094 ret
= mount_entry_on_systemfs(&mntent
);
2095 else if (mntent
.mnt_dir
[0] != '/')
2096 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2097 lxc_name
, lxc_path
);
2099 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2100 lxc_name
, lxc_path
);
2106 INFO("Set up mount entries");
2110 static int setup_mount(const struct lxc_conf
*conf
,
2111 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2112 const char *lxc_name
, const char *lxc_path
)
2120 f
= setmntent(fstab
, "r");
2122 SYSERROR("Failed to open \"%s\"", fstab
);
2126 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2128 ERROR("Failed to set up mount entries");
2134 FILE *make_anonymous_mount_file(struct lxc_list
*mount
)
2138 struct lxc_list
*iterator
;
2142 fd
= memfd_create("lxc_mount_file", MFD_CLOEXEC
);
2144 if (errno
!= ENOSYS
)
2147 TRACE("Created temporary mount file");
2149 f
= fdopen(fd
, "r+");
2150 TRACE("Created anonymous mount file");
2154 SYSERROR("Could not create mount file");
2160 lxc_list_for_each(iterator
, mount
) {
2161 mount_entry
= iterator
->elem
;
2162 ret
= fprintf(f
, "%s\n", mount_entry
);
2163 if (ret
< strlen(mount_entry
))
2164 WARN("Could not write mount entry to mount file");
2167 ret
= fseek(f
, 0, SEEK_SET
);
2169 SYSERROR("Failed to seek mount file");
2177 static int setup_mount_entries(const struct lxc_conf
*conf
,
2178 const struct lxc_rootfs
*rootfs
,
2179 struct lxc_list
*mount
, const char *lxc_name
,
2180 const char *lxc_path
)
2185 f
= make_anonymous_mount_file(mount
);
2189 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2195 static int parse_cap(const char *cap
)
2201 if (!strcmp(cap
, "none"))
2204 for (i
= 0; i
< sizeof(caps_opt
)/sizeof(caps_opt
[0]); i
++) {
2206 if (strcmp(cap
, caps_opt
[i
].name
))
2209 capid
= caps_opt
[i
].value
;
2214 /* try to see if it's numeric, so the user may specify
2215 * capabilities that the running kernel knows about but
2218 capid
= strtol(cap
, &ptr
, 10);
2219 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2220 /* not a valid number */
2222 else if (capid
> lxc_caps_last_cap())
2223 /* we have a number but it's not a valid
2231 int in_caplist(int cap
, struct lxc_list
*caps
)
2233 struct lxc_list
*iterator
;
2236 lxc_list_for_each(iterator
, caps
) {
2237 capid
= parse_cap(iterator
->elem
);
2245 static int setup_caps(struct lxc_list
*caps
)
2247 struct lxc_list
*iterator
;
2251 lxc_list_for_each(iterator
, caps
) {
2253 drop_entry
= iterator
->elem
;
2255 capid
= parse_cap(drop_entry
);
2258 ERROR("unknown capability %s", drop_entry
);
2262 DEBUG("drop capability '%s' (%d)", drop_entry
, capid
);
2264 if (prctl(PR_CAPBSET_DROP
, capid
, 0, 0, 0)) {
2265 SYSERROR("failed to remove %s capability", drop_entry
);
2271 DEBUG("capabilities have been setup");
2276 static int dropcaps_except(struct lxc_list
*caps
)
2278 struct lxc_list
*iterator
;
2281 int numcaps
= lxc_caps_last_cap() + 1;
2282 INFO("found %d capabilities", numcaps
);
2284 if (numcaps
<= 0 || numcaps
> 200)
2287 /* caplist[i] is 1 if we keep capability i */
2288 int *caplist
= alloca(numcaps
* sizeof(int));
2289 memset(caplist
, 0, numcaps
* sizeof(int));
2291 lxc_list_for_each(iterator
, caps
) {
2293 keep_entry
= iterator
->elem
;
2295 capid
= parse_cap(keep_entry
);
2301 ERROR("unknown capability %s", keep_entry
);
2305 DEBUG("keep capability '%s' (%d)", keep_entry
, capid
);
2309 for (i
=0; i
<numcaps
; i
++) {
2312 if (prctl(PR_CAPBSET_DROP
, i
, 0, 0, 0)) {
2313 SYSERROR("failed to remove capability %d", i
);
2318 DEBUG("capabilities have been setup");
2323 static int parse_resource(const char *res
) {
2327 for (i
= 0; i
< sizeof(limit_opt
)/sizeof(limit_opt
[0]); ++i
) {
2328 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2329 return limit_opt
[i
].value
;
2332 /* try to see if it's numeric, so the user may specify
2333 * resources that the running kernel knows about but
2335 if (lxc_safe_int(res
, &resid
) == 0)
2340 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
) {
2341 struct lxc_list
*it
;
2342 struct lxc_limit
*lim
;
2345 lxc_list_for_each(it
, limits
) {
2348 resid
= parse_resource(lim
->resource
);
2350 ERROR("unknown resource %s", lim
->resource
);
2354 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2355 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2356 ERROR("failed to set limit %s: %s", lim
->resource
, strerror(errno
));
2360 ERROR("Cannot set limit %s as prlimit is missing", lim
->resource
);
2367 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2369 struct lxc_conf
*lxc_conf_init(void)
2371 struct lxc_conf
*new;
2374 new = malloc(sizeof(*new));
2376 ERROR("lxc_conf_init : %s", strerror(errno
));
2379 memset(new, 0, sizeof(*new));
2381 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2382 new->personality
= -1;
2384 new->console
.buffer_log_file
= NULL
;
2385 new->console
.buffer_log_file_fd
= -1;
2386 new->console
.buffer_size
= 0;
2387 new->console
.log_path
= NULL
;
2388 new->console
.log_fd
= -1;
2389 new->console
.path
= NULL
;
2390 new->console
.peer
= -1;
2391 new->console
.peerpty
.busy
= -1;
2392 new->console
.peerpty
.master
= -1;
2393 new->console
.peerpty
.slave
= -1;
2394 new->console
.master
= -1;
2395 new->console
.slave
= -1;
2396 new->console
.name
[0] = '\0';
2397 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2398 new->maincmd_fd
= -1;
2400 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2401 if (!new->rootfs
.mount
) {
2402 ERROR("lxc_conf_init : %s", strerror(errno
));
2407 lxc_list_init(&new->cgroup
);
2408 lxc_list_init(&new->network
);
2409 lxc_list_init(&new->mount_list
);
2410 lxc_list_init(&new->caps
);
2411 lxc_list_init(&new->keepcaps
);
2412 lxc_list_init(&new->id_map
);
2413 lxc_list_init(&new->includes
);
2414 lxc_list_init(&new->aliens
);
2415 lxc_list_init(&new->environment
);
2416 lxc_list_init(&new->limits
);
2417 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2418 lxc_list_init(&new->hooks
[i
]);
2419 lxc_list_init(&new->groups
);
2420 new->lsm_aa_profile
= NULL
;
2421 new->lsm_se_context
= NULL
;
2422 new->tmp_umount_proc
= 0;
2424 /* if running in a new user namespace, init and COMMAND
2425 * default to running as UID/GID 0 when using lxc-execute */
2428 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2429 memset(&new->inherit_ns
, 0, sizeof(char *) * LXC_NS_MAX
);
2434 static int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2437 char path
[MAXPATHLEN
];
2440 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/%cid_map", pid
,
2441 idtype
== ID_TYPE_UID
? 'u' : 'g');
2442 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2443 ERROR("failed to create path \"%s\"", path
);
2447 fd
= open(path
, O_WRONLY
);
2449 SYSERROR("failed to open \"%s\"", path
);
2454 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2455 if (ret
!= buf_size
) {
2456 SYSERROR("failed to write %cid mapping to \"%s\"",
2457 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2466 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2468 * @return 1 if functional binary was found
2469 * @return 0 if binary exists but is lacking privilege
2470 * @return -ENOENT if binary does not exist
2471 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2474 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2481 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2484 path
= on_path(binary
, NULL
);
2488 ret
= stat(path
, &st
);
2494 /* Check if the binary is setuid. */
2495 if (st
.st_mode
& S_ISUID
) {
2496 DEBUG("The binary \"%s\" does have the setuid bit set.", path
);
2501 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2502 /* Check if it has the CAP_SETUID capability. */
2503 if ((cap
& CAP_SETUID
) &&
2504 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2505 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2506 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2507 "and CAP_PERMITTED sets.", path
);
2512 /* Check if it has the CAP_SETGID capability. */
2513 if ((cap
& CAP_SETGID
) &&
2514 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2515 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2516 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2517 "and CAP_PERMITTED sets.", path
);
2522 /* If we cannot check for file capabilities we need to give the benefit
2523 * of the doubt. Otherwise we might fail even though all the necessary
2524 * file capabilities are set.
2526 DEBUG("Cannot check for file capabilites as full capability support is "
2527 "missing. Manual intervention needed.");
2536 int lxc_map_ids_exec_wrapper(void *args
)
2538 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2542 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2545 struct lxc_list
*iterator
;
2550 char cmd_output
[MAXPATHLEN
];
2551 /* strlen("new@idmap") = 9
2559 * We add some additional space to make sure that we really have
2560 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2562 char mapbuf
[9 + 1 + LXC_NUMSTRLEN64
+ 1 + LXC_IDMAPLEN
] = {0};
2563 int ret
= 0, uidmap
= 0, gidmap
= 0;
2564 bool use_shadow
= false, had_entry
= false;
2566 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2567 * ranges, then insist that root also reserve ranges in subuid. This
2568 * will protected it by preventing another user from being handed the
2571 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2572 if (uidmap
== -ENOENT
)
2573 WARN("newuidmap binary is missing");
2575 WARN("newuidmap is lacking necessary privileges");
2577 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2578 if (gidmap
== -ENOENT
)
2579 WARN("newgidmap binary is missing");
2581 WARN("newgidmap is lacking necessary privileges");
2583 if (uidmap
> 0 && gidmap
> 0) {
2584 DEBUG("Functional newuidmap and newgidmap binary found.");
2587 /* In case unprivileged users run application containers via
2588 * execute() or a start*() there are valid cases where they may
2589 * only want to map their own {g,u}id. Let's not block them from
2590 * doing so by requiring geteuid() == 0.
2592 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2593 "write directly with euid %d.", geteuid());
2596 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
2597 type
++, u_or_g
= 'g') {
2601 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
2603 lxc_list_for_each(iterator
, idmap
) {
2604 map
= iterator
->elem
;
2605 if (map
->idtype
!= type
)
2610 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
2611 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
2612 use_shadow
? " " : "", map
->nsid
,
2613 map
->hostid
, map
->range
,
2614 use_shadow
? "" : "\n");
2615 if (fill
<= 0 || fill
>= left
) {
2616 /* The kernel only takes <= 4k for writes to
2617 * /proc/<pid>/{g,u}id_map
2619 SYSERROR("Too many %cid mappings defined", u_or_g
);
2628 /* Try to catch the ouput of new{g,u}idmap to make debugging
2632 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2633 lxc_map_ids_exec_wrapper
,
2636 ERROR("new%cidmap failed to write mapping \"%s\": %s",
2637 u_or_g
, cmd_output
, mapbuf
);
2640 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
2642 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
2644 ERROR("Failed to write mapping: %s", mapbuf
);
2647 TRACE("Wrote mapping \"%s\"", mapbuf
);
2650 memset(mapbuf
, 0, sizeof(mapbuf
));
2657 * return the host uid/gid to which the container root is mapped in
2659 * Return true if id was found, false otherwise.
2661 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
2664 struct lxc_list
*it
;
2667 lxc_list_for_each(it
, &conf
->id_map
) {
2669 if (map
->idtype
!= idtype
)
2679 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
2681 struct lxc_list
*it
;
2683 lxc_list_for_each(it
, &conf
->id_map
) {
2685 if (map
->idtype
!= idtype
)
2687 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
2688 return (id
- map
->hostid
) + map
->nsid
;
2693 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
2695 struct lxc_list
*it
;
2697 unsigned int freeid
= 0;
2699 lxc_list_for_each(it
, &conf
->id_map
) {
2701 if (map
->idtype
!= idtype
)
2703 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
2704 freeid
= map
->nsid
+ map
->range
;
2711 int chown_mapped_root_exec_wrapper(void *args
)
2713 execvp("lxc-usernsexec", args
);
2718 * chown_mapped_root: for an unprivileged user with uid/gid X to
2719 * chown a dir to subuid/subgid Y, he needs to run chown as root
2720 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
2721 * nsid Y is mapped to hostuid/hostgid X. That way, the container
2722 * root is privileged with respect to hostuid/hostgid X, allowing
2723 * him to do the chown.
2725 int chown_mapped_root(char *path
, struct lxc_conf
*conf
)
2727 uid_t rootuid
, rootgid
;
2729 int hostuid
, hostgid
, ret
;
2731 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
2733 char *args1
[] = {"lxc-usernsexec",
2738 "--", "chown", ugid
, path
,
2740 char *args2
[] = {"lxc-usernsexec",
2746 "--", "chown", ugid
, path
,
2748 char cmd_output
[MAXPATHLEN
];
2750 hostuid
= geteuid();
2751 hostgid
= getegid();
2753 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
2754 ERROR("No uid mapping for container root");
2757 rootuid
= (uid_t
)val
;
2758 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
2759 ERROR("No gid mapping for container root");
2762 rootgid
= (gid_t
)val
;
2765 if (chown(path
, rootuid
, rootgid
) < 0) {
2766 ERROR("Error chowning %s", path
);
2772 if (rootuid
== hostuid
) {
2774 INFO("Container root is our uid; no need to chown");
2778 /* save the current gid of "path" */
2779 if (stat(path
, &sb
) < 0) {
2780 ERROR("Error stat %s", path
);
2784 /* Update the path argument in case this was overlayfs. */
2785 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
2786 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
2789 * A file has to be group-owned by a gid mapped into the
2790 * container, or the container won't be privileged over it.
2792 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
2793 if (sb
.st_uid
== hostuid
&&
2794 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
2795 chown(path
, -1, hostgid
) < 0) {
2796 ERROR("Failed chgrping %s", path
);
2800 /* "u:0:rootuid:1" */
2801 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
2802 if (ret
< 0 || ret
>= 100) {
2803 ERROR("Error uid printing map string");
2807 /* "u:hostuid:hostuid:1" */
2808 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
2809 if (ret
< 0 || ret
>= 100) {
2810 ERROR("Error uid printing map string");
2814 /* "g:0:rootgid:1" */
2815 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
2816 if (ret
< 0 || ret
>= 100) {
2817 ERROR("Error gid printing map string");
2821 /* "g:pathgid:rootgid+pathgid:1" */
2822 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
2823 rootgid
+ (gid_t
)sb
.st_gid
);
2824 if (ret
< 0 || ret
>= 100) {
2825 ERROR("Error gid printing map string");
2829 /* "g:hostgid:hostgid:1" */
2830 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
2831 if (ret
< 0 || ret
>= 100) {
2832 ERROR("Error gid printing map string");
2836 /* "0:pathgid" (chown) */
2837 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
2838 if (ret
< 0 || ret
>= 100) {
2839 ERROR("Error owner printing format string for chown");
2843 if (hostgid
== sb
.st_gid
)
2844 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2845 chown_mapped_root_exec_wrapper
,
2848 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2849 chown_mapped_root_exec_wrapper
,
2852 ERROR("lxc-usernsexec failed: %s", cmd_output
);
2857 int lxc_ttys_shift_ids(struct lxc_conf
*c
)
2859 if (lxc_list_empty(&c
->id_map
))
2862 if (!strcmp(c
->console
.name
, ""))
2865 if (chown_mapped_root(c
->console
.name
, c
) < 0) {
2866 ERROR("failed to chown console \"%s\"", c
->console
.name
);
2870 TRACE("chowned console \"%s\"", c
->console
.name
);
2875 /* NOTE: Must not be called from inside the container namespace! */
2876 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
2880 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
2881 if (mounted
== -1) {
2882 SYSERROR("failed to mount /proc in the container");
2883 /* continue only if there is no rootfs */
2884 if (conf
->rootfs
.path
)
2886 } else if (mounted
== 1) {
2887 conf
->tmp_umount_proc
= 1;
2893 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
2895 if (lxc_conf
->tmp_umount_proc
== 1) {
2897 lxc_conf
->tmp_umount_proc
= 0;
2901 void remount_all_slave(void)
2903 /* walk /proc/mounts and change any shared entries to slave */
2904 FILE *f
= fopen("/proc/self/mountinfo", "r");
2909 SYSERROR("Failed to open /proc/self/mountinfo to mark all shared");
2910 ERROR("Continuing container startup...");
2914 while (getline(&line
, &len
, f
) != -1) {
2915 char *target
, *opts
;
2916 target
= get_field(line
, 4);
2919 opts
= get_field(target
, 2);
2922 null_endofword(opts
);
2923 if (!strstr(opts
, "shared"))
2925 null_endofword(target
);
2926 if (mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
)) {
2927 SYSERROR("Failed to make %s rslave", target
);
2928 ERROR("Continuing...");
2935 void lxc_execute_bind_init(struct lxc_conf
*conf
)
2938 char path
[PATH_MAX
], destpath
[PATH_MAX
], *p
;
2940 /* If init exists in the container, don't bind mount a static one */
2941 p
= choose_init(conf
->rootfs
.mount
);
2947 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
2948 if (ret
< 0 || ret
>= PATH_MAX
) {
2949 WARN("Path name too long searching for lxc.init.static");
2953 if (!file_exists(path
)) {
2954 INFO("%s does not exist on host", path
);
2958 ret
= snprintf(destpath
, PATH_MAX
, "%s%s", conf
->rootfs
.mount
, "/init.lxc.static");
2959 if (ret
< 0 || ret
>= PATH_MAX
) {
2960 WARN("Path name too long for container's lxc.init.static");
2964 if (!file_exists(destpath
)) {
2965 FILE * pathfile
= fopen(destpath
, "wb");
2967 SYSERROR("Failed to create mount target '%s'", destpath
);
2973 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
2975 SYSERROR("Failed to bind lxc.init.static into container");
2976 INFO("lxc.init.static bound into container at %s", path
);
2980 * This does the work of remounting / if it is shared, calling the
2981 * container pre-mount hooks, and mounting the rootfs.
2983 int do_rootfs_setup(struct lxc_conf
*conf
, const char *name
, const char *lxcpath
)
2985 if (conf
->rootfs_setup
) {
2987 * rootfs was set up in another namespace. bind-mount it
2988 * to give us a mount in our own ns so we can pivot_root to it
2990 const char *path
= conf
->rootfs
.mount
;
2991 if (mount(path
, path
, "rootfs", MS_BIND
, NULL
) < 0) {
2992 ERROR("Failed to bind-mount container / onto itself");
2998 remount_all_slave();
3000 if (run_lxc_hooks(name
, "pre-mount", conf
, lxcpath
, NULL
)) {
3001 ERROR("failed to run pre-mount hooks for container '%s'.", name
);
3005 if (lxc_setup_rootfs(conf
)) {
3006 ERROR("failed to setup rootfs for '%s'", name
);
3010 conf
->rootfs_setup
= true;
3014 static bool verify_start_hooks(struct lxc_conf
*conf
)
3016 struct lxc_list
*it
;
3017 char path
[MAXPATHLEN
];
3018 lxc_list_for_each(it
, &conf
->hooks
[LXCHOOK_START
]) {
3019 char *hookname
= it
->elem
;
3023 ret
= snprintf(path
, MAXPATHLEN
, "%s%s",
3024 conf
->rootfs
.path
? conf
->rootfs
.mount
: "", hookname
);
3025 if (ret
< 0 || ret
>= MAXPATHLEN
)
3027 ret
= stat(path
, &st
);
3029 SYSERROR("Start hook %s not found in container",
3039 int lxc_setup(struct lxc_handler
*handler
)
3042 const char *name
= handler
->name
;
3043 struct lxc_conf
*lxc_conf
= handler
->conf
;
3044 const char *lxcpath
= handler
->lxcpath
;
3046 if (do_rootfs_setup(lxc_conf
, name
, lxcpath
) < 0) {
3047 ERROR("Error setting up rootfs mount after spawn");
3051 if (handler
->nsfd
[LXC_NS_UTS
] == -1) {
3052 if (setup_utsname(lxc_conf
->utsname
)) {
3053 ERROR("failed to setup the utsname for '%s'", name
);
3058 if (lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
)) {
3059 ERROR("failed to setup the network for '%s'", name
);
3063 if (lxc_network_send_name_and_ifindex_to_parent(handler
) < 0) {
3064 ERROR("Failed to network device names and ifindices to parent");
3068 if (lxc_conf
->autodev
> 0) {
3069 if (mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
)) {
3070 ERROR("failed to mount /dev in the container");
3075 /* do automatic mounts (mainly /proc and /sys), but exclude
3076 * those that need to wait until other stuff has finished
3078 if (lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
) < 0) {
3079 ERROR("failed to setup the automatic mounts for '%s'", name
);
3083 if (setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
)) {
3084 ERROR("failed to setup the mounts for '%s'", name
);
3088 if (!lxc_list_empty(&lxc_conf
->mount_list
) && setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
, &lxc_conf
->mount_list
, name
, lxcpath
)) {
3089 ERROR("failed to setup the mount entries for '%s'", name
);
3093 /* Make sure any start hooks are in the container */
3094 if (!verify_start_hooks(lxc_conf
))
3097 if (lxc_conf
->is_execute
)
3098 lxc_execute_bind_init(lxc_conf
);
3100 /* now mount only cgroup, if wanted;
3101 * before, /sys could not have been mounted
3102 * (is either mounted automatically or via fstab entries)
3104 if (lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
) < 0) {
3105 ERROR("failed to setup the automatic mounts for '%s'", name
);
3109 if (run_lxc_hooks(name
, "mount", lxc_conf
, lxcpath
, NULL
)) {
3110 ERROR("failed to run mount hooks for container '%s'.", name
);
3114 if (lxc_conf
->autodev
> 0) {
3115 if (run_lxc_hooks(name
, "autodev", lxc_conf
, lxcpath
, NULL
)) {
3116 ERROR("failed to run autodev hooks for container '%s'.", name
);
3120 if (lxc_fill_autodev(&lxc_conf
->rootfs
)) {
3121 ERROR("failed to populate /dev in the container");
3126 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3129 ERROR("Failed to setup console");
3133 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3135 ERROR("Failed to setup /dev symlinks");
3139 /* mount /proc if it's not already there */
3140 if (lxc_create_tmp_proc_mount(lxc_conf
) < 0) {
3141 ERROR("failed to LSM mount proc for '%s'", name
);
3145 if (setup_pivot_root(&lxc_conf
->rootfs
)) {
3146 ERROR("failed to set rootfs for '%s'", name
);
3150 if (lxc_setup_devpts(lxc_conf
->pts
)) {
3151 ERROR("failed to setup the new pts instance");
3155 ret
= lxc_create_ttys(handler
);
3159 if (setup_personality(lxc_conf
->personality
)) {
3160 ERROR("failed to setup personality");
3164 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3165 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3166 ERROR("Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both.");
3169 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3170 ERROR("failed to keep requested caps");
3173 } else if (setup_caps(&lxc_conf
->caps
)) {
3174 ERROR("failed to drop capabilities");
3178 NOTICE("Container \"%s\" is set up", name
);
3183 int run_lxc_hooks(const char *name
, char *hook
, struct lxc_conf
*conf
,
3184 const char *lxcpath
, char *argv
[])
3187 struct lxc_list
*it
;
3189 if (strcmp(hook
, "pre-start") == 0)
3190 which
= LXCHOOK_PRESTART
;
3191 else if (strcmp(hook
, "start-host") == 0)
3192 which
= LXCHOOK_START_HOST
;
3193 else if (strcmp(hook
, "pre-mount") == 0)
3194 which
= LXCHOOK_PREMOUNT
;
3195 else if (strcmp(hook
, "mount") == 0)
3196 which
= LXCHOOK_MOUNT
;
3197 else if (strcmp(hook
, "autodev") == 0)
3198 which
= LXCHOOK_AUTODEV
;
3199 else if (strcmp(hook
, "start") == 0)
3200 which
= LXCHOOK_START
;
3201 else if (strcmp(hook
, "stop") == 0)
3202 which
= LXCHOOK_STOP
;
3203 else if (strcmp(hook
, "post-stop") == 0)
3204 which
= LXCHOOK_POSTSTOP
;
3205 else if (strcmp(hook
, "clone") == 0)
3206 which
= LXCHOOK_CLONE
;
3207 else if (strcmp(hook
, "destroy") == 0)
3208 which
= LXCHOOK_DESTROY
;
3211 lxc_list_for_each(it
, &conf
->hooks
[which
]) {
3213 char *hookname
= it
->elem
;
3214 ret
= run_script_argv(name
, "lxc", hookname
, hook
, lxcpath
, argv
);
3221 int lxc_clear_config_caps(struct lxc_conf
*c
)
3223 struct lxc_list
*it
, *next
;
3225 lxc_list_for_each_safe(it
, &c
->caps
, next
) {
3233 static int lxc_free_idmap(struct lxc_list
*id_map
) {
3234 struct lxc_list
*it
, *next
;
3236 lxc_list_for_each_safe(it
, id_map
, next
) {
3244 int lxc_clear_idmaps(struct lxc_conf
*c
)
3246 return lxc_free_idmap(&c
->id_map
);
3249 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3251 struct lxc_list
*it
,*next
;
3253 lxc_list_for_each_safe(it
, &c
->keepcaps
, next
) {
3261 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
)
3263 struct lxc_list
*it
,*next
;
3265 const char *k
= NULL
;
3267 if (strcmp(key
, "lxc.cgroup") == 0)
3269 else if (strncmp(key
, "lxc.cgroup.", sizeof("lxc.cgroup.")-1) == 0)
3270 k
= key
+ sizeof("lxc.cgroup.")-1;
3274 lxc_list_for_each_safe(it
, &c
->cgroup
, next
) {
3275 struct lxc_cgroup
*cg
= it
->elem
;
3276 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3279 free(cg
->subsystem
);
3287 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3289 struct lxc_list
*it
, *next
;
3291 const char *k
= NULL
;
3293 if (strcmp(key
, "lxc.limit") == 0
3294 || strcmp(key
, "lxc.prlimit"))
3296 else if (strncmp(key
, "lxc.limit.", sizeof("lxc.limit.")-1) == 0)
3297 k
= key
+ sizeof("lxc.limit.")-1;
3298 else if (strncmp(key
, "lxc.prlimit.", sizeof("lxc.prlimit.")-1) == 0)
3299 k
= key
+ sizeof("lxc.prlimit.")-1;
3303 lxc_list_for_each_safe(it
, &c
->limits
, next
) {
3304 struct lxc_limit
*lim
= it
->elem
;
3305 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3308 free(lim
->resource
);
3315 int lxc_clear_groups(struct lxc_conf
*c
)
3317 struct lxc_list
*it
,*next
;
3319 lxc_list_for_each_safe(it
, &c
->groups
, next
) {
3327 int lxc_clear_environment(struct lxc_conf
*c
)
3329 struct lxc_list
*it
,*next
;
3331 lxc_list_for_each_safe(it
, &c
->environment
, next
) {
3339 int lxc_clear_mount_entries(struct lxc_conf
*c
)
3341 struct lxc_list
*it
,*next
;
3343 lxc_list_for_each_safe(it
, &c
->mount_list
, next
) {
3351 int lxc_clear_automounts(struct lxc_conf
*c
)
3357 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
3359 struct lxc_list
*it
,*next
;
3360 bool all
= false, done
= false;
3361 const char *k
= NULL
;
3364 if (strcmp(key
, "lxc.hook") == 0)
3366 else if (strncmp(key
, "lxc.hook.", sizeof("lxc.hook.")-1) == 0)
3367 k
= key
+ sizeof("lxc.hook.")-1;
3371 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3372 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
3373 lxc_list_for_each_safe(it
, &c
->hooks
[i
], next
) {
3383 ERROR("Invalid hook key: %s", key
);
3389 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
3391 struct lxc_list
*it
,*next
;
3393 lxc_list_for_each_safe(it
, &conf
->aliens
, next
) {
3400 void lxc_clear_includes(struct lxc_conf
*conf
)
3402 struct lxc_list
*it
,*next
;
3404 lxc_list_for_each_safe(it
, &conf
->includes
, next
) {
3411 void lxc_conf_free(struct lxc_conf
*conf
)
3415 if (current_config
== conf
)
3416 current_config
= NULL
;
3417 free(conf
->console
.buffer_log_file
);
3418 free(conf
->console
.log_path
);
3419 free(conf
->console
.path
);
3420 if (conf
->console
.buffer_size
> 0 && conf
->console
.ringbuf
.addr
)
3421 lxc_ringbuf_release(&conf
->console
.ringbuf
);
3422 free(conf
->rootfs
.mount
);
3423 free(conf
->rootfs
.bdev_type
);
3424 free(conf
->rootfs
.options
);
3425 free(conf
->rootfs
.path
);
3426 free(conf
->logfile
);
3427 if (conf
->logfd
!= -1)
3429 free(conf
->utsname
);
3433 free(conf
->execute_cmd
);
3434 free(conf
->init_cmd
);
3435 free(conf
->unexpanded_config
);
3436 free(conf
->pty_names
);
3438 lxc_free_networks(&conf
->network
);
3439 free(conf
->lsm_aa_profile
);
3440 free(conf
->lsm_se_context
);
3441 lxc_seccomp_free(conf
);
3442 lxc_clear_config_caps(conf
);
3443 lxc_clear_config_keepcaps(conf
);
3444 lxc_clear_cgroups(conf
, "lxc.cgroup");
3445 lxc_clear_hooks(conf
, "lxc.hook");
3446 lxc_clear_mount_entries(conf
);
3447 lxc_clear_idmaps(conf
);
3448 lxc_clear_groups(conf
);
3449 lxc_clear_includes(conf
);
3450 lxc_clear_aliens(conf
);
3451 lxc_clear_environment(conf
);
3452 lxc_clear_limits(conf
, "lxc.prlimit");
3453 free(conf
->cgroup_meta
.dir
);
3454 free(conf
->cgroup_meta
.controllers
);
3458 struct userns_fn_data
{
3460 const char *fn_name
;
3465 static int run_userns_fn(void *data
)
3467 struct userns_fn_data
*d
= data
;
3470 /* Close write end of the pipe. */
3473 /* Wait for parent to finish establishing a new mapping in the user
3474 * namespace we are executing in.
3476 if (read(d
->p
[0], &c
, 1) != 1)
3479 /* Close read end of the pipe. */
3483 TRACE("calling function \"%s\"", d
->fn_name
);
3484 /* Call function to run. */
3485 return d
->fn(d
->arg
);
3488 static struct id_map
*mapped_hostid_entry(struct lxc_conf
*conf
, unsigned id
,
3491 struct lxc_list
*it
;
3493 struct id_map
*retmap
= NULL
;
3495 lxc_list_for_each(it
, &conf
->id_map
) {
3497 if (map
->idtype
!= idtype
)
3500 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
3509 retmap
= malloc(sizeof(*retmap
));
3513 memcpy(retmap
, map
, sizeof(*retmap
));
3518 * Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
3519 * existing one or establish a new one.
3521 static struct id_map
*idmap_add(struct lxc_conf
*conf
, uid_t id
, enum idtype type
)
3524 struct id_map
*entry
= NULL
;
3526 /* Reuse existing mapping. */
3527 entry
= mapped_hostid_entry(conf
, id
, type
);
3531 /* Find new mapping. */
3532 hostid_mapped
= find_unmapped_nsid(conf
, type
);
3533 if (hostid_mapped
< 0) {
3534 DEBUG("failed to find free mapping for id %d", id
);
3538 entry
= malloc(sizeof(*entry
));
3542 entry
->idtype
= type
;
3543 entry
->nsid
= hostid_mapped
;
3544 entry
->hostid
= (unsigned long)id
;
3550 /* Run a function in a new user namespace.
3551 * The caller's euid/egid will be mapped if it is not already.
3552 * Afaict, userns_exec_1() is only used to operate based on privileges for the
3553 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
3554 * This means we require only to establish a mapping from:
3555 * - the container root {g,u}id as seen from the host > user's host {g,u}id
3556 * - the container root -> some sub{g,u}id
3557 * The former we add, if the user did not specifiy a mapping. The latter we
3558 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
3559 * there to start the container in the first place.
3561 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
3562 const char *fn_name
)
3566 struct userns_fn_data d
;
3568 struct lxc_list
*it
;
3571 int ret
= -1, status
= -1;
3572 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
3573 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
3574 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
3578 SYSERROR("opening pipe");
3582 d
.fn_name
= fn_name
;
3587 /* Clone child in new user namespace. */
3588 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
3590 ERROR("failed to clone child process in new user namespace");
3600 /* Find container root. */
3601 lxc_list_for_each(it
, &conf
->id_map
) {
3607 if (map
->idtype
== ID_TYPE_UID
&& container_root_uid
== NULL
) {
3608 container_root_uid
= malloc(sizeof(*container_root_uid
));
3609 if (!container_root_uid
)
3611 container_root_uid
->idtype
= map
->idtype
;
3612 container_root_uid
->hostid
= map
->hostid
;
3613 container_root_uid
->nsid
= 0;
3614 container_root_uid
->range
= map
->range
;
3616 /* Check if container root mapping contains a mapping
3619 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
3620 host_uid_map
= container_root_uid
;
3621 } else if (map
->idtype
== ID_TYPE_GID
&& container_root_gid
== NULL
) {
3622 container_root_gid
= malloc(sizeof(*container_root_gid
));
3623 if (!container_root_gid
)
3625 container_root_gid
->idtype
= map
->idtype
;
3626 container_root_gid
->hostid
= map
->hostid
;
3627 container_root_gid
->nsid
= 0;
3628 container_root_gid
->range
= map
->range
;
3630 /* Check if container root mapping contains a mapping
3633 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
3634 host_gid_map
= container_root_gid
;
3637 /* Found container root. */
3638 if (container_root_uid
&& container_root_gid
)
3642 /* This is actually checked earlier but it can't hurt. */
3643 if (!container_root_uid
|| !container_root_gid
) {
3644 ERROR("no mapping for container root found");
3648 /* Check whether the {g,u}id of the user has a mapping. */
3650 host_uid_map
= idmap_add(conf
, euid
, ID_TYPE_UID
);
3653 host_gid_map
= idmap_add(conf
, egid
, ID_TYPE_GID
);
3655 if (!host_uid_map
) {
3656 DEBUG("failed to find mapping for uid %d", euid
);
3660 if (!host_gid_map
) {
3661 DEBUG("failed to find mapping for gid %d", egid
);
3665 /* Allocate new {g,u}id map list. */
3666 idmap
= malloc(sizeof(*idmap
));
3669 lxc_list_init(idmap
);
3671 /* Add container root to the map. */
3672 tmplist
= malloc(sizeof(*tmplist
));
3675 lxc_list_add_elem(tmplist
, container_root_uid
);
3676 lxc_list_add_tail(idmap
, tmplist
);
3678 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
3679 /* idmap will now keep track of that memory. */
3680 container_root_uid
= NULL
;
3682 /* Add container root to the map. */
3683 tmplist
= malloc(sizeof(*tmplist
));
3686 lxc_list_add_elem(tmplist
, host_uid_map
);
3687 lxc_list_add_tail(idmap
, tmplist
);
3689 /* idmap will now keep track of that memory. */
3690 container_root_uid
= NULL
;
3691 /* idmap will now keep track of that memory. */
3692 host_uid_map
= NULL
;
3694 tmplist
= malloc(sizeof(*tmplist
));
3697 lxc_list_add_elem(tmplist
, container_root_gid
);
3698 lxc_list_add_tail(idmap
, tmplist
);
3700 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
3701 /* idmap will now keep track of that memory. */
3702 container_root_gid
= NULL
;
3704 tmplist
= malloc(sizeof(*tmplist
));
3707 lxc_list_add_elem(tmplist
, host_gid_map
);
3708 lxc_list_add_tail(idmap
, tmplist
);
3710 /* idmap will now keep track of that memory. */
3711 container_root_gid
= NULL
;
3712 /* idmap will now keep track of that memory. */
3713 host_gid_map
= NULL
;
3715 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
3716 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
3717 lxc_list_for_each(it
, idmap
) {
3719 TRACE("establishing %cid mapping for \"%d\" in new "
3720 "user namespace: nsuid %lu - hostid %lu - range "
3722 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
3723 map
->nsid
, map
->hostid
, map
->range
);
3727 /* Set up {g,u}id mapping for user namespace of child process. */
3728 ret
= lxc_map_ids(idmap
, pid
);
3730 ERROR("error setting up {g,u}id mappings for child process "
3735 /* Tell child to proceed. */
3736 if (write(p
[1], &c
, 1) != 1) {
3737 SYSERROR("failed telling child process \"%d\" to proceed", pid
);
3742 /* Wait for child to finish. */
3744 status
= wait_for_pid(pid
);
3747 lxc_free_idmap(idmap
);
3748 if (container_root_uid
)
3749 free(container_root_uid
);
3750 if (container_root_gid
)
3751 free(container_root_gid
);
3752 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
3754 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
3767 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
3768 const char *fn_name
)
3772 struct userns_fn_data d
;
3775 struct lxc_list
*cur
;
3778 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
3779 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
3780 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
3784 SYSERROR("opening pipe");
3788 d
.fn_name
= fn_name
;
3793 /* Clone child in new user namespace. */
3794 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
3796 ERROR("failed to clone child process in new user namespace");
3806 /* Allocate new {g,u}id map list. */
3807 idmap
= malloc(sizeof(*idmap
));
3810 lxc_list_init(idmap
);
3812 /* Find container root. */
3813 lxc_list_for_each(cur
, &conf
->id_map
) {
3814 struct id_map
*tmpmap
;
3816 tmplist
= malloc(sizeof(*tmplist
));
3820 tmpmap
= malloc(sizeof(*tmpmap
));
3826 memset(tmpmap
, 0, sizeof(*tmpmap
));
3827 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
3828 tmplist
->elem
= tmpmap
;
3830 lxc_list_add_tail(idmap
, tmplist
);
3834 if (map
->idtype
== ID_TYPE_UID
)
3835 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
3838 if (map
->idtype
== ID_TYPE_GID
)
3839 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
3845 if (map
->idtype
== ID_TYPE_UID
)
3846 if (container_root_uid
== NULL
)
3847 container_root_uid
= map
;
3849 if (map
->idtype
== ID_TYPE_GID
)
3850 if (container_root_gid
== NULL
)
3851 container_root_gid
= map
;
3854 if (!container_root_uid
|| !container_root_gid
) {
3855 ERROR("No mapping for container root found");
3859 /* Check whether the {g,u}id of the user has a mapping. */
3861 host_uid_map
= idmap_add(conf
, euid
, ID_TYPE_UID
);
3863 host_uid_map
= container_root_uid
;
3866 host_gid_map
= idmap_add(conf
, egid
, ID_TYPE_GID
);
3868 host_gid_map
= container_root_gid
;
3870 if (!host_uid_map
) {
3871 DEBUG("Failed to find mapping for uid %d", euid
);
3875 if (!host_gid_map
) {
3876 DEBUG("Failed to find mapping for gid %d", egid
);
3880 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
3881 /* Add container root to the map. */
3882 tmplist
= malloc(sizeof(*tmplist
));
3885 lxc_list_add_elem(tmplist
, host_uid_map
);
3886 lxc_list_add_tail(idmap
, tmplist
);
3888 /* idmap will now keep track of that memory. */
3889 host_uid_map
= NULL
;
3891 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
3892 tmplist
= malloc(sizeof(*tmplist
));
3895 lxc_list_add_elem(tmplist
, host_gid_map
);
3896 lxc_list_add_tail(idmap
, tmplist
);
3898 /* idmap will now keep track of that memory. */
3899 host_gid_map
= NULL
;
3901 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
3902 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
3903 lxc_list_for_each(cur
, idmap
) {
3905 TRACE("establishing %cid mapping for \"%d\" in new "
3906 "user namespace: nsuid %lu - hostid %lu - range "
3908 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
3909 map
->nsid
, map
->hostid
, map
->range
);
3913 /* Set up {g,u}id mapping for user namespace of child process. */
3914 ret
= lxc_map_ids(idmap
, pid
);
3916 ERROR("error setting up {g,u}id mappings for child process "
3921 /* Tell child to proceed. */
3922 if (write(p
[1], &c
, 1) != 1) {
3923 SYSERROR("failed telling child process \"%d\" to proceed", pid
);
3928 /* Wait for child to finish. */
3930 ret
= wait_for_pid(pid
);
3933 lxc_free_idmap(idmap
);
3934 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
3936 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
3946 /* not thread-safe, do not use from api without first forking */
3947 static char* getuname(void)
3949 struct passwd
*result
;
3951 result
= getpwuid(geteuid());
3955 return strdup(result
->pw_name
);
3958 /* not thread-safe, do not use from api without first forking */
3959 static char *getgname(void)
3961 struct group
*result
;
3963 result
= getgrgid(getegid());
3967 return strdup(result
->gr_name
);
3970 /* not thread-safe, do not use from api without first forking */
3971 void suggest_default_idmap(void)
3974 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
3976 char *uname
, *gname
;
3979 if (!(uname
= getuname()))
3982 if (!(gname
= getgname())) {
3987 f
= fopen(subuidfile
, "r");
3989 ERROR("Your system is not configured with subuids");
3994 while (getline(&line
, &len
, f
) != -1) {
3995 size_t no_newline
= 0;
3996 char *p
= strchr(line
, ':'), *p2
;
4003 if (strcmp(line
, uname
))
4005 p2
= strchr(p
, ':');
4012 no_newline
= strcspn(p2
, "\n");
4013 p2
[no_newline
] = '\0';
4015 if (lxc_safe_uint(p
, &uid
) < 0)
4016 WARN("Could not parse UID.");
4017 if (lxc_safe_uint(p2
, &urange
) < 0)
4018 WARN("Could not parse UID range.");
4022 f
= fopen(subgidfile
, "r");
4024 ERROR("Your system is not configured with subgids");
4029 while (getline(&line
, &len
, f
) != -1) {
4030 size_t no_newline
= 0;
4031 char *p
= strchr(line
, ':'), *p2
;
4038 if (strcmp(line
, uname
))
4040 p2
= strchr(p
, ':');
4047 no_newline
= strcspn(p2
, "\n");
4048 p2
[no_newline
] = '\0';
4050 if (lxc_safe_uint(p
, &gid
) < 0)
4051 WARN("Could not parse GID.");
4052 if (lxc_safe_uint(p2
, &grange
) < 0)
4053 WARN("Could not parse GID range.");
4059 if (!urange
|| !grange
) {
4060 ERROR("You do not have subuids or subgids allocated");
4061 ERROR("Unprivileged containers require subuids and subgids");
4065 ERROR("You must either run as root, or define uid mappings");
4066 ERROR("To pass uid mappings to lxc-create, you could create");
4067 ERROR("~/.config/lxc/default.conf:");
4068 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4069 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4070 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4076 static void free_cgroup_settings(struct lxc_list
*result
)
4078 struct lxc_list
*iterator
, *next
;
4080 lxc_list_for_each_safe(iterator
, result
, next
) {
4081 lxc_list_del(iterator
);
4088 * Return the list of cgroup_settings sorted according to the following rules
4089 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4091 struct lxc_list
*sort_cgroup_settings(struct lxc_list
* cgroup_settings
)
4093 struct lxc_list
*result
;
4094 struct lxc_list
*memsw_limit
= NULL
;
4095 struct lxc_list
*it
= NULL
;
4096 struct lxc_cgroup
*cg
= NULL
;
4097 struct lxc_list
*item
= NULL
;
4099 result
= malloc(sizeof(*result
));
4101 ERROR("failed to allocate memory to sort cgroup settings");
4104 lxc_list_init(result
);
4106 /*Iterate over the cgroup settings and copy them to the output list*/
4107 lxc_list_for_each(it
, cgroup_settings
) {
4108 item
= malloc(sizeof(*item
));
4110 ERROR("failed to allocate memory to sort cgroup settings");
4111 free_cgroup_settings(result
);
4114 item
->elem
= it
->elem
;
4116 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4117 /* Store the memsw_limit location */
4119 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 && memsw_limit
!= NULL
) {
4120 /* lxc.cgroup.memory.memsw.limit_in_bytes is found before
4121 * lxc.cgroup.memory.limit_in_bytes, swap these two items */
4122 item
->elem
= memsw_limit
->elem
;
4123 memsw_limit
->elem
= it
->elem
;
4125 lxc_list_add_tail(result
, item
);