make test case a bit more robust using timeouts and retries
[oweals/gnunet.git] / src / dht / gnunet-service-dht.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 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 2, 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  * @file dht/gnunet-service-dht.c
23  * @brief main DHT service shell, building block for DHT implementations
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  */
27
28 #include "platform.h"
29 #include "gnunet_client_lib.h"
30 #include "gnunet_getopt_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_core_service.h"
35 #include "gnunet_signal_lib.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_datacache_lib.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_hello_lib.h"
40 #include "dht.h"
41
42 /**
43  * Handle to the datacache service (for inserting/retrieving data)
44  */
45 struct GNUNET_DATACACHE_Handle *datacache;
46
47 /**
48  * The main scheduler to use for the DHT service
49  */
50 static struct GNUNET_SCHEDULER_Handle *sched;
51
52 /**
53  * The configuration the DHT service is running with
54  */
55 static const struct GNUNET_CONFIGURATION_Handle *cfg;
56
57 /**
58  * Timeout for transmissions to clients
59  */
60 static struct GNUNET_TIME_Relative client_transmit_timeout;
61
62 /**
63  * Handle to the core service
64  */
65 static struct GNUNET_CORE_Handle *coreAPI;
66
67 /**
68  * Handle to the transport service, for getting our hello
69  */
70 static struct GNUNET_TRANSPORT_Handle *transport_handle;
71
72 /**
73  * The identity of our peer.
74  */
75 static struct GNUNET_PeerIdentity my_identity;
76
77 /**
78  * Our HELLO
79  */
80 static struct GNUNET_MessageHeader *my_hello;
81
82 /**
83  * Task to run when we shut down, cleaning up all our trash
84  */
85 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
86
87
88 /**
89  * Linked list of messages to send to clients.
90  */
91 struct PendingMessage
92 {
93   /**
94    * Pointer to next item in the list
95    */
96   struct PendingMessage *next;
97
98   /**
99    * Actual message to be sent
100    */
101   struct GNUNET_MessageHeader *msg;
102
103 };
104
105 /**
106  * Struct containing information about a client,
107  * handle to connect to it, and any pending messages
108  * that need to be sent to it.
109  */
110 struct ClientList
111 {
112   /**
113    * Linked list of active clients
114    */
115   struct ClientList *next;
116
117   /**
118    * The handle to this client
119    */
120   struct GNUNET_SERVER_Client *client_handle;
121
122   /**
123    * Handle to the current transmission request, NULL
124    * if none pending.
125    */
126   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
127
128   /**
129    * Linked list of pending messages for this client
130    */
131   struct PendingMessage *pending_head;
132
133 };
134
135 /**
136  * Context for handling results from a get request.
137  */
138 struct DatacacheGetContext
139 {
140   /**
141    * The client to send the result to.
142    */
143   struct ClientList *client;
144
145   /**
146    * The unique id of this request
147    */
148   unsigned long long unique_id;
149 };
150
151 /**
152  * Context containing information about a DHT message received.
153  */
154 struct DHT_MessageContext
155 {
156   /**
157    * The client this request was received from.
158    */
159   struct ClientList *client;
160
161   /**
162    * The key this request was about
163    */
164   GNUNET_HashCode *key;
165
166   /**
167    * The unique identifier of this request
168    */
169   unsigned long long unique_id;
170
171   /**
172    * Desired replication level
173    */
174   size_t replication;
175
176   /**
177    * Any message options for this request
178    */
179   size_t msg_options;
180 };
181
182 /**
183  * List of active clients.
184  */
185 static struct ClientList *client_list;
186
187
188 /**
189  * Server handlers for handling locally received dht requests
190  */
191 static void
192 handle_dht_start_message (void *cls, struct GNUNET_SERVER_Client *client,
193                           const struct GNUNET_MessageHeader *message);
194
195 static void
196 handle_dht_stop_message (void *cls, struct GNUNET_SERVER_Client *client,
197                          const struct GNUNET_MessageHeader *message);
198
199 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
200   {&handle_dht_start_message, NULL, GNUNET_MESSAGE_TYPE_DHT, 0},
201   {&handle_dht_stop_message, NULL, GNUNET_MESSAGE_TYPE_DHT_STOP, 0},
202   {NULL, NULL, 0, 0}
203 };
204
205
206 /**
207  * Core handler for p2p dht get requests.
208  */
209 static int handle_dht_p2p_get (void *cls,
210                                const struct GNUNET_PeerIdentity *peer,
211                                const struct GNUNET_MessageHeader *message,
212                                struct GNUNET_TIME_Relative latency,
213                                uint32_t distance);
214
215 /**
216  * Core handler for p2p dht put requests.
217  */
218 static int handle_dht_p2p_put (void *cls,
219                                const struct GNUNET_PeerIdentity *peer,
220                                const struct GNUNET_MessageHeader *message,
221                                struct GNUNET_TIME_Relative latency,
222                                uint32_t distance);
223
224 /**
225  * Core handler for p2p dht find peer requests.
226  */
227 static int handle_dht_p2p_find_peer (void *cls,
228                                      const struct GNUNET_PeerIdentity *peer,
229                                      const struct GNUNET_MessageHeader
230                                      *message,
231                                      struct GNUNET_TIME_Relative latency,
232                                      uint32_t distance);
233
234 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
235   {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_GET, 0},
236   {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_PUT, 0},
237   {&handle_dht_p2p_find_peer, GNUNET_MESSAGE_TYPE_DHT_FIND_PEER, 0},
238   {NULL, 0, 0}
239 };
240
241 /**
242  * Forward declaration.
243  */
244 static size_t send_generic_reply (void *cls, size_t size, void *buf);
245
246 /**
247  * Task run to check for messages that need to be sent to a client.
248  *
249  * @param cls a ClientList, containing the client and any messages to be sent to it
250  * @param tc reason this was called
251  */
252 static void
253 process_pending_messages (void *cls,
254                           const struct GNUNET_SCHEDULER_TaskContext *tc)
255 {
256   struct ClientList *client = cls;
257
258   if (client->pending_head == NULL)     /* No messages queued */
259     {
260 #if DEBUG_DHT
261       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
262                   "`%s': Have no pending messages for client.\n", "DHT");
263 #endif
264       return;
265     }
266
267   if (client->transmit_handle == NULL)  /* No current pending messages, we can try to send! */
268     client->transmit_handle =
269       GNUNET_SERVER_notify_transmit_ready (client->client_handle,
270                                            ntohs (client->pending_head->msg->
271                                                   size),
272                                            GNUNET_TIME_relative_multiply
273                                            (GNUNET_TIME_UNIT_SECONDS, 5),
274                                            &send_generic_reply, client);
275   else
276     {
277 #if DEBUG_DHT
278       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
279                   "`%s': Transmit handle is non-null.\n", "DHT");
280 #endif
281     }
282 }
283
284 /**
285  * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
286  * request.  A ClientList is passed as closure, take the head of the list
287  * and copy it into buf, which has the result of sending the message to the
288  * client.
289  *
290  * @param cls closure to this call
291  * @param size maximum number of bytes available to send
292  * @param buf where to copy the actual message to
293  *
294  * @return the number of bytes actually copied, 0 indicates failure
295  */
296 static size_t
297 send_generic_reply (void *cls, size_t size, void *buf)
298 {
299   struct ClientList *client = cls;
300   struct PendingMessage *reply = client->pending_head;
301   int ret;
302
303   client->transmit_handle = NULL;
304   if (buf == NULL)              /* Message timed out, that's crappy... */
305     {
306 #if DEBUG_DHT
307       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s': buffer was NULL\n", "DHT");
308 #endif
309       client->pending_head = reply->next;
310       GNUNET_free (reply->msg);
311       GNUNET_free (reply);
312       return 0;
313     }
314
315   if (size >= ntohs (reply->msg->size))
316     {
317 #if DEBUG_DHT
318       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
319                   "`%s': Copying reply to buffer, REALLY SENT\n", "DHT");
320 #endif
321       memcpy (buf, reply->msg, ntohs (reply->msg->size));
322
323       ret = ntohs (reply->msg->size);
324     }
325   else
326     ret = 0;
327
328   client->pending_head = reply->next;
329   GNUNET_free (reply->msg);
330   GNUNET_free (reply);
331
332   GNUNET_SCHEDULER_add_now (sched, &process_pending_messages, client);
333   return ret;
334 }
335
336 /**
337  * Add a PendingMessage to the clients list of messages to be sent
338  *
339  * @param client the active client to send the message to
340  * @param pending_message the actual message to send
341  */
342 static void
343 add_pending_message (struct ClientList *client,
344                      struct PendingMessage *pending_message)
345 {
346   struct PendingMessage *pos;
347   struct PendingMessage *prev;
348
349   pos = client->pending_head;
350
351 #if DEBUG_DHT
352   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
353               "`%s': Adding pending message for client.\n", "DHT");
354 #endif
355
356   if (pos == NULL)
357     {
358       client->pending_head = pending_message;
359     }
360   else                          /* This means another request is already queued, rely on send_reply to process all pending messages */
361     {
362       while (pos != NULL)       /* Find end of list */
363         {
364           prev = pos;
365           pos = pos->next;
366         }
367
368       GNUNET_assert (prev != NULL);
369       prev->next = pending_message;
370     }
371
372   GNUNET_SCHEDULER_add_now (sched, &process_pending_messages, client);
373
374 }
375
376 /**
377  * Called when a reply needs to be sent to a client, either as
378  * a result it found to a GET or FIND PEER request.
379  *
380  * @param client the client to send the reply to
381  * @param message the encapsulated message to send
382  * @param uid the unique identifier of this request
383  */
384 static void
385 send_reply_to_client (struct ClientList *client,
386                       struct GNUNET_MessageHeader *message,
387                       unsigned long long uid)
388 {
389   struct GNUNET_DHT_Message *reply;
390   struct PendingMessage *pending_message;
391
392   size_t msize;
393   size_t tsize;
394 #if DEBUG_DHT
395   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
396               "`%s': Sending reply to client.\n", "DHT");
397 #endif
398   msize = ntohs (message->size);
399   tsize = sizeof (struct GNUNET_DHT_Message) + msize;
400   reply = GNUNET_malloc (tsize);
401   reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT);
402   reply->header.size = htons (tsize);
403   if (uid != 0)
404     reply->unique = htons (GNUNET_YES);
405   reply->unique_id = GNUNET_htonll (uid);
406   memcpy (&reply[1], message, msize);
407
408   pending_message = GNUNET_malloc (sizeof (struct PendingMessage));
409   pending_message->msg = &reply->header;
410
411   add_pending_message (client, pending_message);
412 }
413
414
415 /**
416  * Iterator for local get request results,
417  *
418  * @param cls closure for iterator, a DatacacheGetContext
419  * @param exp when does this value expire?
420  * @param key the key this data is stored under
421  * @param size the size of the data identified by key
422  * @param data the actual data
423  * @param type the type of the data
424  *
425  * @return GNUNET_OK to continue iteration, anything else
426  * to stop iteration.
427  */
428 static int
429 datacache_get_iterator (void *cls,
430                         struct GNUNET_TIME_Absolute exp,
431                         const GNUNET_HashCode * key,
432                         uint32_t size, const char *data, uint32_t type)
433 {
434   struct DatacacheGetContext *datacache_get_ctx = cls;
435   struct GNUNET_DHT_GetResultMessage *get_result;
436 #if DEBUG_DHT
437   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
438               "`%s': Received `%s' response from datacache\n", "DHT", "GET");
439 #endif
440   get_result =
441     GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
442   get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
443   get_result->header.size =
444     htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
445   get_result->data_size = htons (size);
446   get_result->expiration = exp;
447   memcpy (&get_result->key, key, sizeof (GNUNET_HashCode));
448   get_result->type = htons (type);
449   memcpy (&get_result[1], data, size);
450
451   send_reply_to_client (datacache_get_ctx->client, &get_result->header,
452                         datacache_get_ctx->unique_id);
453
454   GNUNET_free (get_result);
455   return GNUNET_OK;
456 }
457
458 /**
459  * Server handler for initiating local dht get requests
460  *
461  * @param cls closure for service
462  * @param get_msg the actual get message
463  * @param message_context struct containing pertinent information about the get request
464  *
465  */
466 static void
467 handle_dht_get (void *cls, struct GNUNET_DHT_GetMessage *get_msg,
468                 struct DHT_MessageContext *message_context)
469 {
470   size_t get_type;
471   unsigned int results;
472   struct DatacacheGetContext *datacache_get_context;
473
474   GNUNET_assert (ntohs (get_msg->header.size) >=
475                  sizeof (struct GNUNET_DHT_GetMessage));
476   get_type = ntohs (get_msg->type);
477
478 #if DEBUG_DHT
479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
480               "`%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
481               "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
482               message_context->unique_id);
483 #endif
484
485   datacache_get_context = GNUNET_malloc (sizeof (struct DatacacheGetContext));
486   datacache_get_context->client = message_context->client;
487   datacache_get_context->unique_id = message_context->unique_id;
488
489   results = 0;
490   if (datacache != NULL)
491     results =
492       GNUNET_DATACACHE_get (datacache, message_context->key, get_type,
493                             &datacache_get_iterator, datacache_get_context);
494
495   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
496               "`%s': Found %d results for local `%s' request\n", "DHT",
497               results, "GET");
498
499   GNUNET_free (datacache_get_context);
500   /* FIXME: Implement get functionality here */
501 }
502
503
504 /**
505  * Server handler for initiating local dht find peer requests
506  *
507  * @param cls closure for service
508  * @param find_msg the actual find peer message
509  * @param message_context struct containing pertinent information about the request
510  *
511  */
512 static void
513 handle_dht_find_peer (void *cls, struct GNUNET_DHT_FindPeerMessage *find_msg,
514                       struct DHT_MessageContext *message_context)
515 {
516   struct GNUNET_DHT_FindPeerResultMessage *find_peer_result;
517   size_t hello_size;
518   size_t tsize;
519 #if DEBUG_DHT
520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
521               "`%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
522               "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
523               ntohs (find_msg->header.size),
524               sizeof (struct GNUNET_DHT_FindPeerMessage));
525 #endif
526
527   GNUNET_assert (ntohs (find_msg->header.size) >=
528                  sizeof (struct GNUNET_DHT_FindPeerMessage));
529
530   if (my_hello == NULL)
531   {
532 #if DEBUG_DHT
533     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
534                 "`%s': Our HELLO is null, can't return.\n",
535                 "DHT");
536 #endif
537
538     return;
539   }
540
541   /* Simplistic find_peer functionality, always return our hello */
542   hello_size = ntohs(my_hello->size);
543   tsize = hello_size + sizeof (struct GNUNET_DHT_FindPeerResultMessage);
544   find_peer_result = GNUNET_malloc (tsize);
545   find_peer_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
546   find_peer_result->header.size = htons (tsize);
547   find_peer_result->data_size = htons (hello_size);
548   memcpy(&find_peer_result->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity));
549   memcpy (&find_peer_result[1], &my_hello, hello_size);
550
551   send_reply_to_client(message_context->client, &find_peer_result->header, message_context->unique_id);
552   GNUNET_free(find_peer_result);
553   /* FIXME: Implement find peer functionality here */
554 }
555
556
557 /**
558  * Server handler for initiating local dht put requests
559  *
560  * @param cls closure for service
561  * @param put_msg the actual put message
562  * @param message_context struct containing pertinent information about the request
563  */
564 static void
565 handle_dht_put (void *cls, struct GNUNET_DHT_PutMessage *put_msg,
566                 struct DHT_MessageContext *message_context)
567 {
568   size_t put_type;
569   size_t data_size;
570
571   GNUNET_assert (ntohs (put_msg->header.size) >=
572                  sizeof (struct GNUNET_DHT_PutMessage));
573
574   put_type = ntohs (put_msg->type);
575   data_size = ntohs (put_msg->data_size);
576 #if DEBUG_DHT
577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
578               "`%s': %s msg total size is %d, data size %d, struct size %d\n",
579               "DHT", "PUT", ntohs (put_msg->header.size), data_size,
580               sizeof (struct GNUNET_DHT_PutMessage));
581 #endif
582   GNUNET_assert (ntohs (put_msg->header.size) ==
583                  sizeof (struct GNUNET_DHT_PutMessage) + data_size);
584
585 #if DEBUG_DHT
586   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
587               "`%s': Received `%s' request from client, message type %d, key %s\n",
588               "DHT", "PUT", put_type, GNUNET_h2s (message_context->key));
589 #endif
590
591   /**
592    * Simplest DHT functionality, store any message we receive a put request for.
593    */
594   if (datacache != NULL)
595     GNUNET_DATACACHE_put (datacache, message_context->key, data_size,
596                           (char *) &put_msg[1], put_type,
597                           put_msg->expiration);
598   /**
599    * FIXME: Implement dht put request functionality here!
600    */
601
602 }
603
604
605 /**
606  * Find a client if it exists, add it otherwise.
607  *
608  * @param client the server handle to the client
609  *
610  * @return the client if found, a new client otherwise
611  */
612 static struct ClientList *
613 find_active_client (struct GNUNET_SERVER_Client *client)
614 {
615   struct ClientList *pos = client_list;
616   struct ClientList *ret;
617
618   while (pos != NULL)
619     {
620       if (pos->client_handle == client)
621         return pos;
622       pos = pos->next;
623     }
624
625   ret = GNUNET_malloc (sizeof (struct ClientList));
626   ret->client_handle = client;
627   ret->next = client_list;
628   client_list = ret;
629   ret->pending_head = NULL;
630
631   return ret;
632 }
633
634 /**
635  * Construct a message receipt confirmation for a particular uid.
636  * Receipt confirmations are used for any requests that don't expect
637  * a reply otherwise (i.e. put requests, stop requests).
638  *
639  * @param client the handle for the client
640  * @param uid the unique identifier of this message
641  */
642 static void
643 send_client_receipt_confirmation (struct GNUNET_SERVER_Client *client,
644                                   uint64_t uid)
645 {
646   struct GNUNET_DHT_StopMessage *confirm_message;
647   struct ClientList *active_client;
648   struct PendingMessage *pending_message;
649
650 #if DEBUG_DHT
651   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
652               "`%s': Sending receipt confirmation for uid %llu\n", "DHT",
653               uid);
654 #endif
655   confirm_message = GNUNET_malloc (sizeof (struct GNUNET_DHT_StopMessage));
656   confirm_message->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_STOP);
657   confirm_message->header.size =
658     htons (sizeof (struct GNUNET_DHT_StopMessage));
659   confirm_message->unique_id = GNUNET_htonll (uid);
660
661   active_client = find_active_client (client);
662   pending_message = GNUNET_malloc (sizeof (struct PendingMessage));
663   pending_message->msg = &confirm_message->header;
664
665   add_pending_message (active_client, pending_message);
666
667 }
668
669 /**
670  * Handler for any generic DHT messages, calls the appropriate handler
671  * depending on message type, sends confirmation if responses aren't otherwise
672  * expected.
673  *
674  * @param cls closure for the service
675  * @param client the client we received this message from
676  * @param message the actual message received
677  */
678 static void
679 handle_dht_start_message (void *cls, struct GNUNET_SERVER_Client *client,
680                           const struct GNUNET_MessageHeader *message)
681 {
682   struct GNUNET_DHT_Message *dht_msg = (struct GNUNET_DHT_Message *) message;
683   struct GNUNET_MessageHeader *enc_msg;
684   struct DHT_MessageContext *message_context;
685
686   size_t enc_type;
687
688   enc_msg = (struct GNUNET_MessageHeader *) &dht_msg[1];
689   enc_type = ntohs (enc_msg->type);
690
691
692 #if DEBUG_DHT
693   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
694               "`%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
695               "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
696               GNUNET_ntohll (dht_msg->unique_id));
697 #endif
698
699   message_context = GNUNET_malloc (sizeof (struct DHT_MessageContext));
700   message_context->client = find_active_client (client);
701   message_context->key = &dht_msg->key;
702   message_context->unique_id = GNUNET_ntohll (dht_msg->unique_id);
703   message_context->replication = ntohs (dht_msg->desired_replication_level);
704   message_context->msg_options = ntohs (dht_msg->options);
705
706   switch (enc_type)
707     {
708     case GNUNET_MESSAGE_TYPE_DHT_GET:
709       handle_dht_get (cls, (struct GNUNET_DHT_GetMessage *) enc_msg,
710                       message_context);
711       break;
712     case GNUNET_MESSAGE_TYPE_DHT_PUT:
713       handle_dht_put (cls, (struct GNUNET_DHT_PutMessage *) enc_msg,
714                       message_context);
715       send_client_receipt_confirmation (client,
716                                         GNUNET_ntohll (dht_msg->unique_id));
717       break;
718     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
719       handle_dht_find_peer (cls,
720                             (struct GNUNET_DHT_FindPeerMessage *) enc_msg,
721                             message_context);
722       break;
723     default:
724       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
725                   "`%s': Message type (%d) not handled\n", "DHT", enc_type);
726     }
727
728   GNUNET_free (message_context);
729   GNUNET_SERVER_receive_done (client, GNUNET_OK);
730
731 }
732
733 /**
734  * Handler for any generic DHT stop messages, calls the appropriate handler
735  * depending on message type, sends confirmation by default (stop messages
736  * do not otherwise expect replies)
737  *
738  * @param cls closure for the service
739  * @param client the client we received this message from
740  * @param message the actual message received
741  *
742  * TODO: add demultiplexing for stop message types.
743  */
744 static void
745 handle_dht_stop_message (void *cls, struct GNUNET_SERVER_Client *client,
746                          const struct GNUNET_MessageHeader *message)
747 {
748   struct GNUNET_DHT_StopMessage *dht_stop_msg =
749     (struct GNUNET_DHT_StopMessage *) message;
750
751 #if DEBUG_DHT
752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
753               "`%s': Received `%s' request from client, uid %llu\n", "DHT",
754               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
755 #endif
756
757   /* TODO: Put in demultiplexing here */
758
759   send_client_receipt_confirmation (client,
760                                     GNUNET_ntohll (dht_stop_msg->unique_id));
761   GNUNET_SERVER_receive_done (client, GNUNET_OK);
762 }
763
764
765 /**
766  * Core handler for p2p dht get requests.
767  */
768 static int
769 handle_dht_p2p_get (void *cls,
770                     const struct GNUNET_PeerIdentity *peer,
771                     const struct GNUNET_MessageHeader *message,
772                     struct GNUNET_TIME_Relative latency, uint32_t distance)
773 {
774 #if DEBUG_DHT
775   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
776               "`%s': Received `%s' request from another peer\n", "DHT",
777               "GET");
778 #endif
779
780   return GNUNET_YES;
781 }
782
783 /**
784  * Core handler for p2p dht put requests.
785  */
786 static int
787 handle_dht_p2p_put (void *cls,
788                     const struct GNUNET_PeerIdentity *peer,
789                     const struct GNUNET_MessageHeader *message,
790                     struct GNUNET_TIME_Relative latency, uint32_t distance)
791 {
792 #if DEBUG_DHT
793   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
794               "`%s': Received `%s' request from another peer\n", "DHT",
795               "PUT");
796 #endif
797
798   return GNUNET_YES;
799 }
800
801 /**
802  * Core handler for p2p dht find peer requests.
803  */
804 static int
805 handle_dht_p2p_find_peer (void *cls,
806                           const struct GNUNET_PeerIdentity *peer,
807                           const struct GNUNET_MessageHeader *message,
808                           struct GNUNET_TIME_Relative latency,
809                           uint32_t distance)
810 {
811 #if DEBUG_DHT
812   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
813               "`%s': Received `%s' request from another peer\n", "DHT",
814               "FIND PEER");
815 #endif
816
817   return GNUNET_YES;
818 }
819
820
821 /**
822  * Receive the HELLO from transport service,
823  * free current and replace if necessary.
824  *
825  * @param cls NULL
826  * @param message HELLO message of peer
827  */
828 static void
829 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
830 {
831 #if DEBUG_DHT
832   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
833               "Received our `%s' from transport service\n",
834               "HELLO");
835 #endif
836
837   GNUNET_assert (message != NULL);
838   GNUNET_free_non_null(my_hello);
839   my_hello = GNUNET_malloc(ntohs(message->size));
840   memcpy(my_hello, message, ntohs(message->size));
841 }
842
843 /**
844  * Task run during shutdown.
845  *
846  * @param cls unused
847  * @param tc unused
848  */
849 static void
850 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
851 {
852   if (transport_handle != NULL)
853   {
854     GNUNET_free_non_null(my_hello);
855     GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
856     GNUNET_TRANSPORT_disconnect(transport_handle);
857   }
858   if (coreAPI != NULL)
859     GNUNET_CORE_disconnect (coreAPI);
860 }
861
862
863 /**
864  * To be called on core init/fail.
865  *
866  * @param cls service closure
867  * @param server handle to the server for this service
868  * @param identity the public identity of this peer
869  * @param publicKey the public key of this peer
870  */
871 void
872 core_init (void *cls,
873            struct GNUNET_CORE_Handle *server,
874            const struct GNUNET_PeerIdentity *identity,
875            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
876 {
877
878   if (server == NULL)
879     {
880 #if DEBUG_DHT
881   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
882               "%s: Connection to core FAILED!\n", "dht",
883               GNUNET_i2s (identity));
884 #endif
885       GNUNET_SCHEDULER_cancel (sched, cleanup_task);
886       GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
887       return;
888     }
889 #if DEBUG_DHT
890   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
891               "%s: Core connection initialized, I am peer: %s\n", "dht",
892               GNUNET_i2s (identity));
893 #endif
894   /* Copy our identity so we can use it */
895   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
896   /* Set the server to local variable */
897   coreAPI = server;
898 }
899
900
901 /**
902  * Process dht requests.
903  *
904  * @param cls closure
905  * @param scheduler scheduler to use
906  * @param server the initialized server
907  * @param c configuration to use
908  */
909 static void
910 run (void *cls,
911      struct GNUNET_SCHEDULER_Handle *scheduler,
912      struct GNUNET_SERVER_Handle *server,
913      const struct GNUNET_CONFIGURATION_Handle *c)
914 {
915   sched = scheduler;
916   cfg = c;
917
918   datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
919
920   client_transmit_timeout =
921     GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5);
922   GNUNET_SERVER_add_handlers (server, plugin_handlers);
923
924   coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
925                                  cfg,   /* Main configuration */
926                                  client_transmit_timeout,       /* Delay for connecting */
927                                  NULL,  /* FIXME: anything we want to pass around? */
928                                  &core_init,    /* Call core_init once connected */
929                                  NULL,  /* Don't care about pre-connects */
930                                  NULL,  /* Don't care about connects */
931                                  NULL,  /* Don't care about disconnects */
932                                  NULL,  /* Don't want notified about all incoming messages */
933                                  GNUNET_NO,     /* For header only inbound notification */
934                                  NULL,  /* Don't want notified about all outbound messages */
935                                  GNUNET_NO,     /* For header only outbound notification */
936                                  core_handlers);        /* Register these handlers */
937
938   transport_handle = GNUNET_TRANSPORT_connect(sched, cfg, NULL, NULL, NULL, NULL);
939
940   if (transport_handle != NULL)
941     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
942   else
943     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
944
945
946   if (coreAPI == NULL)
947     return;
948
949   /* Scheduled the task to clean up when shutdown is called */
950   cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
951                                                GNUNET_TIME_UNIT_FOREVER_REL,
952                                                &shutdown_task, NULL);
953 }
954
955
956 /**
957  * The main function for the dht service.
958  *
959  * @param argc number of arguments from the command line
960  * @param argv command line arguments
961  * @return 0 ok, 1 on error
962  */
963 int
964 main (int argc, char *const *argv)
965 {
966   return (GNUNET_OK ==
967           GNUNET_SERVICE_run (argc,
968                               argv,
969                               "dht",
970                               GNUNET_SERVICE_OPTION_NONE,
971                               &run, NULL)) ? 0 : 1;
972 }