9ab15ea627a595159b03b0d83b2caaa326e96de3
[oweals/gnunet.git] / src / dv / dv_api.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 dv/dv_api.c
23  * @brief library to access the DV service
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  */
27 #include "platform.h"
28 #include "gnunet_bandwidth_lib.h"
29 #include "gnunet_client_lib.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_container_lib.h"
32 #include "gnunet_arm_service.h"
33 #include "gnunet_hello_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_server_lib.h"
36 #include "gnunet_time_lib.h"
37 #include "gnunet_dv_service.h"
38 #include "dv.h"
39 #include "../transport/plugin_transport.h"
40
41
42 struct PendingMessages
43 {
44   /**
45    * Linked list of pending messages
46    */
47   struct PendingMessages *next;
48
49   /**
50    * Message that is pending
51    */
52   struct GNUNET_DV_SendMessage *msg;
53
54   /**
55    * Timeout for this message
56    */
57   struct GNUNET_TIME_Absolute timeout;
58
59 };
60
61
62
63 /**
64  * Handle for the service.
65  */
66 struct GNUNET_DV_Handle
67 {
68   /**
69    * Our scheduler.
70    */
71   struct GNUNET_SCHEDULER_Handle *sched;
72
73   /**
74    * Configuration to use.
75    */
76   const struct GNUNET_CONFIGURATION_Handle *cfg;
77
78   /**
79    * Socket (if available).
80    */
81   struct GNUNET_CLIENT_Connection *client;
82
83   /**
84    * Currently pending transmission request.
85    */
86   struct GNUNET_CLIENT_TransmitHandle *th;
87
88   /**
89    * List of the currently pending messages for the DV service.
90    */
91   struct PendingMessages *pending_list;
92
93   /**
94    * Message we are currently sending.
95    */
96   struct PendingMessages *current;
97
98   /**
99    * Kill off the connection and any pending messages.
100    */
101   int do_destroy;
102
103   /**
104    * Handler for messages we receive from the DV service
105    */
106   GNUNET_DV_MessageReceivedHandler receive_handler;
107
108   /**
109    * Closure for the receive handler
110    */
111   void *receive_cls;
112
113   /**
114    * Current unique ID
115    */
116   uint32_t uid_gen;
117
118   /**
119    * Hashmap containing outstanding send requests awaiting confirmation.
120    */
121   struct GNUNET_CONTAINER_MultiHashMap *send_callbacks;
122
123 };
124
125
126 struct StartContext
127 {
128   /**
129    * Start message
130    */
131   struct GNUNET_MessageHeader *message;
132
133   /**
134    * Handle to service, in case of timeout
135    */
136   struct GNUNET_DV_Handle *handle;
137 };
138
139 struct SendCallbackContext
140 {
141   /**
142    * The continuation to call once a message is confirmed sent (or failed)
143    */
144   GNUNET_TRANSPORT_TransmitContinuation cont;
145
146   /**
147    * Closure to call with send continuation.
148    */
149   void *cont_cls;
150
151   /**
152    * Target of the message.
153    */
154   struct GNUNET_PeerIdentity target;
155 };
156
157 /**
158  * Convert unique ID to hash code.
159  *
160  * @param uid unique ID to convert
161  * @param hash set to uid (extended with zeros)
162  */
163 static void
164 hash_from_uid (uint32_t uid,
165                GNUNET_HashCode *hash)
166 {
167   memset (hash, 0, sizeof(GNUNET_HashCode));
168   *((uint32_t*)hash) = uid;
169 }
170
171 /**
172  * Try to (re)connect to the dv service.
173  *
174  * @return GNUNET_YES on success, GNUNET_NO on failure.
175  */
176 static int
177 try_connect (struct GNUNET_DV_Handle *ret)
178 {
179   if (ret->client != NULL)
180     return GNUNET_OK;
181   ret->client = GNUNET_CLIENT_connect (ret->sched, "dv", ret->cfg);
182   if (ret->client != NULL)
183     return GNUNET_YES;
184 #if DEBUG_STATISTICS
185   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
186               _("Failed to connect to the dv service!\n"));
187 #endif
188   return GNUNET_NO;
189 }
190
191 static void process_pending_message(struct GNUNET_DV_Handle *handle);
192
193 /**
194  * Send complete, schedule next
195  */
196 static void
197 finish (struct GNUNET_DV_Handle *handle, int code)
198 {
199   struct PendingMessages *pos = handle->current;
200   handle->current = NULL;
201   process_pending_message (handle);
202
203   GNUNET_free(pos->msg);
204   GNUNET_free (pos);
205 }
206
207
208 static size_t
209 transmit_pending (void *cls, size_t size, void *buf)
210 {
211   struct GNUNET_DV_Handle *handle = cls;
212   size_t ret;
213   size_t tsize;
214
215 #if DEBUG_DV
216   if (handle->current != NULL)
217     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DV API: Transmit pending called with message type %d\n", ntohs(handle->current->msg->header.type));
218 #endif
219
220   if (buf == NULL)
221     {
222 #if DEBUG_DV
223       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DV API: Transmit pending FAILED!\n\n\n");
224 #endif
225       finish(handle, GNUNET_SYSERR);
226       return 0;
227     }
228   handle->th = NULL;
229
230   ret = 0;
231
232   if (handle->current != NULL)
233   {
234     tsize = ntohs(handle->current->msg->header.size);
235     if (size >= tsize)
236     {
237       memcpy(buf, handle->current->msg, tsize);
238 #if DEBUG_DV
239       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DV API: Copied %d bytes into buffer!\n\n\n", tsize);
240 #endif
241       finish(handle, GNUNET_OK);
242       return tsize;
243     }
244
245   }
246
247   return ret;
248 }
249
250 /**
251  * Try to send messages from list of messages to send
252  */
253 static void process_pending_message(struct GNUNET_DV_Handle *handle)
254 {
255
256   if (handle->current != NULL)
257     return;                     /* action already pending */
258   if (GNUNET_YES != try_connect (handle))
259     {
260       finish (handle, GNUNET_SYSERR);
261       return;
262     }
263
264   /* schedule next action */
265   handle->current = handle->pending_list;
266   if (NULL == handle->current)
267     {
268       if (handle->do_destroy)
269         {
270           handle->do_destroy = GNUNET_NO;
271           //GNUNET_DV_disconnect (handle); /* FIXME: replace with proper disconnect stuffs */
272         }
273       return;
274     }
275   handle->pending_list = handle->pending_list->next;
276   handle->current->next = NULL;
277
278   if (NULL ==
279       (handle->th = GNUNET_CLIENT_notify_transmit_ready (handle->client,
280                                                     ntohl(handle->current->msg->msgbuf_size),
281                                                     handle->current->msg->timeout,
282                                                     GNUNET_YES,
283                                                     &transmit_pending, handle)))
284     {
285 #if DEBUG_DV
286       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
287                   "Failed to transmit request to dv service.\n");
288 #endif
289       finish (handle, GNUNET_SYSERR);
290     }
291 }
292
293 /**
294  * Add a pending message to the linked list
295  *
296  * @param handle handle to the specified DV api
297  * @param msg the message to add to the list
298  */
299 static void add_pending(struct GNUNET_DV_Handle *handle, struct GNUNET_DV_SendMessage *msg)
300 {
301   struct PendingMessages *new_message;
302   struct PendingMessages *pos;
303   struct PendingMessages *last;
304
305   new_message = GNUNET_malloc(sizeof(struct PendingMessages));
306   new_message->msg = msg;
307
308   if (handle->pending_list != NULL)
309     {
310       pos = handle->pending_list;
311       while(pos != NULL)
312         {
313           last = pos;
314           pos = pos->next;
315         }
316       last->next = new_message;
317     }
318   else
319     {
320       handle->pending_list = new_message;
321     }
322
323   process_pending_message(handle);
324 }
325
326 /**
327  * Handles a message sent from the DV service to us.
328  * Parse it out and give it to the plugin.
329  *
330  * @param cls the handle to the DV API
331  * @param msg the message that was received
332  */
333 void handle_message_receipt (void *cls,
334                              const struct GNUNET_MessageHeader * msg)
335 {
336   struct GNUNET_DV_Handle *handle = cls;
337   struct GNUNET_DV_MessageReceived *received_msg;
338   struct GNUNET_DV_SendResultMessage *send_result_msg;
339   size_t packed_msg_len;
340   size_t sender_address_len;
341   char *sender_address;
342   char *packed_msg;
343   char *packed_msg_start;
344   GNUNET_HashCode uidhash;
345   struct SendCallbackContext *send_ctx;
346
347   if (msg == NULL)
348   {
349     return; /* Connection closed? */
350   }
351
352   GNUNET_assert((ntohs(msg->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_DV_RECEIVE) || (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_DV_SEND_RESULT));
353
354   switch (ntohs(msg->type))
355   {
356   case GNUNET_MESSAGE_TYPE_TRANSPORT_DV_RECEIVE:
357     if (ntohs(msg->size) < sizeof(struct GNUNET_DV_MessageReceived))
358       return;
359
360     received_msg = (struct GNUNET_DV_MessageReceived *)msg;
361     packed_msg_len = ntohl(received_msg->msg_len);
362     sender_address_len = ntohl(received_msg->sender_address_len);
363
364     GNUNET_assert(ntohs(msg->size) == (sizeof(struct GNUNET_DV_MessageReceived) + packed_msg_len + sender_address_len));
365     sender_address = GNUNET_malloc(sender_address_len);
366     memcpy(sender_address, &received_msg[1], sender_address_len);
367     packed_msg_start = (char *)&received_msg[1];
368     packed_msg = GNUNET_malloc(packed_msg_len);
369     memcpy(packed_msg, &packed_msg_start[sender_address_len], packed_msg_len);
370
371 #if DEBUG_DV
372     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DV_API receive: packed message type: %d or %d\n", ntohs(((struct GNUNET_MessageHeader *)packed_msg)->type), ((struct GNUNET_MessageHeader *)packed_msg)->type);
373     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DV_API receive: message sender reported as %s\n", GNUNET_i2s(&received_msg->sender));
374     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DV_API receive: distance is %u\n", ntohl(received_msg->distance));
375 #endif
376
377     handle->receive_handler(handle->receive_cls,
378                             &received_msg->sender,
379                             packed_msg,
380                             packed_msg_len,
381                             ntohl(received_msg->distance),
382                             sender_address,
383                             sender_address_len);
384
385     GNUNET_free(sender_address);
386     break;
387   case GNUNET_MESSAGE_TYPE_TRANSPORT_DV_SEND_RESULT:
388     if (ntohs(msg->size) < sizeof(struct GNUNET_DV_SendResultMessage))
389       return;
390
391     send_result_msg = (struct GNUNET_DV_SendResultMessage *)msg;
392     hash_from_uid(ntohl(send_result_msg->uid), &uidhash);
393     send_ctx = GNUNET_CONTAINER_multihashmap_get(handle->send_callbacks, &uidhash);
394
395     if ((send_ctx != NULL) && (send_ctx->cont != NULL))
396       {
397         if (ntohl(send_result_msg->result) == 0)
398           {
399             send_ctx->cont(send_ctx->cont_cls, &send_ctx->target, GNUNET_OK);
400           }
401         else
402           {
403             send_ctx->cont(send_ctx->cont_cls, &send_ctx->target, GNUNET_SYSERR);
404           }
405       }
406     GNUNET_free_non_null(send_ctx);
407     break;
408   default:
409     break;
410   }
411   GNUNET_CLIENT_receive (handle->client,
412                          &handle_message_receipt,
413                          handle, GNUNET_TIME_UNIT_FOREVER_REL);
414 }
415
416 /**
417  * Send a message from the plugin to the DV service indicating that
418  * a message should be sent via DV to some peer.
419  *
420  * @param dv_handle the handle to the DV api
421  * @param target the final target of the message
422  * @param msgbuf the msg(s) to send
423  * @param msgbuf_size the size of msgbuf
424  * @param priority priority to pass on to core when sending the message
425  * @param timeout how long can this message be delayed (pass through to core)
426  * @param addr the address of this peer (internally known to DV)
427  * @param addrlen the length of the peer address
428  * @param cont continuation to call once the message has been sent (or failed)
429  * @param cont_cls closure for continuation
430  *
431  */
432 int GNUNET_DV_send (struct GNUNET_DV_Handle *dv_handle,
433                     const struct GNUNET_PeerIdentity *target,
434                     const char *msgbuf,
435                     size_t msgbuf_size,
436                     unsigned int priority,
437                     struct GNUNET_TIME_Relative timeout,
438                     const void *addr,
439                     size_t addrlen,
440                     GNUNET_TRANSPORT_TransmitContinuation
441                     cont, void *cont_cls)
442 {
443   struct GNUNET_DV_SendMessage *msg;
444   struct SendCallbackContext *send_ctx;
445   char *end_of_message;
446   GNUNET_HashCode uidhash;
447   int msize;
448 #if DEBUG_DV_MESSAGES
449   dv_handle->uid_gen = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
450 #else
451   dv_handle->uid_gen++;
452 #endif
453
454   msize = sizeof(struct GNUNET_DV_SendMessage) + addrlen + msgbuf_size;
455   msg = GNUNET_malloc(msize);
456   msg->header.size = htons(msize);
457   msg->header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_DV_SEND);
458   memcpy(&msg->target, target, sizeof(struct GNUNET_PeerIdentity));
459   msg->msgbuf_size = htonl(msgbuf_size);
460   msg->priority = htonl(priority);
461   msg->timeout = timeout;
462   msg->addrlen = htonl(addrlen);
463   msg->uid = htonl(dv_handle->uid_gen);
464   memcpy(&msg[1], addr, addrlen);
465   end_of_message = (char *)&msg[1];
466   end_of_message = &end_of_message[addrlen];
467   memcpy(end_of_message, msgbuf, msgbuf_size);
468   add_pending(dv_handle, msg);
469   send_ctx = GNUNET_malloc(sizeof(struct SendCallbackContext));
470   send_ctx->cont = cont;
471   send_ctx->cont_cls = cont_cls;
472   memcpy(&send_ctx->target, target, sizeof(struct GNUNET_PeerIdentity));
473   hash_from_uid(dv_handle->uid_gen, &uidhash);
474   GNUNET_CONTAINER_multihashmap_put(dv_handle->send_callbacks, &uidhash, send_ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
475
476   return GNUNET_OK;
477 }
478
479 /* Forward declaration */
480 void GNUNET_DV_disconnect(struct GNUNET_DV_Handle *handle);
481
482 static size_t
483 transmit_start (void *cls, size_t size, void *buf)
484 {
485   struct StartContext *start_context = cls;
486   struct GNUNET_DV_Handle *handle = start_context->handle;
487   size_t tsize;
488
489   if (buf == NULL)
490     {
491       GNUNET_free(start_context->message);
492       GNUNET_free(start_context);
493       GNUNET_DV_disconnect(handle);
494       return 0;
495     }
496
497   tsize = ntohs(start_context->message->size);
498   if (size >= tsize)
499   {
500     memcpy(buf, start_context->message, tsize);
501     GNUNET_free(start_context->message);
502     GNUNET_free(start_context);
503     return tsize;
504   }
505
506   return 0;
507 }
508
509 /**
510  * Connect to the DV service
511  *
512  * @param sched the scheduler to use
513  * @param cfg the configuration to use
514  * @param receive_handler method call when on receipt from the service
515  * @param receive_handler_cls closure for receive_handler
516  *
517  * @return handle to the DV service
518  */
519 struct GNUNET_DV_Handle *
520 GNUNET_DV_connect (struct GNUNET_SCHEDULER_Handle *sched,
521                   const struct GNUNET_CONFIGURATION_Handle *cfg,
522                   GNUNET_DV_MessageReceivedHandler receive_handler,
523                   void *receive_handler_cls)
524 {
525   struct GNUNET_DV_Handle *handle;
526   struct GNUNET_MessageHeader *start_message;
527   struct StartContext *start_context;
528   handle = GNUNET_malloc(sizeof(struct GNUNET_DV_Handle));
529
530   handle->cfg = cfg;
531   handle->sched = sched;
532   handle->pending_list = NULL;
533   handle->current = NULL;
534   handle->do_destroy = GNUNET_NO;
535   handle->th = NULL;
536   handle->client = GNUNET_CLIENT_connect(sched, "dv", cfg);
537   handle->receive_handler = receive_handler;
538   handle->receive_cls = receive_handler_cls;
539
540   if (handle->client == NULL)
541     {
542       GNUNET_free(handle);
543       return NULL;
544     }
545
546   start_message = GNUNET_malloc(sizeof(struct GNUNET_MessageHeader));
547   start_message->size = htons(sizeof(struct GNUNET_MessageHeader));
548   start_message->type = htons(GNUNET_MESSAGE_TYPE_DV_START);
549
550   start_context = GNUNET_malloc(sizeof(struct StartContext));
551   start_context->handle = handle;
552   start_context->message = start_message;
553   GNUNET_CLIENT_notify_transmit_ready (handle->client,
554                                        sizeof(struct GNUNET_MessageHeader),
555                                        GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60),
556                                        GNUNET_YES,
557                                        &transmit_start, start_context);
558
559   handle->send_callbacks = GNUNET_CONTAINER_multihashmap_create(100);
560
561   GNUNET_CLIENT_receive (handle->client,
562                          &handle_message_receipt,
563                          handle, GNUNET_TIME_UNIT_FOREVER_REL);
564
565   return handle;
566 }
567
568 /**
569  * Disconnect from the DV service
570  *
571  * @param handle the current handle to the service to disconnect
572  */
573 void GNUNET_DV_disconnect(struct GNUNET_DV_Handle *handle)
574 {
575   struct PendingMessages *pos;
576
577   GNUNET_assert(handle != NULL);
578
579   if (handle->th != NULL) /* We have a live transmit request in the Aether */
580     {
581       GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
582       handle->th = NULL;
583     }
584   if (handle->current != NULL) /* We are trying to send something now, clean it up */
585     GNUNET_free(handle->current);
586   while (NULL != (pos = handle->pending_list)) /* Remove all pending sends from the list */
587     {
588       handle->pending_list = pos->next;
589       GNUNET_free(pos);
590     }
591   if (handle->client != NULL) /* Finally, disconnect from the service */
592     {
593       GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
594       handle->client = NULL;
595     }
596
597   GNUNET_free (handle);
598 }
599
600 /* end of dv_api.c */