curly wars / auto-indentation
[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.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, const char *transport, const void *addr,
94                     size_t addrlen)
95 {
96   const struct GNUNET_MessageHeader *hello = cls;
97
98   GST_neighbours_send (target, (const char *) hello, ntohs (hello->size),
99                        GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION, NULL, NULL);
100 }
101
102
103 /**
104  * My HELLO has changed. Tell everyone who should know.
105  *
106  * @param cls unused
107  * @param hello new HELLO
108  */
109 static void
110 process_hello_update (void *cls, const struct GNUNET_MessageHeader *hello)
111 {
112   GST_clients_broadcast (hello, GNUNET_NO);
113   GST_neighbours_iterate (&transmit_our_hello, (void *) hello);
114 }
115
116
117
118 /**
119  * We received some payload.  Prepare to pass it on to our clients.
120  *
121  * @param peer (claimed) identity of the other peer
122  * @param message the message, never NULL
123  * @param ats performance information
124  * @param ats_count number of records in ats
125  * @return how long the plugin should wait until receiving more data
126  */
127 static struct GNUNET_TIME_Relative
128 process_payload (const struct GNUNET_PeerIdentity *peer,
129                  const struct GNUNET_MessageHeader *message,
130                  const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
131 {
132   struct GNUNET_TIME_Relative ret;
133   int do_forward;
134   struct InboundMessage *im;
135   size_t msg_size = ntohs (message->size);
136   size_t size =
137       sizeof (struct InboundMessage) + msg_size +
138       sizeof (struct GNUNET_ATS_Information) * ats_count;
139   char buf[size];
140   struct GNUNET_ATS_Information *ap;
141
142   ret = GNUNET_TIME_UNIT_ZERO;
143   do_forward = GNUNET_SYSERR;
144   ret = GST_neighbours_calculate_receive_delay (peer, msg_size, &do_forward);
145
146   if (!GST_neighbours_test_connected (peer))
147   {
148
149     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
150                 "Discarded %u bytes type %u payload from peer `%s'\n", msg_size,
151                 ntohs (message->type), GNUNET_i2s (peer));
152
153     GNUNET_STATISTICS_update (GST_stats,
154                               gettext_noop
155                               ("# bytes payload discarded due to not connected peer "),
156                               msg_size, GNUNET_NO);
157     return ret;
158   }
159
160   if (do_forward != GNUNET_YES)
161     return ret;
162   im = (struct InboundMessage *) buf;
163   im->header.size = htons (size);
164   im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
165   im->ats_count = htonl (ats_count);
166   im->peer = *peer;
167   ap = (struct GNUNET_ATS_Information *) &im[1];
168   memcpy (ap, ats, ats_count * sizeof (struct GNUNET_ATS_Information));
169   memcpy (&ap[ats_count], message, ntohs (message->size));
170
171   GST_clients_broadcast (&im->header, GNUNET_YES);
172
173   return ret;
174 }
175
176
177 /**
178  * Function called by the transport for each received message.
179  * This function should also be called with "NULL" for the
180  * message to signal that the other peer disconnected.
181  *
182  * @param cls closure, const char* with the name of the plugin we received the message from
183  * @param peer (claimed) identity of the other peer
184  * @param message the message, NULL if we only care about
185  *                learning about the delay until we should receive again -- FIXME!
186  * @param ats performance information
187  * @param ats_count number of records in ats
188  * @param session identifier used for this session (NULL for plugins
189  *                that do not offer bi-directional communication to the sender
190  *                using the same "connection")
191  * @param sender_address binary address of the sender (if we established the
192  *                connection or are otherwise sure of it; should be NULL
193  *                for inbound TCP/UDP connections since it it not clear
194  *                that we could establish ourselves a connection to that
195  *                IP address and get the same system)
196  * @param sender_address_len number of bytes in sender_address
197  * @return how long the plugin should wait until receiving more data
198  *         (plugins that do not support this, can ignore the return value)
199  */
200 static struct GNUNET_TIME_Relative
201 plugin_env_receive_callback (void *cls, const struct GNUNET_PeerIdentity *peer,
202                              const struct GNUNET_MessageHeader *message,
203                              const struct GNUNET_ATS_Information *ats,
204                              uint32_t ats_count, struct Session *session,
205                              const char *sender_address,
206                              uint16_t sender_address_len)
207 {
208   const char *plugin_name = cls;
209   struct GNUNET_TIME_Relative ret;
210   uint16_t type;
211
212   ret = GNUNET_TIME_UNIT_ZERO;
213   if (NULL == message)
214     goto end;
215   type = ntohs (message->type);
216 #if DEBUG_TRANSPORT
217
218   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Received Message with type %u\n", type);
219 #endif
220
221   switch (type)
222   {
223   case GNUNET_MESSAGE_TYPE_HELLO:
224     GST_validation_handle_hello (message);
225     return ret;
226   case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
227 #if DEBUG_TRANSPORT
228     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
229                 "Processing `%s' from `%s'\n", "PING",
230                 (sender_address != NULL) ? GST_plugins_a2s (plugin_name,
231                                                             sender_address,
232                                                             sender_address_len)
233                 : "<inbound>");
234 #endif
235     GST_validation_handle_ping (peer, message, plugin_name, session,
236                                 sender_address, sender_address_len);
237     break;
238   case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
239 #if DEBUG_TRANSPORT
240     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
241                 "Processing `%s' from `%s'\n", "PONG",
242                 (sender_address != NULL) ? GST_plugins_a2s (plugin_name,
243                                                             sender_address,
244                                                             sender_address_len)
245                 : "<inbound>");
246 #endif
247     GST_validation_handle_pong (peer, message);
248     break;
249   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT:
250     GST_neighbours_handle_connect (message, peer, plugin_name, sender_address,
251                                    sender_address_len, session, ats, ats_count);
252     break;
253   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK:
254     GST_neighbours_handle_connect_ack (message, peer, plugin_name,
255                                        sender_address, sender_address_len,
256                                        session, ats, ats_count);
257     break;
258   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK:
259     GST_neighbours_handle_ack (message, peer, plugin_name, sender_address,
260                                sender_address_len, session, ats, ats_count);
261     break;
262   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT:
263     GST_neighbours_handle_disconnect_message (peer, message);
264     break;
265   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE:
266     GST_neighbours_keepalive (peer);
267     break;
268   default:
269     /* should be payload */
270     ret = process_payload (peer, message, ats, ats_count);
271     break;
272   }
273 end:
274 #if 1
275   /* FIXME: this should not be needed, and not sure it's good to have it, but without
276    * this connections seem to go extra-slow */
277   GNUNET_ATS_address_update (GST_ats, peer, plugin_name, sender_address,
278                              sender_address_len, session, ats, ats_count);
279 #endif
280 #if DEBUG_TRANSPORT
281   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
282               "Allowing receive from peer %s to continue in %llu ms\n",
283               GNUNET_i2s (peer), (unsigned long long) ret.rel_value);
284 #endif
285   return ret;
286 }
287
288
289 /**
290  * Function that will be called for each address the transport
291  * is aware that it might be reachable under.  Update our HELLO.
292  *
293  * @param cls name of the plugin (const char*)
294  * @param add_remove should the address added (YES) or removed (NO) from the
295  *                   set of valid addresses?
296  * @param addr one of the addresses of the host
297  *        the specific address format depends on the transport
298  * @param addrlen length of the address
299  */
300 static void
301 plugin_env_address_change_notification (void *cls, int add_remove,
302                                         const void *addr, size_t addrlen)
303 {
304   const char *plugin_name = cls;
305
306   GST_hello_modify_addresses (add_remove, plugin_name, addr, addrlen);
307 }
308
309
310 /**
311  * Function that will be called whenever the plugin internally
312  * cleans up a session pointer and hence the service needs to
313  * discard all of those sessions as well.  Plugins that do not
314  * use sessions can simply omit calling this function and always
315  * use NULL wherever a session pointer is needed.  This function
316  * should be called BEFORE a potential "TransmitContinuation"
317  * from the "TransmitFunction".
318  *
319  * @param cls closure
320  * @param peer which peer was the session for
321  * @param session which session is being destoyed
322  */
323 static void
324 plugin_env_session_end (void *cls, const struct GNUNET_PeerIdentity *peer,
325                         struct Session *session)
326 {
327 #if DEBUG_TRANSPORT
328   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Session %X to peer `%s' ended \n",
329               session, GNUNET_i2s (peer));
330 #endif
331   if (NULL != session)
332     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
333                      "transport-ats",
334                      "Telling ATS to destroy session %p from peer %s\n",
335                      session, GNUNET_i2s (peer));
336   GNUNET_ATS_address_destroyed (GST_ats, peer, NULL, NULL, 0, session);
337   GST_neighbours_session_terminated (peer, session);
338 }
339
340
341 /**
342  * Function called by ATS to notify the callee that the
343  * assigned bandwidth or address for a given peer was changed.  If the
344  * callback is called with address/bandwidth assignments of zero, the
345  * ATS disconnect function will still be called once the disconnect
346  * actually happened.
347  *
348  * @param cls closure
349  * @param peer identity of the peer
350  * @param plugin_name name of the transport plugin, NULL to disconnect
351  * @param session session to use (if available)
352  * @param plugin_addr address to use (if available)
353  * @param plugin_addr_len number of bytes in addr
354  * @param bandwidth_out assigned outbound bandwidth for the connection, 0 to disconnect from peer
355  * @param bandwidth_in assigned inbound bandwidth for the connection, 0 to disconnect from peer
356  */
357 static void
358 ats_request_address_change (void *cls, const struct GNUNET_PeerIdentity *peer,
359                             const char *plugin_name, const void *plugin_addr,
360                             size_t plugin_addr_len, struct Session *session,
361                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
362                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
363                             const struct GNUNET_ATS_Information *ats,
364                             uint32_t ats_count)
365 {
366   uint32_t bw_in = ntohl (bandwidth_in.value__);
367   uint32_t bw_out = ntohl (bandwidth_out.value__);
368
369   /* ATS tells me to disconnect from peer */
370   if ((bw_in == 0) && (bw_out == 0))
371   {
372 #if DEBUG_TRANSPORT
373     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
374                 "ATS tells me to disconnect from peer `%s'\n",
375                 GNUNET_i2s (peer));
376 #endif
377     GST_neighbours_force_disconnect (peer);
378     return;
379   }
380   /* will never return GNUNET_YES since connection is to be established */
381   GST_neighbours_switch_to_address_3way (peer, plugin_name, plugin_addr,
382                                          plugin_addr_len, session, ats,
383                                          ats_count, bandwidth_in,
384                                          bandwidth_out);
385 }
386
387
388 /**
389  * Function called to notify transport users that another
390  * peer connected to us.
391  *
392  * @param cls closure
393  * @param peer the peer that connected
394  * @param ats performance data
395  * @param ats_count number of entries in ats
396  */
397 static void
398 neighbours_connect_notification (void *cls,
399                                  const struct GNUNET_PeerIdentity *peer,
400                                  const struct GNUNET_ATS_Information *ats,
401                                  uint32_t ats_count)
402 {
403   size_t len =
404       sizeof (struct ConnectInfoMessage) +
405       ats_count * sizeof (struct GNUNET_ATS_Information);
406   char buf[len];
407   struct ConnectInfoMessage *connect_msg = (struct ConnectInfoMessage *) buf;
408   struct GNUNET_ATS_Information *ap;
409
410   connect_msg->header.size = htons (sizeof (buf));
411   connect_msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
412   connect_msg->ats_count = htonl (ats_count);
413   connect_msg->id = *peer;
414   ap = (struct GNUNET_ATS_Information *) &connect_msg[1];
415   memcpy (ap, ats, ats_count * sizeof (struct GNUNET_ATS_Information));
416   GST_clients_broadcast (&connect_msg->header, GNUNET_NO);
417 }
418
419
420 /**
421  * Function called to notify transport users that another
422  * peer disconnected from us.
423  *
424  * @param cls closure
425  * @param peer the peer that disconnected
426  */
427 static void
428 neighbours_disconnect_notification (void *cls,
429                                     const struct GNUNET_PeerIdentity *peer)
430 {
431   struct DisconnectInfoMessage disconnect_msg;
432
433   disconnect_msg.header.size = htons (sizeof (struct DisconnectInfoMessage));
434   disconnect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
435   disconnect_msg.reserved = htonl (0);
436   disconnect_msg.peer = *peer;
437   GST_clients_broadcast (&disconnect_msg.header, GNUNET_NO);
438 }
439
440
441 /**
442  * Function called when the service shuts down.  Unloads our plugins
443  * and cancels pending validations.
444  *
445  * @param cls closure, unused
446  * @param tc task context (unused)
447  */
448 static void
449 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
450 {
451   GST_validation_stop ();
452   GST_neighbours_stop ();
453   GST_plugins_unload ();
454
455   GNUNET_ATS_scheduling_done (GST_ats);
456   GST_ats = NULL;
457   GST_clients_stop ();
458   GST_blacklist_stop ();
459   GST_hello_stop ();
460
461   if (GST_peerinfo != NULL)
462   {
463     GNUNET_PEERINFO_disconnect (GST_peerinfo);
464     GST_peerinfo = NULL;
465   }
466   if (GST_stats != NULL)
467   {
468     GNUNET_STATISTICS_destroy (GST_stats, GNUNET_NO);
469     GST_stats = NULL;
470   }
471   if (GST_my_private_key != NULL)
472   {
473     GNUNET_CRYPTO_rsa_key_free (GST_my_private_key);
474     GST_my_private_key = NULL;
475   }
476 }
477
478
479 /**
480  * Initiate transport service.
481  *
482  * @param cls closure
483  * @param server the initialized server
484  * @param c configuration to use
485  */
486 static void
487 run (void *cls, struct GNUNET_SERVER_Handle *server,
488      const struct GNUNET_CONFIGURATION_Handle *c)
489 {
490   char *keyfile;
491
492   /* setup globals */
493   GST_cfg = c;
494   if (GNUNET_OK !=
495       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
496                                                &keyfile))
497   {
498     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
499                 _
500                 ("Transport service is lacking key configuration settings.  Exiting.\n"));
501     GNUNET_SCHEDULER_shutdown ();
502     return;
503   }
504   GST_my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
505   GNUNET_free (keyfile);
506   if (GST_my_private_key == NULL)
507   {
508     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
509                 _("Transport service could not access hostkey.  Exiting.\n"));
510     GNUNET_SCHEDULER_shutdown ();
511     return;
512   }
513   GST_stats = GNUNET_STATISTICS_create ("transport", c);
514   GST_peerinfo = GNUNET_PEERINFO_connect (c);
515   GNUNET_CRYPTO_rsa_key_get_public (GST_my_private_key, &GST_my_public_key);
516   GNUNET_CRYPTO_hash (&GST_my_public_key, sizeof (GST_my_public_key),
517                       &GST_my_identity.hashPubKey);
518   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
519                                 NULL);
520   if (GST_peerinfo == NULL)
521   {
522     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
523                 _("Could not access PEERINFO service.  Exiting.\n"));
524     GNUNET_SCHEDULER_shutdown ();
525     return;
526   }
527
528   /* start subsystems */
529   GST_hello_start (&process_hello_update, NULL);
530   GST_blacklist_start (server);
531   GST_plugins_load (&plugin_env_receive_callback,
532                     &plugin_env_address_change_notification,
533                     &plugin_env_session_end);
534   GST_ats =
535       GNUNET_ATS_scheduling_init (GST_cfg, &ats_request_address_change, NULL);
536   GST_neighbours_start (NULL, &neighbours_connect_notification,
537                         &neighbours_disconnect_notification);
538   GST_clients_start (server);
539   GST_validation_start ();
540 }
541
542
543 /**
544  * The main function for the transport service.
545  *
546  * @param argc number of arguments from the command line
547  * @param argv command line arguments
548  * @return 0 ok, 1 on error
549  */
550 int
551 main (int argc, char *const *argv)
552 {
553   return (GNUNET_OK ==
554           GNUNET_SERVICE_run (argc, argv, "transport",
555                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
556 }
557
558 /* end of file gnunet-service-transport-new.c */