src/rps/rps.conf
src/secretsharing/Makefile
src/secretsharing/secretsharing.conf
-src/sensor/Makefile
-src/sensor/sensor.conf
-src/sensordashboard/Makefile
-src/sensordashboard/sensordashboard.conf
src/scalarproduct/Makefile
src/scalarproduct/scalarproduct.conf
src/set/Makefile
TESTBED = testbed
CONSENSUS = consensus
SECRETSHARING = secretsharing
- SENSOR = sensor
- SENSORDASHBOARD = sensordashboard
endif
if HAVE_EXPERIMENTAL
rps \
social \
$(CONSENSUS) \
- $(SECRETSHARING) \
- $(SENSOR) \
- $(SENSORDASHBOARD)
+ $(SECRETSHARING)
endif
if HAVE_REST
+++ /dev/null
-# This Makefile.am is in the public domain
-AM_CPPFLAGS = -I$(top_srcdir)/src/include
-
-pkgcfgdir= $(pkgdatadir)/config.d/
-
-libexecdir= $(pkglibdir)/libexec/
-
-plugindir = $(libdir)/gnunet
-
-dist_pkgcfg_DATA = \
- sensor.conf
-
-if MINGW
- WINFLAGS = -Wl,--no-undefined -Wl,--export-all-symbols
-endif
-
-if USE_COVERAGE
- AM_CFLAGS = -fprofile-arcs -ftest-coverage
-endif
-
-bin_PROGRAMS = \
- gnunet-sensor
-
-noinst_PROGRAMS = \
- gnunet-sensor-profiler \
- perf-pow-sign
-
-libexec_PROGRAMS = \
- gnunet-service-sensor
-
-lib_LTLIBRARIES = \
- libgnunetsensor.la \
- libgnunetsensorutil.la
-
-gnunet_sensor_SOURCES = \
- gnunet-sensor.c
-gnunet_sensor_LDADD = \
- $(top_builddir)/src/util/libgnunetutil.la \
- libgnunetsensor.la \
- $(GN_LIBINTL)
-
-gnunet_service_sensor_SOURCES = \
- gnunet-service-sensor.c \
- gnunet-service-sensor_monitoring.c \
- gnunet-service-sensor_analysis.c \
- gnunet-service-sensor_reporting.c \
- gnunet-service-sensor_update.c
-gnunet_service_sensor_LDADD = \
- libgnunetsensorutil.la \
- $(top_builddir)/src/util/libgnunetutil.la \
- $(top_builddir)/src/statistics/libgnunetstatistics.la \
- $(top_builddir)/src/peerstore/libgnunetpeerstore.la \
- $(top_builddir)/src/cadet/libgnunetcadet.la \
- $(top_builddir)/src/core/libgnunetcore.la \
- $(GN_LIBINTL)
-
-libgnunetsensor_la_SOURCES = \
- sensor_api.c
-libgnunetsensor_la_LIBADD = \
- $(top_builddir)/src/util/libgnunetutil.la
-libgnunetsensor_la_LDFLAGS = \
- $(GN_LIB_LDFLAGS)
-
-libgnunetsensorutil_la_SOURCES = \
- sensor_util_lib.c \
- sensor_util_lib_crypto.c
-libgnunetsensorutil_la_LIBADD = \
- $(top_builddir)/src/util/libgnunetutil.la \
- $(top_builddir)/src/statistics/libgnunetstatistics.la
-libgnunetsensorutil_la_LDFLAGS = \
- $(GN_LIB_LDFLAGS)
-
-plugin_LTLIBRARIES = \
- libgnunet_plugin_sensor_model_gaussian.la
-
-libgnunet_plugin_sensor_model_gaussian_la_SOURCES = \
- plugin_sensor_model_gaussian.c
-libgnunet_plugin_sensor_model_gaussian_la_LIBADD = \
- libgnunetsensor.la \
- $(top_builddir)/src/util/libgnunetutil.la $(XLIBS) \
- $(LTLIBINTL)
-libgnunet_plugin_sensor_model_gaussian_la_LDFLAGS = \
- $(GN_PLUGIN_LDFLAGS)
-
-check_PROGRAMS = \
- test_sensor_api \
- test_gnunet-service-sensor_reporting \
- test_pow_sign
-
-if ENABLE_TEST_RUN
-AM_TESTS_ENVIRONMENT=export GNUNET_PREFIX=$${GNUNET_PREFIX:-@libdir@};export PATH=$${GNUNET_PREFIX:-@prefix@}/bin:$$PATH;
-TESTS = $(check_PROGRAMS)
-endif
-
-test_sensor_api_SOURCES = \
- test_sensor_api.c
-test_sensor_api_LDADD = \
- $(top_builddir)/src/util/libgnunetutil.la
-
-test_gnunet_service_sensor_reporting_SOURCES = \
- test_gnunet-service-sensor_reporting.c
-test_gnunet_service_sensor_reporting_LDADD = \
- libgnunetsensor.la \
- libgnunetsensorutil.la \
- $(top_builddir)/src/util/libgnunetutil.la \
- $(top_builddir)/src/testbed/libgnunettestbed.la \
- $(top_builddir)/src/peerstore/libgnunetpeerstore.la
-
-test_pow_sign_SOURCES = \
- test_pow_sign.c
-test_pow_sign_LDADD = \
- $(top_builddir)/src/util/libgnunetutil.la \
- $(top_builddir)/src/testbed/libgnunettestbed.la \
- libgnunetsensorutil.la
-
-gnunet_sensor_profiler_SOURCES = \
- gnunet-sensor-profiler.c
-gnunet_sensor_profiler_LDADD = \
- libgnunetsensor.la \
- $(top_builddir)/src/util/libgnunetutil.la \
- $(top_builddir)/src/testbed/libgnunettestbed.la \
- $(top_builddir)/src/peerstore/libgnunetpeerstore.la \
- $(top_builddir)/src/statistics/libgnunetstatistics.la
-
-perf_pow_sign_SOURCES = \
- perf_pow_sign.c
-perf_pow_sign_LDADD = \
- $(top_builddir)/src/util/libgnunetutil.la \
- $(top_builddir)/src/testbed/libgnunettestbed.la \
- libgnunetsensorutil.la
-
-EXTRA_DIST = sensors
-pkgsensordir = sensors
-
-install-data-local:
- $(mkinstalldirs) $(DESTDIR)$(datadir)/$(PACKAGE)/$(pkgsensordir)
- @$(NORMAL_INSTALL)
- for sensor in $(pkgsensordir)/*; do \
- cp -a $$sensor $(DESTDIR)$(datadir)/$(PACKAGE)/$(pkgsensordir)/ ; \
- done
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/gnunet-sensor-profiler.c
- * @brief Profiler for the sensor service
- * @author Omar Tarabai
- */
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "gnunet_testbed_service.h"
-#include "gnunet_peerstore_service.h"
-#include "gnunet_sensor_service.h"
-#include "gnunet_sensor_util_lib.h"
-#include "gnunet_transport_service.h"
-
-/**
- * Time to wait for the peer to startup completely
- */
-#define PEER_STARTUP_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
-
-/**
- * Information about a single peer
- */
-struct PeerInfo
-{
-
- /**
- * Peer Identity
- */
- struct GNUNET_PeerIdentity peer_id;
-
- /**
- * Testbed peer handle
- */
- struct GNUNET_TESTBED_Peer *testbed_peer;
-
- /**
- * Index of this peer within our list
- */
- int index;
-
- /**
- * TESTBED operation used to connect to statistics service
- */
- struct GNUNET_TESTBED_Operation *statistics_op;
-
- /**
- * Handle to the peer's statistics service
- */
- struct GNUNET_STATISTICS_Handle *statistics;
-
-};
-
-/**
- * Name of the configuration file used
- */
-static const char *cfg_filename = "gnunet-sensor-profiler.conf";
-
-/**
- * Directory to read sensor definitions from
- */
-static const char *sensor_src_dir = "sensors";
-
-/**
- * Directory to write new sensor definitions to
- */
-static const char *sensor_dst_dir = "/tmp/gnunet-sensor-profiler";
-
-/**
- * Scheduled task to shutdown
- */
-static struct GNUNET_SCHEDULER_Task * shutdown_task = NULL;
-
-/**
- * GNUnet configuration
- */
-static struct GNUNET_CONFIGURATION_Handle *cfg;
-
-/**
- * Number of peers to run (Option -p)
- */
-static unsigned int num_peers = 0;
-
-/**
- * Set sensors running interval to this value (Option -i)
- */
-static unsigned int sensors_interval = 0;
-
-/**
- * Path to topology file (Option -t)
- */
-static char *topology_file;
-
-/**
- * Number of peers to simulate anomalies on (Option -a)
- */
-static unsigned int anomalous_peers = 0;
-
-/**
- * Array of peer info for all peers
- */
-static struct PeerInfo *all_peers_info;
-
-/**
- * Number of peers that we already collected and start their info
- */
-static int peers_known = 0;
-
-/**
- * TESTBED operation connecting us to peerstore service on collection point
- */
-static struct GNUNET_TESTBED_Operation *peerstore_op;
-
-/**
- * Handle to peerstore service on collection point
- */
-static struct GNUNET_PEERSTORE_Handle *peerstore;
-
-/**
- * Dashboard service on collection point started?
- */
-static int dashboard_service_started = GNUNET_NO;
-
-/**
- * Number of peers started the sensor service successfully
- */
-static int sensor_services_started = 0;
-
-/**
- * Array of sensor names to be used for watching peerstore records
- */
-static char **sensor_names;
-
-/**
- * Size of 'sensor_names' array
- */
-static unsigned int sensor_names_size = 0;
-
-/**
- * Task run after any waiting period
- */
-static struct GNUNET_SCHEDULER_Task * delayed_task = NULL;
-
-
-/**
- * Copy directory recursively
- *
- * @param src Path to source directory
- * @param dst Destination directory, will be created if it does not exist
- * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
- */
-static int
-copy_dir (const char *src, const char *dst);
-
-
-/**
- * Do clean up and shutdown scheduler
- */
-static void
-do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- int i;
-
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutting down.\n");
- if (NULL != delayed_task)
- {
- GNUNET_SCHEDULER_cancel (delayed_task);
- delayed_task = NULL;
- }
- for (i = 0; i < num_peers; i++)
- {
- if (NULL != all_peers_info[i].statistics_op)
- {
- GNUNET_TESTBED_operation_done (all_peers_info[i].statistics_op);
- all_peers_info[i].statistics_op = NULL;
- }
- }
- if (NULL != peerstore_op)
- {
- GNUNET_TESTBED_operation_done (peerstore_op);
- peerstore_op = NULL;
- }
- if (NULL != all_peers_info)
- {
- GNUNET_free (all_peers_info);
- all_peers_info = NULL;
- }
- if (NULL != cfg)
- {
- GNUNET_CONFIGURATION_destroy (cfg);
- cfg = NULL;
- }
- if (NULL != sensor_names)
- {
- for (i = 0; i < sensor_names_size; i++)
- GNUNET_free (sensor_names[i]);
- GNUNET_array_grow (sensor_names, sensor_names_size, 0);
- }
- GNUNET_SCHEDULER_shutdown ();
-}
-
-
-/**
- * Function called with each file/folder inside a directory that is being copied.
- *
- * @param cls closure, destination directory
- * @param filename complete filename (absolute path)
- * @return #GNUNET_OK to continue to iterate.
- * #GNUNET_SYSERR to abort iteration with error
- */
-static int
-copy_dir_scanner (void *cls, const char *filename)
-{
- char *dst_dir = cls;
- char *dst;
- int copy_result;
-
- GNUNET_asprintf (&dst, "%s%s%s", dst_dir, DIR_SEPARATOR_STR,
- GNUNET_STRINGS_get_short_name (filename));
- if (GNUNET_YES == GNUNET_DISK_directory_test (filename, GNUNET_YES))
- copy_result = copy_dir (filename, dst);
- else
- {
- if (GNUNET_YES == GNUNET_DISK_file_test (dst))
- GNUNET_DISK_directory_remove (dst);
- copy_result = GNUNET_DISK_file_copy (filename, dst);
- if (GNUNET_OK == copy_result)
- GNUNET_DISK_fix_permissions (dst, GNUNET_NO, GNUNET_NO);
- }
- GNUNET_free (dst);
- return copy_result;
-}
-
-
-/**
- * Copy directory recursively
- *
- * @param src Path to source directory
- * @param dst Destination directory, will be created if it does not exist
- * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
- */
-static int
-copy_dir (const char *src, const char *dst)
-{
- if (GNUNET_YES != GNUNET_DISK_directory_test (src, GNUNET_YES))
- return GNUNET_SYSERR;
- if (GNUNET_OK != GNUNET_DISK_directory_create (dst))
- return GNUNET_SYSERR;
- if (GNUNET_SYSERR ==
- GNUNET_DISK_directory_scan (src, ©_dir_scanner, (char *) dst))
- return GNUNET_SYSERR;
- return GNUNET_OK;
-}
-
-
-/**
- * Function called with each file/folder inside source sensor directory.
- *
- * @param cls closure (unused)
- * @param filename complete filename (absolute path)
- * @return #GNUNET_OK to continue to iterate.
- */
-static int
-sensor_dir_scanner (void *cls, const char *filename)
-{
- const char *file_basename;
- char *dst_path;
- struct GNUNET_CONFIGURATION_Handle *sensor_cfg;
- char *sensor_name;
-
- file_basename = GNUNET_STRINGS_get_short_name (filename);
- GNUNET_asprintf (&dst_path, "%s%s%s", sensor_dst_dir, DIR_SEPARATOR_STR,
- file_basename);
- if (GNUNET_YES == GNUNET_DISK_directory_test (filename, GNUNET_NO))
- {
- GNUNET_assert (GNUNET_OK == copy_dir (filename, dst_path));
- }
- else
- {
- sensor_name = GNUNET_strdup (file_basename);
- GNUNET_array_append (sensor_names, sensor_names_size, sensor_name);
- sensor_cfg = GNUNET_CONFIGURATION_create ();
- GNUNET_assert (GNUNET_OK ==
- GNUNET_CONFIGURATION_parse (sensor_cfg, filename));
- GNUNET_CONFIGURATION_set_value_string (sensor_cfg, file_basename,
- "COLLECTION_POINT",
- GNUNET_i2s_full (&all_peers_info
- [0].peer_id));
- if (sensors_interval > 0)
- {
- GNUNET_CONFIGURATION_set_value_number (sensor_cfg, file_basename,
- "INTERVAL",
- (unsigned long long int)
- sensors_interval);
- }
- GNUNET_CONFIGURATION_write (sensor_cfg, dst_path);
- GNUNET_CONFIGURATION_destroy (sensor_cfg);
- }
- GNUNET_free (dst_path);
- return GNUNET_OK;
-}
-
-
-/**
- * Load sensor definitions and rewrite them to tmp location.
- * Add collection point peer id and change running interval if needed.
- */
-static void
-rewrite_sensors ()
-{
- GNUNET_assert (GNUNET_YES ==
- GNUNET_DISK_directory_test (sensor_src_dir, GNUNET_YES));
- GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_create (sensor_dst_dir));
- GNUNET_DISK_directory_scan (sensor_src_dir, &sensor_dir_scanner, NULL);
-}
-
-
-/**
- * Callback to be called when dashboard service is started
- *
- * @param cls the callback closure from functions generating an operation
- * @param op the operation that has been finished
- * @param emsg error message in case the operation has failed; will be NULL if
- * operation has executed successfully.
- */
-static void
-dashboard_started (void *cls, struct GNUNET_TESTBED_Operation *op,
- const char *emsg)
-{
- if (NULL != emsg)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
- GNUNET_assert (0);
- }
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Dashboard service started.\n");
- GNUNET_TESTBED_operation_done (op);
- dashboard_service_started = GNUNET_YES;
-}
-
-
-/**
- * Function called by PEERSTORE for each matching record.
- *
- * @param cls closure
- * @param record peerstore record information
- * @param emsg error message, or NULL if no errors
- * @return #GNUNET_YES to continue iterating, #GNUNET_NO to stop
- */
-static int
-peerstore_watch_cb (void *cls,
- const struct GNUNET_PEERSTORE_Record *record,
- const char *emsg)
-{
- struct PeerInfo *peer = cls;
- struct GNUNET_SENSOR_DashboardAnomalyEntry *anomaly;
-
- if (NULL != emsg)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
- GNUNET_assert (0);
- }
- GNUNET_assert (record->value_size ==
- sizeof (struct GNUNET_SENSOR_DashboardAnomalyEntry));
- anomaly = record->value;
- GNUNET_assert (0 ==
- GNUNET_CRYPTO_cmp_peer_identity (&peer->peer_id,
- record->peer));
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Anomaly report:{'peerid': '%s'," "'peer': %d," "'sensor': '%s',"
- "'anomalous': %d," "'neighbors': %f}\n",
- GNUNET_i2s (&peer->peer_id), peer->index, record->key,
- anomaly->anomalous, anomaly->anomalous_neighbors);
- return GNUNET_YES;
-}
-
-
-/**
- * Callback to be called when peerstore service connect operation is completed
- *
- * @param cls the callback closure from functions generating an operation
- * @param op the operation that has been finished
- * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
- * @param emsg error message in case the operation has failed; will be NULL if
- * operation has executed successfully.
- */
-static void
-peerstore_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
- void *ca_result, const char *emsg)
-{
- int i;
- int j;
- struct PeerInfo *peer;
-
- if (NULL != emsg)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
- GNUNET_assert (0);
- }
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected to peerstore service.\n");
- /* Watch for anomaly reports from other peers */
- for (i = 0; i < num_peers; i++)
- {
- peer = &all_peers_info[i];
- for (j = 0; j < sensor_names_size; j++)
- {
- GNUNET_PEERSTORE_watch (peerstore, "sensordashboard-anomalies",
- &peer->peer_id, sensor_names[j],
- &peerstore_watch_cb, peer);
- }
- }
-}
-
-
-/**
- * Adapter function called to establish a connection to peerstore service.
- *
- * @param cls closure
- * @param cfg configuration of the peer to connect to; will be available until
- * GNUNET_TESTBED_operation_done() is called on the operation returned
- * from GNUNET_TESTBED_service_connect()
- * @return service handle to return in 'op_result', NULL on error
- */
-static void *
-peerstore_connect_adapter (void *cls,
- const struct GNUNET_CONFIGURATION_Handle *cfg)
-{
- peerstore = GNUNET_PEERSTORE_connect (cfg);
- GNUNET_assert (NULL != peerstore);
- return peerstore;
-}
-
-
-/**
- * Adapter function called to destroy a connection to peerstore service.
- *
- * @param cls closure
- * @param op_result service handle returned from the connect adapter
- */
-static void
-peerstore_disconnect_adapter (void *cls, void *op_result)
-{
- GNUNET_PEERSTORE_disconnect (peerstore, GNUNET_NO);
- peerstore = NULL;
- peerstore_op = NULL;
-}
-
-
-/**
- * Callback to be called when statistics service connect operation is completed
- *
- * @param cls the callback closure from functions generating an operation
- * @param op the operation that has been finished
- * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
- * @param emsg error message in case the operation has failed; will be NULL if
- * operation has executed successfully.
- */
-static void
-statistics_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
- void *ca_result, const char *emsg)
-{
- struct PeerInfo *peer = cls;
-
- if (NULL != emsg)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
- GNUNET_assert (0);
- }
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Connected to statistics service on peer `%s'.\n", GNUNET_i2s (&peer->peer_id));
- GNUNET_STATISTICS_set (peer->statistics, "# peers connected", 0, GNUNET_NO);
-}
-
-
-/**
- * Adapter function called to establish a connection to statistics service.
- *
- * @param cls closure
- * @param cfg configuration of the peer to connect to; will be available until
- * GNUNET_TESTBED_operation_done() is called on the operation returned
- * from GNUNET_TESTBED_service_connect()
- * @return service handle to return in 'op_result', NULL on error
- */
-static void *
-statistics_connect_adapter (void *cls,
- const struct GNUNET_CONFIGURATION_Handle *cfg)
-{
- struct PeerInfo *peer = cls;
-
- peer->statistics = GNUNET_STATISTICS_create ("core", cfg);
- GNUNET_assert (NULL != peer->statistics);
- return peer->statistics;
-}
-
-
-/**
- * Adapter function called to destroy a connection to statistics service.
- *
- * @param cls closure
- * @param op_result service handle returned from the connect adapter
- */
-static void
-statistics_disconnect_adapter (void *cls, void *op_result)
-{
- struct PeerInfo *peer = cls;
-
- GNUNET_STATISTICS_destroy (peer->statistics, GNUNET_NO);
- peer->statistics = NULL;
-}
-
-
-/**
- * This function is called after the estimated training period is over.
- */
-static void
-simulate_anomalies (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- int i;
- uint32_t an_peer;
- struct GNUNET_TIME_Relative shutdown_delay;
-
- delayed_task = NULL;
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Training period over, simulating anomalies now.\n");
- GNUNET_assert (anomalous_peers <= num_peers);
- for (i = 0; i < anomalous_peers; i++)
- {
- an_peer = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
- if (NULL != all_peers_info[an_peer].statistics_op)
- {
- i--;
- continue;
- }
- all_peers_info[an_peer].statistics_op =
- GNUNET_TESTBED_service_connect (NULL, all_peers_info[an_peer].testbed_peer,
- "statistics", &statistics_connect_cb,
- &all_peers_info[an_peer], &statistics_connect_adapter,
- &statistics_disconnect_adapter, &all_peers_info[an_peer]);
- }
- shutdown_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, num_peers * 6);
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutting down in %s\n",
- GNUNET_STRINGS_relative_time_to_string (shutdown_delay, GNUNET_NO));
- GNUNET_SCHEDULER_cancel (shutdown_task);
- shutdown_task = GNUNET_SCHEDULER_add_delayed (shutdown_delay, &do_shutdown, NULL);
-}
-
-
-/**
- * This function is called after a delay which ensures that all peers are
- * properly initialized
- */
-static void
-peers_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- unsigned long long int training_points;
- struct GNUNET_TIME_Relative training_period;
-
- delayed_task = NULL;
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "All peers are ready.\n");
- GNUNET_assert (GNUNET_OK ==
- GNUNET_CONFIGURATION_get_value_number (cfg,
- "sensor-model-gaussian",
- "TRAINING_WINDOW",
- &training_points));
- training_period =
- GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_multiply
- (GNUNET_TIME_UNIT_SECONDS,
- (sensors_interval ==
- 0) ? 60 : sensors_interval),
- training_points);
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Sleeping for a training period of %s.\n",
- GNUNET_STRINGS_relative_time_to_string (training_period,
- GNUNET_NO));
- delayed_task =
- GNUNET_SCHEDULER_add_delayed (training_period, &simulate_anomalies, NULL);
-}
-
-
-/**
- * Callback to be called when sensor service is started
- *
- * @param cls the callback closure from functions generating an operation
- * @param op the operation that has been finished
- * @param emsg error message in case the operation has failed; will be NULL if
- * operation has executed successfully.
- */
-static void
-sensor_service_started (void *cls, struct GNUNET_TESTBED_Operation *op,
- const char *emsg)
-{
- struct PeerInfo *peer = cls;
-
- if (NULL != emsg)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
- GNUNET_assert (0);
- }
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sensor service started on peer `%s'.\n",
- GNUNET_i2s (&peer->peer_id));
- GNUNET_TESTBED_operation_done (op);
- sensor_services_started++;
- if (sensor_services_started == num_peers)
- {
- delayed_task =
- GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
- (PEER_STARTUP_TIME, num_peers),
- &peers_ready, NULL);
- }
-}
-
-
-/**
- * Callback to be called when the requested peer information is available
- *
- * @param cb_cls the closure from GNUNET_TETSBED_peer_get_information()
- * @param op the operation this callback corresponds to
- * @param pinfo the result; will be NULL if the operation has failed
- * @param emsg error message if the operation has failed; will be NULL if the
- * operation is successfull
- */
-static void
-peer_info_cb (void *cb_cls, struct GNUNET_TESTBED_Operation *op,
- const struct GNUNET_TESTBED_PeerInformation *pinfo,
- const char *emsg)
-{
- struct GNUNET_TESTBED_Peer *testbed_peer = cb_cls;
- struct PeerInfo *peer = &all_peers_info[peers_known];
-
- if (NULL != emsg)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
- GNUNET_assert (0);
- }
- peer->testbed_peer = testbed_peer;
- GNUNET_CRYPTO_get_peer_identity (pinfo->result.cfg, &peer->peer_id);
- peer->index = peers_known;
- peers_known++;
- if (1 == peers_known) /* First peer is collection point */
- {
- /* Rewrite sensors */
- rewrite_sensors ();
- /* Start dashboard */
- GNUNET_TESTBED_peer_manage_service (NULL, testbed_peer, "sensordashboard",
- &dashboard_started, NULL, 1);
- }
- /* Start sensor service on every peer */
- GNUNET_TESTBED_peer_manage_service (NULL, testbed_peer, "sensor",
- &sensor_service_started, peer, 1);
- if (num_peers == peers_known) /* Last peer */
- {
- /* Connect to peerstore on first peer (collection point) */
- peerstore_op =
- GNUNET_TESTBED_service_connect (NULL, all_peers_info[0].testbed_peer,
- "peerstore", &peerstore_connect_cb,
- NULL, &peerstore_connect_adapter,
- &peerstore_disconnect_adapter, NULL);
- }
- GNUNET_TESTBED_operation_done (op);
-}
-
-
-/**
- * Signature of a main function for a testcase.
- *
- * @param cls closure
- * @param h the run handle
- * @param num number of peers in 'peers'
- * @param peers handle to peers run in the testbed. NULL upon timeout (see
- * GNUNET_TESTBED_test_run()).
- * @param links_succeeded the number of overlay link connection attempts that
- * succeeded
- * @param links_failed the number of overlay link connection attempts that
- * failed
- * @see GNUNET_TESTBED_test_run()
- */
-static void
-test_master (void *cls, struct GNUNET_TESTBED_RunHandle *h, unsigned int num,
- struct GNUNET_TESTBED_Peer **peers, unsigned int links_succeeded,
- unsigned int links_failed)
-{
- int i;
-
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "%d peers started. %d links succeeded. %d links failed.\n",
- num_peers, links_succeeded, links_failed);
- GNUNET_assert (num == num_peers);
- /* Collect peer information */
- all_peers_info = GNUNET_new_array (num_peers, struct PeerInfo);
-
- for (i = 0; i < num_peers; i++)
- {
- GNUNET_TESTBED_peer_get_information (peers[i],
- GNUNET_TESTBED_PIT_CONFIGURATION,
- &peer_info_cb, peers[i]);
- }
-}
-
-
-/**
- * Verify that the user passed correct CL args
- *
- * @return #GNUNET_OK if arguments are valid, #GNUNET_SYSERR otherwise
- */
-static int
-verify_args ()
-{
- if (num_peers < 2)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
- _
- ("Invalid or missing number of peers. Set at least 2 peers.\n"));
- return GNUNET_SYSERR;
- }
- if (NULL == topology_file ||
- GNUNET_YES != GNUNET_DISK_file_test (topology_file))
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
- _("Missing or invalid topology file.\n"));
- return GNUNET_SYSERR;
- }
- return GNUNET_OK;
-}
-
-
-/**
- * Actual main function.
- *
- * @param cls unused
- * @param args remaining args, unused
- * @param cfgfile name of the configuration
- * @param cfg configuration handle
- */
-static void
-run (void *cls, char *const *args, const char *cf,
- const struct GNUNET_CONFIGURATION_Handle *c)
-{
- if (GNUNET_OK != verify_args ())
- {
- do_shutdown (NULL, NULL);
- return;
- }
- cfg = GNUNET_CONFIGURATION_create ();
- GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_load (cfg, cfg_filename));
- GNUNET_CONFIGURATION_set_value_string ((struct GNUNET_CONFIGURATION_Handle *)
- cfg, "TESTBED",
- "OVERLAY_TOPOLOGY_FILE",
- topology_file);
- shutdown_task =
- GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown,
- NULL);
- GNUNET_TESTBED_run (NULL, cfg, num_peers, 0, NULL, NULL, &test_master, NULL);
-}
-
-
-/**
- * Main function.
- *
- * @return 0 on success
- */
-int
-main (int argc, char *const *argv)
-{
- static struct GNUNET_GETOPT_CommandLineOption options[] = {
- {'p', "peers", "COUNT", gettext_noop ("Number of peers to run"), GNUNET_YES,
- &GNUNET_GETOPT_set_uint, &num_peers},
- {'t', "topology-file", "FILEPATH", gettext_noop ("Path to topology file"),
- GNUNET_YES, &GNUNET_GETOPT_set_filename, &topology_file},
- {'i', "sensors-interval", "INTERVAL",
- gettext_noop ("Change the interval of running sensors to given value"),
- GNUNET_YES, &GNUNET_GETOPT_set_uint, &sensors_interval},
- {'a', "anomalous-peers", "COUNT",
- gettext_noop ("Number of peers to simulate anomalies on"), GNUNET_YES,
- &GNUNET_GETOPT_set_uint, &anomalous_peers},
- GNUNET_GETOPT_OPTION_END
- };
-
- return (GNUNET_OK ==
- GNUNET_PROGRAM_run (argc, argv, "gnunet-sensor-profiler",
- gettext_noop ("Profiler for sensor service"),
- options, &run, NULL)) ? 0 : 1;
-}
-
-/* end of gnunet-sensor-profiler.c */
+++ /dev/null
-[testbed]
-OVERLAY_TOPOLOGY = FROM_FILE
-
-[sensor]
-SENSOR_DIR = /tmp/gnunet-sensor-profiler/
-
-START_MONITORING = YES
-START_REPORTING = YES
-START_ANALYSIS = YES
-START_UPDATE = NO
-
-[transport]
-PLUGINS = unix
-
-[nat]
-USE_LOCALADDR = YES
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/gnunet-sensor.c
- * @brief sensor tool
- * @author Omar Tarabai
- */
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "gnunet_sensor_service.h"
-
-static int ret;
-
-/**
- * option '-a'
- */
-static int get_all;
-
-/**
- * option '-g'
- */
-static char *get_sensor;
-
-/**
- * option '-f'
- */
-static char *force_anomaly;
-
-/*
- * Handle to sensor service
- */
-static struct GNUNET_SENSOR_Handle *sensor_handle;
-
-/**
- * Run on shutdown
- *
- * @param cls unused
- * @param tc scheduler context
- */
-static void
-shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- if (NULL != sensor_handle)
- {
- GNUNET_SENSOR_disconnect (sensor_handle);
- sensor_handle = NULL;
- }
-}
-
-
-/**
- * Callback for getting sensor info from service
- *
- * @param cls not used
- * @param sensor brief information about sensor (NULL means end of transmission)
- * @param err_msg contains error string if any
- */
-void
-print_sensor_info (void *cls, const struct SensorInfoShort *sensor,
- const char *err_msg)
-{
- if (NULL != err_msg)
- {
- printf ("Error: %s\n", err_msg);
- GNUNET_SCHEDULER_shutdown ();
- return;
- }
- if (NULL == sensor) /* no more sensors from service */
- {
- GNUNET_SCHEDULER_shutdown ();
- return;
- }
- printf ("Name: %s\nVersion: %d.%d\n", sensor->name, sensor->version_major,
- sensor->version_minor);
- if (NULL != sensor->description)
- printf ("Description: %s\n", sensor->description);
- printf ("\n");
-}
-
-
-/**
- * Continuation called after a force anomaly request is sent.
- *
- * @param cls Closure (unused)
- * @param emsg Error message, NULL of no error
- */
-void
-force_anomaly_cont (void *cls, const char *emsg)
-{
- if (NULL != emsg)
- printf ("Error: %s\n", emsg);
- GNUNET_SCHEDULER_shutdown ();
-}
-
-
-/**
- * Main function that will be run by the scheduler.
- *
- * @param cls closure
- * @param args remaining command-line arguments
- * @param cfgfile name of the configuration file used (for saving, can be NULL!)
- * @param cfg configuration
- */
-static void
-run (void *cls, char *const *args, const char *cfgfile,
- const struct GNUNET_CONFIGURATION_Handle *cfg)
-{
- sensor_handle = NULL;
- GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
- NULL);
- sensor_handle = GNUNET_SENSOR_connect (cfg);
- GNUNET_assert (NULL != sensor_handle);
- if (GNUNET_YES == get_all)
- {
- GNUNET_SENSOR_iterate (sensor_handle, GNUNET_TIME_UNIT_FOREVER_REL, NULL,
- &print_sensor_info, NULL);
- }
- else if (NULL != get_sensor)
- {
- GNUNET_SENSOR_iterate (sensor_handle, GNUNET_TIME_UNIT_FOREVER_REL,
- get_sensor, &print_sensor_info, NULL);
- }
- else if (NULL != force_anomaly)
- {
- GNUNET_SENSOR_force_anomaly (sensor_handle, "nse", GNUNET_YES,
- &force_anomaly_cont, NULL);
- }
- ret = 0;
-}
-
-
-/**
- * The main function to sensor.
- *
- * @param argc number of arguments from the command line
- * @param argv command line arguments
- * @return 0 ok, 1 on error
- */
-int
-main (int argc, char *const *argv)
-{
- static const struct GNUNET_GETOPT_CommandLineOption options[] = {
- {'a', "all", NULL,
- gettext_noop ("Retrieve information about all defined sensors"),
- 0, &GNUNET_GETOPT_set_one, &get_all},
- {'g', "get-sensor", NULL,
- gettext_noop ("Retrieve information about a single sensor"),
- 1, &GNUNET_GETOPT_set_string, &get_sensor},
- {'f', "force-anomaly", NULL,
- gettext_noop ("Force an anomaly on a sensor, use only for testing"),
- 1, &GNUNET_GETOPT_set_string, &force_anomaly},
- GNUNET_GETOPT_OPTION_END
- };
-
- return (GNUNET_OK ==
- GNUNET_PROGRAM_run (argc, argv, "gnunet-sensor [options [value]]",
- gettext_noop ("sensor"), options, &run,
- NULL)) ? ret : 1;
-}
-
-/* end of gnunet-sensor.c */
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/gnunet-service-sensor.c
- * @brief sensor service implementation
- * @author Omar Tarabai
- */
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "sensor.h"
-
-/**
- * Our configuration.
- */
-static const struct GNUNET_CONFIGURATION_Handle *cfg;
-
-/**
- * Path to sensor definitions directory
- */
-static char *sensor_dir;
-
-/**
- * Hashmap of loaded sensor definitions
- */
-static struct GNUNET_CONTAINER_MultiHashMap *sensors;
-
-/**
- * Start the monitoring module ?
- */
-static int start_monitoring;
-
-/**
- * Start the analysis module ?
- */
-static int start_analysis;
-
-/**
- * Start the reporting module ?
- */
-static int start_reporting;
-
-/**
- * Start the update module ?
- */
-static int start_update;
-
-
-/**
- * Resets the service by stopping components, reloading sensors and starting
- * components. This is needed when we receive new sensor updates.
- */
-static void
-reset ();
-
-
-/**
- * Stops components and destroys sensors
- */
-static void
-stop ()
-{
- if (GNUNET_YES == start_update)
- SENSOR_update_stop ();
- if (GNUNET_YES == start_analysis)
- SENSOR_analysis_stop ();
- if (GNUNET_YES == start_reporting)
- SENSOR_reporting_stop ();
- if (GNUNET_YES == start_monitoring)
- SENSOR_monitoring_stop ();
- GNUNET_SENSOR_destroy_sensors (sensors);
-}
-
-
-/**
- * Task run during shutdown.
- *
- * @param cls unused
- * @param tc unused
- */
-static void
-shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- stop ();
- if (NULL != sensor_dir)
- {
- GNUNET_free (sensor_dir);
- sensor_dir = NULL;
- }
- GNUNET_SCHEDULER_shutdown ();
-}
-
-
-/**
- * Handle a force anomaly request from client.
- *
- * @param cls closure
- * @param client identification of the client
- * @param message the actual message
- */
-static void
-handle_anomaly_force (void *cls, struct GNUNET_SERVER_Client *client,
- const struct GNUNET_MessageHeader *message)
-{
- struct ForceAnomalyMessage *anomaly_msg;
- struct GNUNET_SENSOR_SensorInfo *sensor;
-
- anomaly_msg = (struct ForceAnomalyMessage *) message;
- sensor =
- GNUNET_CONTAINER_multihashmap_get (sensors,
- &anomaly_msg->sensor_name_hash);
- if (NULL == sensor)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
- "Force anomaly message received for a sensor we don't have.\n");
- GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
- return;
- }
- SENSOR_reporting_anomaly_update (sensor, ntohs (anomaly_msg->anomalous));
- GNUNET_SERVER_receive_done (client, GNUNET_YES);
-}
-
-
-/**
- * Creates a structure with basic sensor info to be sent to a client.
- *
- * @param sensor sensor information
- * @return message ready to be sent to client
- */
-static struct SensorInfoMessage *
-create_sensor_info_msg (struct GNUNET_SENSOR_SensorInfo *sensor)
-{
- struct SensorInfoMessage *msg;
- uint16_t len;
- size_t name_len;
- size_t desc_len;
- char *str_ptr;
-
- name_len = strlen (sensor->name);
- if (NULL == sensor->description)
- desc_len = 0;
- else
- desc_len = strlen (sensor->description) + 1;
- len = 0;
- len += sizeof (struct SensorInfoMessage);
- len += name_len;
- len += desc_len;
- msg = GNUNET_malloc (len);
- msg->header.size = htons (len);
- msg->header.type = htons (GNUNET_MESSAGE_TYPE_SENSOR_INFO);
- msg->name_len = htons (name_len);
- msg->description_len = htons (desc_len);
- msg->version_major = htons (sensor->version_major);
- msg->version_minor = htons (sensor->version_minor);
- str_ptr = (char *) &msg[1];
- memcpy (str_ptr, sensor->name, name_len);
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending sensor name (%d): %.*s\n",
- name_len, name_len, str_ptr);
- str_ptr += name_len;
- memcpy (str_ptr, sensor->description, desc_len);
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Sending sensor description (%d): %.*s\n", desc_len, desc_len,
- str_ptr);
- return msg;
-}
-
-
-/**
- * Handle GET SENSOR message.
- *
- * @param cls closure
- * @param client identification of the client
- * @param message the actual message
- */
-static void
-handle_get_sensor (void *cls, struct GNUNET_SERVER_Client *client,
- const struct GNUNET_MessageHeader *message)
-{
- struct GNUNET_SERVER_TransmitContext *tc;
- char *sensorname;
- size_t sensorname_len;
- struct GNUNET_HashCode key;
- struct GNUNET_SENSOR_SensorInfo *sensorinfo;
- struct SensorInfoMessage *msg;
-
- sensorname = (char *) &message[1];
- sensorname_len = ntohs (message->size) - sizeof (struct GNUNET_MessageHeader);
- GNUNET_log (GNUNET_ERROR_TYPE_INFO,
- "`%s' message received for sensor (%d) `%.*s'\n", "GET SENSOR",
- sensorname_len, sensorname_len, sensorname);
- tc = GNUNET_SERVER_transmit_context_create (client);
- GNUNET_CRYPTO_hash (sensorname, sensorname_len, &key);
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Created key hash for requested sensor\n");
- sensorinfo =
- (struct GNUNET_SENSOR_SensorInfo *)
- GNUNET_CONTAINER_multihashmap_get (sensors, &key);
- if (NULL != sensorinfo)
- {
- msg = create_sensor_info_msg (sensorinfo);
- GNUNET_SERVER_transmit_context_append_message (tc,
- (struct GNUNET_MessageHeader
- *) msg);
- GNUNET_free (msg);
- }
- else
- GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
- "Requested sensor `%.*s' was not found\n", sensorname_len,
- sensorname);
- GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
- GNUNET_MESSAGE_TYPE_SENSOR_END);
- GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
-}
-
-
-/**
- * Iterator for sensors and adds them to transmit context
- *
- * @param cls a `struct GNUNET_SERVER_TransmitContext *`
- * @param key hash of sensor name, key to hashmap
- * @param value a `struct GNUNET_SENSOR_SensorInfo *`
- */
-static int
-add_sensor_to_tc (void *cls, const struct GNUNET_HashCode *key, void *value)
-{
- struct GNUNET_SERVER_TransmitContext *tc = cls;
- struct GNUNET_SENSOR_SensorInfo *sensorinfo = value;
- struct SensorInfoMessage *msg;
-
- msg = create_sensor_info_msg (sensorinfo);
- GNUNET_SERVER_transmit_context_append_message (tc,
- (struct GNUNET_MessageHeader *)
- msg);
-
- GNUNET_free (msg);
- return GNUNET_YES;
-}
-
-
-/**
- * Handle GET ALL SENSORS message.
- *
- * @param cls closure
- * @param client identification of the client
- * @param message the actual message
- */
-static void
-handle_get_all_sensors (void *cls, struct GNUNET_SERVER_Client *client,
- const struct GNUNET_MessageHeader *message)
-{
- struct GNUNET_SERVER_TransmitContext *tc;
-
- GNUNET_log (GNUNET_ERROR_TYPE_INFO, "`%s' message received.\n",
- "GET ALL SENSOR");
- tc = GNUNET_SERVER_transmit_context_create (client);
- GNUNET_CONTAINER_multihashmap_iterate (sensors, &add_sensor_to_tc, tc);
- GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
- GNUNET_MESSAGE_TYPE_SENSOR_END);
- GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
-}
-
-
-/**
- * Loads sensors and starts different service components
- */
-static void
-start ()
-{
- sensors = GNUNET_SENSOR_load_all_sensors (sensor_dir);
- if (GNUNET_YES == start_monitoring)
- SENSOR_monitoring_start (cfg, sensors);
- if (GNUNET_YES == start_reporting)
- SENSOR_reporting_start (cfg, sensors);
- if (GNUNET_YES == start_analysis)
- SENSOR_analysis_start (cfg, sensors);
- if (GNUNET_YES == start_update)
- SENSOR_update_start (cfg, sensors, &reset);
-}
-
-
-/**
- * Process statistics requests.
- *
- * @param cls closure
- * @param server the initialized server
- * @param c configuration to use
- */
-static void
-run (void *cls, struct GNUNET_SERVER_Handle *server,
- const struct GNUNET_CONFIGURATION_Handle *c)
-{
- static const struct GNUNET_SERVER_MessageHandler handlers[] = {
- {&handle_get_sensor, NULL, GNUNET_MESSAGE_TYPE_SENSOR_GET,
- 0},
- {&handle_get_all_sensors, NULL, GNUNET_MESSAGE_TYPE_SENSOR_GETALL,
- sizeof (struct GNUNET_MessageHeader)},
- {
- &handle_anomaly_force, NULL, GNUNET_MESSAGE_TYPE_SENSOR_ANOMALY_FORCE,
- sizeof (struct ForceAnomalyMessage)},
- {NULL, NULL, 0, 0}
- };
-
- cfg = c;
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_filename (cfg, "sensor", "SENSOR_DIR",
- &sensor_dir))
- {
- sensor_dir = GNUNET_SENSOR_get_default_sensor_dir ();
- }
- start_monitoring = GNUNET_YES;
- start_analysis = GNUNET_YES;
- start_reporting = GNUNET_YES;
- start_update = GNUNET_YES;
- if (GNUNET_NO ==
- GNUNET_CONFIGURATION_get_value_yesno (cfg, "sensor", "START_MONITORING"))
- {
- start_monitoring = GNUNET_NO;
- }
- if (GNUNET_NO ==
- GNUNET_CONFIGURATION_get_value_yesno (cfg, "sensor", "START_REPORTING"))
- {
- start_reporting = GNUNET_NO;
- }
- if (GNUNET_NO ==
- GNUNET_CONFIGURATION_get_value_yesno (cfg, "sensor", "START_ANALYSIS"))
- {
- start_analysis = GNUNET_NO;
- }
- if (GNUNET_NO ==
- GNUNET_CONFIGURATION_get_value_yesno (cfg, "sensor", "START_UPDATE"))
- {
- start_update = GNUNET_NO;
- }
- GNUNET_SERVER_add_handlers (server, handlers);
- GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
- NULL);
- start ();
-}
-
-
-/**
- * Resets the service by stopping components, reloading sensors and starting
- * components. This is needed when we receive new sensor updates.
- */
-static void
-reset ()
-{
- stop ();
- start ();
-}
-
-
-/**
- * The main function for the sensor service.
- *
- * @param argc number of arguments from the command line
- * @param argv command line arguments
- * @return 0 ok, 1 on error
- */
-int
-main (int argc, char *const *argv)
-{
- return (GNUNET_OK ==
- GNUNET_SERVICE_run (argc, argv, "sensor", GNUNET_SERVICE_OPTION_NONE,
- &run, NULL)) ? 0 : 1;
-}
-
-/* end of gnunet-service-sensor.c */
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/gnunet-service-sensor_analysis.c
- * @brief sensor service analysis functionality
- * @author Omar Tarabai
- */
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "sensor.h"
-#include "gnunet_peerstore_service.h"
-#include "gnunet_sensor_model_plugin.h"
-
-#define LOG(kind,...) GNUNET_log_from (kind, "sensor-analysis",__VA_ARGS__)
-
-/**
- * Carries information about the analysis model
- * corresponding to one sensor
- */
-struct SensorModel
-{
-
- /**
- * DLL
- */
- struct SensorModel *prev;
-
- /**
- * DLL
- */
- struct SensorModel *next;
-
- /**
- * Pointer to sensor info structure
- */
- struct GNUNET_SENSOR_SensorInfo *sensor;
-
- /**
- * Watcher of sensor values
- */
- struct GNUNET_PEERSTORE_WatchContext *wc;
-
- /**
- * State of sensor. #GNUNET_YES if anomalous, #GNUNET_NO otherwise.
- */
- int anomalous;
-
- /**
- * Number of anomalous readings (positive) received in a row.
- */
- int positive_count;
-
- /**
- * Number of non-anomalous (negative) readings received in a row.
- */
- int negative_count;
-
- /**
- * Closure for model plugin.
- * Usually, the instance of the model created for this sensor.
- */
- void *cls;
-
-};
-
-/**
- * Our configuration.
- */
-static const struct GNUNET_CONFIGURATION_Handle *cfg;
-
-/**
- * Hashmap of loaded sensors
- */
-static struct GNUNET_CONTAINER_MultiHashMap *sensors;
-
-/*
- * Model library name
- */
-static char *model_lib_name;
-
-/**
- * Model handle
- */
-static struct GNUNET_SENSOR_ModelFunctions *model_api;
-
-/**
- * Handle to peerstore service
- */
-static struct GNUNET_PEERSTORE_Handle *peerstore;
-
-/**
- * Head of DLL of created models
- */
-static struct SensorModel *models_head;
-
-/**
- * Tail of DLL of created models
- */
-static struct SensorModel *models_tail;
-
-/**
- * My peer id
- */
-static struct GNUNET_PeerIdentity peerid;
-
-/**
- * How many subsequent values required to flip anomaly label.
- * E.g. After 3 subsequent anomaly reports, status change to anomalous.
- */
-static unsigned long long confirmation_count;
-
-/**
- * Destroy a created model
- */
-static void
-destroy_sensor_model (struct SensorModel *sensor_model)
-{
- GNUNET_assert (NULL != sensor_model);
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying sensor model for `%s'.\n",
- sensor_model->sensor->name);
- if (NULL != sensor_model->wc)
- {
- GNUNET_PEERSTORE_watch_cancel (sensor_model->wc);
- sensor_model->wc = NULL;
- }
- if (NULL != sensor_model->cls)
- {
- model_api->destroy_model (sensor_model->cls);
- sensor_model->cls = NULL;
- }
- GNUNET_free (sensor_model);
- sensor_model = NULL;
-}
-
-
-/**
- * Stop the sensor analysis module
- */
-void
-SENSOR_analysis_stop ()
-{
- struct SensorModel *sm;
-
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Stopping sensor analysis module.\n");
- while (NULL != models_head)
- {
- sm = models_head;
- GNUNET_CONTAINER_DLL_remove (models_head, models_tail, sm);
- destroy_sensor_model (sm);
- }
- if (NULL != peerstore)
- {
- GNUNET_PEERSTORE_disconnect (peerstore, GNUNET_YES);
- peerstore = NULL;
- }
- if (NULL != model_api)
- {
- GNUNET_break (NULL == GNUNET_PLUGIN_unload (model_lib_name, model_api));
- GNUNET_free (model_lib_name);
- model_lib_name = NULL;
- }
-}
-
-
-/**
- * Sensor value watch callback
- *
- * @param cls Sensor model struct
- * @param record Received record from peerstore, should contain new sensor value
- * @param emsg Error message from peerstore if any, NULL if no errors
- * @return #GNUNET_YES
- */
-static int
-sensor_watcher (void *cls,
- const struct GNUNET_PEERSTORE_Record *record,
- const char *emsg)
-{
- struct SensorModel *model = cls;
- double *val;
- int anomalous;
-
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "Received a sensor value, will feed to sensor model.\n");
- if (sizeof (double) != record->value_size)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Received an invalid sensor value."));
- return GNUNET_YES;
- }
- val = (double *) (record->value);
- anomalous = model_api->feed_model (model->cls, *val);
- if (GNUNET_YES == anomalous)
- {
- model->positive_count++;
- model->negative_count = 0;
- if (GNUNET_NO == model->anomalous &&
- model->positive_count >= confirmation_count)
- {
- model->anomalous = GNUNET_YES;
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "Anomaly state started for sensor `%s', value: %f.\n",
- model->sensor->name, val);
- SENSOR_reporting_anomaly_update (model->sensor, model->anomalous);
- }
- }
- else
- {
- model->negative_count++;
- model->positive_count = 0;
- if (GNUNET_YES == model->anomalous &&
- model->negative_count >= confirmation_count)
- {
- model->anomalous = GNUNET_NO;
- LOG (GNUNET_ERROR_TYPE_INFO,
- "Anomaly state stopped for sensor `%s', value: %f.\n",
- model->sensor->name, val);
- SENSOR_reporting_anomaly_update (model->sensor, model->anomalous);
- }
- }
- return GNUNET_YES;
-}
-
-
-/**
- * Iterator for defined sensors
- * Creates sensor model for numeric sensors
- *
- * @param cls unused
- * @param key unused
- * @param value a 'struct GNUNET_SENSOR_SensorInfo *' with sensor information
- * @return #GNUNET_YES to continue iterations
- */
-static int
-init_sensor_model (void *cls, const struct GNUNET_HashCode *key, void *value)
-{
- struct GNUNET_SENSOR_SensorInfo *sensor = value;
- struct SensorModel *sensor_model;
-
- if (0 != strcmp ("numeric", sensor->expected_datatype))
- return GNUNET_YES;
- sensor_model = GNUNET_new (struct SensorModel);
- sensor_model->sensor = sensor;
- sensor_model->wc =
- GNUNET_PEERSTORE_watch (peerstore, "sensor", &peerid, sensor->name,
- &sensor_watcher, sensor_model);
- sensor_model->anomalous = GNUNET_NO;
- sensor_model->positive_count = 0;
- sensor_model->negative_count = 0;
- sensor_model->cls = model_api->create_model (model_api->cls);
- GNUNET_CONTAINER_DLL_insert (models_head, models_tail, sensor_model);
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Created sensor model for `%s'.\n",
- sensor->name);
- return GNUNET_YES;
-}
-
-
-/**
- * Start the sensor analysis module
- *
- * @param c our service configuration
- * @param sensors multihashmap of loaded sensors
- * @return #GNUNET_OK if started successfully, #GNUNET_SYSERR otherwise
- */
-int
-SENSOR_analysis_start (const struct GNUNET_CONFIGURATION_Handle *c,
- struct GNUNET_CONTAINER_MultiHashMap *s)
-{
- char *model_name;
-
- GNUNET_assert (NULL != s);
- cfg = c;
- sensors = s;
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_string (cfg, "sensor-analysis", "MODEL",
- &model_name))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Analysis model not defined in configuration.\n"));
- return GNUNET_SYSERR;
- }
- GNUNET_asprintf (&model_lib_name, "libgnunet_plugin_sensor_model_%s",
- model_name);
- model_api = GNUNET_PLUGIN_load (model_lib_name, (void *) cfg);
- GNUNET_free (model_name);
- if (NULL == model_api)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Could not load analysis model `%s'.\n"),
- model_lib_name);
- return GNUNET_SYSERR;
- }
- peerstore = GNUNET_PEERSTORE_connect (cfg);
- if (NULL == peerstore)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Could not connect to peerstore service.\n"));
- SENSOR_analysis_stop ();
- return GNUNET_SYSERR;
- }
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_number (cfg, "sensor-analysis",
- "CONFIRMATION_COUNT",
- &confirmation_count))
- confirmation_count = 1;
- GNUNET_CRYPTO_get_peer_identity (cfg, &peerid);
- GNUNET_CONTAINER_multihashmap_iterate (sensors, &init_sensor_model, NULL);
- return GNUNET_OK;
-}
-
-/* end of gnunet-service-sensor_analysis.c */
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/gnunet-service-sensor_analysis.c
- * @brief sensor service analysis functionality
- * @author Omar Tarabai
- */
-#include <inttypes.h>
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "sensor.h"
-#include "gnunet_statistics_service.h"
-#include "gnunet_peerstore_service.h"
-
-#define LOG(kind,...) GNUNET_log_from (kind, "sensor-monitoring",__VA_ARGS__)
-
-/**
- * Our configuration.
- */
-static const struct GNUNET_CONFIGURATION_Handle *cfg;
-
-/**
- * Hashmap of loaded sensor definitions
- */
-static struct GNUNET_CONTAINER_MultiHashMap *sensors;
-
-/**
- * Path to sensor definitions directory
- */
-static char *sensor_dir;
-
-/**
- * Handle to statistics service
- */
-static struct GNUNET_STATISTICS_Handle *statistics;
-
-/**
- * Handle to peerstore service
- */
-static struct GNUNET_PEERSTORE_Handle *peerstore;
-
-/**
- * My peer id
- */
-static struct GNUNET_PeerIdentity peerid;
-
-
-/**
- * Stop the sensor monitoring module
- */
-void
-SENSOR_monitoring_stop ()
-{
- if (NULL != statistics)
- {
- GNUNET_STATISTICS_destroy (statistics, GNUNET_YES);
- statistics = NULL;
- }
- if (NULL != peerstore)
- {
- GNUNET_PEERSTORE_disconnect (peerstore, GNUNET_YES);
- peerstore = NULL;
- }
- if (NULL != sensor_dir)
- {
- GNUNET_free (sensor_dir);
- sensor_dir = NULL;
- }
-}
-
-
-/**
- * Change the state of the sensor.
- * Write the change to file to make it persistent.
- *
- * @param sensor sensor info struct
- * @param state new enabled state: #GNUNET_YES / #GNUNET_NO
- */
-static void
-set_sensor_enabled (struct GNUNET_SENSOR_SensorInfo *sensor, int state)
-{
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Sensor `%s': Setting enabled to %d.\n",
- sensor->name, state);
- sensor->enabled = GNUNET_NO;
- GNUNET_assert (NULL != sensor->cfg);
- GNUNET_CONFIGURATION_set_value_string (sensor->cfg, sensor->name, "ENABLED",
- (GNUNET_YES == state) ? "YES" : "NO");
- GNUNET_CONFIGURATION_write (sensor->cfg, sensor->def_file);
-}
-
-
-/**
- * Do a series of checks to determine if sensor should execute
- *
- * @return #GNUNET_YES / #GNUNET_NO
- */
-static int
-should_run_sensor (struct GNUNET_SENSOR_SensorInfo *sensorinfo)
-{
- struct GNUNET_TIME_Absolute now;
-
- if (GNUNET_NO == sensorinfo->enabled)
- {
- LOG (GNUNET_ERROR_TYPE_INFO, "Sensor `%s' is disabled, will not run\n",
- sensorinfo->name);
- return GNUNET_NO;
- }
- now = GNUNET_TIME_absolute_get ();
- if (NULL != sensorinfo->start_time &&
- now.abs_value_us < sensorinfo->start_time->abs_value_us)
- {
- LOG (GNUNET_ERROR_TYPE_INFO,
- "Start time for sensor `%s' not reached yet, will not run\n",
- sensorinfo->name);
- return GNUNET_NO;
- }
- if (NULL != sensorinfo->end_time &&
- now.abs_value_us >= sensorinfo->end_time->abs_value_us)
- {
- LOG (GNUNET_ERROR_TYPE_INFO, "Sensor `%s' expired, disabling.\n",
- sensorinfo->name);
- set_sensor_enabled (sensorinfo, GNUNET_NO);
- return GNUNET_NO;
- }
- return GNUNET_YES;
-}
-
-
-/**
- * Callback function to process statistic values
- *
- * @param cls `struct GNUNET_SENSOR_SensorInfo *`
- * @param ss name of subsystem that created the statistic
- * @param name the name of the datum
- * @param value the current value
- * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
- * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
- */
-static int
-sensor_statistics_iterator (void *cls, const char *ss, const char *name,
- uint64_t value, int is_persistent)
-{
- struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
- double dvalue = (double) value;
- struct GNUNET_TIME_Absolute expiry;
-
- LOG (GNUNET_ERROR_TYPE_INFO,
- "Received a value for sensor `%s': %" PRIu64 "\n", sensorinfo->name,
- value);
- expiry = GNUNET_TIME_relative_to_absolute (sensorinfo->lifetime);
- GNUNET_PEERSTORE_store (peerstore, "sensor", &peerid, sensorinfo->name,
- &dvalue, sizeof (dvalue), expiry,
- GNUNET_PEERSTORE_STOREOPTION_MULTIPLE, NULL, NULL);
- return GNUNET_SYSERR; /* We only want one value */
-}
-
-
-/**
- * Continuation called after sensor gets all gnunet statistics values
- *
- * @param cls `struct GNUNET_SENSOR_SensorInfo *`
- * @param success #GNUNET_OK if statistics were
- * successfully obtained, #GNUNET_SYSERR if not.
- */
-static void
-end_sensor_run_stat (void *cls, int success)
-{
- struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
-
- sensorinfo->gnunet_stat_get_handle = NULL;
- sensorinfo->running = GNUNET_NO;
-}
-
-
-/**
- * Tries to parse a received sensor value to its
- * expected datatype
- *
- * @param value the string value received, should be null terminated
- * @param sensor sensor information struct
- * @param ret pointer to parsed value
- * @return size of new parsed value, 0 for error
- */
-static size_t
-parse_sensor_value (const char *value,
- struct GNUNET_SENSOR_SensorInfo *sensor,
- void **ret)
-{
- double *dval;
- char *endptr;
-
- *ret = NULL;
- if ('\0' == *value)
- return 0;
- if (0 == strcmp ("numeric", sensor->expected_datatype))
- {
- dval = GNUNET_new (double);
-
- *dval = strtod (value, &endptr);
- if (value == endptr)
- {
- GNUNET_free (dval);
- *ret = NULL;
- return 0;
- }
- *ret = dval;
- return sizeof (double);
- }
- if (0 == strcmp ("string", sensor->expected_datatype))
- {
- *ret = GNUNET_strdup (value);
- return strlen (value) + 1;
- }
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Unknown value type expected by sensor, this should not happen.\n"));
- return 0;
-}
-
-
-/**
- * Callback for output of executed sensor process
- *
- * @param cls `struct GNUNET_SENSOR_SensorInfo *`
- * @param line line of output from a command, NULL for the end
- */
-static void
-sensor_process_callback (void *cls, const char *line)
-{
- struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
- void *value;
- size_t valsize;
- struct GNUNET_TIME_Absolute expiry;
-
- if (NULL == line)
- {
- GNUNET_OS_command_stop (sensorinfo->ext_cmd);
- sensorinfo->ext_cmd = NULL;
- sensorinfo->running = GNUNET_NO;
- sensorinfo->ext_cmd_value_received = GNUNET_NO;
- return;
- }
- if (GNUNET_YES == sensorinfo->ext_cmd_value_received)
- return; /* We only want one *valid* value */
- LOG (GNUNET_ERROR_TYPE_INFO, "Received a value for sensor `%s': %s\n",
- sensorinfo->name, line);
- valsize = parse_sensor_value (line, sensorinfo, &value);
- if (valsize == 0) /* invalid value, FIXME: should we disable the sensor now? */
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Received an invalid value for sensor `%s': %s\n"), sensorinfo->name,
- line);
- }
- else
- {
- sensorinfo->ext_cmd_value_received = GNUNET_YES;
- expiry = GNUNET_TIME_relative_to_absolute (sensorinfo->lifetime);
- GNUNET_PEERSTORE_store (peerstore, "sensor", &peerid, sensorinfo->name,
- value, valsize, expiry,
- GNUNET_PEERSTORE_STOREOPTION_MULTIPLE, NULL, NULL);
- GNUNET_free (value);
- }
-}
-
-
-/**
- * Checks if the given file is a path
- *
- * @return #GNUNET_YES / #GNUNET_NO
- */
-static int
-is_path (char *filename)
-{
- size_t filename_len;
- int i;
-
- filename_len = strlen (filename);
- for (i = 0; i < filename_len; i++)
- {
- if (DIR_SEPARATOR == filename[i])
- return GNUNET_YES;
- }
- return GNUNET_NO;
-}
-
-
-/**
- * Actual execution of a sensor
- *
- * @param cls 'struct SensorInfo'
- * @param tc unsed
- */
-static void
-sensor_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
- int check_result;
- char *process_path;
-
- sensorinfo->execution_task =
- GNUNET_SCHEDULER_add_delayed (sensorinfo->interval, &sensor_run,
- sensorinfo);
- if (GNUNET_YES == sensorinfo->running) //FIXME: should we try to kill?
- {
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "Sensor `%s' running for too long, will try again next interval\n",
- sensorinfo->name);
- return;
- }
- if (GNUNET_NO == should_run_sensor (sensorinfo))
- return;
- sensorinfo->running = GNUNET_YES;
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting the execution of sensor `%s'\n",
- sensorinfo->name);
- if (0 == strcmp ("gnunet-statistics", sensorinfo->source))
- {
- sensorinfo->gnunet_stat_get_handle = GNUNET_STATISTICS_get (statistics, sensorinfo->gnunet_stat_service, sensorinfo->gnunet_stat_name, sensorinfo->interval, //try to get values only for the interval of the sensor
- &end_sensor_run_stat,
- &sensor_statistics_iterator,
- sensorinfo);
- if (NULL == sensorinfo->gnunet_stat_get_handle)
- sensorinfo->running = GNUNET_NO;
- }
- else if (0 == strcmp ("process", sensorinfo->source))
- {
- if (GNUNET_YES == is_path (sensorinfo->ext_process))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _
- ("Sensor `%s': External process should not be a path, disabling sensor.\n"),
- sensorinfo->name);
- set_sensor_enabled (sensorinfo, GNUNET_NO);
- return;
- }
- //check if the process exists in $PATH
- process_path = GNUNET_strdup (sensorinfo->ext_process);
- check_result =
- GNUNET_OS_check_helper_binary (process_path, GNUNET_NO, NULL);
- if (GNUNET_SYSERR == check_result)
- {
- //search in sensor directory
- GNUNET_free (process_path);
- GNUNET_asprintf (&process_path, "%s%s-files%s%s", sensor_dir,
- sensorinfo->name, DIR_SEPARATOR_STR,
- sensorinfo->ext_process);
- check_result =
- GNUNET_OS_check_helper_binary (process_path, GNUNET_NO, NULL);
- }
- if (GNUNET_SYSERR == check_result)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _
- ("Sensor `%s' process `%s' problem: binary doesn't exist or not executable\n"),
- sensorinfo->name, sensorinfo->ext_process);
- set_sensor_enabled (sensorinfo, GNUNET_NO);
- sensorinfo->running = GNUNET_NO;
- GNUNET_free (process_path);
- return;
- }
- sensorinfo->ext_cmd_value_received = GNUNET_NO;
- sensorinfo->ext_cmd =
- GNUNET_OS_command_run (&sensor_process_callback, sensorinfo,
- GNUNET_TIME_UNIT_FOREVER_REL, process_path,
- sensorinfo->ext_process, sensorinfo->ext_args,
- NULL);
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Process started for sensor `%s'\n",
- sensorinfo->name);
- GNUNET_free (process_path);
- }
- else
- {
- sensorinfo->running = GNUNET_NO;
- GNUNET_break (0); /* shouldn't happen */
- }
-}
-
-
-/**
- * Starts the execution of a sensor
- *
- * @param cls unused
- * @param key hash of sensor name, key to hashmap (unused)
- * @param value a `struct GNUNET_SENSOR_SensorInfo *`
- * @return #GNUNET_YES if we should continue to
- * iterate,
- * #GNUNET_NO if not.
- */
-static int
-schedule_sensor (void *cls, const struct GNUNET_HashCode *key, void *value)
-{
- struct GNUNET_SENSOR_SensorInfo *sensorinfo = value;
-
- if (GNUNET_NO == should_run_sensor (sensorinfo))
- return GNUNET_YES;
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "Scheduling sensor `%s' to run after %" PRIu64 " microseconds\n",
- sensorinfo->name, sensorinfo->interval.rel_value_us);
- if (NULL != sensorinfo->execution_task)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Sensor `%s' execution task already set, this should not happen\n"),
- sensorinfo->name);
- return GNUNET_NO;
- }
- sensorinfo->execution_task =
- GNUNET_SCHEDULER_add_delayed (sensorinfo->interval, &sensor_run,
- sensorinfo);
- return GNUNET_YES;
-}
-
-
-/**
- * Starts the execution of all enabled sensors
- */
-static void
-schedule_all_sensors ()
-{
- GNUNET_CONTAINER_multihashmap_iterate (sensors, &schedule_sensor, NULL);
-}
-
-
-/**
- * Start the sensor monitoring module
- *
- * @param c our service configuration
- * @param sensors multihashmap of loaded sensors
- * @return #GNUNET_OK if started successfully, #GNUNET_SYSERR otherwise
- */
-int
-SENSOR_monitoring_start (const struct GNUNET_CONFIGURATION_Handle *c,
- struct GNUNET_CONTAINER_MultiHashMap *s)
-{
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting sensor reporting module.\n");
- GNUNET_assert (NULL != s);
- sensors = s;
- cfg = c;
- statistics = GNUNET_STATISTICS_create ("sensor", cfg);
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_filename (cfg, "SENSOR", "SENSOR_DIR",
- &sensor_dir))
- {
- sensor_dir = GNUNET_SENSOR_get_default_sensor_dir ();
- }
- if (NULL == statistics)
- {
- SENSOR_monitoring_stop ();
- return GNUNET_SYSERR;
- }
- peerstore = GNUNET_PEERSTORE_connect (cfg);
- if (NULL == peerstore)
- {
- SENSOR_monitoring_stop ();
- return GNUNET_SYSERR;
- }
- GNUNET_CRYPTO_get_peer_identity (cfg, &peerid);
- schedule_all_sensors ();
- return GNUNET_OK;
-}
-
-/* end of gnunet-service-sensor_analysis.c */
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/gnunet-service-sensor_reporting.c
- * @brief sensor service reporting functionality
- * @author Omar Tarabai
- */
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "sensor.h"
-#include "gnunet_peerstore_service.h"
-#include "gnunet_core_service.h"
-#include "gnunet_cadet_service.h"
-#include "gnunet_applications.h"
-
-#define LOG(kind,...) GNUNET_log_from (kind, "sensor-reporting",__VA_ARGS__)
-
-/**
- * Retry time when failing to connect to collection point
- */
-#define CP_RETRY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
-
-
-/**
- * When we are still generating a proof-of-work and we need to send an anomaly
- * report, we queue them until the generation is complete
- */
-struct AnomalyReportingQueueItem
-{
-
- /**
- * DLL
- */
- struct AnomalyReportingQueueItem *prev;
-
- /**
- * DLL
- */
- struct AnomalyReportingQueueItem *next;
-
- /**
- * Message queue belonging to the peer that is the destination of the report
- */
- struct GNUNET_MQ_Handle *dest_mq;
-
- /**
- * Report type
- */
- int type;
-
-};
-
-struct AnomalyInfo
-{
-
- /**
- * DLL
- */
- struct AnomalyInfo *prev;
-
- /**
- * DLL
- */
- struct AnomalyInfo *next;
-
- /**
- * Sensor information
- */
- struct GNUNET_SENSOR_SensorInfo *sensor;
-
- /**
- * Current anomalous status of sensor
- */
- int anomalous;
-
- /**
- * List of peers that reported an anomaly for this sensor
- */
- struct GNUNET_CONTAINER_MultiPeerMap *anomalous_neighbors;
-
- /**
- * Report block with proof-of-work and signature
- */
- struct GNUNET_SENSOR_crypto_pow_block *report_block;
-
- /**
- * Context of an operation creating pow and signature
- */
- struct GNUNET_SENSOR_crypto_pow_context *report_creation_cx;
-
- /**
- * Head of the queue of pending report destinations
- */
- struct AnomalyReportingQueueItem *reporting_queue_head;
-
- /**
- * Head of the queue of pending report destinations
- */
- struct AnomalyReportingQueueItem *reporting_queue_tail;
-
-};
-
-struct ValueInfo
-{
-
- /**
- * DLL
- */
- struct ValueInfo *prev;
-
- /**
- * DLL
- */
- struct ValueInfo *next;
-
- /**
- * Sensor information
- */
- struct GNUNET_SENSOR_SensorInfo *sensor;
-
- /**
- * Last value read from sensor
- */
- void *last_value;
-
- /**
- * Size of @e last_value
- */
- size_t last_value_size;
-
- /**
- * Timestamp of last value reading
- */
- struct GNUNET_TIME_Absolute last_value_timestamp;
-
- /**
- * Has the last value seen already been reported to collection point?
- */
- int last_value_reported;
-
- /**
- * Watcher of sensor values
- */
- struct GNUNET_PEERSTORE_WatchContext *wc;
-
- /**
- * Collection point reporting task (or NULL)
- */
- struct GNUNET_SCHEDULER_Task *reporting_task;
-
-};
-
-/**
- * Information about a connected CORE peer.
- * Note that we only know about a connected peer if it is running the same
- * application (sensor anomaly reporting) as us.
- */
-struct CorePeer
-{
-
- /**
- * DLL
- */
- struct CorePeer *prev;
-
- /**
- * DLL
- */
- struct CorePeer *next;
-
- /**
- * Peer identity of connected peer
- */
- struct GNUNET_PeerIdentity *peer_id;
-
- /**
- * Message queue for messages to be sent to this peer
- */
- struct GNUNET_MQ_Handle *mq;
-
-};
-
-/**
- * Information about a connected CADET peer (collection point).
- */
-struct CadetPeer
-{
-
- /**
- * DLL
- */
- struct CadetPeer *prev;
-
- /**
- * DLL
- */
- struct CadetPeer *next;
-
- /**
- * Peer Identity
- */
- struct GNUNET_PeerIdentity peer_id;
-
- /**
- * CADET channel handle
- */
- struct GNUNET_CADET_Channel *channel;
-
- /**
- * Message queue for messages to be sent to this peer
- */
- struct GNUNET_MQ_Handle *mq;
-
- /**
- * CADET transmit handle
- */
- struct GNUNET_CADET_TransmitHandle *th;
-
- /**
- * Task used to try reconnection to collection point after failure
- */
- struct GNUNET_SCHEDULER_Task * reconnect_task;
-
- /**
- * Are we currently destroying the channel and its context?
- */
- int destroying;
-
-};
-
-
-/**
- * Our configuration.
- */
-static const struct GNUNET_CONFIGURATION_Handle *cfg;
-
-/**
- * Multihashmap of loaded sensors
- */
-static struct GNUNET_CONTAINER_MultiHashMap *sensors;
-
-/**
- * Handle to peerstore service
- */
-static struct GNUNET_PEERSTORE_Handle *peerstore;
-
-/**
- * Handle to core service
- */
-static struct GNUNET_CORE_Handle *core;
-
-/**
- * Handle to CADET service
- */
-static struct GNUNET_CADET_Handle *cadet;
-
-/**
- * My peer id
- */
-static struct GNUNET_PeerIdentity mypeerid;
-
-/**
- * My private key
- */
-static struct GNUNET_CRYPTO_EddsaPrivateKey *private_key;
-
-/**
- * Head of DLL of anomaly info structs
- */
-static struct AnomalyInfo *ai_head;
-
-/**
- * Tail of DLL of anomaly info structs
- */
-static struct AnomalyInfo *ai_tail;
-
-/**
- * Head of DLL of value info structs
- */
-static struct ValueInfo *vi_head;
-
-/**
- * Tail of DLL of value info structs
- */
-static struct ValueInfo *vi_tail;
-
-/**
- * Head of DLL of CORE peers
- */
-static struct CorePeer *corep_head;
-
-/**
- * Tail of DLL of CORE peers
- */
-static struct CorePeer *corep_tail;
-
-/**
- * Head of DLL of CADET peers
- */
-static struct CadetPeer *cadetp_head;
-
-/**
- * Tail of DLL of CADET peers
- */
-static struct CadetPeer *cadetp_tail;
-
-/**
- * Is the module started?
- */
-static int module_running = GNUNET_NO;
-
-/**
- * Number of known neighborhood peers
- */
-static int neighborhood;
-
-/**
- * Parameter that defines the complexity of the proof-of-work
- */
-static long long unsigned int pow_matching_bits;
-
-
-
-/**
- * Try reconnecting to collection point and send last queued message
- */
-static void
-cp_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
-
-
-/******************************************************************************/
-/****************************** CLEANUP ******************************/
-/******************************************************************************/
-
-/**
- * Destroy anomaly info struct
- *
- * @param ai struct to destroy
- */
-static void
-destroy_anomaly_info (struct AnomalyInfo *ai)
-{
- struct AnomalyReportingQueueItem *ar_item;
-
- ar_item = ai->reporting_queue_head;
- while (NULL != ar_item)
- {
- GNUNET_CONTAINER_DLL_remove (ai->reporting_queue_head,
- ai->reporting_queue_tail, ar_item);
- GNUNET_free (ar_item);
- ar_item = ai->reporting_queue_head;
- }
- if (NULL != ai->report_creation_cx)
- {
- GNUNET_SENSOR_crypto_pow_sign_cancel (ai->report_creation_cx);
- ai->report_creation_cx = NULL;
- }
- if (NULL != ai->report_block)
- {
- GNUNET_free (ai->report_block);
- ai->report_block = NULL;
- }
- if (NULL != ai->anomalous_neighbors)
- {
- GNUNET_CONTAINER_multipeermap_destroy (ai->anomalous_neighbors);
- ai->anomalous_neighbors = NULL;
- }
- GNUNET_free (ai);
-}
-
-
-/**
- * Destroy value info struct
- *
- * @param vi struct to destroy
- */
-static void
-destroy_value_info (struct ValueInfo *vi)
-{
- if (NULL != vi->wc)
- {
- GNUNET_PEERSTORE_watch_cancel (vi->wc);
- vi->wc = NULL;
- }
- if (NULL != vi->reporting_task)
- {
- GNUNET_SCHEDULER_cancel (vi->reporting_task);
- vi->reporting_task = NULL;
- }
- if (NULL != vi->last_value)
- {
- GNUNET_free (vi->last_value);
- vi->last_value = NULL;
- }
- GNUNET_free (vi);
-}
-
-
-/**
- * Destroy core peer struct
- *
- * @param corep struct to destroy
- */
-static void
-destroy_core_peer (struct CorePeer *corep)
-{
- struct AnomalyInfo *ai;
- struct AnomalyReportingQueueItem *ar_item;
-
- ai = ai_head;
- while (NULL != ai)
- {
- GNUNET_assert (NULL != ai->anomalous_neighbors);
- GNUNET_CONTAINER_multipeermap_remove_all (ai->anomalous_neighbors,
- corep->peer_id);
- /* Remove the core peer from any reporting queues */
- ar_item = ai->reporting_queue_head;
- while (NULL != ar_item)
- {
- if (ar_item->dest_mq == corep->mq)
- {
- GNUNET_CONTAINER_DLL_remove (ai->reporting_queue_head,
- ai->reporting_queue_tail, ar_item);
- break;
- }
- ar_item = ar_item->next;
- }
- ai = ai->next;
- }
- if (NULL != corep->mq)
- {
- GNUNET_MQ_destroy (corep->mq);
- corep->mq = NULL;
- }
- GNUNET_free (corep);
-}
-
-
-/**
- * Destroy cadet peer struct
- *
- * @param cadetp struct to destroy
- */
-static void
-destroy_cadet_peer (struct CadetPeer *cadetp)
-{
- cadetp->destroying = GNUNET_YES;
- if (NULL != cadetp->reconnect_task)
- {
- GNUNET_SCHEDULER_cancel (cadetp->reconnect_task);
- cadetp->reconnect_task = NULL;
- }
- if (NULL != cadetp->mq)
- {
- GNUNET_MQ_destroy (cadetp->mq);
- cadetp->mq = NULL;
- }
- if (NULL != cadetp->channel)
- {
- GNUNET_CADET_channel_destroy (cadetp->channel);
- cadetp->channel = NULL;
- }
- GNUNET_free (cadetp);
-}
-
-
-/**
- * Stop sensor reporting module
- */
-void
-SENSOR_reporting_stop ()
-{
- struct ValueInfo *vi;
- struct CorePeer *corep;
- struct AnomalyInfo *ai;
- struct CadetPeer *cadetp;
-
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Stopping sensor anomaly reporting module.\n");
- module_running = GNUNET_NO;
- neighborhood = 0;
- /* Destroy value info's */
- vi = vi_head;
- while (NULL != vi)
- {
- GNUNET_CONTAINER_DLL_remove (vi_head, vi_tail, vi);
- destroy_value_info (vi);
- vi = vi_head;
- }
- /* Destroy core peers */
- corep = corep_head;
- while (NULL != corep)
- {
- GNUNET_CONTAINER_DLL_remove (corep_head, corep_tail, corep);
- destroy_core_peer (corep);
- corep = corep_head;
- }
- /* Destroy anomaly info's */
- ai = ai_head;
- while (NULL != ai)
- {
- GNUNET_CONTAINER_DLL_remove (ai_head, ai_tail, ai);
- destroy_anomaly_info (ai);
- ai = ai_head;
- }
- /* Destroy cadet peers */
- cadetp = cadetp_head;
- while (NULL != cadetp)
- {
- GNUNET_CONTAINER_DLL_remove (cadetp_head, cadetp_tail, cadetp);
- destroy_cadet_peer (cadetp);
- cadetp = cadetp_head;
- }
- /* Disconnect from other services */
- if (NULL != core)
- {
- GNUNET_CORE_disconnect (core);
- core = NULL;
- }
- if (NULL != peerstore)
- {
- GNUNET_PEERSTORE_disconnect (peerstore, GNUNET_NO);
- peerstore = NULL;
- }
- if (NULL != cadet)
- {
- GNUNET_CADET_disconnect (cadet);
- cadet = NULL;
- }
-}
-
-
-/******************************************************************************/
-/****************************** HELPERS ******************************/
-/******************************************************************************/
-
-
-/**
- * Gets the anomaly info struct related to the given sensor
- *
- * @param sensor Sensor to search by
- */
-static struct AnomalyInfo *
-get_anomaly_info_by_sensor (struct GNUNET_SENSOR_SensorInfo *sensor)
-{
- struct AnomalyInfo *ai;
-
- ai = ai_head;
- while (NULL != ai)
- {
- if (ai->sensor == sensor)
- {
- return ai;
- }
- ai = ai->next;
- }
- return NULL;
-}
-
-
-/**
- * Function called to notify a client about the connection
- * begin ready to queue more data. "buf" will be
- * NULL and "size" zero if the connection was closed for
- * writing in the meantime.
- *
- * @param cls closure
- * @param size number of bytes available in buf
- * @param buf where the callee should write the message
- * @return number of bytes written to buf
- */
-static size_t
-cp_mq_ntr (void *cls, size_t size, void *buf)
-{
- struct CadetPeer *cadetp = cls;
- const struct GNUNET_MessageHeader *msg = GNUNET_MQ_impl_current (cadetp->mq);
- uint16_t msize;
-
- LOG (GNUNET_ERROR_TYPE_DEBUG, "cp_mq_ntr()\n");
- cadetp->th = NULL;
- if (NULL == buf)
- {
- LOG (GNUNET_ERROR_TYPE_INFO,
- "Sending anomaly report to collection point failed."
- " Retrying connection in %s.\n",
- GNUNET_STRINGS_relative_time_to_string (CP_RETRY, GNUNET_NO));
- cadetp->reconnect_task =
- GNUNET_SCHEDULER_add_delayed (CP_RETRY, &cp_reconnect, cadetp);
- return 0;
- }
- msize = ntohs (msg->size);
- GNUNET_assert (msize <= size);
- memcpy (buf, msg, msize);
- GNUNET_MQ_impl_send_continue (cadetp->mq);
- return msize;
-}
-
-
-/**
- * Try reconnecting to collection point and send last queued message
- */
-static void
-cp_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct CadetPeer *cadetp = cls;
- const struct GNUNET_MessageHeader *msg;
-
- LOG (GNUNET_ERROR_TYPE_INFO,
- "Retrying connection to collection point `%s'.\n",
- GNUNET_i2s (&cadetp->peer_id));
- cadetp->reconnect_task = NULL;
- GNUNET_assert (NULL == cadetp->channel);
- cadetp->channel =
- GNUNET_CADET_channel_create (cadet, cadetp, &cadetp->peer_id,
- GNUNET_APPLICATION_TYPE_SENSORDASHBOARD,
- GNUNET_CADET_OPTION_RELIABLE);
- msg = GNUNET_MQ_impl_current (cadetp->mq);
- cadetp->th =
- GNUNET_CADET_notify_transmit_ready (cadetp->channel, GNUNET_NO,
- GNUNET_TIME_UNIT_FOREVER_REL,
- ntohs (msg->size), cp_mq_ntr, cadetp);
-}
-
-
-/**
- * Signature of functions implementing the
- * sending functionality of a message queue.
- *
- * @param mq the message queue
- * @param msg the message to send
- * @param impl_state state of the implementation
- */
-static void
-cp_mq_send_impl (struct GNUNET_MQ_Handle *mq,
- const struct GNUNET_MessageHeader *msg, void *impl_state)
-{
- struct CadetPeer *cadetp = impl_state;
-
- LOG (GNUNET_ERROR_TYPE_DEBUG, "cp_mq_send_impl()\n");
- GNUNET_assert (NULL == cadetp->th);
- if (NULL == cadetp->channel)
- {
- LOG (GNUNET_ERROR_TYPE_INFO,
- "Sending anomaly report to collection point failed."
- " Retrying connection in %s.\n",
- GNUNET_STRINGS_relative_time_to_string (CP_RETRY, GNUNET_NO));
- cadetp->reconnect_task =
- GNUNET_SCHEDULER_add_delayed (CP_RETRY, &cp_reconnect, cadetp);
- return;
- }
- cadetp->th =
- GNUNET_CADET_notify_transmit_ready (cadetp->channel, GNUNET_NO,
- GNUNET_TIME_UNIT_FOREVER_REL,
- ntohs (msg->size), cp_mq_ntr, cadetp);
-}
-
-
-/**
- * Signature of functions implementing the
- * destruction of a message queue.
- * Implementations must not free 'mq', but should
- * take care of 'impl_state'.
- *
- * @param mq the message queue to destroy
- * @param impl_state state of the implementation
- */
-static void
-cp_mq_destroy_impl (struct GNUNET_MQ_Handle *mq, void *impl_state)
-{
- struct CadetPeer *cp = impl_state;
-
- LOG (GNUNET_ERROR_TYPE_DEBUG, "cp_mq_destroy_impl()\n");
- if (NULL != cp->th)
- {
- GNUNET_CADET_notify_transmit_ready_cancel (cp->th);
- cp->th = NULL;
- }
-}
-
-
-/**
- * Create the message queue used to send messages to a collection point.
- * This will be used to make sure that the message are queued even if the
- * connection to the collection point can not be established at the moment.
- *
- * @param cp CadetPeer information struct
- * @return Message queue handle
- */
-static struct GNUNET_MQ_Handle *
-cp_mq_create (struct CadetPeer *cp)
-{
- return GNUNET_MQ_queue_for_callbacks (cp_mq_send_impl, cp_mq_destroy_impl,
- NULL, cp, NULL, NULL, NULL);
-}
-
-
-/**
- * Returns context of a connected CADET peer.
- * Creates it first if didn't exist before.
- *
- * @param pid Peer Identity
- * @return Context of connected CADET peer
- */
-static struct CadetPeer *
-get_cadet_peer (struct GNUNET_PeerIdentity pid)
-{
- struct CadetPeer *cadetp;
-
- cadetp = cadetp_head;
- while (NULL != cadetp)
- {
- if (0 == GNUNET_CRYPTO_cmp_peer_identity (&pid, &cadetp->peer_id))
- return cadetp;
- cadetp = cadetp->next;
- }
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating a CADET connection to peer `%s'.\n",
- GNUNET_i2s (&pid));
- /* Not found, create struct and channel */
- cadetp = GNUNET_new (struct CadetPeer);
- cadetp->peer_id = pid;
- cadetp->channel =
- GNUNET_CADET_channel_create (cadet, cadetp, &pid,
- GNUNET_APPLICATION_TYPE_SENSORDASHBOARD,
- GNUNET_CADET_OPTION_RELIABLE);
- cadetp->mq = cp_mq_create (cadetp);
- cadetp->reconnect_task = NULL;
- GNUNET_CONTAINER_DLL_insert (cadetp_head, cadetp_tail, cadetp);
- return cadetp;
-}
-
-
-/**
- * This function is called only when we have a block ready and want to send it
- * to the given peer (represented by its message queue)
- *
- * @param mq Message queue to put the message in
- * @param ai Anomaly info to report
- * @param type Message type
- */
-static void
-do_send_anomaly_report (struct GNUNET_MQ_Handle *mq, struct AnomalyInfo *ai,
- int type)
-{
- struct GNUNET_MessageHeader *msg;
- struct GNUNET_MQ_Envelope *ev;
- size_t block_size;
-
- GNUNET_assert (NULL != ai->report_block);
- block_size =
- sizeof (struct GNUNET_SENSOR_crypto_pow_block) +
- ai->report_block->msg_size;
- ev = GNUNET_MQ_msg_header_extra (msg, block_size, type);
- memcpy (&msg[1], ai->report_block, block_size);
- GNUNET_MQ_send (mq, ev);
-}
-
-
-/**
- * Check if we have signed and proof-of-work block ready.
- * If yes, we send the report directly, if no, we enqueue the reporting until
- * the block is ready.
- *
- * @param mq Message queue to put the message in
- * @param ai Anomaly info to report
- * @param p2p Is the report sent to a neighboring peer
- */
-static void
-send_anomaly_report (struct GNUNET_MQ_Handle *mq, struct AnomalyInfo *ai,
- int p2p)
-{
- struct AnomalyReportingQueueItem *ar_item;
- int type;
-
- type =
- (GNUNET_YES ==
- p2p) ? GNUNET_MESSAGE_TYPE_SENSOR_ANOMALY_REPORT_P2P :
- GNUNET_MESSAGE_TYPE_SENSOR_ANOMALY_REPORT;
- if (NULL == ai->report_block)
- {
- ar_item = GNUNET_new (struct AnomalyReportingQueueItem);
-
- ar_item->dest_mq = mq;
- ar_item->type = type;
- GNUNET_CONTAINER_DLL_insert_tail (ai->reporting_queue_head,
- ai->reporting_queue_tail, ar_item);
- }
- else
- {
- do_send_anomaly_report (mq, ai, type);
- }
-}
-
-
-/**
- * Callback when the crypto module finished created proof-of-work and signature
- * for an anomaly report.
- *
- * @param cls Closure, a `struct AnomalyInfo *`
- * @param block The resulting block, NULL on error
- */
-static void
-report_creation_cb (void *cls, struct GNUNET_SENSOR_crypto_pow_block *block)
-{
- struct AnomalyInfo *ai = cls;
- struct AnomalyReportingQueueItem *ar_item;
-
- ai->report_creation_cx = NULL;
- if (NULL != ai->report_block)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Double creation of proof-of-work, this should not happen.\n"));
- return;
- }
- if (NULL == block)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Failed to create pow and signature block.\n"));
- return;
- }
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Anomaly report POW block ready.\n");
- ai->report_block =
- GNUNET_memdup (block,
- sizeof (struct GNUNET_SENSOR_crypto_pow_block) +
- block->msg_size);
- ar_item = ai->reporting_queue_head;
- while (NULL != ar_item)
- {
- GNUNET_CONTAINER_DLL_remove (ai->reporting_queue_head,
- ai->reporting_queue_tail, ar_item);
- do_send_anomaly_report (ar_item->dest_mq, ai, ar_item->type);
- GNUNET_free (ar_item);
- ar_item = ai->reporting_queue_head;
- }
-}
-
-
-/**
- * When a change to the anomaly info of a sensor is done, this function should
- * be called to create the message, its proof-of-work and signuature ready to
- * be sent to other peers or collection point.
- *
- * @param ai Anomaly Info struct
- */
-static void
-update_anomaly_report_pow_block (struct AnomalyInfo *ai)
-{
- struct GNUNET_SENSOR_AnomalyReportMessage *arm;
- struct GNUNET_TIME_Absolute timestamp;
-
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "Updating anomaly report POW block due to data change.\n");
- if (NULL != ai->report_block)
- {
- GNUNET_free (ai->report_block);
- ai->report_block = NULL;
- }
- if (NULL != ai->report_creation_cx)
- {
- /* If a creation is already running, cancel it because the data changed */
- GNUNET_SENSOR_crypto_pow_sign_cancel (ai->report_creation_cx);
- ai->report_creation_cx = NULL;
- }
- arm = GNUNET_new (struct GNUNET_SENSOR_AnomalyReportMessage);
-
- GNUNET_CRYPTO_hash (ai->sensor->name, strlen (ai->sensor->name) + 1,
- &arm->sensorname_hash);
- arm->sensorversion_major = htons (ai->sensor->version_major);
- arm->sensorversion_minor = htons (ai->sensor->version_minor);
- arm->anomalous = htons (ai->anomalous);
- arm->anomalous_neighbors =
- (0 ==
- neighborhood) ? 0 : ((float)
- GNUNET_CONTAINER_multipeermap_size
- (ai->anomalous_neighbors)) / neighborhood;
- timestamp = GNUNET_TIME_absolute_get ();
- ai->report_creation_cx =
- GNUNET_SENSOR_crypto_pow_sign (arm,
- sizeof (struct
- GNUNET_SENSOR_AnomalyReportMessage),
- ×tamp, &mypeerid.public_key,
- private_key, pow_matching_bits,
- &report_creation_cb, ai);
- GNUNET_free (arm);
-}
-
-
-/**
- * Create a sensor value message from a given value info struct inside a MQ
- * envelope.
- *
- * @param vi Value info struct to use
- * @return Envelope with message
- */
-static struct GNUNET_MQ_Envelope *
-create_value_message (struct ValueInfo *vi)
-{
- struct GNUNET_SENSOR_ValueMessage *vm;
- struct GNUNET_MQ_Envelope *ev;
-
- ev = GNUNET_MQ_msg_extra (vm, vi->last_value_size,
- GNUNET_MESSAGE_TYPE_SENSOR_READING);
- GNUNET_CRYPTO_hash (vi->sensor->name, strlen (vi->sensor->name) + 1,
- &vm->sensorname_hash);
- vm->sensorversion_major = htons (vi->sensor->version_major);
- vm->sensorversion_minor = htons (vi->sensor->version_minor);
- vm->timestamp = vi->last_value_timestamp;
- vm->value_size = htons (vi->last_value_size);
- memcpy (&vm[1], vi->last_value, vi->last_value_size);
- return ev;
-}
-
-
-/******************************************************************************/
-/*************************** CORE Handlers ***************************/
-/******************************************************************************/
-
-
-/**
- * An inbound anomaly report is received from a peer through CORE.
- *
- * @param cls closure (unused)
- * @param peer the other peer involved
- * @param message the actual message
- * @return #GNUNET_OK to keep the connection open,
- * #GNUNET_SYSERR to close connection to the peer (signal serious error)
- */
-static int
-handle_anomaly_report (void *cls, const struct GNUNET_PeerIdentity *other,
- const struct GNUNET_MessageHeader *message)
-{
- struct GNUNET_SENSOR_crypto_pow_block *report_block;
- struct GNUNET_SENSOR_AnomalyReportMessage *arm;
- struct GNUNET_SENSOR_SensorInfo *sensor;
- struct AnomalyInfo *my_anomaly_info;
- struct CadetPeer *cadetp;
- int peer_anomalous;
- int peer_in_anomalous_list;
-
- /* Verify proof-of-work, signature and extract report message */
- report_block = (struct GNUNET_SENSOR_crypto_pow_block *) &message[1];
- if (sizeof (struct GNUNET_SENSOR_AnomalyReportMessage) !=
- GNUNET_SENSOR_crypto_verify_pow_sign (report_block, pow_matching_bits,
- (struct GNUNET_CRYPTO_EddsaPublicKey
- *) &other->public_key,
- (void **) &arm))
- {
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "Received invalid anomaly report from peer `%s'.\n",
- GNUNET_i2s (other));
- GNUNET_break_op (0);
- return GNUNET_SYSERR;
- }
- /* Now we parse the content of the message */
- sensor = GNUNET_CONTAINER_multihashmap_get (sensors, &arm->sensorname_hash);
- if (NULL == sensor ||
- sensor->version_major != ntohs (arm->sensorversion_major) ||
- sensor->version_minor != ntohs (arm->sensorversion_minor))
- {
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "I don't have the sensor reported by the peer `%s'.\n",
- GNUNET_i2s (other));
- return GNUNET_OK;
- }
- my_anomaly_info = get_anomaly_info_by_sensor (sensor);
- GNUNET_assert (NULL != my_anomaly_info);
- peer_in_anomalous_list =
- GNUNET_CONTAINER_multipeermap_contains
- (my_anomaly_info->anomalous_neighbors, other);
- peer_anomalous = ntohs (arm->anomalous);
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "Received an anomaly update from neighbour `%s' (%d).\n",
- GNUNET_i2s (other), peer_anomalous);
- if (GNUNET_YES == peer_anomalous)
- {
- if (GNUNET_YES == peer_in_anomalous_list) /* repeated positive report */
- GNUNET_break_op (0);
- else
- GNUNET_CONTAINER_multipeermap_put (my_anomaly_info->anomalous_neighbors,
- other, NULL,
- GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
- }
- else
- {
- if (GNUNET_NO == peer_in_anomalous_list) /* repeated negative report */
- GNUNET_break_op (0);
- else
- GNUNET_CONTAINER_multipeermap_remove_all
- (my_anomaly_info->anomalous_neighbors, other);
- }
- /* This is important to create an updated block since the data changed */
- update_anomaly_report_pow_block (my_anomaly_info);
- /* Send anomaly update to collection point only if I have the same anomaly */
- if (GNUNET_YES == my_anomaly_info->anomalous &&
- NULL != sensor->collection_point &&
- GNUNET_YES == sensor->report_anomalies)
- {
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "Neighbor update triggered sending anomaly report to collection point `%s'.\n",
- GNUNET_i2s (sensor->collection_point));
- cadetp = get_cadet_peer (*sensor->collection_point);
- send_anomaly_report (cadetp->mq, my_anomaly_info, GNUNET_NO);
- }
- return GNUNET_OK;
-}
-
-
-/******************************************************************************/
-/************************ PEERSTORE callbacks ************************/
-/******************************************************************************/
-
-
-/**
- * Sensor value watch callback
- *
- * @param cls Closure, ValueInfo struct related to the sensor we are watching
- * @param record PEERSTORE new record, NULL if error
- * @param emsg Error message, NULL if no error
- * @return #GNUNET_YES to continue watching
- */
-static int
-value_watch_cb (void *cls,
- const struct GNUNET_PEERSTORE_Record *record,
- const char *emsg)
-{
- struct ValueInfo *vi = cls;
-
- if (NULL != emsg)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("PEERSTORE error: %s.\n"), emsg);
- return GNUNET_YES;
- }
- if (NULL != vi->last_value)
- {
- GNUNET_free (vi->last_value);
- vi->last_value_size = 0;
- }
- vi->last_value = GNUNET_memdup (record->value, record->value_size);
- vi->last_value_size = record->value_size;
- vi->last_value_timestamp = GNUNET_TIME_absolute_get ();
- vi->last_value_reported = GNUNET_NO;
- return GNUNET_YES;
-}
-
-
-/******************************************************************************/
-/************************** CORE callbacks ***************************/
-/******************************************************************************/
-
-
-/**
- * Method called whenever a CORE peer disconnects.
- *
- * @param cls closure (unused)
- * @param peer peer identity this notification is about
- */
-static void
-core_disconnect_cb (void *cls, const struct GNUNET_PeerIdentity *peer)
-{
- struct CorePeer *corep;
-
- if (0 == GNUNET_CRYPTO_cmp_peer_identity (&mypeerid, peer))
- return;
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Core peer `%s' disconnected.\n",
- GNUNET_i2s (peer));
- neighborhood--;
- corep = corep_head;
- while (NULL != corep)
- {
- if (0 == GNUNET_CRYPTO_cmp_peer_identity (peer, corep->peer_id))
- {
- GNUNET_CONTAINER_DLL_remove (corep_head, corep_tail, corep);
- destroy_core_peer (corep);
- return;
- }
- corep = corep->next;
- }
-}
-
-
-/**
- * Method called whenever a given peer connects through CORE.
- *
- * @param cls closure (unused)
- * @param peer peer identity this notification is about
- */
-static void
-core_connect_cb (void *cls, const struct GNUNET_PeerIdentity *peer)
-{
- struct CorePeer *corep;
- struct AnomalyInfo *ai;
-
- if (0 == GNUNET_CRYPTO_cmp_peer_identity (&mypeerid, peer))
- return;
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to core peer `%s'.\n",
- GNUNET_i2s (peer));
- neighborhood++;
- corep = GNUNET_new (struct CorePeer);
- corep->peer_id = (struct GNUNET_PeerIdentity *) peer;
- corep->mq = GNUNET_CORE_mq_create (core, peer);
- GNUNET_CONTAINER_DLL_insert (corep_head, corep_tail, corep);
- /* Send any locally anomalous sensors to the new peer */
- ai = ai_head;
- while (NULL != ai)
- {
- if (GNUNET_YES == ai->anomalous)
- {
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "Updating newly connected neighbor `%s' with anomalous sensor.\n",
- GNUNET_i2s (peer));
- send_anomaly_report (corep->mq, ai, GNUNET_YES);
- }
- ai = ai->next;
- }
-}
-
-
-/**
- * Function called after #GNUNET_CORE_connect has succeeded (or failed
- * for good). Note that the private key of the peer is intentionally
- * not exposed here; if you need it, your process should try to read
- * the private key file directly (which should work if you are
- * authorized...). Implementations of this function must not call
- * #GNUNET_CORE_disconnect (other than by scheduling a new task to
- * do this later).
- *
- * @param cls closure (unused)
- * @param my_identity ID of this peer, NULL if we failed
- */
-static void
-core_startup_cb (void *cls, const struct GNUNET_PeerIdentity *my_identity)
-{
- if (NULL == my_identity)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to connect to CORE service.\n"));
- SENSOR_reporting_stop ();
- return;
- }
- if (0 != GNUNET_CRYPTO_cmp_peer_identity (&mypeerid, my_identity))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Peer identity received from CORE init doesn't match ours.\n"));
- SENSOR_reporting_stop ();
- return;
- }
-}
-
-
-/******************************************************************************/
-/************************* CADET callbacks ***************************/
-/******************************************************************************/
-
-/**
- * Function called whenever a channel is destroyed. Should clean up
- * any associated state.
- *
- * It must NOT call #GNUNET_CADET_channel_destroy on the channel.
- *
- * @param cls closure (set from #GNUNET_CADET_connect)
- * @param channel connection to the other end (henceforth invalid)
- * @param channel_ctx place where local state associated
- * with the channel is stored
- */
-static void
-cadet_channel_destroyed (void *cls, const struct GNUNET_CADET_Channel *channel,
- void *channel_ctx)
-{
- struct CadetPeer *cadetp = channel_ctx;
-
- if (GNUNET_YES == cadetp->destroying)
- return;
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "CADET channel was destroyed by remote peer `%s' or failed to start.\n",
- GNUNET_i2s (&cadetp->peer_id));
- if (NULL != cadetp->th)
- {
- GNUNET_CADET_notify_transmit_ready_cancel (cadetp->th);
- cadetp->th = NULL;
- }
- cadetp->channel = NULL;
-}
-
-
-/******************************************************************************/
-/********************** Local anomaly receiver ***********************/
-/******************************************************************************/
-
-
-/**
- * Used by the analysis module to tell the reporting module about a change in
- * the anomaly status of a sensor.
- *
- * @param sensor Related sensor
- * @param anomalous The new sensor anomalous status
- */
-void
-SENSOR_reporting_anomaly_update (struct GNUNET_SENSOR_SensorInfo *sensor,
- int anomalous)
-{
- struct AnomalyInfo *ai;
- struct CorePeer *corep;
- struct CadetPeer *cadetp;
-
- if (GNUNET_NO == module_running)
- return;
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Received an external anomaly update.\n");
- ai = get_anomaly_info_by_sensor (sensor);
- GNUNET_assert (NULL != ai);
- ai->anomalous = anomalous;
- /* This is important to create an updated block since the data changed */
- update_anomaly_report_pow_block (ai);
- /* Report change to all neighbors */
- corep = corep_head;
- while (NULL != corep)
- {
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "Sending an anomaly report to neighbor `%s'.\n",
- GNUNET_i2s (corep->peer_id));
- send_anomaly_report (corep->mq, ai, GNUNET_YES);
- corep = corep->next;
- }
- /* Report change to collection point if need */
- if (NULL != ai->sensor->collection_point &&
- GNUNET_YES == ai->sensor->report_anomalies)
- {
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "Local anomaly update triggered sending anomaly report to collection point `%s'.\n",
- GNUNET_i2s (ai->sensor->collection_point));
- cadetp = get_cadet_peer (*ai->sensor->collection_point);
- send_anomaly_report (cadetp->mq, ai, GNUNET_NO);
- }
-}
-
-
-/******************************************************************************/
-/******************* Reporting values (periodic) *********************/
-/******************************************************************************/
-
-
-/**
- * Task scheduled to send values to collection point
- *
- * @param cls closure, a `struct ValueReportingContext *`
- * @param tc unused
- */
-static void
-report_value (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct ValueInfo *vi = cls;
- struct GNUNET_SENSOR_SensorInfo *sensor = vi->sensor;
- struct CadetPeer *cadetp;
- struct GNUNET_MQ_Envelope *ev;
-
- vi->reporting_task =
- GNUNET_SCHEDULER_add_delayed (sensor->value_reporting_interval,
- &report_value, vi);
- if (0 == vi->last_value_size || GNUNET_YES == vi->last_value_reported)
- {
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "Did not receive a fresh value from `%s' to report.\n", sensor->name);
- return;
- }
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "Now trying to report last seen value of `%s' to collection point.\n",
- sensor->name);
- cadetp = get_cadet_peer (*sensor->collection_point);
- if (NULL == cadetp->channel)
- {
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "Trying to send value to collection point but connection failed, discarding.\n");
- return;
- }
- ev = create_value_message (vi);
- GNUNET_MQ_send (cadetp->mq, ev);
- vi->last_value_reported = GNUNET_YES;
-}
-
-
-/******************************************************************************/
-/******************************** INIT *******************************/
-/******************************************************************************/
-
-
-/**
- * Iterator for defined sensors and creates anomaly info context
- *
- * @param cls unused
- * @param key unused
- * @param value a `struct GNUNET_SENSOR_SensorInfo *` with sensor information
- * @return #GNUNET_YES to continue iterations
- */
-static int
-init_sensor_reporting (void *cls, const struct GNUNET_HashCode *key,
- void *value)
-{
- struct GNUNET_SENSOR_SensorInfo *sensor = value;
- struct AnomalyInfo *ai;
- struct ValueInfo *vi;
-
- /* Create sensor anomaly info context */
- ai = GNUNET_new (struct AnomalyInfo);
-
- ai->sensor = sensor;
- ai->anomalous = GNUNET_NO;
- ai->anomalous_neighbors =
- GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
- ai->report_block = NULL;
- ai->report_creation_cx = NULL;
- GNUNET_CONTAINER_DLL_insert (ai_head, ai_tail, ai);
- /* Create sensor value info context (if needed to be reported) */
- if (NULL == sensor->collection_point || GNUNET_NO == sensor->report_values)
- return GNUNET_YES;
- LOG (GNUNET_ERROR_TYPE_INFO,
- "Reporting sensor `%s' values to collection point `%s' every %s.\n",
- sensor->name, GNUNET_i2s_full (sensor->collection_point),
- GNUNET_STRINGS_relative_time_to_string (sensor->value_reporting_interval,
- GNUNET_YES));
- vi = GNUNET_new (struct ValueInfo);
- vi->sensor = sensor;
- vi->last_value = NULL;
- vi->last_value_size = 0;
- vi->last_value_reported = GNUNET_NO;
- vi->wc =
- GNUNET_PEERSTORE_watch (peerstore, "sensor", &mypeerid, sensor->name,
- &value_watch_cb, vi);
- vi->reporting_task =
- GNUNET_SCHEDULER_add_delayed (sensor->value_reporting_interval,
- &report_value, vi);
- GNUNET_CONTAINER_DLL_insert (vi_head, vi_tail, vi);
- return GNUNET_YES;
-}
-
-
-/**
- * Start the sensor anomaly reporting module
- *
- * @param c our service configuration
- * @param s multihashmap of loaded sensors
- * @return #GNUNET_OK if started successfully, #GNUNET_SYSERR otherwise
- */
-int
-SENSOR_reporting_start (const struct GNUNET_CONFIGURATION_Handle *c,
- struct GNUNET_CONTAINER_MultiHashMap *s)
-{
- static struct GNUNET_CORE_MessageHandler core_handlers[] = {
- {&handle_anomaly_report, GNUNET_MESSAGE_TYPE_SENSOR_ANOMALY_REPORT_P2P,
- sizeof (struct GNUNET_MessageHeader) +
- sizeof (struct GNUNET_SENSOR_crypto_pow_block) +
- sizeof (struct GNUNET_SENSOR_AnomalyReportMessage)},
- {NULL, 0, 0}
- };
- static struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
- {NULL, 0, 0}
- };
-
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting sensor reporting module.\n");
- GNUNET_assert (NULL != s);
- sensors = s;
- cfg = c;
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_number (cfg, "sensor-reporting",
- "POW_MATCHING_BITS",
- &pow_matching_bits))
- {
- GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "sensor-reporting",
- "POW_MATCHING_BITS");
- SENSOR_reporting_stop ();
- return GNUNET_SYSERR;
- }
- if (pow_matching_bits > sizeof (struct GNUNET_HashCode))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, "Matching bits value too large (%d > %d).\n",
- pow_matching_bits, sizeof (struct GNUNET_HashCode));
- SENSOR_reporting_stop ();
- return GNUNET_SYSERR;
- }
- /* Connect to PEERSTORE */
- peerstore = GNUNET_PEERSTORE_connect (cfg);
- if (NULL == peerstore)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Failed to connect to peerstore service.\n"));
- SENSOR_reporting_stop ();
- return GNUNET_SYSERR;
- }
- /* Connect to CORE */
- core =
- GNUNET_CORE_connect (cfg, NULL, &core_startup_cb, core_connect_cb,
- &core_disconnect_cb, NULL, GNUNET_YES, NULL,
- GNUNET_YES, core_handlers);
- if (NULL == core)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to connect to CORE service.\n"));
- SENSOR_reporting_stop ();
- return GNUNET_SYSERR;
- }
- /* Connect to CADET */
- cadet =
- GNUNET_CADET_connect (cfg, NULL, NULL, &cadet_channel_destroyed,
- cadet_handlers, NULL);
- if (NULL == cadet)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to connect to CADET service.\n"));
- SENSOR_reporting_stop ();
- return GNUNET_SYSERR;
- }
- private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
- if (NULL == private_key)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to load my private key.\n"));
- SENSOR_reporting_stop ();
- return GNUNET_SYSERR;
- }
- GNUNET_CRYPTO_get_peer_identity (cfg, &mypeerid);
- GNUNET_CONTAINER_multihashmap_iterate (sensors, &init_sensor_reporting, NULL);
- neighborhood = 0;
- module_running = GNUNET_YES;
- return GNUNET_OK;
-}
-
-/* end of gnunet-service-sensor_reporting.c */
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/gnunet-service-sensor_update.c
- * @brief sensor service update functionality
- * @author Omar Tarabai
- */
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "sensor.h"
-#include "gnunet_cadet_service.h"
-#include "gnunet_sensor_model_plugin.h"
-#include "gnunet_applications.h"
-
-#define LOG(kind,...) GNUNET_log_from (kind, "sensor-update",__VA_ARGS__)
-
-/**
- * Interval at which to contact update points for new sensor updates.
- */
-#define SENSOR_UPDATE_CHECK_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_DAYS, 1)
-
-/**
- * Interval at which to retry contacting update point if we were busy.
- */
-#define SENSOR_UPDATE_CHECK_RETRY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
-
-
-/**
- * Message queued to be sent to an update point stored in a DLL
- */
-struct PendingMessage
-{
-
- /**
- * DLL
- */
- struct PendingMessage *prev;
-
- /**
- * DLL
- */
- struct PendingMessage *next;
-
- /**
- * Actual queued message
- */
- struct GNUNET_MessageHeader *msg;
-
-};
-
-/**
- * Sensors update point
- */
-struct UpdatePoint
-{
-
- /**
- * DLL
- */
- struct UpdatePoint *prev;
-
- /**
- * DLL
- */
- struct UpdatePoint *next;
-
- /**
- * Identity of peer running update point
- */
- struct GNUNET_PeerIdentity peer_id;
-
- /**
- * CADET channel to update point
- */
- struct GNUNET_CADET_Channel *ch;
-
- /**
- * CADET transmit handle for a message to be sent to update point.
- */
- struct GNUNET_CADET_TransmitHandle *th;
-
- /**
- * Head of DLL of pending requests to be sent to update point.
- */
- struct PendingMessage *pm_head;
-
- /**
- * Tail of DLL of pending requests to be sent to update point.
- */
- struct PendingMessage *pm_tail;
-
- /**
- * Are we waiting for a sensor list?
- */
- int expecting_sensor_list;
-
- /**
- * How many sensor updates did we request and are waiting for.
- */
- int expected_sensor_updates;
-
- /**
- * Did a failure occur while dealing with this update point before?
- */
- int failed;
-
-};
-
-
-/**
- * Our configuration.
- */
-static const struct GNUNET_CONFIGURATION_Handle *cfg;
-
-/**
- * Path to sensor definition directory
- */
-static char *sensor_dir;
-
-/**
- * Hashmap of known sensors
- */
-static struct GNUNET_CONTAINER_MultiHashMap *sensors;
-
-/**
- * Head of update points DLL.
- */
-static struct UpdatePoint *up_head;
-
-/**
- * Tail of update points DLL.
- */
-static struct UpdatePoint *up_tail;
-
-/**
- * The current default update point to use.
- */
-static struct UpdatePoint *up_default;
-
-/**
- * Handle to CADET service
- */
-static struct GNUNET_CADET_Handle *cadet;
-
-/**
- * Are we in the process of checking and updating sensors?
- */
-static int updating;
-
-/**
- * GNUnet scheduler task that starts the update check process.
- */
-static struct GNUNET_SCHEDULER_Task * update_task;
-
-/**
- * Pointer to service reset function called when we have new sensor updates.
- */
-static void (*reset_cb) ();
-
-
-/**
- * Contact update points to check for new updates
- *
- * @param cls unused
- * @param tc GNUnet scheduler task context
- */
-static void
-check_for_updates (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
-
-
-/**
- * Trigger sending next pending message to the default update point if any.
- *
- */
-static void
-trigger_send_next_msg ();
-
-
-/**
- * Cleanup update point context. This does not destroy the struct itself.
- *
- * @param up UpdatePoint struct
- */
-static void
-cleanup_updatepoint (struct UpdatePoint *up)
-{
- struct PendingMessage *pm;
-
- up->expecting_sensor_list = GNUNET_NO;
- up->expected_sensor_updates = 0;
- if (NULL != up->th)
- {
- GNUNET_CADET_notify_transmit_ready_cancel (up->th);
- up->th = NULL;
- }
- pm = up->pm_head;
- while (NULL != pm)
- {
- GNUNET_CONTAINER_DLL_remove (up->pm_head, up->pm_tail, pm);
- GNUNET_free (pm->msg);
- GNUNET_free (pm);
- pm = up->pm_head;
- }
- if (NULL != up->ch)
- {
- GNUNET_CADET_channel_destroy (up->ch);
- up->ch = NULL;
- }
-}
-
-
-/**
- * Stop the sensor update module.
- */
-void
-SENSOR_update_stop ()
-{
- struct UpdatePoint *up;
-
- up_default = NULL;
- up = up_head;
- if (NULL != update_task)
- {
- GNUNET_SCHEDULER_cancel (update_task);
- update_task = NULL;
- }
- while (NULL != up)
- {
- GNUNET_CONTAINER_DLL_remove (up_head, up_tail, up);
- cleanup_updatepoint (up);
- GNUNET_free (up);
- up = up_head;
- }
- if (NULL != cadet)
- {
- GNUNET_CADET_disconnect (cadet);
- cadet = NULL;
- }
- if (NULL != sensor_dir)
- {
- GNUNET_free (sensor_dir);
- sensor_dir = NULL;
- }
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Sensor update module stopped.\n");
-}
-
-
-/**
- * A failure occured in connecting/retrieval/verification with current default
- * update point. This method will try to find another update point, do cleanup
- * and reschedule update check.
- */
-static void
-fail ()
-{
- struct UpdatePoint *up;
-
- cleanup_updatepoint (up_default);
- if (up_default == up_tail)
- {
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "All defined update points failed. Will retry again in %s.\n",
- GNUNET_STRINGS_relative_time_to_string (SENSOR_UPDATE_CHECK_INTERVAL,
- GNUNET_NO));
- up = up_head;
- while (NULL != up)
- {
- up->failed = GNUNET_NO;
- up = up->next;
- }
- update_task =
- GNUNET_SCHEDULER_add_delayed (SENSOR_UPDATE_CHECK_INTERVAL,
- &check_for_updates, NULL);
- return;
- }
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "Update point `%s' failed, trying next one now.\n",
- GNUNET_i2s (&up_default->peer_id));
- up_default = up_default->next;
- update_task = GNUNET_SCHEDULER_add_now (&check_for_updates, NULL);
-}
-
-
-/**
- * Function called to notify a client about the connection begin ready
- * to queue more data. @a buf will be NULL and @a size zero if the
- * connection was closed for writing in the meantime.
- *
- * Perform the actual sending of the message to update point.
- *
- * @param cls closure (unused)
- * @param size number of bytes available in @a buf
- * @param buf where the callee should write the message
- * @return number of bytes written to @a buf
- */
-static size_t
-do_send_msg (void *cls, size_t size, void *buf)
-{
- struct PendingMessage *pm;
- size_t msg_size;
-
- up_default->th = NULL;
- pm = up_default->pm_head;
- msg_size = ntohs (pm->msg->size);
- GNUNET_CONTAINER_DLL_remove (up_default->pm_head, up_default->pm_tail, pm);
- if (NULL == buf || size < msg_size)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
- _("Error trying to send a message to update point `%s'.\n"),
- GNUNET_i2s (&up_default->peer_id));
- fail ();
- return 0;
- }
- memcpy (buf, pm->msg, msg_size);
- GNUNET_free (pm->msg);
- GNUNET_free (pm);
- trigger_send_next_msg ();
- return msg_size;
-}
-
-
-/**
- * Trigger sending next pending message to the default update point if any.
- *
- */
-static void
-trigger_send_next_msg ()
-{
- struct PendingMessage *pm;
-
- if (NULL == up_default->pm_head)
- return;
- if (NULL != up_default->th)
- return;
- pm = up_default->pm_head;
- up_default->th =
- GNUNET_CADET_notify_transmit_ready (up_default->ch, GNUNET_YES,
- GNUNET_TIME_UNIT_FOREVER_REL,
- ntohs (pm->msg->size), &do_send_msg,
- NULL);
-}
-
-
-/**
- * Add a message to the queue to be sent to the current default update point.
- *
- * @param msg Message to be queued
- */
-static void
-queue_msg (struct GNUNET_MessageHeader *msg)
-{
- struct PendingMessage *pm;
-
- pm = GNUNET_new (struct PendingMessage);
-
- pm->msg = msg;
- GNUNET_CONTAINER_DLL_insert_tail (up_default->pm_head, up_default->pm_tail,
- pm);
- trigger_send_next_msg ();
-}
-
-
-/**
- * Contact update points to check for new updates
- *
- * @param cls unused
- * @param tc GNUnet scheduler task context
- */
-static void
-check_for_updates (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct GNUNET_MessageHeader *msg;
- size_t msg_size;
-
- update_task = NULL;
- if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
- return;
- if (GNUNET_YES == updating)
- {
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "Update process still running and update interval already exhausted."
- "Retrying in %s.\n",
- GNUNET_STRINGS_relative_time_to_string (SENSOR_UPDATE_CHECK_RETRY,
- GNUNET_NO));
- update_task =
- GNUNET_SCHEDULER_add_delayed (SENSOR_UPDATE_CHECK_RETRY,
- &check_for_updates, NULL);
- return;
- }
- updating = GNUNET_YES;
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking for sensor updates.\n");
- GNUNET_assert (NULL != up_default);
- up_default->ch =
- GNUNET_CADET_channel_create (cadet, up_default, &up_default->peer_id,
- GNUNET_APPLICATION_TYPE_SENSORUPDATE,
- GNUNET_CADET_OPTION_DEFAULT);
- if (NULL == up_default->ch)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Failed to connect to update point `%s'.\n"),
- GNUNET_i2s (&up_default->peer_id));
- fail ();
- return;
- }
- /* Start by requesting list of sensors available from update point */
- up_default->expecting_sensor_list = GNUNET_YES;
- msg = GNUNET_new (struct GNUNET_MessageHeader);
- msg_size = sizeof (struct GNUNET_MessageHeader);
- msg->size = htons (msg_size);
- msg->type = htons (GNUNET_MESSAGE_TYPE_SENSOR_LIST_REQ);
- queue_msg (msg);
- update_task =
- GNUNET_SCHEDULER_add_delayed (SENSOR_UPDATE_CHECK_INTERVAL,
- &check_for_updates, NULL);
-}
-
-
-/**
- * Function that reads and validates (correctness not connectivity) of available
- * sensor update points.
- *
- * @return number of update points loaded successfully
- */
-static int
-load_update_points ()
-{
- char *points_list;
- int points_list_len;
- int i;
- int start;
- int len;
- struct GNUNET_CRYPTO_EddsaPublicKey public_key;
- struct UpdatePoint *up;
- int count = 0;
-
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_string (cfg, "sensor-update",
- "UPDATE_POINTS", &points_list))
- {
- return 0;
- }
- points_list_len = strlen (points_list) + 1;
- for (i = 0; i < points_list_len; i++)
- {
- if (' ' == points_list[i])
- continue;
- start = i;
- len = 0;
- while (' ' != points_list[i] && '\0' != points_list[i])
- {
- len++;
- i++;
- }
- if (GNUNET_OK !=
- GNUNET_CRYPTO_eddsa_public_key_from_string (points_list + start, len,
- &public_key))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- "Invalid EDDSA public key `%.*s' for update point.\n", len,
- points_list + len);
- continue;
- }
- up = GNUNET_new (struct UpdatePoint);
-
- up->peer_id.public_key = public_key;
- up->ch = NULL;
- up->th = NULL;
- up->expecting_sensor_list = GNUNET_NO;
- up->expected_sensor_updates = 0;
- up->failed = GNUNET_NO;
- GNUNET_CONTAINER_DLL_insert (up_head, up_tail, up);
- count++;
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Loaded update point `%s'.\n",
- GNUNET_i2s_full (&up->peer_id));
- }
- GNUNET_free (points_list);
- return count;
-}
-
-
-/**
- * Checks if the given sensor name and version (retrieved from an update point)
- * is new for us and we would like to install it. This is the case if we don't
- * have this sensor or we have an old version of it.
- *
- * @param sensorname Sensor name
- * @param sensorversion_major First part of version number
- * @param sensorversion_minor Second part of version number
- * @return #GNUNET_YES if we don't have this sensor
- * #GNUNET_NO if we have it
- */
-static int
-update_required (char *sensorname, uint16_t sensorversion_major,
- uint16_t sensorversion_minor)
-{
- struct GNUNET_HashCode key;
- struct GNUNET_SENSOR_SensorInfo *local_sensor;
-
- GNUNET_CRYPTO_hash (sensorname, strlen (sensorname) + 1, &key);
- local_sensor = GNUNET_CONTAINER_multihashmap_get (sensors, &key);
- if (NULL == local_sensor)
- return GNUNET_YES;
- if (GNUNET_SENSOR_version_compare
- (local_sensor->version_major, local_sensor->version_minor,
- sensorversion_major, sensorversion_minor) < 0)
- return GNUNET_YES;
- return GNUNET_NO;
-}
-
-
-/**
- * Handler of a sensor list message received from an update point.
- *
- * @param cls Closure (unused).
- * @param channel Connection to the other end.
- * @param channel_ctx Place to store local state associated with the channel.
- * @param message The actual message.
- * @return #GNUNET_OK to keep the channel open,
- * #GNUNET_SYSERR to close it (signal serious error).
- */
-static int
-handle_sensor_brief (void *cls, struct GNUNET_CADET_Channel *channel,
- void **channel_ctx,
- const struct GNUNET_MessageHeader *message)
-{
- struct GNUNET_SENSOR_SensorBriefMessage *sbm;
- struct GNUNET_MessageHeader *pull_req;
- uint16_t version_major;
- uint16_t version_minor;
- uint16_t msg_size;
-
- GNUNET_assert (*channel_ctx == up_default);
- if (GNUNET_YES != up_default->expecting_sensor_list)
- {
- GNUNET_break_op (0);
- fail ();
- return GNUNET_OK;
- }
- if (GNUNET_MESSAGE_TYPE_SENSOR_END == ntohs (message->type))
- {
- LOG (GNUNET_ERROR_TYPE_DEBUG,
- "Received end of sensor list msg. We already requested %d updates.\n",
- up_default->expected_sensor_updates);
- up_default->expecting_sensor_list = GNUNET_NO;
- if (0 == up_default->expected_sensor_updates)
- {
- updating = GNUNET_NO;
- cleanup_updatepoint (up_default);
- return GNUNET_OK;
- }
- }
- else
- {
- sbm = (struct GNUNET_SENSOR_SensorBriefMessage *) message;
- version_major = ntohs (sbm->version_major);
- version_minor = ntohs (sbm->version_minor);
- if (GNUNET_YES ==
- update_required ((char *) &sbm[1], version_major, version_minor))
- {
- LOG (GNUNET_ERROR_TYPE_INFO,
- "Requesting sensor %s %d.%d from update point.\n", &sbm[1],
- version_major, version_minor);
- /* We duplicate the same msg received but change the type and send it
- * back to update point to ask for full sensor information. */
- msg_size = ntohs (message->size);
- pull_req = GNUNET_malloc (msg_size);
- memcpy (pull_req, message, msg_size);
- pull_req->type = htons (GNUNET_MESSAGE_TYPE_SENSOR_FULL_REQ);
- queue_msg (pull_req);
- up_default->expected_sensor_updates++;
- }
- }
- GNUNET_CADET_receive_done (channel);
- return GNUNET_OK;
-}
-
-
-/**
- * Update local sensor definitions with a sensor retrieved from an update point.
- *
- * @param sensorname Sensor name
- * @param sensorfile Buffer containing the sensor definition file
- * @param sensorfile_size Size of @e sensorfile
- * @param scriptname Name of associated script file, NULL if no script
- * @param scriptfile Buffer containing the script file, NULL if no script
- * @param scriptfile_size Size of @e scriptfile, 0 if no script
- * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
- */
-static int
-update_sensor (char *sensorname, void *sensorfile, uint16_t sensorfile_size,
- char *scriptname, void *scriptfile, uint16_t scriptfile_size)
-{
- char *sensor_path;
- char *script_path;
-
- LOG (GNUNET_ERROR_TYPE_INFO,
- "Received new sensor information:\n" "Name: %s\n"
- "Sensor file size: %d\n" "Script name: %s\n" "Script file size: %d.\n",
- sensorname, sensorfile_size, (NULL == scriptname) ? "None" : scriptname,
- scriptfile_size);
- GNUNET_asprintf (&sensor_path, "%s%s", sensor_dir, sensorname);
- GNUNET_DISK_fn_write (sensor_path, sensorfile, sensorfile_size,
- GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_GROUP_READ
- | GNUNET_DISK_PERM_OTHER_READ |
- GNUNET_DISK_PERM_USER_WRITE);
- if (NULL != scriptname)
- {
- GNUNET_asprintf (&script_path, "%s-files%s%s", sensor_path,
- DIR_SEPARATOR_STR, scriptname);
- GNUNET_DISK_fn_write (script_path, scriptfile, scriptfile_size,
- GNUNET_DISK_PERM_USER_READ |
- GNUNET_DISK_PERM_GROUP_READ |
- GNUNET_DISK_PERM_OTHER_READ |
- GNUNET_DISK_PERM_USER_WRITE |
- GNUNET_DISK_PERM_GROUP_WRITE |
- GNUNET_DISK_PERM_USER_EXEC |
- GNUNET_DISK_PERM_GROUP_EXEC);
- GNUNET_free (script_path);
- }
- GNUNET_free (sensor_path);
- return GNUNET_OK;
-}
-
-
-/**
- * Resets the service after we are done with an update.
- *
- * @param cls unused
- * @param tc unused
- */
-static void
-reset (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- reset_cb ();
-}
-
-
-/**
- * Handler of a sensor list message received from an update point.
- *
- * @param cls Closure (unused).
- * @param channel Connection to the other end.
- * @param channel_ctx Place to store local state associated with the channel.
- * @param message The actual message.
- * @return #GNUNET_OK to keep the channel open,
- * #GNUNET_SYSERR to close it (signal serious error).
- */
-static int
-handle_sensor_full (void *cls, struct GNUNET_CADET_Channel *channel,
- void **channel_ctx,
- const struct GNUNET_MessageHeader *message)
-{
- struct GNUNET_SENSOR_SensorFullMessage *sfm;
- uint16_t msg_size;
- uint16_t sensorfile_size;
- uint16_t scriptfile_size;
- char *sensorname_ptr;
- void *sensorfile_ptr;
- char *scriptname_ptr;
- void *scriptfile_ptr;
-
- /* error check */
- GNUNET_assert (*channel_ctx == up_default);
- msg_size = ntohs (message->size);
- if (up_default->expected_sensor_updates <= 0 ||
- msg_size < sizeof (struct GNUNET_SENSOR_SensorFullMessage))
- {
- GNUNET_break_op (0);
- fail ();
- return GNUNET_OK;
- }
- /* parse received msg */
- sfm = (struct GNUNET_SENSOR_SensorFullMessage *) message;
- sensorname_ptr = (char *) &sfm[1];
- sensorfile_ptr = sensorname_ptr + ntohs (sfm->sensorname_size);
- sensorfile_size = ntohs (sfm->sensorfile_size);
- scriptfile_size = ntohs (sfm->scriptfile_size);
- if (scriptfile_size > 0)
- {
- scriptname_ptr = sensorfile_ptr + sensorfile_size;
- scriptfile_ptr = scriptname_ptr + ntohs (sfm->scriptname_size);
- }
- else
- {
- scriptname_ptr = NULL;
- scriptfile_ptr = NULL;
- }
- update_sensor ((char *) &sfm[1], sensorfile_ptr, sensorfile_size,
- scriptname_ptr, scriptfile_ptr, scriptfile_size);
- up_default->expected_sensor_updates--;
- if (0 == up_default->expected_sensor_updates)
- {
- updating = GNUNET_NO;
- cleanup_updatepoint (up_default);
- GNUNET_SCHEDULER_add_now (&reset, NULL);
- }
- else
- GNUNET_CADET_receive_done (channel);
- return GNUNET_OK;
-}
-
-
-/**
- * Function called whenever a channel is destroyed. Should clean up
- * any associated state.
- *
- * It must NOT call #GNUNET_CADET_channel_destroy on the channel.
- *
- * @param cls closure (set from #GNUNET_CADET_connect)
- * @param channel connection to the other end (henceforth invalid)
- * @param channel_ctx place where local state associated
- * with the channel is stored
- */
-static void
-cadet_channel_destroyed (void *cls, const struct GNUNET_CADET_Channel *channel,
- void *channel_ctx)
-{
- struct UpdatePoint *up = channel_ctx;
-
- up->ch = NULL;
- if (GNUNET_YES == updating)
- {
- fail ();
- return;
- }
- cleanup_updatepoint (up);
-}
-
-
-/**
- * Start the sensor update module
- *
- * @param c our service configuration
- * @param s multihashmap of loaded sensors
- * @param cb callback to reset service components when we have new updates
- * @return #GNUNET_OK if started successfully, #GNUNET_SYSERR otherwise
- */
-int
-SENSOR_update_start (const struct GNUNET_CONFIGURATION_Handle *c,
- struct GNUNET_CONTAINER_MultiHashMap *s, void (*cb) ())
-{
- static struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
- {&handle_sensor_brief, GNUNET_MESSAGE_TYPE_SENSOR_BRIEF, 0},
- {&handle_sensor_brief, GNUNET_MESSAGE_TYPE_SENSOR_END, 0},
- {&handle_sensor_full, GNUNET_MESSAGE_TYPE_SENSOR_FULL, 0},
- {NULL, 0, 0}
- };
- int up_count;
-
- GNUNET_assert (NULL != s);
- cfg = c;
- sensors = s;
- reset_cb = cb;
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_filename (cfg, "SENSOR", "SENSOR_DIR",
- &sensor_dir))
- sensor_dir = GNUNET_SENSOR_get_default_sensor_dir ();
- cadet =
- GNUNET_CADET_connect (cfg, NULL, NULL, &cadet_channel_destroyed,
- cadet_handlers, NULL);
- if (NULL == cadet)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to connect to CADET service.\n"));
- SENSOR_update_stop ();
- return GNUNET_SYSERR;
- }
- up_count = load_update_points ();
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Loaded %d update points.\n", up_count);
- if (0 == up_count)
- {
- SENSOR_update_stop ();
- return GNUNET_SYSERR;
- }
- up_default = up_head;
- updating = GNUNET_NO;
- update_task =
- GNUNET_SCHEDULER_add_delayed (SENSOR_UPDATE_CHECK_INTERVAL,
- &check_for_updates, NULL);
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Sensor update module started.\n");
- return GNUNET_OK;
-}
-
-/* end of gnunet-service-sensor_update.c */
+++ /dev/null
-/*
- This file is part of GNUnet
- Copyright (C) 2012, 2013 GNUnet e.V.
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/gnunet_sensor_model_plugin.h
- * @brief plugin API for sensor analysis models
- * @author Omar Tarabai
- */
-#ifndef GNUNET_SENSOR_MODEL_PLUGIN_H
-#define GNUNET_SENSOR_MODEL_PLUGIN_H
-
-#include "gnunet_util_lib.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#if 0 /* keep Emacsens' auto-indent happy */
-}
-#endif
-#endif
-
-
-/**
- * API for a sensor analysis model
- */
-struct GNUNET_SENSOR_ModelFunctions
-{
-
- /**
- * Closure to pass to all plugin functions.
- */
- void *cls;
-
- /*
- * Create a model instance
- *
- * @param cls closure (plugin state)
- * @return model state to be used for later calls
- */
- void *(*create_model) (void *cls);
-
- /*
- * Destroy a model instance
- *
- * @param cls closure (model state)
- */
- void (*destroy_model) (void *cls);
-
- /*
- * Feed a new value to a model
- *
- * @param cls closure (model state)
- * @param val value to be fed to the model
- * @return #GNUNET_YES in case of a detected outlier, #GNUNET_NO otherwise
- */
- int (*feed_model) (void *cls, double val);
-
-};
-
-
-#if 0 /* keep Emacsens' auto-indent happy */
-{
-#endif
-#ifdef __cplusplus
-}
-#endif
-
-/* end of gnunet_sensor_model_plugin.h */
-#endif
+++ /dev/null
- /*
- * This file is part of GNUnet.
- * Copyright (C)
- *
- * GNUnet is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published
- * by the Free Software Foundation; either version 3, or (at your
- * option) any later version.
- *
- * GNUnet is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GNUnet; see the file COPYING. If not, write to the
- * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-/**
- * @file sensor/perf_pow_sign.c
- * @brief Print the average time required to generate pow for each matching bits
- */
-#include <inttypes.h>
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "gnunet_sensor_util_lib.h"
-#include "gnunet_testbed_service.h"
-#include "gnunet_signatures.h"
-
-/**
- * Number of peers to start for the test
- */
-#define NUM_PEERS 1
-
-/**
- * Size of the message exchanged
- */
-#define MSG_SIZE 1024
-
-/**
- * How many matching bits to start with
- */
-#define MATCHING_BITS_START 1
-
-/**
- * How many matching bits to end with
- */
-#define MATCHING_BITS_END 20
-
-/**
- * How many readings per matching bits value
- */
-#define ITERATIONS 10
-
-/**
- * Test name
- */
-static const char *testname = "test_pow_sign";
-
-/**
- * Name of GNUNET config file used in this test
- */
-static const char *cfg_filename = "test_pow_sign.conf";
-
-/**
- * Status of the test to be returned by main()
- */
-static int ok = 1;
-
-/**
- * Task used to shutdown / expire the test
- */
-static struct GNUNET_SCHEDULER_Task * shutdown_task;
-
-/**
- * Message to be exchanged
- */
-static char msg[MSG_SIZE];
-
-/**
- * Private key of sending peer
- */
-static struct GNUNET_CRYPTO_EddsaPrivateKey *private_key;
-
-/**
- * Public key of sending peer
- */
-static struct GNUNET_CRYPTO_EddsaPublicKey *public_key;
-
-/**
- * The current matching bits being evaluated
- */
-static int current_matching_bits;
-
-/**
- * How many iterations performed for this matching bits value
- */
-static int performed_iterations;
-
-/**
- * Total duration of all iterations
- */
-static struct GNUNET_TIME_Relative total_duration;
-
-/**
- * Task creating pow block
- */
-static struct GNUNET_SENSOR_crypto_pow_context *pow_task;
-
-
-/**
- * Start a new pow calculation
- */
-static void
-pow_start (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
-
-
-/**
- * Shutdown task
- *
- * @param cls Closure (unused)
- * @param tc Task context (unused)
- */
-static void
-do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- if (NULL != pow_task)
- {
- GNUNET_SENSOR_crypto_pow_sign_cancel (pow_task);
- pow_task = NULL;
- }
- if (NULL != private_key)
- {
- GNUNET_free (private_key);
- private_key = NULL;
- }
- if (NULL != public_key)
- {
- GNUNET_free (public_key);
- public_key = NULL;
- }
- GNUNET_SCHEDULER_shutdown ();
-}
-
-
-static void
-pow_cb (void *cls, struct GNUNET_SENSOR_crypto_pow_block *block)
-{
- struct GNUNET_TIME_Absolute end_time;
- struct GNUNET_TIME_Relative duration;
-
- pow_task = NULL;
- end_time = GNUNET_TIME_absolute_get();
- duration = GNUNET_TIME_absolute_get_difference (block->timestamp, end_time);
- printf(".");
- performed_iterations++;
- total_duration = GNUNET_TIME_relative_add (total_duration, duration);
- if (ITERATIONS == performed_iterations)
- {
- total_duration = GNUNET_TIME_relative_divide (total_duration, ITERATIONS);
- printf ("Matching bits %d: %s\n", current_matching_bits,
- GNUNET_STRINGS_relative_time_to_string(total_duration, GNUNET_NO));
- total_duration = GNUNET_TIME_UNIT_ZERO;
- performed_iterations = 0;
- if (MATCHING_BITS_END == current_matching_bits)
- {
- ok = 0;
- GNUNET_SCHEDULER_cancel (shutdown_task);
- GNUNET_SCHEDULER_add_now (do_shutdown, NULL);
- return;
- }
- current_matching_bits ++;
- }
- GNUNET_SCHEDULER_add_now (&pow_start, NULL);
-}
-
-
-/**
- * Start a new pow calculation
- */
-static void
-pow_start (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct GNUNET_TIME_Absolute timestamp;
-
- timestamp = GNUNET_TIME_absolute_get ();
- pow_task = GNUNET_SENSOR_crypto_pow_sign (msg, MSG_SIZE, ×tamp, public_key,
- private_key, current_matching_bits, &pow_cb, NULL);
-}
-
-
-/**
- * Callback to be called when the requested peer information is available
- *
- * @param cb_cls the closure from GNUNET_TETSBED_peer_get_information()
- * @param op the operation this callback corresponds to
- * @param pinfo the result; will be NULL if the operation has failed
- * @param emsg error message if the operation has failed; will be NULL if the
- * operation is successfull
- */
-static void
-peer_info_cb (void *cb_cls, struct GNUNET_TESTBED_Operation *op,
- const struct GNUNET_TESTBED_PeerInformation *pinfo,
- const char *emsg)
-{
- /* generate random data block */
- GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, msg, MSG_SIZE);
- /* get private and public keys */
- private_key =
- GNUNET_CRYPTO_eddsa_key_create_from_configuration (pinfo->result.cfg);
- GNUNET_assert (NULL != private_key);
- public_key = GNUNET_new (struct GNUNET_CRYPTO_EddsaPublicKey);
- GNUNET_CRYPTO_eddsa_key_get_public (private_key, public_key);
- current_matching_bits = MATCHING_BITS_START;
- performed_iterations = 0;
- total_duration = GNUNET_TIME_UNIT_ZERO;
- GNUNET_TESTBED_operation_done (op);
- GNUNET_SCHEDULER_add_now (&pow_start, NULL);
-}
-
-
-/**
- * Signature of a main function for a testcase.
- *
- * @param cls closure
- * @param h the run handle
- * @param num_peers number of peers in 'peers'
- * @param peers handle to peers run in the testbed. NULL upon timeout (see
- * GNUNET_TESTBED_test_run()).
- * @param links_succeeded the number of overlay link connection attempts that
- * succeeded
- * @param links_failed the number of overlay link connection attempts that
- * failed
- * @see GNUNET_TESTBED_test_run()
- */
-static void
-test_master (void *cls, struct GNUNET_TESTBED_RunHandle *h,
- unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
- unsigned int links_succeeded, unsigned int links_failed)
-{
- GNUNET_assert (NUM_PEERS == num_peers);
- GNUNET_assert (0 == links_failed);
- shutdown_task =
- GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown, NULL);
- GNUNET_TESTBED_peer_get_information (peers[0],
- GNUNET_TESTBED_PIT_CONFIGURATION,
- &peer_info_cb, peers[0]);
-}
-
-
-int
-main (int argc, char *argv[])
-{
- GNUNET_log_setup (testname, "INFO", NULL);
- if (GNUNET_OK ==
- GNUNET_TESTBED_test_run (testname, cfg_filename, NUM_PEERS, 0, NULL, NULL,
- &test_master, NULL))
- return ok;
- return 1;
-}
+++ /dev/null
-/*
- * This file is part of GNUnet
- * Copyright (C) 2013 GNUnet e.V.
- *
- * GNUnet is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published
- * by the Free Software Foundation; either version 3, or (at your
- * option) any later version.
- *
- * GNUnet is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GNUnet; see the file COPYING. If not, write to the
- * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-/**
- * @file sensor/plugin_sensor_model_gaussian.c
- * @brief Gaussian model for sensor analysis
- * @author Omar Tarabai
- */
-
-#include "platform.h"
-#include "gnunet_sensor_model_plugin.h"
-#include "gnunet_sensor_service.h"
-#include "sensor.h"
-
-#define LOG(kind,...) GNUNET_log_from (kind, "sensor-model-gaussian", __VA_ARGS__)
-
-/**
- * Plugin state information
- */
-struct Plugin
-{
-
- /**
- * Configuration handle
- */
- const struct GNUNET_CONFIGURATION_Handle *cfg;
-
- /**
- * Number of initial readings to be used for training only
- */
- int training_window;
-
- /**
- * Number of standard deviations considered within "normal"
- */
- int confidence_interval;
-
- /**
- * Increase in weight with each reading
- */
- float weight_inc;
-
-};
-
-/**
- * State of single model instance
- */
-struct Model
-{
-
- /**
- * Pointer to the plugin state
- */
- struct Plugin *plugin;
-
- /**
- * Gaussian sums
- */
- long double s[3];
-
- /**
- * Number of readings so far
- */
- int n;
-
- /**
- * Weight to be used for the next reading
- */
- double w;
-
-};
-
-/**
- * Update local sums of model with a new value.
- *
- * @param model Targe model
- * @param val New value
- */
-static void
-update_sums (struct Model *model, double val)
-{
- int i;
-
- for (i = 0; i < 3; i++)
- model->s[i] += model->w * pow (val, (double) i);
- model->w += model->plugin->weight_inc;
- model->n++;
-}
-
-
-/**
- * Feed a new value to a model
- *
- * @param cls closure (model state)
- * @param val value to be fed to the model
- * @return #GNUNET_YES in case of a detected outlier, #GNUNET_NO otherwise
- */
-static int
-sensor_gaussian_model_feed (void *cls, double val)
-{
- struct Model *model = cls;
- struct Plugin *plugin = model->plugin;
- long double mean;
- long double stddev;
- long double allowed_variance;
-
- if (model->n < plugin->training_window)
- {
- update_sums (model, val);
- return GNUNET_NO;
- }
- if (model->n == plugin->training_window)
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Gaussian model out of training period.\n");
- mean = model->s[1] / model->s[0];
- stddev =
- (model->s[0] * model->s[2] -
- model->s[1] * model->s[1]) / (model->s[0] * (model->s[0] - 1));
- if (stddev < 0) /* Value can be slightly less than 0 due to rounding errors */
- stddev = 0;
- stddev = sqrt (stddev);
- allowed_variance = (plugin->confidence_interval * stddev);
- if ((val < (mean - allowed_variance)) || (val > (mean + allowed_variance)))
- return GNUNET_YES;
- update_sums (model, val);
- return GNUNET_NO;
-}
-
-
-/**
- * Destroy a model instance
- *
- * @param cls closure (model state)
- */
-static void
-sensor_gaussian_model_destroy_model (void *cls)
-{
- struct Model *model = cls;
-
- GNUNET_free (model);
-}
-
-
-/**
- * Create a model instance
- *
- * @param cls closure (plugin state)
- * @return model state to be used for later calls
- */
-static void *
-sensor_gaussian_model_create_model (void *cls)
-{
- struct Plugin *plugin = cls;
- struct Model *model;
-
- model = GNUNET_new (struct Model);
-
- model->plugin = plugin;
- model->w = 1;
- return model;
-}
-
-
-/**
- * Entry point for the plugin.
- *
- * @param cls The struct GNUNET_CONFIGURATION_Handle.
- * @return NULL on error, otherwise the plugin context
- */
-void *
-libgnunet_plugin_sensor_model_gaussian_init (void *cls)
-{
- static struct Plugin plugin;
- const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
- struct GNUNET_SENSOR_ModelFunctions *api;
- unsigned long long num;
-
- if (NULL != plugin.cfg)
- return NULL; /* can only initialize once! */
- memset (&plugin, 0, sizeof (struct Plugin));
- plugin.cfg = cfg;
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_number (cfg, "sensor-model-gaussian",
- "TRAINING_WINDOW", &num))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Missing `TRAINING_WINDOW' value in configuration.\n"));
- return NULL;
- }
- if (num < 1)
- {
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "Minimum training window invalid (<1), setting to 1.\n");
- plugin.training_window = 1;
- }
- else
- {
- plugin.training_window = (int) num;
- }
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_number (cfg, "sensor-model-gaussian",
- "CONFIDENCE_INTERVAL", &num))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Missing `CONFIDENCE_INTERVAL' value in configuration.\n"));
- return NULL;
- }
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_float (cfg, "sensor-model-gaussian",
- "WEIGHT_INC", &plugin.weight_inc))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Missing `WEIGHT_INC' value in configuration.\n"));
- return NULL;
- }
- plugin.confidence_interval = (int) num;
- api = GNUNET_new (struct GNUNET_SENSOR_ModelFunctions);
-
- api->cls = &plugin;
- api->create_model = &sensor_gaussian_model_create_model;
- api->destroy_model = &sensor_gaussian_model_destroy_model;
- api->feed_model = &sensor_gaussian_model_feed;
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Gaussian model plugin is running.\n");
- return api;
-}
-
-
-/**
- * Exit point from the plugin.
- *
- * @param cls The plugin context (as returned by "init")
- * @return Always NULL
- */
-void *
-libgnunet_plugin_sensor_model_gaussian_done (void *cls)
-{
- struct GNUNET_SENSOR_ModelFunctions *api = cls;
- struct Plugin *plugin = api->cls;
-
- plugin->cfg = NULL;
- GNUNET_free (api);
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Guassian model plugin is finished\n");
- return NULL;
-
-}
-
-/* end of plugin_sensor_model_gaussian.c */
+++ /dev/null
-import argparse
-import math
-import networkx
-import random
-import tempfile
-import os
-import time
-import matplotlib.pyplot as plt
-from subprocess import Popen, PIPE, STDOUT
-
-node_colors = None
-graph = None
-pos = None
-
-def get_args():
- parser = argparse.ArgumentParser(description="Sensor profiler")
- parser.add_argument('-p', '--peers', action='store', type=int, required=True,
- help='Number of peers to run')
- parser.add_argument('-l', '--links', action='store', type=int, required=False,
- help='Number of links to create')
- parser.add_argument('-i', '--sensors-interval', action='store', type=int,
- required=False,
- help='Change the interval of running sensors to given value')
- parser.add_argument('-a', '--anomalous-peers', action='store', type=int,
- required=True,
- help='Number of peers to simulate anomalies on')
- return parser.parse_args()
-
-def generate_topology(peers, links):
- global graph
- global node_colors
- global pos
- graph = networkx.empty_graph(peers)
- for i in range(0, links):
- a = 0
- b = 0
- while a == b:
- a = random.randint(0, peers - 1)
- b = random.randint(0, peers - 1)
- graph.add_edge(a, b)
- node_colors = [0] * peers
- pos = networkx.layout.spring_layout(graph)
-
-def create_topology_file():
- global graph
- nodes = list()
- for i in range(len(graph.edge)):
- nodes.append(list())
- for e in graph.edges():
- nodes[e[0]].append(e[1])
- print nodes
- f = tempfile.NamedTemporaryFile(delete=False)
- for i in range(len(nodes)):
- if len(nodes[i]) == 0:
- continue
- f.write('%d:' % i)
- f.write('|'.join(map(str, nodes[i])))
- f.write('\n')
- # f.close()
- return f.name
-
-def draw_graph():
- global graph
- global node_colors
- global pos
- t = int(time.time())
- inc = 2
- name = str(t) + '.png'
- while os.path.exists(name):
- name = '%d(%d).png' % (t, inc)
- inc += 1
- print 'Drawing graph to file: %s' % name
- plt.clf()
- anomaly_lbls = {}
- for i in range(len(graph.node)):
- if node_colors[i] >= 1:
- anomaly_lbls[i] = '\n\n\n' + str(node_colors[i] - 1)
- networkx.draw(graph, pos=pos, node_color=node_colors, with_labels=range(len(graph.node)), cmap=plt.cm.Reds, vmin=0, vmax=2)
- networkx.draw_networkx_labels(graph, pos, anomaly_lbls)
- plt.savefig(name)
-
-def peers_reconnected(p1, p2):
- global graph
- if p2 in graph[p1]:
- print 'Link already exists'
- return
- graph.add_edge(p1, p2)
- draw_graph()
-
-def peers_disconnected(p1, p2):
- global graph
- print 'Disconnected peers %d and %d' % (p1, p2)
- if p2 not in graph[p1]:
- print 'Link does not exist'
- return
- graph.remove_edge(p1, p2)
- draw_graph()
-
-def anomaly_report(report):
- global node_colors
- if 0 == report['anomalous']:
- node_colors[report['peer']] = 0
- else:
- clr = 1 + report['neighbors']
- if node_colors[report['peer']] >= clr:
- return
- node_colors[report['peer']] = clr
- draw_graph()
-
-def handle_profiler_line(line):
- if not line:
- return
- print line
- if 'Peer disconnection request sent' in line: # Peers disconnected
- parts = line.split(':')
- peers = parts[-1].split(',')
- peers_disconnected(int(peers[0]), int(peers[1]))
- return
- if 'Anomaly report:' in line:
- parts = line.split('Anomaly report:')
- anomaly_report(eval(parts[1]))
- return
- if 'Peer connection request sent' in line: # Peers reconnected
- parts = line.split(':')
- peers = parts[-1].split(',')
- peers_reconnected(int(peers[0]), int(peers[1]))
-
-def run_profiler(peers, topology_file, sensors_interval, anomalous_peers):
- cmd1 = "./gnunet-sensor-profiler -p %d -t %s -a %d" % (peers, topology_file, anomalous_peers)
- if sensors_interval:
- cmd1 += " -i %d" % sensors_interval
- cmd2 = "> log 2>&1"
- cmd = "%s %s" % (cmd1, cmd2)
- print cmd
- process = Popen([cmd], shell=True)
- time.sleep(0.5)
- line = ''
- f = open('log')
- while process.poll() is None:
- for c in f.read():
- if not c or c == '\n':
- handle_profiler_line(line)
- line = ''
- else:
- line += c
-
-def main():
- args = vars(get_args())
- num_peers = args['peers']
- if num_peers < 3:
- print 'Min number of peers is 3'
- return
- sensors_interval = None
- if 'sensors_interval' in args:
- sensors_interval = args['sensors_interval']
- if 'links' in args:
- num_links = args['links']
- else:
- #num_links = int(math.log(num_peers) * math.log(num_peers) * num_peers / 2)
- num_links = int(math.log(num_peers) * num_peers)
- # Generate random topology
- generate_topology(num_peers, num_links)
- print 'Generated random topology with %d peers and %d links' % (num_peers, num_links)
- # Create a file with links to cut to split the topology into two
- # Create TESTBED topology file
- top_file = create_topology_file()
- print 'Created TESTBED topology file %s' % top_file
- draw_graph()
- # Run c profiler
- if os.path.isfile('log'):
- os.remove('log')
- run_profiler(num_peers, top_file, sensors_interval, args['anomalous_peers'])
-
-if __name__ == "__main__":
- main()
+++ /dev/null
-[sensor]
-AUTOSTART = @AUTOSTART@
-BINARY = gnunet-service-sensor
-UNIXPATH = $GNUNET_RUNTIME_DIR/gnunet-service-sensor.sock
-@UNIXONLY@ PORT = 2120
-UNIX_MATCH_UID = NO
-UNIX_MATCH_GID = YES
-
-# Which modules to run (default: YES)
-START_MONITORING = YES
-START_REPORTING = YES
-START_ANALYSIS = YES
-START_UPDATE = YES
-
-# Path to directory containing sensor definitions.
-# If not set, will load from default location.
-#SENSOR_DIR =
-
-[sensor-analysis]
-MODEL = gaussian
-# How many subsequent values required to flip anomaly label. (Default: 1)
-CONFIRMATION_COUNT = 1
-
-[sensor-model-gaussian]
-TRAINING_WINDOW = 400
-CONFIDENCE_INTERVAL = 8
-WEIGHT_INC = 0
-
-[sensor-reporting]
-POW_MATCHING_BITS = 15
-
-[sensor-update]
-# Space separated list of trusted peers running update points
-UPDATE_POINTS =
+++ /dev/null
-/*
- This file is part of GNUnet
- Copyright (C) 2012-2013 GNUnet e.V.
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
- */
-/**
- * @file sensor/sensor.h
- * @brief IPC messages and private service declarations
- * @author Omar Tarabai
- */
-
-#include "gnunet_sensor_service.h"
-#include "gnunet_sensor_util_lib.h"
-
-
-GNUNET_NETWORK_STRUCT_BEGIN
-/**
- * Carries a summary of a sensor
- *
- */
- struct SensorInfoMessage
-{
- /**
- * Message header
- */
- struct GNUNET_MessageHeader header;
-
- /**
- * Length of sensor name. Allocated at position 0 after this struct.
- */
- uint16_t name_len;
-
- /**
- * First part of version number
- */
- uint16_t version_major;
-
- /**
- * Second part of version number
- */
- uint16_t version_minor;
-
- /**
- * Length of sensor description. Allocated at position 1 after this struct.
- */
- uint16_t description_len;
-};
-
-/**
- * A message sent to the sensor service to force an anomaly status on a sensor.
- */
-struct ForceAnomalyMessage
-{
-
- /**
- * Message header
- */
- struct GNUNET_MessageHeader header;
-
- /**
- * Hash of the sensor name
- */
- struct GNUNET_HashCode sensor_name_hash;
-
- /**
- * New status
- */
- uint16_t anomalous;
-
-};
-
-GNUNET_NETWORK_STRUCT_END
-/**
- * Stop the sensor analysis module
- */
- void
-SENSOR_analysis_stop ();
-
-
-/**
- * Start the sensor analysis module
- *
- * @param c our service configuration
- * @param sensors multihashmap of loaded sensors
- * @return #GNUNET_OK if started successfully, #GNUNET_SYSERR otherwise
- */
-int
-SENSOR_analysis_start (const struct GNUNET_CONFIGURATION_Handle *c,
- struct GNUNET_CONTAINER_MultiHashMap *s);
-
-
-/**
- * Stop sensor anomaly reporting module
- */
-void
-SENSOR_reporting_stop ();
-
-/**
- * Used by the analysis module to tell the reporting module about a change in
- * the anomaly status of a sensor.
- *
- * @param sensor Related sensor
- * @param anomalous The new sensor anomalous status
- */
-void
-SENSOR_reporting_anomaly_update (struct GNUNET_SENSOR_SensorInfo *sensor,
- int anomalous);
-
-
-/**
- * Start the sensor anomaly reporting module
- *
- * @param c our service configuration
- * @param s multihashmap of loaded sensors
- * @return #GNUNET_OK if started successfully, #GNUNET_SYSERR otherwise
- */
-int
-SENSOR_reporting_start (const struct GNUNET_CONFIGURATION_Handle *c,
- struct GNUNET_CONTAINER_MultiHashMap *s);
-
-
-/**
- * Stop the sensor update module
- */
-void
-SENSOR_update_stop ();
-
-
-/**
- * Start the sensor update module
- *
- * @param c our service configuration
- * @param s multihashmap of loaded sensors
- * @param cb callback to reset service components when we have new updates
- * @return #GNUNET_OK if started successfully, #GNUNET_SYSERR otherwise
- */
-int
-SENSOR_update_start (const struct GNUNET_CONFIGURATION_Handle *c,
- struct GNUNET_CONTAINER_MultiHashMap *s, void (*cb) ());
-
-
-/**
- * Stop the sensor monitoring module
- */
-void
-SENSOR_monitoring_stop ();
-
-
-/**
- * Start the sensor monitoring module
- *
- * @param c our service configuration
- * @param sensors multihashmap of loaded sensors
- * @return #GNUNET_OK if started successfully, #GNUNET_SYSERR otherwise
- */
-int
-SENSOR_monitoring_start (const struct GNUNET_CONFIGURATION_Handle *c,
- struct GNUNET_CONTAINER_MultiHashMap *s);
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/sensor_api.c
- * @brief API for sensor service
- * @author Omar Tarabai
- */
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "sensor.h"
-
-#define LOG(kind,...) GNUNET_log_from (kind, "sensor-api",__VA_ARGS__)
-
-/**
- * Handle to the sensor service.
- */
-struct GNUNET_SENSOR_Handle
-{
-
- /**
- * Our configuration.
- */
- const struct GNUNET_CONFIGURATION_Handle *cfg;
-
- /**
- * Connection to the service.
- */
- struct GNUNET_CLIENT_Connection *client;
-
- /**
- * Head of iteration requests DLL.
- */
- struct GNUNET_SENSOR_IterateContext *ic_head;
-
- /**
- * Tail of iteration requests DLL.
- */
- struct GNUNET_SENSOR_IterateContext *ic_tail;
-
- /**
- * Head of force anomaly requests
- */
- struct GNUNET_SENSOR_ForceAnomalyContext *fa_head;
-
- /**
- * Tail of force anomaly requests
- */
- struct GNUNET_SENSOR_ForceAnomalyContext *fa_tail;
-
- /**
- * Message queue used to send data to service
- */
- struct GNUNET_MQ_Handle *mq;
-
-};
-
-/**
- * Context for an iteration request.
- */
-struct GNUNET_SENSOR_IterateContext
-{
-
- /**
- * Kept in a DLL.
- */
- struct GNUNET_SENSOR_IterateContext *next;
-
- /**
- * Kept in a DLL.
- */
- struct GNUNET_SENSOR_IterateContext *prev;
-
- /**
- * Handle to the SENSOR service.
- */
- struct GNUNET_SENSOR_Handle *h;
-
- /**
- * Function to call with the results.
- */
- GNUNET_SENSOR_SensorIterateCB callback;
-
- /**
- * Closure for 'callback'.
- */
- void *callback_cls;
-
- /**
- * Envelope containing iterate request.
- */
- struct GNUNET_MQ_Envelope *ev;
-
- /**
- * Is the request already sent? If yes, cannot be canceled.
- */
- int request_sent;
-
- /**
- * Are we expecting records from service?
- */
- int receiving;
-
- /**
- * Task responsible for timeout.
- */
- struct GNUNET_SCHEDULER_Task * timeout_task;
-
-};
-
-/**
- * Context of a force anomaly request
- */
-struct GNUNET_SENSOR_ForceAnomalyContext
-{
-
- /**
- * DLL
- */
- struct GNUNET_SENSOR_ForceAnomalyContext *next;
-
- /**
- * DLL
- */
- struct GNUNET_SENSOR_ForceAnomalyContext *prev;
-
- /**
- * Handle to the SENSOR service.
- */
- struct GNUNET_SENSOR_Handle *h;
-
- /**
- * Envelope containing iterate request.
- */
- struct GNUNET_MQ_Envelope *ev;
-
- /**
- * User continuation function
- */
- GNUNET_SENSOR_Continuation cont;
-
- /**
- * Closure for cont
- */
- void *cont_cls;
-
-};
-
-
-/**
- * Notifier of an error encountered by MQ.
- *
- * @param cls Closure, service handle
- * @param error MQ error type
- */
-static void
-mq_error_handler (void *cls, enum GNUNET_MQ_Error error)
-{
- struct GNUNET_SENSOR_Handle *h = cls;
-
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Received an error notification from MQ of type: %d\n"), error);
- GNUNET_SENSOR_disconnect (h); //TODO: try to reconnect
-}
-
-
-/**
- * Handler to a message of type: #GNUNET_MESSAGE_TYPE_SENSOR_END
- *
- * @param cls Closure, service handle
- * @param msg Message received
- */
-static void
-handle_end (void *cls, const struct GNUNET_MessageHeader *msg)
-{
- struct GNUNET_SENSOR_Handle *h = cls;
- struct GNUNET_SENSOR_IterateContext *ic;
- GNUNET_SENSOR_SensorIterateCB cb;
- void *cb_cls;
-
- if (NULL == h->ic_head)
- {
- GNUNET_break_op (0);
- //TODO: reconnect
- return;
- }
- ic = h->ic_head;
- cb = ic->callback;
- cb_cls = ic->callback_cls;
- ic->receiving = GNUNET_NO;
- GNUNET_SENSOR_iterate_cancel (ic);
- if (NULL != cb)
- cb (cb_cls, NULL, NULL);
-}
-
-
-/**
- * Handler to a message of type: #GNUNET_MESSAGE_TYPE_SENSOR_INFO
- *
- * @param cls Closure, service handle
- * @param msg Message received
- */
-static void
-handle_sensor_info (void *cls, const struct GNUNET_MessageHeader *msg)
-{
- struct GNUNET_SENSOR_Handle *h = cls;
- struct GNUNET_SENSOR_IterateContext *ic;
- uint16_t msg_size;
- struct SensorInfoMessage *sensor_msg;
- uint16_t sensor_name_len;
- uint16_t sensor_desc_len;
- struct SensorInfoShort *sensor;
- void *dummy;
-
- if (NULL == h->ic_head)
- {
- GNUNET_break_op (0);
- //TODO: reconnect
- return;
- }
- ic = h->ic_head;
- if (NULL == ic->callback) /* no need to parse message */
- return;
- msg_size = ntohs (msg->size);
- if (msg_size < sizeof (struct SensorInfoMessage))
- {
- GNUNET_break_op (0);
- //TODO: reconnect
- return;
- }
- sensor_msg = (struct SensorInfoMessage *) msg;
- sensor_name_len = ntohs (sensor_msg->name_len);
- sensor_desc_len = ntohs (sensor_msg->description_len);
- if (msg_size !=
- sizeof (struct SensorInfoMessage) + sensor_name_len + sensor_desc_len)
- {
- GNUNET_break_op (0);
- //TODO: reconnect
- return;
- }
- sensor = GNUNET_new (struct SensorInfoShort);
- sensor->version_major = ntohs (sensor_msg->version_major);
- sensor->version_minor = ntohs (sensor_msg->version_minor);
- dummy = &sensor_msg[1];
- sensor->name = GNUNET_strndup (dummy, sensor_name_len);
- dummy += sensor_name_len;
- sensor->description = GNUNET_strndup (dummy, sensor_desc_len);
- ic->callback (ic->callback_cls, sensor, NULL);
- GNUNET_free (sensor->name);
- GNUNET_free (sensor->description);
- GNUNET_free (sensor);
-}
-
-
-/**
- * Disconnect from the sensor service.
- * Please disconnect only when all requests sent are complete or canceled.
- *
- * @param h handle to disconnect
- */
-void
-GNUNET_SENSOR_disconnect (struct GNUNET_SENSOR_Handle *h)
-{
- struct GNUNET_SENSOR_IterateContext *ic;
- GNUNET_SENSOR_SensorIterateCB ic_callback;
- void *ic_callback_cls;
- struct GNUNET_SENSOR_ForceAnomalyContext *fa;
- GNUNET_SENSOR_Continuation fa_cont;
- void *fa_cont_cls;
-
- ic = h->ic_head;
- while (NULL != ic)
- {
- ic_callback = ic->callback;
- ic_callback_cls = ic->callback_cls;
- GNUNET_SENSOR_iterate_cancel (ic);
- if (NULL != ic_callback)
- ic_callback (ic_callback_cls, NULL,
- _("Iterate request canceled due to disconnection.\n"));
- ic = h->ic_head;
- }
- fa = h->fa_head;
- while (NULL != fa)
- {
- fa_cont = fa->cont;
- fa_cont_cls = fa->cont_cls;
- GNUNET_SENSOR_force_anomaly_cancel (fa);
- if (NULL != fa_cont)
- fa_cont (fa_cont_cls,
- _("Force anomaly request canceled due to disconnection.\n"));
- fa = h->fa_head;
- }
- if (NULL != h->mq)
- {
- GNUNET_MQ_destroy (h->mq);
- h->mq = NULL;
- }
- if (NULL != h->client)
- {
- GNUNET_CLIENT_disconnect (h->client);
- h->client = NULL;
- }
- GNUNET_free (h);
-}
-
-
-/**
- * Connect to the sensor service.
- *
- * @return NULL on error
- */
-struct GNUNET_SENSOR_Handle *
-GNUNET_SENSOR_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
-{
- struct GNUNET_CLIENT_Connection *client;
- struct GNUNET_SENSOR_Handle *h;
-
- static const struct GNUNET_MQ_MessageHandler mq_handlers[] = {
- {&handle_sensor_info, GNUNET_MESSAGE_TYPE_SENSOR_INFO, 0},
- {&handle_end, GNUNET_MESSAGE_TYPE_SENSOR_END, 0},
- GNUNET_MQ_HANDLERS_END
- };
-
- client = GNUNET_CLIENT_connect ("sensor", cfg);
- if (NULL == client)
- return NULL;
- h = GNUNET_new (struct GNUNET_SENSOR_Handle);
- h->client = client;
- h->cfg = cfg;
- h->mq =
- GNUNET_MQ_queue_for_connection_client (h->client, mq_handlers,
- &mq_error_handler, h);
- return h;
-}
-
-
-/**
- * Iteration request has timed out.
- *
- * @param cls the 'struct GNUNET_SENSOR_SensorIteratorContext*'
- * @param tc scheduler context
- */
-static void
-signal_sensor_iteration_timeout (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct GNUNET_SENSOR_IterateContext *ic = cls;
- GNUNET_SENSOR_SensorIterateCB cb;
- void *cb_cls;
-
- ic->timeout_task = NULL;
- cb = ic->callback;
- cb_cls = ic->callback_cls;
- GNUNET_SENSOR_iterate_cancel (ic);
- if (NULL != cb)
- cb (cb_cls, NULL,
- _("Timeout transmitting iteration request to `SENSOR' service."));
-}
-
-
-/**
- * Callback from MQ when the request has already been sent to the service.
- * Now it can not be canelled.
- *
- * @param cls closure
- */
-static void
-iterate_request_sent (void *cls)
-{
- struct GNUNET_SENSOR_IterateContext *ic = cls;
-
- ic->request_sent = GNUNET_YES;
- ic->ev = NULL;
- ic->receiving = GNUNET_YES;
-}
-
-
-/**
- * Cancel an iteration request.
- * This should be called before the iterate callback is called with a NULL value.
- *
- * @param ic context of the iterator to cancel
- */
-void
-GNUNET_SENSOR_iterate_cancel (struct GNUNET_SENSOR_IterateContext *ic)
-{
- struct GNUNET_SENSOR_Handle *h;
-
- h = ic->h;
- if (GNUNET_NO == ic->request_sent)
- {
- GNUNET_MQ_send_cancel (ic->ev);
- ic->ev = NULL;
- ic->request_sent = GNUNET_YES;
- }
- if (GNUNET_YES == ic->receiving)
- {
- /* don't remove since we are still expecting records */
- ic->callback = NULL;
- ic->callback_cls = NULL;
- return;
- }
- if (NULL != ic->timeout_task)
- {
- GNUNET_SCHEDULER_cancel (ic->timeout_task);
- ic->timeout_task = NULL;
- }
- GNUNET_CONTAINER_DLL_remove (h->ic_head, h->ic_tail, ic);
- GNUNET_free (ic);
-}
-
-
-/**
- * Get one or all sensors loaded by the sensor service.
- * The callback will be called with each sensor received and once with a NULL
- * value to signal end of iteration.
- *
- * @param h Handle to SENSOR service
- * @param timeout how long to wait until timing out
- * @param sensorname Name of the required sensor, NULL to get all
- * @param callback the function to call for each sensor
- * @param callback_cls closure for callback
- * @return iterator context
- */
-struct GNUNET_SENSOR_IterateContext *
-GNUNET_SENSOR_iterate (struct GNUNET_SENSOR_Handle *h,
- struct GNUNET_TIME_Relative timeout,
- const char *sensor_name,
- GNUNET_SENSOR_SensorIterateCB callback,
- void *callback_cls)
-{
- struct GNUNET_SENSOR_IterateContext *ic;
- struct GNUNET_MessageHeader *msg;
- struct GNUNET_MQ_Envelope *ev;
- size_t sensor_name_len;
-
- if (NULL == sensor_name)
- {
- ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SENSOR_GETALL);
- }
- else
- {
- sensor_name_len = strlen (sensor_name) + 1;
- ev = GNUNET_MQ_msg_extra (msg, sensor_name_len,
- GNUNET_MESSAGE_TYPE_SENSOR_GET);
- memcpy (&msg[1], sensor_name, sensor_name_len);
- }
- GNUNET_MQ_send (h->mq, ev);
- ic = GNUNET_new (struct GNUNET_SENSOR_IterateContext);
-
- ic->h = h;
- ic->ev = ev;
- ic->request_sent = GNUNET_NO;
- ic->receiving = GNUNET_NO;
- ic->callback = callback;
- ic->callback_cls = callback_cls;
- ic->timeout_task =
- GNUNET_SCHEDULER_add_delayed (timeout, &signal_sensor_iteration_timeout,
- ic);
- GNUNET_MQ_notify_sent (ev, &iterate_request_sent, ic);
- GNUNET_CONTAINER_DLL_insert_tail (h->ic_head, h->ic_tail, ic);
- return ic;
-}
-
-
-/**
- * Callback from MQ when the request has already been sent to the service.
- * Now it can not be canelled.
- *
- * @param cls closure
- */
-static void
-force_anomaly_sent (void *cls)
-{
- struct GNUNET_SENSOR_ForceAnomalyContext *fa = cls;
- GNUNET_SENSOR_Continuation cont;
- void *cont_cls;
-
- fa->ev = NULL;
- cont = fa->cont;
- cont_cls = fa->cont_cls;
- GNUNET_SENSOR_force_anomaly_cancel (fa);
- if (NULL != cont)
- cont (cont_cls, NULL);
-}
-
-
-/**
- * Cancel a force anomaly request.
- *
- * @param fa Force anomaly context returned by GNUNET_SENSOR_force_anomaly()
- */
-void
-GNUNET_SENSOR_force_anomaly_cancel (struct GNUNET_SENSOR_ForceAnomalyContext
- *fa)
-{
- struct GNUNET_SENSOR_Handle *h = fa->h;
-
- if (NULL != fa->ev)
- {
- GNUNET_MQ_send_cancel (fa->ev);
- fa->ev = NULL;
- }
- GNUNET_CONTAINER_DLL_remove (h->fa_head, h->fa_tail, fa);
- GNUNET_free (fa);
-}
-
-
-/**
- * Force an anomaly status change on a given sensor. If the sensor reporting
- * module is running, this will trigger the usual reporting logic, therefore,
- * please only use this in a test environment.
- *
- * Also, if the sensor analysis module is running, it might conflict and cause
- * undefined behaviour if it detects a real anomaly.
- *
- * @param h Service handle
- * @param sensor_name Sensor name to set the anomaly status
- * @param anomalous The desired status: #GNUNET_YES / #GNUNET_NO
- * @param cont Continuation function to be called after the request is sent
- * @param cont_cls Closure for cont
- */
-struct GNUNET_SENSOR_ForceAnomalyContext *
-GNUNET_SENSOR_force_anomaly (struct GNUNET_SENSOR_Handle *h, char *sensor_name,
- int anomalous, GNUNET_SENSOR_Continuation cont,
- void *cont_cls)
-{
- struct ForceAnomalyMessage *msg;
- struct GNUNET_MQ_Envelope *ev;
- struct GNUNET_SENSOR_ForceAnomalyContext *fa;
-
- ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SENSOR_ANOMALY_FORCE);
- GNUNET_CRYPTO_hash (sensor_name, strlen (sensor_name) + 1,
- &msg->sensor_name_hash);
- msg->anomalous = htons (anomalous);
- GNUNET_MQ_send (h->mq, ev);
- fa = GNUNET_new (struct GNUNET_SENSOR_ForceAnomalyContext);
-
- fa->h = h;
- fa->cont = cont;
- fa->cont_cls = cont_cls;
- fa->ev = ev;
- GNUNET_CONTAINER_DLL_insert_tail (h->fa_head, h->fa_tail, fa);
- GNUNET_MQ_notify_sent (ev, &force_anomaly_sent, fa);
- return fa;
-}
-
-
-/* end of sensor_api.c */
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/sensor_util_lib.c
- * @brief sensor utilities
- * @author Omar Tarabai
- */
-#include <inttypes.h>
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "gnunet_sensor_util_lib.h"
-#include "gnunet_statistics_service.h"
-
-#define LOG(kind,...) GNUNET_log_from (kind, "sensor-util",__VA_ARGS__)
-
-/**
- * Supported sources of sensor information
- */
-static const char *sources[] = { "gnunet-statistics", "process", NULL };
-
-/**
- * Supported datatypes of sensor information
- */
-static const char *datatypes[] = { "numeric", "string", NULL };
-
-/**
- * Parses a version number string into major and minor
- *
- * @param version full version string
- * @param major pointer to parsed major value
- * @param minor pointer to parsed minor value
- * @return #GNUNET_OK if parsing went ok, #GNUNET_SYSERR in case of error
- */
-static int
-version_parse (char *version, uint16_t * major, uint16_t * minor)
-{
- int majorval = 0;
- int minorval = 0;
-
- for (; isdigit (*version); version++)
- {
- majorval *= 10;
- majorval += *version - '0';
- }
- if (*version != '.')
- return GNUNET_SYSERR;
- version++;
- for (; isdigit (*version); version++)
- {
- minorval *= 10;
- minorval += *version - '0';
- }
- if (*version != 0)
- return GNUNET_SYSERR;
- *major = majorval;
- *minor = minorval;
-
- return GNUNET_OK;
-}
-
-
-/**
- * Load sensor definition from configuration
- *
- * @param cfg configuration handle
- * @param sectionname configuration section containing definition
- */
-static struct GNUNET_SENSOR_SensorInfo *
-load_sensor_from_cfg (struct GNUNET_CONFIGURATION_Handle *cfg,
- const char *sectionname)
-{
- struct GNUNET_SENSOR_SensorInfo *sensor;
- char *version_str;
- char *starttime_str;
- char *endtime_str;
- unsigned long long time_sec;
- char *dummy;
- struct GNUNET_CRYPTO_EddsaPublicKey public_key;
-
- sensor = GNUNET_new (struct GNUNET_SENSOR_SensorInfo);
-
- //name
- sensor->name = GNUNET_strdup (sectionname);
- //version
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_string (cfg, sectionname, "VERSION",
- &version_str))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor version\n"));
- GNUNET_free (sensor);
- return NULL;
- }
- if (GNUNET_OK !=
- version_parse (version_str, &(sensor->version_major),
- &(sensor->version_minor)))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Invalid sensor version number, format should be major.minor\n"));
- GNUNET_free (sensor);
- GNUNET_free (version_str);
- return NULL;
- }
- GNUNET_free (version_str);
- //description
- GNUNET_CONFIGURATION_get_value_string (cfg, sectionname, "DESCRIPTION",
- &sensor->description);
- //category
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_string (cfg, sectionname, "CATEGORY",
- &sensor->category) ||
- NULL == sensor->category)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor category\n"));
- GNUNET_free (sensor);
- return NULL;
- }
- //enabled
- if (GNUNET_NO ==
- GNUNET_CONFIGURATION_get_value_yesno (cfg, sectionname, "ENABLED"))
- sensor->enabled = GNUNET_NO;
- else
- sensor->enabled = GNUNET_YES;
- //start time
- sensor->start_time = NULL;
- if (GNUNET_OK ==
- GNUNET_CONFIGURATION_get_value_string (cfg, sectionname, "START_TIME",
- &starttime_str))
- {
- GNUNET_STRINGS_fancy_time_to_absolute (starttime_str, sensor->start_time);
- GNUNET_free (starttime_str);
- }
- //end time
- sensor->end_time = NULL;
- if (GNUNET_OK ==
- GNUNET_CONFIGURATION_get_value_string (cfg, sectionname, "END_TIME",
- &endtime_str))
- {
- GNUNET_STRINGS_fancy_time_to_absolute (endtime_str, sensor->end_time);
- GNUNET_free (endtime_str);
- }
- //interval
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_number (cfg, sectionname, "INTERVAL",
- &time_sec))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor run interval\n"));
- GNUNET_free (sensor);
- return NULL;
- }
- sensor->interval =
- GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, time_sec);
- //lifetime
- if (GNUNET_OK ==
- GNUNET_CONFIGURATION_get_value_number (cfg, sectionname, "LIFETIME",
- &time_sec))
- {
- sensor->lifetime =
- GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, time_sec);
- if (sensor->lifetime.rel_value_us < sensor->interval.rel_value_us)
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "Lifetime of sensor data is preferred to be higher than interval for sensor `%s'.\n",
- sensor->name);
- }
- else
- sensor->lifetime = GNUNET_TIME_UNIT_FOREVER_REL;
- //capabilities TODO
- //source
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_choice (cfg, sectionname, "SOURCE",
- sources,
- (const char **) &sensor->source))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor source\n"));
- GNUNET_free (sensor);
- return NULL;
- }
- if (sources[0] == sensor->source) //gnunet-statistics
- {
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_string (cfg, sectionname,
- "GNUNET_STAT_SERVICE",
- &sensor->gnunet_stat_service) ||
- GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, sectionname,
- "GNUNET_STAT_NAME",
- &sensor->gnunet_stat_name))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Error reading sensor gnunet-statistics source information\n"));
- GNUNET_free (sensor);
- return NULL;
- }
- sensor->gnunet_stat_get_handle = NULL;
- }
- else if (sources[1] == sensor->source) //process
- {
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_string (cfg, sectionname, "EXT_PROCESS",
- &sensor->ext_process))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor process name\n"));
- GNUNET_free (sensor);
- return NULL;
- }
- GNUNET_CONFIGURATION_get_value_string (cfg, sectionname, "EXT_ARGS",
- &sensor->ext_args);
- }
- //expected datatype
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_choice (cfg, sectionname,
- "EXPECTED_DATATYPE", datatypes,
- (const char **)
- &sensor->expected_datatype))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Error reading sensor expected datatype\n"));
- GNUNET_free (sensor);
- return NULL;
- }
- if (sources[0] == sensor->source && datatypes[0] != sensor->expected_datatype)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _
- ("Invalid expected datatype, gnunet-statistics returns uint64 values\n"));
- GNUNET_free (sensor);
- return NULL;
- }
- //reporting
- sensor->collection_point = NULL;
- sensor->report_values = GNUNET_NO;
- sensor->report_anomalies = GNUNET_NO;
- if (GNUNET_OK ==
- GNUNET_CONFIGURATION_get_value_string (cfg, sectionname,
- "COLLECTION_POINT", &dummy))
- {
- if (GNUNET_OK ==
- GNUNET_CRYPTO_eddsa_public_key_from_string (dummy, strlen (dummy),
- &public_key))
- {
- sensor->collection_point = GNUNET_new (struct GNUNET_PeerIdentity);
-
- sensor->collection_point->public_key = public_key;
- if (GNUNET_OK ==
- GNUNET_CONFIGURATION_get_value_number (cfg, sectionname,
- "VALUE_COLLECTION_INTERVAL",
- &time_sec))
- {
- sensor->report_values = GNUNET_YES;
- sensor->value_reporting_interval =
- GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, time_sec);
- }
- if (GNUNET_YES ==
- GNUNET_CONFIGURATION_get_value_yesno (cfg, sectionname,
- "REPORT_ANOMALIES"))
- sensor->report_anomalies = GNUNET_YES;
- }
- GNUNET_free (dummy);
- }
- //execution task
- sensor->execution_task = NULL;
- //running
- sensor->running = GNUNET_NO;
- return sensor;
-}
-
-
-/**
- * Load sensor definition from file
- *
- * @param filename full path to file containing sensor definition
- */
-static struct GNUNET_SENSOR_SensorInfo *
-load_sensor_from_file (const char *filename)
-{
- struct GNUNET_CONFIGURATION_Handle *sensorcfg;
- const char *filebasename;
- struct GNUNET_SENSOR_SensorInfo *sensor;
-
- //test file
- if (GNUNET_YES != GNUNET_DISK_file_test (filename))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to access sensor file: %s\n"),
- filename);
- return NULL;
- }
- //load file as configuration
- sensorcfg = GNUNET_CONFIGURATION_create ();
- if (GNUNET_SYSERR == GNUNET_CONFIGURATION_parse (sensorcfg, filename))
- {
- GNUNET_CONFIGURATION_destroy (sensorcfg);
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to load sensor definition: %s\n"),
- filename);
- return NULL;
- }
- //configuration section should be the same as filename
- filebasename = GNUNET_STRINGS_get_short_name (filename);
- sensor = load_sensor_from_cfg (sensorcfg, filebasename);
- if (NULL == sensor)
- {
- GNUNET_CONFIGURATION_destroy (sensorcfg);
- return NULL;
- }
- sensor->def_file = GNUNET_strdup (filename);
- sensor->cfg = sensorcfg;
- return sensor;
-}
-
-
-/**
- * Given two version numbers as major and minor, compare them.
- *
- * @param v1_major First part of first version number
- * @param v1_minor Second part of first version number
- * @param v2_major First part of second version number
- * @param v2_minor Second part of second version number
- */
-int
-GNUNET_SENSOR_version_compare (uint16_t v1_major, uint16_t v1_minor,
- uint16_t v2_major, uint16_t v2_minor)
-{
- if (v1_major == v2_major)
- return (v1_minor < v2_minor) ? -1 : (v1_minor > v2_minor);
- else
- return (v1_major < v2_major) ? -1 : (v1_major > v2_major);
-}
-
-
-/**
- * Adds a new sensor to given hashmap.
- * If the same name exist, compares versions and update if old.
- *
- * @param sensor Sensor structure to add
- * @param map Hashmap to add to
- * @return #GNUNET_YES if added
- * #GNUNET_NO if not added which is not necessarily an error
- */
-static int
-add_sensor_to_hashmap (struct GNUNET_SENSOR_SensorInfo *sensor,
- struct GNUNET_CONTAINER_MultiHashMap *map)
-{
- struct GNUNET_HashCode key;
- struct GNUNET_SENSOR_SensorInfo *existing;
-
- GNUNET_CRYPTO_hash (sensor->name, strlen (sensor->name) + 1, &key);
- existing = GNUNET_CONTAINER_multihashmap_get (map, &key);
- if (NULL != existing) //sensor with same name already exists
- {
- if (GNUNET_SENSOR_version_compare
- (existing->version_major, existing->version_minor,
- sensor->version_major, sensor->version_minor) >= 0)
- {
- LOG (GNUNET_ERROR_TYPE_INFO,
- _("Sensor `%s' already exists with same or newer version\n"),
- sensor->name);
- return GNUNET_NO;
- }
- else
- {
- GNUNET_CONTAINER_multihashmap_remove (map, &key, existing); //remove the old version
- GNUNET_free (existing);
- LOG (GNUNET_ERROR_TYPE_INFO, "Upgrading sensor `%s' to a newer version\n",
- sensor->name);
- }
- }
- if (GNUNET_SYSERR ==
- GNUNET_CONTAINER_multihashmap_put (map, &key, sensor,
- GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
- {
- LOG (GNUNET_ERROR_TYPE_ERROR,
- _("Error adding new sensor `%s' to global hashmap.\n"), sensor->name);
- return GNUNET_NO;
- }
- return GNUNET_YES;
-}
-
-
-/**
- * Iterating over files in sensors directory
- *
- * @param cls closure
- * @param filename complete filename (absolute path)
- * @return #GNUNET_OK to continue to iterate
- */
-static int
-reload_sensors_dir_cb (void *cls, const char *filename)
-{
- struct GNUNET_CONTAINER_MultiHashMap *sensors = cls;
- struct GNUNET_SENSOR_SensorInfo *sensor;
-
- if (GNUNET_YES != GNUNET_DISK_file_test (filename))
- return GNUNET_OK;
- sensor = load_sensor_from_file (filename);
- if (NULL == sensor)
- {
- LOG (GNUNET_ERROR_TYPE_ERROR, _("Error loading sensor from file: %s\n"),
- filename);
- return GNUNET_OK;
- }
- if (GNUNET_YES != add_sensor_to_hashmap (sensor, sensors))
- LOG (GNUNET_ERROR_TYPE_WARNING,
- "Could not add sensor `%s' to global hashmap\n", sensor->name);
- return GNUNET_OK;
-}
-
-
-/**
- * Get path to the default directory containing the sensor definition files with
- * a trailing directory separator.
- *
- * @return Default sensor files directory full path
- */
-char *
-GNUNET_SENSOR_get_default_sensor_dir ()
-{
- char *datadir;
- char *sensordir;
-
- datadir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
- GNUNET_asprintf (&sensordir, "%ssensors%s", datadir, DIR_SEPARATOR_STR);
- GNUNET_free (datadir);
- return sensordir;
-}
-
-
-/**
- * Reads sensor definitions from given sensor directory.
- *
- * @param sensordir Path to sensor directory.
- * @return a multihashmap of loaded sensors
- */
-struct GNUNET_CONTAINER_MultiHashMap *
-GNUNET_SENSOR_load_all_sensors (char *sensor_dir)
-{
- struct GNUNET_CONTAINER_MultiHashMap *sensors;
-
- GNUNET_assert (NULL != sensor_dir);
- sensors = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
- LOG (GNUNET_ERROR_TYPE_INFO,
- "Loading sensor definitions from directory `%s'\n", sensor_dir);
- GNUNET_assert (GNUNET_YES ==
- GNUNET_DISK_directory_test (sensor_dir, GNUNET_YES));
- /* read all files in sensors directory */
- GNUNET_DISK_directory_scan (sensor_dir, &reload_sensors_dir_cb, sensors);
- LOG (GNUNET_ERROR_TYPE_INFO, "Loaded %d sensors from directory `%s'\n",
- GNUNET_CONTAINER_multihashmap_size (sensors), sensor_dir);
- return sensors;
-}
-
-
-/**
- * Remove sensor execution from scheduler
- *
- * @param cls unused
- * @param key hash of sensor name, key to hashmap
- * @param value a `struct GNUNET_SENSOR_SensorInfo *`
- * @return #GNUNET_YES if we should continue to
- * iterate,
- * #GNUNET_NO if not.
- */
-static int
-destroy_sensor (void *cls, const struct GNUNET_HashCode *key, void *value)
-{
- struct GNUNET_SENSOR_SensorInfo *sensor = value;
-
- if (NULL != sensor->execution_task)
- {
- GNUNET_SCHEDULER_cancel (sensor->execution_task);
- sensor->execution_task = NULL;
- }
- if (NULL != sensor->gnunet_stat_get_handle)
- {
- GNUNET_STATISTICS_get_cancel (sensor->gnunet_stat_get_handle);
- sensor->gnunet_stat_get_handle = NULL;
- }
- if (NULL != sensor->ext_cmd)
- {
- GNUNET_OS_command_stop (sensor->ext_cmd);
- sensor->ext_cmd = NULL;
- }
- if (NULL != sensor->cfg)
- GNUNET_CONFIGURATION_destroy (sensor->cfg);
- if (NULL != sensor->name)
- GNUNET_free (sensor->name);
- if (NULL != sensor->def_file)
- GNUNET_free (sensor->def_file);
- if (NULL != sensor->description)
- GNUNET_free (sensor->description);
- if (NULL != sensor->category)
- GNUNET_free (sensor->category);
- if (NULL != sensor->capabilities)
- GNUNET_free (sensor->capabilities);
- if (NULL != sensor->gnunet_stat_service)
- GNUNET_free (sensor->gnunet_stat_service);
- if (NULL != sensor->gnunet_stat_name)
- GNUNET_free (sensor->gnunet_stat_name);
- if (NULL != sensor->ext_process)
- GNUNET_free (sensor->ext_process);
- if (NULL != sensor->ext_args)
- GNUNET_free (sensor->ext_args);
- if (NULL != sensor->collection_point)
- GNUNET_free (sensor->collection_point);
- GNUNET_free (sensor);
- return GNUNET_YES;
-}
-
-
-/**
- * Destroys a group of sensors in a hashmap and the hashmap itself
- *
- * @param sensors hashmap containing the sensors
- */
-void
-GNUNET_SENSOR_destroy_sensors (struct GNUNET_CONTAINER_MultiHashMap *sensors)
-{
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying sensor list.\n");
- GNUNET_CONTAINER_multihashmap_iterate (sensors, &destroy_sensor, NULL);
- GNUNET_CONTAINER_multihashmap_destroy (sensors);
-}
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensor/sensor_util_lib_crypto.c
- * @brief senor utilities - crpyto related functions
- * @author Omar Tarabai
- */
-#include <inttypes.h>
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "gnunet_sensor_util_lib.h"
-#include "gnunet_signatures.h"
-
-#define LOG(kind,...) GNUNET_log_from (kind, "sensor-util-crypto",__VA_ARGS__)
-
-/**
- * Context of an operation performed by #GNUNET_SENSOR_crypto_pow_sign()
- */
-struct GNUNET_SENSOR_crypto_pow_context
-{
-
- /**
- * Proof-of-work value
- */
- uint64_t pow;
-
- /**
- * Private key to be used for signing
- */
- struct GNUNET_CRYPTO_EddsaPrivateKey private_key;
-
- /**
- * Number of leading zeros required in the result hash
- */
- int matching_bits;
-
- /**
- * Callback function to call with the result
- */
- GNUNET_SENSOR_UTIL_pow_callback callback;
-
- /**
- * Closure for callback
- */
- void *callback_cls;
-
- /**
- * Task that calculates the proof-of-work
- */
- struct GNUNET_SCHEDULER_Task * calculate_pow_task;
-
- /**
- * Size of msg (allocated after this struct)
- */
- size_t msg_size;
-
- /**
- * Timestamp of the message
- */
- struct GNUNET_TIME_Absolute timestamp;
-
- /**
- * Public key of the peer sending this message
- */
- struct GNUNET_CRYPTO_EddsaPublicKey public_key;
-
-};
-
-
-/**
- * Calculate the scrypt hash
- */
-static void
-pow_hash (const void *buf, size_t buf_len, struct GNUNET_HashCode *result)
-{
- GNUNET_break (0 ==
- gcry_kdf_derive (buf, buf_len, GCRY_KDF_SCRYPT,
- 1 /* subalgo */ ,
- "gnunet-sensor-util-proof-of-work",
- strlen ("gnunet-sensor-util-proof-of-work"), 2
- /* iterations; keep cost of individual op small */
- , sizeof (struct GNUNET_HashCode), result));
-}
-
-
-/**
- * Count the leading zeroes in hash.
- *
- * @param hash to count leading zeros in
- * @return the number of leading zero bits.
- */
-static unsigned int
-count_leading_zeroes (const struct GNUNET_HashCode *hash)
-{
- unsigned int hash_count;
-
- hash_count = 0;
- while ((0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count)))
- hash_count++;
- return hash_count;
-}
-
-
-/**
- * Check if the given proof-of-work is valid
- */
-static int
-check_pow (void *msg, size_t msg_size, uint64_t pow, int matching_bits)
-{
- char buf[msg_size + sizeof (pow)] GNUNET_ALIGN;
- struct GNUNET_HashCode result;
-
- memcpy (buf, &pow, sizeof (pow));
- memcpy (&buf[sizeof (pow)], msg, msg_size);
- pow_hash (buf, sizeof (buf), &result);
- return (count_leading_zeroes (&result) >=
- matching_bits) ? GNUNET_YES : GNUNET_NO;
-}
-
-
-/**
- * Task that checks if pow is correct, otherwise increments and reschedules itself
- */
-static void
-calculate_pow (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct GNUNET_SENSOR_crypto_pow_context *cx = cls;
- struct GNUNET_SENSOR_crypto_pow_block *result_block;
- GNUNET_SENSOR_UTIL_pow_callback callback;
- void *callback_cls;
- int sign_result;
-
- if (0 == cx->pow % 1000)
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking pow %" PRIu64 ".\n", cx->pow);
- if (GNUNET_YES ==
- check_pow (&cx->timestamp,
- sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
- sizeof (struct GNUNET_TIME_Absolute) + cx->msg_size, cx->pow,
- cx->matching_bits))
- {
- LOG (GNUNET_ERROR_TYPE_DEBUG, "Found pow %" PRIu64 ".\n", cx->pow);
- cx->calculate_pow_task = NULL;
- result_block =
- GNUNET_malloc (sizeof (struct GNUNET_SENSOR_crypto_pow_block) +
- cx->msg_size);
- result_block->msg_size = cx->msg_size;
- result_block->pow = cx->pow;
- result_block->timestamp = cx->timestamp;
- result_block->public_key = cx->public_key;
- result_block->purpose.purpose =
- htonl (GNUNET_SIGNATURE_PURPOSE_SENSOR_ANOMALY_REPORT);
- result_block->purpose.size =
- htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
- sizeof (struct GNUNET_TIME_Absolute) +
- sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) + cx->msg_size);
- memcpy (&result_block[1], &cx[1], cx->msg_size);
- sign_result =
- GNUNET_CRYPTO_eddsa_sign (&cx->private_key, &result_block->purpose,
- &result_block->signature);
- callback = cx->callback;
- callback_cls = cx->callback_cls;
- GNUNET_SENSOR_crypto_pow_sign_cancel (cx);
- if (NULL != callback)
- callback (callback_cls, (GNUNET_OK == sign_result) ? result_block : NULL);
- GNUNET_free (result_block);
- return;
- }
- cx->pow++;
- cx->calculate_pow_task = GNUNET_SCHEDULER_add_now (&calculate_pow, cx);
-}
-
-
-/**
- * Cancel an operation started by #GNUNET_SENSOR_crypto_pow_sign().
- * Call only before callback function passed to #GNUNET_SENSOR_crypto_pow_sign()
- * is called with the result.
- */
-void
-GNUNET_SENSOR_crypto_pow_sign_cancel (struct GNUNET_SENSOR_crypto_pow_context
- *cx)
-{
- if (NULL != cx->calculate_pow_task)
- {
- GNUNET_SCHEDULER_cancel (cx->calculate_pow_task);
- cx->calculate_pow_task = NULL;
- }
- GNUNET_free (cx);
- cx = NULL;
-}
-
-
-/**
- * Calculate proof-of-work and sign a message.
- * The result of all operations will be returned via the callback passed to this
- * function. Note that the payload (msg) is copied to the result block.
- *
- * @param msg Message to calculate pow and sign
- * @param msg_size size of msg
- * @param timestamp Timestamp to add to the message to protect against replay attacks
- * @param public_key Public key of the origin peer, to protect against redirect attacks
- * @param private_key Private key of the origin peer to sign the result
- * @param matching_bits Number of leading zeros required in the result hash
- * @param callback Callback function to call with the result
- * @param callback_cls Closure for callback
- * @return Operation context
- */
-struct GNUNET_SENSOR_crypto_pow_context *
-GNUNET_SENSOR_crypto_pow_sign (void *msg, size_t msg_size,
- struct GNUNET_TIME_Absolute *timestamp,
- struct GNUNET_CRYPTO_EddsaPublicKey *public_key,
- struct GNUNET_CRYPTO_EddsaPrivateKey
- *private_key, int matching_bits,
- GNUNET_SENSOR_UTIL_pow_callback callback,
- void *callback_cls)
-{
- struct GNUNET_SENSOR_crypto_pow_context *cx;
-
- cx = GNUNET_malloc (sizeof (struct GNUNET_SENSOR_crypto_pow_context) +
- msg_size);
-
- cx->timestamp = *timestamp;
- cx->public_key = *public_key;
- cx->msg_size = msg_size;
- memcpy (&cx[1], msg, msg_size);
- cx->pow = 0;
- cx->private_key = *private_key;
- cx->matching_bits = matching_bits;
- cx->callback = callback;
- cx->callback_cls = callback_cls;
- cx->calculate_pow_task = GNUNET_SCHEDULER_add_now (&calculate_pow, cx);
- return cx;
-}
-
-
-/**
- * Verify that proof-of-work and signature in the given block are valid.
- * If all valid, a pointer to the payload within the block is set and the size
- * of the payload is returned.
- *
- * **VERY IMPORTANT** : You will still need to verify the timestamp yourself.
- *
- * @param block The block received and needs to be verified
- * @param matching_bits Number of leading zeros in the hash used to verify pow
- * @param public_key Public key of the peer that sent this block
- * @param payload Where to store the pointer to the payload
- * @return Size of the payload, 0 on error
- */
-size_t
-GNUNET_SENSOR_crypto_verify_pow_sign (struct GNUNET_SENSOR_crypto_pow_block *
- block, int matching_bits,
- struct GNUNET_CRYPTO_EddsaPublicKey *
- public_key, void **payload)
-{
- /* Check public key */
- if (0 !=
- memcmp (public_key, &block->public_key,
- sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)))
- {
- LOG (GNUNET_ERROR_TYPE_WARNING, "Public key mismatch.\n");
- return 0;
- }
- /* Check signature */
- if (GNUNET_OK !=
- GNUNET_CRYPTO_eddsa_verify
- (GNUNET_SIGNATURE_PURPOSE_SENSOR_ANOMALY_REPORT, &block->purpose,
- &block->signature, public_key))
- {
- LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid signature.\n");
- return 0;
- }
- /* Check pow */
- if (GNUNET_NO ==
- check_pow (&block->timestamp,
- sizeof (struct GNUNET_TIME_Absolute) +
- sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) + block->msg_size,
- block->pow, matching_bits))
- {
- LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid proof-of-work.\n");
- return 0;
- }
- *payload = &block[1];
- return block->msg_size;
-}
+++ /dev/null
-[average-ping-rtt]
-
-VERSION = 1.0
-DESCRIPTION = Calculate average ping latency to gnunet.org
-CATEGORY = Underlay
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = process
-
-#GNUNET_STAT_SERVICE =
-#GNUNET_STAT_NAME =
-
-EXT_PROCESS = avgping.sh
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 7200
-REPORT_ANOMALIES = YES
+++ /dev/null
-#!/bin/sh
-
-ping -c 10 gnunet.org | awk -F/ '/^rtt/ { print $5 }'
+++ /dev/null
-[core-peers-connected]
-
-VERSION = 1.0
-DESCRIPTION = Gets the number of peers connected to core service
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = core
-GNUNET_STAT_NAME = # peers connected
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[datacache-bytes-stored]
-
-VERSION = 1.0
-DESCRIPTION = Bytes stored by GNUnet datacache service
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = datacache
-GNUNET_STAT_NAME = # bytes stored
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[dht-peers-connected]
-
-VERSION = 1.0
-DESCRIPTION = Gets the number of peers connected to dht service
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = dht
-GNUNET_STAT_NAME = # peers connected
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[fs-peers-connected]
-
-VERSION = 1.0
-DESCRIPTION = Gets the number of peers connected to fs service
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = fs
-GNUNET_STAT_NAME = # peers connected
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[gnunet-version]
-
-VERSION = 1.0
-DESCRIPTION = Gets gnunet version number
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 86400
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = process
-
-#GNUNET_STAT_SERVICE =
-#GNUNET_STAT_NAME =
-
-EXT_PROCESS = gnunet-arm
-EXT_ARGS = -v
-
-EXPECTED_DATATYPE = string
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[known-peers]
-
-VERSION = 1.0
-DESCRIPTION = Gets the number of known peers
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = peerinfo
-GNUNET_STAT_NAME = # peers known
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[nse]
-
-VERSION = 1.0
-DESCRIPTION = GNUnet network size estimate
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = nse
-GNUNET_STAT_NAME = # nodes in the network (estimate)
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[peerstore-memory]
-
-VERSION = 1.0
-DESCRIPTION = Memory consumption of GNUnet peerstore service
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = process
-
-#GNUNET_STAT_SERVICE =
-#GNUNET_STAT_NAME =
-
-EXT_PROCESS = peerstore-memory.sh
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-#!/bin/sh
-
-ps aux | grep 'gnunet-service-peerstore' | grep -v grep | awk '{ print $6 }'
+++ /dev/null
-[transport-bytes-received]
-
-VERSION = 1.0
-DESCRIPTION = Number of bytes received by GNUnet transport service
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = transport
-GNUNET_STAT_NAME = # bytes total received
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[transport-http-connections]
-
-VERSION = 1.0
-DESCRIPTION = Gets the number of transport HTTP connections
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = transport
-GNUNET_STAT_NAME = # HTTP client connections
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[transport-https-connections]
-
-VERSION = 1.0
-DESCRIPTION = Gets the number of transport HTTPS connections
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = transport
-GNUNET_STAT_NAME = # HTTPS client connections
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[transport-peers-connected]
-
-VERSION = 1.0
-DESCRIPTION = Gets the number of peers connected to transport service
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = transport
-GNUNET_STAT_NAME = # peers connected
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[transport-tcp-bytes-transmitted]
-
-VERSION = 1.0
-DESCRIPTION = Number of GNUnet transport TCP bytes transmitted
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = transport
-GNUNET_STAT_NAME = # bytes transmitted via TCP
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-[transport-tcp-sessions-active]
-
-VERSION = 1.0
-DESCRIPTION = Number of GNUnet transport service active TCP sessions
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = transport
-GNUNET_STAT_NAME = # TCP sessions active
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
- /*
- * This file is part of GNUnet.
- * Copyright (C)
- *
- * GNUnet is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published
- * by the Free Software Foundation; either version 3, or (at your
- * option) any later version.
- *
- * GNUnet is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GNUnet; see the file COPYING. If not, write to the
- * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-/**
- * @file sensor/test_gnunet-service-sensor_reporting.c
- * @brief testcase for gnunet-service-sensor_reporting.c
- */
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "gnunet_testbed_service.h"
-#include "gnunet_sensor_util_lib.h"
-#include "sensor.h"
-#include "gnunet_peerstore_service.h"
-#include "gnunet_sensor_service.h"
-
-/**
- * Number of peers to start for the test
- */
-#define NUM_PEERS 2
-
-/**
- * Test timeout
- */
-#define TEST_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
-
-/**
- * How long to wait between starting everything and forcing anomalies to give
- * the peer enough time to stabilize.
- */
-#define ANOMALY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
-
-/**
- * Information about a test peer
- */
-struct TestPeer
-{
-
- /**
- * DLL
- */
- struct TestPeer *prev;
-
- /**
- * DLL
- */
- struct TestPeer *next;
-
- /**
- * TESTBED information about the peer
- */
- struct GNUNET_TESTBED_Peer *testbed_peer;
-
- /**
- * Peer indentity
- */
- struct GNUNET_PeerIdentity peer_id;
-
- /**
- * Peerstore watch context for this peer's anomaly reports
- */
- struct GNUNET_PEERSTORE_WatchContext *wc;
-
- /**
- * TESTBED operation connecting us to sensor service
- */
- struct GNUNET_TESTBED_Operation *sensor_op;
-
- /**
- * Sensor service handle
- */
- struct GNUNET_SENSOR_Handle *sensor;
-
- /**
- * GNUNET scheduler task that forces the anomaly after a stabilization delay
- */
- struct GNUNET_SCHEDULER_Task * delay_task;
-
-};
-
-/**
- * Test name
- */
-static const char *testname = "test_gnunet-service-sensor_reporting";
-
-/**
- * Name of GNUNET config file used in this test
- */
-static const char *cfg_filename = "test_gnunet-service-sensor_reporting.conf";
-
-/**
- * Test sensor name
- */
-static const char *sensor_name = "test-sensor-statistics";
-
-/**
- * Path to read test sensor from
- */
-static const char *sensor_path_src = "test_sensors/test-sensor-statistics";
-
-/**
- * Path to write new test sensor to
- */
-static const char *sensor_path_dest =
- "/tmp/test-gnunet-service-sensor-reporting/test-sensor-statistics";
-
-/**
- * Head of DLL of peers
- */
-static struct TestPeer *peer_head;
-
-/**
- * Tail of DLL of peers
- */
-static struct TestPeer *peer_tail;
-
-/**
- * Number of peers started and got information for
- */
-static int started_peers = 0;
-
-/**
- * Number of peers reported anomalies with full list of anomalous neighbors
- */
-static int reported_peers = 0;
-
-/**
- * TESTBED operation connecting us to peerstore service
- */
-static struct GNUNET_TESTBED_Operation *peerstore_op;
-
-/**
- * Handle to the peerstore service
- */
-static struct GNUNET_PEERSTORE_Handle *peerstore;
-
-/**
- * Task used to shutdown / expire the test
- */
-static struct GNUNET_SCHEDULER_Task * shutdown_task;
-
-/**
- * Status of the test to be returned by main()
- */
-static int ok = 1;
-
-
-static void
-destroy_peer (struct TestPeer *peer)
-{
- if (NULL != peer->delay_task)
- {
- GNUNET_SCHEDULER_cancel (peer->delay_task);
- peer->delay_task = NULL;
- }
- if (NULL != peer->sensor_op)
- {
- GNUNET_TESTBED_operation_done (peer->sensor_op);
- peer->sensor_op = NULL;
- }
- if (NULL != peer->wc)
- {
- GNUNET_PEERSTORE_watch_cancel (peer->wc);
- peer->wc = NULL;
- }
- GNUNET_free (peer);
-}
-
-
-/**
- * Shutdown task
- *
- * @param cls Closure (unused)
- * @param tc Task context (unused)
- */
-static void
-do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct TestPeer *peer;
-
- peer = peer_head;
- while (NULL != peer)
- {
- GNUNET_CONTAINER_DLL_remove (peer_head, peer_tail, peer);
- destroy_peer (peer);
- peer = peer_head;
- }
- if (NULL != peerstore_op)
- {
- GNUNET_TESTBED_operation_done (peerstore_op);
- peerstore_op = NULL;
- }
- GNUNET_SCHEDULER_shutdown ();
-}
-
-
-/**
- * Write new temp sensor directory with a sensor updated with collection point
- * peer id
- */
-static void
-write_new_sensor_dir (struct TestPeer *cp_peer)
-{
- struct GNUNET_CONFIGURATION_Handle *sensorcfg;
-
- GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_test (sensor_path_src));
- sensorcfg = GNUNET_CONFIGURATION_create ();
- GNUNET_assert (GNUNET_SYSERR !=
- GNUNET_CONFIGURATION_parse (sensorcfg, sensor_path_src));
- GNUNET_CONFIGURATION_set_value_string (sensorcfg, sensor_name,
- "COLLECTION_POINT",
- GNUNET_i2s_full (&cp_peer->peer_id));
- GNUNET_assert (GNUNET_OK ==
- GNUNET_DISK_directory_create_for_file (sensor_path_dest));
- GNUNET_CONFIGURATION_write (sensorcfg, sensor_path_dest);
- GNUNET_CONFIGURATION_destroy (sensorcfg);
-}
-
-
-/**
- * Function called by PEERSTORE for each matching record.
- *
- * @param cls closure
- * @param record peerstore record information
- * @param emsg error message, or NULL if no errors
- * @return #GNUNET_YES to continue iterating, #GNUNET_NO to stop
- */
-static int
-peerstore_watch_cb (void *cls,
- const struct GNUNET_PEERSTORE_Record *record,
- const char *emsg)
-{
- struct TestPeer *peer = cls;
- struct GNUNET_SENSOR_DashboardAnomalyEntry *anomaly;
-
- GNUNET_assert (NULL != record);
- GNUNET_assert (record->value_size ==
- sizeof (struct GNUNET_SENSOR_DashboardAnomalyEntry));
- anomaly = record->value;
- GNUNET_assert (0 ==
- GNUNET_CRYPTO_cmp_peer_identity (&peer->peer_id,
- record->peer));
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Peerstore watch got an anomaly report from peer `%s':\n"
- "Anomalous: %d\n" "Anomalous neigbors: %f.\n",
- GNUNET_i2s (&peer->peer_id), anomaly->anomalous,
- anomaly->anomalous_neighbors);
- if (1 == anomaly->anomalous_neighbors)
- reported_peers++;
- if (reported_peers == NUM_PEERS)
- {
- ok = 0;
- GNUNET_SCHEDULER_cancel (shutdown_task);
- shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
- }
- return GNUNET_YES;
-}
-
-
-/**
- * Task that pushes fake anomalies to running peers
- */
-static void
-force_anomaly_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct TestPeer *peer = cls;
-
- peer->delay_task = NULL;
- GNUNET_SENSOR_force_anomaly (peer->sensor, (char *) sensor_name, GNUNET_YES,
- NULL, NULL);
-}
-
-
-/**
- * Callback to be called when sensor service connect operation is completed
- *
- * @param cls the callback closure from functions generating an operation
- * @param op the operation that has been finished
- * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
- * @param emsg error message in case the operation has failed; will be NULL if
- * operation has executed successfully.
- */
-static void
-sensor_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
- void *ca_result, const char *emsg)
-{
- struct TestPeer *peer = cls;
- struct GNUNET_SENSOR_Handle *sensor = ca_result;
-
- peer->sensor = sensor;
- peer->delay_task =
- GNUNET_SCHEDULER_add_delayed (ANOMALY_DELAY, &force_anomaly_task, peer);
-}
-
-
-/**
- * Adapter function called to establish a connection to sensor service.
- *
- * @param cls closure
- * @param cfg configuration of the peer to connect to; will be available until
- * GNUNET_TESTBED_operation_done() is called on the operation returned
- * from GNUNET_TESTBED_service_connect()
- * @return service handle to return in 'op_result', NULL on error
- */
-static void *
-sensor_connect_adapter (void *cls,
- const struct GNUNET_CONFIGURATION_Handle *cfg)
-{
- struct GNUNET_SENSOR_Handle *sensor;
-
- sensor = GNUNET_SENSOR_connect (cfg);
- return sensor;
-}
-
-
-/**
- * Adapter function called to destroy a connection to sensor service.
- *
- * @param cls closure
- * @param op_result service handle returned from the connect adapter
- */
-static void
-sensor_disconnect_adapter (void *cls, void *op_result)
-{
- struct GNUNET_SENSOR_Handle *sensor = op_result;
-
- GNUNET_SENSOR_disconnect (sensor);
-}
-
-
-/**
- * Callback to be called when sensor service is started
- *
- * @param cls the callback closure from functions generating an operation
- * @param op the operation that has been finished
- * @param emsg error message in case the operation has failed; will be NULL if
- * operation has executed successfully.
- */
-static void
-sensor_service_started (void *cls, struct GNUNET_TESTBED_Operation *op,
- const char *emsg)
-{
- struct TestPeer *peer = cls;
-
- if (NULL != emsg)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
- GNUNET_assert (0);
- }
- peer->sensor_op =
- GNUNET_TESTBED_service_connect (NULL, peer->testbed_peer, "sensor",
- &sensor_connect_cb, peer,
- &sensor_connect_adapter,
- &sensor_disconnect_adapter, NULL);
- GNUNET_TESTBED_operation_done (op);
-}
-
-
-/**
- * Callback to be called when peerstore service connect operation is completed
- *
- * @param cls the callback closure from functions generating an operation
- * @param op the operation that has been finished
- * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
- * @param emsg error message in case the operation has failed; will be NULL if
- * operation has executed successfully.
- */
-static void
-peerstore_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
- void *ca_result, const char *emsg)
-{
- struct TestPeer *peer;
-
- peer = peer_head;
- while (NULL != peer)
- {
- GNUNET_PEERSTORE_watch (peerstore, "sensordashboard-anomalies",
- &peer->peer_id, sensor_name, &peerstore_watch_cb,
- peer);
- /* Start sensor service */
- GNUNET_TESTBED_peer_manage_service (NULL, peer->testbed_peer, "sensor",
- &sensor_service_started, peer, 1);
- peer = peer->next;
- }
-}
-
-
-/**
- * Adapter function called to establish a connection to peerstore service.
- *
- * @param cls closure
- * @param cfg configuration of the peer to connect to; will be available until
- * GNUNET_TESTBED_operation_done() is called on the operation returned
- * from GNUNET_TESTBED_service_connect()
- * @return service handle to return in 'op_result', NULL on error
- */
-static void *
-peerstore_connect_adapter (void *cls,
- const struct GNUNET_CONFIGURATION_Handle *cfg)
-{
- peerstore = GNUNET_PEERSTORE_connect (cfg);
- GNUNET_assert (NULL != peerstore);
- return peerstore;
-}
-
-
-/**
- * Adapter function called to destroy a connection to peerstore service.
- *
- * @param cls closure
- * @param op_result service handle returned from the connect adapter
- */
-static void
-peerstore_disconnect_adapter (void *cls, void *op_result)
-{
- GNUNET_PEERSTORE_disconnect (peerstore, GNUNET_NO);
- peerstore = NULL;
- peerstore_op = NULL;
-}
-
-
-/**
- * Callback to be called when dashboard service is started
- *
- * @param cls the callback closure from functions generating an operation
- * @param op the operation that has been finished
- * @param emsg error message in case the operation has failed; will be NULL if
- * operation has executed successfully.
- */
-static void
-dashboard_started (void *cls, struct GNUNET_TESTBED_Operation *op,
- const char *emsg)
-{
- if (NULL != emsg)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
- GNUNET_assert (0);
- }
- GNUNET_TESTBED_operation_done (op);
- /* Connect to peerstore service on first peer */
- peerstore_op =
- GNUNET_TESTBED_service_connect (NULL, peer_head->testbed_peer,
- "peerstore", &peerstore_connect_cb, NULL,
- &peerstore_connect_adapter,
- &peerstore_disconnect_adapter, NULL);
-}
-
-
-/**
- * Callback to be called when the requested peer information is available
- *
- * @param cb_cls the closure from GNUNET_TETSBED_peer_get_information()
- * @param op the operation this callback corresponds to
- * @param pinfo the result; will be NULL if the operation has failed
- * @param emsg error message if the operation has failed; will be NULL if the
- * operation is successfull
- */
-static void
-peer_info_cb (void *cb_cls, struct GNUNET_TESTBED_Operation *op,
- const struct GNUNET_TESTBED_PeerInformation *pinfo,
- const char *emsg)
-{
- struct GNUNET_TESTBED_Peer *testbed_peer = cb_cls;
- struct TestPeer *peer;
-
- peer = GNUNET_new (struct TestPeer);
-
- peer->testbed_peer = testbed_peer;
- peer->delay_task = NULL;
- GNUNET_CRYPTO_get_peer_identity (pinfo->result.cfg, &peer->peer_id);
- if (NULL == peer_head) /* First peer (collection point) */
- {
- /* Rewrite sensor with collection point peer id */
- write_new_sensor_dir (peer);
- }
- GNUNET_CONTAINER_DLL_insert_tail (peer_head, peer_tail, peer);
- started_peers++;
- if (NUM_PEERS == started_peers)
- {
- /* Start dashboard service on first peer */
- GNUNET_TESTBED_peer_manage_service (NULL, peer_head->testbed_peer,
- "sensordashboard", &dashboard_started,
- NULL, 1);
- }
- GNUNET_TESTBED_operation_done (op);
-}
-
-
-/**
- * Signature of a main function for a testcase.
- *
- * @param cls closure
- * @param h the run handle
- * @param num_peers number of peers in 'peers'
- * @param peers handle to peers run in the testbed. NULL upon timeout (see
- * GNUNET_TESTBED_test_run()).
- * @param links_succeeded the number of overlay link connection attempts that
- * succeeded
- * @param links_failed the number of overlay link connection attempts that
- * failed
- * @see GNUNET_TESTBED_test_run()
- */
-static void
-test_master (void *cls, struct GNUNET_TESTBED_RunHandle *h,
- unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
- unsigned int links_succeeded, unsigned int links_failed)
-{
- int i;
-
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "%d peers started. %d links succeeded. %d links failed.\n",
- num_peers, links_succeeded, links_failed);
- GNUNET_assert (NUM_PEERS == num_peers);
- GNUNET_assert (0 == links_failed);
- /* Schedule test timeout */
- shutdown_task =
- GNUNET_SCHEDULER_add_delayed (TEST_TIMEOUT, &do_shutdown, NULL);
- /* Collect peer information */
- for (i = 0; i < num_peers; i++)
- {
- GNUNET_TESTBED_peer_get_information (peers[i],
- GNUNET_TESTBED_PIT_CONFIGURATION,
- &peer_info_cb, peers[i]);
- }
-}
-
-
-int
-main (int argc, char *argv[])
-{
- GNUNET_log_setup (testname, "INFO", NULL);
- if (GNUNET_OK ==
- GNUNET_TESTBED_test_run (testname, cfg_filename, NUM_PEERS, 0, NULL, NULL,
- &test_master, NULL))
- return ok;
- return 1;
-}
+++ /dev/null
-[testbed]
-OVERLAY_TOPOLOGY = CLIQUE
-
-[sensor]
-#PREFIX = valgrind --leak-check=full
-SENSOR_DIR = /tmp/test-gnunet-service-sensor-reporting/
-
-START_MONITORING = NO
-START_REPORTING = YES
-START_ANALYSIS = NO
-START_UPDATE = NO
-
-[sensor-reporting]
-POW_MATCHING_BITS = 2
-
-[transport]
-PLUGINS = unix
-
-[nat]
-USE_LOCALADDR = YES
+++ /dev/null
- /*
- * This file is part of GNUnet.
- * Copyright (C)
- *
- * GNUnet is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published
- * by the Free Software Foundation; either version 3, or (at your
- * option) any later version.
- *
- * GNUnet is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GNUnet; see the file COPYING. If not, write to the
- * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-/**
- * @file sensor/test_pow_sign.c
- * @brief testcase for proof-of-work and signature library functions
- */
-#include <inttypes.h>
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "gnunet_sensor_util_lib.h"
-#include "gnunet_testbed_service.h"
-#include "gnunet_signatures.h"
-
-/**
- * Number of peers to start for the test
- */
-#define NUM_PEERS 1
-
-/**
- * Size of the message exchanged
- */
-#define MSG_SIZE 1024
-
-/**
- * Number of matching bits to use for generating proof-of-work
- */
-#define MATCHING_BITS 5
-
-/**
- * Test timeout
- */
-#define TEST_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
-
-/**
- * Test name
- */
-static const char *testname = "test_pow_sign";
-
-/**
- * Name of GNUNET config file used in this test
- */
-static const char *cfg_filename = "test_pow_sign.conf";
-
-/**
- * Status of the test to be returned by main()
- */
-static int ok = 1;
-
-/**
- * Task used to shutdown / expire the test
- */
-static struct GNUNET_SCHEDULER_Task * shutdown_task;
-
-/**
- * Message to be exchanged
- */
-static char msg[MSG_SIZE];
-
-/**
- * Private key of sending peer
- */
-static struct GNUNET_CRYPTO_EddsaPrivateKey *private_key;
-
-/**
- * Public key of sending peer
- */
-static struct GNUNET_CRYPTO_EddsaPublicKey *public_key;
-
-
-/**
- * Shutdown task
- *
- * @param cls Closure (unused)
- * @param tc Task context (unused)
- */
-static void
-do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- if (NULL != private_key)
- {
- GNUNET_free (private_key);
- private_key = NULL;
- }
- if (NULL != public_key)
- {
- GNUNET_free (public_key);
- public_key = NULL;
- }
- GNUNET_SCHEDULER_shutdown ();
-}
-
-
-static void
-pow_cb (void *cls, struct GNUNET_SENSOR_crypto_pow_block *block)
-{
- void *response;
- struct GNUNET_TIME_Absolute end_time;
- struct GNUNET_TIME_Relative duration;
-
- end_time = GNUNET_TIME_absolute_get();
- duration = GNUNET_TIME_absolute_get_difference (block->timestamp, end_time);
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Received block:\n" "pow: %" PRIu64 ".\n", block->pow);
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Block generation toke %s.\n",
- GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_NO));
- /* Test that the block is valid */
- GNUNET_assert (MSG_SIZE ==
- GNUNET_SENSOR_crypto_verify_pow_sign (block, MATCHING_BITS,
- public_key, &response));
- GNUNET_assert (0 == memcmp (msg, response, MSG_SIZE));
- /* Modify the payload and test that verification returns invalid */
- block->pow++;
- GNUNET_assert (0 ==
- GNUNET_SENSOR_crypto_verify_pow_sign (block, MATCHING_BITS,
- public_key, &response));
- ok = 0;
- GNUNET_SCHEDULER_cancel (shutdown_task);
- GNUNET_SCHEDULER_add_now (do_shutdown, NULL);
-}
-
-
-/**
- * Callback to be called when the requested peer information is available
- *
- * @param cb_cls the closure from GNUNET_TETSBED_peer_get_information()
- * @param op the operation this callback corresponds to
- * @param pinfo the result; will be NULL if the operation has failed
- * @param emsg error message if the operation has failed; will be NULL if the
- * operation is successfull
- */
-static void
-peer_info_cb (void *cb_cls, struct GNUNET_TESTBED_Operation *op,
- const struct GNUNET_TESTBED_PeerInformation *pinfo,
- const char *emsg)
-{
- struct GNUNET_TIME_Absolute timestamp;
-
- /* generate random data block */
- GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, msg, MSG_SIZE);
- /* get private and public keys */
- private_key =
- GNUNET_CRYPTO_eddsa_key_create_from_configuration (pinfo->result.cfg);
- GNUNET_assert (NULL != private_key);
- public_key = GNUNET_new (struct GNUNET_CRYPTO_EddsaPublicKey);
-
- GNUNET_CRYPTO_eddsa_key_get_public (private_key, public_key);
- /* create pow and sign */
- timestamp = GNUNET_TIME_absolute_get ();
- GNUNET_SENSOR_crypto_pow_sign (msg, MSG_SIZE, ×tamp, public_key,
- private_key, MATCHING_BITS, &pow_cb, NULL);
- GNUNET_TESTBED_operation_done (op);
-}
-
-
-/**
- * Signature of a main function for a testcase.
- *
- * @param cls closure
- * @param h the run handle
- * @param num_peers number of peers in 'peers'
- * @param peers handle to peers run in the testbed. NULL upon timeout (see
- * GNUNET_TESTBED_test_run()).
- * @param links_succeeded the number of overlay link connection attempts that
- * succeeded
- * @param links_failed the number of overlay link connection attempts that
- * failed
- * @see GNUNET_TESTBED_test_run()
- */
-static void
-test_master (void *cls, struct GNUNET_TESTBED_RunHandle *h,
- unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
- unsigned int links_succeeded, unsigned int links_failed)
-{
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "%d peers started. %d links succeeded. %d links failed.\n",
- num_peers, links_succeeded, links_failed);
- GNUNET_assert (NUM_PEERS == num_peers);
- GNUNET_assert (0 == links_failed);
- /* Schedule test timeout */
- shutdown_task =
- GNUNET_SCHEDULER_add_delayed (TEST_TIMEOUT, &do_shutdown, NULL);
- GNUNET_TESTBED_peer_get_information (peers[0],
- GNUNET_TESTBED_PIT_CONFIGURATION,
- &peer_info_cb, peers[0]);
-}
-
-
-int
-main (int argc, char *argv[])
-{
- GNUNET_log_setup (testname, "INFO", NULL);
- if (GNUNET_OK ==
- GNUNET_TESTBED_test_run (testname, cfg_filename, NUM_PEERS, 0, NULL, NULL,
- &test_master, NULL))
- return ok;
- return 1;
-}
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C)
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-/**
- * @file sensor/test_sensor_api.c
- * @brief testcase for sensor_api.c
- */
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "gnunet_sensor_service.h"
-
-//FIXME:
-static int ok = 1;
-
-
-static void
-run (void *cls, char *const *args, const char *cfgfile,
- const struct GNUNET_CONFIGURATION_Handle *cfg)
-{
- ok = 0;
-}
-
-
-static int
-check ()
-{
- char *const argv[] = { "test-sensor-api", NULL };
- struct GNUNET_GETOPT_CommandLineOption options[] = {
- GNUNET_GETOPT_OPTION_END
- };
- struct GNUNET_OS_Process *proc;
- char *path = GNUNET_OS_get_libexec_binary_path ("gnunet-service-sensor");
-
- if (NULL == path)
- {
- fprintf (stderr, "Service executable not found `%s'\n",
- "gnunet-service-sensor");
- return -1;
- }
-
- proc =
- GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_ALL, NULL, NULL,
- NULL, path, "gnunet-service-sensor", NULL);
-
- GNUNET_free (path);
- GNUNET_assert (NULL != proc);
- GNUNET_PROGRAM_run (1, argv, "test-sensor-api", "nohelp", options, &run, &ok);
- if (0 != GNUNET_OS_process_kill (proc, SIGTERM))
- {
- GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
- ok = 1;
- }
- GNUNET_OS_process_wait (proc);
- GNUNET_OS_process_destroy (proc);
- return ok;
-}
-
-
-int
-main (int argc, char *argv[])
-{
- GNUNET_log_setup ("test_statistics_api", "WARNING", NULL);
- return check ();
-}
-
-/* end of test_sensor_api.c */
+++ /dev/null
-[test-sensor-statistics]
-
-VERSION = 1.0
-DESCRIPTION = Test sensor for collecting data from gnunet-statistics
-CATEGORY = GNUnet
-ENABLED = YES
-
-# Start and end time format: %Y-%m-%d %H:%M:%S
-#START_TIME =
-#END_TIME =
-#Interval in seconds
-INTERVAL = 60
-#LIFETIME =
-
-#CAPABILITIES =
-
-SOURCE = gnunet-statistics
-
-GNUNET_STAT_SERVICE = test-sensor
-GNUNET_STAT_NAME = test-statistic
-
-#EXT_PROCESS =
-#EXT_ARGS =
-
-EXPECTED_DATATYPE = numeric
-
-# Reporting:
-#COLLECTION_POINT = NCEKA096482PC84GFTG61EHAVXY3BQDTPB5FANATQD5CDADJ2HP0
-# Comment or remove next line to disable reporting sensor values to collection point
-#VALUE_COLLECTION_INTERVAL = 120
-REPORT_ANOMALIES = YES
+++ /dev/null
-# This Makefile.am is in the public domain
-AM_CPPFLAGS = -I$(top_srcdir)/src/include
-
-pkgcfgdir= $(pkgdatadir)/config.d/
-
-libexecdir= $(pkglibdir)/libexec/
-
-dist_pkgcfg_DATA = \
- sensordashboard.conf
-
-if MINGW
- WINFLAGS = -Wl,--no-undefined -Wl,--export-all-symbols
-endif
-
-if USE_COVERAGE
- AM_CFLAGS = -fprofile-arcs -ftest-coverage
-endif
-
-bin_PROGRAMS = \
- gnunet-sensordashboard
-
-libexec_PROGRAMS = \
- gnunet-service-sensordashboard
-
-gnunet_sensordashboard_SOURCES = \
- gnunet-sensordashboard.c
-gnunet_sensordashboard_LDADD = \
- $(top_builddir)/src/util/libgnunetutil.la \
- $(GN_LIBINTL)
-
-gnunet_service_sensordashboard_SOURCES = \
- gnunet-service-sensordashboard.c
-gnunet_service_sensordashboard_LDADD = \
- $(top_builddir)/src/util/libgnunetutil.la \
- $(top_builddir)/src/cadet/libgnunetcadet.la \
- $(top_builddir)/src/sensor/libgnunetsensorutil.la \
- $(top_builddir)/src/peerstore/libgnunetpeerstore.la \
- $(GN_LIBINTL)
-
-
-check_PROGRAMS = \
- test_sensordashboard_api
-
-if ENABLE_TEST_RUN
-AM_TESTS_ENVIRONMENT=export GNUNET_PREFIX=$${GNUNET_PREFIX:-@libdir@};export PATH=$${GNUNET_PREFIX:-@prefix@}/bin:$$PATH;
-TESTS = $(check_PROGRAMS)
-endif
-
-test_sensordashboard_api_SOURCES = \
- test_sensordashboard_api.c
-test_sensordashboard_api_LDADD = \
- $(top_builddir)/src/util/libgnunetutil.la
-
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C) 2001, 2002, 2004, 2005, 2006, 2007, 2009 GNUnet e.V.
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensordashboard/gnunet-sensordashboard.c
- * @brief sensor dashboard tool
- * @author Omar Tarabai
- */
-#include "platform.h"
-#include "gnunet_util_lib.h"
-
-/**
- * Final status code.
- */
-static int ret;
-
-/**
- * Main function that will be run by the scheduler.
- *
- * @param cls closure
- * @param args remaining command-line arguments
- * @param cfgfile name of the configuration file used (for saving, can be NULL!)
- * @param cfg configuration
- */
-static void
-run (void *cls, char *const *args, const char *cfgfile,
- const struct GNUNET_CONFIGURATION_Handle *cfg)
-{
- /* main code here */
-}
-
-
-/**
- * The main function.
- *
- * @param argc number of arguments from the command line
- * @param argv command line arguments
- * @return 0 ok, 1 on error
- */
-int
-main (int argc, char *const *argv)
-{
- static const struct GNUNET_GETOPT_CommandLineOption options[] = {
- /* FIMXE: add options here */
- GNUNET_GETOPT_OPTION_END
- };
- if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
- return 2;
-
- ret =
- (GNUNET_OK ==
- GNUNET_PROGRAM_run (argc, argv, "gnunet-sensordashboard",
- gettext_noop ("help text"), options, &run,
- NULL)) ? ret : 1;
- GNUNET_free ((void *) argv);
- return ret;
-}
-
-/* end of gnunet-sensordashboard.c */
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C) 2009 GNUnet e.V.
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/**
- * @file sensordashboard/gnunet-service-sensordashboard.c
- * @brief Service collecting sensor readings from peers
- * @author Omar Tarabai
- */
-#include <inttypes.h>
-#include "platform.h"
-#include "gnunet_util_lib.h"
-#include "gnunet_applications.h"
-#include "sensordashboard.h"
-#include "gnunet_cadet_service.h"
-#include "gnunet_sensor_util_lib.h"
-#include "gnunet_peerstore_service.h"
-
-
-/**
- * Context of a connected client peer
- */
-struct ClientPeerContext
-{
-
- /**
- * DLL
- */
- struct ClientPeerContext *prev;
-
- /*
- * DLL
- */
- struct ClientPeerContext *next;
-
- /**
- * GNUnet Peer identity
- */
- struct GNUNET_PeerIdentity peerid;
-
- /**
- * Handle to the cadet channel
- */
- struct GNUNET_CADET_Channel *ch;
-
- /**
- * CADET transmit handle if we requested a transmission
- */
- struct GNUNET_CADET_TransmitHandle *th;
-
- /**
- * Head of DLL of pending messages to be sent to client
- */
- struct PendingMessage *pm_head;
-
- /**
- * Tail of DLL of pending messages to be sent to client
- */
- struct PendingMessage *pm_tail;
-
- /**
- * Are we in the process of destroying this context?
- */
- int destroying;
-
-};
-
-/**
- * Message queued to be sent to a client stored in a DLL
- */
-struct PendingMessage
-{
-
- /**
- * DLL
- */
- struct PendingMessage *prev;
-
- /**
- * DLL
- */
- struct PendingMessage *next;
-
- /**
- * Actual queued message
- */
- struct GNUNET_MessageHeader *msg;
-
-};
-
-/**
- * Carries a single reading from a sensor
- */
-struct ClientSensorReading
-{
-
- /**
- * Sensor this reading is related to
- */
- struct GNUNET_SENSOR_SensorInfo *sensor;
-
- /**
- * Timestamp of taking the reading
- */
- struct GNUNET_TIME_Absolute timestamp;
-
- /**
- * Reading value
- */
- void *value;
-
- /**
- * Size of @e value
- */
- uint16_t value_size;
-
-};
-
-
-/**
- * Path to sensor definition directory
- */
-static char *sensor_dir;
-
-/**
- * Global hashmap of defined sensors
- */
-static struct GNUNET_CONTAINER_MultiHashMap *sensors;
-
-/**
- * Handle to CADET service
- */
-static struct GNUNET_CADET_Handle *cadet;
-
-/**
- * Handle to the peerstore service connection
- */
-static struct GNUNET_PEERSTORE_Handle *peerstore;
-
-/**
- * Name of the subsystem used to store sensor values received from remote peers
- * in PEERSTORE
- */
-static char *values_subsystem = "sensordashboard-values";
-
-/**
- * Name of the subsystem used to store anomaly reports received from remote
- * peers in PEERSTORE
- */
-static char *anomalies_subsystem = "sensordashboard-anomalies";
-
-/**
- * Head of a DLL of all connected client peers
- */
-static struct ClientPeerContext *cp_head;
-
-/**
- * Tail of a DLL of all connected client peers
- */
-static struct ClientPeerContext *cp_tail;
-
-/**
- * Parameter that defines the complexity of the proof-of-work
- */
-static long long unsigned int pow_matching_bits;
-
-
-/**
- * Trigger sending next pending message to the given client peer if any.
- *
- * @param cp client peer context struct
- */
-static void
-trigger_send_next_msg (struct ClientPeerContext *cp);
-
-
-/**
- * Destroy a given client peer context
- *
- * @param cp client peer context
- */
-static void
-destroy_clientpeer (struct ClientPeerContext *cp)
-{
- struct PendingMessage *pm;
-
- cp->destroying = GNUNET_YES;
- if (NULL != cp->th)
- {
- GNUNET_CADET_notify_transmit_ready_cancel (cp->th);
- cp->th = NULL;
- }
- pm = cp->pm_head;
- while (NULL != pm)
- {
- GNUNET_CONTAINER_DLL_remove (cp->pm_head, cp->pm_tail, pm);
- GNUNET_free (pm->msg);
- GNUNET_free (pm);
- pm = cp->pm_head;
- }
- if (NULL != cp->ch)
- {
- GNUNET_CADET_channel_destroy (cp->ch);
- cp->ch = NULL;
- }
- GNUNET_free (cp);
-}
-
-
-/**
- * Task run during shutdown.
- *
- * @param cls unused
- * @param tc unused
- */
-static void
-cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct ClientPeerContext *cp;
-
- cp = cp_head;
- while (NULL != cp)
- {
- GNUNET_CONTAINER_DLL_remove (cp_head, cp_tail, cp);
- destroy_clientpeer (cp);
- cp = cp_head;
- }
- if (NULL != cadet)
- {
- GNUNET_CADET_disconnect (cadet);
- cadet = NULL;
- }
- if (NULL != peerstore)
- {
- GNUNET_PEERSTORE_disconnect (peerstore, GNUNET_YES);
- peerstore = NULL;
- }
- GNUNET_SENSOR_destroy_sensors (sensors);
- if (NULL != sensor_dir)
- {
- GNUNET_free (sensor_dir);
- sensor_dir = NULL;
- }
- GNUNET_SCHEDULER_shutdown ();
-}
-
-
-/**
- * Function called whenever a channel is destroyed. Should clean up
- * any associated state.
- *
- * It must NOT call #GNUNET_CADET_channel_destroy on the channel.
- *
- * @param cls closure (set from #GNUNET_CADET_connect)
- * @param channel connection to the other end (henceforth invalid)
- * @param channel_ctx place where local state associated
- * with the channel is stored
- */
-static void
-cadet_channel_destroyed (void *cls, const struct GNUNET_CADET_Channel *channel,
- void *channel_ctx)
-{
- struct ClientPeerContext *cp = channel_ctx;
-
- if (GNUNET_YES == cp->destroying)
- return;
- cp->ch = NULL;
- GNUNET_CONTAINER_DLL_remove (cp_head, cp_tail, cp);
- destroy_clientpeer (cp);
-}
-
-
-/**
- * Method called whenever another peer has added us to a channel
- * the other peer initiated.
- * Only called (once) upon reception of data with a message type which was
- * subscribed to in #GNUNET_CADET_connect.
- *
- * A call to #GNUNET_CADET_channel_destroy causes the channel to be ignored. In
- * this case the handler MUST return NULL.
- *
- * @param cls closure
- * @param channel new handle to the channel
- * @param initiator peer that started the channel
- * @param port Port this channel is for.
- * @param options CadetOption flag field, with all active option bits set to 1.
- *
- * @return initial channel context for the channel
- * (can be NULL -- that's not an error)
- */
-static void *
-cadet_channel_created (void *cls, struct GNUNET_CADET_Channel *channel,
- const struct GNUNET_PeerIdentity *initiator,
- uint32_t port, enum GNUNET_CADET_ChannelOption options)
-{
- struct ClientPeerContext *cp;
-
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Received a channel connection from peer `%s'.\n",
- GNUNET_i2s (initiator));
- cp = GNUNET_new (struct ClientPeerContext);
-
- cp->peerid = *initiator;
- cp->ch = channel;
- cp->destroying = GNUNET_NO;
- GNUNET_CONTAINER_DLL_insert (cp_head, cp_tail, cp);
- return cp;
-}
-
-
-/**
- * Function called to notify a client about the connection begin ready
- * to queue more data. @a buf will be NULL and @a size zero if the
- * connection was closed for writing in the meantime.
- *
- * Perform the actual sending of the message to client peer.
- *
- * @param cls closure, a `struct ClientPeerContext *`
- * @param size number of bytes available in @a buf
- * @param buf where the callee should write the message
- * @return number of bytes written to @a buf
- */
-static size_t
-do_send_msg (void *cls, size_t size, void *buf)
-{
- struct ClientPeerContext *cp = cls;
- struct PendingMessage *pm;
- size_t msg_size;
-
- cp->th = NULL;
- pm = cp->pm_head;
- msg_size = ntohs (pm->msg->size);
- GNUNET_CONTAINER_DLL_remove (cp->pm_head, cp->pm_tail, pm);
- if (NULL == buf || size < msg_size)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
- _("Error trying to send a message to peer `%s'.\n"),
- GNUNET_i2s (&cp->peerid));
- return 0;
- }
- memcpy (buf, pm->msg, msg_size);
- GNUNET_free (pm->msg);
- GNUNET_free (pm);
- trigger_send_next_msg (cp);
- return msg_size;
-}
-
-
-/**
- * Trigger sending next pending message to the given client peer if any.
- *
- * @param cp client peer context struct
- */
-static void
-trigger_send_next_msg (struct ClientPeerContext *cp)
-{
- struct PendingMessage *pm;
-
- if (NULL == cp->pm_head)
- return;
- if (NULL != cp->th)
- return;
- pm = cp->pm_head;
- cp->th =
- GNUNET_CADET_notify_transmit_ready (cp->ch, GNUNET_YES,
- GNUNET_TIME_UNIT_FOREVER_REL,
- ntohs (pm->msg->size), &do_send_msg,
- cp);
-}
-
-
-/**
- * Add a new message to the queue to be sent to the given client peer.
- *
- * @param msg Message to be queued
- * @param cp Client peer context
- */
-static void
-queue_msg (struct GNUNET_MessageHeader *msg, struct ClientPeerContext *cp)
-{
- struct PendingMessage *pm;
-
- pm = GNUNET_new (struct PendingMessage);
-
- pm->msg = msg;
- GNUNET_CONTAINER_DLL_insert_tail (cp->pm_head, cp->pm_tail, pm);
- trigger_send_next_msg (cp);
-}
-
-
-/**
- * Called with any anomaly report received from a peer.
- *
- * Each time the function must call #GNUNET_CADET_receive_done on the channel
- * in order to receive the next message. This doesn't need to be immediate:
- * can be delayed if some processing is done on the message.
- *
- * @param cls Closure (set from #GNUNET_CADET_connect).
- * @param channel Connection to the other end.
- * @param channel_ctx Place to store local state associated with the channel.
- * @param message The actual message.
- * @return #GNUNET_OK to keep the channel open,
- * #GNUNET_SYSERR to close it (signal serious error).
- */
-static int
-handle_anomaly_report (void *cls, struct GNUNET_CADET_Channel *channel,
- void **channel_ctx,
- const struct GNUNET_MessageHeader *message)
-{
- struct ClientPeerContext *cp = *channel_ctx;
- struct GNUNET_SENSOR_crypto_pow_block *report_block;
- struct GNUNET_SENSOR_AnomalyReportMessage *anomaly_msg;
- struct GNUNET_SENSOR_SensorInfo *sensor;
- struct GNUNET_SENSOR_DashboardAnomalyEntry *anomaly_entry;
- struct GNUNET_TIME_Absolute expiry;
-
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Received an anomaly report message from peer `%s'.\n",
- GNUNET_i2s (&cp->peerid));
- report_block = (struct GNUNET_SENSOR_crypto_pow_block *) &message[1];
- if (sizeof (struct GNUNET_SENSOR_AnomalyReportMessage) !=
- GNUNET_SENSOR_crypto_verify_pow_sign (report_block, pow_matching_bits,
- &cp->peerid.public_key,
- (void **) &anomaly_msg))
- {
- GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
- "Received invalid anomaly report from peer `%s'.\n",
- GNUNET_i2s (&cp->peerid));
- GNUNET_break_op (0);
- return GNUNET_SYSERR;
- }
- sensor =
- GNUNET_CONTAINER_multihashmap_get (sensors,
- &anomaly_msg->sensorname_hash);
- if (NULL == sensor)
- {
- GNUNET_break_op (0);
- return GNUNET_SYSERR;
- }
- anomaly_entry = GNUNET_new (struct GNUNET_SENSOR_DashboardAnomalyEntry);
- anomaly_entry->anomalous = ntohs (anomaly_msg->anomalous);
- anomaly_entry->anomalous_neighbors = anomaly_msg->anomalous_neighbors;
- expiry =
- (GNUNET_YES ==
- anomaly_entry->anomalous) ? GNUNET_TIME_UNIT_FOREVER_ABS :
- GNUNET_TIME_absolute_get ();
- GNUNET_PEERSTORE_store (peerstore, anomalies_subsystem, &cp->peerid,
- sensor->name, anomaly_entry,
- sizeof (struct GNUNET_SENSOR_DashboardAnomalyEntry),
- expiry, GNUNET_PEERSTORE_STOREOPTION_REPLACE, NULL,
- NULL);
- GNUNET_free (anomaly_entry);
- GNUNET_CADET_receive_done (channel);
- return GNUNET_OK;
-}
-
-
-/**
- * Iterate over defined sensors, creates and sends brief sensor information to
- * given client peer over CADET.
- *
- * @param cls closure, the client peer
- * @param key sensor key
- * @param value sensor value
- * @return #GNUNET_YES to continue iteration
- */
-static int
-send_sensor_brief (void *cls, const struct GNUNET_HashCode *key, void *value)
-{
- struct ClientPeerContext *cp = cls;
- struct GNUNET_SENSOR_SensorInfo *sensor = value;
- struct GNUNET_SENSOR_SensorBriefMessage *msg;
- uint16_t sensorname_size;
- uint16_t total_size;
-
- /* Create message struct */
- sensorname_size = strlen (sensor->name) + 1;
- total_size =
- sizeof (struct GNUNET_SENSOR_SensorBriefMessage) + sensorname_size;
- msg = GNUNET_malloc (total_size);
- msg->header.size = htons (total_size);
- msg->header.type = htons (GNUNET_MESSAGE_TYPE_SENSOR_BRIEF);
- msg->name_size = htons (sensorname_size);
- msg->version_major = htons (sensor->version_major);
- msg->version_minor = htons (sensor->version_minor);
- memcpy (&msg[1], sensor->name, sensorname_size);
- /* Queue the msg */
- queue_msg ((struct GNUNET_MessageHeader *) msg, cp);
- return GNUNET_YES;
-}
-
-
-/**
- * Called with any sensor list request received.
- *
- * Each time the function must call #GNUNET_CADET_receive_done on the channel
- * in order to receive the next message. This doesn't need to be immediate:
- * can be delayed if some processing is done on the message.
- *
- * @param cls Closure (set from #GNUNET_CADET_connect).
- * @param channel Connection to the other end.
- * @param channel_ctx Place to store local state associated with the channel.
- * @param message The actual message.
- * @return #GNUNET_OK to keep the channel open,
- * #GNUNET_SYSERR to close it (signal serious error).
- */
-static int
-handle_sensor_list_req (void *cls, struct GNUNET_CADET_Channel *channel,
- void **channel_ctx,
- const struct GNUNET_MessageHeader *message)
-{
- struct ClientPeerContext *cp = *channel_ctx;
- struct GNUNET_MessageHeader *end_msg;
-
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Received a sensor list request from peer `%s'.\n",
- GNUNET_i2s (&cp->peerid));
- GNUNET_CONTAINER_multihashmap_iterate (sensors, &send_sensor_brief, cp);
- end_msg = GNUNET_new (struct GNUNET_MessageHeader);
-
- end_msg->size = htons (sizeof (struct GNUNET_MessageHeader));
- end_msg->type = htons (GNUNET_MESSAGE_TYPE_SENSOR_END);
- queue_msg (end_msg, cp);
- GNUNET_CADET_receive_done (channel);
- return GNUNET_OK;
-}
-
-
-/**
- * Parses a sensor reading message struct
- *
- * @param msg message header received
- * @param sensors multihashmap of loaded sensors
- * @return sensor reading struct or NULL if error
- */
-static struct ClientSensorReading *
-parse_reading_message (const struct GNUNET_MessageHeader *msg,
- struct GNUNET_CONTAINER_MultiHashMap *sensors)
-{
- uint16_t msg_size;
- uint16_t value_size;
- struct GNUNET_SENSOR_ValueMessage *vm;
- struct GNUNET_SENSOR_SensorInfo *sensor;
- struct ClientSensorReading *reading;
-
- msg_size = ntohs (msg->size);
- if (msg_size < sizeof (struct GNUNET_SENSOR_ValueMessage))
- {
- GNUNET_break_op (0);
- return NULL;
- }
- vm = (struct GNUNET_SENSOR_ValueMessage *) msg;
- value_size = ntohs (vm->value_size);
- if ((sizeof (struct GNUNET_SENSOR_ValueMessage) + value_size) != msg_size)
- {
- GNUNET_break_op (0);
- return NULL;
- }
- sensor = GNUNET_CONTAINER_multihashmap_get (sensors, &vm->sensorname_hash);
- if (NULL == sensor)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
- "Unknown sensor name in reading message.\n");
- return NULL;
- }
- if ((sensor->version_minor != ntohs (vm->sensorversion_minor)) ||
- (sensor->version_major != ntohs (vm->sensorversion_major)))
- {
- GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
- "Sensor version mismatch in reading message.\n");
- return NULL;
- }
- if (0 == strcmp (sensor->expected_datatype, "numeric") &&
- sizeof (double) != value_size)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
- "Invalid value size for a numerical sensor.\n");
- return NULL;
- }
- reading = GNUNET_new (struct ClientSensorReading);
- reading->sensor = sensor;
- reading->timestamp = vm->timestamp;
- reading->value_size = value_size;
- reading->value = GNUNET_memdup (&vm[1], value_size);
- return reading;
-}
-
-
-/**
- * Called with any sensor reading messages received from CADET.
- *
- * Each time the function must call #GNUNET_CADET_receive_done on the channel
- * in order to receive the next message. This doesn't need to be immediate:
- * can be delayed if some processing is done on the message.
- *
- * @param cls Closure (set from #GNUNET_CADET_connect).
- * @param channel Connection to the other end.
- * @param channel_ctx Place to store local state associated with the channel.
- * @param message The actual message.
- * @return #GNUNET_OK to keep the channel open,
- * #GNUNET_SYSERR to close it (signal serious error).
- */
-static int
-handle_sensor_reading (void *cls, struct GNUNET_CADET_Channel *channel,
- void **channel_ctx,
- const struct GNUNET_MessageHeader *message)
-{
- struct ClientPeerContext *cp = *channel_ctx;
- struct ClientSensorReading *reading;
-
- reading = parse_reading_message (message, sensors);
- if (NULL == reading)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
- "Received an invalid sensor reading from peer `%s'.\n",
- GNUNET_i2s (&cp->peerid));
- return GNUNET_SYSERR;
- }
- GNUNET_log (GNUNET_ERROR_TYPE_INFO,
- "Received a sensor reading from peer `%s':\n"
- "# Sensor name: `%s'\n" "# Timestamp: %" PRIu64 "\n"
- "# Value size: %" PRIu64 ".\n", GNUNET_i2s (&cp->peerid),
- reading->sensor->name, reading->timestamp, reading->value_size);
- GNUNET_PEERSTORE_store (peerstore, values_subsystem, &cp->peerid,
- reading->sensor->name, reading->value,
- reading->value_size, GNUNET_TIME_UNIT_FOREVER_ABS,
- GNUNET_PEERSTORE_STOREOPTION_MULTIPLE, NULL, NULL);
- GNUNET_free (reading->value);
- GNUNET_free (reading);
- GNUNET_CADET_receive_done (channel);
- return GNUNET_OK;
-}
-
-
-/**
- * Create a message with full information about sensor
- *
- * @param sensorname Name of sensor requested
- * @return Message ready to be sent to client or NULL on error
- */
-static struct GNUNET_SENSOR_SensorFullMessage *
-create_full_sensor_msg (char *sensorname)
-{
- struct GNUNET_HashCode key;
- struct GNUNET_SENSOR_SensorInfo *sensor;
- struct GNUNET_SENSOR_SensorFullMessage *msg;
- char *sensor_path;
- char *sensorscript_path;
- uint64_t sensorname_size;
- uint64_t sensorfile_size;
- uint64_t sensorscriptname_size;
- uint64_t sensorscript_size;
- uint64_t total_size;
- void *dummy;
-
- GNUNET_CRYPTO_hash (sensorname, strlen (sensorname) + 1, &key);
- sensor = GNUNET_CONTAINER_multihashmap_get (sensors, &key);
- if (NULL == sensor)
- return NULL;
- GNUNET_asprintf (&sensor_path,
- "%s%s",
- sensor_dir,
- sensorname);
- if (GNUNET_OK !=
- GNUNET_DISK_file_size (sensor_path,
- &sensorfile_size,
- GNUNET_NO,
- GNUNET_YES))
- {
- GNUNET_free (sensor_dir);
- GNUNET_free (sensor_path);
- return NULL;
- }
- sensorname_size = strlen (sensorname) + 1;
- sensorscript_path = NULL;
- sensorscript_size = 0;
- sensorscriptname_size = 0;
- /* Test if there is an associated script */
- if (NULL != sensor->ext_process)
- {
- GNUNET_asprintf (&sensorscript_path,
- "%s%s-files%s%s",
- sensor_dir,
- sensor->name,
- DIR_SEPARATOR_STR,
- sensor->ext_process);
- if (GNUNET_OK ==
- GNUNET_DISK_file_size (sensorscript_path,
- &sensorscript_size,
- GNUNET_NO,
- GNUNET_YES))
- sensorscriptname_size = strlen (sensor->ext_process) + 1;
- }
- /* Construct the msg */
- total_size =
- sizeof (struct GNUNET_SENSOR_SensorFullMessage) + sensorname_size +
- sensorfile_size + sensorscriptname_size + sensorscript_size;
- msg = GNUNET_malloc (total_size);
- msg->header.size = htons (total_size);
- msg->header.type = htons (GNUNET_MESSAGE_TYPE_SENSOR_FULL);
- msg->sensorname_size = htons (sensorname_size);
- msg->sensorfile_size = htons (sensorfile_size);
- msg->scriptname_size = htons (sensorscriptname_size);
- msg->scriptfile_size = htons (sensorscript_size);
- dummy = &msg[1];
- memcpy (dummy, sensorname, sensorname_size);
- dummy += sensorname_size;
- GNUNET_DISK_fn_read (sensor_path, dummy, sensorfile_size);
- dummy += sensorfile_size;
- if (sensorscriptname_size > 0)
- {
- memcpy (dummy, sensor->ext_process, sensorscriptname_size);
- dummy += sensorscriptname_size;
- GNUNET_DISK_fn_read (sensorscript_path, dummy, sensorscript_size);
- }
- GNUNET_free_non_null (sensorscript_path);
- GNUNET_free (sensor_path);
- return msg;
-}
-
-
-/**
- * Called with any request for full sensor information.
- *
- * Each time the function must call #GNUNET_CADET_receive_done on the channel
- * in order to receive the next message. This doesn't need to be immediate:
- * can be delayed if some processing is done on the message.
- *
- * @param cls Closure (set from #GNUNET_CADET_connect).
- * @param channel Connection to the other end.
- * @param channel_ctx Place to store local state associated with the channel.
- * @param message The actual message.
- * @return #GNUNET_OK to keep the channel open,
- * #GNUNET_SYSERR to close it (signal serious error).
- */
-static int
-handle_sensor_full_req (void *cls, struct GNUNET_CADET_Channel *channel,
- void **channel_ctx,
- const struct GNUNET_MessageHeader *message)
-{
- struct ClientPeerContext *cp = *channel_ctx;
- struct GNUNET_SENSOR_SensorBriefMessage *sbm = NULL;
- struct GNUNET_SENSOR_SensorFullMessage *sfm;
- uint16_t msg_size;
- uint16_t sensorname_size;
-
- msg_size = ntohs (message->size);
- /* parse & error check */
- if (msg_size > sizeof (struct GNUNET_SENSOR_SensorBriefMessage))
- {
- sbm = (struct GNUNET_SENSOR_SensorBriefMessage *) message;
- sensorname_size = ntohs (sbm->name_size);
- if (msg_size !=
- sizeof (struct GNUNET_SENSOR_SensorBriefMessage) + sensorname_size)
- sbm = NULL;
- }
- if (NULL == sbm)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
- "Received an invalid full sensor request from peer `%s'.\n",
- GNUNET_i2s (&cp->peerid));
- return GNUNET_SYSERR;
- }
- /* Create and send msg with full sensor info */
- sfm = create_full_sensor_msg ((char *) &sbm[1]);
- if (NULL == sfm)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
- "Error creating full sensor info msg for sensor `%s'.\n",
- (char *) &sbm[1]);
- return GNUNET_SYSERR;
- }
- queue_msg ((struct GNUNET_MessageHeader *) sfm, cp);
- GNUNET_CADET_receive_done (channel);
- return GNUNET_OK;
-}
-
-
-/**
- * Process sensordashboard requests.
- *
- * @param cls closure
- * @param server the initialized server
- * @param cfg configuration to use
- */
-static void
-run (void *cls, struct GNUNET_SERVER_Handle *server,
- const struct GNUNET_CONFIGURATION_Handle *cfg)
-{
- static const struct GNUNET_SERVER_MessageHandler handlers[] = {
- {NULL, NULL, 0, 0}
- };
- static struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
- {&handle_sensor_reading,
- GNUNET_MESSAGE_TYPE_SENSOR_READING, 0},
- {&handle_sensor_list_req,
- GNUNET_MESSAGE_TYPE_SENSOR_LIST_REQ,
- sizeof (struct GNUNET_MessageHeader)},
- {&handle_sensor_full_req,
- GNUNET_MESSAGE_TYPE_SENSOR_FULL_REQ,
- sizeof (struct GNUNET_MessageHeader)},
- {&handle_anomaly_report,
- GNUNET_MESSAGE_TYPE_SENSOR_ANOMALY_REPORT,
- sizeof (struct GNUNET_MessageHeader) +
- sizeof (struct GNUNET_SENSOR_crypto_pow_block) +
- sizeof (struct GNUNET_SENSOR_AnomalyReportMessage)},
- {NULL, 0, 0}
- };
- static uint32_t cadet_ports[] = {
- GNUNET_APPLICATION_TYPE_SENSORDASHBOARD,
- GNUNET_APPLICATION_TYPE_SENSORUPDATE,
- GNUNET_APPLICATION_TYPE_END
- };
-
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_filename (cfg, "SENSOR", "SENSOR_DIR",
- &sensor_dir))
- sensor_dir = GNUNET_SENSOR_get_default_sensor_dir ();
- sensors = GNUNET_SENSOR_load_all_sensors (sensor_dir);
- GNUNET_assert (NULL != sensors);
-
- if (GNUNET_OK !=
- GNUNET_CONFIGURATION_get_value_number (cfg, "sensor-reporting",
- "POW_MATCHING_BITS",
- &pow_matching_bits))
- {
- GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "sensor-reporting",
- "POW_MATCHING_BITS");
- GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
- return;
- }
- if (pow_matching_bits > sizeof (struct GNUNET_HashCode))
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
- "Matching bits value too large (%d > %d).\n", pow_matching_bits,
- sizeof (struct GNUNET_HashCode));
- GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
- return;
- }
-
- cadet =
- GNUNET_CADET_connect (cfg, NULL, &cadet_channel_created,
- &cadet_channel_destroyed, cadet_handlers,
- cadet_ports);
- if (NULL == cadet)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
- _("Failed to connect to `%s' service.\n"), "CADET");
- GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
- return;
- }
- peerstore = GNUNET_PEERSTORE_connect (cfg);
- if (NULL == peerstore)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
- _("Failed to connect to `%s' service.\n"), "PEERSTORE");
- GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
- return;
- }
- GNUNET_SERVER_add_handlers (server, handlers);
- GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
- NULL);
-}
-
-
-/**
- * The main function for the sensordashboard service.
- *
- * @param argc number of arguments from the command line
- * @param argv command line arguments
- * @return 0 ok, 1 on error
- */
-int
-main (int argc, char *const *argv)
-{
- return (GNUNET_OK ==
- GNUNET_SERVICE_run (argc, argv, "sensordashboard",
- GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
-}
-
-/* end of gnunet-service-sensordashboard.c */
+++ /dev/null
-[sensordashboard]
-AUTOSTART = @AUTOSTART@
-BINARY = gnunet-service-sensordashboard
-UNIXPATH = $GNUNET_RUNTIME_DIR/gnunet-service-sensordashboard.sock
-@UNIXONLY@ PORT = 2121
-UNIX_MATCH_UID = NO
-UNIX_MATCH_GID = YES
+++ /dev/null
-/*
- This file is part of GNUnet
- Copyright (C) 2012-2013 GNUnet e.V.
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
- */
-/**
- * @file sensordashboard/sensordashboard.h
- * @brief IPC messages and private service declarations
- * @author Omar Tarabai
- */
-
-#include "gnunet_sensordashboard_service.h"
-
-GNUNET_NETWORK_STRUCT_BEGIN GNUNET_NETWORK_STRUCT_END
+++ /dev/null
-/*
- This file is part of GNUnet.
- Copyright (C) 2009 GNUnet e.V.
-
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 3, or (at your
- option) any later version.
-
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-/**
- * @file template/test_template_api.c
- * @brief testcase for template.c
- */
-#include "platform.h"
-
-static int
-check ()
-{
- return 0;
-}
-
-int
-main (int argc, char *argv[])
-{
- int ret;
-
- ret = check ();
-
- return ret;
-}
-
-/* end of test_template_api.c */