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