From 1d6456542cca0025d37bc46bf12f482c53dde9a7 Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Tue, 12 Nov 2024 15:19:19 +0100 Subject: [PATCH] lib/csrand.c: csrand(): Use read(2) instead of fread(2) We don't need the heavy stdio for getting a few bytes from . Let's use the simpler POSIX API. Signed-off-by: Alejandro Colomar --- lib/csrand.c | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/lib/csrand.c b/lib/csrand.c index 8ded343a..1914a303 100644 --- a/lib/csrand.c +++ b/lib/csrand.c @@ -1,21 +1,19 @@ -/* - * SPDX-FileCopyrightText: Alejandro Colomar - * - * SPDX-License-Identifier: BSD-3-Clause - */ +// SPDX-FileCopyrightText: 2022-2024, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause #include #ident "$Id$" +#include #include #include -#include #include #include #if HAVE_SYS_RANDOM_H #include #endif + #include "bit.h" #include "defines.h" #include "prototypes.h" @@ -34,7 +32,7 @@ static unsigned long csrand_uniform_slow(unsigned long n); unsigned long csrand(void) { - FILE *fp; + int fd; unsigned long r; #ifdef HAVE_GETENTROPY @@ -56,17 +54,16 @@ csrand(void) #endif /* Use /dev/urandom as a last resort. */ - fp = fopen("/dev/urandom", "r"); - if (NULL == fp) { + fd = open("/dev/urandom", O_RDONLY); + if (fd == -1) + goto fail; + + if (read(fd, &r, sizeof(r)) != sizeof(r)) { + close(fd); goto fail; } - if (fread(&r, sizeof(r), 1, fp) != 1) { - fclose(fp); - goto fail; - } - - fclose(fp); + close(fd); return r; fail: