inexorably closer to perfection
[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  * Handle to the core service
59  */
60 static struct GNUNET_CORE_Handle *coreAPI;
61
62 /**
63  * Handle to the transport service, for getting our hello
64  */
65 static struct GNUNET_TRANSPORT_Handle *transport_handle;
66
67 /**
68  * The identity of our peer.
69  */
70 static struct GNUNET_PeerIdentity my_identity;
71
72 /**
73  * Our HELLO
74  */
75 static struct GNUNET_MessageHeader *my_hello;
76
77 /**
78  * Task to run when we shut down, cleaning up all our trash
79  */
80 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
81
82
83 /**
84  * Linked list of messages to send to clients.
85  */
86 struct PendingMessage
87 {
88   /**
89    * Pointer to next item in the list
90    */
91   struct PendingMessage *next;
92
93   /**
94    * Pointer to previous item in the list
95    */
96   struct PendingMessage *prev;
97
98   /**
99    * Actual message to be sent; // avoid allocation
100    */
101   const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
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    * Tail of linked list of pending messages for this client
135    */
136   struct PendingMessage *pending_tail;
137
138 };
139
140 /**
141  * Context for handling results from a get request.
142  */
143 struct DatacacheGetContext
144 {
145   /**
146    * The client to send the result to.
147    */
148   struct ClientList *client;
149
150   /**
151    * The unique id of this request
152    */
153   unsigned long long unique_id;
154 };
155
156 /**
157  * Context containing information about a DHT message received.
158  */
159 struct DHT_MessageContext
160 {
161   /**
162    * The client this request was received from.
163    */
164   struct ClientList *client;
165
166   /**
167    * The key this request was about
168    */
169   GNUNET_HashCode *key;
170
171   /**
172    * The unique identifier of this request
173    */
174   unsigned long long unique_id;
175
176   /**
177    * Desired replication level
178    */
179   size_t replication;
180
181   /**
182    * Any message options for this request
183    */
184   size_t msg_options;
185 };
186
187 /**
188  * List of active clients.
189  */
190 static struct ClientList *client_list;
191
192 /**
193  * Forward declaration.
194  */
195 static size_t send_generic_reply (void *cls, size_t size, void *buf);
196
197
198 /**
199  * Task run to check for messages that need to be sent to a client.
200  *
201  * @param client a ClientList, containing the client and any messages to be sent to it
202  */
203 static void
204 process_pending_messages (struct ClientList *client)
205
206   if (client->pending_head == NULL) 
207     return;    
208   if (client->transmit_handle != NULL) 
209     return;
210   client->transmit_handle =
211     GNUNET_SERVER_notify_transmit_ready (client->client_handle,
212                                          ntohs (client->pending_head->msg->
213                                                 size),
214                                          GNUNET_TIME_UNIT_FOREVER_REL,
215                                          &send_generic_reply, client);
216 }
217
218 /**
219  * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
220  * request.  A ClientList is passed as closure, take the head of the list
221  * and copy it into buf, which has the result of sending the message to the
222  * client.
223  *
224  * @param cls closure to this call
225  * @param size maximum number of bytes available to send
226  * @param buf where to copy the actual message to
227  *
228  * @return the number of bytes actually copied, 0 indicates failure
229  */
230 static size_t
231 send_generic_reply (void *cls, size_t size, void *buf)
232 {
233   struct ClientList *client = cls;
234   char *cbuf = buf;
235   struct PendingMessage *reply;
236   size_t off;
237   size_t msize;
238
239   client->transmit_handle = NULL;
240   if (buf == NULL)             
241     {
242       /* client disconnected */
243 #if DEBUG_DHT
244       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s': buffer was NULL\n", "DHT");
245 #endif
246       return 0;
247     }
248   off = 0;
249   while ( (NULL != (reply = client->pending_head)) &&
250           (size >= off + (msize = ntohs (reply->msg->size))))
251     {
252       GNUNET_CONTAINER_DLL_remove (client->pending_head,
253                                    client->pending_tail,
254                                    reply);
255       memcpy (&cbuf[off], reply->msg, msize);
256       GNUNET_free (reply);
257       off += msize;
258     }
259 #if DEBUG_DHT
260   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
261               "`%s': Copying reply to buffer, REALLY SENT\n", "DHT");
262 #endif
263   process_pending_messages (client);
264   return off;
265 }
266
267
268 /**
269  * Add a PendingMessage to the clients list of messages to be sent
270  *
271  * @param client the active client to send the message to
272  * @param pending_message the actual message to send
273  */
274 static void
275 add_pending_message (struct ClientList *client,
276                      struct PendingMessage *pending_message)
277 {
278   GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
279                                      client->pending_tail,
280                                      client->pending_tail,
281                                      pending_message);
282   process_pending_messages (client);
283 }
284
285
286 /**
287  * Called when a reply needs to be sent to a client, either as
288  * a result it found to a GET or FIND PEER request.
289  *
290  * @param client the client to send the reply to
291  * @param message the encapsulated message to send
292  * @param uid the unique identifier of this request
293  */
294 static void
295 send_reply_to_client (struct ClientList *client,
296                       const struct GNUNET_MessageHeader *message,
297                       unsigned long long uid)
298 {
299   struct GNUNET_DHT_Message *reply;
300   struct PendingMessage *pending_message;
301   uint16_t msize;
302   size_t tsize;
303 #if DEBUG_DHT
304   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
305               "`%s': Sending reply to client.\n", "DHT");
306 #endif
307   msize = ntohs (message->size);
308   tsize = sizeof (struct GNUNET_DHT_Message) + msize;
309   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
310     {
311       GNUNET_BREAK_op (0);
312       return;
313     }
314   reply = GNUNET_malloc (tsize);
315   reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_ROUTE_RESULT);
316   reply->header.size = htons (tsize);
317   if (uid != 0)
318     reply->unique = htonl (GNUNET_YES); // ????
319   reply->unique_id = GNUNET_htonll (uid);
320   memcpy (&reply[1], message, msize);
321   pending_message = GNUNET_malloc (sizeof (struct PendingMessage)); // inline
322   pending_message->msg = &reply->header;
323   add_pending_message (client, pending_message);
324 }
325
326
327 /**
328  * Iterator for local get request results,
329  *
330  * @param cls closure for iterator, a DatacacheGetContext
331  * @param exp when does this value expire?
332  * @param key the key this data is stored under
333  * @param size the size of the data identified by key
334  * @param data the actual data
335  * @param type the type of the data
336  *
337  * @return GNUNET_OK to continue iteration, anything else
338  * to stop iteration.
339  */
340 static int
341 datacache_get_iterator (void *cls,
342                         struct GNUNET_TIME_Absolute exp,
343                         const GNUNET_HashCode * key,
344                         uint32_t size, const char *data, uint32_t type)
345 {
346   struct DatacacheGetContext *datacache_get_ctx = cls;
347   struct GNUNET_DHT_GetResultMessage *get_result;
348 #if DEBUG_DHT
349   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
350               "`%s': Received `%s' response from datacache\n", "DHT", "GET");
351 #endif
352   get_result =
353     GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
354   get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
355   get_result->header.size =
356     htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
357   get_result->data_size = htons (size);
358   get_result->expiration = exp;
359   memcpy (&get_result->key, key, sizeof (GNUNET_HashCode));
360   get_result->type = htons (type);
361   memcpy (&get_result[1], data, size);
362   send_reply_to_client (datacache_get_ctx->client, &get_result->header,
363                         datacache_get_ctx->unique_id);
364   GNUNET_free (get_result);
365   return GNUNET_OK;
366 }
367
368
369 /**
370  * Server handler for initiating local dht get requests
371  *
372  * @param cls closure for service
373  * @param msg the actual get message
374  * @param message_context struct containing pertinent information about the get request
375  */
376 static void
377 handle_dht_get (void *cls, 
378                 const struct GNUNET_MessageHeader *msg,
379                 struct DHT_MessageContext *message_context)
380 {
381   const struct GNUNET_DHT_GetMessage *get_msg;
382   uint16_t get_type;
383   unsigned int results;
384   struct DatacacheGetContext datacache_get_context;
385
386   if (ntohs (msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
387     {
388       GNUNET_break (0);
389       return;
390     }
391   get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
392   get_type = ntohs (get_msg->type);
393 #if DEBUG_DHT
394   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
395               "`%s': Received `%s' request from client, message type %u, key %s, uid %llu\n",
396               "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
397               message_context->unique_id);
398 #endif
399   datacache_get_context.client = message_context->client;
400   datacache_get_context.unique_id = message_context->unique_id;
401   results = 0;
402   if (datacache != NULL)
403     results =
404       GNUNET_DATACACHE_get (datacache, message_context->key, get_type,
405                             &datacache_get_iterator, &datacache_get_context);
406   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
407               "`%s': Found %d results for local `%s' request\n", "DHT",
408               results, "GET");
409 }
410
411
412 /**
413  * Server handler for initiating local dht find peer requests
414  *
415  * @param cls closure for service
416  * @param find_msg the actual find peer message
417  * @param message_context struct containing pertinent information about the request
418  *
419  */
420 static void
421 handle_dht_find_peer (void *cls, 
422                       const struct GNUNET_MessageHeader *find_msg,
423                       struct DHT_MessageContext *message_context)
424 {
425   struct GNUNET_DHT_FindPeerResultMessage *find_peer_result;
426   size_t hello_size;
427   size_t tsize;
428
429 #if DEBUG_DHT
430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
431               "`%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
432               "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
433               ntohs (find_msg->header.size),
434               sizeof (struct GNUNET_DHT_FindPeerMessage));
435 #endif
436   if (my_hello == NULL)
437   {
438 #if DEBUG_DHT
439     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
440                 "`%s': Our HELLO is null, can't return.\n",
441                 "DHT");
442 #endif
443     return;
444   }
445   /* Simplistic find_peer functionality, always return our hello */
446   hello_size = ntohs(my_hello->size);
447   tsize = hello_size + sizeof (struct GNUNET_DHT_FindPeerResultMessage);
448   // check tsize < MAX
449   find_peer_result = GNUNET_malloc (tsize);
450   find_peer_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
451   find_peer_result->header.size = htons (tsize);
452   memcpy (&find_peer_result[1], &my_hello, hello_size);
453   send_reply_to_client(message_context->client, &find_peer_result->header, message_context->unique_id);
454   GNUNET_free(find_peer_result);
455 }
456
457
458 /**
459  * Server handler for initiating local dht put requests
460  *
461  * @param cls closure for service
462  * @param put_msg the actual put message
463  * @param message_context struct containing pertinent information about the request
464  */
465 static void
466 handle_dht_put (void *cls,
467                 const struct GNUNET_MessageHeader *msg,
468                 struct DHT_MessageContext *message_context)
469 {
470   struct GNUNET_DHT_PutMessage *put_msg;
471   size_t put_type;
472   size_t data_size;
473
474   GNUNET_assert (ntohs (msg->header.size) >=
475                  sizeof (struct GNUNET_DHT_PutMessage));
476   put_msg = (struct GNUNET_DHT_PutMessage *)msg;
477   put_type = ntohl (put_msg->type);
478   data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
479 #if DEBUG_DHT
480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
481               "`%s': %s msg total size is %d, data size %d, struct size %d\n",
482               "DHT", "PUT", ntohs (put_msg->header.size), data_size,
483               sizeof (struct GNUNET_DHT_PutMessage));
484   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
485               "`%s': Received `%s' request from client, message type %d, key %s\n",
486               "DHT", "PUT", put_type, GNUNET_h2s (message_context->key));
487 #endif
488   if (datacache != NULL)
489     GNUNET_DATACACHE_put (datacache, message_context->key, data_size,
490                           (char *) &put_msg[1], put_type,
491                           put_msg->expiration);
492 }
493
494
495 /**
496  * Find a client if it exists, add it otherwise.
497  *
498  * @param client the server handle to the client
499  *
500  * @return the client if found, a new client otherwise
501  */
502 static struct ClientList *
503 find_active_client (struct GNUNET_SERVER_Client *client)
504 {
505   struct ClientList *pos = client_list;
506   struct ClientList *ret;
507
508   while (pos != NULL)
509     {
510       if (pos->client_handle == client)
511         return pos;
512       pos = pos->next;
513     }
514
515   ret = GNUNET_malloc (sizeof (struct ClientList));
516   ret->client_handle = client;
517   ret->next = client_list;
518   client_list = ret;
519   return ret;
520 }
521
522 /**
523  * Construct a message receipt confirmation for a particular uid.
524  * Receipt confirmations are used for any requests that don't expect
525  * a reply otherwise (i.e. put requests, stop requests).
526  *
527  * @param client the handle for the client
528  * @param uid the unique identifier of this message
529  */
530 static void
531 send_client_receipt_confirmation (struct GNUNET_SERVER_Client *client,
532                                   uint64_t uid)
533 {
534   struct GNUNET_DHT_StopMessage *confirm_message;
535   struct ClientList *active_client;
536   struct PendingMessage *pending_message;
537
538 #if DEBUG_DHT
539   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
540               "`%s': Sending receipt confirmation for uid %llu\n", "DHT",
541               uid);
542 #endif
543   confirm_message = GNUNET_malloc (sizeof (struct GNUNET_DHT_StopMessage));
544   confirm_message->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_STOP);
545   confirm_message->header.size =
546     htons (sizeof (struct GNUNET_DHT_StopMessage));
547   confirm_message->unique_id = GNUNET_htonll (uid);
548
549   active_client = find_active_client (client);
550   pending_message = GNUNET_malloc (sizeof (struct PendingMessage));
551   pending_message->msg = &confirm_message->header;
552
553   add_pending_message (active_client, pending_message);
554
555 }
556
557 /**
558  * Handler for any generic DHT messages, calls the appropriate handler
559  * depending on message type, sends confirmation if responses aren't otherwise
560  * expected.
561  *
562  * @param cls closure for the service
563  * @param client the client we received this message from
564  * @param message the actual message received
565  */
566 static void
567 handle_dht_start_message (void *cls, struct GNUNET_SERVER_Client *client,
568                           const struct GNUNET_MessageHeader *message)
569 {
570   const struct GNUNET_DHT_Message *dht_msg = (const struct GNUNET_DHT_Message *) message;
571   const struct GNUNET_MessageHeader *enc_msg;
572   struct DHT_MessageContext *message_context;
573   size_t enc_type;
574
575   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
576   enc_type = ntohs (enc_msg->type);
577
578
579 #if DEBUG_DHT
580   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
581               "`%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
582               "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
583               GNUNET_ntohll (dht_msg->unique_id));
584 #endif
585
586   message_context = GNUNET_malloc (sizeof (struct DHT_MessageContext));
587   message_context->client = find_active_client (client);
588   message_context->key = &dht_msg->key;
589   message_context->unique_id = GNUNET_ntohll (dht_msg->unique_id);
590   message_context->replication = ntohl (dht_msg->desired_replication_level);
591   message_context->msg_options = ntohl (dht_msg->options);
592
593   /* FIXME: Implement *remote* DHT operations here (forward request) */
594   /* FIXME: *IF* handling should be local, then do this: */
595   switch (enc_type)
596     {
597     case GNUNET_MESSAGE_TYPE_DHT_GET:
598       handle_dht_get (cls, enc_msg,
599                       message_context);
600       break;
601     case GNUNET_MESSAGE_TYPE_DHT_PUT:
602       handle_dht_put (cls, enc_msg,
603                       message_context);
604       send_client_receipt_confirmation (client,
605                                         GNUNET_ntohll (dht_msg->unique_id));
606       break;
607     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
608       handle_dht_find_peer (cls,
609                             enc_msg,
610                             message_context);
611       break;
612     default:
613       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
614                   "`%s': Message type (%d) not handled\n", "DHT", enc_type);
615     }
616   GNUNET_free (message_context);
617   GNUNET_SERVER_receive_done (client, GNUNET_OK);
618
619 }
620
621 /**
622  * Handler for any generic DHT stop messages, calls the appropriate handler
623  * depending on message type, sends confirmation by default (stop messages
624  * do not otherwise expect replies)
625  *
626  * @param cls closure for the service
627  * @param client the client we received this message from
628  * @param message the actual message received
629  *
630  * TODO: add demultiplexing for stop message types.
631  */
632 static void
633 handle_dht_stop_message (void *cls, struct GNUNET_SERVER_Client *client,
634                          const struct GNUNET_MessageHeader *message)
635 {
636   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
637     (const struct GNUNET_DHT_StopMessage *) message;
638
639 #if DEBUG_DHT
640   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
641               "`%s': Received `%s' request from client, uid %llu\n", "DHT",
642               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
643 #endif
644   /* TODO: actually stop... */
645   GNUNET_SERVER_receive_done (client, GNUNET_OK);
646 }
647
648
649 /**
650  * Core handler for p2p route requests.
651  */
652 static int
653 handle_dht_p2p_route_request (void *cls,
654                               const struct GNUNET_PeerIdentity *peer,
655                               const struct GNUNET_MessageHeader *message,
656                               struct GNUNET_TIME_Relative latency, uint32_t distance)
657 {
658 #if DEBUG_DHT
659   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
660               "`%s': Received `%s' request from another peer\n", "DHT",
661               "GET");
662 #endif
663   // FIXME: setup tracking for sending replies to peer (with timeout)
664   // FIXME: call code from handle_dht_start_message (refactor...)
665   return GNUNET_YES;
666 }
667
668
669 /**
670  * Core handler for p2p route results.
671  */
672 static int
673 handle_dht_p2p_route_result (void *cls,
674                              const struct GNUNET_PeerIdentity *peer,
675                              const struct GNUNET_MessageHeader *message,
676                              struct GNUNET_TIME_Relative latency, uint32_t distance)
677 {
678 #if DEBUG_DHT
679   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
680               "`%s': Received `%s' request from another peer\n", "DHT",
681               "GET");
682 #endif
683   // FIXME: setup tracking for sending replies to peer
684   // FIXME: possibly call code from handle_dht_stop_message? (unique result?) (refactor...)
685   return GNUNET_YES;
686 }
687
688
689 /**
690  * Receive the HELLO from transport service,
691  * free current and replace if necessary.
692  *
693  * @param cls NULL
694  * @param message HELLO message of peer
695  */
696 static void
697 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
698 {
699 #if DEBUG_DHT
700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
701               "Received our `%s' from transport service\n",
702               "HELLO");
703 #endif
704
705   GNUNET_assert (message != NULL);
706   GNUNET_free_non_null(my_hello);
707   my_hello = GNUNET_malloc(ntohs(message->size));
708   memcpy(my_hello, message, ntohs(message->size));
709 }
710
711 /**
712  * Task run during shutdown.
713  *
714  * @param cls unused
715  * @param tc unused
716  */
717 static void
718 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
719 {
720   if (transport_handle != NULL)
721   {
722     GNUNET_free_non_null(my_hello);
723     GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
724     GNUNET_TRANSPORT_disconnect(transport_handle);
725   }
726   if (coreAPI != NULL)
727     GNUNET_CORE_disconnect (coreAPI);
728 }
729
730
731 /**
732  * To be called on core init/fail.
733  *
734  * @param cls service closure
735  * @param server handle to the server for this service
736  * @param identity the public identity of this peer
737  * @param publicKey the public key of this peer
738  */
739 void
740 core_init (void *cls,
741            struct GNUNET_CORE_Handle *server,
742            const struct GNUNET_PeerIdentity *identity,
743            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
744 {
745
746   if (server == NULL)
747     {
748 #if DEBUG_DHT
749   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
750               "%s: Connection to core FAILED!\n", "dht",
751               GNUNET_i2s (identity));
752 #endif
753       GNUNET_SCHEDULER_cancel (sched, cleanup_task);
754       GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
755       return;
756     }
757 #if DEBUG_DHT
758   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
759               "%s: Core connection initialized, I am peer: %s\n", "dht",
760               GNUNET_i2s (identity));
761 #endif
762   /* Copy our identity so we can use it */
763   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
764   /* Set the server to local variable */
765   coreAPI = server;
766 }
767
768
769 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
770   {&handle_dht_start_message, NULL, GNUNET_MESSAGE_TYPE_DHT, 0},
771   {&handle_dht_stop_message, NULL, GNUNET_MESSAGE_TYPE_DHT_STOP, 0},
772   {NULL, NULL, 0, 0}
773 };
774
775
776 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
777   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_ROUTE_REQUEST, 0},
778   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_ROUTE_RESULT, 0},
779   {NULL, 0, 0}
780 };
781
782
783 /**
784  * Process dht requests.
785  *
786  * @param cls closure
787  * @param scheduler scheduler to use
788  * @param server the initialized server
789  * @param c configuration to use
790  */
791 static void
792 run (void *cls,
793      struct GNUNET_SCHEDULER_Handle *scheduler,
794      struct GNUNET_SERVER_Handle *server,
795      const struct GNUNET_CONFIGURATION_Handle *c)
796 {
797   sched = scheduler;
798   cfg = c;
799   datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
800   GNUNET_SERVER_add_handlers (server, plugin_handlers);
801   coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
802                                  cfg,   /* Main configuration */
803                                  GNUNET_TIME_UNIT_FOREVER_REL,
804                                  NULL,  /* FIXME: anything we want to pass around? */
805                                  &core_init,    /* Call core_init once connected */
806                                  NULL,  /* Don't care about pre-connects */
807                                  NULL,  /* Don't care about connects */
808                                  NULL,  /* Don't care about disconnects */
809                                  NULL,  /* Don't want notified about all incoming messages */
810                                  GNUNET_NO,     /* For header only inbound notification */
811                                  NULL,  /* Don't want notified about all outbound messages */
812                                  GNUNET_NO,     /* For header only outbound notification */
813                                  core_handlers);        /* Register these handlers */
814   if (coreAPI == NULL)
815     return;
816   transport_handle = GNUNET_TRANSPORT_connect(sched, cfg, NULL, NULL, NULL, NULL);
817   if (transport_handle != NULL)
818     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
819   else
820     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
821   /* Scheduled the task to clean up when shutdown is called */
822   cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
823                                                GNUNET_TIME_UNIT_FOREVER_REL,
824                                                &shutdown_task, NULL);
825 }
826
827
828 /**
829  * The main function for the dht service.
830  *
831  * @param argc number of arguments from the command line
832  * @param argv command line arguments
833  * @return 0 ok, 1 on error
834  */
835 int
836 main (int argc, char *const *argv)
837 {
838   return (GNUNET_OK ==
839           GNUNET_SERVICE_run (argc,
840                               argv,
841                               "dht",
842                               GNUNET_SERVICE_OPTION_NONE,
843                               &run, NULL)) ? 0 : 1;
844 }