-check RV
[oweals/gnunet.git] / src / dv / plugin_transport_dv.c
1 /*
2      This file is part of GNUnet
3      (C) 2002--2014 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/plugin_transport_dv.c
23  * @brief DV transport service, takes incoming DV requests and deals with
24  * the DV service
25  * @author Nathan Evans
26  * @author Christian Grothoff
27  */
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_statistics_service.h"
32 #include "gnunet_dv_service.h"
33 #include "gnunet_transport_service.h"
34 #include "gnunet_transport_plugin.h"
35 #include "dv.h"
36
37
38 #define LOG(kind,...) GNUNET_log_from (kind, "transport-dv",__VA_ARGS__)
39
40
41 /**
42  * Encapsulation of all of the state of the plugin.
43  */
44 struct Plugin;
45
46
47 /**
48  * An active request for transmission via DV.
49  */
50 struct PendingRequest
51 {
52
53   /**
54    * This is a DLL.
55    */
56   struct PendingRequest *next;
57
58   /**
59    * This is a DLL.
60    */
61   struct PendingRequest *prev;
62
63   /**
64    * Continuation function to call once the transmission buffer
65    * has again space available.  NULL if there is no
66    * continuation to call.
67    */
68   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
69
70   /**
71    * Closure for @e transmit_cont.
72    */
73   void *transmit_cont_cls;
74
75   /**
76    * Transmission handle from DV client library.
77    */
78   struct GNUNET_DV_TransmitHandle *th;
79
80   /**
81    * Session of this request.
82    */
83   struct Session *session;
84
85   /**
86    * Number of bytes to transmit.
87    */
88   size_t size;
89 };
90
91
92 /**
93  * Session handle for connections.
94  */
95 struct Session
96 {
97   /**
98    * Pointer to the global plugin struct.
99    */
100   struct Plugin *plugin;
101
102   /**
103    * Head of pending requests.
104    */
105   struct PendingRequest *pr_head;
106
107   /**
108    * Tail of pending requests.
109    */
110   struct PendingRequest *pr_tail;
111
112   /**
113    * Address we use for the other peer.
114    */
115   struct GNUNET_HELLO_Address *address;
116
117   /**
118    * To whom are we talking to.
119    */
120   struct GNUNET_PeerIdentity sender;
121
122   /**
123    * Number of bytes waiting for transmission to this peer.
124    * FIXME: not set yet.
125    */
126   unsigned long long bytes_in_queue;
127
128   /**
129    * Number of messages waiting for transmission to this peer.
130    * FIXME: not set yet.
131    */
132   unsigned int msgs_in_queue;
133
134   /**
135    * Current distance to the given peer.
136    */
137   uint32_t distance;
138
139   /**
140    * Current network the next hop peer is located in
141    */
142   enum GNUNET_ATS_Network_Type network;
143
144   /**
145    * Does the transport service know about this session (and we thus
146    * need to call `session_end` when it is released?)
147    */
148   int active;
149
150 };
151
152
153 /**
154  * Encapsulation of all of the state of the plugin.
155  */
156 struct Plugin
157 {
158   /**
159    * Our environment.
160    */
161   struct GNUNET_TRANSPORT_PluginEnvironment *env;
162
163   /**
164    * Hash map of sessions (active and inactive).
165    */
166   struct GNUNET_CONTAINER_MultiPeerMap *sessions;
167
168   /**
169    * Copy of the handler array where the closures are
170    * set to this struct's instance.
171    */
172   struct GNUNET_SERVER_MessageHandler *handlers;
173
174   /**
175    * Handle to the DV service
176    */
177   struct GNUNET_DV_ServiceHandle *dvh;
178
179   /**
180    * Tokenizer for boxed messages.
181    */
182   struct GNUNET_SERVER_MessageStreamTokenizer *mst;
183
184   /**
185    * Function to call about session status changes.
186    */
187   GNUNET_TRANSPORT_SessionInfoCallback sic;
188
189   /**
190    * Closure for @e sic.
191    */
192   void *sic_cls;
193 };
194
195
196 /**
197  * If a session monitor is attached, notify it about the new
198  * session state.
199  *
200  * @param plugin our plugin
201  * @param session session that changed state
202  * @param state new state of the session
203  */
204 static void
205 notify_session_monitor (struct Plugin *plugin,
206                         struct Session *session,
207                         enum GNUNET_TRANSPORT_SessionState state)
208 {
209   struct GNUNET_TRANSPORT_SessionInfo info;
210
211   if (NULL == plugin->sic)
212     return;
213   memset (&info, 0, sizeof (info));
214   info.state = state;
215   info.is_inbound = GNUNET_SYSERR; /* hard to say */
216   info.num_msg_pending = session->msgs_in_queue;
217   info.num_bytes_pending = session->bytes_in_queue;
218   /* info.receive_delay remains zero as this is not supported by DV
219      (cannot selectively not receive from 'core') */
220   info.session_timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
221   info.address = session->address;
222   plugin->sic (plugin->sic_cls,
223                session,
224                &info);
225 }
226
227
228 /**
229  * Notify transport service about the change in distance.
230  *
231  * @param session session where the distance changed
232  */
233 static void
234 notify_distance_change (struct Session *session)
235 {
236   struct Plugin *plugin = session->plugin;
237   struct GNUNET_ATS_Information ats;
238
239   if (GNUNET_YES != session->active)
240     return;
241   ats.type = htonl ((uint32_t) GNUNET_ATS_QUALITY_NET_DISTANCE);
242   ats.value = htonl (session->distance);
243   plugin->env->update_address_metrics (plugin->env->cls,
244       session->address, session, &ats, 1);
245 }
246
247
248 /**
249  * Function called by MST on each message from the box.
250  *
251  * @param cls closure with the `struct Plugin *`
252  * @param client identification of the client (with the 'struct Session')
253  * @param message the actual message
254  * @return #GNUNET_OK on success
255  */
256 static int
257 unbox_cb (void *cls,
258           void *client,
259           const struct GNUNET_MessageHeader *message)
260 {
261   struct Plugin *plugin = cls;
262   struct Session *session = client;
263   struct GNUNET_ATS_Information ats;
264
265   ats.type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
266   ats.value = htonl (session->distance);
267   session->active = GNUNET_YES;
268   LOG (GNUNET_ERROR_TYPE_DEBUG,
269        "Delivering message of type %u with %u bytes from peer `%s'\n",
270        ntohs (message->type),
271        ntohs (message->size),
272        GNUNET_i2s (&session->sender));
273
274   plugin->env->receive (plugin->env->cls, session->address, session,
275                         message);
276   plugin->env->update_address_metrics (plugin->env->cls,
277       session->address, session, &ats, 1);
278   return GNUNET_OK;
279 }
280
281
282 /**
283  * Handler for messages received from the DV service.
284  *
285  * @param cls closure with the plugin
286  * @param sender sender of the message
287  * @param distance how far did the message travel
288  * @param msg actual message payload
289  */
290 static void
291 handle_dv_message_received (void *cls,
292                             const struct GNUNET_PeerIdentity *sender,
293                             uint32_t distance,
294                             const struct GNUNET_MessageHeader *msg)
295 {
296   struct Plugin *plugin = cls;
297   struct GNUNET_ATS_Information ats;
298   struct Session *session;
299
300   LOG (GNUNET_ERROR_TYPE_DEBUG,
301        "Received DV_MESSAGE_RECEIVED message for peer `%s': new distance %u\n",
302        GNUNET_i2s (sender), distance);
303   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
304                                                sender);
305   if (NULL == session)
306   {
307     GNUNET_break (0);
308     return;
309   }
310   if (GNUNET_MESSAGE_TYPE_DV_BOX == ntohs (msg->type))
311   {
312     /* need to unbox using MST */
313     LOG (GNUNET_ERROR_TYPE_DEBUG,
314          "Unboxing DV message using MST\n");
315     GNUNET_SERVER_mst_receive (plugin->mst,
316                                session,
317                                (const char *) &msg[1],
318                                ntohs (msg->size) - sizeof (struct GNUNET_MessageHeader),
319                                GNUNET_YES,
320                                GNUNET_NO);
321     return;
322   }
323   ats.type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
324   ats.value = htonl (distance);
325   session->active = GNUNET_YES;
326   LOG (GNUNET_ERROR_TYPE_DEBUG,
327        "Delivering message of type %u with %u bytes from peer `%s'\n",
328        ntohs (msg->type),
329        ntohs (msg->size),
330        GNUNET_i2s (sender));
331   plugin->env->receive (plugin->env->cls, session->address, session, msg);
332   plugin->env->update_address_metrics (plugin->env->cls,
333       session->address, session, &ats, 1);
334 }
335
336
337 /**
338  * Function called if DV starts to be able to talk to a peer.
339  *
340  * @param cls closure with `struct Plugin *`
341  * @param peer newly connected peer
342  * @param distance distance to the peer
343  * @param network the network the next hop is located in
344  */
345 static void
346 handle_dv_connect (void *cls,
347                    const struct GNUNET_PeerIdentity *peer,
348                    uint32_t distance,
349                    enum GNUNET_ATS_Network_Type network)
350 {
351   struct Plugin *plugin = cls;
352   struct Session *session;
353   struct GNUNET_ATS_Information ats[2];
354
355   GNUNET_break (GNUNET_ATS_NET_UNSPECIFIED != network);
356   /**
357    * This requires transport plugin to be linked to libgnunetats.
358    * If you remove it, also remove libgnunetats linkage from Makefile.am
359    */
360   LOG (GNUNET_ERROR_TYPE_DEBUG,
361        "Received `%s' message for peer `%s' with next hop in network %s\n",
362        "DV_CONNECT",
363        GNUNET_i2s (peer),
364        GNUNET_ATS_print_network_type (network));
365
366   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
367                                                peer);
368   if (NULL != session)
369   {
370     GNUNET_break (0);
371     session->distance = distance;
372     notify_distance_change (session);
373     return; /* nothing to do */
374   }
375
376   session = GNUNET_new (struct Session);
377   session->address = GNUNET_HELLO_address_allocate (peer, "dv",
378       NULL, 0, GNUNET_HELLO_ADDRESS_INFO_NONE);
379   session->sender = *peer;
380   session->plugin = plugin;
381   session->distance = distance;
382   session->network = network;
383   GNUNET_assert(GNUNET_YES ==
384                 GNUNET_CONTAINER_multipeermap_put (plugin->sessions,
385                                                    &session->sender, session,
386                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
387
388   LOG (GNUNET_ERROR_TYPE_DEBUG,
389        "Creating new DV session %p for peer `%s' at distance %u\n",
390        session,
391        GNUNET_i2s (peer),
392        distance);
393
394   /* Notify transport and ats about new connection */
395   ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
396   ats[0].value = htonl (distance);
397   ats[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
398   ats[1].value = htonl ((uint32_t) network);
399   session->active = GNUNET_YES;
400   plugin->env->session_start (plugin->env->cls, session->address,
401                               session, ats, 2);
402   notify_session_monitor (session->plugin,
403                           session,
404                           GNUNET_TRANSPORT_SS_UP);
405 }
406
407
408 /**
409  * Function called if DV distance to a peer is changed.
410  *
411  * @param cls closure with `struct Plugin *`
412  * @param peer connected peer
413  * @param distance new distance to the peer
414  * @param network network type used for the connection
415  */
416 static void
417 handle_dv_distance_changed (void *cls,
418                             const struct GNUNET_PeerIdentity *peer,
419                             uint32_t distance,
420                             enum GNUNET_ATS_Network_Type network)
421 {
422   struct Plugin *plugin = cls;
423   struct Session *session;
424
425   GNUNET_break (GNUNET_ATS_NET_UNSPECIFIED != network);
426   LOG (GNUNET_ERROR_TYPE_DEBUG,
427        "Received `%s' message for peer `%s': new distance %u\n",
428        "DV_DISTANCE_CHANGED",
429        GNUNET_i2s (peer),
430        distance);
431   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
432                                                peer);
433   if (NULL == session)
434   {
435     GNUNET_break (0);
436     handle_dv_connect (plugin, peer, distance, network);
437     return;
438   }
439   session->distance = distance;
440   notify_distance_change (session);
441 }
442
443
444 /**
445  * Release session object and clean up associated resources.
446  *
447  * @param session session to clean up
448  */
449 static void
450 free_session (struct Session *session)
451 {
452   struct Plugin *plugin = session->plugin;
453   struct PendingRequest *pr;
454
455   GNUNET_assert (GNUNET_YES ==
456                  GNUNET_CONTAINER_multipeermap_remove (plugin->sessions,
457                                                        &session->sender,
458                                                        session));
459
460   LOG (GNUNET_ERROR_TYPE_DEBUG,
461        "Freeing session %p for peer `%s'\n",
462        session,
463        GNUNET_i2s (&session->sender));
464   if (GNUNET_YES == session->active)
465   {
466     notify_session_monitor (session->plugin,
467                             session,
468                             GNUNET_TRANSPORT_SS_DONE);
469     plugin->env->session_end (plugin->env->cls,
470                               session->address,
471                               session);
472     session->active = GNUNET_NO;
473   }
474   while (NULL != (pr = session->pr_head))
475   {
476     GNUNET_CONTAINER_DLL_remove (session->pr_head,
477                                  session->pr_tail,
478                                  pr);
479     GNUNET_DV_send_cancel (pr->th);
480     pr->th = NULL;
481     if (NULL != pr->transmit_cont)
482       pr->transmit_cont (pr->transmit_cont_cls,
483                          &session->sender,
484                          GNUNET_SYSERR,
485                          pr->size, 0);
486     GNUNET_free (pr);
487   }
488   GNUNET_HELLO_address_free (session->address);
489   GNUNET_free (session);
490 }
491
492
493 /**
494  * Function called if DV is no longer able to talk to a peer.
495  *
496  * @param cls closure with `struct Plugin *`
497  * @param peer peer that disconnected
498  */
499 static void
500 handle_dv_disconnect (void *cls,
501                       const struct GNUNET_PeerIdentity *peer)
502 {
503   struct Plugin *plugin = cls;
504   struct Session *session;
505
506   LOG (GNUNET_ERROR_TYPE_DEBUG,
507        "Received `%s' message for peer `%s'\n",
508        "DV_DISCONNECT",
509        GNUNET_i2s (peer));
510   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
511                                                peer);
512   if (NULL == session)
513     return; /* nothing to do */
514   free_session (session);
515 }
516
517
518 /**
519  * Function called once the delivery of a message has been successful.
520  * Clean up the pending request, and call continuations.
521  *
522  * @param cls closure
523  * @param ok #GNUNET_OK on success, #GNUNET_SYSERR on error
524  */
525 static void
526 send_finished (void *cls,
527                int ok)
528 {
529   struct PendingRequest *pr = cls;
530   struct Session *session = pr->session;
531
532   pr->th = NULL;
533   GNUNET_CONTAINER_DLL_remove (session->pr_head,
534                                session->pr_tail,
535                                pr);
536   if (NULL != pr->transmit_cont)
537     pr->transmit_cont (pr->transmit_cont_cls,
538                        &session->sender,
539                        ok,
540                        pr->size, 0);
541   GNUNET_free (pr);
542 }
543
544
545 /**
546  * Function that can be used by the transport service to transmit
547  * a message using the plugin.
548  *
549  * @param cls closure
550  * @param session the session used
551  * @param priority how important is the message
552  * @param msgbuf the message to transmit
553  * @param msgbuf_size number of bytes in 'msgbuf'
554  * @param timeout when should we time out
555  * @param cont continuation to call once the message has
556  *        been transmitted (or if the transport is ready
557  *        for the next transmission call; or if the
558  *        peer disconnected...)
559  * @param cont_cls closure for @a cont
560  * @return number of bytes used (on the physical network, with overheads);
561  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
562  *         and does NOT mean that the message was not transmitted (DV)
563  */
564 static ssize_t
565 dv_plugin_send (void *cls,
566                 struct Session *session,
567                 const char *msgbuf,
568                 size_t msgbuf_size,
569                 unsigned int priority,
570                 struct GNUNET_TIME_Relative timeout,
571                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
572 {
573   struct Plugin *plugin = cls;
574   struct PendingRequest *pr;
575   const struct GNUNET_MessageHeader *msg;
576   struct GNUNET_MessageHeader *box;
577
578   box = NULL;
579   msg = (const struct GNUNET_MessageHeader *) msgbuf;
580   if (ntohs (msg->size) != msgbuf_size)
581   {
582     /* need to box */
583     LOG (GNUNET_ERROR_TYPE_DEBUG,
584          "Boxing DV message\n");
585     box = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader) + msgbuf_size);
586     box->type = htons (GNUNET_MESSAGE_TYPE_DV_BOX);
587     box->size = htons (sizeof (struct GNUNET_MessageHeader) + msgbuf_size);
588     memcpy (&box[1], msgbuf, msgbuf_size);
589     msg = box;
590   }
591   pr = GNUNET_new (struct PendingRequest);
592   pr->transmit_cont = cont;
593   pr->transmit_cont_cls = cont_cls;
594   pr->session = session;
595   pr->size = msgbuf_size;
596   GNUNET_CONTAINER_DLL_insert_tail (session->pr_head,
597                                     session->pr_tail,
598                                     pr);
599
600   pr->th = GNUNET_DV_send (plugin->dvh,
601                            &session->sender,
602                            msg,
603                            &send_finished,
604                            pr);
605   GNUNET_free_non_null (box);
606   return 0; /* DV */
607 }
608
609
610 /**
611  * Function that can be used to force the plugin to disconnect
612  * from the given peer and cancel all previous transmissions
613  * (and their continuations).
614  *
615  * @param cls closure with the `struct Plugin *`
616  * @param target peer from which to disconnect
617  */
618 static void
619 dv_plugin_disconnect_peer (void *cls,
620                            const struct GNUNET_PeerIdentity *target)
621 {
622   struct Plugin *plugin = cls;
623   struct Session *session;
624   struct PendingRequest *pr;
625
626   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
627                                                target);
628   if (NULL == session)
629     return; /* nothing to do */
630   while (NULL != (pr = session->pr_head))
631   {
632     GNUNET_CONTAINER_DLL_remove (session->pr_head,
633                                  session->pr_tail,
634                                  pr);
635     GNUNET_DV_send_cancel (pr->th);
636     pr->th = NULL;
637     if (NULL != pr->transmit_cont)
638       pr->transmit_cont (pr->transmit_cont_cls,
639                          &session->sender,
640                          GNUNET_SYSERR,
641                          pr->size, 0);
642     GNUNET_free (pr);
643   }
644   session->active = GNUNET_NO;
645 }
646
647
648 /**
649  * Function that can be used to force the plugin to disconnect
650  * from the given peer and cancel all previous transmissions
651  * (and their continuations).
652  *
653  * @param cls closure with the `struct Plugin *`
654  * @param session which session to disconnect
655  * @return #GNUNET_OK
656  */
657 static int
658 dv_plugin_disconnect_session (void *cls,
659                               struct Session *session)
660 {
661   struct PendingRequest *pr;
662
663   while (NULL != (pr = session->pr_head))
664   {
665     GNUNET_CONTAINER_DLL_remove (session->pr_head,
666                                  session->pr_tail,
667                                  pr);
668     GNUNET_DV_send_cancel (pr->th);
669     pr->th = NULL;
670     if (NULL != pr->transmit_cont)
671       pr->transmit_cont (pr->transmit_cont_cls,
672                          &session->sender,
673                          GNUNET_SYSERR,
674                          pr->size, 0);
675     GNUNET_free (pr);
676   }
677   session->active = GNUNET_NO;
678   return GNUNET_OK;
679 }
680
681
682 /**
683  * Convert the transports address to a nice, human-readable
684  * format.
685  *
686  * @param cls closure
687  * @param type name of the transport that generated the address
688  * @param addr one of the addresses of the host, NULL for the last address
689  *        the specific address format depends on the transport
690  * @param addrlen length of the address
691  * @param numeric should (IP) addresses be displayed in numeric form?
692  * @param timeout after how long should we give up?
693  * @param asc function to call on each string
694  * @param asc_cls closure for @a asc
695  */
696 static void
697 dv_plugin_address_pretty_printer (void *cls, const char *type,
698                                   const void *addr,
699                                   size_t addrlen, int numeric,
700                                   struct GNUNET_TIME_Relative timeout,
701                                   GNUNET_TRANSPORT_AddressStringCallback asc,
702                                   void *asc_cls)
703 {
704   if ( (0 == addrlen) &&
705        (0 == strcmp (type, "dv")) )
706     asc (asc_cls,
707          "dv",
708          GNUNET_OK);
709   else
710     asc (asc_cls,
711          NULL,
712          GNUNET_SYSERR);
713   asc (asc_cls,
714        NULL,
715        GNUNET_OK);
716 }
717
718
719 /**
720  * Convert the DV address to a pretty string.
721  *
722  * @param cls closure
723  * @param addr the (hopefully) DV address
724  * @param addrlen the length of the @a addr
725  * @return string representing the DV address
726  */
727 static const char *
728 dv_plugin_address_to_string (void *cls,
729                              const void *addr,
730                              size_t addrlen)
731 {
732   if (0 != addrlen)
733   {
734     GNUNET_break (0); /* malformed */
735     return NULL;
736   }
737   return "dv";
738 }
739
740
741 /**
742  * Another peer has suggested an address for this peer and transport
743  * plugin.  Check that this could be a valid address.  This function
744  * is not expected to 'validate' the address in the sense of trying to
745  * connect to it but simply to see if the binary format is technically
746  * legal for establishing a connection to this peer (and make sure that
747  * the address really corresponds to our network connection/settings
748  * and not some potential man-in-the-middle).
749  *
750  * @param cls closure
751  * @param addr pointer to the address
752  * @param addrlen length of @a addr
753  * @return #GNUNET_OK if this is a plausible address for this peer
754  *         and transport, #GNUNET_SYSERR if not
755  *
756  */
757 static int
758 dv_plugin_check_address (void *cls,
759                          const void *addr,
760                          size_t addrlen)
761 {
762   if (0 != addrlen)
763     return GNUNET_SYSERR;
764   return GNUNET_OK;
765 }
766
767
768 /**
769  * Create a new session to transmit data to the target
770  * This session will used to send data to this peer and the plugin will
771  * notify us by calling the env->session_end function
772  *
773  * @param cls the plugin
774  * @param address the address
775  * @return the session if the address is valid, NULL otherwise
776  */
777 static struct Session *
778 dv_get_session (void *cls,
779                 const struct GNUNET_HELLO_Address *address)
780 {
781   struct Plugin *plugin = cls;
782   struct Session *session;
783
784   if (0 != address->address_length)
785     return NULL;
786   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
787                                                &address->peer);
788   if (NULL == session)
789     return NULL; /* not valid right now */
790   session->active = GNUNET_YES;
791   return session;
792 }
793
794
795 /**
796  * Function called to convert a string address to
797  * a binary address.
798  *
799  * @param cls closure ('struct Plugin*')
800  * @param addr string address
801  * @param addrlen length of the @a addr including \0 termination
802  * @param buf location to store the buffer
803  *        If the function returns #GNUNET_SYSERR, its contents are undefined.
804  * @param added length of created address
805  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
806  */
807 static int
808 dv_plugin_string_to_address (void *cls,
809                              const char *addr,
810                              uint16_t addrlen,
811                              void **buf,
812                              size_t *added)
813 {
814   if ( (addrlen == 3) &&
815        (0 == strcmp ("dv", addr)) )
816   {
817     *added = 0;
818     return GNUNET_OK;
819   }
820   return GNUNET_SYSERR;
821 }
822
823
824 /**
825  * Function that will be called whenever the transport service wants to
826  * notify the plugin that a session is still active and in use and
827  * therefore the session timeout for this session has to be updated
828  *
829  * @param cls closure (`struct Plugin *`)
830  * @param peer which peer was the session for
831  * @param session which session is being updated
832  */
833 static void
834 dv_plugin_update_session_timeout (void *cls,
835                                   const struct GNUNET_PeerIdentity *peer,
836                                   struct Session *session)
837 {
838   /* DV currently doesn't time out like "normal" plugins,
839      so it should be safe to do nothing, right?
840      (or should we add an internal timeout?) */
841 }
842
843
844 /**
845  * Function to obtain the network type for a session
846  * FIXME: we should probably look at the network type
847  * used by the next hop here.  Or find some other way
848  * to properly allow ATS-DV resource allocation.
849  *
850  * @param cls closure (`struct Plugin *`)
851  * @param session the session
852  * @return the network type
853  */
854 static enum GNUNET_ATS_Network_Type
855 dv_get_network (void *cls,
856                 struct Session *session)
857 {
858   GNUNET_assert (NULL != session);
859   return session->network;
860 }
861
862
863 /**
864  * Function that is called to get the keepalive factor.
865  * #GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
866  * calculate the interval between keepalive packets.
867  *
868  * @param cls closure with the `struct Plugin`
869  * @return keepalive factor
870  */
871 static unsigned int
872 dv_plugin_query_keepalive_factor (void *cls)
873 {
874   return 3;
875 }
876
877
878 /**
879  * Return information about the given session to the
880  * monitor callback.
881  *
882  * @param cls the `struct Plugin` with the monitor callback (`sic`)
883  * @param peer peer we send information about
884  * @param value our `struct Session` to send information about
885  * @return #GNUNET_OK (continue to iterate)
886  */
887 static int
888 send_session_info_iter (void *cls,
889                         const struct GNUNET_PeerIdentity *peer,
890                         void *value)
891 {
892   struct Plugin *plugin = cls;
893   struct Session *session = value;
894
895   if (GNUNET_YES != session->active)
896     return GNUNET_OK;
897   notify_session_monitor (plugin,
898                           session,
899                           GNUNET_TRANSPORT_SS_UP);
900   return GNUNET_OK;
901 }
902
903
904 /**
905  * Begin monitoring sessions of a plugin.  There can only
906  * be one active monitor per plugin (i.e. if there are
907  * multiple monitors, the transport service needs to
908  * multiplex the generated events over all of them).
909  *
910  * @param cls closure of the plugin
911  * @param sic callback to invoke, NULL to disable monitor;
912  *            plugin will being by iterating over all active
913  *            sessions immediately and then enter monitor mode
914  * @param sic_cls closure for @a sic
915  */
916 static void
917 dv_plugin_setup_monitor (void *cls,
918                           GNUNET_TRANSPORT_SessionInfoCallback sic,
919                           void *sic_cls)
920 {
921   struct Plugin *plugin = cls;
922
923   plugin->sic = sic;
924   plugin->sic_cls = sic_cls;
925   if (NULL != sic)
926   {
927     GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
928                                            &send_session_info_iter,
929                                            plugin);
930     /* signal end of first iteration */
931     sic (sic_cls, NULL, NULL);
932   }
933 }
934
935
936 /**
937  * Entry point for the plugin.
938  *
939  * @param cls closure with the plugin environment
940  * @return plugin API
941  */
942 void *
943 libgnunet_plugin_transport_dv_init (void *cls)
944 {
945   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
946   struct GNUNET_TRANSPORT_PluginFunctions *api;
947   struct Plugin *plugin;
948
949   plugin = GNUNET_new (struct Plugin);
950   plugin->env = env;
951   plugin->sessions = GNUNET_CONTAINER_multipeermap_create (1024 * 8, GNUNET_YES);
952   plugin->mst = GNUNET_SERVER_mst_create (&unbox_cb,
953                                           plugin);
954   plugin->dvh = GNUNET_DV_service_connect (env->cfg,
955                                            plugin,
956                                            &handle_dv_connect,
957                                            &handle_dv_distance_changed,
958                                            &handle_dv_disconnect,
959                                            &handle_dv_message_received);
960   if (NULL == plugin->dvh)
961   {
962     GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
963     GNUNET_SERVER_mst_destroy (plugin->mst);
964     GNUNET_free (plugin);
965     return NULL;
966   }
967   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
968   api->cls = plugin;
969   api->send = &dv_plugin_send;
970   api->disconnect_peer = &dv_plugin_disconnect_peer;
971   api->disconnect_session = &dv_plugin_disconnect_session;
972   api->address_pretty_printer = &dv_plugin_address_pretty_printer;
973   api->check_address = &dv_plugin_check_address;
974   api->address_to_string = &dv_plugin_address_to_string;
975   api->string_to_address = &dv_plugin_string_to_address;
976   api->query_keepalive_factor = &dv_plugin_query_keepalive_factor;
977   api->get_session = &dv_get_session;
978   api->get_network = &dv_get_network;
979   api->update_session_timeout = &dv_plugin_update_session_timeout;
980   api->setup_monitor = &dv_plugin_setup_monitor;
981   return api;
982 }
983
984
985 /**
986  * Function called to free a session.
987  *
988  * @param cls NULL
989  * @param key unused
990  * @param value session to free
991  * @return #GNUNET_OK (continue to iterate)
992  */
993 static int
994 free_session_iterator (void *cls,
995                        const struct GNUNET_PeerIdentity *key,
996                        void *value)
997 {
998   struct Session *session = value;
999
1000   free_session (session);
1001   return GNUNET_OK;
1002 }
1003
1004
1005 /**
1006  * Exit point from the plugin.
1007  *
1008  * @param cls plugin API
1009  * @return NULL
1010  */
1011 void *
1012 libgnunet_plugin_transport_dv_done (void *cls)
1013 {
1014   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1015   struct Plugin *plugin = api->cls;
1016
1017   GNUNET_DV_service_disconnect (plugin->dvh);
1018   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
1019                                          &free_session_iterator,
1020                                          NULL);
1021   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
1022   GNUNET_SERVER_mst_destroy (plugin->mst);
1023   GNUNET_free (plugin);
1024   GNUNET_free (api);
1025   return NULL;
1026 }
1027
1028 /* end of plugin_transport_dv.c */