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