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