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