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