The commit makes the random be more chaotic than it used to be. This
change also makes the instance in readtab.c where random() is used a
little bit easier to read.
Signed-off-by: Sami Kerola <kerolasa(a)iki.fi>
---
anacron/main.c | 25 +++++++++++++++++++------
anacron/readtab.c | 15 ++++++++-------
2 files changed, 27 insertions(+), 13 deletions(-)
diff --git a/anacron/main.c b/anacron/main.c
index 7889983..88afaca 100644
--- a/anacron/main.c
+++ b/anacron/main.c
@@ -431,23 +431,36 @@ explain_intentions(void)
explain("Jobs will be executed sequentially");
}
+/* Seed random(3). */
+static void
+srandomdev(void) {
+ struct timeval tv;
+ unsigned int seed;
+ FILE *fd;
+
+ if ((fd = fopen("/dev/urandom", "r"))) {
+ fread(&seed, sizeof seed, 1, fd);
+ fclose(fd);
+ } else {
+ gettimeofday(&tv, NULL);
+ /* NOTE: intentional use of uninitialized variable */
+ seed ^= (getpid() << 16) ^ tv.tv_sec ^ tv.tv_usec;
+ }
+ srandom(seed);
+}
+
int
main(int argc, char *argv[])
{
int j;
int cwd;
- struct timeval tv;
- struct timezone tz;
anacrontab = NULL;
spooldir = NULL;
setlocale(LC_ALL, "");
- if (gettimeofday(&tv, &tz) != 0)
- explain("Can't get exact time, failure.");
-
- srandom(getpid()+tv.tv_usec);
+ srandomdev();
if((program_name = strrchr(argv[0], '/')) == NULL)
program_name = argv[0];
diff --git a/anacron/readtab.c b/anacron/readtab.c
index e378faf..2d403e4 100644
--- a/anacron/readtab.c
+++ b/anacron/readtab.c
@@ -281,13 +281,14 @@ parse_tab_line(char *line)
Debug(("Jobs will start in the %02d:00-%02d:00 range.",
range_start, range_stop));
}
if (strncmp(env_var, "RANDOM_DELAY", 12) == 0) {
- r = match_rx("^([[:digit:]]+)$", value, 0);
- if (r != -1) {
- int i = random();
- double x = 0;
- x = (double) i / (double) RAND_MAX * (double) (atoi(value));
- random_number = (int)x;
- Debug(("Randomized delay set: %d", random_number));
+ r = match_rx("^([[:digit:]]+)$", value, 0);
+ if (r != -1) {
+ int divisor = atoi(value);
+ random_number = random();
+ /* The random_number is expected vary in between 0 and
+ * 'value', so divisor need to be value + 1. */
+ random_number %= (divisor + 1);
+ Debug(("Randomized delay set: %d", random_number));
}
else goto reg_invalid;
}
--
1.8.1.1