From 5f6ccd5200b66235f82f76dae42abe731acf9ba3 Mon Sep 17 00:00:00 2001 From: Steven Seungcheol Lee Date: Mon, 22 Nov 2021 17:34:58 +0900 Subject: [PATCH] nvme: fix fatal error for sys/random.h fatal error: sys/random.h: No such file or directory sys/random.h supported from glibc version 2.25 so add header file existence check if there is no sys/random.h, try to read /dev/urandom or /dev/random Signed-off-by: Steven Seungcheol Lee [dwagner: cache errno value, close will overwrite it] Signed-off-by: Daniel Wagner --- ccan/tools/configurator/configurator.c | 3 +++ meson.build | 8 +++++++ nvme.c | 31 ++++++++++++++++++++++---- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/ccan/tools/configurator/configurator.c b/ccan/tools/configurator/configurator.c index 9487e694..0518c9b5 100644 --- a/ccan/tools/configurator/configurator.c +++ b/ccan/tools/configurator/configurator.c @@ -498,6 +498,9 @@ static const struct test base_tests[] = { " return __builtin_cpu_supports(\"mmx\");\n" "}" }, + { "HAVE_SYS_RANDOM", "", + "OUTSIDE_MAIN", NULL, NULL, + "#include \n" }, }; static void c12r_err(int eval, const char *fmt, ...) diff --git a/meson.build b/meson.build index 8efc8525..c81efe01 100644 --- a/meson.build +++ b/meson.build @@ -123,6 +123,14 @@ conf.set10( ), description: 'Is isblank() available?' ) +conf.set10( + 'HAVE_SYS_RANDOM', + cc.compiles( + '''#include ''', + name: 'sys/random.h' + ), + description: 'Is sys/random.h(getrandom) include-able?' +) configure_file( output: 'config.h', diff --git a/nvme.c b/nvme.c index 6ebfa928..09cb2fd8 100644 --- a/nvme.c +++ b/nvme.c @@ -23,7 +23,7 @@ /** * This program uses NVMe IOCTLs to run native nvme commands to a device. */ - +#include "config.h" #include "nvme/tree.h" #include "nvme/types.h" #include @@ -55,7 +55,10 @@ #include #include #include -#include + +#if HAVE_SYS_RANDOM + #include +#endif #include "common.h" #include "nvme.h" @@ -159,6 +162,26 @@ void *nvme_alloc(size_t len, bool *huge) } #endif +static ssize_t getrandom_bytes(void *buf, size_t buflen) +{ +#if !HAVE_SYS_RANDOM + return getrandom(buf, buflen, GRND_NONBLOCK); +#else + ssize_t result; + int fd, err = 0; + + fd = open("/dev/urandom", O_RDONLY); + if (fd < 0) + return fd; + result = read(fd, buf, buflen); + if (result < 0) + err = errno; + close(fd); + errno = err; + return result; +#endif +} + static bool is_chardev(void) { return S_ISCHR(nvme_stat.st_mode); @@ -6757,8 +6780,8 @@ static int gen_dhchap_key(int argc, char **argv, struct command *command, struct if (!raw_secret) return -ENOMEM; if (!cfg.secret) { - if (getrandom(raw_secret, cfg.key_len, GRND_NONBLOCK) < 0) - return errno; + if (getrandom_bytes(raw_secret, cfg.key_len) < 0) + return -errno; } else { int secret_len = 0, i; unsigned int c; -- 2.50.1