| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include <linux/magic.h> |
| 4 |
#include <sys/vfs.h> |
| 5 |
|
| 6 |
#include "binfmt-util.h" |
| 7 |
#include "errno-util.h" |
| 8 |
#include "fd-util.h" |
| 9 |
#include "fileio.h" |
| 10 |
#include "fs-util.h" |
| 11 |
#include "log.h" |
| 12 |
#include "stat-util.h" |
| 13 |
|
| 14 |
int binfmt_mounted_and_writable(void) { |
| 15 |
_cleanup_close_ int fd = -EBADF; |
| 16 |
int r; |
| 17 |
|
| 18 |
fd = RET_NERRNO(open("/proc/sys/fs/binfmt_misc", O_CLOEXEC | O_DIRECTORY | O_PATH)); |
| 19 |
if (fd == -ENOENT) |
| 20 |
return false; |
| 21 |
/* ELOOP happens when binfmt_misc is an automount point under a read-only bind mount of /proc — |
| 22 |
* the kernel cannot trigger the automount and returns ELOOP instead. Common in mock/Koji buildroots. */ |
| 23 |
if (fd == -ELOOP || ERRNO_IS_NEG_PRIVILEGE(fd)) { |
| 24 |
log_debug_errno(fd, "Failed to open /proc/sys/fs/binfmt_misc, ignoring: %m"); |
| 25 |
return false; |
| 26 |
} |
| 27 |
if (fd < 0) |
| 28 |
return fd; |
| 29 |
|
| 30 |
r = fd_is_fs_type(fd, BINFMTFS_MAGIC); |
| 31 |
if (r <= 0) |
| 32 |
return r; |
| 33 |
|
| 34 |
r = access_fd(fd, W_OK); |
| 35 |
if (ERRNO_IS_NEG_FS_WRITE_REFUSED(r)) |
| 36 |
return false; |
| 37 |
if (r < 0) |
| 38 |
return r; |
| 39 |
|
| 40 |
return true; |
| 41 |
} |
| 42 |
|
| 43 |
int disable_binfmt(void) { |
| 44 |
int r; |
| 45 |
|
| 46 |
/* Flush out all rules. This is important during shutdown to cover for rules using "F", since those |
| 47 |
* might pin a file and thus block us from unmounting stuff cleanly. |
| 48 |
* |
| 49 |
* We are a bit careful here, since binfmt_misc might still be an autofs which we don't want to |
| 50 |
* trigger. */ |
| 51 |
|
| 52 |
r = binfmt_mounted_and_writable(); |
| 53 |
if (r < 0) |
| 54 |
return log_warning_errno(r, "Failed to determine whether binfmt_misc is mounted: %m"); |
| 55 |
if (r == 0) { |
| 56 |
log_debug("binfmt_misc is not mounted in read-write mode, not detaching entries."); |
| 57 |
return 0; |
| 58 |
} |
| 59 |
|
| 60 |
r = write_string_file("/proc/sys/fs/binfmt_misc/status", "-1", WRITE_STRING_FILE_DISABLE_BUFFER); |
| 61 |
if (r < 0) |
| 62 |
return log_warning_errno(r, "Failed to unregister binfmt_misc entries: %m"); |
| 63 |
|
| 64 |
log_debug("Unregistered all remaining binfmt_misc entries."); |
| 65 |
return 0; |
| 66 |
} |