fix #3664: during PS_RECONNECT_ATS, primary address may be NULL, causing an NPE if...
[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 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 (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  * Function that will be called to figure if an address is an loopback,
701  * LAN, WAN etc. address
702  *
703  * @param cls closure
704  * @param addr binary address
705  * @param addrlen length of the @a addr
706  * @return type of the network @a addr belongs to
707  */
708 static enum GNUNET_ATS_Network_Type
709 plugin_env_address_to_type (void *cls,
710                             const struct sockaddr *addr,
711                             size_t addrlen)
712 {
713   if (NULL == GST_ats)
714   {
715     GNUNET_break(0);
716     return GNUNET_ATS_NET_UNSPECIFIED;
717   }
718   return GNUNET_ATS_scanner_address_get_type (is,
719                                               addr,
720                                               addrlen);
721 }
722
723
724 /**
725  * Function that will be called to update metrics for an address
726  *
727  * @param cls closure
728  * @param address address to update metrics for
729  * @param session the session
730  * @param ats the ats information to update
731  * @param ats_count the number of @a ats elements
732  */
733 static void
734 plugin_env_update_metrics (void *cls,
735                            const struct GNUNET_HELLO_Address *address,
736                            struct Session *session,
737                            const struct GNUNET_ATS_Information *ats,
738                            uint32_t ats_count)
739 {
740   GST_ats_update_metrics (address,
741                           session,
742                           ats, ats_count);
743 }
744
745
746 /**
747  * Black list check result from blacklist check triggered when a
748  * plugin gave us a new session in #plugin_env_session_start().  If
749  * connection to the peer is disallowed, kill the session.
750  *
751  * @param cls blc_ctx bl context
752  * @param peer the peer
753  * @param result the result
754  */
755 static void
756 plugin_env_session_start_bl_check_cont (void *cls,
757                                         const struct GNUNET_PeerIdentity *peer,
758                                         int result)
759 {
760   struct BlacklistCheckContext *blctx = cls;
761
762   GNUNET_CONTAINER_DLL_remove (bc_head,
763                                bc_tail,
764                                blctx);
765   blctx->blc = NULL;
766   if (GNUNET_OK != result)
767   {
768     cancel_pending_blacklist_checks (blctx->address,
769                                      blctx->session);
770     kill_session (blctx->address->transport_name,
771                   blctx->session);
772   }
773   else if (GNUNET_YES !=
774            GNUNET_HELLO_address_check_option (blctx->address,
775                                               GNUNET_HELLO_ADDRESS_INFO_INBOUND))
776   {
777     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
778                 "Informing verifier about inbound session's address `%s'\n",
779                 GST_plugins_a2s (blctx->address));
780     GST_validation_handle_address (blctx->address);
781   }
782   GNUNET_HELLO_address_free (blctx->address);
783   GNUNET_free (blctx);
784 }
785
786
787 /**
788  * Plugin tells transport service about a new inbound session
789  *
790  * @param cls unused
791  * @param address the address
792  * @param session the new session
793  * @param ats ats information
794  * @param ats_count number of @a ats information
795  */
796 static void
797 plugin_env_session_start (void *cls,
798                           const struct GNUNET_HELLO_Address *address,
799                           struct Session *session,
800                           const struct GNUNET_ATS_Information *ats,
801                           uint32_t ats_count)
802 {
803   struct BlacklistCheckContext *blctx;
804   struct GST_BlacklistCheck *blc;
805
806   if (NULL == address)
807   {
808     GNUNET_break(0);
809     return;
810   }
811   if (NULL == session)
812   {
813     GNUNET_break(0);
814     return;
815   }
816   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
817               "Notification from plugin `%s' about new session %p from peer `%s' address `%s'\n",
818               address->transport_name,
819               session,
820               GNUNET_i2s (&address->peer),
821               GST_plugins_a2s (address));
822   if (GNUNET_YES ==
823       GNUNET_HELLO_address_check_option (address,
824                                          GNUNET_HELLO_ADDRESS_INFO_INBOUND))
825   {
826     /* inbound is always new, but outbound MAY already be known, but
827        for example for UNIX, we have symmetric connections and thus we
828        may not know the address yet; add if necessary! */
829     GST_ats_add_inbound_address (address,
830                                  session,
831                                  ats,
832                                  ats_count);
833   }
834   else
835   {
836     if (GNUNET_YES ==
837         GST_ats_is_known (address,
838                           session))
839     {
840       GST_ats_update_metrics (address,
841                               session,
842                               ats,
843                               ats_count);
844     }
845   }
846   /* Do blacklist check if communication with this peer is allowed */
847   blctx = GNUNET_new (struct BlacklistCheckContext);
848   blctx->address = GNUNET_HELLO_address_copy (address);
849   blctx->session = session;
850   GNUNET_CONTAINER_DLL_insert (bc_head,
851                                bc_tail,
852                                blctx);
853   if (NULL !=
854       (blc = GST_blacklist_test_allowed (&address->peer,
855                                          address->transport_name,
856                                          &plugin_env_session_start_bl_check_cont,
857                                          blctx)))
858   {
859     blctx->blc = blc;
860   }
861 }
862
863
864 /**
865  * Function called by ATS to notify the callee that the
866  * assigned bandwidth or address for a given peer was changed.  If the
867  * callback is called with address/bandwidth assignments of zero, the
868  * ATS disconnect function will still be called once the disconnect
869  * actually happened.
870  *
871  * @param cls closure
872  * @param peer the peer this address is intended for
873  * @param address address to use (for peer given in address)
874  * @param session session to use (if available)
875  * @param bandwidth_out assigned outbound bandwidth for the connection in NBO,
876  *      0 to disconnect from peer
877  * @param bandwidth_in assigned inbound bandwidth for the connection in NBO,
878  *      0 to disconnect from peer
879  * @param ats ATS information
880  * @param ats_count number of @a ats elements
881  */
882 static void
883 ats_request_address_change (void *cls,
884                             const struct GNUNET_PeerIdentity *peer,
885                             const struct GNUNET_HELLO_Address *address,
886                             struct Session *session,
887                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
888                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in)
889 {
890   uint32_t bw_in = ntohl (bandwidth_in.value__);
891   uint32_t bw_out = ntohl (bandwidth_out.value__);
892
893   if (NULL == peer)
894   {
895     /* ATS service died, all suggestions become invalid!
896        (but we'll keep using the allocations for a little
897        while, to keep going while ATS restarts) */
898     /* FIXME: We should drop all
899        connections now, as ATS won't explicitly tell
900        us and be unaware of ongoing resource allocations! */
901     return;
902   }
903   /* ATS tells me to disconnect from peer */
904   if ((0 == bw_in) && (0 == bw_out))
905   {
906     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
907                 "ATS tells me to disconnect from peer `%s'\n",
908                 GNUNET_i2s (peer));
909     GST_neighbours_force_disconnect (peer);
910     return;
911   }
912   GNUNET_assert (NULL != address);
913   GNUNET_STATISTICS_update (GST_stats,
914                             "# ATS suggestions received",
915                             1,
916                             GNUNET_NO);
917   GST_neighbours_switch_to_address (address,
918                                     session,
919                                     bandwidth_in,
920                                     bandwidth_out);
921 }
922
923
924 /**
925  * Function called when the service shuts down.  Unloads our plugins
926  * and cancels pending validations.
927  *
928  * @param cls closure, unused
929  * @param tc task context (unused)
930  */
931 static void
932 shutdown_task (void *cls,
933                const struct GNUNET_SCHEDULER_TaskContext *tc)
934 {
935   GST_neighbours_stop ();
936   GST_plugins_unload ();
937   GST_validation_stop ();
938   GST_ats_done ();
939   GNUNET_ATS_scheduling_done (GST_ats);
940   GST_ats = NULL;
941   GNUNET_ATS_connectivity_done (GST_ats_connect);
942   GST_ats_connect = NULL;
943   GNUNET_ATS_scanner_done (is);
944   is = NULL;
945   GST_clients_stop ();
946   GST_blacklist_stop ();
947   GST_hello_stop ();
948   GST_manipulation_stop ();
949
950   if (NULL != GST_peerinfo)
951   {
952     GNUNET_PEERINFO_disconnect (GST_peerinfo);
953     GST_peerinfo = NULL;
954   }
955   if (NULL != GST_stats)
956   {
957     GNUNET_STATISTICS_destroy (GST_stats, GNUNET_NO);
958     GST_stats = NULL;
959   }
960   if (NULL != GST_my_private_key)
961   {
962     GNUNET_free(GST_my_private_key);
963     GST_my_private_key = NULL;
964   }
965   GST_server = NULL;
966 }
967
968
969 /**
970  * Initiate transport service.
971  *
972  * @param cls closure
973  * @param server the initialized server
974  * @param c configuration to use
975  */
976 static void
977 run (void *cls,
978      struct GNUNET_SERVER_Handle *server,
979      const struct GNUNET_CONFIGURATION_Handle *c)
980 {
981   char *keyfile;
982   struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
983   long long unsigned int max_fd_cfg;
984   int max_fd_rlimit;
985   int max_fd;
986   int friend_only;
987
988   /* setup globals */
989   GST_cfg = c;
990   if (GNUNET_OK !=
991       GNUNET_CONFIGURATION_get_value_filename (c,
992                                                "PEER",
993                                                "PRIVATE_KEY",
994                                                &keyfile))
995   {
996     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
997         _("Transport service is lacking key configuration settings. Exiting.\n"));
998     GNUNET_SCHEDULER_shutdown ();
999     return;
1000   }
1001   if (GNUNET_OK !=
1002       GNUNET_CONFIGURATION_get_value_time (c,
1003                                            "transport",
1004                                            "HELLO_EXPIRATION",
1005                                            &hello_expiration))
1006   {
1007     hello_expiration = GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION;
1008   }
1009   GST_server = server;
1010   pk = GNUNET_CRYPTO_eddsa_key_create_from_file (keyfile);
1011   GNUNET_free (keyfile);
1012   GNUNET_assert (NULL != pk);
1013   GST_my_private_key = pk;
1014
1015   GST_stats = GNUNET_STATISTICS_create ("transport", GST_cfg);
1016   GST_peerinfo = GNUNET_PEERINFO_connect (GST_cfg);
1017   GNUNET_CRYPTO_eddsa_key_get_public (GST_my_private_key,
1018                                       &GST_my_identity.public_key);
1019   GNUNET_assert(NULL != GST_my_private_key);
1020
1021   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1022              "My identity is `%4s'\n",
1023              GNUNET_i2s_full (&GST_my_identity));
1024
1025   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1026                                 &shutdown_task,
1027                                 NULL);
1028   if (NULL == GST_peerinfo)
1029   {
1030     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1031         _("Could not access PEERINFO service.  Exiting.\n"));
1032     GNUNET_SCHEDULER_shutdown ();
1033     return;
1034   }
1035
1036   max_fd_rlimit = 0;
1037   max_fd_cfg = 0;
1038 #if HAVE_GETRLIMIT
1039   struct rlimit r_file;
1040   if (0 == getrlimit (RLIMIT_NOFILE, &r_file))
1041   {
1042     max_fd_rlimit = r_file.rlim_cur;
1043     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1044         "Maximum number of open files was: %u/%u\n",
1045         r_file.rlim_cur,
1046         r_file.rlim_max);
1047   }
1048   max_fd_rlimit = (9 * max_fd_rlimit) / 10; /* Keep 10% for rest of transport */
1049 #endif
1050   GNUNET_CONFIGURATION_get_value_number (GST_cfg,
1051                                          "transport",
1052                                          "MAX_FD",
1053                                          &max_fd_cfg);
1054
1055   if (max_fd_cfg > max_fd_rlimit)
1056     max_fd = max_fd_cfg;
1057   else
1058     max_fd = max_fd_rlimit;
1059   if (max_fd < DEFAULT_MAX_FDS)
1060     max_fd = DEFAULT_MAX_FDS;
1061
1062   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1063               "Limiting number of sockets to %u: validation %u, neighbors: %u\n",
1064              max_fd, (max_fd / 3), (max_fd / 3) * 2);
1065
1066   friend_only = GNUNET_CONFIGURATION_get_value_yesno (GST_cfg,
1067                                                       "topology",
1068                                                       "FRIENDS-ONLY");
1069   if (GNUNET_SYSERR == friend_only)
1070     friend_only = GNUNET_NO; /* According to topology defaults */
1071   /* start subsystems */
1072   GST_hello_start (friend_only,
1073                    &process_hello_update,
1074                    NULL);
1075   GST_blacklist_start (GST_server,
1076                        GST_cfg,
1077                        &GST_my_identity);
1078   is = GNUNET_ATS_scanner_init ();
1079   GST_ats_connect = GNUNET_ATS_connectivity_init (GST_cfg);
1080   GST_ats = GNUNET_ATS_scheduling_init (GST_cfg,
1081                                         &ats_request_address_change,
1082                                         NULL);
1083   GST_ats_init ();
1084   GST_manipulation_init (GST_cfg);
1085   GST_plugins_load (&GST_manipulation_recv,
1086                     &plugin_env_address_change_notification,
1087                     &plugin_env_session_start,
1088                     &plugin_env_session_end,
1089                     &plugin_env_address_to_type,
1090                     &plugin_env_update_metrics);
1091   GST_neighbours_start ((max_fd / 3) * 2);
1092   GST_clients_start (GST_server);
1093   GST_validation_start ((max_fd / 3));
1094 }
1095
1096
1097 /**
1098  * The main function for the transport service.
1099  *
1100  * @param argc number of arguments from the command line
1101  * @param argv command line arguments
1102  * @return 0 ok, 1 on error
1103  */
1104 int
1105 main (int argc, char * const *argv)
1106 {
1107   return
1108       (GNUNET_OK
1109           == GNUNET_SERVICE_run (argc, argv, "transport",
1110               GNUNET_SERVICE_OPTION_NONE, &run, NULL )) ? 0 : 1;
1111 }
1112
1113 /* end of file gnunet-service-transport.c */