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
27 #include <arpa/inet.h>
34 #include <linux/loop.h>
36 #include <netinet/in.h>
43 #include <sys/mount.h>
44 #include <sys/param.h>
45 #include <sys/prctl.h>
46 #include <sys/sendfile.h>
47 #include <sys/socket.h>
49 #include <sys/syscall.h>
50 #include <sys/sysmacros.h>
51 #include <sys/types.h>
52 #include <sys/utsname.h>
63 #include "confile_utils.h"
68 #include "lxcseccomp.h"
70 #include "namespace.h"
73 #include "raw_syscalls.h"
77 #include "storage/overlay.h"
78 #include "syscall_wrappers.h"
83 #include <sys/mkdev.h>
87 #include <sys/statvfs.h>
93 #include <../include/openpty.h>
97 #include <sys/capability.h>
100 #if HAVE_SYS_PERSONALITY_H
101 #include <sys/personality.h>
105 #include "include/strlcat.h"
109 #include <../include/lxcmntent.h>
114 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
115 #include <../include/prlimit.h>
118 lxc_log_define(conf
, lxc
);
120 /* The lxc_conf of the container currently being worked on in an API call.
121 * This is used in the error calls.
124 thread_local
struct lxc_conf
*current_config
;
126 struct lxc_conf
*current_config
;
129 char *lxchook_names
[NUM_LXC_HOOKS
] = {
158 static struct mount_opt mount_opt
[] = {
159 { "async", 1, MS_SYNCHRONOUS
},
160 { "atime", 1, MS_NOATIME
},
161 { "bind", 0, MS_BIND
},
162 { "defaults", 0, 0 },
163 { "dev", 1, MS_NODEV
},
164 { "diratime", 1, MS_NODIRATIME
},
165 { "dirsync", 0, MS_DIRSYNC
},
166 { "exec", 1, MS_NOEXEC
},
167 { "lazytime", 0, MS_LAZYTIME
},
168 { "mand", 0, MS_MANDLOCK
},
169 { "noatime", 0, MS_NOATIME
},
170 { "nodev", 0, MS_NODEV
},
171 { "nodiratime", 0, MS_NODIRATIME
},
172 { "noexec", 0, MS_NOEXEC
},
173 { "nomand", 1, MS_MANDLOCK
},
174 { "norelatime", 1, MS_RELATIME
},
175 { "nostrictatime", 1, MS_STRICTATIME
},
176 { "nosuid", 0, MS_NOSUID
},
177 { "rbind", 0, MS_BIND
|MS_REC
},
178 { "relatime", 0, MS_RELATIME
},
179 { "remount", 0, MS_REMOUNT
},
180 { "ro", 0, MS_RDONLY
},
181 { "rw", 1, MS_RDONLY
},
182 { "strictatime", 0, MS_STRICTATIME
},
183 { "suid", 1, MS_NOSUID
},
184 { "sync", 0, MS_SYNCHRONOUS
},
188 static struct mount_opt propagation_opt
[] = {
189 { "private", 0, MS_PRIVATE
},
190 { "shared", 0, MS_SHARED
},
191 { "slave", 0, MS_SLAVE
},
192 { "unbindable", 0, MS_UNBINDABLE
},
193 { "rprivate", 0, MS_PRIVATE
|MS_REC
},
194 { "rshared", 0, MS_SHARED
|MS_REC
},
195 { "rslave", 0, MS_SLAVE
|MS_REC
},
196 { "runbindable", 0, MS_UNBINDABLE
|MS_REC
},
200 static struct caps_opt caps_opt
[] = {
202 { "chown", CAP_CHOWN
},
203 { "dac_override", CAP_DAC_OVERRIDE
},
204 { "dac_read_search", CAP_DAC_READ_SEARCH
},
205 { "fowner", CAP_FOWNER
},
206 { "fsetid", CAP_FSETID
},
207 { "kill", CAP_KILL
},
208 { "setgid", CAP_SETGID
},
209 { "setuid", CAP_SETUID
},
210 { "setpcap", CAP_SETPCAP
},
211 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
212 { "net_bind_service", CAP_NET_BIND_SERVICE
},
213 { "net_broadcast", CAP_NET_BROADCAST
},
214 { "net_admin", CAP_NET_ADMIN
},
215 { "net_raw", CAP_NET_RAW
},
216 { "ipc_lock", CAP_IPC_LOCK
},
217 { "ipc_owner", CAP_IPC_OWNER
},
218 { "sys_module", CAP_SYS_MODULE
},
219 { "sys_rawio", CAP_SYS_RAWIO
},
220 { "sys_chroot", CAP_SYS_CHROOT
},
221 { "sys_ptrace", CAP_SYS_PTRACE
},
222 { "sys_pacct", CAP_SYS_PACCT
},
223 { "sys_admin", CAP_SYS_ADMIN
},
224 { "sys_boot", CAP_SYS_BOOT
},
225 { "sys_nice", CAP_SYS_NICE
},
226 { "sys_resource", CAP_SYS_RESOURCE
},
227 { "sys_time", CAP_SYS_TIME
},
228 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
229 { "mknod", CAP_MKNOD
},
230 { "lease", CAP_LEASE
},
231 #ifdef CAP_AUDIT_READ
232 { "audit_read", CAP_AUDIT_READ
},
234 #ifdef CAP_AUDIT_WRITE
235 { "audit_write", CAP_AUDIT_WRITE
},
237 #ifdef CAP_AUDIT_CONTROL
238 { "audit_control", CAP_AUDIT_CONTROL
},
240 { "setfcap", CAP_SETFCAP
},
241 { "mac_override", CAP_MAC_OVERRIDE
},
242 { "mac_admin", CAP_MAC_ADMIN
},
244 { "syslog", CAP_SYSLOG
},
246 #ifdef CAP_WAKE_ALARM
247 { "wake_alarm", CAP_WAKE_ALARM
},
249 #ifdef CAP_BLOCK_SUSPEND
250 { "block_suspend", CAP_BLOCK_SUSPEND
},
255 static struct limit_opt limit_opt
[] = {
260 { "core", RLIMIT_CORE
},
263 { "cpu", RLIMIT_CPU
},
266 { "data", RLIMIT_DATA
},
269 { "fsize", RLIMIT_FSIZE
},
272 { "locks", RLIMIT_LOCKS
},
274 #ifdef RLIMIT_MEMLOCK
275 { "memlock", RLIMIT_MEMLOCK
},
277 #ifdef RLIMIT_MSGQUEUE
278 { "msgqueue", RLIMIT_MSGQUEUE
},
281 { "nice", RLIMIT_NICE
},
284 { "nofile", RLIMIT_NOFILE
},
287 { "nproc", RLIMIT_NPROC
},
290 { "rss", RLIMIT_RSS
},
293 { "rtprio", RLIMIT_RTPRIO
},
296 { "rttime", RLIMIT_RTTIME
},
298 #ifdef RLIMIT_SIGPENDING
299 { "sigpending", RLIMIT_SIGPENDING
},
302 { "stack", RLIMIT_STACK
},
306 static int run_buffer(char *buffer
)
310 struct lxc_popen_FILE
*f
;
312 f
= lxc_popen(buffer
);
314 SYSERROR("Failed to popen() %s", buffer
);
318 output
= malloc(LXC_LOG_BUFFER_SIZE
);
320 ERROR("Failed to allocate memory for %s", buffer
);
325 while (fgets(output
, LXC_LOG_BUFFER_SIZE
, f
->f
))
326 DEBUG("Script %s with output: %s", buffer
, output
);
332 SYSERROR("Script exited with error");
334 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
335 ERROR("Script exited with status %d", WEXITSTATUS(ret
));
337 } else if (WIFSIGNALED(ret
)) {
338 ERROR("Script terminated by signal %d", WTERMSIG(ret
));
345 int run_script_argv(const char *name
, unsigned int hook_version
,
346 const char *section
, const char *script
,
347 const char *hookname
, char **argv
)
354 if (hook_version
== 0)
355 INFO("Executing script \"%s\" for container \"%s\", config "
356 "section \"%s\"", script
, name
, section
);
358 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
360 for (i
= 0; argv
&& argv
[i
]; i
++)
361 size
+= strlen(argv
[i
]) + 1;
363 size
+= STRLITERALLEN("exec");
365 size
+= strlen(script
);
371 if (hook_version
== 0) {
372 size
+= strlen(hookname
);
375 size
+= strlen(name
);
378 size
+= strlen(section
);
385 buffer
= malloc(size
);
389 if (hook_version
== 0)
390 buf_pos
= snprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
392 buf_pos
= snprintf(buffer
, size
, "exec %s", script
);
393 if (buf_pos
< 0 || (size_t)buf_pos
>= size
) {
394 ERROR("Failed to create command line for script \"%s\"", script
);
398 if (hook_version
== 1) {
399 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
401 SYSERROR("Failed to set environment variable: "
402 "LXC_HOOK_TYPE=%s", hookname
);
405 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
407 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
409 SYSERROR("Failed to set environment variable: "
410 "LXC_HOOK_SECTION=%s", section
);
413 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
415 if (strcmp(section
, "net") == 0) {
418 if (!argv
|| !argv
[0])
421 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
423 SYSERROR("Failed to set environment variable: "
424 "LXC_NET_TYPE=%s", argv
[0]);
427 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
429 parent
= argv
[1] ? argv
[1] : "";
431 if (strcmp(argv
[0], "macvlan") == 0) {
432 ret
= setenv("LXC_NET_PARENT", parent
, 1);
434 SYSERROR("Failed to set environment "
435 "variable: LXC_NET_PARENT=%s", parent
);
438 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
439 } else if (strcmp(argv
[0], "phys") == 0) {
440 ret
= setenv("LXC_NET_PARENT", parent
, 1);
442 SYSERROR("Failed to set environment "
443 "variable: LXC_NET_PARENT=%s", parent
);
446 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
447 } else if (strcmp(argv
[0], "veth") == 0) {
448 char *peer
= argv
[2] ? argv
[2] : "";
450 ret
= setenv("LXC_NET_PEER", peer
, 1);
452 SYSERROR("Failed to set environment "
453 "variable: LXC_NET_PEER=%s", peer
);
456 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
458 ret
= setenv("LXC_NET_PARENT", parent
, 1);
460 SYSERROR("Failed to set environment "
461 "variable: LXC_NET_PARENT=%s", parent
);
464 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
469 for (i
= 0; argv
&& argv
[i
]; i
++) {
470 size_t len
= size
- buf_pos
;
472 ret
= snprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
473 if (ret
< 0 || (size_t)ret
>= len
) {
474 ERROR("Failed to create command line for script \"%s\"", script
);
480 fret
= run_buffer(buffer
);
487 int run_script(const char *name
, const char *section
, const char *script
, ...)
494 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
495 script
, name
, section
);
497 va_start(ap
, script
);
498 while ((p
= va_arg(ap
, char *)))
499 size
+= strlen(p
) + 1;
502 size
+= STRLITERALLEN("exec");
503 size
+= strlen(script
);
504 size
+= strlen(name
);
505 size
+= strlen(section
);
511 buffer
= alloca(size
);
512 ret
= snprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
513 if (ret
< 0 || ret
>= size
)
516 va_start(ap
, script
);
517 while ((p
= va_arg(ap
, char *))) {
518 int len
= size
- ret
;
520 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
521 if (rc
< 0 || rc
>= len
) {
529 return run_buffer(buffer
);
533 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
534 * the duration of the container run, to prevent the container from marking
535 * the underlying fs readonly on shutdown. unlink the file immediately so
536 * no name pollution is happens.
537 * don't unlink on NFS to avoid random named stale handles.
538 * return -1 on error.
539 * return -2 if nothing needed to be pinned.
540 * return an open fd (>=0) if we pinned it.
542 int pin_rootfs(const char *rootfs
)
545 char absrootfspin
[PATH_MAX
];
550 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
553 absrootfs
= realpath(rootfs
, NULL
);
557 ret
= stat(absrootfs
, &s
);
563 if (!S_ISDIR(s
.st_mode
)) {
568 ret
= snprintf(absrootfspin
, PATH_MAX
, "%s/.lxc-keep", absrootfs
);
570 if (ret
< 0 || ret
>= PATH_MAX
)
573 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
| S_IRUSR
);
577 ret
= fstatfs (fd
, &sfs
);
581 if (sfs
.f_type
== NFS_SUPER_MAGIC
) {
582 DEBUG("Rootfs on NFS, not unlinking pin file \"%s\"", absrootfspin
);
586 (void)unlink(absrootfspin
);
591 /* If we are asking to remount something, make sure that any NOEXEC etc are
594 unsigned long add_required_remount_flags(const char *s
, const char *d
,
600 unsigned long required_flags
= 0;
608 ret
= statvfs(s
, &sb
);
612 if (flags
& MS_REMOUNT
) {
613 if (sb
.f_flag
& MS_NOSUID
)
614 required_flags
|= MS_NOSUID
;
615 if (sb
.f_flag
& MS_NODEV
)
616 required_flags
|= MS_NODEV
;
617 if (sb
.f_flag
& MS_RDONLY
)
618 required_flags
|= MS_RDONLY
;
619 if (sb
.f_flag
& MS_NOEXEC
)
620 required_flags
|= MS_NOEXEC
;
623 if (sb
.f_flag
& MS_NOATIME
)
624 required_flags
|= MS_NOATIME
;
625 if (sb
.f_flag
& MS_NODIRATIME
)
626 required_flags
|= MS_NODIRATIME
;
627 if (sb
.f_flag
& MS_LAZYTIME
)
628 required_flags
|= MS_LAZYTIME
;
629 if (sb
.f_flag
& MS_RELATIME
)
630 required_flags
|= MS_RELATIME
;
631 if (sb
.f_flag
& MS_STRICTATIME
)
632 required_flags
|= MS_STRICTATIME
;
634 return flags
| required_flags
;
640 static int add_shmount_to_list(struct lxc_conf
*conf
)
642 char new_mount
[PATH_MAX
];
643 /* Offset for the leading '/' since the path_cont
644 * is absolute inside the container.
646 int offset
= 1, ret
= -1;
648 ret
= snprintf(new_mount
, sizeof(new_mount
),
649 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
650 conf
->shmount
.path_cont
+ offset
);
651 if (ret
< 0 || (size_t)ret
>= sizeof(new_mount
))
654 return add_elem_to_mount_list(new_mount
, conf
);
657 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
664 const char *destination
;
668 } default_mounts
[] = {
669 /* Read-only bind-mounting... In older kernels, doing that
670 * required to do one MS_BIND mount and then
671 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
672 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
673 * onwards. However, this apparently does not work on kernel
674 * 3.8. Unfortunately, on that very same kernel, doing the same
675 * trick as above doesn't seem to work either, there one needs
676 * to ALSO specify MS_BIND for the remount, otherwise the
677 * entire fs is remounted read-only or the mount fails because
678 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
679 * kernels as low as 2.6.32...
681 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
682 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
683 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
684 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
685 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
686 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
687 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
688 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
689 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
690 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
691 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
692 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
693 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
694 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
695 { 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
},
696 { 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
},
697 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
700 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
702 unsigned long mflags
;
703 char *destination
= NULL
;
705 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
708 if (default_mounts
[i
].source
) {
709 /* will act like strdup if %r is not present */
710 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
715 if (!default_mounts
[i
].destination
) {
716 ERROR("BUG: auto mounts destination %d was NULL", i
);
721 /* will act like strdup if %r is not present */
722 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
730 mflags
= add_required_remount_flags(source
, destination
,
731 default_mounts
[i
].flags
);
732 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
,
733 mflags
, default_mounts
[i
].options
,
734 conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
736 if (r
< 0 && errno
== ENOENT
) {
737 INFO("Mount source or target for \"%s\" on \"%s\" does "
738 "not exist. Skipping", source
, destination
);
741 SYSERROR("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
752 if (flags
& LXC_AUTO_CGROUP_MASK
) {
755 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
756 /* If the type of cgroup mount was not specified, it depends on
757 * the container's capabilities as to what makes sense: if we
758 * have CAP_SYS_ADMIN, the read-only part can be remounted
759 * read-write anyway, so we may as well default to read-write;
760 * then the admin will not be given a false sense of security.
761 * (And if they really want mixed r/o r/w, then they can
762 * explicitly specify :mixed.) OTOH, if the container lacks
763 * CAP_SYS_ADMIN, do only default to :mixed, because then the
764 * container can't remount it read-write.
766 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
767 int has_sys_admin
= 0;
769 if (!lxc_list_empty(&conf
->keepcaps
))
770 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
772 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
774 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
775 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
777 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
780 if (flags
& LXC_AUTO_CGROUP_FORCE
)
781 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
783 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
,
785 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
787 SYSERROR("Failed to mount \"/sys/fs/cgroup\"");
792 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
793 int ret
= add_shmount_to_list(conf
);
795 ERROR("Failed to add shmount entry to container config");
803 static int setup_utsname(struct utsname
*utsname
)
810 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
812 SYSERROR("Failed to set the hostname to \"%s\"", utsname
->nodename
);
816 INFO("Set hostname to \"%s\"", utsname
->nodename
);
821 struct dev_symlinks
{
826 static const struct dev_symlinks dev_symlinks
[] = {
827 { "/proc/self/fd", "fd" },
828 { "/proc/self/fd/0", "stdin" },
829 { "/proc/self/fd/1", "stdout" },
830 { "/proc/self/fd/2", "stderr" },
833 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
839 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
840 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
842 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s",
843 rootfs
->path
? rootfs
->mount
: "", d
->name
);
844 if (ret
< 0 || ret
>= PATH_MAX
)
847 /* Stat the path first. If we don't get an error accept it as
848 * is and don't try to create it
850 ret
= stat(path
, &s
);
854 ret
= symlink(d
->oldpath
, path
);
855 if (ret
&& errno
!= EEXIST
) {
856 if (errno
== EROFS
) {
857 WARN("Failed to create \"%s\". Read-only filesystem", path
);
859 SYSERROR("Failed to create \"%s\"", path
);
868 /* Build a space-separate list of ptys to pass to systemd. */
869 static bool append_ttyname(char **pp
, char *name
)
875 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
879 sprintf(*pp
, "container_ttys=%s", name
);
883 size
= strlen(*pp
) + strlen(name
) + 2;
884 p
= realloc(*pp
, size
);
889 (void)strlcat(p
, " ", size
);
890 (void)strlcat(p
, name
, size
);
895 static int lxc_setup_ttys(struct lxc_conf
*conf
)
898 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
899 char *ttydir
= ttys
->dir
;
900 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
902 if (!conf
->rootfs
.path
)
905 for (i
= 0; i
< ttys
->max
; i
++) {
906 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
908 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
909 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
913 /* create dev/lxc/tty%d" */
914 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
915 "/dev/%s/tty%d", ttydir
, i
+ 1);
916 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
919 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
920 if (ret
< 0 && errno
!= EEXIST
) {
921 SYSERROR("Failed to create \"%s\"", lxcpath
);
926 if (ret
< 0 && errno
!= ENOENT
) {
927 SYSERROR("Failed to unlink \"%s\"", path
);
931 ret
= mount(tty
->name
, lxcpath
, "none", MS_BIND
, 0);
933 SYSWARN("Failed to bind mount \"%s\" onto \"%s\"",
937 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
,
940 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
942 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
945 ret
= symlink(lxcpath
, path
);
947 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
952 /* If we populated /dev, then we need to create
955 ret
= mknod(path
, S_IFREG
| 0000, 0);
956 if (ret
< 0) /* this isn't fatal, continue */
957 SYSERROR("Failed to create \"%s\"", path
);
959 ret
= mount(tty
->name
, path
, "none", MS_BIND
, 0);
961 SYSERROR("Failed to mount '%s'->'%s'", tty
->name
, path
);
965 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, path
);
968 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
)) {
969 ERROR("Error setting up container_ttys string");
974 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
978 int lxc_allocate_ttys(struct lxc_conf
*conf
)
982 struct lxc_tty_info
*ttys
= &conf
->ttys
;
984 /* no tty in the configuration */
988 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
992 for (i
= 0; i
< ttys
->max
; i
++) {
993 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
995 tty
->master
= -EBADF
;
997 ret
= openpty(&tty
->master
, &tty
->slave
, NULL
, NULL
, NULL
);
999 SYSERROR("Failed to create tty %zu", i
);
1001 lxc_delete_tty(ttys
);
1005 ret
= ttyname_r(tty
->slave
, tty
->name
, sizeof(tty
->name
));
1007 SYSERROR("Failed to retrieve name of tty %zu slave", i
);
1009 lxc_delete_tty(ttys
);
1013 DEBUG("Created tty \"%s\" with master fd %d and slave fd %d",
1014 tty
->name
, tty
->master
, tty
->slave
);
1016 /* Prevent leaking the file descriptors to the container */
1017 ret
= fd_cloexec(tty
->master
, true);
1019 SYSWARN("Failed to set FD_CLOEXEC flag on master fd %d of "
1020 "tty device \"%s\"", tty
->master
, tty
->name
);
1022 ret
= fd_cloexec(tty
->slave
, true);
1024 SYSWARN("Failed to set FD_CLOEXEC flag on slave fd %d of "
1025 "tty device \"%s\"", tty
->slave
, tty
->name
);
1030 INFO("Finished creating %zu tty devices", ttys
->max
);
1034 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1041 for (i
= 0; i
< ttys
->max
; i
++) {
1042 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1044 if (tty
->master
>= 0) {
1046 tty
->master
= -EBADF
;
1049 if (tty
->slave
>= 0) {
1051 tty
->slave
= -EBADF
;
1059 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1063 struct lxc_conf
*conf
= handler
->conf
;
1064 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1065 int sock
= handler
->data_sock
[0];
1070 for (i
= 0; i
< ttys
->max
; i
++) {
1072 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1074 ttyfds
[0] = tty
->master
;
1075 ttyfds
[1] = tty
->slave
;
1077 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1081 TRACE("Sent ty \"%s\" with master fd %d and slave fd %d to "
1082 "parent", tty
->name
, tty
->master
, tty
->slave
);
1086 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1088 TRACE("Sent %zu ttys to parent", ttys
->max
);
1093 static int lxc_create_ttys(struct lxc_handler
*handler
)
1096 struct lxc_conf
*conf
= handler
->conf
;
1098 ret
= lxc_allocate_ttys(conf
);
1100 ERROR("Failed to allocate ttys");
1104 ret
= lxc_send_ttys_to_parent(handler
);
1106 ERROR("Failed to send ttys to parent");
1110 if (!conf
->is_execute
) {
1111 ret
= lxc_setup_ttys(conf
);
1113 ERROR("Failed to setup ttys");
1118 if (conf
->ttys
.tty_names
) {
1119 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1121 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1127 lxc_delete_tty(&conf
->ttys
);
1132 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1133 * error, log it but don't fail yet.
1135 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1136 const char *lxcpath
)
1143 INFO("Preparing \"/dev\"");
1145 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1146 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1147 path
= alloca(clen
);
1149 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1150 if (ret
< 0 || (size_t)ret
>= clen
)
1153 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1154 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1155 if (ret
< 0 && errno
!= EEXIST
) {
1156 SYSERROR("Failed to create \"/dev\" directory");
1161 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1162 rootfs
->path
? rootfs
->mount
: NULL
);
1164 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1167 TRACE("Mounted tmpfs on \"%s\"", path
);
1169 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1170 if (ret
< 0 || (size_t)ret
>= clen
) {
1175 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1176 * If not, then create it and exit if that fails...
1178 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1179 if (ret
< 0 && errno
!= EEXIST
) {
1180 SYSERROR("Failed to create directory \"%s\"", path
);
1188 (void)umask(cur_mask
);
1190 INFO("Prepared \"/dev\"");
1194 struct lxc_device_node
{
1201 static const struct lxc_device_node lxc_devices
[] = {
1202 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1203 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1204 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1205 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1206 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1207 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1214 LXC_DEVNODE_PARTIAL
,
1218 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1221 char path
[PATH_MAX
];
1223 int use_mknod
= LXC_DEVNODE_MKNOD
;
1225 ret
= snprintf(path
, PATH_MAX
, "%s/dev",
1226 rootfs
->path
? rootfs
->mount
: "");
1227 if (ret
< 0 || ret
>= PATH_MAX
)
1230 /* ignore, just don't try to fill in */
1231 if (!dir_exists(path
))
1234 INFO("Populating \"/dev\"");
1236 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1237 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1238 char hostpath
[PATH_MAX
];
1239 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1241 ret
= snprintf(path
, PATH_MAX
, "%s/dev/%s",
1242 rootfs
->path
? rootfs
->mount
: "", device
->name
);
1243 if (ret
< 0 || ret
>= PATH_MAX
)
1246 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1247 ret
= mknod(path
, device
->mode
, makedev(device
->maj
, device
->min
));
1248 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1249 DEBUG("Created device node \"%s\"", path
);
1250 } else if (ret
< 0) {
1251 if (errno
!= EPERM
) {
1252 SYSERROR("Failed to create device node \"%s\"", path
);
1256 use_mknod
= LXC_DEVNODE_BIND
;
1259 /* Device nodes are fully useable. */
1260 if (use_mknod
== LXC_DEVNODE_OPEN
)
1263 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1265 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1266 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1268 ret
= open(path
, O_RDONLY
| O_CLOEXEC
);
1271 /* Device nodes are fully useable. */
1272 use_mknod
= LXC_DEVNODE_OPEN
;
1276 SYSTRACE("Failed to open \"%s\" device", path
);
1277 /* Device nodes are only partially useable. */
1278 use_mknod
= LXC_DEVNODE_PARTIAL
;
1282 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1283 /* If we are dealing with partially functional device
1284 * nodes the prio mknod() call will have created the
1285 * device node so we can use it as a bind-mount target.
1287 ret
= mknod(path
, S_IFREG
| 0000, 0);
1288 if (ret
< 0 && errno
!= EEXIST
) {
1289 SYSERROR("Failed to create file \"%s\"", path
);
1294 /* Fallback to bind-mounting the device from the host. */
1295 ret
= snprintf(hostpath
, PATH_MAX
, "/dev/%s", device
->name
);
1296 if (ret
< 0 || ret
>= PATH_MAX
)
1299 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1300 rootfs
->path
? rootfs
->mount
: NULL
);
1302 SYSERROR("Failed to bind mount host device node \"%s\" "
1303 "onto \"%s\"", hostpath
, path
);
1306 DEBUG("Bind mounted host device node \"%s\" onto \"%s\"",
1311 INFO("Populated \"/dev\"");
1315 static int lxc_mount_rootfs(struct lxc_conf
*conf
)
1318 struct lxc_storage
*bdev
;
1319 const struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1321 if (!rootfs
->path
) {
1322 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1324 SYSERROR("Failed to remount \"/\" MS_REC | MS_SLAVE");
1331 ret
= access(rootfs
->mount
, F_OK
);
1333 SYSERROR("Failed to access to \"%s\". Check it is present",
1338 bdev
= storage_init(conf
);
1340 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1341 rootfs
->path
, rootfs
->mount
,
1342 rootfs
->options
? rootfs
->options
: "(null)");
1346 ret
= bdev
->ops
->mount(bdev
);
1349 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1350 rootfs
->path
, rootfs
->mount
,
1351 rootfs
->options
? rootfs
->options
: "(null)");
1355 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1356 rootfs
->path
, rootfs
->mount
,
1357 rootfs
->options
? rootfs
->options
: "(null)");
1362 int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1366 char buf
[LXC_LINELEN
];
1369 char *root
= rootfs
->mount
;
1371 nroot
= realpath(root
, NULL
);
1373 SYSERROR("Failed to resolve \"%s\"", root
);
1383 /* We could use here MS_MOVE, but in userns this mount is locked and
1386 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1388 SYSERROR("Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1394 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1396 SYSERROR("Failed to remount \"/\"");
1400 /* The following code cleans up inhereted mounts which are not required
1403 * The mountinfo file shows not all mounts, if a few points have been
1404 * unmounted between read operations from the mountinfo. So we need to
1405 * read mountinfo a few times.
1407 * This loop can be skipped if a container uses unserns, because all
1408 * inherited mounts are locked and we should live with all this trash.
1413 f
= fopen("./proc/self/mountinfo", "r");
1415 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
1419 while (fgets(buf
, LXC_LINELEN
, f
)) {
1420 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1421 p
= strchr(p
+1, ' ');
1426 p2
= strchr(p
+1, ' ');
1433 if (strcmp(p
+ 1, "/") == 0)
1436 if (strcmp(p
+ 1, "/proc") == 0)
1439 ret
= umount2(p
, MNT_DETACH
);
1450 /* This also can be skipped if a container uses unserns. */
1451 (void)umount2("./proc", MNT_DETACH
);
1453 /* It is weird, but chdir("..") moves us in a new root */
1456 SYSERROR("Failed to chdir(\"..\")");
1462 SYSERROR("Failed to chroot(\".\")");
1469 /* (The following explanation is copied verbatim from the kernel.)
1471 * pivot_root Semantics:
1472 * Moves the root file system of the current process to the directory put_old,
1473 * makes new_root as the new root file system of the current process, and sets
1474 * root/cwd of all processes which had them on the current root to new_root.
1477 * The new_root and put_old must be directories, and must not be on the
1478 * same file system as the current process root. The put_old must be
1479 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1480 * pointed to by put_old must yield the same directory as new_root. No other
1481 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1483 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1484 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1485 * in this situation.
1488 * - we don't move root/cwd if they are not at the root (reason: if something
1489 * cared enough to change them, it's probably wrong to force them elsewhere)
1490 * - it's okay to pick a root that isn't the root of a file system, e.g.
1491 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1492 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1495 static int lxc_pivot_root(const char *rootfs
)
1497 int newroot
= -1, oldroot
= -1, ret
= -1;
1499 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
1501 SYSERROR("Failed to open old root directory");
1505 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
);
1507 SYSERROR("Failed to open new root directory");
1511 /* change into new root fs */
1512 ret
= fchdir(newroot
);
1515 SYSERROR("Failed to change to new rootfs \"%s\"", rootfs
);
1519 /* pivot_root into our new root fs */
1520 ret
= pivot_root(".", ".");
1523 SYSERROR("Failed to pivot_root()");
1527 /* At this point the old-root is mounted on top of our new-root. To
1528 * unmounted it we must not be chdir'd into it, so escape back to
1531 ret
= fchdir(oldroot
);
1534 SYSERROR("Failed to enter old root directory");
1538 /* Make oldroot rslave to make sure our umounts don't propagate to the
1541 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1544 SYSERROR("Failed to make oldroot rslave");
1548 ret
= umount2(".", MNT_DETACH
);
1551 SYSERROR("Failed to detach old root directory");
1555 ret
= fchdir(newroot
);
1558 SYSERROR("Failed to re-enter new root directory");
1564 TRACE("pivot_root(\"%s\") successful", rootfs
);
1575 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1577 if (!rootfs
->path
) {
1578 DEBUG("Container does not have a rootfs");
1582 if (detect_ramfs_rootfs())
1583 return lxc_chroot(rootfs
);
1585 return lxc_pivot_root(rootfs
->mount
);
1588 static const struct id_map
*find_mapped_nsid_entry(struct lxc_conf
*conf
,
1592 struct lxc_list
*it
;
1594 struct id_map
*retmap
= NULL
;
1596 /* Shortcut for container's root mappings. */
1598 if (idtype
== ID_TYPE_UID
)
1599 return conf
->root_nsuid_map
;
1601 if (idtype
== ID_TYPE_GID
)
1602 return conf
->root_nsgid_map
;
1605 lxc_list_for_each(it
, &conf
->id_map
) {
1607 if (map
->idtype
!= idtype
)
1610 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1619 static int lxc_setup_devpts(struct lxc_conf
*conf
)
1623 char devpts_mntopts
[256];
1624 char *mntopt_sets
[5];
1625 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1627 if (conf
->pty_max
<= 0) {
1628 DEBUG("No new devpts instance will be mounted since no pts "
1629 "devices are requested");
1633 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1634 default_devpts_mntopts
, conf
->pty_max
);
1635 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1638 ret
= umount2("/dev/pts", MNT_DETACH
);
1640 SYSWARN("Failed to unmount old devpts instance");
1642 DEBUG("Unmounted old devpts instance");
1644 /* Create mountpoint for devpts instance. */
1645 ret
= mkdir("/dev/pts", 0755);
1646 if (ret
< 0 && errno
!= EEXIST
) {
1647 SYSERROR("Failed to create \"/dev/pts\" directory");
1652 mntopt_sets
[0] = devpts_mntopts
;
1654 /* !gid=5 && max= */
1655 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1657 /* gid=5 && !max= */
1658 mntopt_sets
[2] = default_devpts_mntopts
;
1660 /* !gid=5 && !max= */
1661 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1664 mntopt_sets
[4] = NULL
;
1666 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1667 /* mount new devpts instance */
1668 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1674 SYSERROR("Failed to mount new devpts instance");
1677 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1679 /* Remove any pre-existing /dev/ptmx file. */
1680 ret
= remove("/dev/ptmx");
1682 if (errno
!= ENOENT
) {
1683 SYSERROR("Failed to remove existing \"/dev/ptmx\" file");
1687 DEBUG("Removed existing \"/dev/ptmx\" file");
1690 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1691 ret
= mknod("/dev/ptmx", S_IFREG
| 0000, 0);
1692 if (ret
< 0 && errno
!= EEXIST
) {
1693 SYSERROR("Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1696 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1698 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1699 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1701 DEBUG("Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1704 /* Fallthrough and try to create a symlink. */
1705 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1708 /* Remove the dummy /dev/ptmx file we created above. */
1709 ret
= remove("/dev/ptmx");
1711 SYSERROR("Failed to remove existing \"/dev/ptmx\"");
1715 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1716 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1718 SYSERROR("Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1721 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1726 static int setup_personality(int persona
)
1730 #if HAVE_SYS_PERSONALITY_H
1734 ret
= personality(persona
);
1736 SYSERROR("Failed to set personality to \"0x%x\"", persona
);
1740 INFO("Set personality to \"0x%x\"", persona
);
1746 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1747 const struct lxc_terminal
*console
)
1750 char path
[PATH_MAX
];
1751 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1753 if (console
->path
&& !strcmp(console
->path
, "none"))
1756 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1757 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1760 /* When we are asked to setup a console we remove any previous
1761 * /dev/console bind-mounts.
1763 if (file_exists(path
)) {
1764 ret
= lxc_unstack_mountpoint(path
, false);
1766 SYSERROR("Failed to unmount \"%s\"", path
);
1769 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1773 /* For unprivileged containers autodev or automounts will already have
1774 * taken care of creating /dev/console.
1776 ret
= mknod(path
, S_IFREG
| 0000, 0);
1777 if (ret
< 0 && errno
!= EEXIST
) {
1778 SYSERROR("Failed to create console");
1782 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1784 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1785 S_IXUSR
| S_IXGRP
, console
->name
);
1789 ret
= safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs_path
);
1791 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, path
);
1795 DEBUG("Mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1799 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1800 const struct lxc_terminal
*console
,
1804 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
1805 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1807 if (console
->path
&& !strcmp(console
->path
, "none"))
1810 /* create rootfs/dev/<ttydir> directory */
1811 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1812 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1815 ret
= mkdir(path
, 0755);
1816 if (ret
&& errno
!= EEXIST
) {
1817 SYSERROR("Failed to create \"%s\"", path
);
1820 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1822 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1823 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1826 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1827 if (ret
< 0 && errno
!= EEXIST
) {
1828 SYSERROR("Failed to create \"%s\"", lxcpath
);
1832 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1833 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1836 if (file_exists(path
)) {
1837 ret
= lxc_unstack_mountpoint(path
, false);
1839 SYSERROR("Failed to unmount \"%s\"", path
);
1842 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1846 ret
= mknod(path
, S_IFREG
| 0000, 0);
1847 if (ret
< 0 && errno
!= EEXIST
) {
1848 SYSERROR("Failed to create console");
1852 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1854 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1855 S_IXUSR
| S_IXGRP
, console
->name
);
1859 /* bind mount console->name to '/dev/<ttydir>/console' */
1860 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1862 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1865 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1867 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1868 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1870 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1873 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1875 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1879 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1880 const struct lxc_terminal
*console
, char *ttydir
)
1884 return lxc_setup_dev_console(rootfs
, console
);
1886 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1889 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1891 struct mount_opt
*mo
;
1893 /* If opt is found in mount_opt, set or clear flags.
1894 * Otherwise append it to data. */
1896 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1897 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) == 0) {
1899 *flags
&= ~mo
->flag
;
1907 (void)strlcat(*data
, ",", size
);
1909 (void)strlcat(*data
, opt
, size
);
1912 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1923 s
= strdup(mntopts
);
1927 size
= strlen(s
) + 1;
1928 data
= malloc(size
);
1935 lxc_iterate_parts(p
, s
, ",")
1936 parse_mntopt(p
, mntflags
, &data
, size
);
1947 static void parse_propagationopt(char *opt
, unsigned long *flags
)
1949 struct mount_opt
*mo
;
1951 /* If opt is found in propagation_opt, set or clear flags. */
1952 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
1953 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) != 0)
1957 *flags
&= ~mo
->flag
;
1965 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
1972 s
= strdup(mntopts
);
1974 SYSERROR("Failed to allocate memory");
1979 lxc_iterate_parts(p
, s
, ",")
1980 parse_propagationopt(p
, pflags
);
1986 static void null_endofword(char *word
)
1988 while (*word
&& *word
!= ' ' && *word
!= '\t')
1993 /* skip @nfields spaces in @src */
1994 static char *get_field(char *src
, int nfields
)
1999 for (i
= 0; i
< nfields
; i
++) {
2000 while (*p
&& *p
!= ' ' && *p
!= '\t')
2012 static int mount_entry(const char *fsname
, const char *target
,
2013 const char *fstype
, unsigned long mountflags
,
2014 unsigned long pflags
, const char *data
, bool optional
,
2015 bool dev
, bool relative
, const char *rootfs
)
2018 char srcbuf
[PATH_MAX
];
2019 const char *srcpath
= fsname
;
2025 ret
= snprintf(srcbuf
, PATH_MAX
, "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2026 if (ret
< 0 || ret
>= PATH_MAX
) {
2027 ERROR("source path is too long");
2033 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2037 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2038 srcpath
? srcpath
: "(null)", target
);
2042 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2043 srcpath
? srcpath
: "(null)", target
);
2047 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2048 unsigned long rqd_flags
= 0;
2050 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
2051 "options", srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2053 if (mountflags
& MS_RDONLY
)
2054 rqd_flags
|= MS_RDONLY
;
2056 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2057 unsigned long required_flags
= rqd_flags
;
2059 if (sb
.f_flag
& MS_NOSUID
)
2060 required_flags
|= MS_NOSUID
;
2062 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2063 required_flags
|= MS_NODEV
;
2065 if (sb
.f_flag
& MS_RDONLY
)
2066 required_flags
|= MS_RDONLY
;
2068 if (sb
.f_flag
& MS_NOEXEC
)
2069 required_flags
|= MS_NOEXEC
;
2071 DEBUG("Flags for \"%s\" were %lu, required extra flags "
2072 "are %lu", srcpath
, sb
.f_flag
, required_flags
);
2074 /* If this was a bind mount request, and required_flags
2075 * does not have any flags which are not already in
2076 * mountflags, then skip the remount.
2078 if (!(mountflags
& MS_REMOUNT
)) {
2079 if (!(required_flags
& ~mountflags
) &&
2081 DEBUG("Mountflags already were %lu, "
2082 "skipping remount", mountflags
);
2087 mountflags
|= required_flags
;
2091 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2094 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2095 srcpath
? srcpath
: "(null)", target
);
2099 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2100 srcpath
? srcpath
: "(null)", target
);
2106 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2109 SYSINFO("Failed to change mount propagation "
2110 "for \"%s\" (optional)", target
);
2113 SYSERROR("Failed to change mount propagation "
2114 "for \"%s\" (optional)", target
);
2118 DEBUG("Changed mount propagation for \"%s\"", target
);
2125 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2126 srcpath
? srcpath
: "(null)", target
, fstype
);
2131 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2132 static void cull_mntent_opt(struct mntent
*mntent
)
2143 for (i
= 0; list
[i
]; i
++) {
2146 p
= strstr(mntent
->mnt_opts
, list
[i
]);
2150 p2
= strchr(p
, ',');
2152 /* no more mntopts, so just chop it here */
2157 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
2161 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2163 const struct lxc_rootfs
*rootfs
,
2164 const char *lxc_name
, const char *lxc_path
)
2169 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
2170 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2175 if (hasmntopt(mntent
, "create=dir")) {
2176 ret
= mkdir_p(path
, 0755);
2177 if (ret
< 0 && errno
!= EEXIST
) {
2178 SYSERROR("Failed to create directory \"%s\"", path
);
2183 if (!hasmntopt(mntent
, "create=file"))
2186 ret
= access(path
, F_OK
);
2196 ret
= mkdir_p(p2
, 0755);
2198 if (ret
< 0 && errno
!= EEXIST
) {
2199 SYSERROR("Failed to create directory \"%s\"", path
);
2203 ret
= mknod(path
, S_IFREG
| 0000, 0);
2204 if (ret
< 0 && errno
!= EEXIST
)
2210 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2211 * without a rootfs. */
2212 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2214 const struct lxc_rootfs
*rootfs
,
2215 const char *lxc_name
,
2216 const char *lxc_path
)
2219 unsigned long mntflags
;
2221 bool dev
, optional
, relative
;
2222 unsigned long pflags
= 0;
2223 char *rootfs_path
= NULL
;
2225 optional
= hasmntopt(mntent
, "optional") != NULL
;
2226 dev
= hasmntopt(mntent
, "dev") != NULL
;
2227 relative
= hasmntopt(mntent
, "relative") != NULL
;
2229 if (rootfs
&& rootfs
->path
)
2230 rootfs_path
= rootfs
->mount
;
2232 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2240 cull_mntent_opt(mntent
);
2242 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2246 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2250 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2251 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2257 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
2260 char path
[PATH_MAX
];
2262 /* For containers created without a rootfs all mounts are treated as
2263 * absolute paths starting at / on the host.
2265 if (mntent
->mnt_dir
[0] != '/')
2266 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
2268 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
2269 if (ret
< 0 || ret
>= sizeof(path
))
2272 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2275 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2276 const struct lxc_rootfs
*rootfs
,
2277 const char *lxc_name
,
2278 const char *lxc_path
)
2282 const char *lxcpath
;
2283 char path
[PATH_MAX
];
2286 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2290 /* If rootfs->path is a blockdev path, allow container fstab to use
2291 * <lxcpath>/<name>/rootfs" as the target prefix.
2293 ret
= snprintf(path
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2294 if (ret
< 0 || ret
>= PATH_MAX
)
2297 aux
= strstr(mntent
->mnt_dir
, path
);
2299 offset
= strlen(path
);
2304 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2306 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2309 offset
= strlen(rootfs
->path
);
2312 ret
= snprintf(path
, PATH_MAX
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2313 if (ret
< 0 || ret
>= PATH_MAX
)
2316 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2319 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2320 const struct lxc_rootfs
*rootfs
,
2321 const char *lxc_name
,
2322 const char *lxc_path
)
2325 char path
[PATH_MAX
];
2327 /* relative to root mount point */
2328 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2329 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
2332 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2335 static int mount_file_entries(const struct lxc_conf
*conf
,
2336 const struct lxc_rootfs
*rootfs
, FILE *file
,
2337 const char *lxc_name
, const char *lxc_path
)
2340 struct mntent mntent
;
2343 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2345 ret
= mount_entry_on_systemfs(&mntent
);
2346 else if (mntent
.mnt_dir
[0] != '/')
2347 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2348 lxc_name
, lxc_path
);
2350 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2351 lxc_name
, lxc_path
);
2357 INFO("Finished setting up mounts");
2361 static int setup_mount(const struct lxc_conf
*conf
,
2362 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2363 const char *lxc_name
, const char *lxc_path
)
2371 f
= setmntent(fstab
, "r");
2373 SYSERROR("Failed to open \"%s\"", fstab
);
2377 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2379 ERROR("Failed to set up mount entries");
2386 * In order for nested containers to be able to mount /proc and /sys they need
2387 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2389 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2390 * apparmor rule to deny access to them. This is mostly for convenience: The
2391 * container's root user can mount them anyway and thus has access to the two
2392 * file systems. But a non-root user in the container should not be allowed to
2393 * access them as a side effect without explicitly allowing it.
2395 static const char nesting_helpers
[] =
2396 "proc dev/.lxc/proc proc create=dir,optional\n"
2397 "sys dev/.lxc/sys sysfs create=dir,optional\n";
2399 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2400 bool include_nesting_helpers
)
2404 struct lxc_list
*iterator
;
2407 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2409 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2411 if (errno
!= ENOSYS
)
2414 fd
= lxc_make_tmpfile(template, true);
2416 SYSERROR("Could not create temporary mount file");
2420 TRACE("Created temporary mount file");
2423 SYSERROR("Could not create temporary mount file");
2427 lxc_list_for_each (iterator
, mount
) {
2430 mount_entry
= iterator
->elem
;
2431 len
= strlen(mount_entry
);
2433 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2437 ret
= lxc_write_nointr(fd
, "\n", 1);
2442 if (include_nesting_helpers
) {
2443 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2444 STRARRAYLEN(nesting_helpers
));
2445 if (ret
!= STRARRAYLEN(nesting_helpers
))
2449 ret
= lseek(fd
, 0, SEEK_SET
);
2453 return fdopen(fd
, "r+");
2456 SYSERROR("Failed to write mount entry to temporary mount file");
2461 static int setup_mount_entries(const struct lxc_conf
*conf
,
2462 const struct lxc_rootfs
*rootfs
,
2463 struct lxc_list
*mount
, const char *lxc_name
,
2464 const char *lxc_path
)
2469 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2473 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2479 static int parse_cap(const char *cap
)
2483 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2486 if (strcmp(cap
, "none") == 0)
2489 for (i
= 0; i
< end
; i
++) {
2490 if (strcmp(cap
, caps_opt
[i
].name
))
2493 capid
= caps_opt
[i
].value
;
2498 /* Try to see if it's numeric, so the user may specify
2499 * capabilities that the running kernel knows about but we
2503 capid
= strtol(cap
, &ptr
, 10);
2504 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2505 /* not a valid number */
2507 else if (capid
> lxc_caps_last_cap())
2508 /* we have a number but it's not a valid
2516 int in_caplist(int cap
, struct lxc_list
*caps
)
2519 struct lxc_list
*iterator
;
2521 lxc_list_for_each (iterator
, caps
) {
2522 capid
= parse_cap(iterator
->elem
);
2530 static int setup_caps(struct lxc_list
*caps
)
2534 struct lxc_list
*iterator
;
2536 lxc_list_for_each (iterator
, caps
) {
2539 drop_entry
= iterator
->elem
;
2541 capid
= parse_cap(drop_entry
);
2543 ERROR("unknown capability %s", drop_entry
);
2547 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2548 prctl_arg(0), prctl_arg(0));
2550 SYSERROR("Failed to remove %s capability", drop_entry
);
2553 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2556 DEBUG("Capabilities have been setup");
2560 static int dropcaps_except(struct lxc_list
*caps
)
2562 int i
, capid
, numcaps
;
2564 struct lxc_list
*iterator
;
2566 numcaps
= lxc_caps_last_cap() + 1;
2567 if (numcaps
<= 0 || numcaps
> 200)
2569 TRACE("Found %d capabilities", numcaps
);
2571 /* caplist[i] is 1 if we keep capability i */
2572 int *caplist
= alloca(numcaps
* sizeof(int));
2573 memset(caplist
, 0, numcaps
* sizeof(int));
2575 lxc_list_for_each (iterator
, caps
) {
2576 keep_entry
= iterator
->elem
;
2578 capid
= parse_cap(keep_entry
);
2583 ERROR("Unknown capability %s", keep_entry
);
2587 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2591 for (i
= 0; i
< numcaps
; i
++) {
2597 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2598 prctl_arg(0), prctl_arg(0));
2600 SYSERROR("Failed to remove capability %d", i
);
2605 DEBUG("Capabilities have been setup");
2609 static int parse_resource(const char *res
)
2615 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2616 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2617 return limit_opt
[i
].value
;
2619 /* Try to see if it's numeric, so the user may specify
2620 * resources that the running kernel knows about but
2623 ret
= lxc_safe_int(res
, &resid
);
2630 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2633 struct lxc_list
*it
;
2634 struct lxc_limit
*lim
;
2636 lxc_list_for_each (it
, limits
) {
2639 resid
= parse_resource(lim
->resource
);
2641 ERROR("Unknown resource %s", lim
->resource
);
2645 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2646 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2647 SYSERROR("Failed to set limit %s", lim
->resource
);
2651 TRACE("Setup \"%s\" limit", lim
->resource
);
2653 ERROR("Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
2661 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2663 struct lxc_list
*it
;
2664 struct lxc_sysctl
*elem
;
2667 char filename
[PATH_MAX
] = {0};
2669 lxc_list_for_each (it
, sysctls
) {
2671 tmp
= lxc_string_replace(".", "/", elem
->key
);
2673 ERROR("Failed to replace key %s", elem
->key
);
2677 ret
= snprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2679 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2680 ERROR("Error setting up sysctl parameters path");
2684 ret
= lxc_write_to_file(filename
, elem
->value
,
2685 strlen(elem
->value
), false, 0666);
2687 ERROR("Failed to setup sysctl parameters %s to %s",
2688 elem
->key
, elem
->value
);
2696 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2698 struct lxc_list
*it
;
2699 struct lxc_proc
*elem
;
2702 char filename
[PATH_MAX
] = {0};
2704 lxc_list_for_each (it
, procs
) {
2706 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2708 ERROR("Failed to replace key %s", elem
->filename
);
2712 ret
= snprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2714 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2715 ERROR("Error setting up proc filesystem path");
2719 ret
= lxc_write_to_file(filename
, elem
->value
,
2720 strlen(elem
->value
), false, 0666);
2722 ERROR("Failed to setup proc filesystem %s to %s",
2723 elem
->filename
, elem
->value
);
2731 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2733 struct lxc_conf
*lxc_conf_init(void)
2736 struct lxc_conf
*new;
2738 new = malloc(sizeof(*new));
2741 memset(new, 0, sizeof(*new));
2743 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2744 new->personality
= -1;
2746 new->console
.buffer_size
= 0;
2747 new->console
.log_path
= NULL
;
2748 new->console
.log_fd
= -1;
2749 new->console
.log_size
= 0;
2750 new->console
.path
= NULL
;
2751 new->console
.peer
= -1;
2752 new->console
.proxy
.busy
= -1;
2753 new->console
.proxy
.master
= -1;
2754 new->console
.proxy
.slave
= -1;
2755 new->console
.master
= -1;
2756 new->console
.slave
= -1;
2757 new->console
.name
[0] = '\0';
2758 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2759 new->maincmd_fd
= -1;
2760 new->monitor_signal_pdeath
= SIGKILL
;
2762 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2763 if (!new->rootfs
.mount
) {
2767 new->rootfs
.managed
= true;
2769 lxc_list_init(&new->cgroup
);
2770 lxc_list_init(&new->cgroup2
);
2771 lxc_list_init(&new->network
);
2772 lxc_list_init(&new->mount_list
);
2773 lxc_list_init(&new->caps
);
2774 lxc_list_init(&new->keepcaps
);
2775 lxc_list_init(&new->id_map
);
2776 new->root_nsuid_map
= NULL
;
2777 new->root_nsgid_map
= NULL
;
2778 lxc_list_init(&new->includes
);
2779 lxc_list_init(&new->aliens
);
2780 lxc_list_init(&new->environment
);
2781 lxc_list_init(&new->limits
);
2782 lxc_list_init(&new->sysctls
);
2783 lxc_list_init(&new->procs
);
2784 new->hooks_version
= 0;
2785 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2786 lxc_list_init(&new->hooks
[i
]);
2787 lxc_list_init(&new->groups
);
2788 lxc_list_init(&new->state_clients
);
2789 new->lsm_aa_profile
= NULL
;
2790 lxc_list_init(&new->lsm_aa_raw
);
2791 new->lsm_se_context
= NULL
;
2792 new->tmp_umount_proc
= false;
2793 new->tmp_umount_proc
= 0;
2794 new->shmount
.path_host
= NULL
;
2795 new->shmount
.path_cont
= NULL
;
2797 /* if running in a new user namespace, init and COMMAND
2798 * default to running as UID/GID 0 when using lxc-execute */
2801 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2802 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2807 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2811 char path
[PATH_MAX
];
2813 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2816 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/setgroups", pid
);
2817 if (ret
< 0 || ret
>= PATH_MAX
)
2820 fd
= open(path
, O_WRONLY
);
2821 if (fd
< 0 && errno
!= ENOENT
) {
2822 SYSERROR("Failed to open \"%s\"", path
);
2827 buflen
= STRLITERALLEN("deny\n");
2829 ret
= lxc_write_nointr(fd
, "deny\n", buflen
);
2831 if (ret
!= buflen
) {
2832 SYSERROR("Failed to write \"deny\" to "
2833 "\"/proc/%d/setgroups\"", pid
);
2836 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2840 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/%cid_map", pid
,
2841 idtype
== ID_TYPE_UID
? 'u' : 'g');
2842 if (ret
< 0 || ret
>= PATH_MAX
)
2845 fd
= open(path
, O_WRONLY
);
2847 SYSERROR("Failed to open \"%s\"", path
);
2852 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2854 if (ret
!= buf_size
) {
2855 SYSERROR("Failed to write %cid mapping to \"%s\"",
2856 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2863 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2865 * @return 1 if functional binary was found
2866 * @return 0 if binary exists but is lacking privilege
2867 * @return -ENOENT if binary does not exist
2868 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2870 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2877 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2880 path
= on_path(binary
, NULL
);
2884 ret
= stat(path
, &st
);
2890 /* Check if the binary is setuid. */
2891 if (st
.st_mode
& S_ISUID
) {
2892 DEBUG("The binary \"%s\" does have the setuid bit set", path
);
2897 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2898 /* Check if it has the CAP_SETUID capability. */
2899 if ((cap
& CAP_SETUID
) &&
2900 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2901 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2902 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2903 "and CAP_PERMITTED sets", path
);
2908 /* Check if it has the CAP_SETGID capability. */
2909 if ((cap
& CAP_SETGID
) &&
2910 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2911 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2912 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2913 "and CAP_PERMITTED sets", path
);
2918 /* If we cannot check for file capabilities we need to give the benefit
2919 * of the doubt. Otherwise we might fail even though all the necessary
2920 * file capabilities are set.
2922 DEBUG("Cannot check for file capabilites as full capability support is "
2923 "missing. Manual intervention needed");
2932 int lxc_map_ids_exec_wrapper(void *args
)
2934 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2938 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2943 char cmd_output
[PATH_MAX
];
2945 struct lxc_list
*iterator
;
2947 /* strlen("new@idmap") = 9
2951 * INTTYPE_TO_STRLEN(uint32_t)
2955 * We add some additional space to make sure that we really have
2956 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2958 int ret
= 0, gidmap
= 0, uidmap
= 0;
2959 char mapbuf
[9 + 1 + INTTYPE_TO_STRLEN(uint32_t) + 1 + LXC_IDMAPLEN
] = {0};
2960 bool had_entry
= false, use_shadow
= false;
2961 int hostuid
, hostgid
;
2963 hostuid
= geteuid();
2964 hostgid
= getegid();
2966 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2967 * ranges, then insist that root also reserve ranges in subuid. This
2968 * will protected it by preventing another user from being handed the
2971 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2972 if (uidmap
== -ENOENT
)
2973 WARN("newuidmap binary is missing");
2975 WARN("newuidmap is lacking necessary privileges");
2977 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2978 if (gidmap
== -ENOENT
)
2979 WARN("newgidmap binary is missing");
2981 WARN("newgidmap is lacking necessary privileges");
2983 if (uidmap
> 0 && gidmap
> 0) {
2984 DEBUG("Functional newuidmap and newgidmap binary found");
2987 /* In case unprivileged users run application containers via
2988 * execute() or a start*() there are valid cases where they may
2989 * only want to map their own {g,u}id. Let's not block them from
2990 * doing so by requiring geteuid() == 0.
2992 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2993 "write directly with euid %d", hostuid
);
2996 /* Check if we really need to use newuidmap and newgidmap.
2997 * If the user is only remapping his own {g,u}id, we don't need it.
2999 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
3001 lxc_list_for_each(iterator
, idmap
) {
3002 map
= iterator
->elem
;
3003 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
3004 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
3006 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
3007 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
3014 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
3015 type
++, u_or_g
= 'g') {
3019 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
3021 lxc_list_for_each(iterator
, idmap
) {
3022 map
= iterator
->elem
;
3023 if (map
->idtype
!= type
)
3028 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
3029 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
3030 use_shadow
? " " : "", map
->nsid
,
3031 map
->hostid
, map
->range
,
3032 use_shadow
? "" : "\n");
3033 if (fill
<= 0 || fill
>= left
) {
3034 /* The kernel only takes <= 4k for writes to
3035 * /proc/<pid>/{g,u}id_map
3037 SYSERROR("Too many %cid mappings defined", u_or_g
);
3046 /* Try to catch the ouput of new{g,u}idmap to make debugging
3050 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3051 lxc_map_ids_exec_wrapper
,
3054 ERROR("new%cidmap failed to write mapping \"%s\": %s",
3055 u_or_g
, cmd_output
, mapbuf
);
3058 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3060 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3062 ERROR("Failed to write mapping: %s", mapbuf
);
3065 TRACE("Wrote mapping \"%s\"", mapbuf
);
3068 memset(mapbuf
, 0, sizeof(mapbuf
));
3074 /* Return the host uid/gid to which the container root is mapped in val.
3075 * Return true if id was found, false otherwise.
3077 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
3082 struct lxc_list
*it
;
3084 if (idtype
== ID_TYPE_UID
)
3085 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3087 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3089 lxc_list_for_each (it
, &conf
->id_map
) {
3091 if (map
->idtype
!= idtype
)
3093 if (map
->nsid
!= nsid
)
3102 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
3105 struct lxc_list
*it
;
3107 lxc_list_for_each (it
, &conf
->id_map
) {
3109 if (map
->idtype
!= idtype
)
3112 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3113 return (id
- map
->hostid
) + map
->nsid
;
3119 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
3122 struct lxc_list
*it
;
3123 unsigned int freeid
= 0;
3126 lxc_list_for_each (it
, &conf
->id_map
) {
3128 if (map
->idtype
!= idtype
)
3131 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3132 freeid
= map
->nsid
+ map
->range
;
3140 int chown_mapped_root_exec_wrapper(void *args
)
3142 execvp("lxc-usernsexec", args
);
3146 /* chown_mapped_root: for an unprivileged user with uid/gid X to
3147 * chown a dir to subuid/subgid Y, he needs to run chown as root
3148 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
3149 * nsid Y is mapped to hostuid/hostgid X. That way, the container
3150 * root is privileged with respect to hostuid/hostgid X, allowing
3151 * him to do the chown.
3153 int chown_mapped_root(const char *path
, struct lxc_conf
*conf
)
3155 uid_t rootuid
, rootgid
;
3157 int hostuid
, hostgid
, ret
;
3159 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
3161 const char *args1
[] = {"lxc-usernsexec",
3166 "--", "chown", ugid
, path
,
3168 const char *args2
[] = {"lxc-usernsexec",
3174 "--", "chown", ugid
, path
,
3176 char cmd_output
[PATH_MAX
];
3178 hostuid
= geteuid();
3179 hostgid
= getegid();
3181 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
3182 ERROR("No uid mapping for container root");
3185 rootuid
= (uid_t
)val
;
3187 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
3188 ERROR("No gid mapping for container root");
3191 rootgid
= (gid_t
)val
;
3194 if (chown(path
, rootuid
, rootgid
) < 0) {
3195 ERROR("Error chowning %s", path
);
3202 if (rootuid
== hostuid
) {
3204 INFO("Container root is our uid; no need to chown");
3208 /* save the current gid of "path" */
3209 if (stat(path
, &sb
) < 0) {
3210 ERROR("Error stat %s", path
);
3214 /* Update the path argument in case this was overlayfs. */
3215 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
3216 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
3219 * A file has to be group-owned by a gid mapped into the
3220 * container, or the container won't be privileged over it.
3222 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
3223 if (sb
.st_uid
== hostuid
&&
3224 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
3225 chown(path
, -1, hostgid
) < 0) {
3226 ERROR("Failed chgrping %s", path
);
3230 /* "u:0:rootuid:1" */
3231 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
3232 if (ret
< 0 || ret
>= 100) {
3233 ERROR("Error uid printing map string");
3237 /* "u:hostuid:hostuid:1" */
3238 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
3239 if (ret
< 0 || ret
>= 100) {
3240 ERROR("Error uid printing map string");
3244 /* "g:0:rootgid:1" */
3245 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
3246 if (ret
< 0 || ret
>= 100) {
3247 ERROR("Error gid printing map string");
3251 /* "g:pathgid:rootgid+pathgid:1" */
3252 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
3253 rootgid
+ (gid_t
)sb
.st_gid
);
3254 if (ret
< 0 || ret
>= 100) {
3255 ERROR("Error gid printing map string");
3259 /* "g:hostgid:hostgid:1" */
3260 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
3261 if (ret
< 0 || ret
>= 100) {
3262 ERROR("Error gid printing map string");
3266 /* "0:pathgid" (chown) */
3267 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
3268 if (ret
< 0 || ret
>= 100) {
3269 ERROR("Error owner printing format string for chown");
3273 if (hostgid
== sb
.st_gid
)
3274 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3275 chown_mapped_root_exec_wrapper
,
3278 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3279 chown_mapped_root_exec_wrapper
,
3282 ERROR("lxc-usernsexec failed: %s", cmd_output
);
3287 /* NOTE: Must not be called from inside the container namespace! */
3288 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3292 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
3293 if (mounted
== -1) {
3294 SYSERROR("Failed to mount proc in the container");
3295 /* continue only if there is no rootfs */
3296 if (conf
->rootfs
.path
)
3298 } else if (mounted
== 1) {
3299 conf
->tmp_umount_proc
= true;
3305 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3307 if (!lxc_conf
->tmp_umount_proc
)
3310 (void)umount2("/proc", MNT_DETACH
);
3311 lxc_conf
->tmp_umount_proc
= false;
3314 /* Walk /proc/mounts and change any shared entries to slave. */
3315 void remount_all_slave(void)
3317 int memfd
, mntinfo_fd
, ret
;
3323 mntinfo_fd
= open("/proc/self/mountinfo", O_RDONLY
| O_CLOEXEC
);
3324 if (mntinfo_fd
< 0) {
3325 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
3329 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3331 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3333 if (errno
!= ENOSYS
) {
3334 SYSERROR("Failed to create temporary in-memory file");
3339 memfd
= lxc_make_tmpfile(template, true);
3342 WARN("Failed to create temporary file");
3348 copied
= lxc_sendfile_nointr(memfd
, mntinfo_fd
, NULL
, LXC_SENDFILE_MAX
);
3353 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3360 /* After a successful fdopen() memfd will be closed when calling
3361 * fclose(f). Calling close(memfd) afterwards is undefined.
3363 ret
= lseek(memfd
, 0, SEEK_SET
);
3365 SYSERROR("Failed to reset file descriptor offset");
3370 f
= fdopen(memfd
, "r");
3372 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark "
3373 "all shared. Continuing");
3378 while (getline(&line
, &len
, f
) != -1) {
3380 char *opts
, *target
;
3382 target
= get_field(line
, 4);
3386 opts
= get_field(target
, 2);
3390 null_endofword(opts
);
3391 if (!strstr(opts
, "shared"))
3394 null_endofword(target
);
3395 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3397 SYSERROR("Failed to make \"%s\" MS_SLAVE", target
);
3398 ERROR("Continuing...");
3401 TRACE("Remounted \"%s\" as MS_SLAVE", target
);
3405 TRACE("Remounted all mount table entries as MS_SLAVE");
3408 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3412 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3413 struct lxc_conf
*conf
= handler
->conf
;
3415 /* If init exists in the container, don't bind mount a static one */
3416 p
= choose_init(conf
->rootfs
.mount
);
3420 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3425 INFO("Found existing init at \"%s\"", p
);
3429 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3430 if (ret
< 0 || ret
>= PATH_MAX
)
3433 if (!file_exists(path
)) {
3434 ERROR("The file \"%s\" does not exist on host", path
);
3438 ret
= snprintf(destpath
, PATH_MAX
, "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3439 if (ret
< 0 || ret
>= PATH_MAX
)
3442 if (!file_exists(destpath
)) {
3443 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3444 if (ret
< 0 && errno
!= EEXIST
) {
3445 SYSERROR("Failed to create dummy \"%s\" file as bind mount target", destpath
);
3450 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3452 SYSERROR("Failed to bind mount lxc.init.static into container");
3456 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3460 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3462 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3463 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3467 /* This does the work of remounting / if it is shared, calling the container
3468 * pre-mount hooks, and mounting the rootfs.
3470 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3471 const char *lxcpath
)
3475 if (conf
->rootfs_setup
) {
3476 const char *path
= conf
->rootfs
.mount
;
3478 /* The rootfs was set up in another namespace. bind-mount it to
3479 * give us a mount in our own ns so we can pivot_root to it
3481 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3483 ERROR("Failed to bind mount container / onto itself");
3487 TRACE("Bind mounted container / onto itself");
3491 remount_all_slave();
3493 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3495 ERROR("Failed to run pre-mount hooks");
3499 ret
= lxc_mount_rootfs(conf
);
3501 ERROR("Failed to setup rootfs for");
3505 conf
->rootfs_setup
= true;
3509 static bool verify_start_hooks(struct lxc_conf
*conf
)
3511 char path
[PATH_MAX
];
3512 struct lxc_list
*it
;
3514 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3516 char *hookname
= it
->elem
;
3518 ret
= snprintf(path
, PATH_MAX
, "%s%s",
3519 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3521 if (ret
< 0 || ret
>= PATH_MAX
)
3524 ret
= access(path
, X_OK
);
3526 SYSERROR("Start hook \"%s\" not found in container",
3537 static bool execveat_supported(void)
3539 lxc_raw_execveat(-1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3540 if (errno
== ENOSYS
)
3546 int lxc_setup(struct lxc_handler
*handler
)
3549 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3550 struct lxc_conf
*lxc_conf
= handler
->conf
;
3552 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3554 ERROR("Failed to setup rootfs");
3558 if (handler
->nsfd
[LXC_NS_UTS
] == -1) {
3559 ret
= setup_utsname(lxc_conf
->utsname
);
3561 ERROR("Failed to setup the utsname %s", name
);
3566 ret
= lxc_setup_keyring();
3570 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
);
3572 ERROR("Failed to setup network");
3576 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3578 ERROR("Failed to send network device names and ifindices to parent");
3582 if (lxc_conf
->autodev
> 0) {
3583 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
);
3585 ERROR("Failed to mount \"/dev\"");
3590 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3591 * need to wait until other stuff has finished.
3593 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
);
3595 ERROR("Failed to setup first automatic mounts");
3599 ret
= setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3601 ERROR("Failed to setup mounts");
3605 if (lxc_conf
->is_execute
) {
3606 if (execveat_supported()) {
3608 char path
[PATH_MAX
];
3610 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3611 if (ret
< 0 || ret
>= PATH_MAX
) {
3612 ERROR("Path to init.lxc.static too long");
3616 fd
= open(path
, O_PATH
| O_CLOEXEC
);
3618 SYSERROR("Unable to open lxc.init.static");
3622 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3623 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3625 ret
= lxc_execute_bind_init(handler
);
3627 ERROR("Failed to bind-mount the lxc init system");
3633 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3634 * mounted. It is guaranteed to be mounted now either through
3635 * automatically or via fstab entries.
3637 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
);
3639 ERROR("Failed to setup remaining automatic mounts");
3643 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3645 ERROR("Failed to run mount hooks");
3649 if (lxc_conf
->autodev
> 0) {
3650 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3652 ERROR("Failed to run autodev hooks");
3656 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3658 ERROR("Failed to populate \"/dev\"");
3663 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3664 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3665 &lxc_conf
->mount_list
, name
, lxcpath
);
3667 ERROR("Failed to setup mount entries");
3672 /* Make sure any start hooks are in the container */
3673 if (!verify_start_hooks(lxc_conf
)) {
3674 ERROR("Failed to verify start hooks");
3678 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3679 lxc_conf
->ttys
.dir
);
3681 ERROR("Failed to setup console");
3685 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3687 ERROR("Failed to setup \"/dev\" symlinks");
3691 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3693 ERROR("Failed to \"/proc\" LSMs");
3697 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3699 ERROR("Failed to pivot root into rootfs");
3703 ret
= lxc_setup_devpts(lxc_conf
);
3705 ERROR("Failed to setup new devpts instance");
3709 ret
= lxc_create_ttys(handler
);
3713 ret
= setup_personality(lxc_conf
->personality
);
3715 ERROR("Failed to set personality");
3719 /* Set sysctl value to a path under /proc/sys as determined from the
3720 * key. For e.g. net.ipv4.ip_forward translated to
3721 * /proc/sys/net/ipv4/ip_forward.
3723 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3724 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3726 ERROR("Failed to setup sysctl parameters");
3731 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3732 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3733 ERROR("Container requests lxc.cap.drop and "
3734 "lxc.cap.keep: either use lxc.cap.drop or "
3735 "lxc.cap.keep, not both");
3739 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3740 ERROR("Failed to keep capabilities");
3743 } else if (setup_caps(&lxc_conf
->caps
)) {
3744 ERROR("Failed to drop capabilities");
3748 NOTICE("The container \"%s\" is set up", name
);
3753 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3756 struct lxc_list
*it
;
3759 if (strcmp(hookname
, "pre-start") == 0)
3760 which
= LXCHOOK_PRESTART
;
3761 else if (strcmp(hookname
, "start-host") == 0)
3762 which
= LXCHOOK_START_HOST
;
3763 else if (strcmp(hookname
, "pre-mount") == 0)
3764 which
= LXCHOOK_PREMOUNT
;
3765 else if (strcmp(hookname
, "mount") == 0)
3766 which
= LXCHOOK_MOUNT
;
3767 else if (strcmp(hookname
, "autodev") == 0)
3768 which
= LXCHOOK_AUTODEV
;
3769 else if (strcmp(hookname
, "start") == 0)
3770 which
= LXCHOOK_START
;
3771 else if (strcmp(hookname
, "stop") == 0)
3772 which
= LXCHOOK_STOP
;
3773 else if (strcmp(hookname
, "post-stop") == 0)
3774 which
= LXCHOOK_POSTSTOP
;
3775 else if (strcmp(hookname
, "clone") == 0)
3776 which
= LXCHOOK_CLONE
;
3777 else if (strcmp(hookname
, "destroy") == 0)
3778 which
= LXCHOOK_DESTROY
;
3782 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3784 char *hook
= it
->elem
;
3786 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3795 int lxc_clear_config_caps(struct lxc_conf
*c
)
3797 struct lxc_list
*it
, *next
;
3799 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3808 static int lxc_free_idmap(struct lxc_list
*id_map
)
3810 struct lxc_list
*it
, *next
;
3812 lxc_list_for_each_safe (it
, id_map
, next
) {
3821 int lxc_clear_idmaps(struct lxc_conf
*c
)
3823 return lxc_free_idmap(&c
->id_map
);
3826 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3828 struct lxc_list
*it
, *next
;
3830 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3839 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3841 char *global_token
, *namespaced_token
;
3842 size_t namespaced_token_len
;
3843 struct lxc_list
*it
, *next
, *list
;
3844 const char *k
= key
;
3847 if (version
== CGROUP2_SUPER_MAGIC
) {
3848 global_token
= "lxc.cgroup2";
3849 namespaced_token
= "lxc.cgroup2.";
3850 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
3852 } else if (version
== CGROUP_SUPER_MAGIC
) {
3853 global_token
= "lxc.cgroup";
3854 namespaced_token
= "lxc.cgroup.";
3855 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
3861 if (strcmp(key
, global_token
) == 0)
3863 else if (strncmp(key
, namespaced_token
, namespaced_token_len
) == 0)
3864 k
+= namespaced_token_len
;
3868 lxc_list_for_each_safe (it
, list
, next
) {
3869 struct lxc_cgroup
*cg
= it
->elem
;
3871 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3875 free(cg
->subsystem
);
3884 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3886 struct lxc_list
*it
, *next
;
3887 const char *k
= NULL
;
3890 if (strcmp(key
, "lxc.limit") == 0 || strcmp(key
, "lxc.prlimit") == 0)
3892 else if (strncmp(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")) == 0)
3893 k
= key
+ STRLITERALLEN("lxc.limit.");
3894 else if (strncmp(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")) == 0)
3895 k
= key
+ STRLITERALLEN("lxc.prlimit.");
3899 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3900 struct lxc_limit
*lim
= it
->elem
;
3902 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3906 free(lim
->resource
);
3914 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3916 struct lxc_list
*it
, *next
;
3917 const char *k
= NULL
;
3920 if (strcmp(key
, "lxc.sysctl") == 0)
3922 else if (strncmp(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")) == 0)
3923 k
= key
+ STRLITERALLEN("lxc.sysctl.");
3927 lxc_list_for_each_safe (it
, &c
->sysctls
, next
) {
3928 struct lxc_sysctl
*elem
= it
->elem
;
3930 if (!all
&& strcmp(elem
->key
, k
) != 0)
3943 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3945 struct lxc_list
*it
, *next
;
3946 const char *k
= NULL
;
3949 if (strcmp(key
, "lxc.proc") == 0)
3951 else if (strncmp(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")) == 0)
3952 k
= key
+ STRLITERALLEN("lxc.proc.");
3956 lxc_list_for_each_safe (it
, &c
->procs
, next
) {
3957 struct lxc_proc
*proc
= it
->elem
;
3959 if (!all
&& strcmp(proc
->filename
, k
) != 0)
3963 free(proc
->filename
);
3972 int lxc_clear_groups(struct lxc_conf
*c
)
3974 struct lxc_list
*it
, *next
;
3976 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
3985 int lxc_clear_environment(struct lxc_conf
*c
)
3987 struct lxc_list
*it
, *next
;
3989 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
3998 int lxc_clear_mount_entries(struct lxc_conf
*c
)
4000 struct lxc_list
*it
, *next
;
4002 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
4011 int lxc_clear_automounts(struct lxc_conf
*c
)
4017 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4020 struct lxc_list
*it
, *next
;
4021 const char *k
= NULL
;
4022 bool all
= false, done
= false;
4024 if (strcmp(key
, "lxc.hook") == 0)
4026 else if (strncmp(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")) == 0)
4027 k
= key
+ STRLITERALLEN("lxc.hook.");
4031 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
4032 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
4033 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
4044 ERROR("Invalid hook key: %s", key
);
4051 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
4053 struct lxc_list
*it
, *next
;
4055 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
4062 void lxc_clear_includes(struct lxc_conf
*conf
)
4064 struct lxc_list
*it
, *next
;
4066 lxc_list_for_each_safe (it
, &conf
->includes
, next
) {
4073 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4075 struct lxc_list
*it
, *next
;
4077 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
4086 void lxc_conf_free(struct lxc_conf
*conf
)
4091 if (current_config
== conf
)
4092 current_config
= NULL
;
4093 lxc_terminal_conf_free(&conf
->console
);
4094 free(conf
->rootfs
.mount
);
4095 free(conf
->rootfs
.bdev_type
);
4096 free(conf
->rootfs
.options
);
4097 free(conf
->rootfs
.path
);
4098 free(conf
->logfile
);
4099 if (conf
->logfd
!= -1)
4101 free(conf
->utsname
);
4102 free(conf
->ttys
.dir
);
4103 free(conf
->ttys
.tty_names
);
4106 free(conf
->execute_cmd
);
4107 free(conf
->init_cmd
);
4108 free(conf
->init_cwd
);
4109 free(conf
->unexpanded_config
);
4111 lxc_free_networks(&conf
->network
);
4112 free(conf
->lsm_aa_profile
);
4113 free(conf
->lsm_aa_profile_computed
);
4114 free(conf
->lsm_se_context
);
4115 lxc_seccomp_free(conf
);
4116 lxc_clear_config_caps(conf
);
4117 lxc_clear_config_keepcaps(conf
);
4118 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4119 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4120 lxc_clear_hooks(conf
, "lxc.hook");
4121 lxc_clear_mount_entries(conf
);
4122 lxc_clear_idmaps(conf
);
4123 lxc_clear_groups(conf
);
4124 lxc_clear_includes(conf
);
4125 lxc_clear_aliens(conf
);
4126 lxc_clear_environment(conf
);
4127 lxc_clear_limits(conf
, "lxc.prlimit");
4128 lxc_clear_sysctls(conf
, "lxc.sysctl");
4129 lxc_clear_procs(conf
, "lxc.proc");
4130 lxc_clear_apparmor_raw(conf
);
4131 free(conf
->cgroup_meta
.dir
);
4132 free(conf
->cgroup_meta
.controllers
);
4133 free(conf
->shmount
.path_host
);
4134 free(conf
->shmount
.path_cont
);
4138 struct userns_fn_data
{
4140 const char *fn_name
;
4145 static int run_userns_fn(void *data
)
4149 struct userns_fn_data
*d
= data
;
4151 /* Close write end of the pipe. */
4154 /* Wait for parent to finish establishing a new mapping in the user
4155 * namespace we are executing in.
4157 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4158 /* Close read end of the pipe. */
4164 TRACE("Calling function \"%s\"", d
->fn_name
);
4166 /* Call function to run. */
4167 return d
->fn(d
->arg
);
4170 static struct id_map
*mapped_nsid_add(struct lxc_conf
*conf
, unsigned id
,
4173 const struct id_map
*map
;
4174 struct id_map
*retmap
;
4176 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4180 retmap
= malloc(sizeof(*retmap
));
4184 memcpy(retmap
, map
, sizeof(*retmap
));
4188 static struct id_map
*find_mapped_hostid_entry(struct lxc_conf
*conf
,
4189 unsigned id
, enum idtype idtype
)
4192 struct lxc_list
*it
;
4193 struct id_map
*retmap
= NULL
;
4195 lxc_list_for_each (it
, &conf
->id_map
) {
4197 if (map
->idtype
!= idtype
)
4200 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4209 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4210 * existing one or establish a new one.
4212 static struct id_map
*mapped_hostid_add(struct lxc_conf
*conf
, uid_t id
,
4216 struct id_map
*entry
= NULL
, *tmp
= NULL
;
4218 entry
= malloc(sizeof(*entry
));
4222 /* Reuse existing mapping. */
4223 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
4225 return memcpy(entry
, tmp
, sizeof(*entry
));
4227 /* Find new mapping. */
4228 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4229 if (hostid_mapped
< 0) {
4230 DEBUG("Failed to find free mapping for id %d", id
);
4235 entry
->idtype
= type
;
4236 entry
->nsid
= hostid_mapped
;
4237 entry
->hostid
= (unsigned long)id
;
4243 struct lxc_list
*get_minimal_idmap(struct lxc_conf
*conf
)
4246 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4247 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4248 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4249 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4250 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4252 /* Find container root mappings. */
4253 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4254 if (!container_root_uid
) {
4255 DEBUG("Failed to find mapping for namespace uid %d", 0);
4259 if (euid
>= container_root_uid
->hostid
&&
4260 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4261 host_uid_map
= container_root_uid
;
4263 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4264 if (!container_root_gid
) {
4265 DEBUG("Failed to find mapping for namespace gid %d", 0);
4269 if (egid
>= container_root_gid
->hostid
&&
4270 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4271 host_gid_map
= container_root_gid
;
4273 /* Check whether the {g,u}id of the user has a mapping. */
4275 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4276 if (!host_uid_map
) {
4277 DEBUG("Failed to find mapping for uid %d", euid
);
4282 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4283 if (!host_gid_map
) {
4284 DEBUG("Failed to find mapping for gid %d", egid
);
4288 /* Allocate new {g,u}id map list. */
4289 idmap
= malloc(sizeof(*idmap
));
4292 lxc_list_init(idmap
);
4294 /* Add container root to the map. */
4295 tmplist
= malloc(sizeof(*tmplist
));
4298 lxc_list_add_elem(tmplist
, container_root_uid
);
4299 lxc_list_add_tail(idmap
, tmplist
);
4301 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4302 /* idmap will now keep track of that memory. */
4303 container_root_uid
= NULL
;
4305 /* Add container root to the map. */
4306 tmplist
= malloc(sizeof(*tmplist
));
4309 lxc_list_add_elem(tmplist
, host_uid_map
);
4310 lxc_list_add_tail(idmap
, tmplist
);
4312 /* idmap will now keep track of that memory. */
4313 container_root_uid
= NULL
;
4314 /* idmap will now keep track of that memory. */
4315 host_uid_map
= NULL
;
4317 tmplist
= malloc(sizeof(*tmplist
));
4320 lxc_list_add_elem(tmplist
, container_root_gid
);
4321 lxc_list_add_tail(idmap
, tmplist
);
4323 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4324 /* idmap will now keep track of that memory. */
4325 container_root_gid
= NULL
;
4327 tmplist
= malloc(sizeof(*tmplist
));
4330 lxc_list_add_elem(tmplist
, host_gid_map
);
4331 lxc_list_add_tail(idmap
, tmplist
);
4333 /* idmap will now keep track of that memory. */
4334 container_root_gid
= NULL
;
4335 /* idmap will now keep track of that memory. */
4336 host_gid_map
= NULL
;
4338 TRACE("Allocated minimal idmapping");
4343 lxc_free_idmap(idmap
);
4346 if (container_root_uid
)
4347 free(container_root_uid
);
4348 if (container_root_gid
)
4349 free(container_root_gid
);
4350 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4352 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4358 /* Run a function in a new user namespace.
4359 * The caller's euid/egid will be mapped if it is not already.
4360 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4361 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4362 * This means we require only to establish a mapping from:
4363 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4364 * - the container root -> some sub{g,u}id
4365 * The former we add, if the user did not specifiy a mapping. The latter we
4366 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
4367 * there to start the container in the first place.
4369 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4370 const char *fn_name
)
4374 struct userns_fn_data d
;
4375 struct lxc_list
*idmap
;
4376 int ret
= -1, status
= -1;
4382 idmap
= get_minimal_idmap(conf
);
4386 ret
= pipe2(p
, O_CLOEXEC
);
4388 SYSERROR("Failed to create pipe");
4392 d
.fn_name
= fn_name
;
4397 /* Clone child in new user namespace. */
4398 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
);
4400 ERROR("Failed to clone process in new user namespace");
4407 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4408 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4410 struct lxc_list
*it
;
4412 lxc_list_for_each (it
, idmap
) {
4414 TRACE("Establishing %cid mapping for \"%d\" in new "
4415 "user namespace: nsuid %lu - hostid %lu - range "
4417 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4418 map
->nsid
, map
->hostid
, map
->range
);
4422 /* Set up {g,u}id mapping for user namespace of child process. */
4423 ret
= lxc_map_ids(idmap
, pid
);
4425 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4429 /* Tell child to proceed. */
4430 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4431 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4440 /* Wait for child to finish. */
4442 status
= wait_for_pid(pid
);
4450 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4451 const char *fn_name
)
4457 struct lxc_list
*cur
;
4458 struct userns_fn_data d
;
4461 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4462 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4463 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4468 ret
= pipe2(p
, O_CLOEXEC
);
4470 SYSERROR("opening pipe");
4474 d
.fn_name
= fn_name
;
4479 /* Clone child in new user namespace. */
4480 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
4482 ERROR("Failed to clone process in new user namespace");
4492 /* Allocate new {g,u}id map list. */
4493 idmap
= malloc(sizeof(*idmap
));
4496 lxc_list_init(idmap
);
4498 /* Find container root. */
4499 lxc_list_for_each (cur
, &conf
->id_map
) {
4500 struct id_map
*tmpmap
;
4502 tmplist
= malloc(sizeof(*tmplist
));
4506 tmpmap
= malloc(sizeof(*tmpmap
));
4512 memset(tmpmap
, 0, sizeof(*tmpmap
));
4513 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4514 tmplist
->elem
= tmpmap
;
4516 lxc_list_add_tail(idmap
, tmplist
);
4520 if (map
->idtype
== ID_TYPE_UID
)
4521 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4524 if (map
->idtype
== ID_TYPE_GID
)
4525 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4531 if (map
->idtype
== ID_TYPE_UID
)
4532 if (container_root_uid
== NULL
)
4533 container_root_uid
= map
;
4535 if (map
->idtype
== ID_TYPE_GID
)
4536 if (container_root_gid
== NULL
)
4537 container_root_gid
= map
;
4540 if (!container_root_uid
|| !container_root_gid
) {
4541 ERROR("No mapping for container root found");
4545 /* Check whether the {g,u}id of the user has a mapping. */
4547 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4549 host_uid_map
= container_root_uid
;
4552 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4554 host_gid_map
= container_root_gid
;
4556 if (!host_uid_map
) {
4557 DEBUG("Failed to find mapping for uid %d", euid
);
4561 if (!host_gid_map
) {
4562 DEBUG("Failed to find mapping for gid %d", egid
);
4566 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4567 /* Add container root to the map. */
4568 tmplist
= malloc(sizeof(*tmplist
));
4571 lxc_list_add_elem(tmplist
, host_uid_map
);
4572 lxc_list_add_tail(idmap
, tmplist
);
4574 /* idmap will now keep track of that memory. */
4575 host_uid_map
= NULL
;
4577 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4578 tmplist
= malloc(sizeof(*tmplist
));
4581 lxc_list_add_elem(tmplist
, host_gid_map
);
4582 lxc_list_add_tail(idmap
, tmplist
);
4584 /* idmap will now keep track of that memory. */
4585 host_gid_map
= NULL
;
4587 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4588 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4589 lxc_list_for_each (cur
, idmap
) {
4591 TRACE("establishing %cid mapping for \"%d\" in new "
4592 "user namespace: nsuid %lu - hostid %lu - range "
4594 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4595 map
->nsid
, map
->hostid
, map
->range
);
4599 /* Set up {g,u}id mapping for user namespace of child process. */
4600 ret
= lxc_map_ids(idmap
, pid
);
4602 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4606 /* Tell child to proceed. */
4607 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4608 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4617 /* Wait for child to finish. */
4619 ret
= wait_for_pid(pid
);
4622 lxc_free_idmap(idmap
);
4626 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4628 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4634 /* not thread-safe, do not use from api without first forking */
4635 static char *getuname(void)
4637 struct passwd pwent
;
4638 struct passwd
*pwentp
= NULL
;
4644 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
4648 buf
= malloc(bufsize
);
4652 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
4655 WARN("Could not find matched password record.");
4657 ERROR("Failed to get password record - %u", geteuid());
4662 username
= strdup(pwent
.pw_name
);
4668 /* not thread-safe, do not use from api without first forking */
4669 static char *getgname(void)
4672 struct group
*grentp
= NULL
;
4678 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
4682 buf
= malloc(bufsize
);
4686 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
4689 WARN("Could not find matched group record");
4691 ERROR("Failed to get group record - %u", getegid());
4696 grname
= strdup(grent
.gr_name
);
4702 /* not thread-safe, do not use from api without first forking */
4703 void suggest_default_idmap(void)
4705 char *uname
, *gname
;
4707 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4721 f
= fopen(subuidfile
, "r");
4723 ERROR("Your system is not configured with subuids");
4729 while (getline(&line
, &len
, f
) != -1) {
4731 size_t no_newline
= 0;
4733 p
= strchr(line
, ':');
4741 if (strcmp(line
, uname
))
4744 p2
= strchr(p
, ':');
4751 no_newline
= strcspn(p2
, "\n");
4752 p2
[no_newline
] = '\0';
4754 if (lxc_safe_uint(p
, &uid
) < 0)
4755 WARN("Could not parse UID");
4756 if (lxc_safe_uint(p2
, &urange
) < 0)
4757 WARN("Could not parse UID range");
4761 f
= fopen(subgidfile
, "r");
4763 ERROR("Your system is not configured with subgids");
4769 while (getline(&line
, &len
, f
) != -1) {
4771 size_t no_newline
= 0;
4773 p
= strchr(line
, ':');
4781 if (strcmp(line
, uname
))
4784 p2
= strchr(p
, ':');
4791 no_newline
= strcspn(p2
, "\n");
4792 p2
[no_newline
] = '\0';
4794 if (lxc_safe_uint(p
, &gid
) < 0)
4795 WARN("Could not parse GID");
4796 if (lxc_safe_uint(p2
, &grange
) < 0)
4797 WARN("Could not parse GID range");
4803 if (!urange
|| !grange
) {
4804 ERROR("You do not have subuids or subgids allocated");
4805 ERROR("Unprivileged containers require subuids and subgids");
4811 ERROR("You must either run as root, or define uid mappings");
4812 ERROR("To pass uid mappings to lxc-create, you could create");
4813 ERROR("~/.config/lxc/default.conf:");
4814 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4815 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4816 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4822 static void free_cgroup_settings(struct lxc_list
*result
)
4824 struct lxc_list
*iterator
, *next
;
4826 lxc_list_for_each_safe (iterator
, result
, next
) {
4827 lxc_list_del(iterator
);
4833 /* Return the list of cgroup_settings sorted according to the following rules
4834 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4836 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
4838 struct lxc_list
*result
;
4839 struct lxc_cgroup
*cg
= NULL
;
4840 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
4842 result
= malloc(sizeof(*result
));
4845 lxc_list_init(result
);
4847 /* Iterate over the cgroup settings and copy them to the output list. */
4848 lxc_list_for_each (it
, cgroup_settings
) {
4849 item
= malloc(sizeof(*item
));
4851 free_cgroup_settings(result
);
4855 item
->elem
= it
->elem
;
4857 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4858 /* Store the memsw_limit location */
4860 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 &&
4861 memsw_limit
!= NULL
) {
4862 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4863 * before lxc.cgroup.memory.limit_in_bytes, swap these
4865 item
->elem
= memsw_limit
->elem
;
4866 memsw_limit
->elem
= it
->elem
;
4868 lxc_list_add_tail(result
, item
);