- add randomness to the announce period: 10-20 min
[oweals/gnunet.git] / src / regex / gnunet-daemon-regexprofiler.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012, 2013 Christian Grothoff
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 3, 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  * @file regex/gnunet-daemon-regexprofiler.c
23  * @brief daemon that uses mesh to announce a regular expression. Used in
24  * conjunction with gnunet-regex-profiler to announce regexes on serveral peers
25  * without the need to explicitly connect to the mesh service running on the
26  * peer from within the profiler.
27  * @author Maximilian Szengel
28  * @author Bartlomiej Polot
29  */
30 #include "platform.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_regex_lib.h"
33 #include "gnunet_dht_service.h"
34 #include "gnunet_statistics_service.h"
35
36 /**
37  * Return value from 'main'.
38  */
39 static int global_ret;
40
41 /**
42  * Configuration we use.
43  */
44 static const struct GNUNET_CONFIGURATION_Handle *cfg;
45
46 /**
47  * Handle to the statistics service.
48  */
49 static struct GNUNET_STATISTICS_Handle *stats_handle;
50
51 /**
52  * Peer's dht handle.
53  */
54 static struct GNUNET_DHT_Handle *dht_handle;
55
56 /**
57  * Peer's regex announce handle.
58  */
59 static struct GNUNET_REGEX_announce_handle *announce_handle;
60
61 /**
62  * Hostkey generation context
63  */
64 static struct GNUNET_CRYPTO_RsaKeyGenerationContext *keygen;
65
66 /**
67  * Periodically reannounce regex.
68  */
69 static GNUNET_SCHEDULER_TaskIdentifier reannounce_task;
70
71 /**
72  * How often reannounce regex.
73  */
74 static struct GNUNET_TIME_Relative reannounce_freq;
75
76 /**
77  * Random delay to spread out load on the DHT.
78  */
79 static struct GNUNET_TIME_Relative announce_delay;
80
81 /**
82  * Local peer's PeerID.
83  */
84 static struct GNUNET_PeerIdentity my_full_id;
85
86 /**
87  * Maximal path compression length for regex announcing.
88  */
89 static unsigned long long max_path_compression;
90
91 /**
92  * Name of the file containing policies that this peer should announce. One
93  * policy per line.
94  */
95 static char * policy_filename;
96
97 /**
98  * Prefix to add before every regex we're announcing.
99  */
100 static char * regex_prefix;
101
102 /**
103  * Regex with prefix.
104  */
105 static char *rx_with_pfx;
106
107
108 /**
109  * Task run during shutdown.
110  *
111  * @param cls unused
112  * @param tc unused
113  */
114 static void
115 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
116 {
117   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
118
119   if (NULL != keygen)
120   {
121     GNUNET_CRYPTO_rsa_key_create_stop (keygen);
122     keygen = NULL;
123   }
124   if (NULL != announce_handle)
125   {
126     GNUNET_REGEX_announce_cancel (announce_handle);
127     announce_handle = NULL;
128   }
129
130   if (NULL != dht_handle)
131   {
132     GNUNET_DHT_disconnect (dht_handle);
133     dht_handle = NULL;
134   }
135
136   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
137 }
138
139
140 /**
141  * Announce a previously announced regex re-using cached data.
142  * 
143  * @param cls Closure (regex to announce if needed).
144  * @param tc TaskContext.
145  */
146 static void
147 reannounce_regex (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
148 {
149   char *regex = cls;
150   reannounce_task = GNUNET_SCHEDULER_NO_TASK;
151   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
152   {
153     GNUNET_free (regex);
154     return;
155   }
156
157   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Announcing regex: %s\n", regex);
158   GNUNET_STATISTICS_update (stats_handle, "# regexes announced", 1, GNUNET_NO);
159   if (NULL == announce_handle && NULL != regex)
160   {
161     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
162                 "First time, creating regex: %s\n",
163                 regex);
164     announce_handle = GNUNET_REGEX_announce (dht_handle,
165                                             &my_full_id,
166                                             regex,
167                                             (unsigned int) max_path_compression,
168                                             stats_handle);
169   }
170   else
171   {
172     GNUNET_assert (NULL != announce_handle);
173     GNUNET_REGEX_reannounce (announce_handle);
174   }
175
176   reannounce_task = GNUNET_SCHEDULER_add_delayed (
177     GNUNET_TIME_relative_add (reannounce_freq,
178                               GNUNET_TIME_relative_multiply (
179                                 GNUNET_TIME_UNIT_SECONDS,
180                                 GNUNET_CRYPTO_random_u32 (
181                                   GNUNET_CRYPTO_QUALITY_WEAK,
182                                   600
183                                 )
184                               )
185                              ),
186     &reannounce_regex,
187     cls);
188 }
189
190
191 /**
192  * Announce the given regular expression using Mesh and the path compression
193  * length read from config.
194  *
195  * @param regex regular expression to announce on this peer's mesh.
196  */
197 static void
198 announce_regex (const char * regex)
199 {
200   char *copy;
201
202   if (NULL == regex || 0 == strlen (regex))
203   {
204     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot announce empty regex\n");
205     return;
206   }
207
208   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == reannounce_task);
209   copy = GNUNET_strdup (regex);
210   reannounce_task = GNUNET_SCHEDULER_add_delayed (announce_delay,
211                                                   reannounce_regex,
212                                                   (void *) copy);
213 }
214
215
216 /**
217  * Load regular expressions from filename into 'rxes' array. Array needs to be freed.
218  *
219  * @param filename filename of the file containing the regexes, one per line.
220  * @param rx string with the union of all regular expressions.
221  *
222  * @return number of regular expressions read from filename and in rxes array.
223  * FIXME use load regex lib function
224  */
225 static unsigned int
226 load_regexes (const char *filename, char **rx)
227 {
228   char *data;
229   char *buf;
230   uint64_t filesize;
231   unsigned int offset;
232   unsigned int rx_cnt;
233
234   if (GNUNET_YES != GNUNET_DISK_file_test (policy_filename))
235   {
236     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
237                 "Could not find policy file %s\n", policy_filename);
238     return 0;
239   }
240   if (GNUNET_OK != GNUNET_DISK_file_size (policy_filename, &filesize, GNUNET_YES, GNUNET_YES))
241     filesize = 0;
242   if (0 == filesize)
243   {
244     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Policy file %s is empty.\n", policy_filename);
245     return 0;
246   }
247   data = GNUNET_malloc (filesize);
248   if (filesize != GNUNET_DISK_fn_read (policy_filename, data, filesize))
249   {
250     GNUNET_free (data);
251     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not read policy file %s.\n",
252                 policy_filename);
253     return 0;
254   }
255   buf = data;
256   offset = 0;
257   rx_cnt = 0;
258   while (offset < (filesize - 1))
259   {
260     offset++;
261     if ((data[offset] == '\n') && (buf != &data[offset]))
262     {
263       data[offset] = '|';
264       buf = &data[offset + 1];
265       rx_cnt++;
266     }
267     else if ((data[offset] == '\n') || (data[offset] == '\0'))
268       buf = &data[offset + 1];
269   }
270   data[offset] = '\0';
271   *rx = data;
272
273   return rx_cnt;
274 }
275
276
277 /**
278  * Callback for hostkey read/generation
279  *
280  * @param cls Closure (not used).
281  * @param pk The private key of the local peer.
282  * @param emsg Error message if applicable.
283  */
284 static void
285 key_generation_cb (void *cls,
286                    struct GNUNET_CRYPTO_RsaPrivateKey *pk,
287                    const char *emsg)
288 {
289   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
290
291   keygen = NULL;
292   if (NULL == pk)
293   {
294     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
295                 _("Regexprofiler could not access hostkey: %s. Exiting.\n"),
296                 emsg);
297     GNUNET_SCHEDULER_shutdown ();
298     return;
299   }
300
301   GNUNET_CRYPTO_rsa_key_get_public (pk, &my_public_key);
302   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
303                       &my_full_id.hashPubKey);
304
305   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
306               "Regexprofiler for peer [%s] starting\n",
307               GNUNET_i2s(&my_full_id));
308   announce_regex (rx_with_pfx);
309   GNUNET_free (rx_with_pfx);
310 }
311
312
313 /**
314  * @brief Main function that will be run by the scheduler.
315  *
316  * @param cls closure
317  * @param args remaining command-line arguments
318  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
319  * @param cfg_ configuration
320  */
321 static void
322 run (void *cls, char *const *args GNUNET_UNUSED,
323      const char *cfgfile GNUNET_UNUSED,
324      const struct GNUNET_CONFIGURATION_Handle *cfg_)
325 {
326   char *regex = NULL;
327   char *keyfile;
328
329   cfg = cfg_;
330
331   if (GNUNET_OK !=
332       GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
333                                                &keyfile))
334   {
335     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
336                 _
337                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
338                 "regexprofiler", "hostkey");
339     GNUNET_SCHEDULER_shutdown ();
340     return;
341   }
342
343   if (GNUNET_OK !=
344       GNUNET_CONFIGURATION_get_value_number (cfg, "REGEXPROFILER", "MAX_PATH_COMPRESSION",
345                                              &max_path_compression))
346   {
347     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
348                 _
349                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
350                 "regexprofiler", "max_path_compression");
351     global_ret = GNUNET_SYSERR;
352     GNUNET_SCHEDULER_shutdown ();
353     return;
354   }
355
356   if (GNUNET_OK !=
357       GNUNET_CONFIGURATION_get_value_filename (cfg, "REGEXPROFILER",
358                                                "POLICY_FILE", &policy_filename))
359   {
360     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
361                 _
362                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
363                 "regexprofiler", "policy_file");
364     global_ret = GNUNET_SYSERR;
365     GNUNET_SCHEDULER_shutdown ();
366     return;
367   }
368
369   if (GNUNET_OK !=
370       GNUNET_CONFIGURATION_get_value_string (cfg, "REGEXPROFILER",
371                                              "REGEX_PREFIX", &regex_prefix))
372   {
373     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
374                 _
375                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
376                 "regexprofiler", "regex_prefix");
377     global_ret = GNUNET_SYSERR;
378     GNUNET_SCHEDULER_shutdown ();
379     return;
380   }
381
382   if (GNUNET_OK !=
383       GNUNET_CONFIGURATION_get_value_time (cfg, "REGEXPROFILER",
384                                            "REANNOUNCE_FREQ", &reannounce_freq))
385   {
386     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
387                 "reannounce_freq not given. Using 10 minutes.\n");
388     reannounce_freq =
389       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 10);
390
391   }
392     announce_delay =
393     GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
394                                    GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 600));
395
396   stats_handle = GNUNET_STATISTICS_create ("regexprofiler", cfg);
397
398   dht_handle = GNUNET_DHT_connect (cfg, 1);
399
400   if (NULL == dht_handle)
401   {
402     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
403                 "Could not acquire dht handle. Exiting.\n");
404     global_ret = GNUNET_SYSERR;
405     GNUNET_SCHEDULER_shutdown ();
406     return;
407   }
408
409   /* Read regexes from policy files */
410   if (0 == load_regexes (policy_filename, &regex))
411   {
412     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
413                 "Policy file %s contains no policies. Exiting.\n",
414                 policy_filename);
415     global_ret = GNUNET_SYSERR;
416     GNUNET_SCHEDULER_shutdown ();
417     return;
418   }
419
420   /* Announcing regexes from policy_filename */
421   GNUNET_asprintf (&rx_with_pfx, "%s(%s)", regex_prefix, regex);
422   GNUNET_free (regex);
423
424   keygen = GNUNET_CRYPTO_rsa_key_create_start (keyfile,
425                                                &key_generation_cb,
426                                                NULL);
427   GNUNET_free (keyfile);
428
429   /* Scheduled the task to clean up when shutdown is called */
430   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
431                                 NULL);
432 }
433
434
435 /**
436  * The main function of the regexprofiler service.
437  *
438  * @param argc number of arguments from the command line
439  * @param argv command line arguments
440  * @return 0 ok, 1 on error
441  */
442 int
443 main (int argc, char *const *argv)
444 {
445   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
446     GNUNET_GETOPT_OPTION_END
447   };
448
449   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
450     return 2;
451   return (GNUNET_OK ==
452           GNUNET_PROGRAM_run (argc, argv, "regexprofiler",
453                               gettext_noop
454                               ("Daemon to announce regular expressions for the peer using mesh."),
455                               options, &run, NULL)) ? global_ret : 1;
456 }
457
458
459 #ifdef LINUX
460 #include <malloc.h>
461
462 /**
463  * MINIMIZE heap size (way below 128k) since this process doesn't need much.
464  */
465 void __attribute__ ((constructor)) GNUNET_ARM_memory_init ()
466 {
467   mallopt (M_TRIM_THRESHOLD, 4 * 1024);
468   mallopt (M_TOP_PAD, 1 * 1024);
469   malloc_trim (0);
470 }
471 #endif
472
473
474 /* end of gnunet-daemon-regexprofiler.c */