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