aboutsummaryrefslogtreecommitdiff
path: root/src/testbed/gnunet-daemon-testbed-underlay.c
blob: d430b7fd169c02eb24cca60b7041c76aac238760 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
/*
      This file is part of GNUnet
      (C) 2008--2013 Christian Grothoff (and other contributing authors)

      GNUnet is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
      by the Free Software Foundation; either version 3, or (at your
      option) any later version.

      GNUnet is distributed in the hope that it will be useful, but
      WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with GNUnet; see the file COPYING.  If not, write to the
      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
      Boston, MA 02111-1307, USA.
*/


/**
 * @file testbed/gnunet-daemon-testbed-blacklist.c
 * @brief daemon to restrict incoming connections from other peers at the
 *          transport layer of a peer
 * @author Sree Harsha Totakura <sreeharsha@totakura.in>
 */

#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_transport_service.h"
#include "gnunet_ats_service.h"
#include "gnunet_testing_lib.h"
#include <sqlite3.h>

/**
 * Logging shorthand
 */
#define LOG(type,...)                           \
  GNUNET_log (type, __VA_ARGS__)

/**
 * Debug logging shorthand
 */
#define DEBUG(...)                              \
  LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)

/**
 * Log an error message at log-level 'level' that indicates
 * a failure of the command 'cmd' on file 'filename'
 * with the message given by strerror(errno).
 */
#define LOG_SQLITE(db, msg, level, cmd)                                 \
  do {                                                                  \
    GNUNET_log_from (level, "sqlite", _("`%s' failed at %s:%d with error: %s\n"), \
                     cmd, __FILE__,__LINE__, sqlite3_errmsg(db));  \
    if (msg != NULL)                                                    \
      GNUNET_asprintf(msg, _("`%s' failed at %s:%u with error: %s"), cmd, \
                      __FILE__, __LINE__, sqlite3_errmsg(db));     \
  } while(0)


/**
 * Allow access from the peers read from the whitelist
 */
#define ACCESS_ALLOW 1

/**
 * Deny access from the peers read from the blacklist
 */
#define ACCESS_DENY 0

/**
 * The map to store the peer identities to allow/deny
 */
static struct GNUNET_CONTAINER_MultiPeerMap *map;


/**
 * The map to store the peer identities to allow/deny
 */
static struct GNUNET_CONTAINER_MultiPeerMap *blacklist_map;

/**
 * The database connection
 */
static struct sqlite3 *db;

/**
 * The blacklist handle we obtain from transport when we register ourselves for
 * access control
 */
struct GNUNET_TRANSPORT_Blacklist *bh;

/**
 * The peer ID map
 */
static struct GNUNET_DISK_MapHandle *idmap;

/**
 * The hostkeys data
 */
static char *hostkeys_data;

/**
 * Handle to the transport service.  This is used for setting link metrics
 */
static struct GNUNET_TRANSPORT_Handle *transport;

/**
 * The number of hostkeys in the hostkeys array
 */
static unsigned int num_hostkeys;

/**
 * Task for shutdown
 */
static GNUNET_SCHEDULER_TaskIdentifier shutdown_task;

/**
 * Are we allowing or denying access from peers
 */
static int mode;


/**
 * @ingroup hashmap
 * Iterator over hash map entries.
 *
 * @param cls closure
 * @param key current key code
 * @param value value in the hash map
 * @return #GNUNET_YES if we should continue to
 *         iterate,
 *         #GNUNET_NO if not.
 */
static int
iterator (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
{
  GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multipeermap_remove (map, key,
                                                                     value));
  return GNUNET_YES;
}


/**
 * Cleaup and destroy the map
 */
static void
cleanup_map ()
{
  if (NULL != map)
  {
    GNUNET_assert (GNUNET_SYSERR != GNUNET_CONTAINER_multipeermap_iterate (map,
                                                                           &iterator,
                                                                           NULL));
    GNUNET_CONTAINER_multipeermap_destroy (map);
    map = NULL;
  }
}


/**
 * Shutdown task to cleanup our resources and exit.
 *
 * @param cls NULL
 * @param tc scheduler task context
 */
