Skip to content

Commit

Permalink
lib: Use arc4random if present
Browse files Browse the repository at this point in the history
  • Loading branch information
cmouse committed May 9, 2016
1 parent 0bd1883 commit 19a02b6
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 0 deletions.
2 changes: 2 additions & 0 deletions configure.ac
Expand Up @@ -324,6 +324,8 @@ DOVECOT_FDATASYNC
DOVECOT_LIBCAP
DOVECOT_LIBWRAP

DOVECOT_ARC4RANDOM

AC_DEFINE(PACKAGE_WEBPAGE, "http://www.dovecot.org/", [Support URL])

dnl * after -lsocket and -lnsl tests, inet_aton() may be in them
Expand Down
11 changes: 11 additions & 0 deletions m4/arc4random.m4
@@ -0,0 +1,11 @@
AC_DEFUN([DOVECOT_ARC4RANDOM], [
AC_CHECK_FUNC([arc4random], [
AC_DEFINE([HAVE_ARC4RANDOM], [1], [Define this if you arc4random()])
], [
AC_CHECK_LIB([bsd], [arc4random], [
LIBS="$LIBS -lbsd"
AC_DEFINE([HAVE_ARC4RANDOM], [1], [Define this if you arc4random()])
AC_DEFINE([HAVE_LIBBSD], [1], [Define this if you have libbsd])
])
])
])
11 changes: 11 additions & 0 deletions src/lib/rand.c
Expand Up @@ -31,3 +31,14 @@ void rand_set_seed(unsigned int s)

srand(seed);
}

#ifdef HAVE_ARC4RANDOM
#ifdef HAVE_LIBBSD
#include <bsd/stdlib.h>
#endif

/* this returns [0,RAND_MAX), to keep it compatible with rand() */
int arc4random_rand(void) {
return (int)(arc4random() % ((unsigned)RAND_MAX + 1));
}
#endif
7 changes: 7 additions & 0 deletions src/lib/rand.h
Expand Up @@ -16,4 +16,11 @@ unsigned int rand_get_last_seed(void);
/* Actually seed the prng (could add char* for name of function?) */
void rand_set_seed(unsigned int s);

#ifdef HAVE_ARC4RANDOM

int arc4random_rand(void);
#define rand arc4random_rand

#endif

#endif
14 changes: 14 additions & 0 deletions src/lib/randgen.c
Expand Up @@ -61,10 +61,24 @@ void random_deinit(void)
i_close_fd(&urandom_fd);
}

#ifdef HAVE_ARC4RANDOM
#ifdef HAVE_LIBBSD
#include <bsd/stdlib.h>
#endif

void random_fill_weak(void *buf, size_t size)
{
arc4random_buf(buf, size);
}

#else

void random_fill_weak(void *buf, size_t size)
{
unsigned char *cbuf = buf;

for (; size > 0; size--)
*cbuf++ = (unsigned char)rand();
}

#endif

0 comments on commit 19a02b6

Please sign in to comment.