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