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