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
);
112 #define CAP_SETFCAP 31
115 #ifndef CAP_MAC_OVERRIDE
116 #define CAP_MAC_OVERRIDE 32
119 #ifndef CAP_MAC_ADMIN
120 #define CAP_MAC_ADMIN 33
124 #ifndef PR_CAPBSET_DROP
125 #define PR_CAPBSET_DROP 24
128 #ifndef LO_FLAGS_AUTOCLEAR
129 #define LO_FLAGS_AUTOCLEAR 4
140 /* needed for cgroup automount checks, regardless of whether we
141 * have included linux/capability.h or not */
142 #ifndef CAP_SYS_ADMIN
143 #define CAP_SYS_ADMIN 21
146 /* Define pivot_root() if missing from the C library */
147 #ifndef HAVE_PIVOT_ROOT
148 static int pivot_root(const char * new_root
, const char * put_old
)
150 #ifdef __NR_pivot_root
151 return syscall(__NR_pivot_root
, new_root
, put_old
);
158 extern int pivot_root(const char * new_root
, const char * put_old
);
161 /* Define sethostname() if missing from the C library */
162 #ifndef HAVE_SETHOSTNAME
163 static int sethostname(const char * name
, size_t len
)
165 #ifdef __NR_sethostname
166 return syscall(__NR_sethostname
, name
, len
);
175 #define MS_PRIVATE (1<<18)
179 #define MS_LAZYTIME (1<<25)
182 char *lxchook_names
[NUM_LXC_HOOKS
] = {"pre-start", "pre-mount", "mount",
183 "autodev", "start", "stop",
184 "post-stop", "clone", "destroy",
204 * The lxc_conf of the container currently being worked on in an
206 * This is used in the error calls
209 __thread
struct lxc_conf
*current_config
;
211 struct lxc_conf
*current_config
;
214 static struct mount_opt mount_opt
[] = {
215 { "async", 1, MS_SYNCHRONOUS
},
216 { "atime", 1, MS_NOATIME
},
217 { "bind", 0, MS_BIND
},
218 { "defaults", 0, 0 },
219 { "dev", 1, MS_NODEV
},
220 { "diratime", 1, MS_NODIRATIME
},
221 { "dirsync", 0, MS_DIRSYNC
},
222 { "exec", 1, MS_NOEXEC
},
223 { "lazytime", 0, MS_LAZYTIME
},
224 { "mand", 0, MS_MANDLOCK
},
225 { "noatime", 0, MS_NOATIME
},
226 { "nodev", 0, MS_NODEV
},
227 { "nodiratime", 0, MS_NODIRATIME
},
228 { "noexec", 0, MS_NOEXEC
},
229 { "nomand", 1, MS_MANDLOCK
},
230 { "norelatime", 1, MS_RELATIME
},
231 { "nostrictatime", 1, MS_STRICTATIME
},
232 { "nosuid", 0, MS_NOSUID
},
233 { "rbind", 0, MS_BIND
|MS_REC
},
234 { "relatime", 0, MS_RELATIME
},
235 { "remount", 0, MS_REMOUNT
},
236 { "ro", 0, MS_RDONLY
},
237 { "rw", 1, MS_RDONLY
},
238 { "strictatime", 0, MS_STRICTATIME
},
239 { "suid", 1, MS_NOSUID
},
240 { "sync", 0, MS_SYNCHRONOUS
},
245 static struct caps_opt caps_opt
[] = {
246 { "chown", CAP_CHOWN
},
247 { "dac_override", CAP_DAC_OVERRIDE
},
248 { "dac_read_search", CAP_DAC_READ_SEARCH
},
249 { "fowner", CAP_FOWNER
},
250 { "fsetid", CAP_FSETID
},
251 { "kill", CAP_KILL
},
252 { "setgid", CAP_SETGID
},
253 { "setuid", CAP_SETUID
},
254 { "setpcap", CAP_SETPCAP
},
255 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
256 { "net_bind_service", CAP_NET_BIND_SERVICE
},
257 { "net_broadcast", CAP_NET_BROADCAST
},
258 { "net_admin", CAP_NET_ADMIN
},
259 { "net_raw", CAP_NET_RAW
},
260 { "ipc_lock", CAP_IPC_LOCK
},
261 { "ipc_owner", CAP_IPC_OWNER
},
262 { "sys_module", CAP_SYS_MODULE
},
263 { "sys_rawio", CAP_SYS_RAWIO
},
264 { "sys_chroot", CAP_SYS_CHROOT
},
265 { "sys_ptrace", CAP_SYS_PTRACE
},
266 { "sys_pacct", CAP_SYS_PACCT
},
267 { "sys_admin", CAP_SYS_ADMIN
},
268 { "sys_boot", CAP_SYS_BOOT
},
269 { "sys_nice", CAP_SYS_NICE
},
270 { "sys_resource", CAP_SYS_RESOURCE
},
271 { "sys_time", CAP_SYS_TIME
},
272 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
273 { "mknod", CAP_MKNOD
},
274 { "lease", CAP_LEASE
},
275 #ifdef CAP_AUDIT_READ
276 { "audit_read", CAP_AUDIT_READ
},
278 #ifdef CAP_AUDIT_WRITE
279 { "audit_write", CAP_AUDIT_WRITE
},
281 #ifdef CAP_AUDIT_CONTROL
282 { "audit_control", CAP_AUDIT_CONTROL
},
284 { "setfcap", CAP_SETFCAP
},
285 { "mac_override", CAP_MAC_OVERRIDE
},
286 { "mac_admin", CAP_MAC_ADMIN
},
288 { "syslog", CAP_SYSLOG
},
290 #ifdef CAP_WAKE_ALARM
291 { "wake_alarm", CAP_WAKE_ALARM
},
293 #ifdef CAP_BLOCK_SUSPEND
294 { "block_suspend", CAP_BLOCK_SUSPEND
},
298 static struct caps_opt caps_opt
[] = {};
301 static struct limit_opt limit_opt
[] = {
306 { "core", RLIMIT_CORE
},
309 { "cpu", RLIMIT_CPU
},
312 { "data", RLIMIT_DATA
},
315 { "fsize", RLIMIT_FSIZE
},
318 { "locks", RLIMIT_LOCKS
},
320 #ifdef RLIMIT_MEMLOCK
321 { "memlock", RLIMIT_MEMLOCK
},
323 #ifdef RLIMIT_MSGQUEUE
324 { "msgqueue", RLIMIT_MSGQUEUE
},
327 { "nice", RLIMIT_NICE
},
330 { "nofile", RLIMIT_NOFILE
},
333 { "nproc", RLIMIT_NPROC
},
336 { "rss", RLIMIT_RSS
},
339 { "rtprio", RLIMIT_RTPRIO
},
342 { "rttime", RLIMIT_RTTIME
},
344 #ifdef RLIMIT_SIGPENDING
345 { "sigpending", RLIMIT_SIGPENDING
},
348 { "stack", RLIMIT_STACK
},
352 static int run_buffer(char *buffer
)
354 struct lxc_popen_FILE
*f
;
358 f
= lxc_popen(buffer
);
360 SYSERROR("Failed to popen() %s.", buffer
);
364 output
= malloc(LXC_LOG_BUFFER_SIZE
);
366 ERROR("Failed to allocate memory for %s.", buffer
);
371 while (fgets(output
, LXC_LOG_BUFFER_SIZE
, f
->f
))
372 DEBUG("Script %s with output: %s.", buffer
, output
);
378 SYSERROR("Script exited with error.");
380 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
381 ERROR("Script exited with status %d.", WEXITSTATUS(ret
));
383 } else if (WIFSIGNALED(ret
)) {
384 ERROR("Script terminated by signal %d.", WTERMSIG(ret
));
391 static int run_script_argv(const char *name
, const char *section
,
392 const char *script
, const char *hook
,
393 const char *lxcpath
, char **argsin
)
399 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
400 script
, name
, section
);
402 for (i
= 0; argsin
&& argsin
[i
]; i
++)
403 size
+= strlen(argsin
[i
]) + 1;
405 size
+= strlen(hook
) + 1;
407 size
+= strlen(script
);
408 size
+= strlen(name
);
409 size
+= strlen(section
);
415 buffer
= alloca(size
);
417 ERROR("Failed to allocate memory.");
422 snprintf(buffer
, size
, "%s %s %s %s", script
, name
, section
, hook
);
423 if (ret
< 0 || (size_t)ret
>= size
) {
424 ERROR("Script name too long.");
428 for (i
= 0; argsin
&& argsin
[i
]; i
++) {
429 int len
= size
- ret
;
431 rc
= snprintf(buffer
+ ret
, len
, " %s", argsin
[i
]);
432 if (rc
< 0 || rc
>= len
) {
433 ERROR("Script args too long.");
439 return run_buffer(buffer
);
442 int run_script(const char *name
, const char *section
, const char *script
, ...)
449 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
450 script
, name
, section
);
452 va_start(ap
, script
);
453 while ((p
= va_arg(ap
, char *)))
454 size
+= strlen(p
) + 1;
457 size
+= strlen(script
);
458 size
+= strlen(name
);
459 size
+= strlen(section
);
465 buffer
= alloca(size
);
467 ERROR("Failed to allocate memory.");
471 ret
= snprintf(buffer
, size
, "%s %s %s", script
, name
, section
);
472 if (ret
< 0 || ret
>= size
) {
473 ERROR("Script name too long.");
477 va_start(ap
, script
);
478 while ((p
= va_arg(ap
, char *))) {
479 int len
= size
- ret
;
481 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
482 if (rc
< 0 || rc
>= len
) {
483 ERROR("Script args too long.");
490 return run_buffer(buffer
);
495 * if rootfs is a directory, then open ${rootfs}/lxc.hold for writing for
496 * the duration of the container run, to prevent the container from marking
497 * the underlying fs readonly on shutdown. unlink the file immediately so
498 * no name pollution is happens
499 * return -1 on error.
500 * return -2 if nothing needed to be pinned.
501 * return an open fd (>=0) if we pinned it.
503 int pin_rootfs(const char *rootfs
)
505 char absrootfs
[MAXPATHLEN
];
506 char absrootfspin
[MAXPATHLEN
];
510 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
513 if (!realpath(rootfs
, absrootfs
))
516 if (access(absrootfs
, F_OK
))
519 if (stat(absrootfs
, &s
))
522 if (!S_ISDIR(s
.st_mode
))
525 ret
= snprintf(absrootfspin
, MAXPATHLEN
, "%s/lxc.hold", absrootfs
);
526 if (ret
>= MAXPATHLEN
)
529 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
|S_IRUSR
);
532 (void)unlink(absrootfspin
);
537 * If we are asking to remount something, make sure that any
538 * NOEXEC etc are honored.
540 unsigned long add_required_remount_flags(const char *s
, const char *d
,
545 unsigned long required_flags
= 0;
547 if (!(flags
& MS_REMOUNT
))
555 if (statvfs(s
, &sb
) < 0)
558 if (sb
.f_flag
& MS_NOSUID
)
559 required_flags
|= MS_NOSUID
;
560 if (sb
.f_flag
& MS_NODEV
)
561 required_flags
|= MS_NODEV
;
562 if (sb
.f_flag
& MS_RDONLY
)
563 required_flags
|= MS_RDONLY
;
564 if (sb
.f_flag
& MS_NOEXEC
)
565 required_flags
|= MS_NOEXEC
;
567 return flags
| required_flags
;
573 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
581 const char *destination
;
585 } default_mounts
[] = {
586 /* Read-only bind-mounting... In older kernels, doing that required
587 * to do one MS_BIND mount and then MS_REMOUNT|MS_RDONLY the same
588 * one. According to mount(2) manpage, MS_BIND honors MS_RDONLY from
589 * kernel 2.6.26 onwards. However, this apparently does not work on
590 * kernel 3.8. Unfortunately, on that very same kernel, doing the
591 * same trick as above doesn't seem to work either, there one needs
592 * to ALSO specify MS_BIND for the remount, otherwise the entire
593 * fs is remounted read-only or the mount fails because it's busy...
594 * MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for kernels as low as
597 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
598 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
599 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
600 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
601 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
602 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
603 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
604 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
605 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
606 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
607 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
608 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
609 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
610 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
611 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
612 { 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
},
613 { 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
},
614 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
617 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
618 if ((flags
& default_mounts
[i
].match_mask
) == default_mounts
[i
].match_flag
) {
620 char *destination
= NULL
;
622 unsigned long mflags
;
624 if (default_mounts
[i
].source
) {
625 /* will act like strdup if %r is not present */
626 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
628 SYSERROR("memory allocation error");
632 if (!default_mounts
[i
].destination
) {
633 ERROR("BUG: auto mounts destination %d was NULL", i
);
637 /* will act like strdup if %r is not present */
638 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
641 SYSERROR("memory allocation error");
646 mflags
= add_required_remount_flags(source
, destination
,
647 default_mounts
[i
].flags
);
648 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
, mflags
, default_mounts
[i
].options
, conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
650 if (r
< 0 && errno
== ENOENT
) {
651 INFO("Mount source or target for %s on %s doesn't exist. Skipping.", source
, destination
);
655 SYSERROR("error mounting %s on %s flags %lu", source
, destination
, mflags
);
666 if (flags
& LXC_AUTO_CGROUP_MASK
) {
669 cg_flags
= flags
& LXC_AUTO_CGROUP_MASK
;
670 /* If the type of cgroup mount was not specified, it depends on the
671 * container's capabilities as to what makes sense: if we have
672 * CAP_SYS_ADMIN, the read-only part can be remounted read-write
673 * anyway, so we may as well default to read-write; then the admin
674 * will not be given a false sense of security. (And if they really
675 * want mixed r/o r/w, then they can explicitly specify :mixed.)
676 * OTOH, if the container lacks CAP_SYS_ADMIN, do only default to
677 * :mixed, because then the container can't remount it read-write. */
678 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
679 int has_sys_admin
= 0;
681 if (!lxc_list_empty(&conf
->keepcaps
))
682 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
684 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
686 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
687 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
689 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
692 if (!cgroup_mount(conf
->rootfs
.path
? conf
->rootfs
.mount
: "", handler
, cg_flags
)) {
693 SYSERROR("error mounting /sys/fs/cgroup");
701 static int setup_utsname(struct utsname
*utsname
)
706 if (sethostname(utsname
->nodename
, strlen(utsname
->nodename
))) {
707 SYSERROR("failed to set the hostname to '%s'", utsname
->nodename
);
711 INFO("'%s' hostname has been setup", utsname
->nodename
);
716 struct dev_symlinks
{
721 static const struct dev_symlinks dev_symlinks
[] = {
722 {"/proc/self/fd", "fd"},
723 {"/proc/self/fd/0", "stdin"},
724 {"/proc/self/fd/1", "stdout"},
725 {"/proc/self/fd/2", "stderr"},
728 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
730 char path
[MAXPATHLEN
];
735 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
736 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
737 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs
->path
? rootfs
->mount
: "", d
->name
);
738 if (ret
< 0 || ret
>= MAXPATHLEN
)
742 * Stat the path first. If we don't get an error
743 * accept it as is and don't try to create it
745 if (!stat(path
, &s
)) {
749 ret
= symlink(d
->oldpath
, path
);
751 if (ret
&& errno
!= EEXIST
) {
752 if ( errno
== EROFS
) {
753 WARN("Warning: Read Only file system while creating %s", path
);
755 SYSERROR("Error creating %s", path
);
763 /* Build a space-separate list of ptys to pass to systemd. */
764 static bool append_ptyname(char **pp
, char *name
)
769 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
772 sprintf(*pp
, "container_ttys=%s", name
);
775 p
= realloc(*pp
, strlen(*pp
) + strlen(name
) + 2);
784 static int lxc_setup_ttys(struct lxc_conf
*conf
)
787 const struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
788 char *ttydir
= conf
->ttydir
;
789 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
791 if (!conf
->rootfs
.path
)
794 for (i
= 0; i
< tty_info
->nbtty
; i
++) {
795 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
797 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
798 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
802 /* create dev/lxc/tty%d" */
803 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
804 "/dev/%s/tty%d", ttydir
, i
+ 1);
805 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
808 ret
= creat(lxcpath
, 0660);
809 if (ret
< 0 && errno
!= EEXIST
) {
810 SYSERROR("Failed to create \"%s\"", lxcpath
);
817 if (ret
< 0 && errno
!= ENOENT
) {
818 SYSERROR("Failed to unlink \"%s\"", path
);
822 ret
= mount(pty_info
->name
, lxcpath
, "none", MS_BIND
, 0);
824 WARN("Failed to bind mount \"%s\" onto \"%s\"",
825 pty_info
->name
, path
);
828 DEBUG("bind mounted \"%s\" onto \"%s\"", pty_info
->name
,
831 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
833 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
836 ret
= symlink(lxcpath
, path
);
838 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
843 /* If we populated /dev, then we need to create
846 ret
= access(path
, F_OK
);
848 ret
= creat(path
, 0660);
850 SYSERROR("Failed to create \"%s\"", path
);
851 /* this isn't fatal, continue */
857 ret
= mount(pty_info
->name
, path
, "none", MS_BIND
, 0);
859 SYSERROR("Failed to mount '%s'->'%s'", pty_info
->name
, path
);
863 DEBUG("Bind mounted \"%s\" onto \"%s\"", pty_info
->name
,
867 if (!append_ptyname(&conf
->pty_names
, pty_info
->name
)) {
868 ERROR("Error setting up container_ttys string");
873 INFO("Finished setting up %d /dev/tty<N> device(s)", tty_info
->nbtty
);
877 int lxc_allocate_ttys(const char *name
, struct lxc_conf
*conf
)
879 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
882 /* no tty in the configuration */
886 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
) * conf
->tty
);
887 if (!tty_info
->pty_info
) {
888 SYSERROR("failed to allocate struct *pty_info");
892 for (i
= 0; i
< conf
->tty
; i
++) {
893 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
896 ret
= openpty(&pty_info
->master
, &pty_info
->slave
,
897 pty_info
->name
, NULL
, NULL
);
900 SYSERROR("failed to create pty device number %d", i
);
902 lxc_delete_tty(tty_info
);
906 DEBUG("allocated pty \"%s\" with master fd %d and slave fd %d",
907 pty_info
->name
, pty_info
->master
, pty_info
->slave
);
909 /* Prevent leaking the file descriptors to the container */
910 ret
= fcntl(pty_info
->master
, F_SETFD
, FD_CLOEXEC
);
912 WARN("failed to set FD_CLOEXEC flag on master fd %d of "
913 "pty device \"%s\": %s",
914 pty_info
->master
, pty_info
->name
, strerror(errno
));
916 ret
= fcntl(pty_info
->slave
, F_SETFD
, FD_CLOEXEC
);
918 WARN("failed to set FD_CLOEXEC flag on slave fd %d of "
919 "pty device \"%s\": %s",
920 pty_info
->slave
, pty_info
->name
, strerror(errno
));
925 tty_info
->nbtty
= conf
->tty
;
927 INFO("finished allocating %d pts devices", conf
->tty
);
931 void lxc_delete_tty(struct lxc_tty_info
*tty_info
)
935 for (i
= 0; i
< tty_info
->nbtty
; i
++) {
936 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
938 close(pty_info
->master
);
939 close(pty_info
->slave
);
942 free(tty_info
->pty_info
);
943 tty_info
->pty_info
= NULL
;
947 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
950 struct lxc_conf
*conf
= handler
->conf
;
951 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
952 int sock
= handler
->data_sock
[0];
958 for (i
= 0; i
< conf
->tty
; i
++) {
960 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
962 ttyfds
[0] = pty_info
->master
;
963 ttyfds
[1] = pty_info
->slave
;
965 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
969 TRACE("Send pty \"%s\" with master fd %d and slave fd %d to "
970 "parent", pty_info
->name
, pty_info
->master
, pty_info
->slave
);
974 ERROR("Failed to send %d ttys to parent: %s", conf
->tty
,
977 TRACE("Sent %d ttys to parent", conf
->tty
);
982 static int lxc_create_ttys(struct lxc_handler
*handler
)
985 struct lxc_conf
*conf
= handler
->conf
;
987 ret
= lxc_allocate_ttys(handler
->name
, conf
);
989 ERROR("Failed to allocate ttys");
993 ret
= lxc_send_ttys_to_parent(handler
);
995 ERROR("Failed to send ttys to parent");
999 if (!conf
->is_execute
) {
1000 ret
= lxc_setup_ttys(conf
);
1002 ERROR("Failed to setup ttys");
1007 if (conf
->pty_names
) {
1008 ret
= setenv("container_ttys", conf
->pty_names
, 1);
1010 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->pty_names
);
1016 lxc_delete_tty(&conf
->tty_info
);
1021 static int setup_rootfs_pivot_root(const char *rootfs
)
1023 int oldroot
= -1, newroot
= -1;
1025 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
1027 SYSERROR("Error opening old-/ for fchdir");
1030 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
);
1032 SYSERROR("Error opening new-/ for fchdir");
1036 /* change into new root fs */
1037 if (fchdir(newroot
)) {
1038 SYSERROR("can't chdir to new rootfs '%s'", rootfs
);
1042 /* pivot_root into our new root fs */
1043 if (pivot_root(".", ".")) {
1044 SYSERROR("pivot_root syscall failed");
1049 * at this point the old-root is mounted on top of our new-root
1050 * To unmounted it we must not be chdir'd into it, so escape back
1053 if (fchdir(oldroot
) < 0) {
1054 SYSERROR("Error entering oldroot");
1057 if (umount2(".", MNT_DETACH
) < 0) {
1058 SYSERROR("Error detaching old root");
1062 if (fchdir(newroot
) < 0) {
1063 SYSERROR("Error re-entering newroot");
1070 DEBUG("pivot_root syscall to '%s' successful", rootfs
);
1082 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1083 * error, log it but don't fail yet.
1085 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1086 const char *lxcpath
)
1092 INFO("Preparing \"/dev\"");
1094 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1095 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1096 path
= alloca(clen
);
1098 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1099 if (ret
< 0 || (size_t)ret
>= clen
)
1102 if (!dir_exists(path
)) {
1103 WARN("\"/dev\" directory does not exist. Proceeding without "
1104 "autodev being set up");
1108 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1109 rootfs
->path
? rootfs
->mount
: NULL
);
1111 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1114 INFO("Mounted tmpfs on \"%s\"", path
);
1116 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1117 if (ret
< 0 || (size_t)ret
>= clen
)
1120 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1121 * If not, then create it and exit if that fails...
1123 if (!dir_exists(path
)) {
1124 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1126 SYSERROR("Failed to create directory \"%s\"", path
);
1131 INFO("Prepared \"/dev\"");
1142 static const struct lxc_devs lxc_devs
[] = {
1143 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1144 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1145 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1146 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1147 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1148 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1151 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1154 char path
[MAXPATHLEN
];
1158 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev",
1159 rootfs
->path
? rootfs
->mount
: "");
1160 if (ret
< 0 || ret
>= MAXPATHLEN
)
1163 /* ignore, just don't try to fill in */
1164 if (!dir_exists(path
))
1167 INFO("Populating \"/dev\"");
1169 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1170 for (i
= 0; i
< sizeof(lxc_devs
) / sizeof(lxc_devs
[0]); i
++) {
1171 const struct lxc_devs
*d
= &lxc_devs
[i
];
1173 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev/%s",
1174 rootfs
->path
? rootfs
->mount
: "", d
->name
);
1175 if (ret
< 0 || ret
>= MAXPATHLEN
)
1178 ret
= mknod(path
, d
->mode
, makedev(d
->maj
, d
->min
));
1181 char hostpath
[MAXPATHLEN
];
1183 if (errno
== EEXIST
) {
1184 DEBUG("\"%s\" device already existed", path
);
1188 /* Unprivileged containers cannot create devices, so
1189 * bind mount the device from the host.
1191 ret
= snprintf(hostpath
, MAXPATHLEN
, "/dev/%s", d
->name
);
1192 if (ret
< 0 || ret
>= MAXPATHLEN
)
1195 pathfile
= fopen(path
, "wb");
1197 SYSERROR("Failed to create file \"%s\"", path
);
1202 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1203 rootfs
->path
? rootfs
->mount
: NULL
);
1205 SYSERROR("Failed to bind mount \"%s\" from "
1206 "host into container",
1210 DEBUG("Bind mounted \"%s\" onto \"%s\"", hostpath
,
1213 DEBUG("Created device node \"%s\"", path
);
1218 INFO("Populated \"/dev\"");
1222 static int lxc_setup_rootfs(struct lxc_conf
*conf
)
1225 struct lxc_storage
*bdev
;
1226 const struct lxc_rootfs
*rootfs
;
1228 rootfs
= &conf
->rootfs
;
1229 if (!rootfs
->path
) {
1230 if (mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0)) {
1231 SYSERROR("Failed to make / rslave.");
1237 if (access(rootfs
->mount
, F_OK
)) {
1238 SYSERROR("Failed to access to \"%s\". Check it is present.",
1243 bdev
= storage_init(conf
, rootfs
->path
, rootfs
->mount
, rootfs
->options
);
1245 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1246 rootfs
->path
, rootfs
->mount
,
1247 rootfs
->options
? rootfs
->options
: "(null)");
1251 ret
= bdev
->ops
->mount(bdev
);
1254 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1255 rootfs
->path
, rootfs
->mount
,
1256 rootfs
->options
? rootfs
->options
: "(null)");
1260 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\".",
1261 rootfs
->path
, rootfs
->mount
,
1262 rootfs
->options
? rootfs
->options
: "(null)");
1267 int prepare_ramfs_root(char *root
)
1269 char buf
[LXC_LINELEN
], *p
;
1270 char nroot
[PATH_MAX
];
1275 if (realpath(root
, nroot
) == NULL
)
1278 if (chdir("/") == -1)
1282 * We could use here MS_MOVE, but in userns this mount is
1283 * locked and can't be moved.
1285 if (mount(root
, "/", NULL
, MS_REC
| MS_BIND
, NULL
) < 0) {
1286 SYSERROR("Failed to move %s into /", root
);
1290 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
) < 0) {
1291 SYSERROR("Failed to make . rprivate");
1296 * The following code cleans up inhereted mounts which are not
1299 * The mountinfo file shows not all mounts, if a few points have been
1300 * unmounted between read operations from the mountinfo. So we need to
1301 * read mountinfo a few times.
1303 * This loop can be skipped if a container uses unserns, because all
1304 * inherited mounts are locked and we should live with all this trash.
1309 f
= fopen("./proc/self/mountinfo", "r");
1311 SYSERROR("Unable to open /proc/self/mountinfo");
1314 while (fgets(buf
, LXC_LINELEN
, f
)) {
1315 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1316 p
= strchr(p
+1, ' ');
1319 p2
= strchr(p
+1, ' ');
1326 if (strcmp(p
+ 1, "/") == 0)
1328 if (strcmp(p
+ 1, "/proc") == 0)
1331 if (umount2(p
, MNT_DETACH
) == 0)
1339 /* This also can be skipped if a container uses unserns */
1340 umount2("./proc", MNT_DETACH
);
1342 /* It is weird, but chdir("..") moves us in a new root */
1343 if (chdir("..") == -1) {
1344 SYSERROR("Unable to change working directory");
1348 if (chroot(".") == -1) {
1349 SYSERROR("Unable to chroot");
1356 static int setup_pivot_root(const struct lxc_rootfs
*rootfs
)
1358 if (!rootfs
->path
) {
1359 DEBUG("container does not have a rootfs, so not doing pivot root");
1363 if (detect_ramfs_rootfs()) {
1364 DEBUG("detected that container is on ramfs");
1365 if (prepare_ramfs_root(rootfs
->mount
)) {
1366 ERROR("failed to prepare minimal ramfs root");
1370 DEBUG("prepared ramfs root for container");
1374 if (setup_rootfs_pivot_root(rootfs
->mount
) < 0) {
1375 ERROR("failed to pivot root");
1379 DEBUG("finished pivot root");
1383 static int lxc_setup_devpts(int num_pts
)
1386 const char *default_devpts_mntopts
= "newinstance,ptmxmode=0666,mode=0620,gid=5";
1387 char devpts_mntopts
[256];
1390 DEBUG("no new devpts instance will be mounted since no pts "
1391 "devices are requested");
1395 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%d",
1396 default_devpts_mntopts
, num_pts
);
1397 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1400 /* Unmount old devpts instance. */
1401 ret
= access("/dev/pts/ptmx", F_OK
);
1403 ret
= umount("/dev/pts");
1405 SYSERROR("failed to unmount old devpts instance");
1408 DEBUG("unmounted old /dev/pts instance");
1411 /* Create mountpoint for devpts instance. */
1412 ret
= mkdir("/dev/pts", 0755);
1413 if (ret
< 0 && errno
!= EEXIST
) {
1414 SYSERROR("failed to create the \"/dev/pts\" directory");
1418 /* Mount new devpts instance. */
1419 ret
= mount("devpts", "/dev/pts", "devpts", MS_MGC_VAL
, devpts_mntopts
);
1421 SYSERROR("failed to mount new devpts instance");
1424 DEBUG("mount new devpts instance with options \"%s\"", devpts_mntopts
);
1426 /* Remove any pre-existing /dev/ptmx file. */
1427 ret
= access("/dev/ptmx", F_OK
);
1429 ret
= remove("/dev/ptmx");
1431 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1434 DEBUG("removed existing \"/dev/ptmx\"");
1437 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1438 ret
= open("/dev/ptmx", O_CREAT
, 0666);
1440 SYSERROR("failed to create dummy \"/dev/ptmx\" file as bind mount target");
1444 DEBUG("created dummy \"/dev/ptmx\" file as bind mount target");
1446 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1447 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1449 DEBUG("bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1452 /* Fallthrough and try to create a symlink. */
1453 ERROR("failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1456 /* Remove the dummy /dev/ptmx file we created above. */
1457 ret
= remove("/dev/ptmx");
1459 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1463 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1464 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1466 SYSERROR("failed to create symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1469 DEBUG("created symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1474 static int setup_personality(int persona
)
1476 #if HAVE_SYS_PERSONALITY_H
1480 if (personality(persona
) < 0) {
1481 SYSERROR("failed to set personality to '0x%x'", persona
);
1485 INFO("set personality to '0x%x'", persona
);
1491 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1492 const struct lxc_console
*console
)
1494 char path
[MAXPATHLEN
];
1497 if (console
->path
&& !strcmp(console
->path
, "none"))
1500 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs
->mount
);
1501 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1504 /* When we are asked to setup a console we remove any previous
1505 * /dev/console bind-mounts.
1507 if (file_exists(path
)) {
1508 ret
= lxc_unstack_mountpoint(path
, false);
1510 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1513 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1518 SYSERROR("error unlinking %s", path
);
1523 /* For unprivileged containers autodev or automounts will already have
1524 * taken care of creating /dev/console.
1526 fd
= open(path
, O_CREAT
| O_EXCL
, S_IXUSR
| S_IXGRP
| S_IXOTH
);
1528 if (errno
!= EEXIST
) {
1529 SYSERROR("failed to create console");
1536 if (chmod(console
->name
, S_IXUSR
| S_IXGRP
| S_IXOTH
)) {
1537 SYSERROR("failed to set mode '0%o' to '%s'", S_IXUSR
| S_IXGRP
| S_IXOTH
, console
->name
);
1541 if (safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs
->mount
) < 0) {
1542 ERROR("failed to mount '%s' on '%s'", console
->name
, path
);
1546 DEBUG("mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1550 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1551 const struct lxc_console
*console
,
1555 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
1557 /* create rootfs/dev/<ttydir> directory */
1558 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs
->mount
, ttydir
);
1559 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1562 ret
= mkdir(path
, 0755);
1563 if (ret
&& errno
!= EEXIST
) {
1564 SYSERROR("failed with errno %d to create %s", errno
, path
);
1567 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1569 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs
->mount
, ttydir
);
1570 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1573 ret
= creat(lxcpath
, 0660);
1574 if (ret
== -1 && errno
!= EEXIST
) {
1575 SYSERROR("error %d creating %s", errno
, lxcpath
);
1581 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs
->mount
);
1582 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1585 /* When we are asked to setup a console we remove any previous
1586 * /dev/console bind-mounts.
1588 if (console
->path
&& !strcmp(console
->path
, "none")) {
1590 ret
= stat(path
, &st
);
1592 if (errno
== ENOENT
)
1594 SYSERROR("failed stat() \"%s\"", path
);
1598 /* /dev/console must be character device with major number 5 and
1599 * minor number 1. If not, give benefit of the doubt and assume
1600 * the user has mounted something else right there on purpose.
1602 if (((st
.st_mode
& S_IFMT
) != S_IFCHR
) || major(st
.st_rdev
) != 5 || minor(st
.st_rdev
) != 1)
1605 /* In case the user requested a bind-mount for /dev/console and
1606 * requests a ttydir we move the mount to the
1607 * /dev/<ttydir/console.
1608 * Note, we only move the uppermost mount and clear all other
1609 * mounts underneath for safety.
1610 * If it is a character device created via mknod() we simply
1613 ret
= safe_mount(path
, lxcpath
, "none", MS_MOVE
, NULL
, rootfs
->mount
);
1615 if (errno
!= EINVAL
) {
1616 ERROR("failed to MS_MOVE \"%s\" to \"%s\": %s", path
, lxcpath
, strerror(errno
));
1619 /* path was not a mountpoint */
1620 ret
= rename(path
, lxcpath
);
1622 ERROR("failed to rename \"%s\" to \"%s\": %s", path
, lxcpath
, strerror(errno
));
1625 DEBUG("renamed \"%s\" to \"%s\"", path
, lxcpath
);
1627 DEBUG("moved mount \"%s\" to \"%s\"", path
, lxcpath
);
1630 /* Clear all remaining bind-mounts. */
1631 ret
= lxc_unstack_mountpoint(path
, false);
1633 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1636 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1639 if (file_exists(path
)) {
1640 ret
= lxc_unstack_mountpoint(path
, false);
1642 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1645 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1649 if (safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs
->mount
) < 0) {
1650 ERROR("failed to mount '%s' on '%s'", console
->name
, lxcpath
);
1653 DEBUG("mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1656 /* create symlink from rootfs /dev/console to '<ttydir>/console' */
1657 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/console", ttydir
);
1658 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1662 if (ret
&& errno
!= ENOENT
) {
1663 SYSERROR("error unlinking %s", path
);
1667 ret
= symlink(lxcpath
, path
);
1669 SYSERROR("failed to create symlink for console from \"%s\" to \"%s\"", lxcpath
, path
);
1673 DEBUG("console has been setup under \"%s\" and symlinked to \"%s\"", lxcpath
, path
);
1677 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1678 const struct lxc_console
*console
, char *ttydir
)
1680 /* We don't have a rootfs, /dev/console will be shared. */
1681 if (!rootfs
->path
) {
1682 DEBUG("/dev/console will be shared with the host");
1687 return lxc_setup_dev_console(rootfs
, console
);
1689 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1692 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
)
1694 struct mount_opt
*mo
;
1696 /* If opt is found in mount_opt, set or clear flags.
1697 * Otherwise append it to data. */
1699 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1700 if (!strncmp(opt
, mo
->name
, strlen(mo
->name
))) {
1702 *flags
&= ~mo
->flag
;
1714 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
,
1718 char *p
, *saveptr
= NULL
;
1726 s
= strdup(mntopts
);
1728 SYSERROR("failed to allocate memory");
1732 data
= malloc(strlen(s
) + 1);
1734 SYSERROR("failed to allocate memory");
1740 for (p
= strtok_r(s
, ",", &saveptr
); p
!= NULL
;
1741 p
= strtok_r(NULL
, ",", &saveptr
))
1742 parse_mntopt(p
, mntflags
, &data
);
1753 static void null_endofword(char *word
)
1755 while (*word
&& *word
!= ' ' && *word
!= '\t')
1761 * skip @nfields spaces in @src
1763 static char *get_field(char *src
, int nfields
)
1768 for (i
= 0; i
< nfields
; i
++) {
1769 while (*p
&& *p
!= ' ' && *p
!= '\t')
1778 static int mount_entry(const char *fsname
, const char *target
,
1779 const char *fstype
, unsigned long mountflags
,
1780 const char *data
, int optional
, int dev
,
1788 ret
= safe_mount(fsname
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
1792 INFO("Failed to mount \"%s\" on \"%s\" (optional): %s",
1793 fsname
, target
, strerror(errno
));
1797 SYSERROR("Failed to mount \"%s\" on \"%s\"", fsname
, target
);
1801 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
1802 unsigned long rqd_flags
= 0;
1804 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
1806 fsname
? fsname
: "(none)", target
? target
: "(none)");
1808 if (mountflags
& MS_RDONLY
)
1809 rqd_flags
|= MS_RDONLY
;
1811 if (statvfs(fsname
, &sb
) == 0) {
1812 unsigned long required_flags
= rqd_flags
;
1814 if (sb
.f_flag
& MS_NOSUID
)
1815 required_flags
|= MS_NOSUID
;
1817 if (sb
.f_flag
& MS_NODEV
&& !dev
)
1818 required_flags
|= MS_NODEV
;
1820 if (sb
.f_flag
& MS_RDONLY
)
1821 required_flags
|= MS_RDONLY
;
1823 if (sb
.f_flag
& MS_NOEXEC
)
1824 required_flags
|= MS_NOEXEC
;
1826 DEBUG("Flags for \"%s\" were %lu, required extra flags "
1827 "are %lu", fsname
, sb
.f_flag
, required_flags
);
1829 /* If this was a bind mount request, and required_flags
1830 * does not have any flags which are not already in
1831 * mountflags, then skip the remount.
1833 if (!(mountflags
& MS_REMOUNT
)) {
1834 if (!(required_flags
& ~mountflags
) &&
1836 DEBUG("Mountflags already were %lu, "
1837 "skipping remount", mountflags
);
1842 mountflags
|= required_flags
;
1846 ret
= mount(fsname
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
1849 INFO("Failed to mount \"%s\" on \"%s\" "
1850 "(optional): %s", fsname
, target
,
1855 SYSERROR("Failed to mount \"%s\" on \"%s\"", fsname
, target
);
1863 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"", fsname
,
1869 /* Remove "optional", "create=dir", and "create=file" from mntopt */
1870 static void cull_mntent_opt(struct mntent
*mntent
)
1873 char *list
[] = {"create=dir", "create=file", "optional", NULL
};
1875 for (i
= 0; list
[i
]; i
++) {
1878 p
= strstr(mntent
->mnt_opts
, list
[i
]);
1882 p2
= strchr(p
, ',');
1884 /* no more mntopts, so just chop it here */
1889 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
1893 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
1895 const struct lxc_rootfs
*rootfs
,
1896 const char *lxc_name
,
1897 const char *lxc_path
)
1901 if (!strncmp(mntent
->mnt_type
, "overlay", 7))
1902 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
1903 else if (!strncmp(mntent
->mnt_type
, "aufs", 4))
1904 ret
= aufs_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
1908 if (hasmntopt(mntent
, "create=dir")) {
1909 ret
= mkdir_p(path
, 0755);
1910 if (ret
< 0 && errno
!= EEXIST
) {
1911 SYSERROR("Failed to create directory \"%s\"", path
);
1916 if (hasmntopt(mntent
, "create=file") && access(path
, F_OK
)) {
1926 ret
= mkdir_p(p2
, 0755);
1928 if (ret
< 0 && errno
!= EEXIST
) {
1929 SYSERROR("Failed to create directory \"%s\"", path
);
1933 fd
= open(path
, O_CREAT
, 0644);
1942 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
1943 * without a rootfs. */
1944 static inline int mount_entry_on_generic(struct mntent
*mntent
,
1946 const struct lxc_rootfs
*rootfs
,
1947 const char *lxc_name
,
1948 const char *lxc_path
)
1951 unsigned long mntflags
;
1954 char *rootfs_path
= NULL
;
1956 optional
= hasmntopt(mntent
, "optional") != NULL
;
1957 dev
= hasmntopt(mntent
, "dev") != NULL
;
1959 if (rootfs
&& rootfs
->path
)
1960 rootfs_path
= rootfs
->mount
;
1962 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
1970 cull_mntent_opt(mntent
);
1972 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
1976 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
1977 mntdata
, optional
, dev
, rootfs_path
);
1983 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
1986 char path
[MAXPATHLEN
];
1988 /* For containers created without a rootfs all mounts are treated as
1989 * absolute paths starting at / on the host.
1991 if (mntent
->mnt_dir
[0] != '/')
1992 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
1994 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
1995 if (ret
< 0 || ret
>= sizeof(path
))
1998 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2001 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2002 const struct lxc_rootfs
*rootfs
,
2003 const char *lxc_name
,
2004 const char *lxc_path
)
2008 const char *lxcpath
;
2009 char path
[MAXPATHLEN
];
2012 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2016 /* If rootfs->path is a blockdev path, allow container fstab to use
2017 * <lxcpath>/<name>/rootfs" as the target prefix.
2019 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2020 if (ret
< 0 || ret
>= MAXPATHLEN
)
2023 aux
= strstr(mntent
->mnt_dir
, path
);
2025 offset
= strlen(path
);
2030 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2032 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2035 offset
= strlen(rootfs
->path
);
2038 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2039 if (ret
< 0 || ret
>= MAXPATHLEN
)
2042 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2045 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2046 const struct lxc_rootfs
*rootfs
,
2047 const char *lxc_name
,
2048 const char *lxc_path
)
2050 char path
[MAXPATHLEN
];
2053 /* relative to root mount point */
2054 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2055 if (ret
< 0 || ret
>= sizeof(path
)) {
2056 ERROR("path name too long");
2060 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2063 /* This logs a NOTICE() when a user specifies mounts that would conflict with
2064 * devices liblxc sets up automatically.
2066 static void log_notice_on_conflict(const struct lxc_conf
*conf
, const char *src
,
2069 char *clean_mnt_fsname
, *clean_mnt_dir
, *tmp
;
2070 bool needs_warning
= false;
2072 clean_mnt_fsname
= lxc_deslashify(src
);
2073 if (!clean_mnt_fsname
)
2076 clean_mnt_dir
= lxc_deslashify(dest
);
2077 if (!clean_mnt_dir
) {
2078 free(clean_mnt_fsname
);
2082 tmp
= clean_mnt_dir
;
2086 if (strncmp(src
, "/dev", 4) || strncmp(tmp
, "dev", 3)) {
2087 free(clean_mnt_dir
);
2088 free(clean_mnt_fsname
);
2092 if (!conf
->autodev
&& !conf
->pts
&& !conf
->tty
&&
2093 (!conf
->console
.path
|| !strcmp(conf
->console
.path
, "none"))) {
2094 free(clean_mnt_dir
);
2095 free(clean_mnt_fsname
);
2099 if (!strcmp(tmp
, "dev") && conf
->autodev
> 0)
2100 needs_warning
= true;
2101 else if (!strcmp(tmp
, "dev/pts") && (conf
->autodev
> 0 || conf
->pts
> 0))
2102 needs_warning
= true;
2103 else if (!strcmp(tmp
, "dev/ptmx") && (conf
->autodev
> 0 || conf
->pts
> 0))
2104 needs_warning
= true;
2105 else if (!strcmp(tmp
, "dev/pts/ptmx") && (conf
->autodev
> 0 || conf
->pts
> 0))
2106 needs_warning
= true;
2107 else if (!strcmp(tmp
, "dev/null") && conf
->autodev
> 0)
2108 needs_warning
= true;
2109 else if (!strcmp(tmp
, "dev/zero") && conf
->autodev
> 0)
2110 needs_warning
= true;
2111 else if (!strcmp(tmp
, "dev/full") && conf
->autodev
> 0)
2112 needs_warning
= true;
2113 else if (!strcmp(tmp
, "dev/urandom") && conf
->autodev
> 0)
2114 needs_warning
= true;
2115 else if (!strcmp(tmp
, "dev/random") && conf
->autodev
> 0)
2116 needs_warning
= true;
2117 else if (!strcmp(tmp
, "dev/tty") && conf
->autodev
> 0)
2118 needs_warning
= true;
2119 else if (!strncmp(tmp
, "dev/tty", 7) && (conf
->autodev
> 0 || conf
->tty
> 0))
2120 needs_warning
= true;
2123 NOTICE("Requesting to mount \"%s\" on \"%s\" while requesting "
2124 "automatic device setup under \"/dev\"",
2125 clean_mnt_fsname
, clean_mnt_dir
);
2127 free(clean_mnt_dir
);
2128 free(clean_mnt_fsname
);
2131 static int mount_file_entries(const struct lxc_conf
*conf
,
2132 const struct lxc_rootfs
*rootfs
, FILE *file
,
2133 const char *lxc_name
, const char *lxc_path
)
2135 struct mntent mntent
;
2139 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2140 log_notice_on_conflict(conf
, mntent
.mnt_fsname
, mntent
.mnt_dir
);
2143 ret
= mount_entry_on_systemfs(&mntent
);
2144 else if (mntent
.mnt_dir
[0] != '/')
2145 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2146 lxc_name
, lxc_path
);
2148 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2149 lxc_name
, lxc_path
);
2155 INFO("Set up mount entries");
2159 static int setup_mount(const struct lxc_conf
*conf
,
2160 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2161 const char *lxc_name
, const char *lxc_path
)
2169 f
= setmntent(fstab
, "r");
2171 SYSERROR("Failed to open \"%s\"", fstab
);
2175 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2177 ERROR("Failed to set up mount entries");
2183 FILE *make_anonymous_mount_file(struct lxc_list
*mount
)
2187 struct lxc_list
*iterator
;
2191 fd
= memfd_create("lxc_mount_file", MFD_CLOEXEC
);
2193 if (errno
!= ENOSYS
)
2196 TRACE("Created temporary mount file");
2198 f
= fdopen(fd
, "r+");
2199 TRACE("Created anonymous mount file");
2203 SYSERROR("Could not create mount file");
2209 lxc_list_for_each(iterator
, mount
) {
2210 mount_entry
= iterator
->elem
;
2211 ret
= fprintf(f
, "%s\n", mount_entry
);
2212 if (ret
< strlen(mount_entry
))
2213 WARN("Could not write mount entry to mount file");
2216 ret
= fseek(f
, 0, SEEK_SET
);
2218 SYSERROR("Failed to seek mount file");
2226 static int setup_mount_entries(const struct lxc_conf
*conf
,
2227 const struct lxc_rootfs
*rootfs
,
2228 struct lxc_list
*mount
, const char *lxc_name
,
2229 const char *lxc_path
)
2234 f
= make_anonymous_mount_file(mount
);
2238 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2244 static int parse_cap(const char *cap
)
2250 if (!strcmp(cap
, "none"))
2253 for (i
= 0; i
< sizeof(caps_opt
)/sizeof(caps_opt
[0]); i
++) {
2255 if (strcmp(cap
, caps_opt
[i
].name
))
2258 capid
= caps_opt
[i
].value
;
2263 /* try to see if it's numeric, so the user may specify
2264 * capabilities that the running kernel knows about but
2267 capid
= strtol(cap
, &ptr
, 10);
2268 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2269 /* not a valid number */
2271 else if (capid
> lxc_caps_last_cap())
2272 /* we have a number but it's not a valid
2280 int in_caplist(int cap
, struct lxc_list
*caps
)
2282 struct lxc_list
*iterator
;
2285 lxc_list_for_each(iterator
, caps
) {
2286 capid
= parse_cap(iterator
->elem
);
2294 static int setup_caps(struct lxc_list
*caps
)
2296 struct lxc_list
*iterator
;
2300 lxc_list_for_each(iterator
, caps
) {
2302 drop_entry
= iterator
->elem
;
2304 capid
= parse_cap(drop_entry
);
2307 ERROR("unknown capability %s", drop_entry
);
2311 DEBUG("drop capability '%s' (%d)", drop_entry
, capid
);
2313 if (prctl(PR_CAPBSET_DROP
, capid
, 0, 0, 0)) {
2314 SYSERROR("failed to remove %s capability", drop_entry
);
2320 DEBUG("capabilities have been setup");
2325 static int dropcaps_except(struct lxc_list
*caps
)
2327 struct lxc_list
*iterator
;
2330 int numcaps
= lxc_caps_last_cap() + 1;
2331 INFO("found %d capabilities", numcaps
);
2333 if (numcaps
<= 0 || numcaps
> 200)
2336 /* caplist[i] is 1 if we keep capability i */
2337 int *caplist
= alloca(numcaps
* sizeof(int));
2338 memset(caplist
, 0, numcaps
* sizeof(int));
2340 lxc_list_for_each(iterator
, caps
) {
2342 keep_entry
= iterator
->elem
;
2344 capid
= parse_cap(keep_entry
);
2350 ERROR("unknown capability %s", keep_entry
);
2354 DEBUG("keep capability '%s' (%d)", keep_entry
, capid
);
2358 for (i
=0; i
<numcaps
; i
++) {
2361 if (prctl(PR_CAPBSET_DROP
, i
, 0, 0, 0)) {
2362 SYSERROR("failed to remove capability %d", i
);
2367 DEBUG("capabilities have been setup");
2372 static int parse_resource(const char *res
) {
2376 for (i
= 0; i
< sizeof(limit_opt
)/sizeof(limit_opt
[0]); ++i
) {
2377 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2378 return limit_opt
[i
].value
;
2381 /* try to see if it's numeric, so the user may specify
2382 * resources that the running kernel knows about but
2384 if (lxc_safe_int(res
, &resid
) == 0)
2389 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
) {
2390 struct lxc_list
*it
;
2391 struct lxc_limit
*lim
;
2394 lxc_list_for_each(it
, limits
) {
2397 resid
= parse_resource(lim
->resource
);
2399 ERROR("unknown resource %s", lim
->resource
);
2403 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2404 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2405 ERROR("failed to set limit %s: %s", lim
->resource
, strerror(errno
));
2409 ERROR("Cannot set limit %s as prlimit is missing", lim
->resource
);
2416 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2418 struct lxc_conf
*lxc_conf_init(void)
2420 struct lxc_conf
*new;
2423 new = malloc(sizeof(*new));
2425 ERROR("lxc_conf_init : %s", strerror(errno
));
2428 memset(new, 0, sizeof(*new));
2430 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2431 new->personality
= -1;
2433 new->console
.log_path
= NULL
;
2434 new->console
.log_fd
= -1;
2435 new->console
.log_size
= 0;
2436 new->console
.path
= NULL
;
2437 new->console
.peer
= -1;
2438 new->console
.peerpty
.busy
= -1;
2439 new->console
.peerpty
.master
= -1;
2440 new->console
.peerpty
.slave
= -1;
2441 new->console
.master
= -1;
2442 new->console
.slave
= -1;
2443 new->console
.name
[0] = '\0';
2444 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2445 new->maincmd_fd
= -1;
2447 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2448 if (!new->rootfs
.mount
) {
2449 ERROR("lxc_conf_init : %s", strerror(errno
));
2454 lxc_list_init(&new->cgroup
);
2455 lxc_list_init(&new->network
);
2456 lxc_list_init(&new->mount_list
);
2457 lxc_list_init(&new->caps
);
2458 lxc_list_init(&new->keepcaps
);
2459 lxc_list_init(&new->id_map
);
2460 lxc_list_init(&new->includes
);
2461 lxc_list_init(&new->aliens
);
2462 lxc_list_init(&new->environment
);
2463 lxc_list_init(&new->limits
);
2464 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2465 lxc_list_init(&new->hooks
[i
]);
2466 lxc_list_init(&new->groups
);
2467 new->lsm_aa_profile
= NULL
;
2468 new->lsm_se_context
= NULL
;
2469 new->tmp_umount_proc
= 0;
2471 /* if running in a new user namespace, init and COMMAND
2472 * default to running as UID/GID 0 when using lxc-execute */
2475 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2476 memset(&new->inherit_ns
, 0, sizeof(char *) * LXC_NS_MAX
);
2481 static int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2484 char path
[MAXPATHLEN
];
2487 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/%cid_map", pid
,
2488 idtype
== ID_TYPE_UID
? 'u' : 'g');
2489 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2490 ERROR("failed to create path \"%s\"", path
);
2494 fd
= open(path
, O_WRONLY
);
2496 SYSERROR("failed to open \"%s\"", path
);
2501 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2502 if (ret
!= buf_size
) {
2503 SYSERROR("failed to write %cid mapping to \"%s\"",
2504 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2513 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2515 * @return 1 if functional binary was found
2516 * @return 0 if binary exists but is lacking privilege
2517 * @return -ENOENT if binary does not exist
2518 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2521 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2528 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2531 path
= on_path(binary
, NULL
);
2535 ret
= stat(path
, &st
);
2541 /* Check if the binary is setuid. */
2542 if (st
.st_mode
& S_ISUID
) {
2543 DEBUG("The binary \"%s\" does have the setuid bit set.", path
);
2548 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2549 /* Check if it has the CAP_SETUID capability. */
2550 if ((cap
& CAP_SETUID
) &&
2551 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2552 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2553 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2554 "and CAP_PERMITTED sets.", path
);
2559 /* Check if it has the CAP_SETGID capability. */
2560 if ((cap
& CAP_SETGID
) &&
2561 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2562 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2563 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2564 "and CAP_PERMITTED sets.", path
);
2569 /* If we cannot check for file capabilities we need to give the benefit
2570 * of the doubt. Otherwise we might fail even though all the necessary
2571 * file capabilities are set.
2573 DEBUG("Cannot check for file capabilites as full capability support is "
2574 "missing. Manual intervention needed.");
2583 int lxc_map_ids_exec_wrapper(void *args
)
2585 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2589 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2592 struct lxc_list
*iterator
;
2597 char cmd_output
[MAXPATHLEN
];
2598 /* strlen("new@idmap") = 9
2606 * We add some additional space to make sure that we really have
2607 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2609 char mapbuf
[9 + 1 + LXC_NUMSTRLEN64
+ 1 + LXC_IDMAPLEN
] = {0};
2610 int ret
= 0, uidmap
= 0, gidmap
= 0;
2611 bool use_shadow
= false, had_entry
= false;
2613 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2614 * ranges, then insist that root also reserve ranges in subuid. This
2615 * will protected it by preventing another user from being handed the
2618 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2619 if (uidmap
== -ENOENT
)
2620 WARN("newuidmap binary is missing");
2622 WARN("newuidmap is lacking necessary privileges");
2624 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2625 if (gidmap
== -ENOENT
)
2626 WARN("newgidmap binary is missing");
2628 WARN("newgidmap is lacking necessary privileges");
2630 if (uidmap
> 0 && gidmap
> 0) {
2631 DEBUG("Functional newuidmap and newgidmap binary found.");
2634 /* In case unprivileged users run application containers via
2635 * execute() or a start*() there are valid cases where they may
2636 * only want to map their own {g,u}id. Let's not block them from
2637 * doing so by requiring geteuid() == 0.
2639 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2640 "write directly with euid %d.", geteuid());
2643 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
2644 type
++, u_or_g
= 'g') {
2648 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
2650 lxc_list_for_each(iterator
, idmap
) {
2651 map
= iterator
->elem
;
2652 if (map
->idtype
!= type
)
2657 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
2658 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
2659 use_shadow
? " " : "", map
->nsid
,
2660 map
->hostid
, map
->range
,
2661 use_shadow
? "" : "\n");
2662 if (fill
<= 0 || fill
>= left
) {
2663 /* The kernel only takes <= 4k for writes to
2664 * /proc/<pid>/{g,u}id_map
2666 SYSERROR("Too many %cid mappings defined", u_or_g
);
2675 /* Try to catch the ouput of new{g,u}idmap to make debugging
2679 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2680 lxc_map_ids_exec_wrapper
,
2683 ERROR("new%cidmap failed to write mapping \"%s\": %s",
2684 u_or_g
, cmd_output
, mapbuf
);
2687 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
2689 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
2691 ERROR("Failed to write mapping: %s", mapbuf
);
2694 TRACE("Wrote mapping \"%s\"", mapbuf
);
2697 memset(mapbuf
, 0, sizeof(mapbuf
));
2704 * return the host uid/gid to which the container root is mapped in
2706 * Return true if id was found, false otherwise.
2708 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
2711 struct lxc_list
*it
;
2714 lxc_list_for_each(it
, &conf
->id_map
) {
2716 if (map
->idtype
!= idtype
)
2726 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
2728 struct lxc_list
*it
;
2730 lxc_list_for_each(it
, &conf
->id_map
) {
2732 if (map
->idtype
!= idtype
)
2734 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
2735 return (id
- map
->hostid
) + map
->nsid
;
2740 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
2742 struct lxc_list
*it
;
2744 unsigned int freeid
= 0;
2746 lxc_list_for_each(it
, &conf
->id_map
) {
2748 if (map
->idtype
!= idtype
)
2750 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
2751 freeid
= map
->nsid
+ map
->range
;
2758 int chown_mapped_root_exec_wrapper(void *args
)
2760 execvp("lxc-usernsexec", args
);
2765 * chown_mapped_root: for an unprivileged user with uid/gid X to
2766 * chown a dir to subuid/subgid Y, he needs to run chown as root
2767 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
2768 * nsid Y is mapped to hostuid/hostgid X. That way, the container
2769 * root is privileged with respect to hostuid/hostgid X, allowing
2770 * him to do the chown.
2772 int chown_mapped_root(char *path
, struct lxc_conf
*conf
)
2774 uid_t rootuid
, rootgid
;
2776 int hostuid
, hostgid
, ret
;
2778 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
2780 char *args1
[] = {"lxc-usernsexec",
2785 "--", "chown", ugid
, path
,
2787 char *args2
[] = {"lxc-usernsexec",
2793 "--", "chown", ugid
, path
,
2795 char cmd_output
[MAXPATHLEN
];
2797 hostuid
= geteuid();
2798 hostgid
= getegid();
2800 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
2801 ERROR("No uid mapping for container root");
2804 rootuid
= (uid_t
)val
;
2805 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
2806 ERROR("No gid mapping for container root");
2809 rootgid
= (gid_t
)val
;
2812 if (chown(path
, rootuid
, rootgid
) < 0) {
2813 ERROR("Error chowning %s", path
);
2819 if (rootuid
== hostuid
) {
2821 INFO("Container root is our uid; no need to chown");
2825 /* save the current gid of "path" */
2826 if (stat(path
, &sb
) < 0) {
2827 ERROR("Error stat %s", path
);
2831 /* Update the path argument in case this was overlayfs. */
2832 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
2833 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
2836 * A file has to be group-owned by a gid mapped into the
2837 * container, or the container won't be privileged over it.
2839 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
2840 if (sb
.st_uid
== hostuid
&&
2841 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
2842 chown(path
, -1, hostgid
) < 0) {
2843 ERROR("Failed chgrping %s", path
);
2847 /* "u:0:rootuid:1" */
2848 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
2849 if (ret
< 0 || ret
>= 100) {
2850 ERROR("Error uid printing map string");
2854 /* "u:hostuid:hostuid:1" */
2855 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
2856 if (ret
< 0 || ret
>= 100) {
2857 ERROR("Error uid printing map string");
2861 /* "g:0:rootgid:1" */
2862 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
2863 if (ret
< 0 || ret
>= 100) {
2864 ERROR("Error gid printing map string");
2868 /* "g:pathgid:rootgid+pathgid:1" */
2869 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
2870 rootgid
+ (gid_t
)sb
.st_gid
);
2871 if (ret
< 0 || ret
>= 100) {
2872 ERROR("Error gid printing map string");
2876 /* "g:hostgid:hostgid:1" */
2877 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
2878 if (ret
< 0 || ret
>= 100) {
2879 ERROR("Error gid printing map string");
2883 /* "0:pathgid" (chown) */
2884 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
2885 if (ret
< 0 || ret
>= 100) {
2886 ERROR("Error owner printing format string for chown");
2890 if (hostgid
== sb
.st_gid
)
2891 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2892 chown_mapped_root_exec_wrapper
,
2895 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2896 chown_mapped_root_exec_wrapper
,
2899 ERROR("lxc-usernsexec failed: %s", cmd_output
);
2904 int lxc_ttys_shift_ids(struct lxc_conf
*c
)
2906 if (lxc_list_empty(&c
->id_map
))
2909 if (!strcmp(c
->console
.name
, ""))
2912 if (chown_mapped_root(c
->console
.name
, c
) < 0) {
2913 ERROR("failed to chown console \"%s\"", c
->console
.name
);
2917 TRACE("chowned console \"%s\"", c
->console
.name
);
2922 /* NOTE: Must not be called from inside the container namespace! */
2923 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
2927 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
2928 if (mounted
== -1) {
2929 SYSERROR("failed to mount /proc in the container");
2930 /* continue only if there is no rootfs */
2931 if (conf
->rootfs
.path
)
2933 } else if (mounted
== 1) {
2934 conf
->tmp_umount_proc
= 1;
2940 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
2942 if (lxc_conf
->tmp_umount_proc
== 1) {
2944 lxc_conf
->tmp_umount_proc
= 0;
2948 void remount_all_slave(void)
2950 /* walk /proc/mounts and change any shared entries to slave */
2951 FILE *f
= fopen("/proc/self/mountinfo", "r");
2956 SYSERROR("Failed to open /proc/self/mountinfo to mark all shared");
2957 ERROR("Continuing container startup...");
2961 while (getline(&line
, &len
, f
) != -1) {
2962 char *target
, *opts
;
2963 target
= get_field(line
, 4);
2966 opts
= get_field(target
, 2);
2969 null_endofword(opts
);
2970 if (!strstr(opts
, "shared"))
2972 null_endofword(target
);
2973 if (mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
)) {
2974 SYSERROR("Failed to make %s rslave", target
);
2975 ERROR("Continuing...");
2982 void lxc_execute_bind_init(struct lxc_conf
*conf
)
2985 char path
[PATH_MAX
], destpath
[PATH_MAX
], *p
;
2987 /* If init exists in the container, don't bind mount a static one */
2988 p
= choose_init(conf
->rootfs
.mount
);
2994 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
2995 if (ret
< 0 || ret
>= PATH_MAX
) {
2996 WARN("Path name too long searching for lxc.init.static");
3000 if (!file_exists(path
)) {
3001 INFO("%s does not exist on host", path
);
3005 ret
= snprintf(destpath
, PATH_MAX
, "%s%s", conf
->rootfs
.mount
, "/init.lxc.static");
3006 if (ret
< 0 || ret
>= PATH_MAX
) {
3007 WARN("Path name too long for container's lxc.init.static");
3011 if (!file_exists(destpath
)) {
3012 FILE * pathfile
= fopen(destpath
, "wb");
3014 SYSERROR("Failed to create mount target '%s'", destpath
);
3020 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3022 SYSERROR("Failed to bind lxc.init.static into container");
3023 INFO("lxc.init.static bound into container at %s", path
);
3027 * This does the work of remounting / if it is shared, calling the
3028 * container pre-mount hooks, and mounting the rootfs.
3030 int do_rootfs_setup(struct lxc_conf
*conf
, const char *name
, const char *lxcpath
)
3032 if (conf
->rootfs_setup
) {
3034 * rootfs was set up in another namespace. bind-mount it
3035 * to give us a mount in our own ns so we can pivot_root to it
3037 const char *path
= conf
->rootfs
.mount
;
3038 if (mount(path
, path
, "rootfs", MS_BIND
, NULL
) < 0) {
3039 ERROR("Failed to bind-mount container / onto itself");
3045 remount_all_slave();
3047 if (run_lxc_hooks(name
, "pre-mount", conf
, lxcpath
, NULL
)) {
3048 ERROR("failed to run pre-mount hooks for container '%s'.", name
);
3052 if (lxc_setup_rootfs(conf
)) {
3053 ERROR("failed to setup rootfs for '%s'", name
);
3057 conf
->rootfs_setup
= true;
3061 static bool verify_start_hooks(struct lxc_conf
*conf
)
3063 struct lxc_list
*it
;
3064 char path
[MAXPATHLEN
];
3065 lxc_list_for_each(it
, &conf
->hooks
[LXCHOOK_START
]) {
3066 char *hookname
= it
->elem
;
3070 ret
= snprintf(path
, MAXPATHLEN
, "%s%s",
3071 conf
->rootfs
.path
? conf
->rootfs
.mount
: "", hookname
);
3072 if (ret
< 0 || ret
>= MAXPATHLEN
)
3074 ret
= stat(path
, &st
);
3076 SYSERROR("Start hook %s not found in container",
3086 int lxc_setup(struct lxc_handler
*handler
)
3089 const char *name
= handler
->name
;
3090 struct lxc_conf
*lxc_conf
= handler
->conf
;
3091 const char *lxcpath
= handler
->lxcpath
;
3093 if (do_rootfs_setup(lxc_conf
, name
, lxcpath
) < 0) {
3094 ERROR("Error setting up rootfs mount after spawn");
3098 if (handler
->nsfd
[LXC_NS_UTS
] == -1) {
3099 if (setup_utsname(lxc_conf
->utsname
)) {
3100 ERROR("failed to setup the utsname for '%s'", name
);
3105 if (lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
)) {
3106 ERROR("failed to setup the network for '%s'", name
);
3110 if (lxc_network_send_name_and_ifindex_to_parent(handler
) < 0) {
3111 ERROR("Failed to network device names and ifindices to parent");
3115 if (lxc_conf
->autodev
> 0) {
3116 if (mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
)) {
3117 ERROR("failed to mount /dev in the container");
3122 /* do automatic mounts (mainly /proc and /sys), but exclude
3123 * those that need to wait until other stuff has finished
3125 if (lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
) < 0) {
3126 ERROR("failed to setup the automatic mounts for '%s'", name
);
3130 if (setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
)) {
3131 ERROR("failed to setup the mounts for '%s'", name
);
3135 if (!lxc_list_empty(&lxc_conf
->mount_list
) && setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
, &lxc_conf
->mount_list
, name
, lxcpath
)) {
3136 ERROR("failed to setup the mount entries for '%s'", name
);
3140 /* Make sure any start hooks are in the container */
3141 if (!verify_start_hooks(lxc_conf
))
3144 if (lxc_conf
->is_execute
)
3145 lxc_execute_bind_init(lxc_conf
);
3147 /* now mount only cgroup, if wanted;
3148 * before, /sys could not have been mounted
3149 * (is either mounted automatically or via fstab entries)
3151 if (lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
) < 0) {
3152 ERROR("failed to setup the automatic mounts for '%s'", name
);
3156 if (run_lxc_hooks(name
, "mount", lxc_conf
, lxcpath
, NULL
)) {
3157 ERROR("failed to run mount hooks for container '%s'.", name
);
3161 if (lxc_conf
->autodev
> 0) {
3162 if (run_lxc_hooks(name
, "autodev", lxc_conf
, lxcpath
, NULL
)) {
3163 ERROR("failed to run autodev hooks for container '%s'.", name
);
3167 if (lxc_fill_autodev(&lxc_conf
->rootfs
)) {
3168 ERROR("failed to populate /dev in the container");
3173 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3176 ERROR("Failed to setup console");
3180 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3182 ERROR("Failed to setup /dev symlinks");
3186 /* mount /proc if it's not already there */
3187 if (lxc_create_tmp_proc_mount(lxc_conf
) < 0) {
3188 ERROR("failed to LSM mount proc for '%s'", name
);
3192 if (setup_pivot_root(&lxc_conf
->rootfs
)) {
3193 ERROR("failed to set rootfs for '%s'", name
);
3197 if (lxc_setup_devpts(lxc_conf
->pts
)) {
3198 ERROR("failed to setup the new pts instance");
3202 ret
= lxc_create_ttys(handler
);
3206 if (setup_personality(lxc_conf
->personality
)) {
3207 ERROR("failed to setup personality");
3211 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3212 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3213 ERROR("Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both.");
3216 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3217 ERROR("failed to keep requested caps");
3220 } else if (setup_caps(&lxc_conf
->caps
)) {
3221 ERROR("failed to drop capabilities");
3225 NOTICE("Container \"%s\" is set up", name
);
3230 int run_lxc_hooks(const char *name
, char *hook
, struct lxc_conf
*conf
,
3231 const char *lxcpath
, char *argv
[])
3234 struct lxc_list
*it
;
3236 if (strcmp(hook
, "pre-start") == 0)
3237 which
= LXCHOOK_PRESTART
;
3238 else if (strcmp(hook
, "start-host") == 0)
3239 which
= LXCHOOK_START_HOST
;
3240 else if (strcmp(hook
, "pre-mount") == 0)
3241 which
= LXCHOOK_PREMOUNT
;
3242 else if (strcmp(hook
, "mount") == 0)
3243 which
= LXCHOOK_MOUNT
;
3244 else if (strcmp(hook
, "autodev") == 0)
3245 which
= LXCHOOK_AUTODEV
;
3246 else if (strcmp(hook
, "start") == 0)
3247 which
= LXCHOOK_START
;
3248 else if (strcmp(hook
, "stop") == 0)
3249 which
= LXCHOOK_STOP
;
3250 else if (strcmp(hook
, "post-stop") == 0)
3251 which
= LXCHOOK_POSTSTOP
;
3252 else if (strcmp(hook
, "clone") == 0)
3253 which
= LXCHOOK_CLONE
;
3254 else if (strcmp(hook
, "destroy") == 0)
3255 which
= LXCHOOK_DESTROY
;
3258 lxc_list_for_each(it
, &conf
->hooks
[which
]) {
3260 char *hookname
= it
->elem
;
3261 ret
= run_script_argv(name
, "lxc", hookname
, hook
, lxcpath
, argv
);
3268 int lxc_clear_config_caps(struct lxc_conf
*c
)
3270 struct lxc_list
*it
, *next
;
3272 lxc_list_for_each_safe(it
, &c
->caps
, next
) {
3280 static int lxc_free_idmap(struct lxc_list
*id_map
) {
3281 struct lxc_list
*it
, *next
;
3283 lxc_list_for_each_safe(it
, id_map
, next
) {
3291 int lxc_clear_idmaps(struct lxc_conf
*c
)
3293 return lxc_free_idmap(&c
->id_map
);
3296 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3298 struct lxc_list
*it
,*next
;
3300 lxc_list_for_each_safe(it
, &c
->keepcaps
, next
) {
3308 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
)
3310 struct lxc_list
*it
,*next
;
3312 const char *k
= NULL
;
3314 if (strcmp(key
, "lxc.cgroup") == 0)
3316 else if (strncmp(key
, "lxc.cgroup.", sizeof("lxc.cgroup.")-1) == 0)
3317 k
= key
+ sizeof("lxc.cgroup.")-1;
3321 lxc_list_for_each_safe(it
, &c
->cgroup
, next
) {
3322 struct lxc_cgroup
*cg
= it
->elem
;
3323 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3326 free(cg
->subsystem
);
3334 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3336 struct lxc_list
*it
, *next
;
3338 const char *k
= NULL
;
3340 if (strcmp(key
, "lxc.limit") == 0
3341 || strcmp(key
, "lxc.prlimit"))
3343 else if (strncmp(key
, "lxc.limit.", sizeof("lxc.limit.")-1) == 0)
3344 k
= key
+ sizeof("lxc.limit.")-1;
3345 else if (strncmp(key
, "lxc.prlimit.", sizeof("lxc.prlimit.")-1) == 0)
3346 k
= key
+ sizeof("lxc.prlimit.")-1;
3350 lxc_list_for_each_safe(it
, &c
->limits
, next
) {
3351 struct lxc_limit
*lim
= it
->elem
;
3352 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3355 free(lim
->resource
);
3362 int lxc_clear_groups(struct lxc_conf
*c
)
3364 struct lxc_list
*it
,*next
;
3366 lxc_list_for_each_safe(it
, &c
->groups
, next
) {
3374 int lxc_clear_environment(struct lxc_conf
*c
)
3376 struct lxc_list
*it
,*next
;
3378 lxc_list_for_each_safe(it
, &c
->environment
, next
) {
3386 int lxc_clear_mount_entries(struct lxc_conf
*c
)
3388 struct lxc_list
*it
,*next
;
3390 lxc_list_for_each_safe(it
, &c
->mount_list
, next
) {
3398 int lxc_clear_automounts(struct lxc_conf
*c
)
3404 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
3406 struct lxc_list
*it
,*next
;
3407 bool all
= false, done
= false;
3408 const char *k
= NULL
;
3411 if (strcmp(key
, "lxc.hook") == 0)
3413 else if (strncmp(key
, "lxc.hook.", sizeof("lxc.hook.")-1) == 0)
3414 k
= key
+ sizeof("lxc.hook.")-1;
3418 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3419 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
3420 lxc_list_for_each_safe(it
, &c
->hooks
[i
], next
) {
3430 ERROR("Invalid hook key: %s", key
);
3436 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
3438 struct lxc_list
*it
,*next
;
3440 lxc_list_for_each_safe(it
, &conf
->aliens
, next
) {
3447 void lxc_clear_includes(struct lxc_conf
*conf
)
3449 struct lxc_list
*it
,*next
;
3451 lxc_list_for_each_safe(it
, &conf
->includes
, next
) {
3458 void lxc_conf_free(struct lxc_conf
*conf
)
3462 if (current_config
== conf
)
3463 current_config
= NULL
;
3464 free(conf
->console
.log_path
);
3465 free(conf
->console
.path
);
3466 if (conf
->console
.log_size
> 0 && conf
->console
.ringbuf
.addr
)
3467 lxc_ringbuf_release(&conf
->console
.ringbuf
);
3468 free(conf
->rootfs
.mount
);
3469 free(conf
->rootfs
.bdev_type
);
3470 free(conf
->rootfs
.options
);
3471 free(conf
->rootfs
.path
);
3472 free(conf
->logfile
);
3473 if (conf
->logfd
!= -1)
3475 free(conf
->utsname
);
3479 free(conf
->execute_cmd
);
3480 free(conf
->init_cmd
);
3481 free(conf
->unexpanded_config
);
3482 free(conf
->pty_names
);
3484 lxc_free_networks(&conf
->network
);
3485 free(conf
->lsm_aa_profile
);
3486 free(conf
->lsm_se_context
);
3487 lxc_seccomp_free(conf
);
3488 lxc_clear_config_caps(conf
);
3489 lxc_clear_config_keepcaps(conf
);
3490 lxc_clear_cgroups(conf
, "lxc.cgroup");
3491 lxc_clear_hooks(conf
, "lxc.hook");
3492 lxc_clear_mount_entries(conf
);
3493 lxc_clear_idmaps(conf
);
3494 lxc_clear_groups(conf
);
3495 lxc_clear_includes(conf
);
3496 lxc_clear_aliens(conf
);
3497 lxc_clear_environment(conf
);
3498 lxc_clear_limits(conf
, "lxc.prlimit");
3499 free(conf
->cgroup_meta
.dir
);
3500 free(conf
->cgroup_meta
.controllers
);
3504 struct userns_fn_data
{
3506 const char *fn_name
;
3511 static int run_userns_fn(void *data
)
3513 struct userns_fn_data
*d
= data
;
3516 /* Close write end of the pipe. */
3519 /* Wait for parent to finish establishing a new mapping in the user
3520 * namespace we are executing in.
3522 if (read(d
->p
[0], &c
, 1) != 1)
3525 /* Close read end of the pipe. */
3529 TRACE("calling function \"%s\"", d
->fn_name
);
3530 /* Call function to run. */
3531 return d
->fn(d
->arg
);
3534 static struct id_map
*mapped_hostid_entry(struct lxc_conf
*conf
, unsigned id
,
3537 struct lxc_list
*it
;
3539 struct id_map
*retmap
= NULL
;
3541 lxc_list_for_each(it
, &conf
->id_map
) {
3543 if (map
->idtype
!= idtype
)
3546 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
3555 retmap
= malloc(sizeof(*retmap
));
3559 memcpy(retmap
, map
, sizeof(*retmap
));
3564 * Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
3565 * existing one or establish a new one.
3567 static struct id_map
*idmap_add(struct lxc_conf
*conf
, uid_t id
, enum idtype type
)
3570 struct id_map
*entry
= NULL
;
3572 /* Reuse existing mapping. */
3573 entry
= mapped_hostid_entry(conf
, id
, type
);
3577 /* Find new mapping. */
3578 hostid_mapped
= find_unmapped_nsid(conf
, type
);
3579 if (hostid_mapped
< 0) {
3580 DEBUG("failed to find free mapping for id %d", id
);
3584 entry
= malloc(sizeof(*entry
));
3588 entry
->idtype
= type
;
3589 entry
->nsid
= hostid_mapped
;
3590 entry
->hostid
= (unsigned long)id
;
3596 /* Run a function in a new user namespace.
3597 * The caller's euid/egid will be mapped if it is not already.
3598 * Afaict, userns_exec_1() is only used to operate based on privileges for the
3599 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
3600 * This means we require only to establish a mapping from:
3601 * - the container root {g,u}id as seen from the host > user's host {g,u}id
3602 * - the container root -> some sub{g,u}id
3603 * The former we add, if the user did not specifiy a mapping. The latter we
3604 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
3605 * there to start the container in the first place.
3607 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
3608 const char *fn_name
)
3612 struct userns_fn_data d
;
3614 struct lxc_list
*it
;
3617 int ret
= -1, status
= -1;
3618 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
3619 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
3620 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
3624 SYSERROR("opening pipe");
3628 d
.fn_name
= fn_name
;
3633 /* Clone child in new user namespace. */
3634 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
3636 ERROR("failed to clone child process in new user namespace");
3646 /* Find container root. */
3647 lxc_list_for_each(it
, &conf
->id_map
) {
3653 if (map
->idtype
== ID_TYPE_UID
&& container_root_uid
== NULL
) {
3654 container_root_uid
= malloc(sizeof(*container_root_uid
));
3655 if (!container_root_uid
)
3657 container_root_uid
->idtype
= map
->idtype
;
3658 container_root_uid
->hostid
= map
->hostid
;
3659 container_root_uid
->nsid
= 0;
3660 container_root_uid
->range
= map
->range
;
3662 /* Check if container root mapping contains a mapping
3665 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
3666 host_uid_map
= container_root_uid
;
3667 } else if (map
->idtype
== ID_TYPE_GID
&& container_root_gid
== NULL
) {
3668 container_root_gid
= malloc(sizeof(*container_root_gid
));
3669 if (!container_root_gid
)
3671 container_root_gid
->idtype
= map
->idtype
;
3672 container_root_gid
->hostid
= map
->hostid
;
3673 container_root_gid
->nsid
= 0;
3674 container_root_gid
->range
= map
->range
;
3676 /* Check if container root mapping contains a mapping
3679 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
3680 host_gid_map
= container_root_gid
;
3683 /* Found container root. */
3684 if (container_root_uid
&& container_root_gid
)
3688 /* This is actually checked earlier but it can't hurt. */
3689 if (!container_root_uid
|| !container_root_gid
) {
3690 ERROR("no mapping for container root found");
3694 /* Check whether the {g,u}id of the user has a mapping. */
3696 host_uid_map
= idmap_add(conf
, euid
, ID_TYPE_UID
);
3699 host_gid_map
= idmap_add(conf
, egid
, ID_TYPE_GID
);
3701 if (!host_uid_map
) {
3702 DEBUG("failed to find mapping for uid %d", euid
);
3706 if (!host_gid_map
) {
3707 DEBUG("failed to find mapping for gid %d", egid
);
3711 /* Allocate new {g,u}id map list. */
3712 idmap
= malloc(sizeof(*idmap
));
3715 lxc_list_init(idmap
);
3717 /* Add container root to the map. */
3718 tmplist
= malloc(sizeof(*tmplist
));
3721 lxc_list_add_elem(tmplist
, container_root_uid
);
3722 lxc_list_add_tail(idmap
, tmplist
);
3724 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
3725 /* idmap will now keep track of that memory. */
3726 container_root_uid
= NULL
;
3728 /* Add container root to the map. */
3729 tmplist
= malloc(sizeof(*tmplist
));
3732 lxc_list_add_elem(tmplist
, host_uid_map
);
3733 lxc_list_add_tail(idmap
, tmplist
);
3735 /* idmap will now keep track of that memory. */
3736 container_root_uid
= NULL
;
3737 /* idmap will now keep track of that memory. */
3738 host_uid_map
= NULL
;
3740 tmplist
= malloc(sizeof(*tmplist
));
3743 lxc_list_add_elem(tmplist
, container_root_gid
);
3744 lxc_list_add_tail(idmap
, tmplist
);
3746 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
3747 /* idmap will now keep track of that memory. */
3748 container_root_gid
= NULL
;
3750 tmplist
= malloc(sizeof(*tmplist
));
3753 lxc_list_add_elem(tmplist
, host_gid_map
);
3754 lxc_list_add_tail(idmap
, tmplist
);
3756 /* idmap will now keep track of that memory. */
3757 container_root_gid
= NULL
;
3758 /* idmap will now keep track of that memory. */
3759 host_gid_map
= NULL
;
3761 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
3762 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
3763 lxc_list_for_each(it
, idmap
) {
3765 TRACE("establishing %cid mapping for \"%d\" in new "
3766 "user namespace: nsuid %lu - hostid %lu - range "
3768 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
3769 map
->nsid
, map
->hostid
, map
->range
);
3773 /* Set up {g,u}id mapping for user namespace of child process. */
3774 ret
= lxc_map_ids(idmap
, pid
);
3776 ERROR("error setting up {g,u}id mappings for child process "
3781 /* Tell child to proceed. */
3782 if (write(p
[1], &c
, 1) != 1) {
3783 SYSERROR("failed telling child process \"%d\" to proceed", pid
);
3788 /* Wait for child to finish. */
3790 status
= wait_for_pid(pid
);
3793 lxc_free_idmap(idmap
);
3794 if (container_root_uid
)
3795 free(container_root_uid
);
3796 if (container_root_gid
)
3797 free(container_root_gid
);
3798 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
3800 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
3813 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
3814 const char *fn_name
)
3818 struct userns_fn_data d
;
3821 struct lxc_list
*cur
;
3824 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
3825 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
3826 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
3830 SYSERROR("opening pipe");
3834 d
.fn_name
= fn_name
;
3839 /* Clone child in new user namespace. */
3840 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
3842 ERROR("failed to clone child process in new user namespace");
3852 /* Allocate new {g,u}id map list. */
3853 idmap
= malloc(sizeof(*idmap
));
3856 lxc_list_init(idmap
);
3858 /* Find container root. */
3859 lxc_list_for_each(cur
, &conf
->id_map
) {
3860 struct id_map
*tmpmap
;
3862 tmplist
= malloc(sizeof(*tmplist
));
3866 tmpmap
= malloc(sizeof(*tmpmap
));
3872 memset(tmpmap
, 0, sizeof(*tmpmap
));
3873 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
3874 tmplist
->elem
= tmpmap
;
3876 lxc_list_add_tail(idmap
, tmplist
);
3880 if (map
->idtype
== ID_TYPE_UID
)
3881 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
3884 if (map
->idtype
== ID_TYPE_GID
)
3885 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
3891 if (map
->idtype
== ID_TYPE_UID
)
3892 if (container_root_uid
== NULL
)
3893 container_root_uid
= map
;
3895 if (map
->idtype
== ID_TYPE_GID
)
3896 if (container_root_gid
== NULL
)
3897 container_root_gid
= map
;
3900 if (!container_root_uid
|| !container_root_gid
) {
3901 ERROR("No mapping for container root found");
3905 /* Check whether the {g,u}id of the user has a mapping. */
3907 host_uid_map
= idmap_add(conf
, euid
, ID_TYPE_UID
);
3909 host_uid_map
= container_root_uid
;
3912 host_gid_map
= idmap_add(conf
, egid
, ID_TYPE_GID
);
3914 host_gid_map
= container_root_gid
;
3916 if (!host_uid_map
) {
3917 DEBUG("Failed to find mapping for uid %d", euid
);
3921 if (!host_gid_map
) {
3922 DEBUG("Failed to find mapping for gid %d", egid
);
3926 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
3927 /* Add container root to the map. */
3928 tmplist
= malloc(sizeof(*tmplist
));
3931 lxc_list_add_elem(tmplist
, host_uid_map
);
3932 lxc_list_add_tail(idmap
, tmplist
);
3934 /* idmap will now keep track of that memory. */
3935 host_uid_map
= NULL
;
3937 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
3938 tmplist
= malloc(sizeof(*tmplist
));
3941 lxc_list_add_elem(tmplist
, host_gid_map
);
3942 lxc_list_add_tail(idmap
, tmplist
);
3944 /* idmap will now keep track of that memory. */
3945 host_gid_map
= NULL
;
3947 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
3948 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
3949 lxc_list_for_each(cur
, idmap
) {
3951 TRACE("establishing %cid mapping for \"%d\" in new "
3952 "user namespace: nsuid %lu - hostid %lu - range "
3954 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
3955 map
->nsid
, map
->hostid
, map
->range
);
3959 /* Set up {g,u}id mapping for user namespace of child process. */
3960 ret
= lxc_map_ids(idmap
, pid
);
3962 ERROR("error setting up {g,u}id mappings for child process "
3967 /* Tell child to proceed. */
3968 if (write(p
[1], &c
, 1) != 1) {
3969 SYSERROR("failed telling child process \"%d\" to proceed", pid
);
3974 /* Wait for child to finish. */
3976 ret
= wait_for_pid(pid
);
3979 lxc_free_idmap(idmap
);
3980 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
3982 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
3992 /* not thread-safe, do not use from api without first forking */
3993 static char* getuname(void)
3995 struct passwd
*result
;
3997 result
= getpwuid(geteuid());
4001 return strdup(result
->pw_name
);
4004 /* not thread-safe, do not use from api without first forking */
4005 static char *getgname(void)
4007 struct group
*result
;
4009 result
= getgrgid(getegid());
4013 return strdup(result
->gr_name
);
4016 /* not thread-safe, do not use from api without first forking */
4017 void suggest_default_idmap(void)
4020 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4022 char *uname
, *gname
;
4025 if (!(uname
= getuname()))
4028 if (!(gname
= getgname())) {
4033 f
= fopen(subuidfile
, "r");
4035 ERROR("Your system is not configured with subuids");
4040 while (getline(&line
, &len
, f
) != -1) {
4041 size_t no_newline
= 0;
4042 char *p
= strchr(line
, ':'), *p2
;
4049 if (strcmp(line
, uname
))
4051 p2
= strchr(p
, ':');
4058 no_newline
= strcspn(p2
, "\n");
4059 p2
[no_newline
] = '\0';
4061 if (lxc_safe_uint(p
, &uid
) < 0)
4062 WARN("Could not parse UID.");
4063 if (lxc_safe_uint(p2
, &urange
) < 0)
4064 WARN("Could not parse UID range.");
4068 f
= fopen(subgidfile
, "r");
4070 ERROR("Your system is not configured with subgids");
4075 while (getline(&line
, &len
, f
) != -1) {
4076 size_t no_newline
= 0;
4077 char *p
= strchr(line
, ':'), *p2
;
4084 if (strcmp(line
, uname
))
4086 p2
= strchr(p
, ':');
4093 no_newline
= strcspn(p2
, "\n");
4094 p2
[no_newline
] = '\0';
4096 if (lxc_safe_uint(p
, &gid
) < 0)
4097 WARN("Could not parse GID.");
4098 if (lxc_safe_uint(p2
, &grange
) < 0)
4099 WARN("Could not parse GID range.");
4105 if (!urange
|| !grange
) {
4106 ERROR("You do not have subuids or subgids allocated");
4107 ERROR("Unprivileged containers require subuids and subgids");
4111 ERROR("You must either run as root, or define uid mappings");
4112 ERROR("To pass uid mappings to lxc-create, you could create");
4113 ERROR("~/.config/lxc/default.conf:");
4114 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4115 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4116 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4122 static void free_cgroup_settings(struct lxc_list
*result
)
4124 struct lxc_list
*iterator
, *next
;
4126 lxc_list_for_each_safe(iterator
, result
, next
) {
4127 lxc_list_del(iterator
);
4134 * Return the list of cgroup_settings sorted according to the following rules
4135 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4137 struct lxc_list
*sort_cgroup_settings(struct lxc_list
* cgroup_settings
)
4139 struct lxc_list
*result
;
4140 struct lxc_list
*memsw_limit
= NULL
;
4141 struct lxc_list
*it
= NULL
;
4142 struct lxc_cgroup
*cg
= NULL
;
4143 struct lxc_list
*item
= NULL
;
4145 result
= malloc(sizeof(*result
));
4147 ERROR("failed to allocate memory to sort cgroup settings");
4150 lxc_list_init(result
);
4152 /*Iterate over the cgroup settings and copy them to the output list*/
4153 lxc_list_for_each(it
, cgroup_settings
) {
4154 item
= malloc(sizeof(*item
));
4156 ERROR("failed to allocate memory to sort cgroup settings");
4157 free_cgroup_settings(result
);
4160 item
->elem
= it
->elem
;
4162 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4163 /* Store the memsw_limit location */
4165 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 && memsw_limit
!= NULL
) {
4166 /* lxc.cgroup.memory.memsw.limit_in_bytes is found before
4167 * lxc.cgroup.memory.limit_in_bytes, swap these two items */
4168 item
->elem
= memsw_limit
->elem
;
4169 memsw_limit
->elem
= it
->elem
;
4171 lxc_list_add_tail(result
, item
);