document API, do not pass unused 'session' argument
[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_SuggestHandle *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_suggest_address_cancel (GST_ats, &n->id);
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  * FIXME
2096  */
2097 struct BlacklistCheckSwitchContext
2098 {
2099   /**
2100    * FIXME
2101    */
2102   struct BlacklistCheckSwitchContext *prev;
2103
2104   /**
2105    * FIXME
2106    */
2107   struct BlacklistCheckSwitchContext *next;
2108
2109   /**
2110    * FIXME
2111    */
2112   struct GST_BlacklistCheck *blc;
2113
2114   /**
2115    * FIXME
2116    */
2117   struct GNUNET_HELLO_Address *address;
2118
2119   /**
2120    * FIXME
2121    */
2122   struct Session *session;
2123
2124   /**
2125    * FIXME
2126    */
2127   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
2128
2129   /**
2130    * FIXME
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_suggest_address (GST_ats,
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_suggest_address (GST_ats, peer);
2325     break;
2326   case GNUNET_TRANSPORT_PS_INIT_ATS:
2327     /* SYN message takes priority over us asking ATS for address:
2328      * Wait for ATS to suggest an address and send SYN_ACK */
2329     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_SYN_RECV_ATS,
2330         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
2331     break;
2332   case GNUNET_TRANSPORT_PS_SYN_RECV_ATS:
2333     /* We already wait for an address to send an SYN_ACK */
2334     break;
2335   case GNUNET_TRANSPORT_PS_SYN_SENT:
2336   case GNUNET_TRANSPORT_PS_SYN_RECV_ACK:
2337     /* Send ACK immediately */
2338     n->ack_state = ACK_SEND_ACK;
2339     send_connect_ack_message (n->primary_address.address,
2340                               n->primary_address.session, ts);
2341     break;
2342   case GNUNET_TRANSPORT_PS_CONNECTED:
2343     /* we are already connected and can thus send the ACK immediately */
2344     GNUNET_assert (NULL != n->primary_address.address);
2345     GNUNET_assert (NULL != n->primary_address.session);
2346     n->ack_state = ACK_SEND_ACK;
2347     send_connect_ack_message (n->primary_address.address,
2348                               n->primary_address.session, ts);
2349     break;
2350   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
2351     /* We wait for ATS address suggestion */
2352     break;
2353   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
2354     /* We received a SYN message while waiting for a SYN_ACK in fast
2355      * reconnect. Send SYN_ACK immediately */
2356     n->ack_state = ACK_SEND_ACK;
2357     send_connect_ack_message (n->primary_address.address,
2358         n->primary_address.session, n->connect_ack_timestamp);
2359     break;
2360   case GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT:
2361     /* We are already connected and can thus send the ACK immediately;
2362        still, it can never hurt to have an alternative address, so also
2363        tell ATS  about it */
2364     GNUNET_assert (NULL != n->primary_address.address);
2365     GNUNET_assert (NULL != n->primary_address.session);
2366     n->ack_state = ACK_SEND_ACK;
2367     send_connect_ack_message (n->primary_address.address,
2368         n->primary_address.session, ts);
2369     break;
2370   case GNUNET_TRANSPORT_PS_DISCONNECT:
2371     /* Get rid of remains without terminating sessions, ready to re-try */
2372     free_neighbour (n, GNUNET_YES);
2373     n = setup_neighbour (peer);
2374     /* Remember the SYN time stamp for ACK message */
2375     n->ack_state = ACK_SEND_SYN_ACK;
2376     n->connect_ack_timestamp = ts;
2377     /* Request an address for the peer */
2378     n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, peer);
2379     GNUNET_ATS_reset_backoff (GST_ats, peer);
2380     set_state (n, GNUNET_TRANSPORT_PS_SYN_RECV_ATS);
2381     break;
2382   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
2383     /* should not be possible */
2384     GNUNET_assert (0);
2385     break;
2386   default:
2387     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2388                 "Unhandled state `%s'\n",
2389                 GNUNET_TRANSPORT_ps2s (n->state));
2390     GNUNET_break (0);
2391     return GNUNET_SYSERR;
2392   }
2393   return GNUNET_OK;
2394 }
2395
2396
2397 /**
2398  * Check if the given @a address is the same that we are already
2399  * using for the respective neighbour. If so, update the bandwidth
2400  * assignment and possibly the session and return #GNUNET_OK.
2401  * If the new address is different from what the neighbour is
2402  * using right now, return #GNUNET_NO.
2403  *
2404  * @param address address of the other peer,
2405  * @param session session to use or NULL if transport should initiate a session
2406  * @param bandwidth_in inbound quota to be used when connection is up,
2407  *      0 to disconnect from peer
2408  * @param bandwidth_out outbound quota to be used when connection is up,
2409  *      0 to disconnect from peer
2410  * @return #GNUNET_OK if we were able to just update the bandwidth and session,
2411  *         #GNUNET_NO if more extensive changes are required (address changed)
2412  */
2413 static int
2414 try_run_fast_ats_update (const struct GNUNET_HELLO_Address *address,
2415                          struct Session *session,
2416                          struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
2417                          struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
2418 {
2419   struct NeighbourMapEntry *n;
2420   int connected;
2421
2422   n = lookup_neighbour (&address->peer);
2423   if ( (NULL == n) ||
2424        (NULL == n->primary_address.address) ||
2425        (0 != GNUNET_HELLO_address_cmp (address,
2426                                        n->primary_address.address)) )
2427     return GNUNET_NO;
2428   /* We are not really switching addresses, but merely adjusting
2429      session and/or bandwidth, can do fast ATS update! */
2430   if (session != n->primary_address.session)
2431   {
2432     /* switch to a different session, but keeping same address; could
2433        happen if there is a 2nd inbound connection */
2434     connected = GNUNET_TRANSPORT_is_connected (n->state);
2435     if (GNUNET_YES == connected)
2436       GST_ats_set_in_use (n->primary_address.address,
2437                           n->primary_address.session,
2438                           GNUNET_NO);
2439     n->primary_address.session = session;
2440     if (GNUNET_YES == connected)
2441       GST_ats_set_in_use (n->primary_address.address,
2442                           n->primary_address.session,
2443                           GNUNET_YES);
2444   }
2445   n->primary_address.bandwidth_in = bandwidth_in;
2446   n->primary_address.bandwidth_out = bandwidth_out;
2447   GST_neighbours_set_incoming_quota (&address->peer,
2448                                      bandwidth_in);
2449   send_outbound_quota (&address->peer,
2450                        bandwidth_out);
2451   return GNUNET_OK;
2452 }
2453
2454
2455 /**
2456  * We've been asked to switch addresses, and just now got the result
2457  * from the blacklist check to see if this is allowed.
2458  *
2459  * @param cls the `struct BlacklistCheckSwitchContext` with
2460  *        the information about the future address
2461  * @param peer the peer we may switch addresses on
2462  * @param result #GNUNET_NO if we are not allowed to use the new
2463  *        address
2464  */
2465 static void
2466 switch_address_bl_check_cont (void *cls,
2467                               const struct GNUNET_PeerIdentity *peer,
2468                               int result)
2469 {
2470   struct BlacklistCheckSwitchContext *blc_ctx = cls;
2471   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2472   struct NeighbourMapEntry *n;
2473
2474   if (result == GNUNET_NO)
2475   {
2476     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2477                 "Blacklist denied to switch to suggested address `%s' session %p for peer `%s'\n",
2478                 GST_plugins_a2s (blc_ctx->address),
2479                 blc_ctx->session,
2480                 GNUNET_i2s (&blc_ctx->address->peer));
2481     GNUNET_STATISTICS_update (GST_stats,
2482                               "# ATS suggestions ignored (blacklist denied)",
2483                               1,
2484                               GNUNET_NO);
2485     /* FIXME: tell plugin to force killing session here and now! */
2486     /* FIXME: Let ATS know that the suggested address did not work! */
2487     goto cleanup;
2488   }
2489
2490   papi = GST_plugins_find (blc_ctx->address->transport_name);
2491   GNUNET_assert (NULL != papi);
2492
2493   if (NULL == blc_ctx->session)
2494   {
2495     /* need to create a session, ATS only gave us an address */
2496     blc_ctx->session = papi->get_session (papi->cls,
2497                                           blc_ctx->address);
2498     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2499                 "Obtained new session for peer `%s' and  address '%s': %p\n",
2500                 GNUNET_i2s (&blc_ctx->address->peer),
2501                 GST_plugins_a2s (blc_ctx->address),
2502                 blc_ctx->session);
2503     if (NULL != blc_ctx->session)
2504       GST_ats_new_session (blc_ctx->address,
2505                            blc_ctx->session);
2506   }
2507   if (NULL == blc_ctx->session)
2508   {
2509     /* session creation failed, bad!, fail! */
2510     GNUNET_STATISTICS_update (GST_stats,
2511                               "# ATS suggestions ignored (failed to create session)",
2512                               1,
2513                               GNUNET_NO);
2514     /* No session could be obtained, remove blacklist check and clean up */
2515     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2516                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
2517                 GNUNET_i2s (&blc_ctx->address->peer),
2518                 GST_plugins_a2s (blc_ctx->address));
2519     /* FIXME: Let ATS know that the suggested address did not work! */
2520     goto cleanup;
2521   }
2522
2523   /* We did this check already before going into blacklist, but
2524      it is theoretically possible that the situation changed in
2525      the meantime, hence we check again here */
2526   if (GNUNET_OK ==
2527       try_run_fast_ats_update (blc_ctx->address,
2528                                blc_ctx->session,
2529                                blc_ctx->bandwidth_in,
2530                                blc_ctx->bandwidth_out))
2531     goto cleanup; /* was just a minor update, we're done */
2532
2533   /* check if we also need to setup the neighbour entry */
2534   if (NULL == (n = lookup_neighbour (peer)))
2535   {
2536     n = setup_neighbour (peer);
2537     n->state = GNUNET_TRANSPORT_PS_INIT_ATS;
2538   }
2539
2540   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2541               "Peer `%s' switches to address `%s' session %p\n",
2542               GNUNET_i2s (&blc_ctx->address->peer),
2543               GST_plugins_a2s (blc_ctx->address),
2544               blc_ctx->session);
2545
2546   switch (n->state)
2547   {
2548   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
2549     GNUNET_break (0);
2550     free_neighbour (n, GNUNET_NO);
2551     return;
2552   case GNUNET_TRANSPORT_PS_INIT_ATS:
2553     /* We requested an address and ATS suggests one:
2554      * set primary address and send SYN message*/
2555     set_primary_address (n,
2556                          blc_ctx->address,
2557                          blc_ctx->session,
2558                          blc_ctx->bandwidth_in,
2559                          blc_ctx->bandwidth_out,
2560                          GNUNET_NO);
2561     if (ACK_SEND_SYN_ACK == n->ack_state)
2562     {
2563       /* Send pending SYN_ACK message */
2564       n->ack_state = ACK_SEND_ACK;
2565       send_connect_ack_message (n->primary_address.address,
2566                                 n->primary_address.session,
2567                                 n->connect_ack_timestamp);
2568     }
2569     set_state_and_timeout (n,
2570                            GNUNET_TRANSPORT_PS_SYN_SENT,
2571                            GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2572     send_syn (&n->primary_address);
2573     break;
2574   case GNUNET_TRANSPORT_PS_SYN_SENT:
2575     /* ATS suggested a new address while waiting for an SYN_ACK:
2576      * Switch and send new SYN */
2577     /* ATS suggests a different address, switch again */
2578     set_primary_address (n,
2579                          blc_ctx->address,
2580                          blc_ctx->session,
2581                          blc_ctx->bandwidth_in,
2582                          blc_ctx->bandwidth_out,
2583                          GNUNET_NO);
2584     if (ACK_SEND_SYN_ACK == n->ack_state)
2585     {
2586       /* Send pending SYN_ACK message */
2587       n->ack_state = ACK_SEND_ACK;
2588       send_connect_ack_message (n->primary_address.address,
2589                                 n->primary_address.session,
2590                                 n->connect_ack_timestamp);
2591     }
2592     set_state_and_timeout (n,
2593                            GNUNET_TRANSPORT_PS_SYN_SENT,
2594                            GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2595     send_syn (&n->primary_address);
2596     break;
2597   case GNUNET_TRANSPORT_PS_SYN_RECV_ATS:
2598     /* We requested an address and ATS suggests one:
2599      * set primary address and send SYN_ACK message*/
2600     set_primary_address (n,
2601                          blc_ctx->address,
2602                          blc_ctx->session,
2603                          blc_ctx->bandwidth_in,
2604                          blc_ctx->bandwidth_out,
2605                          GNUNET_NO);
2606     /* Send an ACK message as a response to the SYN msg */
2607     set_state_and_timeout (n,
2608                            GNUNET_TRANSPORT_PS_SYN_RECV_ACK,
2609                            GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2610     send_connect_ack_message (n->primary_address.address,
2611                               n->primary_address.session,
2612                               n->connect_ack_timestamp);
2613     if ( (ACK_SEND_SYN_ACK == n->ack_state) ||
2614          (ACK_UNDEFINED == n->ack_state) )
2615       n->ack_state = ACK_SEND_ACK;
2616     break;
2617   case GNUNET_TRANSPORT_PS_SYN_RECV_ACK:
2618     /* ATS asks us to switch while we were trying to connect; switch to new
2619        address and check blacklist again */
2620     if ( (ACK_SEND_SYN_ACK == n->ack_state) )
2621     {
2622       n->ack_state = ACK_SEND_ACK;
2623       send_connect_ack_message (n->primary_address.address,
2624                                 n->primary_address.session,
2625                                 n->connect_ack_timestamp);
2626     }
2627     set_primary_address (n,
2628                          blc_ctx->address,
2629                          blc_ctx->session,
2630                          blc_ctx->bandwidth_in,
2631                          blc_ctx->bandwidth_out,
2632                          GNUNET_NO);
2633     set_state_and_timeout (n,
2634                            GNUNET_TRANSPORT_PS_SYN_RECV_ACK,
2635                            GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2636     break;
2637   case GNUNET_TRANSPORT_PS_CONNECTED:
2638     GNUNET_assert (NULL != n->primary_address.address);
2639     GNUNET_assert (NULL != n->primary_address.session);
2640     if (n->primary_address.session == blc_ctx->session)
2641     {
2642       /* not an address change, just a quota change */
2643       // FIXME: this case should have been caught above!
2644       set_primary_address (n,
2645                            blc_ctx->address,
2646                            blc_ctx->session,
2647                            blc_ctx->bandwidth_in,
2648                            blc_ctx->bandwidth_out,
2649                            GNUNET_YES);
2650       break;
2651     }
2652     /* ATS asks us to switch a life connection; see if we can get
2653        a SYN_ACK on it before we actually do this! */
2654     set_alternative_address (n,
2655                              blc_ctx->address,
2656                              blc_ctx->session,
2657                              blc_ctx->bandwidth_in,
2658                              blc_ctx->bandwidth_out);
2659     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT,
2660                            GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2661     GNUNET_STATISTICS_update (GST_stats,
2662                               gettext_noop ("# Attempts to switch addresses"),
2663                               1,
2664                               GNUNET_NO);
2665     send_syn (&n->alternative_address);
2666     break;
2667   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
2668     set_primary_address (n,
2669                          blc_ctx->address,
2670                          blc_ctx->session,
2671                          blc_ctx->bandwidth_in,
2672                          blc_ctx->bandwidth_out,
2673                          GNUNET_NO);
2674     if (ACK_SEND_SYN_ACK == n->ack_state)
2675     {
2676       /* Send pending SYN_ACK message */
2677       n->ack_state = ACK_SEND_ACK;
2678       send_connect_ack_message (n->primary_address.address,
2679                                 n->primary_address.session,
2680                                 n->connect_ack_timestamp);
2681     }
2682     set_state_and_timeout (n,
2683                            GNUNET_TRANSPORT_PS_RECONNECT_SENT,
2684                            GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT));
2685     send_syn (&n->primary_address);
2686     break;
2687   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
2688     /* ATS asks us to switch while we were trying to reconnect; switch to new
2689        address and send SYN again */
2690     set_primary_address (n,
2691                          blc_ctx->address,
2692                          blc_ctx->session,
2693                          blc_ctx->bandwidth_in,
2694                          blc_ctx->bandwidth_out,
2695                          GNUNET_NO);
2696     set_state_and_timeout (n,
2697                            GNUNET_TRANSPORT_PS_RECONNECT_SENT,
2698                            GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT));
2699     send_syn (&n->primary_address);
2700     break;
2701   case GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT:
2702     if ( (0 == GNUNET_HELLO_address_cmp(n->primary_address.address,
2703                                         blc_ctx->address)) &&
2704          (n->primary_address.session == blc_ctx->session) )
2705     {
2706       /* ATS switches back to still-active session */
2707       free_address (&n->alternative_address);
2708       set_state (n, GNUNET_TRANSPORT_PS_CONNECTED);
2709       break;
2710     }
2711     /* ATS asks us to switch a life connection, send */
2712     set_alternative_address (n,
2713                              blc_ctx->address,
2714                              blc_ctx->session,
2715                              blc_ctx->bandwidth_in,
2716                              blc_ctx->bandwidth_out);
2717     set_state_and_timeout (n,
2718                            GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT,
2719                            GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT));
2720     send_syn (&n->alternative_address);
2721     break;
2722   case GNUNET_TRANSPORT_PS_DISCONNECT:
2723     /* not going to switch addresses while disconnecting */
2724     GNUNET_STATISTICS_update (GST_stats,
2725                               "# ATS suggestion ignored (disconnecting)",
2726                               1,
2727                               GNUNET_NO);
2728     return;
2729   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
2730     GNUNET_assert (0);
2731     break;
2732   default:
2733     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2734                 "Unhandled state `%s'\n",
2735                 GNUNET_TRANSPORT_ps2s (n->state));
2736     GNUNET_break (0);
2737     break;
2738   }
2739  cleanup:
2740   GNUNET_CONTAINER_DLL_remove (pending_bc_head,
2741                                pending_bc_tail,
2742                                blc_ctx);
2743   GNUNET_HELLO_address_free (blc_ctx->address);
2744   GNUNET_free (blc_ctx);
2745 }
2746
2747
2748 /**
2749  * For the given peer, switch to this address.
2750  *
2751  * Before accepting this addresses and actively using it, a blacklist check
2752  * is performed. If this blacklist check fails the address will be destroyed.
2753  *
2754  * @param address address of the other peer,
2755  * @param session session to use or NULL if transport should initiate a session
2756  * @param bandwidth_in inbound quota to be used when connection is up,
2757  *      0 to disconnect from peer
2758  * @param bandwidth_out outbound quota to be used when connection is up,
2759  *      0 to disconnect from peer
2760  */
2761 void
2762 GST_neighbours_switch_to_address (const struct GNUNET_HELLO_Address *address,
2763                                   struct Session *session,
2764                                   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
2765                                   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
2766 {
2767   struct GST_BlacklistCheck *blc;
2768   struct BlacklistCheckSwitchContext *blc_ctx;
2769
2770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2771               "ATS has decided on an address for peer %s\n",
2772               GNUNET_i2s (&address->peer));
2773   GNUNET_assert (NULL != address->transport_name);
2774   if (GNUNET_OK ==
2775       try_run_fast_ats_update (address,
2776                                session,
2777                                bandwidth_in,
2778                                bandwidth_out))
2779     return;
2780
2781   /* Check if plugin is available */
2782   if (NULL == (GST_plugins_find (address->transport_name)))
2783   {
2784     /* we don't have the plugin for this address */
2785     GNUNET_break (0);
2786     return;
2787   }
2788   if ((NULL == session) &&
2789       (GNUNET_HELLO_address_check_option (address,
2790                                           GNUNET_HELLO_ADDRESS_INFO_INBOUND)))
2791   {
2792     /* This is a inbound address and we do not have a session to use! */
2793     GNUNET_break (0);
2794     return;
2795   }
2796
2797   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2798               "ATS suggests %s address '%s' for peer `%s'\n",
2799               GNUNET_HELLO_address_check_option (address,
2800                                                  GNUNET_HELLO_ADDRESS_INFO_INBOUND)
2801               ? "inbound" : "outbound",
2802               GST_plugins_a2s (address),
2803               GNUNET_i2s (&address->peer));
2804
2805   /* Perform blacklist check */
2806   blc_ctx = GNUNET_new (struct BlacklistCheckSwitchContext);
2807   blc_ctx->address = GNUNET_HELLO_address_copy (address);
2808   blc_ctx->session = session;
2809   blc_ctx->bandwidth_in = bandwidth_in;
2810   blc_ctx->bandwidth_out = bandwidth_out;
2811   GNUNET_CONTAINER_DLL_insert (pending_bc_head,
2812                                pending_bc_tail,
2813                                blc_ctx);
2814   if (NULL != (blc = GST_blacklist_test_allowed (&address->peer,
2815                                                  address->transport_name,
2816                                                  &switch_address_bl_check_cont,
2817                                                  blc_ctx)))
2818   {
2819     blc_ctx->blc = blc;
2820   }
2821 }
2822
2823
2824 /**
2825  * Function called to send network utilization data to ATS for
2826  * each active connection.
2827  *
2828  * @param cls NULL
2829  * @param key peer we send utilization data for
2830  * @param value the `struct NeighbourMapEntry *` with data to send
2831  * @return #GNUNET_OK (continue to iterate)
2832  */
2833 static int
2834 send_utilization_data (void *cls,
2835                        const struct GNUNET_PeerIdentity *key,
2836                        void *value)
2837 {
2838   struct NeighbourMapEntry *n = value;
2839   struct GNUNET_ATS_Information atsi[4];
2840   uint32_t bps_pl_in;
2841   uint32_t bps_pl_out;
2842   uint32_t bps_in;
2843   uint32_t bps_out;
2844   struct GNUNET_TIME_Relative delta;
2845
2846   if (GNUNET_TRANSPORT_PS_CONNECTED != n->state)
2847     return GNUNET_OK;
2848   delta = GNUNET_TIME_absolute_get_difference (n->last_util_transmission,
2849                                                GNUNET_TIME_absolute_get ());
2850
2851   bps_pl_in = 0;
2852
2853   if ((0 != n->util_payload_bytes_recv) && (0 != delta.rel_value_us))
2854     bps_pl_in =  (1000LL * 1000LL *  n->util_payload_bytes_recv) / (delta.rel_value_us);
2855   bps_pl_out = 0;
2856   if ((0 != n->util_payload_bytes_sent) && (0 != delta.rel_value_us))
2857     bps_pl_out = (1000LL * 1000LL * n->util_payload_bytes_sent) / delta.rel_value_us;
2858   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2859               "`%s' payload: received %u Bytes/s, sent %u Bytes/s\n",
2860               GNUNET_i2s (key),
2861               bps_pl_in,
2862               bps_pl_out);
2863   bps_in = 0;
2864   if ((0 != n->util_total_bytes_recv) && (0 != delta.rel_value_us))
2865     bps_in =  (1000LL * 1000LL *  n->util_total_bytes_recv) / (delta.rel_value_us);
2866   bps_out = 0;
2867   if ((0 != n->util_total_bytes_sent) && (0 != delta.rel_value_us))
2868     bps_out = (1000LL * 1000LL * n->util_total_bytes_sent) / delta.rel_value_us;
2869
2870
2871   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2872               "`%s' total: received %u Bytes/s, sent %u Bytes/s\n",
2873               GNUNET_i2s (key),
2874               bps_in,
2875               bps_out);
2876   atsi[0].type = htonl (GNUNET_ATS_UTILIZATION_OUT);
2877   atsi[0].value = htonl (bps_out);
2878   atsi[1].type = htonl (GNUNET_ATS_UTILIZATION_IN);
2879   atsi[1].value = htonl (bps_in);
2880
2881   atsi[2].type = htonl (GNUNET_ATS_UTILIZATION_PAYLOAD_OUT);
2882   atsi[2].value = htonl (bps_pl_out);
2883   atsi[3].type = htonl (GNUNET_ATS_UTILIZATION_PAYLOAD_IN);
2884   atsi[3].value = htonl (bps_pl_in);
2885
2886   GST_ats_update_metrics (n->primary_address.address,
2887                           n->primary_address.session,
2888                           atsi, 4);
2889   n->util_payload_bytes_recv = 0;
2890   n->util_payload_bytes_sent = 0;
2891   n->util_total_bytes_recv = 0;
2892   n->util_total_bytes_sent = 0;
2893   n->last_util_transmission = GNUNET_TIME_absolute_get ();
2894   return GNUNET_OK;
2895 }
2896
2897
2898 /**
2899  * Task transmitting utilization in a regular interval
2900  *
2901  * @param cls the 'struct NeighbourMapEntry' for which we are running
2902  * @param tc scheduler context (unused)
2903  */
2904 static void
2905 utilization_transmission (void *cls,
2906                           const struct GNUNET_SCHEDULER_TaskContext *tc)
2907 {
2908   util_transmission_tk = NULL;
2909
2910   if (0 < GNUNET_CONTAINER_multipeermap_size (neighbours))
2911     GNUNET_CONTAINER_multipeermap_iterate (neighbours, send_utilization_data, NULL);
2912
2913   util_transmission_tk = GNUNET_SCHEDULER_add_delayed (UTIL_TRANSMISSION_INTERVAL,
2914       utilization_transmission, NULL);
2915
2916 }
2917
2918
2919 /**
2920  * Track information about data we received from the
2921  * given address (used to notify ATS about our utilization
2922  * of allocated resources).
2923  *
2924  * @param address the address we got data from
2925  * @param message the message we received (really only the size is used)
2926  */
2927 void
2928 GST_neighbours_notify_data_recv (const struct GNUNET_HELLO_Address *address,
2929                                  const struct GNUNET_MessageHeader *message)
2930 {
2931   struct NeighbourMapEntry *n;
2932
2933   n = lookup_neighbour (&address->peer);
2934   if (NULL == n)
2935     return;
2936   n->util_total_bytes_recv += ntohs (message->size);
2937 }
2938
2939
2940 /**
2941  * Track information about payload (useful data) we received from the
2942  * given address (used to notify ATS about our utilization of
2943  * allocated resources).
2944  *
2945  * @param address the address we got data from
2946  * @param message the message we received (really only the size is used)
2947  */
2948 void
2949 GST_neighbours_notify_payload_recv (const struct GNUNET_HELLO_Address *address,
2950                                     const struct GNUNET_MessageHeader *message)
2951 {
2952   struct NeighbourMapEntry *n;
2953
2954   n = lookup_neighbour (&address->peer);
2955   if (NULL == n)
2956     return;
2957   n->util_payload_bytes_recv += ntohs (message->size);
2958 }
2959
2960
2961 /**
2962  * Track information about data we transmitted using the given @a
2963  * address and @a session (used to notify ATS about our utilization of
2964  * allocated resources).
2965  *
2966  * @param address the address we transmitted data to
2967  * @param session session we used to transmit data
2968  * @param message the message we sent (really only the size is used)
2969  */
2970 void
2971 GST_neighbours_notify_data_sent (const struct GNUNET_HELLO_Address *address,
2972                                  struct Session *session,
2973                                  size_t size)
2974 {
2975   struct NeighbourMapEntry *n;
2976
2977   n = lookup_neighbour (&address->peer);
2978   if (NULL == n)
2979       return;
2980   if (n->primary_address.session != session)
2981     return;
2982   n->util_total_bytes_sent += size;
2983 }
2984
2985
2986 /**
2987  * Track information about payload (useful data) we transmitted using the
2988  * given address (used to notify ATS about our utilization of
2989  * allocated resources).
2990  *
2991  * @param address the address we transmitted data to
2992  * @param message the message we sent (really only the size is used)
2993  */
2994 void
2995 GST_neighbours_notify_payload_sent (const struct GNUNET_PeerIdentity *peer,
2996                                     size_t size)
2997 {
2998   struct NeighbourMapEntry *n;
2999
3000   n = lookup_neighbour (peer);
3001   if (NULL == n)
3002     return;
3003   n->util_payload_bytes_sent += size;
3004 }
3005
3006
3007 /**
3008  * Master task run for every neighbour.  Performs all of the time-related
3009  * activities (keep alive, send next message, disconnect if idle, finish
3010  * clean up after disconnect).
3011  *
3012  * @param cls the 'struct NeighbourMapEntry' for which we are running
3013  * @param tc scheduler context (unused)
3014  */
3015 static void
3016 master_task (void *cls,
3017              const struct GNUNET_SCHEDULER_TaskContext *tc)
3018 {
3019   struct NeighbourMapEntry *n = cls;
3020   struct GNUNET_TIME_Relative delay;
3021
3022   n->task = NULL;
3023   delay = GNUNET_TIME_absolute_get_remaining (n->timeout);
3024   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3025               "Master task runs for neighbour `%s' in state %s with timeout in %s\n",
3026               GNUNET_i2s (&n->id),
3027               GNUNET_TRANSPORT_ps2s(n->state),
3028               GNUNET_STRINGS_relative_time_to_string (delay,
3029                                                       GNUNET_YES));
3030   switch (n->state)
3031   {
3032   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3033     /* invalid state for master task, clean up */
3034     GNUNET_break (0);
3035     free_neighbour (n, GNUNET_NO);
3036     return;
3037   case GNUNET_TRANSPORT_PS_INIT_ATS:
3038     if (0 == delay.rel_value_us)
3039     {
3040       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3041                   "Connection to `%s' timed out waiting for ATS to provide address\n",
3042                   GNUNET_i2s (&n->id));
3043       free_neighbour (n, GNUNET_NO);
3044       return;
3045     }
3046     break;
3047   case GNUNET_TRANSPORT_PS_SYN_SENT:
3048     if (0 == delay.rel_value_us)
3049     {
3050       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3051                   "Connection to `%s' timed out waiting for other peer to send SYN_ACK\n",
3052                   GNUNET_i2s (&n->id));
3053       /* Remove address and request and additional one */
3054       unset_primary_address (n);
3055       set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
3056           GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3057       return;
3058     }
3059     break;
3060   case GNUNET_TRANSPORT_PS_SYN_RECV_ATS:
3061     if (0 == delay.rel_value_us)
3062     {
3063       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3064                   "Connection to `%s' timed out waiting ATS to provide address to use for SYN_ACK\n",
3065                   GNUNET_i2s (&n->id));
3066       free_neighbour (n, GNUNET_NO);
3067       return;
3068     }
3069     break;
3070   case GNUNET_TRANSPORT_PS_SYN_RECV_ACK:
3071     if (0 == delay.rel_value_us)
3072     {
3073       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3074                   "Connection to `%s' timed out waiting for other peer to send ACK\n",
3075                   GNUNET_i2s (&n->id));
3076       disconnect_neighbour (n);
3077       return;
3078     }
3079     break;
3080   case GNUNET_TRANSPORT_PS_CONNECTED:
3081     if (0 == delay.rel_value_us)
3082     {
3083       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3084                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
3085                   GNUNET_i2s (&n->id));
3086       disconnect_neighbour (n);
3087       return;
3088     }
3089     try_transmission_to_peer (n);
3090     send_keepalive (n);
3091     break;
3092   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3093     if (0 == delay.rel_value_us)
3094     {
3095       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3096                   "Connection to `%s' timed out, waiting for ATS replacement address\n",
3097                   GNUNET_i2s (&n->id));
3098       disconnect_neighbour (n);
3099       return;
3100     }
3101     break;
3102   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3103     if (0 == delay.rel_value_us)
3104     {
3105       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3106                   "Connection to `%s' timed out, waiting for other peer to SYN_ACK replacement address\n",
3107                   GNUNET_i2s (&n->id));
3108       disconnect_neighbour (n);
3109       return;
3110     }
3111     break;
3112   case GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT:
3113     if (0 == delay.rel_value_us)
3114     {
3115       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3116                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs (after trying to SYN on alternative address)\n",
3117                   GNUNET_i2s (&n->id));
3118       GNUNET_STATISTICS_update (GST_stats,
3119                                 gettext_noop ("# Failed attempts to switch addresses (no response)"),
3120                                 1,
3121                                 GNUNET_NO);
3122       disconnect_neighbour (n);
3123       return;
3124     }
3125     try_transmission_to_peer (n);
3126     send_keepalive (n);
3127     break;
3128   case GNUNET_TRANSPORT_PS_DISCONNECT:
3129     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3130                 "Cleaning up connection to `%s' after sending DISCONNECT\n",
3131                 GNUNET_i2s (&n->id));
3132     free_neighbour (n, GNUNET_NO);
3133     return;
3134   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3135     /* how did we get here!? */
3136     GNUNET_assert (0);
3137     break;
3138   default:
3139     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3140                 "Unhandled state `%s'\n",
3141                 GNUNET_TRANSPORT_ps2s (n->state));
3142     GNUNET_break (0);
3143     break;
3144   }
3145   if ( (GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT == n->state) ||
3146        (GNUNET_TRANSPORT_PS_CONNECTED == n->state) )
3147   {
3148     /* if we are *now* in one of the two states, we're sending
3149        keep alive messages, so we need to consider the keepalive
3150        delay, not just the connection timeout */
3151     delay = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time),
3152                                       delay);
3153   }
3154   if (NULL == n->task)
3155     n->task = GNUNET_SCHEDULER_add_delayed (delay,
3156                                             &master_task,
3157                                             n);
3158 }
3159
3160
3161 /**
3162  * Send a ACK message to the neighbour to confirm that we
3163  * got his SYN_ACK.
3164  *
3165  * @param n neighbour to send the ACK to
3166  */
3167 static void
3168 send_session_ack_message (struct NeighbourMapEntry *n)
3169 {
3170   struct GNUNET_MessageHeader msg;
3171
3172   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Sending ACK message to peer `%s'\n",
3173               GNUNET_i2s (&n->id));
3174
3175   msg.size = htons (sizeof (struct GNUNET_MessageHeader));
3176   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
3177   (void) send_with_session(n,
3178                            (const char *) &msg, sizeof (struct GNUNET_MessageHeader),
3179                            UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_NO,
3180                            NULL, NULL);
3181 }
3182
3183
3184 /**
3185  * We received a 'SESSION_SYN_ACK' message from the other peer.
3186  * Consider switching to it.
3187  *
3188  * @param message possibly a 'struct SessionConnectMessage' (check format)
3189  * @param peer identity of the peer to switch the address for
3190  * @param address address of the other peer, NULL if other peer
3191  *                       connected to us
3192  * @param session session to use (or NULL)
3193  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
3194  */
3195 int
3196 GST_neighbours_handle_session_syn_ack (const struct GNUNET_MessageHeader *message,
3197                                        const struct GNUNET_HELLO_Address *address,
3198                                        struct Session *session)
3199 {
3200   const struct TransportSynMessage *scm;
3201   struct GNUNET_TIME_Absolute ts;
3202   struct NeighbourMapEntry *n;
3203
3204   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3205               "Received SYN_ACK message from peer `%s'\n",
3206               GNUNET_i2s (&address->peer));
3207
3208   if (ntohs (message->size) != sizeof (struct TransportSynMessage))
3209   {
3210     GNUNET_break_op (0);
3211     return GNUNET_SYSERR;
3212   }
3213   GNUNET_STATISTICS_update (GST_stats,
3214                             gettext_noop
3215                             ("# SYN_ACK messages received"),
3216                             1, GNUNET_NO);
3217   scm = (const struct TransportSynMessage *) message;
3218   GNUNET_break_op (ntohl (scm->reserved) == 0);
3219   if (NULL == (n = lookup_neighbour (&address->peer)))
3220   {
3221     GNUNET_STATISTICS_update (GST_stats,
3222                               gettext_noop
3223                               ("# unexpected SYN_ACK messages (no peer)"),
3224                               1, GNUNET_NO);
3225     return GNUNET_SYSERR;
3226   }
3227   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
3228   switch (n->state)
3229   {
3230   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3231     GNUNET_break (0);
3232     free_neighbour (n, GNUNET_NO);
3233     return GNUNET_SYSERR;
3234   case GNUNET_TRANSPORT_PS_INIT_ATS:
3235     GNUNET_STATISTICS_update (GST_stats,
3236                               gettext_noop
3237                               ("# unexpected SYN_ACK messages (not ready)"),
3238                               1, GNUNET_NO);
3239     break;
3240   case GNUNET_TRANSPORT_PS_SYN_SENT:
3241     if (ts.abs_value_us != n->primary_address.connect_timestamp.abs_value_us)
3242     {
3243       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3244                   "SYN_ACK ignored as the timestamp does not match our SYN request\n");
3245       return GNUNET_OK;
3246     }
3247     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED,
3248         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3249     GNUNET_STATISTICS_set (GST_stats,
3250                            gettext_noop ("# peers connected"),
3251                            ++neighbours_connected,
3252                            GNUNET_NO);
3253     neighbours_connect_notification (&n->id,
3254                                      n->primary_address.bandwidth_in,
3255                                      n->primary_address.bandwidth_out);
3256     /* Tell ATS that the outbound session we created to send SYN was successful */
3257     set_primary_address (n,
3258                          n->primary_address.address,
3259                          n->primary_address.session,
3260                          n->primary_address.bandwidth_in,
3261                          n->primary_address.bandwidth_out,
3262                          GNUNET_YES);
3263     send_session_ack_message (n);
3264     break;
3265   case GNUNET_TRANSPORT_PS_SYN_RECV_ATS:
3266   case GNUNET_TRANSPORT_PS_SYN_RECV_ACK:
3267     GNUNET_STATISTICS_update (GST_stats,
3268                               gettext_noop
3269                               ("# unexpected SYN_ACK messages (not ready)"),
3270                               1, GNUNET_NO);
3271     break;
3272   case GNUNET_TRANSPORT_PS_CONNECTED:
3273     /* duplicate SYN_ACK, let's answer by duplicate ACK just in case */
3274     send_session_ack_message (n);
3275     break;
3276   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3277     /* we didn't expect any SYN_ACK, as we are waiting for ATS
3278        to give us a new address... */
3279     GNUNET_STATISTICS_update (GST_stats,
3280                               gettext_noop
3281                               ("# unexpected SYN_ACK messages (waiting on ATS)"),
3282                               1, GNUNET_NO);
3283     break;
3284   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3285     /* Reconnecting with new address address worked; go back to connected! */
3286     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED,
3287         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3288     send_session_ack_message (n);
3289     break;
3290   case GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT:
3291     /* new address worked; adopt it and go back to connected! */
3292     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED,
3293                            GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3294     GNUNET_break (GNUNET_NO == n->alternative_address.ats_active);
3295
3296     /* Set primary addresses */
3297     set_primary_address (n, n->alternative_address.address,
3298         n->alternative_address.session, n->alternative_address.bandwidth_in,
3299         n->alternative_address.bandwidth_out, GNUNET_YES);
3300     GNUNET_STATISTICS_update (GST_stats, gettext_noop
3301         ("# Successful attempts to switch addresses"), 1, GNUNET_NO);
3302
3303     free_address (&n->alternative_address);
3304     send_session_ack_message (n);
3305     break;
3306   case GNUNET_TRANSPORT_PS_DISCONNECT:
3307     GNUNET_STATISTICS_update (GST_stats,
3308                               gettext_noop
3309                               ("# unexpected SYN_ACK messages (disconnecting)"),
3310                               1, GNUNET_NO);
3311     return GNUNET_SYSERR;
3312   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3313     GNUNET_assert (0);
3314     break;
3315   default:
3316     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3317                 "Unhandled state `%s'\n",
3318                 GNUNET_TRANSPORT_ps2s (n->state));
3319     GNUNET_break (0);
3320     return GNUNET_SYSERR;
3321   }
3322   return GNUNET_OK;
3323 }
3324
3325
3326 /**
3327  * A session was terminated. Take note; if needed, try to get
3328  * an alternative address from ATS.
3329  *
3330  * @param peer identity of the peer where the session died
3331  * @param session session that is gone
3332  * @return #GNUNET_YES if this was a session used, #GNUNET_NO if
3333  *        this session was not in use
3334  */
3335 int
3336 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
3337                                    struct Session *session)
3338 {
3339   struct NeighbourMapEntry *n;
3340   struct BlackListCheckContext *bcc;
3341   struct BlackListCheckContext *bcc_next;
3342
3343   /* make sure to cancel all ongoing blacklist checks involving 'session' */
3344   bcc_next = bc_head;
3345   while (NULL != (bcc = bcc_next))
3346   {
3347     bcc_next = bcc->next;
3348     if (bcc->na.session == session)
3349     {
3350       if (NULL != bcc->bc)
3351         GST_blacklist_test_cancel (bcc->bc);
3352       GNUNET_HELLO_address_free (bcc->na.address);
3353       GNUNET_CONTAINER_DLL_remove (bc_head,
3354                                    bc_tail,
3355                                    bcc);
3356       GNUNET_free (bcc);
3357     }
3358   }
3359   if (NULL == (n = lookup_neighbour (peer)))
3360     return GNUNET_NO; /* can't affect us */
3361   if (session != n->primary_address.session)
3362   {
3363     /* Free alternative address */
3364     if (session == n->alternative_address.session)
3365     {
3366       if ( (GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT == n->state) )
3367         set_state (n, GNUNET_TRANSPORT_PS_CONNECTED);
3368       free_address (&n->alternative_address);
3369     }
3370     return GNUNET_NO; /* doesn't affect us further */
3371   }
3372
3373   n->expect_latency_response = GNUNET_NO;
3374   /* The session for neighbour's primary address died */
3375   switch (n->state)
3376   {
3377   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3378     GNUNET_break (0);
3379     free_neighbour (n, GNUNET_NO);
3380     return GNUNET_YES;
3381   case GNUNET_TRANSPORT_PS_INIT_ATS:
3382     GNUNET_break (0);
3383     free_neighbour (n, GNUNET_NO);
3384     return GNUNET_YES;
3385   case GNUNET_TRANSPORT_PS_SYN_SENT:
3386     /* The session used to send the SYN terminated:
3387      * this implies a connect error*/
3388     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3389                 "Failed to send SYN in %s with `%s' %p: session terminated\n",
3390                 "CONNECT_SENT",
3391                 GST_plugins_a2s (n->primary_address.address),
3392                 n->primary_address.session,
3393                 GNUNET_i2s (peer));
3394
3395     /* Destroy the address since it cannot be used */
3396     unset_primary_address (n);
3397     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_INIT_ATS,
3398         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3399     break;
3400   case GNUNET_TRANSPORT_PS_SYN_RECV_ATS:
3401   case GNUNET_TRANSPORT_PS_SYN_RECV_ACK:
3402     /* error on inbound session; free neighbour entirely */
3403     free_address (&n->primary_address);
3404     free_neighbour (n, GNUNET_NO);
3405     return GNUNET_YES;
3406   case GNUNET_TRANSPORT_PS_CONNECTED:
3407     /* Our primary connection died, try a fast reconnect */
3408     unset_primary_address (n);
3409     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_ATS,
3410         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3411     break;
3412   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3413     /* we don't have an address, how can it go down? */
3414     GNUNET_break (0);
3415     break;
3416   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3417     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3418                 "Failed to send SYN in %s with `%s' %p: session terminated\n",
3419                 "RECONNECT_SENT",
3420                 GST_plugins_a2s (n->primary_address.address),
3421                 n->primary_address.session,
3422                 GNUNET_i2s (peer));
3423     /* Destroy the address since it cannot be used */
3424     unset_primary_address (n);
3425     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_ATS,
3426         GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT));
3427     break;
3428   case GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT:
3429     /* primary went down while we were waiting for SYN_ACK on secondary;
3430        secondary as primary */
3431
3432     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3433         "Connection `%s' %p to peer `%s' was terminated while switching, "
3434         "switching to alternative address `%s' %p\n",
3435         GST_plugins_a2s (n->primary_address.address),
3436         n->primary_address.session,
3437         GNUNET_i2s (peer),
3438         GST_plugins_a2s (n->alternative_address.address),
3439         n->alternative_address.session);
3440
3441     /* Destroy the inbound address since it cannot be used */
3442     free_address (&n->primary_address);
3443     n->primary_address = n->alternative_address;
3444     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
3445     set_state_and_timeout (n, GNUNET_TRANSPORT_PS_RECONNECT_SENT,
3446         GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT));
3447     break;
3448   case GNUNET_TRANSPORT_PS_DISCONNECT:
3449     free_address (&n->primary_address);
3450     break;
3451   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3452     /* neighbour was freed and plugins told to terminate session */
3453     return GNUNET_NO;
3454     break;
3455   default:
3456     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3457                 "Unhandled state `%s'\n",
3458                 GNUNET_TRANSPORT_ps2s (n->state));
3459     GNUNET_break (0);
3460     break;
3461   }
3462   if (NULL != n->task)
3463     GNUNET_SCHEDULER_cancel (n->task);
3464   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
3465   return GNUNET_YES;
3466 }
3467
3468
3469 /**
3470  * We received a 'ACK' message from the other peer.
3471  * If we sent a 'SYN_ACK' last, this means we are now
3472  * connected.  Otherwise, do nothing.
3473  *
3474  * @param message possibly a 'struct SessionConnectMessage' (check format)
3475  * @param address address of the other peer
3476  * @param session session to use (or NULL)
3477  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
3478  */
3479 int
3480 GST_neighbours_handle_session_ack (const struct GNUNET_MessageHeader *message,
3481                                    const struct GNUNET_HELLO_Address *address,
3482                                    struct Session *session)
3483 {
3484   struct NeighbourMapEntry *n;
3485
3486   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3487               "Received ACK message from peer `%s'\n",
3488               GNUNET_i2s (&address->peer));
3489   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
3490   {
3491     GNUNET_break_op (0);
3492     return GNUNET_SYSERR;
3493   }
3494   GNUNET_STATISTICS_update (GST_stats,
3495                             gettext_noop
3496                             ("# ACK messages received"),
3497                             1, GNUNET_NO);
3498   if (NULL == (n = lookup_neighbour (&address->peer)))
3499   {
3500     GNUNET_break_op (0);
3501     return GNUNET_SYSERR;
3502   }
3503
3504   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3505               "Received %s for peer `%s' in state %s/%s\n",
3506               "ACK",
3507               GNUNET_i2s (&address->peer),
3508               GNUNET_TRANSPORT_ps2s (n->state),
3509               print_ack_state (n->ack_state));
3510
3511   /* Check if we are in a plausible state for having sent
3512      a SYN_ACK.  If not, return, otherwise break.
3513
3514      The remote peers sends a ACK as a response for a SYN_ACK
3515      message.
3516
3517      We expect a ACK:
3518      - If a remote peer has sent a SYN, we responded with a SYN_ACK and
3519      now wait for the ACK to finally be connected
3520      - If we sent a SYN_ACK to this peer before */
3521
3522   if ( (GNUNET_TRANSPORT_PS_SYN_RECV_ACK != n->state) &&
3523        (ACK_SEND_ACK != n->ack_state))
3524   {
3525     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3526                 "Received unexpected ACK message from peer `%s' in state %s/%s\n",
3527                 GNUNET_i2s (&address->peer),
3528                 GNUNET_TRANSPORT_ps2s (n->state),
3529                 print_ack_state (n->ack_state));
3530
3531     GNUNET_STATISTICS_update (GST_stats,
3532                               gettext_noop ("# unexpected ACK messages"), 1,
3533                               GNUNET_NO);
3534     return GNUNET_OK;
3535   }
3536
3537   /* We are connected */
3538   if (GNUNET_NO == GST_neighbours_test_connected(&n->id))
3539   {
3540     /* Notify about connection */
3541     neighbours_connect_notification (&n->id,
3542                                      n->primary_address.bandwidth_in,
3543                                      n->primary_address.bandwidth_out);
3544     GNUNET_STATISTICS_set (GST_stats,
3545                            gettext_noop ("# peers connected"),
3546                            ++neighbours_connected,
3547                            GNUNET_NO);
3548   }
3549
3550   if (GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT == n->state)
3551   {
3552     /* We tried to switch addresses while being connect. We explicitly wait
3553      * for a SYN_ACK before going to GNUNET_TRANSPORT_PS_CONNECTED,
3554      * so we do not want to set the address as in use! */
3555     return GNUNET_OK;
3556   }
3557
3558   set_state_and_timeout (n, GNUNET_TRANSPORT_PS_CONNECTED,
3559     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
3560
3561   /* Set primary address to used */
3562   set_primary_address (n,
3563                        n->primary_address.address,
3564                        n->primary_address.session,
3565                        n->primary_address.bandwidth_in,
3566                        n->primary_address.bandwidth_out,
3567                        GNUNET_YES);
3568   return GNUNET_OK;
3569 }
3570
3571
3572 /**
3573  * Test if we're connected to the given peer.
3574  *
3575  * @param target peer to test
3576  * @return #GNUNET_YES if we are connected, #GNUNET_NO if not
3577  */
3578 int
3579 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
3580 {
3581   return test_connected (lookup_neighbour (target));
3582 }
3583
3584
3585 /**
3586  * Change the incoming quota for the given peer.
3587  *
3588  * @param neighbour identity of peer to change qutoa for
3589  * @param quota new quota
3590  */
3591 void
3592 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
3593                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
3594 {
3595   struct NeighbourMapEntry *n;
3596
3597   if (NULL == (n = lookup_neighbour (neighbour)))
3598   {
3599     GNUNET_STATISTICS_update (GST_stats,
3600                               gettext_noop
3601                               ("# SET QUOTA messages ignored (no such peer)"),
3602                               1, GNUNET_NO);
3603     return;
3604   }
3605   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3606               "Setting inbound quota of %u Bps for peer `%s' to all clients\n",
3607               ntohl (quota.value__), GNUNET_i2s (&n->id));
3608   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
3609   if (0 != ntohl (quota.value__))
3610     return;
3611   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3612               "Disconnecting peer `%4s' due to SET_QUOTA\n",
3613               GNUNET_i2s (&n->id));
3614   if (GNUNET_YES == test_connected (n))
3615     GNUNET_STATISTICS_update (GST_stats,
3616                               gettext_noop ("# disconnects due to quota of 0"),
3617                               1, GNUNET_NO);
3618   disconnect_neighbour (n);
3619 }
3620
3621
3622 static void
3623 delayed_disconnect (void *cls,
3624                     const struct GNUNET_SCHEDULER_TaskContext* tc)
3625 {
3626   struct NeighbourMapEntry *n = cls;
3627
3628   n->delayed_disconnect_task = NULL;
3629   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3630               "Disconnecting by request from peer %s\n",
3631               GNUNET_i2s (&n->id));
3632   free_neighbour (n, GNUNET_NO);
3633 }
3634
3635
3636 /**
3637  * We received a disconnect message from the given peer,
3638  * validate and process.
3639  *
3640  * @param peer sender of the message
3641  * @param msg the disconnect message
3642  */
3643 void
3644 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity *peer,
3645                                           const struct GNUNET_MessageHeader *msg)
3646 {
3647   struct NeighbourMapEntry *n;
3648   const struct SessionDisconnectMessage *sdm;
3649
3650   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3651               "Received DISCONNECT message from peer `%s'\n",
3652               GNUNET_i2s (peer));
3653   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
3654   {
3655     GNUNET_break_op (0);
3656     GNUNET_STATISTICS_update (GST_stats,
3657                               gettext_noop
3658                               ("# disconnect messages ignored (malformed)"), 1,
3659                               GNUNET_NO);
3660     return;
3661   }
3662   GNUNET_STATISTICS_update (GST_stats,
3663                             gettext_noop
3664                             ("# DISCONNECT messages received"),
3665                             1, GNUNET_NO);
3666   sdm = (const struct SessionDisconnectMessage *) msg;
3667   if (NULL == (n = lookup_neighbour (peer)))
3668     return;                     /* gone already */
3669   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value_us <= n->connect_ack_timestamp.abs_value_us)
3670   {
3671     GNUNET_STATISTICS_update (GST_stats,
3672                               gettext_noop
3673                               ("# disconnect messages ignored (timestamp)"), 1,
3674                               GNUNET_NO);
3675     return;
3676   }
3677   if (0 != memcmp (peer, &sdm->public_key, sizeof (struct GNUNET_PeerIdentity)))
3678   {
3679     GNUNET_break_op (0);
3680     return;
3681   }
3682   if (ntohl (sdm->purpose.size) !=
3683       sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
3684       sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
3685       sizeof (struct GNUNET_TIME_AbsoluteNBO))
3686   {
3687     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3688                 "%s message from peer `%s' has invalid size \n",
3689                 "DISCONNECT",
3690                 GNUNET_i2s (peer));
3691     GNUNET_break_op (0);
3692     return;
3693   }
3694   if (GNUNET_OK !=
3695       GNUNET_CRYPTO_eddsa_verify
3696       (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT, &sdm->purpose,
3697        &sdm->signature, &sdm->public_key))
3698   {
3699     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3700                 "%s message from peer `%s' cannot be verified \n",
3701                 "DISCONNECT",
3702                 GNUNET_i2s (peer));
3703     GNUNET_break_op (0);
3704     return;
3705   }
3706   n->delayed_disconnect_task = GNUNET_SCHEDULER_add_now (&delayed_disconnect, n);
3707 }
3708
3709
3710 /**
3711  * Closure for the #neighbours_iterate() function.
3712  */
3713 struct IteratorContext
3714 {
3715   /**
3716    * Function to call on each connected neighbour.
3717    */
3718   GST_NeighbourIterator cb;
3719
3720   /**
3721    * Closure for @e cb.
3722    */
3723   void *cb_cls;
3724 };
3725
3726
3727 /**
3728  * Call the callback from the closure for each neighbour.
3729  *
3730  * @param cls the `struct IteratorContext`
3731  * @param key the hash of the public key of the neighbour
3732  * @param value the `struct NeighbourMapEntry`
3733  * @return #GNUNET_OK (continue to iterate)
3734  */
3735 static int
3736 neighbours_iterate (void *cls,
3737                     const struct GNUNET_PeerIdentity *key,
3738                     void *value)
3739 {
3740   struct IteratorContext *ic = cls;
3741   struct NeighbourMapEntry *n = value;
3742   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
3743   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
3744
3745
3746   if (NULL != n->primary_address.address)
3747   {
3748     bandwidth_in = n->primary_address.bandwidth_in;
3749     bandwidth_out = n->primary_address.bandwidth_out;
3750   }
3751   else
3752   {
3753     bandwidth_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
3754     bandwidth_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
3755   }
3756   ic->cb (ic->cb_cls,
3757           &n->id,
3758           n->primary_address.address,
3759           n->state,
3760           n->timeout,
3761           bandwidth_in, bandwidth_out);
3762   return GNUNET_OK;
3763 }
3764
3765
3766 /**
3767  * Iterate over all connected neighbours.
3768  *
3769  * @param cb function to call
3770  * @param cb_cls closure for cb
3771  */
3772 void
3773 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
3774 {
3775   struct IteratorContext ic;
3776
3777   if (NULL == neighbours)
3778     return; /* can happen during shutdown */
3779   ic.cb = cb;
3780   ic.cb_cls = cb_cls;
3781   GNUNET_CONTAINER_multipeermap_iterate (neighbours, &neighbours_iterate, &ic);
3782 }
3783
3784
3785 /**
3786  * If we have an active connection to the given target, it must be shutdown.
3787  *
3788  * @param target peer to disconnect from
3789  */
3790 void
3791 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
3792 {
3793   struct NeighbourMapEntry *n;
3794
3795   if (NULL == (n = lookup_neighbour (target)))
3796     return;  /* not active */
3797   if (GNUNET_YES == test_connected (n))
3798     GNUNET_STATISTICS_update (GST_stats,
3799                               gettext_noop
3800                               ("# disconnected from peer upon explicit request"), 1,
3801                               GNUNET_NO);
3802   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3803               "Forced disconnect from peer %s\n",
3804               GNUNET_i2s (target));
3805   disconnect_neighbour (n);
3806 }
3807
3808
3809 /**
3810  * Obtain current latency information for the given neighbour.
3811  *
3812  * @param peer to get the latency for
3813  * @return observed latency of the address, FOREVER if the
3814  *         the connection is not up
3815  */
3816 struct GNUNET_TIME_Relative
3817 GST_neighbour_get_latency (const struct GNUNET_PeerIdentity *peer)
3818 {
3819   struct NeighbourMapEntry *n;
3820
3821   n = lookup_neighbour (peer);
3822   if (NULL == n)
3823     return GNUNET_TIME_UNIT_FOREVER_REL;
3824   switch (n->state)
3825   {
3826   case GNUNET_TRANSPORT_PS_CONNECTED:
3827   case GNUNET_TRANSPORT_PS_SWITCH_SYN_SENT:
3828   case GNUNET_TRANSPORT_PS_RECONNECT_SENT:
3829   case GNUNET_TRANSPORT_PS_RECONNECT_ATS:
3830     return n->latency;
3831   case GNUNET_TRANSPORT_PS_NOT_CONNECTED:
3832   case GNUNET_TRANSPORT_PS_INIT_ATS:
3833   case GNUNET_TRANSPORT_PS_SYN_RECV_ATS:
3834   case GNUNET_TRANSPORT_PS_SYN_RECV_ACK:
3835   case GNUNET_TRANSPORT_PS_SYN_SENT:
3836   case GNUNET_TRANSPORT_PS_DISCONNECT:
3837   case GNUNET_TRANSPORT_PS_DISCONNECT_FINISHED:
3838     return GNUNET_TIME_UNIT_FOREVER_REL;
3839   default:
3840     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3841                 "Unhandled state `%s'\n",
3842                 GNUNET_TRANSPORT_ps2s (n->state));
3843     GNUNET_break (0);
3844     break;
3845   }
3846   return GNUNET_TIME_UNIT_FOREVER_REL;
3847 }
3848
3849
3850 /**
3851  * Obtain current address information for the given neighbour.
3852  *
3853  * @param peer
3854  * @return address currently used
3855  */
3856 struct GNUNET_HELLO_Address *
3857 GST_neighbour_get_current_address (const struct GNUNET_PeerIdentity *peer)
3858 {
3859   struct NeighbourMapEntry *n;
3860
3861   n = lookup_neighbour (peer);
3862   if (NULL == n)
3863     return NULL;
3864   return n->primary_address.address;
3865 }
3866
3867
3868 /**
3869  * Initialize the neighbours subsystem.
3870  *
3871  * @param max_fds maximum number of fds to use
3872  */
3873 void
3874 GST_neighbours_start (unsigned int max_fds)
3875 {
3876   neighbours = GNUNET_CONTAINER_multipeermap_create (NEIGHBOUR_TABLE_SIZE, GNUNET_NO);
3877   util_transmission_tk = GNUNET_SCHEDULER_add_delayed (UTIL_TRANSMISSION_INTERVAL,
3878                                                        &utilization_transmission,
3879                                                        NULL);
3880 }
3881
3882
3883 /**
3884  * Disconnect from the given neighbour.
3885  *
3886  * @param cls unused
3887  * @param key hash of neighbour's public key (not used)
3888  * @param value the 'struct NeighbourMapEntry' of the neighbour
3889  * @return #GNUNET_OK (continue to iterate)
3890  */
3891 static int
3892 disconnect_all_neighbours (void *cls,
3893                            const struct GNUNET_PeerIdentity *key,
3894                            void *value)
3895 {
3896   struct NeighbourMapEntry *n = value;
3897
3898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3899               "Disconnecting peer `%4s', %s\n",
3900               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
3901   free_neighbour (n, GNUNET_NO);
3902   return GNUNET_OK;
3903 }
3904
3905
3906 /**
3907  * Cleanup the neighbours subsystem.
3908  */
3909 void
3910 GST_neighbours_stop ()
3911 {
3912   struct BlacklistCheckSwitchContext *cur;
3913   struct BlacklistCheckSwitchContext *next;
3914
3915   if (NULL == neighbours)
3916     return;
3917   if (NULL != util_transmission_tk)
3918   {
3919     GNUNET_SCHEDULER_cancel (util_transmission_tk);
3920     util_transmission_tk = NULL;
3921   }
3922   GNUNET_CONTAINER_multipeermap_iterate (neighbours,
3923                                          &disconnect_all_neighbours,
3924                                          NULL);
3925   GNUNET_CONTAINER_multipeermap_destroy (neighbours);
3926
3927   next = pending_bc_head;
3928   for (cur = next; NULL != cur; cur = next)
3929   {
3930     next = cur->next;
3931     GNUNET_CONTAINER_DLL_remove (pending_bc_head,
3932                                  pending_bc_tail,
3933                                  cur);
3934
3935     if (NULL != cur->blc)
3936     {
3937       GST_blacklist_test_cancel (cur->blc);
3938       cur->blc = NULL;
3939     }
3940     if (NULL != cur->address)
3941       GNUNET_HELLO_address_free (cur->address);
3942     GNUNET_free (cur);
3943   }
3944   neighbours = NULL;
3945 }
3946
3947
3948 /* end of file gnunet-service-transport_neighbours.c */