warning if inbound session does not have address length 0
[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_hello_lib.h"
29 #include "gnunet_statistics_service.h"
30 #include "gnunet_transport_service.h"
31 #include "gnunet_peerinfo_service.h"
32 #include "gnunet_ats_service.h"
33 #include "gnunet-service-transport.h"
34 #include "gnunet-service-transport_blacklist.h"
35 #include "gnunet-service-transport_clients.h"
36 #include "gnunet-service-transport_hello.h"
37 #include "gnunet-service-transport_neighbours.h"
38 #include "gnunet-service-transport_plugins.h"
39 #include "gnunet-service-transport_validation.h"
40 #include "gnunet-service-transport_manipulation.h"
41 #include "transport.h"
42
43 /* globals */
44
45 /**
46  * Statistics handle.
47  */
48 struct GNUNET_STATISTICS_Handle *GST_stats;
49
50 /**
51  * Configuration handle.
52  */
53 const struct GNUNET_CONFIGURATION_Handle *GST_cfg;
54
55 /**
56  * Configuration handle.
57  */
58 struct GNUNET_PeerIdentity GST_my_identity;
59
60 /**
61  * Handle to peerinfo service.
62  */
63 struct GNUNET_PEERINFO_Handle *GST_peerinfo;
64
65 /**
66  * Handle to our service's server.
67  */
68 static struct GNUNET_SERVER_Handle *GST_server;
69
70 /**
71  * Our public key.
72  */
73 struct GNUNET_CRYPTO_EccPublicSignKey GST_my_public_key;
74
75 /**
76  * Our private key.
77  */
78 struct GNUNET_CRYPTO_EccPrivateKey *GST_my_private_key;
79
80 /**
81  * ATS handle.
82  */
83 struct GNUNET_ATS_SchedulingHandle *GST_ats;
84
85 /**
86  * DEBUGGING connection counter
87  */
88 static int connections;
89
90 /**
91  * Hello address expiration
92  */
93 struct GNUNET_TIME_Relative hello_expiration;
94
95
96 /**
97  * Transmit our HELLO message to the given (connected) neighbour.
98  *
99  * @param cls the 'HELLO' message
100  * @param target a connected neighbour
101  * @param address the address
102  * @param bandwidth_in inbound quota in NBO
103  * @param bandwidth_out outbound quota in NBO
104  */
105 static void
106 transmit_our_hello (void *cls, const struct GNUNET_PeerIdentity *target,
107                     const struct GNUNET_HELLO_Address *address,
108                     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
109                     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
110 {
111   const struct GNUNET_MessageHeader *hello = cls;
112
113   GST_neighbours_send (target, (const char *) hello, ntohs (hello->size),
114                        hello_expiration, NULL, NULL);
115 }
116
117
118 /**
119  * My HELLO has changed. Tell everyone who should know.
120  *
121  * @param cls unused
122  * @param hello new HELLO
123  */
124 static void
125 process_hello_update (void *cls, const struct GNUNET_MessageHeader *hello)
126 {
127   GST_clients_broadcast (hello, GNUNET_NO);
128   GST_neighbours_iterate (&transmit_our_hello, (void *) hello);
129 }
130
131
132
133 /**
134  * We received some payload.  Prepare to pass it on to our clients.
135  *
136  * @param peer (claimed) identity of the other peer
137  * @param address the address
138  * @param session session used
139  * @param message the message to process
140  * @return how long the plugin should wait until receiving more data
141  */
142 static struct GNUNET_TIME_Relative
143 process_payload (const struct GNUNET_PeerIdentity *peer,
144                  const struct GNUNET_HELLO_Address *address,
145                  struct Session *session,
146                  const struct GNUNET_MessageHeader *message)
147 {
148   struct GNUNET_TIME_Relative ret;
149   int do_forward;
150   struct InboundMessage *im;
151   size_t msg_size = ntohs (message->size);
152   size_t size =
153       sizeof (struct InboundMessage) + msg_size;
154   char buf[size] GNUNET_ALIGN;
155
156   do_forward = GNUNET_SYSERR;
157   ret = GST_neighbours_calculate_receive_delay (peer, msg_size, &do_forward);
158
159   if (!GST_neighbours_test_connected (peer))
160   {
161
162     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
163                 "Discarded %u bytes type %u payload from peer `%s'\n", msg_size,
164                 ntohs (message->type), GNUNET_i2s (peer));
165
166     GNUNET_STATISTICS_update (GST_stats,
167                               gettext_noop
168                               ("# bytes payload discarded due to not connected peer "),
169                               msg_size, GNUNET_NO);
170     return ret;
171   }
172
173   GST_ats_add_address ((struct GNUNET_HELLO_Address *) address, session);
174
175   if (do_forward != GNUNET_YES)
176     return ret;
177   im = (struct InboundMessage *) buf;
178   im->header.size = htons (size);
179   im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
180   im->peer = *peer;
181   memcpy (&im[1], message, ntohs (message->size));
182
183   GST_clients_broadcast (&im->header, GNUNET_YES);
184
185   return ret;
186 }
187
188
189 /**
190  * Function called by the transport for each received message.
191  * This function should also be called with "NULL" for the
192  * message to signal that the other peer disconnected.
193  *
194  * @param cls closure, const char* with the name of the plugin we received the message from
195  * @param peer (claimed) identity of the other peer
196  * @param message the message, NULL if we only care about
197  *                learning about the delay until we should receive again -- FIXME!
198  * @param session identifier used for this session (NULL for plugins
199  *                that do not offer bi-directional communication to the sender
200  *                using the same "connection")
201  * @param sender_address binary address of the sender (if we established the
202  *                connection or are otherwise sure of it; should be NULL
203  *                for inbound TCP/UDP connections since it it not clear
204  *                that we could establish ourselves a connection to that
205  *                IP address and get the same system)
206  * @param sender_address_len number of bytes in sender_address
207  * @return how long the plugin should wait until receiving more data
208  *         (plugins that do not support this, can ignore the return value)
209  */
210 struct GNUNET_TIME_Relative
211 GST_receive_callback (void *cls, const struct GNUNET_PeerIdentity *peer,
212                              const struct GNUNET_MessageHeader *message,
213                              struct Session *session,
214                              const char *sender_address,
215                              uint16_t sender_address_len)
216 {
217   const char *plugin_name = cls;
218   struct GNUNET_TIME_Relative ret;
219   struct GNUNET_HELLO_Address address;
220   uint16_t type;
221
222   address.peer = *peer;
223   address.address = sender_address;
224   address.address_length = sender_address_len;
225   address.transport_name = plugin_name;
226   ret = GNUNET_TIME_UNIT_ZERO;
227   if (NULL == message)
228     goto end;
229   type = ntohs (message->type);
230   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Message with type %u from peer `%s'\n", type, GNUNET_i2s (peer));
231
232   GNUNET_STATISTICS_update (GST_stats,
233                         gettext_noop
234                         ("# bytes total received"),
235                             ntohs (message->size), GNUNET_NO);
236
237   switch (type)
238   {
239   case GNUNET_MESSAGE_TYPE_HELLO_LEGACY:
240     /* Legacy HELLO message, discard  */
241     return ret;
242   case GNUNET_MESSAGE_TYPE_HELLO:
243     GST_validation_handle_hello (message);
244     return ret;
245   case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
246     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
247                 "Processing `%s' from `%s'\n", "PING",
248                 (sender_address !=
249                  NULL) ? GST_plugins_a2s (&address) : TRANSPORT_SESSION_INBOUND_STRING);
250     GST_validation_handle_ping (peer, message, &address, session);
251     break;
252   case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
253     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
254                 "Processing `%s' from `%s'\n", "PONG",
255                 (sender_address !=
256                  NULL) ? GST_plugins_a2s (&address) : TRANSPORT_SESSION_INBOUND_STRING);
257     GST_validation_handle_pong (peer, message);
258     break;
259   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT:
260     GST_neighbours_handle_connect (message, peer, &address, session);
261     break;
262   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK:
263     GST_neighbours_handle_connect_ack (message, peer, &address, session);
264     break;
265   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK:
266     GST_neighbours_handle_session_ack (message, peer, &address, session);
267     break;
268   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT:
269     GST_neighbours_handle_disconnect_message (peer, message);
270     break;
271   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE:
272     GST_neighbours_keepalive (peer);
273     break;
274   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE:
275     GST_neighbours_keepalive_response (peer);
276     break;
277   default:
278     /* should be payload */
279     GNUNET_STATISTICS_update (GST_stats,
280                               gettext_noop
281                               ("# bytes payload received"),
282                               ntohs (message->size), GNUNET_NO);
283     ret = process_payload (peer, &address, session, message);
284     break;
285   }
286 end:
287   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
288               "Allowing receive from peer %s to continue in %s\n",
289               GNUNET_i2s (peer), 
290               GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
291   return ret;
292 }
293
294
295 /**
296  * Function that will be called for each address the transport
297  * is aware that it might be reachable under.  Update our HELLO.
298  *
299  * @param cls name of the plugin (const char*)
300  * @param add_remove should the address added (YES) or removed (NO) from the
301  *                   set of valid addresses?
302  * @param addr one of the addresses of the host
303  *        the specific address format depends on the transport
304  * @param addrlen length of the address
305  * @param dest_plugin destination plugin to use this address with
306  */
307 static void
308 plugin_env_address_change_notification (void *cls, int add_remove,
309                                         const void *addr, size_t addrlen,
310                                         const char *dest_plugin)
311 {
312   struct GNUNET_HELLO_Address address;
313
314   address.peer = GST_my_identity;
315   address.transport_name = dest_plugin;
316   address.address = addr;
317   address.address_length = addrlen;
318   GST_hello_modify_addresses (add_remove, &address);
319 }
320
321
322 /**
323  * Function that will be called whenever the plugin internally
324  * cleans up a session pointer and hence the service needs to
325  * discard all of those sessions as well.  Plugins that do not
326  * use sessions can simply omit calling this function and always
327  * use NULL wherever a session pointer is needed.  This function
328  * should be called BEFORE a potential "TransmitContinuation"
329  * from the "TransmitFunction".
330  *
331  * @param cls closure
332  * @param peer which peer was the session for
333  * @param session which session is being destoyed
334  */
335 static void
336 plugin_env_session_end (void *cls, const struct GNUNET_PeerIdentity *peer,
337                         struct Session *session)
338 {
339   const char *transport_name = cls;
340   struct GNUNET_HELLO_Address address;
341
342   GNUNET_assert (strlen (transport_name) > 0);
343   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Session %p to peer `%s' ended \n",
344               session, GNUNET_i2s (peer));
345   if (NULL != session)
346     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
347                      "transport-ats",
348                      "Telling ATS to destroy session %p from peer %s\n",
349                      session, GNUNET_i2s (peer));
350   address.peer = *peer;
351   address.address = NULL;
352   address.address_length = 0;
353   address.transport_name = transport_name;
354   GST_neighbours_session_terminated (peer, session);
355
356   /* Tell ATS that session has ended */
357   GNUNET_ATS_address_destroyed (GST_ats, &address, session);
358 }
359
360
361 /**
362  * Function that will be called to figure if an address is an loopback,
363  * LAN, WAN etc. address
364  *
365  * @param cls closure
366  * @param addr binary address
367  * @param addrlen length of the address
368  * @return ATS Information containing the network type
369  */
370 static struct GNUNET_ATS_Information
371 plugin_env_address_to_type (void *cls,
372                             const struct sockaddr *addr,
373                             size_t addrlen)
374 {
375   struct GNUNET_ATS_Information ats;
376   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
377   ats.value = htonl (GNUNET_ATS_NET_UNSPECIFIED);
378   if (GST_ats == NULL)
379   {
380     GNUNET_break (0);
381     return ats;
382   }
383   if (((addr->sa_family != AF_INET) && (addrlen != sizeof (struct sockaddr_in))) &&
384       ((addr->sa_family != AF_INET6) && (addrlen != sizeof (struct sockaddr_in6))) &&
385       (addr->sa_family != AF_UNIX))
386   {
387     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Malformed address with length %u `%s'\n",
388                 addrlen,
389                 GNUNET_a2s(addr, addrlen));
390     GNUNET_break (0);
391     return ats;
392   }
393   return GNUNET_ATS_address_get_type(GST_ats, addr, addrlen);
394 }
395
396
397 /**
398  * Notify ATS about the new address including the network this address is
399  * located in.
400  *
401  * @param address the address
402  * @param session the session
403  */
404 void
405 GST_ats_add_address (const struct GNUNET_HELLO_Address *address,
406                                                                                  struct Session *session)
407 {
408   struct GNUNET_TRANSPORT_PluginFunctions *papi;
409         struct GNUNET_ATS_Information ats;
410         uint32_t net;
411
412   /* valid new address, let ATS know! */
413   if (NULL == address->transport_name)
414   {
415         GNUNET_break (0);
416         return;
417   }
418   if (NULL == (papi = GST_plugins_find (address->transport_name)))
419   {
420     /* we don't have the plugin for this address */
421         GNUNET_break (0);
422         return;
423   }
424
425   if (GNUNET_YES == GNUNET_ATS_session_known (GST_ats, address, session))
426         return;
427
428         net = papi->get_network (NULL, (void *) session);
429   if (GNUNET_ATS_NET_UNSPECIFIED == net)
430   {
431     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
432                                                 _("Could not obtain a valid network for `%s' %s\n"),
433                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
434         GNUNET_break (0);
435   }
436         ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
437         ats.value = htonl(net);
438         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
439                         "Notifying ATS about peer `%s''s new address `%s' session %p in network %s\n",
440                         GNUNET_i2s (&address->peer),
441                         (0 == address->address_length) ? "<inbound>" : GST_plugins_a2s (address),
442                         session,
443                         GNUNET_ATS_print_network_type(net));
444         GNUNET_ATS_address_add (GST_ats,
445                         address, session, &ats, 1);
446 }
447
448
449 /**
450  * Notify ATS about property changes to an address
451  *
452  * @param peer the peer
453  * @param address the address
454  * @param session the session
455  * @param ats performance information
456  * @param ats_count number of elements in ats
457  */
458 void
459 GST_ats_update_metrics (const struct GNUNET_PeerIdentity *peer,
460                         const struct GNUNET_HELLO_Address *address,
461                         struct Session *session,
462                         const struct GNUNET_ATS_Information *ats,
463                         uint32_t ats_count)
464 {
465         struct GNUNET_ATS_Information *ats_new;
466
467   if (GNUNET_NO == GNUNET_ATS_session_known (GST_ats, address, session))
468         return;
469
470         /* Call to manipulation to manipulate ATS information */
471         ats_new = GST_manipulation_manipulate_metrics (peer, address, session, ats, ats_count);
472         if (NULL == ats_new)
473         {
474                         GNUNET_break (0);
475                         return;
476         }
477   if (GNUNET_NO == GNUNET_ATS_address_update (GST_ats, address, session, ats_new, ats_count))
478   {
479         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
480                         _("Address or session unknown: failed to update properties for peer `%s' plugin `%s' address `%s' session %p\n"),
481                         GNUNET_i2s (peer), address->transport_name, GST_plugins_a2s (address), session);
482   }
483   GNUNET_free (ats_new);
484 }
485
486
487 /**
488  * Function that will be called to figure if an address is an loopback,
489  * LAN, WAN etc. address
490  *
491  * @param cls closure
492  * @param peer the peer
493  * @param address binary address
494  * @param address_len length of the address
495  * @param session the session
496  * @param ats the ats information to update
497  * @param ats_count the number of ats elements
498  */
499 static void
500 plugin_env_update_metrics (void *cls,
501                            const struct GNUNET_PeerIdentity *peer,
502                            const void *address,
503                            uint16_t address_len,
504                            struct Session *session,
505                            const struct GNUNET_ATS_Information *ats,
506                            uint32_t ats_count)
507 {
508   struct GNUNET_HELLO_Address haddress;
509   const char *plugin_name = cls;
510
511         if ((NULL == ats) || (0 == ats_count))
512                 return;
513         GNUNET_assert (NULL != GST_ats);
514
515
516         haddress.peer = *peer;
517         haddress.address = address;
518   haddress.address_length = address_len;
519   haddress.transport_name = plugin_name;
520
521         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating metrics for peer `%s' address %s session %p\n",
522                         GNUNET_i2s (peer), GST_plugins_a2s(&haddress), session);
523   GST_ats_update_metrics (peer, &haddress, session, ats, ats_count);
524 }
525
526 /**
527  * Plugin tells transport service about a new (inbound) session
528  *
529  * @param cls unused
530  * @param peer the peer
531  * @param plugin plugin name
532  * @param address address
533  * @param address_len address length
534  * @param session the new session
535  * @param ats ats information
536  * @param ats_count number of ats information
537  */
538
539 static void
540 plugin_env_session_start (void *cls,
541            const struct GNUNET_PeerIdentity *peer,
542            const char *plugin,
543            const void *address,
544            uint16_t address_len,
545            struct Session *session,
546            const struct GNUNET_ATS_Information *ats,
547            uint32_t ats_count)
548 {
549         struct GNUNET_HELLO_Address *addr;
550         if (NULL == peer)
551         {
552                 GNUNET_break (0);
553                 return;
554         }
555         if (NULL == plugin)
556         {
557                 GNUNET_break (0);
558                 return;
559         }
560         if ((address_len != 0) && (NULL == address))
561         {
562                 GNUNET_break (0);
563                 return;
564         }
565         if (NULL == session)
566         {
567                 GNUNET_break (0);
568                 return;
569         }
570
571         addr = GNUNET_HELLO_address_allocate (peer, plugin, address, address_len);
572         if (0 != address_len)
573         {
574                 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
575                                 "Inbound session from plugin `%s' about new session %p from peer `%s' address `%s' does not have address length 0 but %u\n",
576                                 plugin, session, GNUNET_i2s (peer), GST_plugins_a2s(addr), address_len);
577         }
578         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
579                         "Notification from plugin `%s' about new session %p from peer `%s' address `%s'\n",
580                         plugin, session, GNUNET_i2s (peer), GST_plugins_a2s(addr));
581         GST_ats_add_address (addr, session);
582
583         if (0 < ats_count)
584                 GST_ats_update_metrics (peer, addr, session, ats, ats_count);
585         GNUNET_free (addr);
586 }
587
588 /**
589  * Function called by ATS to notify the callee that the
590  * assigned bandwidth or address for a given peer was changed.  If the
591  * callback is called with address/bandwidth assignments of zero, the
592  * ATS disconnect function will still be called once the disconnect
593  * actually happened.
594  *
595  * @param cls closure
596  * @param address address to use (for peer given in address)
597  * @param session session to use (if available)
598  * @param bandwidth_out assigned outbound bandwidth for the connection, 0 to disconnect from peer
599  * @param bandwidth_in assigned inbound bandwidth for the connection, 0 to disconnect from peer
600  * @param ats ATS information
601  * @param ats_count number of ATS elements
602  */
603 static void
604 ats_request_address_change (void *cls,
605                             const struct GNUNET_HELLO_Address *address,
606                             struct Session *session,
607                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
608                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
609                             const struct GNUNET_ATS_Information *ats,
610                             uint32_t ats_count)
611 {
612   uint32_t bw_in = ntohl (bandwidth_in.value__);
613   uint32_t bw_out = ntohl (bandwidth_out.value__);
614
615   /* ATS tells me to disconnect from peer */
616   if ((bw_in == 0) && (bw_out == 0))
617   {
618     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
619                 "ATS tells me to disconnect from peer `%s'\n",
620                 GNUNET_i2s (&address->peer));
621     GST_neighbours_force_disconnect (&address->peer);
622     return;
623   }
624   GST_neighbours_switch_to_address (&address->peer, address, session, ats,
625                                          ats_count, bandwidth_in,
626                                          bandwidth_out);
627 }
628
629
630 /**
631  * Function called to notify transport users that another
632  * peer connected to us.
633  *
634  * @param cls closure
635  * @param peer the peer that connected
636  * @param bandwidth_in inbound bandwidth in NBO
637  * @param bandwidth_out outbound bandwidth in NBO
638  */
639 static void
640 neighbours_connect_notification (void *cls,
641                                  const struct GNUNET_PeerIdentity *peer,
642                                  struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
643                                  struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
644 {
645   size_t len = sizeof (struct ConnectInfoMessage);
646   char buf[len] GNUNET_ALIGN;
647   struct ConnectInfoMessage *connect_msg = (struct ConnectInfoMessage *) buf;
648
649   connections++;
650   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
651               "We are now connected to peer `%s' and %u peers in total\n",
652               GNUNET_i2s (peer), connections);
653
654   connect_msg->header.size = htons (sizeof (buf));
655   connect_msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
656   connect_msg->id = *peer;
657   connect_msg->quota_in = bandwidth_in;
658   connect_msg->quota_out = bandwidth_out;
659   GST_clients_broadcast (&connect_msg->header, GNUNET_NO);
660 }
661
662
663 /**
664  * Function called to notify transport users that another
665  * peer disconnected from us.
666  *
667  * @param cls closure
668  * @param peer the peer that disconnected
669  */
670 static void
671 neighbours_disconnect_notification (void *cls,
672                                     const struct GNUNET_PeerIdentity *peer)
673 {
674   struct DisconnectInfoMessage disconnect_msg;
675
676   connections--;
677   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
678               "Peer `%s' disconnected and we are connected to %u peers\n",
679               GNUNET_i2s (peer), connections);
680
681   GST_manipulation_peer_disconnect (peer);
682   disconnect_msg.header.size = htons (sizeof (struct DisconnectInfoMessage));
683   disconnect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
684   disconnect_msg.reserved = htonl (0);
685   disconnect_msg.peer = *peer;
686   GST_clients_broadcast (&disconnect_msg.header, GNUNET_NO);
687 }
688
689
690 /**
691  * Function called to notify transport users that a neighbour peer changed its
692  * active address.
693  *
694  * @param cls closure
695  * @param peer peer this update is about (never NULL)
696  * @param address address, NULL on disconnect
697  */
698 static void
699 neighbours_address_notification (void *cls,
700                                  const struct GNUNET_PeerIdentity *peer,
701                                  const struct GNUNET_HELLO_Address *address)
702 {
703   GST_clients_broadcast_address_notification (peer, address);
704 }
705
706
707 /**
708  * Function called when the service shuts down.  Unloads our plugins
709  * and cancels pending validations.
710  *
711  * @param cls closure, unused
712  * @param tc task context (unused)
713  */
714 static void
715 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
716 {
717   GST_neighbours_stop ();
718   GST_validation_stop ();
719   GST_plugins_unload ();
720
721   GNUNET_ATS_scheduling_done (GST_ats);
722   GST_ats = NULL;
723   GST_clients_stop ();
724   GST_blacklist_stop ();
725   GST_hello_stop ();
726   GST_manipulation_stop ();
727
728   if (NULL != GST_peerinfo)
729   {
730     GNUNET_PEERINFO_disconnect (GST_peerinfo);
731     GST_peerinfo = NULL;
732   }
733   if (NULL != GST_stats)
734   {
735     GNUNET_STATISTICS_destroy (GST_stats, GNUNET_NO);
736     GST_stats = NULL;
737   }
738   if (NULL != GST_my_private_key)
739   {
740     GNUNET_free (GST_my_private_key);
741     GST_my_private_key = NULL;
742   }
743   GST_server = NULL;
744 }
745
746
747 /**
748  * Initiate transport service.
749  *
750  * @param cls closure
751  * @param server the initialized server
752  * @param c configuration to use
753  */
754 static void
755 run (void *cls, struct GNUNET_SERVER_Handle *server,
756      const struct GNUNET_CONFIGURATION_Handle *c)
757 {
758   char *keyfile;
759   struct GNUNET_CRYPTO_EccPrivateKey *pk;
760   long long unsigned int max_fd_cfg;
761   int max_fd_rlimit;
762   int max_fd;
763   int friend_only;
764
765   /* setup globals */
766   GST_cfg = c;
767   if (GNUNET_OK !=
768       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
769                                                &keyfile))
770   {
771     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
772                 _
773                 ("Transport service is lacking key configuration settings.  Exiting.\n"));
774     GNUNET_SCHEDULER_shutdown ();
775     return;
776   }
777   if (GNUNET_OK !=
778       GNUNET_CONFIGURATION_get_value_time (c, "transport", "HELLO_EXPIRATION",
779                                            &hello_expiration))
780   {
781     hello_expiration = GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION;
782   }
783   GST_server = server;
784   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
785   GNUNET_free (keyfile);
786   GNUNET_assert (NULL != pk);
787   GST_my_private_key = pk;
788
789   GST_stats = GNUNET_STATISTICS_create ("transport", GST_cfg);
790   GST_peerinfo = GNUNET_PEERINFO_connect (GST_cfg);
791   GNUNET_CRYPTO_ecc_key_get_public_for_signature (GST_my_private_key, &GST_my_public_key);
792   GNUNET_CRYPTO_hash (&GST_my_public_key, sizeof (GST_my_public_key),
793                       &GST_my_identity.hashPubKey);
794   GNUNET_assert (NULL != GST_my_private_key);
795
796   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
797               "My identity is `%4s'\n", GNUNET_i2s (&GST_my_identity));
798
799   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
800                                 NULL);
801   if (NULL == GST_peerinfo)
802   {
803     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
804                 _("Could not access PEERINFO service.  Exiting.\n"));
805     GNUNET_SCHEDULER_shutdown ();
806     return;
807   }
808
809   max_fd_rlimit = 0;
810   max_fd_cfg = 0;
811 #if HAVE_GETRLIMIT
812   struct rlimit r_file;
813   if (0 == getrlimit (RLIMIT_NOFILE, &r_file))
814   {
815     max_fd_rlimit = r_file.rlim_cur;
816     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
817                 "Maximum number of open files was: %u/%u\n", r_file.rlim_cur,
818                 r_file.rlim_max);
819   }
820   max_fd_rlimit = (9 * max_fd_rlimit) / 10; /* Keep 10% for rest of transport */
821 #endif
822   GNUNET_CONFIGURATION_get_value_number (GST_cfg, "transport", "MAX_FD", &max_fd_cfg);
823
824   if (max_fd_cfg > max_fd_rlimit)
825         max_fd = max_fd_cfg;
826   else
827         max_fd = max_fd_rlimit;
828   if (max_fd < DEFAULT_MAX_FDS)
829         max_fd = DEFAULT_MAX_FDS;
830
831   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
832               "Limiting number of sockets to %u: validation %u, neighbors: %u\n",
833               max_fd, (max_fd / 3) , (max_fd / 3) * 2);
834
835   friend_only = GNUNET_CONFIGURATION_get_value_yesno(GST_cfg, "topology","FRIENDS-ONLY");
836   if (GNUNET_SYSERR == friend_only)
837         friend_only = GNUNET_NO; /* According to topology defaults */
838   /* start subsystems */
839   GST_hello_start (friend_only, &process_hello_update, NULL);
840   GNUNET_assert (NULL != GST_hello_get());
841   GST_blacklist_start (GST_server, GST_cfg, &GST_my_identity);
842   GST_ats =
843       GNUNET_ATS_scheduling_init (GST_cfg, &ats_request_address_change, NULL);
844   GST_manipulation_init (GST_cfg);
845   GST_plugins_load (&GST_manipulation_recv,
846                     &plugin_env_address_change_notification,
847                     &plugin_env_session_start,
848                     &plugin_env_session_end,
849                     &plugin_env_address_to_type,
850                     &plugin_env_update_metrics);
851   GST_neighbours_start (NULL,
852                         &neighbours_connect_notification,
853                         &neighbours_disconnect_notification,
854                         &neighbours_address_notification,
855                         (max_fd / 3) * 2);
856   GST_clients_start (GST_server);
857   GST_validation_start ((max_fd / 3));
858 }
859
860
861 /**
862  * The main function for the transport service.
863  *
864  * @param argc number of arguments from the command line
865  * @param argv command line arguments
866  * @return 0 ok, 1 on error
867  */
868 int
869 main (int argc, char *const *argv)
870 {
871   return (GNUNET_OK ==
872           GNUNET_SERVICE_run (argc, argv, "transport",
873                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
874 }
875
876 /* end of file gnunet-service-transport.c */