debug: Add group logging classes
[gd/samba-autobuild/.git] / lib / util / genrand.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Functions to create reasonable random numbers for crypto use.
5
6    Copyright (C) Jeremy Allison 2001
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "replace.h"
23 #include "system/filesys.h"
24 #include "lib/util/genrand.h"
25 #include "sys_rw_data.h"
26 #include "lib/util/blocking.h"
27
28 static int urand_fd = -1;
29
30 static void open_urandom(void)
31 {
32         if (urand_fd != -1) {
33                 return;
34         }
35         urand_fd = open( "/dev/urandom", O_RDONLY,0);
36         if (urand_fd == -1) {
37                 abort();
38         }
39         smb_set_close_on_exec(urand_fd);
40 }
41
42 _PUBLIC_ void generate_random_buffer(uint8_t *out, int len)
43 {
44         ssize_t rw_ret;
45
46         open_urandom();
47
48         rw_ret = read_data(urand_fd, out, len);
49         if (rw_ret != len) {
50                 abort();
51         }
52 }
53
54 /*
55  * Keep generate_secret_buffer in case we ever want to do something
56  * different
57  */
58 _PUBLIC_ void generate_secret_buffer(uint8_t *out, int len)
59 {
60         generate_random_buffer(out, len);
61 }