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