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