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