generate our own HELLO before starting validations
[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 PING from `%s'\n",
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 PONG from `%s'\n",
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,
576                                               message);
577     break;
578   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE:
579     GST_neighbours_keepalive (&address->peer,
580                               message);
581     break;
582   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE:
583     GST_neighbours_keepalive_response (&address->peer,
584                                        message);
585     break;
586   default:
587     /* should be payload */
588     GNUNET_STATISTICS_update (GST_stats,
589                               gettext_noop ("# bytes payload received"),
590                               ntohs (message->size),
591                               GNUNET_NO);
592     ret = process_payload (address,
593                            session,
594                            message);
595     break;
596   }
597  end:
598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
599               "Allowing receive from peer %s to continue in %s\n",
600               GNUNET_i2s (&address->peer),
601               GNUNET_STRINGS_relative_time_to_string (ret,
602                                                       GNUNET_YES));
603   return ret;
604 }
605
606
607 /**
608  * Function that will be called for each address the transport
609  * is aware that it might be reachable under.  Update our HELLO.
610  *
611  * @param cls name of the plugin (const char*)
612  * @param add_remove should the address added (YES) or removed (NO) from the
613  *                   set of valid addresses?
614  * @param address the address to add or remove
615  */
616 static void
617 plugin_env_address_change_notification (void *cls,
618                                         int add_remove,
619                                         const struct GNUNET_HELLO_Address *address)
620 {
621   static int addresses = 0;
622   struct GNUNET_STATISTICS_Handle *cfg = GST_stats;
623
624   if (GNUNET_YES == add_remove)
625   {
626     addresses ++;
627     GNUNET_STATISTICS_update (cfg, "# transport addresses", 1, GNUNET_NO);
628   }
629   else if (GNUNET_NO == add_remove)
630   {
631     if (0 == addresses)
632       GNUNET_break (0);
633     else
634     {
635       addresses --;
636       GNUNET_STATISTICS_update (cfg, "# transport addresses", -1, GNUNET_NO);
637     }
638   }
639
640   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
641               "Transport now has %u addresses to communicate\n",
642               addresses);
643   GST_hello_modify_addresses (add_remove, address);
644 }
645
646
647 /**
648  * Function that will be called whenever the plugin internally
649  * cleans up a session pointer and hence the service needs to
650  * discard all of those sessions as well.  Plugins that do not
651  * use sessions can simply omit calling this function and always
652  * use NULL wherever a session pointer is needed.  This function
653  * should be called BEFORE a potential "TransmitContinuation"
654  * from the "TransmitFunction".
655  *
656  * @param cls closure
657  * @param address which address was the session for
658  * @param session which session is being destoyed
659  */
660 static void
661 plugin_env_session_end (void *cls,
662                         const struct GNUNET_HELLO_Address *address,
663                         struct Session *session)
664 {
665   struct SessionKiller *sk;
666
667   if (NULL == address)
668   {
669     GNUNET_break (0);
670     return;
671   }
672   if (NULL == session)
673   {
674     GNUNET_break (0);
675     return;
676   }
677   GNUNET_assert (strlen (address->transport_name) > 0);
678
679   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
680               "Notification from plugin about terminated session %p from peer `%s' address `%s'\n",
681               session,
682               GNUNET_i2s (&address->peer),
683               GST_plugins_a2s (address));
684
685   GST_neighbours_session_terminated (&address->peer, session);
686   GST_ats_del_session (address, session);
687   cancel_pending_blacklist_checks (address, session);
688
689   for (sk = sk_head; NULL != sk; sk = sk->next)
690   {
691     if (sk->session == session)
692     {
693       GNUNET_CONTAINER_DLL_remove (sk_head, sk_tail, sk);
694       GNUNET_SCHEDULER_cancel (sk->task);
695       GNUNET_free(sk);
696       break;
697     }
698   }
699 }
700
701
702 /**
703  * Black list check result from blacklist check triggered when a
704  * plugin gave us a new session in #plugin_env_session_start().  If
705  * connection to the peer is disallowed, kill the session.
706  *
707  * @param cls blc_ctx bl context
708  * @param peer the peer
709  * @param result the result
710  */
711 static void
712 plugin_env_session_start_bl_check_cont (void *cls,
713                                         const struct GNUNET_PeerIdentity *peer,
714                                         int result)
715 {
716   struct BlacklistCheckContext *blctx = cls;
717
718   GNUNET_CONTAINER_DLL_remove (bc_head,
719                                bc_tail,
720                                blctx);
721   blctx->blc = NULL;
722   if (GNUNET_OK != result)
723   {
724     cancel_pending_blacklist_checks (blctx->address,
725                                      blctx->session);
726     kill_session (blctx->address->transport_name,
727                   blctx->session);
728   }
729   else if (GNUNET_YES !=
730            GNUNET_HELLO_address_check_option (blctx->address,
731                                               GNUNET_HELLO_ADDRESS_INFO_INBOUND))
732   {
733     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
734                 "Informing verifier about inbound session's address `%s'\n",
735                 GST_plugins_a2s (blctx->address));
736     GST_validation_handle_address (blctx->address);
737   }
738   GNUNET_HELLO_address_free (blctx->address);
739   GNUNET_free (blctx);
740 }
741
742
743 /**
744  * Plugin tells transport service about a new inbound session
745  *
746  * @param cls unused
747  * @param address the address
748  * @param session the new session
749  * @param scope network scope information
750  */
751 static void
752 plugin_env_session_start (void *cls,
753                           const struct GNUNET_HELLO_Address *address,
754                           struct Session *session,
755                           enum GNUNET_ATS_Network_Type scope)
756 {
757   struct BlacklistCheckContext *blctx;
758   struct GST_BlacklistCheck *blc;
759   struct GNUNET_ATS_Properties prop;
760
761   if (NULL == address)
762   {
763     GNUNET_break(0);
764     return;
765   }
766   if (NULL == session)
767   {
768     GNUNET_break(0);
769     return;
770   }
771   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
772               "Notification from plugin `%s' about new session from peer `%s' address `%s'\n",
773               address->transport_name,
774               GNUNET_i2s (&address->peer),
775               GST_plugins_a2s (address));
776   if (GNUNET_YES ==
777       GNUNET_HELLO_address_check_option (address,
778                                          GNUNET_HELLO_ADDRESS_INFO_INBOUND))
779   {
780     /* inbound is always new, but outbound MAY already be known, but
781        for example for UNIX, we have symmetric connections and thus we
782        may not know the address yet; add if necessary! */
783     /* FIXME: maybe change API here so we just pass scope? */
784     memset (&prop, 0, sizeof (prop));
785     prop.scope = scope;
786     GST_ats_add_inbound_address (address,
787                                  session,
788                                  &prop);
789   }
790   /* Do blacklist check if communication with this peer is allowed */
791   blctx = GNUNET_new (struct BlacklistCheckContext);
792   blctx->address = GNUNET_HELLO_address_copy (address);
793   blctx->session = session;
794   GNUNET_CONTAINER_DLL_insert (bc_head,
795                                bc_tail,
796                                blctx);
797   if (NULL !=
798       (blc = GST_blacklist_test_allowed (&address->peer,
799                                          address->transport_name,
800                                          &plugin_env_session_start_bl_check_cont,
801                                          blctx)))
802   {
803     blctx->blc = blc;
804   }
805 }
806
807
808 /**
809  * Function called by ATS to notify the callee that the
810  * assigned bandwidth or address for a given peer was changed.  If the
811  * callback is called with address/bandwidth assignments of zero, the
812  * ATS disconnect function will still be called once the disconnect
813  * actually happened.
814  *
815  * @param cls closure
816  * @param peer the peer this address is intended for
817  * @param address address to use (for peer given in address)
818  * @param session session to use (if available)
819  * @param bandwidth_out assigned outbound bandwidth for the connection in NBO,
820  *      0 to disconnect from peer
821  * @param bandwidth_in assigned inbound bandwidth for the connection in NBO,
822  *      0 to disconnect from peer
823  * @param ats ATS information
824  * @param ats_count number of @a ats elements
825  */
826 static void
827 ats_request_address_change (void *cls,
828                             const struct GNUNET_PeerIdentity *peer,
829                             const struct GNUNET_HELLO_Address *address,
830                             struct Session *session,
831                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
832                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in)
833 {
834   uint32_t bw_in = ntohl (bandwidth_in.value__);
835   uint32_t bw_out = ntohl (bandwidth_out.value__);
836
837   if (NULL == peer)
838   {
839     /* ATS service died, all suggestions become invalid!
840        (but we'll keep using the allocations for a little
841        while, to keep going while ATS restarts) */
842     /* FIXME: We should drop all
843        connections now, as ATS won't explicitly tell
844        us and be unaware of ongoing resource allocations! */
845     return;
846   }
847   /* ATS tells me to disconnect from peer */
848   if ((0 == bw_in) && (0 == bw_out))
849   {
850     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
851                 "ATS tells me to disconnect from peer `%s'\n",
852                 GNUNET_i2s (peer));
853     GST_neighbours_force_disconnect (peer);
854     return;
855   }
856   GNUNET_assert (NULL != address);
857   GNUNET_STATISTICS_update (GST_stats,
858                             "# ATS suggestions received",
859                             1,
860                             GNUNET_NO);
861   GST_neighbours_switch_to_address (address,
862                                     session,
863                                     bandwidth_in,
864                                     bandwidth_out);
865 }
866
867
868 /**
869  * Function called when the service shuts down.  Unloads our plugins
870  * and cancels pending validations.
871  *
872  * @param cls closure, unused
873  * @param tc task context (unused)
874  */
875 static void
876 shutdown_task (void *cls,
877                const struct GNUNET_SCHEDULER_TaskContext *tc)
878 {
879   GST_neighbours_stop ();
880   GST_plugins_unload ();
881   GST_validation_stop ();
882   GST_ats_done ();
883   GNUNET_ATS_scheduling_done (GST_ats);
884   GST_ats = NULL;
885   GNUNET_ATS_connectivity_done (GST_ats_connect);
886   GST_ats_connect = NULL;
887   GNUNET_ATS_scanner_done (GST_is);
888   GST_is = NULL;
889   GST_clients_stop ();
890   GST_blacklist_stop ();
891   GST_hello_stop ();
892   GST_manipulation_stop ();
893
894   if (NULL != GST_peerinfo)
895   {
896     GNUNET_PEERINFO_disconnect (GST_peerinfo);
897     GST_peerinfo = NULL;
898   }
899   if (NULL != GST_stats)
900   {
901     GNUNET_STATISTICS_destroy (GST_stats, GNUNET_NO);
902     GST_stats = NULL;
903   }
904   if (NULL != GST_my_private_key)
905   {
906     GNUNET_free(GST_my_private_key);
907     GST_my_private_key = NULL;
908   }
909   GST_server = NULL;
910 }
911
912
913 /**
914  * Initiate transport service.
915  *
916  * @param cls closure
917  * @param server the initialized server
918  * @param c configuration to use
919  */
920 static void
921 run (void *cls,
922      struct GNUNET_SERVER_Handle *server,
923      const struct GNUNET_CONFIGURATION_Handle *c)
924 {
925   char *keyfile;
926   struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
927   long long unsigned int max_fd_cfg;
928   int max_fd_rlimit;
929   int max_fd;
930   int friend_only;
931
932   /* setup globals */
933   GST_cfg = c;
934   if (GNUNET_OK !=
935       GNUNET_CONFIGURATION_get_value_filename (c,
936                                                "PEER",
937                                                "PRIVATE_KEY",
938                                                &keyfile))
939   {
940     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
941         _("Transport service is lacking key configuration settings. Exiting.\n"));
942     GNUNET_SCHEDULER_shutdown ();
943     return;
944   }
945   if (GNUNET_OK !=
946       GNUNET_CONFIGURATION_get_value_time (c,
947                                            "transport",
948                                            "HELLO_EXPIRATION",
949                                            &hello_expiration))
950   {
951     hello_expiration = GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION;
952   }
953   GST_server = server;
954   pk = GNUNET_CRYPTO_eddsa_key_create_from_file (keyfile);
955   GNUNET_free (keyfile);
956   GNUNET_assert (NULL != pk);
957   GST_my_private_key = pk;
958
959   GST_stats = GNUNET_STATISTICS_create ("transport", GST_cfg);
960   GST_peerinfo = GNUNET_PEERINFO_connect (GST_cfg);
961   GNUNET_CRYPTO_eddsa_key_get_public (GST_my_private_key,
962                                       &GST_my_identity.public_key);
963   GNUNET_assert(NULL != GST_my_private_key);
964
965   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
966              "My identity is `%4s'\n",
967              GNUNET_i2s_full (&GST_my_identity));
968
969   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
970                                 &shutdown_task,
971                                 NULL);
972   if (NULL == GST_peerinfo)
973   {
974     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
975         _("Could not access PEERINFO service.  Exiting.\n"));
976     GNUNET_SCHEDULER_shutdown ();
977     return;
978   }
979
980   max_fd_rlimit = 0;
981   max_fd_cfg = 0;
982 #if HAVE_GETRLIMIT
983   struct rlimit r_file;
984   if (0 == getrlimit (RLIMIT_NOFILE, &r_file))
985   {
986     max_fd_rlimit = r_file.rlim_cur;
987     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
988         "Maximum number of open files was: %u/%u\n",
989         r_file.rlim_cur,
990         r_file.rlim_max);
991   }
992   max_fd_rlimit = (9 * max_fd_rlimit) / 10; /* Keep 10% for rest of transport */
993 #endif
994   GNUNET_CONFIGURATION_get_value_number (GST_cfg,
995                                          "transport",
996                                          "MAX_FD",
997                                          &max_fd_cfg);
998
999   if (max_fd_cfg > max_fd_rlimit)
1000     max_fd = max_fd_cfg;
1001   else
1002     max_fd = max_fd_rlimit;
1003   if (max_fd < DEFAULT_MAX_FDS)
1004     max_fd = DEFAULT_MAX_FDS;
1005
1006   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1007               "Limiting number of sockets to %u: validation %u, neighbors: %u\n",
1008              max_fd, (max_fd / 3), (max_fd / 3) * 2);
1009
1010   friend_only = GNUNET_CONFIGURATION_get_value_yesno (GST_cfg,
1011                                                       "topology",
1012                                                       "FRIENDS-ONLY");
1013   if (GNUNET_SYSERR == friend_only)
1014     friend_only = GNUNET_NO; /* According to topology defaults */
1015   /* start subsystems */
1016   GST_blacklist_start (GST_server,
1017                        GST_cfg,
1018                        &GST_my_identity);
1019   GST_is = GNUNET_ATS_scanner_init ();
1020   GST_ats_connect = GNUNET_ATS_connectivity_init (GST_cfg);
1021   GST_ats = GNUNET_ATS_scheduling_init (GST_cfg,
1022                                         &ats_request_address_change,
1023                                         NULL);
1024   GST_ats_init ();
1025   GST_manipulation_init ();
1026   GST_plugins_load (&GST_manipulation_recv,
1027                     &plugin_env_address_change_notification,
1028                     &plugin_env_session_start,
1029                     &plugin_env_session_end);
1030   GST_hello_start (friend_only,
1031                    &process_hello_update,
1032                    NULL);
1033   GST_neighbours_start ((max_fd / 3) * 2);
1034   GST_clients_start (GST_server);
1035   GST_validation_start ((max_fd / 3));
1036 }
1037
1038
1039 /**
1040  * The main function for the transport service.
1041  *
1042  * @param argc number of arguments from the command line
1043  * @param argv command line arguments
1044  * @return 0 ok, 1 on error
1045  */
1046 int
1047 main (int argc,
1048       char * const *argv)
1049 {
1050   return
1051       (GNUNET_OK
1052           == GNUNET_SERVICE_run (argc, argv, "transport",
1053               GNUNET_SERVICE_OPTION_NONE, &run, NULL )) ? 0 : 1;
1054 }
1055
1056 /* end of file gnunet-service-transport.c */