Skip to content

Commit 7a99db6

Browse files
committed
Tidy up php_random_bytes and add /dev/arandom
1 parent bbc9198 commit 7a99db6

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

ext/standard/random.c

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -36,47 +36,46 @@ union rand_long_buffer {
3636
};
3737

3838
// Copy/pasted from mcrypt.c
39-
static int php_random_bytes(char *bytes, zend_long size)
39+
static int php_random_bytes(void *bytes, size_t size)
4040
{
4141
int n = 0;
4242

4343
#if PHP_WIN32
44-
/* random/urandom equivalent on Windows */
45-
BYTE *win_bytes = (BYTE *) bytes;
46-
if (php_win32_get_random_bytes(win_bytes, (size_t) size) == FAILURE) {
44+
/* Defer to CryptGenRandom on Windows */
45+
if (php_win32_get_random_bytes(bytes, size) == FAILURE) {
4746
php_error_docref(NULL, E_WARNING, "Could not gather sufficient random data");
4847
return FAILURE;
4948
}
50-
n = (int)size;
5149
#else
52-
// @todo Need to cache the fd for random_int() call within loop
53-
int fd;
50+
int fd = -1;
5451
size_t read_bytes = 0;
55-
52+
#if HAVE_DEV_ARANDOM
53+
fd = open("/dev/arandom", O_RDONLY);
54+
#else
55+
#if HAVE_DEV_URANDOM
5656
fd = open("/dev/urandom", O_RDONLY);
57+
#endif
58+
#endif
5759
if (fd < 0) {
5860
php_error_docref(NULL, E_WARNING, "Cannot open source device");
5961
return FAILURE;
6062
}
63+
6164
while (read_bytes < size) {
6265
n = read(fd, bytes + read_bytes, size - read_bytes);
6366
if (n < 0) {
6467
break;
6568
}
6669
read_bytes += n;
6770
}
68-
n = read_bytes;
6971

7072
close(fd);
71-
if (n < size) {
73+
if (read_bytes < size) {
7274
php_error_docref(NULL, E_WARNING, "Could not gather sufficient random data");
7375
return FAILURE;
7476
}
7577
#endif
7678

77-
// @todo - Do we need to do this?
78-
bytes[size] = '\0';
79-
8079
return SUCCESS;
8180
}
8281

@@ -103,6 +102,8 @@ PHP_FUNCTION(random_bytes)
103102
return;
104103
}
105104

105+
bytes->val[size] = '\0';
106+
106107
RETURN_STR(bytes);
107108
}
108109
/* }}} */

0 commit comments

Comments
 (0)