aboutsummaryrefslogtreecommitdiff
path: root/src/dht/gnunet-service-dht.c
blob: f03cb379bf018e3c90b4befd12509f88edb9e4af (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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
/*
     This file is part of GNUnet.
     (C) 2009, 2010 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 2, 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 dht/gnunet-service-dht.c
 * @brief main DHT service shell, building block for DHT implementations
 * @author Christian Grothoff
 * @author Nathan Evans
 */

#include "platform.h"
#include "gnunet_client_lib.h"
#include "gnunet_getopt_lib.h"
#include "gnunet_os_lib.h"
#include "gnunet_protocols.h"
#include "gnunet_service_lib.h"
#include "gnunet_core_service.h"
#include "gnunet_signal_lib.h"
#include "gnunet_util_lib.h"
#include "gnunet_datacache_lib.h"
#include "dht.h"

/**
 * Handle to the datacache service (for inserting/retrieving data)
 */
struct GNUNET_DATACACHE_Handle *datacache;

/**
 * The main scheduler to use for the DHT service
 */
static struct GNUNET_SCHEDULER_Handle *sched;

/**
 * The configuration the DHT service is running with
 */
static const struct GNUNET_CONFIGURATION_Handle *cfg;

/**
 * Timeout for transmissions to clients
 */
static struct GNUNET_TIME_Relative client_transmit_timeout;

/**
 * Handle to the core service
 */
static struct GNUNET_CORE_Handle *coreAPI;

/**
 * The identity of our peer.
 */
static struct GNUNET_PeerIdentity my_identity;

/**
 * Task to run when we shut down, cleaning up all our trash
 */
static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;

/**
 * Context for handling results from a get request.
 */
struct DatacacheGetContext
{
  /**
   * The client to send the result to.
   */
  struct GNUNET_SERVER_Client *client;

  /**
   * The unique id of this request
   */
  unsigned long long unique_id;
};


struct DHT_MessageContext
{
  /**
   * The client this request was received from.
   */
  struct GNUNET_SERVER_Client *client;

  /**
   * The key this request was about
   */
  GNUNET_HashCode *key;

  /**
   * The unique identifier of this request
   */
  unsigned long long unique_id;

  /**
   * Desired replication level
   */
  size_t replication;

  /**
   * Any message options for this request
   */
  size_t msg_options;
};

/**
 * Server handler for handling locally received dht requests
 */
static void
handle_dht_start_message (void *cls, struct GNUNET_SERVER_Client *client,
                          const struct GNUNET_MessageHeader *message);

static void
handle_dht_stop_message (void *cls, struct GNUNET_SERVER_Client *client,
                         const struct GNUNET_MessageHeader *message);

static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
  {&handle_dht_start_message, NULL, GNUNET_MESSAGE_TYPE_DHT, 0},
  {&handle_dht_stop_message, NULL, GNUNET_MESSAGE_TYPE_DHT_STOP, 0},
  {NULL, NULL, 0, 0}
};


/**
 * Core handler for p2p dht get requests.
 */
static int handle_dht_p2p_get (void *cls,
                               const struct GNUNET_PeerIdentity *peer,
                               const struct GNUNET_MessageHeader *message,
                               struct GNUNET_TIME_Relative latency,
                               uint32_t distance);

/**
 * Core handler for p2p dht put requests.
 */
static int handle_dht_p2p_put (void *cls,
                               const struct GNUNET_PeerIdentity *peer,
                               const struct GNUNET_MessageHeader *message,
                               struct GNUNET_TIME_Relative latency,
                               uint32_t distance);

/**
 * Core handler for p2p dht find peer requests.
 */
static int handle_dht_p2p_find_peer (void *cls,
                                     const struct GNUNET_PeerIdentity *peer,
                                     const struct GNUNET_MessageHeader
                                     *message,
                                     struct GNUNET_TIME_Relative latency,
                                     uint32_t distance);

static struct GNUNET_CORE_MessageHandler core_handlers[] = {
  {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_GET, 0},
  {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_PUT, 0},
  {&handle_dht_p2p_find_peer, GNUNET_MESSAGE_TYPE_DHT_FIND_PEER, 0},
  {NULL, 0, 0}
};


