- fix state selection
[oweals/gnunet.git] / src / dv / dv_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009--2013 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_util_lib.h"
29 #include "gnunet_dv_service.h"
30 #include "gnunet_protocols.h"
31 #include "dv.h"
32 #include "gnunet_transport_plugin.h"
33
34 #define LOG(kind,...) GNUNET_log_from (kind, "dv-api",__VA_ARGS__)
35
36
37 /**
38  * Information we track for each peer.
39  */
40 struct ConnectedPeer;
41
42
43 /**
44  * Handle for a send operation.
45  */
46 struct GNUNET_DV_TransmitHandle
47 {
48   /**
49    * Kept in a DLL.
50    */
51   struct GNUNET_DV_TransmitHandle *next;
52
53   /**
54    * Kept in a DLL.
55    */
56   struct GNUNET_DV_TransmitHandle *prev;
57
58   /**
59    * Handle to the service.
60    */
61   struct GNUNET_DV_ServiceHandle *sh;
62
63   /**
64    * Function to call upon completion.
65    */
66   GNUNET_DV_MessageSentCallback cb;
67
68   /**
69    * Closure for @a cb.
70    */
71   void *cb_cls;
72
73   /**
74    * The actual message (allocated at the end of this struct).
75    */
76   const struct GNUNET_MessageHeader *msg;
77
78   /**
79    * Destination for the message.
80    */
81   struct ConnectedPeer *target;
82
83   /**
84    * UID of our message, if any.
85    */
86   uint32_t uid;
87
88 };
89
90
91 /**
92  * Information we track for each peer.
93  */
94 struct ConnectedPeer
95 {
96
97   /**
98    * Identity of the peer.
99    */
100   struct GNUNET_PeerIdentity pid;
101
102   /**
103    * Head of DLL of transmission handles where we need
104    * to invoke a continuation when we are informed about
105    * successful transmission.  The respective request
106    * has already been sent to the DV service.
107    */
108   struct GNUNET_DV_TransmitHandle *head;
109
110   /**
111    * Tail of DLL of transmission handles where we need
112    * to invoke a continuation when we are informed about
113    * successful transmission.  The respective request
114    * has already been sent to the DV service.
115    */
116   struct GNUNET_DV_TransmitHandle *tail;
117
118 };
119
120
121 /**
122  * Handle to the DV service.
123  */
124 struct GNUNET_DV_ServiceHandle
125 {
126
127   /**
128    * Connection to DV service.
129    */
130   struct GNUNET_CLIENT_Connection *client;
131
132   /**
133    * Active request for transmission to DV service.
134    */
135   struct GNUNET_CLIENT_TransmitHandle *th;
136
137   /**
138    * Our configuration.
139    */
140   const struct GNUNET_CONFIGURATION_Handle *cfg;
141
142   /**
143    * Closure for the callbacks.
144    */
145   void *cls;
146
147   /**
148    * Function to call on connect events.
149    */
150   GNUNET_DV_ConnectCallback connect_cb;
151
152   /**
153    * Function to call on distance change events.
154    */
155   GNUNET_DV_DistanceChangedCallback distance_cb;
156
157   /**
158    * Function to call on disconnect events.
159    */
160   GNUNET_DV_DisconnectCallback disconnect_cb;
161
162   /**
163    * Function to call on receiving messages events.
164    */
165   GNUNET_DV_MessageReceivedCallback message_cb;
166
167   /**
168    * Head of messages to transmit.
169    */
170   struct GNUNET_DV_TransmitHandle *th_head;
171
172   /**
173    * Tail of messages to transmit.
174    */
175   struct GNUNET_DV_TransmitHandle *th_tail;
176
177   /**
178    * Information tracked per connected peer.  Maps peer
179    * identities to `struct ConnectedPeer` entries.
180    */
181   struct GNUNET_CONTAINER_MultiPeerMap *peers;
182
183   /**
184    * Current unique ID
185    */
186   uint32_t uid_gen;
187
188 };
189
190
191 /**
192  * Disconnect and then reconnect to the DV service.
193  *
194  * @param sh service handle
195  */
196 static void
197 reconnect (struct GNUNET_DV_ServiceHandle *sh);
198
199
200 /**
201  * Gives a message from our queue to the DV service.
202  *
203  * @param cls handle to the dv service (struct GNUNET_DV_ServiceHandle)
204  * @param size how many bytes can we send
205  * @param buf where to copy the message to send
206  * @return how many bytes we copied to @a buf
207  */
208 static size_t
209 transmit_pending (void *cls, size_t size, void *buf)
210 {
211   struct GNUNET_DV_ServiceHandle *sh = cls;
212   char *cbuf = buf;
213   struct GNUNET_DV_TransmitHandle *th;
214   size_t ret;
215   size_t tsize;
216
217   sh->th = NULL;
218   if (NULL == buf)
219   {
220     reconnect (sh);
221     return 0;
222   }
223   ret = 0;
224   while ( (NULL != (th = sh->th_head)) &&
225           (size - ret >= (tsize = ntohs (th->msg->size)) ))
226   {
227     GNUNET_CONTAINER_DLL_remove (sh->th_head,
228                                  sh->th_tail,
229                                  th);
230     memcpy (&cbuf[ret], th->msg, tsize);
231     th->msg = NULL;
232     ret += tsize;
233     if (NULL != th->cb)
234     {
235       GNUNET_CONTAINER_DLL_insert (th->target->head,
236                                    th->target->tail,
237                                    th);
238     }
239     else
240     {
241       GNUNET_free (th);
242     }
243   }
244   return ret;
245 }
246
247
248 /**
249  * Start sending messages from our queue to the service.
250  *
251  * @param sh service handle
252  */
253 static void
254 start_transmit (struct GNUNET_DV_ServiceHandle *sh)
255 {
256   if (NULL != sh->th)
257     return;
258   if (NULL == sh->th_head)
259     return;
260   sh->th =
261     GNUNET_CLIENT_notify_transmit_ready (sh->client,
262                                          ntohs (sh->th_head->msg->size),
263                                          GNUNET_TIME_UNIT_FOREVER_REL,
264                                          GNUNET_NO,
265                                          &transmit_pending, sh);
266 }
267
268
269 /**
270  * We got disconnected from the service and thus all of the
271  * pending send callbacks will never be confirmed.  Clean up.
272  *
273  * @param cls the 'struct GNUNET_DV_ServiceHandle'
274  * @param key a peer identity
275  * @param value a `struct ConnectedPeer` to clean up
276  * @return #GNUNET_OK (continue to iterate)
277  */
278 static int
279 cleanup_send_cb (void *cls,
280                  const struct GNUNET_PeerIdentity *key,
281                  void *value)
282 {
283   struct GNUNET_DV_ServiceHandle *sh = cls;
284   struct ConnectedPeer *peer = value;
285   struct GNUNET_DV_TransmitHandle *th;
286
287   GNUNET_assert (GNUNET_YES ==
288                  GNUNET_CONTAINER_multipeermap_remove (sh->peers,
289                                                        key,
290                                                        peer));
291   sh->disconnect_cb (sh->cls,
292                      key);
293   while (NULL != (th = peer->head))
294   {
295     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, th);
296     th->cb (th->cb_cls, GNUNET_SYSERR);
297     GNUNET_free (th);
298   }
299   GNUNET_free (peer);
300   return GNUNET_OK;
301 }
302
303
304 /**
305  * Handles a message sent from the DV service to us.
306  * Parse it out and give it to the plugin.
307  *
308  * @param cls the handle to the DV API
309  * @param msg the message that was received
310  */
311 static void
312 handle_message_receipt (void *cls,
313                         const struct GNUNET_MessageHeader *msg)
314 {
315   struct GNUNET_DV_ServiceHandle *sh = cls;
316   const struct GNUNET_DV_ConnectMessage *cm;
317   const struct GNUNET_DV_DistanceUpdateMessage *dum;
318   const struct GNUNET_DV_DisconnectMessage *dm;
319   const struct GNUNET_DV_ReceivedMessage *rm;
320   const struct GNUNET_MessageHeader *payload;
321   const struct GNUNET_DV_AckMessage *ack;
322   struct GNUNET_DV_TransmitHandle *th;
323   struct GNUNET_DV_TransmitHandle *tn;
324   struct ConnectedPeer *peer;
325
326   if (NULL == msg)
327   {
328     /* Connection closed */
329     reconnect (sh);
330     return;
331   }
332   LOG (GNUNET_ERROR_TYPE_DEBUG,
333        "Received message of type %u from DV service\n",
334        (unsigned int) msg->type);
335   switch (ntohs (msg->type))
336   {
337   case GNUNET_MESSAGE_TYPE_DV_CONNECT:
338     if (ntohs (msg->size) != sizeof (struct GNUNET_DV_ConnectMessage))
339     {
340       GNUNET_break (0);
341       reconnect (sh);
342       return;
343     }
344     cm = (const struct GNUNET_DV_ConnectMessage *) msg;
345     peer = GNUNET_CONTAINER_multipeermap_get (sh->peers,
346                                               &cm->peer);
347     if (NULL != peer)
348     {
349       GNUNET_break (0);
350       reconnect (sh);
351       return;
352     }
353     peer = GNUNET_new (struct ConnectedPeer);
354     peer->pid = cm->peer;
355     GNUNET_assert (GNUNET_OK ==
356                    GNUNET_CONTAINER_multipeermap_put (sh->peers,
357                                                       &peer->pid,
358                                                       peer,
359                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
360     sh->connect_cb (sh->cls,
361                     &cm->peer,
362                     ntohl (cm->distance),
363                     (enum GNUNET_ATS_Network_Type) ntohl (cm->network));
364     break;
365   case GNUNET_MESSAGE_TYPE_DV_DISTANCE_CHANGED:
366     if (ntohs (msg->size) != sizeof (struct GNUNET_DV_DistanceUpdateMessage))
367     {
368       GNUNET_break (0);
369       reconnect (sh);
370       return;
371     }
372     dum = (const struct GNUNET_DV_DistanceUpdateMessage *) msg;
373     sh->distance_cb (sh->cls,
374                      &dum->peer,
375                      ntohl (dum->distance),
376                      (enum GNUNET_ATS_Network_Type) ntohl (dum->network));
377     break;
378   case GNUNET_MESSAGE_TYPE_DV_DISCONNECT:
379     if (ntohs (msg->size) != sizeof (struct GNUNET_DV_DisconnectMessage))
380     {
381       GNUNET_break (0);
382       reconnect (sh);
383       return;
384     }
385     dm = (const struct GNUNET_DV_DisconnectMessage *) msg;
386     peer = GNUNET_CONTAINER_multipeermap_get (sh->peers,
387                                               &dm->peer);
388     if (NULL == peer)
389     {
390       GNUNET_break (0);
391       reconnect (sh);
392       return;
393     }
394     tn = sh->th_head;
395     while (NULL != (th = tn))
396     {
397       tn = th->next;
398       if (peer == th->target)
399       {
400         GNUNET_CONTAINER_DLL_remove (sh->th_head,
401                                      sh->th_tail,
402                                      th);
403         th->cb (th->cb_cls, GNUNET_SYSERR);
404         GNUNET_free (th);
405       }
406     }
407     cleanup_send_cb (sh, &dm->peer, peer);
408     break;
409   case GNUNET_MESSAGE_TYPE_DV_RECV:
410     if (ntohs (msg->size) < sizeof (struct GNUNET_DV_ReceivedMessage) + sizeof (struct GNUNET_MessageHeader))
411     {
412       GNUNET_break (0);
413       reconnect (sh);
414       return;
415     }
416     rm = (const struct GNUNET_DV_ReceivedMessage *) msg;
417     payload = (const struct GNUNET_MessageHeader *) &rm[1];
418     if (ntohs (msg->size) != sizeof (struct GNUNET_DV_ReceivedMessage) + ntohs (payload->size))
419     {
420       GNUNET_break (0);
421       reconnect (sh);
422       return;
423     }
424     sh->message_cb (sh->cls,
425                     &rm->sender,
426                     ntohl (rm->distance),
427                     payload);
428     break;
429   case GNUNET_MESSAGE_TYPE_DV_SEND_ACK:
430   case GNUNET_MESSAGE_TYPE_DV_SEND_NACK:
431     if (ntohs (msg->size) != sizeof (struct GNUNET_DV_AckMessage))
432     {
433       GNUNET_break (0);
434       reconnect (sh);
435       return;
436     }
437     ack = (const struct GNUNET_DV_AckMessage *) msg;
438     peer = GNUNET_CONTAINER_multipeermap_get (sh->peers,
439                                               &ack->target);
440     if (NULL == peer)
441       return; /* this happens, just ignore */
442     for (th = peer->head; NULL != th; th = th->next)
443     {
444       if (th->uid != ntohl (ack->uid))
445         continue;
446       LOG (GNUNET_ERROR_TYPE_DEBUG,
447            "Matched ACK for message to peer %s\n",
448            GNUNET_i2s (&ack->target));
449       GNUNET_CONTAINER_DLL_remove (peer->head,
450                                    peer->tail,
451                                    th);
452       th->cb (th->cb_cls,
453               (ntohs (ack->header.type) == GNUNET_MESSAGE_TYPE_DV_SEND_ACK)
454               ? GNUNET_OK
455               : GNUNET_SYSERR);
456       GNUNET_free (th);
457       break;
458     }
459     break;
460   default:
461     reconnect (sh);
462     break;
463   }
464   GNUNET_CLIENT_receive (sh->client,
465                          &handle_message_receipt, sh,
466                          GNUNET_TIME_UNIT_FOREVER_REL);
467 }
468
469
470 /**
471  * Transmit the start message to the DV service.
472  *
473  * @param cls the `struct GNUNET_DV_ServiceHandle *`
474  * @param size number of bytes available in buf
475  * @param buf where to copy the message
476  * @return number of bytes written to buf
477  */
478 static size_t
479 transmit_start (void *cls,
480                 size_t size,
481                 void *buf)
482 {
483   struct GNUNET_DV_ServiceHandle *sh = cls;
484   struct GNUNET_MessageHeader start_message;
485
486   sh->th = NULL;
487   if (NULL == buf)
488   {
489     GNUNET_break (0);
490     reconnect (sh);
491     return 0;
492   }
493   GNUNET_assert (size >= sizeof (start_message));
494   start_message.size = htons (sizeof (struct GNUNET_MessageHeader));
495   start_message.type = htons (GNUNET_MESSAGE_TYPE_DV_START);
496   memcpy (buf, &start_message, sizeof (start_message));
497   GNUNET_CLIENT_receive (sh->client,
498                          &handle_message_receipt, sh,
499                          GNUNET_TIME_UNIT_FOREVER_REL);
500   start_transmit (sh);
501   return sizeof (start_message);
502 }
503
504
505 /**
506  * Disconnect and then reconnect to the DV service.
507  *
508  * @param sh service handle
509  */
510 static void
511 reconnect (struct GNUNET_DV_ServiceHandle *sh)
512 {
513   if (NULL != sh->th)
514   {
515     GNUNET_CLIENT_notify_transmit_ready_cancel (sh->th);
516     sh->th = NULL;
517   }
518   if (NULL != sh->client)
519   {
520     GNUNET_CLIENT_disconnect (sh->client);
521     sh->client = NULL;
522   }
523   GNUNET_CONTAINER_multipeermap_iterate (sh->peers,
524                                          &cleanup_send_cb,
525                                          sh);
526   LOG (GNUNET_ERROR_TYPE_DEBUG,
527        "Connecting to DV service\n");
528   sh->client = GNUNET_CLIENT_connect ("dv", sh->cfg);
529   if (NULL == sh->client)
530   {
531     GNUNET_break (0);
532     return;
533   }
534   sh->th = GNUNET_CLIENT_notify_transmit_ready (sh->client,
535                                                 sizeof (struct GNUNET_MessageHeader),
536                                                 GNUNET_TIME_UNIT_FOREVER_REL,
537                                                 GNUNET_YES,
538                                                 &transmit_start,
539                                                 sh);
540 }
541
542
543 /**
544  * Connect to the DV service.
545  *
546  * @param cfg configuration
547  * @param cls closure for callbacks
548  * @param connect_cb function to call on connects
549  * @param distance_cb function to call if distances change
550  * @param disconnect_cb function to call on disconnects
551  * @param message_cb function to call if we receive messages
552  * @return handle to access the service
553  */
554 struct GNUNET_DV_ServiceHandle *
555 GNUNET_DV_service_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
556                            void *cls,
557                            GNUNET_DV_ConnectCallback connect_cb,
558                            GNUNET_DV_DistanceChangedCallback distance_cb,
559                            GNUNET_DV_DisconnectCallback disconnect_cb,
560                            GNUNET_DV_MessageReceivedCallback message_cb)
561 {
562   struct GNUNET_DV_ServiceHandle *sh;
563
564   sh = GNUNET_new (struct GNUNET_DV_ServiceHandle);
565   sh->cfg = cfg;
566   sh->cls = cls;
567   sh->connect_cb = connect_cb;
568   sh->distance_cb = distance_cb;
569   sh->disconnect_cb = disconnect_cb;
570   sh->message_cb = message_cb;
571   sh->peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
572   reconnect (sh);
573   return sh;
574 }
575
576
577 /**
578  * Disconnect from DV service.
579  *
580  * @param sh service handle
581  */
582 void
583 GNUNET_DV_service_disconnect (struct GNUNET_DV_ServiceHandle *sh)
584 {
585   struct GNUNET_DV_TransmitHandle *pos;
586
587   if (NULL == sh)
588     return;
589   if (NULL != sh->th)
590   {
591     GNUNET_CLIENT_notify_transmit_ready_cancel (sh->th);
592     sh->th = NULL;
593   }
594   while (NULL != (pos = sh->th_head))
595   {
596     GNUNET_CONTAINER_DLL_remove (sh->th_head,
597                                  sh->th_tail,
598                                  pos);
599     GNUNET_free (pos);
600   }
601   if (NULL != sh->client)
602   {
603     GNUNET_CLIENT_disconnect (sh->client);
604     sh->client = NULL;
605   }
606   GNUNET_CONTAINER_multipeermap_iterate (sh->peers,
607                                          &cleanup_send_cb,
608                                          sh);
609   GNUNET_CONTAINER_multipeermap_destroy (sh->peers);
610   GNUNET_free (sh);
611 }
612
613
614 /**
615  * Send a message via DV service.
616  *
617  * @param sh service handle
618  * @param target intended recpient
619  * @param msg message payload
620  * @param cb function to invoke when done
621  * @param cb_cls closure for @a cb
622  * @return handle to cancel the operation
623  */
624 struct GNUNET_DV_TransmitHandle *
625 GNUNET_DV_send (struct GNUNET_DV_ServiceHandle *sh,
626                 const struct GNUNET_PeerIdentity *target,
627                 const struct GNUNET_MessageHeader *msg,
628                 GNUNET_DV_MessageSentCallback cb,
629                 void *cb_cls)
630 {
631   struct GNUNET_DV_TransmitHandle *th;
632   struct GNUNET_DV_SendMessage *sm;
633   struct ConnectedPeer *peer;
634
635   if (ntohs (msg->size) + sizeof (struct GNUNET_DV_SendMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
636   {
637     GNUNET_break (0);
638     return NULL;
639   }
640   LOG (GNUNET_ERROR_TYPE_DEBUG,
641        "Asked to send %u bytes of type %u to %s\n",
642        (unsigned int) msg->size,
643        (unsigned int) msg->type,
644        GNUNET_i2s (target));
645   peer = GNUNET_CONTAINER_multipeermap_get (sh->peers,
646                                             target);
647   if (NULL == peer)
648   {
649     GNUNET_break (0);
650     return NULL;
651   }
652   th = GNUNET_malloc (sizeof (struct GNUNET_DV_TransmitHandle) +
653                       sizeof (struct GNUNET_DV_SendMessage) +
654                       ntohs (msg->size));
655   th->sh = sh;
656   th->target = peer;
657   th->cb = cb;
658   th->cb_cls = cb_cls;
659   th->msg = (const struct GNUNET_MessageHeader *) &th[1];
660   sm = (struct GNUNET_DV_SendMessage *) &th[1];
661   sm->header.type = htons (GNUNET_MESSAGE_TYPE_DV_SEND);
662   sm->header.size = htons (sizeof (struct GNUNET_DV_SendMessage) +
663                            ntohs (msg->size));
664   if (0 == sh->uid_gen)
665     sh->uid_gen = 1;
666   th->uid = sh->uid_gen;
667   sm->uid = htonl (sh->uid_gen++);
668   /* use memcpy here as 'target' may not be sufficiently aligned */
669   memcpy (&sm->target, target, sizeof (struct GNUNET_PeerIdentity));
670   memcpy (&sm[1], msg, ntohs (msg->size));
671   GNUNET_CONTAINER_DLL_insert (sh->th_head,
672                                sh->th_tail,
673                                th);
674   start_transmit (sh);
675   return th;
676 }
677
678
679 /**
680  * Abort send operation (naturally, the message may have
681  * already been transmitted; this only stops the 'cb'
682  * from being called again).
683  *
684  * @param th send operation to cancel
685  */
686 void
687 GNUNET_DV_send_cancel (struct GNUNET_DV_TransmitHandle *th)
688 {
689   struct GNUNET_DV_ServiceHandle *sh = th->sh;
690
691   if (NULL == th->msg)
692     GNUNET_CONTAINER_DLL_remove (th->target->head,
693                                  th->target->tail,
694                                  th);
695   else
696     GNUNET_CONTAINER_DLL_remove (sh->th_head,
697                                  sh->th_tail,
698                                  th);
699   GNUNET_free (th);
700 }
701
702
703 /* end of dv_api.c */