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