-attempting to fix LRN's NAT connect issue
[oweals/gnunet.git] / src / transport / gnunet-service-transport_neighbours.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010,2011,2012 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  * TODO:
27  * - "address_change_cb" is NEVER invoked; when should we call this one exactly?
28  * - TEST, TEST, TEST...
29  */
30 #include "platform.h"
31 #include "gnunet_ats_service.h"
32 #include "gnunet-service-transport_neighbours.h"
33 #include "gnunet-service-transport_plugins.h"
34 #include "gnunet-service-transport_validation.h"
35 #include "gnunet-service-transport_clients.h"
36 #include "gnunet-service-transport.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet-service-transport_blacklist.h"
39 #include "gnunet_constants.h"
40 #include "transport.h"
41
42
43 /**
44  * Size of the neighbour hash map.
45  */
46 #define NEIGHBOUR_TABLE_SIZE 256
47
48 /**
49  * Time we give plugin to transmit DISCONNECT message before the
50  * neighbour entry self-destructs.
51  */
52 #define DISCONNECT_SENT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100)
53
54 /**
55  * How often must a peer violate bandwidth quotas before we start
56  * to simply drop its messages?
57  */
58 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
59
60 /**
61  * How often do we send KEEPALIVE messages to each of our neighbours and measure
62  * the latency with this neighbour?
63  * (idle timeout is 5 minutes or 300 seconds, so with 100s interval we
64  * send 3 keepalives in each interval, so 3 messages would need to be
65  * lost in a row for a disconnect).
66  */
67 #define KEEPALIVE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100)
68
69 /**
70  * How long are we willing to wait for a response from ATS before timing out?
71  */
72 #define ATS_RESPONSE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500)
73
74 /**
75  * How long are we willing to wait for an ACK from the other peer before
76  * giving up on our connect operation?
77  */
78 #define SETUP_CONNECTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
79
80 /**
81  * How long are we willing to wait for a successful reconnect if 
82  * an existing connection went down?  Much shorter than the
83  * usual SETUP_CONNECTION_TIMEOUT as we do not inform the
84  * higher layers about the disconnect during this period.
85  */
86 #define FAST_RECONNECT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
87
88 /**
89  * How long are we willing to wait for a response from the blacklist
90  * subsystem before timing out?
91  */
92 #define BLACKLIST_RESPONSE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500)
93
94
95 GNUNET_NETWORK_STRUCT_BEGIN
96
97 /**
98  * Message a peer sends to another to indicate that it intends to
99  * setup a connection/session for data exchange.  A 'SESSION_CONNECT'
100  * should be answered with a 'SESSION_CONNECT_ACK' with the same body
101  * to confirm.  A 'SESSION_CONNECT_ACK' should then be followed with
102  * a 'SESSION_ACK'.  Once the 'SESSION_ACK' is received, both peers 
103  * should be connected.
104  */
105 struct SessionConnectMessage
106 {
107   /**
108    * Header of type 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT'
109    * or 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK'
110    */
111   struct GNUNET_MessageHeader header;
112
113   /**
114    * Always zero.
115    */
116   uint32_t reserved GNUNET_PACKED;
117
118   /**
119    * Absolute time at the sender.  Only the most recent connect
120    * message implies which session is preferred by the sender.
121    */
122   struct GNUNET_TIME_AbsoluteNBO timestamp;
123
124 };
125
126
127 /**
128  * Message we send to the other peer to notify him that we intentionally
129  * are disconnecting (to reduce timeouts).  This is just a friendly 
130  * notification, peers must not rely on always receiving disconnect
131  * messages.
132  */
133 struct SessionDisconnectMessage
134 {
135   /**
136    * Header of type 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT'
137    */
138   struct GNUNET_MessageHeader header;
139
140   /**
141    * Always zero.
142    */
143   uint32_t reserved GNUNET_PACKED;
144
145   /**
146    * Purpose of the signature.  Extends over the timestamp.
147    * Purpose should be GNUNET_SIGNATURE_PURPOSE_TRANSPORT_DISCONNECT.
148    */
149   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
150
151   /**
152    * Absolute time at the sender.  Only the most recent connect
153    * message implies which session is preferred by the sender.
154    */
155   struct GNUNET_TIME_AbsoluteNBO timestamp;
156
157   /**
158    * Public key of the sender.
159    */
160   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
161
162   /**
163    * Signature of the peer that sends us the disconnect.  Only
164    * valid if the timestamp is AFTER the timestamp from the
165    * corresponding 'CONNECT' message.
166    */
167   struct GNUNET_CRYPTO_RsaSignature signature;
168
169 };
170
171 GNUNET_NETWORK_STRUCT_END
172
173
174 /**
175  * For each neighbour we keep a list of messages
176  * that we still want to transmit to the neighbour.
177  */
178 struct MessageQueue
179 {
180
181   /**
182    * This is a doubly linked list.
183    */
184   struct MessageQueue *next;
185
186   /**
187    * This is a doubly linked list.
188    */
189   struct MessageQueue *prev;
190
191   /**
192    * Function to call once we're done.
193    */
194   GST_NeighbourSendContinuation cont;
195
196   /**
197    * Closure for 'cont'
198    */
199   void *cont_cls;
200
201   /**
202    * The message(s) we want to transmit, GNUNET_MessageHeader(s)
203    * stuck together in memory.  Allocated at the end of this struct.
204    */
205   const char *message_buf;
206
207   /**
208    * Size of the message buf
209    */
210   size_t message_buf_size;
211
212   /**
213    * At what time should we fail?
214    */
215   struct GNUNET_TIME_Absolute timeout;
216
217 };
218
219
220 /**
221  * Possible state of a neighbour.  Initially, we are S_NOT_CONNECTED.
222  *
223  * Then, there are two main paths. If we receive a CONNECT message, we
224  * first run a check against the blacklist (S_CONNECT_RECV_BLACKLIST_INBOUND).
225  * If this check is successful, we give the inbound address to ATS.
226  * After the check we ask ATS for a suggestion (S_CONNECT_RECV_ATS).
227  * If ATS makes a suggestion, we ALSO give that suggestion to the blacklist
228  * (S_CONNECT_RECV_BLACKLIST).  Once the blacklist approves the
229  * address we got from ATS, we send our CONNECT_ACK and go to
230  * S_CONNECT_RECV_ACK.  If we receive a SESSION_ACK, we go to
231  * S_CONNECTED (and notify everyone about the new connection).  If the
232  * operation times out, we go to S_DISCONNECT.
233  *
234  * The other case is where we transmit a CONNECT message first.  We
235  * start with S_INIT_ATS.  If we get an address, we enter
236  * S_INIT_BLACKLIST and check the blacklist.  If the blacklist is OK
237  * with the connection, we actually send the CONNECT message and go to
238  * state S_CONNECT_SENT.  Once we receive a CONNECT_ACK, we go to
239  * S_CONNECTED (and notify everyone about the new connection and send
240  * back a SESSION_ACK).  If the operation times out, we go to
241  * S_DISCONNECT.
242  *
243  * If the session is in trouble (i.e. transport-level disconnect or
244  * timeout), we go to S_RECONNECT_ATS where we ask ATS for a new
245  * address (we don't notify anyone about the disconnect yet).  Once we
246  * have a new address, we go to S_RECONNECT_BLACKLIST to check the new
247  * address against the blacklist.  If the blacklist approves, we enter
248  * S_RECONNECT_SENT and send a CONNECT message.  If we receive a
249  * CONNECT_ACK, we go to S_CONNECTED and nobody noticed that we had
250  * trouble; we also send a SESSION_ACK at this time just in case.  If
251  * the operation times out, we go to S_DISCONNECT (and notify everyone
252  * about the lost connection).
253  *
254  * If ATS decides to switch addresses while we have a normal
255  * connection, we go to S_CONNECTED_SWITCHING_BLACKLIST to check the
256  * new address against the blacklist.  If the blacklist approves, we
257  * go to S_CONNECTED_SWITCHING_CONNECT_SENT and send a
258  * SESSION_CONNECT.  If we get a SESSION_ACK back, we switch the
259  * primary connection to the suggested alternative from ATS, go back
260  * to S_CONNECTED and send a SESSION_ACK to the other peer just to be
261  * sure.  If the operation times out (or the blacklist disapproves),
262  * we go to S_CONNECTED (and notify ATS that the given alternative
263  * address is "invalid").
264  *
265  * Once a session is in S_DISCONNECT, it is cleaned up and then goes
266  * to (S_DISCONNECT_FINISHED).  If we receive an explicit disconnect
267  * request, we can go from any state to S_DISCONNECT, possibly after
268  * generating disconnect notifications.
269  *
270  * Note that it is quite possible that while we are in any of these
271  * states, we could receive a 'CONNECT' request from the other peer.
272  * We then enter a 'weird' state where we pursue our own primary state
273  * machine (as described above), but with the 'send_connect_ack' flag
274  * set to 1.  If our state machine allows us to send a 'CONNECT_ACK'
275  * (because we have an acceptable address), we send the 'CONNECT_ACK'
276  * and set the 'send_connect_ack' to 2.  If we then receive a
277  * 'SESSION_ACK', we go to 'S_CONNECTED' (and reset 'send_connect_ack'
278  * to 0).
279  * 
280  */ 
281 enum State
282 {
283   /**
284    * fresh peer or completely disconnected
285    */
286   S_NOT_CONNECTED = 0,
287
288   /**
289    * Asked to initiate connection, trying to get address from ATS
290    */
291   S_INIT_ATS,
292
293   /**
294    * Asked to initiate connection, trying to get address approved
295    * by blacklist.
296    */
297   S_INIT_BLACKLIST,
298
299   /**
300    * Sent CONNECT message to other peer, waiting for CONNECT_ACK
301    */
302   S_CONNECT_SENT,
303
304   /**
305    * Received a CONNECT, do a blacklist check for inbound address
306    */
307   S_CONNECT_RECV_BLACKLIST_INBOUND,
308
309   /**
310    * Received a CONNECT, asking ATS about address suggestions.
311    */
312   S_CONNECT_RECV_ATS,
313
314   /**
315    * Received CONNECT from other peer, got an address, checking with blacklist.
316    */
317   S_CONNECT_RECV_BLACKLIST,
318
319   /**
320    * CONNECT request from other peer was SESSION_ACK'ed, waiting for
321    * SESSION_ACK.
322    */
323   S_CONNECT_RECV_ACK,
324
325   /**
326    * Got our CONNECT_ACK/SESSION_ACK, connection is up.
327    */
328   S_CONNECTED,
329
330   /**
331    * Connection got into trouble, rest of the system still believes
332    * it to be up, but we're getting a new address from ATS.
333    */
334   S_RECONNECT_ATS,
335
336   /**
337    * Connection got into trouble, rest of the system still believes
338    * it to be up; we are checking the new address against the blacklist.
339    */
340   S_RECONNECT_BLACKLIST,
341
342   /**
343    * Sent CONNECT over new address (either by ATS telling us to switch
344    * addresses or from RECONNECT_ATS); if this fails, we need to tell
345    * the rest of the system about a disconnect.
346    */
347   S_RECONNECT_SENT,
348
349   /**
350    * We have some primary connection, but ATS suggested we switch
351    * to some alternative; we're now checking the alternative against
352    * the blacklist.
353    */
354   S_CONNECTED_SWITCHING_BLACKLIST,
355
356   /** 
357    * We have some primary connection, but ATS suggested we switch
358    * to some alternative; we now sent a CONNECT message for the
359    * alternative session to the other peer and waiting for a
360    * CONNECT_ACK to make this our primary connection.
361    */
362   S_CONNECTED_SWITCHING_CONNECT_SENT,
363
364   /**
365    * Disconnect in progress (we're sending the DISCONNECT message to the
366    * other peer; after that is finished, the state will be cleaned up).
367    */
368   S_DISCONNECT,
369
370   /**
371    * We're finished with the disconnect; clean up state now!
372    */
373   S_DISCONNECT_FINISHED
374 };
375
376
377 /**
378  * A possible address we could use to communicate with a neighbour.
379  */
380 struct NeighbourAddress
381 {
382
383   /**
384    * Active session for this address.
385    */
386   struct Session *session;
387
388   /**
389    * Network-level address information.
390    */
391   struct GNUNET_HELLO_Address *address;
392
393   /**
394    * Timestamp of the 'SESSION_CONNECT' message we sent to the other
395    * peer for this address.  Use to check that the ACK is in response
396    * to our most recent 'CONNECT'.
397    */
398   struct GNUNET_TIME_Absolute connect_timestamp;
399
400   /**
401    * Inbound bandwidth from ATS for this address.
402    */
403   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
404
405   /**
406    * Outbound bandwidth from ATS for this address.
407    */
408   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
409
410   /**
411    * Did we tell ATS that this is our 'active' address?
412    */
413   int ats_active;
414   
415 };
416
417
418 /**
419  * Entry in neighbours.
420  */
421 struct NeighbourMapEntry
422 {
423
424   /**
425    * Head of list of messages we would like to send to this peer;
426    * must contain at most one message per client.
427    */
428   struct MessageQueue *messages_head;
429
430   /**
431    * Tail of list of messages we would like to send to this peer; must
432    * contain at most one message per client.
433    */
434   struct MessageQueue *messages_tail;
435
436   /**
437    * Are we currently trying to send a message? If so, which one?
438    */
439   struct MessageQueue *is_active;
440
441   /**
442    * Primary address we currently use to communicate with the neighbour.
443    */
444   struct NeighbourAddress primary_address;
445
446   /**
447    * Alternative address currently under consideration for communicating
448    * with the neighbour.
449    */
450   struct NeighbourAddress alternative_address;
451
452   /**
453    * Identity of this neighbour.
454    */
455   struct GNUNET_PeerIdentity id;
456
457   /**
458    * Main task that drives this peer (timeouts, keepalives, etc.).
459    * Always runs the 'master_task'.
460    */
461   GNUNET_SCHEDULER_TaskIdentifier task;
462
463   /**
464    * At what time should we sent the next keep-alive message?
465    */
466   struct GNUNET_TIME_Absolute keep_alive_time;
467
468   /**
469    * At what time did we sent the last keep-alive message?  Used 
470    * to calculate round-trip time ("latency").
471    */
472   struct GNUNET_TIME_Absolute last_keep_alive_time;
473
474   /**
475    * Timestamp we should include in our next CONNECT_ACK message.
476    * (only valid if 'send_connect_ack' is GNUNET_YES).  Used to build
477    * our CONNECT_ACK message.
478    */
479   struct GNUNET_TIME_Absolute connect_ack_timestamp;
480
481   /**
482    * Time where we should cut the connection (timeout) if we don't
483    * make progress in the state machine (or get a KEEPALIVE_RESPONSE
484    * if we are in S_CONNECTED).
485    */
486   struct GNUNET_TIME_Absolute timeout;
487
488   /**
489    * Latest calculated latency value
490    */
491   struct GNUNET_TIME_Relative latency;
492
493   /**
494    * Tracker for inbound bandwidth.
495    */
496   struct GNUNET_BANDWIDTH_Tracker in_tracker;
497
498   /**
499    * How often has the other peer (recently) violated the inbound
500    * traffic limit?  Incremented by 10 per violation, decremented by 1
501    * per non-violation (for each time interval).
502    */
503   unsigned int quota_violation_count;
504
505   /**
506    * The current state of the peer.
507    */
508   enum State state;
509
510   /**
511    * Did we sent an KEEP_ALIVE message and are we expecting a response?
512    */
513   int expect_latency_response;
514
515   /**
516    * Flag to set if we still need to send a CONNECT_ACK message to the other peer
517    * (once we have an address to use and the peer has been allowed by our
518    * blacklist).  Set to 1 if we need to send a CONNECT_ACK.  Set to 2 if we
519    * did send a CONNECT_ACK and should go to 'S_CONNECTED' upon receiving
520    * a 'SESSION_ACK' (regardless of what our own state machine might say).
521    */
522   int send_connect_ack;
523
524 };
525
526
527 /**
528  * Context for blacklist checks and the 'handle_test_blacklist_cont'
529  * function.  Stores information about ongoing blacklist checks.
530  */
531 struct BlackListCheckContext
532 {
533   
534   /**
535    * We keep blacklist checks in a DLL.
536    */
537   struct BlackListCheckContext *next;
538
539   /**
540    * We keep blacklist checks in a DLL.
541    */
542   struct BlackListCheckContext *prev;
543
544   /**
545    * Address that is being checked.
546    */
547   struct NeighbourAddress na;
548   
549   /**
550    * ATS information about the address.
551    */
552   struct GNUNET_ATS_Information *ats;
553
554   /**
555    * Handle to the ongoing blacklist check.
556    */
557   struct GST_BlacklistCheck *bc;
558
559   /**
560    * Size of the 'ats' array.
561    */
562   uint32_t ats_count;
563
564 };
565
566
567 /**
568  * Hash map from peer identities to the respective 'struct NeighbourMapEntry'.
569  */
570 static struct GNUNET_CONTAINER_MultiHashMap *neighbours;
571
572 /**
573  * We keep blacklist checks in a DLL so that we can find
574  * the 'sessions' in their 'struct NeighbourAddress' if
575  * a session goes down.
576  */
577 static struct BlackListCheckContext *bc_head;
578
579 /**
580  * We keep blacklist checks in a DLL.
581  */
582 static struct BlackListCheckContext *bc_tail;
583
584 /**
585  * Closure for connect_notify_cb, disconnect_notify_cb and address_change_cb
586  */
587 static void *callback_cls;
588
589 /**
590  * Function to call when we connected to a neighbour.
591  */
592 static GNUNET_TRANSPORT_NotifyConnect connect_notify_cb;
593
594 /**
595  * Function to call when we disconnected from a neighbour.
596  */
597 static GNUNET_TRANSPORT_NotifyDisconnect disconnect_notify_cb;
598
599 /**
600  * Function to call when we changed an active address of a neighbour.
601  */
602 static GNUNET_TRANSPORT_PeerIterateCallback address_change_cb;
603
604 /**
605  * counter for connected neighbours
606  */
607 static unsigned int neighbours_connected;
608
609 /**
610  * Number of bytes we have currently queued for transmission.
611  */
612 static unsigned long long bytes_in_send_queue;
613
614
615 /**
616  * Lookup a neighbour entry in the neighbours hash map.
617  *
618  * @param pid identity of the peer to look up
619  * @return the entry, NULL if there is no existing record
620  */
621 static struct NeighbourMapEntry *
622 lookup_neighbour (const struct GNUNET_PeerIdentity *pid)
623 {
624   if (NULL == neighbours)
625     return NULL;
626   return GNUNET_CONTAINER_multihashmap_get (neighbours, &pid->hashPubKey);
627 }
628
629 static const char *
630 print_state (int state)
631 {
632
633   switch (state)
634   {
635   case S_NOT_CONNECTED:
636     return "S_NOT_CONNECTED";
637     break;
638   case S_INIT_ATS:
639     return "S_INIT_ATS";
640     break;
641   case S_INIT_BLACKLIST:
642     return "S_INIT_BLACKLIST";
643     break;
644   case S_CONNECT_SENT:
645     return "S_CONNECT_SENT";
646     break;
647   case S_CONNECT_RECV_BLACKLIST_INBOUND:
648     return "S_CONNECT_RECV_BLACKLIST_INBOUND";
649     break;
650   case S_CONNECT_RECV_ATS:
651     return "S_CONNECT_RECV_ATS";
652     break;
653   case S_CONNECT_RECV_BLACKLIST:
654     return "S_CONNECT_RECV_BLACKLIST";
655     break;
656   case S_CONNECT_RECV_ACK:
657     return "S_CONNECT_RECV_ACK";
658     break;
659   case S_CONNECTED:
660     return "S_CONNECTED";
661     break;
662   case S_RECONNECT_ATS:
663     return "S_RECONNECT_ATS";
664     break;
665   case S_RECONNECT_BLACKLIST:
666     return "S_RECONNECT_BLACKLIST";
667     break;
668   case S_RECONNECT_SENT:
669     return "S_RECONNECT_SENT";
670     break;
671   case S_CONNECTED_SWITCHING_BLACKLIST:
672     return "S_CONNECTED_SWITCHING_BLACKLIST";
673     break;
674   case S_CONNECTED_SWITCHING_CONNECT_SENT:
675     return "S_CONNECTED_SWITCHING_CONNECT_SENT";
676     break;
677   case S_DISCONNECT:
678     return "S_DISCONNECT";
679     break;
680   case S_DISCONNECT_FINISHED:
681     return "S_DISCONNECT_FINISHED";
682     break;
683   default:
684     return "UNDEFINED";
685     GNUNET_break (0);
686     break;
687   }
688   GNUNET_break (0);
689   return "UNDEFINED";
690 }
691
692 /**
693  * Test if we're connected to the given peer.
694  *
695  * @param n neighbour entry of peer to test
696  * @return GNUNET_YES if we are connected, GNUNET_NO if not
697  */
698 static int
699 test_connected (struct NeighbourMapEntry *n)
700 {
701   if (NULL == n)
702     return GNUNET_NO;
703   switch (n->state)
704   {
705   case S_NOT_CONNECTED:
706   case S_INIT_ATS:
707   case S_INIT_BLACKLIST:
708   case S_CONNECT_SENT:
709   case S_CONNECT_RECV_BLACKLIST_INBOUND:
710   case S_CONNECT_RECV_ATS:
711   case S_CONNECT_RECV_BLACKLIST:
712   case S_CONNECT_RECV_ACK:
713     return GNUNET_NO;
714   case S_CONNECTED:
715   case S_RECONNECT_ATS:
716   case S_RECONNECT_BLACKLIST:
717   case S_RECONNECT_SENT:
718   case S_CONNECTED_SWITCHING_BLACKLIST:
719   case S_CONNECTED_SWITCHING_CONNECT_SENT:
720     return GNUNET_YES;
721   case S_DISCONNECT:
722   case S_DISCONNECT_FINISHED:
723     return GNUNET_NO;
724   default:
725     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
726     GNUNET_break (0);
727     break;
728   }
729   return GNUNET_SYSERR;
730 }
731
732 /**
733  * Send information about a new outbound quota to our clients.
734  *
735  * @param target affected peer
736  * @param quota new quota
737  */
738 static void
739 send_outbound_quota (const struct GNUNET_PeerIdentity *target,
740                      struct GNUNET_BANDWIDTH_Value32NBO quota)
741 {
742   struct QuotaSetMessage q_msg;
743
744   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
745               "Sending outbound quota of %u Bps for peer `%s' to all clients\n",
746               ntohl (quota.value__), GNUNET_i2s (target));
747   q_msg.header.size = htons (sizeof (struct QuotaSetMessage));
748   q_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
749   q_msg.quota = quota;
750   q_msg.peer = (*target);
751   GST_clients_broadcast (&q_msg.header, GNUNET_NO);
752 }
753
754
755 /**
756  * We don't need a given neighbour address any more.
757  * Release its resources and give appropriate notifications
758  * to ATS and other subsystems.
759  *
760  * @param na address we are done with; 'na' itself must NOT be 'free'd, only the contents!
761  */
762 static void
763 free_address (struct NeighbourAddress *na)
764 {
765   if (GNUNET_YES == na->ats_active)
766   {
767     GST_validation_set_address_use (na->address, na->session, GNUNET_NO, __LINE__);
768     GNUNET_ATS_address_in_use (GST_ats, na->address, na->session, GNUNET_NO);
769     GNUNET_ATS_address_destroyed (GST_ats, na->address, na->session);
770   }
771   else
772   {
773     if (NULL != na->address)
774     {
775       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "HACK: destroy address\n");
776       GNUNET_ATS_address_destroyed (GST_ats, na->address, na->session);
777     }
778   }
779   na->ats_active = GNUNET_NO;
780   if (NULL != na->address)
781   {
782     GNUNET_HELLO_address_free (na->address);
783     na->address = NULL;
784   }
785   na->session = NULL;
786 }
787
788
789 /**
790  * Initialize the 'struct NeighbourAddress'.
791  *
792  * @param na neighbour address to initialize
793  * @param address address of the other peer, NULL if other peer
794  *                       connected to us
795  * @param session session to use (or NULL, in which case an
796  *        address must be setup)
797  * @param bandwidth_in inbound quota to be used when connection is up
798  * @param bandwidth_out outbound quota to be used when connection is up
799  * @param is_active GNUNET_YES to mark this as the active address with ATS
800  */
801 static void
802 set_address (struct NeighbourAddress *na,
803              const struct GNUNET_HELLO_Address *address,
804              struct Session *session,
805              struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
806              struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
807              int is_active)
808 {
809   struct GNUNET_TRANSPORT_PluginFunctions *papi;
810
811   if (NULL == (papi = GST_plugins_find (address->transport_name)))  
812   {
813     GNUNET_break (0);
814     return;
815   }
816   if (session == na->session)
817   {
818     na->bandwidth_in = bandwidth_in;
819     na->bandwidth_out = bandwidth_out;
820     if (is_active != na->ats_active)
821     {
822       na->ats_active = is_active;
823       GNUNET_ATS_address_in_use (GST_ats, na->address, na->session, is_active);
824       GST_validation_set_address_use (na->address, na->session, is_active,  __LINE__);
825     }
826     if (GNUNET_YES == is_active)
827     {
828       /* FIXME: is this the right place to set quotas? */
829       GST_neighbours_set_incoming_quota (&address->peer, bandwidth_in);
830       send_outbound_quota (&address->peer, bandwidth_out);
831     }    
832     return;
833   }
834   free_address (na);
835   if (NULL == session)
836     session = papi->get_session (papi->cls, address);    
837   if (NULL == session)
838   {
839     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
840                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
841                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));    
842     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
843     return;
844   }
845   na->address = GNUNET_HELLO_address_copy (address);
846   na->bandwidth_in = bandwidth_in;
847   na->bandwidth_out = bandwidth_out;
848   na->session = session;
849   na->ats_active = is_active;
850   if (GNUNET_YES == is_active)
851   {
852     /* Telling ATS about new session */
853     GNUNET_ATS_address_in_use (GST_ats, na->address, na->session, GNUNET_YES);
854     GST_validation_set_address_use (na->address, na->session, GNUNET_YES,  __LINE__);
855
856     /* FIXME: is this the right place to set quotas? */
857     GST_neighbours_set_incoming_quota (&address->peer, bandwidth_in);
858     send_outbound_quota (&address->peer, bandwidth_out);
859   }
860 }
861
862
863 /**
864  * Free a neighbour map entry.
865  *
866  * @param n entry to free
867  * @param keep_sessions GNUNET_NO to tell plugin to terminate sessions,
868  *                      GNUNET_YES to keep all sessions
869  */
870 static void
871 free_neighbour (struct NeighbourMapEntry *n, int keep_sessions)
872 {
873   struct MessageQueue *mq;
874   struct GNUNET_TRANSPORT_PluginFunctions *papi;
875
876   n->is_active = NULL; /* always free'd by its own continuation! */
877
878   /* fail messages currently in the queue */
879   while (NULL != (mq = n->messages_head))
880   {
881     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
882     if (NULL != mq->cont)
883       mq->cont (mq->cont_cls, GNUNET_SYSERR);
884     GNUNET_free (mq);
885   }
886   /* It is too late to send other peer disconnect notifications, but at
887      least internally we need to get clean... */
888   if (GNUNET_YES == test_connected (n))
889   {
890     GNUNET_STATISTICS_set (GST_stats, 
891                            gettext_noop ("# peers connected"), 
892                            --neighbours_connected,
893                            GNUNET_NO);
894     disconnect_notify_cb (callback_cls, &n->id);
895   }
896
897   /* FIXME-PLUGIN-API: This does not seem to guarantee that all
898      transport sessions eventually get killed due to inactivity; they
899      MUST have their own timeout logic (but at least TCP doesn't have
900      one yet).  Are we sure that EVERY 'session' of a plugin is
901      actually cleaned up this way!?  Note that if we are switching
902      between two TCP sessions to the same peer, the existing plugin
903      API gives us not even the means to selectively kill only one of
904      them! Killing all sessions like this seems to be very, very
905      wrong. */
906   if ((GNUNET_NO == keep_sessions) &&
907       (NULL != n->primary_address.address) &&
908       (NULL != (papi = GST_plugins_find (n->primary_address.address->transport_name))))
909     papi->disconnect (papi->cls, &n->id);
910
911   n->state = S_DISCONNECT_FINISHED;
912
913   GNUNET_assert (GNUNET_YES ==
914                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
915                                                        &n->id.hashPubKey, n));
916
917   /* cut transport-level connection */
918   free_address (&n->primary_address);
919   free_address (&n->alternative_address);
920
921   // FIXME-ATS-API: we might want to be more specific about
922   // which states we do this from in the future (ATS should
923   // have given us a 'suggest_address' handle, and if we have
924   // such a handle, we should cancel the operation here!
925   GNUNET_ATS_suggest_address_cancel (GST_ats, &n->id);
926
927   if (GNUNET_SCHEDULER_NO_TASK != n->task)
928   {
929     GNUNET_SCHEDULER_cancel (n->task);
930     n->task = GNUNET_SCHEDULER_NO_TASK;
931   }
932   /* free rest of memory */
933   GNUNET_free (n);
934 }
935
936
937 /**
938  * Transmit a message using the current session of the given
939  * neighbour.
940  *
941  * @param n entry for the recipient
942  * @param msgbuf buffer to transmit
943  * @param msgbuf_size number of bytes in buffer
944  * @param priority transmission priority
945  * @param timeout transmission timeout
946  * @param cont continuation to call when finished (can be NULL)
947  * @param cont_cls closure for cont
948  */
949 static void
950 send_with_session (struct NeighbourMapEntry *n,
951                    const char *msgbuf, size_t msgbuf_size,
952                    uint32_t priority,
953                    struct GNUNET_TIME_Relative timeout,
954                    GNUNET_TRANSPORT_TransmitContinuation cont,
955                    void *cont_cls)
956 {
957   struct GNUNET_TRANSPORT_PluginFunctions *papi;
958
959   GNUNET_assert (n->primary_address.session != NULL);
960   if ( ( (NULL == (papi = GST_plugins_find (n->primary_address.address->transport_name))) ||
961          (-1 == papi->send (papi->cls,
962                             n->primary_address.session,
963                             msgbuf, msgbuf_size,
964                             priority,
965                             timeout,
966                             cont, cont_cls))) &&
967        (NULL != cont) )
968     cont (cont_cls, &n->id, GNUNET_SYSERR);
969   GNUNET_break (NULL != papi);
970 }
971
972
973 /**
974  * Master task run for every neighbour.  Performs all of the time-related
975  * activities (keep alive, send next message, disconnect if idle, finish
976  * clean up after disconnect).
977  *
978  * @param cls the 'struct NeighbourMapEntry' for which we are running
979  * @param tc scheduler context (unused)
980  */
981 static void
982 master_task (void *cls,
983              const struct GNUNET_SCHEDULER_TaskContext *tc);
984
985
986 /**
987  * Function called when the 'DISCONNECT' message has been sent by the
988  * plugin.  Frees the neighbour --- if the entry still exists.
989  *
990  * @param cls NULL
991  * @param target identity of the neighbour that was disconnected
992  * @param result GNUNET_OK if the disconnect got out successfully
993  */
994 static void
995 send_disconnect_cont (void *cls, const struct GNUNET_PeerIdentity *target,
996                       int result)
997 {
998   struct NeighbourMapEntry *n;
999
1000   n = lookup_neighbour (target);
1001   if (NULL == n)
1002     return; /* already gone */
1003   if (S_DISCONNECT != n->state)
1004     return; /* have created a fresh entry since */
1005   n->state = S_DISCONNECT;
1006   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1007     GNUNET_SCHEDULER_cancel (n->task);
1008   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1009 }
1010
1011
1012 /**
1013  * Transmit a DISCONNECT message to the other peer.
1014  *
1015  * @param n neighbour to send DISCONNECT message.
1016  */
1017 static void
1018 send_disconnect (struct NeighbourMapEntry *n)
1019 {
1020   struct SessionDisconnectMessage disconnect_msg;
1021
1022   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1023               "Sending DISCONNECT message to peer `%4s'\n",
1024               GNUNET_i2s (&n->id));
1025   disconnect_msg.header.size = htons (sizeof (struct SessionDisconnectMessage));
1026   disconnect_msg.header.type =
1027       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1028   disconnect_msg.reserved = htonl (0);
1029   disconnect_msg.purpose.size =
1030       htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1031              sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1032              sizeof (struct GNUNET_TIME_AbsoluteNBO));
1033   disconnect_msg.purpose.purpose =
1034       htonl (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1035   disconnect_msg.timestamp =
1036       GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1037   disconnect_msg.public_key = GST_my_public_key;
1038   GNUNET_assert (GNUNET_OK ==
1039                  GNUNET_CRYPTO_rsa_sign (GST_my_private_key,
1040                                          &disconnect_msg.purpose,
1041                                          &disconnect_msg.signature));
1042
1043   send_with_session (n,
1044                      (const char *) &disconnect_msg, sizeof (disconnect_msg),
1045                      UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
1046                      &send_disconnect_cont, NULL);
1047   GNUNET_STATISTICS_update (GST_stats,
1048                             gettext_noop
1049                             ("# DISCONNECT messages sent"), 1,
1050                             GNUNET_NO);
1051 }
1052
1053
1054 /**
1055  * Disconnect from the given neighbour, clean up the record.
1056  *
1057  * @param n neighbour to disconnect from
1058  */
1059 static void
1060 disconnect_neighbour (struct NeighbourMapEntry *n)
1061 {
1062   /* depending on state, notify neighbour and/or upper layers of this peer 
1063      about disconnect */
1064   switch (n->state)
1065   {
1066   case S_NOT_CONNECTED:
1067   case S_INIT_ATS:
1068   case S_INIT_BLACKLIST:
1069     /* other peer is completely unaware of us, no need to send DISCONNECT */
1070     n->state = S_DISCONNECT_FINISHED;
1071     free_neighbour (n, GNUNET_NO);
1072     return;
1073   case S_CONNECT_SENT:
1074     send_disconnect (n); 
1075     n->state = S_DISCONNECT;
1076     break;
1077   case S_CONNECT_RECV_BLACKLIST_INBOUND:
1078   case S_CONNECT_RECV_ATS:
1079   case S_CONNECT_RECV_BLACKLIST:
1080     /* we never ACK'ed the other peer's request, no need to send DISCONNECT */
1081     n->state = S_DISCONNECT_FINISHED;
1082     free_neighbour (n, GNUNET_NO);
1083     return;
1084   case S_CONNECT_RECV_ACK:
1085     /* we DID ACK the other peer's request, must send DISCONNECT */
1086     send_disconnect (n); 
1087     n->state = S_DISCONNECT;
1088     break;   
1089   case S_CONNECTED:
1090   case S_RECONNECT_BLACKLIST:
1091   case S_RECONNECT_SENT:
1092   case S_CONNECTED_SWITCHING_BLACKLIST:
1093   case S_CONNECTED_SWITCHING_CONNECT_SENT:
1094     /* we are currently connected, need to send disconnect and do
1095        internal notifications and update statistics */
1096     send_disconnect (n);
1097     GNUNET_STATISTICS_set (GST_stats, 
1098                            gettext_noop ("# peers connected"), 
1099                            --neighbours_connected,
1100                            GNUNET_NO);
1101     disconnect_notify_cb (callback_cls, &n->id);
1102     n->state = S_DISCONNECT;
1103     break;
1104   case S_RECONNECT_ATS:
1105     /* ATS address request timeout, disconnect without sending disconnect message */
1106     GNUNET_STATISTICS_set (GST_stats,
1107                            gettext_noop ("# peers connected"),
1108                            --neighbours_connected,
1109                            GNUNET_NO);
1110     disconnect_notify_cb (callback_cls, &n->id);
1111     n->state = S_DISCONNECT;
1112     break;
1113   case S_DISCONNECT:
1114     /* already disconnected, ignore */
1115     break;
1116   case S_DISCONNECT_FINISHED:
1117     /* already cleaned up, how did we get here!? */
1118     GNUNET_assert (0);
1119     break;
1120   default:
1121     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1122     GNUNET_break (0);
1123     break;
1124   }
1125   /* schedule timeout to clean up */
1126   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1127     GNUNET_SCHEDULER_cancel (n->task);
1128   n->task = GNUNET_SCHEDULER_add_delayed (DISCONNECT_SENT_TIMEOUT,
1129                                           &master_task, n);
1130 }
1131
1132
1133 /**
1134  * We're done with our transmission attempt, continue processing.
1135  *
1136  * @param cls the 'struct MessageQueue' of the message
1137  * @param receiver intended receiver
1138  * @param success whether it worked or not
1139  */
1140 static void
1141 transmit_send_continuation (void *cls,
1142                             const struct GNUNET_PeerIdentity *receiver,
1143                             int success)
1144 {
1145   struct MessageQueue *mq = cls;
1146   struct NeighbourMapEntry *n;
1147
1148   if (NULL == (n = lookup_neighbour (receiver)))
1149   {
1150     GNUNET_free (mq);
1151     return; /* disconnect or other error while transmitting, can happen */
1152   }
1153   if (n->is_active == mq)
1154   {
1155     /* this is still "our" neighbour, remove us from its queue
1156        and allow it to send the next message now */
1157     n->is_active = NULL;
1158     if (GNUNET_SCHEDULER_NO_TASK != n->task)
1159       GNUNET_SCHEDULER_cancel (n->task);
1160     n->task = GNUNET_SCHEDULER_add_now (&master_task, n);    
1161   }
1162   GNUNET_assert (bytes_in_send_queue >= mq->message_buf_size);
1163   bytes_in_send_queue -= mq->message_buf_size;
1164   GNUNET_STATISTICS_set (GST_stats,
1165                         gettext_noop
1166                          ("# bytes in message queue for other peers"),
1167                          bytes_in_send_queue, GNUNET_NO);
1168   if (GNUNET_OK == success)
1169     GNUNET_STATISTICS_update (GST_stats,
1170                               gettext_noop
1171                               ("# messages transmitted to other peers"),
1172                               1, GNUNET_NO);
1173   else
1174     GNUNET_STATISTICS_update (GST_stats,
1175                               gettext_noop
1176                               ("# transmission failures for messages to other peers"),
1177                               1, GNUNET_NO);
1178   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1179               "Sending message to `%s' of type %u was a %s\n",
1180               GNUNET_i2s (receiver),
1181               ntohs (((struct GNUNET_MessageHeader *) mq->message_buf)->type),
1182               (success == GNUNET_OK) ? "success" : "FAILURE");
1183   if (NULL != mq->cont)
1184     mq->cont (mq->cont_cls, success);
1185   GNUNET_free (mq);
1186 }
1187
1188
1189 /**
1190  * Check the message list for the given neighbour and if we can
1191  * send a message, do so.  This function should only be called
1192  * if the connection is at least generally ready for transmission.
1193  * While we will only send one message at a time, no bandwidth
1194  * quota management is performed here.  If a message was given to
1195  * the plugin, the continuation will automatically re-schedule
1196  * the 'master' task once the next message might be transmitted.
1197  *
1198  * @param n target peer for which to transmit
1199  */
1200 static void
1201 try_transmission_to_peer (struct NeighbourMapEntry *n)
1202 {
1203   struct MessageQueue *mq;
1204   struct GNUNET_TIME_Relative timeout;
1205
1206   if (NULL == n->primary_address.address)
1207   {
1208     /* no address, why are we here? */
1209     GNUNET_break (0);
1210     return;
1211   }
1212   if ((0 == n->primary_address.address->address_length) && 
1213       (NULL == n->primary_address.session))
1214   {
1215     /* no address, why are we here? */
1216     GNUNET_break (0);
1217     return;
1218   }
1219   if (NULL != n->is_active)
1220   {
1221     /* transmission already pending */
1222     return;                     
1223   }
1224
1225   /* timeout messages from the queue that are past their due date */
1226   while (NULL != (mq = n->messages_head))
1227   {
1228     timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1229     if (timeout.rel_value > 0)
1230       break;
1231     GNUNET_STATISTICS_update (GST_stats,
1232                               gettext_noop
1233                               ("# messages timed out while in transport queue"),
1234                               1, GNUNET_NO);
1235     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1236     n->is_active = mq;
1237     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);     /* timeout */
1238   }
1239   if (NULL == mq)
1240     return;                     /* no more messages */
1241   GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1242   n->is_active = mq;
1243   send_with_session (n,
1244                      mq->message_buf, mq->message_buf_size,
1245                      0 /* priority */, timeout,
1246                      &transmit_send_continuation, mq);
1247 }
1248
1249
1250 /**
1251  * Send keepalive message to the neighbour.  Must only be called
1252  * if we are on 'connected' state.  Will internally determine
1253  * if a keepalive is truly needed (so can always be called).
1254  *
1255  * @param n neighbour that went idle and needs a keepalive
1256  */
1257 static void
1258 send_keepalive (struct NeighbourMapEntry *n)
1259 {
1260   struct GNUNET_MessageHeader m;
1261
1262   GNUNET_assert (S_CONNECTED == n->state);
1263   if (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time).rel_value > 0)
1264     return; /* no keepalive needed at this time */
1265   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1266   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE);
1267   send_with_session (n,
1268                      (const void *) &m, sizeof (m),
1269                      UINT32_MAX /* priority */,
1270                      KEEPALIVE_FREQUENCY,
1271                      NULL, NULL);
1272   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# keepalives sent"), 1,
1273                             GNUNET_NO);
1274   n->expect_latency_response = GNUNET_YES;
1275   n->last_keep_alive_time = GNUNET_TIME_absolute_get ();
1276   n->keep_alive_time = GNUNET_TIME_relative_to_absolute (KEEPALIVE_FREQUENCY);
1277 }
1278
1279
1280 /**
1281  * Keep the connection to the given neighbour alive longer,
1282  * we received a KEEPALIVE (or equivalent); send a response.
1283  *
1284  * @param neighbour neighbour to keep alive (by sending keep alive response)
1285  */
1286 void
1287 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
1288 {
1289   struct NeighbourMapEntry *n;
1290   struct GNUNET_MessageHeader m;
1291
1292   if (NULL == (n = lookup_neighbour (neighbour)))
1293   {
1294     GNUNET_STATISTICS_update (GST_stats,
1295                               gettext_noop
1296                               ("# KEEPALIVE messages discarded (peer unknown)"),
1297                               1, GNUNET_NO);
1298     return;
1299   }
1300   if (NULL == n->primary_address.session)
1301   {
1302     GNUNET_STATISTICS_update (GST_stats,
1303                               gettext_noop
1304                               ("# KEEPALIVE messages discarded (no session)"),
1305                               1, GNUNET_NO);
1306     return;
1307   }
1308   /* send reply to allow neighbour to measure latency */
1309   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1310   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE);
1311   send_with_session(n,
1312                     (const void *) &m, sizeof (m),
1313                     UINT32_MAX /* priority */,
1314                     KEEPALIVE_FREQUENCY,
1315                     NULL, NULL);
1316 }
1317
1318
1319 /**
1320  * We received a KEEP_ALIVE_RESPONSE message and use this to calculate
1321  * latency to this peer.  Pass the updated information (existing ats
1322  * plus calculated latency) to ATS.
1323  *
1324  * @param neighbour neighbour to keep alive
1325  * @param ats performance data
1326  * @param ats_count number of entries in ats
1327  */
1328 void
1329 GST_neighbours_keepalive_response (const struct GNUNET_PeerIdentity *neighbour,
1330                                    const struct GNUNET_ATS_Information *ats,
1331                                    uint32_t ats_count)
1332 {
1333   struct NeighbourMapEntry *n;
1334   uint32_t latency;
1335   struct GNUNET_ATS_Information ats_new[ats_count + 1];
1336
1337   if (NULL == (n = lookup_neighbour (neighbour)))
1338   {
1339     GNUNET_STATISTICS_update (GST_stats,
1340                               gettext_noop
1341                               ("# KEEPALIVE_RESPONSE messages discarded (not connected)"),
1342                               1, GNUNET_NO);
1343     return;
1344   }
1345   if ( (S_CONNECTED != n->state) ||
1346        (GNUNET_YES != n->expect_latency_response) )
1347   {
1348     GNUNET_STATISTICS_update (GST_stats,
1349                               gettext_noop
1350                               ("# KEEPALIVE_RESPONSE messages discarded (not expected)"),
1351                               1, GNUNET_NO);
1352     return;
1353   }
1354   n->expect_latency_response = GNUNET_NO;
1355   n->latency = GNUNET_TIME_absolute_get_duration (n->last_keep_alive_time);
1356   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1358               "Latency for peer `%s' is %llu ms\n",
1359               GNUNET_i2s (&n->id), n->latency.rel_value);
1360   memcpy (ats_new, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
1361   /* append latency */
1362   ats_new[ats_count].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1363   if (n->latency.rel_value > UINT32_MAX)
1364     latency = UINT32_MAX;
1365   else
1366     latency = n->latency.rel_value;
1367   ats_new[ats_count].value = htonl (latency);
1368   GNUNET_ATS_address_update (GST_ats, 
1369                              n->primary_address.address, 
1370                              n->primary_address.session, ats_new,
1371                              ats_count + 1);
1372 }
1373
1374
1375 /**
1376  * We have received a message from the given sender.  How long should
1377  * we delay before receiving more?  (Also used to keep the peer marked
1378  * as live).
1379  *
1380  * @param sender sender of the message
1381  * @param size size of the message
1382  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
1383  *                   GNUNET_NO if the neighbour is not connected or violates the quota,
1384  *                   GNUNET_SYSERR if the connection is not fully up yet
1385  * @return how long to wait before reading more from this sender
1386  */
1387 struct GNUNET_TIME_Relative
1388 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
1389                                         *sender, ssize_t size, int *do_forward)
1390 {
1391   struct NeighbourMapEntry *n;
1392   struct GNUNET_TIME_Relative ret;
1393   
1394   if (NULL == neighbours)
1395   {
1396     *do_forward = GNUNET_NO;
1397     return GNUNET_TIME_UNIT_FOREVER_REL; /* This can happen during shutdown */
1398   }
1399   if (NULL == (n = lookup_neighbour (sender)))
1400   {
1401     GST_neighbours_try_connect (sender);
1402     if (NULL == (n = lookup_neighbour (sender)))
1403     {
1404       GNUNET_STATISTICS_update (GST_stats,
1405                                 gettext_noop
1406                                 ("# messages discarded due to lack of neighbour record"),
1407                                 1, GNUNET_NO);
1408       *do_forward = GNUNET_NO;
1409       return GNUNET_TIME_UNIT_ZERO;
1410     }
1411   }
1412   if (! test_connected (n))
1413   {
1414     *do_forward = GNUNET_SYSERR;
1415     return GNUNET_TIME_UNIT_ZERO;
1416   }
1417   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
1418   {
1419     n->quota_violation_count++;
1420     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1421                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
1422                 n->in_tracker.available_bytes_per_s__,
1423                 n->quota_violation_count);
1424     /* Discount 32k per violation */
1425     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1426   }
1427   else
1428   {
1429     if (n->quota_violation_count > 0)
1430     {
1431       /* try to add 32k back */
1432       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1433       n->quota_violation_count--;
1434     }
1435   }
1436   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1437   {
1438     GNUNET_STATISTICS_update (GST_stats,
1439                               gettext_noop
1440                               ("# bandwidth quota violations by other peers"),
1441                               1, GNUNET_NO);
1442     *do_forward = GNUNET_NO;
1443     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1444   }
1445   *do_forward = GNUNET_YES;
1446   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 32 * 1024);
1447   if (ret.rel_value > 0)
1448   {
1449     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1450                 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
1451                 (unsigned long long) n->in_tracker.
1452                 consumption_since_last_update__,
1453                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1454                 (unsigned long long) ret.rel_value);
1455     GNUNET_STATISTICS_update (GST_stats,
1456                               gettext_noop ("# ms throttling suggested"),
1457                               (int64_t) ret.rel_value, GNUNET_NO);
1458   }
1459   return ret;
1460 }
1461
1462
1463 /**
1464  * Transmit a message to the given target using the active connection.
1465  *
1466  * @param target destination
1467  * @param msg message to send
1468  * @param msg_size number of bytes in msg
1469  * @param timeout when to fail with timeout
1470  * @param cont function to call when done
1471  * @param cont_cls closure for 'cont'
1472  */
1473 void
1474 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
1475                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
1476                      GST_NeighbourSendContinuation cont, void *cont_cls)
1477 {
1478   struct NeighbourMapEntry *n;
1479   struct MessageQueue *mq;
1480
1481   /* All ove these cases should never happen; they are all API violations.
1482      But we check anyway, just to be sure. */
1483   if (NULL == (n = lookup_neighbour (target)))
1484   {
1485     GNUNET_break (0);
1486     if (NULL != cont)
1487       cont (cont_cls, GNUNET_SYSERR);
1488     return;
1489   }
1490   if (GNUNET_YES != test_connected (n))
1491   {
1492     GNUNET_break (0);
1493     if (NULL != cont)
1494       cont (cont_cls, GNUNET_SYSERR);
1495     return;
1496   }
1497   bytes_in_send_queue += msg_size;
1498   GNUNET_STATISTICS_set (GST_stats,
1499                          gettext_noop
1500                          ("# bytes in message queue for other peers"),
1501                          bytes_in_send_queue, GNUNET_NO);
1502   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
1503   mq->cont = cont;
1504   mq->cont_cls = cont_cls;
1505   memcpy (&mq[1], msg, msg_size);
1506   mq->message_buf = (const char *) &mq[1];
1507   mq->message_buf_size = msg_size;
1508   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1509   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
1510   if ( (NULL != n->is_active) ||
1511        ( (NULL == n->primary_address.session) && (NULL == n->primary_address.address)) )
1512     return;
1513   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1514     GNUNET_SCHEDULER_cancel (n->task);
1515   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1516 }
1517
1518
1519 /**
1520  * Send a SESSION_CONNECT message via the given address.
1521  *
1522  * @param na address to use
1523  */
1524 static void
1525 send_session_connect (struct NeighbourAddress *na)
1526 {
1527   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1528   struct SessionConnectMessage connect_msg;
1529   
1530   if (NULL == (papi = GST_plugins_find (na->address->transport_name)))  
1531   {
1532     GNUNET_break (0);
1533     return;
1534   }
1535   if (NULL == na->session)
1536     na->session = papi->get_session (papi->cls, na->address);    
1537   if (NULL == na->session)
1538   {
1539     GNUNET_break (0);
1540     return;
1541   }
1542   na->connect_timestamp = GNUNET_TIME_absolute_get ();
1543   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1544   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1545   connect_msg.reserved = htonl (0);
1546   connect_msg.timestamp = GNUNET_TIME_absolute_hton (na->connect_timestamp);
1547   (void) papi->send (papi->cls,
1548                      na->session,
1549                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1550                      UINT_MAX,
1551                      GNUNET_TIME_UNIT_FOREVER_REL,
1552                      NULL, NULL);
1553 }
1554
1555
1556 /**
1557  * Send a SESSION_CONNECT_ACK message via the given address.
1558  *
1559  * @param address address to use
1560  * @param session session to use
1561  * @param timestamp timestamp to use for the ACK message
1562  */
1563 static void
1564 send_session_connect_ack_message (const struct GNUNET_HELLO_Address *address,
1565                                   struct Session *session,
1566                                   struct GNUNET_TIME_Absolute timestamp)
1567 {
1568   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1569   struct SessionConnectMessage connect_msg;
1570   
1571   if (NULL == (papi = GST_plugins_find (address->transport_name)))  
1572   {
1573     GNUNET_break (0);
1574     return;
1575   }
1576   if (NULL == session)
1577     session = papi->get_session (papi->cls, address);    
1578   if (NULL == session)
1579   {
1580     GNUNET_break (0);
1581     return;
1582   }
1583   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1584   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK);
1585   connect_msg.reserved = htonl (0);
1586   connect_msg.timestamp = GNUNET_TIME_absolute_hton (timestamp);
1587   (void) papi->send (papi->cls,
1588                      session,
1589                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1590                      UINT_MAX,
1591                      GNUNET_TIME_UNIT_FOREVER_REL,
1592                      NULL, NULL);
1593 }
1594
1595
1596 /**
1597  * Create a fresh entry in the neighbour map for the given peer
1598  *
1599  * @param peer peer to create an entry for
1600  * @return new neighbour map entry
1601  */
1602 static struct NeighbourMapEntry *
1603 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
1604 {
1605   struct NeighbourMapEntry *n;
1606
1607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1608               "Creating new neighbour entry for `%s'\n", 
1609               GNUNET_i2s (peer));
1610   n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
1611   n->id = *peer;
1612   n->state = S_NOT_CONNECTED;
1613   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1614   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1615                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1616                                  MAX_BANDWIDTH_CARRY_S);
1617   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1618   GNUNET_assert (GNUNET_OK ==
1619                  GNUNET_CONTAINER_multihashmap_put (neighbours,
1620                                                     &n->id.hashPubKey, n,
1621                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1622   return n;
1623 }
1624
1625
1626 /**
1627  * Check if the two given addresses are the same.
1628  * Actually only checks if the sessions are non-NULL
1629  * (which they should be) and then if they are identical;
1630  * the actual addresses don't matter if the session
1631  * pointers match anyway, and we must have session pointers
1632  * at this time.
1633  *
1634  * @param a1 first address to compare
1635  * @param a2 other address to compare
1636  * @return GNUNET_NO if the addresses do not match, GNUNET_YES if they do match
1637  */
1638 static int
1639 address_matches (const struct NeighbourAddress *a1,
1640                  const struct NeighbourAddress *a2)
1641 {
1642   if ( (NULL == a1->session) ||
1643        (NULL == a2->session) )
1644   {
1645     GNUNET_break (0);
1646     return 0;
1647   }
1648   return (a1->session == a2->session) ? GNUNET_YES : GNUNET_NO;
1649 }
1650
1651
1652 /**
1653  * Try to create a connection to the given target (eventually).
1654  *
1655  * @param target peer to try to connect to
1656  */
1657 void
1658 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
1659 {
1660   struct NeighbourMapEntry *n;
1661
1662   if (NULL == neighbours)  
1663     return; /* during shutdown, do nothing */
1664   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1665               "Asked to connect to peer `%s'\n",
1666               GNUNET_i2s (target));
1667   if (0 ==
1668       memcmp (target, &GST_my_identity, sizeof (struct GNUNET_PeerIdentity)))
1669   {
1670     /* refuse to connect to myself */
1671     /* FIXME: can this happen? Is this not an API violation? */
1672     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1673                 "Refusing to try to connect to myself.\n");
1674     return;
1675   }
1676   n = lookup_neighbour (target);
1677   if (NULL != n)
1678   {
1679     switch (n->state)
1680     {
1681     case S_NOT_CONNECTED:
1682       /* this should not be possible */
1683       GNUNET_break (0);
1684       free_neighbour (n, GNUNET_NO);
1685       break;
1686     case S_INIT_ATS:
1687     case S_INIT_BLACKLIST:
1688     case S_CONNECT_SENT:
1689     case S_CONNECT_RECV_BLACKLIST_INBOUND:
1690     case S_CONNECT_RECV_ATS:
1691     case S_CONNECT_RECV_BLACKLIST:
1692     case S_CONNECT_RECV_ACK:
1693       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1694                   "Ignoring request to try to connect to `%s', already trying!\n",
1695                   GNUNET_i2s (target));
1696       return; /* already trying */
1697     case S_CONNECTED:      
1698     case S_RECONNECT_ATS:
1699     case S_RECONNECT_BLACKLIST:
1700     case S_RECONNECT_SENT:
1701     case S_CONNECTED_SWITCHING_BLACKLIST:
1702     case S_CONNECTED_SWITCHING_CONNECT_SENT:
1703       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1704                   "Ignoring request to try to connect, already connected to `%s'!\n",
1705                   GNUNET_i2s (target));
1706       return; /* already connected */
1707     case S_DISCONNECT:
1708       /* get rid of remains, ready to re-try immediately */
1709       free_neighbour (n, GNUNET_NO);
1710       break;
1711     case S_DISCONNECT_FINISHED:
1712       /* should not be possible */      
1713       GNUNET_assert (0); 
1714     default:
1715       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1716       GNUNET_break (0);
1717       free_neighbour (n, GNUNET_NO);
1718       break;
1719     }
1720   }
1721   n = setup_neighbour (target);  
1722   n->state = S_INIT_ATS; 
1723   n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1724
1725   GNUNET_ATS_reset_backoff (GST_ats, target);
1726   GNUNET_ATS_suggest_address (GST_ats, target);
1727 }
1728
1729
1730 /**
1731  * Function called with the result of a blacklist check.
1732  *
1733  * @param cls closure with the 'struct BlackListCheckContext'
1734  * @param peer peer this check affects
1735  * @param result GNUNET_OK if the address is allowed
1736  */
1737 static void
1738 handle_test_blacklist_cont (void *cls,
1739                             const struct GNUNET_PeerIdentity *peer,
1740                             int result)
1741 {
1742   struct BlackListCheckContext *bcc = cls;
1743   struct NeighbourMapEntry *n;
1744
1745   bcc->bc = NULL;
1746   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1747               "Connection to new address of peer `%s' based on blacklist is `%s'\n",
1748               GNUNET_i2s (peer),
1749               (GNUNET_OK == result) ? "allowed" : "FORBIDDEN");
1750   if (NULL == (n = lookup_neighbour (peer)))
1751     goto cleanup; /* nobody left to care about new address */
1752   if (GNUNET_OK == result)
1753   {
1754     /* valid new address, let ATS know (regardless of where we are
1755        in the state machine) */
1756     GNUNET_ATS_address_add (GST_ats,
1757                             bcc->na.address,
1758                             bcc->na.session,
1759                             bcc->ats, bcc->ats_count);
1760   }
1761   switch (n->state)
1762   {
1763   case S_NOT_CONNECTED:
1764     /* this should not be possible */
1765     GNUNET_break (0);
1766     free_neighbour (n, GNUNET_NO);
1767     break;
1768   case S_INIT_ATS:
1769     /* still waiting on ATS suggestion */
1770     break;
1771   case S_INIT_BLACKLIST:
1772     /* check if the address the blacklist was fine with matches
1773        ATS suggestion, if so, we can move on! */
1774     if ( (GNUNET_OK == result) &&
1775          (1 == n->send_connect_ack) )
1776     {
1777       n->send_connect_ack = 2;
1778       send_session_connect_ack_message (bcc->na.address,
1779                                         bcc->na.session,
1780                                         n->connect_ack_timestamp);
1781     }
1782     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1783       break; /* result for an address we currently don't care about */
1784     if (GNUNET_OK == result)
1785     {
1786       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1787       n->state = S_CONNECT_SENT;
1788       send_session_connect (&n->primary_address);
1789     }
1790     else
1791     {
1792       // FIXME: should also possibly destroy session with plugin!?
1793       GNUNET_ATS_address_destroyed (GST_ats,
1794                                     bcc->na.address,
1795                                     NULL);
1796       free_address (&n->primary_address);
1797       n->state = S_INIT_ATS;
1798       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1799       // FIXME: do we need to ask ATS again for suggestions?
1800       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1801     }
1802     break;
1803   case S_CONNECT_SENT:
1804     /* waiting on CONNECT_ACK, switch session and send ACK if one is pending */
1805     if ( (GNUNET_OK == result) &&
1806          (1 == n->send_connect_ack) )
1807     {
1808       n->send_connect_ack = 2;
1809       /* FIXME: we might be switching to a different address here without
1810          asking (or telling!) ATS; while this is done for a good reason --
1811          our CONNECT was not answered, but we got another session with
1812          a CONNECT from the other peer, so maybe this is an inbound session
1813          that actually works -- this is unclean as ATS needs to be told
1814          about this (or even asked first!?) Anyway, I'm adding this as
1815          something expermental for now to see if it fixes issues LRN reported
1816          on IRC on 24/6/2012.  */
1817       set_address (&n->primary_address,
1818                    bcc->na.address,
1819                    bcc->na.session,
1820                    n->primary_address.bandwidth_in,
1821                    n->primary_address.bandwidth_out,
1822                    GNUNET_YES);
1823       send_session_connect_ack_message (n->primary_address.address,
1824                                         n->primary_address.session,
1825                                         n->connect_ack_timestamp);
1826     }
1827     break; 
1828   case S_CONNECT_RECV_BLACKLIST_INBOUND:
1829     n->state = S_CONNECT_RECV_ATS;
1830     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1831     GNUNET_ATS_reset_backoff (GST_ats, peer);
1832     GNUNET_ATS_suggest_address (GST_ats, peer);
1833     break;
1834   case S_CONNECT_RECV_ATS:
1835     /* still waiting on ATS suggestion, don't care about blacklist */
1836     break;
1837   case S_CONNECT_RECV_BLACKLIST:
1838     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1839       break; /* result for an address we currently don't care about */
1840     if (GNUNET_OK == result)
1841     {
1842       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1843       n->state = S_CONNECT_RECV_ACK;
1844       send_session_connect_ack_message (bcc->na.address,
1845                                         bcc->na.session,
1846                                         n->connect_ack_timestamp);
1847       if (1 == n->send_connect_ack) 
1848         n->send_connect_ack = 2;
1849     }
1850     else
1851     {
1852       // FIXME: should also possibly destroy session with plugin!?
1853       GNUNET_ATS_address_destroyed (GST_ats,
1854                                     bcc->na.address,
1855                                     NULL);
1856       free_address (&n->primary_address);
1857       n->state = S_INIT_ATS;
1858       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1859       // FIXME: do we need to ask ATS again for suggestions?
1860       GNUNET_ATS_reset_backoff (GST_ats, peer);
1861       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1862     }
1863     break;
1864   case S_CONNECT_RECV_ACK:
1865     /* waiting on SESSION_ACK, send ACK if one is pending */
1866     if ( (GNUNET_OK == result) &&
1867          (1 == n->send_connect_ack) )
1868     {
1869       n->send_connect_ack = 2;
1870       send_session_connect_ack_message (n->primary_address.address,
1871                                         n->primary_address.session,
1872                                         n->connect_ack_timestamp);
1873     }
1874     break; 
1875   case S_CONNECTED:
1876     /* already connected, don't care about blacklist */
1877     break;
1878   case S_RECONNECT_ATS:
1879     /* still waiting on ATS suggestion, don't care about blacklist */
1880     break;     
1881   case S_RECONNECT_BLACKLIST:
1882     if ( (GNUNET_OK == result) &&
1883          (1 == n->send_connect_ack) )
1884     {
1885       n->send_connect_ack = 2;
1886       send_session_connect_ack_message (bcc->na.address,
1887                                         bcc->na.session,
1888                                         n->connect_ack_timestamp);
1889     }
1890     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1891       break; /* result for an address we currently don't care about */
1892     if (GNUNET_OK == result)
1893     {
1894       send_session_connect (&n->primary_address);
1895       n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
1896       n->state = S_RECONNECT_SENT;
1897     }
1898     else
1899     {
1900       GNUNET_ATS_address_destroyed (GST_ats,
1901                                     bcc->na.address,
1902                                     NULL);
1903       n->state = S_RECONNECT_ATS;
1904       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1905       // FIXME: do we need to ask ATS again for suggestions?
1906       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1907     }
1908     break;
1909   case S_RECONNECT_SENT:
1910     /* waiting on CONNECT_ACK, don't care about blacklist */
1911     if ( (GNUNET_OK == result) &&
1912          (1 == n->send_connect_ack) )
1913     {
1914       n->send_connect_ack = 2;
1915       send_session_connect_ack_message (n->primary_address.address,
1916                                         n->primary_address.session,
1917                                         n->connect_ack_timestamp);
1918     }
1919     break;     
1920   case S_CONNECTED_SWITCHING_BLACKLIST:
1921     if (GNUNET_YES != address_matches (&bcc->na, &n->alternative_address))
1922       break; /* result for an address we currently don't care about */
1923     if (GNUNET_OK == result)
1924     {
1925       send_session_connect (&n->alternative_address);
1926       n->state = S_CONNECTED_SWITCHING_CONNECT_SENT;
1927     }
1928     else
1929     {
1930       GNUNET_ATS_address_destroyed (GST_ats,
1931                                     bcc->na.address,
1932                                     NULL);
1933       free_address (&n->alternative_address);
1934       n->state = S_CONNECTED;
1935     }
1936     break;
1937   case S_CONNECTED_SWITCHING_CONNECT_SENT:
1938     /* waiting on CONNECT_ACK, don't care about blacklist */
1939     if ( (GNUNET_OK == result) &&
1940          (1 == n->send_connect_ack) )
1941     {
1942       n->send_connect_ack = 2;
1943       send_session_connect_ack_message (n->primary_address.address,
1944                                         n->primary_address.session,
1945                                         n->connect_ack_timestamp);
1946     }
1947     break;     
1948   case S_DISCONNECT:
1949     /* Nothing to do here, ATS will already do what can be done */
1950     break;
1951   case S_DISCONNECT_FINISHED:
1952     /* should not be possible */
1953     GNUNET_assert (0);
1954     break;
1955   default:
1956     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1957     GNUNET_break (0);
1958     free_neighbour (n, GNUNET_NO);
1959     break;
1960   }
1961  cleanup:
1962   GNUNET_HELLO_address_free (bcc->na.address);
1963   GNUNET_CONTAINER_DLL_remove (bc_head,
1964                                bc_tail,
1965                                bcc);
1966   GNUNET_free (bcc);
1967 }
1968
1969
1970 /**
1971  * We want to know if connecting to a particular peer via
1972  * a particular address is allowed.  Check it!
1973  *
1974  * @param peer identity of the peer to switch the address for
1975  * @param ts time at which the check was initiated
1976  * @param address address of the other peer, NULL if other peer
1977  *                       connected to us
1978  * @param session session to use (or NULL)
1979  * @param ats performance data
1980  * @param ats_count number of entries in ats (excluding 0-termination)
1981  */
1982 static void
1983 check_blacklist (const struct GNUNET_PeerIdentity *peer,
1984                  struct GNUNET_TIME_Absolute ts,
1985                  const struct GNUNET_HELLO_Address *address,
1986                  struct Session *session,
1987                  const struct GNUNET_ATS_Information *ats,
1988                  uint32_t ats_count)
1989 {
1990   struct BlackListCheckContext *bcc;
1991   struct GST_BlacklistCheck *bc;
1992
1993   bcc =
1994       GNUNET_malloc (sizeof (struct BlackListCheckContext) +
1995                      sizeof (struct GNUNET_ATS_Information) * ats_count);
1996   bcc->ats_count = ats_count;
1997   bcc->na.address = GNUNET_HELLO_address_copy (address);
1998   bcc->na.session = session;
1999   bcc->na.connect_timestamp = ts;
2000   bcc->ats = (struct GNUNET_ATS_Information *) &bcc[1];
2001   memcpy (bcc->ats, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
2002   GNUNET_CONTAINER_DLL_insert (bc_head,
2003                                bc_tail,
2004                                bcc);
2005   if (NULL != (bc = GST_blacklist_test_allowed (peer, 
2006                                                 address->transport_name,
2007                                                 &handle_test_blacklist_cont, bcc)))
2008     bcc->bc = bc; 
2009   /* if NULL == bc, 'cont' was already called and 'bcc' already free'd, so
2010      we must only store 'bc' if 'bc' is non-NULL... */
2011 }
2012
2013
2014 /**
2015  * We received a 'SESSION_CONNECT' message from the other peer.
2016  * Consider switching to it.
2017  *
2018  * @param message possibly a 'struct SessionConnectMessage' (check format)
2019  * @param peer identity of the peer to switch the address for
2020  * @param address address of the other peer, NULL if other peer
2021  *                       connected to us
2022  * @param session session to use (or NULL)
2023  * @param ats performance data
2024  * @param ats_count number of entries in ats (excluding 0-termination)
2025  */
2026 void
2027 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
2028                                const struct GNUNET_PeerIdentity *peer,
2029                                const struct GNUNET_HELLO_Address *address,
2030                                struct Session *session,
2031                                const struct GNUNET_ATS_Information *ats,
2032                                uint32_t ats_count)
2033 {
2034   const struct SessionConnectMessage *scm;
2035   struct NeighbourMapEntry *n;
2036   struct GNUNET_TIME_Absolute ts;
2037
2038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2039               "Received CONNECT message from peer `%s'\n", 
2040               GNUNET_i2s (peer));
2041
2042   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2043   {
2044     GNUNET_break_op (0);
2045     return;
2046   }
2047   if (NULL == neighbours)
2048     return; /* we're shutting down */
2049   scm = (const struct SessionConnectMessage *) message;
2050   GNUNET_break_op (0 == ntohl (scm->reserved));
2051   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2052   n = lookup_neighbour (peer);
2053   if (NULL == n)
2054     n = setup_neighbour (peer);
2055   n->send_connect_ack = 1;
2056   n->connect_ack_timestamp = ts;
2057
2058   switch (n->state)
2059   {  
2060   case S_NOT_CONNECTED:
2061     n->state = S_CONNECT_RECV_BLACKLIST_INBOUND;
2062     /* Do a blacklist check for the new address */
2063     check_blacklist (peer, ts, address, session, ats, ats_count);
2064     break;
2065   case S_INIT_ATS:
2066   case S_INIT_BLACKLIST:
2067   case S_CONNECT_SENT:
2068   case S_CONNECT_RECV_ATS:
2069   case S_CONNECT_RECV_BLACKLIST:
2070   case S_CONNECT_RECV_ACK:
2071     /* It can never hurt to have an alternative address in the above cases, 
2072        see if it is allowed */
2073     check_blacklist (peer, ts, address, session, ats, ats_count);
2074     break;
2075   case S_CONNECTED:
2076     /* we are already connected and can thus send the ACK immediately;
2077        still, it can never hurt to have an alternative address, so also
2078        tell ATS  about it */
2079     GNUNET_assert (NULL != n->primary_address.address);
2080     GNUNET_assert (NULL != n->primary_address.session);
2081     n->send_connect_ack = 0;
2082     send_session_connect_ack_message (n->primary_address.address,
2083                                       n->primary_address.session, ts);
2084     check_blacklist (peer, ts, address, session, ats, ats_count);
2085     break;
2086   case S_RECONNECT_ATS:
2087   case S_RECONNECT_BLACKLIST:
2088   case S_RECONNECT_SENT:
2089     /* It can never hurt to have an alternative address in the above cases, 
2090        see if it is allowed */
2091     check_blacklist (peer, ts, address, session, ats, ats_count);
2092     break;
2093   case S_CONNECTED_SWITCHING_BLACKLIST:
2094   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2095     /* we are already connected and can thus send the ACK immediately;
2096        still, it can never hurt to have an alternative address, so also
2097        tell ATS  about it */
2098     GNUNET_assert (NULL != n->primary_address.address);
2099     GNUNET_assert (NULL != n->primary_address.session);
2100     n->send_connect_ack = 0;
2101     send_session_connect_ack_message (n->primary_address.address,
2102                                       n->primary_address.session, ts);
2103     check_blacklist (peer, ts, address, session, ats, ats_count);
2104     break;
2105   case S_DISCONNECT:
2106     /* get rid of remains without terminating sessions, ready to re-try */
2107     free_neighbour (n, GNUNET_YES);
2108     n = setup_neighbour (peer);
2109     n->state = S_CONNECT_RECV_BLACKLIST_INBOUND;
2110     check_blacklist (peer, ts, address, session, ats, ats_count);
2111     break;
2112   case S_DISCONNECT_FINISHED:
2113     /* should not be possible */
2114     GNUNET_assert (0);
2115     break;
2116   default:
2117     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2118     GNUNET_break (0);
2119     free_neighbour (n, GNUNET_NO);
2120     break;
2121   }
2122 }
2123
2124
2125 /**
2126  * For an existing neighbour record, set the active connection to
2127  * use the given address.  
2128  *
2129  * @param peer identity of the peer to switch the address for
2130  * @param address address of the other peer, NULL if other peer
2131  *                       connected to us
2132  * @param session session to use (or NULL)
2133  * @param ats performance data
2134  * @param ats_count number of entries in ats
2135  * @param bandwidth_in inbound quota to be used when connection is up
2136  * @param bandwidth_out outbound quota to be used when connection is up
2137  */
2138 void
2139 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
2140                                   const struct GNUNET_HELLO_Address *address,
2141                                   struct Session *session,
2142                                   const struct GNUNET_ATS_Information *ats,
2143                                   uint32_t ats_count,
2144                                   struct GNUNET_BANDWIDTH_Value32NBO
2145                                   bandwidth_in,
2146                                   struct GNUNET_BANDWIDTH_Value32NBO
2147                                   bandwidth_out)
2148 {
2149   struct NeighbourMapEntry *n;
2150   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2151
2152   GNUNET_assert (address->transport_name != NULL);
2153   if (NULL == (n = lookup_neighbour (peer)))
2154     return;
2155
2156   /* Obtain an session for this address from plugin */
2157   if (NULL == (papi = GST_plugins_find (address->transport_name)))
2158   {
2159     /* we don't have the plugin for this address */
2160     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2161     return;
2162   }
2163   if ((NULL == session) && (0 == address->address_length))
2164   {
2165     GNUNET_break (0);
2166     if (strlen (address->transport_name) > 0)
2167       GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2168     return;
2169   }
2170
2171   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2172               "ATS tells us to switch to address '%s' session %p for peer `%s' in state %s\n",
2173               (address->address_length != 0) ? GST_plugins_a2s (address): "<inbound>",
2174               session,
2175               GNUNET_i2s (peer),
2176               print_state (n->state));
2177
2178   if (NULL == session)
2179   {
2180     session = papi->get_session (papi->cls, address);
2181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2182                 "Obtained new session for peer `%s' and  address '%s': %p\n",
2183                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address), session);
2184   }
2185   if (NULL == session)
2186   {
2187     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2188                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
2189                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));    
2190     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2191     return;
2192   }
2193   switch (n->state)
2194   {
2195   case S_NOT_CONNECTED:
2196     GNUNET_break (0);
2197     free_neighbour (n, GNUNET_NO);
2198     return;
2199   case S_INIT_ATS:
2200     set_address (&n->primary_address,
2201                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2202     n->state = S_INIT_BLACKLIST;
2203     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2204     check_blacklist (&n->id,
2205                      n->connect_ack_timestamp,
2206                      address, session, ats, ats_count);    
2207     break;
2208   case S_INIT_BLACKLIST:
2209     /* ATS suggests a different address, switch again */
2210     set_address (&n->primary_address,
2211                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2212     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2213     check_blacklist (&n->id,
2214                      n->connect_ack_timestamp,
2215                      address, session, ats, ats_count);    
2216     break;
2217   case S_CONNECT_SENT:
2218     /* ATS suggests a different address, switch again */
2219     set_address (&n->primary_address,
2220                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2221     n->state = S_INIT_BLACKLIST;
2222     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2223     check_blacklist (&n->id,
2224                      n->connect_ack_timestamp,
2225                      address, session, ats, ats_count);    
2226     break;
2227   case S_CONNECT_RECV_ATS:
2228     set_address (&n->primary_address,
2229                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2230     n->state = S_CONNECT_RECV_BLACKLIST;
2231     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2232     check_blacklist (&n->id,
2233                      n->connect_ack_timestamp,
2234                      address, session, ats, ats_count);    
2235     break;
2236   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2237     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2238     check_blacklist (&n->id,
2239                      n->connect_ack_timestamp,
2240                      address, session, ats, ats_count);
2241     break;
2242   case S_CONNECT_RECV_BLACKLIST:
2243   case S_CONNECT_RECV_ACK:
2244     /* ATS asks us to switch while we were trying to connect; switch to new
2245        address and check blacklist again */
2246     set_address (&n->primary_address,
2247                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2248     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2249     check_blacklist (&n->id,
2250                      n->connect_ack_timestamp,
2251                      address, session, ats, ats_count);    
2252     break;
2253   case S_CONNECTED:
2254     GNUNET_assert (NULL != n->primary_address.address);
2255     GNUNET_assert (NULL != n->primary_address.session);
2256     if (n->primary_address.session == session)
2257     {
2258       /* not an address change, just a quota change */
2259       set_address (&n->primary_address,
2260                    address, session, bandwidth_in, bandwidth_out, GNUNET_YES);
2261       break;
2262     }
2263     /* ATS asks us to switch a life connection; see if we can get
2264        a CONNECT_ACK on it before we actually do this! */
2265     set_address (&n->alternative_address,
2266                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2267     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2268     check_blacklist (&n->id,
2269                      GNUNET_TIME_absolute_get (),
2270                      address, session, ats, ats_count);
2271     break;
2272   case S_RECONNECT_ATS:
2273     set_address (&n->primary_address,
2274                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2275     n->state = S_RECONNECT_BLACKLIST;
2276     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2277     check_blacklist (&n->id,
2278                      n->connect_ack_timestamp,
2279                      address, session, ats, ats_count);    
2280     break;
2281   case S_RECONNECT_BLACKLIST:
2282     /* ATS asks us to switch while we were trying to reconnect; switch to new
2283        address and check blacklist again */
2284     set_address (&n->primary_address,
2285                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2286     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2287     check_blacklist (&n->id,
2288                      n->connect_ack_timestamp,
2289                      address, session, ats, ats_count);    
2290     break;
2291   case S_RECONNECT_SENT:
2292     /* ATS asks us to switch while we were trying to reconnect; switch to new
2293        address and check blacklist again */
2294     set_address (&n->primary_address,
2295                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2296     n->state = S_RECONNECT_BLACKLIST;
2297     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2298     check_blacklist (&n->id,
2299                      n->connect_ack_timestamp,
2300                      address, session, ats, ats_count); 
2301     break;
2302   case S_CONNECTED_SWITCHING_BLACKLIST:
2303     if (n->primary_address.session == session)
2304     {
2305       /* ATS switches back to still-active session */
2306       free_address (&n->alternative_address);
2307       n->state = S_CONNECTED;
2308       break;
2309     }
2310     /* ATS asks us to switch a life connection, update blacklist check */
2311     set_address (&n->alternative_address,
2312                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2313     check_blacklist (&n->id,
2314                      GNUNET_TIME_absolute_get (),
2315                      address, session, ats, ats_count);
2316     break;
2317   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2318     if (n->primary_address.session == session)
2319     {
2320       /* ATS switches back to still-active session */
2321       free_address (&n->alternative_address);
2322       n->state = S_CONNECTED;
2323       break;
2324     }
2325     /* ATS asks us to switch a life connection, update blacklist check */
2326     set_address (&n->alternative_address,
2327                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2328     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2329     check_blacklist (&n->id,
2330                      GNUNET_TIME_absolute_get (),
2331                      address, session, ats, ats_count);
2332     break;
2333   case S_DISCONNECT:
2334     /* not going to switch addresses while disconnecting */
2335     return;
2336   case S_DISCONNECT_FINISHED:
2337     GNUNET_assert (0);
2338     break;
2339   default:
2340     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2341     GNUNET_break (0);
2342     break;
2343   }
2344 }
2345
2346
2347 /**
2348  * Master task run for every neighbour.  Performs all of the time-related
2349  * activities (keep alive, send next message, disconnect if idle, finish
2350  * clean up after disconnect).
2351  *
2352  * @param cls the 'struct NeighbourMapEntry' for which we are running
2353  * @param tc scheduler context (unused)
2354  */
2355 static void
2356 master_task (void *cls,
2357              const struct GNUNET_SCHEDULER_TaskContext *tc)
2358 {
2359   struct NeighbourMapEntry *n = cls;
2360   struct GNUNET_TIME_Relative delay;
2361
2362   n->task = GNUNET_SCHEDULER_NO_TASK;
2363   delay = GNUNET_TIME_absolute_get_remaining (n->timeout);  
2364   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2365               "Master task runs for neighbour `%s' in state %s with timeout in %llu ms\n",
2366               GNUNET_i2s (&n->id),
2367               print_state(n->state),
2368               (unsigned long long) delay.rel_value);
2369   switch (n->state)
2370   {
2371   case S_NOT_CONNECTED:
2372     /* invalid state for master task, clean up */
2373     GNUNET_break (0);
2374     n->state = S_DISCONNECT_FINISHED;
2375     free_neighbour (n, GNUNET_NO);
2376     return;
2377   case S_INIT_ATS:
2378     if (0 == delay.rel_value)
2379     {
2380       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2381                   "Connection to `%s' timed out waiting for ATS to provide address\n",
2382                   GNUNET_i2s (&n->id));
2383       n->state = S_DISCONNECT_FINISHED;
2384       free_neighbour (n, GNUNET_NO);
2385       return;
2386     }
2387     break;
2388   case S_INIT_BLACKLIST:
2389     if (0 == delay.rel_value)
2390     {
2391       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2392                   "Connection to `%s' timed out waiting for BLACKLIST to approve address\n",
2393                   GNUNET_i2s (&n->id));
2394       n->state = S_DISCONNECT_FINISHED;
2395       free_neighbour (n, GNUNET_NO);
2396       return;
2397     }
2398     break;
2399   case S_CONNECT_SENT:
2400     if (0 == delay.rel_value)
2401     {
2402       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2403                   "Connection to `%s' timed out waiting for other peer to send CONNECT_ACK\n",
2404                   GNUNET_i2s (&n->id));
2405       disconnect_neighbour (n);
2406       return;
2407     }
2408     break;
2409   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2410     if (0 == delay.rel_value)
2411     {
2412       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2413                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for received CONNECT\n",
2414                   GNUNET_i2s (&n->id));
2415       n->state = S_DISCONNECT_FINISHED;
2416       free_neighbour (n, GNUNET_NO);
2417       return;
2418     }
2419     break;
2420   case S_CONNECT_RECV_ATS:
2421     if (0 == delay.rel_value)
2422     {
2423       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2424                   "Connection to `%s' timed out waiting ATS to provide address to use for CONNECT_ACK\n",
2425                   GNUNET_i2s (&n->id));
2426       n->state = S_DISCONNECT_FINISHED;
2427       free_neighbour (n, GNUNET_NO);
2428       return;
2429     }
2430     break;
2431   case S_CONNECT_RECV_BLACKLIST:
2432     if (0 == delay.rel_value)
2433     {
2434       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2435                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for CONNECT_ACK\n",
2436                   GNUNET_i2s (&n->id));
2437       n->state = S_DISCONNECT_FINISHED;
2438       free_neighbour (n, GNUNET_NO);
2439       return;
2440     }
2441     break;
2442   case S_CONNECT_RECV_ACK:
2443     if (0 == delay.rel_value)
2444     {
2445       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2446                   "Connection to `%s' timed out waiting for other peer to send SESSION_ACK\n",
2447                   GNUNET_i2s (&n->id));
2448       disconnect_neighbour (n);
2449       return;
2450     }
2451     break;
2452   case S_CONNECTED:
2453     if (0 == delay.rel_value)
2454     {
2455       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2456                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2457                   GNUNET_i2s (&n->id));
2458       disconnect_neighbour (n);
2459       return;
2460     }
2461     try_transmission_to_peer (n);
2462     send_keepalive (n);
2463     break;
2464   case S_RECONNECT_ATS:
2465     if (0 == delay.rel_value)
2466     {
2467       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2468                   "Connection to `%s' timed out, waiting for ATS replacement address\n",
2469                   GNUNET_i2s (&n->id));
2470       disconnect_neighbour (n);
2471       return;
2472     }
2473     break;
2474   case S_RECONNECT_BLACKLIST:
2475     if (0 == delay.rel_value)
2476     {
2477       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2478                   "Connection to `%s' timed out, waiting for BLACKLIST to approve replacement address\n",
2479                   GNUNET_i2s (&n->id));
2480       disconnect_neighbour (n);
2481       return;
2482     }
2483     break;
2484   case S_RECONNECT_SENT:
2485     if (0 == delay.rel_value)
2486     {
2487       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488                   "Connection to `%s' timed out, waiting for other peer to CONNECT_ACK replacement address\n",
2489                   GNUNET_i2s (&n->id));
2490       disconnect_neighbour (n);
2491       return;
2492     }
2493     break;
2494   case S_CONNECTED_SWITCHING_BLACKLIST:
2495     if (0 == delay.rel_value)
2496     {
2497       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2498                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2499                   GNUNET_i2s (&n->id));
2500       disconnect_neighbour (n);
2501       return;
2502     }
2503     try_transmission_to_peer (n);
2504     send_keepalive (n);
2505     break;
2506   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2507     if (0 == delay.rel_value)
2508     {
2509       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2510                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs (after trying to CONNECT on alternative address)\n",
2511                   GNUNET_i2s (&n->id));
2512       disconnect_neighbour (n);
2513       return;
2514     }
2515     try_transmission_to_peer (n);
2516     send_keepalive (n);
2517     break;
2518   case S_DISCONNECT:
2519     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2520                 "Cleaning up connection to `%s' after sending DISCONNECT\n",
2521                 GNUNET_i2s (&n->id));
2522     free_neighbour (n, GNUNET_NO);
2523     n->state = S_DISCONNECT_FINISHED;
2524     return;
2525   case S_DISCONNECT_FINISHED:
2526     /* how did we get here!? */
2527     GNUNET_assert (0);
2528     break;
2529   default:
2530     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2531     GNUNET_break (0);
2532     break;  
2533   }
2534   if ( (S_CONNECTED_SWITCHING_CONNECT_SENT == n->state) ||
2535        (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
2536        (S_CONNECTED == n->state) )    
2537   {
2538     /* if we are *now* in one of these three states, we're sending
2539        keep alive messages, so we need to consider the keepalive
2540        delay, not just the connection timeout */
2541     delay = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time),
2542                                       delay);
2543   }
2544   if (GNUNET_SCHEDULER_NO_TASK == n->task)
2545     n->task = GNUNET_SCHEDULER_add_delayed (delay,
2546                                             &master_task,
2547                                             n);
2548 }
2549
2550
2551 /**
2552  * Send a SESSION_ACK message to the neighbour to confirm that we
2553  * got his CONNECT_ACK.
2554  *
2555  * @param n neighbour to send the SESSION_ACK to
2556  */
2557 static void
2558 send_session_ack_message (struct NeighbourMapEntry *n)
2559 {
2560   struct GNUNET_MessageHeader msg;
2561
2562   msg.size = htons (sizeof (struct GNUNET_MessageHeader));
2563   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
2564   (void) send_with_session(n,
2565                            (const char *) &msg, sizeof (struct GNUNET_MessageHeader),
2566                            UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
2567                            NULL, NULL);
2568 }
2569
2570
2571 /**
2572  * We received a 'SESSION_CONNECT_ACK' message from the other peer.
2573  * Consider switching to it.
2574  *
2575  * @param message possibly a 'struct SessionConnectMessage' (check format)
2576  * @param peer identity of the peer to switch the address for
2577  * @param address address of the other peer, NULL if other peer
2578  *                       connected to us
2579  * @param session session to use (or NULL)
2580  * @param ats performance data
2581  * @param ats_count number of entries in ats
2582  */
2583 void
2584 GST_neighbours_handle_connect_ack (const struct GNUNET_MessageHeader *message,
2585                                    const struct GNUNET_PeerIdentity *peer,
2586                                    const struct GNUNET_HELLO_Address *address,
2587                                    struct Session *session,
2588                                    const struct GNUNET_ATS_Information *ats,
2589                                    uint32_t ats_count)
2590 {
2591   const struct SessionConnectMessage *scm;
2592   struct GNUNET_TIME_Absolute ts;
2593   struct NeighbourMapEntry *n;
2594
2595   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2596               "Received CONNECT_ACK message from peer `%s'\n",
2597               GNUNET_i2s (peer));
2598
2599   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2600   {
2601     GNUNET_break_op (0);
2602     return;
2603   }
2604   scm = (const struct SessionConnectMessage *) message;
2605   GNUNET_break_op (ntohl (scm->reserved) == 0);
2606   if (NULL == (n = lookup_neighbour (peer)))
2607   {
2608     GNUNET_STATISTICS_update (GST_stats,
2609                               gettext_noop
2610                               ("# unexpected CONNECT_ACK messages (no peer)"),
2611                               1, GNUNET_NO);
2612     return;
2613   }
2614   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2615   switch (n->state)
2616   {
2617   case S_NOT_CONNECTED:
2618     GNUNET_break (0);
2619     free_neighbour (n, GNUNET_NO);
2620     return;
2621   case S_INIT_ATS:
2622   case S_INIT_BLACKLIST:
2623     GNUNET_STATISTICS_update (GST_stats,
2624                               gettext_noop
2625                               ("# unexpected CONNECT_ACK messages (not ready)"),
2626                               1, GNUNET_NO);
2627     break;    
2628   case S_CONNECT_SENT:
2629     if (ts.abs_value != n->primary_address.connect_timestamp.abs_value)
2630       break; /* ACK does not match our original CONNECT message */
2631     n->state = S_CONNECTED;
2632     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2633     GNUNET_STATISTICS_set (GST_stats, 
2634                            gettext_noop ("# peers connected"), 
2635                            ++neighbours_connected,
2636                            GNUNET_NO);
2637     connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2638     /* Tell ATS that the outbound session we created to send CONNECT was successfull */
2639     GNUNET_ATS_address_add (GST_ats,
2640                             n->primary_address.address,
2641                             n->primary_address.session,
2642                             ats, ats_count);
2643     set_address (&n->primary_address,
2644                  n->primary_address.address,
2645                  n->primary_address.session,
2646                  n->primary_address.bandwidth_in,
2647                  n->primary_address.bandwidth_out,
2648                  GNUNET_YES);
2649     send_session_ack_message (n);
2650     break;
2651   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2652   case S_CONNECT_RECV_ATS:
2653   case S_CONNECT_RECV_BLACKLIST:
2654   case S_CONNECT_RECV_ACK:
2655     GNUNET_STATISTICS_update (GST_stats,
2656                               gettext_noop
2657                               ("# unexpected CONNECT_ACK messages (not ready)"),
2658                               1, GNUNET_NO);
2659     break;
2660   case S_CONNECTED:
2661     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2662     send_session_ack_message (n);
2663     break;
2664   case S_RECONNECT_ATS:
2665   case S_RECONNECT_BLACKLIST:
2666     /* we didn't expect any CONNECT_ACK, as we are waiting for ATS
2667        to give us a new address... */
2668     GNUNET_STATISTICS_update (GST_stats,
2669                               gettext_noop
2670                               ("# unexpected CONNECT_ACK messages (waiting on ATS)"),
2671                               1, GNUNET_NO);
2672     break;
2673   case S_RECONNECT_SENT:
2674     /* new address worked; go back to connected! */
2675     n->state = S_CONNECTED;
2676     send_session_ack_message (n);
2677     break;
2678   case S_CONNECTED_SWITCHING_BLACKLIST:
2679     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2680     send_session_ack_message (n);
2681     break;
2682   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2683     /* new address worked; adopt it and go back to connected! */
2684     n->state = S_CONNECTED;
2685     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2686     GNUNET_break (GNUNET_NO == n->alternative_address.ats_active);
2687     GNUNET_ATS_address_add(GST_ats,
2688                            n->alternative_address.address,
2689                            n->alternative_address.session,
2690                            ats, ats_count);
2691     set_address (&n->primary_address,
2692                  n->alternative_address.address,
2693                  n->alternative_address.session,
2694                  n->alternative_address.bandwidth_in,
2695                  n->alternative_address.bandwidth_out,
2696                  GNUNET_YES);
2697     free_address (&n->alternative_address);
2698     send_session_ack_message (n);
2699     break;    
2700   case S_DISCONNECT:
2701     GNUNET_STATISTICS_update (GST_stats,
2702                               gettext_noop
2703                               ("# unexpected CONNECT_ACK messages (disconnecting)"),
2704                               1, GNUNET_NO);
2705     break;
2706   case S_DISCONNECT_FINISHED:
2707     GNUNET_assert (0);
2708     break;
2709   default:
2710     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2711     GNUNET_break (0);
2712     break;   
2713   }
2714 }
2715
2716
2717 /**
2718  * A session was terminated. Take note; if needed, try to get
2719  * an alternative address from ATS.
2720  *
2721  * @param peer identity of the peer where the session died
2722  * @param session session that is gone
2723  * @return GNUNET_YES if this was a session used, GNUNET_NO if
2724  *        this session was not in use
2725  */
2726 int
2727 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
2728                                    struct Session *session)
2729 {
2730   struct NeighbourMapEntry *n;
2731   struct BlackListCheckContext *bcc;
2732   struct BlackListCheckContext *bcc_next;
2733
2734   /* make sure to cancel all ongoing blacklist checks involving 'session' */
2735   bcc_next = bc_head;
2736   while (NULL != (bcc = bcc_next))
2737   {
2738     bcc_next = bcc->next;
2739     if (bcc->na.session == session)
2740     {
2741       GST_blacklist_test_cancel (bcc->bc);
2742       GNUNET_HELLO_address_free (bcc->na.address);
2743       GNUNET_CONTAINER_DLL_remove (bc_head,
2744                                    bc_tail,
2745                                    bcc);
2746       GNUNET_free (bcc);
2747     }
2748   }
2749   if (NULL == (n = lookup_neighbour (peer)))
2750     return GNUNET_NO; /* can't affect us */
2751   if (session != n->primary_address.session)
2752   {
2753     if (session == n->alternative_address.session)
2754     {
2755       free_address (&n->alternative_address);
2756       if ( (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
2757            (S_CONNECTED_SWITCHING_CONNECT_SENT == n->state) )
2758         n->state = S_CONNECTED;
2759       else
2760         GNUNET_break (0);
2761     }
2762     return GNUNET_NO; /* doesn't affect us further */
2763   }
2764
2765   n->expect_latency_response = GNUNET_NO;
2766   switch (n->state)
2767   {
2768   case S_NOT_CONNECTED:
2769     GNUNET_break (0);
2770     free_neighbour (n, GNUNET_NO);
2771     return GNUNET_YES;
2772   case S_INIT_ATS:
2773     GNUNET_break (0);
2774     free_neighbour (n, GNUNET_NO);
2775     return GNUNET_YES;
2776   case S_INIT_BLACKLIST:
2777   case S_CONNECT_SENT:
2778     free_address (&n->primary_address);
2779     n->state = S_INIT_ATS;
2780     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2781     // FIXME: need to ask ATS for suggestions again?
2782     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2783     break;
2784   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2785   case S_CONNECT_RECV_ATS:    
2786   case S_CONNECT_RECV_BLACKLIST:
2787   case S_CONNECT_RECV_ACK:
2788     /* error on inbound session; free neighbour entirely */
2789     free_address (&n->primary_address);
2790     free_neighbour (n, GNUNET_NO);
2791     return GNUNET_YES;
2792   case S_CONNECTED:
2793     free_address (&n->primary_address);
2794     n->state = S_RECONNECT_ATS;
2795     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2796     /* FIXME: is this ATS call needed? */
2797     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2798     break;
2799   case S_RECONNECT_ATS:
2800     /* we don't have an address, how can it go down? */
2801     GNUNET_break (0);
2802     break;
2803   case S_RECONNECT_BLACKLIST:
2804   case S_RECONNECT_SENT:
2805     n->state = S_RECONNECT_ATS;
2806     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2807     // FIXME: need to ask ATS for suggestions again?
2808     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2809     break;
2810   case S_CONNECTED_SWITCHING_BLACKLIST:
2811     /* primary went down while we were checking secondary against
2812        blacklist, adopt secondary as primary */       
2813     free_address (&n->primary_address);
2814     n->primary_address = n->alternative_address;
2815     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2816     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2817     n->state = S_RECONNECT_BLACKLIST;
2818     break;
2819   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2820     /* primary went down while we were waiting for CONNECT_ACK on secondary;
2821        secondary as primary */       
2822     free_address (&n->primary_address);
2823     n->primary_address = n->alternative_address;
2824     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2825     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2826     n->state = S_RECONNECT_SENT;
2827     break;
2828   case S_DISCONNECT:
2829     free_address (&n->primary_address);
2830     break;
2831   case S_DISCONNECT_FINISHED:
2832     /* neighbour was freed and plugins told to terminate session */
2833     break;
2834   default:
2835     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2836     GNUNET_break (0);
2837     break;
2838   }
2839   if (GNUNET_SCHEDULER_NO_TASK != n->task)
2840     GNUNET_SCHEDULER_cancel (n->task);
2841   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
2842   return GNUNET_YES;
2843 }
2844
2845
2846 /**
2847  * We received a 'SESSION_ACK' message from the other peer.
2848  * If we sent a 'CONNECT_ACK' last, this means we are now
2849  * connected.  Otherwise, do nothing.
2850  *
2851  * @param message possibly a 'struct SessionConnectMessage' (check format)
2852  * @param peer identity of the peer to switch the address for
2853  * @param address address of the other peer, NULL if other peer
2854  *                       connected to us
2855  * @param session session to use (or NULL)
2856  * @param ats performance data
2857  * @param ats_count number of entries in ats
2858  */
2859 void
2860 GST_neighbours_handle_session_ack (const struct GNUNET_MessageHeader *message,
2861                                    const struct GNUNET_PeerIdentity *peer,
2862                                    const struct GNUNET_HELLO_Address *address,
2863                                    struct Session *session,
2864                                    const struct GNUNET_ATS_Information *ats,
2865                                    uint32_t ats_count)
2866 {
2867   struct NeighbourMapEntry *n;
2868
2869   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2870               "Received SESSION_ACK message from peer `%s'\n",
2871               GNUNET_i2s (peer));
2872   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
2873   {
2874     GNUNET_break_op (0);
2875     return;
2876   }
2877   if (NULL == (n = lookup_neighbour (peer)))
2878     return;
2879   /* check if we are in a plausible state for having sent
2880      a CONNECT_ACK.  If not, return, otherwise break */
2881   if ( ( (S_CONNECT_RECV_ACK != n->state) &&
2882          (S_CONNECT_SENT != n->state) ) ||
2883        (2 != n->send_connect_ack) )
2884   {
2885     GNUNET_STATISTICS_update (GST_stats,
2886                               gettext_noop ("# unexpected SESSION ACK messages"), 1,
2887                               GNUNET_NO);
2888     return;
2889   }
2890   n->state = S_CONNECTED;
2891   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2892   GNUNET_STATISTICS_set (GST_stats, 
2893                          gettext_noop ("# peers connected"), 
2894                          ++neighbours_connected,
2895                          GNUNET_NO);
2896   connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2897   GNUNET_ATS_address_add(GST_ats,
2898                          n->primary_address.address,
2899                          n->primary_address.session,
2900                          ats, ats_count);
2901   set_address (&n->primary_address,
2902                n->primary_address.address,
2903                n->primary_address.session,
2904                n->primary_address.bandwidth_in,
2905                n->primary_address.bandwidth_out,
2906                GNUNET_YES);
2907 }
2908
2909
2910 /**
2911  * Test if we're connected to the given peer.
2912  *
2913  * @param target peer to test
2914  * @return GNUNET_YES if we are connected, GNUNET_NO if not
2915  */
2916 int
2917 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
2918 {
2919   return test_connected (lookup_neighbour (target));
2920 }
2921
2922
2923 /**
2924  * Change the incoming quota for the given peer.
2925  *
2926  * @param neighbour identity of peer to change qutoa for
2927  * @param quota new quota
2928  */
2929 void
2930 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
2931                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
2932 {
2933   struct NeighbourMapEntry *n;
2934
2935   if (NULL == (n = lookup_neighbour (neighbour)))
2936   {
2937     GNUNET_STATISTICS_update (GST_stats,
2938                               gettext_noop
2939                               ("# SET QUOTA messages ignored (no such peer)"),
2940                               1, GNUNET_NO);
2941     return;
2942   }
2943   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2944               "Setting inbound quota of %u Bps for peer `%s' to all clients\n",
2945               ntohl (quota.value__), GNUNET_i2s (&n->id));
2946   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
2947   if (0 != ntohl (quota.value__))
2948     return;
2949   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
2950               GNUNET_i2s (&n->id), "SET_QUOTA");
2951   if (GNUNET_YES == test_connected (n))
2952     GNUNET_STATISTICS_update (GST_stats,
2953                               gettext_noop ("# disconnects due to quota of 0"),
2954                               1, GNUNET_NO);
2955   disconnect_neighbour (n);
2956 }
2957
2958
2959 /**
2960  * We received a disconnect message from the given peer,
2961  * validate and process.
2962  *
2963  * @param peer sender of the message
2964  * @param msg the disconnect message
2965  */
2966 void
2967 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity
2968                                           *peer,
2969                                           const struct GNUNET_MessageHeader
2970                                           *msg)
2971 {
2972   struct NeighbourMapEntry *n;
2973   const struct SessionDisconnectMessage *sdm;
2974   struct GNUNET_HashCode hc;
2975
2976   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2977               "Received DISCONNECT message from peer `%s'\n",
2978               GNUNET_i2s (peer));
2979   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
2980   {
2981     // GNUNET_break_op (0);
2982     GNUNET_STATISTICS_update (GST_stats,
2983                               gettext_noop
2984                               ("# disconnect messages ignored (old format)"), 1,
2985                               GNUNET_NO);
2986     return;
2987   }
2988   sdm = (const struct SessionDisconnectMessage *) msg;
2989   if (NULL == (n = lookup_neighbour (peer)))
2990     return;                     /* gone already */
2991   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value <= n->connect_ack_timestamp.abs_value)
2992   {
2993     GNUNET_STATISTICS_update (GST_stats,
2994                               gettext_noop
2995                               ("# disconnect messages ignored (timestamp)"), 1,
2996                               GNUNET_NO);
2997     return;
2998   }
2999   GNUNET_CRYPTO_hash (&sdm->public_key,
3000                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3001                       &hc);
3002   if (0 != memcmp (peer, &hc, sizeof (struct GNUNET_PeerIdentity)))
3003   {
3004     GNUNET_break_op (0);
3005     return;
3006   }
3007   if (ntohl (sdm->purpose.size) !=
3008       sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3009       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
3010       sizeof (struct GNUNET_TIME_AbsoluteNBO))
3011   {
3012     GNUNET_break_op (0);
3013     return;
3014   }
3015   if (GNUNET_OK !=
3016       GNUNET_CRYPTO_rsa_verify
3017       (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT, &sdm->purpose,
3018        &sdm->signature, &sdm->public_key))
3019   {
3020     GNUNET_break_op (0);
3021     return;
3022   }
3023   if (GNUNET_YES == test_connected (n))
3024     GNUNET_STATISTICS_update (GST_stats,
3025                               gettext_noop
3026                               ("# other peer asked to disconnect from us"), 1,
3027                               GNUNET_NO);
3028   disconnect_neighbour (n);
3029 }
3030
3031
3032 /**
3033  * Closure for the neighbours_iterate function.
3034  */
3035 struct IteratorContext
3036 {
3037   /**
3038    * Function to call on each connected neighbour.
3039    */
3040   GST_NeighbourIterator cb;
3041
3042   /**
3043    * Closure for 'cb'.
3044    */
3045   void *cb_cls;
3046 };
3047
3048
3049 /**
3050  * Call the callback from the closure for each connected neighbour.
3051  *
3052  * @param cls the 'struct IteratorContext'
3053  * @param key the hash of the public key of the neighbour
3054  * @param value the 'struct NeighbourMapEntry'
3055  * @return GNUNET_OK (continue to iterate)
3056  */
3057 static int
3058 neighbours_iterate (void *cls, const struct GNUNET_HashCode * key, void *value)
3059 {
3060   struct IteratorContext *ic = cls;
3061   struct NeighbourMapEntry *n = value;
3062
3063   if (GNUNET_YES == test_connected (n))
3064     ic->cb (ic->cb_cls, &n->id, NULL, 0, n->primary_address.address);
3065   return GNUNET_OK;
3066 }
3067
3068
3069 /**
3070  * Iterate over all connected neighbours.
3071  *
3072  * @param cb function to call
3073  * @param cb_cls closure for cb
3074  */
3075 void
3076 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
3077 {
3078   struct IteratorContext ic;
3079
3080   if (NULL == neighbours)  
3081     return; /* can happen during shutdown */
3082   ic.cb = cb;
3083   ic.cb_cls = cb_cls;
3084   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &neighbours_iterate, &ic);
3085 }
3086
3087
3088 /**
3089  * If we have an active connection to the given target, it must be shutdown.
3090  *
3091  * @param target peer to disconnect from
3092  */
3093 void
3094 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
3095 {
3096   struct NeighbourMapEntry *n;
3097
3098   if (NULL == (n = lookup_neighbour (target)))
3099     return;  /* not active */
3100   if (GNUNET_YES == test_connected (n))
3101     GNUNET_STATISTICS_update (GST_stats,
3102                               gettext_noop
3103                               ("# disconnected from peer upon explicit request"), 1,
3104                               GNUNET_NO);
3105   disconnect_neighbour (n);
3106 }
3107
3108
3109 /**
3110  * Obtain current latency information for the given neighbour.
3111  *
3112  * @param peer to get the latency for
3113  * @return observed latency of the address, FOREVER if the 
3114  *         the connection is not up
3115  */
3116 struct GNUNET_TIME_Relative
3117 GST_neighbour_get_latency (const struct GNUNET_PeerIdentity *peer)
3118 {
3119   struct NeighbourMapEntry *n;
3120
3121   n = lookup_neighbour (peer);
3122   if (NULL == n) 
3123     return GNUNET_TIME_UNIT_FOREVER_REL;
3124   switch (n->state)
3125   {
3126   case S_CONNECTED:
3127   case S_RECONNECT_SENT:
3128   case S_RECONNECT_ATS:
3129     return n->latency;
3130   case S_NOT_CONNECTED:
3131   case S_INIT_BLACKLIST:
3132   case S_INIT_ATS:
3133   case S_CONNECT_RECV_BLACKLIST_INBOUND:
3134   case S_CONNECT_SENT:
3135   case S_CONNECT_RECV_BLACKLIST:
3136   case S_DISCONNECT:
3137   case S_DISCONNECT_FINISHED:
3138     return GNUNET_TIME_UNIT_FOREVER_REL;
3139   default:
3140     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
3141     GNUNET_break (0);
3142     break;
3143   }
3144   return GNUNET_TIME_UNIT_FOREVER_REL;   
3145 }
3146
3147
3148 /**
3149  * Obtain current address information for the given neighbour.
3150  *
3151  * @param peer
3152  * @return address currently used
3153  */
3154 struct GNUNET_HELLO_Address *
3155 GST_neighbour_get_current_address (const struct GNUNET_PeerIdentity *peer)
3156 {
3157   struct NeighbourMapEntry *n;
3158
3159   n = lookup_neighbour (peer);
3160   if (NULL == n)
3161     return NULL;
3162   return n->primary_address.address;
3163 }
3164
3165
3166 /**
3167  * Initialize the neighbours subsystem.
3168  *
3169  * @param cls closure for callbacks
3170  * @param connect_cb function to call if we connect to a peer
3171  * @param disconnect_cb function to call if we disconnect from a peer
3172  * @param peer_address_cb function to call if we change an active address
3173  *                   of a neighbour
3174  */
3175 void
3176 GST_neighbours_start (void *cls,
3177                       GNUNET_TRANSPORT_NotifyConnect connect_cb,
3178                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb,
3179                       GNUNET_TRANSPORT_PeerIterateCallback peer_address_cb)
3180 {
3181   callback_cls = cls;
3182   connect_notify_cb = connect_cb;
3183   disconnect_notify_cb = disconnect_cb;
3184   address_change_cb = peer_address_cb;
3185   neighbours = GNUNET_CONTAINER_multihashmap_create (NEIGHBOUR_TABLE_SIZE);
3186 }
3187
3188
3189 /**
3190  * Disconnect from the given neighbour.
3191  *
3192  * @param cls unused
3193  * @param key hash of neighbour's public key (not used)
3194  * @param value the 'struct NeighbourMapEntry' of the neighbour
3195  * @return GNUNET_OK (continue to iterate)
3196  */
3197 static int
3198 disconnect_all_neighbours (void *cls, const struct GNUNET_HashCode * key, void *value)
3199 {
3200   struct NeighbourMapEntry *n = value;
3201
3202   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3203               "Disconnecting peer `%4s', %s\n",
3204               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
3205   n->state = S_DISCONNECT_FINISHED;
3206   free_neighbour (n, GNUNET_NO);
3207   return GNUNET_OK;
3208 }
3209
3210
3211 /**
3212  * Cleanup the neighbours subsystem.
3213  */
3214 void
3215 GST_neighbours_stop ()
3216 {
3217   if (NULL == neighbours)
3218     return;
3219   GNUNET_CONTAINER_multihashmap_iterate (neighbours, 
3220                                          &disconnect_all_neighbours,
3221                                          NULL);
3222   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
3223   neighbours = NULL;
3224   callback_cls = NULL;
3225   connect_notify_cb = NULL;
3226   disconnect_notify_cb = NULL;
3227   address_change_cb = NULL;
3228 }
3229
3230
3231 /* end of file gnunet-service-transport_neighbours.c */