static void
do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  cleanup_map ();
  if (NULL != bh)
    GNUNET_TRANSPORT_blacklist_cancel (bh);
}


/**
 * Function that decides if a connection is acceptable or not.
 *
 * @param cls closure
 * @param pid peer to approve or disapproave
 * @return GNUNET_OK if the connection is allowed, GNUNET_SYSERR if not
 */
static int
check_access (void *cls, const struct GNUNET_PeerIdentity * pid)
{
  int contains;

  if (NULL != map)
    contains = GNUNET_CONTAINER_multipeermap_contains (map, pid);
  else
    contains = GNUNET_NO;
  if (ACCESS_DENY == mode)
    return (contains) ? GNUNET_SYSERR : GNUNET_OK;
  return (contains) ? GNUNET_OK : GNUNET_SYSERR;
}


static int
get_identity (unsigned int offset, struct GNUNET_PeerIdentity *id)
{
  struct GNUNET_CRYPTO_EddsaPrivateKey private_key;

  if (offset >= num_hostkeys)
    return GNUNET_SYSERR;
  (void) memcpy (&private_key,
                 hostkeys_data + (offset * GNUNET_TESTING_HOSTKEYFILESIZE),
                 GNUNET_TESTING_HOSTKEYFILESIZE);
  GNUNET_CRYPTO_eddsa_key_get_public (&private_key, &id->public_key);
  return GNUNET_OK;
}


/**
 * Function to blacklist a peer
 *
 * @param offset the offset where to find the peer's hostkey in the array of hostkeys
 */
static void
blacklist_peer (unsigned int offset)
{
  struct GNUNET_PeerIdentity id;

  GNUNET_assert (offset < num_hostkeys);
  GNUNET_assert (GNUNET_OK == get_identity (offset, &id));
  GNUNET_break (GNUNET_OK ==
                GNUNET_CONTAINER_multipeermap_put (map, &id, &id,
                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));

}

/**
 * Blacklist peer
 */
struct BlackListRow
{
  /**
   * Next ptr
   */
  struct BlackListRow *next;

  /**
   * The offset where to find the hostkey for the peer
   */
  unsigned int id;
};


/**
 * Whilelist entry
 */
struct WhiteListRow
{
  /**
   * Next ptr
   */
  struct WhiteListRow *next;
  
  /**
   * The offset where to find the hostkey for the peer
   */
  unsigned int id;
  
  /**
   * Bandwidth to be assigned to the link
   */
  int bandwidth;

  /**
   * Latency to be assigned to the link
   */
  int latency;

  /**
   * Loss to be assigned to the link
   */
  int loss;
};


/**
 * Function to load keys
 */
static int
load_keys (const struct GNUNET_CONFIGURATION_Handle *c)
{
  char *data_dir;
  char *idfile;
  struct GNUNET_DISK_FileHandle *fd;
  uint64_t fsize;

  data_dir = NULL;
  idfile = NULL;
  fd = NULL;
  fsize = 0;
  data_dir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
  GNUNET_asprintf (&idfile, "%s/testing_hostkeys.ecc", data_dir);
  GNUNET_free (data_dir);
  data_dir = NULL;
  if (GNUNET_OK !=
      GNUNET_DISK_file_size (idfile, &fsize, GNUNET_YES, GNUNET_YES))
  {
    GNUNET_free (idfile);
    return GNUNET_SYSERR;
  }
  if (0 != (fsize % GNUNET_TESTING_HOSTKEYFILESIZE))
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         _("Incorrect hostkey file format: %s\n"), idfile);
    GNUNET_free (idfile);
    return GNUNET_SYSERR;
  }
  fd = GNUNET_DISK_file_open (idfile, GNUNET_DISK_OPEN_READ,
                              GNUNET_DISK_PERM_NONE);
  if (NULL == fd)
  {
    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", idfile);
    GNUNET_free (idfile);
    return GNUNET_SYSERR;
  }
  GNUNET_free (idfile);
  idfile = NULL;
  hostkeys_data = GNUNET_DISK_file_map (fd,
                                        &idmap,
                                        GNUNET_DISK_MAP_TYPE_READ,
                                        fsize);
  if (NULL != hostkeys_data)
    num_hostkeys = fsize / GNUNET_TESTING_HOSTKEYFILESIZE;
  return GNUNET_OK;
}


