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