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