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