fix for memory leaks
[oweals/gnunet.git] / src / sensor / gnunet-service-sensor.c
1 /*
2      This file is part of GNUnet.
3      (C) 
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 sensor/gnunet-service-sensor.c
23  * @brief sensor service implementation
24  * @author Omar Tarabai
25  */
26 #include <inttypes.h>
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "sensor.h"
30 #include "gnunet_statistics_service.h"
31
32 /**
33  * Minimum sensor execution interval (in seconds)
34  */
35 #define MIN_INTERVAL 30
36
37 /**
38  * Structure containing sensor definition
39  */
40 struct SensorInfo
41 {
42
43   /*
44    * Sensor name
45    */
46   char *name;
47
48   /*
49    * Path to definition file
50    */
51   char *def_file;
52
53   /*
54    * First part of version number
55    */
56   uint16_t version_major;
57
58   /*
59    * Second part of version number
60    */
61   uint16_t version_minor;
62
63   /*
64    * Sensor description
65    */
66   char *description;
67
68   /*
69    * Sensor currently enabled
70    */
71   int enabled;
72
73   /*
74    * Category under which the sensor falls (e.g. tcp, datastore)
75    */
76   char *category;
77
78   /*
79    * When does the sensor become active
80    */
81   struct GNUNET_TIME_Absolute *start_time;
82
83   /*
84    * When does the sensor expire
85    */
86   struct GNUNET_TIME_Absolute *end_time;
87
88   /*
89    * Time interval to collect sensor information (e.g. every 1 min)
90    */
91   struct GNUNET_TIME_Relative interval;
92
93   /*
94    * Lifetime of an information sample after which it is deleted from storage
95    */
96   struct GNUNET_TIME_Relative lifetime;
97
98   /*
99    * A set of required peer capabilities for the sensor to collect meaningful information (e.g. ipv6)
100    */
101   char *capabilities;
102
103   /*
104    * Either "gnunet-statistics" or external "process"
105    */
106   char *source;
107
108   /*
109    * Name of the GNUnet service that is the source for the gnunet-statistics entry
110    */
111   char *gnunet_stat_service;
112
113   /*
114    * Name of the gnunet-statistics entry
115    */
116   char *gnunet_stat_name;
117
118   /**
119    * Handle to statistics get request (OR GNUNET_SCHEDULER_NO_TASK)
120    */
121   struct GNUNET_STATISTICS_GetHandle *gnunet_stat_get_handle;
122
123   /*
124    * Name of the external process to be executed
125    */
126   char *ext_process;
127
128   /*
129    * Arguments to be passed to the external process
130    */
131   char *ext_args;
132
133   /*
134    * The output datatype to be expected
135    */
136   char *expected_datatype;
137
138   /*
139    * Peer-identity of peer running collection point
140    */
141   struct GNUNET_PeerIdentity *collection_point;
142
143   /*
144    * Time interval to send sensor information to collection point (e.g. every 30 mins)
145    */
146   struct GNUNET_TIME_Relative *collection_interval;
147
148   /*
149    * Flag specifying if value is to be communicated to the p2p network
150    */
151   int p2p_report;
152
153   /*
154    * Time interval to communicate value to the p2p network
155    */
156   struct GNUNET_TIME_Relative *p2p_interval;
157
158   /*
159    * Execution task (OR GNUNET_SCHEDULER_NO_TASK)
160    */
161   GNUNET_SCHEDULER_TaskIdentifier execution_task;
162
163   /*
164    * Is the sensor being executed
165    */
166   int running;
167
168 };
169
170 /**
171  * Our configuration.
172  */
173 static const struct GNUNET_CONFIGURATION_Handle *cfg;
174
175 /**
176  * Hashmap of loaded sensor definitions
177  */
178 struct GNUNET_CONTAINER_MultiHashMap *sensors;
179
180 /**
181  * Supported sources of sensor information
182  */
183 static const char *sources[] = { "gnunet-statistics", "process", NULL };
184
185 /**
186  * Supported datatypes of sensor information
187  */
188 static const char *datatypes[] = { "uint64", "double", "string", NULL };
189
190 /**
191  * Handle to statistics service
192  */
193 struct GNUNET_STATISTICS_Handle *statistics;
194
195 /**
196  * Remove sensor execution from scheduler
197  *
198  * @param cls unused
199  * @param key hash of sensor name, key to hashmap
200  * @param value a 'struct SensorInfo *'
201  * @return #GNUNET_YES if we should continue to
202  *         iterate,
203  *         #GNUNET_NO if not.
204  */
205 int destroy_sensor(void *cls,
206     const struct GNUNET_HashCode *key, void *value)
207 {
208   struct SensorInfo *sensorinfo = value;
209
210   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Destroying sensor `%s'\n", sensorinfo->name);
211   if(NULL != sensorinfo->gnunet_stat_get_handle)
212   {
213     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Canceling a statistics get request for sensor `%s'\n", sensorinfo->name);
214     GNUNET_STATISTICS_get_cancel(sensorinfo->gnunet_stat_get_handle);
215   }
216   if(GNUNET_SCHEDULER_NO_TASK != sensorinfo->execution_task)
217   {
218     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Unscheduling sensor `%s'\n", sensorinfo->name);
219     GNUNET_SCHEDULER_cancel(sensorinfo->execution_task);
220     sensorinfo->execution_task = GNUNET_SCHEDULER_NO_TASK;
221   }
222   if(NULL != sensorinfo->name)
223     GNUNET_free(sensorinfo->name);
224   if(NULL != sensorinfo->def_file)
225     GNUNET_free(sensorinfo->def_file);
226   if(NULL != sensorinfo->description)
227     GNUNET_free(sensorinfo->description);
228   if(NULL != sensorinfo->category)
229     GNUNET_free(sensorinfo->category);
230   if(NULL != sensorinfo->capabilities)
231     GNUNET_free(sensorinfo->capabilities);
232   if(NULL != sensorinfo->gnunet_stat_service)
233     GNUNET_free(sensorinfo->gnunet_stat_service);
234   if(NULL != sensorinfo->gnunet_stat_name)
235     GNUNET_free(sensorinfo->gnunet_stat_name);
236   if(NULL != sensorinfo->ext_process)
237     GNUNET_free(sensorinfo->ext_process);
238   if(NULL != sensorinfo->ext_args)
239     GNUNET_free(sensorinfo->ext_args);
240   GNUNET_free(sensorinfo);
241   return GNUNET_YES;
242 }
243
244 /**
245  * Task run during shutdown.
246  *
247  * @param cls unused
248  * @param tc unused
249  */
250 static void
251 shutdown_task (void *cls,
252                const struct GNUNET_SCHEDULER_TaskContext *tc)
253 {
254   GNUNET_CONTAINER_multihashmap_iterate(sensors, &destroy_sensor, NULL);
255   GNUNET_CONTAINER_multihashmap_destroy(sensors);
256   if(NULL != statistics)
257     GNUNET_STATISTICS_destroy(statistics, GNUNET_YES);
258   GNUNET_SCHEDULER_shutdown();
259 }
260
261
262 /**
263  * A client disconnected.  Remove all of its data structure entries.
264  *
265  * @param cls closure, NULL
266  * @param client identification of the client
267  */
268 static void
269 handle_client_disconnect (void *cls,
270                           struct GNUNET_SERVER_Client
271                           * client)
272 {
273 }
274
275 /**
276  * Parses a version number string into major and minor
277  *
278  * @param version full version string
279  * @param major pointer to parsed major value
280  * @param minor pointer to parsed minor value
281  * @return #GNUNET_OK if parsing went ok, #GNUNET_SYSERROR in case of error
282  */
283 static int
284 version_parse(char *version, uint16_t *major, uint16_t *minor)
285 {
286   int majorval = 0;
287   int minorval = 0;
288
289   for(; isdigit(*version); version++)
290   {
291     majorval *= 10;
292     majorval += *version - '0';
293   }
294   if(*version != '.')
295     return GNUNET_SYSERR;
296   version++;
297   for(; isdigit(*version); version++)
298   {
299     minorval *= 10;
300     minorval += *version - '0';
301   }
302   if(*version != 0)
303     return GNUNET_SYSERR;
304   *major = majorval;
305   *minor = minorval;
306
307   return GNUNET_OK;
308 }
309
310 /**
311  * Load sensor definition from configuration
312  *
313  * @param cfg configuration handle
314  * @param sectionname configuration section containing definition
315  */
316 static struct SensorInfo *
317 load_sensor_from_cfg(struct GNUNET_CONFIGURATION_Handle *cfg, const char *sectionname)
318 {
319   struct SensorInfo *sensor;
320   char *version_str;
321   char *starttime_str;
322   char *endtime_str;
323   unsigned long long time_sec;
324
325   sensor = GNUNET_new(struct SensorInfo);
326   //name
327   sensor->name = GNUNET_strdup(sectionname);
328   //version
329   if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "VERSION", &version_str))
330   {
331     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor version\n"));
332     GNUNET_free(sensor);
333     return NULL;
334   }
335   if(GNUNET_OK != version_parse(version_str, &(sensor->version_major), &(sensor->version_minor)))
336   {
337     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Invalid sensor version number, format should be major.minor\n"));
338     GNUNET_free(sensor);
339     GNUNET_free(version_str);
340     return NULL;
341   }
342   GNUNET_free(version_str);
343   //description
344   GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "DESCRIPTION", &sensor->description);
345   //category
346   if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "CATEGORY", &sensor->category) ||
347         NULL == sensor->category)
348   {
349     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor category\n"));
350     GNUNET_free(sensor);
351     return NULL;
352   }
353   //enabled
354   if(GNUNET_NO == GNUNET_CONFIGURATION_get_value_yesno(cfg, sectionname, "ENABLED"))
355     sensor->enabled = GNUNET_NO;
356   else
357     sensor->enabled = GNUNET_YES;
358   //start time
359   sensor->start_time = NULL;
360   if(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "START_TIME", &starttime_str))
361   {
362     GNUNET_STRINGS_fancy_time_to_absolute(starttime_str, sensor->start_time);
363     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Start time loaded: `%s'. Parsed: %d\n", starttime_str, (NULL != sensor->start_time));
364     GNUNET_free(starttime_str);
365   }
366   //end time
367   sensor->end_time = NULL;
368   if(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "END_TIME", &endtime_str))
369   {
370     GNUNET_STRINGS_fancy_time_to_absolute(endtime_str, sensor->end_time);
371     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "End time loaded: `%s'. Parsed: %d\n", endtime_str, (NULL != sensor->end_time));
372     GNUNET_free(endtime_str);
373   }
374   //interval
375   if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, sectionname, "INTERVAL", &time_sec))
376   {
377     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor run interval\n"));
378     GNUNET_free(sensor);
379     return NULL;
380   }
381   if(time_sec < MIN_INTERVAL)
382   {
383     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Sensor run interval too low (%" PRIu64 " < %d)\n"),
384         time_sec, MIN_INTERVAL);
385     GNUNET_free(sensor);
386     return NULL;
387   }
388   sensor->interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, time_sec);
389   //lifetime
390   if(GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, sectionname, "LIFETIME", &time_sec))
391   {
392     sensor->lifetime = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, time_sec);
393   }
394   else
395     sensor->lifetime = GNUNET_TIME_UNIT_FOREVER_REL;
396   //capabilities TODO
397   //source
398   if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_choice(cfg, sectionname, "SOURCE", sources, (const char **)&sensor->source))
399   {
400     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor source\n"));
401     GNUNET_free(sensor);
402     return NULL;
403   }
404   if(sources[0] == sensor->source) //gnunet-statistics
405   {
406     if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "GNUNET_STAT_SERVICE", &sensor->gnunet_stat_service) ||
407         GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "GNUNET_STAT_NAME", &sensor->gnunet_stat_name))
408     {
409       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor gnunet-statistics source information\n"));
410       GNUNET_free(sensor);
411       return NULL;
412     }
413     sensor->gnunet_stat_get_handle = NULL;
414   }
415   else if(sources[1] == sensor->source) //process
416   {
417     if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "EXT_PROCESS", &sensor->ext_process))
418     {
419       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor process name\n"));
420       GNUNET_free(sensor);
421       return NULL;
422     }
423     GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "EXT_ARGS", &sensor->ext_args);
424   }
425   //expected datatype
426   if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_choice(cfg, sectionname, "EXPECTED_DATATYPE", datatypes, (const char **)&sensor->expected_datatype))
427   {
428     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor expected datatype\n"));
429     GNUNET_free(sensor);
430     return NULL;
431   }
432   if(sources[0] == sensor->source && datatypes[0] != sensor->expected_datatype)
433   {
434     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Invalid expected datatype, gnunet-statistics returns uint64 values\n"));
435     GNUNET_free(sensor);
436     return NULL;
437   }
438   //TODO: reporting mechanism
439   //execution task
440   sensor->execution_task = GNUNET_SCHEDULER_NO_TASK;
441   //running
442   sensor->running = GNUNET_NO;
443
444   return sensor;
445 }
446
447 /**
448  * Load sensor definition from file
449  *
450  * @param filename full path to file containing sensor definition
451  */
452 static struct SensorInfo *
453 load_sensor_from_file(const char *filename)
454 {
455   struct GNUNET_CONFIGURATION_Handle *sensorcfg;
456   const char *filebasename;
457   struct SensorInfo *sensor;
458
459   //test file
460   if(GNUNET_YES != GNUNET_DISK_file_test(filename))
461   {
462     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Failed to access sensor file: %s\n"), filename);
463     return NULL;
464   }
465   //load file as configuration
466   sensorcfg = GNUNET_CONFIGURATION_create();
467   if(GNUNET_SYSERR == GNUNET_CONFIGURATION_parse(sensorcfg, filename))
468   {
469     GNUNET_CONFIGURATION_destroy(sensorcfg);
470     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Failed to load sensor definition: %s\n"), filename);
471     return NULL;
472   }
473   //configuration section should be the same as filename
474   filebasename = GNUNET_STRINGS_get_short_name(filename);
475   sensor = load_sensor_from_cfg(sensorcfg, filebasename);
476   sensor->def_file = GNUNET_strdup(filename);
477
478   GNUNET_CONFIGURATION_destroy(sensorcfg);
479
480   return sensor;
481 }
482
483 /**
484  * Compares version numbers of two sensors
485  *
486  * @param s1 first sensor
487  * @param s2 second sensor
488  * @return 1: s1 > s2, 0: s1 == s2, -1: s1 < s2
489  */
490 static int
491 sensor_version_compare(struct SensorInfo *s1, struct SensorInfo *s2)
492 {
493   if(s1->version_major == s2->version_major)
494     return (s1->version_minor < s2->version_minor) ? -1 : (s1->version_minor > s2->version_minor);
495   else
496     return (s1->version_major < s2->version_major) ? -1 : (s1->version_major > s2->version_major);
497 }
498
499 /**
500  * Adds a new sensor to given hashmap.
501  * If the same name exist, compares versions and update if old.
502  *
503  * @param sensor Sensor structure to add
504  * @param map Hashmap to add to
505  * @return #GNUNET_YES if added, #GNUNET_NO if not added which is not necessarily an error
506  */
507 static int
508 add_sensor_to_hashmap(struct SensorInfo *sensor, struct GNUNET_CONTAINER_MultiHashMap *map)
509 {
510   struct GNUNET_HashCode key;
511   struct SensorInfo *existing;
512
513   GNUNET_CRYPTO_hash(sensor->name, strlen(sensor->name), &key);
514   existing = GNUNET_CONTAINER_multihashmap_get(map, &key);
515   if(NULL != existing) //sensor with same name already exists
516   {
517     if(sensor_version_compare(existing, sensor) >= 0) //same or newer version already exist
518     {
519       GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Sensor `%s' already exists with same or newer version\n"), sensor->name);
520       return GNUNET_NO;
521     }
522     else
523     {
524       GNUNET_CONTAINER_multihashmap_remove(map, &key, existing); //remove the old version
525       GNUNET_free(existing);
526       GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Upgrading sensor `%s' to a newer version\n"), sensor->name);
527     }
528   }
529   if(GNUNET_SYSERR == GNUNET_CONTAINER_multihashmap_put(map, &key, sensor, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
530   {
531     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error adding new sensor `%s' to global hashmap, this should not happen\n"), sensor->name);
532     return GNUNET_NO;
533   }
534
535   return GNUNET_YES;
536 }
537
538 /**
539  * Iterating over files in sensors directory
540  *
541  * @param cls closure
542  * @param filename complete filename (absolute path)
543  * @return #GNUNET_OK to continue to iterate
544  */
545 static int
546 reload_sensors_dir_cb(void *cls, const char *filename)
547 {
548   struct SensorInfo *sensor;
549
550   if(GNUNET_YES != GNUNET_DISK_file_test(filename))
551     return GNUNET_OK;
552   sensor = load_sensor_from_file(filename);
553   if(NULL == sensor)
554   {
555     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error loading sensor from file: %s\n"), filename);
556     return GNUNET_OK;
557   }
558   if(GNUNET_YES == add_sensor_to_hashmap(sensor, sensors))
559     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, _("Sensor `%s' added to global hashmap\n"), sensor->name);
560   else
561     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, ("Could not add sensor `%s' to global hashmap\n"), sensor->name);
562
563   return GNUNET_OK;
564 }
565
566 /*
567  * Get path to the directory containing the sensor definition files
568  *
569  * @return sensor files directory
570  */
571 static char *
572 get_sensor_dir()
573 {
574   char* datadir;
575   char* sensordir;
576
577   datadir = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_DATADIR);
578   GNUNET_asprintf(&sensordir, "%ssensors%s",
579       datadir, DIR_SEPARATOR_STR);
580   GNUNET_free(datadir);
581
582   return sensordir;
583 }
584
585 /**
586  * Reads sensor definitions from data files
587  *
588  */
589 static void
590 reload_sensors()
591 {
592   char* sensordir;
593
594   sensordir = get_sensor_dir();
595   GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Reloading sensor definitions from directory `%s'\n"), sensordir);
596   GNUNET_assert(GNUNET_YES == GNUNET_DISK_directory_test(sensordir, GNUNET_YES));
597
598   //read all files in sensors directory
599   GNUNET_DISK_directory_scan(sensordir, &reload_sensors_dir_cb, NULL);
600   GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Loaded %d sensors from directory `%s'\n"),
601       GNUNET_CONTAINER_multihashmap_size(sensors), sensordir);
602   GNUNET_free(sensordir);
603 }
604
605 /**
606  * Creates a structure with basic sensor info to be sent to a client
607  *
608  * @param sensor sensor information
609  * @return message ready to be sent to client
610  */
611 static struct SensorInfoMessage *
612 create_sensor_info_msg(struct SensorInfo *sensor)
613 {
614   struct SensorInfoMessage *msg;
615   uint16_t len;
616   size_t name_len;
617   size_t desc_len;
618   char *str_ptr;
619
620   name_len = strlen(sensor->name);
621   if(NULL == sensor->description)
622     desc_len = 0;
623   else
624     desc_len = strlen(sensor->description) + 1;
625   len = 0;
626   len += sizeof(struct SensorInfoMessage);
627   len += name_len;
628   len += desc_len;
629   msg = GNUNET_malloc(len);
630   msg->header.size = htons(len);
631   msg->header.type = htons(GNUNET_MESSAGE_TYPE_SENSOR_INFO);
632   msg->name_len = htons(name_len);
633   msg->description_len = htons(desc_len);
634   msg->version_major = htons(sensor->version_major);
635   msg->version_minor = htons(sensor->version_minor);
636   str_ptr = (char*) &msg[1];
637   memcpy(str_ptr, sensor->name, name_len);
638   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending sensor name (%d): %.*s\n",
639         name_len, name_len, str_ptr);
640   str_ptr += name_len;
641   memcpy(str_ptr, sensor->description, desc_len);
642   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending sensor description (%d): %.*s\n",
643           desc_len, desc_len, str_ptr);
644
645   return msg;
646 }
647
648 /**
649  * Handle GET SENSOR message.
650  *
651  * @param cls closure
652  * @param client identification of the client
653  * @param message the actual message
654  */
655 static void
656 handle_get_sensor (void *cls, struct GNUNET_SERVER_Client *client,
657             const struct GNUNET_MessageHeader *message)
658 {
659   struct GNUNET_SERVER_TransmitContext *tc;
660   char *sensorname;
661   size_t sensorname_len;
662   struct GNUNET_HashCode key;
663   struct SensorInfo *sensorinfo;
664   struct SensorInfoMessage *msg;
665
666   sensorname = (char *)&message[1];
667   sensorname_len = ntohs(message->size) - sizeof(struct GNUNET_MessageHeader);
668   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "`%s' message received for sensor (%d) `%.*s'\n",
669               "GET SENSOR", sensorname_len, sensorname_len, sensorname);
670   tc = GNUNET_SERVER_transmit_context_create (client);
671   GNUNET_CRYPTO_hash(sensorname, sensorname_len, &key);
672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Created key hash for requested sensor\n");
673   sensorinfo = (struct SensorInfo *)GNUNET_CONTAINER_multihashmap_get(sensors, &key);
674   if(NULL != sensorinfo)
675   {
676     msg = create_sensor_info_msg(sensorinfo);
677     GNUNET_SERVER_transmit_context_append_message(tc, (struct GNUNET_MessageHeader *)msg);
678     GNUNET_free(msg);
679   }
680   else
681     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Requested sensor `%.*s' was not found\n",
682         sensorname_len, sensorname);
683   GNUNET_SERVER_transmit_context_append_data(tc, NULL, 0, GNUNET_MESSAGE_TYPE_SENSOR_END);
684   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
685 }
686
687 /**
688  * Iterator for sensors and adds them to transmit context
689  *
690  * @param cls a 'struct GNUNET_SERVER_TransmitContext *'
691  * @param key hash of sensor name, key to hashmap
692  * @param value a 'struct SensorInfo *'
693  */
694 int add_sensor_to_tc(void *cls,
695     const struct GNUNET_HashCode *key, void *value)
696 {
697   struct GNUNET_SERVER_TransmitContext *tc = cls;
698   struct SensorInfo *sensorinfo = value;
699   struct SensorInfoMessage *msg;
700
701   msg = create_sensor_info_msg(sensorinfo);
702   GNUNET_SERVER_transmit_context_append_message(tc, (struct GNUNET_MessageHeader *)msg);
703
704   GNUNET_free(msg);
705
706   return GNUNET_YES;
707 }
708
709 /**
710  * Handle GET ALL SENSORS message.
711  *
712  * @param cls closure
713  * @param client identification of the client
714  * @param message the actual message
715  */
716 static void
717 handle_get_all_sensors (void *cls, struct GNUNET_SERVER_Client *client,
718             const struct GNUNET_MessageHeader *message)
719 {
720   struct GNUNET_SERVER_TransmitContext *tc;
721
722   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "`%s' message received.\n",
723                 "GET ALL SENSOR");
724   tc = GNUNET_SERVER_transmit_context_create (client);
725   GNUNET_CONTAINER_multihashmap_iterate(sensors, &add_sensor_to_tc, tc);
726   GNUNET_SERVER_transmit_context_append_data(tc, NULL, 0, GNUNET_MESSAGE_TYPE_SENSOR_END);
727   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
728 }
729
730 /**
731  * Do a series of checks to determine if sensor should execute
732  *
733  * @return #GNUNET_YES / #GNUNET_NO
734  */
735 static int
736 should_run_sensor(struct SensorInfo *sensorinfo)
737 {
738   //FIXME: some checks should disable the sensor (e.g. expired)
739   struct GNUNET_TIME_Absolute now;
740
741   if(GNUNET_NO == sensorinfo->enabled)
742   {
743     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Sensor `%s' is disabled, will not run\n", sensorinfo->name);
744     return GNUNET_NO;
745   }
746   now = GNUNET_TIME_absolute_get();
747   if(NULL != sensorinfo->start_time
748       && now.abs_value_us < sensorinfo->start_time->abs_value_us)
749   {
750     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Start time for sensor `%s' not reached yet, will not run\n", sensorinfo->name);
751     return GNUNET_NO;
752   }
753   if(NULL != sensorinfo->end_time
754       && now.abs_value_us >= sensorinfo->end_time->abs_value_us)
755   {
756     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "End time for sensor `%s' passed, will not run\n", sensorinfo->name);
757     return GNUNET_NO;
758   }
759   return GNUNET_YES;
760 }
761
762 /**
763  * Callback function to process statistic values
764  *
765  * @param cls 'struct SensorInfo *'
766  * @param subsystem name of subsystem that created the statistic
767  * @param name the name of the datum
768  * @param value the current value
769  * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
770  * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
771  */
772 int sensor_statistics_iterator (void *cls,
773     const char *subsystem,
774     const char *name,
775     uint64_t value,
776     int is_persistent)
777 {
778   struct SensorInfo *sensorinfo = cls;
779
780   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received a value for sensor `%s': %" PRIu64 "\n", sensorinfo->name, value);
781   return GNUNET_OK;
782 }
783
784 /**
785  * Continuation called after sensor gets all gnunet statistics values
786  *
787  * @param cls 'struct SensorInfo *'
788  * @param success #GNUNET_OK if statistics were
789  *        successfully obtained, #GNUNET_SYSERR if not.
790  */
791 void end_sensor_run_stat (void *cls, int success)
792 {
793   struct SensorInfo *sensorinfo = cls;
794
795   sensorinfo->gnunet_stat_get_handle = NULL;
796   sensorinfo->running = GNUNET_NO;
797 }
798
799 /**
800  * Callback for output of executed sensor process
801  *
802  * @param cls 'struct SensorInfo *'
803  * @param line line of output from a command, NULL for the end
804  */
805 void sensor_process_callback (void *cls, const char *line)
806 {
807   struct SensorInfo *sensorinfo = cls;
808
809   if(NULL == line)
810   {
811     sensorinfo->running = GNUNET_NO;
812     return;
813   }
814   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received a value for sensor `%s': %s\n", sensorinfo->name, line);
815 }
816
817 /**
818  * Actual execution of a sensor
819  *
820  * @param cls 'struct SensorInfo'
821  * @param tc unsed
822  */
823 void
824 sensor_run (void *cls,
825     const struct GNUNET_SCHEDULER_TaskContext * tc)
826 {
827   struct SensorInfo *sensorinfo = cls;
828   int check_result;
829   char *sensors_dir;
830   char *process_path;
831
832   sensorinfo->execution_task = GNUNET_SCHEDULER_add_delayed(sensorinfo->interval, &sensor_run, sensorinfo);
833   if(GNUNET_YES == sensorinfo->running) //FIXME: should we try to kill?
834   {
835     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sensor `%s' running for too long, will try again next interval\n", sensorinfo->name);
836     return;
837   }
838   if(GNUNET_NO == should_run_sensor(sensorinfo))
839     return;
840   sensorinfo->running = GNUNET_YES;
841   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Starting the execution of sensor `%s'\n", sensorinfo->name);
842   if(sources[0] == sensorinfo->source) //gnunet-statistics
843   {
844     if(NULL == statistics)
845     {
846       statistics = GNUNET_STATISTICS_create("sensor", cfg);
847     }
848     sensorinfo->gnunet_stat_get_handle = GNUNET_STATISTICS_get(statistics,
849         sensorinfo->gnunet_stat_service,
850         sensorinfo->gnunet_stat_name,
851         sensorinfo->interval, //try to get values only for the interval of the sensor
852         &end_sensor_run_stat,
853         &sensor_statistics_iterator,
854         sensorinfo);
855   }
856   else if(sources[1] == sensorinfo->source)
857   {
858     //FIXME: break execution if process is a path
859     //check if the process exists in $PATH
860     process_path = GNUNET_strdup(sensorinfo->ext_process);
861     check_result =
862         GNUNET_OS_check_helper_binary(sensorinfo->ext_process, GNUNET_NO, NULL); //search in $PATH
863     if(GNUNET_SYSERR == check_result)
864     {
865       //search in sensor directory
866       sensors_dir = get_sensor_dir();
867       GNUNET_free(process_path);
868       GNUNET_asprintf(&process_path, "%s%s-files%s%s",
869           sensors_dir,
870           sensorinfo->name,
871           DIR_SEPARATOR_STR,
872           sensorinfo->ext_process);
873       GNUNET_free(sensors_dir);
874       check_result =
875         GNUNET_OS_check_helper_binary(process_path, GNUNET_NO, NULL);
876     }
877     if(GNUNET_SYSERR == check_result)
878     {
879       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Sensor `%s' process `%s' problem: binary doesn't exist or not executable\n",
880           sensorinfo->name,
881           sensorinfo->ext_process);
882       //FIXME: disable sensor here?
883       sensorinfo->running = GNUNET_NO;
884       GNUNET_free(process_path);
885       return;
886     }
887     GNUNET_OS_command_run(&sensor_process_callback,
888         sensorinfo,
889         GNUNET_TIME_UNIT_FOREVER_REL,
890         process_path,
891         sensorinfo->ext_process,
892         sensorinfo->ext_args,
893         NULL);
894     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Process started for sensor `%s'\n", sensorinfo->name);
895   }
896   else
897   {
898     sensorinfo->running = GNUNET_NO;
899     GNUNET_break(0); //shouldn't happen
900   }
901 }
902
903 /**
904  * Starts the execution of a sensor
905  *
906  * @param cls unused
907  * @param key hash of sensor name, key to hashmap (unused)
908  * @param value a 'struct SensorInfo *'
909  * @return #GNUNET_YES if we should continue to
910  *         iterate,
911  *         #GNUNET_NO if not.
912  */
913 int schedule_sensor(void *cls,
914     const struct GNUNET_HashCode *key, void *value)
915 {
916   struct SensorInfo *sensorinfo = value;
917
918   if(GNUNET_NO == should_run_sensor(sensorinfo))
919     return GNUNET_YES;
920   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling sensor `%s' to run after %" PRIu64 " microseconds\n",
921       sensorinfo->name, sensorinfo->interval.rel_value_us);
922   if(GNUNET_SCHEDULER_NO_TASK != sensorinfo->execution_task)
923   {
924     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Sensor `%s' execution task already set, this should not happen\n", sensorinfo->name);
925     return GNUNET_NO;
926   }
927   sensorinfo->execution_task = GNUNET_SCHEDULER_add_delayed(sensorinfo->interval, &sensor_run, sensorinfo);
928   return GNUNET_YES;
929 }
930
931 /**
932  * Starts the execution of all enabled sensors
933  *
934  */
935 static void
936 schedule_all_sensors()
937 {
938   GNUNET_CONTAINER_multihashmap_iterate(sensors, &schedule_sensor, NULL);
939 }
940
941 /**
942  * Process statistics requests.
943  *
944  * @param cls closure
945  * @param server the initialized server
946  * @param c configuration to use
947  */
948 static void
949 run (void *cls,
950      struct GNUNET_SERVER_Handle *server,
951      const struct GNUNET_CONFIGURATION_Handle *c)
952 {
953   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
954     {&handle_get_sensor, NULL, GNUNET_MESSAGE_TYPE_SENSOR_GET,
955      0},
956     {&handle_get_all_sensors, NULL, GNUNET_MESSAGE_TYPE_SENSOR_GETALL,
957      sizeof (struct GNUNET_MessageHeader)},
958     {NULL, NULL, 0, 0}
959   };
960
961   cfg = c;
962   sensors = GNUNET_CONTAINER_multihashmap_create(10, GNUNET_NO);
963   reload_sensors();
964   schedule_all_sensors();
965   GNUNET_SERVER_add_handlers (server, handlers);
966   GNUNET_SERVER_disconnect_notify (server, 
967                                    &handle_client_disconnect,
968                                    NULL);
969   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
970                                 &shutdown_task,
971                                 NULL);
972 }
973
974
975 /**
976  * The main function for the sensor service.
977  *
978  * @param argc number of arguments from the command line
979  * @param argv command line arguments
980  * @return 0 ok, 1 on error
981  */
982 int
983 main (int argc, char *const *argv)
984 {
985   return (GNUNET_OK ==
986           GNUNET_SERVICE_run (argc,
987                               argv,
988                               "sensor",
989                               GNUNET_SERVICE_OPTION_NONE,
990                               &run, NULL)) ? 0 : 1;
991 }
992
993 /* end of gnunet-service-sensor.c */