indentation
[oweals/gnunet.git] / src / util / crypto_random.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19
20 */
21
22 /**
23  * @file util/crypto_random.c
24  * @brief functions to gather random numbers
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_common.h"
29 #include "gnunet_crypto_lib.h"
30 #include "gnunet_os_lib.h"
31 #include <gcrypt.h>
32
33 /**
34  * Create a cryptographically weak pseudo-random number in the interval of 0 to 1.
35  * 
36  * @return number between 0 and 1.
37  */
38 static double
39 weak_random ()
40 {
41   return ((double) RANDOM () / RAND_MAX);
42 }
43
44
45 /**
46  * Produce a random value.
47  *
48  * @param mode desired quality of the random number
49  * @param i the upper limit (exclusive) for the random number
50  * @return a random value in the interval [0,i[.
51  */
52 uint32_t
53 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i)
54 {
55 #ifdef gcry_fast_random_poll
56   static unsigned int invokeCount;
57 #endif
58   uint32_t ret;
59   uint32_t ul;
60
61   GNUNET_assert (i > 0);
62
63   switch (mode)
64   {
65   case GNUNET_CRYPTO_QUALITY_STRONG:
66     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
67 #ifdef gcry_fast_random_poll
68     if ((invokeCount++ % 256) == 0)
69       gcry_fast_random_poll ();
70 #endif
71     ul = UINT32_MAX - (UINT32_MAX % i);
72     do
73     {
74       gcry_randomize ((unsigned char *) &ret,
75                       sizeof (uint32_t), GCRY_STRONG_RANDOM);
76     }
77     while (ret >= ul);
78     return ret % i;
79   case GNUNET_CRYPTO_QUALITY_NONCE:
80     ul = UINT32_MAX - (UINT32_MAX % i);
81     do
82     {
83       gcry_create_nonce (&ret, sizeof (ret));
84     }
85     while (ret >= ul);
86     return ret % i;
87   case GNUNET_CRYPTO_QUALITY_WEAK:
88     ret = i * weak_random ();
89     if (ret >= i)
90       ret = i - 1;
91     return ret;
92   default:
93     GNUNET_assert (0);
94   }
95   return 0;
96 }
97
98
99 /**
100  * Get an array with a random permutation of the
101  * numbers 0...n-1.
102  * @param mode GNUNET_RANDOM_QUALITY_STRONG if the strong (but expensive)
103  *        PRNG should be used, GNUNET_RANDOM_QUALITY_WEAK otherwise
104  * @param n the size of the array
105  * @return the permutation array (allocated from heap)
106  */
107 unsigned int *
108 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n)
109 {
110   unsigned int *ret;
111   unsigned int i;
112   unsigned int tmp;
113   uint32_t x;
114
115   GNUNET_assert (n > 0);
116   ret = GNUNET_malloc (n * sizeof (unsigned int));
117   for (i = 0; i < n; i++)
118     ret[i] = i;
119   for (i = n - 1; i > 0; i--)
120   {
121     x = GNUNET_CRYPTO_random_u32 (mode, i + 1);
122     tmp = ret[x];
123     ret[x] = ret[i];
124     ret[i] = tmp;
125   }
126   return ret;
127 }
128
129 /**
130  * Random on unsigned 64-bit values.
131  *
132  *
133  * @param mode desired quality of the random number
134  * @param max value returned will be in range [0,max) (exclusive)
135  * @return random 64-bit number
136  */
137 uint64_t
138 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max)
139 {
140   uint64_t ret;
141   uint64_t ul;
142
143   GNUNET_assert (max > 0);
144   switch (mode)
145   {
146   case GNUNET_CRYPTO_QUALITY_STRONG:
147     ul = UINT64_MAX - (UINT64_MAX % max);
148     do
149     {
150       gcry_randomize ((unsigned char *) &ret,
151                       sizeof (uint64_t), GCRY_STRONG_RANDOM);
152     }
153     while (ret >= ul);
154     return ret % max;
155   case GNUNET_CRYPTO_QUALITY_NONCE:
156     ul = UINT64_MAX - (UINT64_MAX % max);
157     do
158     {
159       gcry_create_nonce (&ret, sizeof (ret));
160     }
161     while (ret >= ul);
162
163     return ret % max;
164   case GNUNET_CRYPTO_QUALITY_WEAK:
165     ret = max * weak_random ();
166     if (ret >= max)
167       ret = max - 1;
168     return ret;
169   default:
170     GNUNET_assert (0);
171   }
172   return 0;
173 }
174
175 /**
176  * This function should only be called in testcases
177  * where strong entropy gathering is not desired
178  * (for example, for hostkey generation).
179  */
180 void
181 GNUNET_CRYPTO_random_disable_entropy_gathering ()
182 {
183   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
184 }
185
186
187 /**
188  * Process ID of the "find" process that we use for
189  * entropy gathering.
190  */
191 static struct GNUNET_OS_Process *genproc;
192
193 /**
194  * Function called by libgcrypt whenever we are
195  * blocked gathering entropy.
196  */
197 static void
198 entropy_generator (void *cls,
199                    const char *what, int printchar, int current, int total)
200 {
201   unsigned long code;
202   enum GNUNET_OS_ProcessStatusType type;
203   int ret;
204
205   if (0 != strcmp (what, "need_entropy"))
206     return;
207   if (current == total)
208   {
209     if (genproc != NULL)
210     {
211       if (0 != GNUNET_OS_process_kill (genproc, SIGTERM))
212         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "kill");
213       GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
214       GNUNET_OS_process_close (genproc);
215       genproc = NULL;
216     }
217     return;
218   }
219   if (genproc != NULL)
220   {
221     ret = GNUNET_OS_process_status (genproc, &type, &code);
222     if (ret == GNUNET_NO)
223       return;                   /* still running */
224     if (ret == GNUNET_SYSERR)
225     {
226       GNUNET_break (0);
227       return;
228     }
229     if (0 != GNUNET_OS_process_kill (genproc, SIGTERM))
230       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "kill");
231     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
232     GNUNET_OS_process_close (genproc);
233     genproc = NULL;
234   }
235   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
236               _("Starting `%s' process to generate entropy\n"), "find");
237   genproc = GNUNET_OS_start_process (NULL, NULL, "sh",
238                                      "sh",
239                                      "-c",
240                                      "exec find / -mount -type f -exec cp {} /dev/null \\; 2>/dev/null",
241                                      NULL);
242 }
243
244
245 static void
246 killfind ()
247 {
248   if (genproc != NULL)
249   {
250     GNUNET_OS_process_kill (genproc, SIGKILL);
251     GNUNET_OS_process_close (genproc);
252     genproc = NULL;
253   }
254 }
255
256
257 void __attribute__ ((constructor)) GNUNET_CRYPTO_random_init ()
258 {
259   gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
260   if (!gcry_check_version (GCRYPT_VERSION))
261   {
262     fprintf (stderr,
263              _
264              ("libgcrypt has not the expected version (version %s is required).\n"),
265              GCRYPT_VERSION);
266     abort ();
267   }
268 #ifdef gcry_fast_random_poll
269   gcry_fast_random_poll ();
270 #endif
271   gcry_set_progress_handler (&entropy_generator, NULL);
272   atexit (&killfind);
273   SRANDOM (time (NULL) ^
274            GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
275 }
276
277
278 void __attribute__ ((destructor)) GNUNET_CRYPTO_random_fini ()
279 {
280   gcry_set_progress_handler (NULL, NULL);
281 }
282
283
284
285 /* end of crypto_random.c */