/**
 * Function to read blacklist rows from the database
 *
 * @param db the database connection
 * @param pid the identity of this peer
 * @param bl_rows where to store the retrieved blacklist rows
 * @return GNUNET_SYSERR upon error OR the number of rows retrieved
 */
static int
db_read_blacklist (struct sqlite3 *db, unsigned int pid, struct BlackListRow **bl_rows)
{
  static const char *query_bl = "SELECT (oid) FROM blacklist WHERE (id == ?);";
  struct sqlite3_stmt *stmt_bl;
  struct BlackListRow *lr;
  int nrows;
  int peer_id;
  int ret;

  if (SQLITE_OK != (ret = sqlite3_prepare_v2 (db, query_bl, -1, &stmt_bl, NULL)))
  {
    LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_prepare_v2");
    return GNUNET_SYSERR;
  }
  if (SQLITE_OK != (ret = sqlite3_bind_int (stmt_bl, 1, pid)))
  {
    LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_bind_int");
    sqlite3_finalize (stmt_bl);
    return GNUNET_SYSERR;
  }
  nrows = 0;
  do
  {
    ret = sqlite3_step (stmt_bl);
    if (SQLITE_ROW != ret)
      break;
    peer_id = sqlite3_column_int (stmt_bl, 1);
    lr = GNUNET_new (struct BlackListRow);
    lr->id = peer_id;
    lr->next = *bl_rows;
    *bl_rows = lr;
    nrows++;
  } while (1);
  sqlite3_finalize (stmt_bl);
  stmt_bl = NULL;
  return nrows;
}


/**
 * Function to read whitelist rows from the database
 *
 * @param db the database connection
 * @param pid the identity of this peer
 * @param wl_rows where to store the retrieved whitelist rows
 * @return GNUNET_SYSERR upon error OR the number of rows retrieved
 */
static int
db_read_whitelist (struct sqlite3 *db, unsigned int pid, struct WhiteListRow **wl_rows)
{
  static const char *query_wl = "SELECT (oid, bandwidth, latency, loss) FROM whitelist WHERE (id == ?);";
  struct sqlite3_stmt *stmt_wl;
  struct WhiteListRow *lr;
  int nrows;
  int ret;
  
  if (SQLITE_OK != (ret = sqlite3_prepare_v2 (db, query_wl, -1, &stmt_wl, NULL)))
  {
    LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_prepare_v2");
    return GNUNET_SYSERR;
  }
  if (SQLITE_OK != (ret = sqlite3_bind_int (stmt_wl, 1, pid)))
  {
    LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_bind_int");
    sqlite3_finalize (stmt_wl);
    return GNUNET_SYSERR;
  }
  nrows = 0;
  do
  {
    ret = sqlite3_step (stmt_wl);
    if (SQLITE_ROW != ret)
      break;
    nrows++;
    lr = GNUNET_new (struct WhiteListRow);
    lr->id = sqlite3_column_int (stmt_wl, 1);
    lr->bandwidth = sqlite3_column_int (stmt_wl, 2);
    lr->latency = sqlite3_column_int (stmt_wl, 3);
    lr->loss = sqlite3_column_int (stmt_wl, 4);
    lr->next = *wl_rows;
    *wl_rows = lr;
  } while (1);
  sqlite3_finalize (stmt_wl);
  return nrows;
}


/**
 * Main function that will be run.
 *
 * @param cls closure
 * @param args remaining command-line arguments
 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
 * @param c configuration
 */
