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