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