- fixes
[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
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_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   GNUNET_SCHEDULER_TaskIdentifier task;
73 };
74
75
76 /* globals */
77
78 /**
79  * Statistics handle.
80  */
81 struct GNUNET_STATISTICS_Handle *GST_stats;
82
83 /**
84  * Configuration handle.
85  */
86 const struct GNUNET_CONFIGURATION_Handle *GST_cfg;
87
88 /**
89  * Configuration handle.
90  */
91 struct GNUNET_PeerIdentity GST_my_identity;
92
93 /**
94  * Handle to peerinfo service.
95  */
96 struct GNUNET_PEERINFO_Handle *GST_peerinfo;
97
98 /**
99  * Handle to our service's server.
100  */
101 static struct GNUNET_SERVER_Handle *GST_server;
102
103 /**
104  * Our private key.
105  */
106 struct GNUNET_CRYPTO_EddsaPrivateKey *GST_my_private_key;
107
108 /**
109  * ATS handle.
110  */
111 struct GNUNET_ATS_SchedulingHandle *GST_ats;
112
113 /**
114  * Hello address expiration
115  */
116 struct GNUNET_TIME_Relative hello_expiration;
117
118 /**
119  * DEBUGGING connection counter
120  */
121 static int connections;
122
123 /**
124  * Head of DLL of asynchronous tasks to kill sessions.
125  */
126 static struct SessionKiller *sk_head;
127
128 /**
129  * Tail of DLL of asynchronous tasks to kill sessions.
130  */
131 static struct SessionKiller *sk_tail;
132
133
134 /**
135  * Transmit our HELLO message to the given (connected) neighbour.
136  *
137  * @param cls the 'HELLO' message
138  * @param target a connected neighbour
139  * @param address the address
140  * @param state current state this peer is in
141  * @param state_timeout timeout for the current state of the peer
142  * @param bandwidth_in inbound quota in NBO
143  * @param bandwidth_out outbound quota in NBO
144  */
145 static void
146 transmit_our_hello (void *cls, const struct GNUNET_PeerIdentity *target,
147                     const struct GNUNET_HELLO_Address *address,
148                     enum GNUNET_TRANSPORT_PeerState state,
149                     struct GNUNET_TIME_Absolute state_timeout,
150                     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
151                     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
152 {
153   const struct GNUNET_MessageHeader *hello = cls;
154
155   if ( GNUNET_NO == GST_neighbours_test_connected(target) )
156     return;
157
158   GST_neighbours_send (target,
159                        hello,
160                        ntohs (hello->size),
161                        hello_expiration, NULL, NULL);
162 }
163
164
165 /**
166  * My HELLO has changed. Tell everyone who should know.
167  *
168  * @param cls unused
169  * @param hello new HELLO
170  */
171 static void
172 process_hello_update (void *cls,
173                       const struct GNUNET_MessageHeader *hello)
174 {
175   GST_clients_broadcast (hello, GNUNET_NO);
176   GST_neighbours_iterate (&transmit_our_hello, (void *) hello);
177 }
178
179
180 /**
181  * We received some payload.  Prepare to pass it on to our clients.
182  *
183  * @param peer (claimed) identity of the other peer
184  * @param address the address
185  * @param session session used
186  * @param message the message to process
187  * @return how long the plugin should wait until receiving more data
188  */
189 static struct GNUNET_TIME_Relative
190 process_payload (const struct GNUNET_PeerIdentity *peer,
191                  const struct GNUNET_HELLO_Address *address,
192                  struct Session *session,
193                  const struct GNUNET_MessageHeader *message)
194 {
195   struct GNUNET_TIME_Relative ret;
196   int do_forward;
197   struct InboundMessage *im;
198   size_t msg_size = ntohs (message->size);
199   size_t size =
200       sizeof (struct InboundMessage) + msg_size;
201   char buf[size] GNUNET_ALIGN;
202
203   do_forward = GNUNET_SYSERR;
204   ret = GST_neighbours_calculate_receive_delay (peer, msg_size, &do_forward);
205   if (! GST_neighbours_test_connected (peer))
206   {
207     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
208                 "Discarded %u bytes type %u payload from peer `%s'\n",
209                 msg_size,
210                 ntohs (message->type), GNUNET_i2s (peer));
211     GNUNET_STATISTICS_update (GST_stats,
212                               gettext_noop
213                               ("# bytes payload discarded due to not connected peer"),
214                               msg_size, GNUNET_NO);
215     return ret;
216   }
217
218   GST_ats_add_address (address, session, NULL, 0);
219
220   if (GNUNET_YES != do_forward)
221     return ret;
222   im = (struct InboundMessage *) buf;
223   im->header.size = htons (size);
224   im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
225   im->peer = *peer;
226   memcpy (&im[1], message, ntohs (message->size));
227   GST_clients_broadcast (&im->header, GNUNET_YES);
228   return ret;
229 }
230
231
232 /**
233  * Task to asynchronously terminate a session.
234  *
235  * @param cls the `struct SessionKiller` with the information for the kill
236  * @param tc scheduler context
237  */
238 static void
239 kill_session_task (void *cls,
240                    const struct GNUNET_SCHEDULER_TaskContext *tc)
241 {
242   struct SessionKiller *sk = cls;
243
244   sk->task = GNUNET_SCHEDULER_NO_TASK;
245   GNUNET_CONTAINER_DLL_remove (sk_head, sk_tail, sk);
246   sk->plugin->disconnect_session (sk->plugin->cls,
247                                   sk->session);
248   GNUNET_free (sk);
249 }
250
251
252 /**
253  * Force plugin to terminate session due to communication
254  * issue.
255  *
256  * @param plugin_name name of the plugin
257  * @param session session to termiante
258  */
259 static void
260 kill_session (const char *plugin_name,
261               struct Session *session)
262 {
263   struct GNUNET_TRANSPORT_PluginFunctions *plugin;
264   struct SessionKiller *sk;
265
266   for (sk = sk_head; NULL != sk; sk = sk->next)
267     if (sk->session == session)
268       return;
269   plugin = GST_plugins_find (plugin_name);
270   if (NULL == plugin)
271   {
272     GNUNET_break (0);
273     return;
274   }
275   /* need to issue disconnect asynchronously */
276   sk = GNUNET_new (struct SessionKiller);
277   sk->session = session;
278   sk->plugin = plugin;
279   sk->task = GNUNET_SCHEDULER_add_now (&kill_session_task,
280                                        sk);
281   GNUNET_CONTAINER_DLL_insert (sk_head, sk_tail, sk);
282 }
283
284
285 /**
286  * Function called by the transport for each received message.
287  *
288  * @param cls closure, const char* with the name of the plugin we received the message from
289  * @param peer (claimed) identity of the other peer
290  * @param message the message, NULL if we only care about
291  *                learning about the delay until we should receive again
292  * @param session identifier used for this session (NULL for plugins
293  *                that do not offer bi-directional communication to the sender
294  *                using the same "connection")
295  * @param sender_address binary address of the sender (if we established the
296  *                connection or are otherwise sure of it; should be NULL
297  *                for inbound TCP/UDP connections since it it not clear
298  *                that we could establish ourselves a connection to that
299  *                IP address and get the same system)
300  * @param sender_address_len number of bytes in @a sender_address
301  * @return how long the plugin should wait until receiving more data
302  *         (plugins that do not support this, can ignore the return value)
303  */
304 struct GNUNET_TIME_Relative
305 GST_receive_callback (void *cls,
306                       const struct GNUNET_PeerIdentity *peer,
307                       const struct GNUNET_MessageHeader *message,
308                       struct Session *session,
309                       const char *sender_address,
310                       uint16_t sender_address_len)
311 {
312   const char *plugin_name = cls;
313   struct GNUNET_TIME_Relative ret;
314   struct GNUNET_HELLO_Address address;
315   uint16_t type;
316
317   address.peer = *peer;
318   address.address = sender_address;
319   address.address_length = sender_address_len;
320   address.transport_name = plugin_name;
321   ret = GNUNET_TIME_UNIT_ZERO;
322   if (NULL == message)
323     goto end;
324   type = ntohs (message->type);
325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
326               "Received Message with type %u from peer `%s'\n",
327               type,
328               GNUNET_i2s (peer));
329
330   GNUNET_STATISTICS_update (GST_stats,
331                             gettext_noop
332                             ("# bytes total received"),
333                             ntohs (message->size), GNUNET_NO);
334   GST_neighbours_notify_data_recv (peer, &address, session, message);
335
336   switch (type)
337   {
338   case GNUNET_MESSAGE_TYPE_HELLO_LEGACY:
339     /* Legacy HELLO message, discard  */
340     return ret;
341   case GNUNET_MESSAGE_TYPE_HELLO:
342     if (GNUNET_OK !=
343         GST_validation_handle_hello (message))
344     {
345       GNUNET_break_op (0);
346       kill_session (plugin_name, session);
347     }
348     return ret;
349   case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
350     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
351                 "Processing `%s' from `%s'\n", "PING",
352                 (sender_address !=
353                  NULL) ? GST_plugins_a2s (&address) : TRANSPORT_SESSION_INBOUND_STRING);
354     if (GNUNET_OK !=
355         GST_validation_handle_ping (peer, message, &address, session))
356       kill_session (plugin_name, session);
357     break;
358   case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
359     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
360                 "Processing `%s' from `%s'\n", "PONG",
361                 (sender_address !=
362                  NULL) ? GST_plugins_a2s (&address) : TRANSPORT_SESSION_INBOUND_STRING);
363     if (GNUNET_OK !=
364         GST_validation_handle_pong (peer, message))
365     {
366       GNUNET_break_op (0);
367       kill_session (plugin_name, session);
368     }
369     break;
370   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT:
371     if (GNUNET_OK !=
372         GST_neighbours_handle_connect (message, peer, &address, session))
373     {
374       GNUNET_break_op (0);
375       kill_session (plugin_name, session);
376     }
377     break;
378   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK:
379     if (GNUNET_OK !=
380         GST_neighbours_handle_connect_ack (message, peer, &address, session))
381     {
382       kill_session (plugin_name, session);
383     }
384     break;
385   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK:
386     if (GNUNET_OK !=
387         GST_neighbours_handle_session_ack (message, peer, &address, session))
388     {
389       GNUNET_break_op (0);
390       kill_session (plugin_name, session);
391     }
392     break;
393   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT:
394     GST_neighbours_handle_disconnect_message (peer, message);
395     break;
396   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE:
397     GST_neighbours_keepalive (peer, message);
398     break;
399   case GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE:
400     GST_neighbours_keepalive_response (peer, message);
401     break;
402   default:
403     /* should be payload */
404     GNUNET_STATISTICS_update (GST_stats,
405                               gettext_noop
406                               ("# bytes payload received"),
407                               ntohs (message->size), GNUNET_NO);
408     GST_neighbours_notify_payload_recv (peer, &address, session, message);
409     ret = process_payload (peer, &address, session, message);
410     break;
411   }
412 end:
413   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
414               "Allowing receive from peer %s to continue in %s\n",
415               GNUNET_i2s (peer),
416               GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
417   return ret;
418 }
419
420
421 /**
422  * Function that will be called for each address the transport
423  * is aware that it might be reachable under.  Update our HELLO.
424  *
425  * @param cls name of the plugin (const char*)
426  * @param add_remove should the address added (YES) or removed (NO) from the
427  *                   set of valid addresses?
428  * @param addr one of the addresses of the host
429  *        the specific address format depends on the transport
430  * @param addrlen length of the @a addr
431  * @param dest_plugin destination plugin to use this address with
432  */
433 static void
434 plugin_env_address_change_notification (void *cls, int add_remove,
435                                         const void *addr, size_t addrlen,
436                                         const char *dest_plugin)
437 {
438   struct GNUNET_HELLO_Address address;
439
440   address.peer = GST_my_identity;
441   address.transport_name = dest_plugin;
442   address.address = addr;
443   address.address_length = addrlen;
444   GST_hello_modify_addresses (add_remove, &address);
445 }
446
447
448 /**
449  * Function that will be called whenever the plugin internally
450  * cleans up a session pointer and hence the service needs to
451  * discard all of those sessions as well.  Plugins that do not
452  * use sessions can simply omit calling this function and always
453  * use NULL wherever a session pointer is needed.  This function
454  * should be called BEFORE a potential "TransmitContinuation"
455  * from the "TransmitFunction".
456  *
457  * @param cls closure
458  * @param peer which peer was the session for
459  * @param session which session is being destoyed
460  */
461 static void
462 plugin_env_session_end (void *cls, const struct GNUNET_PeerIdentity *peer,
463                         struct Session *session)
464 {
465   const char *transport_name = cls;
466   struct GNUNET_HELLO_Address address;
467   struct SessionKiller *sk;
468
469   GNUNET_assert (strlen (transport_name) > 0);
470   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
471               "Session %p to peer `%s' ended \n",
472               session,
473               GNUNET_i2s (peer));
474   if (NULL != session)
475     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
476                      "transport-ats",
477                      "Telling ATS to destroy session %p from peer %s\n",
478                      session, GNUNET_i2s (peer));
479   address.peer = *peer;
480   address.address = NULL;
481   address.address_length = 0;
482   address.transport_name = transport_name;
483   GST_neighbours_session_terminated (peer, session);
484
485   /* Tell ATS that session has ended */
486   GNUNET_ATS_address_destroyed (GST_ats, &address, session);
487   for (sk = sk_head; NULL != sk; sk = sk->next)
488   {
489     if (sk->session == session)
490     {
491       GNUNET_CONTAINER_DLL_remove (sk_head, sk_tail, sk);
492       GNUNET_SCHEDULER_cancel (sk->task);
493       GNUNET_free (sk);
494       break;
495     }
496   }
497 }
498
499
500 /**
501  * Function that will be called to figure if an address is an loopback,
502  * LAN, WAN etc. address
503  *
504  * @param cls closure
505  * @param addr binary address
506  * @param addrlen length of the address
507  * @return ATS Information containing the network type
508  */
509 static struct GNUNET_ATS_Information
510 plugin_env_address_to_type (void *cls,
511                             const struct sockaddr *addr,
512                             size_t addrlen)
513 {
514   struct GNUNET_ATS_Information ats;
515
516   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
517   ats.value = htonl (GNUNET_ATS_NET_UNSPECIFIED);
518   if (NULL == GST_ats)
519   {
520     GNUNET_break (0);
521     return ats;
522   }
523   if (((addr->sa_family != AF_INET) && (addrlen != sizeof (struct sockaddr_in))) &&
524       ((addr->sa_family != AF_INET6) && (addrlen != sizeof (struct sockaddr_in6))) &&
525       (addr->sa_family != AF_UNIX))
526   {
527     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
528                 "Malformed address with length %u `%s'\n",
529                 addrlen,
530                 GNUNET_a2s (addr, addrlen));
531     GNUNET_break (0);
532     return ats;
533   }
534   return GNUNET_ATS_address_get_type (GST_ats, addr, addrlen);
535 }
536
537
538 /**
539  * Notify ATS about the new address including the network this address is
540  * located in.
541  *
542  * @param address the address
543  * @param session the session
544  * @param ats ats information
545  * @param ats_count number of @a ats information
546  */
547 void
548 GST_ats_add_address (const struct GNUNET_HELLO_Address *address,
549                      struct Session *session,
550                      const struct GNUNET_ATS_Information *ats,
551                      uint32_t ats_count)
552 {
553   struct GNUNET_TRANSPORT_PluginFunctions *papi;
554   struct GNUNET_ATS_Information ats2[ats_count + 1];
555   uint32_t net;
556
557   /* valid new address, let ATS know! */
558   if (NULL == address->transport_name)
559   {
560     GNUNET_break (0);
561     return;
562   }
563   if (NULL == (papi = GST_plugins_find (address->transport_name)))
564   {
565     /* we don't have the plugin for this address */
566     GNUNET_break (0);
567     return;
568   }
569
570   if (GNUNET_YES == GNUNET_ATS_session_known (GST_ats, address, session))
571   {
572     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
573                 "ATS already knows the address, not passing it on again\n");
574     return;
575   }
576
577   net = papi->get_network (NULL, session);
578   if (GNUNET_ATS_NET_UNSPECIFIED == net)
579   {
580     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
581                 _("Could not obtain a valid network for `%s' %s (%s)\n"),
582                 GNUNET_i2s (&address->peer),
583                 GST_plugins_a2s (address),
584                 address->transport_name);
585     GNUNET_break (0);
586   }
587   ats2[0].type = htonl (GNUNET_ATS_NETWORK_TYPE);
588   ats2[0].value = htonl(net);
589   memcpy (&ats2[1], ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
591               "Notifying ATS about peer `%s''s new address `%s' session %p in network %s\n",
592               GNUNET_i2s (&address->peer),
593               (0 == address->address_length) ? "<inbound>" : GST_plugins_a2s (address),
594               session,
595               GNUNET_ATS_print_network_type(net));
596   GNUNET_ATS_address_add (GST_ats,
597                           address, session,
598                           ats2, ats_count + 1);
599 }
600
601
602 /**
603  * Notify ATS about property changes to an address
604  *
605  * @param peer the peer
606  * @param address the address
607  * @param session the session
608  * @param ats performance information
609  * @param ats_count number of elements in @a ats
610  */
611 void
612 GST_ats_update_metrics (const struct GNUNET_PeerIdentity *peer,
613                         const struct GNUNET_HELLO_Address *address,
614                         struct Session *session,
615                         const struct GNUNET_ATS_Information *ats,
616                         uint32_t ats_count)
617 {
618   struct GNUNET_ATS_Information *ats_new;
619
620   if (GNUNET_NO == GNUNET_ATS_session_known (GST_ats, address, session))
621     return;
622
623   /* Call to manipulation to manipulate ATS information */
624   ats_new = GST_manipulation_manipulate_metrics (peer, address, session, ats,
625                                                  ats_count);
626   if (NULL == ats_new)
627   {
628     GNUNET_break(0);
629     return;
630   }
631   if (GNUNET_NO == GNUNET_ATS_address_update (GST_ats,
632       address, session, ats_new, ats_count))
633   {
634     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
635                 _("Address or session unknown: failed to update properties for peer `%s' plugin `%s' address `%s' session %p\n"),
636                 GNUNET_i2s (peer),
637                 address->transport_name,
638                 GST_plugins_a2s (address),
639                 session);
640   }
641   GNUNET_free (ats_new);
642 }
643
644
645 /**
646  * Function that will be called to figure if an address is an loopback,
647  * LAN, WAN etc. address
648  *
649  * @param cls closure
650  * @param peer the peer
651  * @param address binary address
652  * @param address_len length of the @a address
653  * @param session the session
654  * @param ats the ats information to update
655  * @param ats_count the number of @a ats elements
656  */
657 static void
658 plugin_env_update_metrics (void *cls,
659                            const struct GNUNET_PeerIdentity *peer,
660                            const void *address,
661                            uint16_t address_len,
662                            struct Session *session,
663                            const struct GNUNET_ATS_Information *ats,
664                            uint32_t ats_count)
665 {
666   const char *plugin_name = cls;
667   struct GNUNET_HELLO_Address haddress;
668
669   if ((NULL == ats) || (0 == ats_count))
670     return;
671   GNUNET_assert (NULL != GST_ats);
672
673   haddress.peer = *peer;
674   haddress.address = address;
675   haddress.address_length = address_len;
676   haddress.transport_name = plugin_name;
677
678   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
679               "Updating metrics for peer `%s' address %s session %p\n",
680               GNUNET_i2s (peer),
681               GST_plugins_a2s (&haddress),
682               session);
683   GST_ats_update_metrics (peer, &haddress, session, ats, ats_count);
684 }
685
686
687 /**
688  * Plugin tells transport service about a new (inbound) session
689  *
690  * @param cls unused
691  * @param peer the peer
692  * @param plugin plugin name
693  * @param address address
694  * @param address_len @a address length
695  * @param session the new session
696  * @param ats ats information
697  * @param ats_count number of @a ats information
698  */
699 static void
700 plugin_env_session_start (void *cls,
701                           const struct GNUNET_PeerIdentity *peer,
702                           const char *plugin,
703                           const void *address, uint16_t address_len,
704                           struct Session *session,
705                           const struct GNUNET_ATS_Information *ats,
706                           uint32_t ats_count)
707 {
708   struct GNUNET_HELLO_Address *addr;
709
710   if (NULL == peer)
711   {
712     GNUNET_break(0);
713     return;
714   }
715   if (NULL == plugin)
716   {
717     GNUNET_break(0);
718     return;
719   }
720   if (NULL == session)
721   {
722     GNUNET_break(0);
723     return;
724   }
725
726   addr = GNUNET_HELLO_address_allocate (peer, plugin, address, address_len);
727   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
728               "Notification from plugin `%s' about new session %p from peer `%s' address `%s'\n",
729               plugin,
730               session,
731               GNUNET_i2s (peer),
732               GST_plugins_a2s (addr));
733   GST_ats_add_address (addr, session, ats, ats_count);
734   GNUNET_free(addr);
735 }
736
737
738 /**
739  * Function called by ATS to notify the callee that the
740  * assigned bandwidth or address for a given peer was changed.  If the
741  * callback is called with address/bandwidth assignments of zero, the
742  * ATS disconnect function will still be called once the disconnect
743  * actually happened.
744  *
745  * @param cls closure
746  * @param address address to use (for peer given in address)
747  * @param session session to use (if available)
748  * @param bandwidth_out assigned outbound bandwidth for the connection in NBO,
749  *      0 to disconnect from peer
750  * @param bandwidth_in assigned inbound bandwidth for the connection in NBO,
751  *      0 to disconnect from peer
752  * @param ats ATS information
753  * @param ats_count number of @a ats elements
754  */
755 static void
756 ats_request_address_change (void *cls,
757                             const struct GNUNET_HELLO_Address *address,
758                             struct Session *session,
759                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
760                             struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
761                             const struct GNUNET_ATS_Information *ats,
762                             uint32_t ats_count)
763 {
764   uint32_t bw_in = ntohl (bandwidth_in.value__);
765   uint32_t bw_out = ntohl (bandwidth_out.value__);
766
767   /* ATS tells me to disconnect from peer */
768   if ((0 == bw_in) && (0 == bw_out))
769   {
770     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
771                 "ATS tells me to disconnect from peer `%s'\n",
772                 GNUNET_i2s (&address->peer));
773     GST_neighbours_force_disconnect (&address->peer);
774     return;
775   }
776   GST_neighbours_switch_to_address (&address->peer, address, session, ats,
777                                     ats_count, bandwidth_in,
778                                     bandwidth_out);
779 }
780
781
782 /**
783  * Function called to notify transport users that another
784  * peer connected to us.
785  *
786  * @param cls closure
787  * @param peer the peer that connected
788  * @param bandwidth_in inbound bandwidth in NBO
789  * @param bandwidth_out outbound bandwidth in NBO
790  */
791 static void
792 neighbours_connect_notification (void *cls,
793                                  const struct GNUNET_PeerIdentity *peer,
794                                  struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
795                                  struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
796 {
797   size_t len = sizeof (struct ConnectInfoMessage);
798   char buf[len] GNUNET_ALIGN;
799   struct ConnectInfoMessage *connect_msg = (struct ConnectInfoMessage *) buf;
800
801   connections++;
802   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
803               "We are now connected to peer `%s' and %u peers in total\n",
804               GNUNET_i2s (peer), connections);
805   connect_msg->header.size = htons (sizeof (buf));
806   connect_msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
807   connect_msg->id = *peer;
808   connect_msg->quota_in = bandwidth_in;
809   connect_msg->quota_out = bandwidth_out;
810   GST_clients_broadcast (&connect_msg->header, GNUNET_NO);
811 }
812
813
814 /**
815  * Function called to notify transport users that another
816  * peer disconnected from us.
817  *
818  * @param cls closure
819  * @param peer the peer that disconnected
820  */
821 static void
822 neighbours_disconnect_notification (void *cls,
823                                     const struct GNUNET_PeerIdentity *peer)
824 {
825   struct DisconnectInfoMessage disconnect_msg;
826
827   connections--;
828   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
829               "Peer `%s' disconnected and we are connected to %u peers\n",
830               GNUNET_i2s (peer), connections);
831
832   GST_manipulation_peer_disconnect (peer);
833   disconnect_msg.header.size = htons (sizeof (struct DisconnectInfoMessage));
834   disconnect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
835   disconnect_msg.reserved = htonl (0);
836   disconnect_msg.peer = *peer;
837   GST_clients_broadcast (&disconnect_msg.header, GNUNET_NO);
838 }
839
840
841 /**
842  * Function called to notify transport users that a neighbour peer changed its
843  * active address.
844  *
845  * @param cls closure
846  * @param peer peer this update is about (never NULL)
847  * @param address address, NULL on disconnect
848  * @param state current state this peer is in
849  * @param state_timeout timeout for the current state of the peer
850  * @param bandwidth_in bandwidth assigned inbound
851  * @param bandwidth_out bandwidth assigned outbound
852  */
853 static void
854 neighbours_changed_notification (void *cls,
855                                  const struct GNUNET_PeerIdentity *peer,
856                                  const struct GNUNET_HELLO_Address *address,
857                                  enum GNUNET_TRANSPORT_PeerState state,
858                                  struct GNUNET_TIME_Absolute state_timeout,
859                                  struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
860                                  struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
861 {
862   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
863       "Notifying about change for peer `%s' with address `%s' in state `%s' timing out at %s\n",
864       GNUNET_i2s (peer),
865       (NULL != address) ? GST_plugins_a2s (address) : "<none>",
866       GNUNET_TRANSPORT_p2s(state),
867       GNUNET_STRINGS_absolute_time_to_string(state_timeout));
868
869   GST_clients_broadcast_peer_notification (peer, address, state, state_timeout);
870 }
871
872
873 /**
874  * Function called when the service shuts down.  Unloads our plugins
875  * and cancels pending validations.
876  *
877  * @param cls closure, unused
878  * @param tc task context (unused)
879  */
880 static void
881 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
882 {
883   GST_neighbours_stop ();
884   GST_validation_stop ();
885   GST_plugins_unload ();
886
887   GNUNET_ATS_scheduling_done (GST_ats);
888   GST_ats = 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, struct GNUNET_SERVER_Handle *server,
922      const struct GNUNET_CONFIGURATION_Handle *c)
923 {
924   char *keyfile;
925   struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
926   long long unsigned int max_fd_cfg;
927   int max_fd_rlimit;
928   int max_fd;
929   int friend_only;
930
931   /* setup globals */
932   GST_cfg = c;
933   if (GNUNET_OK !=
934       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
935                                                &keyfile))
936   {
937     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
938                 _("Transport service is lacking key configuration settings. Exiting.\n"));
939     GNUNET_SCHEDULER_shutdown ();
940     return;
941   }
942   if (GNUNET_OK !=
943       GNUNET_CONFIGURATION_get_value_time (c, "transport", "HELLO_EXPIRATION",
944                                            &hello_expiration))
945   {
946     hello_expiration = GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION;
947   }
948   GST_server = server;
949   pk = GNUNET_CRYPTO_eddsa_key_create_from_file (keyfile);
950   GNUNET_free (keyfile);
951   GNUNET_assert (NULL != pk);
952   GST_my_private_key = pk;
953
954   GST_stats = GNUNET_STATISTICS_create ("transport", GST_cfg);
955   GST_peerinfo = GNUNET_PEERINFO_connect (GST_cfg);
956   GNUNET_CRYPTO_eddsa_key_get_public (GST_my_private_key,
957                                                   &GST_my_identity.public_key);
958   GNUNET_assert (NULL != GST_my_private_key);
959
960   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
961               "My identity is `%4s'\n", GNUNET_i2s (&GST_my_identity));
962
963   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
964                                 NULL);
965   if (NULL == GST_peerinfo)
966   {
967     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
968                 _("Could not access PEERINFO service.  Exiting.\n"));
969     GNUNET_SCHEDULER_shutdown ();
970     return;
971   }
972
973   max_fd_rlimit = 0;
974   max_fd_cfg = 0;
975 #if HAVE_GETRLIMIT
976   struct rlimit r_file;
977   if (0 == getrlimit (RLIMIT_NOFILE, &r_file))
978   {
979     max_fd_rlimit = r_file.rlim_cur;
980     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
981                 "Maximum number of open files was: %u/%u\n",
982                 r_file.rlim_cur,
983                 r_file.rlim_max);
984   }
985   max_fd_rlimit = (9 * max_fd_rlimit) / 10; /* Keep 10% for rest of transport */
986 #endif
987   GNUNET_CONFIGURATION_get_value_number (GST_cfg, "transport", "MAX_FD", &max_fd_cfg);
988
989   if (max_fd_cfg > max_fd_rlimit)
990         max_fd = max_fd_cfg;
991   else
992         max_fd = max_fd_rlimit;
993   if (max_fd < DEFAULT_MAX_FDS)
994         max_fd = DEFAULT_MAX_FDS;
995
996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
997               "Limiting number of sockets to %u: validation %u, neighbors: %u\n",
998               max_fd, (max_fd / 3) , (max_fd / 3) * 2);
999
1000   friend_only = GNUNET_CONFIGURATION_get_value_yesno(GST_cfg, "topology","FRIENDS-ONLY");
1001   if (GNUNET_SYSERR == friend_only)
1002         friend_only = GNUNET_NO; /* According to topology defaults */
1003   /* start subsystems */
1004   GST_hello_start (friend_only, &process_hello_update, NULL);
1005   GNUNET_assert (NULL != GST_hello_get());
1006   GST_blacklist_start (GST_server, GST_cfg, &GST_my_identity);
1007   GST_ats =
1008       GNUNET_ATS_scheduling_init (GST_cfg, &ats_request_address_change, NULL);
1009   GST_manipulation_init (GST_cfg);
1010   GST_plugins_load (&GST_manipulation_recv,
1011                     &plugin_env_address_change_notification,
1012                     &plugin_env_session_start,
1013                     &plugin_env_session_end,
1014                     &plugin_env_address_to_type,
1015                     &plugin_env_update_metrics);
1016   GST_neighbours_start (NULL,
1017                         &neighbours_connect_notification,
1018                         &neighbours_disconnect_notification,
1019                         &neighbours_changed_notification,
1020                         (max_fd / 3) * 2);
1021   GST_clients_start (GST_server);
1022   GST_validation_start ((max_fd / 3));
1023 }
1024
1025
1026 /**
1027  * The main function for the transport service.
1028  *
1029  * @param argc number of arguments from the command line
1030  * @param argv command line arguments
1031  * @return 0 ok, 1 on error
1032  */
1033 int
1034 main (int argc, char *const *argv)
1035 {
1036   return (GNUNET_OK ==
1037           GNUNET_SERVICE_run (argc, argv, "transport",
1038                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1039 }
1040
1041 /* end of file gnunet-service-transport.c */