Various changes:
[oweals/gnunet.git] / src / transport / gnunet-service-transport.c
1 /*
2  This file is part of GNUnet.
3  (C) 2010-2015 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  * @file transport/gnunet-service-transport.c
22  * @brief main for gnunet-service-transport
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "gnunet_hello_lib.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet_transport_service.h"
30 #include "gnunet_peerinfo_service.h"
31 #include "gnunet_ats_service.h"
32 #include "gnunet-service-transport.h"
33 #include "gnunet-service-transport_ats.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   struct GNUNET_SCHEDULER_Task * task;
73 };
74
75
76 /**
77  * We track active blacklist checks in a DLL so we can cancel them if
78  * necessary.  We typically check against the blacklist a few times
79  * during connection setup, as the check is asynchronous and the
80  * blacklist may change its mind before the connection goes fully up.
81  * Similarly, the session may die during the asynchronous check, so
82  * we use this list to then cancel ongoing checks.
83  */
84 struct BlacklistCheckContext
85 {
86   /**
87    * We keep these in a DLL.
88    */
89   struct BlacklistCheckContext *prev;
90
91   /**
92    * We keep these in a DLL.
93    */
94   struct BlacklistCheckContext *next;
95
96   /**
97    * Handle with the blacklist subsystem.
98    */
99   struct GST_BlacklistCheck *blc;
100
101   /**
102    * The address we are checking.
103    */
104   struct GNUNET_HELLO_Address *address;
105
106   /**
107    * Session associated with the address (or NULL).
108    */
109   struct Session *session;
110
111   /**
112    * Message to process in the continuation if the
113    * blacklist check is ok, can be NULL.
114    */
115   struct GNUNET_MessageHeader *msg;
116
117 };
118
119 /* globals */
120
121 /**
122  * Statistics handle.
123  */
124 struct GNUNET_STATISTICS_Handle *GST_stats;
125
126 /**
127  * Configuration handle.
128  */
129 const struct GNUNET_CONFIGURATION_Handle *GST_cfg;
130
131 /**
132  * Configuration handle.
133  */
134 struct GNUNET_PeerIdentity GST_my_identity;
135
136 /**
137  * Handle to peerinfo service.
138  */
139 struct GNUNET_PEERINFO_Handle *GST_peerinfo;
140
141 /**
142  * Handle to our service's server.
143  */
144 static struct GNUNET_SERVER_Handle *GST_server;
145
146 /**
147  * Our private key.
148  */
149 struct GNUNET_CRYPTO_EddsaPrivateKey *GST_my_private_key;
150
151 /**
152  * ATS scheduling handle.
153  */
154 struct GNUNET_ATS_SchedulingHandle *GST_ats;
155
156 /**
157  * ATS connectivity handle.
158  */
159 struct GNUNET_ATS_ConnectivityHandle *GST_ats_connect;
160
161 /**
162  * Hello address expiration
163  */
164 struct GNUNET_TIME_Relative hello_expiration;
165
166 /**
167  * Head of DLL of asynchronous tasks to kill sessions.
168  */
169 static struct SessionKiller *sk_head;
170
171 /**
172  * Tail of DLL of asynchronous tasks to kill sessions.
173  */
174 static struct SessionKiller *sk_tail;
175
176 /**
177  * Interface scanner determines our LAN address range(s).
178  */
179 static struct GNUNET_ATS_InterfaceScanner *is;
180
181 /**
182  * Head of DLL of blacklist checks we have pending for
183  * incoming sessions and/or SYN requests.  We may
184  * want to move this into the blacklist-logic at some
185  * point.
186  */
187 struct BlacklistCheckContext *bc_head;
188
189 /**
190  * Tail of DLL of blacklist checks we have pending for
191  * incoming sessions and/or SYN requests.
192  */
193 struct BlacklistCheckContext *bc_tail;
194
195
196 /**
197  * Transmit our HELLO message to the given (connected) neighbour.
198  *
199  * @param cls the 'HELLO' message
200  * @param peer identity of the peer
201  * @param address the address
202  * @param state current state this peer is in
203  * @param state_timeout timeout for the current state of the peer
204  * @param bandwidth_in inbound quota in NBO
205  * @param bandwidth_out outbound quota in NBO
206  */
207 static void
208 transmit_our_hello (void *cls,
209                     const struct GNUNET_PeerIdentity *peer,
210                     const struct GNUNET_HELLO_Address *address,
211                     enum GNUNET_TRANSPORT_PeerState state,
212                     struct GNUNET_TIME_Absolute state_timeout,
213                     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
214                     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
215 {
216   const struct GNUNET_MessageHeader *hello = cls;
217
218   if (GNUNET_NO == GST_neighbours_test_connected (peer))
219     return;
220
221   GST_neighbours_send (peer,
222                        hello,
223                        ntohs (hello->size),
224                        hello_expiration,
225                        NULL, NULL);
226 }
227
228
229 /**
230  * My HELLO has changed. Tell everyone who should know.
231  *
232  * @param cls unused
233  * @param hello new HELLO
234  */
235 static void
236 process_hello_update (void *cls,
237                       const struct GNUNET_MessageHeader *hello)
238 {
239   GST_clients_broadcast (hello, GNUNET_NO);
240   GST_neighbours_iterate (&transmit_our_hello, (void *) hello);
241 }
242
243
244 /**
245  * We received some payload.  Prepare to pass it on to our clients.
246  *
247  * @param address address and (claimed) identity of the other peer
248  * @param session identifier used for this session (NULL for plugins
249  *                that do not offer bi-directional communication to the sender
250  *                using the same "connection")
251  * @param message the message to process
252  * @return how long the plugin should wait until receiving more data
253  */
254 static struct GNUNET_TIME_Relative
255 process_payload (const struct GNUNET_HELLO_Address *address,
256                  struct Session *session,
257                  const struct GNUNET_MessageHeader *message)
258 {
259   struct GNUNET_TIME_Relative ret;
260   int do_forward;
261   struct InboundMessage *im;
262   size_t msg_size = ntohs (message->size);
263   size_t size = sizeof(struct InboundMessage) + msg_size;
264   char buf[size] GNUNET_ALIGN;
265
266   do_forward = GNUNET_SYSERR;
267   ret = GST_neighbours_calculate_receive_delay (&address->peer,
268                                                 msg_size,
269                                                 &do_forward);
270   if (! GST_neighbours_test_connected (&address->peer))
271   {
272     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
273                 "Discarded %u bytes type %u payload from peer `%s'\n",
274                 msg_size,
275                 ntohs (message->type),
276                 GNUNET_i2s (&address->peer));
277     GNUNET_STATISTICS_update (GST_stats, gettext_noop
278                               ("# bytes payload discarded due to not connected peer"),
279                               msg_size,
280                               GNUNET_NO);
281     return ret;
282   }
283
284   if (GNUNET_YES != do_forward)
285     return ret;
286   im = (struct InboundMessage *) buf;
287   im->header.size = htons (size);
288   im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
289   im->peer = address->peer;
290   memcpy (&im[1], message, ntohs (message->size));
291   GST_clients_broadcast (&im->header, GNUNET_YES);
292   return ret;
293 }
294
295
296 /**
297  * Task to asynchronously terminate a session.
298  *
299  * @param cls the `struct SessionKiller` with the information for the kill
300  * @param tc scheduler context
301  */
302 static void
303 kill_session_task (void *cls,
304                    const struct GNUNET_SCHEDULER_TaskContext *tc)
305 {
306   struct SessionKiller *sk = cls;
307
308   sk->task = NULL;
309   GNUNET_CONTAINER_DLL_remove (sk_head, sk_tail, sk);
310   sk->plugin->disconnect_session (sk->plugin->cls, sk->session);
311   GNUNET_free(sk);
312 }
313
314
315 /**
316  * Cancel all blacklist checks that are pending for the given address and session.
317  * NOTE: Consider moving the "bc_*" logic into blacklist.h?
318  *
319  * @param address address to remove from check
320  * @param sesssion session that must match to remove for check
321  */
322 static void
323 cancel_pending_blacklist_checks (const struct GNUNET_HELLO_Address *address,
324                                  struct Session *session)
325 {
326   struct BlacklistCheckContext *blctx;
327   struct BlacklistCheckContext *next;
328
329   next = bc_head;
330   for (blctx = next; NULL != blctx; blctx = next)
331   {
332     next = blctx->next;
333     if ( (NULL != blctx->address) &&
334          (0 == GNUNET_HELLO_address_cmp(blctx->address, address)) &&
335          (blctx->session == session))
336     {
337       GNUNET_CONTAINER_DLL_remove (bc_head,
338                                    bc_tail,
339                                    blctx);
340       if (NULL != blctx->blc)
341       {
342         GST_blacklist_test_cancel (blctx->blc);
343         blctx->blc = NULL;
344       }
345       GNUNET_HELLO_address_free (blctx->address);
346       GNUNET_free_non_null (blctx->msg);
347       GNUNET_free (blctx);
348     }
349   }
350 }
351
352
353 /**
354  * Force plugin to terminate session due to communication
355  * issue.
356  *
357  * @param plugin_name name of the plugin
358  * @param session session to termiante
359  */
360 static void
361 kill_session (const char *plugin_name,
362               struct Session *session)
363 {
364   struct GNUNET_TRANSPORT_PluginFunctions *plugin;
365   struct SessionKiller *sk;
366
367   for (sk = sk_head; NULL != sk; sk = sk->next)
368     if (sk->session == session)
369       return;
370   plugin = GST_plugins_find (plugin_name);
371   if (NULL == plugin)
372   {
373     GNUNET_break(0);
374     return;
375   }
376   /* need to issue disconnect asynchronously */
377   sk = GNUNET_new (struct SessionKiller);
378   sk->session = session;
379   sk->plugin = plugin;
380   sk->task = GNUNET_SCHEDULER_add_now (&kill_session_task, sk);
381   GNUNET_CONTAINER_DLL_insert (sk_head,
382                                sk_tail,
383                                sk);
384 }
385
386
387 /**
388  * Black list check result for try_connect call
389  * If connection to the peer is allowed request adddress and ???
390  *
391  * @param cls blc_ctx bl context
392  * @param peer the peer
393  * @param result the result
394  */
395 static void
396 connect_bl_check_cont (void *cls,
397                        const struct GNUNET_PeerIdentity *peer,
398                        int result)
399 {
400   struct BlacklistCheckContext *blctx = cls;
401
402   GNUNET_CONTAINER_DLL_remove (bc_head,
403                                bc_tail,
404                                blctx);
405   blctx->blc = NULL;
406   if (GNUNET_OK == result)
407   {
408     /* Blacklist allows to speak to this peer, forward SYN to neighbours  */
409     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
410                 "Received SYN message from peer `%s' at `%s'\n",
411                 GNUNET_i2s (peer),
412                 GST_plugins_a2s (blctx->address));
413     if (GNUNET_OK !=
414         GST_neighbours_handle_session_syn (blctx->msg,
415                                            &blctx->address->peer))
416     {
417       cancel_pending_blacklist_checks (blctx->address,
418                                        blctx->session);
419       kill_session (blctx->address->transport_name,
420                     blctx->session);
421     }
422   }
423   else
424   {
425     /* Blacklist denies to speak to this peer */
426     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
427                 "Discarding SYN message from `%s' due to denied blacklist check\n",
428                 GNUNET_i2s (peer));
429     cancel_pending_blacklist_checks (blctx->address,
430                                      blctx->session);
431     kill_session (blctx->address->transport_name,
432                   blctx->session);
433   }
434
435   if (NULL != blctx->address)
436     GNUNET_HELLO_address_free (blctx->address);
437   GNUNET_free (blctx->msg);
438   GNUNET_free (blctx);
439 }
440
441
442 /**
443  * Function called by the transport for each received message.
444  *
445  * @param cls closure, const char* with the name of the plugin we received the message from
446  * @param address address and (claimed) identity of the other peer
447  * @param message the message, NULL if we only care about
448  *                learning about the delay until we should receive again
449  * @param session identifier used for this session (NULL for plugins
450  *                that do not offer bi-directional communication to the sender
451  *                using the same "connection")
452  * @return how long the plugin should wait until receiving more data
453  *         (plugins that do not support this, can ignore the return value)
454  */
455 struct GNUNET_TIME_Relative
456 GST_receive_callback (void *cls,
457                       const struct GNUNET_HELLO_Address *address,
458                       struct Session *session,
459                       const struct GNUNET_MessageHeader *message)
460 {
461   const char *plugin_name = cls;
462   struct GNUNET_TIME_Relative ret;
463   struct BlacklistCheckContext *blctx;
464   struct GST_BlacklistCheck *blc;
465   uint16_t type;
466
467   ret = GNUNET_TIME_UNIT_ZERO;
468   if (NULL == message)
469     goto end;
470   type = ntohs (message->type);
471   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
472               "Received message with type %u from peer `%s'\n",
473               type,
474               GNUNET_i2s (&address->peer));
475
476   GNUNET_STATISTICS_update (GST_stats,
477                             gettext_noop ("# bytes total received"),
478                             ntohs (message->size),
479                             GNUNET_NO);
480   GST_neighbours_notify_data_recv (address,
481                                    message);
482   switch (type)
483   {
484   case GNUNET_MESSAGE_TYPE_HELLO_LEGACY:
485     /* Legacy HELLO message, discard  */
486     return ret;
487   case GNUNET_MESSAGE_TYPE_HELLO:
488     if (GNUNET_OK != GST_validation_handle_hello (message))
489     {
490       GNUNET_break_op (0);
491       cancel_pending_blacklist_checks (address,
492                                        session);
493     }
494     return ret;
495   case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
496     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
497                 "Processing `%s' from `%s'\n", "PING",
498                 GST_plugins_a2s (address));
499     if (GNUNET_OK !=
500         GST_validation_handle_ping (&address->peer,
501                                     message,
502                                     address,
503                                     session))
504     {
505       cancel_pending_blacklist_checks (address,
506                                        session);
507       kill_session (plugin_name,
508                     session);
509     }
510     break;
511   case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
512     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
513                "Processing `%s' from `%s'\n", "PONG",
514                GST_plugins_a2s (address));
515     if (GNUNET_OK != GST_validation_handle_pong (&address->peer, message))
516     {
517       GNUNET_break_op(0);
518       cancel_pending_blacklist_checks (address, session);
519       kill_session (plugin_name, session);
520     }
521     break;
522   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_SYN:
523     /* Do blacklist check if communication with this peer is allowed */
524     blctx = GNUNET_new (struct BlacklistCheckContext);
525     blctx->address = GNUNET_HELLO_address_copy (address);
526     blctx->session = session;
527     blctx->msg = GNUNET_malloc (ntohs(message->size));
528     memcpy (blctx->msg,
529             message,
530             ntohs (message->size));
531     GNUNET_CONTAINER_DLL_insert (bc_head,
532                                  bc_tail,
533                                  blctx);
534     if (NULL !=
535         (blc = GST_blacklist_test_allowed (&address->peer,
536                                            NULL,
537                                            &connect_bl_check_cont,
538                                            blctx)))
539     {
540       blctx->blc = blc;
541     }
542     break;
543   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_SYN_ACK:
544     if (GNUNET_OK !=
545         GST_neighbours_handle_session_syn_ack (message,
546                                                address,
547                                                session))
548     {
549       cancel_pending_blacklist_checks (address, session);
550       kill_session (plugin_name, session);
551     }
552     break;
553   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK:
554     if (GNUNET_OK !=
555         GST_neighbours_handle_session_ack (message,
556                                            address,
557                                            session))
558     {
559       GNUNET_break_op(0);
560       cancel_pending_blacklist_checks (address, session);
561       kill_session (plugin_name, session);
562     }
563     break;
564   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT:
565     GST_neighbours_handle_disconnect_message (&address->peer, message);
566     break;
567   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE:
568     GST_neighbours_keepalive (&address->peer, message);
569     break;
570   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE:
571     GST_neighbours_keepalive_response (&address->peer, message);
572     break;
573   default:
574     /* should be payload */
575     GNUNET_STATISTICS_update (GST_stats,
576                               gettext_noop ("# bytes payload received"),
577                               ntohs (message->size),
578                               GNUNET_NO);
579     GST_neighbours_notify_payload_recv (address,
580                                         message);
581     ret = process_payload (address,
582                            session,
583                            message);
584     break;
585   }
586   end:
587   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
588               "Allowing receive from peer %s to continue in %s\n",
589               GNUNET_i2s (&address->peer),
590               GNUNET_STRINGS_relative_time_to_string (ret,
591                                                       GNUNET_YES));
592   return ret;
593 }
594
595
596 /**
597  * Function that will be called for each address the transport
598  * is aware that it might be reachable under.  Update our HELLO.
599  *
600  * @param cls name of the plugin (const char*)
601  * @param add_remove should the address added (YES) or removed (NO) from the
602  *                   set of valid addresses?
603  * @param address the address to add or remove
604  */
605 static void
606 plugin_env_address_change_notification (void *cls,
607                                         int add_remove,
608                                         const struct GNUNET_HELLO_Address *address)
609 {
610   static int addresses = 0;
611   struct GNUNET_STATISTICS_Handle *cfg = GST_stats;
612
613   if (GNUNET_YES == add_remove)
614   {
615     addresses ++;
616     GNUNET_STATISTICS_update (cfg, "# transport addresses", 1, GNUNET_NO);
617   }
618   else if (GNUNET_NO == add_remove)
619   {
620     if (0 == addresses)
621       GNUNET_break (0);
622     else
623     {
624       addresses --;
625       GNUNET_STATISTICS_update (cfg, "# transport addresses", -1, GNUNET_NO);
626     }
627   }
628
629   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
630               "Transport now has %u addresses to communicate\n",
631               addresses);
632   GST_hello_modify_addresses (add_remove, address);
633 }
634
635
636 /**
637  * Function that will be called whenever the plugin internally
638  * cleans up a session pointer and hence the service needs to
639  * discard all of those sessions as well.  Plugins that do not
640  * use sessions can simply omit calling this function and always
641  * use NULL wherever a session pointer is needed.  This function
642  * should be called BEFORE a potential "TransmitContinuation"
643  * from the "TransmitFunction".
644  *
645  * @param cls closure
646  * @param address which address was the session for
647  * @param session which session is being destoyed
648  */
649 static void
650 plugin_env_session_end (void *cls,
651                         const struct GNUNET_HELLO_Address *address,
652                         struct Session *session)
653 {
654   struct SessionKiller *sk;
655
656   if (NULL == address)
657   {
658     GNUNET_break (0);
659     return;
660   }
661   if (NULL == session)
662   {
663     GNUNET_break (0);
664     return;
665   }
666   GNUNET_assert (strlen (address->transport_name) > 0);
667
668   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
669               "Notification from plugin about terminated session %p from peer `%s' address `%s'\n",
670               session,
671               GNUNET_i2s (&address->peer),
672               GST_plugins_a2s (address));
673
674   GST_neighbours_session_terminated (&address->peer, session);
675   GST_ats_del_session (address, session);
676   cancel_pending_blacklist_checks (address, session);
677
678   for (sk = sk_head; NULL != sk; sk = sk->next)
679   {
680     if (sk->session == session)
681     {
682       GNUNET_CONTAINER_DLL_remove (sk_head, sk_tail, sk);
683       GNUNET_SCHEDULER_cancel (sk->task);
684       GNUNET_free(sk);
685       break;
686     }
687   }
688 }
689
690
691 /**
692  * Function that will be called to figure if an address is an loopback,
693  * LAN, WAN etc. address
694  *
695  * @param cls closure
696  * @param addr binary address
697  * @param addrlen length of the @a addr
698  * @return type of the network @a addr belongs to
699  */
700 static enum GNUNET_ATS_Network_Type
701 plugin_env_address_to_type (void *cls,
702                             const struct sockaddr *addr,
703                             size_t addrlen)
704 {
705   if (NULL == GST_ats)
706   {
707     GNUNET_break(0);
708     return GNUNET_ATS_NET_UNSPECIFIED;
709   }
710   return GNUNET_ATS_scanner_address_get_type (is,
711                                               addr,
712                                               addrlen);
713 }
714
715
716 /**
717  * Function that will be called to update metrics for an address
718  *
719  * @param cls closure
720  * @param address address to update metrics for
721  * @param session the session
722  * @param ats the ats information to update
723  * @param ats_count the number of @a ats elements
724  */
725 static void
726 plugin_env_update_metrics (void *cls,
727                            const struct GNUNET_HELLO_Address *address,
728                            struct Session *session,
729                            const struct GNUNET_ATS_Information *ats,
730                            uint32_t ats_count)
731 {
732   GST_ats_update_metrics (address,
733                           session,
734                           ats, ats_count);
735 }
736
737
738 /**
739  * Black list check result from blacklist check triggered when a
740  * plugin gave us a new session in #plugin_env_session_start().  If
741  * connection to the peer is disallowed, kill the session.
742  *
743  * @param cls blc_ctx bl context
744  * @param peer the peer
745  * @param result the result
746  */
747 static void
748 plugin_env_session_start_bl_check_cont (void *cls,
749                                         const struct GNUNET_PeerIdentity *peer,
750                                         int result)
751 {
752   struct BlacklistCheckContext *blctx = cls;
753
754   GNUNET_CONTAINER_DLL_remove (bc_head,
755                                bc_tail,
756                                blctx);
757   blctx->blc = NULL;
758   if (GNUNET_OK != result)
759   {
760     cancel_pending_blacklist_checks (blctx->address,
761                                      blctx->session);
762     kill_session (blctx->address->transport_name,
763                   blctx->session);
764   }
765   else if (GNUNET_YES !=
766            GNUNET_HELLO_address_check_option (blctx->address,
767                                               GNUNET_HELLO_ADDRESS_INFO_INBOUND))
768   {
769     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
770                 "Informing verifier about inbound session's address `%s'\n",
771                 GST_plugins_a2s (blctx->address));
772     GST_validation_handle_address (blctx->address);
773   }
774   GNUNET_HELLO_address_free (blctx->address);
775   GNUNET_free (blctx);
776 }
777
778
779 /**
780  * Plugin tells transport service about a new inbound session
781  *
782  * @param cls unused
783  * @param address the address
784  * @param session the new session
785  * @param ats ats information
786  * @param ats_count number of @a ats information
787  */
788 static void
789 plugin_env_session_start (void *cls,
790                           const struct GNUNET_HELLO_Address *address,
791                           struct Session *session,
792                           const struct GNUNET_ATS_Information *ats,
793                           uint32_t ats_count)
794 {
795   struct BlacklistCheckContext *blctx;
796   struct GST_BlacklistCheck *blc;
797
798   if (NULL == address)
799   {
800     GNUNET_break(0);
801     return;
802   }
803   if (NULL == session)
804   {
805     GNUNET_break(0);
806     return;
807   }
808   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
809               "Notification from plugin `%s' about new session %p from peer `%s' address `%s'\n",
810               address->transport_name,
811               session,
812               GNUNET_i2s (&address->peer),
813               GST_plugins_a2s (address));
814   if (GNUNET_YES ==
815       GNUNET_HELLO_address_check_option (address,
816                                          GNUNET_HELLO_ADDRESS_INFO_INBOUND))
817   {
818     /* inbound is always new, but outbound MAY already be known, but
819        for example for UNIX, we have symmetric connections and thus we
820        may not know the address yet; add if necessary! */
821     GST_ats_add_inbound_address (address,
822                                  session,
823                                  ats,
824                                  ats_count);
825   }
826   else
827   {
828     if (GNUNET_YES ==
829         GST_ats_is_known (address,
830                           session))
831     {
832       GST_ats_update_metrics (address,
833                               session,
834                               ats,
835                               ats_count);
836     }
837   }
838   /* Do blacklist check if communication with this peer is allowed */
839   blctx = GNUNET_new (struct BlacklistCheckContext);
840   blctx->address = GNUNET_HELLO_address_copy (address);
841   blctx->session = session;
842   GNUNET_CONTAINER_DLL_insert (bc_head,
843                                bc_tail,
844                                blctx);
845   if (NULL !=
846       (blc = GST_blacklist_test_allowed (&address->peer,
847                                          address->transport_name,
848                                          &plugin_env_session_start_bl_check_cont,
849                                          blctx)))
850   {
851     blctx->blc = blc;
852   }
853 }
854
855
856 /**
857  * Function called by ATS to notify the callee that the
858  * assigned bandwidth or address for a given peer was changed.  If the
859  * callback is called with address/bandwidth assignments of zero, the
860  * ATS disconnect function will still be called once the disconnect
861  * actually happened.
862  *
863  * @param cls closure
864  * @param peer the peer this address is intended for
865  * @param address address to use (for peer given in address)
866  * @param session session to use (if available)
867  * @param bandwidth_out assigned outbound bandwidth for the connection in NBO,
868  *      0 to disconnect from peer
869  * @param bandwidth_in assigned inbound bandwidth for the connection in NBO,
870  *      0 to disconnect from peer
871  * @param ats ATS information
872  * @param ats_count number of @a ats elements
873  */
874 static void
875 ats_request_address_change (void *cls,
876                             const struct GNUNET_PeerIdentity *peer,
877                             const struct GNUNET_HELLO_Address *address,
878                             struct Session *session,
879                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
880                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in)
881 {
882   uint32_t bw_in = ntohl (bandwidth_in.value__);
883   uint32_t bw_out = ntohl (bandwidth_out.value__);
884
885   if (NULL == peer)
886   {
887     /* ATS service died, all suggestions become invalid!
888        (but we'll keep using the allocations for a little
889        while, to keep going while ATS restarts) */
890     // FIXME: do something?
891     return;
892   }
893   /* ATS tells me to disconnect from peer */
894   if ((0 == bw_in) && (0 == bw_out))
895   {
896     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
897                 "ATS tells me to disconnect from peer `%s'\n",
898                 GNUNET_i2s (peer));
899     GST_neighbours_force_disconnect (peer);
900     return;
901   }
902   GNUNET_assert (NULL != address);
903   GNUNET_STATISTICS_update (GST_stats,
904                             "# ATS suggestions received",
905                             1,
906                             GNUNET_NO);
907   GST_neighbours_switch_to_address (address,
908                                     session,
909                                     bandwidth_in,
910                                     bandwidth_out);
911 }
912
913
914 /**
915  * Function called when the service shuts down.  Unloads our plugins
916  * and cancels pending validations.
917  *
918  * @param cls closure, unused
919  * @param tc task context (unused)
920  */
921 static void
922 shutdown_task (void *cls,
923                const struct GNUNET_SCHEDULER_TaskContext *tc)
924 {
925   GST_neighbours_stop ();
926   GST_plugins_unload ();
927   GST_validation_stop ();
928   GST_ats_done ();
929   GNUNET_ATS_scheduling_done (GST_ats);
930   GST_ats = NULL;
931   GNUNET_ATS_connectivity_done (GST_ats_connect);
932   GST_ats_connect = NULL;
933   GNUNET_ATS_scanner_done (is);
934   is = NULL;
935   GST_clients_stop ();
936   GST_blacklist_stop ();
937   GST_hello_stop ();
938   GST_manipulation_stop ();
939
940   if (NULL != GST_peerinfo)
941   {
942     GNUNET_PEERINFO_disconnect (GST_peerinfo);
943     GST_peerinfo = NULL;
944   }
945   if (NULL != GST_stats)
946   {
947     GNUNET_STATISTICS_destroy (GST_stats, GNUNET_NO);
948     GST_stats = NULL;
949   }
950   if (NULL != GST_my_private_key)
951   {
952     GNUNET_free(GST_my_private_key);
953     GST_my_private_key = NULL;
954   }
955   GST_server = NULL;
956 }
957
958
959 /**
960  * Initiate transport service.
961  *
962  * @param cls closure
963  * @param server the initialized server
964  * @param c configuration to use
965  */
966 static void
967 run (void *cls,
968      struct GNUNET_SERVER_Handle *server,
969      const struct GNUNET_CONFIGURATION_Handle *c)
970 {
971   char *keyfile;
972   struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
973   long long unsigned int max_fd_cfg;
974   int max_fd_rlimit;
975   int max_fd;
976   int friend_only;
977
978   /* setup globals */
979   GST_cfg = c;
980   if (GNUNET_OK !=
981       GNUNET_CONFIGURATION_get_value_filename (c,
982                                                "PEER",
983                                                "PRIVATE_KEY",
984                                                &keyfile))
985   {
986     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
987         _("Transport service is lacking key configuration settings. Exiting.\n"));
988     GNUNET_SCHEDULER_shutdown ();
989     return;
990   }
991   if (GNUNET_OK !=
992       GNUNET_CONFIGURATION_get_value_time (c,
993                                            "transport",
994                                            "HELLO_EXPIRATION",
995                                            &hello_expiration))
996   {
997     hello_expiration = GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION;
998   }
999   GST_server = server;
1000   pk = GNUNET_CRYPTO_eddsa_key_create_from_file (keyfile);
1001   GNUNET_free (keyfile);
1002   GNUNET_assert (NULL != pk);
1003   GST_my_private_key = pk;
1004
1005   GST_stats = GNUNET_STATISTICS_create ("transport", GST_cfg);
1006   GST_peerinfo = GNUNET_PEERINFO_connect (GST_cfg);
1007   GNUNET_CRYPTO_eddsa_key_get_public (GST_my_private_key,
1008                                       &GST_my_identity.public_key);
1009   GNUNET_assert(NULL != GST_my_private_key);
1010
1011   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1012              "My identity is `%4s'\n",
1013              GNUNET_i2s_full (&GST_my_identity));
1014
1015   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1016                                 &shutdown_task,
1017                                 NULL);
1018   if (NULL == GST_peerinfo)
1019   {
1020     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1021         _("Could not access PEERINFO service.  Exiting.\n"));
1022     GNUNET_SCHEDULER_shutdown ();
1023     return;
1024   }
1025
1026   max_fd_rlimit = 0;
1027   max_fd_cfg = 0;
1028 #if HAVE_GETRLIMIT
1029   struct rlimit r_file;
1030   if (0 == getrlimit (RLIMIT_NOFILE, &r_file))
1031   {
1032     max_fd_rlimit = r_file.rlim_cur;
1033     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1034         "Maximum number of open files was: %u/%u\n",
1035         r_file.rlim_cur,
1036         r_file.rlim_max);
1037   }
1038   max_fd_rlimit = (9 * max_fd_rlimit) / 10; /* Keep 10% for rest of transport */
1039 #endif
1040   GNUNET_CONFIGURATION_get_value_number (GST_cfg,
1041                                          "transport",
1042                                          "MAX_FD",
1043                                          &max_fd_cfg);
1044
1045   if (max_fd_cfg > max_fd_rlimit)
1046     max_fd = max_fd_cfg;
1047   else
1048     max_fd = max_fd_rlimit;
1049   if (max_fd < DEFAULT_MAX_FDS)
1050     max_fd = DEFAULT_MAX_FDS;
1051
1052   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1053               "Limiting number of sockets to %u: validation %u, neighbors: %u\n",
1054              max_fd, (max_fd / 3), (max_fd / 3) * 2);
1055
1056   friend_only = GNUNET_CONFIGURATION_get_value_yesno (GST_cfg, "topology",
1057       "FRIENDS-ONLY");
1058   if (GNUNET_SYSERR == friend_only)
1059     friend_only = GNUNET_NO; /* According to topology defaults */
1060   /* start subsystems */
1061   GST_hello_start (friend_only, &process_hello_update, NULL );
1062   GNUNET_assert(NULL != GST_hello_get());
1063   GST_blacklist_start (GST_server, GST_cfg, &GST_my_identity);
1064   is = GNUNET_ATS_scanner_init ();
1065   GST_ats_connect = GNUNET_ATS_connectivity_init (GST_cfg);
1066   GST_ats = GNUNET_ATS_scheduling_init (GST_cfg,
1067                                         &ats_request_address_change,
1068                                         NULL);
1069   GST_ats_init ();
1070   GST_manipulation_init (GST_cfg);
1071   GST_plugins_load (&GST_manipulation_recv,
1072                     &plugin_env_address_change_notification,
1073                     &plugin_env_session_start,
1074                     &plugin_env_session_end,
1075                     &plugin_env_address_to_type,
1076                     &plugin_env_update_metrics);
1077   GST_neighbours_start ((max_fd / 3) * 2);
1078   GST_clients_start (GST_server);
1079   GST_validation_start ((max_fd / 3));
1080 }
1081
1082
1083 /**
1084  * The main function for the transport service.
1085  *
1086  * @param argc number of arguments from the command line
1087  * @param argv command line arguments
1088  * @return 0 ok, 1 on error
1089  */
1090 int
1091 main (int argc, char * const *argv)
1092 {
1093   return
1094       (GNUNET_OK
1095           == GNUNET_SERVICE_run (argc, argv, "transport",
1096               GNUNET_SERVICE_OPTION_NONE, &run, NULL )) ? 0 : 1;
1097 }
1098
1099 /* end of file gnunet-service-transport.c */