util: unify how we see srand()

This commit is contained in:
Lennart Poettering 2014-10-30 15:35:37 +01:00
parent 97768fc574
commit ef309a681f
5 changed files with 34 additions and 26 deletions

View file

@ -480,7 +480,7 @@ int main(int argc, char *argv[]) {
log_parse_environment(); log_parse_environment();
log_open(); log_open();
srand(time(NULL)); initialize_srand();
r = parse_argv(argc, argv); r = parse_argv(argc, argv);
if (r <= 0) if (r <= 0)

View file

@ -2521,28 +2521,22 @@ int dev_urandom(void *p, size_t n) {
return 0; return 0;
} }
void random_bytes(void *p, size_t n) { void initialize_srand(void) {
static bool srand_called = false; static bool srand_called = false;
uint8_t *q; unsigned x;
int r; #ifdef HAVE_SYS_AUXV_H
void *auxv;
#endif
r = dev_urandom(p, n); if (srand_called)
if (r >= 0)
return; return;
/* If some idiot made /dev/urandom unavailable to us, he'll x = 0;
* get a PRNG instead. */
if (!srand_called) {
unsigned x = 0;
#ifdef HAVE_SYS_AUXV_H #ifdef HAVE_SYS_AUXV_H
/* The kernel provides us with a bit of entropy in /* The kernel provides us with a bit of entropy in auxv, so
* auxv, so let's try to make use of that to seed the * let's try to make use of that to seed the pseudo-random
* pseudo-random generator. It's better than * generator. It's better than nothing... */
* nothing... */
void *auxv;
auxv = (void*) getauxval(AT_RANDOM); auxv = (void*) getauxval(AT_RANDOM);
if (auxv) if (auxv)
@ -2556,6 +2550,19 @@ void random_bytes(void *p, size_t n) {
srand_called = true; srand_called = true;
} }
void random_bytes(void *p, size_t n) {
uint8_t *q;
int r;
r = dev_urandom(p, n);
if (r >= 0)
return;
/* If some idiot made /dev/urandom unavailable to us, he'll
* get a PRNG instead. */
initialize_srand();
for (q = p; q < (uint8_t*) p + n; q ++) for (q = p; q < (uint8_t*) p + n; q ++)
*q = rand(); *q = rand();
} }

View file

@ -321,6 +321,7 @@ int make_console_stdio(void);
int dev_urandom(void *p, size_t n); int dev_urandom(void *p, size_t n);
void random_bytes(void *p, size_t n); void random_bytes(void *p, size_t n);
void initialize_srand(void);
static inline uint64_t random_u64(void) { static inline uint64_t random_u64(void) {
uint64_t u; uint64_t u;

View file

@ -922,7 +922,7 @@ int main(int argc, char *argv[])
goto exit; goto exit;
} }
srand((unsigned int)getpid()); initialize_srand();
for (cnt = 20; cnt > 0; cnt--) { for (cnt = 20; cnt > 0; cnt--) {
struct timespec duration; struct timespec duration;

View file

@ -861,7 +861,7 @@ int scsi_get_serial(struct udev *udev,
int retval; int retval;
memzero(dev_scsi->serial, len); memzero(dev_scsi->serial, len);
srand((unsigned int)getpid()); initialize_srand();
for (cnt = 20; cnt > 0; cnt--) { for (cnt = 20; cnt > 0; cnt--) {
struct timespec duration; struct timespec duration;