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