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