Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

csrand(): Use POSIX read(2) instead of the heavier stdio #1119

Merged
merged 1 commit into from
Dec 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 10 additions & 13 deletions lib/csrand.c
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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
Expand All @@ -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:
Expand Down
Loading