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