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