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