diff options
author | Lennart Poettering <lennart@poettering.net> | 2014-10-30 21:34:49 -0400 |
---|---|---|
committer | Anthony G. Basile <blueness@gentoo.org> | 2014-10-30 21:34:49 -0400 |
commit | c306f4eab68ed5c084f993499a323cc98b480574 (patch) | |
tree | 05501c837d67d81a36fa157ee67f029b1f0e684d /src/shared | |
parent | 25268b958a8d5cd703b2cd442004cbbee96043e0 (diff) |
util: unify how we see srand()
Signed-off-by: Anthony G. Basile <blueness@gentoo.org>
Diffstat (limited to 'src/shared')
-rw-r--r-- | src/shared/util.c | 53 | ||||
-rw-r--r-- | src/shared/util.h | 1 |
2 files changed, 31 insertions, 23 deletions
diff --git a/src/shared/util.c b/src/shared/util.c index 3cad297873..e953363483 100644 --- a/src/shared/util.c +++ b/src/shared/util.c @@ -701,8 +701,36 @@ int dev_urandom(void *p, size_t n) { return 0; } -void random_bytes(void *p, size_t n) { +void initialize_srand(void) { static bool srand_called = false; + unsigned x; +#ifdef HAVE_SYS_AUXV_H + void *auxv; +#endif + + if (srand_called) + return; + + x = 0; + +#ifdef HAVE_SYS_AUXV_H + /* The kernel provides us with a bit of entropy in auxv, so + * let's try to make use of that to seed the pseudo-random + * generator. It's better than nothing... */ + + auxv = (void*) getauxval(AT_RANDOM); + if (auxv) + x ^= *(unsigned*) auxv; +#endif + + x ^= (unsigned) now(CLOCK_REALTIME); + x ^= (unsigned) gettid(); + + srand(x); + srand_called = true; +} + +void random_bytes(void *p, size_t n) { uint8_t *q; int r; @@ -713,28 +741,7 @@ void random_bytes(void *p, size_t n) { /* If some idiot made /dev/urandom unavailable to us, he'll * get a PRNG instead. */ - if (!srand_called) { - unsigned x = 0; - -#ifdef HAVE_SYS_AUXV_H - /* The kernel provides us with a bit of entropy in - * auxv, so let's try to make use of that to seed the - * pseudo-random generator. It's better than - * nothing... */ - - void *auxv; - - auxv = (void*) getauxval(AT_RANDOM); - if (auxv) - x ^= *(unsigned*) auxv; -#endif - - x ^= (unsigned) now(CLOCK_REALTIME); - x ^= (unsigned) gettid(); - - srand(x); - srand_called = true; - } + initialize_srand(); for (q = p; q < (uint8_t*) p + n; q ++) *q = rand(); diff --git a/src/shared/util.h b/src/shared/util.h index 9550aa19f9..f57a73cec6 100644 --- a/src/shared/util.h +++ b/src/shared/util.h @@ -192,6 +192,7 @@ bool ignore_file(const char *filename) _pure_; int dev_urandom(void *p, size_t n); void random_bytes(void *p, size_t n); +void initialize_srand(void); /* For basic lookup tables with strictly enumerated entries */ #define __DEFINE_STRING_TABLE_LOOKUP(name,type,scope) \ |