1 /******************************************************************************
2 *
3 * Copyright 2016 Google, Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19 #define LOG_TAG "bt_osi_rand"
20
21 #include <base/logging.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29
30 #include "osi/include/log.h"
31 #include "osi/include/osi.h"
32
33 #define RANDOM_PATH "/dev/urandom"
34
osi_rand(void)35 int osi_rand(void) {
36 int rand;
37 int rand_fd = open(RANDOM_PATH, O_RDONLY);
38
39 if (rand_fd == INVALID_FD) {
40 LOG_ERROR("%s can't open rand fd %s: %s ", __func__, RANDOM_PATH,
41 strerror(errno));
42 CHECK(rand_fd != INVALID_FD);
43 }
44
45 ssize_t read_bytes = read(rand_fd, &rand, sizeof(rand));
46 close(rand_fd);
47
48 CHECK(read_bytes == sizeof(rand));
49
50 if (rand < 0) rand = -rand;
51
52 return rand;
53 }
54