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