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