static size_t
send_reply (void *cls, size_t size, void *buf)
{
  struct GNUNET_DHT_Message *reply = cls;

  if (buf == NULL)              /* Message timed out, that's crappy... */
    {
      GNUNET_free (reply);
      return 0;
    }

  if (size >= ntohs (reply->header.size))
    {
      memcpy (buf, reply, ntohs (reply->header.size));
      return ntohs (reply->header.size);
    }
  else
    return 0;
}


static void
send_reply_to_client (struct GNUNET_SERVER_Client *client,
                      struct GNUNET_MessageHeader *message,
                      unsigned long long uid)
{
  struct GNUNET_DHT_Message *reply;
  size_t msize;
  size_t tsize;
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Sending reply to client.\n", "DHT");
#endif
  msize = ntohs (message->size);
  tsize = sizeof (struct GNUNET_DHT_Message) + msize;
  reply = GNUNET_malloc (tsize);
  reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT);
  reply->header.size = htons (tsize);
  if (uid != 0)
    reply->unique = htons (GNUNET_YES);
  reply->unique_id = GNUNET_htonll (uid);
  memcpy (&reply[1], message, msize);

  GNUNET_SERVER_notify_transmit_ready (client,
                                       tsize,
                                       GNUNET_TIME_relative_multiply
                                       (GNUNET_TIME_UNIT_SECONDS, 5),
                                       &send_reply, reply);

}


/**
 * Iterator for local get request results, return
 * GNUNET_OK to continue iteration, anything else
 * to stop iteration.
 */
static int
datacache_get_iterator (void *cls,
                        struct GNUNET_TIME_Absolute exp,
                        const GNUNET_HashCode * key,
                        uint32_t size, const char *data, uint32_t type)
{
  struct DatacacheGetContext *datacache_get_ctx = cls;
  struct GNUNET_DHT_GetResultMessage *get_result;

  get_result =
    GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
  get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
  get_result->header.size =
    htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
  get_result->data_size = htons (size);
  get_result->expiration = exp;
  memcpy (&get_result->key, key, sizeof (GNUNET_HashCode));
  get_result->type = htons (type);
  memcpy (&get_result[1], data, size);

  send_reply_to_client (datacache_get_ctx->client, &get_result->header,
                        datacache_get_ctx->unique_id);

  GNUNET_free (get_result);
  return GNUNET_OK;
}

/**
 * Server handler for initiating local dht get requests
 */
static void
handle_dht_get (void *cls, struct GNUNET_DHT_GetMessage *get_msg,
                struct DHT_MessageContext *message_context)
{
#if DEBUG_DHT
  GNUNET_HashCode get_key;
#endif
  size_t get_type;
  unsigned int results;
  struct DatacacheGetContext *datacache_get_context;

  GNUNET_assert (ntohs (get_msg->header.size) >=
                 sizeof (struct GNUNET_DHT_GetMessage));
  get_type = ntohs (get_msg->type);

#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
              "DHT", "GET", get_type, GNUNET_h2s (&get_key),
              message_context->unique_id);
#endif

  datacache_get_context = GNUNET_malloc (sizeof (struct DatacacheGetContext));
  datacache_get_context->client = message_context->client;
  datacache_get_context->unique_id = message_context->unique_id;

  results = 0;
  if (datacache != NULL)
    results =
      GNUNET_DATACACHE_get (datacache, message_context->key, get_type,
                            datacache_get_iterator, datacache_get_context);

#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Found %d results for local `%s' request\n", "DHT",
              results, "GET");
#endif
  GNUNET_free (datacache_get_context);
  /* FIXME: Implement get functionality here */
}


/**
 * Server handler for initiating local dht find peer requests
 */
static void
handle_dht_find_peer (void *cls, struct GNUNET_DHT_FindPeerMessage *find_msg,
                      struct DHT_MessageContext *message_context)
{
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
              "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
              ntohs (find_msg->header.size),
              sizeof (struct GNUNET_DHT_FindPeerMessage));
#endif

  GNUNET_assert (ntohs (find_msg->header.size) >=
                 sizeof (struct GNUNET_DHT_FindPeerMessage));

  /* FIXME: Implement find peer functionality here */
}


/**
 * Server handler for initiating local dht put requests
 */
static void
handle_dht_put (void *cls, struct GNUNET_DHT_PutMessage *put_msg,
                struct DHT_MessageContext *message_context)
{
  size_t put_type;
  size_t data_size;

  GNUNET_assert (ntohs (put_msg->header.size) >=
                 sizeof (struct GNUNET_DHT_PutMessage));

