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