f172011f8175e93d54ff28fe3079919f2260be4f
[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   reannounce_task = GNUNET_SCHEDULER_add_delayed (reannounce_freq,
176                                                   &reannounce_regex,
177                                                   cls);
178 }
179
180
181 /**
182  * Announce the given regular expression using Mesh and the path compression
183  * length read from config.
184  *
185  * @param regex regular expression to announce on this peer's mesh.
186  */
187 static void
188 announce_regex (const char * regex)
189 {
190   char *copy;
191
192   if (NULL == regex || 0 == strlen (regex))
193   {
194     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot announce empty regex\n");
195     return;
196   }
197
198   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == reannounce_task);
199   copy = GNUNET_strdup (regex);
200   reannounce_task = GNUNET_SCHEDULER_add_delayed (announce_delay,
201                                                   reannounce_regex,
202                                                   (void *) copy);
203 }
204
205
206 /**
207  * Load regular expressions from filename into 'rxes' array. Array needs to be freed.
208  *
209  * @param filename filename of the file containing the regexes, one per line.
210  * @param rx string with the union of all regular expressions.
211  *
212  * @return number of regular expressions read from filename and in rxes array.
213  * FIXME use load regex lib function
214  */
215 static unsigned int
216 load_regexes (const char *filename, char **rx)
217 {
218   char *data;
219   char *buf;
220   uint64_t filesize;
221   unsigned int offset;
222   unsigned int rx_cnt;
223
224   if (GNUNET_YES != GNUNET_DISK_file_test (policy_filename))
225   {
226     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
227                 "Could not find policy file %s\n", policy_filename);
228     return 0;
229   }
230   if (GNUNET_OK != GNUNET_DISK_file_size (policy_filename, &filesize, GNUNET_YES, GNUNET_YES))
231     filesize = 0;
232   if (0 == filesize)
233   {
234     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Policy file %s is empty.\n", policy_filename);
235     return 0;
236   }
237   data = GNUNET_malloc (filesize);
238   if (filesize != GNUNET_DISK_fn_read (policy_filename, data, filesize))
239   {
240     GNUNET_free (data);
241     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not read policy file %s.\n",
242                 policy_filename);
243     return 0;
244   }
245   buf = data;
246   offset = 0;
247   rx_cnt = 0;
248   while (offset < (filesize - 1))
249   {
250     offset++;
251     if ((data[offset] == '\n') && (buf != &data[offset]))
252     {
253       data[offset] = '|';
254       buf = &data[offset + 1];
255       rx_cnt++;
256     }
257     else if ((data[offset] == '\n') || (data[offset] == '\0'))
258       buf = &data[offset + 1];
259   }
260   data[offset] = '\0';
261   *rx = data;
262
263   return rx_cnt;
264 }
265
266
267 /**
268  * Callback for hostkey read/generation
269  *
270  * @param cls Closure (not used).
271  * @param pk The private key of the local peer.
272  * @param emsg Error message if applicable.
273  */
274 static void
275 key_generation_cb (void *cls,
276                    struct GNUNET_CRYPTO_RsaPrivateKey *pk,
277                    const char *emsg)
278 {
279   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
280
281   keygen = NULL;
282   if (NULL == pk)
283   {
284     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
285                 _("Regexprofiler could not access hostkey: %s. Exiting.\n"),
286                 emsg);
287     GNUNET_SCHEDULER_shutdown ();
288     return;
289   }
290
291   GNUNET_CRYPTO_rsa_key_get_public (pk, &my_public_key);
292   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
293                       &my_full_id.hashPubKey);
294
295   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
296               "Regexprofiler for peer [%s] starting\n",
297               GNUNET_i2s(&my_full_id));
298   announce_regex (rx_with_pfx);
299   GNUNET_free (rx_with_pfx);
300 }
301
302
303 /**
304  * @brief Main function that will be run by the scheduler.
305  *
306  * @param cls closure
307  * @param args remaining command-line arguments
308  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
309  * @param cfg_ configuration
310  */
311 static void
312 run (void *cls, char *const *args GNUNET_UNUSED,
313      const char *cfgfile GNUNET_UNUSED,
314      const struct GNUNET_CONFIGURATION_Handle *cfg_)
315 {
316   char *regex = NULL;
317   char *keyfile;
318
319   cfg = cfg_;
320
321   if (GNUNET_OK !=
322       GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
323                                                &keyfile))
324   {
325     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
326                 _
327                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
328                 "regexprofiler", "hostkey");
329     GNUNET_SCHEDULER_shutdown ();
330     return;
331   }
332
333   if (GNUNET_OK !=
334       GNUNET_CONFIGURATION_get_value_number (cfg, "REGEXPROFILER", "MAX_PATH_COMPRESSION",
335                                              &max_path_compression))
336   {
337     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
338                 _
339                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
340                 "regexprofiler", "max_path_compression");
341     global_ret = GNUNET_SYSERR;
342     GNUNET_SCHEDULER_shutdown ();
343     return;
344   }
345
346   if (GNUNET_OK !=
347       GNUNET_CONFIGURATION_get_value_filename (cfg, "REGEXPROFILER",
348                                                "POLICY_FILE", &policy_filename))
349   {
350     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
351                 _
352                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
353                 "regexprofiler", "policy_file");
354     global_ret = GNUNET_SYSERR;
355     GNUNET_SCHEDULER_shutdown ();
356     return;
357   }
358
359   if (GNUNET_OK !=
360       GNUNET_CONFIGURATION_get_value_string (cfg, "REGEXPROFILER",
361                                              "REGEX_PREFIX", &regex_prefix))
362   {
363     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
364                 _
365                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
366                 "regexprofiler", "regex_prefix");
367     global_ret = GNUNET_SYSERR;
368     GNUNET_SCHEDULER_shutdown ();
369     return;
370   }
371
372   if (GNUNET_OK !=
373       GNUNET_CONFIGURATION_get_value_time (cfg, "REGEXPROFILER",
374                                            "REANNOUNCE_FREQ", &reannounce_freq))
375   {
376     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
377                 "reannounce_freq not given. Using 10 minutes.\n");
378     reannounce_freq =
379       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 10);
380
381   }
382     announce_delay =
383     GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
384                                    GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 600));
385
386   stats_handle = GNUNET_STATISTICS_create ("regexprofiler", cfg);
387
388   dht_handle = GNUNET_DHT_connect (cfg, 1);
389
390   if (NULL == dht_handle)
391   {
392     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
393                 "Could not acquire dht handle. Exiting.\n");
394     global_ret = GNUNET_SYSERR;
395     GNUNET_SCHEDULER_shutdown ();
396     return;
397   }
398
399   /* Read regexes from policy files */
400   if (0 == load_regexes (policy_filename, &regex))
401   {
402     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
403                 "Policy file %s contains no policies. Exiting.\n",
404                 policy_filename);
405     global_ret = GNUNET_SYSERR;
406     GNUNET_SCHEDULER_shutdown ();
407     return;
408   }
409
410   /* Announcing regexes from policy_filename */
411   GNUNET_asprintf (&rx_with_pfx, "%s(%s)", regex_prefix, regex);
412   GNUNET_free (regex);
413
414   keygen = GNUNET_CRYPTO_rsa_key_create_start (keyfile,
415                                                &key_generation_cb,
416                                                NULL);
417   GNUNET_free (keyfile);
418
419   /* Scheduled the task to clean up when shutdown is called */
420   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
421                                 NULL);
422 }
423
424
425 /**
426  * The main function of the regexprofiler service.
427  *
428  * @param argc number of arguments from the command line
429  * @param argv command line arguments
430  * @return 0 ok, 1 on error
431  */
432 int
433 main (int argc, char *const *argv)
434 {
435   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
436     GNUNET_GETOPT_OPTION_END
437   };
438
439   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
440     return 2;
441   return (GNUNET_OK ==
442           GNUNET_PROGRAM_run (argc, argv, "regexprofiler",
443                               gettext_noop
444                               ("Daemon to announce regular expressions for the peer using mesh."),
445                               options, &run, NULL)) ? global_ret : 1;
446 }
447
448
449 #ifdef LINUX
450 #include <malloc.h>
451
452 /**
453  * MINIMIZE heap size (way below 128k) since this process doesn't need much.
454  */
455 void __attribute__ ((constructor)) GNUNET_ARM_memory_init ()
456 {
457   mallopt (M_TRIM_THRESHOLD, 4 * 1024);
458   mallopt (M_TOP_PAD, 1 * 1024);
459   malloc_trim (0);
460 }
461 #endif
462
463
464 /* end of gnunet-daemon-regexprofiler.c */