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