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