aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/restricted/aws/aws-c-common/source/posix/device_random.c
blob: f446002231bdaeda72b0d11b02c4fb57e9a1f8e5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */
#include <aws/common/device_random.h>

#include <aws/common/byte_buf.h>
#include <aws/common/thread.h>

#include <fcntl.h>
#include <unistd.h>

static int s_rand_fd = -1;
static aws_thread_once s_rand_init = AWS_THREAD_ONCE_STATIC_INIT;

#ifdef O_CLOEXEC
#    define OPEN_FLAGS (O_RDONLY | O_CLOEXEC)
#else
#    define OPEN_FLAGS (O_RDONLY)
#endif
static void s_init_rand(void *user_data) {
    (void)user_data;
    s_rand_fd = open("/dev/urandom", OPEN_FLAGS);

    if (s_rand_fd == -1) {
        s_rand_fd = open("/dev/urandom", O_RDONLY);

        if (s_rand_fd == -1) {
            abort();
        }
    }

    if (-1 == fcntl(s_rand_fd, F_SETFD, FD_CLOEXEC)) {
        abort();
    }
}

static int s_fallback_device_random_buffer(struct aws_byte_buf *output) {

    aws_thread_call_once(&s_rand_init, s_init_rand, NULL);

    size_t diff = output->capacity - output->len;

    ssize_t amount_read = read(s_rand_fd, output->buffer + output->len, diff);

    if (amount_read != diff) {
        return aws_raise_error(AWS_ERROR_RANDOM_GEN_FAILED);
    }

    output->len += diff;

    return AWS_OP_SUCCESS;
}

int aws_device_random_buffer(struct aws_byte_buf *output) {
    return s_fallback_device_random_buffer(output);
}