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