- replace deprecated INCLUDES with AM_CPPFLAGS
[oweals/gnunet.git] / src / dv / plugin_transport_dv.c
1 /*
2      This file is part of GNUnet
3      (C) 2002--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/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
29 #include "platform.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_connection_lib.h"
32 #include "gnunet_server_lib.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_statistics_service.h"
35 #include "gnunet_dv_service.h"
36 #include "gnunet_transport_service.h"
37 #include "gnunet_transport_plugin.h"
38 #include "dv.h"
39
40
41 #define LOG(kind,...) GNUNET_log_from (kind, "transport-dv",__VA_ARGS__)
42
43
44 /**
45  * Encapsulation of all of the state of the plugin.
46  */
47 struct Plugin;
48
49
50 /**
51  * An active request for transmission via DV.
52  */
53 struct PendingRequest
54 {
55
56   /**
57    * This is a DLL.
58    */
59   struct PendingRequest *next;
60
61   /**
62    * This is a DLL.
63    */
64   struct PendingRequest *prev;
65
66   /**
67    * Continuation function to call once the transmission buffer
68    * has again space available.  NULL if there is no
69    * continuation to call.
70    */
71   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
72
73   /**
74    * Closure for transmit_cont.
75    */
76   void *transmit_cont_cls;
77
78   /**
79    * Transmission handle from DV client library.
80    */
81   struct GNUNET_DV_TransmitHandle *th;
82
83   /**
84    * Session of this request.
85    */
86   struct Session *session;
87
88 };
89
90
91 /**
92  * Session handle for connections.
93  */
94 struct Session
95 {
96
97   /**
98    * Mandatory session header.
99    */
100   struct SessionHeader header;
101
102   /**
103    * Pointer to the global plugin struct.
104    */
105   struct Plugin *plugin;
106
107   /**
108    * Head of pending requests.
109    */
110   struct PendingRequest *pr_head;
111
112   /**
113    * Tail of pending requests.
114    */
115   struct PendingRequest *pr_tail;
116
117   /**
118    * To whom are we talking to.
119    */
120   struct GNUNET_PeerIdentity sender;
121
122   /**
123    * Current distance to the given peer.
124    */
125   uint32_t distance;
126
127   /**
128    * Does the transport service know about this session (and we thus
129    * need to call 'session_end' when it is released?)
130    */
131   int active;
132
133 };
134
135
136 /**
137  * Encapsulation of all of the state of the plugin.
138  */
139 struct Plugin
140 {
141   /**
142    * Our environment.
143    */
144   struct GNUNET_TRANSPORT_PluginEnvironment *env;
145
146   /**
147    * Hash map of sessions (active and inactive).
148    */
149   struct GNUNET_CONTAINER_MultiHashMap *sessions;
150
151   /**
152    * Copy of the handler array where the closures are
153    * set to this struct's instance.
154    */
155   struct GNUNET_SERVER_MessageHandler *handlers;
156
157   /**
158    * Handle to the DV service
159    */
160   struct GNUNET_DV_ServiceHandle *dvh;
161
162   /**
163    * Tokenizer for boxed messages.
164    */
165   struct GNUNET_SERVER_MessageStreamTokenizer *mst; 
166
167 };
168
169
170 /**
171  * Notify transport service about the change in distance.
172  *
173  * @param session session where the distance changed
174  */
175 static void
176 notify_distance_change (struct Session *session)
177 {
178   struct Plugin *plugin = session->plugin;
179   struct GNUNET_ATS_Information ats;
180
181   ats.type = htonl ((uint32_t) GNUNET_ATS_QUALITY_NET_DISTANCE);
182   ats.value = htonl (session->distance);
183   plugin->env->update_address_metrics (plugin->env->cls,
184                                        &session->sender,
185                                        "", 0,
186                                        session,
187                                        &ats, 1);
188 }
189
190
191 /**
192  * Function called by MST on each message from the box.
193  *
194  * @param cls closure with the 'struct Plugin'
195  * @param client identification of the client (with the 'struct Session')
196  * @param message the actual message
197  * @return GNUNET_OK on success
198  */
199 static int
200 unbox_cb (void *cls,
201           void *client,
202           const struct GNUNET_MessageHeader *message)
203 {
204   struct Plugin *plugin = cls;
205   struct Session *session = client;
206   struct GNUNET_ATS_Information ats;
207   
208   ats.type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
209   ats.value = htonl (session->distance);
210   session->active = GNUNET_YES;
211   plugin->env->receive (plugin->env->cls, 
212                         &session->sender,
213                         message,
214                         session, "", 0);
215   plugin->env->update_address_metrics (plugin->env->cls,
216                 &session->sender, "", 0, session, &ats, 1);
217   return GNUNET_OK;
218 }
219
220
221 /**
222  * Handler for messages received from the DV service.
223  *
224  * @param cls closure with the plugin
225  * @param sender sender of the message
226  * @param distance how far did the message travel
227  * @param msg actual message payload 
228  */
229 static void
230 handle_dv_message_received (void *cls,
231                             const struct GNUNET_PeerIdentity *sender,
232                             uint32_t distance,
233                             const struct GNUNET_MessageHeader *msg)
234 {
235   struct Plugin *plugin = cls;
236   struct GNUNET_ATS_Information ats;
237   struct Session *session;
238
239   session = GNUNET_CONTAINER_multihashmap_get (plugin->sessions,
240                                                &sender->hashPubKey);
241   if (NULL == session)    
242   {
243     GNUNET_break (0);
244     return;
245   }
246   if (GNUNET_MESSAGE_TYPE_DV_BOX == ntohs (msg->type))
247   {
248     /* need to unbox using MST */
249     GNUNET_SERVER_mst_receive (plugin->mst, 
250                                session,
251                                (const char *) &msg[1],
252                                ntohs (msg->size) - sizeof (struct GNUNET_MessageHeader),
253                                GNUNET_YES,
254                                GNUNET_NO);
255     return;
256   }
257   ats.type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
258   ats.value = htonl (distance);
259   session->active = GNUNET_YES;
260   plugin->env->receive (plugin->env->cls, sender,
261                         msg,
262                         session, "", 0);
263   plugin->env->update_address_metrics (plugin->env->cls,
264                                        sender, "", 0, session, &ats, 1);
265 }
266
267
268 /**
269  * Function called if DV starts to be able to talk to a peer.
270  *
271  * @param cls closure with 'struct Plugin'
272  * @param peer newly connected peer
273  * @param distance distance to the peer
274  */
275 static void 
276 handle_dv_connect (void *cls,
277                    const struct GNUNET_PeerIdentity *peer,
278                    uint32_t distance)
279 {
280   struct Plugin *plugin = cls;
281   struct Session *session;
282
283   session = GNUNET_CONTAINER_multihashmap_get (plugin->sessions,
284                                                &peer->hashPubKey);
285   if (NULL != session)    
286   {
287     GNUNET_break (0);
288     session->distance = distance;
289     if (GNUNET_YES == session->active)
290       notify_distance_change (session);
291     return; /* nothing to do */  
292   }
293   session = GNUNET_new (struct Session);
294   session->sender = *peer;
295   session->distance = distance;
296   GNUNET_assert (GNUNET_YES ==
297                  GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
298                                                     &session->sender.hashPubKey,
299                                                     session,
300                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
301 }
302
303
304 /**
305  * Function called if DV distance to a peer is changed.
306  *
307  * @param cls closure with 'struct Plugin'
308  * @param peer connected peer
309  * @param distance new distance to the peer
310  */
311 static void 
312 handle_dv_distance_changed (void *cls,
313                             const struct GNUNET_PeerIdentity *peer,
314                             uint32_t distance)
315 {
316   struct Plugin *plugin = cls;
317   struct Session *session;
318
319   session = GNUNET_CONTAINER_multihashmap_get (plugin->sessions,
320                                                &peer->hashPubKey);
321   if (NULL == session)    
322   {
323     GNUNET_break (0);
324     handle_dv_connect (plugin, peer, distance);
325     return;
326   }
327   session->distance = distance;
328   if (GNUNET_YES == session->active)
329     notify_distance_change (session);
330 }
331
332
333 /**
334  * Release session object and clean up associated resources.
335  *
336  * @param session session to clean up
337  */
338 static void
339 free_session (struct Session *session)
340 {
341   struct Plugin *plugin = session->plugin;
342   struct PendingRequest *pr;
343
344   GNUNET_assert (GNUNET_YES ==
345                  GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
346                                                        &session->sender.hashPubKey,
347                                                        session));
348   if (GNUNET_YES == session->active)
349     plugin->env->session_end (plugin->env->cls,
350                               &session->sender,
351                               session);
352   while (NULL != (pr = session->pr_head))
353   {
354     GNUNET_CONTAINER_DLL_remove (session->pr_head,
355                                  session->pr_tail,
356                                  pr);
357     GNUNET_DV_send_cancel (pr->th);
358     pr->th = NULL;
359     if (NULL != pr->transmit_cont)
360       pr->transmit_cont (pr->transmit_cont_cls,
361                          &session->sender,
362                          GNUNET_SYSERR, 0, 0);
363     GNUNET_free (pr);
364   }
365   GNUNET_free (session);
366 }
367
368
369 /**
370  * Function called if DV is no longer able to talk to a peer.
371  *
372  * @param cls closure with 'struct Plugin'
373  * @param peer peer that disconnected
374  */
375 static void 
376 handle_dv_disconnect (void *cls,
377                       const struct GNUNET_PeerIdentity *peer)
378 {
379   struct Plugin *plugin = cls;
380   struct Session *session;
381
382   session = GNUNET_CONTAINER_multihashmap_get (plugin->sessions,
383                                                &peer->hashPubKey);
384   if (NULL == session)    
385     return; /* nothing to do */
386   free_session (session);
387 }
388
389
390 /**
391  * Function called once the delivery of a message has been successful.
392  * Clean up the pending request, and call continuations.
393  *
394  * @param cls closure
395  * @param ok GNUNET_OK on success, GNUNET_SYSERR on error
396  */
397 static void
398 send_finished (void *cls,
399                int ok)
400 {
401   struct PendingRequest *pr = cls;
402   struct Session *session = pr->session;
403
404   pr->th = NULL;
405   GNUNET_CONTAINER_DLL_remove (session->pr_head,
406                                session->pr_tail,
407                                pr);
408   if (NULL != pr->transmit_cont)
409     pr->transmit_cont (pr->transmit_cont_cls,
410                        &session->sender,
411                        ok, 0, 0);
412   GNUNET_free (pr);
413 }
414
415
416 /**
417  * Function that can be used by the transport service to transmit
418  * a message using the plugin.
419  *
420  * @param cls closure
421  * @param session the session used
422  * @param priority how important is the message
423  * @param msgbuf the message to transmit
424  * @param msgbuf_size number of bytes in 'msgbuf'
425  * @param timeout when should we time out
426  * @param cont continuation to call once the message has
427  *        been transmitted (or if the transport is ready
428  *        for the next transmission call; or if the
429  *        peer disconnected...)
430  * @param cont_cls closure for cont
431  * @return number of bytes used (on the physical network, with overheads);
432  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
433  *         and does NOT mean that the message was not transmitted (DV)
434  */
435 static ssize_t
436 dv_plugin_send (void *cls, 
437                 struct Session *session,
438                 const char *msgbuf, size_t msgbuf_size, unsigned int priority,
439                 struct GNUNET_TIME_Relative timeout, 
440                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
441 {
442   struct PendingRequest *pr;
443   const struct GNUNET_MessageHeader *msg;
444   struct GNUNET_MessageHeader *box;
445
446   box = NULL;
447   msg = (const struct GNUNET_MessageHeader *) msgbuf;
448   if (ntohs (msg->size) != msgbuf_size)
449   {
450     /* need to box */
451     box = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader) + msgbuf_size);
452     box->type = htons (GNUNET_MESSAGE_TYPE_DV_BOX);
453     box->size = htons (sizeof (struct GNUNET_MessageHeader) + msgbuf_size);
454     memcpy (&box[1], msgbuf, msgbuf_size);
455     msg = box;
456   }
457   pr = GNUNET_new (struct PendingRequest);
458   pr->transmit_cont = cont;
459   pr->transmit_cont_cls = cont_cls;
460   pr->session = session;
461   GNUNET_CONTAINER_DLL_insert_tail (session->pr_head,
462                                     session->pr_tail,
463                                     pr);
464   pr->th = GNUNET_DV_send (session->plugin->dvh,
465                            &session->sender,
466                            msg,
467                            &send_finished,
468                            pr);
469   GNUNET_free_non_null (box);
470   return 0; /* DV */
471 }
472
473
474 /**
475  * Function that can be used to force the plugin to disconnect
476  * from the given peer and cancel all previous transmissions
477  * (and their continuations).
478  *
479  * @param cls closure
480  * @param target peer from which to disconnect
481  */
482 static void
483 dv_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
484 {
485   struct Plugin *plugin = cls;
486   struct Session *session;
487   struct PendingRequest *pr;
488
489   session = GNUNET_CONTAINER_multihashmap_get (plugin->sessions,
490                                                &target->hashPubKey);
491   if (NULL == session)    
492     return; /* nothing to do */  
493   while (NULL != (pr = session->pr_head))
494   {
495     GNUNET_CONTAINER_DLL_remove (session->pr_head,
496                                  session->pr_tail,
497                                  pr);
498     GNUNET_DV_send_cancel (pr->th);
499     pr->th = NULL;
500     if (NULL != pr->transmit_cont)
501       pr->transmit_cont (pr->transmit_cont_cls,
502                          &session->sender,
503                          GNUNET_SYSERR, 0, 0);
504     GNUNET_free (pr);
505   }
506   session->active = GNUNET_NO;
507 }
508
509
510 /**
511  * Convert the transports address to a nice, human-readable
512  * format.
513  *
514  * @param cls closure
515  * @param type name of the transport that generated the address
516  * @param addr one of the addresses of the host, NULL for the last address
517  *        the specific address format depends on the transport
518  * @param addrlen length of the address
519  * @param numeric should (IP) addresses be displayed in numeric form?
520  * @param timeout after how long should we give up?
521  * @param asc function to call on each string
522  * @param asc_cls closure for asc
523  */
524 static void
525 dv_plugin_address_pretty_printer (void *cls, const char *type, const void *addr,
526                                   size_t addrlen, int numeric,
527                                   struct GNUNET_TIME_Relative timeout,
528                                   GNUNET_TRANSPORT_AddressStringCallback asc,
529                                   void *asc_cls)
530 {
531   if ( (0 == addrlen) &&
532        (0 == strcmp (type, "dv")) )
533     asc (asc_cls, "dv");
534   asc (asc_cls, NULL);
535 }
536
537
538 /**
539  * Convert the DV address to a pretty string.
540  *
541  * @param cls closure
542  * @param addr the (hopefully) DV address
543  * @param addrlen the length of the address
544  *
545  * @return string representing the DV address
546  */
547 static const char *
548 dv_plugin_address_to_string (void *cls, const void *addr, size_t addrlen)
549 {
550   if (0 != addrlen)
551   {
552     GNUNET_break (0); /* malformed */
553     return NULL; 
554   }
555   return "dv";
556 }
557
558
559 /**
560  * Another peer has suggested an address for this peer and transport
561  * plugin.  Check that this could be a valid address.  This function
562  * is not expected to 'validate' the address in the sense of trying to
563  * connect to it but simply to see if the binary format is technically
564  * legal for establishing a connection to this peer (and make sure that
565  * the address really corresponds to our network connection/settings
566  * and not some potential man-in-the-middle).
567  *
568  * @param cls closure
569  * @param addr pointer to the address
570  * @param addrlen length of addr
571  * @return GNUNET_OK if this is a plausible address for this peer
572  *         and transport, GNUNET_SYSERR if not
573  *
574  */
575 static int
576 dv_plugin_check_address (void *cls, const void *addr, size_t addrlen)
577 {
578   if (0 != addrlen)
579     return GNUNET_SYSERR;
580   return GNUNET_OK;
581 }
582
583
584 /**
585  * Create a new session to transmit data to the target
586  * This session will used to send data to this peer and the plugin will
587  * notify us by calling the env->session_end function
588  *
589  * @param cls the plugin
590  * @param address the address
591  * @return the session if the address is valid, NULL otherwise
592  */
593 static struct Session * 
594 dv_get_session (void *cls,
595                 const struct GNUNET_HELLO_Address *address)
596 {
597   struct Plugin *plugin = cls;
598   struct Session *session;
599
600   if (0 != address->address_length)
601     return NULL;
602   session = GNUNET_CONTAINER_multihashmap_get (plugin->sessions,
603                                                &address->peer.hashPubKey);
604   if (NULL == session)
605     return NULL; /* not valid right now */
606   session->active = GNUNET_YES;
607   return session;
608 }
609
610
611 /**
612  * Function called to convert a string address to
613  * a binary address.
614  *
615  * @param cls closure ('struct Plugin*')
616  * @param addr string address
617  * @param addrlen length of the address including \0 termination
618  * @param buf location to store the buffer
619  *        If the function returns GNUNET_SYSERR, its contents are undefined.
620  * @param added length of created address
621  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
622  */
623 static int 
624 dv_plugin_string_to_address (void *cls,
625                              const char *addr,
626                              uint16_t addrlen,
627                              void **buf,
628                              size_t *added)
629 {
630   if ( (addrlen == 3) &&
631        (0 == strcmp ("dv", addr)) )
632   {
633     *added = 0;
634     return GNUNET_OK;
635   }
636   return GNUNET_SYSERR;
637 }
638
639
640
641 /**
642  * Function to obtain the network type for a session
643  * FIXME: we should probably look at the network type
644  * used by the next hop here.  Or find some other way
645  * to properly allow ATS-DV resource allocation.
646  *
647  * @param cls closure ('struct Plugin*')
648  * @param session the session
649  * @return the network type
650  */
651 static enum GNUNET_ATS_Network_Type 
652 dv_get_network (void *cls,
653                 struct Session *session)
654 {
655   GNUNET_assert (NULL != session);
656   return GNUNET_ATS_NET_UNSPECIFIED;
657 }
658
659
660 /**
661  * Entry point for the plugin.
662  *
663  * @param cls closure with the plugin environment
664  * @return plugin API
665  */
666 void *
667 libgnunet_plugin_transport_dv_init (void *cls)
668 {
669   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
670   struct GNUNET_TRANSPORT_PluginFunctions *api;
671   struct Plugin *plugin;
672
673   plugin = GNUNET_new (struct Plugin);
674   plugin->env = env;
675   plugin->sessions = GNUNET_CONTAINER_multihashmap_create (1024 * 8, GNUNET_YES);
676   plugin->mst = GNUNET_SERVER_mst_create (&unbox_cb,
677                                           plugin);
678   plugin->dvh = GNUNET_DV_service_connect (env->cfg,
679                                            plugin,
680                                            &handle_dv_connect,
681                                            &handle_dv_distance_changed,
682                                            &handle_dv_disconnect,
683                                            &handle_dv_message_received);
684   if (NULL == plugin->dvh)
685   {
686     GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
687     GNUNET_SERVER_mst_destroy (plugin->mst);    
688     GNUNET_free (plugin);
689     return NULL;
690   }
691   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
692   api->cls = plugin;
693   api->send = &dv_plugin_send;
694   api->disconnect = &dv_plugin_disconnect;
695   api->address_pretty_printer = &dv_plugin_address_pretty_printer;
696   api->check_address = &dv_plugin_check_address;
697   api->address_to_string = &dv_plugin_address_to_string;
698   api->string_to_address = &dv_plugin_string_to_address;
699   api->get_session = &dv_get_session;
700   api->get_network = &dv_get_network;
701   return api;
702 }
703
704
705 /**
706  * Function called to free a session.
707  *
708  * @param cls NULL
709  * @param key unused
710  * @param value session to free
711  * @return GNUNET_OK (continue to iterate)
712  */
713 static int
714 free_session_iterator (void *cls,
715                        const struct GNUNET_HashCode *key,
716                        void *value)
717 {
718   struct Session *session = value;
719
720   free_session (session);
721   return GNUNET_OK;
722 }
723
724
725 /**
726  * Exit point from the plugin.
727  *
728  * @param cls plugin API
729  * @return NULL
730  */
731 void *
732 libgnunet_plugin_transport_dv_done (void *cls)
733 {
734   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
735   struct Plugin *plugin = api->cls;
736
737   GNUNET_DV_service_disconnect (plugin->dvh);
738   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions,
739                                          &free_session_iterator,
740                                          NULL);
741   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
742   GNUNET_SERVER_mst_destroy (plugin->mst);    
743   GNUNET_free (plugin);
744   GNUNET_free (api);
745   return NULL;
746 }
747
748 /* end of plugin_transport_dv.c */