  put_type = ntohs (put_msg->type);
  data_size = ntohs (put_msg->data_size);
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': %s msg total size is %d, data size %d, struct size %d\n",
              "DHT", "PUT", ntohs (put_msg->header.size), data_size,
              sizeof (struct GNUNET_DHT_PutMessage));
#endif
  GNUNET_assert (ntohs (put_msg->header.size) ==
                 sizeof (struct GNUNET_DHT_PutMessage) + data_size);

#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Received `%s' request from client, message type %d, key %s\n",
              "DHT", "PUT", put_type, GNUNET_h2s (message_context->key));
#endif

  /**
   * Simplest DHT functionality, store any message we receive a put request for.
   */
  if (datacache != NULL)
    GNUNET_DATACACHE_put (datacache, message_context->key, data_size,
                          (char *) &put_msg[1], put_type,
                          put_msg->expiration);
  /**
   * FIXME: Implement dht put request functionality here!
   */

}

/**
 * Context for sending receipt confirmations. Not used yet.
 */
struct SendConfirmationContext
{
  /**
   * The message to send.
   */
  struct GNUNET_DHT_StopMessage *message;

  /**
   * Transmit handle.
   */
  struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
};

static size_t
send_confirmation (void *cls, size_t size, void *buf)
{
  struct GNUNET_DHT_StopMessage *confirmation_message = cls;

  if (buf == NULL)              /* Message timed out, that's crappy... */
    {
      GNUNET_free (confirmation_message);
      return 0;
    }

  if (size >= ntohs (confirmation_message->header.size))
    {
      memcpy (buf, confirmation_message,
              ntohs (confirmation_message->header.size));
      return ntohs (confirmation_message->header.size);
    }
  else
    return 0;
}


static void
send_client_receipt_confirmation (struct GNUNET_SERVER_Client *client,
                                  uint64_t uid)
{
  struct GNUNET_DHT_StopMessage *confirm_message;

#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Sending receipt confirmation for uid %llu\n", "DHT",
              uid);
#endif
  confirm_message = GNUNET_malloc (sizeof (struct GNUNET_DHT_StopMessage));
  confirm_message->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_STOP);
  confirm_message->header.size =
    htons (sizeof (struct GNUNET_DHT_StopMessage));
  confirm_message->unique_id = GNUNET_htonll (uid);

  GNUNET_SERVER_notify_transmit_ready (client,
                                       sizeof (struct GNUNET_DHT_StopMessage),
                                       GNUNET_TIME_relative_multiply
                                       (GNUNET_TIME_UNIT_SECONDS, 5),
                                       &send_confirmation, confirm_message);

}

static void
handle_dht_start_message (void *cls, struct GNUNET_SERVER_Client *client,
                          const struct GNUNET_MessageHeader *message)
{
  struct GNUNET_DHT_Message *dht_msg = (struct GNUNET_DHT_Message *) message;
  struct GNUNET_MessageHeader *enc_msg;
  struct DHT_MessageContext *message_context;
  size_t enc_type;

  enc_msg = (struct GNUNET_MessageHeader *) &dht_msg[1];
  enc_type = ntohs (enc_msg->type);


#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
              "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
              GNUNET_ntohll (dht_msg->unique_id));
#endif

  message_context = GNUNET_malloc (sizeof (struct DHT_MessageContext));
  message_context->client = client;
  message_context->key = &dht_msg->key;
  message_context->unique_id = GNUNET_ntohll (dht_msg->unique_id);
  message_context->replication = ntohs (dht_msg->desired_replication_level);
  message_context->msg_options = ntohs (dht_msg->options);

  switch (enc_type)
    {
    case GNUNET_MESSAGE_TYPE_DHT_GET:
      handle_dht_get (cls, (struct GNUNET_DHT_GetMessage *) enc_msg,
                      message_context);
      break;
    case GNUNET_MESSAGE_TYPE_DHT_PUT:
      handle_dht_put (cls, (struct GNUNET_DHT_PutMessage *) enc_msg,
                      message_context);
      send_client_receipt_confirmation (client,
                                        GNUNET_ntohll (dht_msg->unique_id));
      break;
    case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
      handle_dht_find_peer (cls,
                            (struct GNUNET_DHT_FindPeerMessage *) enc_msg,
                            message_context);
      break;
    default:
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "`%s': Message type (%d) not handled\n", "DHT", enc_type);
    }

  GNUNET_free (message_context);
  GNUNET_SERVER_receive_done (client, GNUNET_OK);

}


