1 From 450dfb09ee72ffedea8f2a25fdce17295f01f62f Mon Sep 17 00:00:00 2001
2 From: Stephan Mueller <smueller@chronox.de>
3 Date: Tue, 8 Aug 2017 10:04:06 +0200
4 Subject: [PATCH] Unify code to read from seed sources
6 Remove the code duplication for FD reads and syscall reads.
8 This patch also fixes the use of __NR_getrandom resolution.
10 [Upstream commit: https://github.com/smuellerDD/libkcapi/commit/450dfb09ee72ffedea8f2a25fdce17295f01f62f]
11 Signed-off-by: Marcin Nowakowski <marcin.nowakowski@imgtec.com>
14 apps/kcapi-rng.c | 71 +++++++++++++++++++++++++-------------------------------
15 1 file changed, 32 insertions(+), 39 deletions(-)
17 diff --git a/apps/kcapi-rng.c b/apps/kcapi-rng.c
18 index e15edf9..96da111 100644
19 --- a/apps/kcapi-rng.c
20 +++ b/apps/kcapi-rng.c
27 +#include <sys/syscall.h>
32 /* Minimum seed is 256 bits. */
33 #define KCAPI_RNG_MINSEEDSIZE 32
35 -struct kcapi_handle *rng = NULL;
36 -unsigned int Verbosity = 0;
37 -char *rng_name = NULL;
38 +static struct kcapi_handle *rng = NULL;
39 +static unsigned int Verbosity = 0;
40 +static char *rng_name = NULL;
42 -#ifndef HAVE_GETRANDOM
43 -static int read_complete(int fd, uint8_t *buf, uint32_t buflen)
44 +#if !defined(HAVE_GETRANDOM) && !defined(__NR_getrandom)
45 +static int random_fd = -1;
46 +static int open_random(void)
49 + random_fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
54 - ret = read(fd, buf, buflen);
59 - } while ((0 < ret || EINTR == errno || ERESTART == errno)
68 -static int read_random(uint8_t *buf, uint32_t buflen)
69 +static void close_random(void)
74 - fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
78 - ret = read_complete(fd, buf, buflen);
85 static int get_random(uint8_t *buf, uint32_t buflen)
92 +#if (!defined(HAVE_GETRANDOM) && !defined(__NR_getrandom))
93 + ret = open_random();
100 - return getrandom(buf, buflen, 0);
101 + ret = getrandom(buf, buflen, 0);
102 +#elif defined __NR_getrandom
103 + ret = syscall(__NR_getrandom, buf, buflen, 0);
105 -# ifdef __NR_getrandom
107 - int ret = syscall(__NR_getrandom, buf, buflen, 0);
109 + ret = read(random_fd, buf, buflen);
114 @@ -98,14 +92,13 @@ static int get_random(uint8_t *buf, uint32_t buflen)
115 } while ((0 < ret || EINTR == errno || ERESTART == errno)
118 +#if (!defined(HAVE_GETRANDOM) && !defined(__NR_getrandom))
127 - return read_random(buf, buflen);
132 static void usage(void)