fixing segfault since session->plugin was NULL
[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   /**
295    * This requires transport plugin to be linked to libgnunetats.
296    * If you remove it, also remove libgnunetats linkage from Makefile.am
297    */
298   LOG (GNUNET_ERROR_TYPE_DEBUG,
299       "Received `%s' message for peer `%s' with next hop in network %s \n",
300       "DV_CONNECT",
301       GNUNET_i2s (peer),
302       GNUNET_ATS_print_network_type (network));
303
304   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
305                                                peer);
306   if (NULL != session)
307   {
308     GNUNET_break (0);
309     session->distance = distance;
310     if (GNUNET_YES == session->active)
311       notify_distance_change (session);
312     return; /* nothing to do */
313   }
314
315   session = GNUNET_new (struct Session);
316   session->sender = *peer;
317   session->plugin = plugin;
318   session->distance = distance;
319   session->network = network;
320   GNUNET_assert(
321       GNUNET_YES == GNUNET_CONTAINER_multipeermap_put (plugin->sessions,
322           &session->sender, session,
323           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
324
325   LOG (GNUNET_ERROR_TYPE_DEBUG,
326       "Creating new session %p for peer `%s'\n",
327       session,
328       GNUNET_i2s (peer));
329
330   /* Notify transport and ats about new connection */
331   ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
332   ats[0].value = htonl (distance);
333   ats[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
334   ats[1].value = htonl (network);
335   plugin->env->session_start (plugin->env->cls, peer, PLUGIN_NAME, NULL, 0,
336       session, ats, 2);
337 }
338
339
340 /**
341  * Function called if DV distance to a peer is changed.
342  *
343  * @param cls closure with 'struct Plugin'
344  * @param peer connected peer
345  * @param distance new distance to the peer
346  */
347 static void
348 handle_dv_distance_changed (void *cls,
349                             const struct GNUNET_PeerIdentity *peer,
350                             uint32_t distance)
351 {
352   struct Plugin *plugin = cls;
353   struct Session *session;
354
355   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message for peer `%s': new distance %u\n",
356       "DV_DISTANCE_CHANGED",
357       GNUNET_i2s (peer), distance);
358
359   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
360                                                peer);
361   if (NULL == session)
362   {
363     GNUNET_break (0);
364     /* FIXME */
365     handle_dv_connect (plugin, peer, distance, 0);
366     return;
367   }
368   session->distance = distance;
369   if (GNUNET_YES == session->active)
370     notify_distance_change (session);
371 }
372
373
374 /**
375  * Release session object and clean up associated resources.
376  *
377  * @param session session to clean up
378  */
379 static void
380 free_session (struct Session *session)
381 {
382   struct Plugin *plugin = session->plugin;
383   struct PendingRequest *pr;
384
385   GNUNET_assert (GNUNET_YES ==
386                  GNUNET_CONTAINER_multipeermap_remove (plugin->sessions,
387                                                        &session->sender,
388                                                        session));
389
390   LOG (GNUNET_ERROR_TYPE_DEBUG,
391       "Freeing session %p for peer `%s'\n",
392       session,
393       GNUNET_i2s (&session->sender));
394
395   if (GNUNET_YES == session->active)
396     plugin->env->session_end (plugin->env->cls,
397                               &session->sender,
398                               session);
399   while (NULL != (pr = session->pr_head))
400   {
401     GNUNET_CONTAINER_DLL_remove (session->pr_head,
402                                  session->pr_tail,
403                                  pr);
404     GNUNET_DV_send_cancel (pr->th);
405     pr->th = NULL;
406     if (NULL != pr->transmit_cont)
407       pr->transmit_cont (pr->transmit_cont_cls,
408                          &session->sender,
409                          GNUNET_SYSERR, 0, 0);
410     GNUNET_free (pr);
411   }
412   GNUNET_free (session);
413 }
414
415
416 /**
417  * Function called if DV is no longer able to talk to a peer.
418  *
419  * @param cls closure with 'struct Plugin'
420  * @param peer peer that disconnected
421  */
422 static void
423 handle_dv_disconnect (void *cls,
424                       const struct GNUNET_PeerIdentity *peer)
425 {
426   struct Plugin *plugin = cls;
427   struct Session *session;
428
429   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message for peer `%s'\n",
430       "DV_DISCONNECT",
431       GNUNET_i2s (peer));
432
433   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
434                                                peer);
435   if (NULL == session)
436     return; /* nothing to do */
437
438   free_session (session);
439 }
440
441
442 /**
443  * Function called once the delivery of a message has been successful.
444  * Clean up the pending request, and call continuations.
445  *
446  * @param cls closure
447  * @param ok GNUNET_OK on success, GNUNET_SYSERR on error
448  */
449 static void
450 send_finished (void *cls,
451                int ok)
452 {
453   struct PendingRequest *pr = cls;
454   struct Session *session = pr->session;
455
456   pr->th = NULL;
457   GNUNET_CONTAINER_DLL_remove (session->pr_head,
458                                session->pr_tail,
459                                pr);
460   if (NULL != pr->transmit_cont)
461     pr->transmit_cont (pr->transmit_cont_cls,
462                        &session->sender,
463                        ok, 0, 0);
464   GNUNET_free (pr);
465 }
466
467
468 /**
469  * Function that can be used by the transport service to transmit
470  * a message using the plugin.
471  *
472  * @param cls closure
473  * @param session the session used
474  * @param priority how important is the message
475  * @param msgbuf the message to transmit
476  * @param msgbuf_size number of bytes in 'msgbuf'
477  * @param timeout when should we time out
478  * @param cont continuation to call once the message has
479  *        been transmitted (or if the transport is ready
480  *        for the next transmission call; or if the
481  *        peer disconnected...)
482  * @param cont_cls closure for cont
483  * @return number of bytes used (on the physical network, with overheads);
484  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
485  *         and does NOT mean that the message was not transmitted (DV)
486  */
487 static ssize_t
488 dv_plugin_send (void *cls,
489                 struct Session *session,
490                 const char *msgbuf, size_t msgbuf_size, unsigned int priority,
491                 struct GNUNET_TIME_Relative timeout,
492                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
493 {
494   struct Plugin *plugin = cls;
495   struct PendingRequest *pr;
496   const struct GNUNET_MessageHeader *msg;
497   struct GNUNET_MessageHeader *box;
498
499   box = NULL;
500   msg = (const struct GNUNET_MessageHeader *) msgbuf;
501   if (ntohs (msg->size) != msgbuf_size)
502   {
503     /* need to box */
504     box = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader) + msgbuf_size);
505     box->type = htons (GNUNET_MESSAGE_TYPE_DV_BOX);
506     box->size = htons (sizeof (struct GNUNET_MessageHeader) + msgbuf_size);
507     memcpy (&box[1], msgbuf, msgbuf_size);
508     msg = box;
509   }
510   pr = GNUNET_new (struct PendingRequest);
511   pr->transmit_cont = cont;
512   pr->transmit_cont_cls = cont_cls;
513   pr->session = session;
514   GNUNET_CONTAINER_DLL_insert_tail (session->pr_head,
515                                     session->pr_tail,
516                                     pr);
517
518   pr->th = GNUNET_DV_send (plugin->dvh,
519                            &session->sender,
520                            msg ,
521                            &send_finished,
522                            pr);
523   GNUNET_free_non_null (box);
524   return 0; /* DV */
525 }
526
527
528 /**
529  * Function that can be used to force the plugin to disconnect
530  * from the given peer and cancel all previous transmissions
531  * (and their continuations).
532  *
533  * @param cls closure
534  * @param target peer from which to disconnect
535  */
536 static void
537 dv_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
538 {
539   struct Plugin *plugin = cls;
540   struct Session *session;
541   struct PendingRequest *pr;
542
543   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
544                                                target);
545   if (NULL == session)
546     return; /* nothing to do */
547   while (NULL != (pr = session->pr_head))
548   {
549     GNUNET_CONTAINER_DLL_remove (session->pr_head,
550                                  session->pr_tail,
551                                  pr);
552     GNUNET_DV_send_cancel (pr->th);
553     pr->th = NULL;
554     if (NULL != pr->transmit_cont)
555       pr->transmit_cont (pr->transmit_cont_cls,
556                          &session->sender,
557                          GNUNET_SYSERR, 0, 0);
558     GNUNET_free (pr);
559   }
560   session->active = GNUNET_NO;
561 }
562
563
564 /**
565  * Convert the transports address to a nice, human-readable
566  * format.
567  *
568  * @param cls closure
569  * @param type name of the transport that generated the address
570  * @param addr one of the addresses of the host, NULL for the last address
571  *        the specific address format depends on the transport
572  * @param addrlen length of the address
573  * @param numeric should (IP) addresses be displayed in numeric form?
574  * @param timeout after how long should we give up?
575  * @param asc function to call on each string
576  * @param asc_cls closure for asc
577  */
578 static void
579 dv_plugin_address_pretty_printer (void *cls, const char *type, const void *addr,
580                                   size_t addrlen, int numeric,
581                                   struct GNUNET_TIME_Relative timeout,
582                                   GNUNET_TRANSPORT_AddressStringCallback asc,
583                                   void *asc_cls)
584 {
585   if ( (0 == addrlen) &&
586        (0 == strcmp (type, "dv")) )
587     asc (asc_cls, "dv");
588   asc (asc_cls, NULL);
589 }
590
591
592 /**
593  * Convert the DV address to a pretty string.
594  *
595  * @param cls closure
596  * @param addr the (hopefully) DV address
597  * @param addrlen the length of the address
598  *
599  * @return string representing the DV address
600  */
601 static const char *
602 dv_plugin_address_to_string (void *cls, const void *addr, size_t addrlen)
603 {
604   if (0 != addrlen)
605   {
606     GNUNET_break (0); /* malformed */
607     return NULL;
608   }
609   return "dv";
610 }
611
612
613 /**
614  * Another peer has suggested an address for this peer and transport
615  * plugin.  Check that this could be a valid address.  This function
616  * is not expected to 'validate' the address in the sense of trying to
617  * connect to it but simply to see if the binary format is technically
618  * legal for establishing a connection to this peer (and make sure that
619  * the address really corresponds to our network connection/settings
620  * and not some potential man-in-the-middle).
621  *
622  * @param cls closure
623  * @param addr pointer to the address
624  * @param addrlen length of addr
625  * @return GNUNET_OK if this is a plausible address for this peer
626  *         and transport, GNUNET_SYSERR if not
627  *
628  */
629 static int
630 dv_plugin_check_address (void *cls, const void *addr, size_t addrlen)
631 {
632   if (0 != addrlen)
633     return GNUNET_SYSERR;
634   return GNUNET_OK;
635 }
636
637
638 /**
639  * Create a new session to transmit data to the target
640  * This session will used to send data to this peer and the plugin will
641  * notify us by calling the env->session_end function
642  *
643  * @param cls the plugin
644  * @param address the address
645  * @return the session if the address is valid, NULL otherwise
646  */
647 static struct Session *
648 dv_get_session (void *cls,
649                 const struct GNUNET_HELLO_Address *address)
650 {
651   struct Plugin *plugin = cls;
652   struct Session *session;
653
654   if (0 != address->address_length)
655     return NULL;
656   session = GNUNET_CONTAINER_multipeermap_get (plugin->sessions,
657                                                &address->peer);
658   if (NULL == session)
659     return NULL; /* not valid right now */
660   session->active = GNUNET_YES;
661   return session;
662 }
663
664
665 /**
666  * Function called to convert a string address to
667  * a binary address.
668  *
669  * @param cls closure ('struct Plugin*')
670  * @param addr string address
671  * @param addrlen length of the address including \0 termination
672  * @param buf location to store the buffer
673  *        If the function returns GNUNET_SYSERR, its contents are undefined.
674  * @param added length of created address
675  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
676  */
677 static int
678 dv_plugin_string_to_address (void *cls,
679                              const char *addr,
680                              uint16_t addrlen,
681                              void **buf,
682                              size_t *added)
683 {
684   if ( (addrlen == 3) &&
685        (0 == strcmp ("dv", addr)) )
686   {
687     *added = 0;
688     return GNUNET_OK;
689   }
690   return GNUNET_SYSERR;
691 }
692
693
694
695 /**
696  * Function to obtain the network type for a session
697  * FIXME: we should probably look at the network type
698  * used by the next hop here.  Or find some other way
699  * to properly allow ATS-DV resource allocation.
700  *
701  * @param cls closure ('struct Plugin*')
702  * @param session the session
703  * @return the network type
704  */
705 static enum GNUNET_ATS_Network_Type
706 dv_get_network (void *cls,
707                 struct Session *session)
708 {
709   GNUNET_assert (NULL != session);
710   return session->network;
711 }
712
713
714 /**
715  * Entry point for the plugin.
716  *
717  * @param cls closure with the plugin environment
718  * @return plugin API
719  */
720 void *
721 libgnunet_plugin_transport_dv_init (void *cls)
722 {
723   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
724   struct GNUNET_TRANSPORT_PluginFunctions *api;
725   struct Plugin *plugin;
726
727   plugin = GNUNET_new (struct Plugin);
728   plugin->env = env;
729   plugin->sessions = GNUNET_CONTAINER_multipeermap_create (1024 * 8, GNUNET_YES);
730   plugin->mst = GNUNET_SERVER_mst_create (&unbox_cb,
731                                           plugin);
732   plugin->dvh = GNUNET_DV_service_connect (env->cfg,
733                                            plugin,
734                                            &handle_dv_connect,
735                                            &handle_dv_distance_changed,
736                                            &handle_dv_disconnect,
737                                            &handle_dv_message_received);
738   if (NULL == plugin->dvh)
739   {
740     GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
741     GNUNET_SERVER_mst_destroy (plugin->mst);
742     GNUNET_free (plugin);
743     return NULL;
744   }
745   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
746   api->cls = plugin;
747   api->send = &dv_plugin_send;
748   api->disconnect = &dv_plugin_disconnect;
749   api->address_pretty_printer = &dv_plugin_address_pretty_printer;
750   api->check_address = &dv_plugin_check_address;
751   api->address_to_string = &dv_plugin_address_to_string;
752   api->string_to_address = &dv_plugin_string_to_address;
753   api->get_session = &dv_get_session;
754   api->get_network = &dv_get_network;
755   return api;
756 }
757
758
759 /**
760  * Function called to free a session.
761  *
762  * @param cls NULL
763  * @param key unused
764  * @param value session to free
765  * @return GNUNET_OK (continue to iterate)
766  */
767 static int
768 free_session_iterator (void *cls,
769                        const struct GNUNET_PeerIdentity *key,
770                        void *value)
771 {
772   struct Session *session = value;
773
774   free_session (session);
775   return GNUNET_OK;
776 }
777
778
779 /**
780  * Exit point from the plugin.
781  *
782  * @param cls plugin API
783  * @return NULL
784  */
785 void *
786 libgnunet_plugin_transport_dv_done (void *cls)
787 {
788   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
789   struct Plugin *plugin = api->cls;
790
791   GNUNET_DV_service_disconnect (plugin->dvh);
792   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
793                                          &free_session_iterator,
794                                          NULL);
795   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
796   GNUNET_SERVER_mst_destroy (plugin->mst);
797   GNUNET_free (plugin);
798   GNUNET_free (api);
799   return NULL;
800 }
801
802 /* end of plugin_transport_dv.c */