5ce09223cbc7dd1eb5b07928cd265ec3f59d932d
[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 /**
1680  * Send a SESSION_CONNECT message via the given address.
1681  *
1682  * @param na address to use
1683  */
1684 static void
1685 send_session_connect (struct NeighbourAddress *na)
1686 {
1687   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1688   struct SessionConnectMessage connect_msg;
1689   struct NeighbourMapEntry *n;
1690
1691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1692               "Sending SESSION_CONNECT message to peer %s\n",
1693               GNUNET_i2s (&na->address->peer));
1694   if (NULL == (papi = GST_plugins_find (na->address->transport_name)))
1695   {
1696     GNUNET_break (0);
1697     return;
1698   }
1699   if (NULL == na->session)
1700     na->session = papi->get_session (papi->cls, na->address);
1701   if (NULL == na->session)
1702   {
1703     GNUNET_break (0);
1704     return;
1705   }
1706   GNUNET_STATISTICS_update (GST_stats,
1707                             gettext_noop
1708                             ("# SESSION_CONNECT messages sent"),
1709                             1, GNUNET_NO);
1710   na->connect_timestamp = GNUNET_TIME_absolute_get ();
1711   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1712   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1713   connect_msg.reserved = htonl (0);
1714   connect_msg.timestamp = GNUNET_TIME_absolute_hton (na->connect_timestamp);
1715   if (-1 ==
1716       papi->send (papi->cls,
1717                   na->session,
1718                   (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1719                   UINT_MAX,
1720                   SETUP_CONNECTION_TIMEOUT,
1721                   send_session_connect_cont, NULL))
1722   {
1723     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1724                 _("Failed to transmit CONNECT message via plugin to %s\n"),
1725                 GST_plugins_a2s (na->address));
1726
1727     n = lookup_neighbour (&na->address->peer);
1728     if (NULL == n)
1729     {
1730       GNUNET_break (0);
1731       return;
1732     }
1733     /* Hard failure to send the CONNECT message with this address:
1734        Destroy address and session */
1735     GNUNET_ATS_address_destroyed (GST_ats, na->address, na->session);
1736     GNUNET_ATS_address_destroyed (GST_ats, na->address, NULL);
1737
1738     /* Remove address and request and additional one */
1739     unset_primary_address (n);
1740     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
1741         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
1742     return;
1743   }
1744
1745   GST_neighbours_notify_data_sent (&na->address->peer,
1746                                    na->address,
1747                                    na->session,
1748                                    sizeof (struct SessionConnectMessage));
1749
1750 }
1751
1752
1753 /**
1754  * Send a CONNECT_ACK message via the given address.
1755  *
1756  * @param address address to use
1757  * @param session session to use
1758  * @param timestamp timestamp to use for the ACK message
1759  */
1760 static void
1761 send_connect_ack_message (const struct GNUNET_HELLO_Address *address,
1762                                   struct Session *session,
1763                                   struct GNUNET_TIME_Absolute timestamp)
1764 {
1765   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1766   struct SessionConnectMessage connect_msg;
1767   struct NeighbourMapEntry *n;
1768
1769   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1770               "Sending CONNECT_ACK to peer `%s'\n",
1771               GNUNET_i2s (&address->peer));
1772   if (NULL == (papi = GST_plugins_find (address->transport_name)))
1773   {
1774     GNUNET_break (0);
1775     return;
1776   }
1777   if (NULL == session)
1778     session = papi->get_session (papi->cls, address);
1779   if (NULL == session)
1780   {
1781     GNUNET_break (0);
1782     return;
1783   }
1784   GNUNET_STATISTICS_update (GST_stats,
1785                             gettext_noop
1786                             ("# CONNECT_ACK messages sent"),
1787                             1, GNUNET_NO);
1788   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1789   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK);
1790   connect_msg.reserved = htonl (0);
1791   connect_msg.timestamp = GNUNET_TIME_absolute_hton (timestamp);
1792
1793   if (GNUNET_SYSERR == papi->send (papi->cls,
1794                      session,
1795                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1796                      UINT_MAX,
1797                      GNUNET_TIME_UNIT_FOREVER_REL,
1798                      NULL, NULL))
1799   {
1800     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1801                 _("Failed to transmit CONNECT_ACK message via plugin to %s\n"),
1802                 GST_plugins_a2s (address));
1803
1804     n = lookup_neighbour (&address->peer);
1805     if (NULL == n)
1806     {
1807       GNUNET_break (0);
1808       return;
1809     }
1810     /* Hard failure to send the CONNECT_ACK message with this address:
1811        Destroy session (and address)  */
1812     if (GNUNET_YES == GNUNET_HELLO_address_check_option(address,
1813         GNUNET_HELLO_ADDRESS_INFO_INBOUND))
1814     {
1815       GNUNET_ATS_address_destroyed (GST_ats, address, session);
1816       GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
1817     }
1818     else
1819     {
1820       GNUNET_ATS_address_destroyed (GST_ats, address, session);
1821     }
1822
1823     /* Remove address and request and additional one */
1824     unset_primary_address (n);
1825     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
1826         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
1827     return;
1828   }
1829
1830 }
1831
1832 struct QuotaNotificationRequest
1833 {
1834   struct GNUNET_PeerIdentity peer;
1835   struct Session *session;
1836   char *plugin;
1837 };
1838
1839 struct QNR_LookContext
1840 {
1841   struct GNUNET_PeerIdentity peer;
1842   struct Session *session;
1843   const char *plugin;
1844
1845   struct QuotaNotificationRequest *res;
1846 };
1847
1848 static int
1849 find_notification_request (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1850 {
1851   struct QNR_LookContext *qnr_ctx = cls;
1852   struct QuotaNotificationRequest *qnr = value;
1853
1854   if ((qnr->session == qnr_ctx->session) &&
1855       (0 == memcmp (&qnr->peer, &qnr_ctx->peer, sizeof (struct GNUNET_PeerIdentity))) &&
1856       (0 == strcmp(qnr_ctx->plugin, qnr->plugin)))
1857   {
1858     qnr_ctx->res = value;
1859     return GNUNET_NO;
1860   }
1861   return GNUNET_YES;
1862 }
1863
1864 void
1865 GST_neighbours_register_quota_notification(void *cls,
1866     const struct GNUNET_PeerIdentity *peer, const char *plugin,
1867     struct Session *session)
1868 {
1869   struct QuotaNotificationRequest *qnr;
1870   struct QNR_LookContext qnr_ctx;
1871
1872   if (NULL == registered_quota_notifications)
1873   {
1874     return; /* init or shutdown */
1875   }
1876
1877   qnr_ctx.peer = (*peer);
1878   qnr_ctx.plugin = plugin;
1879   qnr_ctx.session = session;
1880   qnr_ctx.res = NULL;
1881
1882   GNUNET_CONTAINER_multipeermap_get_multiple (registered_quota_notifications,
1883       peer, &find_notification_request, &qnr_ctx);
1884   if (NULL != qnr_ctx.res)
1885   {
1886     GNUNET_break(0);
1887     return;
1888   }
1889
1890   qnr = GNUNET_new (struct QuotaNotificationRequest);
1891   qnr->peer =  (*peer);
1892   qnr->plugin = GNUNET_strdup (plugin);
1893   qnr->session = session;
1894
1895   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1896       "Adding notification for peer `%s' plugin `%s' session %p \n",
1897       GNUNET_i2s (peer), plugin, session);
1898
1899   GNUNET_CONTAINER_multipeermap_put (registered_quota_notifications, peer,
1900       qnr, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1901 }
1902
1903
1904 void
1905 GST_neighbours_unregister_quota_notification(void *cls,
1906     const struct GNUNET_PeerIdentity *peer, const char *plugin, struct Session *session)
1907 {
1908   struct QNR_LookContext qnr_ctx;
1909
1910   if (NULL == registered_quota_notifications)
1911   {
1912     return; /* init or shutdown */
1913   }
1914
1915   qnr_ctx.peer = (*peer);
1916   qnr_ctx.plugin = plugin;
1917   qnr_ctx.session = session;
1918   qnr_ctx.res = NULL;
1919
1920   GNUNET_CONTAINER_multipeermap_iterate (registered_quota_notifications,
1921       &find_notification_request, &qnr_ctx);
1922   if (NULL == qnr_ctx.res)
1923   {
1924     GNUNET_break(0);
1925     return;
1926   }
1927
1928   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1929       "Removing notification for peer `%s' plugin `%s' session %p \n",
1930       GNUNET_i2s (peer), plugin, session);
1931
1932   GNUNET_CONTAINER_multipeermap_remove (registered_quota_notifications, peer,
1933       qnr_ctx.res);
1934   GNUNET_free (qnr_ctx.res->plugin);
1935   GNUNET_free (qnr_ctx.res);
1936 }
1937
1938 static int
1939 notification_cb(void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1940 {
1941   /* struct NeighbourMapEntry *n = cls; */
1942   struct QuotaNotificationRequest *qnr = value;
1943   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1944   struct GNUNET_TIME_Relative delay;
1945   int do_forward;
1946
1947   papi = GST_plugins_find(qnr->plugin);
1948   if (NULL == papi)
1949   {
1950     GNUNET_break (0);
1951     return GNUNET_OK;
1952   }
1953
1954   delay = GST_neighbours_calculate_receive_delay (key, 0, &do_forward);
1955   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1956       "New inbound delay for peer `%s' is %llu ms\n", GNUNET_i2s (key),
1957       delay.rel_value_us / 1000);
1958
1959   if (NULL != papi->update_inbound_delay)
1960     papi->update_inbound_delay (papi->cls, key, qnr->session, delay);
1961   return GNUNET_OK;
1962 }
1963
1964 static
1965 int
1966 free_notification_cb(void *cls, const struct GNUNET_PeerIdentity *key,
1967     void *value)
1968 {
1969   /* struct NeighbourMapEntry *n = cls; */
1970   struct QuotaNotificationRequest *qnr = value;
1971
1972   GNUNET_CONTAINER_multipeermap_remove (registered_quota_notifications, key,
1973       qnr);
1974   GNUNET_free(qnr->plugin);
1975   GNUNET_free(qnr);
1976
1977   return GNUNET_OK;
1978 }
1979
1980 static void
1981 inbound_bw_tracker_update(void *cls)
1982 {
1983   struct NeighbourMapEntry *n = cls;
1984
1985   /* Quota was updated, tell plugins to update the time to receive next */
1986   GNUNET_CONTAINER_multipeermap_get_multiple (registered_quota_notifications,
1987       &n->id, &notification_cb, n);
1988 }
1989
1990
1991 /**
1992  * Create a fresh entry in the neighbour map for the given peer
1993  *
1994  * @param peer peer to create an entry for
1995  * @return new neighbour map entry
1996  */
1997 static struct NeighbourMapEntry *
1998 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
1999 {
2000   struct NeighbourMapEntry *n;
2001
2002   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2003               "Creating new neighbour entry for `%s'\n",
2004               GNUNET_i2s (peer));
2005   n = GNUNET_new (struct NeighbourMapEntry);
2006   n->id = *peer;
2007   n->ack_state = ACK_UNDEFINED;
2008   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2009   n->last_util_transmission = GNUNET_TIME_absolute_get();
2010   n->util_payload_bytes_recv = 0;
2011   n->util_payload_bytes_sent = 0;
2012   n->util_total_bytes_recv = 0;
2013   n->util_total_bytes_sent = 0;
2014   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker, &inbound_bw_tracker_update, n,
2015                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2016                                  MAX_BANDWIDTH_CARRY_S);
2017   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
2018   set_state_and_timeout (n, GNUNET_TRANSPORT_PS_NOT_CONNECTED, GNUNET_TIME_UNIT_FOREVER_ABS);
2019   GNUNET_assert (GNUNET_OK ==
2020                  GNUNET_CONTAINER_multipeermap_put (neighbours,
2021                                                     &n->id, n,
2022                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2023   return n;
2024 }
2025
2026
2027 /**
2028  * Check if the two given addresses are the same.
2029  * Actually only checks if the sessions are non-NULL
2030  * (which they should be) and then if they are identical;
2031  * the actual addresses don't matter if the session
2032  * pointers match anyway, and we must have session pointers
2033  * at this time.
2034  *
2035  * @param a1 first address to compare
2036  * @param a2 other address to compare
2037  * @return #GNUNET_NO if the addresses do not match, #GNUNET_YES if they do match
2038  */
2039 static int
2040 address_matches (const struct NeighbourAddress *a1,
2041                  const struct NeighbourAddress *a2)
2042 {
2043   if ( (NULL == a1->session) ||
2044        (NULL == a2->session) )
2045   {
2046     GNUNET_break (0);
2047     return 0;
2048   }
2049   return (a1->session == a2->session) ? GNUNET_YES : GNUNET_NO;
2050 }
2051
2052
2053 /* We received a address suggestion after requesting an address in
2054  * try_connect or after receiving a connect, switch to address
2055  */
2056 static void
2057 address_suggest_cont (void *cls,
2058     const struct GNUNET_PeerIdentity *peer,
2059     const struct GNUNET_HELLO_Address *address, struct Session *session,
2060     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
2061     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
2062     const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
2063 {
2064   GST_neighbours_switch_to_address(peer, address, session, ats, ats_count,
2065       bandwidth_in, bandwidth_out);
2066 }
2067
2068
2069 struct BlacklistCheckSwitchContext
2070 {
2071   struct BlacklistCheckSwitchContext *prev;
2072   struct BlacklistCheckSwitchContext *next;
2073
2074
2075   struct GST_BlacklistCheck *blc;
2076
2077   struct GNUNET_HELLO_Address *address;
2078   struct Session *session;
2079   struct GNUNET_ATS_Information *ats;
2080   uint32_t ats_count;
2081
2082   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
2083   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
2084 };
2085
2086 /**
2087  * Black list check result for try_connect call
2088  * If connection to the peer is allowed request adddress and
2089  *
2090  * @param cls blc_ctx bl context
2091  * @param peer the peer
2092  * @param result the result
2093  */
2094 static void
2095 try_connect_bl_check_cont (void *cls,
2096     const struct GNUNET_PeerIdentity *peer, int result)
2097 {
2098   struct BlacklistCheckSwitchContext *blc_ctx = cls;
2099   struct NeighbourMapEntry *n;
2100
2101   GNUNET_CONTAINER_DLL_remove (pending_bc_head, pending_bc_tail, blc_ctx);
2102   GNUNET_free (blc_ctx);
2103
2104   if (GNUNET_OK != result)
2105   {
2106     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2107         _("Blacklisting disapproved to connect to peer `%s'\n"),
2108         GNUNET_i2s (peer));
2109     return;
2110   }
2111
2112   /* Setup a new neighbour */
2113   n = setup_neighbour (peer);
2114
2115   /* Request address suggestions for this peer */
2116   set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
2117       GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
2118   GNUNET_ATS_reset_backoff (GST_ats, peer);
2119   n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, peer,
2120       &address_suggest_cont, n);
2121 }
2122
2123
2124
2125 /**
2126  * Try to create a connection to the given target (eventually).
2127  *
2128  * @param target peer to try to connect to
2129  */
2130 void
2131 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
2132 {
2133   struct NeighbourMapEntry *n;
2134   struct GST_BlacklistCheck *blc;
2135   struct BlacklistCheckSwitchContext *blc_ctx;
2136
2137   if (NULL == neighbours)
2138   {
2139     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2140                 "Asked to connect to peer `%s' during shutdown\n",
2141                 GNUNET_i2s (target));
2142     return; /* during shutdown, do nothing */
2143   }
2144   n = lookup_neighbour (target);
2145   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2146               "Asked to connect to peer `%s' (state: %s)\n",
2147               GNUNET_i2s (target),
2148               (NULL != n) ? GNUNET_TRANSPORT_ps2s(n->state) : "NEW PEER");
2149   if (NULL != n)
2150   {
2151     switch (n->state)
2152     {
2153     case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
2154       /* this should not be possible */
2155       GNUNET_break (0);
2156       free_neighbour (n, GNUNET_NO);
2157       break;
2158     case GNUNET_TRANSPORT_PS_INIT_ATS:
2159     case GNUNET_TRANSPORT_PS_CONNECT_SENT:
2160     case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
2161     case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
2162     case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
2163     case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
2164       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2165                   "Ignoring request to try to connect to `%s', already trying!\n",
2166                   GNUNET_i2s (target));
2167       return; /* already trying */
2168     case GNUNET_TRANSPORT_PS_CONNECTED:
2169     case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
2170     case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
2171     case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
2172     case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
2173     case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
2174       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2175                   "Ignoring request to try to connect, already connected to `%s'!\n",
2176                   GNUNET_i2s (target));
2177       return; /* already connected */
2178     case GNUNET_TRANSPORT_PS_DISCONNECT:
2179       /* get rid of remains, ready to re-try immediately */
2180       free_neighbour (n, GNUNET_NO);
2181       break;
2182     case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
2183       /* should not be possible */
2184       GNUNET_assert (0);
2185     default:
2186       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2187                   "Unhandled state `%s'\n",
2188                   GNUNET_TRANSPORT_ps2s (n->state));
2189       GNUNET_break (0);
2190       free_neighbour (n, GNUNET_NO);
2191       break;
2192     }
2193   }
2194
2195   /* Do blacklist check if connecting to this peer is allowed */
2196   blc_ctx = GNUNET_new (struct BlacklistCheckSwitchContext);
2197   GNUNET_CONTAINER_DLL_insert (pending_bc_head, pending_bc_tail, blc_ctx);
2198
2199   if (NULL != (blc = GST_blacklist_test_allowed (target, NULL,
2200         &try_connect_bl_check_cont, blc_ctx)))
2201   {
2202     blc_ctx->blc = blc;
2203   }
2204 }
2205
2206
2207 /**
2208  * Function called with the result of a blacklist check.
2209  *
2210  * @param cls closure with the `struct BlackListCheckContext`
2211  * @param peer peer this check affects
2212  * @param result #GNUNET_OK if the address is allowed
2213  */
2214 static void
2215 handle_connect_blacklist_check_cont (void *cls,
2216                             const struct GNUNET_PeerIdentity *peer,
2217                             int result)
2218 {
2219   struct BlackListCheckContext *bcc = cls;
2220   struct NeighbourMapEntry *n;
2221
2222   bcc->bc = NULL;
2223   GNUNET_CONTAINER_DLL_remove (bc_head,
2224                                bc_tail,
2225                                bcc);
2226   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2227               "Connection to new address of peer `%s' based on blacklist is `%s'\n",
2228               GNUNET_i2s (peer),
2229               (GNUNET_OK == result) ? "allowed" : "FORBIDDEN");
2230   if (GNUNET_OK == result)
2231   {
2232     /* Blacklist agreed on connecting to a peer with this address */
2233     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2234         "Notifying ATS peer's `%s' %s address `%s' session %p\n",
2235         GNUNET_i2s (peer),
2236         (GNUNET_YES == GNUNET_HELLO_address_check_option(bcc->na.address,
2237             GNUNET_HELLO_ADDRESS_INFO_INBOUND)) ? "inbound" : "outbound",
2238         GST_plugins_a2s (bcc->na.address), bcc->na.session);
2239     GST_ats_add_address (bcc->na.address, bcc->na.session, NULL, 0);
2240   }
2241
2242   if (NULL == (n = lookup_neighbour (peer)))
2243   {
2244     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2245                 "No neighbor entry for peer `%s', ignoring blacklist result\n",
2246                 GNUNET_i2s (peer));
2247     goto cleanup; /* nobody left to care about new address */
2248   }
2249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2250               "Received connect blacklist check result for peer `%s' in state %s/%s\n",
2251               GNUNET_i2s (peer),
2252               GNUNET_TRANSPORT_ps2s (n->state),
2253               print_ack_state (n->ack_state));
2254   switch (n->state)
2255   {
2256   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
2257     /* this should not be possible */
2258     GNUNET_break (0);
2259     free_neighbour (n, GNUNET_NO);
2260     break;
2261   case GNUNET_TRANSPORT_PS_INIT_ATS:
2262     /* waiting on ATS suggestion; still, pass address to ATS as a
2263        possibility */
2264     break;
2265   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
2266 #if 0
2267     /* TODO Why should I send an connect ACK message */
2268     /* waiting on CONNECT_ACK, send ACK if one is pending */
2269
2270     if ( (GNUNET_OK == result) &&
2271          (ACK_SEND_CONNECT_ACK == n->ack_state) )
2272     {
2273       n->ack_state = ACK_SEND_SESSION_ACK;
2274       send_connect_ack_message (n->primary_address.address,
2275                                         n->primary_address.session,
2276                                         n->connect_ack_timestamp);
2277     }
2278 #endif
2279     break;
2280   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
2281     if (GNUNET_OK == result)
2282     {
2283       /* We received a connect request and blacklist allowed to communicate
2284        * with this peer, request an address from ATS*/
2285       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS,
2286           GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
2287       GNUNET_ATS_reset_backoff (GST_ats, peer);
2288       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2289                   "Requesting address for peer %s to ATS\n",
2290                   GNUNET_i2s (peer));
2291       if (NULL == n->suggest_handle)
2292         n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, peer,
2293             &address_suggest_cont, n);
2294       else
2295         GNUNET_ATS_reset_backoff (GST_ats, peer);
2296     }
2297     else
2298     {
2299       /* FIXME: state handling required! */
2300     }
2301     break;
2302   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
2303     /* waiting on ATS suggestion, don't care about blacklist */
2304     break;
2305   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
2306     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
2307     {
2308       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2309                   "Blacklist result ignored, as it is not for our primary address\n");
2310       break; /* result for an address we currently don't care about */
2311     }
2312     if (GNUNET_OK == result)
2313     {
2314       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK,
2315           GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2316       send_connect_ack_message (bcc->na.address,
2317                                         bcc->na.session,
2318                                         n->connect_ack_timestamp);
2319       if (ACK_SEND_CONNECT_ACK == n->ack_state)
2320         n->ack_state = ACK_SEND_SESSION_ACK;
2321     }
2322     else
2323     {
2324       struct GNUNET_TRANSPORT_PluginFunctions *plugin;
2325
2326       plugin = GST_plugins_find (bcc->na.address->transport_name);
2327       if ( (NULL != plugin) &&
2328            (NULL != bcc->na.session) )
2329       {
2330         plugin->disconnect_session (plugin->cls,
2331                                     bcc->na.session);
2332         break;
2333       }
2334       GNUNET_break (NULL != plugin);
2335       free_address (&n->primary_address);
2336       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
2337           GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
2338       GNUNET_ATS_reset_backoff (GST_ats, peer);
2339     }
2340     break;
2341   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
2342     /* waiting on SESSION_ACK, send ACK if one is pending */
2343     if ( (GNUNET_OK == result) &&
2344          (ACK_SEND_CONNECT_ACK == n->ack_state) )
2345     {
2346       n->ack_state = ACK_SEND_SESSION_ACK;
2347       send_connect_ack_message (n->primary_address.address,
2348                                         n->primary_address.session,
2349                                         n->connect_ack_timestamp);
2350     }
2351     break;
2352   case GNUNET_TRANSPORT_PS_CONNECTED:
2353     /* already connected, don't care about blacklist */
2354     break;
2355   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
2356     /* still waiting on ATS suggestion, don't care about blacklist */
2357     break;
2358   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
2359     if ( (GNUNET_OK == result) &&
2360          (ACK_SEND_CONNECT_ACK == n->ack_state) )
2361     {
2362       n->ack_state = ACK_SEND_SESSION_ACK;
2363       send_connect_ack_message (bcc->na.address,
2364                                         bcc->na.session,
2365                                         n->connect_ack_timestamp);
2366     }
2367     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
2368     {
2369       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2370                   "Blacklist result ignored, as it is not for our primary address\n");
2371       break; /* result for an address we currently don't care about */
2372     }
2373     if (GNUNET_OK == result)
2374     {
2375       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_SENT,
2376           GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT));
2377       send_session_connect (&n->primary_address);
2378     }
2379     else
2380     {
2381       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_ATS,
2382           GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
2383     }
2384     break;
2385   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
2386     /* waiting on CONNECT_ACK, don't care about blacklist */
2387     if ( (GNUNET_OK == result) &&
2388          (ACK_SEND_CONNECT_ACK == n->ack_state) )
2389     {
2390       n->ack_state = ACK_SEND_SESSION_ACK;
2391       send_connect_ack_message (n->primary_address.address,
2392                                         n->primary_address.session,
2393                                         n->connect_ack_timestamp);
2394     }
2395     break;
2396   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
2397     if (GNUNET_YES != address_matches (&bcc->na, &n->alternative_address))
2398     {
2399       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2400                   "Blacklist result ignored, as it is not for our primary address\n");
2401       break; /* result for an address we currently don't care about */
2402     }
2403     if (GNUNET_OK == result)
2404     {
2405       send_session_connect (&n->alternative_address);
2406       set_state (n, GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT);
2407     }
2408     else
2409     {
2410       set_state(n, GNUNET_TRANSPORT_PS_CONNECTED);
2411       free_address (&n->alternative_address);
2412     }
2413     break;
2414   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
2415     /* waiting on CONNECT_ACK, don't care about blacklist */
2416     if ( (GNUNET_OK == result) &&
2417          (ACK_SEND_CONNECT_ACK == n->ack_state) )
2418     {
2419       n->ack_state = ACK_SEND_SESSION_ACK;
2420       send_connect_ack_message (n->primary_address.address,
2421                                         n->primary_address.session,
2422                                         n->connect_ack_timestamp);
2423     }
2424     break;
2425   case GNUNET_TRANSPORT_PS_DISCONNECT:
2426     /* Nothing to do here, ATS will already do what can be done */
2427     break;
2428   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
2429     /* should not be possible */
2430     GNUNET_assert (0);
2431     break;
2432   default:
2433     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2434                 "Unhandled state `%s'\n",
2435                 GNUNET_TRANSPORT_ps2s (n->state));
2436     GNUNET_break (0);
2437     free_neighbour (n, GNUNET_NO);
2438     break;
2439   }
2440  cleanup:
2441   GNUNET_HELLO_address_free (bcc->na.address);
2442   GNUNET_free (bcc);
2443 }
2444
2445
2446 /**
2447  * We received a CONNECT message and want to know if connecting to a particular
2448  * peer via a particular address is allowed.  Check it!
2449  *
2450  * @param peer identity of the peer to switch the address for
2451  * @param ts time at which the check was initiated
2452  * @param address address of the other peer, NULL if other peer
2453  *                       connected to us
2454  * @param session session to use (or NULL)
2455  */
2456 static void
2457 connect_check_blacklist (const struct GNUNET_PeerIdentity *peer,
2458                  struct GNUNET_TIME_Absolute ts,
2459                  const struct GNUNET_HELLO_Address *address,
2460                  struct Session *session)
2461 {
2462   struct BlackListCheckContext *bcc;
2463   struct GST_BlacklistCheck *bc;
2464
2465   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2466               "Checking peer `%s' against blacklist\n",
2467               GNUNET_i2s (peer));
2468   bcc = GNUNET_new (struct BlackListCheckContext);
2469   bcc->na.address = GNUNET_HELLO_address_copy (address);
2470   bcc->na.session = session;
2471   bcc->na.connect_timestamp = ts;
2472   GNUNET_CONTAINER_DLL_insert (bc_head,
2473                                bc_tail,
2474                                bcc);
2475   if (NULL != (bc = GST_blacklist_test_allowed (peer,
2476         (NULL != address) ? address->transport_name : NULL,
2477         &handle_connect_blacklist_check_cont, bcc)))
2478     bcc->bc = bc;
2479   /* if NULL == bc, 'cont' was already called and 'bcc' already free'd, so
2480      we must only store 'bc' if 'bc' is non-NULL... */
2481 }
2482
2483
2484 /**
2485  * We received a 'SESSION_CONNECT' message from the other peer.
2486  * Consider switching to it.
2487  *
2488  * @param message possibly a 'struct SessionConnectMessage' (check format)
2489  * @param peer identity of the peer to switch the address for
2490  * @param address address of the other peer, NULL if other peer
2491  *                       connected to us
2492  * @param session session to use (or NULL)
2493  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
2494  */
2495 int
2496 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
2497                                const struct GNUNET_PeerIdentity *peer,
2498                                const struct GNUNET_HELLO_Address *address,
2499                                struct Session *session)
2500 {
2501   const struct SessionConnectMessage *scm;
2502   struct NeighbourMapEntry *n;
2503   struct GNUNET_TIME_Absolute ts;
2504
2505   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2506               "Received CONNECT message from peer `%s' with `%s' %p\n",
2507               GNUNET_i2s (peer), GST_plugins_a2s (address), session);
2508   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2509   {
2510     GNUNET_break_op (0);
2511     return GNUNET_SYSERR;
2512   }
2513   GNUNET_STATISTICS_update (GST_stats,
2514                             gettext_noop
2515                             ("# CONNECT messages received"),
2516                             1, GNUNET_NO);
2517   if (NULL == neighbours)
2518   {
2519     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2520                 _("CONNECT request from peer `%s' ignored due impending shutdown\n"),
2521                 GNUNET_i2s (peer));
2522     return GNUNET_OK; /* we're shutting down */
2523   }
2524   scm = (const struct SessionConnectMessage *) message;
2525   GNUNET_break_op (0 == ntohl (scm->reserved));
2526   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2527   n = lookup_neighbour (peer);
2528   if (NULL == n)
2529   {
2530     /* This is a new neighbour and set to not connected */
2531     n = setup_neighbour (peer);
2532   }
2533
2534   /* Remember this CONNECT message in neighbour */
2535   n->ack_state = ACK_SEND_CONNECT_ACK;
2536   n->connect_ack_timestamp = ts;
2537
2538   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2539               "Received SESSION_CONNECT for peer `%s' in state %s/%s\n",
2540               GNUNET_i2s (peer),
2541               GNUNET_TRANSPORT_ps2s (n->state),
2542               print_ack_state (n->ack_state));
2543   switch (n->state)
2544   {
2545   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
2546     /* Check if we are allowed to connect with this peer and this address */
2547     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND,
2548         GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2549     connect_check_blacklist (peer, ts, address, session);
2550     break;
2551   case GNUNET_TRANSPORT_PS_INIT_ATS:
2552     /* CONNECT message takes priority over us asking ATS for address */
2553     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND,
2554         GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2555     /* fallthrough */
2556   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
2557   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
2558   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
2559   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
2560   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
2561     /* It can never hurt to have an alternative address in the above cases,
2562        see if it is allowed */
2563     connect_check_blacklist (peer, ts, address, session);
2564     break;
2565   case GNUNET_TRANSPORT_PS_CONNECTED:
2566     /* we are already connected and can thus send the ACK immediately;
2567        still, it can never hurt to have an alternative address, so also
2568        tell ATS  about it */
2569     GNUNET_assert (NULL != n->primary_address.address);
2570     GNUNET_assert (NULL != n->primary_address.session);
2571     n->ack_state = ACK_UNDEFINED;
2572     send_connect_ack_message (n->primary_address.address,
2573                                       n->primary_address.session, ts);
2574     connect_check_blacklist (peer, ts, address, session);
2575     break;
2576   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
2577   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
2578   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
2579     /* It can never hurt to have an alternative address in the above cases,
2580        see if it is allowed */
2581     connect_check_blacklist (peer, ts, address, session);
2582     break;
2583   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
2584   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
2585     /* we are already connected and can thus send the ACK immediately;
2586        still, it can never hurt to have an alternative address, so also
2587        tell ATS  about it */
2588     GNUNET_assert (NULL != n->primary_address.address);
2589     GNUNET_assert (NULL != n->primary_address.session);
2590     n->ack_state = ACK_UNDEFINED;
2591     send_connect_ack_message (n->primary_address.address,
2592                                       n->primary_address.session, ts);
2593     connect_check_blacklist (peer, ts, address, session);
2594     break;
2595   case GNUNET_TRANSPORT_PS_DISCONNECT:
2596     /* get rid of remains without terminating sessions, ready to re-try */
2597     free_neighbour (n, GNUNET_YES);
2598     n = setup_neighbour (peer);
2599     /* Remember the CONNECT timestamp for ACK message */
2600     n->ack_state = ACK_SEND_CONNECT_ACK;
2601     n->connect_ack_timestamp = ts;
2602     /* Request an address for the peer */
2603     GNUNET_ATS_suggest_address (GST_ats, peer, address_suggest_cont, n);
2604     GNUNET_ATS_reset_backoff (GST_ats, peer);
2605     set_state (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS);
2606     break;
2607   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
2608     /* should not be possible */
2609     GNUNET_assert (0);
2610     break;
2611   default:
2612     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2613                 "Unhandled state `%s'\n",
2614                 GNUNET_TRANSPORT_ps2s (n->state));
2615     GNUNET_break (0);
2616     return GNUNET_SYSERR;
2617   }
2618   return GNUNET_OK;
2619 }
2620
2621 static void
2622 switch_address_bl_check_cont (void *cls,
2623     const struct GNUNET_PeerIdentity *peer, int result)
2624 {
2625   struct BlacklistCheckSwitchContext *blc_ctx = cls;
2626   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2627   struct NeighbourMapEntry *n;
2628
2629   if ( (NULL == (n = lookup_neighbour (peer))) || (result == GNUNET_NO) ||
2630        (NULL == (papi = GST_plugins_find (blc_ctx->address->transport_name))) )
2631   {
2632     if (NULL == n)
2633     {
2634       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2635                   "Peer %s is unknown, suggestion ignored\n",
2636                   GNUNET_i2s (peer));
2637     }
2638     if (result == GNUNET_NO)
2639     {
2640       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2641           "Blacklist denied to switch to suggested address `%s' session %p for peer `%s'\n",
2642           GST_plugins_a2s (blc_ctx->address),
2643           blc_ctx->session,
2644           GNUNET_i2s (&blc_ctx->address->peer));
2645     }
2646     if (NULL == (papi = GST_plugins_find (blc_ctx->address->transport_name)))
2647     {
2648       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2649           "Plugin `%s' for suggested address `%s' session %p for peer `%s' is not available\n",
2650           blc_ctx->address->transport_name,
2651           GST_plugins_a2s (blc_ctx->address),
2652           blc_ctx->session,
2653           GNUNET_i2s (&blc_ctx->address->peer));
2654     }
2655
2656     /* This address is blacklisted, delete address and session (if existing) in ATS */
2657     GNUNET_ATS_address_destroyed (GST_ats, blc_ctx->address, blc_ctx->session);
2658
2659     if ( (GNUNET_YES == (GNUNET_HELLO_address_check_option (blc_ctx->address,
2660           GNUNET_HELLO_ADDRESS_INFO_INBOUND))) && (NULL != blc_ctx->session))
2661     {
2662       /* This is an inbound address, destroy full  address */
2663       GNUNET_ATS_address_destroyed (GST_ats, blc_ctx->address, NULL );
2664     }
2665
2666     /* Remove blacklist check and clean up */
2667     GNUNET_CONTAINER_DLL_remove (pending_bc_head, pending_bc_tail, blc_ctx);
2668     GNUNET_HELLO_address_free (blc_ctx->address);
2669     GNUNET_free_non_null (blc_ctx->ats);
2670     GNUNET_free (blc_ctx);
2671     return;
2672   }
2673
2674   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2675       "Blacklist accepted to switch to suggested address `%s' session %p for peer `%s'\n",
2676       GST_plugins_a2s (blc_ctx->address),
2677       blc_ctx->session,
2678       GNUNET_i2s (&blc_ctx->address->peer));
2679
2680   if (NULL == blc_ctx->session)
2681   {
2682     blc_ctx->session = papi->get_session (papi->cls, blc_ctx->address);
2683     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2684                 "Obtained new session for peer `%s' and  address '%s': %p\n",
2685                 GNUNET_i2s (&blc_ctx->address->peer), GST_plugins_a2s (blc_ctx->address), blc_ctx->session);
2686   }
2687   if (NULL == blc_ctx->session)
2688   {
2689     /* No session could be obtained, remove blacklist check and clean up */
2690     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2691                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
2692                 GNUNET_i2s (&blc_ctx->address->peer),
2693                 GST_plugins_a2s (blc_ctx->address));
2694     /* Delete address in ATS */
2695     GNUNET_ATS_address_destroyed (GST_ats, blc_ctx->address, NULL);
2696
2697     GNUNET_CONTAINER_DLL_remove (pending_bc_head, pending_bc_tail, blc_ctx);
2698     GNUNET_HELLO_address_free (blc_ctx->address);
2699     GNUNET_free_non_null (blc_ctx->ats);
2700     GNUNET_free (blc_ctx);
2701     return;
2702   }
2703
2704   switch (n->state)
2705   {
2706   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
2707     GNUNET_break (0);
2708     free_neighbour (n, GNUNET_NO);
2709     return;
2710   case GNUNET_TRANSPORT_PS_INIT_ATS:
2711     /* We requested an address and ATS suggests one:
2712      * set primary address and send CONNECT message*/
2713     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2714         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2715     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_SENT,
2716         GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2717     send_session_connect (&n->primary_address);
2718     break;
2719   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
2720     /* waiting on CONNECT_ACK, send ACK if one is pending */
2721     if (ACK_SEND_CONNECT_ACK == n->ack_state)
2722     {
2723       n->ack_state = ACK_SEND_SESSION_ACK;
2724       send_connect_ack_message (n->primary_address.address,
2725                                         n->primary_address.session,
2726                                         n->connect_ack_timestamp);
2727     }
2728     /* ATS suggests a different address, switch again */
2729     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2730         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2731     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_SENT,
2732         GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2733     send_session_connect (&n->primary_address);
2734     break;
2735   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
2736     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2737         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2738     /* Send an ACK message as a response to the CONNECT msg */
2739     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK,
2740         GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2741     send_connect_ack_message (n->primary_address.address,
2742                                       n->primary_address.session,
2743                                       n->connect_ack_timestamp);
2744     if (ACK_SEND_CONNECT_ACK == n->ack_state)
2745       n->ack_state = ACK_SEND_SESSION_ACK;
2746
2747     break;
2748   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
2749     set_timeout (n, GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2750     /* REMOVE */ connect_check_blacklist (&n->id, n->connect_ack_timestamp,
2751         blc_ctx->address, blc_ctx->session);
2752     break;
2753   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
2754   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
2755     /* ATS asks us to switch while we were trying to connect; switch to new
2756        address and check blacklist again */
2757     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2758         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2759     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST,
2760         GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2761     /* REMOVE */ connect_check_blacklist (&n->id, n->connect_ack_timestamp,
2762         blc_ctx->address, blc_ctx->session);
2763     break;
2764   case GNUNET_TRANSPORT_PS_CONNECTED:
2765     GNUNET_assert (NULL != n->primary_address.address);
2766     GNUNET_assert (NULL != n->primary_address.session);
2767     if (n->primary_address.session == blc_ctx->session)
2768     {
2769       /* not an address change, just a quota change */
2770       set_primary_address (n, blc_ctx->address, blc_ctx->session,
2771           blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_YES);
2772       break;
2773     }
2774     /* ATS asks us to switch a life connection; see if we can get
2775        a CONNECT_ACK on it before we actually do this! */
2776     set_state (n, GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST);
2777     set_alternative_address (n, blc_ctx->address, blc_ctx->session,
2778         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out);
2779     /* REMOVE */ connect_check_blacklist (&n->id, GNUNET_TIME_absolute_get (),
2780         blc_ctx->address, blc_ctx->session);
2781     break;
2782   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
2783     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2784         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2785     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST,
2786         GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2787     /* REMOVE */ connect_check_blacklist (&n->id, n->connect_ack_timestamp,
2788         blc_ctx->address, blc_ctx->session);
2789     break;
2790   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
2791     /* ATS asks us to switch while we were trying to reconnect; switch to new
2792        address and check blacklist again */
2793     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2794         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2795     set_timeout (n, GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2796     /* REMOVE */ connect_check_blacklist (&n->id, n->connect_ack_timestamp,
2797         blc_ctx->address, blc_ctx->session);
2798     break;
2799   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
2800     /* ATS asks us to switch while we were trying to reconnect; switch to new
2801        address and check blacklist again */
2802     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2803         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2804     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST,
2805         GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT));
2806     /* REMOVE */ connect_check_blacklist (&n->id, n->connect_ack_timestamp,
2807         blc_ctx->address, blc_ctx->session);
2808     break;
2809   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
2810     if (n->primary_address.session == blc_ctx->session)
2811     {
2812       /* ATS switches back to still-active session */
2813       set_state(n, GNUNET_TRANSPORT_PS_CONNECTED);
2814       free_address (&n->alternative_address);
2815       break;
2816     }
2817     /* ATS asks us to switch a life connection, update blacklist check */
2818     set_primary_address (n, blc_ctx->address, blc_ctx->session,
2819         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out, GNUNET_NO);
2820     /* REMOVE */ connect_check_blacklist (&n->id, GNUNET_TIME_absolute_get (),
2821         blc_ctx->address, blc_ctx->session);
2822     break;
2823   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
2824     if (n->primary_address.session == blc_ctx->session)
2825     {
2826       /* ATS switches back to still-active session */
2827       free_address (&n->alternative_address);
2828       set_state (n, GNUNET_TRANSPORT_PS_CONNECTED);
2829       break;
2830     }
2831     /* ATS asks us to switch a life connection, update blacklist check */
2832     set_state (n, GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST);
2833     set_alternative_address (n, blc_ctx->address, blc_ctx->session,
2834         blc_ctx->bandwidth_in, blc_ctx->bandwidth_out);
2835     /* REMOVE */ connect_check_blacklist (&n->id, GNUNET_TIME_absolute_get (),
2836         blc_ctx->address, blc_ctx->session);
2837     break;
2838   case GNUNET_TRANSPORT_PS_DISCONNECT:
2839     /* not going to switch addresses while disconnecting */
2840     return;
2841   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
2842     GNUNET_assert (0);
2843     break;
2844   default:
2845     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2846                 "Unhandled state `%s'\n",
2847                 GNUNET_TRANSPORT_ps2s (n->state));
2848     GNUNET_break (0);
2849     break;
2850   }
2851
2852   GNUNET_CONTAINER_DLL_remove (pending_bc_head, pending_bc_tail, blc_ctx);
2853   GNUNET_HELLO_address_free(blc_ctx->address);
2854   GNUNET_free_non_null (blc_ctx->ats);
2855   GNUNET_free (blc_ctx);
2856   return;
2857 }
2858
2859
2860 /**
2861  * For the given peer, switch to this address.
2862  *
2863  * Before accepting this addresses and actively using it, a blacklist check
2864  * is performed. If this blacklist check fails the address will be destroyed.
2865  *
2866  * @param peer identity of the peer to switch the address for
2867  * @param address address of the other peer,
2868  * @param session session to use or NULL if transport should initiate a session
2869  * @param ats performance data
2870  * @param ats_count number of entries in ats
2871  * @param bandwidth_in inbound quota to be used when connection is up,
2872  *      0 to disconnect from peer
2873  * @param bandwidth_out outbound quota to be used when connection is up,
2874  *      0 to disconnect from peer
2875  */
2876 void
2877 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
2878                                   const struct GNUNET_HELLO_Address *address,
2879                                   struct Session *session,
2880                                   const struct GNUNET_ATS_Information *ats,
2881                                   uint32_t ats_count,
2882                                   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
2883                                   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
2884 {
2885   struct NeighbourMapEntry *n;
2886   struct GST_BlacklistCheck *blc;
2887   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2888   struct BlacklistCheckSwitchContext *blc_ctx;
2889   int c;
2890
2891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2892               "ATS has decided on an address for peer %s\n",
2893               GNUNET_i2s (peer));
2894   GNUNET_assert (NULL != address->transport_name);
2895   if (NULL == (n = lookup_neighbour (peer)))
2896   {
2897     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2898                 "Peer %s is unknown, suggestion ignored\n",
2899                 GNUNET_i2s (peer));
2900     return;
2901   }
2902
2903   /* Check if plugin is available */
2904   if (NULL == (papi = GST_plugins_find (address->transport_name)))
2905   {
2906     /* we don't have the plugin for this address */
2907     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2908                 "Plugin `%s' is unknown, suggestion for peer %s ignored\n",
2909                 address->transport_name,
2910                 GNUNET_i2s (peer));
2911     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2912     return;
2913   }
2914   if ((NULL == session) &&
2915       (GNUNET_HELLO_address_check_option (address, GNUNET_HELLO_ADDRESS_INFO_INBOUND)))
2916   {
2917     /* This is a inbound address and we do not have a session to use! */
2918     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2919                 "Inbound address without session `%s'! Destroying address...\n",
2920                 GST_plugins_a2s (address));
2921     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2922     return;
2923   }
2924
2925   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2926     "ATS tells us to switch to %s address '%s' session %p for "
2927     "peer `%s' in state %s/%s (quota in/out %u %u )\n",
2928     GNUNET_HELLO_address_check_option (address,
2929         GNUNET_HELLO_ADDRESS_INFO_INBOUND) ? "inbound" : "outbound",
2930     GST_plugins_a2s (address), session, GNUNET_i2s (peer),
2931     GNUNET_TRANSPORT_ps2s (n->state), print_ack_state (n->ack_state),
2932     ntohl (bandwidth_in.value__), ntohl (bandwidth_out.value__));
2933
2934   /* Perform blacklist check */
2935   blc_ctx = GNUNET_new (struct BlacklistCheckSwitchContext);
2936   blc_ctx->address = GNUNET_HELLO_address_copy (address);
2937   blc_ctx->session = session;
2938   blc_ctx->bandwidth_in = bandwidth_in;
2939   blc_ctx->bandwidth_out = bandwidth_out;
2940   blc_ctx->ats_count = ats_count;
2941   blc_ctx->ats = NULL;
2942   if (ats_count > 0)
2943   {
2944     blc_ctx->ats = GNUNET_malloc (ats_count * sizeof (struct GNUNET_ATS_Information));
2945     for (c = 0; c < ats_count; c++)
2946     {
2947       blc_ctx->ats[c].type = ats[c].type;
2948       blc_ctx->ats[c].value = ats[c].value;
2949     }
2950   }
2951
2952   GNUNET_CONTAINER_DLL_insert (pending_bc_head, pending_bc_tail, blc_ctx);
2953   if (NULL != (blc = GST_blacklist_test_allowed (peer, address->transport_name,
2954       &switch_address_bl_check_cont, blc_ctx)))
2955   {
2956     blc_ctx->blc = blc;
2957   }
2958 }
2959
2960
2961 static int
2962 send_utilization_data (void *cls,
2963                        const struct GNUNET_PeerIdentity *key,
2964                        void *value)
2965 {
2966   struct NeighbourMapEntry *n = value;
2967   struct GNUNET_ATS_Information atsi[4];
2968   uint32_t bps_pl_in;
2969   uint32_t bps_pl_out;
2970   uint32_t bps_in;
2971   uint32_t bps_out;
2972   struct GNUNET_TIME_Relative delta;
2973
2974   delta = GNUNET_TIME_absolute_get_difference (n->last_util_transmission,
2975                                                GNUNET_TIME_absolute_get ());
2976
2977   bps_pl_in = 0;
2978
2979   if ((0 != n->util_payload_bytes_recv) && (0 != delta.rel_value_us))
2980     bps_pl_in =  (1000LL * 1000LL *  n->util_payload_bytes_recv) / (delta.rel_value_us);
2981   bps_pl_out = 0;
2982   if ((0 != n->util_payload_bytes_sent) && (0 != delta.rel_value_us))
2983     bps_pl_out = (1000LL * 1000LL * n->util_payload_bytes_sent) / delta.rel_value_us;
2984   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2985               "`%s' payload: received %u Bytes/s, sent %u Bytes/s\n",
2986               GNUNET_i2s (key),
2987               bps_pl_in,
2988               bps_pl_out);
2989   bps_in = 0;
2990   if ((0 != n->util_total_bytes_recv) && (0 != delta.rel_value_us))
2991     bps_in =  (1000LL * 1000LL *  n->util_total_bytes_recv) / (delta.rel_value_us);
2992   bps_out = 0;
2993   if ((0 != n->util_total_bytes_sent) && (0 != delta.rel_value_us))
2994     bps_out = (1000LL * 1000LL * n->util_total_bytes_sent) / delta.rel_value_us;
2995
2996
2997   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2998               "`%s' total: received %u Bytes/s, sent %u Bytes/s\n",
2999               GNUNET_i2s (key),
3000               bps_in,
3001               bps_out);
3002   atsi[0].type = htonl (GNUNET_ATS_UTILIZATION_OUT);
3003   atsi[0].value = htonl (bps_out);
3004   atsi[1].type = htonl (GNUNET_ATS_UTILIZATION_IN);
3005   atsi[1].value = htonl (bps_in);
3006
3007   atsi[2].type = htonl (GNUNET_ATS_UTILIZATION_PAYLOAD_OUT);
3008   atsi[2].value = htonl (bps_pl_out);
3009   atsi[3].type = htonl (GNUNET_ATS_UTILIZATION_PAYLOAD_IN);
3010   atsi[3].value = htonl (bps_pl_in);
3011
3012   GST_ats_update_metrics (key, n->primary_address.address,
3013       n->primary_address.session, atsi, 4);
3014   n->util_payload_bytes_recv = 0;
3015   n->util_payload_bytes_sent = 0;
3016   n->util_total_bytes_recv = 0;
3017   n->util_total_bytes_sent = 0;
3018   n->last_util_transmission = GNUNET_TIME_absolute_get();
3019   return GNUNET_OK;
3020 }
3021
3022
3023 /**
3024  * Task transmitting utilization in a regular interval
3025  *
3026  * @param cls the 'struct NeighbourMapEntry' for which we are running
3027  * @param tc scheduler context (unused)
3028  */
3029 static void
3030 utilization_transmission (void *cls,
3031                           const struct GNUNET_SCHEDULER_TaskContext *tc)
3032 {
3033   util_transmission_tk = GNUNET_SCHEDULER_NO_TASK;
3034
3035   if (0 < GNUNET_CONTAINER_multipeermap_size (neighbours))
3036     GNUNET_CONTAINER_multipeermap_iterate (neighbours, send_utilization_data, NULL);
3037
3038   util_transmission_tk = GNUNET_SCHEDULER_add_delayed (UTIL_TRANSMISSION_INTERVAL,
3039       utilization_transmission, NULL);
3040
3041 }
3042
3043
3044 void
3045 GST_neighbours_notify_data_recv (const struct GNUNET_PeerIdentity *peer,
3046                                  const struct GNUNET_HELLO_Address *address,
3047                                  struct Session *session,
3048                                  const struct GNUNET_MessageHeader *message)
3049 {
3050   struct NeighbourMapEntry *n;
3051
3052   n = lookup_neighbour (peer);
3053   if (NULL == n)
3054     return;
3055   n->util_total_bytes_recv += ntohs(message->size);
3056 }
3057
3058
3059 void
3060 GST_neighbours_notify_payload_recv (const struct GNUNET_PeerIdentity *peer,
3061                                     const struct GNUNET_HELLO_Address *address,
3062                                     struct Session *session,
3063                                     const struct GNUNET_MessageHeader *message)
3064 {
3065   struct NeighbourMapEntry *n;
3066   n = lookup_neighbour (peer);
3067   if (NULL == n)
3068     return;
3069   n->util_payload_bytes_recv += ntohs(message->size);
3070 }
3071
3072
3073 void
3074 GST_neighbours_notify_data_sent (const struct GNUNET_PeerIdentity *peer,
3075                                  const struct GNUNET_HELLO_Address *address,
3076                                  struct Session *session,
3077                                  size_t size)
3078 {
3079   struct NeighbourMapEntry *n;
3080   n = lookup_neighbour (peer);
3081   if (NULL == n)
3082       return;
3083   if (n->primary_address.session != session)
3084     return;
3085   n->util_total_bytes_sent += size;
3086 }
3087
3088
3089 void
3090 GST_neighbours_notify_payload_sent (const struct GNUNET_PeerIdentity *peer,
3091                                     size_t size)
3092 {
3093   struct NeighbourMapEntry *n;
3094   n = lookup_neighbour (peer);
3095   if (NULL == n)
3096     return;
3097   n->util_payload_bytes_sent += size;
3098 }
3099
3100
3101 /**
3102  * Master task run for every neighbour.  Performs all of the time-related
3103  * activities (keep alive, send next message, disconnect if idle, finish
3104  * clean up after disconnect).
3105  *
3106  * @param cls the 'struct NeighbourMapEntry' for which we are running
3107  * @param tc scheduler context (unused)
3108  */
3109 static void
3110 master_task (void *cls,
3111              const struct GNUNET_SCHEDULER_TaskContext *tc)
3112 {
3113   struct NeighbourMapEntry *n = cls;
3114   struct GNUNET_TIME_Relative delay;
3115
3116   n->task = GNUNET_SCHEDULER_NO_TASK;
3117   delay = GNUNET_TIME_absolute_get_remaining (n->timeout);
3118   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3119               "Master task runs for neighbour `%s' in state %s with timeout in %s\n",
3120               GNUNET_i2s (&n->id),
3121               GNUNET_TRANSPORT_ps2s(n->state),
3122               GNUNET_STRINGS_relative_time_to_string (delay,
3123                                                       GNUNET_YES));
3124   switch (n->state)
3125   {
3126   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3127     /* invalid state for master task, clean up */
3128     GNUNET_break (0);
3129     free_neighbour (n, GNUNET_NO);
3130     return;
3131   case GNUNET_TRANSPORT_PS_INIT_ATS:
3132     if (0 == delay.rel_value_us)
3133     {
3134       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3135                   "Connection to `%s' timed out waiting for ATS to provide address\n",
3136                   GNUNET_i2s (&n->id));
3137       free_neighbour (n, GNUNET_NO);
3138       return;
3139     }
3140     break;
3141   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
3142     if (0 == delay.rel_value_us)
3143     {
3144       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3145                   "Connection to `%s' timed out waiting for other peer to send CONNECT_ACK\n",
3146                   GNUNET_i2s (&n->id));
3147       /* We could not send to this address, delete address and session */
3148       if (NULL != n->primary_address.session)
3149         GNUNET_ATS_address_destroyed (GST_ats, n->primary_address.address,
3150             n->primary_address.session);
3151       GNUNET_ATS_address_destroyed (GST_ats, n->primary_address.address, NULL);
3152
3153       /* Remove address and request and additional one */
3154       GNUNET_break (0);
3155       unset_primary_address (n);
3156       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
3157           GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3158       return;
3159     }
3160     break;
3161   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
3162     if (0 == delay.rel_value_us)
3163     {
3164       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3165                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for received CONNECT\n",
3166                   GNUNET_i2s (&n->id));
3167       free_neighbour (n, GNUNET_NO);
3168       return;
3169     }
3170     break;
3171   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
3172     if (0 == delay.rel_value_us)
3173     {
3174       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3175                   "Connection to `%s' timed out waiting ATS to provide address to use for CONNECT_ACK\n",
3176                   GNUNET_i2s (&n->id));
3177       free_neighbour (n, GNUNET_NO);
3178       return;
3179     }
3180     break;
3181   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
3182     if (0 == delay.rel_value_us)
3183     {
3184       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3185                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for CONNECT_ACK\n",
3186                   GNUNET_i2s (&n->id));
3187       free_neighbour (n, GNUNET_NO);
3188       return;
3189     }
3190     break;
3191   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
3192     if (0 == delay.rel_value_us)
3193     {
3194       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3195                   "Connection to `%s' timed out waiting for other peer to send SESSION_ACK\n",
3196                   GNUNET_i2s (&n->id));
3197       disconnect_neighbour (n);
3198       return;
3199     }
3200     break;
3201   case GNUNET_TRANSPORT_PS_CONNECTED:
3202     if (0 == delay.rel_value_us)
3203     {
3204       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3205                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
3206                   GNUNET_i2s (&n->id));
3207       disconnect_neighbour (n);
3208       return;
3209     }
3210     try_transmission_to_peer (n);
3211     send_keepalive (n);
3212     break;
3213   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3214     if (0 == delay.rel_value_us)
3215     {
3216       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3217                   "Connection to `%s' timed out, waiting for ATS replacement address\n",
3218                   GNUNET_i2s (&n->id));
3219       disconnect_neighbour (n);
3220       return;
3221     }
3222     break;
3223   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
3224     if (0 == delay.rel_value_us)
3225     {
3226       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3227                   "Connection to `%s' timed out, waiting for BLACKLIST to approve replacement address\n",
3228                   GNUNET_i2s (&n->id));
3229       disconnect_neighbour (n);
3230       return;
3231     }
3232     break;
3233   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3234     if (0 == delay.rel_value_us)
3235     {
3236       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3237                   "Connection to `%s' timed out, waiting for other peer to CONNECT_ACK replacement address\n",
3238                   GNUNET_i2s (&n->id));
3239       disconnect_neighbour (n);
3240       return;
3241     }
3242     break;
3243   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
3244     if (0 == delay.rel_value_us)
3245     {
3246       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3247                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
3248                   GNUNET_i2s (&n->id));
3249       disconnect_neighbour (n);
3250       return;
3251     }
3252     try_transmission_to_peer (n);
3253     send_keepalive (n);
3254     break;
3255   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
3256     if (0 == delay.rel_value_us)
3257     {
3258       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3259                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs (after trying to CONNECT on alternative address)\n",
3260                   GNUNET_i2s (&n->id));
3261       disconnect_neighbour (n);
3262       return;
3263     }
3264     try_transmission_to_peer (n);
3265     send_keepalive (n);
3266     break;
3267   case GNUNET_TRANSPORT_PS_DISCONNECT:
3268     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3269                 "Cleaning up connection to `%s' after sending DISCONNECT\n",
3270                 GNUNET_i2s (&n->id));
3271     free_neighbour (n, GNUNET_NO);
3272     return;
3273   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3274     /* how did we get here!? */
3275     GNUNET_assert (0);
3276     break;
3277   default:
3278     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3279                 "Unhandled state `%s'\n",
3280                 GNUNET_TRANSPORT_ps2s (n->state));
3281     GNUNET_break (0);
3282     break;
3283   }
3284   if ( (GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT == n->state) ||
3285        (GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
3286        (GNUNET_TRANSPORT_PS_CONNECTED == n->state) )
3287   {
3288     /* if we are *now* in one of these three states, we're sending
3289        keep alive messages, so we need to consider the keepalive
3290        delay, not just the connection timeout */
3291     delay = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time),
3292                                       delay);
3293   }
3294   if (GNUNET_SCHEDULER_NO_TASK == n->task)
3295     n->task = GNUNET_SCHEDULER_add_delayed (delay,
3296                                             &master_task,
3297                                             n);
3298 }
3299
3300
3301 /**
3302  * Send a SESSION_ACK message to the neighbour to confirm that we
3303  * got his CONNECT_ACK.
3304  *
3305  * @param n neighbour to send the SESSION_ACK to
3306  */
3307 static void
3308 send_session_ack_message (struct NeighbourMapEntry *n)
3309 {
3310   struct GNUNET_MessageHeader msg;
3311
3312   msg.size = htons (sizeof (struct GNUNET_MessageHeader));
3313   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
3314   (void) send_with_session(n,
3315                            (const char *) &msg, sizeof (struct GNUNET_MessageHeader),
3316                            UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_NO,
3317                            NULL, NULL);
3318 }
3319
3320
3321 /**
3322  * We received a 'SESSION_CONNECT_ACK' message from the other peer.
3323  * Consider switching to it.
3324  *
3325  * @param message possibly a 'struct SessionConnectMessage' (check format)
3326  * @param peer identity of the peer to switch the address for
3327  * @param address address of the other peer, NULL if other peer
3328  *                       connected to us
3329  * @param session session to use (or NULL)
3330  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
3331  */
3332 int
3333 GST_neighbours_handle_connect_ack (const struct GNUNET_MessageHeader *message,
3334                                    const struct GNUNET_PeerIdentity *peer,
3335                                    const struct GNUNET_HELLO_Address *address,
3336                                    struct Session *session)
3337 {
3338   const struct SessionConnectMessage *scm;
3339   struct GNUNET_TIME_Absolute ts;
3340   struct NeighbourMapEntry *n;
3341
3342   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3343               "Received CONNECT_ACK message from peer `%s'\n",
3344               GNUNET_i2s (peer));
3345
3346   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
3347   {
3348     GNUNET_break_op (0);
3349     return GNUNET_SYSERR;
3350   }
3351   GNUNET_STATISTICS_update (GST_stats,
3352                             gettext_noop
3353                             ("# CONNECT_ACK messages received"),
3354                             1, GNUNET_NO);
3355   scm = (const struct SessionConnectMessage *) message;
3356   GNUNET_break_op (ntohl (scm->reserved) == 0);
3357   if (NULL == (n = lookup_neighbour (peer)))
3358   {
3359     GNUNET_STATISTICS_update (GST_stats,
3360                               gettext_noop
3361                               ("# unexpected CONNECT_ACK messages (no peer)"),
3362                               1, GNUNET_NO);
3363     return GNUNET_SYSERR;
3364   }
3365   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
3366   switch (n->state)
3367   {
3368   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3369     GNUNET_break (0);
3370     free_neighbour (n, GNUNET_NO);
3371     return GNUNET_SYSERR;
3372   case GNUNET_TRANSPORT_PS_INIT_ATS:
3373     GNUNET_STATISTICS_update (GST_stats,
3374                               gettext_noop
3375                               ("# unexpected CONNECT_ACK messages (not ready)"),
3376                               1, GNUNET_NO);
3377     break;
3378   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
3379     if (ts.abs_value_us != n->primary_address.connect_timestamp.abs_value_us)
3380     {
3381       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3382                   "CONNECT_ACK ignored as the timestamp does not match our CONNECT request\n");
3383       return GNUNET_OK;
3384     }
3385     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED,
3386         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3387     GNUNET_STATISTICS_set (GST_stats,
3388                            gettext_noop ("# peers connected"),
3389                            ++neighbours_connected,
3390                            GNUNET_NO);
3391     connect_notify_cb (callback_cls, &n->id,
3392                        n->primary_address.bandwidth_in,
3393                        n->primary_address.bandwidth_out);
3394     /* Tell ATS that the outbound session we created to send CONNECT was successful */
3395     GST_ats_add_address (n->primary_address.address,
3396                          n->primary_address.session,
3397                          NULL, 0);
3398     set_primary_address (n,
3399                  n->primary_address.address,
3400                  n->primary_address.session,
3401                  n->primary_address.bandwidth_in,
3402                  n->primary_address.bandwidth_out,
3403                  GNUNET_YES);
3404     send_session_ack_message (n);
3405     break;
3406   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
3407   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
3408   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
3409   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
3410     GNUNET_STATISTICS_update (GST_stats,
3411                               gettext_noop
3412                               ("# unexpected CONNECT_ACK messages (not ready)"),
3413                               1, GNUNET_NO);
3414     break;
3415   case GNUNET_TRANSPORT_PS_CONNECTED:
3416     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
3417     send_session_ack_message (n);
3418     break;
3419   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3420   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
3421     /* we didn't expect any CONNECT_ACK, as we are waiting for ATS
3422        to give us a new address... */
3423     GNUNET_STATISTICS_update (GST_stats,
3424                               gettext_noop
3425                               ("# unexpected CONNECT_ACK messages (waiting on ATS)"),
3426                               1, GNUNET_NO);
3427     break;
3428   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3429     /* new address worked; go back to connected! */
3430     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED,
3431         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3432     send_session_ack_message (n);
3433     break;
3434   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
3435     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
3436     send_session_ack_message (n);
3437     break;
3438   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
3439     /* new address worked; adopt it and go back to connected! */
3440     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED,
3441         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3442     GNUNET_break (GNUNET_NO == n->alternative_address.ats_active);
3443
3444     GST_ats_add_address (n->alternative_address.address,
3445                          n->alternative_address.session,
3446                          NULL, 0);
3447     set_primary_address (n, n->alternative_address.address,
3448         n->alternative_address.session, n->alternative_address.bandwidth_in,
3449         n->alternative_address.bandwidth_out, GNUNET_YES);
3450
3451     free_address (&n->alternative_address);
3452     send_session_ack_message (n);
3453     break;
3454   case GNUNET_TRANSPORT_PS_DISCONNECT:
3455     GNUNET_STATISTICS_update (GST_stats,
3456                               gettext_noop
3457                               ("# unexpected CONNECT_ACK messages (disconnecting)"),
3458                               1, GNUNET_NO);
3459     return GNUNET_SYSERR;
3460   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3461     GNUNET_assert (0);
3462     break;
3463   default:
3464     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3465                 "Unhandled state `%s'\n",
3466                 GNUNET_TRANSPORT_ps2s (n->state));
3467     GNUNET_break (0);
3468     return GNUNET_SYSERR;
3469   }
3470   return GNUNET_OK;
3471 }
3472
3473
3474 /**
3475  * A session was terminated. Take note; if needed, try to get
3476  * an alternative address from ATS.
3477  *
3478  * @param peer identity of the peer where the session died
3479  * @param session session that is gone
3480  * @return #GNUNET_YES if this was a session used, #GNUNET_NO if
3481  *        this session was not in use
3482  */
3483 int
3484 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
3485                                    struct Session *session)
3486 {
3487   struct NeighbourMapEntry *n;
3488   struct BlackListCheckContext *bcc;
3489   struct BlackListCheckContext *bcc_next;
3490
3491   /* make sure to cancel all ongoing blacklist checks involving 'session' */
3492   bcc_next = bc_head;
3493   while (NULL != (bcc = bcc_next))
3494   {
3495     bcc_next = bcc->next;
3496     if (bcc->na.session == session)
3497     {
3498       if (NULL != bcc->bc)
3499         GST_blacklist_test_cancel (bcc->bc);
3500       GNUNET_HELLO_address_free (bcc->na.address);
3501       GNUNET_CONTAINER_DLL_remove (bc_head,
3502                                    bc_tail,
3503                                    bcc);
3504       GNUNET_free (bcc);
3505     }
3506   }
3507   if (NULL == (n = lookup_neighbour (peer)))
3508     return GNUNET_NO; /* can't affect us */
3509   if (session != n->primary_address.session)
3510   {
3511     if (session == n->alternative_address.session)
3512     {
3513       if ( (GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
3514            (GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT == n->state) )
3515         set_state (n, GNUNET_TRANSPORT_PS_CONNECTED);
3516       else
3517         GNUNET_break (0);
3518       free_address (&n->alternative_address);
3519     }
3520     return GNUNET_NO; /* doesn't affect us further */
3521   }
3522
3523   n->expect_latency_response = GNUNET_NO;
3524   /* The session for neighbour's primary address died */
3525   switch (n->state)
3526   {
3527   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3528     GNUNET_break (0);
3529     free_neighbour (n, GNUNET_NO);
3530     return GNUNET_YES;
3531   case GNUNET_TRANSPORT_PS_INIT_ATS:
3532     GNUNET_break (0);
3533     free_neighbour (n, GNUNET_NO);
3534     return GNUNET_YES;
3535   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
3536     /* The session used to send the CONNECT terminated:
3537      * this implies a connect error*/
3538     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3539                 "Could not send CONNECT message with address `%s' session %p: session terminated, requesting new address\n",
3540                 GST_plugins_a2s (n->primary_address.address), n->primary_address.session,
3541                 GNUNET_i2s (peer));
3542     GNUNET_ATS_address_destroyed (GST_ats, n->primary_address.address, NULL);
3543     unset_primary_address (n);
3544     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
3545         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3546     break;
3547   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
3548   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
3549   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
3550   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
3551     /* error on inbound session; free neighbour entirely */
3552     free_address (&n->primary_address);
3553     free_neighbour (n, GNUNET_NO);
3554     return GNUNET_YES;
3555   case GNUNET_TRANSPORT_PS_CONNECTED:
3556     unset_primary_address (n);
3557     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_ATS,
3558         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3559     break;
3560   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3561     /* we don't have an address, how can it go down? */
3562     GNUNET_break (0);
3563     break;
3564   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
3565   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3566     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_ATS, GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3567     break;
3568   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
3569     /* primary went down while we were checking secondary against
3570        blacklist, adopt secondary as primary */
3571     free_address (&n->primary_address);
3572     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST, GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT));
3573     n->primary_address = n->alternative_address;
3574     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
3575     break;
3576   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
3577     /* primary went down while we were waiting for CONNECT_ACK on secondary;
3578        secondary as primary */
3579     free_address (&n->primary_address);
3580     n->primary_address = n->alternative_address;
3581     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
3582     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_SENT, GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT));
3583     break;
3584   case GNUNET_TRANSPORT_PS_DISCONNECT:
3585     free_address (&n->primary_address);
3586     break;
3587   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3588     /* neighbour was freed and plugins told to terminate session */
3589     return GNUNET_NO;
3590     break;
3591   default:
3592     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3593                 "Unhandled state `%s'\n",
3594                 GNUNET_TRANSPORT_ps2s (n->state));
3595     GNUNET_break (0);
3596     break;
3597   }
3598   if (GNUNET_SCHEDULER_NO_TASK != n->task)
3599     GNUNET_SCHEDULER_cancel (n->task);
3600   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
3601   return GNUNET_YES;
3602 }
3603
3604
3605 /**
3606  * We received a 'SESSION_ACK' message from the other peer.
3607  * If we sent a 'CONNECT_ACK' last, this means we are now
3608  * connected.  Otherwise, do nothing.
3609  *
3610  * @param message possibly a 'struct SessionConnectMessage' (check format)
3611  * @param peer identity of the peer to switch the address for
3612  * @param address address of the other peer, NULL if other peer
3613  *                       connected to us
3614  * @param session session to use (or NULL)
3615  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
3616  */
3617 int
3618 GST_neighbours_handle_session_ack (const struct GNUNET_MessageHeader *message,
3619                                    const struct GNUNET_PeerIdentity *peer,
3620                                    const struct GNUNET_HELLO_Address *address,
3621                                    struct Session *session)
3622 {
3623   struct NeighbourMapEntry *n;
3624
3625   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3626               "Received SESSION_ACK message from peer `%s'\n",
3627               GNUNET_i2s (peer));
3628   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
3629   {
3630     GNUNET_break_op (0);
3631     return GNUNET_SYSERR;
3632   }
3633   GNUNET_STATISTICS_update (GST_stats,
3634                             gettext_noop
3635                             ("# SESSION_ACK messages received"),
3636                             1, GNUNET_NO);
3637   if (NULL == (n = lookup_neighbour (peer)))
3638   {
3639     GNUNET_break_op (0);
3640     return GNUNET_SYSERR;
3641   }
3642   /* check if we are in a plausible state for having sent
3643      a CONNECT_ACK.  If not, return, otherwise break */
3644   if ( ( (GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK != n->state) &&
3645          (GNUNET_TRANSPORT_PS_CONNECT_SENT != n->state) ) ||
3646        (ACK_SEND_SESSION_ACK != n->ack_state) )
3647   {
3648     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3649                 "Received SESSION_ACK message from peer `%s' in state %s/%s\n",
3650                 GNUNET_i2s (peer),
3651                 GNUNET_TRANSPORT_ps2s (n->state),
3652                 print_ack_state (n->ack_state));
3653     GNUNET_STATISTICS_update (GST_stats,
3654                               gettext_noop ("# unexpected SESSION_ACK messages"), 1,
3655                               GNUNET_NO);
3656     return GNUNET_OK;
3657   }
3658   set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED, GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3659   GNUNET_STATISTICS_set (GST_stats,
3660                          gettext_noop ("# peers connected"),
3661                          ++neighbours_connected,
3662                          GNUNET_NO);
3663   connect_notify_cb (callback_cls, &n->id,
3664                      n->primary_address.bandwidth_in,
3665                      n->primary_address.bandwidth_out);
3666
3667   GST_ats_add_address (n->primary_address.address,
3668                        n->primary_address.session,
3669                        NULL, 0);
3670   set_primary_address (n,
3671                n->primary_address.address,
3672                n->primary_address.session,
3673                n->primary_address.bandwidth_in,
3674                n->primary_address.bandwidth_out,
3675                GNUNET_YES);
3676   return GNUNET_OK;
3677 }
3678
3679
3680 /**
3681  * Test if we're connected to the given peer.
3682  *
3683  * @param target peer to test
3684  * @return #GNUNET_YES if we are connected, #GNUNET_NO if not
3685  */
3686 int
3687 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
3688 {
3689   return test_connected (lookup_neighbour (target));
3690 }
3691
3692 /**
3693  * Change the incoming quota for the given peer.
3694  *
3695  * @param neighbour identity of peer to change qutoa for
3696  * @param quota new quota
3697  */
3698 void
3699 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
3700                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
3701 {
3702   struct NeighbourMapEntry *n;
3703
3704   if (NULL == (n = lookup_neighbour (neighbour)))
3705   {
3706     GNUNET_STATISTICS_update (GST_stats,
3707                               gettext_noop
3708                               ("# SET QUOTA messages ignored (no such peer)"),
3709                               1, GNUNET_NO);
3710     return;
3711   }
3712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3713               "Setting inbound quota of %u Bps for peer `%s' to all clients\n",
3714               ntohl (quota.value__), GNUNET_i2s (&n->id));
3715   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
3716   if (0 != ntohl (quota.value__))
3717     return;
3718   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3719               "Disconnecting peer `%4s' due to SET_QUOTA\n",
3720               GNUNET_i2s (&n->id));
3721   if (GNUNET_YES == test_connected (n))
3722     GNUNET_STATISTICS_update (GST_stats,
3723                               gettext_noop ("# disconnects due to quota of 0"),
3724                               1, GNUNET_NO);
3725   disconnect_neighbour (n);
3726 }
3727
3728
3729 /**
3730  * We received a disconnect message from the given peer,
3731  * validate and process.
3732  *
3733  * @param peer sender of the message
3734  * @param msg the disconnect message
3735  */
3736 void
3737 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity *peer,
3738                                           const struct GNUNET_MessageHeader *msg)
3739 {
3740   struct NeighbourMapEntry *n;
3741   const struct SessionDisconnectMessage *sdm;
3742
3743   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3744               "Received DISCONNECT message from peer `%s'\n",
3745               GNUNET_i2s (peer));
3746   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
3747   {
3748     // GNUNET_break_op (0);
3749     GNUNET_STATISTICS_update (GST_stats,
3750                               gettext_noop
3751                               ("# disconnect messages ignored (old format)"), 1,
3752                               GNUNET_NO);
3753     return;
3754   }
3755   GNUNET_STATISTICS_update (GST_stats,
3756                             gettext_noop
3757                             ("# DISCONNECT messages received"),
3758                             1, GNUNET_NO);
3759   sdm = (const struct SessionDisconnectMessage *) msg;
3760   if (NULL == (n = lookup_neighbour (peer)))
3761     return;                     /* gone already */
3762   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value_us <= n->connect_ack_timestamp.abs_value_us)
3763   {
3764     GNUNET_STATISTICS_update (GST_stats,
3765                               gettext_noop
3766                               ("# disconnect messages ignored (timestamp)"), 1,
3767                               GNUNET_NO);
3768     return;
3769   }
3770   if (0 != memcmp (peer, &sdm->public_key, sizeof (struct GNUNET_PeerIdentity)))
3771   {
3772     GNUNET_break_op (0);
3773     return;
3774   }
3775   if (ntohl (sdm->purpose.size) !=
3776       sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
3777       sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
3778       sizeof (struct GNUNET_TIME_AbsoluteNBO))
3779   {
3780     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3781                 "%s message from peer `%s' has invalid size \n",
3782                 "DISCONNECT",
3783                 GNUNET_i2s (peer));
3784     GNUNET_break_op (0);
3785     return;
3786   }
3787   if (GNUNET_OK !=
3788       GNUNET_CRYPTO_eddsa_verify
3789       (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT, &sdm->purpose,
3790        &sdm->signature, &sdm->public_key))
3791   {
3792     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3793                 "%s message from peer `%s' cannot be verified \n",
3794                 "DISCONNECT",
3795                 GNUNET_i2s (peer));
3796     GNUNET_break_op (0);
3797     return;
3798   }
3799   if (GNUNET_YES == test_connected (n))
3800     GNUNET_STATISTICS_update (GST_stats,
3801                               gettext_noop
3802                               ("# other peer asked to disconnect from us"), 1,
3803                               GNUNET_NO);
3804   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3805               "Disconnecting by request from peer %s\n",
3806               GNUNET_i2s (peer));
3807   disconnect_neighbour (n);
3808 }
3809
3810
3811 /**
3812  * Closure for the neighbours_iterate function.
3813  */
3814 struct IteratorContext
3815 {
3816   /**
3817    * Function to call on each connected neighbour.
3818    */
3819   GST_NeighbourIterator cb;
3820
3821   /**
3822    * Closure for 'cb'.
3823    */
3824   void *cb_cls;
3825 };
3826
3827
3828 /**
3829  * Call the callback from the closure for each neighbour.
3830  *
3831  * @param cls the `struct IteratorContext`
3832  * @param key the hash of the public key of the neighbour
3833  * @param value the `struct NeighbourMapEntry`
3834  * @return #GNUNET_OK (continue to iterate)
3835  */
3836 static int
3837 neighbours_iterate (void *cls,
3838                     const struct GNUNET_PeerIdentity *key,
3839                     void *value)
3840 {
3841   struct IteratorContext *ic = cls;
3842   struct NeighbourMapEntry *n = value;
3843   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
3844   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
3845
3846
3847   if (NULL != n->primary_address.address)
3848   {
3849     bandwidth_in = n->primary_address.bandwidth_in;
3850     bandwidth_out = n->primary_address.bandwidth_out;
3851   }
3852   else
3853   {
3854     bandwidth_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
3855     bandwidth_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
3856   }
3857   ic->cb (ic->cb_cls,
3858           &n->id,
3859           n->primary_address.address,
3860           n->state,
3861           n->timeout,
3862           bandwidth_in, bandwidth_out);
3863   return GNUNET_OK;
3864 }
3865
3866
3867 /**
3868  * Iterate over all connected neighbours.
3869  *
3870  * @param cb function to call
3871  * @param cb_cls closure for cb
3872  */
3873 void
3874 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
3875 {
3876   struct IteratorContext ic;
3877
3878   if (NULL == neighbours)
3879     return; /* can happen during shutdown */
3880   ic.cb = cb;
3881   ic.cb_cls = cb_cls;
3882   GNUNET_CONTAINER_multipeermap_iterate (neighbours, &neighbours_iterate, &ic);
3883 }
3884
3885
3886 /**
3887  * If we have an active connection to the given target, it must be shutdown.
3888  *
3889  * @param target peer to disconnect from
3890  */
3891 void
3892 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
3893 {
3894   struct NeighbourMapEntry *n;
3895
3896   if (NULL == (n = lookup_neighbour (target)))
3897     return;  /* not active */
3898   if (GNUNET_YES == test_connected (n))
3899     GNUNET_STATISTICS_update (GST_stats,
3900                               gettext_noop
3901                               ("# disconnected from peer upon explicit request"), 1,
3902                               GNUNET_NO);
3903   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3904               "Forced disconnect from peer %s\n",
3905               GNUNET_i2s (target));
3906   disconnect_neighbour (n);
3907 }
3908
3909
3910 /**
3911  * Obtain current latency information for the given neighbour.
3912  *
3913  * @param peer to get the latency for
3914  * @return observed latency of the address, FOREVER if the
3915  *         the connection is not up
3916  */
3917 struct GNUNET_TIME_Relative
3918 GST_neighbour_get_latency (const struct GNUNET_PeerIdentity *peer)
3919 {
3920   struct NeighbourMapEntry *n;
3921
3922   n = lookup_neighbour (peer);
3923   if (NULL == n)
3924     return GNUNET_TIME_UNIT_FOREVER_REL;
3925   switch (n->state)
3926   {
3927   case GNUNET_TRANSPORT_PS_CONNECTED:
3928   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_CONNECT_SENT:
3929   case GNUNET_TRANSPORT_PS_CONNECTED_SWITCHING_BLACKLIST:
3930   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3931   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3932   case GNUNET_TRANSPORT_PS_RECONNECT_BLACKLIST:
3933     return n->latency;
3934   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3935   case GNUNET_TRANSPORT_PS_INIT_ATS:
3936   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST_INBOUND:
3937   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ATS:
3938   case GNUNET_TRANSPORT_PS_CONNECT_RECV_BLACKLIST:
3939   case GNUNET_TRANSPORT_PS_CONNECT_RECV_ACK:
3940   case GNUNET_TRANSPORT_PS_CONNECT_SENT:
3941   case GNUNET_TRANSPORT_PS_DISCONNECT:
3942   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3943     return GNUNET_TIME_UNIT_FOREVER_REL;
3944   default:
3945     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3946                 "Unhandled state `%s'\n",
3947                 GNUNET_TRANSPORT_ps2s (n->state));
3948     GNUNET_break (0);
3949     break;
3950   }
3951   return GNUNET_TIME_UNIT_FOREVER_REL;
3952 }
3953
3954
3955 /**
3956  * Obtain current address information for the given neighbour.
3957  *
3958  * @param peer
3959  * @return address currently used
3960  */
3961 struct GNUNET_HELLO_Address *
3962 GST_neighbour_get_current_address (const struct GNUNET_PeerIdentity *peer)
3963 {
3964   struct NeighbourMapEntry *n;
3965
3966   n = lookup_neighbour (peer);
3967   if (NULL == n)
3968     return NULL;
3969   return n->primary_address.address;
3970 }
3971
3972
3973 /**
3974  * Initialize the neighbours subsystem.
3975  *
3976  * @param cls closure for callbacks
3977  * @param connect_cb function to call if we connect to a peer
3978  * @param disconnect_cb function to call if we disconnect from a peer
3979  * @param peer_address_cb function to call if we change an active address
3980  *                   of a neighbour
3981  * @param max_fds maximum number of fds to use
3982  */
3983 void
3984 GST_neighbours_start (void *cls,
3985                       NotifyConnect connect_cb,
3986                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb,
3987                       GNUNET_TRANSPORT_NeighbourChangeCallback peer_address_cb,
3988                       unsigned int max_fds)
3989 {
3990   callback_cls = cls;
3991   connect_notify_cb = connect_cb;
3992   disconnect_notify_cb = disconnect_cb;
3993   neighbour_change_cb = peer_address_cb;
3994   neighbours = GNUNET_CONTAINER_multipeermap_create (NEIGHBOUR_TABLE_SIZE, GNUNET_NO);
3995   registered_quota_notifications = GNUNET_CONTAINER_multipeermap_create (NEIGHBOUR_TABLE_SIZE, GNUNET_NO);
3996   util_transmission_tk = GNUNET_SCHEDULER_add_delayed (UTIL_TRANSMISSION_INTERVAL,
3997       utilization_transmission, NULL);
3998 }
3999
4000
4001 /**
4002  * Disconnect from the given neighbour.
4003  *
4004  * @param cls unused
4005  * @param key hash of neighbour's public key (not used)
4006  * @param value the 'struct NeighbourMapEntry' of the neighbour
4007  * @return #GNUNET_OK (continue to iterate)
4008  */
4009 static int
4010 disconnect_all_neighbours (void *cls,
4011                            const struct GNUNET_PeerIdentity *key,
4012                            void *value)
4013 {
4014   struct NeighbourMapEntry *n = value;
4015
4016   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4017               "Disconnecting peer `%4s', %s\n",
4018               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
4019   free_neighbour (n, GNUNET_NO);
4020   return GNUNET_OK;
4021 }
4022
4023
4024 /**
4025  * Cleanup the neighbours subsystem.
4026  */
4027 void
4028 GST_neighbours_stop ()
4029 {
4030   struct BlacklistCheckSwitchContext *cur;
4031   struct BlacklistCheckSwitchContext *next;
4032
4033   if (NULL == neighbours)
4034     return;
4035   if (GNUNET_SCHEDULER_NO_TASK != util_transmission_tk)
4036   {
4037     GNUNET_SCHEDULER_cancel (util_transmission_tk);
4038     util_transmission_tk = GNUNET_SCHEDULER_NO_TASK;
4039   }
4040
4041   GNUNET_CONTAINER_multipeermap_iterate (neighbours,
4042                                          &disconnect_all_neighbours,
4043                                          NULL);
4044   GNUNET_CONTAINER_multipeermap_destroy (neighbours);
4045
4046   next = pending_bc_head;
4047   for (cur = next; NULL != cur; cur = next )
4048   {
4049     next = cur->next;
4050     GNUNET_CONTAINER_DLL_remove (pending_bc_head, pending_bc_tail, cur);
4051
4052     if (NULL != cur->blc)
4053     {
4054       GST_blacklist_test_cancel (cur->blc);
4055       cur->blc = NULL;
4056     }
4057     if (NULL != cur->address)
4058       GNUNET_HELLO_address_free (cur->address);
4059     GNUNET_free_non_null (cur->ats);
4060     GNUNET_free (cur);
4061   }
4062
4063   GNUNET_CONTAINER_multipeermap_iterate (registered_quota_notifications,
4064       &free_notification_cb, NULL);
4065   GNUNET_CONTAINER_multipeermap_destroy (registered_quota_notifications);
4066   registered_quota_notifications = NULL;
4067
4068   neighbours = NULL;
4069   callback_cls = NULL;
4070   connect_notify_cb = NULL;
4071   disconnect_notify_cb = NULL;
4072   neighbour_change_cb = NULL;
4073 }
4074
4075
4076 /* end of file gnunet-service-transport_neighbours.c */