- add disk scan
[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  * Periodically reannounce regex.
63  */
64 static GNUNET_SCHEDULER_TaskIdentifier reannounce_task;
65
66 /**
67  * What's the maximum reannounce period.
68  */
69 static struct GNUNET_TIME_Relative reannounce_period_max;
70
71 /**
72  * Maximal path compression length for regex announcing.
73  */
74 static unsigned long long max_path_compression;
75
76 /**
77  * Name of the file containing policies that this peer should announce. One
78  * policy per line.
79  */
80 static char * policy_filename;
81
82 /**
83  * Prefix to add before every regex we're announcing.
84  */
85 static char * regex_prefix;
86
87 /**
88  * Regex with prefix.
89  */
90 static char *rx_with_pfx;
91
92 /**
93  * How many put rounds should we do.
94  */
95 static unsigned int rounds = 5;
96
97
98 /**
99  * Task run during shutdown.
100  *
101  * @param cls unused
102  * @param tc unused
103  */
104 static void
105 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
106 {
107   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
108
109   if (NULL != announce_handle)
110   {
111     GNUNET_REGEX_announce_cancel (announce_handle);
112     announce_handle = NULL;
113   }
114
115   if (NULL != dht_handle)
116   {
117     GNUNET_DHT_disconnect (dht_handle);
118     dht_handle = NULL;
119   }
120
121   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
122               "Daemon for %s shutting down\n",
123               policy_filename);
124 }
125
126
127 /**
128  * Announce a previously announced regex re-using cached data.
129  * 
130  * @param cls Closure (regex to announce if needed).
131  * @param tc TaskContext.
132  */
133 static void
134 reannounce_regex (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
135 {
136   struct GNUNET_PeerIdentity id;
137   struct GNUNET_TIME_Relative random_delay;
138   char *regex = cls;
139
140   reannounce_task = GNUNET_SCHEDULER_NO_TASK;
141   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
142   {
143     GNUNET_free (regex);
144     return;
145   }
146
147   if (0 == rounds--)
148   {
149     global_ret = 0;
150     GNUNET_SCHEDULER_shutdown ();
151     GNUNET_free (regex);
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     memset (&id, 0, sizeof (struct GNUNET_PeerIdentity));
162     announce_handle = GNUNET_REGEX_announce (dht_handle,
163                                             &id,
164                                             regex,
165                                             (unsigned int) max_path_compression,
166                                             stats_handle);
167   }
168   else
169   {
170     GNUNET_assert (NULL != announce_handle);
171     GNUNET_REGEX_reannounce (announce_handle);
172   }
173
174   random_delay =
175     GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
176                                    GNUNET_CRYPTO_random_u32 (
177                                      GNUNET_CRYPTO_QUALITY_WEAK,
178                                      reannounce_period_max.rel_value));
179   reannounce_task = GNUNET_SCHEDULER_add_delayed (random_delay,
180                                                   &reannounce_regex, cls);
181 }
182
183
184 /**
185  * Announce the given regular expression using regex and the path compression
186  * length read from config.
187  *
188  * @param regex regular expression to announce on this peer's mesh.
189  */
190 static void
191 announce_regex (const char * regex)
192 {
193   char *copy;
194
195   if (NULL == regex || 0 == strlen (regex))
196   {
197     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot announce empty regex\n");
198     return;
199   }
200
201   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
202               "Daemon for %s starting\n",
203               policy_filename);
204   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == reannounce_task);
205   copy = GNUNET_strdup (regex);
206   reannounce_task = GNUNET_SCHEDULER_add_now (reannounce_regex, (void *) copy);
207 }
208
209
210 /**
211  * Load regular expressions from filename into 'rxes' array. Array needs to be freed.
212  *
213  * @param filename filename of the file containing the regexes, one per line.
214  * @param rx string with the union of all regular expressions.
215  *
216  * @return number of regular expressions read from filename and in rxes array.
217  * FIXME use load regex lib function
218  */
219 static unsigned int
220 load_regexes (const char *filename, char **rx)
221 {
222   char *data;
223   char *buf;
224   uint64_t filesize;
225   unsigned int offset;
226   unsigned int rx_cnt;
227
228   if (GNUNET_YES != GNUNET_DISK_file_test (policy_filename))
229   {
230     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
231                 "Could not find policy file %s\n", policy_filename);
232     return 0;
233   }
234   if (GNUNET_OK != GNUNET_DISK_file_size (policy_filename, &filesize, GNUNET_YES, GNUNET_YES))
235     filesize = 0;
236   if (0 == filesize)
237   {
238     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Policy file %s is empty.\n", policy_filename);
239     return 0;
240   }
241   data = GNUNET_malloc (filesize);
242   if (filesize != GNUNET_DISK_fn_read (policy_filename, data, filesize))
243   {
244     GNUNET_free (data);
245     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not read policy file %s.\n",
246                 policy_filename);
247     return 0;
248   }
249   buf = data;
250   offset = 0;
251   rx_cnt = 0;
252   while (offset < (filesize - 1))
253   {
254     offset++;
255     if ((data[offset] == '\n') && (buf != &data[offset]))
256     {
257       data[offset] = '|';
258       buf = &data[offset + 1];
259       rx_cnt++;
260     }
261     else if ((data[offset] == '\n') || (data[offset] == '\0'))
262       buf = &data[offset + 1];
263   }
264   data[offset] = '\0';
265   *rx = data;
266
267   return rx_cnt;
268 }
269
270 /**
271  * Scan through the policy_dir looking for the n-th filename.
272  *
273  * @param cls Closure (target number n).
274  * @param filename complete filename (absolute path).
275  * @return GNUNET_OK to continue to iterate,
276  *  GNUNET_NO to stop when found
277  */
278 static int
279 scan (void *cls, const char *filename)
280 {
281   long n = (long) cls;
282   static long c = 0;
283
284   if (c == n)
285   {
286     policy_filename = GNUNET_strdup (filename);
287     return GNUNET_NO;
288   }
289   c++;
290   return GNUNET_OK;
291 }
292
293
294 /**
295  * @brief Main function that will be run by the scheduler.
296  *
297  * @param cls closure
298  * @param args remaining command-line arguments
299  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
300  * @param cfg_ configuration
301  */
302 static void
303 run (void *cls, char *const *args GNUNET_UNUSED,
304      const char *cfgfile GNUNET_UNUSED,
305      const struct GNUNET_CONFIGURATION_Handle *cfg_)
306 {
307   char *regex = NULL;
308   char *policy_dir;
309   long long unsigned int peer_id;
310
311   cfg = cfg_;
312
313   if (GNUNET_OK !=
314       GNUNET_CONFIGURATION_get_value_number (cfg, "REGEXPROFILER",
315                                              "MAX_PATH_COMPRESSION",
316                                              &max_path_compression))
317   {
318     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
319                 _
320                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
321                 "regexprofiler", "max_path_compression");
322     global_ret = GNUNET_SYSERR;
323     GNUNET_SCHEDULER_shutdown ();
324     return;
325   }
326   if (GNUNET_OK !=
327       GNUNET_CONFIGURATION_get_value_string (cfg, "REGEXPROFILER",
328                                              "POLICY_DIR", &policy_dir))
329   {
330     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
331                 _
332                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
333                 "regexprofiler", "policy_dir");
334     global_ret = GNUNET_SYSERR;
335     GNUNET_SCHEDULER_shutdown ();
336     return;
337   }
338   if (GNUNET_OK !=
339       GNUNET_CONFIGURATION_get_value_number (cfg, "TESTBED",
340                                              "PEERID", &peer_id))
341   {
342     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
343                 _
344                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
345                 "regexprofiler", "policy_file");
346     global_ret = GNUNET_SYSERR;
347     GNUNET_SCHEDULER_shutdown ();
348     return;
349   }
350
351   if (GNUNET_OK !=
352       GNUNET_CONFIGURATION_get_value_string (cfg, "REGEXPROFILER",
353                                              "REGEX_PREFIX", &regex_prefix))
354   {
355     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
356                 _
357                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
358                 "regexprofiler", "regex_prefix");
359     global_ret = GNUNET_SYSERR;
360     GNUNET_SCHEDULER_shutdown ();
361     return;
362   }
363
364   if (GNUNET_OK !=
365       GNUNET_CONFIGURATION_get_value_time (cfg, "REGEXPROFILER",
366                                            "REANNOUNCE_PERIOD_MAX",
367                                            &reannounce_period_max))
368   {
369     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
370                 "reannounce_period_max not given. Using 10 minutes.\n");
371     reannounce_period_max =
372       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 10);
373   }
374
375   stats_handle = GNUNET_STATISTICS_create ("regexprofiler", cfg);
376
377   dht_handle = GNUNET_DHT_connect (cfg, 1);
378
379   if (NULL == dht_handle)
380   {
381     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
382                 "Could not acquire dht handle. Exiting.\n");
383     global_ret = GNUNET_SYSERR;
384     GNUNET_SCHEDULER_shutdown ();
385     return;
386   }
387
388   /* Read regexes from policy files */
389   GNUNET_assert (-1 != GNUNET_DISK_directory_scan (policy_dir, &scan, peer_id));
390   if (0 == load_regexes (policy_filename, &regex))
391   {
392     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
393                 "Policy file %s contains no policies. Exiting.\n",
394                 policy_filename);
395     global_ret = GNUNET_SYSERR;
396     GNUNET_SCHEDULER_shutdown ();
397     return;
398   }
399
400   /* Announcing regexes from policy_filename */
401   GNUNET_asprintf (&rx_with_pfx, "%s(%s)", regex_prefix, regex);
402   announce_regex (rx_with_pfx);
403   GNUNET_free (regex);
404   GNUNET_free (rx_with_pfx);
405
406   /* Scheduled the task to clean up when shutdown is called */
407   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
408                                 NULL);
409 }
410
411
412 /**
413  * The main function of the regexprofiler service.
414  *
415  * @param argc number of arguments from the command line
416  * @param argv command line arguments
417  * @return 0 ok, 1 on error
418  */
419 int
420 main (int argc, char *const *argv)
421 {
422   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
423     GNUNET_GETOPT_OPTION_END
424   };
425
426   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
427     return 2;
428   return (GNUNET_OK ==
429           GNUNET_PROGRAM_run (argc, argv, "regexprofiler",
430                               gettext_noop
431                               ("Daemon to announce regular expressions for the peer using mesh."),
432                               options, &run, NULL)) ? global_ret : 1;
433 }
434
435
436 #ifdef LINUX
437 #include <malloc.h>
438
439 /**
440  * MINIMIZE heap size (way below 128k) since this process doesn't need much.
441  */
442 void __attribute__ ((constructor)) GNUNET_ARM_memory_init ()
443 {
444   mallopt (M_TRIM_THRESHOLD, 4 * 1024);
445   mallopt (M_TOP_PAD, 1 * 1024);
446   malloc_trim (0);
447 }
448 #endif
449
450
451 /* end of gnunet-daemon-regexprofiler.c */