-ensure stats queues do not grow too big
[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_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 /**
106  * @ingroup hashmap
107  * Iterator over hash map entries.
108  *
109  * @param cls closure
110  * @param key current key code
111  * @param value value in the hash map
112  * @return #GNUNET_YES if we should continue to
113  *         iterate,
114  *         #GNUNET_NO if not.
115  */
116 static int
117 iterator (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
118 {
119   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multipeermap_remove (map, key,
120                                                                      value));
121   return GNUNET_YES;
122 }
123
124
125 /**
126  * Cleaup and destroy the map
127  */
128 static void
129 cleanup_map ()
130 {
131   if (NULL != map)
132   {
133     GNUNET_assert (GNUNET_SYSERR != GNUNET_CONTAINER_multipeermap_iterate (map,
134                                                                            &iterator,
135                                                                            NULL));
136     GNUNET_CONTAINER_multipeermap_destroy (map);
137     map = NULL;
138   }
139 }
140
141
142 /**
143  * Function that decides if a connection is acceptable or not.
144  *
145  * @param cls closure
146  * @param pid peer to approve or disapproave
147  * @return GNUNET_OK if the connection is allowed, GNUNET_SYSERR if not
148  */
149 static int
150 check_access (void *cls, const struct GNUNET_PeerIdentity * pid)
151 {
152   int contains;
153
154   GNUNET_assert (NULL != map);
155   contains = GNUNET_CONTAINER_multipeermap_contains (map, pid);
156   if (GNUNET_YES == contains)
157   {
158     DEBUG ("Permitting `%s'\n", GNUNET_i2s (pid));
159     return GNUNET_OK;
160   }
161   DEBUG ("Not permitting `%s'\n", GNUNET_i2s (pid));
162   return GNUNET_SYSERR;
163 }
164
165
166 static int
167 get_identity (unsigned int offset, struct GNUNET_PeerIdentity *id)
168 {
169   struct GNUNET_CRYPTO_EddsaPrivateKey private_key;
170
171   if (offset >= num_hostkeys)
172     return GNUNET_SYSERR;
173   (void) memcpy (&private_key,
174                  hostkeys_data + (offset * GNUNET_TESTING_HOSTKEYFILESIZE),
175                  GNUNET_TESTING_HOSTKEYFILESIZE);
176   GNUNET_CRYPTO_eddsa_key_get_public (&private_key, &id->public_key);
177   return GNUNET_OK;
178 }
179
180
181 /**
182  * Whilelist entry
183  */
184 struct WhiteListRow
185 {
186   /**
187    * Next ptr
188    */
189   struct WhiteListRow *next;
190
191   /**
192    * The offset where to find the hostkey for the peer
193    */
194   unsigned int id;
195
196   /**
197    * Latency to be assigned to the link
198    */
199   int latency;
200
201 };
202
203
204 /**
205  * Function to load keys
206  */
207 static int
208 load_keys (const struct GNUNET_CONFIGURATION_Handle *c)
209 {
210   char *data_dir;
211   char *idfile;
212   uint64_t fsize;
213
214   data_dir = NULL;
215   idfile = NULL;
216   fsize = 0;
217   data_dir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
218   GNUNET_asprintf (&idfile, "%s/testing_hostkeys.ecc", data_dir);
219   GNUNET_free (data_dir);
220   data_dir = NULL;
221   if (GNUNET_OK !=
222       GNUNET_DISK_file_size (idfile, &fsize, GNUNET_YES, GNUNET_YES))
223   {
224     GNUNET_free (idfile);
225     return GNUNET_SYSERR;
226   }
227   if (0 != (fsize % GNUNET_TESTING_HOSTKEYFILESIZE))
228   {
229     LOG (GNUNET_ERROR_TYPE_ERROR,
230          _("Incorrect hostkey file format: %s\n"), idfile);
231     GNUNET_free (idfile);
232     return GNUNET_SYSERR;
233   }
234   hostkeys_fd = GNUNET_DISK_file_open (idfile, GNUNET_DISK_OPEN_READ,
235                                        GNUNET_DISK_PERM_NONE);
236   if (NULL == hostkeys_fd)
237   {
238     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", idfile);
239     GNUNET_free (idfile);
240     return GNUNET_SYSERR;
241   }
242   GNUNET_free (idfile);
243   idfile = NULL;
244   hostkeys_data = GNUNET_DISK_file_map (hostkeys_fd,
245                                         &hostkeys_map,
246                                         GNUNET_DISK_MAP_TYPE_READ,
247                                         fsize);
248   if (NULL == hostkeys_data)
249   {
250
251     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "mmap");
252     return GNUNET_SYSERR;
253   }
254   num_hostkeys = fsize / GNUNET_TESTING_HOSTKEYFILESIZE;
255   return GNUNET_OK;
256 }
257
258
259 /**
260  * Function to unload keys
261  */
262 static void
263 unload_keys ()
264 {
265   if (NULL != hostkeys_map)
266   {
267     GNUNET_assert (NULL != hostkeys_data);
268     GNUNET_DISK_file_unmap (hostkeys_map);
269     hostkeys_map = NULL;
270     hostkeys_data = NULL;
271   }
272   if (NULL != hostkeys_fd)
273   {
274     GNUNET_DISK_file_close (hostkeys_fd);
275     hostkeys_fd = NULL;
276   }
277 }
278
279
280 /**
281  * Shutdown task to cleanup our resources and exit.
282  *
283  * @param cls NULL
284  */
285 static void
286 do_shutdown (void *cls)
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_Properties prop;
363   struct GNUNET_TIME_Relative delay;
364   unsigned long long pid;
365   unsigned int nrows;
366   int ret;
367
368   if (GNUNET_OK !=
369       GNUNET_CONFIGURATION_get_value_number (c, "TESTBED",
370                                              "PEERID", &pid))
371   {
372     GNUNET_break (0);
373     return;
374   }
375   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "TESTBED-UNDERLAY",
376                                                             "DBFILE",
377                                                             &dbfile))
378   {
379     GNUNET_break (0);
380     return;
381   }
382   if (SQLITE_OK != (ret = sqlite3_open_v2 (dbfile, &db, SQLITE_OPEN_READONLY, NULL)))
383   {
384     if (NULL != db)
385     {
386       LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_open_v2");
387       GNUNET_break (SQLITE_OK == sqlite3_close (db));
388     }
389     else
390       LOG (GNUNET_ERROR_TYPE_ERROR, "Cannot open sqlite file %s\n", dbfile);
391     GNUNET_free (dbfile);
392     return;
393   }
394   DEBUG ("Opened database %s\n", dbfile);
395   GNUNET_free (dbfile);
396   dbfile = NULL;
397   wl_head = NULL;
398   if (GNUNET_OK != load_keys (c))
399       goto close_db;
400
401   transport = GNUNET_TRANSPORT_connect (c, NULL, NULL, NULL, NULL, NULL);
402   if (NULL == transport)
403   {
404     GNUNET_break (0);
405     return;
406   }
407   /* read and process whitelist */
408   nrows = 0;
409   wl_head = NULL;
410   nrows = db_read_whitelist (db, pid, &wl_head);
411   if ((GNUNET_SYSERR == nrows) || (0 == nrows))
412   {
413     GNUNET_TRANSPORT_disconnect (transport);
414     goto close_db;
415   }
416   map = GNUNET_CONTAINER_multipeermap_create (nrows, GNUNET_NO);
417   while (NULL != (wl_entry = wl_head))
418   {
419     wl_head = wl_entry->next;
420     delay.rel_value_us = wl_entry->latency;
421     memset (&prop, 0, sizeof (prop));
422     GNUNET_assert (GNUNET_OK == get_identity (wl_entry->id, &identity));
423     GNUNET_break (GNUNET_OK ==
424                   GNUNET_CONTAINER_multipeermap_put (map, &identity, &identity,
425                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
426     DEBUG ("Setting %u ms latency to peer `%s'\n",
427            wl_entry->latency,
428            GNUNET_i2s (&identity));
429     GNUNET_TRANSPORT_set_traffic_metric (transport,
430                                          &identity,
431                                          &prop,
432                                          delay,
433                                          delay);
434     GNUNET_free (wl_entry);
435   }
436   bh = GNUNET_TRANSPORT_blacklist (c, &check_access, NULL);
437   GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
438
439  close_db:
440   GNUNET_break (SQLITE_OK == sqlite3_close (db));
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, "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 }