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