dhtlog updates
[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   if (mode == GNUNET_CRYPTO_QUALITY_STRONG)
64     {
65       /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
66 #ifdef gcry_fast_random_poll
67       if ((invokeCount++ % 256) == 0)
68         gcry_fast_random_poll ();
69 #endif
70       ul = UINT32_MAX - (UINT32_MAX % i);
71       do
72         {
73           gcry_randomize ((unsigned char *) &ret,
74                           sizeof (uint32_t), GCRY_STRONG_RANDOM);
75         }
76       while (ret >= ul);
77       return ret % i;
78     }
79   else
80     {
81       ret = i * weak_random ();
82       if (ret >= i)
83         ret = i - 1;
84       return ret;
85     }
86 }
87
88
89 /**
90  * Get an array with a random permutation of the
91  * numbers 0...n-1.
92  * @param mode GNUNET_RANDOM_QUALITY_STRONG if the strong (but expensive)
93  *        PRNG should be used, GNUNET_RANDOM_QUALITY_WEAK otherwise
94  * @param n the size of the array
95  * @return the permutation array (allocated from heap)
96  */
97 unsigned int *
98 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n)
99 {
100   unsigned int *ret;
101   unsigned int i;
102   unsigned int tmp;
103   uint32_t x;
104
105   GNUNET_assert (n > 0);
106   ret = GNUNET_malloc (n * sizeof (unsigned int));
107   for (i = 0; i < n; i++)
108     ret[i] = i;
109   for (i = n - 1; i > 0; i--)
110     {
111       x = GNUNET_CRYPTO_random_u32 (mode, i+1);
112       tmp = ret[x];
113       ret[x] = ret[i];
114       ret[i] = tmp;
115     }
116   return ret;
117 }
118
119 /**
120  * Random on unsigned 64-bit values.
121  *
122  *
123  * @param mode desired quality of the random number
124  * @param max value returned will be in range [0,max) (exclusive)
125  * @return random 64-bit number
126  */
127 uint64_t
128 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max)
129 {
130   uint64_t ret;
131   uint64_t ul;
132
133   GNUNET_assert (max > 0);
134   if (mode == GNUNET_CRYPTO_QUALITY_STRONG)
135     {
136       ul = UINT64_MAX - (UINT64_MAX % max);
137       do
138         {
139           gcry_randomize ((unsigned char *) &ret,
140                           sizeof (uint64_t), GCRY_STRONG_RANDOM);
141         }
142       while (ret >= ul);
143       return ret % max;
144     }
145   else
146     {
147       ret = max * weak_random ();
148       if (ret >= max)
149         ret = max - 1;
150       return ret;
151     }
152 }
153
154 /**
155  * This function should only be called in testcases
156  * where strong entropy gathering is not desired
157  * (for example, for hostkey generation).
158  */
159 void
160 GNUNET_CRYPTO_random_disable_entropy_gathering ()
161 {
162   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
163 }
164
165
166 /**
167  * Process ID of the "find" process that we use for
168  * entropy gathering.
169  */
170 static pid_t genproc;
171
172 /**
173  * Function called by libgcrypt whenever we are
174  * blocked gathering entropy.
175  */
176 static void
177 entropy_generator (void *cls,
178                    const char *what, int printchar, int current, int total)
179 {
180   unsigned long code;
181   enum GNUNET_OS_ProcessStatusType type;
182   int ret;
183
184   if (0 != strcmp (what, "need_entropy"))
185     return;
186   if (current == total)
187     {
188       if (genproc != 0)
189         {
190           if (0 != PLIBC_KILL (genproc, SIGTERM))
191             GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "kill");
192           GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
193           genproc = 0;
194         }
195       return;
196     }
197   if (genproc != 0)
198     {
199       ret = GNUNET_OS_process_status (genproc, &type, &code);
200       if (ret == GNUNET_NO)
201         return;                 /* still running */
202       if (ret == GNUNET_SYSERR)
203         {
204           GNUNET_break (0);
205           return;
206         }
207       if (0 != PLIBC_KILL (genproc, SIGTERM))
208         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "kill");
209       GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
210       genproc = 0;
211     }
212   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
213               _("Starting `%s' process to generate entropy\n"), "find");
214   genproc = GNUNET_OS_start_process (NULL, NULL, "sh",
215                                      "sh",
216                                      "-c",
217                                      "exec find / -mount -type f -exec cp {} /dev/null \\; 2>/dev/null",
218                                      NULL);
219 }
220
221
222 static void
223 killfind ()
224 {
225   if (genproc != 0)
226     {
227       PLIBC_KILL (genproc, SIGKILL);
228       genproc = 0;
229     }
230 }
231
232
233 void __attribute__ ((constructor)) GNUNET_CRYPTO_random_init ()
234 {
235   SRANDOM (time (NULL));
236   gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
237   if (!gcry_check_version (GCRYPT_VERSION))
238     {
239       fprintf (stderr,
240                _
241                ("libgcrypt has not the expected version (version %s is required).\n"),
242                GCRYPT_VERSION);
243       abort ();
244     }
245 #ifdef gcry_fast_random_poll
246   gcry_fast_random_poll ();
247 #endif
248   gcry_set_progress_handler (&entropy_generator, NULL);
249   atexit (&killfind);
250 }
251
252
253 void __attribute__ ((destructor)) GNUNET_CRYPTO_random_fini ()
254 {
255   gcry_set_progress_handler (NULL, NULL);
256 }
257
258
259
260 /* end of crypto_random.c */