]> git.sesse.net Git - vlc/blob - src/misc/rand.c
Use var_Inherit* instead of var_CreateGet*.
[vlc] / src / misc / rand.c
1 /*****************************************************************************
2  * rand.c : non-predictible random bytes generator
3  *****************************************************************************
4  * Copyright © 2007 Rémi Denis-Courmont
5  * $Id$
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
20  *****************************************************************************/
21
22 #ifdef HAVE_CONFIG_H
23 # include "config.h"
24 #endif
25
26 #include <vlc_common.h>
27 #include <vlc_rand.h>
28
29 #ifndef WIN32
30 #include <stdint.h>
31 #include <string.h>
32 #include <stdlib.h>
33
34 #include <sys/types.h>
35 #include <fcntl.h>
36 #include <unistd.h>
37 #include <pthread.h>
38 #include <vlc_fs.h>
39
40 #include <vlc_md5.h>
41
42 /*
43  * Pseudo-random number generator using a HMAC-MD5 in counter mode.
44  * Probably not very secure (expert patches welcome) but definitely
45  * better than rand() which is defined to be reproducible...
46  */
47 #define BLOCK_SIZE 64
48
49 static uint8_t okey[BLOCK_SIZE], ikey[BLOCK_SIZE];
50
51 static void vlc_rand_init (void)
52 {
53 #if defined (__OpenBSD__) || defined (__OpenBSD_kernel__)
54     static const char randfile[] = "/dev/random";
55 #else
56     static const char randfile[] = "/dev/urandom";
57 #endif
58     uint8_t key[BLOCK_SIZE];
59
60     /* Get non-predictible value as key for HMAC */
61     int fd = vlc_open (randfile, O_RDONLY);
62     if (fd == -1)
63         return; /* Uho! */
64
65     for (size_t i = 0; i < sizeof (key);)
66     {
67          ssize_t val = read (fd, key + i, sizeof (key) - i);
68          if (val > 0)
69              i += val;
70     }
71
72     /* Precompute outer and inner keys for HMAC */
73     for (size_t i = 0; i < sizeof (key); i++)
74     {
75         okey[i] = key[i] ^ 0x5c;
76         ikey[i] = key[i] ^ 0x36;
77     }
78
79     close (fd);
80 }
81
82
83 void vlc_rand_bytes (void *buf, size_t len)
84 {
85     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
86     static uint64_t counter = 0;
87
88     uint64_t stamp = NTPtime64 ();
89
90     while (len > 0)
91     {
92         uint64_t val;
93         struct md5_s mdi, mdo;
94
95         InitMD5 (&mdi);
96         InitMD5 (&mdo);
97
98         pthread_mutex_lock (&lock);
99         if (counter == 0)
100             vlc_rand_init ();
101         val = counter++;
102
103         AddMD5 (&mdi, ikey, sizeof (ikey));
104         AddMD5 (&mdo, okey, sizeof (okey));
105         pthread_mutex_unlock (&lock);
106
107         AddMD5 (&mdi, &stamp, sizeof (stamp));
108         AddMD5 (&mdi, &val, sizeof (val));
109         EndMD5 (&mdi);
110         AddMD5 (&mdo, mdi.p_digest, sizeof (mdi.p_digest));
111         EndMD5 (&mdo);
112
113         if (len < sizeof (mdo.p_digest))
114         {
115             memcpy (buf, mdo.p_digest, len);
116             break;
117         }
118
119         memcpy (buf, mdo.p_digest, sizeof (mdo.p_digest));
120         len -= sizeof (mdo.p_digest);
121         buf = ((uint8_t *)buf) + sizeof (mdo.p_digest);
122     }
123 }
124
125 #else /* WIN32 */
126
127 #include <wincrypt.h>
128
129 void vlc_rand_bytes (void *buf, size_t len)
130 {
131     HCRYPTPROV hProv;
132     size_t count = len;
133     uint8_t *p_buf = (uint8_t *)buf;
134
135     /* fill buffer with pseudo-random data */
136     while (count > 0)
137     {
138         unsigned int val;
139         val = rand();
140         if (count < sizeof (val))
141         {
142             memcpy (p_buf, &val, count);
143             break;
144         }
145  
146         memcpy (p_buf, &val, sizeof (val));
147         count -= sizeof (val);
148         p_buf += sizeof (val);
149     }
150
151     /* acquire default encryption context */
152     if( CryptAcquireContext(
153         &hProv,            // Variable to hold returned handle.
154         NULL,              // Use default key container.
155         MS_DEF_PROV,       // Use default CSP.
156         PROV_RSA_FULL,     // Type of provider to acquire.
157         0) )
158     {
159         /* fill buffer with pseudo-random data, intial buffer content
160            is used as auxillary random seed */
161         CryptGenRandom(hProv, len, buf);
162         CryptReleaseContext(hProv, 0);
163     }
164 }
165 #endif
166
167 static struct
168 {
169     bool           init;
170     unsigned short subi[3];
171     vlc_mutex_t    lock;
172 } rand48 = { false, { 0, 0, 0, }, VLC_STATIC_MUTEX, };
173
174 static void init_rand48 (void)
175 {
176     if (!rand48.init)
177     {
178         vlc_rand_bytes (rand48.subi, sizeof (rand48.subi));
179 #if 0 // short would be more than 16-bits ?
180         for (unsigned i = 0; i < 3; i++)
181             subi[i] &= 0xffff;
182 #endif
183     }
184 }
185
186 /**
187  * PRNG uniformly distributed between 0.0 and 1.0 with 48-bits precision.
188  *
189  * @note Contrary to POSIX drand48(), this function is thread-safe.
190  * @warning Series generated by this function are not reproducible.
191  * Use erand48() if you need reproducible series.
192  *
193  * @return a double value within [0.0, 1.0] inclusive
194  */
195 double vlc_drand48 (void)
196 {
197     double ret;
198
199     vlc_mutex_lock (&rand48.lock);
200     init_rand48 ();
201     ret = erand48 (rand48.subi);
202     vlc_mutex_unlock (&rand48.lock);
203     return ret;
204 }
205
206 /**
207  * PRNG uniformly distributed between 0 and 2^32 - 1.
208  *
209  * @note Contrary to POSIX lrand48(), this function is thread-safe.
210  * @warning Series generated by this function are not reproducible.
211  * Use nrand48() if you need reproducible series.
212  *
213  * @return an integral value within [0.0, 2^32-1] inclusive
214  */
215 long vlc_lrand48 (void)
216 {
217     long ret;
218
219     vlc_mutex_lock (&rand48.lock);
220     init_rand48 ();
221     ret = nrand48 (rand48.subi);
222     vlc_mutex_unlock (&rand48.lock);
223     return ret;
224 }
225
226 /**
227  * PRNG uniformly distributed between -2^32 and 2^32 - 1.
228  *
229  * @note Contrary to POSIX mrand48(), this function is thread-safe.
230  * @warning Series generated by this function are not reproducible.
231  * Use jrand48() if you need reproducible series.
232  *
233  * @return an integral value within [-2^32, 2^32-1] inclusive
234  */
235 long vlc_mrand48 (void)
236 {
237     long ret;
238
239     vlc_mutex_lock (&rand48.lock);
240     init_rand48 ();
241     ret = jrand48 (rand48.subi);
242     vlc_mutex_unlock (&rand48.lock);
243     return ret;
244 }