25896726177d73cedbe13653d21ef0d2fc16a1a6
[oweals/gnunet.git] / src / transport / gnunet-service-transport_neighbours.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010-2013 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_neighbours.c
23  * @brief neighbour management
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_ats_service.h"
28 #include "gnunet-service-transport_neighbours.h"
29 #include "gnunet-service-transport_plugins.h"
30 #include "gnunet-service-transport_validation.h"
31 #include "gnunet-service-transport_clients.h"
32 #include "gnunet-service-transport.h"
33 #include "gnunet_peerinfo_service.h"
34 #include "gnunet-service-transport_blacklist.h"
35 #include "gnunet_constants.h"
36 #include "transport.h"
37
38
39
40 /**
41  * Size of the neighbour hash map.
42  */
43 #define NEIGHBOUR_TABLE_SIZE 256
44
45 /**
46  * Time we give plugin to transmit DISCONNECT message before the
47  * neighbour entry self-destructs.
48  */
49 #define DISCONNECT_SENT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100)
50
51 /**
52  * How often must a peer violate bandwidth quotas before we start
53  * to simply drop its messages?
54  */
55 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
56
57 /**
58  * How long are we willing to wait for a response from ATS before timing out?
59  */
60 #define ATS_RESPONSE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 5000)
61
62 /**
63  * How long are we willing to wait for an ACK from the other peer before
64  * giving up on our connect operation?
65  */
66 #define SETUP_CONNECTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
67
68 /**
69  * How long are we willing to wait for a successful reconnect if
70  * an existing connection went down?  Much shorter than the
71  * usual SETUP_CONNECTION_TIMEOUT as we do not inform the
72  * higher layers about the disconnect during this period.
73  */
74 #define FAST_RECONNECT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
75
76 /**
77  * How long are we willing to wait for a response from the blacklist
78  * subsystem before timing out?
79  */
80 #define BLACKLIST_RESPONSE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500)
81
82 /**
83  * Interval to send utilization data
84  */
85 #define UTIL_TRANSMISSION_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
86
87 /**
88  * State describing which kind a reply this neighbour should send
89  */
90 enum GST_ACK_State
91 {
92   /**
93    * We did not receive a CONNECT message for this neighbour
94    */
95   ACK_UNDEFINED = 0,
96
97   /* The neighbour received a CONNECT message and has to send a CONNECT_ACK
98    * as reply */
99   ACK_SEND_CONNECT_ACK = 1,
100
101   /* The neighbour sent a CONNECT_ACK message and has to send a SESSION_ACK
102    * as reply */
103   ACK_SEND_SESSION_ACK = 2
104 };
105
106
107 GNUNET_NETWORK_STRUCT_BEGIN
108
109 /**
110  * Message a peer sends to another to indicate that it intends to
111  * setup a connection/session for data exchange.  A 'SESSION_CONNECT'
112  * should be answered with a 'SESSION_CONNECT_ACK' with the same body
113  * to confirm.  A 'SESSION_CONNECT_ACK' should then be followed with
114  * a 'SESSION_ACK'.  Once the 'SESSION_ACK' is received, both peers
115  * should be connected.
116  */
117 struct SessionConnectMessage
118 {
119   /**
120    * Header of type #GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT
121    * or #GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK
122    */
123   struct GNUNET_MessageHeader header;
124
125   /**
126    * Always zero.
127    */
128   uint32_t reserved GNUNET_PACKED;
129
130   /**
131    * Absolute time at the sender.  Only the most recent connect
132    * message implies which session is preferred by the sender.
133    */
134   struct GNUNET_TIME_AbsoluteNBO timestamp;
135
136 };
137
138
139 /**
140  * Message a peer sends to another when connected to indicate that a
141  * session is in use and the peer is still alive or to respond to a keep alive.
142  * A peer sends a message with type #GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE
143  * to request a message with #GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE.
144  * When the keep alive response with type is received, transport service
145  * will call the respective plugin to update the session timeout
146  */
147 struct SessionKeepAliveMessage
148 {
149   /**
150    * Header of type #GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE or
151    * #GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE.
152    */
153   struct GNUNET_MessageHeader header;
154
155   /**
156    * A nonce to identify the session the keep alive is used for
157    */
158   uint32_t nonce GNUNET_PACKED;
159 };
160
161 /**
162  * Message we send to the other peer to notify him that we intentionally
163  * are disconnecting (to reduce timeouts).  This is just a friendly
164  * notification, peers must not rely on always receiving disconnect
165  * messages.
166  */
167 struct SessionDisconnectMessage
168 {
169   /**
170    * Header of type #GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT
171    */
172   struct GNUNET_MessageHeader header;
173
174   /**
175    * Always zero.
176    */
177   uint32_t reserved GNUNET_PACKED;
178
179   /**
180    * Purpose of the signature.  Extends over the timestamp.
181    * Purpose should be #GNUNET_SIGNATURE_PURPOSE_TRANSPORT_DISCONNECT.
182    */
183   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
184
185   /**
186    * Absolute time at the sender.  Only the most recent connect
187    * message implies which session is preferred by the sender.
188    */
189   struct GNUNET_TIME_AbsoluteNBO timestamp;
190
191   /**
192    * Public key of the sender.
193    */
194   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
195
196   /**
197    * Signature of the peer that sends us the disconnect.  Only
198    * valid if the timestamp is AFTER the timestamp from the
199    * corresponding 'CONNECT' message.
200    */
201   struct GNUNET_CRYPTO_EddsaSignature signature;
202
203 };
204
205 GNUNET_NETWORK_STRUCT_END
206
207
208 /**
209  * For each neighbour we keep a list of messages
210  * that we still want to transmit to the neighbour.
211  */
212 struct MessageQueue
213 {
214
215   /**
216    * This is a doubly linked list.
217    */
218   struct MessageQueue *next;
219
220   /**
221    * This is a doubly linked list.
222    */
223   struct MessageQueue *prev;
224
225   /**
226    * Function to call once we're done.
227    */
228   GST_NeighbourSendContinuation cont;
229
230   /**
231    * Closure for @e cont
232    */
233   void *cont_cls;
234
235   /**
236    * The message(s) we want to transmit, GNUNET_MessageHeader(s)
237    * stuck together in memory.  Allocated at the end of this struct.
238    */
239   const char *message_buf;
240
241   /**
242    * Size of the message buf
243    */
244   size_t message_buf_size;
245
246   /**
247    * At what time should we fail?
248    */
249   struct GNUNET_TIME_Absolute timeout;
250
251 };
252
253
254
255
256 /**
257  * A possible address we could use to communicate with a neighbour.
258  */
259 struct NeighbourAddress
260 {
261
262   /**
263    * Active session for this address.
264    */
265   struct Session *session;
266
267   /**
268    * Network-level address information.
269    */
270   struct GNUNET_HELLO_Address *address;
271
272   /**
273    * Timestamp of the 'SESSION_CONNECT' message we sent to the other
274    * peer for this address.  Use to check that the ACK is in response
275    * to our most recent 'CONNECT'.
276    */
277   struct GNUNET_TIME_Absolute connect_timestamp;
278
279   /**
280    * Inbound bandwidth from ATS for this address.
281    */
282   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
283
284   /**
285    * Outbound bandwidth from ATS for this address.
286    */
287   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
288
289   /**
290    * Did we tell ATS that this is our 'active' address?
291    */
292   int ats_active;
293
294   /**
295    * The current nonce sent in the last keep alive messages
296    */
297   uint32_t keep_alive_nonce;
298 };
299
300 /**
301  * Entry in neighbours.
302  */
303 struct NeighbourMapEntry
304 {
305
306   /**
307    * Head of list of messages we would like to send to this peer;
308    * must contain at most one message per client.
309    */
310   struct MessageQueue *messages_head;
311
312   /**
313    * Tail of list of messages we would like to send to this peer; must
314    * contain at most one message per client.
315    */
316   struct MessageQueue *messages_tail;
317
318   /**
319    * Are we currently trying to send a message? If so, which one?
320    */
321   struct MessageQueue *is_active;
322
323   /**
324    * Primary address we currently use to communicate with the neighbour.
325    */
326   struct NeighbourAddress primary_address;
327
328   /**
329    * Alternative address currently under consideration for communicating
330    * with the neighbour.
331    */
332   struct NeighbourAddress alternative_address;
333
334   /**
335    * Identity of this neighbour.
336    */
337   struct GNUNET_PeerIdentity id;
338
339   /**
340    * Main task that drives this peer (timeouts, keepalives, etc.).
341    * Always runs the 'master_task'.
342    */
343   GNUNET_SCHEDULER_TaskIdentifier task;
344
345   /**
346    * At what time should we sent the next keep-alive message?
347    */
348   struct GNUNET_TIME_Absolute keep_alive_time;
349
350   /**
351    * At what time did we sent the last keep-alive message?  Used
352    * to calculate round-trip time ("latency").
353    */
354   struct GNUNET_TIME_Absolute last_keep_alive_time;
355
356   /**
357    * Timestamp we should include in our next CONNECT_ACK message.
358    * (only valid if 'send_connect_ack' is #GNUNET_YES).  Used to build
359    * our CONNECT_ACK message.
360    */
361   struct GNUNET_TIME_Absolute connect_ack_timestamp;
362
363   /**
364    * ATS address suggest handle
365    */
366   struct GNUNET_ATS_SuggestHandle *suggest_handle;
367
368   /**
369    * Time where we should cut the connection (timeout) if we don't
370    * make progress in the state machine (or get a KEEPALIVE_RESPONSE
371    * if we are in S_CONNECTED).
372    */
373   struct GNUNET_TIME_Absolute timeout;
374
375   /**
376    * Latest calculated latency value
377    */
378   struct GNUNET_TIME_Relative latency;
379
380   /**
381    * Tracker for inbound bandwidth.
382    */
383   struct GNUNET_BANDWIDTH_Tracker in_tracker;
384
385   /**
386    * How often has the other peer (recently) violated the inbound
387    * traffic limit?  Incremented by 10 per violation, decremented by 1
388    * per non-violation (for each time interval).
389    */
390   unsigned int quota_violation_count;
391
392   /**
393    * The current state of the peer.
394    */
395   enum GNUNET_TRANSPORT_PeerState state;
396
397   /**
398    * Did we sent an KEEP_ALIVE message and are we expecting a response?
399    */
400   int expect_latency_response;
401
402   /**
403    * Flag to set if we still need to send a CONNECT_ACK message to the other peer
404    * (once we have an address to use and the peer has been allowed by our
405    * blacklist).  Initially set to #ACK_UNDEFINED. Set to #ACK_SEND_CONNECT_ACK
406    * if we need to send a CONNECT_ACK.  Set to #ACK_SEND_CONNECT_ACK if we did
407    * send a CONNECT_ACK and should go to 'S_CONNECTED' upon receiving a
408    * 'SESSION_ACK' (regardless of what our own state machine might say).
409    */
410   enum GST_ACK_State ack_state;
411
412   /**
413    * Tracking utilization of outbound bandwidth
414    */
415   uint32_t util_payload_bytes_sent;
416
417   /**
418    * Tracking utilization of inbound bandwidth
419    */
420   uint32_t util_payload_bytes_recv;
421
422   /**
423    * Tracking utilization of outbound bandwidth
424    */
425   uint32_t util_total_bytes_sent;
426
427   /**
428    * Tracking utilization of inbound bandwidth
429    */
430   uint32_t util_total_bytes_recv;
431
432   /**
433    * Date of last utilization transmission
434    */
435   struct GNUNET_TIME_Absolute last_util_transmission;
436 };
437
438
439 /**
440  * Context for blacklist checks and the #handle_test_blacklist_cont()
441  * function.  Stores information about ongoing blacklist checks.
442  */
443 struct BlackListCheckContext
444 {
445
446   /**
447    * We keep blacklist checks in a DLL.
448    */
449   struct BlackListCheckContext *next;
450
451   /**
452    * We keep blacklist checks in a DLL.
453    */
454   struct BlackListCheckContext *prev;
455
456   /**
457    * Address that is being checked.
458    */
459   struct NeighbourAddress na;
460
461   /**
462    * Handle to the ongoing blacklist check.
463    */
464   struct GST_BlacklistCheck *bc;
465 };
466
467
468 /**
469  * Hash map from peer identities to the respective 'struct NeighbourMapEntry'.
470  */
471 static struct GNUNET_CONTAINER_MultiPeerMap *neighbours;
472
473 /**
474  * We keep blacklist checks in a DLL so that we can find
475  * the 'sessions' in their 'struct NeighbourAddress' if
476  * a session goes down.
477  */
478 static struct BlackListCheckContext *bc_head;
479
480 /**
481  * We keep blacklist checks in a DLL.
482  */
483 static struct BlackListCheckContext *bc_tail;
484
485 /**
486  * List of pending blacklist checks: head
487  */
488 static struct BlacklistCheckSwitchContext *pending_bc_head;
489
490 /**
491  * List of pending blacklist checks: tail
492  */
493 static struct BlacklistCheckSwitchContext *pending_bc_tail;
494
495 /**
496  * Closure for #connect_notify_cb, #disconnect_notify_cb and #neighbour_change_cb
497  */
498 static void *callback_cls;
499
500 /**
501  * Function to call when we connected to a neighbour.
502  */
503 static NotifyConnect connect_notify_cb;
504
505 /**
506  * Function to call when we disconnected from a neighbour.
507  */
508 static GNUNET_TRANSPORT_NotifyDisconnect disconnect_notify_cb;
509
510 /**
511  * Function to call when a neighbour changed address, state or bandwidth.
512  */
513 static GNUNET_TRANSPORT_NeighbourChangeCallback neighbour_change_cb;
514
515 /**
516  * counter for connected neighbours
517  */
518 static unsigned int neighbours_connected;
519
520 /**
521  * Number of bytes we have currently queued for transmission.
522  */
523 static unsigned long long bytes_in_send_queue;
524
525 /**
526  * Task transmitting utilization data
527  */
528 static GNUNET_SCHEDULER_TaskIdentifier util_transmission_tk;
529
530
531 static struct GNUNET_CONTAINER_MultiPeerMap *registered_quota_notifications;
532
533 static char *
534 print_ack_state (enum GST_ACK_State s)
535 {
536   switch (s) {
537     case ACK_UNDEFINED:
538       return "UNDEFINED";
539     case ACK_SEND_CONNECT_ACK:
540       return "SEND_CONNECT_ACK";
541     case ACK_SEND_SESSION_ACK:
542       return "SEND_SESSION_ACK";
543     default:
544       GNUNET_break (0);
545       return "N/A";
546   }
547 }
548
549 /**
550  * Lookup a neighbour entry in the neighbours hash map.
551  *
552  * @param pid identity of the peer to look up
553  * @return the entry, NULL if there is no existing record
554  */
555 static struct NeighbourMapEntry *
556 lookup_neighbour (const struct GNUNET_PeerIdentity *pid)
557 {
558   if (NULL == neighbours)
559     return NULL;
560   return GNUNET_CONTAINER_multipeermap_get (neighbours, pid);
561 }
562
563
564 /**
565  * Test if we're connected to the given peer.
566  *
567  * @param n neighbour entry of peer to test
568  * @return #GNUNET_YES if we are connected, #GNUNET_NO if not
569  */
570 static int
571 test_connected (struct NeighbourMapEntry *n)
572 {
573   if (NULL == n)
574     return GNUNET_NO;
575   return GNUNET_TRANSPORT_is_connected (n->state);
576 }
577
578 /**
579  * Send information about a new outbound quota to our clients.
580  *
581  * @param target affected peer
582  * @param quota new quota
583  */
584 static void
585 send_outbound_quota (const struct GNUNET_PeerIdentity *target,
586                      struct GNUNET_BANDWIDTH_Value32NBO quota)
587 {
588   struct QuotaSetMessage q_msg;
589
590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
591               "Sending outbound quota of %u Bps for peer `%s' to all clients\n",
592               ntohl (quota.value__), GNUNET_i2s (target));
593   q_msg.header.size = htons (sizeof (struct QuotaSetMessage));
594   q_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
595   q_msg.quota = quota;
596   q_msg.peer = (*target);
597   GST_clients_broadcast (&q_msg.header, GNUNET_NO);
598 }
599
600
601 /**
602  * We don't need a given neighbour address any more.
603  * Release its resources and give appropriate notifications
604  * to ATS and other subsystems.
605  *
606  * @param na address we are done with; @a na itself must NOT be 'free'd, only the contents!
607  */
608 static void
609 free_address (struct NeighbourAddress *na)
610 {
611   if (GNUNET_YES == na->ats_active)
612   {
613     GST_validation_set_address_use (na->address, na->session, GNUNET_NO);
614     GNUNET_ATS_address_in_use (GST_ats, na->address, na->session, GNUNET_NO);
615   }
616
617   na->bandwidth_in = GNUNET_BANDWIDTH_value_init (0);
618   na->bandwidth_out = GNUNET_BANDWIDTH_value_init (0);
619   na->ats_active = GNUNET_NO;
620   na->keep_alive_nonce = 0;
621   if (NULL != na->address)
622   {
623     GNUNET_HELLO_address_free (na->address);
624     na->address = NULL;
625   }
626   na->session = NULL;
627 }
628
629
630 /**
631  * Set net state for this neighbour and notify monitoring
632  *
633  * @param n the respective neighbour
634  * @param s the new state
635  */
636 static void
637 set_state (struct NeighbourMapEntry *n, enum GNUNET_TRANSPORT_PeerState s)
638 {
639   n->state = s;
640   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Neighbour `%s' changed state to %s\n",
641       GNUNET_i2s (&n->id),
642       GNUNET_TRANSPORT_ps2s(s));
643   neighbour_change_cb (callback_cls,
644       &n->id,
645       n->primary_address.address,
646       n->state, n->timeout,
647       n->primary_address.bandwidth_in,
648       n->primary_address.bandwidth_out);
649 }
650
651
652 /**
653  * Set net state and state timeout for this neighbour and notify monitoring
654  *
655  * @param n the respective neighbour
656  * @param s the new state
657  * @param timeout the new timeout
658  */
659 static void
660 set_state_and_timeout (struct NeighbourMapEntry *n,
661     enum GNUNET_TRANSPORT_PeerState s,
662     struct GNUNET_TIME_Absolute timeout)
663 {
664   n->state = s;
665   n->timeout = timeout;
666   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Neighbour `%s' changed state to %s with timeout %s\n",
667       GNUNET_i2s (&n->id),
668       GNUNET_TRANSPORT_ps2s(s),
669       GNUNET_STRINGS_absolute_time_to_string (timeout));
670   neighbour_change_cb (callback_cls,
671       &n->id,
672       n->primary_address.address,
673       n->state, n->timeout,
674       n->primary_address.bandwidth_in,
675       n->primary_address.bandwidth_out);
676 }
677
678
679 /**
680  * Set new state timeout for this neighbour and notify monitoring
681  *
682  * @param n the respective neighbour
683  * @param timeout the new timeout
684  */
685 static void
686 set_timeout (struct NeighbourMapEntry *n,
687     struct GNUNET_TIME_Absolute timeout)
688 {
689   n->timeout = timeout;
690   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Neighbour `%s' changed timeout %s\n",
691       GNUNET_i2s (&n->id),
692       GNUNET_STRINGS_absolute_time_to_string (timeout));
693   neighbour_change_cb (callback_cls,
694       &n->id,
695       n->primary_address.address,
696       n->state, n->timeout,
697       n->primary_address.bandwidth_in,
698       n->primary_address.bandwidth_out);
699 }
700
701
702 /**
703  * Initialize the alternative address of a neighbour
704  *
705  * @param n the neighbour
706  * @param address address of the other peer, NULL if other peer
707  *                       connected to us
708  * @param session session to use (or NULL, in which case an
709  *        address must be setup)
710  * @param bandwidth_in inbound quota to be used when connection is up
711  * @param bandwidth_out outbound quota to be used when connection is up
712  */
713 static void
714 set_alternative_address (struct NeighbourMapEntry *n,
715              const struct GNUNET_HELLO_Address *address,
716              struct Session *session,
717              struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
718              struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
719 {
720   struct GNUNET_TRANSPORT_PluginFunctions *papi;
721   if (NULL == (papi = GST_plugins_find (address->transport_name)))
722   {
723     GNUNET_break (0);
724     return;
725   }
726   if (session == n->alternative_address.session)
727   {
728     n->alternative_address.bandwidth_in = bandwidth_in;
729     n->alternative_address.bandwidth_out = bandwidth_out;
730     return;
731   }
732   free_address (&n->alternative_address);
733   if (NULL == session)
734     session = papi->get_session (papi->cls, address);
735   if (NULL == session)
736   {
737     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
738                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
739                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
740     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
741     return;
742   }
743
744   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Neighbour `%s' configured alternative address %s\n",
745       GNUNET_i2s (&n->id),
746       GST_plugins_a2s(address));
747
748   n->alternative_address.address = GNUNET_HELLO_address_copy (address);
749   n->alternative_address.bandwidth_in = bandwidth_in;
750   n->alternative_address.bandwidth_out = bandwidth_out;
751   n->alternative_address.session = session;
752   n->alternative_address.ats_active = GNUNET_NO;
753   n->alternative_address.keep_alive_nonce = 0;
754 }
755
756
757 /**
758  * Initialize the primary address of a neighbour
759  *
760  * @param n the neighbour
761  * @param address address of the other peer, NULL if other peer
762  *                       connected to us
763  * @param session session to use (or NULL, in which case an
764  *        address must be setup)
765  * @param bandwidth_in inbound quota to be used when connection is up
766  * @param bandwidth_out outbound quota to be used when connection is up
767  * @param is_active #GNUNET_YES to mark this as the active address with ATS
768  */
769 static void
770 set_primary_address (struct NeighbourMapEntry *n,
771              const struct GNUNET_HELLO_Address *address,
772              struct Session *session,
773              struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
774              struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
775              int is_active)
776 {
777   struct GNUNET_TRANSPORT_PluginFunctions *papi;
778
779   if (NULL == (papi = GST_plugins_find (address->transport_name)))
780   {
781     GNUNET_break (0);
782     return;
783   }
784   if (session == n->primary_address.session)
785   {
786     n->primary_address.bandwidth_in = bandwidth_in;
787     n->primary_address.bandwidth_out = bandwidth_out;
788     if (is_active != n->primary_address.ats_active)
789     {
790       n->primary_address.ats_active = is_active;
791       GNUNET_ATS_address_in_use (GST_ats, n->primary_address.address, n->primary_address.session, is_active);
792       GST_validation_set_address_use (n->primary_address.address, n->primary_address.session, is_active);
793     }
794     if (GNUNET_YES == is_active)
795     {
796       GST_neighbours_set_incoming_quota (&address->peer, bandwidth_in);
797       send_outbound_quota (&address->peer, bandwidth_out);
798     }
799     return;
800   }
801   free_address (&n->primary_address);
802   if (NULL == session)
803     session = papi->get_session (papi->cls, address);
804   if (NULL == session)
805   {
806     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
807                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
808                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
809     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
810     return;
811   }
812
813   n->primary_address.address = GNUNET_HELLO_address_copy (address);
814   n->primary_address.bandwidth_in = bandwidth_in;
815   n->primary_address.bandwidth_out = bandwidth_out;
816   n->primary_address.session = session;
817   n->primary_address.ats_active = is_active;
818   n->primary_address.keep_alive_nonce = 0;
819   if (GNUNET_YES == is_active)
820   {
821     /* Telling ATS about new session */
822     GNUNET_ATS_address_in_use (GST_ats, n->primary_address.address, n->primary_address.session, GNUNET_YES);
823     GST_validation_set_address_use (n->primary_address.address, n->primary_address.session, GNUNET_YES);
824     GST_neighbours_set_incoming_quota (&address->peer, bandwidth_in);
825     send_outbound_quota (&address->peer, bandwidth_out);
826   }
827
828   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Neighbour `%s' switched to address `%s'\n",
829       GNUNET_i2s (&n->id),
830       GST_plugins_a2s(address));
831
832   neighbour_change_cb (callback_cls,
833       &n->id,
834       n->primary_address.address,
835       n->state, n->timeout,
836       n->primary_address.bandwidth_in,
837       n->primary_address.bandwidth_out);
838 }
839
840 /**
841  * Clear the primary address of a neighbour since this primary address is not
842  * valid anymore and notify monitoring about it
843  *
844  * @param n the neighbour
845  */
846 static void
847 unset_primary_address (struct NeighbourMapEntry *n)
848 {
849   /* Unset primary address */
850   free_address (&n->primary_address);
851
852   /* Notify monitoring about it */
853   neighbour_change_cb (callback_cls,
854       &n->id,
855       NULL,
856       n->state, n->timeout,
857       n->primary_address.bandwidth_in,
858       n->primary_address.bandwidth_out);
859 }
860
861
862
863 /**
864  * Free a neighbour map entry.
865  *
866  * @param n entry to free
867  * @param keep_sessions #GNUNET_NO to tell plugin to terminate sessions,
868  *                      #GNUNET_YES to keep all sessions
869  */
870 static void
871 free_neighbour (struct NeighbourMapEntry *n,
872                 int keep_sessions)
873 {
874   struct MessageQueue *mq;
875   struct GNUNET_TRANSPORT_PluginFunctions *papi;
876   struct GNUNET_HELLO_Address *backup_primary;
877
878   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
879               "Freeing neighbour state of peer `%s'\n",
880               GNUNET_i2s (&n->id));
881   n->is_active = NULL; /* always free'd by its own continuation! */
882
883   /* fail messages currently in the queue */
884   while (NULL != (mq = n->messages_head))
885   {
886     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
887     if (NULL != mq->cont)
888       mq->cont (mq->cont_cls, GNUNET_SYSERR, mq->message_buf_size, 0);
889     GNUNET_free (mq);
890   }
891   /* It is too late to send other peer disconnect notifications, but at
892      least internally we need to get clean... */
893   if (GNUNET_YES == test_connected (n))
894   {
895     GNUNET_STATISTICS_set (GST_stats,
896                            gettext_noop ("# peers connected"),
897                            --neighbours_connected,
898                            GNUNET_NO);
899     disconnect_notify_cb (callback_cls, &n->id);
900   }
901
902   /* Mark peer as disconnected */
903   set_state (n, GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED);
904
905   if (NULL != n->primary_address.address)
906     backup_primary = GNUNET_HELLO_address_copy (n->primary_address.address);
907   else
908     backup_primary = NULL;
909
910   /* free addresses and mark as unused */
911   unset_primary_address (n);
912   free_address (&n->alternative_address);
913
914   /* cut all transport-level connection for this peer */
915   if ((GNUNET_NO == keep_sessions) &&
916       (NULL != backup_primary) &&
917       (NULL != (papi = GST_plugins_find (backup_primary->transport_name))))
918     papi->disconnect_peer (papi->cls, &n->id);
919
920   if (NULL != backup_primary)
921     GNUNET_HELLO_address_free (backup_primary);
922   GNUNET_assert (GNUNET_YES ==
923                  GNUNET_CONTAINER_multipeermap_remove (neighbours,
924                                                        &n->id, n));
925
926   /* Cancel address requests for this peer */
927   if (NULL != n->suggest_handle)
928   {
929     GNUNET_ATS_suggest_address_cancel (GST_ats, &n->id);
930     n->suggest_handle = NULL;
931   }
932
933   /* Cancel the master task */
934   if (GNUNET_SCHEDULER_NO_TASK != n->task)
935   {
936     GNUNET_SCHEDULER_cancel (n->task);
937     n->task = GNUNET_SCHEDULER_NO_TASK;
938   }
939   /* free rest of memory */
940   GNUNET_free (n);
941 }
942
943
944 /**
945  * Transmit a message using the current session of the given
946  * neighbour.
947  *
948  * @param n entry for the recipient
949  * @param msgbuf buffer to transmit
950  * @param msgbuf_size number of bytes in @a msgbuf buffer
951  * @param priority transmission priority
952  * @param timeout transmission timeout
953  * @param use_keepalive_timeout #GNUNET_YES to use plugin-specific keep-alive
954  *        timeout (@a timeout is ignored in that case), #GNUNET_NO otherwise
955  * @param cont continuation to call when finished (can be NULL)
956  * @param cont_cls closure for @a cont
957  * @return timeout (copy of @a timeout or a calculated one if
958  *         @a use_keepalive_timeout is #GNUNET_YES.
959  */
960 static struct GNUNET_TIME_Relative
961 send_with_session (struct NeighbourMapEntry *n,
962                    const char *msgbuf, size_t msgbuf_size,
963                    uint32_t priority,
964                    struct GNUNET_TIME_Relative timeout,
965                    unsigned int use_keepalive_timeout,
966                    GNUNET_TRANSPORT_TransmitContinuation cont,
967                    void *cont_cls)
968 {
969   struct GNUNET_TRANSPORT_PluginFunctions *papi;
970   struct GNUNET_TIME_Relative result = GNUNET_TIME_UNIT_FOREVER_REL;
971
972   GNUNET_assert (n->primary_address.session != NULL);
973   if ( ((NULL == (papi = GST_plugins_find (n->primary_address.address->transport_name)) ||
974          (-1 == papi->send (papi->cls,
975                             n->primary_address.session,
976                             msgbuf, msgbuf_size,
977                             priority,
978                             (result = (GNUNET_NO == use_keepalive_timeout) ? timeout :
979                                 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
980                                                              papi->query_keepalive_factor (papi->cls))),
981                             cont, cont_cls)))) &&
982        (NULL != cont))
983     cont (cont_cls, &n->id, GNUNET_SYSERR, msgbuf_size, 0);
984   GST_neighbours_notify_data_sent (&n->id,
985       n->primary_address.address, n->primary_address.session, msgbuf_size);
986   GNUNET_break (NULL != papi);
987   return result;
988 }
989
990
991 /**
992  * Master task run for every neighbour.  Performs all of the time-related
993  * activities (keep alive, send next message, disconnect if idle, finish
994  * clean up after disconnect).
995  *
996  * @param cls the `struct NeighbourMapEntry` for which we are running
997  * @param tc scheduler context (unused)
998  */
999 static void
1000 master_task (void *cls,
1001              const struct GNUNET_SCHEDULER_TaskContext *tc);
1002
1003
1004 /**
1005  * Function called when the 'DISCONNECT' message has been sent by the
1006  * plugin.  Frees the neighbour --- if the entry still exists.
1007  *
1008  * @param cls NULL
1009  * @param target identity of the neighbour that was disconnected
1010  * @param result #GNUNET_OK if the disconnect got out successfully
1011  * @param payload bytes payload
1012  * @param physical bytes physical
1013  */
1014 static void
1015 send_disconnect_cont (void *cls, const struct GNUNET_PeerIdentity *target,
1016                       int result, size_t payload, size_t physical)
1017 {
1018   struct NeighbourMapEntry *n;
1019
1020   n = lookup_neighbour (target);
1021   if (NULL == n)
1022     return; /* already gone */
1023   if (GNUNET_TRANSPORT_PS_DISCONNECT != n->state)
1024     return; /* have created a fresh entry since */
1025   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1026     GNUNET_SCHEDULER_cancel (n->task);
1027   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1028 }
1029
1030
1031 /**
1032  * Transmit a DISCONNECT message to the other peer.
1033  *
1034  * @param n neighbour to send DISCONNECT message.
1035  */
1036 static void
1037 send_disconnect (struct NeighbourMapEntry *n)
1038 {
1039   struct SessionDisconnectMessage disconnect_msg;
1040
1041   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1042               "Sending DISCONNECT message to peer `%4s'\n",
1043               GNUNET_i2s (&n->id));
1044   disconnect_msg.header.size = htons (sizeof (struct SessionDisconnectMessage));
1045   disconnect_msg.header.type =
1046       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1047   disconnect_msg.reserved = htonl (0);
1048   disconnect_msg.purpose.size =
1049       htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1050              sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
1051              sizeof (struct GNUNET_TIME_AbsoluteNBO));
1052   disconnect_msg.purpose.purpose =
1053       htonl (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1054   disconnect_msg.timestamp =
1055       GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1056   disconnect_msg.public_key = GST_my_identity.public_key;
1057   GNUNET_assert (GNUNET_OK ==
1058                  GNUNET_CRYPTO_eddsa_sign (GST_my_private_key,
1059                                          &disconnect_msg.purpose,
1060                                          &disconnect_msg.signature));
1061
1062   (void) send_with_session (n,
1063                             (const char *) &disconnect_msg, sizeof (disconnect_msg),
1064                             UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
1065                             GNUNET_NO, &send_disconnect_cont, NULL);
1066   GNUNET_STATISTICS_update (GST_stats,
1067                             gettext_noop
1068                             ("# DISCONNECT messages sent"), 1,
1069                             GNUNET_NO);
1070 }
1071
1072
1073 /**
1074  * Disconnect from the given neighbour, clean up the record.
1075  *
1076  * @param n neighbour to disconnect from
1077  */
1078 static void
1079 disconnect_neighbour (struct NeighbourMapEntry *n)
1080 {
1081   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1082               "Disconnecting from peer %s in state %s\n",
1083               GNUNET_i2s (&n->id),
1084               GNUNET_TRANSPORT_ps2s (n->state));
1085   /* depending on state, notify neighbour and/or upper layers of this peer
1086      about disconnect */
1087   switch (n->state)
1088   {
1089   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
1090   case GNUNET_TRANSPORT_PS_INIT_ATS:
1091     /* other peer is completely unaware of us, no need to send DISCONNECT */
1092     free_neighbour (n, GNUNET_NO);
1093     return;
1094   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
1095     send_disconnect (n);
1096     set_state (n, GNUNET_TRANSPORT_PS_DISCONNECT);
1097     break;
1098   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
1099   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
1100   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
1101     /* we never ACK'ed the other peer's request, no need to send DISCONNECT */
1102     set_state (n, GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED);
1103     free_neighbour (n, GNUNET_NO);
1104     return;
1105   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
1106     /* we DID ACK the other peer's request, must send DISCONNECT */
1107     send_disconnect (n);
1108     set_state (n, GNUNET_TRANSPORT_PS_DISCONNECT);
1109     break;
1110   case GNUNET_TRANSPORT_PS_CONNECTED:
1111   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
1112   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
1113   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
1114   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
1115     /* we are currently connected, need to send disconnect and do
1116        internal notifications and update statistics */
1117     send_disconnect (n);
1118     GNUNET_STATISTICS_set (GST_stats,
1119                            gettext_noop ("# peers connected"),
1120                            --neighbours_connected,
1121                            GNUNET_NO);
1122     disconnect_notify_cb (callback_cls, &n->id);
1123     set_state (n, GNUNET_TRANSPORT_PS_DISCONNECT);
1124     break;
1125   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
1126     /* ATS address request timeout, disconnect without sending disconnect message */
1127     GNUNET_STATISTICS_set (GST_stats,
1128                            gettext_noop ("# peers connected"),
1129                            --neighbours_connected,
1130                            GNUNET_NO);
1131     disconnect_notify_cb (callback_cls, &n->id);
1132     set_state (n, GNUNET_TRANSPORT_PS_DISCONNECT);
1133     break;
1134   case GNUNET_TRANSPORT_PS_DISCONNECT:
1135     /* already disconnected, ignore */
1136     break;
1137   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
1138     /* already cleaned up, how did we get here!? */
1139     GNUNET_assert (0);
1140     break;
1141   default:
1142     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1143                 "Unhandled state `%s'\n",
1144                 GNUNET_TRANSPORT_ps2s (n->state));
1145     GNUNET_break (0);
1146     break;
1147   }
1148   /* schedule timeout to clean up */
1149   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1150     GNUNET_SCHEDULER_cancel (n->task);
1151   n->task = GNUNET_SCHEDULER_add_delayed (DISCONNECT_SENT_TIMEOUT,
1152                                           &master_task, n);
1153 }
1154
1155
1156 /**
1157  * We're done with our transmission attempt, continue processing.
1158  *
1159  * @param cls the `struct MessageQueue` of the message
1160  * @param receiver intended receiver
1161  * @param success whether it worked or not
1162  * @param size_payload bytes payload sent
1163  * @param physical bytes sent on wire
1164  */
1165 static void
1166 transmit_send_continuation (void *cls,
1167                             const struct GNUNET_PeerIdentity *receiver,
1168                             int success, size_t size_payload, size_t physical)
1169 {
1170   struct MessageQueue *mq = cls;
1171   struct NeighbourMapEntry *n;
1172
1173   if (NULL == (n = lookup_neighbour (receiver)))
1174   {
1175     GNUNET_free (mq);
1176     return; /* disconnect or other error while transmitting, can happen */
1177   }
1178   if (n->is_active == mq)
1179   {
1180     /* this is still "our" neighbour, remove us from its queue
1181        and allow it to send the next message now */
1182     n->is_active = NULL;
1183     if (GNUNET_SCHEDULER_NO_TASK != n->task)
1184       GNUNET_SCHEDULER_cancel (n->task);
1185     n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1186   }
1187   if (bytes_in_send_queue < mq->message_buf_size)
1188   {
1189     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1190                 "Bytes_in_send_queue `%u', Message_size %u, result: %s, payload %u, on wire %u\n",
1191                 bytes_in_send_queue, mq->message_buf_size,
1192                 (GNUNET_OK == success) ? "OK" : "FAIL",
1193                 size_payload, physical);
1194     GNUNET_break (0);
1195   }
1196
1197
1198   GNUNET_break (size_payload == mq->message_buf_size);
1199   bytes_in_send_queue -= mq->message_buf_size;
1200   GNUNET_STATISTICS_set (GST_stats,
1201                         gettext_noop
1202                          ("# bytes in message queue for other peers"),
1203                          bytes_in_send_queue, GNUNET_NO);
1204   if (GNUNET_OK == success)
1205     GNUNET_STATISTICS_update (GST_stats,
1206                               gettext_noop
1207                               ("# messages transmitted to other peers"),
1208                               1, GNUNET_NO);
1209   else
1210     GNUNET_STATISTICS_update (GST_stats,
1211                               gettext_noop
1212                               ("# transmission failures for messages to other peers"),
1213                               1, GNUNET_NO);
1214   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1215               "Sending message to `%s' of type %u was a %s\n",
1216               GNUNET_i2s (receiver),
1217               ntohs (((struct GNUNET_MessageHeader *) mq->message_buf)->type),
1218               (success == GNUNET_OK) ? "success" : "FAILURE");
1219   if (NULL != mq->cont)
1220     mq->cont (mq->cont_cls, success, size_payload, physical);
1221   GNUNET_free (mq);
1222 }
1223
1224
1225 /**
1226  * Check the message list for the given neighbour and if we can
1227  * send a message, do so.  This function should only be called
1228  * if the connection is at least generally ready for transmission.
1229  * While we will only send one message at a time, no bandwidth
1230  * quota management is performed here.  If a message was given to
1231  * the plugin, the continuation will automatically re-schedule
1232  * the 'master' task once the next message might be transmitted.
1233  *
1234  * @param n target peer for which to transmit
1235  */
1236 static void
1237 try_transmission_to_peer (struct NeighbourMapEntry *n)
1238 {
1239   struct MessageQueue *mq;
1240   struct GNUNET_TIME_Relative timeout;
1241
1242   if (NULL == n->primary_address.address)
1243   {
1244     /* no address, why are we here? */
1245     GNUNET_break (0);
1246     return;
1247   }
1248   if ((0 == n->primary_address.address->address_length) &&
1249       (NULL == n->primary_address.session))
1250   {
1251     /* no address, why are we here? */
1252     GNUNET_break (0);
1253     return;
1254   }
1255   if (NULL != n->is_active)
1256   {
1257     /* transmission already pending */
1258     return;
1259   }
1260
1261   /* timeout messages from the queue that are past their due date */
1262   while (NULL != (mq = n->messages_head))
1263   {
1264     timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1265     if (timeout.rel_value_us > 0)
1266       break;
1267     GNUNET_STATISTICS_update (GST_stats,
1268                               gettext_noop
1269                               ("# messages timed out while in transport queue"),
1270                               1, GNUNET_NO);
1271     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1272     n->is_active = mq;
1273     transmit_send_continuation (mq, &n->id,
1274                                 GNUNET_SYSERR,
1275                                 mq->message_buf_size, 0);     /* timeout */
1276   }
1277   if (NULL == mq)
1278     return;                     /* no more messages */
1279   GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1280   n->is_active = mq;
1281   (void) send_with_session (n,
1282                             mq->message_buf, mq->message_buf_size,
1283                             0 /* priority */, timeout, GNUNET_NO,
1284                             &transmit_send_continuation, mq);
1285 }
1286
1287
1288 /**
1289  * Send keepalive message to the neighbour.  Must only be called
1290  * if we are on 'connected' state or while trying to switch addresses.
1291  * Will internally determine if a keepalive is truly needed (so can
1292  * always be called).
1293  *
1294  * @param n neighbour that went idle and needs a keepalive
1295  */
1296 static void
1297 send_keepalive (struct NeighbourMapEntry *n)
1298 {
1299   struct SessionKeepAliveMessage m;
1300   struct GNUNET_TIME_Relative timeout;
1301   uint32_t nonce;
1302
1303   GNUNET_assert ((GNUNET_TRANSPORT_PS_CONNECTED == n->state) ||
1304                  (GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
1305                  (GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT));
1306   if (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time).rel_value_us > 0)
1307     return; /* no keepalive needed at this time */
1308
1309   nonce = 0; /* 0 indicates 'not set' */
1310   while (0 == nonce)
1311     nonce = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1312
1313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1314       "Sending keep alive to peer `%s' with nonce %u\n",
1315       GNUNET_i2s (&n->id), nonce);
1316
1317   m.header.size = htons (sizeof (struct SessionKeepAliveMessage));
1318   m.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE);
1319   m.nonce = htonl (nonce);
1320
1321   timeout = send_with_session (n,
1322                                (const void *) &m, sizeof (m),
1323                                UINT32_MAX /* priority */,
1324                                GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES,
1325                                NULL, NULL);
1326   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# keepalives sent"), 1,
1327                             GNUNET_NO);
1328   n->primary_address.keep_alive_nonce = nonce;
1329   n->expect_latency_response = GNUNET_YES;
1330   n->last_keep_alive_time = GNUNET_TIME_absolute_get ();
1331   n->keep_alive_time = GNUNET_TIME_relative_to_absolute (timeout);
1332
1333 }
1334
1335
1336 /**
1337  * Keep the connection to the given neighbour alive longer,
1338  * we received a KEEPALIVE (or equivalent); send a response.
1339  *
1340  * @param neighbour neighbour to keep alive (by sending keep alive response)
1341  * @param m the keep alive message containing the nonce to respond to
1342  */
1343 void
1344 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour,
1345     const struct GNUNET_MessageHeader *m)
1346 {
1347   struct NeighbourMapEntry *n;
1348   const struct SessionKeepAliveMessage *msg_in;
1349   struct SessionKeepAliveMessage msg;
1350
1351   if (sizeof (struct SessionKeepAliveMessage) != ntohs (m->size))
1352     return;
1353
1354   msg_in = (struct SessionKeepAliveMessage *) m;
1355   if (NULL == (n = lookup_neighbour (neighbour)))
1356   {
1357     GNUNET_STATISTICS_update (GST_stats,
1358                               gettext_noop
1359                               ("# KEEPALIVE messages discarded (peer unknown)"),
1360                               1, GNUNET_NO);
1361     return;
1362   }
1363   if (NULL == n->primary_address.session)
1364   {
1365     GNUNET_STATISTICS_update (GST_stats,
1366                               gettext_noop
1367                               ("# KEEPALIVE messages discarded (no session)"),
1368                               1, GNUNET_NO);
1369     return;
1370   }
1371
1372   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1373       "Received keep alive request from peer `%s' with nonce %u\n",
1374       GNUNET_i2s (&n->id), ntohl (msg_in->nonce));
1375
1376   /* send reply to allow neighbour to measure latency */
1377   msg.header.size = htons (sizeof (struct SessionKeepAliveMessage));
1378   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE);
1379   msg.nonce = msg_in->nonce;
1380   (void) send_with_session(n,
1381                            (const void *) &msg, sizeof (struct SessionKeepAliveMessage),
1382                            UINT32_MAX /* priority */,
1383                            GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES,
1384                            NULL, NULL);
1385 }
1386
1387
1388 /**
1389  * We received a KEEP_ALIVE_RESPONSE message and use this to calculate
1390  * latency to this peer.  Pass the updated information (existing ats
1391  * plus calculated latency) to ATS.
1392  *
1393  * @param neighbour neighbour to keep alive
1394  * @param m the message containing the keep alive response
1395  */
1396 void
1397 GST_neighbours_keepalive_response (const struct GNUNET_PeerIdentity *neighbour,
1398     const struct GNUNET_MessageHeader *m)
1399 {
1400   struct NeighbourMapEntry *n;
1401   const struct SessionKeepAliveMessage *msg;
1402   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1403   uint32_t latency;
1404   struct GNUNET_ATS_Information ats;
1405
1406   if (sizeof (struct SessionKeepAliveMessage) != ntohs (m->size))
1407     return;
1408
1409   msg = (const struct SessionKeepAliveMessage *) m;
1410   if (NULL == (n = lookup_neighbour (neighbour)))
1411   {
1412     GNUNET_STATISTICS_update (GST_stats,
1413                               gettext_noop
1414                               ("# KEEPALIVE_RESPONSE messages discarded (not connected)"),
1415                               1, GNUNET_NO);
1416     return;
1417   }
1418   if ( (GNUNET_TRANSPORT_PS_CONNECTED != n->state) ||
1419        (GNUNET_YES != n->expect_latency_response) )
1420   {
1421     GNUNET_STATISTICS_update (GST_stats,
1422                               gettext_noop
1423                               ("# KEEPALIVE_RESPONSE messages discarded (not expected)"),
1424                               1, GNUNET_NO);
1425     return;
1426   }
1427   if (NULL == n->primary_address.address)
1428   {
1429     GNUNET_STATISTICS_update (GST_stats,
1430                               gettext_noop
1431                               ("# KEEPALIVE_RESPONSE messages discarded (address changed)"),
1432                               1, GNUNET_NO);
1433     return;
1434   }
1435   if (n->primary_address.keep_alive_nonce != ntohl (msg->nonce))
1436   {
1437     GNUNET_STATISTICS_update (GST_stats,
1438                               gettext_noop
1439                               ("# KEEPALIVE_RESPONSE messages discarded (wrong nonce)"),
1440                               1, GNUNET_NO);
1441     return;
1442   }
1443   else
1444   {
1445     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1446         "Received keep alive response from peer `%s' for session %p\n",
1447         GNUNET_i2s (&n->id), n->primary_address.session);
1448
1449   }
1450
1451   /* Update session timeout here */
1452   if (NULL != (papi = GST_plugins_find (n->primary_address.address->transport_name)))
1453   {
1454     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1455         "Updating session for peer `%s' for session %p\n",
1456         GNUNET_i2s (&n->id), n->primary_address.session);
1457     papi->update_session_timeout (papi->cls, &n->id, n->primary_address.session);
1458   }
1459   else
1460   {
1461     GNUNET_break (0);
1462   }
1463
1464   n->primary_address.keep_alive_nonce = 0;
1465   n->expect_latency_response = GNUNET_NO;
1466   n->latency = GNUNET_TIME_absolute_get_duration (n->last_keep_alive_time);
1467   set_timeout (n, GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1468
1469   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1470               "Latency for peer `%s' is %s\n",
1471               GNUNET_i2s (&n->id),
1472               GNUNET_STRINGS_relative_time_to_string (n->latency,
1473                                                       GNUNET_YES));
1474   /* append latency */
1475   ats.type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1476   if (n->latency.rel_value_us > UINT32_MAX)
1477     latency = UINT32_MAX;
1478   else
1479     latency = n->latency.rel_value_us;
1480   ats.value = htonl (latency);
1481   GST_ats_update_metrics (&n->id, n->primary_address.address,
1482       n->primary_address.session, &ats, 1);
1483 }
1484
1485
1486 /**
1487  * We have received a message from the given sender.  How long should
1488  * we delay before receiving more?  (Also used to keep the peer marked
1489  * as live).
1490  *
1491  * @param sender sender of the message
1492  * @param size size of the message
1493  * @param do_forward set to #GNUNET_YES if the message should be forwarded to clients
1494  *                   #GNUNET_NO if the neighbour is not connected or violates the quota,
1495  *                   #GNUNET_SYSERR if the connection is not fully up yet
1496  * @return how long to wait before reading more from this sender
1497  */
1498 struct GNUNET_TIME_Relative
1499 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
1500                                         *sender, ssize_t size, int *do_forward)
1501 {
1502   struct NeighbourMapEntry *n;
1503   struct GNUNET_TIME_Relative ret;
1504
1505   if (NULL == neighbours)
1506   {
1507     *do_forward = GNUNET_NO;
1508     return GNUNET_TIME_UNIT_FOREVER_REL; /* This can happen during shutdown */
1509   }
1510   if (NULL == (n = lookup_neighbour (sender)))
1511   {
1512     GST_neighbours_try_connect (sender);
1513     if (NULL == (n = lookup_neighbour (sender)))
1514     {
1515       GNUNET_STATISTICS_update (GST_stats,
1516                                 gettext_noop
1517                                 ("# messages discarded due to lack of neighbour record"),
1518                                 1, GNUNET_NO);
1519       *do_forward = GNUNET_NO;
1520       return GNUNET_TIME_UNIT_ZERO;
1521     }
1522   }
1523   if (! test_connected (n))
1524   {
1525     *do_forward = GNUNET_SYSERR;
1526     return GNUNET_TIME_UNIT_ZERO;
1527   }
1528   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
1529   {
1530     n->quota_violation_count++;
1531     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1532                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
1533                 n->in_tracker.available_bytes_per_s__,
1534                 n->quota_violation_count);
1535     /* Discount 32k per violation */
1536     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1537   }
1538   else
1539   {
1540     if (n->quota_violation_count > 0)
1541     {
1542       /* try to add 32k back */
1543       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1544       n->quota_violation_count--;
1545     }
1546   }
1547   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1548   {
1549     GNUNET_STATISTICS_update (GST_stats,
1550                               gettext_noop
1551                               ("# bandwidth quota violations by other peers"),
1552                               1, GNUNET_NO);
1553     *do_forward = GNUNET_NO;
1554     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1555   }
1556   *do_forward = GNUNET_YES;
1557   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 32 * 1024);
1558   if (ret.rel_value_us > 0)
1559   {
1560     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1561                 "Throttling read (%llu bytes excess at %u b/s), waiting %s before reading more.\n",
1562                 (unsigned long long) n->in_tracker.
1563                 consumption_since_last_update__,
1564                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1565                 GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
1566     GNUNET_STATISTICS_update (GST_stats,
1567                               gettext_noop ("# ms throttling suggested"),
1568                               (int64_t) ret.rel_value_us / 1000LL,
1569                               GNUNET_NO);
1570   }
1571   return ret;
1572 }
1573
1574
1575 /**
1576  * Transmit a message to the given target using the active connection.
1577  *
1578  * @param target destination
1579  * @param msg message to send
1580  * @param msg_size number of bytes in msg
1581  * @param timeout when to fail with timeout
1582  * @param cont function to call when done
1583  * @param cont_cls closure for 'cont'
1584  */
1585 void
1586 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
1587                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
1588                      GST_NeighbourSendContinuation cont, void *cont_cls)
1589 {
1590   struct NeighbourMapEntry *n;
1591   struct MessageQueue *mq;
1592
1593   /* All ove these cases should never happen; they are all API violations.
1594      But we check anyway, just to be sure. */
1595   if (NULL == (n = lookup_neighbour (target)))
1596   {
1597     GNUNET_break (0);
1598     if (NULL != cont)
1599       cont (cont_cls, GNUNET_SYSERR, msg_size, 0);
1600     return;
1601   }
1602   if (GNUNET_YES != test_connected (n))
1603   {
1604     GNUNET_break (0);
1605     if (NULL != cont)
1606       cont (cont_cls, GNUNET_SYSERR, msg_size, 0);
1607     return;
1608   }
1609   bytes_in_send_queue += msg_size;
1610   GNUNET_STATISTICS_set (GST_stats,
1611                          gettext_noop
1612                          ("# bytes in message queue for other peers"),
1613                          bytes_in_send_queue, GNUNET_NO);
1614   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
1615   mq->cont = cont;
1616   mq->cont_cls = cont_cls;
1617   memcpy (&mq[1], msg, msg_size);
1618   mq->message_buf = (const char *) &mq[1];
1619   mq->message_buf_size = msg_size;
1620   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1621   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
1622   if ( (NULL != n->is_active) ||
1623        ( (NULL == n->primary_address.session) && (NULL == n->primary_address.address)) )
1624     return;
1625   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1626     GNUNET_SCHEDULER_cancel (n->task);
1627   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1628 }
1629
1630 static void
1631 send_session_connect_cont (void *cls,
1632                       const struct GNUNET_PeerIdentity *target,
1633                       int result,
1634                       size_t size_payload,
1635                       size_t size_on_wire)
1636 {
1637   struct NeighbourMapEntry *n;
1638
1639   n = lookup_neighbour (target);
1640   if (NULL == n)
1641   {
1642     /* CONNECT continuation was called after neighbor was freed,
1643      * for example due to a time out for the state or the session
1644      * used was already terminated: nothing to do here... */
1645     return;
1646   }
1647
1648   if (GNUNET_TRANSPORT_PS_CONNECT_SENT != n->state)
1649   {
1650     /* CONNECT continuation was called after neighbor changed state,
1651      * for example due to a time out for the state or the session
1652      * used was already terminated: nothing to do here... */
1653     return;
1654   }
1655   if (GNUNET_OK == result)
1656     return;
1657
1658   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1659             _("Failed to send CONNECT message to peer `%s' using address `%s' session %p\n"),
1660             GNUNET_i2s (target),
1661             GST_plugins_a2s (n->primary_address.address),
1662             n->primary_address.session);
1663
1664   /* Failed to send CONNECT message with this address */
1665   GNUNET_ATS_address_destroyed (GST_ats, n->primary_address.address,
1666       n->primary_address.session);
1667   GNUNET_ATS_address_destroyed (GST_ats, n->primary_address.address,
1668       NULL);
1669
1670   /* Remove address and request and additional one */
1671   unset_primary_address (n);
1672
1673   set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
1674       GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
1675   return;
1676 }
1677
1678 /**
1679  * Send a SESSION_CONNECT message via the given address.
1680  *
1681  * @param na address to use
1682  */
1683 static void
1684 send_session_connect (struct NeighbourAddress *na)
1685 {
1686   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1687   struct SessionConnectMessage connect_msg;
1688   struct NeighbourMapEntry *n;
1689
1690   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1691               "Sending SESSION_CONNECT message to peer %s\n",
1692               GNUNET_i2s (&na->address->peer));
1693   if (NULL == (papi = GST_plugins_find (na->address->transport_name)))
1694   {
1695     GNUNET_break (0);
1696     return;
1697   }
1698   if (NULL == na->session)
1699     na->session = papi->get_session (papi->cls, na->address);
1700   if (NULL == na->session)
1701   {
1702     GNUNET_break (0);
1703     return;
1704   }
1705   GNUNET_STATISTICS_update (GST_stats,
1706                             gettext_noop
1707                             ("# SESSION_CONNECT messages sent"),
1708                             1, GNUNET_NO);
1709   na->connect_timestamp = GNUNET_TIME_absolute_get ();
1710   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1711   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1712   connect_msg.reserved = htonl (0);
1713   connect_msg.timestamp = GNUNET_TIME_absolute_hton (na->connect_timestamp);
1714   if (-1 ==
1715       papi->send (papi->cls,
1716                   na->session,
1717                   (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1718                   UINT_MAX,
1719                   SETUP_CONNECTION_TIMEOUT,
1720                   send_session_connect_cont, NULL))
1721   {
1722     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1723                 _("Failed to transmit CONNECT message via plugin to %s\n"),
1724                 GST_plugins_a2s (na->address));
1725
1726     n = lookup_neighbour (&na->address->peer);
1727     if (NULL == n)
1728     {
1729       GNUNET_break (0);
1730       return;
1731     }
1732     /* Hard failure to send the CONNECT message with this address:
1733        Destroy address and session */
1734     GNUNET_ATS_address_destroyed (GST_ats, na->address, na->session);
1735     GNUNET_ATS_address_destroyed (GST_ats, na->address, NULL);
1736
1737     /* Remove address and request and additional one */
1738     unset_primary_address (n);
1739     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
1740         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
1741     return;
1742   }
1743
1744   GST_neighbours_notify_data_sent (&na->address->peer,
1745                                    na->address,
1746                                    na->session,
1747                                    sizeof (struct SessionConnectMessage));
1748
1749 }
1750
1751
1752 static void
1753 send_session_connect_ack_cont (void *cls,
1754                       const struct GNUNET_PeerIdentity *target,
1755                       int result,
1756                       size_t size_payload,
1757                       size_t size_on_wire)
1758 {
1759   struct NeighbourMapEntry *n;
1760
1761   n = lookup_neighbour (target);
1762   if (NULL == n)
1763   {
1764     /* CONNECT_ACK continuation was called after neighbor was freed,
1765      * for example due to a time out for the state or the session
1766      * used was already terminated: nothing to do here... */
1767     return;
1768   }
1769
1770   if (GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK != n->state)
1771   {
1772     /* CONNECT_ACK continuation was called after neighbor changed state,
1773      * for example due to a time out for the state or the session
1774      * used was already terminated: nothing to do here... */
1775     return;
1776   }
1777   if (GNUNET_OK == result)
1778     return;
1779
1780   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1781             _("Failed to send CONNECT_ACK message to peer `%s' using address `%s' session %p\n"),
1782             GNUNET_i2s (target),
1783             GST_plugins_a2s (n->primary_address.address),
1784             n->primary_address.session);
1785
1786   /* Failed to send CONNECT_ACK message with this address */
1787   GNUNET_ATS_address_destroyed (GST_ats, n->primary_address.address,
1788       n->primary_address.session);
1789   GNUNET_ATS_address_destroyed (GST_ats, n->primary_address.address,
1790       NULL);
1791
1792   /* Remove address and request and additional one */
1793   unset_primary_address (n);
1794
1795   set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS,
1796       GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
1797   return;
1798 }
1799
1800
1801 /**
1802  * Send a CONNECT_ACK message via the given address.
1803  *
1804  * @param address address to use
1805  * @param session session to use
1806  * @param timestamp timestamp to use for the ACK message
1807  */
1808 static void
1809 send_connect_ack_message (const struct GNUNET_HELLO_Address *address,
1810                                   struct Session *session,
1811                                   struct GNUNET_TIME_Absolute timestamp)
1812 {
1813   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1814   struct SessionConnectMessage connect_msg;
1815   struct NeighbourMapEntry *n;
1816
1817   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1818               "Sending CONNECT_ACK to peer `%s'\n",
1819               GNUNET_i2s (&address->peer));
1820   if (NULL == (papi = GST_plugins_find (address->transport_name)))
1821   {
1822     GNUNET_break (0);
1823     return;
1824   }
1825   if (NULL == session)
1826     session = papi->get_session (papi->cls, address);
1827   if (NULL == session)
1828   {
1829     GNUNET_break (0);
1830     return;
1831   }
1832   GNUNET_STATISTICS_update (GST_stats,
1833                             gettext_noop
1834                             ("# CONNECT_ACK messages sent"),
1835                             1, GNUNET_NO);
1836   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1837   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK);
1838   connect_msg.reserved = htonl (0);
1839   connect_msg.timestamp = GNUNET_TIME_absolute_hton (timestamp);
1840
1841   if (GNUNET_SYSERR == papi->send (papi->cls,
1842                      session,
1843                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1844                      UINT_MAX,
1845                      GNUNET_TIME_UNIT_FOREVER_REL,
1846                      send_session_connect_ack_cont, NULL))
1847   {
1848     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1849                 _("Failed to transmit CONNECT_ACK message via plugin to %s\n"),
1850                 GST_plugins_a2s (address));
1851
1852     n = lookup_neighbour (&address->peer);
1853     if (NULL == n)
1854     {
1855       GNUNET_break (0);
1856       return;
1857     }
1858     /* Hard failure to send the CONNECT_ACK message with this address:
1859        Destroy session (and address)  */
1860     if (GNUNET_YES == GNUNET_HELLO_address_check_option(address,
1861         GNUNET_HELLO_ADDRESS_INFO_INBOUND))
1862     {
1863       GNUNET_ATS_address_destroyed (GST_ats, address, session);
1864       GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
1865     }
1866     else
1867       GNUNET_ATS_address_destroyed (GST_ats, address, session);
1868
1869     /* Remove address and request and additional one */
1870     unset_primary_address (n);
1871     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS,
1872         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
1873     return;
1874   }
1875
1876 }
1877
1878 struct QuotaNotificationRequest
1879 {
1880   struct GNUNET_PeerIdentity peer;
1881   struct Session *session;
1882   char *plugin;
1883 };
1884
1885 struct QNR_LookContext
1886 {
1887   struct GNUNET_PeerIdentity peer;
1888   struct Session *session;
1889   const char *plugin;
1890
1891   struct QuotaNotificationRequest *res;
1892 };
1893
1894 static int
1895 find_notification_request (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1896 {
1897   struct QNR_LookContext *qnr_ctx = cls;
1898   struct QuotaNotificationRequest *qnr = value;
1899
1900   if ((qnr->session == qnr_ctx->session) &&
1901       (0 == memcmp (&qnr->peer, &qnr_ctx->peer, sizeof (struct GNUNET_PeerIdentity))) &&
1902       (0 == strcmp(qnr_ctx->plugin, qnr->plugin)))
1903   {
1904     qnr_ctx->res = value;
1905     return GNUNET_NO;
1906   }
1907   return GNUNET_YES;
1908 }
1909
1910 void
1911 GST_neighbours_register_quota_notification(void *cls,
1912     const struct GNUNET_PeerIdentity *peer, const char *plugin,
1913     struct Session *session)
1914 {
1915   struct QuotaNotificationRequest *qnr;
1916   struct QNR_LookContext qnr_ctx;
1917
1918   if (NULL == registered_quota_notifications)
1919   {
1920     return; /* init or shutdown */
1921   }
1922
1923   qnr_ctx.peer = (*peer);
1924   qnr_ctx.plugin = plugin;
1925   qnr_ctx.session = session;
1926   qnr_ctx.res = NULL;
1927
1928   GNUNET_CONTAINER_multipeermap_get_multiple (registered_quota_notifications,
1929       peer, &find_notification_request, &qnr_ctx);
1930   if (NULL != qnr_ctx.res)
1931   {
1932     GNUNET_break(0);
1933     return;
1934   }
1935
1936   qnr = GNUNET_new (struct QuotaNotificationRequest);
1937   qnr->peer =  (*peer);
1938   qnr->plugin = GNUNET_strdup (plugin);
1939   qnr->session = session;
1940
1941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1942       "Adding notification for peer `%s' plugin `%s' session %p \n",
1943       GNUNET_i2s (peer), plugin, session);
1944
1945   GNUNET_CONTAINER_multipeermap_put (registered_quota_notifications, peer,
1946       qnr, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1947 }
1948
1949
1950 void
1951 GST_neighbours_unregister_quota_notification(void *cls,
1952     const struct GNUNET_PeerIdentity *peer, const char *plugin, struct Session *session)
1953 {
1954   struct QNR_LookContext qnr_ctx;
1955
1956   if (NULL == registered_quota_notifications)
1957   {
1958     return; /* init or shutdown */
1959   }
1960
1961   qnr_ctx.peer = (*peer);
1962   qnr_ctx.plugin = plugin;
1963   qnr_ctx.session = session;
1964   qnr_ctx.res = NULL;
1965
1966   GNUNET_CONTAINER_multipeermap_iterate (registered_quota_notifications,
1967       &find_notification_request, &qnr_ctx);
1968   if (NULL == qnr_ctx.res)
1969   {
1970     GNUNET_break(0);
1971     return;
1972   }
1973
1974   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1975       "Removing notification for peer `%s' plugin `%s' session %p \n",
1976       GNUNET_i2s (peer), plugin, session);
1977
1978   GNUNET_CONTAINER_multipeermap_remove (registered_quota_notifications, peer,
1979       qnr_ctx.res);
1980   GNUNET_free (qnr_ctx.res->plugin);
1981   GNUNET_free (qnr_ctx.res);
1982 }
1983
1984 static int
1985 notification_cb(void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1986 {
1987   /* struct NeighbourMapEntry *n = cls; */
1988   struct QuotaNotificationRequest *qnr = value;
1989   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1990   struct GNUNET_TIME_Relative delay;
1991   int do_forward;
1992
1993   papi = GST_plugins_find(qnr->plugin);
1994   if (NULL == papi)
1995   {
1996     GNUNET_break (0);
1997     return GNUNET_OK;
1998   }
1999
2000   delay = GST_neighbours_calculate_receive_delay (key, 0, &do_forward);
2001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2002       "New inbound delay for peer `%s' is %llu ms\n", GNUNET_i2s (key),
2003       delay.rel_value_us / 1000);
2004
2005   if (NULL != papi->update_inbound_delay)
2006     papi->update_inbound_delay (papi->cls, key, qnr->session, delay);
2007   return GNUNET_OK;
2008 }
2009
2010 static
2011 int
2012 free_notification_cb(void *cls, const struct GNUNET_PeerIdentity *key,
2013     void *value)
2014 {
2015   /* struct NeighbourMapEntry *n = cls; */
2016   struct QuotaNotificationRequest *qnr = value;
2017
2018   GNUNET_CONTAINER_multipeermap_remove (registered_quota_notifications, key,
2019       qnr);
2020   GNUNET_free(qnr->plugin);
2021   GNUNET_free(qnr);
2022
2023   return GNUNET_OK;
2024 }
2025
2026 static void
2027 inbound_bw_tracker_update(void *cls)
2028 {
2029   struct NeighbourMapEntry *n = cls;
2030
2031   /* Quota was updated, tell plugins to update the time to receive next */
2032   GNUNET_CONTAINER_multipeermap_get_multiple (registered_quota_notifications,
2033       &n->id, &notification_cb, n);
2034 }
2035
2036
2037 /**
2038  * Create a fresh entry in the neighbour map for the given peer
2039  *
2040  * @param peer peer to create an entry for
2041  * @return new neighbour map entry
2042  */
2043 static struct NeighbourMapEntry *
2044 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
2045 {
2046   struct NeighbourMapEntry *n;
2047
2048   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2049               "Creating new neighbour entry for `%s'\n",
2050               GNUNET_i2s (peer));
2051   n = GNUNET_new (struct NeighbourMapEntry);
2052   n->id = *peer;
2053   n->ack_state = ACK_UNDEFINED;
2054   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2055   n->last_util_transmission = GNUNET_TIME_absolute_get();
2056   n->util_payload_bytes_recv = 0;
2057   n->util_payload_bytes_sent = 0;
2058   n->util_total_bytes_recv = 0;
2059   n->util_total_bytes_sent = 0;
2060   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker, &inbound_bw_tracker_update, n,
2061                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2062                                  MAX_BANDWIDTH_CARRY_S);
2063   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
2064   set_state_and_timeout (n, GNUNET_TRANSPORT_PS_NOT_CONNECTED, GNUNET_TIME_UNIT_FOREVER_ABS);
2065   GNUNET_assert (GNUNET_OK ==
2066                  GNUNET_CONTAINER_multipeermap_put (neighbours,
2067                                                     &n->id, n,
2068                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2069   return n;
2070 }
2071
2072
2073 /**
2074  * Check if the two given addresses are the same.
2075  * Actually only checks if the sessions are non-NULL
2076  * (which they should be) and then if they are identical;
2077  * the actual addresses don't matter if the session
2078  * pointers match anyway, and we must have session pointers
2079  * at this time.
2080  *
2081  * @param a1 first address to compare
2082  * @param a2 other address to compare
2083  * @return #GNUNET_NO if the addresses do not match, #GNUNET_YES if they do match
2084  */
2085 static int
2086 address_matches (const struct NeighbourAddress *a1,
2087                  const struct NeighbourAddress *a2)
2088 {
2089   if ( (NULL == a1->session) ||
2090        (NULL == a2->session) )
2091   {
2092     GNUNET_break (0);
2093     return 0;
2094   }
2095   return (a1->session == a2->session) ? GNUNET_YES : GNUNET_NO;
2096 }
2097
2098
2099 /* We received a address suggestion after requesting an address in
2100  * try_connect or after receiving a connect, switch to address
2101  */
2102 static void
2103 address_suggest_cont (void *cls,
2104     const struct GNUNET_PeerIdentity *peer,
2105     const struct GNUNET_HELLO_Address *address, struct Session *session,
2106     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
2107     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
2108     const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
2109 {
2110   GST_neighbours_switch_to_address(peer, address, session, ats, ats_count,
2111       bandwidth_in, bandwidth_out);
2112 }
2113
2114
2115 struct BlacklistCheckSwitchContext
2116 {
2117   struct BlacklistCheckSwitchContext *prev;
2118   struct BlacklistCheckSwitchContext *next;
2119
2120
2121   struct GST_BlacklistCheck *blc;
2122
2123   struct GNUNET_HELLO_Address *address;
2124   struct Session *session;
2125   struct GNUNET_ATS_Information *ats;
2126   uint32_t ats_count;
2127
2128   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
2129   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
2130 };
2131
2132 /**
2133  * Black list check result for try_connect call
2134  * If connection to the peer is allowed request adddress and
2135  *
2136  * @param cls blc_ctx bl context
2137  * @param peer the peer
2138  * @param result the result
2139  */
2140 static void
2141 try_connect_bl_check_cont (void *cls,
2142     const struct GNUNET_PeerIdentity *peer, int result)
2143 {
2144   struct BlacklistCheckSwitchContext *blc_ctx = cls;
2145   struct NeighbourMapEntry *n;
2146
2147   GNUNET_CONTAINER_DLL_remove (pending_bc_head, pending_bc_tail, blc_ctx);
2148   GNUNET_free (blc_ctx);
2149
2150   if (GNUNET_OK != result)
2151   {
2152     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2153         _("Blacklisting disapproved to connect to peer `%s'\n"),
2154         GNUNET_i2s (peer));
2155     return;
2156   }
2157
2158   /* Setup a new neighbour */
2159   n = setup_neighbour (peer);
2160
2161   /* Request address suggestions for this peer */
2162   set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
2163       GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
2164   GNUNET_ATS_reset_backoff (GST_ats, peer);
2165   n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, peer,
2166       &address_suggest_cont, n);
2167 }
2168
2169
2170
2171 /**
2172  * Try to create a connection to the given target (eventually).
2173  *
2174  * @param target peer to try to connect to
2175  */
2176 void
2177 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
2178 {
2179   struct NeighbourMapEntry *n;
2180   struct GST_BlacklistCheck *blc;
2181   struct BlacklistCheckSwitchContext *blc_ctx;
2182
2183   if (NULL == neighbours)
2184   {
2185     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2186                 "Asked to connect to peer `%s' during shutdown\n",
2187                 GNUNET_i2s (target));
2188     return; /* during shutdown, do nothing */
2189   }
2190   n = lookup_neighbour (target);
2191   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2192               "Asked to connect to peer `%s' (state: %s)\n",
2193               GNUNET_i2s (target),
2194               (NULL != n) ? GNUNET_TRANSPORT_ps2s(n->state) : "NEW PEER");
2195   if (NULL != n)
2196   {
2197     switch (n->state)
2198     {
2199     case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
2200       /* this should not be possible */
2201       GNUNET_break (0);
2202       free_neighbour (n, GNUNET_NO);
2203       break;
2204     case GNUNET_TRANSPORT_PS_INIT_ATS:
2205     case GNUNET_TRANSPORT_PS_CONNECT_SENT:
2206     case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
2207     case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
2208     case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
2209     case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
2210       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2211                   "Ignoring request to try to connect to `%s', already trying!\n",
2212                   GNUNET_i2s (target));
2213       return; /* already trying */
2214     case GNUNET_TRANSPORT_PS_CONNECTED:
2215     case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
2216     case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
2217     case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
2218     case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
2219     case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
2220       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2221                   "Ignoring request to try to connect, already connected to `%s'!\n",
2222                   GNUNET_i2s (target));
2223       return; /* already connected */
2224     case GNUNET_TRANSPORT_PS_DISCONNECT:
2225       /* get rid of remains, ready to re-try immediately */
2226       free_neighbour (n, GNUNET_NO);
2227       break;
2228     case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
2229       /* should not be possible */
2230       GNUNET_assert (0);
2231       return;
2232     default:
2233       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2234                   "Unhandled state `%s'\n",
2235                   GNUNET_TRANSPORT_ps2s (n->state));
2236       GNUNET_break (0);
2237       free_neighbour (n, GNUNET_NO);
2238       break;
2239     }
2240   }
2241
2242   /* Do blacklist check if connecting to this peer is allowed */
2243   blc_ctx = GNUNET_new (struct BlacklistCheckSwitchContext);
2244   GNUNET_CONTAINER_DLL_insert (pending_bc_head, pending_bc_tail, blc_ctx);
2245
2246   if (NULL != (blc = GST_blacklist_test_allowed (target, NULL,
2247         &try_connect_bl_check_cont, blc_ctx)))
2248   {
2249     blc_ctx->blc = blc;
2250   }
2251 }
2252
2253
2254 /**
2255  * Function called with the result of a blacklist check.
2256  *
2257  * @param cls closure with the `struct BlackListCheckContext`
2258  * @param peer peer this check affects
2259  * @param result #GNUNET_OK if the address is allowed
2260  */
2261 static void
2262 handle_connect_blacklist_check_cont (void *cls,
2263                             const struct GNUNET_PeerIdentity *peer,
2264                             int result)
2265 {
2266   struct BlackListCheckContext *bcc = cls;
2267   struct NeighbourMapEntry *n;
2268
2269   bcc->bc = NULL;
2270   GNUNET_CONTAINER_DLL_remove (bc_head,
2271                                bc_tail,
2272                                bcc);
2273   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2274               "Connection to new address of peer `%s' based on blacklist is `%s'\n",
2275               GNUNET_i2s (peer),
2276               (GNUNET_OK == result) ? "allowed" : "FORBIDDEN");
2277
2278   if (NULL == (n = lookup_neighbour (peer)))
2279   {
2280     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2281                 "No neighbor entry for peer `%s', ignoring blacklist result\n",
2282                 GNUNET_i2s (peer));
2283     goto cleanup; /* nobody left to care about new address */
2284   }
2285
2286   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2287               "Blacklist check after CONNECT for peer `%s' in state %s/%s: %s\n",
2288               GNUNET_i2s (peer),
2289               GNUNET_TRANSPORT_ps2s (n->state),
2290               print_ack_state (n->ack_state),
2291               (GNUNET_OK == result) ? "OK" : "FAIL");
2292
2293   if (GNUNET_OK == result)
2294   {
2295     /* Blacklist agreed on connecting to a peer with this address, notify ATS */
2296     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2297         "Notifying ATS peer's `%s' %s address `%s' session %p\n",
2298         GNUNET_i2s (peer),
2299         (GNUNET_YES == GNUNET_HELLO_address_check_option(bcc->na.address,
2300             GNUNET_HELLO_ADDRESS_INFO_INBOUND)) ? "inbound" : "outbound",
2301         GST_plugins_a2s (bcc->na.address), bcc->na.session);
2302     GST_ats_add_address (bcc->na.address, bcc->na.session, NULL, 0);
2303   }
2304
2305   switch (n->state)
2306   {
2307   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
2308     /* This should not be possible */
2309     GNUNET_break (0);
2310     free_neighbour (n, GNUNET_NO);
2311     break;
2312   case GNUNET_TRANSPORT_PS_INIT_ATS:
2313     /* Waiting on ATS suggestion */
2314     break;
2315   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
2316 #if 0
2317     /* TODO Why should I send an connect ACK message */
2318     /* waiting on CONNECT_ACK, send ACK if one is pending */
2319
2320     if ( (GNUNET_OK == result) &&
2321          (ACK_SEND_CONNECT_ACK == n->ack_state) )
2322     {
2323       n->ack_state = ACK_SEND_SESSION_ACK;
2324       send_connect_ack_message (n->primary_address.address,
2325                                         n->primary_address.session,
2326                                         n->connect_ack_timestamp);
2327     }
2328 #endif
2329     break;
2330   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
2331     if (GNUNET_OK == result)
2332     {
2333       /* We received a connect request and blacklist allowed to communicate
2334        * with this peer, request an address from ATS*/
2335       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS,
2336           GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
2337
2338       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339                   "Requesting address for peer %s to ATS\n",
2340                   GNUNET_i2s (peer));
2341       if (NULL == n->suggest_handle)
2342         n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, peer,
2343             &address_suggest_cont, n);
2344       GNUNET_ATS_reset_backoff (GST_ats, peer);
2345     }
2346     else
2347     {
2348       /* We received a CONNECT message from a peer, but blacklist denies to
2349        * communicate with this peer and this address
2350        * - Previous state: NOT_CONNECTED:
2351        * We can free the neighbour, since the CONNECT created it
2352        * - Previous state INIT_ATS:
2353        *
2354        * */
2355       free_neighbour (n, GNUNET_NO);
2356     }
2357     break;
2358   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
2359     /* waiting on ATS suggestion, don't care about blacklist */
2360     break;
2361   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
2362     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
2363     {
2364       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2365                   "Blacklist result ignored, as it is not for our primary address\n");
2366       break; /* result for an address we currently don't care about */
2367     }
2368     if (GNUNET_OK == result)
2369     {
2370       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK,
2371           GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2372       send_connect_ack_message (bcc->na.address,
2373                                         bcc->na.session,
2374                                         n->connect_ack_timestamp);
2375       if (ACK_SEND_CONNECT_ACK == n->ack_state)
2376         n->ack_state = ACK_SEND_SESSION_ACK;
2377     }
2378     else
2379     {
2380       struct GNUNET_TRANSPORT_PluginFunctions *plugin;
2381
2382       plugin = GST_plugins_find (bcc->na.address->transport_name);
2383       if ( (NULL != plugin) &&
2384            (NULL != bcc->na.session) )
2385       {
2386         plugin->disconnect_session (plugin->cls,
2387                                     bcc->na.session);
2388         break;
2389       }
2390       GNUNET_break (NULL != plugin);
2391       free_address (&n->primary_address);
2392       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
2393           GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
2394       GNUNET_ATS_reset_backoff (GST_ats, peer);
2395     }
2396     break;
2397   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
2398     /* waiting on SESSION_ACK, send ACK if one is pending */
2399     if ( (GNUNET_OK == result) &&
2400          (ACK_SEND_CONNECT_ACK == n->ack_state) )
2401     {
2402       /* TODO: Why should this happen? */
2403       /* *Debug message: */ GNUNET_break (0);
2404
2405       n->ack_state = ACK_SEND_SESSION_ACK;
2406       send_connect_ack_message (n->primary_address.address,
2407                                         n->primary_address.session,
2408                                         n->connect_ack_timestamp);
2409     }
2410     break;
2411   case GNUNET_TRANSPORT_PS_CONNECTED:
2412     /* already connected, don't care about blacklist */
2413     break;
2414   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
2415     /* still waiting on ATS suggestion, don't care about blacklist */
2416     break;
2417   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
2418     if ( (GNUNET_OK == result) &&
2419          (ACK_SEND_CONNECT_ACK == n->ack_state) )
2420     {
2421       n->ack_state = ACK_SEND_SESSION_ACK;
2422       send_connect_ack_message (bcc->na.address,
2423                                         bcc->na.session,
2424                                         n->connect_ack_timestamp);
2425     }
2426     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
2427     {
2428       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2429                   "Blacklist result ignored, as it is not for our primary address\n");
2430       break; /* result for an address we currently don't care about */
2431     }
2432     if (GNUNET_OK == result)
2433     {
2434       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_SENT,
2435           GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT));
2436       send_session_connect (&n->primary_address);
2437     }
2438     else
2439     {
2440       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_ATS,
2441           GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
2442     }
2443     break;
2444   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
2445     /* waiting on CONNECT_ACK, don't care about blacklist */
2446     if ( (GNUNET_OK == result) &&
2447          (ACK_SEND_CONNECT_ACK == n->ack_state) )
2448     {
2449       n->ack_state = ACK_SEND_SESSION_ACK;
2450       send_connect_ack_message (n->primary_address.address,
2451                                         n->primary_address.session,
2452                                         n->connect_ack_timestamp);
2453     }
2454     break;
2455   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
2456     if (GNUNET_YES != address_matches (&bcc->na, &n->alternative_address))
2457     {
2458       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2459                   "Blacklist result ignored, as it is not for our primary address\n");
2460       break; /* result for an address we currently don't care about */
2461     }
2462     if (GNUNET_OK == result)
2463     {
2464       send_session_connect (&n->alternative_address);
2465       set_state (n, GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT);
2466     }
2467     else
2468     {
2469       set_state(n, GNUNET_TRANSPORT_PS_CONNECTED);
2470       free_address (&n->alternative_address);
2471     }
2472     break;
2473   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
2474     /* waiting on CONNECT_ACK, don't care about blacklist */
2475     if ( (GNUNET_OK == result) &&
2476          (ACK_SEND_CONNECT_ACK == n->ack_state) )
2477     {
2478       n->ack_state = ACK_SEND_SESSION_ACK;
2479       send_connect_ack_message (n->primary_address.address,
2480                                         n->primary_address.session,
2481                                         n->connect_ack_timestamp);
2482     }
2483     break;
2484   case GNUNET_TRANSPORT_PS_DISCONNECT:
2485     /* Nothing to do here, ATS will already do what can be done */
2486     break;
2487   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
2488     /* should not be possible */
2489     GNUNET_assert (0);
2490     break;
2491   default:
2492     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2493                 "Unhandled state `%s'\n",
2494                 GNUNET_TRANSPORT_ps2s (n->state));
2495     GNUNET_break (0);
2496     free_neighbour (n, GNUNET_NO);
2497     break;
2498   }
2499  cleanup:
2500   GNUNET_HELLO_address_free (bcc->na.address);
2501   GNUNET_free (bcc);
2502 }
2503
2504
2505 /**
2506  * We received a CONNECT message and want to know if connecting to a particular
2507  * peer via a particular address is allowed.  Check it!
2508  *
2509  * @param peer identity of the peer to switch the address for
2510  * @param ts time at which the check was initiated
2511  * @param address address of the other peer, NULL if other peer
2512  *                       connected to us
2513  * @param session session to use (or NULL)
2514  */
2515 static void
2516 connect_check_blacklist (const struct GNUNET_PeerIdentity *peer,
2517                  struct GNUNET_TIME_Absolute ts,
2518                  const struct GNUNET_HELLO_Address *address,
2519                  struct Session *session)
2520 {
2521   struct BlackListCheckContext *bcc;
2522   struct GST_BlacklistCheck *bc;
2523
2524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2525               "Checking peer `%s' against blacklist\n",
2526               GNUNET_i2s (peer));
2527   bcc = GNUNET_new (struct BlackListCheckContext);
2528   bcc->na.address = GNUNET_HELLO_address_copy (address);
2529   bcc->na.session = session;
2530   bcc->na.connect_timestamp = ts;
2531   GNUNET_CONTAINER_DLL_insert (bc_head,
2532                                bc_tail,
2533                                bcc);
2534   if (NULL != (bc = GST_blacklist_test_allowed (peer,
2535         (NULL != address) ? address->transport_name : NULL,
2536         &handle_connect_blacklist_check_cont, bcc)))
2537     bcc->bc = bc;
2538   /* if NULL == bc, 'cont' was already called and 'bcc' already free'd, so
2539      we must only store 'bc' if 'bc' is non-NULL... */
2540 }
2541
2542
2543 /**
2544  * We received a 'SESSION_CONNECT' message from the other peer.
2545  * Consider switching to it.
2546  *
2547  * @param message possibly a 'struct SessionConnectMessage' (check format)
2548  * @param peer identity of the peer to switch the address for
2549  * @param address address of the other peer, NULL if other peer
2550  *                       connected to us
2551  * @param session session to use (or NULL)
2552  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
2553  */
2554 int
2555 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
2556                                const struct GNUNET_PeerIdentity *peer,
2557                                const struct GNUNET_HELLO_Address *address,
2558                                struct Session *session)
2559 {
2560   const struct SessionConnectMessage *scm;
2561   struct NeighbourMapEntry *n;
2562   struct GNUNET_TIME_Absolute ts;
2563
2564   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2565               "Received CONNECT message from peer `%s' with `%s' %p\n",
2566               GNUNET_i2s (peer), GST_plugins_a2s (address), session);
2567   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2568   {
2569     GNUNET_break_op (0);
2570     return GNUNET_SYSERR;
2571   }
2572   GNUNET_STATISTICS_update (GST_stats,
2573                             gettext_noop
2574                             ("# CONNECT messages received"),
2575                             1, GNUNET_NO);
2576   if (NULL == neighbours)
2577   {
2578     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2579                 _("CONNECT request from peer `%s' ignored due impending shutdown\n"),
2580                 GNUNET_i2s (peer));
2581     return GNUNET_OK; /* we're shutting down */
2582   }
2583   scm = (const struct SessionConnectMessage *) message;
2584   GNUNET_break_op (0 == ntohl (scm->reserved));
2585   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2586   n = lookup_neighbour (peer);
2587   if (NULL == n)
2588   {
2589     /* This is a new neighbour and set to not connected */
2590     n = setup_neighbour (peer);
2591   }
2592
2593   /* Remember this CONNECT message in neighbour */
2594   n->ack_state = ACK_SEND_CONNECT_ACK;
2595   n->connect_ack_timestamp = ts;
2596
2597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2598               "Received CONNECT for peer `%s' in state %s/%s\n",
2599               GNUNET_i2s (peer),
2600               GNUNET_TRANSPORT_ps2s (n->state),
2601               print_ack_state (n->ack_state));
2602
2603   switch (n->state)
2604   {
2605   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
2606     /* Check if we are allowed to connect with this peer and this address */
2607     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND,
2608         GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2609     connect_check_blacklist (peer, ts, address, session);
2610     break;
2611   case GNUNET_TRANSPORT_PS_INIT_ATS:
2612     /* CONNECT message takes priority over us asking ATS for address */
2613     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND,
2614         GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2615     connect_check_blacklist (peer, ts, address, session);
2616     break;
2617   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
2618   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
2619   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
2620   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
2621   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
2622     /* It can never hurt to have an alternative address in the above cases,
2623        see if it is allowed */
2624     connect_check_blacklist (peer, ts, address, session);
2625     break;
2626   case GNUNET_TRANSPORT_PS_CONNECTED:
2627     /* we are already connected and can thus send the ACK immediately;
2628        still, it can never hurt to have an alternative address, so also
2629        tell ATS  about it */
2630     GNUNET_assert (NULL != n->primary_address.address);
2631     GNUNET_assert (NULL != n->primary_address.session);
2632     n->ack_state = ACK_UNDEFINED;
2633     send_connect_ack_message (n->primary_address.address,
2634                                       n->primary_address.session, ts);
2635     connect_check_blacklist (peer, ts, address, session);
2636     break;
2637   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
2638   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
2639   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
2640     /* It can never hurt to have an alternative address in the above cases,
2641        see if it is allowed */
2642     connect_check_blacklist (peer, ts, address, session);
2643     break;
2644   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
2645   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
2646     /* we are already connected and can thus send the ACK immediately;
2647        still, it can never hurt to have an alternative address, so also
2648        tell ATS  about it */
2649     GNUNET_assert (NULL != n->primary_address.address);
2650     GNUNET_assert (NULL != n->primary_address.session);
2651     n->ack_state = ACK_UNDEFINED;
2652     send_connect_ack_message (n->primary_address.address,
2653                                       n->primary_address.session, ts);
2654     connect_check_blacklist (peer, ts, address, session);
2655     break;
2656   case GNUNET_TRANSPORT_PS_DISCONNECT:
2657     /* get rid of remains without terminating sessions, ready to re-try */
2658     free_neighbour (n, GNUNET_YES);
2659     n = setup_neighbour (peer);
2660     /* Remember the CONNECT timestamp for ACK message */
2661     n->ack_state = ACK_SEND_CONNECT_ACK;
2662     n->connect_ack_timestamp = ts;
2663     /* Request an address for the peer */
2664     GNUNET_ATS_suggest_address (GST_ats, peer, address_suggest_cont, n);
2665     GNUNET_ATS_reset_backoff (GST_ats, peer);
2666     set_state (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS);
2667     break;
2668   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
2669     /* should not be possible */
2670     GNUNET_assert (0);
2671     break;
2672   default:
2673     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2674                 "Unhandled state `%s'\n",
2675                 GNUNET_TRANSPORT_ps2s (n->state));
2676     GNUNET_break (0);
2677     return GNUNET_SYSERR;
2678   }
2679   return GNUNET_OK;
2680 }
2681
2682 static void
2683 switch_address_bl_check_cont (void *cls,
2684     const struct GNUNET_PeerIdentity *peer, int result)
2685 {
2686   struct BlacklistCheckSwitchContext *blc_ctx = cls;
2687   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2688   struct NeighbourMapEntry *n;
2689
2690   if ( (NULL == (n = lookup_neighbour (peer))) || (result == GNUNET_NO) ||
2691        (NULL == (papi = GST_plugins_find (blc_ctx->address->transport_name))) )
2692   {
2693     if (NULL == n)
2694     {
2695       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2696                   "Peer %s is unknown, suggestion ignored\n",
2697                   GNUNET_i2s (peer));
2698     }
2699     if (result == GNUNET_NO)
2700     {
2701       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2702           "Blacklist denied to switch to suggested address `%s' session %p for peer `%s'\n",
2703           GST_plugins_a2s (blc_ctx->address),
2704           blc_ctx->session,
2705           GNUNET_i2s (&blc_ctx->address->peer));
2706     }
2707     if (NULL == (papi = GST_plugins_find (blc_ctx->address->transport_name)))
2708     {
2709       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2710           "Plugin `%s' for suggested address `%s' session %p for peer `%s' is not available\n",
2711           blc_ctx->address->transport_name,
2712           GST_plugins_a2s (blc_ctx->address),
2713           blc_ctx->session,
2714           GNUNET_i2s (&blc_ctx->address->peer));
2715     }
2716
2717     /* This address is blacklisted, delete address and session (if existing) in ATS */
2718     GNUNET_ATS_address_destroyed (GST_ats, blc_ctx->address, blc_ctx->session);
2719
2720     if ( (GNUNET_YES == (GNUNET_HELLO_address_check_option (blc_ctx->address,
2721           GNUNET_HELLO_ADDRESS_INFO_INBOUND))) && (NULL != blc_ctx->session))
2722     {
2723       /* This is an inbound address, destroy full  address */
2724       GNUNET_ATS_address_destroyed (GST_ats, blc_ctx->address, NULL );
2725     }
2726
2727     /* Remove blacklist check and clean up */
2728     GNUNET_CONTAINER_DLL_remove (pending_bc_head, pending_bc_tail, blc_ctx);
2729     GNUNET_HELLO_address_free (blc_ctx->address);
2730     GNUNET_free_non_null (blc_ctx->ats);
2731     GNUNET_free (blc_ctx);
2732     return;
2733   }
2734
2735   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2736       "Blacklist accepted to switch to suggested address `%s' session %p for peer `%s'\n",
2737       GST_plugins_a2s (blc_ctx->address),
2738       blc_ctx->session,
2739       GNUNET_i2s (&blc_ctx->address->peer));
2740
2741   if (NULL == blc_ctx->session)
2742   {
2743     blc_ctx->session = papi->get_session (papi->cls, blc_ctx->address);
2744     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2745                 "Obtained new session for peer `%s' and  address '%s': %p\n",
2746                 GNUNET_i2s (&blc_ctx->address->peer), GST_plugins_a2s (blc_ctx->address), blc_ctx->session);
2747   }
2748   if (NULL == blc_ctx->session)
2749   {
2750     /* No session could be obtained, remove blacklist check and clean up */
2751     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2752                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
2753                 GNUNET_i2s (&blc_ctx->address->peer),
2754                 GST_plugins_a2s (blc_ctx->address));
2755     /* Delete address in ATS */
2756     GNUNET_ATS_address_destroyed (GST_ats, blc_ctx->address, NULL);
2757
2758     GNUNET_CONTAINER_DLL_remove (pending_bc_head, pending_bc_tail, blc_ctx);
2759     GNUNET_HELLO_address_free (blc_ctx->address);
2760     GNUNET_free_non_null (blc_ctx->ats);
2761     GNUNET_free (blc_ctx);
2762     return;
2763   }
2764
2765   switch (n->state)
2766   {
2767   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
2768     GNUNET_break (0);
2769     free_neighbour (n, GNUNET_NO);
2770     return;
2771   case GNUNET_TRANSPORT_PS_INIT_ATS:
2772     /* We requested an address and ATS suggests one:
2773      * set primary address and send CONNECT message*/
2774     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2775         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2776     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_SENT,
2777         GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2778     send_session_connect (&n->primary_address);
2779     break;
2780   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
2781     /* waiting on CONNECT_ACK, send ACK if one is pending */
2782     if (ACK_SEND_CONNECT_ACK == n->ack_state)
2783     {
2784       n->ack_state = ACK_SEND_SESSION_ACK;
2785       send_connect_ack_message (n->primary_address.address,
2786                                         n->primary_address.session,
2787                                         n->connect_ack_timestamp);
2788     }
2789     /* ATS suggests a different address, switch again */
2790     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2791         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2792     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_SENT,
2793         GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2794     send_session_connect (&n->primary_address);
2795     break;
2796   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
2797     /* We received an suggestion while waiting for a CONNECT blacklist check,
2798      * this suggestion was permitted by a blacklist check, so send ACK*/
2799   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
2800     /* We requested an address and ATS suggests one:
2801      * set primary address and send CONNECT_ACK message*/
2802     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2803         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2804     /* Send an ACK message as a response to the CONNECT msg */
2805     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK,
2806         GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2807     send_connect_ack_message (n->primary_address.address,
2808                               n->primary_address.session,
2809                               n->connect_ack_timestamp);
2810     if (ACK_SEND_CONNECT_ACK == n->ack_state)
2811       n->ack_state = ACK_SEND_SESSION_ACK;
2812
2813     break;
2814   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
2815   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
2816     /* ATS asks us to switch while we were trying to connect; switch to new
2817        address and check blacklist again */
2818     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2819         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2820     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST,
2821         GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2822     /* REMOVE */ connect_check_blacklist (&n->id, n->connect_ack_timestamp,
2823         blc_ctx->address, blc_ctx->session);
2824     break;
2825   case GNUNET_TRANSPORT_PS_CONNECTED:
2826     GNUNET_assert (NULL != n->primary_address.address);
2827     GNUNET_assert (NULL != n->primary_address.session);
2828     if (n->primary_address.session == blc_ctx->session)
2829     {
2830       /* not an address change, just a quota change */
2831       set_primary_address (n, blc_ctx->address, blc_ctx->session,
2832           blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_YES);
2833       break;
2834     }
2835     /* ATS asks us to switch a life connection; see if we can get
2836        a CONNECT_ACK on it before we actually do this! */
2837     set_state (n, GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST);
2838     set_alternative_address (n, blc_ctx->address, blc_ctx->session,
2839         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out);
2840     /* REMOVE */ connect_check_blacklist (&n->id, GNUNET_TIME_absolute_get (),
2841         blc_ctx->address, blc_ctx->session);
2842     break;
2843   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
2844     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2845         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2846     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST,
2847         GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2848     /* REMOVE */ connect_check_blacklist (&n->id, n->connect_ack_timestamp,
2849         blc_ctx->address, blc_ctx->session);
2850     break;
2851   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
2852     /* ATS asks us to switch while we were trying to reconnect; switch to new
2853        address and check blacklist again */
2854     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2855         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2856     set_timeout (n, GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2857     /* REMOVE */ connect_check_blacklist (&n->id, n->connect_ack_timestamp,
2858         blc_ctx->address, blc_ctx->session);
2859     break;
2860   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
2861     /* ATS asks us to switch while we were trying to reconnect; switch to new
2862        address and check blacklist again */
2863     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2864         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2865     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST,
2866         GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2867     /* REMOVE */ connect_check_blacklist (&n->id, n->connect_ack_timestamp,
2868         blc_ctx->address, blc_ctx->session);
2869     break;
2870   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
2871     if (n->primary_address.session == blc_ctx->session)
2872     {
2873       /* ATS switches back to still-active session */
2874       set_state(n, GNUNET_TRANSPORT_PS_CONNECTED);
2875       free_address (&n->alternative_address);
2876       break;
2877     }
2878     /* ATS asks us to switch a life connection, update blacklist check */
2879     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2880         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2881     /* REMOVE */ connect_check_blacklist (&n->id, GNUNET_TIME_absolute_get (),
2882         blc_ctx->address, blc_ctx->session);
2883     break;
2884   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
2885     if (n->primary_address.session == blc_ctx->session)
2886     {
2887       /* ATS switches back to still-active session */
2888       free_address (&n->alternative_address);
2889       set_state (n, GNUNET_TRANSPORT_PS_CONNECTED);
2890       break;
2891     }
2892     /* ATS asks us to switch a life connection, update blacklist check */
2893     set_state (n, GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST);
2894     set_alternative_address (n, blc_ctx->address, blc_ctx->session,
2895         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out);
2896     /* REMOVE */ connect_check_blacklist (&n->id, GNUNET_TIME_absolute_get (),
2897         blc_ctx->address, blc_ctx->session);
2898     break;
2899   case GNUNET_TRANSPORT_PS_DISCONNECT:
2900     /* not going to switch addresses while disconnecting */
2901     return;
2902   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
2903     GNUNET_assert (0);
2904     break;
2905   default:
2906     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2907                 "Unhandled state `%s'\n",
2908                 GNUNET_TRANSPORT_ps2s (n->state));
2909     GNUNET_break (0);
2910     break;
2911   }
2912
2913   GNUNET_CONTAINER_DLL_remove (pending_bc_head, pending_bc_tail, blc_ctx);
2914   GNUNET_HELLO_address_free(blc_ctx->address);
2915   GNUNET_free_non_null (blc_ctx->ats);
2916   GNUNET_free (blc_ctx);
2917   return;
2918 }
2919
2920
2921 /**
2922  * For the given peer, switch to this address.
2923  *
2924  * Before accepting this addresses and actively using it, a blacklist check
2925  * is performed. If this blacklist check fails the address will be destroyed.
2926  *
2927  * @param peer identity of the peer to switch the address for
2928  * @param address address of the other peer,
2929  * @param session session to use or NULL if transport should initiate a session
2930  * @param ats performance data
2931  * @param ats_count number of entries in ats
2932  * @param bandwidth_in inbound quota to be used when connection is up,
2933  *      0 to disconnect from peer
2934  * @param bandwidth_out outbound quota to be used when connection is up,
2935  *      0 to disconnect from peer
2936  */
2937 void
2938 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
2939                                   const struct GNUNET_HELLO_Address *address,
2940                                   struct Session *session,
2941                                   const struct GNUNET_ATS_Information *ats,
2942                                   uint32_t ats_count,
2943                                   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
2944                                   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
2945 {
2946   struct NeighbourMapEntry *n;
2947   struct GST_BlacklistCheck *blc;
2948   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2949   struct BlacklistCheckSwitchContext *blc_ctx;
2950   int c;
2951
2952   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2953               "ATS has decided on an address for peer %s\n",
2954               GNUNET_i2s (peer));
2955   GNUNET_assert (NULL != address->transport_name);
2956   if (NULL == (n = lookup_neighbour (peer)))
2957   {
2958     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2959                 "Peer %s is unknown, suggestion ignored\n",
2960                 GNUNET_i2s (peer));
2961     return;
2962   }
2963
2964   /* Check if plugin is available */
2965   if (NULL == (papi = GST_plugins_find (address->transport_name)))
2966   {
2967     /* we don't have the plugin for this address */
2968     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2969                 "Plugin `%s' is unknown, suggestion for peer %s ignored\n",
2970                 address->transport_name,
2971                 GNUNET_i2s (peer));
2972     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2973     return;
2974   }
2975   if ((NULL == session) &&
2976       (GNUNET_HELLO_address_check_option (address, GNUNET_HELLO_ADDRESS_INFO_INBOUND)))
2977   {
2978     /* This is a inbound address and we do not have a session to use! */
2979     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2980                 "Inbound address without session `%s'! Destroying address...\n",
2981                 GST_plugins_a2s (address));
2982     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2983     return;
2984   }
2985
2986   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2987     "ATS tells us to switch to %s address '%s' session %p for "
2988     "peer `%s' in state %s/%s (quota in/out %u %u )\n",
2989     GNUNET_HELLO_address_check_option (address,
2990         GNUNET_HELLO_ADDRESS_INFO_INBOUND) ? "inbound" : "outbound",
2991     GST_plugins_a2s (address), session, GNUNET_i2s (peer),
2992     GNUNET_TRANSPORT_ps2s (n->state), print_ack_state (n->ack_state),
2993     ntohl (bandwidth_in.value__), ntohl (bandwidth_out.value__));
2994
2995   /* Perform blacklist check */
2996   blc_ctx = GNUNET_new (struct BlacklistCheckSwitchContext);
2997   blc_ctx->address = GNUNET_HELLO_address_copy (address);
2998   blc_ctx->session = session;
2999   blc_ctx->bandwidth_in = bandwidth_in;
3000   blc_ctx->bandwidth_out = bandwidth_out;
3001   blc_ctx->ats_count = ats_count;
3002   blc_ctx->ats = NULL;
3003   if (ats_count > 0)
3004   {
3005     blc_ctx->ats = GNUNET_malloc (ats_count * sizeof (struct GNUNET_ATS_Information));
3006     for (c = 0; c < ats_count; c++)
3007     {
3008       blc_ctx->ats[c].type = ats[c].type;
3009       blc_ctx->ats[c].value = ats[c].value;
3010     }
3011   }
3012
3013   GNUNET_CONTAINER_DLL_insert (pending_bc_head, pending_bc_tail, blc_ctx);
3014   if (NULL != (blc = GST_blacklist_test_allowed (peer, address->transport_name,
3015       &switch_address_bl_check_cont, blc_ctx)))
3016   {
3017     blc_ctx->blc = blc;
3018   }
3019 }
3020
3021
3022 static int
3023 send_utilization_data (void *cls,
3024                        const struct GNUNET_PeerIdentity *key,
3025                        void *value)
3026 {
3027   struct NeighbourMapEntry *n = value;
3028   struct GNUNET_ATS_Information atsi[4];
3029   uint32_t bps_pl_in;
3030   uint32_t bps_pl_out;
3031   uint32_t bps_in;
3032   uint32_t bps_out;
3033   struct GNUNET_TIME_Relative delta;
3034
3035   delta = GNUNET_TIME_absolute_get_difference (n->last_util_transmission,
3036                                                GNUNET_TIME_absolute_get ());
3037
3038   bps_pl_in = 0;
3039
3040   if ((0 != n->util_payload_bytes_recv) && (0 != delta.rel_value_us))
3041     bps_pl_in =  (1000LL * 1000LL *  n->util_payload_bytes_recv) / (delta.rel_value_us);
3042   bps_pl_out = 0;
3043   if ((0 != n->util_payload_bytes_sent) && (0 != delta.rel_value_us))
3044     bps_pl_out = (1000LL * 1000LL * n->util_payload_bytes_sent) / delta.rel_value_us;
3045   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3046               "`%s' payload: received %u Bytes/s, sent %u Bytes/s\n",
3047               GNUNET_i2s (key),
3048               bps_pl_in,
3049               bps_pl_out);
3050   bps_in = 0;
3051   if ((0 != n->util_total_bytes_recv) && (0 != delta.rel_value_us))
3052     bps_in =  (1000LL * 1000LL *  n->util_total_bytes_recv) / (delta.rel_value_us);
3053   bps_out = 0;
3054   if ((0 != n->util_total_bytes_sent) && (0 != delta.rel_value_us))
3055     bps_out = (1000LL * 1000LL * n->util_total_bytes_sent) / delta.rel_value_us;
3056
3057
3058   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3059               "`%s' total: received %u Bytes/s, sent %u Bytes/s\n",
3060               GNUNET_i2s (key),
3061               bps_in,
3062               bps_out);
3063   atsi[0].type = htonl (GNUNET_ATS_UTILIZATION_OUT);
3064   atsi[0].value = htonl (bps_out);
3065   atsi[1].type = htonl (GNUNET_ATS_UTILIZATION_IN);
3066   atsi[1].value = htonl (bps_in);
3067
3068   atsi[2].type = htonl (GNUNET_ATS_UTILIZATION_PAYLOAD_OUT);
3069   atsi[2].value = htonl (bps_pl_out);
3070   atsi[3].type = htonl (GNUNET_ATS_UTILIZATION_PAYLOAD_IN);
3071   atsi[3].value = htonl (bps_pl_in);
3072
3073   GST_ats_update_metrics (key, n->primary_address.address,
3074       n->primary_address.session, atsi, 4);
3075   n->util_payload_bytes_recv = 0;
3076   n->util_payload_bytes_sent = 0;
3077   n->util_total_bytes_recv = 0;
3078   n->util_total_bytes_sent = 0;
3079   n->last_util_transmission = GNUNET_TIME_absolute_get();
3080   return GNUNET_OK;
3081 }
3082
3083
3084 /**
3085  * Task transmitting utilization in a regular interval
3086  *
3087  * @param cls the 'struct NeighbourMapEntry' for which we are running
3088  * @param tc scheduler context (unused)
3089  */
3090 static void
3091 utilization_transmission (void *cls,
3092                           const struct GNUNET_SCHEDULER_TaskContext *tc)
3093 {
3094   util_transmission_tk = GNUNET_SCHEDULER_NO_TASK;
3095
3096   if (0 < GNUNET_CONTAINER_multipeermap_size (neighbours))
3097     GNUNET_CONTAINER_multipeermap_iterate (neighbours, send_utilization_data, NULL);
3098
3099   util_transmission_tk = GNUNET_SCHEDULER_add_delayed (UTIL_TRANSMISSION_INTERVAL,
3100       utilization_transmission, NULL);
3101
3102 }
3103
3104
3105 void
3106 GST_neighbours_notify_data_recv (const struct GNUNET_PeerIdentity *peer,
3107                                  const struct GNUNET_HELLO_Address *address,
3108                                  struct Session *session,
3109                                  const struct GNUNET_MessageHeader *message)
3110 {
3111   struct NeighbourMapEntry *n;
3112
3113   n = lookup_neighbour (peer);
3114   if (NULL == n)
3115     return;
3116   n->util_total_bytes_recv += ntohs(message->size);
3117 }
3118
3119
3120 void
3121 GST_neighbours_notify_payload_recv (const struct GNUNET_PeerIdentity *peer,
3122                                     const struct GNUNET_HELLO_Address *address,
3123                                     struct Session *session,
3124                                     const struct GNUNET_MessageHeader *message)
3125 {
3126   struct NeighbourMapEntry *n;
3127   n = lookup_neighbour (peer);
3128   if (NULL == n)
3129     return;
3130   n->util_payload_bytes_recv += ntohs(message->size);
3131 }
3132
3133
3134 void
3135 GST_neighbours_notify_data_sent (const struct GNUNET_PeerIdentity *peer,
3136                                  const struct GNUNET_HELLO_Address *address,
3137                                  struct Session *session,
3138                                  size_t size)
3139 {
3140   struct NeighbourMapEntry *n;
3141   n = lookup_neighbour (peer);
3142   if (NULL == n)
3143       return;
3144   if (n->primary_address.session != session)
3145     return;
3146   n->util_total_bytes_sent += size;
3147 }
3148
3149
3150 void
3151 GST_neighbours_notify_payload_sent (const struct GNUNET_PeerIdentity *peer,
3152                                     size_t size)
3153 {
3154   struct NeighbourMapEntry *n;
3155   n = lookup_neighbour (peer);
3156   if (NULL == n)
3157     return;
3158   n->util_payload_bytes_sent += size;
3159 }
3160
3161
3162 /**
3163  * Master task run for every neighbour.  Performs all of the time-related
3164  * activities (keep alive, send next message, disconnect if idle, finish
3165  * clean up after disconnect).
3166  *
3167  * @param cls the 'struct NeighbourMapEntry' for which we are running
3168  * @param tc scheduler context (unused)
3169  */
3170 static void
3171 master_task (void *cls,
3172              const struct GNUNET_SCHEDULER_TaskContext *tc)
3173 {
3174   struct NeighbourMapEntry *n = cls;
3175   struct GNUNET_TIME_Relative delay;
3176
3177   n->task = GNUNET_SCHEDULER_NO_TASK;
3178   delay = GNUNET_TIME_absolute_get_remaining (n->timeout);
3179   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3180               "Master task runs for neighbour `%s' in state %s with timeout in %s\n",
3181               GNUNET_i2s (&n->id),
3182               GNUNET_TRANSPORT_ps2s(n->state),
3183               GNUNET_STRINGS_relative_time_to_string (delay,
3184                                                       GNUNET_YES));
3185   switch (n->state)
3186   {
3187   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3188     /* invalid state for master task, clean up */
3189     GNUNET_break (0);
3190     free_neighbour (n, GNUNET_NO);
3191     return;
3192   case GNUNET_TRANSPORT_PS_INIT_ATS:
3193     if (0 == delay.rel_value_us)
3194     {
3195       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3196                   "Connection to `%s' timed out waiting for ATS to provide address\n",
3197                   GNUNET_i2s (&n->id));
3198       free_neighbour (n, GNUNET_NO);
3199       return;
3200     }
3201     break;
3202   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
3203     if (0 == delay.rel_value_us)
3204     {
3205       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3206                   "Connection to `%s' timed out waiting for other peer to send CONNECT_ACK\n",
3207                   GNUNET_i2s (&n->id));
3208       /* We could not send to this address, delete address and session */
3209       if (NULL != n->primary_address.session)
3210         GNUNET_ATS_address_destroyed (GST_ats, n->primary_address.address,
3211             n->primary_address.session);
3212       GNUNET_ATS_address_destroyed (GST_ats, n->primary_address.address, NULL);
3213
3214       /* Remove address and request and additional one */
3215       GNUNET_break (0);
3216       unset_primary_address (n);
3217       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
3218           GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3219       return;
3220     }
3221     break;
3222   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
3223     if (0 == delay.rel_value_us)
3224     {
3225       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3226                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for received CONNECT\n",
3227                   GNUNET_i2s (&n->id));
3228       free_neighbour (n, GNUNET_NO);
3229       return;
3230     }
3231     break;
3232   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
3233     if (0 == delay.rel_value_us)
3234     {
3235       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3236                   "Connection to `%s' timed out waiting ATS to provide address to use for CONNECT_ACK\n",
3237                   GNUNET_i2s (&n->id));
3238       free_neighbour (n, GNUNET_NO);
3239       return;
3240     }
3241     break;
3242   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
3243     if (0 == delay.rel_value_us)
3244     {
3245       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3246                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for CONNECT_ACK\n",
3247                   GNUNET_i2s (&n->id));
3248       free_neighbour (n, GNUNET_NO);
3249       return;
3250     }
3251     break;
3252   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
3253     if (0 == delay.rel_value_us)
3254     {
3255       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3256                   "Connection to `%s' timed out waiting for other peer to send SESSION_ACK\n",
3257                   GNUNET_i2s (&n->id));
3258       disconnect_neighbour (n);
3259       return;
3260     }
3261     break;
3262   case GNUNET_TRANSPORT_PS_CONNECTED:
3263     if (0 == delay.rel_value_us)
3264     {
3265       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3266                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
3267                   GNUNET_i2s (&n->id));
3268       disconnect_neighbour (n);
3269       return;
3270     }
3271     try_transmission_to_peer (n);
3272     send_keepalive (n);
3273     break;
3274   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3275     if (0 == delay.rel_value_us)
3276     {
3277       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3278                   "Connection to `%s' timed out, waiting for ATS replacement address\n",
3279                   GNUNET_i2s (&n->id));
3280       disconnect_neighbour (n);
3281       return;
3282     }
3283     break;
3284   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
3285     if (0 == delay.rel_value_us)
3286     {
3287       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3288                   "Connection to `%s' timed out, waiting for BLACKLIST to approve replacement address\n",
3289                   GNUNET_i2s (&n->id));
3290       disconnect_neighbour (n);
3291       return;
3292     }
3293     break;
3294   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3295     if (0 == delay.rel_value_us)
3296     {
3297       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3298                   "Connection to `%s' timed out, waiting for other peer to CONNECT_ACK replacement address\n",
3299                   GNUNET_i2s (&n->id));
3300       disconnect_neighbour (n);
3301       return;
3302     }
3303     break;
3304   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
3305     if (0 == delay.rel_value_us)
3306     {
3307       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3308                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
3309                   GNUNET_i2s (&n->id));
3310       disconnect_neighbour (n);
3311       return;
3312     }
3313     try_transmission_to_peer (n);
3314     send_keepalive (n);
3315     break;
3316   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
3317     if (0 == delay.rel_value_us)
3318     {
3319       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3320                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs (after trying to CONNECT on alternative address)\n",
3321                   GNUNET_i2s (&n->id));
3322       disconnect_neighbour (n);
3323       return;
3324     }
3325     try_transmission_to_peer (n);
3326     send_keepalive (n);
3327     break;
3328   case GNUNET_TRANSPORT_PS_DISCONNECT:
3329     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3330                 "Cleaning up connection to `%s' after sending DISCONNECT\n",
3331                 GNUNET_i2s (&n->id));
3332     free_neighbour (n, GNUNET_NO);
3333     return;
3334   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3335     /* how did we get here!? */
3336     GNUNET_assert (0);
3337     break;
3338   default:
3339     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3340                 "Unhandled state `%s'\n",
3341                 GNUNET_TRANSPORT_ps2s (n->state));
3342     GNUNET_break (0);
3343     break;
3344   }
3345   if ( (GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT == n->state) ||
3346        (GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
3347        (GNUNET_TRANSPORT_PS_CONNECTED == n->state) )
3348   {
3349     /* if we are *now* in one of these three states, we're sending
3350        keep alive messages, so we need to consider the keepalive
3351        delay, not just the connection timeout */
3352     delay = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time),
3353                                       delay);
3354   }
3355   if (GNUNET_SCHEDULER_NO_TASK == n->task)
3356     n->task = GNUNET_SCHEDULER_add_delayed (delay,
3357                                             &master_task,
3358                                             n);
3359 }
3360
3361
3362 /**
3363  * Send a SESSION_ACK message to the neighbour to confirm that we
3364  * got his CONNECT_ACK.
3365  *
3366  * @param n neighbour to send the SESSION_ACK to
3367  */
3368 static void
3369 send_session_ack_message (struct NeighbourMapEntry *n)
3370 {
3371   struct GNUNET_MessageHeader msg;
3372
3373   msg.size = htons (sizeof (struct GNUNET_MessageHeader));
3374   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
3375   (void) send_with_session(n,
3376                            (const char *) &msg, sizeof (struct GNUNET_MessageHeader),
3377                            UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_NO,
3378                            NULL, NULL);
3379 }
3380
3381
3382 /**
3383  * We received a 'SESSION_CONNECT_ACK' message from the other peer.
3384  * Consider switching to it.
3385  *
3386  * @param message possibly a 'struct SessionConnectMessage' (check format)
3387  * @param peer identity of the peer to switch the address for
3388  * @param address address of the other peer, NULL if other peer
3389  *                       connected to us
3390  * @param session session to use (or NULL)
3391  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
3392  */
3393 int
3394 GST_neighbours_handle_connect_ack (const struct GNUNET_MessageHeader *message,
3395                                    const struct GNUNET_PeerIdentity *peer,
3396                                    const struct GNUNET_HELLO_Address *address,
3397                                    struct Session *session)
3398 {
3399   const struct SessionConnectMessage *scm;
3400   struct GNUNET_TIME_Absolute ts;
3401   struct NeighbourMapEntry *n;
3402
3403   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3404               "Received CONNECT_ACK message from peer `%s'\n",
3405               GNUNET_i2s (peer));
3406
3407   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
3408   {
3409     GNUNET_break_op (0);
3410     return GNUNET_SYSERR;
3411   }
3412   GNUNET_STATISTICS_update (GST_stats,
3413                             gettext_noop
3414                             ("# CONNECT_ACK messages received"),
3415                             1, GNUNET_NO);
3416   scm = (const struct SessionConnectMessage *) message;
3417   GNUNET_break_op (ntohl (scm->reserved) == 0);
3418   if (NULL == (n = lookup_neighbour (peer)))
3419   {
3420     GNUNET_STATISTICS_update (GST_stats,
3421                               gettext_noop
3422                               ("# unexpected CONNECT_ACK messages (no peer)"),
3423                               1, GNUNET_NO);
3424     return GNUNET_SYSERR;
3425   }
3426   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
3427   switch (n->state)
3428   {
3429   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3430     GNUNET_break (0);
3431     free_neighbour (n, GNUNET_NO);
3432     return GNUNET_SYSERR;
3433   case GNUNET_TRANSPORT_PS_INIT_ATS:
3434     GNUNET_STATISTICS_update (GST_stats,
3435                               gettext_noop
3436                               ("# unexpected CONNECT_ACK messages (not ready)"),
3437                               1, GNUNET_NO);
3438     break;
3439   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
3440     if (ts.abs_value_us != n->primary_address.connect_timestamp.abs_value_us)
3441     {
3442       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3443                   "CONNECT_ACK ignored as the timestamp does not match our CONNECT request\n");
3444       return GNUNET_OK;
3445     }
3446     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED,
3447         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3448     GNUNET_STATISTICS_set (GST_stats,
3449                            gettext_noop ("# peers connected"),
3450                            ++neighbours_connected,
3451                            GNUNET_NO);
3452     connect_notify_cb (callback_cls, &n->id,
3453                        n->primary_address.bandwidth_in,
3454                        n->primary_address.bandwidth_out);
3455     /* Tell ATS that the outbound session we created to send CONNECT was successful */
3456     GST_ats_add_address (n->primary_address.address,
3457                          n->primary_address.session,
3458                          NULL, 0);
3459     set_primary_address (n,
3460                  n->primary_address.address,
3461                  n->primary_address.session,
3462                  n->primary_address.bandwidth_in,
3463                  n->primary_address.bandwidth_out,
3464                  GNUNET_YES);
3465     send_session_ack_message (n);
3466     break;
3467   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
3468   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
3469   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
3470   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
3471     GNUNET_STATISTICS_update (GST_stats,
3472                               gettext_noop
3473                               ("# unexpected CONNECT_ACK messages (not ready)"),
3474                               1, GNUNET_NO);
3475     break;
3476   case GNUNET_TRANSPORT_PS_CONNECTED:
3477     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
3478     send_session_ack_message (n);
3479     break;
3480   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3481   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
3482     /* we didn't expect any CONNECT_ACK, as we are waiting for ATS
3483        to give us a new address... */
3484     GNUNET_STATISTICS_update (GST_stats,
3485                               gettext_noop
3486                               ("# unexpected CONNECT_ACK messages (waiting on ATS)"),
3487                               1, GNUNET_NO);
3488     break;
3489   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3490     /* new address worked; go back to connected! */
3491     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED,
3492         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3493     send_session_ack_message (n);
3494     break;
3495   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
3496     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
3497     send_session_ack_message (n);
3498     break;
3499   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
3500     /* new address worked; adopt it and go back to connected! */
3501     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED,
3502         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3503     GNUNET_break (GNUNET_NO == n->alternative_address.ats_active);
3504
3505     GST_ats_add_address (n->alternative_address.address,
3506                          n->alternative_address.session,
3507                          NULL, 0);
3508     set_primary_address (n, n->alternative_address.address,
3509         n->alternative_address.session, n->alternative_address.bandwidth_in,
3510         n->alternative_address.bandwidth_out, GNUNET_YES);
3511
3512     free_address (&n->alternative_address);
3513     send_session_ack_message (n);
3514     break;
3515   case GNUNET_TRANSPORT_PS_DISCONNECT:
3516     GNUNET_STATISTICS_update (GST_stats,
3517                               gettext_noop
3518                               ("# unexpected CONNECT_ACK messages (disconnecting)"),
3519                               1, GNUNET_NO);
3520     return GNUNET_SYSERR;
3521   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3522     GNUNET_assert (0);
3523     break;
3524   default:
3525     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3526                 "Unhandled state `%s'\n",
3527                 GNUNET_TRANSPORT_ps2s (n->state));
3528     GNUNET_break (0);
3529     return GNUNET_SYSERR;
3530   }
3531   return GNUNET_OK;
3532 }
3533
3534
3535 /**
3536  * A session was terminated. Take note; if needed, try to get
3537  * an alternative address from ATS.
3538  *
3539  * @param peer identity of the peer where the session died
3540  * @param session session that is gone
3541  * @return #GNUNET_YES if this was a session used, #GNUNET_NO if
3542  *        this session was not in use
3543  */
3544 int
3545 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
3546                                    struct Session *session)
3547 {
3548   struct NeighbourMapEntry *n;
3549   struct BlackListCheckContext *bcc;
3550   struct BlackListCheckContext *bcc_next;
3551
3552   /* make sure to cancel all ongoing blacklist checks involving 'session' */
3553   bcc_next = bc_head;
3554   while (NULL != (bcc = bcc_next))
3555   {
3556     bcc_next = bcc->next;
3557     if (bcc->na.session == session)
3558     {
3559       if (NULL != bcc->bc)
3560         GST_blacklist_test_cancel (bcc->bc);
3561       GNUNET_HELLO_address_free (bcc->na.address);
3562       GNUNET_CONTAINER_DLL_remove (bc_head,
3563                                    bc_tail,
3564                                    bcc);
3565       GNUNET_free (bcc);
3566     }
3567   }
3568   if (NULL == (n = lookup_neighbour (peer)))
3569     return GNUNET_NO; /* can't affect us */
3570   if (session != n->primary_address.session)
3571   {
3572     if (session == n->alternative_address.session)
3573     {
3574       if ( (GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
3575            (GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT == n->state) )
3576         set_state (n, GNUNET_TRANSPORT_PS_CONNECTED);
3577       else
3578         GNUNET_break (0);
3579       free_address (&n->alternative_address);
3580     }
3581     return GNUNET_NO; /* doesn't affect us further */
3582   }
3583
3584   n->expect_latency_response = GNUNET_NO;
3585   /* The session for neighbour's primary address died */
3586   switch (n->state)
3587   {
3588   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3589     GNUNET_break (0);
3590     free_neighbour (n, GNUNET_NO);
3591     return GNUNET_YES;
3592   case GNUNET_TRANSPORT_PS_INIT_ATS:
3593     GNUNET_break (0);
3594     free_neighbour (n, GNUNET_NO);
3595     return GNUNET_YES;
3596   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
3597     /* The session used to send the CONNECT terminated:
3598      * this implies a connect error*/
3599     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3600                 "Could not send CONNECT message with address `%s' session %p: session terminated, requesting new address\n",
3601                 GST_plugins_a2s (n->primary_address.address), n->primary_address.session,
3602                 GNUNET_i2s (peer));
3603     GNUNET_ATS_address_destroyed (GST_ats, n->primary_address.address, NULL);
3604     unset_primary_address (n);
3605     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
3606         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3607     break;
3608   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
3609   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
3610   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
3611   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
3612     /* error on inbound session; free neighbour entirely */
3613     free_address (&n->primary_address);
3614     free_neighbour (n, GNUNET_NO);
3615     return GNUNET_YES;
3616   case GNUNET_TRANSPORT_PS_CONNECTED:
3617     unset_primary_address (n);
3618     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_ATS,
3619         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3620     break;
3621   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3622     /* we don't have an address, how can it go down? */
3623     GNUNET_break (0);
3624     break;
3625   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
3626   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3627     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_ATS, GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3628     break;
3629   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
3630     /* primary went down while we were checking secondary against
3631        blacklist, adopt secondary as primary */
3632     free_address (&n->primary_address);
3633     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST, GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT));
3634     n->primary_address = n->alternative_address;
3635     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
3636     break;
3637   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
3638     /* primary went down while we were waiting for CONNECT_ACK on secondary;
3639        secondary as primary */
3640     free_address (&n->primary_address);
3641     n->primary_address = n->alternative_address;
3642     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
3643     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_SENT, GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT));
3644     break;
3645   case GNUNET_TRANSPORT_PS_DISCONNECT:
3646     free_address (&n->primary_address);
3647     break;
3648   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3649     /* neighbour was freed and plugins told to terminate session */
3650     return GNUNET_NO;
3651     break;
3652   default:
3653     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3654                 "Unhandled state `%s'\n",
3655                 GNUNET_TRANSPORT_ps2s (n->state));
3656     GNUNET_break (0);
3657     break;
3658   }
3659   if (GNUNET_SCHEDULER_NO_TASK != n->task)
3660     GNUNET_SCHEDULER_cancel (n->task);
3661   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
3662   return GNUNET_YES;
3663 }
3664
3665
3666 /**
3667  * We received a 'SESSION_ACK' message from the other peer.
3668  * If we sent a 'CONNECT_ACK' last, this means we are now
3669  * connected.  Otherwise, do nothing.
3670  *
3671  * @param message possibly a 'struct SessionConnectMessage' (check format)
3672  * @param peer identity of the peer to switch the address for
3673  * @param address address of the other peer, NULL if other peer
3674  *                       connected to us
3675  * @param session session to use (or NULL)
3676  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
3677  */
3678 int
3679 GST_neighbours_handle_session_ack (const struct GNUNET_MessageHeader *message,
3680                                    const struct GNUNET_PeerIdentity *peer,
3681                                    const struct GNUNET_HELLO_Address *address,
3682                                    struct Session *session)
3683 {
3684   struct NeighbourMapEntry *n;
3685
3686   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3687               "Received SESSION_ACK message from peer `%s'\n",
3688               GNUNET_i2s (peer));
3689   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
3690   {
3691     GNUNET_break_op (0);
3692     return GNUNET_SYSERR;
3693   }
3694   GNUNET_STATISTICS_update (GST_stats,
3695                             gettext_noop
3696                             ("# SESSION_ACK messages received"),
3697                             1, GNUNET_NO);
3698   if (NULL == (n = lookup_neighbour (peer)))
3699   {
3700     GNUNET_break_op (0);
3701     return GNUNET_SYSERR;
3702   }
3703   /* check if we are in a plausible state for having sent
3704      a CONNECT_ACK.  If not, return, otherwise break */
3705   if ( ( (GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK != n->state) &&
3706          (GNUNET_TRANSPORT_PS_CONNECT_SENT != n->state) ) ||
3707        (ACK_SEND_SESSION_ACK != n->ack_state) )
3708   {
3709     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3710                 "Received SESSION_ACK message from peer `%s' in state %s/%s\n",
3711                 GNUNET_i2s (peer),
3712                 GNUNET_TRANSPORT_ps2s (n->state),
3713                 print_ack_state (n->ack_state));
3714     GNUNET_STATISTICS_update (GST_stats,
3715                               gettext_noop ("# unexpected SESSION_ACK messages"), 1,
3716                               GNUNET_NO);
3717     return GNUNET_OK;
3718   }
3719   set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED, GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3720   GNUNET_STATISTICS_set (GST_stats,
3721                          gettext_noop ("# peers connected"),
3722                          ++neighbours_connected,
3723                          GNUNET_NO);
3724   connect_notify_cb (callback_cls, &n->id,
3725                      n->primary_address.bandwidth_in,
3726                      n->primary_address.bandwidth_out);
3727
3728   GST_ats_add_address (n->primary_address.address,
3729                        n->primary_address.session,
3730                        NULL, 0);
3731   set_primary_address (n,
3732                n->primary_address.address,
3733                n->primary_address.session,
3734                n->primary_address.bandwidth_in,
3735                n->primary_address.bandwidth_out,
3736                GNUNET_YES);
3737   return GNUNET_OK;
3738 }
3739
3740
3741 /**
3742  * Test if we're connected to the given peer.
3743  *
3744  * @param target peer to test
3745  * @return #GNUNET_YES if we are connected, #GNUNET_NO if not
3746  */
3747 int
3748 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
3749 {
3750   return test_connected (lookup_neighbour (target));
3751 }
3752
3753 /**
3754  * Change the incoming quota for the given peer.
3755  *
3756  * @param neighbour identity of peer to change qutoa for
3757  * @param quota new quota
3758  */
3759 void
3760 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
3761                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
3762 {
3763   struct NeighbourMapEntry *n;
3764
3765   if (NULL == (n = lookup_neighbour (neighbour)))
3766   {
3767     GNUNET_STATISTICS_update (GST_stats,
3768                               gettext_noop
3769                               ("# SET QUOTA messages ignored (no such peer)"),
3770                               1, GNUNET_NO);
3771     return;
3772   }
3773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3774               "Setting inbound quota of %u Bps for peer `%s' to all clients\n",
3775               ntohl (quota.value__), GNUNET_i2s (&n->id));
3776   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
3777   if (0 != ntohl (quota.value__))
3778     return;
3779   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3780               "Disconnecting peer `%4s' due to SET_QUOTA\n",
3781               GNUNET_i2s (&n->id));
3782   if (GNUNET_YES == test_connected (n))
3783     GNUNET_STATISTICS_update (GST_stats,
3784                               gettext_noop ("# disconnects due to quota of 0"),
3785                               1, GNUNET_NO);
3786   disconnect_neighbour (n);
3787 }
3788
3789
3790 /**
3791  * We received a disconnect message from the given peer,
3792  * validate and process.
3793  *
3794  * @param peer sender of the message
3795  * @param msg the disconnect message
3796  */
3797 void
3798 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity *peer,
3799                                           const struct GNUNET_MessageHeader *msg)
3800 {
3801   struct NeighbourMapEntry *n;
3802   const struct SessionDisconnectMessage *sdm;
3803
3804   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3805               "Received DISCONNECT message from peer `%s'\n",
3806               GNUNET_i2s (peer));
3807   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
3808   {
3809     // GNUNET_break_op (0);
3810     GNUNET_STATISTICS_update (GST_stats,
3811                               gettext_noop
3812                               ("# disconnect messages ignored (old format)"), 1,
3813                               GNUNET_NO);
3814     return;
3815   }
3816   GNUNET_STATISTICS_update (GST_stats,
3817                             gettext_noop
3818                             ("# DISCONNECT messages received"),
3819                             1, GNUNET_NO);
3820   sdm = (const struct SessionDisconnectMessage *) msg;
3821   if (NULL == (n = lookup_neighbour (peer)))
3822     return;                     /* gone already */
3823   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value_us <= n->connect_ack_timestamp.abs_value_us)
3824   {
3825     GNUNET_STATISTICS_update (GST_stats,
3826                               gettext_noop
3827                               ("# disconnect messages ignored (timestamp)"), 1,
3828                               GNUNET_NO);
3829     return;
3830   }
3831   if (0 != memcmp (peer, &sdm->public_key, sizeof (struct GNUNET_PeerIdentity)))
3832   {
3833     GNUNET_break_op (0);
3834     return;
3835   }
3836   if (ntohl (sdm->purpose.size) !=
3837       sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
3838       sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
3839       sizeof (struct GNUNET_TIME_AbsoluteNBO))
3840   {
3841     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3842                 "%s message from peer `%s' has invalid size \n",
3843                 "DISCONNECT",
3844                 GNUNET_i2s (peer));
3845     GNUNET_break_op (0);
3846     return;
3847   }
3848   if (GNUNET_OK !=
3849       GNUNET_CRYPTO_eddsa_verify
3850       (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT, &sdm->purpose,
3851        &sdm->signature, &sdm->public_key))
3852   {
3853     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3854                 "%s message from peer `%s' cannot be verified \n",
3855                 "DISCONNECT",
3856                 GNUNET_i2s (peer));
3857     GNUNET_break_op (0);
3858     return;
3859   }
3860   if (GNUNET_YES == test_connected (n))
3861     GNUNET_STATISTICS_update (GST_stats,
3862                               gettext_noop
3863                               ("# other peer asked to disconnect from us"), 1,
3864                               GNUNET_NO);
3865   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3866               "Disconnecting by request from peer %s\n",
3867               GNUNET_i2s (peer));
3868   disconnect_neighbour (n);
3869 }
3870
3871
3872 /**
3873  * Closure for the neighbours_iterate function.
3874  */
3875 struct IteratorContext
3876 {
3877   /**
3878    * Function to call on each connected neighbour.
3879    */
3880   GST_NeighbourIterator cb;
3881
3882   /**
3883    * Closure for 'cb'.
3884    */
3885   void *cb_cls;
3886 };
3887
3888
3889 /**
3890  * Call the callback from the closure for each neighbour.
3891  *
3892  * @param cls the `struct IteratorContext`
3893  * @param key the hash of the public key of the neighbour
3894  * @param value the `struct NeighbourMapEntry`
3895  * @return #GNUNET_OK (continue to iterate)
3896  */
3897 static int
3898 neighbours_iterate (void *cls,
3899                     const struct GNUNET_PeerIdentity *key,
3900                     void *value)
3901 {
3902   struct IteratorContext *ic = cls;
3903   struct NeighbourMapEntry *n = value;
3904   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
3905   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
3906
3907
3908   if (NULL != n->primary_address.address)
3909   {
3910     bandwidth_in = n->primary_address.bandwidth_in;
3911     bandwidth_out = n->primary_address.bandwidth_out;
3912   }
3913   else
3914   {
3915     bandwidth_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
3916     bandwidth_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
3917   }
3918   ic->cb (ic->cb_cls,
3919           &n->id,
3920           n->primary_address.address,
3921           n->state,
3922           n->timeout,
3923           bandwidth_in, bandwidth_out);
3924   return GNUNET_OK;
3925 }
3926
3927
3928 /**
3929  * Iterate over all connected neighbours.
3930  *
3931  * @param cb function to call
3932  * @param cb_cls closure for cb
3933  */
3934 void
3935 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
3936 {
3937   struct IteratorContext ic;
3938
3939   if (NULL == neighbours)
3940     return; /* can happen during shutdown */
3941   ic.cb = cb;
3942   ic.cb_cls = cb_cls;
3943   GNUNET_CONTAINER_multipeermap_iterate (neighbours, &neighbours_iterate, &ic);
3944 }
3945
3946
3947 /**
3948  * If we have an active connection to the given target, it must be shutdown.
3949  *
3950  * @param target peer to disconnect from
3951  */
3952 void
3953 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
3954 {
3955   struct NeighbourMapEntry *n;
3956
3957   if (NULL == (n = lookup_neighbour (target)))
3958     return;  /* not active */
3959   if (GNUNET_YES == test_connected (n))
3960     GNUNET_STATISTICS_update (GST_stats,
3961                               gettext_noop
3962                               ("# disconnected from peer upon explicit request"), 1,
3963                               GNUNET_NO);
3964   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3965               "Forced disconnect from peer %s\n",
3966               GNUNET_i2s (target));
3967   disconnect_neighbour (n);
3968 }
3969
3970
3971 /**
3972  * Obtain current latency information for the given neighbour.
3973  *
3974  * @param peer to get the latency for
3975  * @return observed latency of the address, FOREVER if the
3976  *         the connection is not up
3977  */
3978 struct GNUNET_TIME_Relative
3979 GST_neighbour_get_latency (const struct GNUNET_PeerIdentity *peer)
3980 {
3981   struct NeighbourMapEntry *n;
3982
3983   n = lookup_neighbour (peer);
3984   if (NULL == n)
3985     return GNUNET_TIME_UNIT_FOREVER_REL;
3986   switch (n->state)
3987   {
3988   case GNUNET_TRANSPORT_PS_CONNECTED:
3989   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
3990   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
3991   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3992   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3993   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
3994     return n->latency;
3995   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3996   case GNUNET_TRANSPORT_PS_INIT_ATS:
3997   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
3998   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
3999   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
4000   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
4001   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
4002   case GNUNET_TRANSPORT_PS_DISCONNECT:
4003   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
4004     return GNUNET_TIME_UNIT_FOREVER_REL;
4005   default:
4006     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4007                 "Unhandled state `%s'\n",
4008                 GNUNET_TRANSPORT_ps2s (n->state));
4009     GNUNET_break (0);
4010     break;
4011   }
4012   return GNUNET_TIME_UNIT_FOREVER_REL;
4013 }
4014
4015
4016 /**
4017  * Obtain current address information for the given neighbour.
4018  *
4019  * @param peer
4020  * @return address currently used
4021  */
4022 struct GNUNET_HELLO_Address *
4023 GST_neighbour_get_current_address (const struct GNUNET_PeerIdentity *peer)
4024 {
4025   struct NeighbourMapEntry *n;
4026
4027   n = lookup_neighbour (peer);
4028   if (NULL == n)
4029     return NULL;
4030   return n->primary_address.address;
4031 }
4032
4033
4034 /**
4035  * Initialize the neighbours subsystem.
4036  *
4037  * @param cls closure for callbacks
4038  * @param connect_cb function to call if we connect to a peer
4039  * @param disconnect_cb function to call if we disconnect from a peer
4040  * @param peer_address_cb function to call if we change an active address
4041  *                   of a neighbour
4042  * @param max_fds maximum number of fds to use
4043  */
4044 void
4045 GST_neighbours_start (void *cls,
4046                       NotifyConnect connect_cb,
4047                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb,
4048                       GNUNET_TRANSPORT_NeighbourChangeCallback peer_address_cb,
4049                       unsigned int max_fds)
4050 {
4051   callback_cls = cls;
4052   connect_notify_cb = connect_cb;
4053   disconnect_notify_cb = disconnect_cb;
4054   neighbour_change_cb = peer_address_cb;
4055   neighbours = GNUNET_CONTAINER_multipeermap_create (NEIGHBOUR_TABLE_SIZE, GNUNET_NO);
4056   registered_quota_notifications = GNUNET_CONTAINER_multipeermap_create (NEIGHBOUR_TABLE_SIZE, GNUNET_NO);
4057   util_transmission_tk = GNUNET_SCHEDULER_add_delayed (UTIL_TRANSMISSION_INTERVAL,
4058       utilization_transmission, NULL);
4059 }
4060
4061
4062 /**
4063  * Disconnect from the given neighbour.
4064  *
4065  * @param cls unused
4066  * @param key hash of neighbour's public key (not used)
4067  * @param value the 'struct NeighbourMapEntry' of the neighbour
4068  * @return #GNUNET_OK (continue to iterate)
4069  */
4070 static int
4071 disconnect_all_neighbours (void *cls,
4072                            const struct GNUNET_PeerIdentity *key,
4073                            void *value)
4074 {
4075   struct NeighbourMapEntry *n = value;
4076
4077   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4078               "Disconnecting peer `%4s', %s\n",
4079               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
4080   free_neighbour (n, GNUNET_NO);
4081   return GNUNET_OK;
4082 }
4083
4084
4085 /**
4086  * Cleanup the neighbours subsystem.
4087  */
4088 void
4089 GST_neighbours_stop ()
4090 {
4091   struct BlacklistCheckSwitchContext *cur;
4092   struct BlacklistCheckSwitchContext *next;
4093
4094   if (NULL == neighbours)
4095     return;
4096   if (GNUNET_SCHEDULER_NO_TASK != util_transmission_tk)
4097   {
4098     GNUNET_SCHEDULER_cancel (util_transmission_tk);
4099     util_transmission_tk = GNUNET_SCHEDULER_NO_TASK;
4100   }
4101
4102   GNUNET_CONTAINER_multipeermap_iterate (neighbours,
4103                                          &disconnect_all_neighbours,
4104                                          NULL);
4105   GNUNET_CONTAINER_multipeermap_destroy (neighbours);
4106
4107   next = pending_bc_head;
4108   for (cur = next; NULL != cur; cur = next )
4109   {
4110     next = cur->next;
4111     GNUNET_CONTAINER_DLL_remove (pending_bc_head, pending_bc_tail, cur);
4112
4113     if (NULL != cur->blc)
4114     {
4115       GST_blacklist_test_cancel (cur->blc);
4116       cur->blc = NULL;
4117     }
4118     if (NULL != cur->address)
4119       GNUNET_HELLO_address_free (cur->address);
4120     GNUNET_free_non_null (cur->ats);
4121     GNUNET_free (cur);
4122   }
4123
4124   GNUNET_CONTAINER_multipeermap_iterate (registered_quota_notifications,
4125       &free_notification_cb, NULL);
4126   GNUNET_CONTAINER_multipeermap_destroy (registered_quota_notifications);
4127   registered_quota_notifications = NULL;
4128
4129   neighbours = NULL;
4130   callback_cls = NULL;
4131   connect_notify_cb = NULL;
4132   disconnect_notify_cb = NULL;
4133   neighbour_change_cb = NULL;
4134 }
4135
4136
4137 /* end of file gnunet-service-transport_neighbours.c */