- fixes
[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   return (contains) ? GNUNET_OK : GNUNET_SYSERR;
162 }
163
164
165 static int
166 get_identity (unsigned int offset, struct GNUNET_PeerIdentity *id)
167 {
168   struct GNUNET_CRYPTO_EddsaPrivateKey private_key;
169
170   if (offset >= num_hostkeys)
171     return GNUNET_SYSERR;
172   (void) memcpy (&private_key,
173                  hostkeys_data + (offset * GNUNET_TESTING_HOSTKEYFILESIZE),
174                  GNUNET_TESTING_HOSTKEYFILESIZE);
175   GNUNET_CRYPTO_eddsa_key_get_public (&private_key, &id->public_key);
176   return GNUNET_OK;
177 }
178
179
180 /**
181  * Whilelist entry
182  */
183 struct WhiteListRow
184 {
185   /**
186    * Next ptr
187    */
188   struct WhiteListRow *next;
189   
190   /**
191    * The offset where to find the hostkey for the peer
192    */
193   unsigned int id;
194   
195   /**
196    * Latency to be assigned to the link
197    */
198   int latency;
199
200 };
201
202
203 /**
204  * Function to load keys
205  */
206 static int
207 load_keys (const struct GNUNET_CONFIGURATION_Handle *c)
208 {
209   char *data_dir;
210   char *idfile;
211   uint64_t fsize;
212
213   data_dir = NULL;
214   idfile = NULL;
215   fsize = 0;
216   data_dir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
217   GNUNET_asprintf (&idfile, "%s/testing_hostkeys.ecc", data_dir);
218   GNUNET_free (data_dir);
219   data_dir = NULL;
220   if (GNUNET_OK !=
221       GNUNET_DISK_file_size (idfile, &fsize, GNUNET_YES, GNUNET_YES))
222   {
223     GNUNET_free (idfile);
224     return GNUNET_SYSERR;
225   }
226   if (0 != (fsize % GNUNET_TESTING_HOSTKEYFILESIZE))
227   {
228     LOG (GNUNET_ERROR_TYPE_ERROR,
229          _("Incorrect hostkey file format: %s\n"), idfile);
230     GNUNET_free (idfile);
231     return GNUNET_SYSERR;
232   }
233   hostkeys_fd = GNUNET_DISK_file_open (idfile, GNUNET_DISK_OPEN_READ,
234                                        GNUNET_DISK_PERM_NONE);
235   if (NULL == hostkeys_fd)
236   {
237     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", idfile);
238     GNUNET_free (idfile);
239     return GNUNET_SYSERR;
240   }
241   GNUNET_free (idfile);
242   idfile = NULL;
243   hostkeys_data = GNUNET_DISK_file_map (hostkeys_fd,
244                                         &hostkeys_map,
245                                         GNUNET_DISK_MAP_TYPE_READ,
246                                         fsize);
247   if (NULL == hostkeys_data)
248   {
249
250     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "mmap");
251     return GNUNET_SYSERR;
252   }
253   num_hostkeys = fsize / GNUNET_TESTING_HOSTKEYFILESIZE;
254   return GNUNET_OK;
255 }
256
257
258 /**
259  * Function to unload keys
260  */
261 static void
262 unload_keys ()
263 {
264   if (NULL != hostkeys_map)
265   {
266     GNUNET_assert (NULL != hostkeys_data);
267     GNUNET_DISK_file_unmap (hostkeys_map);
268     hostkeys_map = NULL;
269     hostkeys_data = NULL;
270   }
271   if (NULL != hostkeys_fd)
272   {
273     GNUNET_DISK_file_close (hostkeys_fd);
274     hostkeys_fd = NULL;
275   }
276 }
277
278
279 /**
280  * Shutdown task to cleanup our resources and exit.
281  *
282  * @param cls NULL
283  * @param tc scheduler task context
284  */
285 static void
286 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
287 {
288   if (NULL != transport)
289   {
290     GNUNET_TRANSPORT_disconnect (transport);
291     transport = NULL;
292   }
293   cleanup_map ();
294   unload_keys ();
295   if (NULL != bh)
296     GNUNET_TRANSPORT_blacklist_cancel (bh);
297 }
298
299
300 /**
301  * Function to read whitelist rows from the database
302  *
303  * @param db the database connection
304  * @param pid the identity of this peer
305  * @param wl_rows where to store the retrieved whitelist rows
306  * @return GNUNET_SYSERR upon error OR the number of rows retrieved
307  */
308 static int
309 db_read_whitelist (struct sqlite3 *db, int pid, struct WhiteListRow **wl_rows)
310 {
311   static const char *query_wl = "SELECT oid, latency FROM whitelist WHERE (id == ?);";
312   struct sqlite3_stmt *stmt_wl;
313   struct WhiteListRow *lr;
314   int nrows;
315   int ret;
316   
317   if (SQLITE_OK != (ret = sqlite3_prepare_v2 (db, query_wl, -1, &stmt_wl, NULL)))
318   {
319     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_prepare_v2");
320     return GNUNET_SYSERR;
321   }
322   if (SQLITE_OK != (ret = sqlite3_bind_int (stmt_wl, 1, pid)))
323   {
324     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_bind_int");
325     sqlite3_finalize (stmt_wl);
326     return GNUNET_SYSERR;
327   }
328   nrows = 0;
329   do
330   {
331     ret = sqlite3_step (stmt_wl);
332     if (SQLITE_ROW != ret)
333       break;
334     nrows++;
335     lr = GNUNET_new (struct WhiteListRow);
336     lr->id = sqlite3_column_int (stmt_wl, 0);
337     lr->latency = sqlite3_column_int (stmt_wl, 1);
338     lr->next = *wl_rows;
339     *wl_rows = lr;
340   } while (1);
341   sqlite3_finalize (stmt_wl);
342   return nrows;
343 }
344
345
346 /**
347  * Main function that will be run.
348  *
349  * @param cls closure
350  * @param args remaining command-line arguments
351  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
352  * @param c configuration
353  */
354 static void
355 run (void *cls, char *const *args, const char *cfgfile,
356      const struct GNUNET_CONFIGURATION_Handle *c)
357 {
358   char *dbfile;
359   struct WhiteListRow *wl_head;
360   struct WhiteListRow *wl_entry;
361   struct GNUNET_PeerIdentity identity;
362   struct GNUNET_ATS_Information params[1];
363   unsigned long long pid;
364   unsigned int nrows;
365   int ret;
366
367   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (c, "TESTBED",
368                                                             "PEERID", &pid))
369   {
370     GNUNET_break (0);
371     return;
372   }
373   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "TESTBED-UNDERLAY",
374                                                             "DBFILE",
375                                                             &dbfile))
376   {
377     GNUNET_break (0);
378     return;
379   }
380   if (SQLITE_OK != (ret = sqlite3_open_v2 (dbfile, &db, SQLITE_OPEN_READONLY, NULL)))
381   {
382     if (NULL != db)
383     {
384       LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_open_v2");
385       sqlite3_close (db);
386     }
387     else
388       LOG (GNUNET_ERROR_TYPE_ERROR, "Cannot open sqlite file %s\n", dbfile);
389     GNUNET_free (dbfile);
390     return;
391   }
392   DEBUG ("Opened database %s\n", dbfile);
393   GNUNET_free (dbfile);
394   dbfile = NULL;
395   wl_head = NULL;
396   if (GNUNET_OK != load_keys (c))
397       goto close_db;
398   
399   transport = GNUNET_TRANSPORT_connect (c, NULL, NULL, NULL, NULL, NULL);
400   if (NULL == transport)
401   {
402     GNUNET_break (0);
403     return;
404   }
405   /* read and process whitelist */
406   nrows = 0;
407   wl_head = NULL;
408   nrows = db_read_whitelist (db, pid, &wl_head);
409   if ((GNUNET_SYSERR == nrows) || (0 == nrows))
410   {
411     GNUNET_TRANSPORT_disconnect (transport);
412     goto close_db;
413   }
414   map = GNUNET_CONTAINER_multipeermap_create (nrows, GNUNET_NO);
415   params[0].type = GNUNET_ATS_QUALITY_NET_DELAY;
416   while (NULL != (wl_entry = wl_head))
417   {
418     wl_head = wl_entry->next;
419     params[0].value = wl_entry->latency;
420     GNUNET_assert (GNUNET_OK == get_identity (wl_entry->id, &identity));
421     GNUNET_break (GNUNET_OK ==
422                   GNUNET_CONTAINER_multipeermap_put (map, &identity, &identity,
423                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
424     DEBUG ("Setting %u ms latency to peer `%s'\n",
425            wl_entry->latency,
426            GNUNET_i2s (&identity));
427     GNUNET_TRANSPORT_set_traffic_metric (transport,
428                                          &identity,
429                                          GNUNET_YES,
430                                          GNUNET_YES, /* FIXME: Separate inbound, outboud metrics */
431                                          params, 1);
432     GNUNET_free (wl_entry);
433   }
434   bh = GNUNET_TRANSPORT_blacklist (c, &check_access, NULL);
435   shutdown_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
436                                                 &do_shutdown, NULL);
437
438  close_db:
439   GNUNET_break (SQLITE_OK == sqlite3_close (db));
440   return;
441 }
442
443
444 /**
445  * The main function.
446  *
447  * @param argc number of arguments from the command line
448  * @param argv command line arguments
449  * @return 0 ok, 1 on error
450  */
451 int
452 main (int argc, char *const *argv)
453 {
454   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
455     GNUNET_GETOPT_OPTION_END
456   };
457   int ret;
458
459   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
460     return 2;
461 #ifdef SQLITE_CONFIG_MMAP_SIZE
462   (void) sqlite3_config (SQLITE_CONFIG_MMAP_SIZE, 512000, 256000000);
463 #endif
464   ret =
465       (GNUNET_OK ==
466        GNUNET_PROGRAM_run (argc, argv, "gnunet-daemon-testbed-underlay",
467                            _
468                            ("Daemon to restrict underlay network in testbed deployments"),
469                            options, &run, NULL)) ? 0 : 1;
470   GNUNET_free ((void*) argv);
471   return ret;
472 }