improving r17722
[oweals/gnunet.git] / src / transport / gnunet-service-transport.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010,2011 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 transport/gnunet-service-transport-new.c
23  * @brief
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet_transport_service.h"
30 #include "gnunet_peerinfo_service.h"
31 #include "gnunet_ats_service.h"
32 #include "gnunet-service-transport.h"
33 #include "gnunet-service-transport_blacklist.h"
34 #include "gnunet-service-transport_clients.h"
35 #include "gnunet-service-transport_hello.h"
36 #include "gnunet-service-transport_neighbours.h"
37 #include "gnunet-service-transport_plugins.h"
38 #include "gnunet-service-transport_validation.h"
39 #include "transport.h"
40
41 /* globals */
42
43 /**
44  * Statistics handle.
45  */
46 struct GNUNET_STATISTICS_Handle *GST_stats;
47
48 /**
49  * Configuration handle.
50  */
51 const struct GNUNET_CONFIGURATION_Handle *GST_cfg;
52
53 /**
54  * Configuration handle.
55  */
56 struct GNUNET_PeerIdentity GST_my_identity;
57
58 /**
59  * Handle to peerinfo service.
60  */
61 struct GNUNET_PEERINFO_Handle *GST_peerinfo;
62
63 /**
64  * Our public key.
65  */
66 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded GST_my_public_key;
67
68 /**
69  * Our private key.
70  */
71 struct GNUNET_CRYPTO_RsaPrivateKey *GST_my_private_key;
72
73 /**
74  * ATS handle.
75  */
76 struct GNUNET_ATS_SchedulingHandle *GST_ats;
77
78
79 /**
80  * Transmit our HELLO message to the given (connected) neighbour.
81  *
82  * @param cls the 'HELLO' message
83  * @param target a connected neighbour
84  * @param ats performance information (unused)
85  * @param ats_count number of records in ats (unused)
86  * @param transport plugin
87  * @param addr address
88  * @param addrlen address length
89  */
90 static void
91 transmit_our_hello (void *cls, const struct GNUNET_PeerIdentity *target,
92                     const struct GNUNET_ATS_Information *ats,
93                     uint32_t ats_count,
94                     const char * transport,
95                     const void * addr,
96                     size_t addrlen)
97 {
98   const struct GNUNET_MessageHeader *hello = cls;
99
100   GST_neighbours_send (target, (const char *) hello, ntohs (hello->size),
101                        GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION, NULL, NULL);
102 }
103
104
105 /**
106  * My HELLO has changed. Tell everyone who should know.
107  *
108  * @param cls unused
109  * @param hello new HELLO
110  */
111 static void
112 process_hello_update (void *cls, const struct GNUNET_MessageHeader *hello)
113 {
114   GST_clients_broadcast (hello, GNUNET_NO);
115   GST_neighbours_iterate (&transmit_our_hello, (void *) hello);
116 }
117
118
119 /**
120  * Try to initiate a connection to the given peer if the blacklist
121  * allowed it.
122  *
123  * @param cls closure (unused, NULL)
124  * @param peer identity of peer that was tested
125  * @param result GNUNET_OK if the connection is allowed,
126  *               GNUNET_NO if not
127  */
128 static void
129 try_connect_if_allowed (void *cls, const struct GNUNET_PeerIdentity *peer,
130                         int result)
131 {
132   if (GNUNET_OK != result)
133     return;                     /* not allowed */
134   GST_neighbours_try_connect (peer);
135 }
136
137
138 /**
139  * We received some payload.  Prepare to pass it on to our clients. 
140  *
141  * @param peer (claimed) identity of the other peer
142  * @param message the message, NULL if we only care about
143  *                learning about the delay until we should receive again -- FIXME!
144  * @param ats performance information
145  * @param ats_count number of records in ats
146  * @return how long the plugin should wait until receiving more data
147  */
148 static struct GNUNET_TIME_Relative
149 process_payload (const struct GNUNET_PeerIdentity *peer,
150                  const struct GNUNET_MessageHeader *message,
151                  const struct GNUNET_ATS_Information *ats,
152                  uint32_t ats_count)
153 {
154   struct GNUNET_TIME_Relative ret;
155   int do_forward;
156   struct InboundMessage *im;
157   size_t size = sizeof (struct InboundMessage) + ntohs (message->size) + sizeof (struct GNUNET_ATS_Information) * ats_count;
158   char buf[size];
159   struct GNUNET_ATS_Information *ap;
160   
161   ret = GNUNET_TIME_UNIT_ZERO;
162   do_forward = GNUNET_SYSERR;
163   ret =
164     GST_neighbours_calculate_receive_delay (peer,
165                                             (message ==
166                                              NULL) ? 0 :
167                                             ntohs (message->size),
168                                             &do_forward);
169   im = (struct InboundMessage*) buf;    
170   im->header.size = htons (size);
171   im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
172   im->ats_count = htonl (ats_count);
173   im->peer = *peer;
174   ap = (struct GNUNET_ATS_Information*) &im[1];
175   memcpy (ap, ats, ats_count * sizeof (struct GNUNET_ATS_Information));
176   memcpy (&ap[ats_count], message, ntohs (message->size));
177
178   switch (do_forward)
179   {
180   case GNUNET_YES:
181     GST_clients_broadcast (&im->header, GNUNET_YES);      
182     break;
183   case GNUNET_NO:
184     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
185                 _("Discarded %u bytes of type %u from %s: quota violated or no neighbour record!\n"),
186                 ntohs (message->size),
187                 ntohs (message->type),
188                 GNUNET_i2s (peer));
189     break;
190   case GNUNET_SYSERR:
191     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
192                 _("Discarded %u bytes of type %u from %s: connection is down!\n"),
193                 ntohs (message->size),
194                 ntohs (message->type),
195                 GNUNET_i2s (peer));
196     /* FIXME: store until connection is up? This is virtually always a SETKEY and a PING... */
197     break;
198   default:
199     GNUNET_break (0);
200     break;
201   }    
202   return ret;
203 }
204
205
206 /**
207  * Function called by the transport for each received message.
208  * This function should also be called with "NULL" for the
209  * message to signal that the other peer disconnected.
210  *
211  * @param cls closure, const char* with the name of the plugin we received the message from
212  * @param peer (claimed) identity of the other peer
213  * @param message the message, NULL if we only care about
214  *                learning about the delay until we should receive again -- FIXME!
215  * @param ats performance information
216  * @param ats_count number of records in ats
217  * @param session identifier used for this session (NULL for plugins
218  *                that do not offer bi-directional communication to the sender
219  *                using the same "connection")
220  * @param sender_address binary address of the sender (if we established the
221  *                connection or are otherwise sure of it; should be NULL
222  *                for inbound TCP/UDP connections since it it not clear
223  *                that we could establish ourselves a connection to that
224  *                IP address and get the same system)
225  * @param sender_address_len number of bytes in sender_address
226  * @return how long the plugin should wait until receiving more data
227  *         (plugins that do not support this, can ignore the return value)
228  */
229 static struct GNUNET_TIME_Relative
230 plugin_env_receive_callback (void *cls, const struct GNUNET_PeerIdentity *peer,
231                              const struct GNUNET_MessageHeader *message,
232                              const struct GNUNET_ATS_Information *ats,
233                              uint32_t ats_count, struct Session *session,
234                              const char *sender_address,
235                              uint16_t sender_address_len)
236 {
237   const char *plugin_name = cls;
238   struct GNUNET_TIME_Relative ret;
239   uint16_t type;
240   
241   ret = GNUNET_TIME_UNIT_ZERO;
242   if (NULL == message)
243     goto end;
244   type = ntohs (message->type);
245   switch (type)
246   {
247   case GNUNET_MESSAGE_TYPE_HELLO:
248     GST_validation_handle_hello (message);
249     return ret;
250   case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
251 #if DEBUG_TRANSPORT
252     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
253                 "Processing `%s' from `%s'\n", "PING",
254                 (sender_address != NULL) ? GST_plugins_a2s (plugin_name,
255                                                             sender_address,
256                                                             sender_address_len)
257                 : "<inbound>");
258 #endif
259     GST_validation_handle_ping (peer, message, plugin_name, session,
260                                 sender_address, sender_address_len);
261     break;
262   case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
263 #if DEBUG_TRANSPORT
264     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
265                 "Processing `%s' from `%s'\n", "PONG",
266                 (sender_address != NULL) ? GST_plugins_a2s (plugin_name,
267                                                             sender_address,
268                                                             sender_address_len)
269                 : "<inbound>");
270 #endif
271     GST_validation_handle_pong (peer, message);
272     break;
273   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT:
274     GST_neighbours_handle_connect (message,
275                                    peer,
276                                    plugin_name, sender_address, sender_address_len,
277                                    session, ats, ats_count);
278     (void) GST_blacklist_test_allowed (peer, NULL, &try_connect_if_allowed,
279                                        NULL);
280     break;
281   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT:
282     GST_neighbours_handle_disconnect_message (peer, message);
283     break;
284   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE:
285     GST_neighbours_keepalive (peer);
286     break;
287   default:
288     /* should be payload */
289     ret = process_payload (peer,
290                            message,
291                            ats, ats_count);
292     break;
293   }
294  end:
295 #if 1
296   /* FIXME: this should not be needed, and not sure it's good to have it, but without
297      this connections seem to go extra-slow */
298   GNUNET_ATS_address_update (GST_ats, peer,
299                              plugin_name, sender_address, sender_address_len,
300                              session,
301                              ats, ats_count);  
302 #endif
303 #if DEBUG_TRANSPORT
304   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
305               "Allowing receive from peer %s to continue in %llu ms\n",
306               GNUNET_i2s (peer),
307               (unsigned long long) ret.rel_value);
308 #endif
309   return ret;
310 }
311
312
313 /**
314  * Function that will be called for each address the transport
315  * is aware that it might be reachable under.  Update our HELLO.
316  *
317  * @param cls name of the plugin (const char*)
318  * @param add_remove should the address added (YES) or removed (NO) from the
319  *                   set of valid addresses?
320  * @param addr one of the addresses of the host
321  *        the specific address format depends on the transport
322  * @param addrlen length of the address
323  */
324 static void
325 plugin_env_address_change_notification (void *cls, int add_remove,
326                                         const void *addr, size_t addrlen)
327 {
328   const char *plugin_name = cls;
329
330   GST_hello_modify_addresses (add_remove, plugin_name, addr, addrlen);
331 }
332
333
334 /**
335  * Function that will be called whenever the plugin internally
336  * cleans up a session pointer and hence the service needs to
337  * discard all of those sessions as well.  Plugins that do not
338  * use sessions can simply omit calling this function and always
339  * use NULL wherever a session pointer is needed.  This function
340  * should be called BEFORE a potential "TransmitContinuation"
341  * from the "TransmitFunction".
342  *
343  * @param cls closure
344  * @param peer which peer was the session for
345  * @param session which session is being destoyed
346  */
347 static void
348 plugin_env_session_end (void *cls, const struct GNUNET_PeerIdentity *peer,
349                         struct Session *session)
350 {
351 #if DEBUG_TRANSPORT
352   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
353               "Session %X to peer `%s' ended \n",
354               session, GNUNET_i2s (peer));
355 #endif
356   if (NULL != session)
357     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO  | GNUNET_ERROR_TYPE_BULK,
358                      "transport-ats",
359                      "Telling ATS to destroy session %p from peer %s\n",
360                      session,              
361                      GNUNET_i2s (peer));
362   GNUNET_ATS_address_destroyed (GST_ats, peer, NULL, NULL, 0, session);
363   GST_neighbours_session_terminated (peer, session);
364 }
365
366
367 /**
368  * Function called by ATS to notify the callee that the
369  * assigned bandwidth or address for a given peer was changed.  If the
370  * callback is called with address/bandwidth assignments of zero, the
371  * ATS disconnect function will still be called once the disconnect
372  * actually happened.
373  *
374  * @param cls closure
375  * @param peer identity of the peer
376  * @param plugin_name name of the transport plugin, NULL to disconnect
377  * @param session session to use (if available)
378  * @param plugin_addr address to use (if available)
379  * @param plugin_addr_len number of bytes in addr
380  * @param bandwidth_out assigned outbound bandwidth for the connection, 0 to disconnect from peer
381  * @param bandwidth_in assigned inbound bandwidth for the connection, 0 to disconnect from peer
382  */
383 static void
384 ats_request_address_change (void *cls, const struct GNUNET_PeerIdentity *peer,
385                             const char *plugin_name,
386                             const void *plugin_addr, size_t plugin_addr_len,
387                             struct Session *session,
388                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
389                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
390                             const struct GNUNET_ATS_Information * ats,
391                             uint32_t ats_count)
392 {
393   uint32_t bw_in = ntohl (bandwidth_in.value__);
394   uint32_t bw_out = ntohl (bandwidth_out.value__);
395   struct QuotaSetMessage msg;
396
397   /* ATS tells me to disconnect from peer*/
398   if ((bw_in == 0) && (bw_out == 0))
399   {
400 #if DEBUG_TRANSPORT
401     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
402                 "ATS tells me to disconnect from peer `%s'\n",
403                 GNUNET_i2s (peer));
404 #endif
405     GST_neighbours_force_disconnect(peer);
406     return;
407   }
408   if (GNUNET_YES !=
409       GST_neighbours_switch_to_address (peer, plugin_name, plugin_addr,
410                                         plugin_addr_len, session, ats, ats_count))
411   {
412 #if DEBUG_TRANSPORT
413     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
414                 "Connection is not yet up, ignoring quota for now\n");
415 #endif
416     /* FIXME: maybe we should let ATS know somehow?  This is a problem
417        with the design; ATS may assign bandwidth, but we don't use it;
418        the current ATS API doesn't give us a good way to sync the
419        connection status between ATS and TRANSPORT */
420     return;
421   }
422 #if DEBUG_TRANSPORT
423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
424               "Sending outbound quota of %u Bps for peer `%s' to all clients\n",
425               ntohl (bandwidth_out.value__), GNUNET_i2s (peer));
426 #endif
427   msg.header.size = htons (sizeof (struct QuotaSetMessage));
428   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
429   msg.quota = bandwidth_out;
430   msg.peer = (*peer);
431   GST_clients_broadcast (&msg.header, GNUNET_NO);  
432 #if DEBUG_TRANSPORT
433   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
434               "Setting inbound quota of %u for peer `%s' to \n",
435               ntohl (bandwidth_in.value__), GNUNET_i2s (peer));
436 #endif
437   GST_neighbours_set_incoming_quota (peer, bandwidth_in);
438 }
439
440
441 /**
442  * Function called to notify transport users that another
443  * peer connected to us.
444  *
445  * @param cls closure
446  * @param peer the peer that connected
447  * @param ats performance data
448  * @param ats_count number of entries in ats
449  */
450 static void
451 neighbours_connect_notification (void *cls,
452                                  const struct GNUNET_PeerIdentity *peer,
453                                  const struct GNUNET_ATS_Information
454                                  *ats, uint32_t ats_count)
455 {
456   size_t len = sizeof (struct ConnectInfoMessage) +
457       ats_count * sizeof (struct GNUNET_ATS_Information);
458   char buf[len];
459   struct ConnectInfoMessage *connect_msg = (struct ConnectInfoMessage *) buf;
460   struct GNUNET_ATS_Information *ap;
461
462   connect_msg->header.size = htons (sizeof (buf));
463   connect_msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
464   connect_msg->ats_count = htonl (ats_count);
465   connect_msg->id = *peer;
466   ap = (struct GNUNET_ATS_Information *) &connect_msg[1];
467   memcpy (ap, ats,
468           ats_count * sizeof (struct GNUNET_ATS_Information));
469   GST_clients_broadcast (&connect_msg->header, GNUNET_NO);
470 }
471
472
473 /**
474  * Function called to notify transport users that another
475  * peer disconnected from us.
476  *
477  * @param cls closure
478  * @param peer the peer that disconnected
479  */
480 static void
481 neighbours_disconnect_notification (void *cls,
482                                     const struct GNUNET_PeerIdentity *peer)
483 {
484   struct DisconnectInfoMessage disconnect_msg;
485
486   disconnect_msg.header.size = htons (sizeof (struct DisconnectInfoMessage));
487   disconnect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
488   disconnect_msg.reserved = htonl (0);
489   disconnect_msg.peer = *peer;
490   GST_clients_broadcast (&disconnect_msg.header, GNUNET_NO);
491 }
492
493
494 /**
495  * Function called when the service shuts down.  Unloads our plugins
496  * and cancels pending validations.
497  *
498  * @param cls closure, unused
499  * @param tc task context (unused)
500  */
501 static void
502 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
503 {
504   GST_validation_stop ();
505   GST_plugins_unload ();
506   GST_neighbours_stop ();
507   GNUNET_ATS_scheduling_done (GST_ats);
508   GST_ats = NULL;
509   GST_clients_stop ();
510   GST_blacklist_stop ();
511   GST_hello_stop ();
512
513   if (GST_peerinfo != NULL)
514   {
515     GNUNET_PEERINFO_disconnect (GST_peerinfo);
516     GST_peerinfo = NULL;
517   }
518   if (GST_stats != NULL)
519   {
520     GNUNET_STATISTICS_destroy (GST_stats, GNUNET_NO);
521     GST_stats = NULL;
522   }
523   if (GST_my_private_key != NULL)
524   {
525     GNUNET_CRYPTO_rsa_key_free (GST_my_private_key);
526     GST_my_private_key = NULL;
527   }
528 }
529
530
531 /**
532  * Initiate transport service.
533  *
534  * @param cls closure
535  * @param server the initialized server
536  * @param c configuration to use
537  */
538 static void
539 run (void *cls, struct GNUNET_SERVER_Handle *server,
540      const struct GNUNET_CONFIGURATION_Handle *c)
541 {
542   char *keyfile;
543
544   /* setup globals */
545   GST_cfg = c;
546   if (GNUNET_OK !=
547       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
548                                                &keyfile))
549   {
550     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
551                 _
552                 ("Transport service is lacking key configuration settings.  Exiting.\n"));
553     GNUNET_SCHEDULER_shutdown ();
554     return;
555   }
556   GST_my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
557   GNUNET_free (keyfile);
558   if (GST_my_private_key == NULL)
559   {
560     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
561                 _("Transport service could not access hostkey.  Exiting.\n"));
562     GNUNET_SCHEDULER_shutdown ();
563     return;
564   }
565   GST_stats = GNUNET_STATISTICS_create ("transport", c);
566   GST_peerinfo = GNUNET_PEERINFO_connect (c);
567   GNUNET_CRYPTO_rsa_key_get_public (GST_my_private_key, &GST_my_public_key);
568   GNUNET_CRYPTO_hash (&GST_my_public_key, sizeof (GST_my_public_key),
569                       &GST_my_identity.hashPubKey);
570   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
571                                 NULL);
572   if (GST_peerinfo == NULL)
573   {
574     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
575                 _("Could not access PEERINFO service.  Exiting.\n"));
576     GNUNET_SCHEDULER_shutdown ();
577     return;
578   }
579
580   /* start subsystems */
581   GST_hello_start (&process_hello_update, NULL);
582   GST_blacklist_start (server);
583   GST_plugins_load (&plugin_env_receive_callback,
584                     &plugin_env_address_change_notification,
585                     &plugin_env_session_end);
586   GST_ats = GNUNET_ATS_scheduling_init (GST_cfg, &ats_request_address_change, NULL);
587   GST_neighbours_start (NULL, &neighbours_connect_notification,
588                         &neighbours_disconnect_notification);
589   GST_clients_start (server);
590   GST_validation_start ();
591 }
592
593
594 /**
595  * The main function for the transport service.
596  *
597  * @param argc number of arguments from the command line
598  * @param argv command line arguments
599  * @return 0 ok, 1 on error
600  */
601 int
602 main (int argc, char *const *argv)
603 {
604   return (GNUNET_OK ==
605           GNUNET_SERVICE_run (argc, argv, "transport",
606                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
607 }
608
609 /* end of file gnunet-service-transport-new.c */