Marie Janssen | 093f013 | 2016-03-10 11:27:53 -0800 | [diff] [blame] | 1 | /****************************************************************************** |
| 2 | * |
Jakub Pawlowski | 5b790fe | 2017-09-18 09:00:20 -0700 | [diff] [blame] | 3 | * Copyright 2016 Google, Inc. |
Marie Janssen | 093f013 | 2016-03-10 11:27:53 -0800 | [diff] [blame] | 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 | |
Jack He | f2af1c4 | 2016-12-13 01:59:12 -0800 | [diff] [blame] | 21 | #include <base/logging.h> |
Marie Janssen | 093f013 | 2016-03-10 11:27:53 -0800 | [diff] [blame] | 22 | #include <errno.h> |
| 23 | #include <fcntl.h> |
Mark Salyzyn | 6aee1e8 | 2016-10-17 09:43:39 -0700 | [diff] [blame] | 24 | #include <stdio.h> |
Marie Janssen | 093f013 | 2016-03-10 11:27:53 -0800 | [diff] [blame] | 25 | #include <string.h> |
Marie Janssen | 093f013 | 2016-03-10 11:27:53 -0800 | [diff] [blame] | 26 | #include <sys/stat.h> |
Myles Watson | b55040c | 2016-10-19 13:15:34 -0700 | [diff] [blame] | 27 | #include <sys/types.h> |
Marie Janssen | 093f013 | 2016-03-10 11:27:53 -0800 | [diff] [blame] | 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 | |
| 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(LOG_TAG, "%s can't open rand fd %s: %s ", __func__, RANDOM_PATH, |
| 41 | strerror(errno)); |
Myles Watson | 1dc4b36 | 2017-03-21 10:28:20 -0700 | [diff] [blame] | 42 | CHECK(rand_fd != INVALID_FD); |
Marie Janssen | 093f013 | 2016-03-10 11:27:53 -0800 | [diff] [blame] | 43 | } |
| 44 | |
| 45 | ssize_t read_bytes = read(rand_fd, &rand, sizeof(rand)); |
| 46 | close(rand_fd); |
| 47 | |
Jack He | f2af1c4 | 2016-12-13 01:59:12 -0800 | [diff] [blame] | 48 | CHECK(read_bytes == sizeof(rand)); |
Marie Janssen | 093f013 | 2016-03-10 11:27:53 -0800 | [diff] [blame] | 49 | |
Myles Watson | b55040c | 2016-10-19 13:15:34 -0700 | [diff] [blame] | 50 | if (rand < 0) rand = -rand; |
Marie Janssen | 093f013 | 2016-03-10 11:27:53 -0800 | [diff] [blame] | 51 | |
| 52 | return rand; |
| 53 | } |