static void
handle_dht_stop_message (void *cls, struct GNUNET_SERVER_Client *client,
                         const struct GNUNET_MessageHeader *message)
{
  struct GNUNET_DHT_StopMessage *dht_stop_msg =
    (struct GNUNET_DHT_StopMessage *) message;

#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Received `%s' request from client, uid %llu\n", "DHT",
              "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
#endif

  /* TODO: Put in demultiplexing here */

  send_client_receipt_confirmation (client,
                                    GNUNET_ntohll (dht_stop_msg->unique_id));
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


/**
 * Core handler for p2p dht get requests.
 */
static int
handle_dht_p2p_get (void *cls,
                    const struct GNUNET_PeerIdentity *peer,
                    const struct GNUNET_MessageHeader *message,
                    struct GNUNET_TIME_Relative latency, uint32_t distance)
{
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Received `%s' request from another peer\n", "DHT",
              "GET");
#endif

  return GNUNET_YES;
}

/**
 * Core handler for p2p dht put requests.
 */
static int
handle_dht_p2p_put (void *cls,
                    const struct GNUNET_PeerIdentity *peer,
                    const struct GNUNET_MessageHeader *message,
                    struct GNUNET_TIME_Relative latency, uint32_t distance)
{
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Received `%s' request from another peer\n", "DHT",
              "PUT");
#endif

  return GNUNET_YES;
}

/**
 * Core handler for p2p dht find peer requests.
 */
static int
handle_dht_p2p_find_peer (void *cls,
                          const struct GNUNET_PeerIdentity *peer,
                          const struct GNUNET_MessageHeader *message,
                          struct GNUNET_TIME_Relative latency,
                          uint32_t distance)
{
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Received `%s' request from another peer\n", "DHT",
              "FIND PEER");
#endif

  return GNUNET_YES;
}

/**
 * Task run during shutdown.
 *
 * @param cls unused
 * @param tc unused
 */
static void
shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  GNUNET_CORE_disconnect (coreAPI);
}

/**
 * To be called on core init/fail.
 */
void
core_init (void *cls,
           struct GNUNET_CORE_Handle *server,
           const struct GNUNET_PeerIdentity *identity,
           const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
{

  if (server == NULL)
    {
      GNUNET_SCHEDULER_cancel (sched, cleanup_task);
      GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
      return;
    }
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "%s: Core connection initialized, I am peer: %s\n", "dht",
              GNUNET_i2s (identity));
#endif
  memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
  coreAPI = server;
}

/**
 * Process dht requests.
 *
 * @param cls closure
 * @param scheduler scheduler to use
 * @param server the initialized server
 * @param c configuration to use
 */
static void
run (void *cls,
     struct GNUNET_SCHEDULER_Handle *scheduler,
     struct GNUNET_SERVER_Handle *server,
     const struct GNUNET_CONFIGURATION_Handle *c)
{
  sched = scheduler;
  cfg = c;

  datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");

  client_transmit_timeout =
    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5);
  GNUNET_SERVER_add_handlers (server, plugin_handlers);

  coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
                                 cfg,   /* Main configuration */
                                 client_transmit_timeout,       /* Delay for connecting */
                                 NULL,  /* FIXME: anything we want to pass around? */
                                 &core_init,    /* Call core_init once connected */
                                 NULL,  /* Don't care about pre-connects */
                                 NULL,  /* Don't care about connects */
                                 NULL,  /* Don't care about disconnects */
                                 NULL,  /* Don't want notified about all incoming messages */
                                 GNUNET_NO,     /* For header only inbound notification */
                                 NULL,  /* Don't want notified about all outbound messages */
                                 GNUNET_NO,     /* For header only outbound notification */
                                 core_handlers);        /* Register these handlers */

  if (coreAPI == NULL)
    return;

  /* Scheduled the task to clean up when shutdown is called */
  cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
                                               GNUNET_TIME_UNIT_FOREVER_REL,
                                               &shutdown_task, NULL);
}


/**
 * The main function for the dht service.
 *
 * @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)
{
  return (GNUNET_OK ==
          GNUNET_SERVICE_run (argc,
                              argv,
                              "dht",
                              GNUNET_SERVICE_OPTION_NONE,
                              &run, NULL)) ? 0 : 1;
}