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