1221206fd4c7061ac74b8b2ce2d756fa16565ddd
[profile/ivi/pulseaudio.git] / src / polypcore / random.c
1 /* $Id$ */
2
3 /***
4   This file is part of polypaudio.
5  
6   polypaudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation; either version 2.1 of the
9   License, or (at your option) any later version.
10  
11   polypaudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15  
16   You should have received a copy of the GNU Lesser General Public
17   License along with polypaudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <assert.h>
32 #include <time.h>
33
34 #include <polypcore/util.h>
35 #include <polypcore/log.h>
36
37 #include "random.h"
38
39 static int has_whined = 0;
40
41 static const char *devices[] = { "/dev/urandom", "/dev/random", NULL };
42
43 static int random_proper(void *ret_data, size_t length) {
44 #ifdef OS_IS_WIN32
45     assert(ret_data && length);
46
47     return -1;
48
49 #else /* OS_IS_WIN32 */
50
51     int fd, ret;
52     ssize_t r = 0;
53     const char **device;
54
55     assert(ret_data && length);
56
57     device = devices;
58
59     while (*device) {
60         ret = 0;
61
62         if ((fd = open(*device, O_RDONLY)) >= 0) {
63
64             if ((r = pa_loop_read(fd, ret_data, length)) < 0 || (size_t) r != length)
65                 ret = -1;
66
67             close(fd);
68         } else
69             ret = -1;
70
71         if (ret == 0)
72             break;
73     }
74
75     return ret;
76 #endif /* OS_IS_WIN32 */
77 }
78
79 void pa_random_seed(void) {
80     unsigned int seed;
81
82     if (random_proper(&seed, sizeof(unsigned int)) < 0) {
83         if (!has_whined)
84             pa_log_warn(__FILE__": failed to get proper entropy. Falling back to seeding with current time.");
85         has_whined = 1;
86
87         seed = (unsigned int) time(NULL);
88     }
89
90     srand(seed);
91 }
92
93 void pa_random(void *ret_data, size_t length) {
94     uint8_t *p;
95     size_t l;
96
97     assert(ret_data && length);
98
99     if (random_proper(ret_data, length) >= 0)
100         return;
101
102     if (!has_whined)
103         pa_log_warn(__FILE__": failed to get proper entropy. Falling back to unsecure pseudo RNG.");
104     has_whined = 1;
105
106     for (p = ret_data, l = length; l > 0; p++, l--)
107         *p = (uint8_t) rand();
108 }