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