-indentation
[oweals/gnunet.git] / src / testbed / gnunet-daemon-testbed-underlay.c
1 /*
2       This file is part of GNUnet
3       (C) 2008--2013 Christian Grothoff (and other contributing authors)
4
5       GNUnet is free software; you can redistribute it and/or modify
6       it under the terms of the GNU General Public License as published
7       by the Free Software Foundation; either version 3, or (at your
8       option) any later version.
9
10       GNUnet is distributed in the hope that it will be useful, but
11       WITHOUT ANY WARRANTY; without even the implied warranty of
12       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13       General Public License for more details.
14
15       You should have received a copy of the GNU General Public License
16       along with GNUnet; see the file COPYING.  If not, write to the
17       Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18       Boston, MA 02111-1307, USA.
19 */
20
21
22 /**
23  * @file testbed/gnunet-daemon-testbed-blacklist.c
24  * @brief daemon to restrict incoming connections from other peers at the
25  *          transport layer of a peer
26  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
27  */
28
29 #include "platform.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_transport_service.h"
32 #include "gnunet_ats_service.h"
33 #include "gnunet_testing_lib.h"
34 #include <sqlite3.h>
35
36 /**
37  * Logging shorthand
38  */
39 #define LOG(type,...)                           \
40   GNUNET_log (type, __VA_ARGS__)
41
42 /**
43  * Debug logging shorthand
44  */
45 #define DEBUG(...)                              \
46   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
47
48 /**
49  * Log an error message at log-level 'level' that indicates
50  * a failure of the command 'cmd' on file 'filename'
51  * with the message given by strerror(errno).
52  */
53 #define LOG_SQLITE(db, msg, level, cmd)                                 \
54   do {                                                                  \
55     GNUNET_log_from (level, "sqlite", _("`%s' failed at %s:%d with error: %s\n"), \
56                      cmd, __FILE__,__LINE__, sqlite3_errmsg(db));  \
57     if (msg != NULL)                                                    \
58       GNUNET_asprintf(msg, _("`%s' failed at %s:%u with error: %s"), cmd, \
59                       __FILE__, __LINE__, sqlite3_errmsg(db));     \
60   } while(0)
61
62
63 /**
64  * The map to store the peer identities to allow/deny
65  */
66 static struct GNUNET_CONTAINER_MultiPeerMap *map;
67
68 /**
69  * The database connection
70  */
71 static struct sqlite3 *db;
72
73 /**
74  * The blacklist handle we obtain from transport when we register ourselves for
75  * access control
76  */
77 struct GNUNET_TRANSPORT_Blacklist *bh;
78
79 /**
80  * The hostkeys file
81  */
82 struct GNUNET_DISK_FileHandle *hostkeys_fd;
83
84 /**
85  * The hostkeys map
86  */
87 static struct GNUNET_DISK_MapHandle *hostkeys_map;
88
89 /**
90  * The hostkeys data
91  */
92 static void *hostkeys_data;
93
94 /**
95  * Handle to the transport service.  This is used for setting link metrics
96  */
97 static struct GNUNET_TRANSPORT_Handle *transport;
98
99 /**
100  * The number of hostkeys in the hostkeys array
101  */
102 static unsigned int num_hostkeys;
103
104 /**
105  * Task for shutdown
106  */
107 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task;
108
109
110 /**
111  * @ingroup hashmap
112  * Iterator over hash map entries.
113  *
114  * @param cls closure
115  * @param key current key code
116  * @param value value in the hash map
117  * @return #GNUNET_YES if we should continue to
118  *         iterate,
119  *         #GNUNET_NO if not.
120  */
121 static int
122 iterator (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
123 {
124   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multipeermap_remove (map, key,
125                                                                      value));
126   return GNUNET_YES;
127 }
128
129
130 /**
131  * Cleaup and destroy the map
132  */
133 static void
134 cleanup_map ()
135 {
136   if (NULL != map)
137   {
138     GNUNET_assert (GNUNET_SYSERR != GNUNET_CONTAINER_multipeermap_iterate (map,
139                                                                            &iterator,
140                                                                            NULL));
141     GNUNET_CONTAINER_multipeermap_destroy (map);
142     map = NULL;
143   }
144 }
145
146
147 /**
148  * Function that decides if a connection is acceptable or not.
149  *
150  * @param cls closure
151  * @param pid peer to approve or disapproave
152  * @return GNUNET_OK if the connection is allowed, GNUNET_SYSERR if not
153  */
154 static int
155 check_access (void *cls, const struct GNUNET_PeerIdentity * pid)
156 {
157   int contains;
158
159   GNUNET_assert (NULL != map);
160   contains = GNUNET_CONTAINER_multipeermap_contains (map, pid);
161   if (GNUNET_YES == contains)
162   {
163     DEBUG ("Permitting `%s'\n", GNUNET_i2s (pid));
164     return GNUNET_OK;
165   }
166   DEBUG ("Not permitting `%s'\n", GNUNET_i2s (pid));
167   return GNUNET_SYSERR;
168 }
169
170
171 static int
172 get_identity (unsigned int offset, struct GNUNET_PeerIdentity *id)
173 {
174   struct GNUNET_CRYPTO_EddsaPrivateKey private_key;
175
176   if (offset >= num_hostkeys)
177     return GNUNET_SYSERR;
178   (void) memcpy (&private_key,
179                  hostkeys_data + (offset * GNUNET_TESTING_HOSTKEYFILESIZE),
180                  GNUNET_TESTING_HOSTKEYFILESIZE);
181   GNUNET_CRYPTO_eddsa_key_get_public (&private_key, &id->public_key);
182   return GNUNET_OK;
183 }
184
185
186 /**
187  * Whilelist entry
188  */
189 struct WhiteListRow
190 {
191   /**
192    * Next ptr
193    */
194   struct WhiteListRow *next;
195   
196   /**
197    * The offset where to find the hostkey for the peer
198    */
199   unsigned int id;
200   
201   /**
202    * Latency to be assigned to the link
203    */
204   int latency;
205
206 };
207
208
209 /**
210  * Function to load keys
211  */
212 static int
213 load_keys (const struct GNUNET_CONFIGURATION_Handle *c)
214 {
215   char *data_dir;
216   char *idfile;
217   uint64_t fsize;
218
219   data_dir = NULL;
220   idfile = NULL;
221   fsize = 0;
222   data_dir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
223   GNUNET_asprintf (&idfile, "%s/testing_hostkeys.ecc", data_dir);
224   GNUNET_free (data_dir);
225   data_dir = NULL;
226   if (GNUNET_OK !=
227       GNUNET_DISK_file_size (idfile, &fsize, GNUNET_YES, GNUNET_YES))
228   {
229     GNUNET_free (idfile);
230     return GNUNET_SYSERR;
231   }
232   if (0 != (fsize % GNUNET_TESTING_HOSTKEYFILESIZE))
233   {
234     LOG (GNUNET_ERROR_TYPE_ERROR,
235          _("Incorrect hostkey file format: %s\n"), idfile);
236     GNUNET_free (idfile);
237     return GNUNET_SYSERR;
238   }
239   hostkeys_fd = GNUNET_DISK_file_open (idfile, GNUNET_DISK_OPEN_READ,
240                                        GNUNET_DISK_PERM_NONE);
241   if (NULL == hostkeys_fd)
242   {
243     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", idfile);
244     GNUNET_free (idfile);
245     return GNUNET_SYSERR;
246   }
247   GNUNET_free (idfile);
248   idfile = NULL;
249   hostkeys_data = GNUNET_DISK_file_map (hostkeys_fd,
250                                         &hostkeys_map,
251                                         GNUNET_DISK_MAP_TYPE_READ,
252                                         fsize);
253   if (NULL == hostkeys_data)
254   {
255
256     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "mmap");
257     return GNUNET_SYSERR;
258   }
259   num_hostkeys = fsize / GNUNET_TESTING_HOSTKEYFILESIZE;
260   return GNUNET_OK;
261 }
262
263
264 /**
265  * Function to unload keys
266  */
267 static void
268 unload_keys ()
269 {
270   if (NULL != hostkeys_map)
271   {
272     GNUNET_assert (NULL != hostkeys_data);
273     GNUNET_DISK_file_unmap (hostkeys_map);
274     hostkeys_map = NULL;
275     hostkeys_data = NULL;
276   }
277   if (NULL != hostkeys_fd)
278   {
279     GNUNET_DISK_file_close (hostkeys_fd);
280     hostkeys_fd = NULL;
281   }
282 }
283
284
285 /**
286  * Shutdown task to cleanup our resources and exit.
287  *
288  * @param cls NULL
289  * @param tc scheduler task context
290  */
291 static void
292 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
293 {
294   if (NULL != transport)
295   {
296     GNUNET_TRANSPORT_disconnect (transport);
297     transport = NULL;
298   }
299   cleanup_map ();
300   unload_keys ();
301   if (NULL != bh)
302     GNUNET_TRANSPORT_blacklist_cancel (bh);
303 }
304
305
306 /**
307  * Function to read whitelist rows from the database
308  *
309  * @param db the database connection
310  * @param pid the identity of this peer
311  * @param wl_rows where to store the retrieved whitelist rows
312  * @return GNUNET_SYSERR upon error OR the number of rows retrieved
313  */
314 static int
315 db_read_whitelist (struct sqlite3 *db, int pid, struct WhiteListRow **wl_rows)
316 {
317   static const char *query_wl = "SELECT oid, latency FROM whitelist WHERE (id == ?);";
318   struct sqlite3_stmt *stmt_wl;
319   struct WhiteListRow *lr;
320   int nrows;
321   int ret;
322   
323   if (SQLITE_OK != (ret = sqlite3_prepare_v2 (db, query_wl, -1, &stmt_wl, NULL)))
324   {
325     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_prepare_v2");
326     return GNUNET_SYSERR;
327   }
328   if (SQLITE_OK != (ret = sqlite3_bind_int (stmt_wl, 1, pid)))
329   {
330     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_bind_int");
331     sqlite3_finalize (stmt_wl);
332     return GNUNET_SYSERR;
333   }
334   nrows = 0;
335   do
336   {
337     ret = sqlite3_step (stmt_wl);
338     if (SQLITE_ROW != ret)
339       break;
340     nrows++;
341     lr = GNUNET_new (struct WhiteListRow);
342     lr->id = sqlite3_column_int (stmt_wl, 0);
343     lr->latency = sqlite3_column_int (stmt_wl, 1);
344     lr->next = *wl_rows;
345     *wl_rows = lr;
346   } while (1);
347   sqlite3_finalize (stmt_wl);
348   return nrows;
349 }
350
351
352 /**
353  * Main function that will be run.
354  *
355  * @param cls closure
356  * @param args remaining command-line arguments
357  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
358  * @param c configuration
359  */
360 static void
361 run (void *cls, char *const *args, const char *cfgfile,
362      const struct GNUNET_CONFIGURATION_Handle *c)
363 {
364   char *dbfile;
365   struct WhiteListRow *wl_head;
366   struct WhiteListRow *wl_entry;
367   struct GNUNET_PeerIdentity identity;
368   struct GNUNET_ATS_Information params[1];
369   unsigned long long pid;
370   unsigned int nrows;
371   int ret;
372
373   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (c, "TESTBED",
374                                                             "PEERID", &pid))
375   {
376     GNUNET_break (0);
377     return;
378   }
379   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "TESTBED-UNDERLAY",
380                                                             "DBFILE",
381                                                             &dbfile))
382   {
383     GNUNET_break (0);
384     return;
385   }
386   if (SQLITE_OK != (ret = sqlite3_open_v2 (dbfile, &db, SQLITE_OPEN_READONLY, NULL)))
387   {
388     if (NULL != db)
389     {
390       LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_open_v2");
391       sqlite3_close (db);
392     }
393     else
394       LOG (GNUNET_ERROR_TYPE_ERROR, "Cannot open sqlite file %s\n", dbfile);
395     GNUNET_free (dbfile);
396     return;
397   }
398   DEBUG ("Opened database %s\n", dbfile);
399   GNUNET_free (dbfile);
400   dbfile = NULL;
401   wl_head = NULL;
402   if (GNUNET_OK != load_keys (c))
403       goto close_db;
404   
405   transport = GNUNET_TRANSPORT_connect (c, NULL, NULL, NULL, NULL, NULL);
406   if (NULL == transport)
407   {
408     GNUNET_break (0);
409     return;
410   }
411   /* read and process whitelist */
412   nrows = 0;
413   wl_head = NULL;
414   nrows = db_read_whitelist (db, pid, &wl_head);
415   if ((GNUNET_SYSERR == nrows) || (0 == nrows))
416   {
417     GNUNET_TRANSPORT_disconnect (transport);
418     goto close_db;
419   }
420   map = GNUNET_CONTAINER_multipeermap_create (nrows, GNUNET_NO);
421   params[0].type = GNUNET_ATS_QUALITY_NET_DELAY;
422   while (NULL != (wl_entry = wl_head))
423   {
424     wl_head = wl_entry->next;
425     params[0].value = wl_entry->latency;
426     GNUNET_assert (GNUNET_OK == get_identity (wl_entry->id, &identity));
427     GNUNET_break (GNUNET_OK ==
428                   GNUNET_CONTAINER_multipeermap_put (map, &identity, &identity,
429                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
430     DEBUG ("Setting %u ms latency to peer `%s'\n",
431            wl_entry->latency,
432            GNUNET_i2s (&identity));
433     GNUNET_TRANSPORT_set_traffic_metric (transport,
434                                          &identity,
435                                          GNUNET_YES,
436                                          GNUNET_YES, /* FIXME: Separate inbound, outboud metrics */
437                                          params, 1);
438     GNUNET_free (wl_entry);
439   }
440   bh = GNUNET_TRANSPORT_blacklist (c, &check_access, NULL);
441   shutdown_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
442                                                 &do_shutdown, NULL);
443
444  close_db:
445   GNUNET_break (SQLITE_OK == sqlite3_close (db));
446   return;
447 }
448
449
450 /**
451  * The main function.
452  *
453  * @param argc number of arguments from the command line
454  * @param argv command line arguments
455  * @return 0 ok, 1 on error
456  */
457 int
458 main (int argc, char *const *argv)
459 {
460   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
461     GNUNET_GETOPT_OPTION_END
462   };
463   int ret;
464
465   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
466     return 2;
467 #ifdef SQLITE_CONFIG_MMAP_SIZE
468   (void) sqlite3_config (SQLITE_CONFIG_MMAP_SIZE, 512000, 256000000);
469 #endif
470   ret =
471       (GNUNET_OK ==
472        GNUNET_PROGRAM_run (argc, argv, "testbed-underlay",
473                            _
474                            ("Daemon to restrict underlay network in testbed deployments"),
475                            options, &run, NULL)) ? 0 : 1;
476   GNUNET_free ((void*) argv);
477   return ret;
478 }