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