Skip to content

Commit

Permalink
random: add getrandom fallback for android
Browse files Browse the repository at this point in the history
Signed-off-by: William Casarin <[email protected]>
  • Loading branch information
jb55 committed Feb 10, 2024
1 parent 4a6f19a commit 65ab15d
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/random.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ static int fill_random(unsigned char* data, size_t size) {
} else {
return 1;
}
#elif defined(__ANDROID__)
int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) {
return 0; // Failed to open /dev/urandom
}
ssize_t read_bytes = 0;
while (size > 0) {
read_bytes = read(fd, data, size);
if (read_bytes <= 0) {
if (errno == EINTR) {
continue; // If interrupted by signal, try again
}
close(fd);
return 0; // Failed to read
}
data += read_bytes;
size -= read_bytes;
}
close(fd);
return 1;
#elif defined(__linux__) || defined(__FreeBSD__)
/* If `getrandom(2)` is not available you should fallback to /dev/urandom */
ssize_t res = getrandom(data, size, 0);
Expand Down

0 comments on commit 65ab15d

Please sign in to comment.