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 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", mntpt
, device
->name
);
1211 if (ret
< 0 || ret
>= sizeof(path
))
1212 return log_error(-1, "Failed to create device path for %s", device
->name
);
1213 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
, rootfs
->path
? rootfs
->mount
: NULL
);
1217 return log_error_errno(-1, errno
, "Failed to bind mount host device node \"%s\" onto \"%s\"", hostpath
, device
->name
);
1218 DEBUG("Bind mounted host device node \"%s\" onto \"%s\"", hostpath
, device
->name
);
1222 INFO("Populated \"/dev\"");
1226 static int lxc_mount_rootfs(struct lxc_conf
*conf
)
1229 struct lxc_storage
*bdev
;
1230 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1232 if (!rootfs
->path
) {
1233 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1235 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
1237 rootfs
->mntpt_fd
= openat(-1, "/", O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_PATH
);
1238 if (rootfs
->mntpt_fd
< 0)
1244 ret
= access(rootfs
->mount
, F_OK
);
1246 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
1249 bdev
= storage_init(conf
);
1251 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1252 rootfs
->path
, rootfs
->mount
,
1253 rootfs
->options
? rootfs
->options
: "(null)");
1255 ret
= bdev
->ops
->mount(bdev
);
1258 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1259 rootfs
->path
, rootfs
->mount
,
1260 rootfs
->options
? rootfs
->options
: "(null)");
1262 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1263 rootfs
->path
, rootfs
->mount
,
1264 rootfs
->options
? rootfs
->options
: "(null)");
1266 rootfs
->mntpt_fd
= openat(-1, rootfs
->mount
, O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_PATH
);
1267 if (rootfs
->mntpt_fd
< 0)
1273 static int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1275 __do_free
char *nroot
= NULL
;
1277 char *root
= rootfs
->mount
;
1279 nroot
= realpath(root
, NULL
);
1281 return log_error_errno(-1, errno
, "Failed to resolve \"%s\"", root
);
1287 /* We could use here MS_MOVE, but in userns this mount is locked and
1290 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1292 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1294 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1296 return log_error_errno(-1, errno
, "Failed to remount \"/\"");
1298 /* The following code cleans up inherited mounts which are not required
1301 * The mountinfo file shows not all mounts, if a few points have been
1302 * unmounted between read operations from the mountinfo. So we need to
1303 * read mountinfo a few times.
1305 * This loop can be skipped if a container uses userns, because all
1306 * inherited mounts are locked and we should live with all this trash.
1309 __do_fclose
FILE *f
= NULL
;
1310 __do_free
char *line
= NULL
;
1311 char *slider1
, *slider2
;
1315 f
= fopen("./proc/self/mountinfo", "re");
1317 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
1319 while (getline(&line
, &len
, f
) > 0) {
1320 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
1321 slider1
= strchr(slider1
+ 1, ' ');
1326 slider2
= strchr(slider1
+ 1, ' ');
1333 if (strcmp(slider1
+ 1, "/") == 0)
1336 if (strcmp(slider1
+ 1, "/proc") == 0)
1339 ret
= umount2(slider1
, MNT_DETACH
);
1348 /* This also can be skipped if a container uses userns. */
1349 (void)umount2("./proc", MNT_DETACH
);
1351 /* It is weird, but chdir("..") moves us in a new root */
1354 return log_error_errno(-1, errno
, "Failed to chdir(\"..\")");
1358 return log_error_errno(-1, errno
, "Failed to chroot(\".\")");
1363 /* (The following explanation is copied verbatim from the kernel.)
1365 * pivot_root Semantics:
1366 * Moves the root file system of the current process to the directory put_old,
1367 * makes new_root as the new root file system of the current process, and sets
1368 * root/cwd of all processes which had them on the current root to new_root.
1371 * The new_root and put_old must be directories, and must not be on the
1372 * same file system as the current process root. The put_old must be
1373 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1374 * pointed to by put_old must yield the same directory as new_root. No other
1375 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1377 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1378 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1379 * in this situation.
1382 * - we don't move root/cwd if they are not at the root (reason: if something
1383 * cared enough to change them, it's probably wrong to force them elsewhere)
1384 * - it's okay to pick a root that isn't the root of a file system, e.g.
1385 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1386 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1389 static int lxc_pivot_root(const char *rootfs
)
1391 __do_close
int oldroot
= -EBADF
, newroot
= -EBADF
;
1394 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1396 return log_error_errno(-1, errno
, "Failed to open old root directory");
1398 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1400 return log_error_errno(-1, errno
, "Failed to open new root directory");
1402 /* change into new root fs */
1403 ret
= fchdir(newroot
);
1405 return log_error_errno(-1, errno
, "Failed to change to new rootfs \"%s\"", rootfs
);
1407 /* pivot_root into our new root fs */
1408 ret
= pivot_root(".", ".");
1410 return log_error_errno(-1, errno
, "Failed to pivot_root()");
1412 /* At this point the old-root is mounted on top of our new-root. To
1413 * unmounted it we must not be chdir'd into it, so escape back to
1416 ret
= fchdir(oldroot
);
1418 return log_error_errno(-1, errno
, "Failed to enter old root directory");
1420 /* Make oldroot a depedent mount to make sure our umounts don't propagate to the
1423 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1425 return log_error_errno(-1, errno
, "Failed to recursively turn old root mount tree into dependent mount");
1427 ret
= umount2(".", MNT_DETACH
);
1429 return log_error_errno(-1, errno
, "Failed to detach old root directory");
1431 ret
= fchdir(newroot
);
1433 return log_error_errno(-1, errno
, "Failed to re-enter new root directory");
1435 TRACE("pivot_root(\"%s\") successful", rootfs
);
1440 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1443 return log_debug(0, "Container does not have a rootfs");
1445 if (detect_ramfs_rootfs())
1446 return lxc_chroot(rootfs
);
1448 return lxc_pivot_root(rootfs
->mount
);
1451 static const struct id_map
*find_mapped_nsid_entry(const struct lxc_conf
*conf
,
1455 struct lxc_list
*it
;
1457 struct id_map
*retmap
= NULL
;
1459 /* Shortcut for container's root mappings. */
1461 if (idtype
== ID_TYPE_UID
)
1462 return conf
->root_nsuid_map
;
1464 if (idtype
== ID_TYPE_GID
)
1465 return conf
->root_nsgid_map
;
1468 lxc_list_for_each(it
, &conf
->id_map
) {
1470 if (map
->idtype
!= idtype
)
1473 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1482 int lxc_setup_devpts_parent(struct lxc_handler
*handler
)
1486 if (handler
->conf
->pty_max
<= 0)
1489 ret
= lxc_abstract_unix_recv_fds(handler
->data_sock
[1], &handler
->conf
->devpts_fd
, 1,
1490 &handler
->conf
->devpts_fd
, sizeof(handler
->conf
->devpts_fd
));
1492 return log_error_errno(-1, errno
, "Failed to receive devpts fd from child");
1494 TRACE("Received devpts file descriptor %d from child", handler
->conf
->devpts_fd
);
1498 static int lxc_setup_devpts_child(struct lxc_handler
*handler
)
1500 __do_close
int devpts_fd
= -EBADF
;
1503 char devpts_mntopts
[256];
1504 char *mntopt_sets
[5];
1505 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1506 struct lxc_conf
*conf
= handler
->conf
;
1507 int sock
= handler
->data_sock
[0];
1509 if (conf
->pty_max
<= 0)
1510 return log_debug(0, "No new devpts instance will be mounted since no pts devices are requested");
1512 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1513 default_devpts_mntopts
, conf
->pty_max
);
1514 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1517 (void)umount2("/dev/pts", MNT_DETACH
);
1519 /* Create mountpoint for devpts instance. */
1520 ret
= mkdir("/dev/pts", 0755);
1521 if (ret
< 0 && errno
!= EEXIST
)
1522 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1525 mntopt_sets
[0] = devpts_mntopts
;
1527 /* !gid=5 && max= */
1528 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1530 /* gid=5 && !max= */
1531 mntopt_sets
[2] = default_devpts_mntopts
;
1533 /* !gid=5 && !max= */
1534 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1537 mntopt_sets
[4] = NULL
;
1539 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1540 /* mount new devpts instance */
1541 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1547 return log_error_errno(-1, errno
, "Failed to mount new devpts instance");
1548 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1550 devpts_fd
= openat(-EBADF
, "/dev/pts", O_CLOEXEC
| O_DIRECTORY
| O_PATH
| O_NOFOLLOW
);
1551 if (devpts_fd
< 0) {
1553 TRACE("Failed to create detached devpts mount");
1554 ret
= lxc_abstract_unix_send_fds(sock
, NULL
, 0, &devpts_fd
, sizeof(int));
1556 ret
= lxc_abstract_unix_send_fds(sock
, &devpts_fd
, 1, NULL
, 0);
1559 return log_error_errno(-1, errno
, "Failed to send devpts fd to parent");
1561 TRACE("Sent devpts file descriptor %d to parent", devpts_fd
);
1563 /* Remove any pre-existing /dev/ptmx file. */
1564 ret
= remove("/dev/ptmx");
1566 if (errno
!= ENOENT
)
1567 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\" file");
1569 DEBUG("Removed existing \"/dev/ptmx\" file");
1572 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1573 ret
= mknod("/dev/ptmx", S_IFREG
| 0000, 0);
1574 if (ret
< 0 && errno
!= EEXIST
)
1575 return log_error_errno(-1, errno
, "Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1576 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1578 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1579 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1581 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1583 /* Fallthrough and try to create a symlink. */
1584 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1586 /* Remove the dummy /dev/ptmx file we created above. */
1587 ret
= remove("/dev/ptmx");
1589 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\"");
1591 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1592 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1594 return log_error_errno(-1, errno
, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1596 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1600 static int setup_personality(int persona
)
1604 #if HAVE_SYS_PERSONALITY_H
1608 ret
= personality(persona
);
1610 return log_error_errno(-1, errno
, "Failed to set personality to \"0x%x\"", persona
);
1612 INFO("Set personality to \"0x%x\"", persona
);
1618 static inline bool wants_console(const struct lxc_terminal
*terminal
)
1620 return !terminal
->path
|| strcmp(terminal
->path
, "none");
1623 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1624 const struct lxc_terminal
*console
,
1628 char path
[PATH_MAX
];
1629 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1631 if (!wants_console(console
))
1635 * When we are asked to setup a console we remove any previous
1636 * /dev/console bind-mounts.
1638 if (exists_file_at(rootfs
->dev_mntpt_fd
, "console")) {
1639 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1640 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1643 ret
= lxc_unstack_mountpoint(path
, false);
1645 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", path
);
1647 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1651 * For unprivileged containers autodev or automounts will already have
1652 * taken care of creating /dev/console.
1654 ret
= mknodat(rootfs
->dev_mntpt_fd
, "console", S_IFREG
| 0000, 0);
1655 if (ret
< 0 && errno
!= EEXIST
)
1656 return log_error_errno(-errno
, errno
, "Failed to create console");
1658 ret
= fchmod(console
->pty
, S_IXUSR
| S_IXGRP
);
1660 return log_error_errno(-errno
, errno
, "Failed to set mode \"0%o\" to \"%s\"", S_IXUSR
| S_IXGRP
, console
->name
);
1662 if (pty_mnt_fd
>= 0) {
1663 ret
= move_mount(pty_mnt_fd
, "", rootfs
->dev_mntpt_fd
, "console", MOVE_MOUNT_F_EMPTY_PATH
);
1665 DEBUG("Moved mount \"%s\" onto \"%s\"", console
->name
, path
);
1669 if (ret
&& errno
!= ENOSYS
)
1670 return log_error_errno(-1, errno
,
1671 "Failed to mount %d(%s) on \"%s\"",
1672 pty_mnt_fd
, console
->name
, path
);
1675 ret
= safe_mount_beneath_at(rootfs
->dev_mntpt_fd
, console
->name
, "console", NULL
, MS_BIND
, NULL
);
1677 if (errno
== ENOSYS
) {
1678 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1679 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1682 ret
= safe_mount(console
->name
, path
, "none", MS_BIND
, NULL
, rootfs_path
);
1684 return log_error_errno(-1, errno
, "Failed to mount %d(%s) on \"%s\"", pty_mnt_fd
, console
->name
, path
);
1689 DEBUG("Mounted pty device %d(%s) onto \"%s\"", pty_mnt_fd
, console
->name
, path
);
1693 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1694 const struct lxc_terminal
*console
,
1695 char *ttydir
, int pty_mnt_fd
)
1698 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
1699 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1701 if (!wants_console(console
))
1704 /* create rootfs/dev/<ttydir> directory */
1705 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1706 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1709 ret
= mkdir(path
, 0755);
1710 if (ret
&& errno
!= EEXIST
)
1711 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", path
);
1712 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1714 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1715 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1718 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1719 if (ret
< 0 && errno
!= EEXIST
)
1720 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", lxcpath
);
1722 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1723 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1726 if (file_exists(path
)) {
1727 ret
= lxc_unstack_mountpoint(path
, false);
1729 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", path
);
1731 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1734 ret
= mknod(path
, S_IFREG
| 0000, 0);
1735 if (ret
< 0 && errno
!= EEXIST
)
1736 return log_error_errno(-errno
, errno
, "Failed to create console");
1738 ret
= fchmod(console
->pty
, S_IXUSR
| S_IXGRP
);
1740 return log_error_errno(-errno
, errno
, "Failed to set mode \"0%o\" to \"%s\"", S_IXUSR
| S_IXGRP
, console
->name
);
1742 /* bind mount console->name to '/dev/<ttydir>/console' */
1743 if (pty_mnt_fd
>= 0) {
1744 ret
= move_mount(pty_mnt_fd
, "", -EBADF
, lxcpath
, MOVE_MOUNT_F_EMPTY_PATH
);
1746 DEBUG("Moved mount \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1750 if (ret
&& errno
!= ENOSYS
)
1751 return log_error_errno(-1, errno
,
1752 "Failed to mount %d(%s) on \"%s\"",
1753 pty_mnt_fd
, console
->name
, lxcpath
);
1756 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1758 return log_error_errno(-1, errno
, "Failed to mount %d(%s) on \"%s\"", pty_mnt_fd
, console
->name
, lxcpath
);
1759 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1762 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1763 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1765 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1766 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1768 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1772 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1773 const struct lxc_terminal
*console
, char *ttydir
,
1778 return lxc_setup_dev_console(rootfs
, console
, pty_mnt_fd
);
1780 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
, pty_mnt_fd
);
1783 static int parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1787 /* If '=' is contained in opt, the option must go into data. */
1788 if (!strchr(opt
, '=')) {
1790 * If opt is found in mount_opt, set or clear flags.
1791 * Otherwise append it to data.
1793 size_t opt_len
= strlen(opt
);
1794 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1795 size_t mo_name_len
= strlen(mo
->name
);
1797 if (opt_len
== mo_name_len
&& strncmp(opt
, mo
->name
, mo_name_len
) == 0) {
1799 *flags
&= ~mo
->flag
;
1807 if (strlen(*data
)) {
1808 ret
= strlcat(*data
, ",", size
);
1810 return log_error_errno(ret
, errno
, "Failed to append \",\" to %s", *data
);
1813 ret
= strlcat(*data
, opt
, size
);
1815 return log_error_errno(ret
, errno
, "Failed to append \"%s\" to %s", opt
, *data
);
1820 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1822 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
1823 char *mntopt_cur
= NULL
;
1826 if (*mntdata
|| *mntflags
)
1827 return ret_errno(EINVAL
);
1832 mntopts_dup
= strdup(mntopts
);
1834 return ret_errno(ENOMEM
);
1836 size
= strlen(mntopts_dup
) + 1;
1837 mntopts_new
= zalloc(size
);
1839 return ret_errno(ENOMEM
);
1841 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",")
1842 if (parse_mntopt(mntopt_cur
, mntflags
, &mntopts_new
, size
) < 0)
1843 return ret_errno(EINVAL
);
1846 *mntdata
= move_ptr(mntopts_new
);
1851 static void parse_propagationopt(char *opt
, unsigned long *flags
)
1853 struct mount_opt
*mo
;
1855 /* If opt is found in propagation_opt, set or clear flags. */
1856 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
1857 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) != 0)
1861 *flags
&= ~mo
->flag
;
1869 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
1871 __do_free
char *s
= NULL
;
1877 s
= strdup(mntopts
);
1879 return log_error_errno(-ENOMEM
, errno
, "Failed to allocate memory");
1882 lxc_iterate_parts(p
, s
, ",")
1883 parse_propagationopt(p
, pflags
);
1888 static void null_endofword(char *word
)
1890 while (*word
&& *word
!= ' ' && *word
!= '\t')
1895 /* skip @nfields spaces in @src */
1896 static char *get_field(char *src
, int nfields
)
1901 for (i
= 0; i
< nfields
; i
++) {
1902 while (*p
&& *p
!= ' ' && *p
!= '\t')
1914 static int mount_entry(const char *fsname
, const char *target
,
1915 const char *fstype
, unsigned long mountflags
,
1916 unsigned long pflags
, const char *data
, bool optional
,
1917 bool dev
, bool relative
, const char *rootfs
)
1920 char srcbuf
[PATH_MAX
];
1921 const char *srcpath
= fsname
;
1927 ret
= snprintf(srcbuf
, sizeof(srcbuf
), "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
1928 if (ret
< 0 || ret
>= sizeof(srcbuf
))
1929 return log_error_errno(-1, errno
, "source path is too long");
1933 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
1937 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
1938 srcpath
? srcpath
: "(null)", target
);
1940 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
1941 srcpath
? srcpath
: "(null)", target
);
1944 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
1946 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
1947 srcpath
? srcpath
: "(none)", target
? target
: "(none)");
1950 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
1951 unsigned long required_flags
= 0;
1953 if (sb
.f_flag
& MS_NOSUID
)
1954 required_flags
|= MS_NOSUID
;
1956 if (sb
.f_flag
& MS_NODEV
&& !dev
)
1957 required_flags
|= MS_NODEV
;
1959 if (sb
.f_flag
& MS_RDONLY
)
1960 required_flags
|= MS_RDONLY
;
1962 if (sb
.f_flag
& MS_NOEXEC
)
1963 required_flags
|= MS_NOEXEC
;
1965 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
1966 srcpath
, sb
.f_flag
, required_flags
);
1968 /* If this was a bind mount request, and required_flags
1969 * does not have any flags which are not already in
1970 * mountflags, then skip the remount.
1972 if (!(mountflags
& MS_REMOUNT
) &&
1973 (!(required_flags
& ~mountflags
) && !(mountflags
& MS_RDONLY
))) {
1974 DEBUG("Mountflags already were %lu, skipping remount", mountflags
);
1978 mountflags
|= required_flags
;
1982 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
1985 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
1986 srcpath
? srcpath
: "(null)",
1989 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
1990 srcpath
? srcpath
: "(null)",
1999 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2002 return log_info_errno(0, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2004 return log_error_errno(-1, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2006 DEBUG("Changed mount propagation for \"%s\"", target
);
2009 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2010 srcpath
? srcpath
: "(null)", target
, fstype
);
2015 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2016 static void cull_mntent_opt(struct mntent
*mntent
)
2027 for (i
= 0; list
[i
]; i
++) {
2030 p
= strstr(mntent
->mnt_opts
, list
[i
]);
2034 p2
= strchr(p
, ',');
2036 /* no more mntopts, so just chop it here */
2041 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
2045 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2047 const struct lxc_rootfs
*rootfs
,
2048 const char *lxc_name
, const char *lxc_path
)
2050 __do_free
char *p1
= NULL
;
2054 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
2055 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2060 if (hasmntopt(mntent
, "create=dir")) {
2061 ret
= mkdir_p(path
, 0755);
2062 if (ret
< 0 && errno
!= EEXIST
)
2063 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2066 if (!hasmntopt(mntent
, "create=file"))
2069 ret
= access(path
, F_OK
);
2079 ret
= mkdir_p(p2
, 0755);
2080 if (ret
< 0 && errno
!= EEXIST
)
2081 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2083 ret
= mknod(path
, S_IFREG
| 0000, 0);
2084 if (ret
< 0 && errno
!= EEXIST
)
2090 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2091 * without a rootfs. */
2092 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2094 const struct lxc_rootfs
*rootfs
,
2095 const char *lxc_name
,
2096 const char *lxc_path
)
2098 __do_free
char *mntdata
= NULL
;
2099 unsigned long mntflags
= 0, pflags
= 0;
2100 char *rootfs_path
= NULL
;
2102 bool dev
, optional
, relative
;
2104 optional
= hasmntopt(mntent
, "optional") != NULL
;
2105 dev
= hasmntopt(mntent
, "dev") != NULL
;
2106 relative
= hasmntopt(mntent
, "relative") != NULL
;
2108 if (rootfs
&& rootfs
->path
)
2109 rootfs_path
= rootfs
->mount
;
2111 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2119 cull_mntent_opt(mntent
);
2121 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2125 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2129 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2130 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2135 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
2138 char path
[PATH_MAX
];
2140 /* For containers created without a rootfs all mounts are treated as
2141 * absolute paths starting at / on the host.
2143 if (mntent
->mnt_dir
[0] != '/')
2144 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
2146 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
2147 if (ret
< 0 || ret
>= sizeof(path
))
2150 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2153 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2154 const struct lxc_rootfs
*rootfs
,
2155 const char *lxc_name
,
2156 const char *lxc_path
)
2160 const char *lxcpath
;
2161 char path
[PATH_MAX
];
2164 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2168 /* If rootfs->path is a blockdev path, allow container fstab to use
2169 * <lxcpath>/<name>/rootfs" as the target prefix.
2171 ret
= snprintf(path
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2172 if (ret
< 0 || ret
>= PATH_MAX
)
2175 aux
= strstr(mntent
->mnt_dir
, path
);
2177 offset
= strlen(path
);
2182 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2184 return log_warn(ret
, "Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2185 offset
= strlen(rootfs
->path
);
2188 ret
= snprintf(path
, PATH_MAX
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2189 if (ret
< 0 || ret
>= PATH_MAX
)
2192 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2195 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2196 const struct lxc_rootfs
*rootfs
,
2197 const char *lxc_name
,
2198 const char *lxc_path
)
2201 char path
[PATH_MAX
];
2203 /* relative to root mount point */
2204 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2205 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
2208 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2211 static int mount_file_entries(const struct lxc_rootfs
*rootfs
, FILE *file
,
2212 const char *lxc_name
, const char *lxc_path
)
2215 struct mntent mntent
;
2217 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2221 ret
= mount_entry_on_systemfs(&mntent
);
2222 else if (mntent
.mnt_dir
[0] != '/')
2223 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2224 lxc_name
, lxc_path
);
2226 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2227 lxc_name
, lxc_path
);
2232 if (!feof(file
) || ferror(file
))
2233 return log_error(-1, "Failed to parse mount entries");
2238 static inline void __auto_endmntent__(FILE **f
)
2244 #define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2246 static int setup_mount(const struct lxc_conf
*conf
,
2247 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2248 const char *lxc_name
, const char *lxc_path
)
2250 __do_endmntent
FILE *f
= NULL
;
2256 f
= setmntent(fstab
, "re");
2258 return log_error_errno(-1, errno
, "Failed to open \"%s\"", fstab
);
2260 ret
= mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2262 ERROR("Failed to set up mount entries");
2268 * In order for nested containers to be able to mount /proc and /sys they need
2269 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2271 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2272 * apparmor rule to deny access to them. This is mostly for convenience: The
2273 * container's root user can mount them anyway and thus has access to the two
2274 * file systems. But a non-root user in the container should not be allowed to
2275 * access them as a side effect without explicitly allowing it.
2277 static const char nesting_helpers
[] =
2278 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2279 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2281 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2282 bool include_nesting_helpers
)
2284 __do_close
int fd
= -EBADF
;
2288 struct lxc_list
*iterator
;
2290 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2292 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2294 if (errno
!= ENOSYS
)
2297 fd
= lxc_make_tmpfile(template, true);
2299 return log_error_errno(NULL
, errno
, "Could not create temporary mount file");
2301 TRACE("Created temporary mount file");
2304 lxc_list_for_each (iterator
, mount
) {
2307 mount_entry
= iterator
->elem
;
2308 len
= strlen(mount_entry
);
2310 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2314 ret
= lxc_write_nointr(fd
, "\n", 1);
2319 if (include_nesting_helpers
) {
2320 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2321 STRARRAYLEN(nesting_helpers
));
2322 if (ret
!= STRARRAYLEN(nesting_helpers
))
2326 ret
= lseek(fd
, 0, SEEK_SET
);
2330 f
= fdopen(fd
, "re+");
2332 move_fd(fd
); /* Transfer ownership of fd. */
2336 static int setup_mount_entries(const struct lxc_conf
*conf
,
2337 const struct lxc_rootfs
*rootfs
,
2338 struct lxc_list
*mount
, const char *lxc_name
,
2339 const char *lxc_path
)
2341 __do_fclose
FILE *f
= NULL
;
2343 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2347 return mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2350 static int parse_cap(const char *cap
)
2354 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2357 if (strcmp(cap
, "none") == 0)
2360 for (i
= 0; i
< end
; i
++) {
2361 if (strcmp(cap
, caps_opt
[i
].name
))
2364 capid
= caps_opt
[i
].value
;
2369 /* Try to see if it's numeric, so the user may specify
2370 * capabilities that the running kernel knows about but we
2374 capid
= strtol(cap
, &ptr
, 10);
2375 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2376 /* not a valid number */
2378 else if (capid
> lxc_caps_last_cap())
2379 /* we have a number but it's not a valid
2387 int in_caplist(int cap
, struct lxc_list
*caps
)
2390 struct lxc_list
*iterator
;
2392 lxc_list_for_each (iterator
, caps
) {
2393 capid
= parse_cap(iterator
->elem
);
2401 static int setup_caps(struct lxc_list
*caps
)
2405 struct lxc_list
*iterator
;
2407 lxc_list_for_each (iterator
, caps
) {
2410 drop_entry
= iterator
->elem
;
2412 capid
= parse_cap(drop_entry
);
2414 return log_error(-1, "unknown capability %s", drop_entry
);
2416 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2417 prctl_arg(0), prctl_arg(0));
2419 return log_error_errno(-1, errno
, "Failed to remove %s capability", drop_entry
);
2420 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2423 DEBUG("Capabilities have been setup");
2427 static int dropcaps_except(struct lxc_list
*caps
)
2429 __do_free
int *caplist
= NULL
;
2430 int i
, capid
, numcaps
;
2432 struct lxc_list
*iterator
;
2434 numcaps
= lxc_caps_last_cap() + 1;
2435 if (numcaps
<= 0 || numcaps
> 200)
2437 TRACE("Found %d capabilities", numcaps
);
2439 /* caplist[i] is 1 if we keep capability i */
2440 caplist
= must_realloc(NULL
, numcaps
* sizeof(int));
2441 memset(caplist
, 0, numcaps
* sizeof(int));
2443 lxc_list_for_each (iterator
, caps
) {
2444 keep_entry
= iterator
->elem
;
2446 capid
= parse_cap(keep_entry
);
2451 return log_error(-1, "Unknown capability %s", keep_entry
);
2453 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2457 for (i
= 0; i
< numcaps
; i
++) {
2463 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2464 prctl_arg(0), prctl_arg(0));
2466 return log_error_errno(-1, errno
, "Failed to remove capability %d", i
);
2469 DEBUG("Capabilities have been setup");
2473 static int parse_resource(const char *res
)
2479 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2480 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2481 return limit_opt
[i
].value
;
2483 /* Try to see if it's numeric, so the user may specify
2484 * resources that the running kernel knows about but
2487 ret
= lxc_safe_int(res
, &resid
);
2494 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2497 struct lxc_list
*it
;
2498 struct lxc_limit
*lim
;
2500 lxc_list_for_each (it
, limits
) {
2503 resid
= parse_resource(lim
->resource
);
2505 return log_error(-1, "Unknown resource %s", lim
->resource
);
2507 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2508 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0)
2509 return log_error_errno(-1, errno
, "Failed to set limit %s", lim
->resource
);
2511 TRACE("Setup \"%s\" limit", lim
->resource
);
2513 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
2520 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2522 __do_free
char *tmp
= NULL
;
2523 struct lxc_list
*it
;
2524 struct lxc_sysctl
*elem
;
2526 char filename
[PATH_MAX
] = {0};
2528 lxc_list_for_each (it
, sysctls
) {
2530 tmp
= lxc_string_replace(".", "/", elem
->key
);
2532 return log_error(-1, "Failed to replace key %s", elem
->key
);
2534 ret
= snprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2535 if (ret
< 0 || (size_t)ret
>= sizeof(filename
))
2536 return log_error(-1, "Error setting up sysctl parameters path");
2538 ret
= lxc_write_to_file(filename
, elem
->value
,
2539 strlen(elem
->value
), false, 0666);
2541 return log_error_errno(-1, errno
, "Failed to setup sysctl parameters %s to %s",
2542 elem
->key
, elem
->value
);
2548 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2550 __do_free
char *tmp
= NULL
;
2551 struct lxc_list
*it
;
2552 struct lxc_proc
*elem
;
2554 char filename
[PATH_MAX
] = {0};
2556 lxc_list_for_each (it
, procs
) {
2558 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2560 return log_error(-1, "Failed to replace key %s", elem
->filename
);
2562 ret
= snprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2563 if (ret
< 0 || (size_t)ret
>= sizeof(filename
))
2564 return log_error(-1, "Error setting up proc filesystem path");
2566 ret
= lxc_write_to_file(filename
, elem
->value
,
2567 strlen(elem
->value
), false, 0666);
2569 return log_error_errno(-1, errno
, "Failed to setup proc filesystem %s to %s", elem
->filename
, elem
->value
);
2575 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2577 struct lxc_conf
*lxc_conf_init(void)
2580 struct lxc_conf
*new;
2582 new = malloc(sizeof(*new));
2585 memset(new, 0, sizeof(*new));
2587 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2588 new->personality
= -1;
2590 new->console
.buffer_size
= 0;
2591 new->console
.log_path
= NULL
;
2592 new->console
.log_fd
= -1;
2593 new->console
.log_size
= 0;
2594 new->console
.path
= NULL
;
2595 new->console
.peer
= -1;
2596 new->console
.proxy
.busy
= -1;
2597 new->console
.proxy
.ptx
= -1;
2598 new->console
.proxy
.pty
= -1;
2599 new->console
.ptx
= -1;
2600 new->console
.pty
= -1;
2601 new->console
.name
[0] = '\0';
2602 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2603 new->maincmd_fd
= -1;
2604 new->monitor_signal_pdeath
= SIGKILL
;
2606 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2607 if (!new->rootfs
.mount
) {
2611 new->rootfs
.managed
= true;
2612 new->rootfs
.mntpt_fd
= -EBADF
;
2613 new->rootfs
.dev_mntpt_fd
= -EBADF
;
2615 lxc_list_init(&new->cgroup
);
2616 lxc_list_init(&new->cgroup2
);
2617 lxc_list_init(&new->devices
);
2618 lxc_list_init(&new->network
);
2619 lxc_list_init(&new->mount_list
);
2620 lxc_list_init(&new->caps
);
2621 lxc_list_init(&new->keepcaps
);
2622 lxc_list_init(&new->id_map
);
2623 new->root_nsuid_map
= NULL
;
2624 new->root_nsgid_map
= NULL
;
2625 lxc_list_init(&new->includes
);
2626 lxc_list_init(&new->aliens
);
2627 lxc_list_init(&new->environment
);
2628 lxc_list_init(&new->limits
);
2629 lxc_list_init(&new->sysctls
);
2630 lxc_list_init(&new->procs
);
2631 new->hooks_version
= 0;
2632 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2633 lxc_list_init(&new->hooks
[i
]);
2634 lxc_list_init(&new->groups
);
2635 lxc_list_init(&new->state_clients
);
2636 new->lsm_aa_profile
= NULL
;
2637 lxc_list_init(&new->lsm_aa_raw
);
2638 new->lsm_se_context
= NULL
;
2639 new->lsm_se_keyring_context
= NULL
;
2640 new->keyring_disable_session
= false;
2641 new->tmp_umount_proc
= false;
2642 new->tmp_umount_proc
= 0;
2643 new->shmount
.path_host
= NULL
;
2644 new->shmount
.path_cont
= NULL
;
2646 /* if running in a new user namespace, init and COMMAND
2647 * default to running as UID/GID 0 when using lxc-execute */
2650 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2651 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2652 memset(&new->timens
, 0, sizeof(struct timens_offsets
));
2653 seccomp_conf_init(new);
2658 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2661 __do_close
int fd
= -EBADF
;
2663 char path
[PATH_MAX
];
2665 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2666 __do_close
int setgroups_fd
= -EBADF
;
2668 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/setgroups", pid
);
2669 if (ret
< 0 || ret
>= PATH_MAX
)
2672 setgroups_fd
= open(path
, O_WRONLY
);
2673 if (setgroups_fd
< 0 && errno
!= ENOENT
)
2674 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
2676 if (setgroups_fd
>= 0) {
2677 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
2678 STRLITERALLEN("deny\n"));
2679 if (ret
!= STRLITERALLEN("deny\n"))
2680 return log_error_errno(-1, errno
, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
2681 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2685 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/%cid_map", pid
,
2686 idtype
== ID_TYPE_UID
? 'u' : 'g');
2687 if (ret
< 0 || ret
>= PATH_MAX
)
2690 fd
= open(path
, O_WRONLY
| O_CLOEXEC
);
2692 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
2694 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2695 if (ret
!= buf_size
)
2696 return log_error_errno(-1, errno
, "Failed to write %cid mapping to \"%s\"",
2697 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2702 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2704 * @return 1 if functional binary was found
2705 * @return 0 if binary exists but is lacking privilege
2706 * @return -ENOENT if binary does not exist
2707 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2709 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2711 __do_free
char *path
= NULL
;
2716 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2720 path
= on_path(binary
, NULL
);
2724 ret
= stat(path
, &st
);
2728 /* Check if the binary is setuid. */
2729 if (st
.st_mode
& S_ISUID
)
2730 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path
);
2732 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2733 /* Check if it has the CAP_SETUID capability. */
2734 if ((cap
& CAP_SETUID
) &&
2735 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2736 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
))
2737 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
2739 /* Check if it has the CAP_SETGID capability. */
2740 if ((cap
& CAP_SETGID
) &&
2741 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2742 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
))
2743 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
2745 /* If we cannot check for file capabilities we need to give the benefit
2746 * of the doubt. Otherwise we might fail even though all the necessary
2747 * file capabilities are set.
2749 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
2755 static int lxc_map_ids_exec_wrapper(void *args
)
2757 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2761 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2766 char cmd_output
[PATH_MAX
];
2768 struct lxc_list
*iterator
;
2770 int ret
= 0, gidmap
= 0, uidmap
= 0;
2771 char mapbuf
[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
2772 INTTYPE_TO_STRLEN(pid_t
) + STRLITERALLEN(" ") +
2773 LXC_IDMAPLEN
] = {0};
2774 bool had_entry
= false, use_shadow
= false;
2775 int hostuid
, hostgid
;
2777 hostuid
= geteuid();
2778 hostgid
= getegid();
2780 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2781 * ranges, then insist that root also reserve ranges in subuid. This
2782 * will protected it by preventing another user from being handed the
2785 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2786 if (uidmap
== -ENOENT
)
2787 WARN("newuidmap binary is missing");
2789 WARN("newuidmap is lacking necessary privileges");
2791 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2792 if (gidmap
== -ENOENT
)
2793 WARN("newgidmap binary is missing");
2795 WARN("newgidmap is lacking necessary privileges");
2797 if (uidmap
> 0 && gidmap
> 0) {
2798 DEBUG("Functional newuidmap and newgidmap binary found");
2801 /* In case unprivileged users run application containers via
2802 * execute() or a start*() there are valid cases where they may
2803 * only want to map their own {g,u}id. Let's not block them from
2804 * doing so by requiring geteuid() == 0.
2806 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2807 "write directly with euid %d", hostuid
);
2810 /* Check if we really need to use newuidmap and newgidmap.
2811 * If the user is only remapping his own {g,u}id, we don't need it.
2813 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
2815 lxc_list_for_each(iterator
, idmap
) {
2816 map
= iterator
->elem
;
2817 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
2818 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
2820 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
2821 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
2828 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
2829 type
++, u_or_g
= 'g') {
2833 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
2835 lxc_list_for_each(iterator
, idmap
) {
2836 map
= iterator
->elem
;
2837 if (map
->idtype
!= type
)
2842 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
2843 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
2844 use_shadow
? " " : "", map
->nsid
,
2845 map
->hostid
, map
->range
,
2846 use_shadow
? "" : "\n");
2848 * The kernel only takes <= 4k for writes to
2849 * /proc/<pid>/{g,u}id_map
2851 if (fill
<= 0 || fill
>= left
)
2852 return log_error_errno(-1, errno
, "Too many %cid mappings defined", u_or_g
);
2859 /* Try to catch the output of new{g,u}idmap to make debugging
2863 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2864 lxc_map_ids_exec_wrapper
,
2867 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g
, cmd_output
, mapbuf
);
2868 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
2870 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
2872 return log_error(-1, "Failed to write mapping: %s", mapbuf
);
2873 TRACE("Wrote mapping \"%s\"", mapbuf
);
2876 memset(mapbuf
, 0, sizeof(mapbuf
));
2883 * Return the host uid/gid to which the container root is mapped in val.
2884 * Return true if id was found, false otherwise.
2886 static id_t
get_mapped_rootid(const struct lxc_conf
*conf
, enum idtype idtype
)
2890 struct lxc_list
*it
;
2892 if (idtype
== ID_TYPE_UID
)
2893 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
2895 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
2897 lxc_list_for_each (it
, &conf
->id_map
) {
2899 if (map
->idtype
!= idtype
)
2901 if (map
->nsid
!= nsid
)
2906 if (idtype
== ID_TYPE_UID
)
2907 return LXC_INVALID_UID
;
2909 return LXC_INVALID_GID
;
2912 int mapped_hostid(unsigned id
, const struct lxc_conf
*conf
, enum idtype idtype
)
2915 struct lxc_list
*it
;
2917 lxc_list_for_each (it
, &conf
->id_map
) {
2919 if (map
->idtype
!= idtype
)
2922 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
2923 return (id
- map
->hostid
) + map
->nsid
;
2929 int find_unmapped_nsid(const struct lxc_conf
*conf
, enum idtype idtype
)
2932 struct lxc_list
*it
;
2933 unsigned int freeid
= 0;
2936 lxc_list_for_each (it
, &conf
->id_map
) {
2938 if (map
->idtype
!= idtype
)
2941 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
2942 freeid
= map
->nsid
+ map
->range
;
2950 /* NOTE: Must not be called from inside the container namespace! */
2951 static int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
2955 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
2956 if (mounted
== -1) {
2957 SYSERROR("Failed to mount proc in the container");
2958 /* continue only if there is no rootfs */
2959 if (conf
->rootfs
.path
)
2961 } else if (mounted
== 1) {
2962 conf
->tmp_umount_proc
= true;
2968 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
2970 if (!lxc_conf
->tmp_umount_proc
)
2973 (void)umount2("/proc", MNT_DETACH
);
2974 lxc_conf
->tmp_umount_proc
= false;
2977 /* Walk /proc/mounts and change any shared entries to dependent mounts. */
2978 void turn_into_dependent_mounts(void)
2980 __do_free
char *line
= NULL
;
2981 __do_fclose
FILE *f
= NULL
;
2982 __do_close
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
2987 mntinfo_fd
= open("/proc/self/mountinfo", O_RDONLY
| O_CLOEXEC
);
2988 if (mntinfo_fd
< 0) {
2989 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
2993 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
2995 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
2997 if (errno
!= ENOSYS
) {
2998 SYSERROR("Failed to create temporary in-memory file");
3002 memfd
= lxc_make_tmpfile(template, true);
3004 WARN("Failed to create temporary file");
3009 copied
= fd_to_fd(mntinfo_fd
, memfd
);
3011 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3015 ret
= lseek(memfd
, 0, SEEK_SET
);
3017 SYSERROR("Failed to reset file descriptor offset");
3021 f
= fdopen(memfd
, "re");
3023 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3028 * After a successful fdopen() memfd will be closed when calling
3029 * fclose(f). Calling close(memfd) afterwards is undefined.
3033 while (getline(&line
, &len
, f
) != -1) {
3034 char *opts
, *target
;
3036 target
= get_field(line
, 4);
3040 opts
= get_field(target
, 2);
3044 null_endofword(opts
);
3045 if (!strstr(opts
, "shared"))
3048 null_endofword(target
);
3049 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3051 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
3054 TRACE("Recursively turned old root mount tree into dependent mount");
3056 TRACE("Turned all mount table entries into dependent mount");
3059 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3063 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3064 struct lxc_conf
*conf
= handler
->conf
;
3066 /* If init exists in the container, don't bind mount a static one */
3067 p
= choose_init(conf
->rootfs
.mount
);
3069 __do_free
char *old
= p
;
3071 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3075 INFO("Found existing init at \"%s\"", p
);
3079 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3080 if (ret
< 0 || ret
>= PATH_MAX
)
3083 if (!file_exists(path
))
3084 return log_error_errno(-1, errno
, "The file \"%s\" does not exist on host", path
);
3086 ret
= snprintf(destpath
, PATH_MAX
, "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3087 if (ret
< 0 || ret
>= PATH_MAX
)
3090 if (!file_exists(destpath
)) {
3091 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3092 if (ret
< 0 && errno
!= EEXIST
)
3093 return log_error_errno(-1, errno
, "Failed to create dummy \"%s\" file as bind mount target", destpath
);
3096 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3098 return log_error_errno(-1, errno
, "Failed to bind mount lxc.init.static into container");
3100 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3104 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3106 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3107 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3111 /* This does the work of remounting / if it is shared, calling the container
3112 * pre-mount hooks, and mounting the rootfs.
3114 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3115 const char *lxcpath
)
3119 if (conf
->rootfs_setup
) {
3120 const char *path
= conf
->rootfs
.mount
;
3122 /* The rootfs was set up in another namespace. bind-mount it to
3123 * give us a mount in our own ns so we can pivot_root to it
3125 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3127 return log_error(-1, "Failed to bind mount container / onto itself");
3129 return log_trace(0, "Bind mounted container / onto itself");
3132 turn_into_dependent_mounts();
3134 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3136 return log_error(-1, "Failed to run pre-mount hooks");
3138 ret
= lxc_mount_rootfs(conf
);
3140 return log_error(-1, "Failed to setup rootfs for");
3142 conf
->rootfs_setup
= true;
3146 static bool verify_start_hooks(struct lxc_conf
*conf
)
3148 char path
[PATH_MAX
];
3149 struct lxc_list
*it
;
3151 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3153 char *hookname
= it
->elem
;
3155 ret
= snprintf(path
, PATH_MAX
, "%s%s",
3156 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3158 if (ret
< 0 || ret
>= PATH_MAX
)
3161 ret
= access(path
, X_OK
);
3163 return log_error_errno(false, errno
, "Start hook \"%s\" not found in container", hookname
);
3171 static bool execveat_supported(void)
3173 execveat(-1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3174 if (errno
== ENOSYS
)
3180 static int lxc_setup_boot_id(void)
3183 const char *boot_id_path
= "/proc/sys/kernel/random/boot_id";
3184 const char *mock_boot_id_path
= "/dev/.lxc-boot-id";
3187 if (access(boot_id_path
, F_OK
))
3190 memset(&n
, 0, sizeof(n
));
3191 if (lxc_id128_randomize(&n
)) {
3192 SYSERROR("Failed to generate random data for uuid");
3196 ret
= lxc_id128_write(mock_boot_id_path
, n
);
3198 SYSERROR("Failed to write uuid to %s", mock_boot_id_path
);
3202 ret
= chmod(mock_boot_id_path
, 0444);
3204 SYSERROR("Failed to chown %s", mock_boot_id_path
);
3205 (void)unlink(mock_boot_id_path
);
3209 ret
= mount(mock_boot_id_path
, boot_id_path
, NULL
, MS_BIND
, NULL
);
3211 SYSERROR("Failed to mount %s to %s", mock_boot_id_path
,
3213 (void)unlink(mock_boot_id_path
);
3217 ret
= mount(NULL
, boot_id_path
, NULL
,
3218 (MS_BIND
| MS_REMOUNT
| MS_RDONLY
| MS_NOSUID
| MS_NOEXEC
|
3222 SYSERROR("Failed to remount %s read-only", boot_id_path
);
3223 (void)unlink(mock_boot_id_path
);
3230 static int lxc_setup_keyring(struct lsm_ops
*lsm_ops
, const struct lxc_conf
*conf
)
3232 key_serial_t keyring
;
3235 if (conf
->lsm_se_keyring_context
)
3236 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_keyring_context
);
3237 else if (conf
->lsm_se_context
)
3238 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_context
);
3240 return log_error_errno(-1, errno
, "Failed to set keyring context");
3243 * Try to allocate a new session keyring for the container to prevent
3244 * information leaks.
3246 keyring
= keyctl(KEYCTL_JOIN_SESSION_KEYRING
, prctl_arg(0),
3247 prctl_arg(0), prctl_arg(0), prctl_arg(0));
3251 DEBUG("The keyctl() syscall is not supported or blocked");
3256 DEBUG("Failed to access kernel keyring. Continuing...");
3259 SYSERROR("Failed to create kernel keyring");
3267 int lxc_setup(struct lxc_handler
*handler
)
3269 __do_close
int pty_mnt_fd
= -EBADF
;
3271 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3272 struct lxc_conf
*lxc_conf
= handler
->conf
;
3274 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3276 return log_error(-1, "Failed to setup rootfs");
3278 if (handler
->nsfd
[LXC_NS_UTS
] == -EBADF
) {
3279 ret
= setup_utsname(lxc_conf
->utsname
);
3281 return log_error(-1, "Failed to setup the utsname %s", name
);
3284 if (!lxc_conf
->keyring_disable_session
) {
3285 ret
= lxc_setup_keyring(handler
->lsm_ops
, lxc_conf
);
3287 return log_error(-1, "Failed to setup container keyring");
3290 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
3291 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
,
3292 &lxc_conf
->network
);
3294 return log_error(-1, "Failed to setup network");
3296 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3298 return log_error(-1, "Failed to send network device names and ifindices to parent");
3301 if (wants_console(&lxc_conf
->console
)) {
3302 pty_mnt_fd
= open_tree(-EBADF
, lxc_conf
->console
.name
,
3303 OPEN_TREE_CLONE
| OPEN_TREE_CLOEXEC
| AT_EMPTY_PATH
);
3305 SYSTRACE("Failed to create detached mount for container's console \"%s\"",
3306 lxc_conf
->console
.name
);
3308 TRACE("Created detached mount for container's console \"%s\"",
3309 lxc_conf
->console
.name
);
3312 if (lxc_conf
->autodev
> 0) {
3313 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxc_conf
->autodevtmpfssize
, lxcpath
);
3315 return log_error(-1, "Failed to mount \"/dev\"");
3318 lxc_conf
->rootfs
.dev_mntpt_fd
= openat(lxc_conf
->rootfs
.mntpt_fd
, "dev",
3319 O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_NOFOLLOW
);
3320 if (lxc_conf
->rootfs
.dev_mntpt_fd
< 0 && errno
!= ENOENT
)
3321 return log_error_errno(-errno
, errno
, "Failed to open \"/dev\"");
3323 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3324 * need to wait until other stuff has finished.
3326 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
);
3328 return log_error(-1, "Failed to setup first automatic mounts");
3330 ret
= setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3332 return log_error(-1, "Failed to setup mounts");
3334 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3335 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3336 &lxc_conf
->mount_list
, name
, lxcpath
);
3338 return log_error(-1, "Failed to setup mount entries");
3341 if (lxc_conf
->is_execute
) {
3342 if (execveat_supported()) {
3344 char path
[PATH_MAX
];
3346 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3347 if (ret
< 0 || ret
>= PATH_MAX
)
3348 return log_error(-1, "Path to init.lxc.static too long");
3350 fd
= open(path
, O_PATH
| O_CLOEXEC
);
3352 return log_error_errno(-1, errno
, "Unable to open lxc.init.static");
3354 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3355 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3357 ret
= lxc_execute_bind_init(handler
);
3359 return log_error(-1, "Failed to bind-mount the lxc init system");
3363 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3364 * mounted. It is guaranteed to be mounted now either through
3365 * automatically or via fstab entries.
3367 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
);
3369 return log_error(-1, "Failed to setup remaining automatic mounts");
3371 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3373 return log_error(-1, "Failed to run mount hooks");
3375 if (lxc_conf
->autodev
> 0) {
3376 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3378 return log_error(-1, "Failed to run autodev hooks");
3380 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3382 return log_error(-1, "Failed to populate \"/dev\"");
3385 /* Make sure any start hooks are in the container */
3386 if (!verify_start_hooks(lxc_conf
))
3387 return log_error(-1, "Failed to verify start hooks");
3389 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3391 return log_error(-1, "Failed to \"/proc\" LSMs");
3393 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3394 lxc_conf
->ttys
.dir
, pty_mnt_fd
);
3396 return log_error(-1, "Failed to setup console");
3398 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3400 return log_error(-1, "Failed to setup \"/dev\" symlinks");
3402 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3404 return log_error(-1, "Failed to pivot root into rootfs");
3406 /* Setting the boot-id is best-effort for now. */
3407 if (lxc_conf
->autodev
> 0)
3408 (void)lxc_setup_boot_id();
3410 ret
= lxc_setup_devpts_child(handler
);
3412 return log_error(-1, "Failed to setup new devpts instance");
3414 ret
= lxc_create_ttys(handler
);
3418 ret
= setup_personality(lxc_conf
->personality
);
3420 return log_error(-1, "Failed to set personality");
3422 /* Set sysctl value to a path under /proc/sys as determined from the
3423 * key. For e.g. net.ipv4.ip_forward translated to
3424 * /proc/sys/net/ipv4/ip_forward.
3426 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3427 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3429 return log_error(-1, "Failed to setup sysctl parameters");
3432 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3433 if (!lxc_list_empty(&lxc_conf
->caps
))
3434 return log_error(-1, "Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both");
3436 if (dropcaps_except(&lxc_conf
->keepcaps
))
3437 return log_error(-1, "Failed to keep capabilities");
3438 } else if (setup_caps(&lxc_conf
->caps
)) {
3439 return log_error(-1, "Failed to drop capabilities");
3442 close_prot_errno_disarm(lxc_conf
->rootfs
.mntpt_fd
)
3443 close_prot_errno_disarm(lxc_conf
->rootfs
.dev_mntpt_fd
)
3444 NOTICE("The container \"%s\" is set up", name
);
3449 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3452 struct lxc_list
*it
;
3455 for (which
= 0; which
< NUM_LXC_HOOKS
; which
++) {
3456 if (strcmp(hookname
, lxchook_names
[which
]) == 0)
3460 if (which
>= NUM_LXC_HOOKS
)
3463 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3465 char *hook
= it
->elem
;
3467 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3476 int lxc_clear_config_caps(struct lxc_conf
*c
)
3478 struct lxc_list
*it
, *next
;
3480 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3489 static int lxc_free_idmap(struct lxc_list
*id_map
)
3491 struct lxc_list
*it
, *next
;
3493 lxc_list_for_each_safe(it
, id_map
, next
) {
3502 static int __lxc_free_idmap(struct lxc_list
*id_map
)
3504 lxc_free_idmap(id_map
);
3508 define_cleanup_function(struct lxc_list
*, __lxc_free_idmap
);
3510 int lxc_clear_idmaps(struct lxc_conf
*c
)
3512 return lxc_free_idmap(&c
->id_map
);
3515 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3517 struct lxc_list
*it
, *next
;
3519 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3528 int lxc_clear_namespace(struct lxc_conf
*c
)
3531 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
3532 free(c
->ns_share
[i
]);
3533 c
->ns_share
[i
] = NULL
;
3538 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3540 char *global_token
, *namespaced_token
;
3541 size_t namespaced_token_len
;
3542 struct lxc_list
*it
, *next
, *list
;
3543 const char *k
= key
;
3546 if (version
== CGROUP2_SUPER_MAGIC
) {
3547 global_token
= "lxc.cgroup2";
3548 namespaced_token
= "lxc.cgroup2.";
3549 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
3551 } else if (version
== CGROUP_SUPER_MAGIC
) {
3552 global_token
= "lxc.cgroup";
3553 namespaced_token
= "lxc.cgroup.";
3554 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
3560 if (strcmp(key
, global_token
) == 0)
3562 else if (strncmp(key
, namespaced_token
, namespaced_token_len
) == 0)
3563 k
+= namespaced_token_len
;
3567 lxc_list_for_each_safe (it
, list
, next
) {
3568 struct lxc_cgroup
*cg
= it
->elem
;
3570 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3574 free(cg
->subsystem
);
3583 static void lxc_clear_devices(struct lxc_conf
*conf
)
3585 struct lxc_list
*list
= &conf
->devices
;
3586 struct lxc_list
*it
, *next
;
3588 lxc_list_for_each_safe(it
, list
, next
) {
3594 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3596 struct lxc_list
*it
, *next
;
3597 const char *k
= NULL
;
3600 if (strcmp(key
, "lxc.limit") == 0 || strcmp(key
, "lxc.prlimit") == 0)
3602 else if (strncmp(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")) == 0)
3603 k
= key
+ STRLITERALLEN("lxc.limit.");
3604 else if (strncmp(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")) == 0)
3605 k
= key
+ STRLITERALLEN("lxc.prlimit.");
3609 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3610 struct lxc_limit
*lim
= it
->elem
;
3612 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3616 free(lim
->resource
);
3624 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3626 struct lxc_list
*it
, *next
;
3627 const char *k
= NULL
;
3630 if (strcmp(key
, "lxc.sysctl") == 0)
3632 else if (strncmp(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")) == 0)
3633 k
= key
+ STRLITERALLEN("lxc.sysctl.");
3637 lxc_list_for_each_safe (it
, &c
->sysctls
, next
) {
3638 struct lxc_sysctl
*elem
= it
->elem
;
3640 if (!all
&& strcmp(elem
->key
, k
) != 0)
3653 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3655 struct lxc_list
*it
, *next
;
3656 const char *k
= NULL
;
3659 if (strcmp(key
, "lxc.proc") == 0)
3661 else if (strncmp(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")) == 0)
3662 k
= key
+ STRLITERALLEN("lxc.proc.");
3666 lxc_list_for_each_safe (it
, &c
->procs
, next
) {
3667 struct lxc_proc
*proc
= it
->elem
;
3669 if (!all
&& strcmp(proc
->filename
, k
) != 0)
3673 free(proc
->filename
);
3682 int lxc_clear_groups(struct lxc_conf
*c
)
3684 struct lxc_list
*it
, *next
;
3686 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
3695 int lxc_clear_environment(struct lxc_conf
*c
)
3697 struct lxc_list
*it
, *next
;
3699 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
3708 int lxc_clear_mount_entries(struct lxc_conf
*c
)
3710 struct lxc_list
*it
, *next
;
3712 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
3721 int lxc_clear_automounts(struct lxc_conf
*c
)
3727 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
3730 struct lxc_list
*it
, *next
;
3731 const char *k
= NULL
;
3732 bool all
= false, done
= false;
3734 if (strcmp(key
, "lxc.hook") == 0)
3736 else if (strncmp(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")) == 0)
3737 k
= key
+ STRLITERALLEN("lxc.hook.");
3741 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
3742 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
3743 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
3754 return log_error(-1, "Invalid hook key: %s", key
);
3759 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
3761 struct lxc_list
*it
, *next
;
3763 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
3770 void lxc_clear_includes(struct lxc_conf
*conf
)
3772 struct lxc_list
*it
, *next
;
3774 lxc_list_for_each_safe (it
, &conf
->includes
, next
) {
3781 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
3783 struct lxc_list
*it
, *next
;
3785 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
3794 void lxc_conf_free(struct lxc_conf
*conf
)
3799 if (current_config
== conf
)
3800 current_config
= NULL
;
3801 lxc_terminal_conf_free(&conf
->console
);
3802 free(conf
->rootfs
.mount
);
3803 free(conf
->rootfs
.bdev_type
);
3804 free(conf
->rootfs
.options
);
3805 free(conf
->rootfs
.path
);
3806 free(conf
->rootfs
.data
);
3807 close_prot_errno_disarm(conf
->rootfs
.mntpt_fd
);
3808 close_prot_errno_disarm(conf
->rootfs
.dev_mntpt_fd
);
3809 free(conf
->logfile
);
3810 if (conf
->logfd
!= -1)
3812 free(conf
->utsname
);
3813 free(conf
->ttys
.dir
);
3814 free(conf
->ttys
.tty_names
);
3817 free(conf
->execute_cmd
);
3818 free(conf
->init_cmd
);
3819 free(conf
->init_cwd
);
3820 free(conf
->unexpanded_config
);
3822 lxc_free_networks(&conf
->network
);
3823 free(conf
->lsm_aa_profile
);
3824 free(conf
->lsm_aa_profile_computed
);
3825 free(conf
->lsm_se_context
);
3826 lxc_seccomp_free(&conf
->seccomp
);
3827 lxc_clear_config_caps(conf
);
3828 lxc_clear_config_keepcaps(conf
);
3829 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
3830 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
3831 lxc_clear_devices(conf
);
3832 lxc_clear_cgroup2_devices(conf
);
3833 lxc_clear_hooks(conf
, "lxc.hook");
3834 lxc_clear_mount_entries(conf
);
3835 lxc_clear_idmaps(conf
);
3836 lxc_clear_groups(conf
);
3837 lxc_clear_includes(conf
);
3838 lxc_clear_aliens(conf
);
3839 lxc_clear_environment(conf
);
3840 lxc_clear_limits(conf
, "lxc.prlimit");
3841 lxc_clear_sysctls(conf
, "lxc.sysctl");
3842 lxc_clear_procs(conf
, "lxc.proc");
3843 lxc_clear_apparmor_raw(conf
);
3844 lxc_clear_namespace(conf
);
3845 free(conf
->cgroup_meta
.dir
);
3846 free(conf
->cgroup_meta
.monitor_dir
);
3847 free(conf
->cgroup_meta
.monitor_pivot_dir
);
3848 free(conf
->cgroup_meta
.container_dir
);
3849 free(conf
->cgroup_meta
.namespace_dir
);
3850 free(conf
->cgroup_meta
.controllers
);
3851 free(conf
->shmount
.path_host
);
3852 free(conf
->shmount
.path_cont
);
3856 struct userns_fn_data
{
3858 const char *fn_name
;
3863 static int run_userns_fn(void *data
)
3865 struct userns_fn_data
*d
= data
;
3869 close_prot_errno_disarm(d
->p
[1]);
3872 * Wait for parent to finish establishing a new mapping in the user
3873 * namespace we are executing in.
3875 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
3876 close_prot_errno_disarm(d
->p
[0]);
3881 TRACE("Calling function \"%s\"", d
->fn_name
);
3883 /* Call function to run. */
3884 return d
->fn(d
->arg
);
3887 static struct id_map
*mapped_nsid_add(const struct lxc_conf
*conf
, unsigned id
,
3890 const struct id_map
*map
;
3891 struct id_map
*retmap
;
3893 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
3897 retmap
= malloc(sizeof(*retmap
));
3901 memcpy(retmap
, map
, sizeof(*retmap
));
3905 static struct id_map
*find_mapped_hostid_entry(const struct lxc_conf
*conf
,
3906 unsigned id
, enum idtype idtype
)
3909 struct lxc_list
*it
;
3910 struct id_map
*retmap
= NULL
;
3912 lxc_list_for_each (it
, &conf
->id_map
) {
3914 if (map
->idtype
!= idtype
)
3917 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
3926 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
3927 * existing one or establish a new one.
3929 static struct id_map
*mapped_hostid_add(const struct lxc_conf
*conf
, uid_t id
,
3932 __do_free
struct id_map
*entry
= NULL
;
3934 struct id_map
*tmp
= NULL
;
3936 entry
= malloc(sizeof(*entry
));
3940 /* Reuse existing mapping. */
3941 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
3943 memcpy(entry
, tmp
, sizeof(*entry
));
3945 /* Find new mapping. */
3946 hostid_mapped
= find_unmapped_nsid(conf
, type
);
3947 if (hostid_mapped
< 0)
3948 return log_debug(NULL
, "Failed to find free mapping for id %d", id
);
3950 entry
->idtype
= type
;
3951 entry
->nsid
= hostid_mapped
;
3952 entry
->hostid
= (unsigned long)id
;
3956 return move_ptr(entry
);
3959 static struct lxc_list
*get_minimal_idmap(const struct lxc_conf
*conf
,
3960 uid_t
*resuid
, gid_t
*resgid
)
3962 __do_free
struct id_map
*container_root_uid
= NULL
,
3963 *container_root_gid
= NULL
,
3964 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
3965 __do_free
struct lxc_list
*idmap
= NULL
;
3967 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3968 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3969 struct lxc_list
*tmplist
= NULL
;
3971 /* Find container root mappings. */
3972 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
3973 if (!container_root_uid
)
3974 return log_debug(NULL
, "Failed to find mapping for namespace uid %d", 0);
3976 if (euid
>= container_root_uid
->hostid
&&
3977 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
3978 host_uid_map
= move_ptr(container_root_uid
);
3980 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
3981 if (!container_root_gid
)
3982 return log_debug(NULL
, "Failed to find mapping for namespace gid %d", 0);
3984 if (egid
>= container_root_gid
->hostid
&&
3985 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
3986 host_gid_map
= move_ptr(container_root_gid
);
3988 /* Check whether the {g,u}id of the user has a mapping. */
3990 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
3992 return log_debug(NULL
, "Failed to find mapping for uid %d", euid
);
3995 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
3997 return log_debug(NULL
, "Failed to find mapping for gid %d", egid
);
3999 /* Allocate new {g,u}id map list. */
4000 idmap
= malloc(sizeof(*idmap
));
4003 lxc_list_init(idmap
);
4005 /* Add container root to the map. */
4006 tmplist
= malloc(sizeof(*tmplist
));
4009 /* idmap will now keep track of that memory. */
4010 lxc_list_add_elem(tmplist
, move_ptr(host_uid_map
));
4011 lxc_list_add_tail(idmap
, tmplist
);
4013 if (container_root_uid
) {
4014 /* Add container root to the map. */
4015 tmplist
= malloc(sizeof(*tmplist
));
4018 /* idmap will now keep track of that memory. */
4019 lxc_list_add_elem(tmplist
, move_ptr(container_root_uid
));
4020 lxc_list_add_tail(idmap
, tmplist
);
4023 tmplist
= malloc(sizeof(*tmplist
));
4026 /* idmap will now keep track of that memory. */
4027 lxc_list_add_elem(tmplist
, move_ptr(host_gid_map
));
4028 lxc_list_add_tail(idmap
, tmplist
);
4030 if (container_root_gid
) {
4031 tmplist
= malloc(sizeof(*tmplist
));
4034 /* idmap will now keep track of that memory. */
4035 lxc_list_add_elem(tmplist
, move_ptr(container_root_gid
));
4036 lxc_list_add_tail(idmap
, tmplist
);
4039 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid
, nsgid
);
4045 return move_ptr(idmap
);
4049 * Run a function in a new user namespace.
4050 * The caller's euid/egid will be mapped if it is not already.
4051 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4052 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4053 * This means we require only to establish a mapping from:
4054 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4055 * - the container root -> some sub{g,u}id
4056 * The former we add, if the user did not specify a mapping. The latter we
4057 * retrieve from the container's configured {g,u}id mappings as it must have been
4058 * there to start the container in the first place.
4060 int userns_exec_1(const struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4061 const char *fn_name
)
4063 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
4064 int ret
= -1, status
= -1;
4066 struct userns_fn_data d
= {
4077 idmap
= get_minimal_idmap(conf
, NULL
, NULL
);
4079 return ret_errno(ENOENT
);
4081 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
4085 d
.p
[0] = pipe_fds
[0];
4086 d
.p
[1] = pipe_fds
[1];
4088 /* Clone child in new user namespace. */
4089 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
4091 ERROR("Failed to clone process in new user namespace");
4095 close_prot_errno_disarm(pipe_fds
[0]);
4097 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4098 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4100 struct lxc_list
*it
;
4102 lxc_list_for_each(it
, idmap
) {
4104 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
4105 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
4109 /* Set up {g,u}id mapping for user namespace of child process. */
4110 ret
= lxc_map_ids(idmap
, pid
);
4112 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4116 /* Tell child to proceed. */
4117 if (lxc_write_nointr(pipe_fds
[1], &c
, 1) != 1) {
4118 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4123 close_prot_errno_disarm(pipe_fds
[0]);
4124 close_prot_errno_disarm(pipe_fds
[1]);
4126 /* Wait for child to finish. */
4128 status
= wait_for_pid(pid
);
4136 int userns_exec_minimal(const struct lxc_conf
*conf
,
4137 int (*fn_parent
)(void *), void *fn_parent_data
,
4138 int (*fn_child
)(void *), void *fn_child_data
)
4140 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
4141 uid_t resuid
= LXC_INVALID_UID
;
4142 gid_t resgid
= LXC_INVALID_GID
;
4148 if (!conf
|| !fn_child
)
4149 return ret_errno(EINVAL
);
4151 idmap
= get_minimal_idmap(conf
, &resuid
, &resgid
);
4153 return ret_errno(ENOENT
);
4155 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
4161 SYSERROR("Failed to create new process");
4166 close_prot_errno_disarm(sock_fds
[1]);
4168 ret
= unshare(CLONE_NEWUSER
);
4170 SYSERROR("Failed to unshare new user namespace");
4171 _exit(EXIT_FAILURE
);
4174 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
4176 _exit(EXIT_FAILURE
);
4178 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
4180 _exit(EXIT_FAILURE
);
4182 close_prot_errno_disarm(sock_fds
[0]);
4184 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
4185 _exit(EXIT_FAILURE
);
4187 ret
= setresgid(resgid
, resgid
, resgid
);
4189 SYSERROR("Failed to setresgid(%d, %d, %d)",
4190 resgid
, resgid
, resgid
);
4191 _exit(EXIT_FAILURE
);
4194 ret
= setresuid(resuid
, resuid
, resuid
);
4196 SYSERROR("Failed to setresuid(%d, %d, %d)",
4197 resuid
, resuid
, resuid
);
4198 _exit(EXIT_FAILURE
);
4201 ret
= fn_child(fn_child_data
);
4203 SYSERROR("Running function in new user namespace failed");
4204 _exit(EXIT_FAILURE
);
4207 _exit(EXIT_SUCCESS
);
4210 close_prot_errno_disarm(sock_fds
[0]);
4212 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4213 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4215 struct lxc_list
*it
;
4217 lxc_list_for_each(it
, idmap
) {
4219 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
4220 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
4224 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
4226 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
4230 /* Set up {g,u}id mapping for user namespace of child process. */
4231 ret
= lxc_map_ids(idmap
, pid
);
4233 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4237 /* Tell child to proceed. */
4238 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
4240 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4244 if (fn_parent
&& fn_parent(fn_parent_data
)) {
4245 SYSERROR("Running parent function failed");
4246 _exit(EXIT_FAILURE
);
4250 close_prot_errno_disarm(sock_fds
[0]);
4251 close_prot_errno_disarm(sock_fds
[1]);
4253 /* Wait for child to finish. */
4257 return wait_for_pid(pid
);
4260 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4261 const char *fn_name
)
4267 struct lxc_list
*cur
;
4268 struct userns_fn_data d
;
4271 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4272 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4273 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4278 ret
= pipe2(p
, O_CLOEXEC
);
4280 SYSERROR("opening pipe");
4284 d
.fn_name
= fn_name
;
4289 /* Clone child in new user namespace. */
4290 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
4292 ERROR("Failed to clone process in new user namespace");
4302 /* Allocate new {g,u}id map list. */
4303 idmap
= malloc(sizeof(*idmap
));
4306 lxc_list_init(idmap
);
4308 /* Find container root. */
4309 lxc_list_for_each (cur
, &conf
->id_map
) {
4310 struct id_map
*tmpmap
;
4312 tmplist
= malloc(sizeof(*tmplist
));
4316 tmpmap
= malloc(sizeof(*tmpmap
));
4322 memset(tmpmap
, 0, sizeof(*tmpmap
));
4323 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4324 tmplist
->elem
= tmpmap
;
4326 lxc_list_add_tail(idmap
, tmplist
);
4330 if (map
->idtype
== ID_TYPE_UID
)
4331 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4334 if (map
->idtype
== ID_TYPE_GID
)
4335 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4341 if (map
->idtype
== ID_TYPE_UID
)
4342 if (container_root_uid
== NULL
)
4343 container_root_uid
= map
;
4345 if (map
->idtype
== ID_TYPE_GID
)
4346 if (container_root_gid
== NULL
)
4347 container_root_gid
= map
;
4350 if (!container_root_uid
|| !container_root_gid
) {
4351 ERROR("No mapping for container root found");
4355 /* Check whether the {g,u}id of the user has a mapping. */
4357 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4359 host_uid_map
= container_root_uid
;
4362 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4364 host_gid_map
= container_root_gid
;
4366 if (!host_uid_map
) {
4367 DEBUG("Failed to find mapping for uid %d", euid
);
4371 if (!host_gid_map
) {
4372 DEBUG("Failed to find mapping for gid %d", egid
);
4376 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4377 /* Add container root to the map. */
4378 tmplist
= malloc(sizeof(*tmplist
));
4381 lxc_list_add_elem(tmplist
, host_uid_map
);
4382 lxc_list_add_tail(idmap
, tmplist
);
4384 /* idmap will now keep track of that memory. */
4385 host_uid_map
= NULL
;
4387 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4388 tmplist
= malloc(sizeof(*tmplist
));
4391 lxc_list_add_elem(tmplist
, host_gid_map
);
4392 lxc_list_add_tail(idmap
, tmplist
);
4394 /* idmap will now keep track of that memory. */
4395 host_gid_map
= NULL
;
4397 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4398 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4399 lxc_list_for_each (cur
, idmap
) {
4401 TRACE("establishing %cid mapping for \"%d\" in new "
4402 "user namespace: nsuid %lu - hostid %lu - range "
4404 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4405 map
->nsid
, map
->hostid
, map
->range
);
4409 /* Set up {g,u}id mapping for user namespace of child process. */
4410 ret
= lxc_map_ids(idmap
, pid
);
4412 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4416 /* Tell child to proceed. */
4417 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4418 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4427 /* Wait for child to finish. */
4429 ret
= wait_for_pid(pid
);
4432 __lxc_free_idmap(idmap
);
4434 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4436 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4442 static int add_idmap_entry(struct lxc_list
*idmap
, enum idtype idtype
,
4443 unsigned long nsid
, unsigned long hostid
,
4444 unsigned long range
)
4446 __do_free
struct id_map
*new_idmap
= NULL
;
4447 __do_free
struct lxc_list
*new_list
= NULL
;
4449 new_idmap
= zalloc(sizeof(*new_idmap
));
4451 return ret_errno(ENOMEM
);
4453 new_idmap
->idtype
= idtype
;
4454 new_idmap
->hostid
= hostid
;
4455 new_idmap
->nsid
= nsid
;
4456 new_idmap
->range
= range
;
4458 new_list
= zalloc(sizeof(*new_list
));
4460 return ret_errno(ENOMEM
);
4462 new_list
->elem
= move_ptr(new_idmap
);
4463 lxc_list_add_tail(idmap
, move_ptr(new_list
));
4465 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
4466 idtype
== ID_TYPE_UID
? 'u' : 'g', nsid
, hostid
, range
);
4470 int userns_exec_mapped_root(const char *path
, int path_fd
,
4471 const struct lxc_conf
*conf
)
4473 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
4474 __do_close
int fd
= -EBADF
;
4475 int target_fd
= -EBADF
;
4480 uid_t container_host_uid
, hostuid
;
4481 gid_t container_host_gid
, hostgid
;
4484 if (!conf
|| (!path
&& path_fd
< 0))
4485 return ret_errno(EINVAL
);
4490 container_host_uid
= get_mapped_rootid(conf
, ID_TYPE_UID
);
4491 if (!uid_valid(container_host_uid
))
4492 return log_error(-1, "No uid mapping for container root");
4494 container_host_gid
= get_mapped_rootid(conf
, ID_TYPE_GID
);
4495 if (!gid_valid(container_host_gid
))
4496 return log_error(-1, "No gid mapping for container root");
4499 fd
= open(path
, O_CLOEXEC
| O_NOCTTY
);
4501 return log_error_errno(-errno
, errno
, "Failed to open \"%s\"", path
);
4504 target_fd
= path_fd
;
4507 hostuid
= geteuid();
4508 /* We are root so chown directly. */
4510 ret
= fchown(target_fd
, container_host_uid
, container_host_gid
);
4512 return log_error_errno(-errno
, errno
,
4513 "Failed to fchown(%d(%s), %d, %d)",
4514 target_fd
, path
, container_host_uid
,
4515 container_host_gid
);
4516 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd
, path
,
4517 container_host_uid
, container_host_gid
);
4520 /* The container's root host id matches */
4521 if (container_host_uid
== hostuid
)
4522 return log_info(0, "Container root id is mapped to our uid");
4524 /* Get the current ids of our target. */
4525 ret
= fstat(target_fd
, &st
);
4527 return log_error_errno(-errno
, errno
, "Failed to stat \"%s\"", path
);
4529 hostgid
= getegid();
4530 if (st
.st_uid
== hostuid
&& mapped_hostid(st
.st_gid
, conf
, ID_TYPE_GID
) < 0) {
4531 ret
= fchown(target_fd
, -1, hostgid
);
4533 return log_error_errno(-errno
, errno
,
4534 "Failed to fchown(%d(%s), -1, %d)",
4535 target_fd
, path
, hostgid
);
4536 TRACE("Chowned %d(%s) to -1:%d", target_fd
, path
, hostgid
);
4539 idmap
= malloc(sizeof(*idmap
));
4542 lxc_list_init(idmap
);
4544 /* "u:0:rootuid:1" */
4545 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, 0, container_host_uid
, 1);
4547 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4549 /* "u:hostuid:hostuid:1" */
4550 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, hostuid
, hostuid
, 1);
4552 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4554 /* "g:0:rootgid:1" */
4555 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, 0, container_host_gid
, 1);
4557 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4559 /* "g:hostgid:hostgid:1" */
4560 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, hostgid
, hostgid
, 1);
4562 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4564 if (hostgid
!= st
.st_gid
) {
4565 /* "g:pathgid:rootgid+pathgid:1" */
4566 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, st
.st_gid
,
4567 container_host_gid
+ (gid_t
)st
.st_gid
, 1);
4569 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4572 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
4578 SYSERROR("Failed to create new process");
4583 close_prot_errno_disarm(sock_fds
[1]);
4585 ret
= unshare(CLONE_NEWUSER
);
4587 SYSERROR("Failed to unshare new user namespace");
4588 _exit(EXIT_FAILURE
);
4591 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
4593 _exit(EXIT_FAILURE
);
4595 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
4597 _exit(EXIT_FAILURE
);
4599 close_prot_errno_disarm(sock_fds
[0]);
4601 if (!lxc_switch_uid_gid(0, 0))
4602 _exit(EXIT_FAILURE
);
4604 if (!lxc_setgroups(0, NULL
))
4605 _exit(EXIT_FAILURE
);
4607 ret
= fchown(target_fd
, 0, st
.st_gid
);
4609 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
4610 _exit(EXIT_FAILURE
);
4613 TRACE("Chowned %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
4614 _exit(EXIT_SUCCESS
);
4617 close_prot_errno_disarm(sock_fds
[0]);
4619 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4620 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4622 struct lxc_list
*it
;
4624 lxc_list_for_each(it
, idmap
) {
4626 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
4627 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
4631 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
4633 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
4637 /* Set up {g,u}id mapping for user namespace of child process. */
4638 ret
= lxc_map_ids(idmap
, pid
);
4640 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4644 /* Tell child to proceed. */
4645 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
4647 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4652 close_prot_errno_disarm(sock_fds
[0]);
4653 close_prot_errno_disarm(sock_fds
[1]);
4655 /* Wait for child to finish. */
4659 return wait_for_pid(pid
);
4662 /* not thread-safe, do not use from api without first forking */
4663 static char *getuname(void)
4665 __do_free
char *buf
= NULL
;
4666 struct passwd pwent
;
4667 struct passwd
*pwentp
= NULL
;
4671 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
4675 buf
= malloc(bufsize
);
4679 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
4682 WARN("Could not find matched password record.");
4684 return log_error(NULL
, "Failed to get password record - %u", geteuid());
4687 return strdup(pwent
.pw_name
);
4690 /* not thread-safe, do not use from api without first forking */
4691 static char *getgname(void)
4693 __do_free
char *buf
= NULL
;
4695 struct group
*grentp
= NULL
;
4699 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
4703 buf
= malloc(bufsize
);
4707 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
4710 WARN("Could not find matched group record");
4712 return log_error(NULL
, "Failed to get group record - %u", getegid());
4715 return strdup(grent
.gr_name
);
4718 /* not thread-safe, do not use from api without first forking */
4719 void suggest_default_idmap(void)
4721 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
4722 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
4723 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4734 subuid_f
= fopen(subuidfile
, "re");
4736 ERROR("Your system is not configured with subuids");
4740 while (getline(&line
, &len
, subuid_f
) != -1) {
4742 size_t no_newline
= 0;
4744 p
= strchr(line
, ':');
4752 if (strcmp(line
, uname
))
4755 p2
= strchr(p
, ':');
4762 no_newline
= strcspn(p2
, "\n");
4763 p2
[no_newline
] = '\0';
4765 if (lxc_safe_uint(p
, &uid
) < 0)
4766 WARN("Could not parse UID");
4767 if (lxc_safe_uint(p2
, &urange
) < 0)
4768 WARN("Could not parse UID range");
4771 subgid_f
= fopen(subgidfile
, "re");
4773 ERROR("Your system is not configured with subgids");
4777 while (getline(&line
, &len
, subgid_f
) != -1) {
4779 size_t no_newline
= 0;
4781 p
= strchr(line
, ':');
4789 if (strcmp(line
, uname
))
4792 p2
= strchr(p
, ':');
4799 no_newline
= strcspn(p2
, "\n");
4800 p2
[no_newline
] = '\0';
4802 if (lxc_safe_uint(p
, &gid
) < 0)
4803 WARN("Could not parse GID");
4804 if (lxc_safe_uint(p2
, &grange
) < 0)
4805 WARN("Could not parse GID range");
4808 if (!urange
|| !grange
) {
4809 ERROR("You do not have subuids or subgids allocated");
4810 ERROR("Unprivileged containers require subuids and subgids");
4814 ERROR("You must either run as root, or define uid mappings");
4815 ERROR("To pass uid mappings to lxc-create, you could create");
4816 ERROR("~/.config/lxc/default.conf:");
4817 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4818 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4819 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4822 static void free_cgroup_settings(struct lxc_list
*result
)
4824 struct lxc_list
*iterator
, *next
;
4826 lxc_list_for_each_safe (iterator
, result
, next
) {
4827 lxc_list_del(iterator
);
4828 free_disarm(iterator
);
4830 free_disarm(result
);
4833 /* Return the list of cgroup_settings sorted according to the following rules
4834 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4836 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
4838 struct lxc_list
*result
;
4839 struct lxc_cgroup
*cg
= NULL
;
4840 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
4842 result
= malloc(sizeof(*result
));
4845 lxc_list_init(result
);
4847 /* Iterate over the cgroup settings and copy them to the output list. */
4848 lxc_list_for_each (it
, cgroup_settings
) {
4849 item
= malloc(sizeof(*item
));
4851 free_cgroup_settings(result
);
4855 item
->elem
= it
->elem
;
4857 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4858 /* Store the memsw_limit location */
4860 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 &&
4861 memsw_limit
!= NULL
) {
4862 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4863 * before lxc.cgroup.memory.limit_in_bytes, swap these
4865 item
->elem
= memsw_limit
->elem
;
4866 memsw_limit
->elem
= it
->elem
;
4868 lxc_list_add_tail(result
, item
);