-ignore unmatched NACK/ACKs
[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   return GNUNET_OK;
300 }
301
302
303 /**
304  * Handles a message sent from the DV service to us.
305  * Parse it out and give it to the plugin.
306  *
307  * @param cls the handle to the DV API
308  * @param msg the message that was received
309  */
310 static void
311 handle_message_receipt (void *cls,
312                         const struct GNUNET_MessageHeader *msg)
313 {
314   struct GNUNET_DV_ServiceHandle *sh = cls;
315   const struct GNUNET_DV_ConnectMessage *cm;
316   const struct GNUNET_DV_DistanceUpdateMessage *dum;
317   const struct GNUNET_DV_DisconnectMessage *dm;
318   const struct GNUNET_DV_ReceivedMessage *rm;
319   const struct GNUNET_MessageHeader *payload;
320   const struct GNUNET_DV_AckMessage *ack;
321   struct GNUNET_DV_TransmitHandle *th;
322   struct GNUNET_DV_TransmitHandle *tn;
323   struct ConnectedPeer *peer;
324
325   if (NULL == msg)
326   {
327     /* Connection closed */
328     reconnect (sh);
329     return;
330   }
331   LOG (GNUNET_ERROR_TYPE_DEBUG,
332        "Received message of type %u from DV service\n",
333        (unsigned int) msg->type);
334   switch (ntohs (msg->type))
335   {
336   case GNUNET_MESSAGE_TYPE_DV_CONNECT:
337     if (ntohs (msg->size) != sizeof (struct GNUNET_DV_ConnectMessage))
338     {
339       GNUNET_break (0);
340       reconnect (sh);
341       return;
342     }
343     cm = (const struct GNUNET_DV_ConnectMessage *) msg;
344     peer = GNUNET_CONTAINER_multipeermap_get (sh->peers,
345                                               &cm->peer);
346     if (NULL != peer)
347     {
348       GNUNET_break (0);
349       reconnect (sh);
350       return;
351     }
352     peer = GNUNET_new (struct ConnectedPeer);
353     peer->pid = cm->peer;
354     GNUNET_assert (GNUNET_OK ==
355                    GNUNET_CONTAINER_multipeermap_put (sh->peers,
356                                                       &peer->pid,
357                                                       peer,
358                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
359     sh->connect_cb (sh->cls,
360                     &cm->peer,
361                     ntohl (cm->distance), ntohl (cm->network));
362     break;
363   case GNUNET_MESSAGE_TYPE_DV_DISTANCE_CHANGED:
364     if (ntohs (msg->size) != sizeof (struct GNUNET_DV_DistanceUpdateMessage))
365     {
366       GNUNET_break (0);
367       reconnect (sh);
368       return;
369     }
370     dum = (const struct GNUNET_DV_DistanceUpdateMessage *) msg;
371     sh->distance_cb (sh->cls,
372                      &dum->peer,
373                      ntohl (dum->distance));
374     break;
375   case GNUNET_MESSAGE_TYPE_DV_DISCONNECT:
376     if (ntohs (msg->size) != sizeof (struct GNUNET_DV_DisconnectMessage))
377     {
378       GNUNET_break (0);
379       reconnect (sh);
380       return;
381     }
382     dm = (const struct GNUNET_DV_DisconnectMessage *) msg;
383     peer = GNUNET_CONTAINER_multipeermap_get (sh->peers,
384                                               &dm->peer);
385     if (NULL == peer)
386     {
387       GNUNET_break (0);
388       reconnect (sh);
389       return;
390     }
391     tn = sh->th_head;
392     while (NULL != (th = tn))
393     {
394       tn = th->next;
395       if (peer == th->target)
396       {
397         GNUNET_CONTAINER_DLL_remove (sh->th_head,
398                                      sh->th_tail,
399                                      th);
400         th->cb (th->cb_cls, GNUNET_SYSERR);
401         GNUNET_free (th);
402       }
403     }
404     cleanup_send_cb (sh, &dm->peer, peer);
405     break;
406   case GNUNET_MESSAGE_TYPE_DV_RECV:
407     if (ntohs (msg->size) < sizeof (struct GNUNET_DV_ReceivedMessage) + sizeof (struct GNUNET_MessageHeader))
408     {
409       GNUNET_break (0);
410       reconnect (sh);
411       return;
412     }
413     rm = (const struct GNUNET_DV_ReceivedMessage *) msg;
414     payload = (const struct GNUNET_MessageHeader *) &rm[1];
415     if (ntohs (msg->size) != sizeof (struct GNUNET_DV_ReceivedMessage) + ntohs (payload->size))
416     {
417       GNUNET_break (0);
418       reconnect (sh);
419       return;
420     }
421     sh->message_cb (sh->cls,
422                     &rm->sender,
423                     ntohl (rm->distance),
424                     payload);
425     break;
426   case GNUNET_MESSAGE_TYPE_DV_SEND_ACK:
427   case GNUNET_MESSAGE_TYPE_DV_SEND_NACK:
428     if (ntohs (msg->size) != sizeof (struct GNUNET_DV_AckMessage))
429     {
430       GNUNET_break (0);
431       reconnect (sh);
432       return;
433     }
434     ack = (const struct GNUNET_DV_AckMessage *) msg;
435     peer = GNUNET_CONTAINER_multipeermap_get (sh->peers,
436                                               &ack->target);
437     if (NULL == peer)
438       return; /* this happens, just ignore */
439     for (th = peer->head; NULL != th; th = th->next)
440     {
441       if (th->uid != ntohl (ack->uid))
442         continue;
443       LOG (GNUNET_ERROR_TYPE_DEBUG,
444            "Matched ACK for message to peer %s\n",
445            GNUNET_i2s (&ack->target));
446       GNUNET_CONTAINER_DLL_remove (peer->head,
447                                    peer->tail,
448                                    th);
449       th->cb (th->cb_cls,
450               (ntohs (ack->header.type) == GNUNET_MESSAGE_TYPE_DV_SEND_ACK)
451               ? GNUNET_OK
452               : GNUNET_SYSERR);
453       GNUNET_free (th);
454       break;
455     }
456     break;
457   default:
458     reconnect (sh);
459     break;
460   }
461   GNUNET_CLIENT_receive (sh->client,
462                          &handle_message_receipt, sh,
463                          GNUNET_TIME_UNIT_FOREVER_REL);
464 }
465
466
467 /**
468  * Transmit the start message to the DV service.
469  *
470  * @param cls the `struct GNUNET_DV_ServiceHandle *`
471  * @param size number of bytes available in buf
472  * @param buf where to copy the message
473  * @return number of bytes written to buf
474  */
475 static size_t
476 transmit_start (void *cls,
477                 size_t size,
478                 void *buf)
479 {
480   struct GNUNET_DV_ServiceHandle *sh = cls;
481   struct GNUNET_MessageHeader start_message;
482
483   sh->th = NULL;
484   if (NULL == buf)
485   {
486     GNUNET_break (0);
487     reconnect (sh);
488     return 0;
489   }
490   GNUNET_assert (size >= sizeof (start_message));
491   start_message.size = htons (sizeof (struct GNUNET_MessageHeader));
492   start_message.type = htons (GNUNET_MESSAGE_TYPE_DV_START);
493   memcpy (buf, &start_message, sizeof (start_message));
494   GNUNET_CLIENT_receive (sh->client,
495                          &handle_message_receipt, sh,
496                          GNUNET_TIME_UNIT_FOREVER_REL);
497   start_transmit (sh);
498   return sizeof (start_message);
499 }
500
501
502 /**
503  * Disconnect and then reconnect to the DV service.
504  *
505  * @param sh service handle
506  */
507 static void
508 reconnect (struct GNUNET_DV_ServiceHandle *sh)
509 {
510   if (NULL != sh->th)
511   {
512     GNUNET_CLIENT_notify_transmit_ready_cancel (sh->th);
513     sh->th = NULL;
514   }
515   if (NULL != sh->client)
516   {
517     GNUNET_CLIENT_disconnect (sh->client);
518     sh->client = NULL;
519   }
520   GNUNET_CONTAINER_multipeermap_iterate (sh->peers,
521                                          &cleanup_send_cb,
522                                          sh);
523   LOG (GNUNET_ERROR_TYPE_DEBUG,
524        "Connecting to DV service\n");
525   sh->client = GNUNET_CLIENT_connect ("dv", sh->cfg);
526   if (NULL == sh->client)
527   {
528     GNUNET_break (0);
529     return;
530   }
531   sh->th = GNUNET_CLIENT_notify_transmit_ready (sh->client,
532                                                 sizeof (struct GNUNET_MessageHeader),
533                                                 GNUNET_TIME_UNIT_FOREVER_REL,
534                                                 GNUNET_YES,
535                                                 &transmit_start,
536                                                 sh);
537 }
538
539
540 /**
541  * Connect to the DV service.
542  *
543  * @param cfg configuration
544  * @param cls closure for callbacks
545  * @param connect_cb function to call on connects
546  * @param distance_cb function to call if distances change
547  * @param disconnect_cb function to call on disconnects
548  * @param message_cb function to call if we receive messages
549  * @return handle to access the service
550  */
551 struct GNUNET_DV_ServiceHandle *
552 GNUNET_DV_service_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
553                            void *cls,
554                            GNUNET_DV_ConnectCallback connect_cb,
555                            GNUNET_DV_DistanceChangedCallback distance_cb,
556                            GNUNET_DV_DisconnectCallback disconnect_cb,
557                            GNUNET_DV_MessageReceivedCallback message_cb)
558 {
559   struct GNUNET_DV_ServiceHandle *sh;
560
561   sh = GNUNET_new (struct GNUNET_DV_ServiceHandle);
562   sh->cfg = cfg;
563   sh->cls = cls;
564   sh->connect_cb = connect_cb;
565   sh->distance_cb = distance_cb;
566   sh->disconnect_cb = disconnect_cb;
567   sh->message_cb = message_cb;
568   sh->peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
569   reconnect (sh);
570   return sh;
571 }
572
573
574 /**
575  * Disconnect from DV service.
576  *
577  * @param sh service handle
578  */
579 void
580 GNUNET_DV_service_disconnect (struct GNUNET_DV_ServiceHandle *sh)
581 {
582   struct GNUNET_DV_TransmitHandle *pos;
583
584   if (NULL == sh)
585     return;
586   if (NULL != sh->th)
587   {
588     GNUNET_CLIENT_notify_transmit_ready_cancel (sh->th);
589     sh->th = NULL;
590   }
591   while (NULL != (pos = sh->th_head))
592   {
593     GNUNET_CONTAINER_DLL_remove (sh->th_head,
594                                  sh->th_tail,
595                                  pos);
596     GNUNET_free (pos);
597   }
598   if (NULL != sh->client)
599   {
600     GNUNET_CLIENT_disconnect (sh->client);
601     sh->client = NULL;
602   }
603   GNUNET_CONTAINER_multipeermap_iterate (sh->peers,
604                                          &cleanup_send_cb,
605                                          sh);
606   GNUNET_CONTAINER_multipeermap_destroy (sh->peers);
607   GNUNET_free (sh);
608 }
609
610
611 /**
612  * Send a message via DV service.
613  *
614  * @param sh service handle
615  * @param target intended recpient
616  * @param msg message payload
617  * @param cb function to invoke when done
618  * @param cb_cls closure for @a cb
619  * @return handle to cancel the operation
620  */
621 struct GNUNET_DV_TransmitHandle *
622 GNUNET_DV_send (struct GNUNET_DV_ServiceHandle *sh,
623                 const struct GNUNET_PeerIdentity *target,
624                 const struct GNUNET_MessageHeader *msg,
625                 GNUNET_DV_MessageSentCallback cb,
626                 void *cb_cls)
627 {
628   struct GNUNET_DV_TransmitHandle *th;
629   struct GNUNET_DV_SendMessage *sm;
630   struct ConnectedPeer *peer;
631
632   if (ntohs (msg->size) + sizeof (struct GNUNET_DV_SendMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
633   {
634     GNUNET_break (0);
635     return NULL;
636   }
637   LOG (GNUNET_ERROR_TYPE_DEBUG,
638        "Asked to send %u bytes of type %u to %s\n",
639        (unsigned int) msg->size,
640        (unsigned int) msg->type,
641        GNUNET_i2s (target));
642   peer = GNUNET_CONTAINER_multipeermap_get (sh->peers,
643                                             target);
644   if (NULL == peer)
645   {
646     GNUNET_break (0);
647     return NULL;
648   }
649   th = GNUNET_malloc (sizeof (struct GNUNET_DV_TransmitHandle) +
650                       sizeof (struct GNUNET_DV_SendMessage) +
651                       ntohs (msg->size));
652   th->sh = sh;
653   th->target = peer;
654   th->cb = cb;
655   th->cb_cls = cb_cls;
656   th->msg = (const struct GNUNET_MessageHeader *) &th[1];
657   sm = (struct GNUNET_DV_SendMessage *) &th[1];
658   sm->header.type = htons (GNUNET_MESSAGE_TYPE_DV_SEND);
659   sm->header.size = htons (sizeof (struct GNUNET_DV_SendMessage) +
660                            ntohs (msg->size));
661   if (0 == sh->uid_gen)
662     sh->uid_gen = 1;
663   th->uid = sh->uid_gen;
664   sm->uid = htonl (sh->uid_gen++);
665   /* use memcpy here as 'target' may not be sufficiently aligned */
666   memcpy (&sm->target, target, sizeof (struct GNUNET_PeerIdentity));
667   memcpy (&sm[1], msg, ntohs (msg->size));
668   GNUNET_CONTAINER_DLL_insert (sh->th_head,
669                                sh->th_tail,
670                                th);
671   start_transmit (sh);
672   return th;
673 }
674
675
676 /**
677  * Abort send operation (naturally, the message may have
678  * already been transmitted; this only stops the 'cb'
679  * from being called again).
680  *
681  * @param th send operation to cancel
682  */
683 void
684 GNUNET_DV_send_cancel (struct GNUNET_DV_TransmitHandle *th)
685 {
686   struct GNUNET_DV_ServiceHandle *sh = th->sh;
687
688   if (NULL == th->msg)
689     GNUNET_CONTAINER_DLL_remove (th->target->head,
690                                  th->target->tail,
691                                  th);
692   else
693     GNUNET_CONTAINER_DLL_remove (sh->th_head,
694                                  sh->th_tail,
695                                  th);
696   GNUNET_free (th);
697 }
698
699
700 /* end of dv_api.c */