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