| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
#include <aws/common/device_random.h> |
| 6 |
|
| 7 |
#include <aws/common/byte_buf.h> |
| 8 |
#include <aws/common/thread.h> |
| 9 |
|
| 10 |
#include <fcntl.h> |
| 11 |
#include <unistd.h> |
| 12 |
|
| 13 |
static int s_rand_fd = -1; |
| 14 |
static aws_thread_once s_rand_init = AWS_THREAD_ONCE_STATIC_INIT; |
| 15 |
|
| 16 |
#ifdef O_CLOEXEC |
| 17 |
# define OPEN_FLAGS (O_RDONLY | O_CLOEXEC) |
| 18 |
#else |
| 19 |
# define OPEN_FLAGS (O_RDONLY) |
| 20 |
#endif |
| 21 |
static void s_init_rand(void *user_data) { |
| 22 |
(void)user_data; |
| 23 |
s_rand_fd = open("/dev/urandom", OPEN_FLAGS); |
| 24 |
|
| 25 |
if (s_rand_fd == -1) { |
| 26 |
s_rand_fd = open("/dev/urandom", O_RDONLY); |
| 27 |
|
| 28 |
if (s_rand_fd == -1) { |
| 29 |
abort(); |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
if (-1 == fcntl(s_rand_fd, F_SETFD, FD_CLOEXEC)) { |
| 34 |
abort(); |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
int aws_device_random_buffer_append(struct aws_byte_buf *output, size_t n) { |
| 39 |
AWS_PRECONDITION(aws_byte_buf_is_valid(output)); |
| 40 |
|
| 41 |
aws_thread_call_once(&s_rand_init, s_init_rand, NULL); |
| 42 |
|
| 43 |
size_t space_available = output->capacity - output->len; |
| 44 |
if (space_available < n) { |
| 45 |
AWS_POSTCONDITION(aws_byte_buf_is_valid(output)); |
| 46 |
return aws_raise_error(AWS_ERROR_SHORT_BUFFER); |
| 47 |
} |
| 48 |
|
| 49 |
size_t original_len = output->len; |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
while (n > 0) { |
| 54 |
size_t capped_n = aws_min_size( |
| 55 |
n, 1024 * 1024 * 1024 * 1 ); |
| 56 |
|
| 57 |
ssize_t amount_read = read(s_rand_fd, output->buffer + output->len, capped_n); |
| 58 |
|
| 59 |
if (amount_read <= 0) { |
| 60 |
output->len = original_len; |
| 61 |
AWS_POSTCONDITION(aws_byte_buf_is_valid(output)); |
| 62 |
return aws_raise_error(AWS_ERROR_RANDOM_GEN_FAILED); |
| 63 |
} |
| 64 |
|
| 65 |
output->len += amount_read; |
| 66 |
n -= amount_read; |
| 67 |
} |
| 68 |
|
| 69 |
AWS_POSTCONDITION(aws_byte_buf_is_valid(output)); |
| 70 |
return AWS_OP_SUCCESS; |
| 71 |
} |
| 72 |
|
| 73 |
int aws_device_random_buffer(struct aws_byte_buf *output) { |
| 74 |
return aws_device_random_buffer_append(output, output->capacity - output->len); |
| 75 |
} |