static void
run (void *cls, char *const *args, const char *cfgfile,
     const struct GNUNET_CONFIGURATION_Handle *c)
{
  char *dbfile;
  struct BlackListRow *bl_head;
  struct BlackListRow *bl_entry;
  struct WhiteListRow *wl_head;
  struct WhiteListRow *wl_entry;
  struct GNUNET_PeerIdentity identity;
  struct GNUNET_ATS_Information triplet[3];
  unsigned long long pid;
  unsigned int nrows;
  int ret;

  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (c, "TESTBED",
                                                            "PEERID", &pid))
  {
    GNUNET_break (0);
    return;
  }
  transport = GNUNET_TRANSPORT_connect (c, NULL, NULL, NULL, NULL, NULL);
  if (NULL == transport)
  {
    GNUNET_break (0);
    return;
  }
  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "TESTBED",
                                                            "UNDERLAY_DB",
                                                            &dbfile))
  {
    GNUNET_break (0);
    return;
  }
  if (SQLITE_OK != (ret = sqlite3_open_v2 (dbfile, &db, SQLITE_OPEN_READONLY, NULL)))
  {
    if (NULL != db)
    {
      LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_open_v2");
      sqlite3_close (db);
    }
    else
      LOG (GNUNET_ERROR_TYPE_ERROR, "Cannot open sqlite file %s\n", dbfile);
    GNUNET_free (dbfile);
    return;
  }
  DEBUG ("Opened database %s\n", dbfile);
  GNUNET_free (dbfile);
  dbfile = NULL;
  bl_head = NULL;
  wl_head = NULL;
  nrows = db_read_blacklist (db, pid, &bl_head);
  if (GNUNET_SYSERR == nrows)
    goto close_db;
  if (nrows > 0)
  {
    blacklist_map = GNUNET_CONTAINER_multipeermap_create (nrows, GNUNET_YES);
    if (GNUNET_OK != load_keys (c))
      goto close_db;
  }
  while (NULL != (bl_entry = bl_head))
  {
    bl_head = bl_entry->next;
    blacklist_peer (bl_entry->id);
    GNUNET_free (bl_entry);
  }
  if (NULL != blacklist_map)
  {
    bh = GNUNET_TRANSPORT_blacklist (c, &check_access, NULL);
    shutdown_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
                                                  &do_shutdown, NULL);
  }
  /* read and process whitelist */
  nrows = 0;
  wl_head = NULL;
  nrows = db_read_whitelist (db, pid, &wl_head);
  if ((GNUNET_SYSERR == nrows) || (0 == nrows))
    goto close_db;
  triplet[0].type = 0; //FIXME: not implemented: GNUNET_ATS_QUALITY_NET_THROUGHPUT
  triplet[1].type = GNUNET_ATS_QUALITY_NET_DELAY;
  triplet[2].type =  0; //FIXME: not implemented: GNUNET_ATS_QUALITY_NET_LOSSRATE;
  while (NULL != (wl_entry = wl_head))
  {
    wl_head = wl_entry->next;
    triplet[0].value = wl_entry->bandwidth; //FIXME: bandwidth != throughput !!
    triplet[1].value = wl_entry->latency;
    triplet[2].value = wl_entry->loss;
    GNUNET_assert (GNUNET_OK == get_identity (wl_entry->id, &identity));
    GNUNET_TRANSPORT_set_traffic_metric (transport,
                                         &identity,
                                         GNUNET_YES,
                                         GNUNET_YES, /* FIXME: Separate inbound, outboud metrics */
                                         triplet, 3);
    GNUNET_free (wl_entry);
  }

 close_db:
  while (NULL != (bl_entry = bl_head))
  {
    bl_head = bl_entry->next;
    GNUNET_free (bl_entry);
  }
  GNUNET_break (GNUNET_OK == sqlite3_close (db));
  return;
}


/**
 * The main function.
 *
 * @param argc number of arguments from the command line
 * @param argv command line arguments
 * @return 0 ok, 1 on error
 */
int
main (int argc, char *const *argv)
{
  static const struct GNUNET_GETOPT_CommandLineOption options[] = {
    GNUNET_GETOPT_OPTION_END
  };
  int ret;

  if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
    return 2;
#ifdef SQLITE_CONFIG_MMAP_SIZE
  (void) sqlite3_config (SQLITE_CONFIG_MMAP_SIZE, 512000, 256000000);
#endif
  ret =
      (GNUNET_OK ==
       GNUNET_PROGRAM_run (argc, argv, "gnunet-daemon-testbed-underlay",
                           _
                           ("Daemon to restrict underlay network in testbed deployments"),
                           options, &run, NULL)) ? 0 : 1;
  GNUNET_free ((void*) argv);
  return ret;
}