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