1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <linux/loop.h>
15 #include <netinet/in.h>
22 #include <sys/mount.h>
23 #include <sys/param.h>
24 #include <sys/prctl.h>
25 #include <sys/sendfile.h>
26 #include <sys/socket.h>
28 #include <sys/syscall.h>
29 #include <sys/sysmacros.h>
30 #include <sys/types.h>
31 #include <sys/utsname.h>
39 #include "cgroup2_devices.h"
43 #include "confile_utils.h"
48 #include "lxcseccomp.h"
50 #include "memory_utils.h"
51 #include "mount_utils.h"
52 #include "namespace.h"
55 #include "process_utils.h"
59 #include "storage/overlay.h"
60 #include "syscall_wrappers.h"
66 #include <sys/mkdev.h>
70 #include <sys/statvfs.h>
76 #include <../include/openpty.h>
80 #include <sys/capability.h>
83 #if HAVE_SYS_PERSONALITY_H
84 #include <sys/personality.h>
88 #include "include/strlcat.h"
92 #include <../include/lxcmntent.h>
97 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
98 #include <../include/prlimit.h>
101 lxc_log_define(conf
, lxc
);
103 /* The lxc_conf of the container currently being worked on in an API call.
104 * This is used in the error calls.
107 thread_local
struct lxc_conf
*current_config
;
109 struct lxc_conf
*current_config
;
112 char *lxchook_names
[NUM_LXC_HOOKS
] = {
141 static struct mount_opt mount_opt
[] = {
142 { "async", 1, MS_SYNCHRONOUS
},
143 { "atime", 1, MS_NOATIME
},
144 { "bind", 0, MS_BIND
},
145 { "defaults", 0, 0 },
146 { "dev", 1, MS_NODEV
},
147 { "diratime", 1, MS_NODIRATIME
},
148 { "dirsync", 0, MS_DIRSYNC
},
149 { "exec", 1, MS_NOEXEC
},
150 { "lazytime", 0, MS_LAZYTIME
},
151 { "mand", 0, MS_MANDLOCK
},
152 { "noatime", 0, MS_NOATIME
},
153 { "nodev", 0, MS_NODEV
},
154 { "nodiratime", 0, MS_NODIRATIME
},
155 { "noexec", 0, MS_NOEXEC
},
156 { "nomand", 1, MS_MANDLOCK
},
157 { "norelatime", 1, MS_RELATIME
},
158 { "nostrictatime", 1, MS_STRICTATIME
},
159 { "nosuid", 0, MS_NOSUID
},
160 { "rbind", 0, MS_BIND
|MS_REC
},
161 { "relatime", 0, MS_RELATIME
},
162 { "remount", 0, MS_REMOUNT
},
163 { "ro", 0, MS_RDONLY
},
164 { "rw", 1, MS_RDONLY
},
165 { "strictatime", 0, MS_STRICTATIME
},
166 { "suid", 1, MS_NOSUID
},
167 { "sync", 0, MS_SYNCHRONOUS
},
171 static struct mount_opt propagation_opt
[] = {
172 { "private", 0, MS_PRIVATE
},
173 { "shared", 0, MS_SHARED
},
174 { "slave", 0, MS_SLAVE
},
175 { "unbindable", 0, MS_UNBINDABLE
},
176 { "rprivate", 0, MS_PRIVATE
|MS_REC
},
177 { "rshared", 0, MS_SHARED
|MS_REC
},
178 { "rslave", 0, MS_SLAVE
|MS_REC
},
179 { "runbindable", 0, MS_UNBINDABLE
|MS_REC
},
183 static struct caps_opt caps_opt
[] = {
185 { "chown", CAP_CHOWN
},
186 { "dac_override", CAP_DAC_OVERRIDE
},
187 { "dac_read_search", CAP_DAC_READ_SEARCH
},
188 { "fowner", CAP_FOWNER
},
189 { "fsetid", CAP_FSETID
},
190 { "kill", CAP_KILL
},
191 { "setgid", CAP_SETGID
},
192 { "setuid", CAP_SETUID
},
193 { "setpcap", CAP_SETPCAP
},
194 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
195 { "net_bind_service", CAP_NET_BIND_SERVICE
},
196 { "net_broadcast", CAP_NET_BROADCAST
},
197 { "net_admin", CAP_NET_ADMIN
},
198 { "net_raw", CAP_NET_RAW
},
199 { "ipc_lock", CAP_IPC_LOCK
},
200 { "ipc_owner", CAP_IPC_OWNER
},
201 { "sys_module", CAP_SYS_MODULE
},
202 { "sys_rawio", CAP_SYS_RAWIO
},
203 { "sys_chroot", CAP_SYS_CHROOT
},
204 { "sys_ptrace", CAP_SYS_PTRACE
},
205 { "sys_pacct", CAP_SYS_PACCT
},
206 { "sys_admin", CAP_SYS_ADMIN
},
207 { "sys_boot", CAP_SYS_BOOT
},
208 { "sys_nice", CAP_SYS_NICE
},
209 { "sys_resource", CAP_SYS_RESOURCE
},
210 { "sys_time", CAP_SYS_TIME
},
211 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
212 { "mknod", CAP_MKNOD
},
213 { "lease", CAP_LEASE
},
214 #ifdef CAP_AUDIT_READ
215 { "audit_read", CAP_AUDIT_READ
},
217 #ifdef CAP_AUDIT_WRITE
218 { "audit_write", CAP_AUDIT_WRITE
},
220 #ifdef CAP_AUDIT_CONTROL
221 { "audit_control", CAP_AUDIT_CONTROL
},
223 { "setfcap", CAP_SETFCAP
},
224 { "mac_override", CAP_MAC_OVERRIDE
},
225 { "mac_admin", CAP_MAC_ADMIN
},
227 { "syslog", CAP_SYSLOG
},
229 #ifdef CAP_WAKE_ALARM
230 { "wake_alarm", CAP_WAKE_ALARM
},
232 #ifdef CAP_BLOCK_SUSPEND
233 { "block_suspend", CAP_BLOCK_SUSPEND
},
238 static struct limit_opt limit_opt
[] = {
243 { "core", RLIMIT_CORE
},
246 { "cpu", RLIMIT_CPU
},
249 { "data", RLIMIT_DATA
},
252 { "fsize", RLIMIT_FSIZE
},
255 { "locks", RLIMIT_LOCKS
},
257 #ifdef RLIMIT_MEMLOCK
258 { "memlock", RLIMIT_MEMLOCK
},
260 #ifdef RLIMIT_MSGQUEUE
261 { "msgqueue", RLIMIT_MSGQUEUE
},
264 { "nice", RLIMIT_NICE
},
267 { "nofile", RLIMIT_NOFILE
},
270 { "nproc", RLIMIT_NPROC
},
273 { "rss", RLIMIT_RSS
},
276 { "rtprio", RLIMIT_RTPRIO
},
279 { "rttime", RLIMIT_RTTIME
},
281 #ifdef RLIMIT_SIGPENDING
282 { "sigpending", RLIMIT_SIGPENDING
},
285 { "stack", RLIMIT_STACK
},
289 static int run_buffer(char *buffer
)
291 __do_free
char *output
= NULL
;
292 __do_lxc_pclose
struct lxc_popen_FILE
*f
= NULL
;
295 f
= lxc_popen(buffer
);
297 return log_error_errno(-1, errno
, "Failed to popen() %s", buffer
);
299 output
= malloc(LXC_LOG_BUFFER_SIZE
);
301 return log_error_errno(-1, ENOMEM
, "Failed to allocate memory for %s", buffer
);
305 return log_error_errno(-1, errno
, "Failed to retrieve underlying file descriptor");
307 for (int i
= 0; i
< 10; i
++) {
310 bytes_read
= lxc_read_nointr(fd
, output
, LXC_LOG_BUFFER_SIZE
- 1);
311 if (bytes_read
> 0) {
312 output
[bytes_read
] = '\0';
313 DEBUG("Script %s produced output: %s", buffer
, output
);
320 ret
= lxc_pclose(move_ptr(f
));
322 return log_error_errno(-1, errno
, "Script exited with error");
323 else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0)
324 return log_error(-1, "Script exited with status %d", WEXITSTATUS(ret
));
325 else if (WIFSIGNALED(ret
))
326 return log_error(-1, "Script terminated by signal %d", WTERMSIG(ret
));
331 int run_script_argv(const char *name
, unsigned int hook_version
,
332 const char *section
, const char *script
,
333 const char *hookname
, char **argv
)
335 __do_free
char *buffer
= NULL
;
339 if (hook_version
== 0)
340 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
341 script
, name
, section
);
343 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
345 for (i
= 0; argv
&& argv
[i
]; i
++)
346 size
+= strlen(argv
[i
]) + 1;
348 size
+= STRLITERALLEN("exec");
350 size
+= strlen(script
);
356 if (hook_version
== 0) {
357 size
+= strlen(hookname
);
360 size
+= strlen(name
);
363 size
+= strlen(section
);
370 buffer
= malloc(size
);
374 if (hook_version
== 0)
375 buf_pos
= snprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
377 buf_pos
= snprintf(buffer
, size
, "exec %s", script
);
378 if (buf_pos
< 0 || (size_t)buf_pos
>= size
)
379 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
381 if (hook_version
== 1) {
382 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
384 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_TYPE=%s", hookname
);
386 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
388 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
390 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_SECTION=%s", section
);
391 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
393 if (strcmp(section
, "net") == 0) {
396 if (!argv
|| !argv
[0])
399 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
401 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_TYPE=%s", argv
[0]);
402 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
404 parent
= argv
[1] ? argv
[1] : "";
406 if (strcmp(argv
[0], "macvlan") == 0) {
407 ret
= setenv("LXC_NET_PARENT", parent
, 1);
409 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
410 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
411 } else if (strcmp(argv
[0], "phys") == 0) {
412 ret
= setenv("LXC_NET_PARENT", parent
, 1);
414 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
415 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
416 } else if (strcmp(argv
[0], "veth") == 0) {
417 char *peer
= argv
[2] ? argv
[2] : "";
419 ret
= setenv("LXC_NET_PEER", peer
, 1);
421 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PEER=%s", peer
);
422 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
424 ret
= setenv("LXC_NET_PARENT", parent
, 1);
426 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
427 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
432 for (i
= 0; argv
&& argv
[i
]; i
++) {
433 size_t len
= size
- buf_pos
;
435 ret
= snprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
436 if (ret
< 0 || (size_t)ret
>= len
)
437 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
441 return run_buffer(buffer
);
444 int run_script(const char *name
, const char *section
, const char *script
, ...)
446 __do_free
char *buffer
= NULL
;
452 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
453 script
, name
, section
);
455 va_start(ap
, script
);
456 while ((p
= va_arg(ap
, char *)))
457 size
+= strlen(p
) + 1;
460 size
+= STRLITERALLEN("exec");
461 size
+= strlen(script
);
462 size
+= strlen(name
);
463 size
+= strlen(section
);
469 buffer
= must_realloc(NULL
, size
);
470 ret
= snprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
471 if (ret
< 0 || ret
>= size
)
474 va_start(ap
, script
);
475 while ((p
= va_arg(ap
, char *))) {
476 int len
= size
- ret
;
478 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
479 if (rc
< 0 || rc
>= len
) {
487 return run_buffer(buffer
);
491 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
492 * the duration of the container run, to prevent the container from marking
493 * the underlying fs readonly on shutdown. unlink the file immediately so
494 * no name pollution is happens.
495 * don't unlink on NFS to avoid random named stale handles.
496 * return -1 on error.
497 * return -2 if nothing needed to be pinned.
498 * return an open fd (>=0) if we pinned it.
500 int pin_rootfs(const char *rootfs
)
502 __do_free
char *absrootfs
= NULL
;
504 char absrootfspin
[PATH_MAX
];
508 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
511 absrootfs
= realpath(rootfs
, NULL
);
515 ret
= stat(absrootfs
, &s
);
519 if (!S_ISDIR(s
.st_mode
))
522 ret
= snprintf(absrootfspin
, sizeof(absrootfspin
), "%s/.lxc-keep", absrootfs
);
523 if (ret
< 0 || (size_t)ret
>= sizeof(absrootfspin
))
526 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
| S_IRUSR
| O_CLOEXEC
);
530 ret
= fstatfs (fd
, &sfs
);
534 if (sfs
.f_type
== NFS_SUPER_MAGIC
)
535 return log_debug(fd
, "Rootfs on NFS, not unlinking pin file \"%s\"", absrootfspin
);
537 (void)unlink(absrootfspin
);
542 /* If we are asking to remount something, make sure that any NOEXEC etc are
545 unsigned long add_required_remount_flags(const char *s
, const char *d
,
551 unsigned long required_flags
= 0;
559 ret
= statvfs(s
, &sb
);
563 if (flags
& MS_REMOUNT
) {
564 if (sb
.f_flag
& MS_NOSUID
)
565 required_flags
|= MS_NOSUID
;
566 if (sb
.f_flag
& MS_NODEV
)
567 required_flags
|= MS_NODEV
;
568 if (sb
.f_flag
& MS_RDONLY
)
569 required_flags
|= MS_RDONLY
;
570 if (sb
.f_flag
& MS_NOEXEC
)
571 required_flags
|= MS_NOEXEC
;
574 if (sb
.f_flag
& MS_NOATIME
)
575 required_flags
|= MS_NOATIME
;
576 if (sb
.f_flag
& MS_NODIRATIME
)
577 required_flags
|= MS_NODIRATIME
;
578 if (sb
.f_flag
& MS_LAZYTIME
)
579 required_flags
|= MS_LAZYTIME
;
580 if (sb
.f_flag
& MS_RELATIME
)
581 required_flags
|= MS_RELATIME
;
582 if (sb
.f_flag
& MS_STRICTATIME
)
583 required_flags
|= MS_STRICTATIME
;
585 return flags
| required_flags
;
591 static int add_shmount_to_list(struct lxc_conf
*conf
)
593 char new_mount
[PATH_MAX
];
594 /* Offset for the leading '/' since the path_cont
595 * is absolute inside the container.
597 int offset
= 1, ret
= -1;
599 ret
= snprintf(new_mount
, sizeof(new_mount
),
600 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
601 conf
->shmount
.path_cont
+ offset
);
602 if (ret
< 0 || (size_t)ret
>= sizeof(new_mount
))
605 return add_elem_to_mount_list(new_mount
, conf
);
608 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
615 const char *destination
;
619 } default_mounts
[] = {
620 /* Read-only bind-mounting... In older kernels, doing that
621 * required to do one MS_BIND mount and then
622 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
623 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
624 * onwards. However, this apparently does not work on kernel
625 * 3.8. Unfortunately, on that very same kernel, doing the same
626 * trick as above doesn't seem to work either, there one needs
627 * to ALSO specify MS_BIND for the remount, otherwise the
628 * entire fs is remounted read-only or the mount fails because
629 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
630 * kernels as low as 2.6.32...
632 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
633 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
634 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
635 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
636 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
637 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
638 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
639 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
640 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
641 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
642 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
643 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
644 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
645 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
646 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
647 { 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
},
648 { 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
},
649 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
652 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
653 __do_free
char *destination
= NULL
, *source
= NULL
;
655 unsigned long mflags
;
656 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
659 if (default_mounts
[i
].source
) {
660 /* will act like strdup if %r is not present */
661 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
666 if (!default_mounts
[i
].destination
)
667 return log_error(-1, "BUG: auto mounts destination %d was NULL", i
);
669 /* will act like strdup if %r is not present */
670 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
674 mflags
= add_required_remount_flags(source
, destination
,
675 default_mounts
[i
].flags
);
676 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
,
677 mflags
, default_mounts
[i
].options
,
678 conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
680 if (r
< 0 && errno
== ENOENT
) {
681 INFO("Mount source or target for \"%s\" on \"%s\" does not exist. Skipping", source
, destination
);
684 SYSERROR("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
693 if (flags
& LXC_AUTO_CGROUP_MASK
) {
696 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
697 /* If the type of cgroup mount was not specified, it depends on
698 * the container's capabilities as to what makes sense: if we
699 * have CAP_SYS_ADMIN, the read-only part can be remounted
700 * read-write anyway, so we may as well default to read-write;
701 * then the admin will not be given a false sense of security.
702 * (And if they really want mixed r/o r/w, then they can
703 * explicitly specify :mixed.) OTOH, if the container lacks
704 * CAP_SYS_ADMIN, do only default to :mixed, because then the
705 * container can't remount it read-write.
707 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
708 int has_sys_admin
= 0;
710 if (!lxc_list_empty(&conf
->keepcaps
))
711 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
713 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
715 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
716 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
718 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
721 if (flags
& LXC_AUTO_CGROUP_FORCE
)
722 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
724 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
,
726 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
728 return log_error_errno(-1, errno
, "Failed to mount \"/sys/fs/cgroup\"");
731 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
732 int ret
= add_shmount_to_list(conf
);
734 return log_error(-1, "Failed to add shmount entry to container config");
740 static int setup_utsname(struct utsname
*utsname
)
747 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
749 return log_error_errno(-1, errno
, "Failed to set the hostname to \"%s\"",
752 INFO("Set hostname to \"%s\"", utsname
->nodename
);
757 struct dev_symlinks
{
762 static const struct dev_symlinks dev_symlinks
[] = {
763 { "/proc/self/fd", "fd" },
764 { "/proc/self/fd/0", "stdin" },
765 { "/proc/self/fd/1", "stdout" },
766 { "/proc/self/fd/2", "stderr" },
769 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
775 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
776 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
778 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s",
779 rootfs
->path
? rootfs
->mount
: "", d
->name
);
780 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
783 /* Stat the path first. If we don't get an error accept it as
784 * is and don't try to create it
786 ret
= stat(path
, &s
);
790 ret
= symlink(d
->oldpath
, path
);
791 if (ret
&& errno
!= EEXIST
) {
793 WARN("Failed to create \"%s\". Read-only filesystem", path
);
795 return log_error_errno(-1, errno
, "Failed to create \"%s\"", path
);
802 /* Build a space-separate list of ptys to pass to systemd. */
803 static bool append_ttyname(char **pp
, char *name
)
809 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
813 sprintf(*pp
, "container_ttys=%s", name
);
817 size
= strlen(*pp
) + strlen(name
) + 2;
818 p
= realloc(*pp
, size
);
823 (void)strlcat(p
, " ", size
);
824 (void)strlcat(p
, name
, size
);
829 static int lxc_setup_ttys(struct lxc_conf
*conf
)
832 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
833 char *ttydir
= ttys
->dir
;
834 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
836 if (!conf
->rootfs
.path
)
839 for (i
= 0; i
< ttys
->max
; i
++) {
840 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
842 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
843 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
847 /* create dev/lxc/tty%d" */
848 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
849 "/dev/%s/tty%d", ttydir
, i
+ 1);
850 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
853 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
854 if (ret
< 0 && errno
!= EEXIST
) {
855 SYSERROR("Failed to create \"%s\"", lxcpath
);
860 if (ret
< 0 && errno
!= ENOENT
) {
861 SYSERROR("Failed to unlink \"%s\"", path
);
865 ret
= mount(tty
->name
, lxcpath
, "none", MS_BIND
, 0);
867 SYSWARN("Failed to bind mount \"%s\" onto \"%s\"", tty
->name
, lxcpath
);
870 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, lxcpath
);
872 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
874 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
877 ret
= symlink(lxcpath
, path
);
879 return log_error_errno(-1, errno
, "Failed to create symlink \"%s\" -> \"%s\"", path
, lxcpath
);
881 /* If we populated /dev, then we need to create
884 ret
= mknod(path
, S_IFREG
| 0000, 0);
885 if (ret
< 0) /* this isn't fatal, continue */
886 SYSERROR("Failed to create \"%s\"", path
);
888 ret
= mount(tty
->name
, path
, "none", MS_BIND
, 0);
890 SYSERROR("Failed to mount '%s'->'%s'", tty
->name
, path
);
894 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, path
);
897 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
))
898 return log_error(-1, "Error setting up container_ttys string");
901 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
905 define_cleanup_function(struct lxc_tty_info
*, lxc_delete_tty
);
907 static int lxc_allocate_ttys(struct lxc_conf
*conf
)
909 struct lxc_terminal_info
*tty_new
= NULL
;
911 call_cleaner(lxc_delete_tty
) struct lxc_tty_info
*ttys
= &conf
->ttys
;
913 /* no tty in the configuration */
917 tty_new
= malloc(sizeof(struct lxc_terminal_info
) * ttys
->max
);
922 for (size_t i
= 0; i
< ttys
->max
; i
++) {
923 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
927 ret
= openpty(&tty
->ptx
, &tty
->pty
, NULL
, NULL
, NULL
);
930 return log_error_errno(-ENOTTY
, ENOTTY
, "Failed to create tty %zu", i
);
933 ret
= ttyname_r(tty
->pty
, tty
->name
, sizeof(tty
->name
));
936 return log_error_errno(-ENOTTY
, ENOTTY
, "Failed to retrieve name of tty %zu pty", i
);
939 DEBUG("Created tty \"%s\" with ptx fd %d and pty fd %d",
940 tty
->name
, tty
->ptx
, tty
->pty
);
942 /* Prevent leaking the file descriptors to the container */
943 ret
= fd_cloexec(tty
->ptx
, true);
945 SYSWARN("Failed to set FD_CLOEXEC flag on ptx fd %d of tty device \"%s\"",
946 tty
->ptx
, tty
->name
);
948 ret
= fd_cloexec(tty
->pty
, true);
950 SYSWARN("Failed to set FD_CLOEXEC flag on pty fd %d of tty device \"%s\"",
951 tty
->pty
, tty
->name
);
956 INFO("Finished creating %zu tty devices", ttys
->max
);
961 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
966 for (int i
= 0; i
< ttys
->max
; i
++) {
967 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
968 close_prot_errno_disarm(tty
->ptx
);
969 close_prot_errno_disarm(tty
->pty
);
972 free_disarm(ttys
->tty
);
975 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
979 struct lxc_conf
*conf
= handler
->conf
;
980 struct lxc_tty_info
*ttys
= &conf
->ttys
;
981 int sock
= handler
->data_sock
[0];
986 for (i
= 0; i
< ttys
->max
; i
++) {
988 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
990 ttyfds
[0] = tty
->ptx
;
991 ttyfds
[1] = tty
->pty
;
993 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
997 TRACE("Sent tty \"%s\" with ptx fd %d and pty fd %d to parent",
998 tty
->name
, tty
->ptx
, tty
->pty
);
1002 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1004 TRACE("Sent %zu ttys to parent", ttys
->max
);
1009 static int lxc_create_ttys(struct lxc_handler
*handler
)
1012 struct lxc_conf
*conf
= handler
->conf
;
1014 ret
= lxc_allocate_ttys(conf
);
1016 ERROR("Failed to allocate ttys");
1020 ret
= lxc_send_ttys_to_parent(handler
);
1022 ERROR("Failed to send ttys to parent");
1026 if (!conf
->is_execute
) {
1027 ret
= lxc_setup_ttys(conf
);
1029 ERROR("Failed to setup ttys");
1034 if (conf
->ttys
.tty_names
) {
1035 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1037 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1043 lxc_delete_tty(&conf
->ttys
);
1048 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1049 * error, log it but don't fail yet.
1051 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1052 int autodevtmpfssize
, const char *lxcpath
)
1054 const char *path
= rootfs
->path
? rootfs
->mount
: NULL
;
1057 char mount_options
[128];
1059 INFO("Preparing \"/dev\"");
1061 sprintf(mount_options
, "size=%d,mode=755", (autodevtmpfssize
!= 0) ? autodevtmpfssize
: 500000);
1062 DEBUG("Using mount options: %s", mount_options
);
1064 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1065 ret
= mkdirat(rootfs
->mntpt_fd
, "dev" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1066 if (ret
< 0 && errno
!= EEXIST
) {
1067 SYSERROR("Failed to create \"/dev\" directory");
1072 ret
= safe_mount_beneath_at(rootfs
->mntpt_fd
, "none", "dev", "tmpfs", 0, mount_options
);
1074 __do_free
char *fallback_path
= NULL
;
1076 if (errno
!= ENOSYS
) {
1077 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1082 fallback_path
= must_make_path(path
, "/dev", NULL
);
1083 ret
= safe_mount("none", fallback_path
, "tmpfs", 0, mount_options
, path
);
1085 ret
= safe_mount("none", "dev", "tmpfs", 0, mount_options
, NULL
);
1088 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1092 TRACE("Mounted tmpfs on \"%s\"", path
);
1094 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1095 * If not, then create it and exit if that fails...
1097 ret
= mkdirat(rootfs
->mntpt_fd
, "dev/pts", S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1098 if (ret
< 0 && errno
!= EEXIST
) {
1099 SYSERROR("Failed to create directory \"%s\"", path
);
1107 (void)umask(cur_mask
);
1109 INFO("Prepared \"/dev\"");
1113 struct lxc_device_node
{
1120 static const struct lxc_device_node lxc_devices
[] = {
1121 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1122 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1123 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1124 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1125 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1126 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1133 LXC_DEVNODE_PARTIAL
,
1137 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1139 __do_close
int dev_dir_fd
= -EBADF
;
1142 int use_mknod
= LXC_DEVNODE_MKNOD
;
1144 /* ignore, just don't try to fill in */
1145 if (!exists_dir_at(rootfs
->mntpt_fd
, "dev"))
1148 dev_dir_fd
= openat(rootfs
->mntpt_fd
, "dev/", O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_PATH
| O_NOFOLLOW
);
1152 INFO("Populating \"/dev\"");
1154 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1155 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1156 char hostpath
[PATH_MAX
], path
[PATH_MAX
];
1157 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1159 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1160 ret
= mknodat(dev_dir_fd
, device
->name
, device
->mode
, makedev(device
->maj
, device
->min
));
1161 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1162 DEBUG("Created device node \"%s\"", device
->name
);
1163 } else if (ret
< 0) {
1165 return log_error_errno(-1, errno
, "Failed to create device node \"%s\"", device
->name
);
1167 use_mknod
= LXC_DEVNODE_BIND
;
1170 /* Device nodes are fully useable. */
1171 if (use_mknod
== LXC_DEVNODE_OPEN
)
1174 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1175 __do_close
int fd
= -EBADF
;
1177 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1178 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1180 fd
= openat(dev_dir_fd
, device
->name
, O_RDONLY
| O_CLOEXEC
);
1182 /* Device nodes are fully useable. */
1183 use_mknod
= LXC_DEVNODE_OPEN
;
1187 SYSTRACE("Failed to open \"%s\" device", device
->name
);
1188 /* Device nodes are only partially useable. */
1189 use_mknod
= LXC_DEVNODE_PARTIAL
;
1193 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1194 /* If we are dealing with partially functional device
1195 * nodes the prio mknod() call will have created the
1196 * device node so we can use it as a bind-mount target.
1198 ret
= mknodat(dev_dir_fd
, device
->name
, S_IFREG
| 0000, 0);
1199 if (ret
< 0 && errno
!= EEXIST
)
1200 return log_error_errno(-1, errno
, "Failed to create file \"%s\"", device
->name
);
1203 /* Fallback to bind-mounting the device from the host. */
1204 snprintf(hostpath
, sizeof(hostpath
), "/dev/%s", device
->name
);
1206 ret
= safe_mount_beneath_at(dev_dir_fd
, hostpath
, device
->name
, NULL
, MS_BIND
, NULL
);
1208 const char *mntpt
= rootfs
->path
? rootfs
->mount
: NULL
;
1209 if (errno
== ENOSYS
) {
1210 snprintf(path
, sizeof(path
), "%s/dev/%s", mntpt
, device
->name
);
1211 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
, rootfs
->path
? rootfs
->mount
: NULL
);
1215 return log_error_errno(-1, errno
, "Failed to bind mount host device node \"%s\" onto \"%s\"", hostpath
, device
->name
);
1216 DEBUG("Bind mounted host device node \"%s\" onto \"%s\"", hostpath
, device
->name
);
1220 INFO("Populated \"/dev\"");
1224 static int lxc_mount_rootfs(struct lxc_conf
*conf
)
1227 struct lxc_storage
*bdev
;
1228 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1230 if (!rootfs
->path
) {
1231 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1233 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
1235 rootfs
->mntpt_fd
= openat(-1, "/", O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_PATH
);
1236 if (rootfs
->mntpt_fd
< 0)
1242 ret
= access(rootfs
->mount
, F_OK
);
1244 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
1247 bdev
= storage_init(conf
);
1249 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1250 rootfs
->path
, rootfs
->mount
,
1251 rootfs
->options
? rootfs
->options
: "(null)");
1253 ret
= bdev
->ops
->mount(bdev
);
1256 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1257 rootfs
->path
, rootfs
->mount
,
1258 rootfs
->options
? rootfs
->options
: "(null)");
1260 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1261 rootfs
->path
, rootfs
->mount
,
1262 rootfs
->options
? rootfs
->options
: "(null)");
1264 rootfs
->mntpt_fd
= openat(-1, rootfs
->mount
, O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_PATH
);
1265 if (rootfs
->mntpt_fd
< 0)
1271 static int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1273 __do_free
char *nroot
= NULL
;
1275 char *root
= rootfs
->mount
;
1277 nroot
= realpath(root
, NULL
);
1279 return log_error_errno(-1, errno
, "Failed to resolve \"%s\"", root
);
1285 /* We could use here MS_MOVE, but in userns this mount is locked and
1288 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1290 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1292 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1294 return log_error_errno(-1, errno
, "Failed to remount \"/\"");
1296 /* The following code cleans up inherited mounts which are not required
1299 * The mountinfo file shows not all mounts, if a few points have been
1300 * unmounted between read operations from the mountinfo. So we need to
1301 * read mountinfo a few times.
1303 * This loop can be skipped if a container uses userns, because all
1304 * inherited mounts are locked and we should live with all this trash.
1307 __do_fclose
FILE *f
= NULL
;
1308 __do_free
char *line
= NULL
;
1309 char *slider1
, *slider2
;
1313 f
= fopen("./proc/self/mountinfo", "re");
1315 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
1317 while (getline(&line
, &len
, f
) > 0) {
1318 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
1319 slider1
= strchr(slider1
+ 1, ' ');
1324 slider2
= strchr(slider1
+ 1, ' ');
1331 if (strcmp(slider1
+ 1, "/") == 0)
1334 if (strcmp(slider1
+ 1, "/proc") == 0)
1337 ret
= umount2(slider1
, MNT_DETACH
);
1346 /* This also can be skipped if a container uses userns. */
1347 (void)umount2("./proc", MNT_DETACH
);
1349 /* It is weird, but chdir("..") moves us in a new root */
1352 return log_error_errno(-1, errno
, "Failed to chdir(\"..\")");
1356 return log_error_errno(-1, errno
, "Failed to chroot(\".\")");
1361 /* (The following explanation is copied verbatim from the kernel.)
1363 * pivot_root Semantics:
1364 * Moves the root file system of the current process to the directory put_old,
1365 * makes new_root as the new root file system of the current process, and sets
1366 * root/cwd of all processes which had them on the current root to new_root.
1369 * The new_root and put_old must be directories, and must not be on the
1370 * same file system as the current process root. The put_old must be
1371 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1372 * pointed to by put_old must yield the same directory as new_root. No other
1373 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1375 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1376 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1377 * in this situation.
1380 * - we don't move root/cwd if they are not at the root (reason: if something
1381 * cared enough to change them, it's probably wrong to force them elsewhere)
1382 * - it's okay to pick a root that isn't the root of a file system, e.g.
1383 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1384 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1387 static int lxc_pivot_root(const char *rootfs
)
1389 __do_close
int oldroot
= -EBADF
, newroot
= -EBADF
;
1392 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1394 return log_error_errno(-1, errno
, "Failed to open old root directory");
1396 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1398 return log_error_errno(-1, errno
, "Failed to open new root directory");
1400 /* change into new root fs */
1401 ret
= fchdir(newroot
);
1403 return log_error_errno(-1, errno
, "Failed to change to new rootfs \"%s\"", rootfs
);
1405 /* pivot_root into our new root fs */
1406 ret
= pivot_root(".", ".");
1408 return log_error_errno(-1, errno
, "Failed to pivot_root()");
1410 /* At this point the old-root is mounted on top of our new-root. To
1411 * unmounted it we must not be chdir'd into it, so escape back to
1414 ret
= fchdir(oldroot
);
1416 return log_error_errno(-1, errno
, "Failed to enter old root directory");
1418 /* Make oldroot a depedent mount to make sure our umounts don't propagate to the
1421 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1423 return log_error_errno(-1, errno
, "Failed to recursively turn old root mount tree into dependent mount");
1425 ret
= umount2(".", MNT_DETACH
);
1427 return log_error_errno(-1, errno
, "Failed to detach old root directory");
1429 ret
= fchdir(newroot
);
1431 return log_error_errno(-1, errno
, "Failed to re-enter new root directory");
1433 TRACE("pivot_root(\"%s\") successful", rootfs
);
1438 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1441 return log_debug(0, "Container does not have a rootfs");
1443 if (detect_ramfs_rootfs())
1444 return lxc_chroot(rootfs
);
1446 return lxc_pivot_root(rootfs
->mount
);
1449 static const struct id_map
*find_mapped_nsid_entry(const struct lxc_conf
*conf
,
1453 struct lxc_list
*it
;
1455 struct id_map
*retmap
= NULL
;
1457 /* Shortcut for container's root mappings. */
1459 if (idtype
== ID_TYPE_UID
)
1460 return conf
->root_nsuid_map
;
1462 if (idtype
== ID_TYPE_GID
)
1463 return conf
->root_nsgid_map
;
1466 lxc_list_for_each(it
, &conf
->id_map
) {
1468 if (map
->idtype
!= idtype
)
1471 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1480 static int lxc_setup_devpts(struct lxc_handler
*handler
)
1482 __do_close
int devpts_fd
= -EBADF
;
1485 char devpts_mntopts
[256];
1486 char *mntopt_sets
[5];
1487 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1488 struct lxc_conf
*conf
= handler
->conf
;
1489 int sock
= handler
->data_sock
[0];
1491 if (conf
->pty_max
<= 0)
1492 return log_debug(0, "No new devpts instance will be mounted since no pts devices are requested");
1494 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1495 default_devpts_mntopts
, conf
->pty_max
);
1496 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1499 (void)umount2("/dev/pts", MNT_DETACH
);
1501 /* Create mountpoint for devpts instance. */
1502 ret
= mkdir("/dev/pts", 0755);
1503 if (ret
< 0 && errno
!= EEXIST
)
1504 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1507 mntopt_sets
[0] = devpts_mntopts
;
1509 /* !gid=5 && max= */
1510 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1512 /* gid=5 && !max= */
1513 mntopt_sets
[2] = default_devpts_mntopts
;
1515 /* !gid=5 && !max= */
1516 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1519 mntopt_sets
[4] = NULL
;
1521 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1522 /* mount new devpts instance */
1523 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1529 return log_error_errno(-1, errno
, "Failed to mount new devpts instance");
1530 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1532 devpts_fd
= openat(-EBADF
, "/dev/pts", O_CLOEXEC
| O_DIRECTORY
| O_PATH
| O_NOFOLLOW
);
1533 if (devpts_fd
< 0) {
1535 TRACE("Failed to create detached devpts mount");
1536 ret
= lxc_abstract_unix_send_fds(sock
, NULL
, 0, &devpts_fd
, sizeof(int));
1538 ret
= lxc_abstract_unix_send_fds(sock
, &devpts_fd
, 1, NULL
, 0);
1541 return log_error_errno(-1, errno
, "Failed to send devpts fd to parent");
1542 TRACE("Sent devpts file descriptor %d to parent", devpts_fd
);
1544 /* Remove any pre-existing /dev/ptmx file. */
1545 ret
= remove("/dev/ptmx");
1547 if (errno
!= ENOENT
)
1548 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\" file");
1550 DEBUG("Removed existing \"/dev/ptmx\" file");
1553 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1554 ret
= mknod("/dev/ptmx", S_IFREG
| 0000, 0);
1555 if (ret
< 0 && errno
!= EEXIST
)
1556 return log_error_errno(-1, errno
, "Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1557 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1559 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1560 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1562 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1564 /* Fallthrough and try to create a symlink. */
1565 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1567 /* Remove the dummy /dev/ptmx file we created above. */
1568 ret
= remove("/dev/ptmx");
1570 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\"");
1572 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1573 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1575 return log_error_errno(-1, errno
, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1576 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1581 static int setup_personality(int persona
)
1585 #if HAVE_SYS_PERSONALITY_H
1589 ret
= personality(persona
);
1591 return log_error_errno(-1, errno
, "Failed to set personality to \"0x%x\"", persona
);
1593 INFO("Set personality to \"0x%x\"", persona
);
1599 static inline bool wants_console(const struct lxc_terminal
*terminal
)
1601 return !terminal
->path
|| strcmp(terminal
->path
, "none");
1604 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1605 const struct lxc_terminal
*console
,
1609 char path
[PATH_MAX
];
1610 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1612 if (!wants_console(console
))
1616 * When we are asked to setup a console we remove any previous
1617 * /dev/console bind-mounts.
1619 if (exists_file_at(rootfs
->dev_mntpt_fd
, "console")) {
1620 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1621 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1624 ret
= lxc_unstack_mountpoint(path
, false);
1626 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", path
);
1628 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1632 * For unprivileged containers autodev or automounts will already have
1633 * taken care of creating /dev/console.
1635 ret
= mknodat(rootfs
->dev_mntpt_fd
, "console", S_IFREG
| 0000, 0);
1636 if (ret
< 0 && errno
!= EEXIST
)
1637 return log_error_errno(-errno
, errno
, "Failed to create console");
1639 ret
= fchmod(console
->pty
, S_IXUSR
| S_IXGRP
);
1641 return log_error_errno(-errno
, errno
, "Failed to set mode \"0%o\" to \"%s\"", S_IXUSR
| S_IXGRP
, console
->name
);
1643 if (pty_mnt_fd
>= 0) {
1644 ret
= move_mount(pty_mnt_fd
, "", rootfs
->dev_mntpt_fd
, "console", MOVE_MOUNT_F_EMPTY_PATH
);
1646 DEBUG("Moved mount \"%s\" onto \"%s\"", console
->name
, path
);
1650 if (ret
&& errno
!= ENOSYS
)
1651 return log_error_errno(-1, errno
,
1652 "Failed to mount %d(%s) on \"%s\"",
1653 pty_mnt_fd
, console
->name
, path
);
1656 ret
= safe_mount_beneath_at(rootfs
->dev_mntpt_fd
, console
->name
, "console", NULL
, MS_BIND
, NULL
);
1658 if (errno
== ENOSYS
) {
1659 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1660 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1663 ret
= safe_mount(console
->name
, path
, "none", MS_BIND
, NULL
, rootfs_path
);
1665 return log_error_errno(-1, errno
, "Failed to mount %d(%s) on \"%s\"", pty_mnt_fd
, console
->name
, path
);
1670 DEBUG("Mounted pty device %d(%s) onto \"%s\"", pty_mnt_fd
, console
->name
, path
);
1674 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1675 const struct lxc_terminal
*console
,
1676 char *ttydir
, int pty_mnt_fd
)
1679 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
1680 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1682 if (!wants_console(console
))
1685 /* create rootfs/dev/<ttydir> directory */
1686 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1687 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1690 ret
= mkdir(path
, 0755);
1691 if (ret
&& errno
!= EEXIST
)
1692 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", path
);
1693 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1695 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1696 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1699 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1700 if (ret
< 0 && errno
!= EEXIST
)
1701 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", lxcpath
);
1703 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1704 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1707 if (file_exists(path
)) {
1708 ret
= lxc_unstack_mountpoint(path
, false);
1710 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", path
);
1712 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1715 ret
= mknod(path
, S_IFREG
| 0000, 0);
1716 if (ret
< 0 && errno
!= EEXIST
)
1717 return log_error_errno(-errno
, errno
, "Failed to create console");
1719 ret
= fchmod(console
->pty
, S_IXUSR
| S_IXGRP
);
1721 return log_error_errno(-errno
, errno
, "Failed to set mode \"0%o\" to \"%s\"", S_IXUSR
| S_IXGRP
, console
->name
);
1723 /* bind mount console->name to '/dev/<ttydir>/console' */
1724 if (pty_mnt_fd
>= 0) {
1725 ret
= move_mount(pty_mnt_fd
, "", -EBADF
, lxcpath
, MOVE_MOUNT_F_EMPTY_PATH
);
1727 DEBUG("Moved mount \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1731 if (ret
&& errno
!= ENOSYS
)
1732 return log_error_errno(-1, errno
,
1733 "Failed to mount %d(%s) on \"%s\"",
1734 pty_mnt_fd
, console
->name
, lxcpath
);
1737 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1739 return log_error_errno(-1, errno
, "Failed to mount %d(%s) on \"%s\"", pty_mnt_fd
, console
->name
, lxcpath
);
1740 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1743 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1744 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1746 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1747 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1749 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1753 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1754 const struct lxc_terminal
*console
, char *ttydir
,
1759 return lxc_setup_dev_console(rootfs
, console
, pty_mnt_fd
);
1761 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
, pty_mnt_fd
);
1764 static int parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1768 /* If '=' is contained in opt, the option must go into data. */
1769 if (!strchr(opt
, '=')) {
1771 * If opt is found in mount_opt, set or clear flags.
1772 * Otherwise append it to data.
1774 size_t opt_len
= strlen(opt
);
1775 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1776 size_t mo_name_len
= strlen(mo
->name
);
1778 if (opt_len
== mo_name_len
&& strncmp(opt
, mo
->name
, mo_name_len
) == 0) {
1780 *flags
&= ~mo
->flag
;
1788 if (strlen(*data
)) {
1789 ret
= strlcat(*data
, ",", size
);
1791 return log_error_errno(ret
, errno
, "Failed to append \",\" to %s", *data
);
1794 ret
= strlcat(*data
, opt
, size
);
1796 return log_error_errno(ret
, errno
, "Failed to append \"%s\" to %s", opt
, *data
);
1801 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1803 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
1804 char *mntopt_cur
= NULL
;
1807 if (*mntdata
|| *mntflags
)
1808 return ret_errno(EINVAL
);
1813 mntopts_dup
= strdup(mntopts
);
1815 return ret_errno(ENOMEM
);
1817 size
= strlen(mntopts_dup
) + 1;
1818 mntopts_new
= zalloc(size
);
1820 return ret_errno(ENOMEM
);
1822 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",")
1823 if (parse_mntopt(mntopt_cur
, mntflags
, &mntopts_new
, size
) < 0)
1824 return ret_errno(EINVAL
);
1827 *mntdata
= move_ptr(mntopts_new
);
1832 static void parse_propagationopt(char *opt
, unsigned long *flags
)
1834 struct mount_opt
*mo
;
1836 /* If opt is found in propagation_opt, set or clear flags. */
1837 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
1838 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) != 0)
1842 *flags
&= ~mo
->flag
;
1850 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
1852 __do_free
char *s
= NULL
;
1858 s
= strdup(mntopts
);
1860 return log_error_errno(-ENOMEM
, errno
, "Failed to allocate memory");
1863 lxc_iterate_parts(p
, s
, ",")
1864 parse_propagationopt(p
, pflags
);
1869 static void null_endofword(char *word
)
1871 while (*word
&& *word
!= ' ' && *word
!= '\t')
1876 /* skip @nfields spaces in @src */
1877 static char *get_field(char *src
, int nfields
)
1882 for (i
= 0; i
< nfields
; i
++) {
1883 while (*p
&& *p
!= ' ' && *p
!= '\t')
1895 static int mount_entry(const char *fsname
, const char *target
,
1896 const char *fstype
, unsigned long mountflags
,
1897 unsigned long pflags
, const char *data
, bool optional
,
1898 bool dev
, bool relative
, const char *rootfs
)
1901 char srcbuf
[PATH_MAX
];
1902 const char *srcpath
= fsname
;
1908 ret
= snprintf(srcbuf
, sizeof(srcbuf
), "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
1909 if (ret
< 0 || ret
>= sizeof(srcbuf
))
1910 return log_error_errno(-1, errno
, "source path is too long");
1914 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
1918 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
1919 srcpath
? srcpath
: "(null)", target
);
1921 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
1922 srcpath
? srcpath
: "(null)", target
);
1925 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
1927 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
1928 srcpath
? srcpath
: "(none)", target
? target
: "(none)");
1931 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
1932 unsigned long required_flags
= 0;
1934 if (sb
.f_flag
& MS_NOSUID
)
1935 required_flags
|= MS_NOSUID
;
1937 if (sb
.f_flag
& MS_NODEV
&& !dev
)
1938 required_flags
|= MS_NODEV
;
1940 if (sb
.f_flag
& MS_RDONLY
)
1941 required_flags
|= MS_RDONLY
;
1943 if (sb
.f_flag
& MS_NOEXEC
)
1944 required_flags
|= MS_NOEXEC
;
1946 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
1947 srcpath
, sb
.f_flag
, required_flags
);
1949 /* If this was a bind mount request, and required_flags
1950 * does not have any flags which are not already in
1951 * mountflags, then skip the remount.
1953 if (!(mountflags
& MS_REMOUNT
) &&
1954 (!(required_flags
& ~mountflags
) && !(mountflags
& MS_RDONLY
))) {
1955 DEBUG("Mountflags already were %lu, skipping remount", mountflags
);
1959 mountflags
|= required_flags
;
1963 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
1966 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
1967 srcpath
? srcpath
: "(null)",
1970 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
1971 srcpath
? srcpath
: "(null)",
1980 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
1983 return log_info_errno(0, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
1985 return log_error_errno(-1, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
1987 DEBUG("Changed mount propagation for \"%s\"", target
);
1990 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
1991 srcpath
? srcpath
: "(null)", target
, fstype
);
1996 /* Remove "optional", "create=dir", and "create=file" from mntopt */
1997 static void cull_mntent_opt(struct mntent
*mntent
)
2008 for (i
= 0; list
[i
]; i
++) {
2011 p
= strstr(mntent
->mnt_opts
, list
[i
]);
2015 p2
= strchr(p
, ',');
2017 /* no more mntopts, so just chop it here */
2022 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
2026 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2028 const struct lxc_rootfs
*rootfs
,
2029 const char *lxc_name
, const char *lxc_path
)
2031 __do_free
char *p1
= NULL
;
2035 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
2036 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2041 if (hasmntopt(mntent
, "create=dir")) {
2042 ret
= mkdir_p(path
, 0755);
2043 if (ret
< 0 && errno
!= EEXIST
)
2044 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2047 if (!hasmntopt(mntent
, "create=file"))
2050 ret
= access(path
, F_OK
);
2060 ret
= mkdir_p(p2
, 0755);
2061 if (ret
< 0 && errno
!= EEXIST
)
2062 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2064 ret
= mknod(path
, S_IFREG
| 0000, 0);
2065 if (ret
< 0 && errno
!= EEXIST
)
2071 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2072 * without a rootfs. */
2073 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2075 const struct lxc_rootfs
*rootfs
,
2076 const char *lxc_name
,
2077 const char *lxc_path
)
2079 __do_free
char *mntdata
= NULL
;
2080 unsigned long mntflags
= 0, pflags
= 0;
2081 char *rootfs_path
= NULL
;
2083 bool dev
, optional
, relative
;
2085 optional
= hasmntopt(mntent
, "optional") != NULL
;
2086 dev
= hasmntopt(mntent
, "dev") != NULL
;
2087 relative
= hasmntopt(mntent
, "relative") != NULL
;
2089 if (rootfs
&& rootfs
->path
)
2090 rootfs_path
= rootfs
->mount
;
2092 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2100 cull_mntent_opt(mntent
);
2102 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2106 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2110 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2111 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2116 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
2119 char path
[PATH_MAX
];
2121 /* For containers created without a rootfs all mounts are treated as
2122 * absolute paths starting at / on the host.
2124 if (mntent
->mnt_dir
[0] != '/')
2125 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
2127 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
2128 if (ret
< 0 || ret
>= sizeof(path
))
2131 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2134 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2135 const struct lxc_rootfs
*rootfs
,
2136 const char *lxc_name
,
2137 const char *lxc_path
)
2141 const char *lxcpath
;
2142 char path
[PATH_MAX
];
2145 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2149 /* If rootfs->path is a blockdev path, allow container fstab to use
2150 * <lxcpath>/<name>/rootfs" as the target prefix.
2152 ret
= snprintf(path
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2153 if (ret
< 0 || ret
>= PATH_MAX
)
2156 aux
= strstr(mntent
->mnt_dir
, path
);
2158 offset
= strlen(path
);
2163 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2165 return log_warn(ret
, "Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2166 offset
= strlen(rootfs
->path
);
2169 ret
= snprintf(path
, PATH_MAX
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2170 if (ret
< 0 || ret
>= PATH_MAX
)
2173 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2176 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2177 const struct lxc_rootfs
*rootfs
,
2178 const char *lxc_name
,
2179 const char *lxc_path
)
2182 char path
[PATH_MAX
];
2184 /* relative to root mount point */
2185 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2186 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
2189 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2192 static int mount_file_entries(const struct lxc_rootfs
*rootfs
, FILE *file
,
2193 const char *lxc_name
, const char *lxc_path
)
2196 struct mntent mntent
;
2198 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2202 ret
= mount_entry_on_systemfs(&mntent
);
2203 else if (mntent
.mnt_dir
[0] != '/')
2204 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2205 lxc_name
, lxc_path
);
2207 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2208 lxc_name
, lxc_path
);
2213 if (!feof(file
) || ferror(file
))
2214 return log_error(-1, "Failed to parse mount entries");
2219 static inline void __auto_endmntent__(FILE **f
)
2225 #define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2227 static int setup_mount(const struct lxc_conf
*conf
,
2228 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2229 const char *lxc_name
, const char *lxc_path
)
2231 __do_endmntent
FILE *f
= NULL
;
2237 f
= setmntent(fstab
, "re");
2239 return log_error_errno(-1, errno
, "Failed to open \"%s\"", fstab
);
2241 ret
= mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2243 ERROR("Failed to set up mount entries");
2249 * In order for nested containers to be able to mount /proc and /sys they need
2250 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2252 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2253 * apparmor rule to deny access to them. This is mostly for convenience: The
2254 * container's root user can mount them anyway and thus has access to the two
2255 * file systems. But a non-root user in the container should not be allowed to
2256 * access them as a side effect without explicitly allowing it.
2258 static const char nesting_helpers
[] =
2259 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2260 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2262 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2263 bool include_nesting_helpers
)
2265 __do_close
int fd
= -EBADF
;
2269 struct lxc_list
*iterator
;
2271 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2273 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2275 if (errno
!= ENOSYS
)
2278 fd
= lxc_make_tmpfile(template, true);
2280 return log_error_errno(NULL
, errno
, "Could not create temporary mount file");
2282 TRACE("Created temporary mount file");
2285 lxc_list_for_each (iterator
, mount
) {
2288 mount_entry
= iterator
->elem
;
2289 len
= strlen(mount_entry
);
2291 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2295 ret
= lxc_write_nointr(fd
, "\n", 1);
2300 if (include_nesting_helpers
) {
2301 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2302 STRARRAYLEN(nesting_helpers
));
2303 if (ret
!= STRARRAYLEN(nesting_helpers
))
2307 ret
= lseek(fd
, 0, SEEK_SET
);
2311 f
= fdopen(fd
, "re+");
2313 move_fd(fd
); /* Transfer ownership of fd. */
2317 static int setup_mount_entries(const struct lxc_conf
*conf
,
2318 const struct lxc_rootfs
*rootfs
,
2319 struct lxc_list
*mount
, const char *lxc_name
,
2320 const char *lxc_path
)
2322 __do_fclose
FILE *f
= NULL
;
2324 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2328 return mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2331 static int parse_cap(const char *cap
)
2335 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2338 if (strcmp(cap
, "none") == 0)
2341 for (i
= 0; i
< end
; i
++) {
2342 if (strcmp(cap
, caps_opt
[i
].name
))
2345 capid
= caps_opt
[i
].value
;
2350 /* Try to see if it's numeric, so the user may specify
2351 * capabilities that the running kernel knows about but we
2355 capid
= strtol(cap
, &ptr
, 10);
2356 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2357 /* not a valid number */
2359 else if (capid
> lxc_caps_last_cap())
2360 /* we have a number but it's not a valid
2368 int in_caplist(int cap
, struct lxc_list
*caps
)
2371 struct lxc_list
*iterator
;
2373 lxc_list_for_each (iterator
, caps
) {
2374 capid
= parse_cap(iterator
->elem
);
2382 static int setup_caps(struct lxc_list
*caps
)
2386 struct lxc_list
*iterator
;
2388 lxc_list_for_each (iterator
, caps
) {
2391 drop_entry
= iterator
->elem
;
2393 capid
= parse_cap(drop_entry
);
2395 return log_error(-1, "unknown capability %s", drop_entry
);
2397 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2398 prctl_arg(0), prctl_arg(0));
2400 return log_error_errno(-1, errno
, "Failed to remove %s capability", drop_entry
);
2401 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2404 DEBUG("Capabilities have been setup");
2408 static int dropcaps_except(struct lxc_list
*caps
)
2410 __do_free
int *caplist
= NULL
;
2411 int i
, capid
, numcaps
;
2413 struct lxc_list
*iterator
;
2415 numcaps
= lxc_caps_last_cap() + 1;
2416 if (numcaps
<= 0 || numcaps
> 200)
2418 TRACE("Found %d capabilities", numcaps
);
2420 /* caplist[i] is 1 if we keep capability i */
2421 caplist
= must_realloc(NULL
, numcaps
* sizeof(int));
2422 memset(caplist
, 0, numcaps
* sizeof(int));
2424 lxc_list_for_each (iterator
, caps
) {
2425 keep_entry
= iterator
->elem
;
2427 capid
= parse_cap(keep_entry
);
2432 return log_error(-1, "Unknown capability %s", keep_entry
);
2434 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2438 for (i
= 0; i
< numcaps
; i
++) {
2444 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2445 prctl_arg(0), prctl_arg(0));
2447 return log_error_errno(-1, errno
, "Failed to remove capability %d", i
);
2450 DEBUG("Capabilities have been setup");
2454 static int parse_resource(const char *res
)
2460 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2461 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2462 return limit_opt
[i
].value
;
2464 /* Try to see if it's numeric, so the user may specify
2465 * resources that the running kernel knows about but
2468 ret
= lxc_safe_int(res
, &resid
);
2475 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2478 struct lxc_list
*it
;
2479 struct lxc_limit
*lim
;
2481 lxc_list_for_each (it
, limits
) {
2484 resid
= parse_resource(lim
->resource
);
2486 return log_error(-1, "Unknown resource %s", lim
->resource
);
2488 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2489 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0)
2490 return log_error_errno(-1, errno
, "Failed to set limit %s", lim
->resource
);
2492 TRACE("Setup \"%s\" limit", lim
->resource
);
2494 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
2501 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2503 __do_free
char *tmp
= NULL
;
2504 struct lxc_list
*it
;
2505 struct lxc_sysctl
*elem
;
2507 char filename
[PATH_MAX
] = {0};
2509 lxc_list_for_each (it
, sysctls
) {
2511 tmp
= lxc_string_replace(".", "/", elem
->key
);
2513 return log_error(-1, "Failed to replace key %s", elem
->key
);
2515 ret
= snprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2516 if (ret
< 0 || (size_t)ret
>= sizeof(filename
))
2517 return log_error(-1, "Error setting up sysctl parameters path");
2519 ret
= lxc_write_to_file(filename
, elem
->value
,
2520 strlen(elem
->value
), false, 0666);
2522 return log_error_errno(-1, errno
, "Failed to setup sysctl parameters %s to %s",
2523 elem
->key
, elem
->value
);
2529 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2531 __do_free
char *tmp
= NULL
;
2532 struct lxc_list
*it
;
2533 struct lxc_proc
*elem
;
2535 char filename
[PATH_MAX
] = {0};
2537 lxc_list_for_each (it
, procs
) {
2539 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2541 return log_error(-1, "Failed to replace key %s", elem
->filename
);
2543 ret
= snprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2544 if (ret
< 0 || (size_t)ret
>= sizeof(filename
))
2545 return log_error(-1, "Error setting up proc filesystem path");
2547 ret
= lxc_write_to_file(filename
, elem
->value
,
2548 strlen(elem
->value
), false, 0666);
2550 return log_error_errno(-1, errno
, "Failed to setup proc filesystem %s to %s", elem
->filename
, elem
->value
);
2556 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2558 struct lxc_conf
*lxc_conf_init(void)
2561 struct lxc_conf
*new;
2563 new = malloc(sizeof(*new));
2566 memset(new, 0, sizeof(*new));
2568 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2569 new->personality
= -1;
2571 new->console
.buffer_size
= 0;
2572 new->console
.log_path
= NULL
;
2573 new->console
.log_fd
= -1;
2574 new->console
.log_size
= 0;
2575 new->console
.path
= NULL
;
2576 new->console
.peer
= -1;
2577 new->console
.proxy
.busy
= -1;
2578 new->console
.proxy
.ptx
= -1;
2579 new->console
.proxy
.pty
= -1;
2580 new->console
.ptx
= -1;
2581 new->console
.pty
= -1;
2582 new->console
.name
[0] = '\0';
2583 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2584 new->maincmd_fd
= -1;
2585 new->monitor_signal_pdeath
= SIGKILL
;
2587 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2588 if (!new->rootfs
.mount
) {
2592 new->rootfs
.managed
= true;
2593 new->rootfs
.mntpt_fd
= -EBADF
;
2594 new->rootfs
.dev_mntpt_fd
= -EBADF
;
2596 lxc_list_init(&new->cgroup
);
2597 lxc_list_init(&new->cgroup2
);
2598 lxc_list_init(&new->devices
);
2599 lxc_list_init(&new->network
);
2600 lxc_list_init(&new->mount_list
);
2601 lxc_list_init(&new->caps
);
2602 lxc_list_init(&new->keepcaps
);
2603 lxc_list_init(&new->id_map
);
2604 new->root_nsuid_map
= NULL
;
2605 new->root_nsgid_map
= NULL
;
2606 lxc_list_init(&new->includes
);
2607 lxc_list_init(&new->aliens
);
2608 lxc_list_init(&new->environment
);
2609 lxc_list_init(&new->limits
);
2610 lxc_list_init(&new->sysctls
);
2611 lxc_list_init(&new->procs
);
2612 new->hooks_version
= 0;
2613 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2614 lxc_list_init(&new->hooks
[i
]);
2615 lxc_list_init(&new->groups
);
2616 lxc_list_init(&new->state_clients
);
2617 new->lsm_aa_profile
= NULL
;
2618 lxc_list_init(&new->lsm_aa_raw
);
2619 new->lsm_se_context
= NULL
;
2620 new->lsm_se_keyring_context
= NULL
;
2621 new->keyring_disable_session
= false;
2622 new->tmp_umount_proc
= false;
2623 new->tmp_umount_proc
= 0;
2624 new->shmount
.path_host
= NULL
;
2625 new->shmount
.path_cont
= NULL
;
2627 /* if running in a new user namespace, init and COMMAND
2628 * default to running as UID/GID 0 when using lxc-execute */
2631 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2632 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2633 memset(&new->timens
, 0, sizeof(struct timens_offsets
));
2634 seccomp_conf_init(new);
2639 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2642 __do_close
int fd
= -EBADF
;
2644 char path
[PATH_MAX
];
2646 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2647 __do_close
int setgroups_fd
= -EBADF
;
2649 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/setgroups", pid
);
2650 if (ret
< 0 || ret
>= PATH_MAX
)
2653 setgroups_fd
= open(path
, O_WRONLY
);
2654 if (setgroups_fd
< 0 && errno
!= ENOENT
)
2655 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
2657 if (setgroups_fd
>= 0) {
2658 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
2659 STRLITERALLEN("deny\n"));
2660 if (ret
!= STRLITERALLEN("deny\n"))
2661 return log_error_errno(-1, errno
, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
2662 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2666 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/%cid_map", pid
,
2667 idtype
== ID_TYPE_UID
? 'u' : 'g');
2668 if (ret
< 0 || ret
>= PATH_MAX
)
2671 fd
= open(path
, O_WRONLY
| O_CLOEXEC
);
2673 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
2675 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2676 if (ret
!= buf_size
)
2677 return log_error_errno(-1, errno
, "Failed to write %cid mapping to \"%s\"",
2678 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2683 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2685 * @return 1 if functional binary was found
2686 * @return 0 if binary exists but is lacking privilege
2687 * @return -ENOENT if binary does not exist
2688 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2690 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2692 __do_free
char *path
= NULL
;
2697 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2701 path
= on_path(binary
, NULL
);
2705 ret
= stat(path
, &st
);
2709 /* Check if the binary is setuid. */
2710 if (st
.st_mode
& S_ISUID
)
2711 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path
);
2713 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2714 /* Check if it has the CAP_SETUID capability. */
2715 if ((cap
& CAP_SETUID
) &&
2716 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2717 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
))
2718 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
2720 /* Check if it has the CAP_SETGID capability. */
2721 if ((cap
& CAP_SETGID
) &&
2722 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2723 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
))
2724 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
2726 /* If we cannot check for file capabilities we need to give the benefit
2727 * of the doubt. Otherwise we might fail even though all the necessary
2728 * file capabilities are set.
2730 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
2736 static int lxc_map_ids_exec_wrapper(void *args
)
2738 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2742 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2747 char cmd_output
[PATH_MAX
];
2749 struct lxc_list
*iterator
;
2751 int ret
= 0, gidmap
= 0, uidmap
= 0;
2752 char mapbuf
[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
2753 INTTYPE_TO_STRLEN(pid_t
) + STRLITERALLEN(" ") +
2754 LXC_IDMAPLEN
] = {0};
2755 bool had_entry
= false, use_shadow
= false;
2756 int hostuid
, hostgid
;
2758 hostuid
= geteuid();
2759 hostgid
= getegid();
2761 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2762 * ranges, then insist that root also reserve ranges in subuid. This
2763 * will protected it by preventing another user from being handed the
2766 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2767 if (uidmap
== -ENOENT
)
2768 WARN("newuidmap binary is missing");
2770 WARN("newuidmap is lacking necessary privileges");
2772 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2773 if (gidmap
== -ENOENT
)
2774 WARN("newgidmap binary is missing");
2776 WARN("newgidmap is lacking necessary privileges");
2778 if (uidmap
> 0 && gidmap
> 0) {
2779 DEBUG("Functional newuidmap and newgidmap binary found");
2782 /* In case unprivileged users run application containers via
2783 * execute() or a start*() there are valid cases where they may
2784 * only want to map their own {g,u}id. Let's not block them from
2785 * doing so by requiring geteuid() == 0.
2787 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2788 "write directly with euid %d", hostuid
);
2791 /* Check if we really need to use newuidmap and newgidmap.
2792 * If the user is only remapping his own {g,u}id, we don't need it.
2794 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
2796 lxc_list_for_each(iterator
, idmap
) {
2797 map
= iterator
->elem
;
2798 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
2799 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
2801 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
2802 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
2809 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
2810 type
++, u_or_g
= 'g') {
2814 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
2816 lxc_list_for_each(iterator
, idmap
) {
2817 map
= iterator
->elem
;
2818 if (map
->idtype
!= type
)
2823 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
2824 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
2825 use_shadow
? " " : "", map
->nsid
,
2826 map
->hostid
, map
->range
,
2827 use_shadow
? "" : "\n");
2829 * The kernel only takes <= 4k for writes to
2830 * /proc/<pid>/{g,u}id_map
2832 if (fill
<= 0 || fill
>= left
)
2833 return log_error_errno(-1, errno
, "Too many %cid mappings defined", u_or_g
);
2840 /* Try to catch the output of new{g,u}idmap to make debugging
2844 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2845 lxc_map_ids_exec_wrapper
,
2848 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g
, cmd_output
, mapbuf
);
2849 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
2851 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
2853 return log_error(-1, "Failed to write mapping: %s", mapbuf
);
2854 TRACE("Wrote mapping \"%s\"", mapbuf
);
2857 memset(mapbuf
, 0, sizeof(mapbuf
));
2864 * Return the host uid/gid to which the container root is mapped in val.
2865 * Return true if id was found, false otherwise.
2867 static id_t
get_mapped_rootid(const struct lxc_conf
*conf
, enum idtype idtype
)
2871 struct lxc_list
*it
;
2873 if (idtype
== ID_TYPE_UID
)
2874 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
2876 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
2878 lxc_list_for_each (it
, &conf
->id_map
) {
2880 if (map
->idtype
!= idtype
)
2882 if (map
->nsid
!= nsid
)
2887 if (idtype
== ID_TYPE_UID
)
2888 return LXC_INVALID_UID
;
2890 return LXC_INVALID_GID
;
2893 int mapped_hostid(unsigned id
, const struct lxc_conf
*conf
, enum idtype idtype
)
2896 struct lxc_list
*it
;
2898 lxc_list_for_each (it
, &conf
->id_map
) {
2900 if (map
->idtype
!= idtype
)
2903 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
2904 return (id
- map
->hostid
) + map
->nsid
;
2910 int find_unmapped_nsid(const struct lxc_conf
*conf
, enum idtype idtype
)
2913 struct lxc_list
*it
;
2914 unsigned int freeid
= 0;
2917 lxc_list_for_each (it
, &conf
->id_map
) {
2919 if (map
->idtype
!= idtype
)
2922 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
2923 freeid
= map
->nsid
+ map
->range
;
2931 /* NOTE: Must not be called from inside the container namespace! */
2932 static int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
2936 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
2937 if (mounted
== -1) {
2938 SYSERROR("Failed to mount proc in the container");
2939 /* continue only if there is no rootfs */
2940 if (conf
->rootfs
.path
)
2942 } else if (mounted
== 1) {
2943 conf
->tmp_umount_proc
= true;
2949 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
2951 if (!lxc_conf
->tmp_umount_proc
)
2954 (void)umount2("/proc", MNT_DETACH
);
2955 lxc_conf
->tmp_umount_proc
= false;
2958 /* Walk /proc/mounts and change any shared entries to dependent mounts. */
2959 void turn_into_dependent_mounts(void)
2961 __do_free
char *line
= NULL
;
2962 __do_fclose
FILE *f
= NULL
;
2963 __do_close
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
2968 mntinfo_fd
= open("/proc/self/mountinfo", O_RDONLY
| O_CLOEXEC
);
2969 if (mntinfo_fd
< 0) {
2970 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
2974 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
2976 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
2978 if (errno
!= ENOSYS
) {
2979 SYSERROR("Failed to create temporary in-memory file");
2983 memfd
= lxc_make_tmpfile(template, true);
2985 WARN("Failed to create temporary file");
2991 copied
= lxc_sendfile_nointr(memfd
, mntinfo_fd
, NULL
, LXC_SENDFILE_MAX
);
2996 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3000 ret
= lseek(memfd
, 0, SEEK_SET
);
3002 SYSERROR("Failed to reset file descriptor offset");
3006 f
= fdopen(memfd
, "re");
3008 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3013 * After a successful fdopen() memfd will be closed when calling
3014 * fclose(f). Calling close(memfd) afterwards is undefined.
3018 while (getline(&line
, &len
, f
) != -1) {
3019 char *opts
, *target
;
3021 target
= get_field(line
, 4);
3025 opts
= get_field(target
, 2);
3029 null_endofword(opts
);
3030 if (!strstr(opts
, "shared"))
3033 null_endofword(target
);
3034 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3036 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
3039 TRACE("Recursively turned old root mount tree into dependent mount");
3041 TRACE("Turned all mount table entries into dependent mount");
3044 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3048 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3049 struct lxc_conf
*conf
= handler
->conf
;
3051 /* If init exists in the container, don't bind mount a static one */
3052 p
= choose_init(conf
->rootfs
.mount
);
3054 __do_free
char *old
= p
;
3056 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3060 INFO("Found existing init at \"%s\"", p
);
3064 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3065 if (ret
< 0 || ret
>= PATH_MAX
)
3068 if (!file_exists(path
))
3069 return log_error_errno(-1, errno
, "The file \"%s\" does not exist on host", path
);
3071 ret
= snprintf(destpath
, PATH_MAX
, "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3072 if (ret
< 0 || ret
>= PATH_MAX
)
3075 if (!file_exists(destpath
)) {
3076 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3077 if (ret
< 0 && errno
!= EEXIST
)
3078 return log_error_errno(-1, errno
, "Failed to create dummy \"%s\" file as bind mount target", destpath
);
3081 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3083 return log_error_errno(-1, errno
, "Failed to bind mount lxc.init.static into container");
3085 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3089 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3091 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3092 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3096 /* This does the work of remounting / if it is shared, calling the container
3097 * pre-mount hooks, and mounting the rootfs.
3099 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3100 const char *lxcpath
)
3104 if (conf
->rootfs_setup
) {
3105 const char *path
= conf
->rootfs
.mount
;
3107 /* The rootfs was set up in another namespace. bind-mount it to
3108 * give us a mount in our own ns so we can pivot_root to it
3110 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3112 return log_error(-1, "Failed to bind mount container / onto itself");
3114 return log_trace(0, "Bind mounted container / onto itself");
3117 turn_into_dependent_mounts();
3119 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3121 return log_error(-1, "Failed to run pre-mount hooks");
3123 ret
= lxc_mount_rootfs(conf
);
3125 return log_error(-1, "Failed to setup rootfs for");
3127 conf
->rootfs_setup
= true;
3131 static bool verify_start_hooks(struct lxc_conf
*conf
)
3133 char path
[PATH_MAX
];
3134 struct lxc_list
*it
;
3136 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3138 char *hookname
= it
->elem
;
3140 ret
= snprintf(path
, PATH_MAX
, "%s%s",
3141 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3143 if (ret
< 0 || ret
>= PATH_MAX
)
3146 ret
= access(path
, X_OK
);
3148 return log_error_errno(false, errno
, "Start hook \"%s\" not found in container", hookname
);
3156 static bool execveat_supported(void)
3158 execveat(-1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3159 if (errno
== ENOSYS
)
3165 static int lxc_setup_boot_id(void)
3168 const char *boot_id_path
= "/proc/sys/kernel/random/boot_id";
3169 const char *mock_boot_id_path
= "/dev/.lxc-boot-id";
3172 if (access(boot_id_path
, F_OK
))
3175 memset(&n
, 0, sizeof(n
));
3176 if (lxc_id128_randomize(&n
)) {
3177 SYSERROR("Failed to generate random data for uuid");
3181 ret
= lxc_id128_write(mock_boot_id_path
, n
);
3183 SYSERROR("Failed to write uuid to %s", mock_boot_id_path
);
3187 ret
= chmod(mock_boot_id_path
, 0444);
3189 SYSERROR("Failed to chown %s", mock_boot_id_path
);
3190 (void)unlink(mock_boot_id_path
);
3194 ret
= mount(mock_boot_id_path
, boot_id_path
, NULL
, MS_BIND
, NULL
);
3196 SYSERROR("Failed to mount %s to %s", mock_boot_id_path
,
3198 (void)unlink(mock_boot_id_path
);
3202 ret
= mount(NULL
, boot_id_path
, NULL
,
3203 (MS_BIND
| MS_REMOUNT
| MS_RDONLY
| MS_NOSUID
| MS_NOEXEC
|
3207 SYSERROR("Failed to remount %s read-only", boot_id_path
);
3208 (void)unlink(mock_boot_id_path
);
3215 static int lxc_setup_keyring(struct lsm_ops
*lsm_ops
, const struct lxc_conf
*conf
)
3217 key_serial_t keyring
;
3220 if (conf
->lsm_se_keyring_context
)
3221 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_keyring_context
);
3222 else if (conf
->lsm_se_context
)
3223 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_context
);
3225 return log_error_errno(-1, errno
, "Failed to set keyring context");
3228 * Try to allocate a new session keyring for the container to prevent
3229 * information leaks.
3231 keyring
= keyctl(KEYCTL_JOIN_SESSION_KEYRING
, prctl_arg(0),
3232 prctl_arg(0), prctl_arg(0), prctl_arg(0));
3236 DEBUG("The keyctl() syscall is not supported or blocked");
3241 DEBUG("Failed to access kernel keyring. Continuing...");
3244 SYSERROR("Failed to create kernel keyring");
3252 int lxc_setup(struct lxc_handler
*handler
)
3254 __do_close
int pty_mnt_fd
= -EBADF
;
3256 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3257 struct lxc_conf
*lxc_conf
= handler
->conf
;
3259 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3261 return log_error(-1, "Failed to setup rootfs");
3263 if (handler
->nsfd
[LXC_NS_UTS
] == -EBADF
) {
3264 ret
= setup_utsname(lxc_conf
->utsname
);
3266 return log_error(-1, "Failed to setup the utsname %s", name
);
3269 if (!lxc_conf
->keyring_disable_session
) {
3270 ret
= lxc_setup_keyring(handler
->lsm_ops
, lxc_conf
);
3272 return log_error(-1, "Failed to setup container keyring");
3275 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
3276 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
,
3277 &lxc_conf
->network
);
3279 return log_error(-1, "Failed to setup network");
3281 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3283 return log_error(-1, "Failed to send network device names and ifindices to parent");
3286 if (wants_console(&lxc_conf
->console
)) {
3287 pty_mnt_fd
= open_tree(-EBADF
, lxc_conf
->console
.name
,
3288 OPEN_TREE_CLONE
| OPEN_TREE_CLOEXEC
| AT_EMPTY_PATH
);
3290 SYSTRACE("Failed to create detached mount for container's console \"%s\"",
3291 lxc_conf
->console
.name
);
3293 TRACE("Created detached mount for container's console \"%s\"",
3294 lxc_conf
->console
.name
);
3297 if (lxc_conf
->autodev
> 0) {
3298 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxc_conf
->autodevtmpfssize
, lxcpath
);
3300 return log_error(-1, "Failed to mount \"/dev\"");
3303 lxc_conf
->rootfs
.dev_mntpt_fd
= openat(lxc_conf
->rootfs
.mntpt_fd
, "dev",
3304 O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_NOFOLLOW
);
3305 if (lxc_conf
->rootfs
.dev_mntpt_fd
< 0 && errno
!= ENOENT
)
3306 return log_error_errno(-errno
, errno
, "Failed to open \"/dev\"");
3308 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3309 * need to wait until other stuff has finished.
3311 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
);
3313 return log_error(-1, "Failed to setup first automatic mounts");
3315 ret
= setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3317 return log_error(-1, "Failed to setup mounts");
3319 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3320 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3321 &lxc_conf
->mount_list
, name
, lxcpath
);
3323 return log_error(-1, "Failed to setup mount entries");
3326 if (lxc_conf
->is_execute
) {
3327 if (execveat_supported()) {
3329 char path
[PATH_MAX
];
3331 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3332 if (ret
< 0 || ret
>= PATH_MAX
)
3333 return log_error(-1, "Path to init.lxc.static too long");
3335 fd
= open(path
, O_PATH
| O_CLOEXEC
);
3337 return log_error_errno(-1, errno
, "Unable to open lxc.init.static");
3339 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3340 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3342 ret
= lxc_execute_bind_init(handler
);
3344 return log_error(-1, "Failed to bind-mount the lxc init system");
3348 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3349 * mounted. It is guaranteed to be mounted now either through
3350 * automatically or via fstab entries.
3352 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
);
3354 return log_error(-1, "Failed to setup remaining automatic mounts");
3356 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3358 return log_error(-1, "Failed to run mount hooks");
3360 if (lxc_conf
->autodev
> 0) {
3361 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3363 return log_error(-1, "Failed to run autodev hooks");
3365 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3367 return log_error(-1, "Failed to populate \"/dev\"");
3370 /* Make sure any start hooks are in the container */
3371 if (!verify_start_hooks(lxc_conf
))
3372 return log_error(-1, "Failed to verify start hooks");
3374 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3376 return log_error(-1, "Failed to \"/proc\" LSMs");
3378 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3379 lxc_conf
->ttys
.dir
, pty_mnt_fd
);
3381 return log_error(-1, "Failed to setup console");
3383 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3385 return log_error(-1, "Failed to setup \"/dev\" symlinks");
3387 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3389 return log_error(-1, "Failed to pivot root into rootfs");
3391 /* Setting the boot-id is best-effort for now. */
3392 if (lxc_conf
->autodev
> 0)
3393 (void)lxc_setup_boot_id();
3395 ret
= lxc_setup_devpts(handler
);
3397 return log_error(-1, "Failed to setup new devpts instance");
3399 ret
= lxc_create_ttys(handler
);
3403 ret
= setup_personality(lxc_conf
->personality
);
3405 return log_error(-1, "Failed to set personality");
3407 /* Set sysctl value to a path under /proc/sys as determined from the
3408 * key. For e.g. net.ipv4.ip_forward translated to
3409 * /proc/sys/net/ipv4/ip_forward.
3411 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3412 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3414 return log_error(-1, "Failed to setup sysctl parameters");
3417 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3418 if (!lxc_list_empty(&lxc_conf
->caps
))
3419 return log_error(-1, "Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both");
3421 if (dropcaps_except(&lxc_conf
->keepcaps
))
3422 return log_error(-1, "Failed to keep capabilities");
3423 } else if (setup_caps(&lxc_conf
->caps
)) {
3424 return log_error(-1, "Failed to drop capabilities");
3427 close_prot_errno_disarm(lxc_conf
->rootfs
.mntpt_fd
)
3428 close_prot_errno_disarm(lxc_conf
->rootfs
.dev_mntpt_fd
)
3429 NOTICE("The container \"%s\" is set up", name
);
3434 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3437 struct lxc_list
*it
;
3440 for (which
= 0; which
< NUM_LXC_HOOKS
; which
++) {
3441 if (strcmp(hookname
, lxchook_names
[which
]) == 0)
3445 if (which
>= NUM_LXC_HOOKS
)
3448 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3450 char *hook
= it
->elem
;
3452 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3461 int lxc_clear_config_caps(struct lxc_conf
*c
)
3463 struct lxc_list
*it
, *next
;
3465 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3474 static int lxc_free_idmap(struct lxc_list
*id_map
)
3476 struct lxc_list
*it
, *next
;
3478 lxc_list_for_each_safe(it
, id_map
, next
) {
3487 static int __lxc_free_idmap(struct lxc_list
*id_map
)
3489 lxc_free_idmap(id_map
);
3493 define_cleanup_function(struct lxc_list
*, __lxc_free_idmap
);
3495 int lxc_clear_idmaps(struct lxc_conf
*c
)
3497 return lxc_free_idmap(&c
->id_map
);
3500 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3502 struct lxc_list
*it
, *next
;
3504 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3513 int lxc_clear_namespace(struct lxc_conf
*c
)
3516 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
3517 free(c
->ns_share
[i
]);
3518 c
->ns_share
[i
] = NULL
;
3523 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3525 char *global_token
, *namespaced_token
;
3526 size_t namespaced_token_len
;
3527 struct lxc_list
*it
, *next
, *list
;
3528 const char *k
= key
;
3531 if (version
== CGROUP2_SUPER_MAGIC
) {
3532 global_token
= "lxc.cgroup2";
3533 namespaced_token
= "lxc.cgroup2.";
3534 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
3536 } else if (version
== CGROUP_SUPER_MAGIC
) {
3537 global_token
= "lxc.cgroup";
3538 namespaced_token
= "lxc.cgroup.";
3539 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
3545 if (strcmp(key
, global_token
) == 0)
3547 else if (strncmp(key
, namespaced_token
, namespaced_token_len
) == 0)
3548 k
+= namespaced_token_len
;
3552 lxc_list_for_each_safe (it
, list
, next
) {
3553 struct lxc_cgroup
*cg
= it
->elem
;
3555 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3559 free(cg
->subsystem
);
3568 static void lxc_clear_devices(struct lxc_conf
*conf
)
3570 struct lxc_list
*list
= &conf
->devices
;
3571 struct lxc_list
*it
, *next
;
3573 lxc_list_for_each_safe(it
, list
, next
) {
3579 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3581 struct lxc_list
*it
, *next
;
3582 const char *k
= NULL
;
3585 if (strcmp(key
, "lxc.limit") == 0 || strcmp(key
, "lxc.prlimit") == 0)
3587 else if (strncmp(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")) == 0)
3588 k
= key
+ STRLITERALLEN("lxc.limit.");
3589 else if (strncmp(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")) == 0)
3590 k
= key
+ STRLITERALLEN("lxc.prlimit.");
3594 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3595 struct lxc_limit
*lim
= it
->elem
;
3597 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3601 free(lim
->resource
);
3609 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3611 struct lxc_list
*it
, *next
;
3612 const char *k
= NULL
;
3615 if (strcmp(key
, "lxc.sysctl") == 0)
3617 else if (strncmp(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")) == 0)
3618 k
= key
+ STRLITERALLEN("lxc.sysctl.");
3622 lxc_list_for_each_safe (it
, &c
->sysctls
, next
) {
3623 struct lxc_sysctl
*elem
= it
->elem
;
3625 if (!all
&& strcmp(elem
->key
, k
) != 0)
3638 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3640 struct lxc_list
*it
, *next
;
3641 const char *k
= NULL
;
3644 if (strcmp(key
, "lxc.proc") == 0)
3646 else if (strncmp(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")) == 0)
3647 k
= key
+ STRLITERALLEN("lxc.proc.");
3651 lxc_list_for_each_safe (it
, &c
->procs
, next
) {
3652 struct lxc_proc
*proc
= it
->elem
;
3654 if (!all
&& strcmp(proc
->filename
, k
) != 0)
3658 free(proc
->filename
);
3667 int lxc_clear_groups(struct lxc_conf
*c
)
3669 struct lxc_list
*it
, *next
;
3671 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
3680 int lxc_clear_environment(struct lxc_conf
*c
)
3682 struct lxc_list
*it
, *next
;
3684 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
3693 int lxc_clear_mount_entries(struct lxc_conf
*c
)
3695 struct lxc_list
*it
, *next
;
3697 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
3706 int lxc_clear_automounts(struct lxc_conf
*c
)
3712 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
3715 struct lxc_list
*it
, *next
;
3716 const char *k
= NULL
;
3717 bool all
= false, done
= false;
3719 if (strcmp(key
, "lxc.hook") == 0)
3721 else if (strncmp(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")) == 0)
3722 k
= key
+ STRLITERALLEN("lxc.hook.");
3726 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
3727 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
3728 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
3739 return log_error(-1, "Invalid hook key: %s", key
);
3744 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
3746 struct lxc_list
*it
, *next
;
3748 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
3755 void lxc_clear_includes(struct lxc_conf
*conf
)
3757 struct lxc_list
*it
, *next
;
3759 lxc_list_for_each_safe (it
, &conf
->includes
, next
) {
3766 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
3768 struct lxc_list
*it
, *next
;
3770 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
3779 void lxc_conf_free(struct lxc_conf
*conf
)
3784 if (current_config
== conf
)
3785 current_config
= NULL
;
3786 lxc_terminal_conf_free(&conf
->console
);
3787 free(conf
->rootfs
.mount
);
3788 free(conf
->rootfs
.bdev_type
);
3789 free(conf
->rootfs
.options
);
3790 free(conf
->rootfs
.path
);
3791 free(conf
->rootfs
.data
);
3792 close_prot_errno_disarm(conf
->rootfs
.mntpt_fd
);
3793 close_prot_errno_disarm(conf
->rootfs
.dev_mntpt_fd
);
3794 free(conf
->logfile
);
3795 if (conf
->logfd
!= -1)
3797 free(conf
->utsname
);
3798 free(conf
->ttys
.dir
);
3799 free(conf
->ttys
.tty_names
);
3802 free(conf
->execute_cmd
);
3803 free(conf
->init_cmd
);
3804 free(conf
->init_cwd
);
3805 free(conf
->unexpanded_config
);
3807 lxc_free_networks(&conf
->network
);
3808 free(conf
->lsm_aa_profile
);
3809 free(conf
->lsm_aa_profile_computed
);
3810 free(conf
->lsm_se_context
);
3811 lxc_seccomp_free(&conf
->seccomp
);
3812 lxc_clear_config_caps(conf
);
3813 lxc_clear_config_keepcaps(conf
);
3814 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
3815 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
3816 lxc_clear_devices(conf
);
3817 lxc_clear_cgroup2_devices(conf
);
3818 lxc_clear_hooks(conf
, "lxc.hook");
3819 lxc_clear_mount_entries(conf
);
3820 lxc_clear_idmaps(conf
);
3821 lxc_clear_groups(conf
);
3822 lxc_clear_includes(conf
);
3823 lxc_clear_aliens(conf
);
3824 lxc_clear_environment(conf
);
3825 lxc_clear_limits(conf
, "lxc.prlimit");
3826 lxc_clear_sysctls(conf
, "lxc.sysctl");
3827 lxc_clear_procs(conf
, "lxc.proc");
3828 lxc_clear_apparmor_raw(conf
);
3829 lxc_clear_namespace(conf
);
3830 free(conf
->cgroup_meta
.dir
);
3831 free(conf
->cgroup_meta
.monitor_dir
);
3832 free(conf
->cgroup_meta
.container_dir
);
3833 free(conf
->cgroup_meta
.namespace_dir
);
3834 free(conf
->cgroup_meta
.controllers
);
3835 free(conf
->shmount
.path_host
);
3836 free(conf
->shmount
.path_cont
);
3840 struct userns_fn_data
{
3842 const char *fn_name
;
3847 static int run_userns_fn(void *data
)
3849 struct userns_fn_data
*d
= data
;
3853 close_prot_errno_disarm(d
->p
[1]);
3856 * Wait for parent to finish establishing a new mapping in the user
3857 * namespace we are executing in.
3859 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
3860 close_prot_errno_disarm(d
->p
[0]);
3865 TRACE("Calling function \"%s\"", d
->fn_name
);
3867 /* Call function to run. */
3868 return d
->fn(d
->arg
);
3871 static struct id_map
*mapped_nsid_add(const struct lxc_conf
*conf
, unsigned id
,
3874 const struct id_map
*map
;
3875 struct id_map
*retmap
;
3877 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
3881 retmap
= malloc(sizeof(*retmap
));
3885 memcpy(retmap
, map
, sizeof(*retmap
));
3889 static struct id_map
*find_mapped_hostid_entry(const struct lxc_conf
*conf
,
3890 unsigned id
, enum idtype idtype
)
3893 struct lxc_list
*it
;
3894 struct id_map
*retmap
= NULL
;
3896 lxc_list_for_each (it
, &conf
->id_map
) {
3898 if (map
->idtype
!= idtype
)
3901 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
3910 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
3911 * existing one or establish a new one.
3913 static struct id_map
*mapped_hostid_add(const struct lxc_conf
*conf
, uid_t id
,
3916 __do_free
struct id_map
*entry
= NULL
;
3918 struct id_map
*tmp
= NULL
;
3920 entry
= malloc(sizeof(*entry
));
3924 /* Reuse existing mapping. */
3925 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
3927 memcpy(entry
, tmp
, sizeof(*entry
));
3929 /* Find new mapping. */
3930 hostid_mapped
= find_unmapped_nsid(conf
, type
);
3931 if (hostid_mapped
< 0)
3932 return log_debug(NULL
, "Failed to find free mapping for id %d", id
);
3934 entry
->idtype
= type
;
3935 entry
->nsid
= hostid_mapped
;
3936 entry
->hostid
= (unsigned long)id
;
3940 return move_ptr(entry
);
3943 static struct lxc_list
*get_minimal_idmap(const struct lxc_conf
*conf
,
3944 uid_t
*resuid
, gid_t
*resgid
)
3946 __do_free
struct id_map
*container_root_uid
= NULL
,
3947 *container_root_gid
= NULL
,
3948 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
3949 __do_free
struct lxc_list
*idmap
= NULL
;
3951 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3952 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3953 struct lxc_list
*tmplist
= NULL
;
3955 /* Find container root mappings. */
3956 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
3957 if (!container_root_uid
)
3958 return log_debug(NULL
, "Failed to find mapping for namespace uid %d", 0);
3960 if (euid
>= container_root_uid
->hostid
&&
3961 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
3962 host_uid_map
= move_ptr(container_root_uid
);
3964 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
3965 if (!container_root_gid
)
3966 return log_debug(NULL
, "Failed to find mapping for namespace gid %d", 0);
3968 if (egid
>= container_root_gid
->hostid
&&
3969 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
3970 host_gid_map
= move_ptr(container_root_gid
);
3972 /* Check whether the {g,u}id of the user has a mapping. */
3974 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
3976 return log_debug(NULL
, "Failed to find mapping for uid %d", euid
);
3979 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
3981 return log_debug(NULL
, "Failed to find mapping for gid %d", egid
);
3983 /* Allocate new {g,u}id map list. */
3984 idmap
= malloc(sizeof(*idmap
));
3987 lxc_list_init(idmap
);
3989 /* Add container root to the map. */
3990 tmplist
= malloc(sizeof(*tmplist
));
3993 /* idmap will now keep track of that memory. */
3994 lxc_list_add_elem(tmplist
, move_ptr(host_uid_map
));
3995 lxc_list_add_tail(idmap
, tmplist
);
3997 if (container_root_uid
) {
3998 /* Add container root to the map. */
3999 tmplist
= malloc(sizeof(*tmplist
));
4002 /* idmap will now keep track of that memory. */
4003 lxc_list_add_elem(tmplist
, move_ptr(container_root_uid
));
4004 lxc_list_add_tail(idmap
, tmplist
);
4007 tmplist
= malloc(sizeof(*tmplist
));
4010 /* idmap will now keep track of that memory. */
4011 lxc_list_add_elem(tmplist
, move_ptr(host_gid_map
));
4012 lxc_list_add_tail(idmap
, tmplist
);
4014 if (container_root_gid
) {
4015 tmplist
= malloc(sizeof(*tmplist
));
4018 /* idmap will now keep track of that memory. */
4019 lxc_list_add_elem(tmplist
, move_ptr(container_root_gid
));
4020 lxc_list_add_tail(idmap
, tmplist
);
4023 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid
, nsgid
);
4029 return move_ptr(idmap
);
4033 * Run a function in a new user namespace.
4034 * The caller's euid/egid will be mapped if it is not already.
4035 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4036 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4037 * This means we require only to establish a mapping from:
4038 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4039 * - the container root -> some sub{g,u}id
4040 * The former we add, if the user did not specify a mapping. The latter we
4041 * retrieve from the container's configured {g,u}id mappings as it must have been
4042 * there to start the container in the first place.
4044 int userns_exec_1(const struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4045 const char *fn_name
)
4047 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
4048 int ret
= -1, status
= -1;
4050 struct userns_fn_data d
= {
4061 idmap
= get_minimal_idmap(conf
, NULL
, NULL
);
4063 return ret_errno(ENOENT
);
4065 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
4069 d
.p
[0] = pipe_fds
[0];
4070 d
.p
[1] = pipe_fds
[1];
4072 /* Clone child in new user namespace. */
4073 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
4075 ERROR("Failed to clone process in new user namespace");
4079 close_prot_errno_disarm(pipe_fds
[0]);
4081 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4082 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4084 struct lxc_list
*it
;
4086 lxc_list_for_each(it
, idmap
) {
4088 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
4089 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
4093 /* Set up {g,u}id mapping for user namespace of child process. */
4094 ret
= lxc_map_ids(idmap
, pid
);
4096 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4100 /* Tell child to proceed. */
4101 if (lxc_write_nointr(pipe_fds
[1], &c
, 1) != 1) {
4102 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4107 close_prot_errno_disarm(pipe_fds
[0]);
4108 close_prot_errno_disarm(pipe_fds
[1]);
4110 /* Wait for child to finish. */
4112 status
= wait_for_pid(pid
);
4120 int userns_exec_minimal(const struct lxc_conf
*conf
,
4121 int (*fn_parent
)(void *), void *fn_parent_data
,
4122 int (*fn_child
)(void *), void *fn_child_data
)
4124 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
4125 uid_t resuid
= LXC_INVALID_UID
;
4126 gid_t resgid
= LXC_INVALID_GID
;
4132 if (!conf
|| !fn_child
)
4133 return ret_errno(EINVAL
);
4135 idmap
= get_minimal_idmap(conf
, &resuid
, &resgid
);
4137 return ret_errno(ENOENT
);
4139 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
4145 SYSERROR("Failed to create new process");
4150 close_prot_errno_disarm(sock_fds
[1]);
4152 ret
= unshare(CLONE_NEWUSER
);
4154 SYSERROR("Failed to unshare new user namespace");
4155 _exit(EXIT_FAILURE
);
4158 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
4160 _exit(EXIT_FAILURE
);
4162 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
4164 _exit(EXIT_FAILURE
);
4166 close_prot_errno_disarm(sock_fds
[0]);
4168 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
4169 _exit(EXIT_FAILURE
);
4171 ret
= setresgid(resgid
, resgid
, resgid
);
4173 SYSERROR("Failed to setresgid(%d, %d, %d)",
4174 resgid
, resgid
, resgid
);
4175 _exit(EXIT_FAILURE
);
4178 ret
= setresuid(resuid
, resuid
, resuid
);
4180 SYSERROR("Failed to setresuid(%d, %d, %d)",
4181 resuid
, resuid
, resuid
);
4182 _exit(EXIT_FAILURE
);
4185 ret
= fn_child(fn_child_data
);
4187 SYSERROR("Running function in new user namespace failed");
4188 _exit(EXIT_FAILURE
);
4191 _exit(EXIT_SUCCESS
);
4194 close_prot_errno_disarm(sock_fds
[0]);
4196 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4197 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4199 struct lxc_list
*it
;
4201 lxc_list_for_each(it
, idmap
) {
4203 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
4204 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
4208 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
4210 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
4214 /* Set up {g,u}id mapping for user namespace of child process. */
4215 ret
= lxc_map_ids(idmap
, pid
);
4217 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4221 /* Tell child to proceed. */
4222 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
4224 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4228 if (fn_parent
&& fn_parent(fn_parent_data
)) {
4229 SYSERROR("Running parent function failed");
4230 _exit(EXIT_FAILURE
);
4234 close_prot_errno_disarm(sock_fds
[0]);
4235 close_prot_errno_disarm(sock_fds
[1]);
4237 /* Wait for child to finish. */
4241 return wait_for_pid(pid
);
4244 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4245 const char *fn_name
)
4251 struct lxc_list
*cur
;
4252 struct userns_fn_data d
;
4255 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4256 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4257 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4262 ret
= pipe2(p
, O_CLOEXEC
);
4264 SYSERROR("opening pipe");
4268 d
.fn_name
= fn_name
;
4273 /* Clone child in new user namespace. */
4274 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
4276 ERROR("Failed to clone process in new user namespace");
4286 /* Allocate new {g,u}id map list. */
4287 idmap
= malloc(sizeof(*idmap
));
4290 lxc_list_init(idmap
);
4292 /* Find container root. */
4293 lxc_list_for_each (cur
, &conf
->id_map
) {
4294 struct id_map
*tmpmap
;
4296 tmplist
= malloc(sizeof(*tmplist
));
4300 tmpmap
= malloc(sizeof(*tmpmap
));
4306 memset(tmpmap
, 0, sizeof(*tmpmap
));
4307 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4308 tmplist
->elem
= tmpmap
;
4310 lxc_list_add_tail(idmap
, tmplist
);
4314 if (map
->idtype
== ID_TYPE_UID
)
4315 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4318 if (map
->idtype
== ID_TYPE_GID
)
4319 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4325 if (map
->idtype
== ID_TYPE_UID
)
4326 if (container_root_uid
== NULL
)
4327 container_root_uid
= map
;
4329 if (map
->idtype
== ID_TYPE_GID
)
4330 if (container_root_gid
== NULL
)
4331 container_root_gid
= map
;
4334 if (!container_root_uid
|| !container_root_gid
) {
4335 ERROR("No mapping for container root found");
4339 /* Check whether the {g,u}id of the user has a mapping. */
4341 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4343 host_uid_map
= container_root_uid
;
4346 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4348 host_gid_map
= container_root_gid
;
4350 if (!host_uid_map
) {
4351 DEBUG("Failed to find mapping for uid %d", euid
);
4355 if (!host_gid_map
) {
4356 DEBUG("Failed to find mapping for gid %d", egid
);
4360 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4361 /* Add container root to the map. */
4362 tmplist
= malloc(sizeof(*tmplist
));
4365 lxc_list_add_elem(tmplist
, host_uid_map
);
4366 lxc_list_add_tail(idmap
, tmplist
);
4368 /* idmap will now keep track of that memory. */
4369 host_uid_map
= NULL
;
4371 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4372 tmplist
= malloc(sizeof(*tmplist
));
4375 lxc_list_add_elem(tmplist
, host_gid_map
);
4376 lxc_list_add_tail(idmap
, tmplist
);
4378 /* idmap will now keep track of that memory. */
4379 host_gid_map
= NULL
;
4381 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4382 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4383 lxc_list_for_each (cur
, idmap
) {
4385 TRACE("establishing %cid mapping for \"%d\" in new "
4386 "user namespace: nsuid %lu - hostid %lu - range "
4388 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4389 map
->nsid
, map
->hostid
, map
->range
);
4393 /* Set up {g,u}id mapping for user namespace of child process. */
4394 ret
= lxc_map_ids(idmap
, pid
);
4396 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4400 /* Tell child to proceed. */
4401 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4402 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4411 /* Wait for child to finish. */
4413 ret
= wait_for_pid(pid
);
4416 __lxc_free_idmap(idmap
);
4418 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4420 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4426 static int add_idmap_entry(struct lxc_list
*idmap
, enum idtype idtype
,
4427 unsigned long nsid
, unsigned long hostid
,
4428 unsigned long range
)
4430 __do_free
struct id_map
*new_idmap
= NULL
;
4431 __do_free
struct lxc_list
*new_list
= NULL
;
4433 new_idmap
= zalloc(sizeof(*new_idmap
));
4435 return ret_errno(ENOMEM
);
4437 new_idmap
->idtype
= idtype
;
4438 new_idmap
->hostid
= hostid
;
4439 new_idmap
->nsid
= nsid
;
4440 new_idmap
->range
= range
;
4442 new_list
= zalloc(sizeof(*new_list
));
4444 return ret_errno(ENOMEM
);
4446 new_list
->elem
= move_ptr(new_idmap
);
4447 lxc_list_add_tail(idmap
, move_ptr(new_list
));
4449 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
4450 idtype
== ID_TYPE_UID
? 'u' : 'g', nsid
, hostid
, range
);
4454 int userns_exec_mapped_root(const char *path
, int path_fd
,
4455 const struct lxc_conf
*conf
)
4457 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
4458 __do_close
int fd
= -EBADF
;
4459 int target_fd
= -EBADF
;
4464 uid_t container_host_uid
, hostuid
;
4465 gid_t container_host_gid
, hostgid
;
4468 if (!conf
|| (!path
&& path_fd
< 0))
4469 return ret_errno(EINVAL
);
4474 container_host_uid
= get_mapped_rootid(conf
, ID_TYPE_UID
);
4475 if (!uid_valid(container_host_uid
))
4476 return log_error(-1, "No uid mapping for container root");
4478 container_host_gid
= get_mapped_rootid(conf
, ID_TYPE_GID
);
4479 if (!gid_valid(container_host_gid
))
4480 return log_error(-1, "No gid mapping for container root");
4483 fd
= open(path
, O_CLOEXEC
| O_NOCTTY
);
4485 return log_error_errno(-errno
, errno
, "Failed to open \"%s\"", path
);
4488 target_fd
= path_fd
;
4491 hostuid
= geteuid();
4492 /* We are root so chown directly. */
4494 ret
= fchown(target_fd
, container_host_uid
, container_host_gid
);
4496 return log_error_errno(-errno
, errno
,
4497 "Failed to fchown(%d(%s), %d, %d)",
4498 target_fd
, path
, container_host_uid
,
4499 container_host_gid
);
4500 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd
, path
,
4501 container_host_uid
, container_host_gid
);
4504 /* The container's root host id matches */
4505 if (container_host_uid
== hostuid
)
4506 return log_info(0, "Container root id is mapped to our uid");
4508 /* Get the current ids of our target. */
4509 ret
= fstat(target_fd
, &st
);
4511 return log_error_errno(-errno
, errno
, "Failed to stat \"%s\"", path
);
4513 hostgid
= getegid();
4514 if (st
.st_uid
== hostuid
&& mapped_hostid(st
.st_gid
, conf
, ID_TYPE_GID
) < 0) {
4515 ret
= fchown(target_fd
, -1, hostgid
);
4517 return log_error_errno(-errno
, errno
,
4518 "Failed to fchown(%d(%s), -1, %d)",
4519 target_fd
, path
, hostgid
);
4520 TRACE("Chowned %d(%s) to -1:%d", target_fd
, path
, hostgid
);
4523 idmap
= malloc(sizeof(*idmap
));
4526 lxc_list_init(idmap
);
4528 /* "u:0:rootuid:1" */
4529 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, 0, container_host_uid
, 1);
4531 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4533 /* "u:hostuid:hostuid:1" */
4534 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, hostuid
, hostuid
, 1);
4536 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4538 /* "g:0:rootgid:1" */
4539 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, 0, container_host_gid
, 1);
4541 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4543 /* "g:hostgid:hostgid:1" */
4544 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, hostgid
, hostgid
, 1);
4546 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4548 if (hostgid
!= st
.st_gid
) {
4549 /* "g:pathgid:rootgid+pathgid:1" */
4550 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, st
.st_gid
,
4551 container_host_gid
+ (gid_t
)st
.st_gid
, 1);
4553 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4556 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
4562 SYSERROR("Failed to create new process");
4567 close_prot_errno_disarm(sock_fds
[1]);
4569 ret
= unshare(CLONE_NEWUSER
);
4571 SYSERROR("Failed to unshare new user namespace");
4572 _exit(EXIT_FAILURE
);
4575 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
4577 _exit(EXIT_FAILURE
);
4579 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
4581 _exit(EXIT_FAILURE
);
4583 close_prot_errno_disarm(sock_fds
[0]);
4585 if (!lxc_switch_uid_gid(0, 0))
4586 _exit(EXIT_FAILURE
);
4588 if (!lxc_setgroups(0, NULL
))
4589 _exit(EXIT_FAILURE
);
4591 ret
= fchown(target_fd
, 0, st
.st_gid
);
4593 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
4594 _exit(EXIT_FAILURE
);
4597 TRACE("Chowned %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
4598 _exit(EXIT_SUCCESS
);
4601 close_prot_errno_disarm(sock_fds
[0]);
4603 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4604 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4606 struct lxc_list
*it
;
4608 lxc_list_for_each(it
, idmap
) {
4610 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
4611 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
4615 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
4617 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
4621 /* Set up {g,u}id mapping for user namespace of child process. */
4622 ret
= lxc_map_ids(idmap
, pid
);
4624 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4628 /* Tell child to proceed. */
4629 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
4631 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4636 close_prot_errno_disarm(sock_fds
[0]);
4637 close_prot_errno_disarm(sock_fds
[1]);
4639 /* Wait for child to finish. */
4643 return wait_for_pid(pid
);
4646 /* not thread-safe, do not use from api without first forking */
4647 static char *getuname(void)
4649 __do_free
char *buf
= NULL
;
4650 struct passwd pwent
;
4651 struct passwd
*pwentp
= NULL
;
4655 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
4659 buf
= malloc(bufsize
);
4663 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
4666 WARN("Could not find matched password record.");
4668 return log_error(NULL
, "Failed to get password record - %u", geteuid());
4671 return strdup(pwent
.pw_name
);
4674 /* not thread-safe, do not use from api without first forking */
4675 static char *getgname(void)
4677 __do_free
char *buf
= NULL
;
4679 struct group
*grentp
= NULL
;
4683 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
4687 buf
= malloc(bufsize
);
4691 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
4694 WARN("Could not find matched group record");
4696 return log_error(NULL
, "Failed to get group record - %u", getegid());
4699 return strdup(grent
.gr_name
);
4702 /* not thread-safe, do not use from api without first forking */
4703 void suggest_default_idmap(void)
4705 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
4706 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
4707 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4718 subuid_f
= fopen(subuidfile
, "re");
4720 ERROR("Your system is not configured with subuids");
4724 while (getline(&line
, &len
, subuid_f
) != -1) {
4726 size_t no_newline
= 0;
4728 p
= strchr(line
, ':');
4736 if (strcmp(line
, uname
))
4739 p2
= strchr(p
, ':');
4746 no_newline
= strcspn(p2
, "\n");
4747 p2
[no_newline
] = '\0';
4749 if (lxc_safe_uint(p
, &uid
) < 0)
4750 WARN("Could not parse UID");
4751 if (lxc_safe_uint(p2
, &urange
) < 0)
4752 WARN("Could not parse UID range");
4755 subgid_f
= fopen(subgidfile
, "re");
4757 ERROR("Your system is not configured with subgids");
4761 while (getline(&line
, &len
, subgid_f
) != -1) {
4763 size_t no_newline
= 0;
4765 p
= strchr(line
, ':');
4773 if (strcmp(line
, uname
))
4776 p2
= strchr(p
, ':');
4783 no_newline
= strcspn(p2
, "\n");
4784 p2
[no_newline
] = '\0';
4786 if (lxc_safe_uint(p
, &gid
) < 0)
4787 WARN("Could not parse GID");
4788 if (lxc_safe_uint(p2
, &grange
) < 0)
4789 WARN("Could not parse GID range");
4792 if (!urange
|| !grange
) {
4793 ERROR("You do not have subuids or subgids allocated");
4794 ERROR("Unprivileged containers require subuids and subgids");
4798 ERROR("You must either run as root, or define uid mappings");
4799 ERROR("To pass uid mappings to lxc-create, you could create");
4800 ERROR("~/.config/lxc/default.conf:");
4801 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4802 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4803 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4806 static void free_cgroup_settings(struct lxc_list
*result
)
4808 struct lxc_list
*iterator
, *next
;
4810 lxc_list_for_each_safe (iterator
, result
, next
) {
4811 lxc_list_del(iterator
);
4812 free_disarm(iterator
);
4814 free_disarm(result
);
4817 /* Return the list of cgroup_settings sorted according to the following rules
4818 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4820 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
4822 struct lxc_list
*result
;
4823 struct lxc_cgroup
*cg
= NULL
;
4824 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
4826 result
= malloc(sizeof(*result
));
4829 lxc_list_init(result
);
4831 /* Iterate over the cgroup settings and copy them to the output list. */
4832 lxc_list_for_each (it
, cgroup_settings
) {
4833 item
= malloc(sizeof(*item
));
4835 free_cgroup_settings(result
);
4839 item
->elem
= it
->elem
;
4841 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4842 /* Store the memsw_limit location */
4844 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 &&
4845 memsw_limit
!= NULL
) {
4846 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4847 * before lxc.cgroup.memory.limit_in_bytes, swap these
4849 item
->elem
= memsw_limit
->elem
;
4850 memsw_limit
->elem
= it
->elem
;
4852 lxc_list_add_tail(result
, item
);