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
);
125 /* Define sethostname() if missing from the C library */
126 #ifndef HAVE_SETHOSTNAME
127 static int sethostname(const char * name
, size_t len
)
129 #ifdef __NR_sethostname
130 return syscall(__NR_sethostname
, name
, len
);
139 #define MS_PRIVATE (1<<18)
143 #define MS_LAZYTIME (1<<25)
146 char *lxchook_names
[NUM_LXC_HOOKS
] = {"pre-start", "pre-mount", "mount",
147 "autodev", "start", "stop",
148 "post-stop", "clone", "destroy",
168 * The lxc_conf of the container currently being worked on in an
170 * This is used in the error calls
173 __thread
struct lxc_conf
*current_config
;
175 struct lxc_conf
*current_config
;
178 static struct mount_opt mount_opt
[] = {
179 { "async", 1, MS_SYNCHRONOUS
},
180 { "atime", 1, MS_NOATIME
},
181 { "bind", 0, MS_BIND
},
182 { "defaults", 0, 0 },
183 { "dev", 1, MS_NODEV
},
184 { "diratime", 1, MS_NODIRATIME
},
185 { "dirsync", 0, MS_DIRSYNC
},
186 { "exec", 1, MS_NOEXEC
},
187 { "lazytime", 0, MS_LAZYTIME
},
188 { "mand", 0, MS_MANDLOCK
},
189 { "noatime", 0, MS_NOATIME
},
190 { "nodev", 0, MS_NODEV
},
191 { "nodiratime", 0, MS_NODIRATIME
},
192 { "noexec", 0, MS_NOEXEC
},
193 { "nomand", 1, MS_MANDLOCK
},
194 { "norelatime", 1, MS_RELATIME
},
195 { "nostrictatime", 1, MS_STRICTATIME
},
196 { "nosuid", 0, MS_NOSUID
},
197 { "rbind", 0, MS_BIND
|MS_REC
},
198 { "relatime", 0, MS_RELATIME
},
199 { "remount", 0, MS_REMOUNT
},
200 { "ro", 0, MS_RDONLY
},
201 { "rw", 1, MS_RDONLY
},
202 { "strictatime", 0, MS_STRICTATIME
},
203 { "suid", 1, MS_NOSUID
},
204 { "sync", 0, MS_SYNCHRONOUS
},
209 static struct caps_opt caps_opt
[] = {
210 { "chown", CAP_CHOWN
},
211 { "dac_override", CAP_DAC_OVERRIDE
},
212 { "dac_read_search", CAP_DAC_READ_SEARCH
},
213 { "fowner", CAP_FOWNER
},
214 { "fsetid", CAP_FSETID
},
215 { "kill", CAP_KILL
},
216 { "setgid", CAP_SETGID
},
217 { "setuid", CAP_SETUID
},
218 { "setpcap", CAP_SETPCAP
},
219 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
220 { "net_bind_service", CAP_NET_BIND_SERVICE
},
221 { "net_broadcast", CAP_NET_BROADCAST
},
222 { "net_admin", CAP_NET_ADMIN
},
223 { "net_raw", CAP_NET_RAW
},
224 { "ipc_lock", CAP_IPC_LOCK
},
225 { "ipc_owner", CAP_IPC_OWNER
},
226 { "sys_module", CAP_SYS_MODULE
},
227 { "sys_rawio", CAP_SYS_RAWIO
},
228 { "sys_chroot", CAP_SYS_CHROOT
},
229 { "sys_ptrace", CAP_SYS_PTRACE
},
230 { "sys_pacct", CAP_SYS_PACCT
},
231 { "sys_admin", CAP_SYS_ADMIN
},
232 { "sys_boot", CAP_SYS_BOOT
},
233 { "sys_nice", CAP_SYS_NICE
},
234 { "sys_resource", CAP_SYS_RESOURCE
},
235 { "sys_time", CAP_SYS_TIME
},
236 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
237 { "mknod", CAP_MKNOD
},
238 { "lease", CAP_LEASE
},
239 #ifdef CAP_AUDIT_READ
240 { "audit_read", CAP_AUDIT_READ
},
242 #ifdef CAP_AUDIT_WRITE
243 { "audit_write", CAP_AUDIT_WRITE
},
245 #ifdef CAP_AUDIT_CONTROL
246 { "audit_control", CAP_AUDIT_CONTROL
},
248 { "setfcap", CAP_SETFCAP
},
249 { "mac_override", CAP_MAC_OVERRIDE
},
250 { "mac_admin", CAP_MAC_ADMIN
},
252 { "syslog", CAP_SYSLOG
},
254 #ifdef CAP_WAKE_ALARM
255 { "wake_alarm", CAP_WAKE_ALARM
},
257 #ifdef CAP_BLOCK_SUSPEND
258 { "block_suspend", CAP_BLOCK_SUSPEND
},
262 static struct caps_opt caps_opt
[] = {};
265 static struct limit_opt limit_opt
[] = {
270 { "core", RLIMIT_CORE
},
273 { "cpu", RLIMIT_CPU
},
276 { "data", RLIMIT_DATA
},
279 { "fsize", RLIMIT_FSIZE
},
282 { "locks", RLIMIT_LOCKS
},
284 #ifdef RLIMIT_MEMLOCK
285 { "memlock", RLIMIT_MEMLOCK
},
287 #ifdef RLIMIT_MSGQUEUE
288 { "msgqueue", RLIMIT_MSGQUEUE
},
291 { "nice", RLIMIT_NICE
},
294 { "nofile", RLIMIT_NOFILE
},
297 { "nproc", RLIMIT_NPROC
},
300 { "rss", RLIMIT_RSS
},
303 { "rtprio", RLIMIT_RTPRIO
},
306 { "rttime", RLIMIT_RTTIME
},
308 #ifdef RLIMIT_SIGPENDING
309 { "sigpending", RLIMIT_SIGPENDING
},
312 { "stack", RLIMIT_STACK
},
316 static int run_buffer(char *buffer
)
318 struct lxc_popen_FILE
*f
;
322 f
= lxc_popen(buffer
);
324 SYSERROR("Failed to popen() %s.", buffer
);
328 output
= malloc(LXC_LOG_BUFFER_SIZE
);
330 ERROR("Failed to allocate memory for %s.", buffer
);
335 while (fgets(output
, LXC_LOG_BUFFER_SIZE
, f
->f
))
336 DEBUG("Script %s with output: %s.", buffer
, output
);
342 SYSERROR("Script exited with error.");
344 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
345 ERROR("Script exited with status %d.", WEXITSTATUS(ret
));
347 } else if (WIFSIGNALED(ret
)) {
348 ERROR("Script terminated by signal %d.", WTERMSIG(ret
));
355 static int run_script_argv(const char *name
, const char *section
,
356 const char *script
, const char *hook
,
357 const char *lxcpath
, char **argsin
)
363 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
364 script
, name
, section
);
366 for (i
= 0; argsin
&& argsin
[i
]; i
++)
367 size
+= strlen(argsin
[i
]) + 1;
369 size
+= strlen(hook
) + 1;
371 size
+= strlen(script
);
372 size
+= strlen(name
);
373 size
+= strlen(section
);
379 buffer
= alloca(size
);
381 ERROR("Failed to allocate memory.");
386 snprintf(buffer
, size
, "%s %s %s %s", script
, name
, section
, hook
);
387 if (ret
< 0 || (size_t)ret
>= size
) {
388 ERROR("Script name too long.");
392 for (i
= 0; argsin
&& argsin
[i
]; i
++) {
393 int len
= size
- ret
;
395 rc
= snprintf(buffer
+ ret
, len
, " %s", argsin
[i
]);
396 if (rc
< 0 || rc
>= len
) {
397 ERROR("Script args too long.");
403 return run_buffer(buffer
);
406 int run_script(const char *name
, const char *section
, const char *script
, ...)
413 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
414 script
, name
, section
);
416 va_start(ap
, script
);
417 while ((p
= va_arg(ap
, char *)))
418 size
+= strlen(p
) + 1;
421 size
+= strlen(script
);
422 size
+= strlen(name
);
423 size
+= strlen(section
);
429 buffer
= alloca(size
);
431 ERROR("Failed to allocate memory.");
435 ret
= snprintf(buffer
, size
, "%s %s %s", script
, name
, section
);
436 if (ret
< 0 || ret
>= size
) {
437 ERROR("Script name too long.");
441 va_start(ap
, script
);
442 while ((p
= va_arg(ap
, char *))) {
443 int len
= size
- ret
;
445 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
446 if (rc
< 0 || rc
>= len
) {
447 ERROR("Script args too long.");
454 return run_buffer(buffer
);
459 * if rootfs is a directory, then open ${rootfs}/lxc.hold for writing for
460 * the duration of the container run, to prevent the container from marking
461 * the underlying fs readonly on shutdown. unlink the file immediately so
462 * no name pollution is happens
463 * return -1 on error.
464 * return -2 if nothing needed to be pinned.
465 * return an open fd (>=0) if we pinned it.
467 int pin_rootfs(const char *rootfs
)
469 char absrootfs
[MAXPATHLEN
];
470 char absrootfspin
[MAXPATHLEN
];
474 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
477 if (!realpath(rootfs
, absrootfs
))
480 if (access(absrootfs
, F_OK
))
483 if (stat(absrootfs
, &s
))
486 if (!S_ISDIR(s
.st_mode
))
489 ret
= snprintf(absrootfspin
, MAXPATHLEN
, "%s/lxc.hold", absrootfs
);
490 if (ret
>= MAXPATHLEN
)
493 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
|S_IRUSR
);
496 (void)unlink(absrootfspin
);
501 * If we are asking to remount something, make sure that any
502 * NOEXEC etc are honored.
504 unsigned long add_required_remount_flags(const char *s
, const char *d
,
509 unsigned long required_flags
= 0;
511 if (!(flags
& MS_REMOUNT
))
519 if (statvfs(s
, &sb
) < 0)
522 if (sb
.f_flag
& MS_NOSUID
)
523 required_flags
|= MS_NOSUID
;
524 if (sb
.f_flag
& MS_NODEV
)
525 required_flags
|= MS_NODEV
;
526 if (sb
.f_flag
& MS_RDONLY
)
527 required_flags
|= MS_RDONLY
;
528 if (sb
.f_flag
& MS_NOEXEC
)
529 required_flags
|= MS_NOEXEC
;
531 return flags
| required_flags
;
537 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
545 const char *destination
;
549 } default_mounts
[] = {
550 /* Read-only bind-mounting... In older kernels, doing that required
551 * to do one MS_BIND mount and then MS_REMOUNT|MS_RDONLY the same
552 * one. According to mount(2) manpage, MS_BIND honors MS_RDONLY from
553 * kernel 2.6.26 onwards. However, this apparently does not work on
554 * kernel 3.8. Unfortunately, on that very same kernel, doing the
555 * same trick as above doesn't seem to work either, there one needs
556 * to ALSO specify MS_BIND for the remount, otherwise the entire
557 * fs is remounted read-only or the mount fails because it's busy...
558 * MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for kernels as low as
561 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
562 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
563 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
564 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
565 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
566 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
567 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
568 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
569 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
570 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
571 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
572 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
573 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
574 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
575 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
576 { 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
},
577 { 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
},
578 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
581 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
582 if ((flags
& default_mounts
[i
].match_mask
) == default_mounts
[i
].match_flag
) {
584 char *destination
= NULL
;
586 unsigned long mflags
;
588 if (default_mounts
[i
].source
) {
589 /* will act like strdup if %r is not present */
590 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
592 SYSERROR("memory allocation error");
596 if (!default_mounts
[i
].destination
) {
597 ERROR("BUG: auto mounts destination %d was NULL", i
);
601 /* will act like strdup if %r is not present */
602 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
605 SYSERROR("memory allocation error");
610 mflags
= add_required_remount_flags(source
, destination
,
611 default_mounts
[i
].flags
);
612 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
, mflags
, default_mounts
[i
].options
, conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
614 if (r
< 0 && errno
== ENOENT
) {
615 INFO("Mount source or target for %s on %s doesn't exist. Skipping.", source
, destination
);
619 SYSERROR("error mounting %s on %s flags %lu", source
, destination
, mflags
);
630 if (flags
& LXC_AUTO_CGROUP_MASK
) {
633 cg_flags
= flags
& LXC_AUTO_CGROUP_MASK
;
634 /* If the type of cgroup mount was not specified, it depends on the
635 * container's capabilities as to what makes sense: if we have
636 * CAP_SYS_ADMIN, the read-only part can be remounted read-write
637 * anyway, so we may as well default to read-write; then the admin
638 * will not be given a false sense of security. (And if they really
639 * want mixed r/o r/w, then they can explicitly specify :mixed.)
640 * OTOH, if the container lacks CAP_SYS_ADMIN, do only default to
641 * :mixed, because then the container can't remount it read-write. */
642 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
643 int has_sys_admin
= 0;
645 if (!lxc_list_empty(&conf
->keepcaps
))
646 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
648 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
650 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
651 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
653 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
656 if (!cgroup_mount(conf
->rootfs
.path
? conf
->rootfs
.mount
: "", handler
, cg_flags
)) {
657 SYSERROR("error mounting /sys/fs/cgroup");
665 static int setup_utsname(struct utsname
*utsname
)
670 if (sethostname(utsname
->nodename
, strlen(utsname
->nodename
))) {
671 SYSERROR("failed to set the hostname to '%s'", utsname
->nodename
);
675 INFO("'%s' hostname has been setup", utsname
->nodename
);
680 struct dev_symlinks
{
685 static const struct dev_symlinks dev_symlinks
[] = {
686 {"/proc/self/fd", "fd"},
687 {"/proc/self/fd/0", "stdin"},
688 {"/proc/self/fd/1", "stdout"},
689 {"/proc/self/fd/2", "stderr"},
692 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
694 char path
[MAXPATHLEN
];
699 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
700 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
701 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs
->path
? rootfs
->mount
: "", d
->name
);
702 if (ret
< 0 || ret
>= MAXPATHLEN
)
706 * Stat the path first. If we don't get an error
707 * accept it as is and don't try to create it
709 if (!stat(path
, &s
)) {
713 ret
= symlink(d
->oldpath
, path
);
715 if (ret
&& errno
!= EEXIST
) {
716 if ( errno
== EROFS
) {
717 WARN("Warning: Read Only file system while creating %s", path
);
719 SYSERROR("Error creating %s", path
);
727 /* Build a space-separate list of ptys to pass to systemd. */
728 static bool append_ptyname(char **pp
, char *name
)
733 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
736 sprintf(*pp
, "container_ttys=%s", name
);
739 p
= realloc(*pp
, strlen(*pp
) + strlen(name
) + 2);
748 static int lxc_setup_ttys(struct lxc_conf
*conf
)
751 const struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
752 char *ttydir
= conf
->ttydir
;
753 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
755 if (!conf
->rootfs
.path
)
758 for (i
= 0; i
< tty_info
->nbtty
; i
++) {
759 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
761 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
762 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
766 /* create dev/lxc/tty%d" */
767 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
768 "/dev/%s/tty%d", ttydir
, i
+ 1);
769 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
772 ret
= creat(lxcpath
, 0660);
773 if (ret
< 0 && errno
!= EEXIST
) {
774 SYSERROR("Failed to create \"%s\"", lxcpath
);
781 if (ret
< 0 && errno
!= ENOENT
) {
782 SYSERROR("Failed to unlink \"%s\"", path
);
786 ret
= mount(pty_info
->name
, lxcpath
, "none", MS_BIND
, 0);
788 WARN("Failed to bind mount \"%s\" onto \"%s\"",
789 pty_info
->name
, path
);
792 DEBUG("bind mounted \"%s\" onto \"%s\"", pty_info
->name
,
795 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
797 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
800 ret
= symlink(lxcpath
, path
);
802 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
807 /* If we populated /dev, then we need to create
810 ret
= access(path
, F_OK
);
812 ret
= creat(path
, 0660);
814 SYSERROR("Failed to create \"%s\"", path
);
815 /* this isn't fatal, continue */
821 ret
= mount(pty_info
->name
, path
, "none", MS_BIND
, 0);
823 SYSERROR("Failed to mount '%s'->'%s'", pty_info
->name
, path
);
827 DEBUG("Bind mounted \"%s\" onto \"%s\"", pty_info
->name
,
831 if (!append_ptyname(&conf
->pty_names
, pty_info
->name
)) {
832 ERROR("Error setting up container_ttys string");
837 INFO("Finished setting up %d /dev/tty<N> device(s)", tty_info
->nbtty
);
841 int lxc_allocate_ttys(const char *name
, struct lxc_conf
*conf
)
843 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
846 /* no tty in the configuration */
850 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
) * conf
->tty
);
851 if (!tty_info
->pty_info
) {
852 SYSERROR("failed to allocate struct *pty_info");
856 for (i
= 0; i
< conf
->tty
; i
++) {
857 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
860 ret
= openpty(&pty_info
->master
, &pty_info
->slave
,
861 pty_info
->name
, NULL
, NULL
);
864 SYSERROR("failed to create pty device number %d", i
);
866 lxc_delete_tty(tty_info
);
870 DEBUG("allocated pty \"%s\" with master fd %d and slave fd %d",
871 pty_info
->name
, pty_info
->master
, pty_info
->slave
);
873 /* Prevent leaking the file descriptors to the container */
874 ret
= fcntl(pty_info
->master
, F_SETFD
, FD_CLOEXEC
);
876 WARN("failed to set FD_CLOEXEC flag on master fd %d of "
877 "pty device \"%s\": %s",
878 pty_info
->master
, pty_info
->name
, strerror(errno
));
880 ret
= fcntl(pty_info
->slave
, F_SETFD
, FD_CLOEXEC
);
882 WARN("failed to set FD_CLOEXEC flag on slave fd %d of "
883 "pty device \"%s\": %s",
884 pty_info
->slave
, pty_info
->name
, strerror(errno
));
889 tty_info
->nbtty
= conf
->tty
;
891 INFO("finished allocating %d pts devices", conf
->tty
);
895 void lxc_delete_tty(struct lxc_tty_info
*tty_info
)
899 for (i
= 0; i
< tty_info
->nbtty
; i
++) {
900 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
902 close(pty_info
->master
);
903 close(pty_info
->slave
);
906 free(tty_info
->pty_info
);
907 tty_info
->pty_info
= NULL
;
911 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
914 struct lxc_conf
*conf
= handler
->conf
;
915 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
916 int sock
= handler
->data_sock
[0];
922 for (i
= 0; i
< conf
->tty
; i
++) {
924 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
926 ttyfds
[0] = pty_info
->master
;
927 ttyfds
[1] = pty_info
->slave
;
929 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
933 TRACE("Send pty \"%s\" with master fd %d and slave fd %d to "
934 "parent", pty_info
->name
, pty_info
->master
, pty_info
->slave
);
938 ERROR("Failed to send %d ttys to parent: %s", conf
->tty
,
941 TRACE("Sent %d ttys to parent", conf
->tty
);
946 static int lxc_create_ttys(struct lxc_handler
*handler
)
949 struct lxc_conf
*conf
= handler
->conf
;
951 ret
= lxc_allocate_ttys(handler
->name
, conf
);
953 ERROR("Failed to allocate ttys");
957 ret
= lxc_send_ttys_to_parent(handler
);
959 ERROR("Failed to send ttys to parent");
963 if (!conf
->is_execute
) {
964 ret
= lxc_setup_ttys(conf
);
966 ERROR("Failed to setup ttys");
971 if (conf
->pty_names
) {
972 ret
= setenv("container_ttys", conf
->pty_names
, 1);
974 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->pty_names
);
980 lxc_delete_tty(&conf
->tty_info
);
985 static int setup_rootfs_pivot_root(const char *rootfs
)
987 int oldroot
= -1, newroot
= -1;
989 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
991 SYSERROR("Error opening old-/ for fchdir");
994 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
);
996 SYSERROR("Error opening new-/ for fchdir");
1000 /* change into new root fs */
1001 if (fchdir(newroot
)) {
1002 SYSERROR("can't chdir to new rootfs '%s'", rootfs
);
1006 /* pivot_root into our new root fs */
1007 if (pivot_root(".", ".")) {
1008 SYSERROR("pivot_root syscall failed");
1013 * at this point the old-root is mounted on top of our new-root
1014 * To unmounted it we must not be chdir'd into it, so escape back
1017 if (fchdir(oldroot
) < 0) {
1018 SYSERROR("Error entering oldroot");
1021 if (umount2(".", MNT_DETACH
) < 0) {
1022 SYSERROR("Error detaching old root");
1026 if (fchdir(newroot
) < 0) {
1027 SYSERROR("Error re-entering newroot");
1034 DEBUG("pivot_root syscall to '%s' successful", rootfs
);
1046 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1047 * error, log it but don't fail yet.
1049 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1050 const char *lxcpath
)
1056 INFO("Preparing \"/dev\"");
1058 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1059 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1060 path
= alloca(clen
);
1062 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1063 if (ret
< 0 || (size_t)ret
>= clen
)
1066 if (!dir_exists(path
)) {
1067 WARN("\"/dev\" directory does not exist. Proceeding without "
1068 "autodev being set up");
1072 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1073 rootfs
->path
? rootfs
->mount
: NULL
);
1075 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1078 INFO("Mounted tmpfs on \"%s\"", path
);
1080 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1081 if (ret
< 0 || (size_t)ret
>= clen
)
1084 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1085 * If not, then create it and exit if that fails...
1087 if (!dir_exists(path
)) {
1088 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1090 SYSERROR("Failed to create directory \"%s\"", path
);
1095 INFO("Prepared \"/dev\"");
1106 static const struct lxc_devs lxc_devs
[] = {
1107 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1108 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1109 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1110 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1111 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1112 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1115 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1118 char path
[MAXPATHLEN
];
1122 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev",
1123 rootfs
->path
? rootfs
->mount
: "");
1124 if (ret
< 0 || ret
>= MAXPATHLEN
)
1127 /* ignore, just don't try to fill in */
1128 if (!dir_exists(path
))
1131 INFO("Populating \"/dev\"");
1133 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1134 for (i
= 0; i
< sizeof(lxc_devs
) / sizeof(lxc_devs
[0]); i
++) {
1135 const struct lxc_devs
*d
= &lxc_devs
[i
];
1137 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev/%s",
1138 rootfs
->path
? rootfs
->mount
: "", d
->name
);
1139 if (ret
< 0 || ret
>= MAXPATHLEN
)
1142 ret
= mknod(path
, d
->mode
, makedev(d
->maj
, d
->min
));
1145 char hostpath
[MAXPATHLEN
];
1147 if (errno
== EEXIST
) {
1148 DEBUG("\"%s\" device already existed", path
);
1152 /* Unprivileged containers cannot create devices, so
1153 * bind mount the device from the host.
1155 ret
= snprintf(hostpath
, MAXPATHLEN
, "/dev/%s", d
->name
);
1156 if (ret
< 0 || ret
>= MAXPATHLEN
)
1159 pathfile
= fopen(path
, "wb");
1161 SYSERROR("Failed to create file \"%s\"", path
);
1166 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1167 rootfs
->path
? rootfs
->mount
: NULL
);
1169 SYSERROR("Failed to bind mount \"%s\" from "
1170 "host into container",
1174 DEBUG("Bind mounted \"%s\" onto \"%s\"", hostpath
,
1177 DEBUG("Created device node \"%s\"", path
);
1182 INFO("Populated \"/dev\"");
1186 static int lxc_setup_rootfs(struct lxc_conf
*conf
)
1189 struct lxc_storage
*bdev
;
1190 const struct lxc_rootfs
*rootfs
;
1192 rootfs
= &conf
->rootfs
;
1193 if (!rootfs
->path
) {
1194 if (mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0)) {
1195 SYSERROR("Failed to make / rslave.");
1201 if (access(rootfs
->mount
, F_OK
)) {
1202 SYSERROR("Failed to access to \"%s\". Check it is present.",
1207 bdev
= storage_init(conf
);
1209 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1210 rootfs
->path
, rootfs
->mount
,
1211 rootfs
->options
? rootfs
->options
: "(null)");
1215 ret
= bdev
->ops
->mount(bdev
);
1218 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1219 rootfs
->path
, rootfs
->mount
,
1220 rootfs
->options
? rootfs
->options
: "(null)");
1224 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\".",
1225 rootfs
->path
, rootfs
->mount
,
1226 rootfs
->options
? rootfs
->options
: "(null)");
1231 int prepare_ramfs_root(char *root
)
1233 char buf
[LXC_LINELEN
], *p
;
1234 char nroot
[PATH_MAX
];
1239 if (realpath(root
, nroot
) == NULL
)
1242 if (chdir("/") == -1)
1246 * We could use here MS_MOVE, but in userns this mount is
1247 * locked and can't be moved.
1249 if (mount(root
, "/", NULL
, MS_REC
| MS_BIND
, NULL
) < 0) {
1250 SYSERROR("Failed to move %s into /", root
);
1254 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
) < 0) {
1255 SYSERROR("Failed to make . rprivate");
1260 * The following code cleans up inhereted mounts which are not
1263 * The mountinfo file shows not all mounts, if a few points have been
1264 * unmounted between read operations from the mountinfo. So we need to
1265 * read mountinfo a few times.
1267 * This loop can be skipped if a container uses unserns, because all
1268 * inherited mounts are locked and we should live with all this trash.
1273 f
= fopen("./proc/self/mountinfo", "r");
1275 SYSERROR("Unable to open /proc/self/mountinfo");
1278 while (fgets(buf
, LXC_LINELEN
, f
)) {
1279 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1280 p
= strchr(p
+1, ' ');
1283 p2
= strchr(p
+1, ' ');
1290 if (strcmp(p
+ 1, "/") == 0)
1292 if (strcmp(p
+ 1, "/proc") == 0)
1295 if (umount2(p
, MNT_DETACH
) == 0)
1303 /* This also can be skipped if a container uses unserns */
1304 umount2("./proc", MNT_DETACH
);
1306 /* It is weird, but chdir("..") moves us in a new root */
1307 if (chdir("..") == -1) {
1308 SYSERROR("Unable to change working directory");
1312 if (chroot(".") == -1) {
1313 SYSERROR("Unable to chroot");
1320 static int setup_pivot_root(const struct lxc_rootfs
*rootfs
)
1322 if (!rootfs
->path
) {
1323 DEBUG("container does not have a rootfs, so not doing pivot root");
1327 if (detect_ramfs_rootfs()) {
1328 DEBUG("detected that container is on ramfs");
1329 if (prepare_ramfs_root(rootfs
->mount
)) {
1330 ERROR("failed to prepare minimal ramfs root");
1334 DEBUG("prepared ramfs root for container");
1338 if (setup_rootfs_pivot_root(rootfs
->mount
) < 0) {
1339 ERROR("failed to pivot root");
1343 DEBUG("finished pivot root");
1347 static int lxc_setup_devpts(int num_pts
)
1350 const char *default_devpts_mntopts
= "newinstance,ptmxmode=0666,mode=0620,gid=5";
1351 char devpts_mntopts
[256];
1354 DEBUG("no new devpts instance will be mounted since no pts "
1355 "devices are requested");
1359 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%d",
1360 default_devpts_mntopts
, num_pts
);
1361 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1364 /* Unmount old devpts instance. */
1365 ret
= access("/dev/pts/ptmx", F_OK
);
1367 ret
= umount("/dev/pts");
1369 SYSERROR("failed to unmount old devpts instance");
1372 DEBUG("unmounted old /dev/pts instance");
1375 /* Create mountpoint for devpts instance. */
1376 ret
= mkdir("/dev/pts", 0755);
1377 if (ret
< 0 && errno
!= EEXIST
) {
1378 SYSERROR("failed to create the \"/dev/pts\" directory");
1382 /* Mount new devpts instance. */
1383 ret
= mount("devpts", "/dev/pts", "devpts", MS_MGC_VAL
, devpts_mntopts
);
1385 SYSERROR("failed to mount new devpts instance");
1388 DEBUG("mount new devpts instance with options \"%s\"", devpts_mntopts
);
1390 /* Remove any pre-existing /dev/ptmx file. */
1391 ret
= access("/dev/ptmx", F_OK
);
1393 ret
= remove("/dev/ptmx");
1395 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1398 DEBUG("removed existing \"/dev/ptmx\"");
1401 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1402 ret
= open("/dev/ptmx", O_CREAT
, 0666);
1404 SYSERROR("failed to create dummy \"/dev/ptmx\" file as bind mount target");
1408 DEBUG("created dummy \"/dev/ptmx\" file as bind mount target");
1410 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1411 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1413 DEBUG("bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1416 /* Fallthrough and try to create a symlink. */
1417 ERROR("failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1420 /* Remove the dummy /dev/ptmx file we created above. */
1421 ret
= remove("/dev/ptmx");
1423 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1427 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1428 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1430 SYSERROR("failed to create symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1433 DEBUG("created symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1438 static int setup_personality(int persona
)
1440 #if HAVE_SYS_PERSONALITY_H
1444 if (personality(persona
) < 0) {
1445 SYSERROR("failed to set personality to '0x%x'", persona
);
1449 INFO("set personality to '0x%x'", persona
);
1455 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1456 const struct lxc_console
*console
)
1458 char path
[MAXPATHLEN
];
1461 if (console
->path
&& !strcmp(console
->path
, "none"))
1464 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs
->mount
);
1465 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1468 /* When we are asked to setup a console we remove any previous
1469 * /dev/console bind-mounts.
1471 if (file_exists(path
)) {
1472 ret
= lxc_unstack_mountpoint(path
, false);
1474 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1477 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1482 SYSERROR("error unlinking %s", path
);
1487 /* For unprivileged containers autodev or automounts will already have
1488 * taken care of creating /dev/console.
1490 fd
= open(path
, O_CREAT
| O_EXCL
, S_IXUSR
| S_IXGRP
| S_IXOTH
);
1492 if (errno
!= EEXIST
) {
1493 SYSERROR("failed to create console");
1500 if (chmod(console
->name
, S_IXUSR
| S_IXGRP
| S_IXOTH
)) {
1501 SYSERROR("failed to set mode '0%o' to '%s'", S_IXUSR
| S_IXGRP
| S_IXOTH
, console
->name
);
1505 if (safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs
->mount
) < 0) {
1506 ERROR("failed to mount '%s' on '%s'", console
->name
, path
);
1510 DEBUG("mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1514 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1515 const struct lxc_console
*console
,
1519 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
1521 /* create rootfs/dev/<ttydir> directory */
1522 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs
->mount
, ttydir
);
1523 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1526 ret
= mkdir(path
, 0755);
1527 if (ret
&& errno
!= EEXIST
) {
1528 SYSERROR("failed with errno %d to create %s", errno
, path
);
1531 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1533 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs
->mount
, ttydir
);
1534 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1537 ret
= creat(lxcpath
, 0660);
1538 if (ret
== -1 && errno
!= EEXIST
) {
1539 SYSERROR("error %d creating %s", errno
, lxcpath
);
1545 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs
->mount
);
1546 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1549 /* When we are asked to setup a console we remove any previous
1550 * /dev/console bind-mounts.
1552 if (console
->path
&& !strcmp(console
->path
, "none")) {
1554 ret
= stat(path
, &st
);
1556 if (errno
== ENOENT
)
1558 SYSERROR("failed stat() \"%s\"", path
);
1562 /* /dev/console must be character device with major number 5 and
1563 * minor number 1. If not, give benefit of the doubt and assume
1564 * the user has mounted something else right there on purpose.
1566 if (((st
.st_mode
& S_IFMT
) != S_IFCHR
) || major(st
.st_rdev
) != 5 || minor(st
.st_rdev
) != 1)
1569 /* In case the user requested a bind-mount for /dev/console and
1570 * requests a ttydir we move the mount to the
1571 * /dev/<ttydir/console.
1572 * Note, we only move the uppermost mount and clear all other
1573 * mounts underneath for safety.
1574 * If it is a character device created via mknod() we simply
1577 ret
= safe_mount(path
, lxcpath
, "none", MS_MOVE
, NULL
, rootfs
->mount
);
1579 if (errno
!= EINVAL
) {
1580 ERROR("failed to MS_MOVE \"%s\" to \"%s\": %s", path
, lxcpath
, strerror(errno
));
1583 /* path was not a mountpoint */
1584 ret
= rename(path
, lxcpath
);
1586 ERROR("failed to rename \"%s\" to \"%s\": %s", path
, lxcpath
, strerror(errno
));
1589 DEBUG("renamed \"%s\" to \"%s\"", path
, lxcpath
);
1591 DEBUG("moved mount \"%s\" to \"%s\"", path
, lxcpath
);
1594 /* Clear all remaining bind-mounts. */
1595 ret
= lxc_unstack_mountpoint(path
, false);
1597 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1600 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1603 if (file_exists(path
)) {
1604 ret
= lxc_unstack_mountpoint(path
, false);
1606 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1609 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1613 if (safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs
->mount
) < 0) {
1614 ERROR("failed to mount '%s' on '%s'", console
->name
, lxcpath
);
1617 DEBUG("mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1620 /* create symlink from rootfs /dev/console to '<ttydir>/console' */
1621 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/console", ttydir
);
1622 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1626 if (ret
&& errno
!= ENOENT
) {
1627 SYSERROR("error unlinking %s", path
);
1631 ret
= symlink(lxcpath
, path
);
1633 SYSERROR("failed to create symlink for console from \"%s\" to \"%s\"", lxcpath
, path
);
1637 DEBUG("console has been setup under \"%s\" and symlinked to \"%s\"", lxcpath
, path
);
1641 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1642 const struct lxc_console
*console
, char *ttydir
)
1644 /* We don't have a rootfs, /dev/console will be shared. */
1645 if (!rootfs
->path
) {
1646 DEBUG("/dev/console will be shared with the host");
1651 return lxc_setup_dev_console(rootfs
, console
);
1653 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1656 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
)
1658 struct mount_opt
*mo
;
1660 /* If opt is found in mount_opt, set or clear flags.
1661 * Otherwise append it to data. */
1663 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1664 if (!strncmp(opt
, mo
->name
, strlen(mo
->name
))) {
1666 *flags
&= ~mo
->flag
;
1678 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
,
1682 char *p
, *saveptr
= NULL
;
1690 s
= strdup(mntopts
);
1692 SYSERROR("failed to allocate memory");
1696 data
= malloc(strlen(s
) + 1);
1698 SYSERROR("failed to allocate memory");
1704 for (p
= strtok_r(s
, ",", &saveptr
); p
!= NULL
;
1705 p
= strtok_r(NULL
, ",", &saveptr
))
1706 parse_mntopt(p
, mntflags
, &data
);
1717 static void null_endofword(char *word
)
1719 while (*word
&& *word
!= ' ' && *word
!= '\t')
1725 * skip @nfields spaces in @src
1727 static char *get_field(char *src
, int nfields
)
1732 for (i
= 0; i
< nfields
; i
++) {
1733 while (*p
&& *p
!= ' ' && *p
!= '\t')
1742 static int mount_entry(const char *fsname
, const char *target
,
1743 const char *fstype
, unsigned long mountflags
,
1744 const char *data
, int optional
, int dev
,
1752 ret
= safe_mount(fsname
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
1756 INFO("Failed to mount \"%s\" on \"%s\" (optional): %s",
1757 fsname
, target
, strerror(errno
));
1761 SYSERROR("Failed to mount \"%s\" on \"%s\"", fsname
, target
);
1765 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
1766 unsigned long rqd_flags
= 0;
1768 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
1770 fsname
? fsname
: "(none)", target
? target
: "(none)");
1772 if (mountflags
& MS_RDONLY
)
1773 rqd_flags
|= MS_RDONLY
;
1775 if (statvfs(fsname
, &sb
) == 0) {
1776 unsigned long required_flags
= rqd_flags
;
1778 if (sb
.f_flag
& MS_NOSUID
)
1779 required_flags
|= MS_NOSUID
;
1781 if (sb
.f_flag
& MS_NODEV
&& !dev
)
1782 required_flags
|= MS_NODEV
;
1784 if (sb
.f_flag
& MS_RDONLY
)
1785 required_flags
|= MS_RDONLY
;
1787 if (sb
.f_flag
& MS_NOEXEC
)
1788 required_flags
|= MS_NOEXEC
;
1790 DEBUG("Flags for \"%s\" were %lu, required extra flags "
1791 "are %lu", fsname
, sb
.f_flag
, required_flags
);
1793 /* If this was a bind mount request, and required_flags
1794 * does not have any flags which are not already in
1795 * mountflags, then skip the remount.
1797 if (!(mountflags
& MS_REMOUNT
)) {
1798 if (!(required_flags
& ~mountflags
) &&
1800 DEBUG("Mountflags already were %lu, "
1801 "skipping remount", mountflags
);
1806 mountflags
|= required_flags
;
1810 ret
= mount(fsname
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
1813 INFO("Failed to mount \"%s\" on \"%s\" "
1814 "(optional): %s", fsname
, target
,
1819 SYSERROR("Failed to mount \"%s\" on \"%s\"", fsname
, target
);
1827 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"", fsname
,
1833 /* Remove "optional", "create=dir", and "create=file" from mntopt */
1834 static void cull_mntent_opt(struct mntent
*mntent
)
1837 char *list
[] = {"create=dir", "create=file", "optional", NULL
};
1839 for (i
= 0; list
[i
]; i
++) {
1842 p
= strstr(mntent
->mnt_opts
, list
[i
]);
1846 p2
= strchr(p
, ',');
1848 /* no more mntopts, so just chop it here */
1853 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
1857 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
1859 const struct lxc_rootfs
*rootfs
,
1860 const char *lxc_name
,
1861 const char *lxc_path
)
1865 if (!strncmp(mntent
->mnt_type
, "overlay", 7))
1866 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
1867 else if (!strncmp(mntent
->mnt_type
, "aufs", 4))
1868 ret
= aufs_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
1872 if (hasmntopt(mntent
, "create=dir")) {
1873 ret
= mkdir_p(path
, 0755);
1874 if (ret
< 0 && errno
!= EEXIST
) {
1875 SYSERROR("Failed to create directory \"%s\"", path
);
1880 if (hasmntopt(mntent
, "create=file") && access(path
, F_OK
)) {
1890 ret
= mkdir_p(p2
, 0755);
1892 if (ret
< 0 && errno
!= EEXIST
) {
1893 SYSERROR("Failed to create directory \"%s\"", path
);
1897 fd
= open(path
, O_CREAT
, 0644);
1906 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
1907 * without a rootfs. */
1908 static inline int mount_entry_on_generic(struct mntent
*mntent
,
1910 const struct lxc_rootfs
*rootfs
,
1911 const char *lxc_name
,
1912 const char *lxc_path
)
1915 unsigned long mntflags
;
1918 char *rootfs_path
= NULL
;
1920 optional
= hasmntopt(mntent
, "optional") != NULL
;
1921 dev
= hasmntopt(mntent
, "dev") != NULL
;
1923 if (rootfs
&& rootfs
->path
)
1924 rootfs_path
= rootfs
->mount
;
1926 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
1934 cull_mntent_opt(mntent
);
1936 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
1940 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
1941 mntdata
, optional
, dev
, rootfs_path
);
1947 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
1950 char path
[MAXPATHLEN
];
1952 /* For containers created without a rootfs all mounts are treated as
1953 * absolute paths starting at / on the host.
1955 if (mntent
->mnt_dir
[0] != '/')
1956 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
1958 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
1959 if (ret
< 0 || ret
>= sizeof(path
))
1962 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
1965 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
1966 const struct lxc_rootfs
*rootfs
,
1967 const char *lxc_name
,
1968 const char *lxc_path
)
1972 const char *lxcpath
;
1973 char path
[MAXPATHLEN
];
1976 lxcpath
= lxc_global_config_value("lxc.lxcpath");
1980 /* If rootfs->path is a blockdev path, allow container fstab to use
1981 * <lxcpath>/<name>/rootfs" as the target prefix.
1983 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, lxc_name
);
1984 if (ret
< 0 || ret
>= MAXPATHLEN
)
1987 aux
= strstr(mntent
->mnt_dir
, path
);
1989 offset
= strlen(path
);
1994 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
1996 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
1999 offset
= strlen(rootfs
->path
);
2002 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2003 if (ret
< 0 || ret
>= MAXPATHLEN
)
2006 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2009 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2010 const struct lxc_rootfs
*rootfs
,
2011 const char *lxc_name
,
2012 const char *lxc_path
)
2014 char path
[MAXPATHLEN
];
2017 /* relative to root mount point */
2018 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2019 if (ret
< 0 || ret
>= sizeof(path
)) {
2020 ERROR("path name too long");
2024 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2027 /* This logs a NOTICE() when a user specifies mounts that would conflict with
2028 * devices liblxc sets up automatically.
2030 static void log_notice_on_conflict(const struct lxc_conf
*conf
, const char *src
,
2033 char *clean_mnt_fsname
, *clean_mnt_dir
, *tmp
;
2034 bool needs_warning
= false;
2036 clean_mnt_fsname
= lxc_deslashify(src
);
2037 if (!clean_mnt_fsname
)
2040 clean_mnt_dir
= lxc_deslashify(dest
);
2041 if (!clean_mnt_dir
) {
2042 free(clean_mnt_fsname
);
2046 tmp
= clean_mnt_dir
;
2050 if (strncmp(src
, "/dev", 4) || strncmp(tmp
, "dev", 3)) {
2051 free(clean_mnt_dir
);
2052 free(clean_mnt_fsname
);
2056 if (!conf
->autodev
&& !conf
->pts
&& !conf
->tty
&&
2057 (!conf
->console
.path
|| !strcmp(conf
->console
.path
, "none"))) {
2058 free(clean_mnt_dir
);
2059 free(clean_mnt_fsname
);
2063 if (!strcmp(tmp
, "dev") && conf
->autodev
> 0)
2064 needs_warning
= true;
2065 else if (!strcmp(tmp
, "dev/pts") && (conf
->autodev
> 0 || conf
->pts
> 0))
2066 needs_warning
= true;
2067 else if (!strcmp(tmp
, "dev/ptmx") && (conf
->autodev
> 0 || conf
->pts
> 0))
2068 needs_warning
= true;
2069 else if (!strcmp(tmp
, "dev/pts/ptmx") && (conf
->autodev
> 0 || conf
->pts
> 0))
2070 needs_warning
= true;
2071 else if (!strcmp(tmp
, "dev/null") && conf
->autodev
> 0)
2072 needs_warning
= true;
2073 else if (!strcmp(tmp
, "dev/zero") && conf
->autodev
> 0)
2074 needs_warning
= true;
2075 else if (!strcmp(tmp
, "dev/full") && conf
->autodev
> 0)
2076 needs_warning
= true;
2077 else if (!strcmp(tmp
, "dev/urandom") && conf
->autodev
> 0)
2078 needs_warning
= true;
2079 else if (!strcmp(tmp
, "dev/random") && conf
->autodev
> 0)
2080 needs_warning
= true;
2081 else if (!strcmp(tmp
, "dev/tty") && conf
->autodev
> 0)
2082 needs_warning
= true;
2083 else if (!strncmp(tmp
, "dev/tty", 7) && (conf
->autodev
> 0 || conf
->tty
> 0))
2084 needs_warning
= true;
2087 NOTICE("Requesting to mount \"%s\" on \"%s\" while requesting "
2088 "automatic device setup under \"/dev\"",
2089 clean_mnt_fsname
, clean_mnt_dir
);
2091 free(clean_mnt_dir
);
2092 free(clean_mnt_fsname
);
2095 static int mount_file_entries(const struct lxc_conf
*conf
,
2096 const struct lxc_rootfs
*rootfs
, FILE *file
,
2097 const char *lxc_name
, const char *lxc_path
)
2099 struct mntent mntent
;
2103 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2104 log_notice_on_conflict(conf
, mntent
.mnt_fsname
, mntent
.mnt_dir
);
2107 ret
= mount_entry_on_systemfs(&mntent
);
2108 else if (mntent
.mnt_dir
[0] != '/')
2109 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2110 lxc_name
, lxc_path
);
2112 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2113 lxc_name
, lxc_path
);
2119 INFO("Set up mount entries");
2123 static int setup_mount(const struct lxc_conf
*conf
,
2124 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2125 const char *lxc_name
, const char *lxc_path
)
2133 f
= setmntent(fstab
, "r");
2135 SYSERROR("Failed to open \"%s\"", fstab
);
2139 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2141 ERROR("Failed to set up mount entries");
2147 FILE *make_anonymous_mount_file(struct lxc_list
*mount
)
2151 struct lxc_list
*iterator
;
2155 fd
= memfd_create("lxc_mount_file", MFD_CLOEXEC
);
2157 if (errno
!= ENOSYS
)
2160 TRACE("Created temporary mount file");
2162 f
= fdopen(fd
, "r+");
2163 TRACE("Created anonymous mount file");
2167 SYSERROR("Could not create mount file");
2173 lxc_list_for_each(iterator
, mount
) {
2174 mount_entry
= iterator
->elem
;
2175 ret
= fprintf(f
, "%s\n", mount_entry
);
2176 if (ret
< strlen(mount_entry
))
2177 WARN("Could not write mount entry to mount file");
2180 ret
= fseek(f
, 0, SEEK_SET
);
2182 SYSERROR("Failed to seek mount file");
2190 static int setup_mount_entries(const struct lxc_conf
*conf
,
2191 const struct lxc_rootfs
*rootfs
,
2192 struct lxc_list
*mount
, const char *lxc_name
,
2193 const char *lxc_path
)
2198 f
= make_anonymous_mount_file(mount
);
2202 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2208 static int parse_cap(const char *cap
)
2214 if (!strcmp(cap
, "none"))
2217 for (i
= 0; i
< sizeof(caps_opt
)/sizeof(caps_opt
[0]); i
++) {
2219 if (strcmp(cap
, caps_opt
[i
].name
))
2222 capid
= caps_opt
[i
].value
;
2227 /* try to see if it's numeric, so the user may specify
2228 * capabilities that the running kernel knows about but
2231 capid
= strtol(cap
, &ptr
, 10);
2232 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2233 /* not a valid number */
2235 else if (capid
> lxc_caps_last_cap())
2236 /* we have a number but it's not a valid
2244 int in_caplist(int cap
, struct lxc_list
*caps
)
2246 struct lxc_list
*iterator
;
2249 lxc_list_for_each(iterator
, caps
) {
2250 capid
= parse_cap(iterator
->elem
);
2258 static int setup_caps(struct lxc_list
*caps
)
2260 struct lxc_list
*iterator
;
2264 lxc_list_for_each(iterator
, caps
) {
2266 drop_entry
= iterator
->elem
;
2268 capid
= parse_cap(drop_entry
);
2271 ERROR("unknown capability %s", drop_entry
);
2275 DEBUG("drop capability '%s' (%d)", drop_entry
, capid
);
2277 if (prctl(PR_CAPBSET_DROP
, capid
, 0, 0, 0)) {
2278 SYSERROR("failed to remove %s capability", drop_entry
);
2284 DEBUG("capabilities have been setup");
2289 static int dropcaps_except(struct lxc_list
*caps
)
2291 struct lxc_list
*iterator
;
2294 int numcaps
= lxc_caps_last_cap() + 1;
2295 INFO("found %d capabilities", numcaps
);
2297 if (numcaps
<= 0 || numcaps
> 200)
2300 /* caplist[i] is 1 if we keep capability i */
2301 int *caplist
= alloca(numcaps
* sizeof(int));
2302 memset(caplist
, 0, numcaps
* sizeof(int));
2304 lxc_list_for_each(iterator
, caps
) {
2306 keep_entry
= iterator
->elem
;
2308 capid
= parse_cap(keep_entry
);
2314 ERROR("unknown capability %s", keep_entry
);
2318 DEBUG("keep capability '%s' (%d)", keep_entry
, capid
);
2322 for (i
=0; i
<numcaps
; i
++) {
2325 if (prctl(PR_CAPBSET_DROP
, i
, 0, 0, 0)) {
2326 SYSERROR("failed to remove capability %d", i
);
2331 DEBUG("capabilities have been setup");
2336 static int parse_resource(const char *res
) {
2340 for (i
= 0; i
< sizeof(limit_opt
)/sizeof(limit_opt
[0]); ++i
) {
2341 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2342 return limit_opt
[i
].value
;
2345 /* try to see if it's numeric, so the user may specify
2346 * resources that the running kernel knows about but
2348 if (lxc_safe_int(res
, &resid
) == 0)
2353 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
) {
2354 struct lxc_list
*it
;
2355 struct lxc_limit
*lim
;
2358 lxc_list_for_each(it
, limits
) {
2361 resid
= parse_resource(lim
->resource
);
2363 ERROR("unknown resource %s", lim
->resource
);
2367 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2368 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2369 ERROR("failed to set limit %s: %s", lim
->resource
, strerror(errno
));
2373 ERROR("Cannot set limit %s as prlimit is missing", lim
->resource
);
2380 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2382 struct lxc_conf
*lxc_conf_init(void)
2384 struct lxc_conf
*new;
2387 new = malloc(sizeof(*new));
2389 ERROR("lxc_conf_init : %s", strerror(errno
));
2392 memset(new, 0, sizeof(*new));
2394 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2395 new->personality
= -1;
2397 new->console
.buffer_log_file
= NULL
;
2398 new->console
.buffer_log_file_fd
= -1;
2399 new->console
.buffer_size
= 0;
2400 new->console
.log_path
= NULL
;
2401 new->console
.log_fd
= -1;
2402 new->console
.path
= NULL
;
2403 new->console
.peer
= -1;
2404 new->console
.peerpty
.busy
= -1;
2405 new->console
.peerpty
.master
= -1;
2406 new->console
.peerpty
.slave
= -1;
2407 new->console
.master
= -1;
2408 new->console
.slave
= -1;
2409 new->console
.name
[0] = '\0';
2410 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2411 new->maincmd_fd
= -1;
2413 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2414 if (!new->rootfs
.mount
) {
2415 ERROR("lxc_conf_init : %s", strerror(errno
));
2420 lxc_list_init(&new->cgroup
);
2421 lxc_list_init(&new->network
);
2422 lxc_list_init(&new->mount_list
);
2423 lxc_list_init(&new->caps
);
2424 lxc_list_init(&new->keepcaps
);
2425 lxc_list_init(&new->id_map
);
2426 lxc_list_init(&new->includes
);
2427 lxc_list_init(&new->aliens
);
2428 lxc_list_init(&new->environment
);
2429 lxc_list_init(&new->limits
);
2430 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2431 lxc_list_init(&new->hooks
[i
]);
2432 lxc_list_init(&new->groups
);
2433 new->lsm_aa_profile
= NULL
;
2434 new->lsm_se_context
= NULL
;
2435 new->tmp_umount_proc
= 0;
2437 /* if running in a new user namespace, init and COMMAND
2438 * default to running as UID/GID 0 when using lxc-execute */
2441 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2442 memset(&new->inherit_ns
, 0, sizeof(char *) * LXC_NS_MAX
);
2447 static int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2450 char path
[MAXPATHLEN
];
2453 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/%cid_map", pid
,
2454 idtype
== ID_TYPE_UID
? 'u' : 'g');
2455 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2456 ERROR("failed to create path \"%s\"", path
);
2460 fd
= open(path
, O_WRONLY
);
2462 SYSERROR("failed to open \"%s\"", path
);
2467 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2468 if (ret
!= buf_size
) {
2469 SYSERROR("failed to write %cid mapping to \"%s\"",
2470 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2479 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2481 * @return 1 if functional binary was found
2482 * @return 0 if binary exists but is lacking privilege
2483 * @return -ENOENT if binary does not exist
2484 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2487 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2494 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2497 path
= on_path(binary
, NULL
);
2501 ret
= stat(path
, &st
);
2507 /* Check if the binary is setuid. */
2508 if (st
.st_mode
& S_ISUID
) {
2509 DEBUG("The binary \"%s\" does have the setuid bit set.", path
);
2514 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2515 /* Check if it has the CAP_SETUID capability. */
2516 if ((cap
& CAP_SETUID
) &&
2517 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2518 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2519 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2520 "and CAP_PERMITTED sets.", path
);
2525 /* Check if it has the CAP_SETGID capability. */
2526 if ((cap
& CAP_SETGID
) &&
2527 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2528 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2529 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2530 "and CAP_PERMITTED sets.", path
);
2535 /* If we cannot check for file capabilities we need to give the benefit
2536 * of the doubt. Otherwise we might fail even though all the necessary
2537 * file capabilities are set.
2539 DEBUG("Cannot check for file capabilites as full capability support is "
2540 "missing. Manual intervention needed.");
2549 int lxc_map_ids_exec_wrapper(void *args
)
2551 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2555 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2558 struct lxc_list
*iterator
;
2563 char cmd_output
[MAXPATHLEN
];
2564 /* strlen("new@idmap") = 9
2572 * We add some additional space to make sure that we really have
2573 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2575 char mapbuf
[9 + 1 + LXC_NUMSTRLEN64
+ 1 + LXC_IDMAPLEN
] = {0};
2576 int ret
= 0, uidmap
= 0, gidmap
= 0;
2577 bool use_shadow
= false, had_entry
= false;
2579 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2580 * ranges, then insist that root also reserve ranges in subuid. This
2581 * will protected it by preventing another user from being handed the
2584 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2585 if (uidmap
== -ENOENT
)
2586 WARN("newuidmap binary is missing");
2588 WARN("newuidmap is lacking necessary privileges");
2590 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2591 if (gidmap
== -ENOENT
)
2592 WARN("newgidmap binary is missing");
2594 WARN("newgidmap is lacking necessary privileges");
2596 if (uidmap
> 0 && gidmap
> 0) {
2597 DEBUG("Functional newuidmap and newgidmap binary found.");
2600 /* In case unprivileged users run application containers via
2601 * execute() or a start*() there are valid cases where they may
2602 * only want to map their own {g,u}id. Let's not block them from
2603 * doing so by requiring geteuid() == 0.
2605 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2606 "write directly with euid %d.", geteuid());
2609 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
2610 type
++, u_or_g
= 'g') {
2614 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
2616 lxc_list_for_each(iterator
, idmap
) {
2617 map
= iterator
->elem
;
2618 if (map
->idtype
!= type
)
2623 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
2624 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
2625 use_shadow
? " " : "", map
->nsid
,
2626 map
->hostid
, map
->range
,
2627 use_shadow
? "" : "\n");
2628 if (fill
<= 0 || fill
>= left
) {
2629 /* The kernel only takes <= 4k for writes to
2630 * /proc/<pid>/{g,u}id_map
2632 SYSERROR("Too many %cid mappings defined", u_or_g
);
2641 /* Try to catch the ouput of new{g,u}idmap to make debugging
2645 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2646 lxc_map_ids_exec_wrapper
,
2649 ERROR("new%cidmap failed to write mapping \"%s\": %s",
2650 u_or_g
, cmd_output
, mapbuf
);
2653 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
2655 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
2657 ERROR("Failed to write mapping: %s", mapbuf
);
2660 TRACE("Wrote mapping \"%s\"", mapbuf
);
2663 memset(mapbuf
, 0, sizeof(mapbuf
));
2670 * return the host uid/gid to which the container root is mapped in
2672 * Return true if id was found, false otherwise.
2674 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
2677 struct lxc_list
*it
;
2680 lxc_list_for_each(it
, &conf
->id_map
) {
2682 if (map
->idtype
!= idtype
)
2692 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
2694 struct lxc_list
*it
;
2696 lxc_list_for_each(it
, &conf
->id_map
) {
2698 if (map
->idtype
!= idtype
)
2700 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
2701 return (id
- map
->hostid
) + map
->nsid
;
2706 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
2708 struct lxc_list
*it
;
2710 unsigned int freeid
= 0;
2712 lxc_list_for_each(it
, &conf
->id_map
) {
2714 if (map
->idtype
!= idtype
)
2716 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
2717 freeid
= map
->nsid
+ map
->range
;
2724 int chown_mapped_root_exec_wrapper(void *args
)
2726 execvp("lxc-usernsexec", args
);
2731 * chown_mapped_root: for an unprivileged user with uid/gid X to
2732 * chown a dir to subuid/subgid Y, he needs to run chown as root
2733 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
2734 * nsid Y is mapped to hostuid/hostgid X. That way, the container
2735 * root is privileged with respect to hostuid/hostgid X, allowing
2736 * him to do the chown.
2738 int chown_mapped_root(const char *path
, struct lxc_conf
*conf
)
2740 uid_t rootuid
, rootgid
;
2742 int hostuid
, hostgid
, ret
;
2744 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
2746 const char *args1
[] = {"lxc-usernsexec",
2751 "--", "chown", ugid
, path
,
2753 const char *args2
[] = {"lxc-usernsexec",
2759 "--", "chown", ugid
, path
,
2761 char cmd_output
[MAXPATHLEN
];
2763 hostuid
= geteuid();
2764 hostgid
= getegid();
2766 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
2767 ERROR("No uid mapping for container root");
2770 rootuid
= (uid_t
)val
;
2771 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
2772 ERROR("No gid mapping for container root");
2775 rootgid
= (gid_t
)val
;
2778 if (chown(path
, rootuid
, rootgid
) < 0) {
2779 ERROR("Error chowning %s", path
);
2785 if (rootuid
== hostuid
) {
2787 INFO("Container root is our uid; no need to chown");
2791 /* save the current gid of "path" */
2792 if (stat(path
, &sb
) < 0) {
2793 ERROR("Error stat %s", path
);
2797 /* Update the path argument in case this was overlayfs. */
2798 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
2799 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
2802 * A file has to be group-owned by a gid mapped into the
2803 * container, or the container won't be privileged over it.
2805 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
2806 if (sb
.st_uid
== hostuid
&&
2807 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
2808 chown(path
, -1, hostgid
) < 0) {
2809 ERROR("Failed chgrping %s", path
);
2813 /* "u:0:rootuid:1" */
2814 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
2815 if (ret
< 0 || ret
>= 100) {
2816 ERROR("Error uid printing map string");
2820 /* "u:hostuid:hostuid:1" */
2821 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
2822 if (ret
< 0 || ret
>= 100) {
2823 ERROR("Error uid printing map string");
2827 /* "g:0:rootgid:1" */
2828 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
2829 if (ret
< 0 || ret
>= 100) {
2830 ERROR("Error gid printing map string");
2834 /* "g:pathgid:rootgid+pathgid:1" */
2835 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
2836 rootgid
+ (gid_t
)sb
.st_gid
);
2837 if (ret
< 0 || ret
>= 100) {
2838 ERROR("Error gid printing map string");
2842 /* "g:hostgid:hostgid:1" */
2843 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
2844 if (ret
< 0 || ret
>= 100) {
2845 ERROR("Error gid printing map string");
2849 /* "0:pathgid" (chown) */
2850 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
2851 if (ret
< 0 || ret
>= 100) {
2852 ERROR("Error owner printing format string for chown");
2856 if (hostgid
== sb
.st_gid
)
2857 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2858 chown_mapped_root_exec_wrapper
,
2861 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2862 chown_mapped_root_exec_wrapper
,
2865 ERROR("lxc-usernsexec failed: %s", cmd_output
);
2870 int lxc_ttys_shift_ids(struct lxc_conf
*c
)
2872 if (lxc_list_empty(&c
->id_map
))
2875 if (!strcmp(c
->console
.name
, ""))
2878 if (chown_mapped_root(c
->console
.name
, c
) < 0) {
2879 ERROR("failed to chown console \"%s\"", c
->console
.name
);
2883 TRACE("chowned console \"%s\"", c
->console
.name
);
2888 /* NOTE: Must not be called from inside the container namespace! */
2889 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
2893 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
2894 if (mounted
== -1) {
2895 SYSERROR("failed to mount /proc in the container");
2896 /* continue only if there is no rootfs */
2897 if (conf
->rootfs
.path
)
2899 } else if (mounted
== 1) {
2900 conf
->tmp_umount_proc
= 1;
2906 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
2908 if (lxc_conf
->tmp_umount_proc
== 1) {
2910 lxc_conf
->tmp_umount_proc
= 0;
2914 void remount_all_slave(void)
2916 /* walk /proc/mounts and change any shared entries to slave */
2917 FILE *f
= fopen("/proc/self/mountinfo", "r");
2922 SYSERROR("Failed to open /proc/self/mountinfo to mark all shared");
2923 ERROR("Continuing container startup...");
2927 while (getline(&line
, &len
, f
) != -1) {
2928 char *target
, *opts
;
2929 target
= get_field(line
, 4);
2932 opts
= get_field(target
, 2);
2935 null_endofword(opts
);
2936 if (!strstr(opts
, "shared"))
2938 null_endofword(target
);
2939 if (mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
)) {
2940 SYSERROR("Failed to make %s rslave", target
);
2941 ERROR("Continuing...");
2948 void lxc_execute_bind_init(struct lxc_conf
*conf
)
2951 char path
[PATH_MAX
], destpath
[PATH_MAX
], *p
;
2953 /* If init exists in the container, don't bind mount a static one */
2954 p
= choose_init(conf
->rootfs
.mount
);
2960 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
2961 if (ret
< 0 || ret
>= PATH_MAX
) {
2962 WARN("Path name too long searching for lxc.init.static");
2966 if (!file_exists(path
)) {
2967 INFO("%s does not exist on host", path
);
2971 ret
= snprintf(destpath
, PATH_MAX
, "%s%s", conf
->rootfs
.mount
, "/init.lxc.static");
2972 if (ret
< 0 || ret
>= PATH_MAX
) {
2973 WARN("Path name too long for container's lxc.init.static");
2977 if (!file_exists(destpath
)) {
2978 FILE * pathfile
= fopen(destpath
, "wb");
2980 SYSERROR("Failed to create mount target '%s'", destpath
);
2986 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
2988 SYSERROR("Failed to bind lxc.init.static into container");
2989 INFO("lxc.init.static bound into container at %s", path
);
2993 * This does the work of remounting / if it is shared, calling the
2994 * container pre-mount hooks, and mounting the rootfs.
2996 int do_rootfs_setup(struct lxc_conf
*conf
, const char *name
, const char *lxcpath
)
2998 if (conf
->rootfs_setup
) {
3000 * rootfs was set up in another namespace. bind-mount it
3001 * to give us a mount in our own ns so we can pivot_root to it
3003 const char *path
= conf
->rootfs
.mount
;
3004 if (mount(path
, path
, "rootfs", MS_BIND
, NULL
) < 0) {
3005 ERROR("Failed to bind-mount container / onto itself");
3011 remount_all_slave();
3013 if (run_lxc_hooks(name
, "pre-mount", conf
, lxcpath
, NULL
)) {
3014 ERROR("failed to run pre-mount hooks for container '%s'.", name
);
3018 if (lxc_setup_rootfs(conf
)) {
3019 ERROR("failed to setup rootfs for '%s'", name
);
3023 conf
->rootfs_setup
= true;
3027 static bool verify_start_hooks(struct lxc_conf
*conf
)
3029 struct lxc_list
*it
;
3030 char path
[MAXPATHLEN
];
3031 lxc_list_for_each(it
, &conf
->hooks
[LXCHOOK_START
]) {
3032 char *hookname
= it
->elem
;
3036 ret
= snprintf(path
, MAXPATHLEN
, "%s%s",
3037 conf
->rootfs
.path
? conf
->rootfs
.mount
: "", hookname
);
3038 if (ret
< 0 || ret
>= MAXPATHLEN
)
3040 ret
= stat(path
, &st
);
3042 SYSERROR("Start hook %s not found in container",
3052 int lxc_setup(struct lxc_handler
*handler
)
3055 const char *name
= handler
->name
;
3056 struct lxc_conf
*lxc_conf
= handler
->conf
;
3057 const char *lxcpath
= handler
->lxcpath
;
3059 if (do_rootfs_setup(lxc_conf
, name
, lxcpath
) < 0) {
3060 ERROR("Error setting up rootfs mount after spawn");
3064 if (handler
->nsfd
[LXC_NS_UTS
] == -1) {
3065 if (setup_utsname(lxc_conf
->utsname
)) {
3066 ERROR("failed to setup the utsname for '%s'", name
);
3071 if (lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
)) {
3072 ERROR("failed to setup the network for '%s'", name
);
3076 if (lxc_network_send_name_and_ifindex_to_parent(handler
) < 0) {
3077 ERROR("Failed to network device names and ifindices to parent");
3081 if (lxc_conf
->autodev
> 0) {
3082 if (mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
)) {
3083 ERROR("failed to mount /dev in the container");
3088 /* do automatic mounts (mainly /proc and /sys), but exclude
3089 * those that need to wait until other stuff has finished
3091 if (lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
) < 0) {
3092 ERROR("failed to setup the automatic mounts for '%s'", name
);
3096 if (setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
)) {
3097 ERROR("failed to setup the mounts for '%s'", name
);
3101 if (!lxc_list_empty(&lxc_conf
->mount_list
) && setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
, &lxc_conf
->mount_list
, name
, lxcpath
)) {
3102 ERROR("failed to setup the mount entries for '%s'", name
);
3106 /* Make sure any start hooks are in the container */
3107 if (!verify_start_hooks(lxc_conf
))
3110 if (lxc_conf
->is_execute
)
3111 lxc_execute_bind_init(lxc_conf
);
3113 /* now mount only cgroup, if wanted;
3114 * before, /sys could not have been mounted
3115 * (is either mounted automatically or via fstab entries)
3117 if (lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
) < 0) {
3118 ERROR("failed to setup the automatic mounts for '%s'", name
);
3122 if (run_lxc_hooks(name
, "mount", lxc_conf
, lxcpath
, NULL
)) {
3123 ERROR("failed to run mount hooks for container '%s'.", name
);
3127 if (lxc_conf
->autodev
> 0) {
3128 if (run_lxc_hooks(name
, "autodev", lxc_conf
, lxcpath
, NULL
)) {
3129 ERROR("failed to run autodev hooks for container '%s'.", name
);
3133 if (lxc_fill_autodev(&lxc_conf
->rootfs
)) {
3134 ERROR("failed to populate /dev in the container");
3139 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3142 ERROR("Failed to setup console");
3146 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3148 ERROR("Failed to setup /dev symlinks");
3152 /* mount /proc if it's not already there */
3153 if (lxc_create_tmp_proc_mount(lxc_conf
) < 0) {
3154 ERROR("failed to LSM mount proc for '%s'", name
);
3158 if (setup_pivot_root(&lxc_conf
->rootfs
)) {
3159 ERROR("failed to set rootfs for '%s'", name
);
3163 if (lxc_setup_devpts(lxc_conf
->pts
)) {
3164 ERROR("failed to setup the new pts instance");
3168 ret
= lxc_create_ttys(handler
);
3172 if (setup_personality(lxc_conf
->personality
)) {
3173 ERROR("failed to setup personality");
3177 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3178 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3179 ERROR("Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both.");
3182 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3183 ERROR("failed to keep requested caps");
3186 } else if (setup_caps(&lxc_conf
->caps
)) {
3187 ERROR("failed to drop capabilities");
3191 NOTICE("Container \"%s\" is set up", name
);
3196 int run_lxc_hooks(const char *name
, char *hook
, struct lxc_conf
*conf
,
3197 const char *lxcpath
, char *argv
[])
3200 struct lxc_list
*it
;
3202 if (strcmp(hook
, "pre-start") == 0)
3203 which
= LXCHOOK_PRESTART
;
3204 else if (strcmp(hook
, "start-host") == 0)
3205 which
= LXCHOOK_START_HOST
;
3206 else if (strcmp(hook
, "pre-mount") == 0)
3207 which
= LXCHOOK_PREMOUNT
;
3208 else if (strcmp(hook
, "mount") == 0)
3209 which
= LXCHOOK_MOUNT
;
3210 else if (strcmp(hook
, "autodev") == 0)
3211 which
= LXCHOOK_AUTODEV
;
3212 else if (strcmp(hook
, "start") == 0)
3213 which
= LXCHOOK_START
;
3214 else if (strcmp(hook
, "stop") == 0)
3215 which
= LXCHOOK_STOP
;
3216 else if (strcmp(hook
, "post-stop") == 0)
3217 which
= LXCHOOK_POSTSTOP
;
3218 else if (strcmp(hook
, "clone") == 0)
3219 which
= LXCHOOK_CLONE
;
3220 else if (strcmp(hook
, "destroy") == 0)
3221 which
= LXCHOOK_DESTROY
;
3224 lxc_list_for_each(it
, &conf
->hooks
[which
]) {
3226 char *hookname
= it
->elem
;
3227 ret
= run_script_argv(name
, "lxc", hookname
, hook
, lxcpath
, argv
);
3234 int lxc_clear_config_caps(struct lxc_conf
*c
)
3236 struct lxc_list
*it
, *next
;
3238 lxc_list_for_each_safe(it
, &c
->caps
, next
) {
3246 static int lxc_free_idmap(struct lxc_list
*id_map
) {
3247 struct lxc_list
*it
, *next
;
3249 lxc_list_for_each_safe(it
, id_map
, next
) {
3257 int lxc_clear_idmaps(struct lxc_conf
*c
)
3259 return lxc_free_idmap(&c
->id_map
);
3262 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3264 struct lxc_list
*it
,*next
;
3266 lxc_list_for_each_safe(it
, &c
->keepcaps
, next
) {
3274 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
)
3276 struct lxc_list
*it
,*next
;
3278 const char *k
= NULL
;
3280 if (strcmp(key
, "lxc.cgroup") == 0)
3282 else if (strncmp(key
, "lxc.cgroup.", sizeof("lxc.cgroup.")-1) == 0)
3283 k
= key
+ sizeof("lxc.cgroup.")-1;
3287 lxc_list_for_each_safe(it
, &c
->cgroup
, next
) {
3288 struct lxc_cgroup
*cg
= it
->elem
;
3289 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3292 free(cg
->subsystem
);
3300 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3302 struct lxc_list
*it
, *next
;
3304 const char *k
= NULL
;
3306 if (strcmp(key
, "lxc.limit") == 0
3307 || strcmp(key
, "lxc.prlimit"))
3309 else if (strncmp(key
, "lxc.limit.", sizeof("lxc.limit.")-1) == 0)
3310 k
= key
+ sizeof("lxc.limit.")-1;
3311 else if (strncmp(key
, "lxc.prlimit.", sizeof("lxc.prlimit.")-1) == 0)
3312 k
= key
+ sizeof("lxc.prlimit.")-1;
3316 lxc_list_for_each_safe(it
, &c
->limits
, next
) {
3317 struct lxc_limit
*lim
= it
->elem
;
3318 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3321 free(lim
->resource
);
3328 int lxc_clear_groups(struct lxc_conf
*c
)
3330 struct lxc_list
*it
,*next
;
3332 lxc_list_for_each_safe(it
, &c
->groups
, next
) {
3340 int lxc_clear_environment(struct lxc_conf
*c
)
3342 struct lxc_list
*it
,*next
;
3344 lxc_list_for_each_safe(it
, &c
->environment
, next
) {
3352 int lxc_clear_mount_entries(struct lxc_conf
*c
)
3354 struct lxc_list
*it
,*next
;
3356 lxc_list_for_each_safe(it
, &c
->mount_list
, next
) {
3364 int lxc_clear_automounts(struct lxc_conf
*c
)
3370 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
3372 struct lxc_list
*it
,*next
;
3373 bool all
= false, done
= false;
3374 const char *k
= NULL
;
3377 if (strcmp(key
, "lxc.hook") == 0)
3379 else if (strncmp(key
, "lxc.hook.", sizeof("lxc.hook.")-1) == 0)
3380 k
= key
+ sizeof("lxc.hook.")-1;
3384 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3385 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
3386 lxc_list_for_each_safe(it
, &c
->hooks
[i
], next
) {
3396 ERROR("Invalid hook key: %s", key
);
3402 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
3404 struct lxc_list
*it
,*next
;
3406 lxc_list_for_each_safe(it
, &conf
->aliens
, next
) {
3413 void lxc_clear_includes(struct lxc_conf
*conf
)
3415 struct lxc_list
*it
,*next
;
3417 lxc_list_for_each_safe(it
, &conf
->includes
, next
) {
3424 void lxc_conf_free(struct lxc_conf
*conf
)
3428 if (current_config
== conf
)
3429 current_config
= NULL
;
3430 free(conf
->console
.buffer_log_file
);
3431 free(conf
->console
.log_path
);
3432 free(conf
->console
.path
);
3433 if (conf
->console
.buffer_size
> 0 && conf
->console
.ringbuf
.addr
)
3434 lxc_ringbuf_release(&conf
->console
.ringbuf
);
3435 free(conf
->rootfs
.mount
);
3436 free(conf
->rootfs
.bdev_type
);
3437 free(conf
->rootfs
.options
);
3438 free(conf
->rootfs
.path
);
3439 free(conf
->logfile
);
3440 if (conf
->logfd
!= -1)
3442 free(conf
->utsname
);
3446 free(conf
->execute_cmd
);
3447 free(conf
->init_cmd
);
3448 free(conf
->unexpanded_config
);
3449 free(conf
->pty_names
);
3451 lxc_free_networks(&conf
->network
);
3452 free(conf
->lsm_aa_profile
);
3453 free(conf
->lsm_se_context
);
3454 lxc_seccomp_free(conf
);
3455 lxc_clear_config_caps(conf
);
3456 lxc_clear_config_keepcaps(conf
);
3457 lxc_clear_cgroups(conf
, "lxc.cgroup");
3458 lxc_clear_hooks(conf
, "lxc.hook");
3459 lxc_clear_mount_entries(conf
);
3460 lxc_clear_idmaps(conf
);
3461 lxc_clear_groups(conf
);
3462 lxc_clear_includes(conf
);
3463 lxc_clear_aliens(conf
);
3464 lxc_clear_environment(conf
);
3465 lxc_clear_limits(conf
, "lxc.prlimit");
3466 free(conf
->cgroup_meta
.dir
);
3467 free(conf
->cgroup_meta
.controllers
);
3471 struct userns_fn_data
{
3473 const char *fn_name
;
3478 static int run_userns_fn(void *data
)
3480 struct userns_fn_data
*d
= data
;
3483 /* Close write end of the pipe. */
3486 /* Wait for parent to finish establishing a new mapping in the user
3487 * namespace we are executing in.
3489 if (read(d
->p
[0], &c
, 1) != 1)
3492 /* Close read end of the pipe. */
3496 TRACE("calling function \"%s\"", d
->fn_name
);
3497 /* Call function to run. */
3498 return d
->fn(d
->arg
);
3501 static struct id_map
*mapped_hostid_entry(struct lxc_conf
*conf
, unsigned id
,
3504 struct lxc_list
*it
;
3506 struct id_map
*retmap
= NULL
;
3508 lxc_list_for_each(it
, &conf
->id_map
) {
3510 if (map
->idtype
!= idtype
)
3513 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
3522 retmap
= malloc(sizeof(*retmap
));
3526 memcpy(retmap
, map
, sizeof(*retmap
));
3531 * Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
3532 * existing one or establish a new one.
3534 static struct id_map
*idmap_add(struct lxc_conf
*conf
, uid_t id
, enum idtype type
)
3537 struct id_map
*entry
= NULL
;
3539 /* Reuse existing mapping. */
3540 entry
= mapped_hostid_entry(conf
, id
, type
);
3544 /* Find new mapping. */
3545 hostid_mapped
= find_unmapped_nsid(conf
, type
);
3546 if (hostid_mapped
< 0) {
3547 DEBUG("failed to find free mapping for id %d", id
);
3551 entry
= malloc(sizeof(*entry
));
3555 entry
->idtype
= type
;
3556 entry
->nsid
= hostid_mapped
;
3557 entry
->hostid
= (unsigned long)id
;
3563 /* Run a function in a new user namespace.
3564 * The caller's euid/egid will be mapped if it is not already.
3565 * Afaict, userns_exec_1() is only used to operate based on privileges for the
3566 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
3567 * This means we require only to establish a mapping from:
3568 * - the container root {g,u}id as seen from the host > user's host {g,u}id
3569 * - the container root -> some sub{g,u}id
3570 * The former we add, if the user did not specifiy a mapping. The latter we
3571 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
3572 * there to start the container in the first place.
3574 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
3575 const char *fn_name
)
3579 struct userns_fn_data d
;
3581 struct lxc_list
*it
;
3584 int ret
= -1, status
= -1;
3585 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
3586 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
3587 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
3591 SYSERROR("opening pipe");
3595 d
.fn_name
= fn_name
;
3600 /* Clone child in new user namespace. */
3601 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
3603 ERROR("failed to clone child process in new user namespace");
3613 /* Find container root. */
3614 lxc_list_for_each(it
, &conf
->id_map
) {
3620 if (map
->idtype
== ID_TYPE_UID
&& container_root_uid
== NULL
) {
3621 container_root_uid
= malloc(sizeof(*container_root_uid
));
3622 if (!container_root_uid
)
3624 container_root_uid
->idtype
= map
->idtype
;
3625 container_root_uid
->hostid
= map
->hostid
;
3626 container_root_uid
->nsid
= 0;
3627 container_root_uid
->range
= map
->range
;
3629 /* Check if container root mapping contains a mapping
3632 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
3633 host_uid_map
= container_root_uid
;
3634 } else if (map
->idtype
== ID_TYPE_GID
&& container_root_gid
== NULL
) {
3635 container_root_gid
= malloc(sizeof(*container_root_gid
));
3636 if (!container_root_gid
)
3638 container_root_gid
->idtype
= map
->idtype
;
3639 container_root_gid
->hostid
= map
->hostid
;
3640 container_root_gid
->nsid
= 0;
3641 container_root_gid
->range
= map
->range
;
3643 /* Check if container root mapping contains a mapping
3646 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
3647 host_gid_map
= container_root_gid
;
3650 /* Found container root. */
3651 if (container_root_uid
&& container_root_gid
)
3655 /* This is actually checked earlier but it can't hurt. */
3656 if (!container_root_uid
|| !container_root_gid
) {
3657 ERROR("no mapping for container root found");
3661 /* Check whether the {g,u}id of the user has a mapping. */
3663 host_uid_map
= idmap_add(conf
, euid
, ID_TYPE_UID
);
3666 host_gid_map
= idmap_add(conf
, egid
, ID_TYPE_GID
);
3668 if (!host_uid_map
) {
3669 DEBUG("failed to find mapping for uid %d", euid
);
3673 if (!host_gid_map
) {
3674 DEBUG("failed to find mapping for gid %d", egid
);
3678 /* Allocate new {g,u}id map list. */
3679 idmap
= malloc(sizeof(*idmap
));
3682 lxc_list_init(idmap
);
3684 /* Add container root to the map. */
3685 tmplist
= malloc(sizeof(*tmplist
));
3688 lxc_list_add_elem(tmplist
, container_root_uid
);
3689 lxc_list_add_tail(idmap
, tmplist
);
3691 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
3692 /* idmap will now keep track of that memory. */
3693 container_root_uid
= NULL
;
3695 /* Add container root to the map. */
3696 tmplist
= malloc(sizeof(*tmplist
));
3699 lxc_list_add_elem(tmplist
, host_uid_map
);
3700 lxc_list_add_tail(idmap
, tmplist
);
3702 /* idmap will now keep track of that memory. */
3703 container_root_uid
= NULL
;
3704 /* idmap will now keep track of that memory. */
3705 host_uid_map
= NULL
;
3707 tmplist
= malloc(sizeof(*tmplist
));
3710 lxc_list_add_elem(tmplist
, container_root_gid
);
3711 lxc_list_add_tail(idmap
, tmplist
);
3713 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
3714 /* idmap will now keep track of that memory. */
3715 container_root_gid
= NULL
;
3717 tmplist
= malloc(sizeof(*tmplist
));
3720 lxc_list_add_elem(tmplist
, host_gid_map
);
3721 lxc_list_add_tail(idmap
, tmplist
);
3723 /* idmap will now keep track of that memory. */
3724 container_root_gid
= NULL
;
3725 /* idmap will now keep track of that memory. */
3726 host_gid_map
= NULL
;
3728 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
3729 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
3730 lxc_list_for_each(it
, idmap
) {
3732 TRACE("establishing %cid mapping for \"%d\" in new "
3733 "user namespace: nsuid %lu - hostid %lu - range "
3735 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
3736 map
->nsid
, map
->hostid
, map
->range
);
3740 /* Set up {g,u}id mapping for user namespace of child process. */
3741 ret
= lxc_map_ids(idmap
, pid
);
3743 ERROR("error setting up {g,u}id mappings for child process "
3748 /* Tell child to proceed. */
3749 if (write(p
[1], &c
, 1) != 1) {
3750 SYSERROR("failed telling child process \"%d\" to proceed", pid
);
3755 /* Wait for child to finish. */
3757 status
= wait_for_pid(pid
);
3760 lxc_free_idmap(idmap
);
3761 if (container_root_uid
)
3762 free(container_root_uid
);
3763 if (container_root_gid
)
3764 free(container_root_gid
);
3765 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
3767 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
3780 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
3781 const char *fn_name
)
3785 struct userns_fn_data d
;
3788 struct lxc_list
*cur
;
3791 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
3792 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
3793 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
3797 SYSERROR("opening pipe");
3801 d
.fn_name
= fn_name
;
3806 /* Clone child in new user namespace. */
3807 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
3809 ERROR("failed to clone child process in new user namespace");
3819 /* Allocate new {g,u}id map list. */
3820 idmap
= malloc(sizeof(*idmap
));
3823 lxc_list_init(idmap
);
3825 /* Find container root. */
3826 lxc_list_for_each(cur
, &conf
->id_map
) {
3827 struct id_map
*tmpmap
;
3829 tmplist
= malloc(sizeof(*tmplist
));
3833 tmpmap
= malloc(sizeof(*tmpmap
));
3839 memset(tmpmap
, 0, sizeof(*tmpmap
));
3840 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
3841 tmplist
->elem
= tmpmap
;
3843 lxc_list_add_tail(idmap
, tmplist
);
3847 if (map
->idtype
== ID_TYPE_UID
)
3848 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
3851 if (map
->idtype
== ID_TYPE_GID
)
3852 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
3858 if (map
->idtype
== ID_TYPE_UID
)
3859 if (container_root_uid
== NULL
)
3860 container_root_uid
= map
;
3862 if (map
->idtype
== ID_TYPE_GID
)
3863 if (container_root_gid
== NULL
)
3864 container_root_gid
= map
;
3867 if (!container_root_uid
|| !container_root_gid
) {
3868 ERROR("No mapping for container root found");
3872 /* Check whether the {g,u}id of the user has a mapping. */
3874 host_uid_map
= idmap_add(conf
, euid
, ID_TYPE_UID
);
3876 host_uid_map
= container_root_uid
;
3879 host_gid_map
= idmap_add(conf
, egid
, ID_TYPE_GID
);
3881 host_gid_map
= container_root_gid
;
3883 if (!host_uid_map
) {
3884 DEBUG("Failed to find mapping for uid %d", euid
);
3888 if (!host_gid_map
) {
3889 DEBUG("Failed to find mapping for gid %d", egid
);
3893 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
3894 /* Add container root to the map. */
3895 tmplist
= malloc(sizeof(*tmplist
));
3898 lxc_list_add_elem(tmplist
, host_uid_map
);
3899 lxc_list_add_tail(idmap
, tmplist
);
3901 /* idmap will now keep track of that memory. */
3902 host_uid_map
= NULL
;
3904 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
3905 tmplist
= malloc(sizeof(*tmplist
));
3908 lxc_list_add_elem(tmplist
, host_gid_map
);
3909 lxc_list_add_tail(idmap
, tmplist
);
3911 /* idmap will now keep track of that memory. */
3912 host_gid_map
= NULL
;
3914 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
3915 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
3916 lxc_list_for_each(cur
, idmap
) {
3918 TRACE("establishing %cid mapping for \"%d\" in new "
3919 "user namespace: nsuid %lu - hostid %lu - range "
3921 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
3922 map
->nsid
, map
->hostid
, map
->range
);
3926 /* Set up {g,u}id mapping for user namespace of child process. */
3927 ret
= lxc_map_ids(idmap
, pid
);
3929 ERROR("error setting up {g,u}id mappings for child process "
3934 /* Tell child to proceed. */
3935 if (write(p
[1], &c
, 1) != 1) {
3936 SYSERROR("failed telling child process \"%d\" to proceed", pid
);
3941 /* Wait for child to finish. */
3943 ret
= wait_for_pid(pid
);
3946 lxc_free_idmap(idmap
);
3947 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
3949 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
3959 /* not thread-safe, do not use from api without first forking */
3960 static char* getuname(void)
3962 struct passwd
*result
;
3964 result
= getpwuid(geteuid());
3968 return strdup(result
->pw_name
);
3971 /* not thread-safe, do not use from api without first forking */
3972 static char *getgname(void)
3974 struct group
*result
;
3976 result
= getgrgid(getegid());
3980 return strdup(result
->gr_name
);
3983 /* not thread-safe, do not use from api without first forking */
3984 void suggest_default_idmap(void)
3987 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
3989 char *uname
, *gname
;
3992 if (!(uname
= getuname()))
3995 if (!(gname
= getgname())) {
4000 f
= fopen(subuidfile
, "r");
4002 ERROR("Your system is not configured with subuids");
4007 while (getline(&line
, &len
, f
) != -1) {
4008 size_t no_newline
= 0;
4009 char *p
= strchr(line
, ':'), *p2
;
4016 if (strcmp(line
, uname
))
4018 p2
= strchr(p
, ':');
4025 no_newline
= strcspn(p2
, "\n");
4026 p2
[no_newline
] = '\0';
4028 if (lxc_safe_uint(p
, &uid
) < 0)
4029 WARN("Could not parse UID.");
4030 if (lxc_safe_uint(p2
, &urange
) < 0)
4031 WARN("Could not parse UID range.");
4035 f
= fopen(subgidfile
, "r");
4037 ERROR("Your system is not configured with subgids");
4042 while (getline(&line
, &len
, f
) != -1) {
4043 size_t no_newline
= 0;
4044 char *p
= strchr(line
, ':'), *p2
;
4051 if (strcmp(line
, uname
))
4053 p2
= strchr(p
, ':');
4060 no_newline
= strcspn(p2
, "\n");
4061 p2
[no_newline
] = '\0';
4063 if (lxc_safe_uint(p
, &gid
) < 0)
4064 WARN("Could not parse GID.");
4065 if (lxc_safe_uint(p2
, &grange
) < 0)
4066 WARN("Could not parse GID range.");
4072 if (!urange
|| !grange
) {
4073 ERROR("You do not have subuids or subgids allocated");
4074 ERROR("Unprivileged containers require subuids and subgids");
4078 ERROR("You must either run as root, or define uid mappings");
4079 ERROR("To pass uid mappings to lxc-create, you could create");
4080 ERROR("~/.config/lxc/default.conf:");
4081 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4082 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4083 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4089 static void free_cgroup_settings(struct lxc_list
*result
)
4091 struct lxc_list
*iterator
, *next
;
4093 lxc_list_for_each_safe(iterator
, result
, next
) {
4094 lxc_list_del(iterator
);
4101 * Return the list of cgroup_settings sorted according to the following rules
4102 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4104 struct lxc_list
*sort_cgroup_settings(struct lxc_list
* cgroup_settings
)
4106 struct lxc_list
*result
;
4107 struct lxc_list
*memsw_limit
= NULL
;
4108 struct lxc_list
*it
= NULL
;
4109 struct lxc_cgroup
*cg
= NULL
;
4110 struct lxc_list
*item
= NULL
;
4112 result
= malloc(sizeof(*result
));
4114 ERROR("failed to allocate memory to sort cgroup settings");
4117 lxc_list_init(result
);
4119 /*Iterate over the cgroup settings and copy them to the output list*/
4120 lxc_list_for_each(it
, cgroup_settings
) {
4121 item
= malloc(sizeof(*item
));
4123 ERROR("failed to allocate memory to sort cgroup settings");
4124 free_cgroup_settings(result
);
4127 item
->elem
= it
->elem
;
4129 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4130 /* Store the memsw_limit location */
4132 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 && memsw_limit
!= NULL
) {
4133 /* lxc.cgroup.memory.memsw.limit_in_bytes is found before
4134 * lxc.cgroup.memory.limit_in_bytes, swap these two items */
4135 item
->elem
= memsw_limit
->elem
;
4136 memsw_limit
->elem
= it
->elem
;
4138 lxc_list_add_tail(result
, item
);