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