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