]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/csrand.c: csrand(): Use read(2) instead of fread(2)
authorAlejandro Colomar <alx@kernel.org>
Tue, 12 Nov 2024 14:19:19 +0000 (15:19 +0100)
committerSerge Hallyn <serge@hallyn.com>
Mon, 2 Dec 2024 03:43:25 +0000 (21:43 -0600)
We don't need the heavy stdio for getting a few bytes from
</dev/urandom>.  Let's use the simpler POSIX API.

Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/csrand.c

index 8ded343a596d51d55ac85806aec1ea54ed4a5f38..1914a30368e5c8b90c5413298950bbcec535db39 100644 (file)
@@ -1,21 +1,19 @@
-/*
- * SPDX-FileCopyrightText:  Alejandro Colomar <alx@kernel.org>
- *
- * SPDX-License-Identifier:  BSD-3-Clause
- */
+// SPDX-FileCopyrightText: 2022-2024, Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: BSD-3-Clause
 
 #include <config.h>
 
 #ident "$Id$"
 
+#include <fcntl.h>
 #include <limits.h>
 #include <stdint.h>
-#include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 #if HAVE_SYS_RANDOM_H
 #include <sys/random.h>
 #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 (fread(&r, sizeof(r), 1, fp) != 1) {
-               fclose(fp);
+       if (read(fd, &r, sizeof(r)) != sizeof(r)) {
+               close(fd);
                goto fail;
        }
 
-       fclose(fp);
+       close(fd);
        return r;
 
 fail: