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