1 /******************************************************************************
2  *
3  *  Copyright (C) 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 <assert.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <string.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 
29 #include "osi/include/log.h"
30 #include "osi/include/osi.h"
31 
32 #define RANDOM_PATH "/dev/urandom"
33 
osi_rand(void)34 int osi_rand(void) {
35   int rand;
36   int rand_fd = open(RANDOM_PATH, O_RDONLY);
37 
38   if (rand_fd == INVALID_FD) {
39     LOG_ERROR(LOG_TAG, "%s can't open rand fd %s: %s ", __func__, RANDOM_PATH,
40               strerror(errno));
41     assert(0);
42   }
43 
44   ssize_t read_bytes = read(rand_fd, &rand, sizeof(rand));
45   close(rand_fd);
46 
47   assert(read_bytes == sizeof(rand));
48 
49   if (rand < 0)
50     rand = -rand;
51 
52   return rand;
53 }
54