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