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