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